NetNewsWire/Shared/SmartFeeds/SmartFeed.swift

91 lines
2.1 KiB
Swift
Raw Normal View History

2017-11-19 22:57:42 +01:00
//
// SmartFeed.swift
2018-08-29 07:18:24 +02:00
// NetNewsWire
2017-11-19 22:57:42 +01:00
//
// Created by Brent Simmons on 11/19/17.
// Copyright © 2017 Ranchero Software. All rights reserved.
//
import Foundation
import RSCore
import Articles
2017-11-19 22:57:42 +01:00
import Account
protocol SmartFeedDelegate: DisplayNameProvider, ArticleFetcher {
func fetchUnreadCount(for: Account, callback: @escaping (Int) -> Void)
}
final class SmartFeed: PseudoFeed {
var nameForDisplay: String {
return delegate.nameForDisplay
}
2017-11-19 22:57:42 +01:00
var unreadCount = 0 {
didSet {
if unreadCount != oldValue {
postUnreadCountDidChangeNotification()
}
}
}
#if os(macOS)
var pasteboardWriter: NSPasteboardWriting {
return SmartFeedPasteboardWriter(smartFeed: self)
}
#endif
private let delegate: SmartFeedDelegate
private var unreadCounts = [String: Int]()
2017-11-19 22:57:42 +01:00
init(delegate: SmartFeedDelegate) {
self.delegate = delegate
2017-11-19 22:57:42 +01:00
NotificationCenter.default.addObserver(self, selector: #selector(unreadCountDidChange(_:)), name: .UnreadCountDidChange, object: nil)
queueFetchUnreadCounts() // Fetch unread count at startup
2017-11-19 22:57:42 +01:00
}
@objc func unreadCountDidChange(_ note: Notification) {
if note.object is AppDelegate {
queueFetchUnreadCounts()
2017-11-19 22:57:42 +01:00
}
}
@objc func fetchUnreadCounts() {
AccountManager.shared.activeAccounts.forEach { self.fetchUnreadCount(for: $0) }
}
}
extension SmartFeed: ArticleFetcher {
func fetchArticles() -> Set<Article> {
return delegate.fetchArticles()
}
func fetchUnreadArticles() -> Set<Article> {
return delegate.fetchUnreadArticles()
}
2017-11-19 22:57:42 +01:00
}
private extension SmartFeed {
2017-11-19 22:57:42 +01:00
func queueFetchUnreadCounts() {
CoalescingQueue.standard.add(self, #selector(fetchUnreadCounts))
}
2017-11-19 22:57:42 +01:00
func fetchUnreadCount(for account: Account) {
delegate.fetchUnreadCount(for: account) { (accountUnreadCount) in
self.unreadCounts[account.accountID] = accountUnreadCount
2017-11-19 22:57:42 +01:00
self.updateUnreadCount()
}
}
func updateUnreadCount() {
unreadCount = AccountManager.shared.activeAccounts.reduce(0) { (result, account) -> Int in
if let oneUnreadCount = unreadCounts[account.accountID] {
2017-11-19 22:57:42 +01:00
return result + oneUnreadCount
}
return result
}
}
}