mirror of
https://github.com/Ranchero-Software/NetNewsWire
synced 2026-11-28 00:04:25 +00:00
Convert to async/await.
This commit is contained in:
1 parent
8607a60a14
commit
b681dea6fa
1 file changed
+128
-148
@@ -14,173 +14,153 @@ import RSCore
|
||||
import Articles
|
||||
import Account
|
||||
|
||||
public final class WidgetDataEncoder {
|
||||
public var isRunning = false
|
||||
@MainActor final class WidgetDataEncoder {
|
||||
static let shared = WidgetDataEncoder()
|
||||
|
||||
var isRunning = false
|
||||
|
||||
private let fetchLimit = 7
|
||||
|
||||
private lazy var appGroup = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as! String
|
||||
private lazy var containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup)
|
||||
private lazy var imageContainer = containerURL?.appendingPathComponent("widgetImages", isDirectory: true)
|
||||
private lazy var dataURL = containerURL?.appendingPathComponent("widget-data.json")
|
||||
private let imageContainer: URL
|
||||
private let dataURL: URL
|
||||
|
||||
private static let logger = Logger(subsystem: Bundle.main.bundleIdentifier!, category: "WidgetDataEncoder")
|
||||
|
||||
init () {
|
||||
if imageContainer != nil {
|
||||
try? FileManager.default.createDirectory(at: imageContainer!, withIntermediateDirectories: true, attributes: nil)
|
||||
init?() {
|
||||
guard let appGroup = Bundle.main.object(forInfoDictionaryKey: "AppGroup") as? String else {
|
||||
Self.logger.error("WidgetDataEncoder: unable to create appGroup")
|
||||
return nil
|
||||
}
|
||||
guard let containerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) else {
|
||||
Self.logger.error("WidgetDataEncoder: unable to create containerURL")
|
||||
return nil
|
||||
}
|
||||
|
||||
self.imageContainer = containerURL.appendingPathComponent("widgetImages", isDirectory: true)
|
||||
self.dataURL = containerURL.appendingPathComponent("widget-data.json")
|
||||
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: imageContainer, withIntermediateDirectories: true, attributes: nil)
|
||||
} catch {
|
||||
Self.logger.error("WidgetDataEncoder: unable to create folder for images")
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func encode() {
|
||||
if #available(iOS 14, *) {
|
||||
isRunning = true
|
||||
|
||||
flushSharedContainer()
|
||||
Self.logger.debug("Encoding widget data")
|
||||
|
||||
DispatchQueue.main.async {
|
||||
self.encodeWidgetData() { latestData in
|
||||
guard let latestData = latestData else {
|
||||
self.isRunning = false
|
||||
return
|
||||
}
|
||||
|
||||
let encodedData = try? JSONEncoder().encode(latestData)
|
||||
|
||||
Self.logger.debug("Finished encoding widget data")
|
||||
|
||||
if self.fileExists() {
|
||||
try? FileManager.default.removeItem(at: self.dataURL!)
|
||||
Self.logger.debug("Removed widget data from container")
|
||||
}
|
||||
|
||||
if FileManager.default.createFile(atPath: self.dataURL!.path, contents: encodedData, attributes: nil) {
|
||||
Self.logger.info("Wrote widget data to container")
|
||||
WidgetCenter.shared.reloadAllTimelines()
|
||||
}
|
||||
|
||||
self.isRunning = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@available(iOS 14, *)
|
||||
@MainActor private func encodeWidgetData(completion: @escaping (WidgetData?) -> Void) {
|
||||
let dispatchGroup = DispatchGroup()
|
||||
var groupError: Error? = nil
|
||||
|
||||
var unread = [LatestArticle]()
|
||||
|
||||
dispatchGroup.enter()
|
||||
AccountManager.shared.fetchArticlesAsync(.unread(fetchLimit)) { (articleSetResult) in
|
||||
MainActor.assumeIsolated {
|
||||
switch articleSetResult {
|
||||
case .success(let articles):
|
||||
for article in articles {
|
||||
let latestArticle = LatestArticle(id: article.sortableArticleID,
|
||||
feedTitle: article.sortableName,
|
||||
articleTitle: ArticleStringFormatter.truncatedTitle(article).isEmpty ? ArticleStringFormatter.truncatedSummary(article) : ArticleStringFormatter.truncatedTitle(article),
|
||||
articleSummary: article.summary,
|
||||
feedIconPath: self.writeImageDataToSharedContainer(article.iconImage()?.image.dataRepresentation()),
|
||||
pubDate: article.datePublished?.description ?? "")
|
||||
unread.append(latestArticle)
|
||||
}
|
||||
case .failure(let databaseError):
|
||||
groupError = databaseError
|
||||
}
|
||||
dispatchGroup.leave()
|
||||
}
|
||||
if isRunning {
|
||||
Self.logger.debug("WidgetDataEncoder: skipping encode because already in encode")
|
||||
return
|
||||
}
|
||||
|
||||
var starred = [LatestArticle]()
|
||||
Self.logger.debug("WidgetDataEncoder: encoding")
|
||||
isRunning = true
|
||||
|
||||
dispatchGroup.enter()
|
||||
AccountManager.shared.fetchArticlesAsync(.starred(fetchLimit)) { (articleSetResult) in
|
||||
MainActor.assumeIsolated {
|
||||
switch articleSetResult {
|
||||
case .success(let articles):
|
||||
for article in articles {
|
||||
let latestArticle = LatestArticle(id: article.sortableArticleID,
|
||||
feedTitle: article.sortableName,
|
||||
articleTitle: ArticleStringFormatter.truncatedTitle(article).isEmpty ? ArticleStringFormatter.truncatedSummary(article) : ArticleStringFormatter.truncatedTitle(article),
|
||||
articleSummary: article.summary,
|
||||
feedIconPath: self.writeImageDataToSharedContainer(article.iconImage()?.image.dataRepresentation()),
|
||||
pubDate: article.datePublished?.description ?? "")
|
||||
starred.append(latestArticle)
|
||||
}
|
||||
case .failure(let databaseError):
|
||||
groupError = databaseError
|
||||
}
|
||||
dispatchGroup.leave()
|
||||
flushSharedContainer()
|
||||
|
||||
Task { @MainActor in
|
||||
defer {
|
||||
isRunning = false
|
||||
}
|
||||
}
|
||||
|
||||
var today = [LatestArticle]()
|
||||
|
||||
dispatchGroup.enter()
|
||||
AccountManager.shared.fetchArticlesAsync(.today(fetchLimit)) { (articleSetResult) in
|
||||
MainActor.assumeIsolated {
|
||||
switch articleSetResult {
|
||||
case .success(let articles):
|
||||
for article in articles {
|
||||
let latestArticle = LatestArticle(id: article.sortableArticleID,
|
||||
feedTitle: article.sortableName,
|
||||
articleTitle: ArticleStringFormatter.truncatedTitle(article).isEmpty ? ArticleStringFormatter.truncatedSummary(article) : ArticleStringFormatter.truncatedTitle(article),
|
||||
articleSummary: article.summary,
|
||||
feedIconPath: self.writeImageDataToSharedContainer(article.iconImage()?.image.dataRepresentation()),
|
||||
pubDate: article.datePublished?.description ?? "")
|
||||
today.append(latestArticle)
|
||||
}
|
||||
case .failure(let databaseError):
|
||||
groupError = databaseError
|
||||
}
|
||||
dispatchGroup.leave()
|
||||
}
|
||||
}
|
||||
|
||||
dispatchGroup.notify(queue: .main) {
|
||||
if let groupError {
|
||||
Self.logger.error("WidgetDataEncoder failed to write the widget data: \(groupError.localizedDescription)")
|
||||
completion(nil)
|
||||
} else {
|
||||
let latestData = WidgetData(currentUnreadCount: SmartFeedsController.shared.unreadFeed.unreadCount,
|
||||
currentTodayCount: SmartFeedsController.shared.todayFeed.unreadCount,
|
||||
currentStarredCount: (try? AccountManager.shared.fetchCountForStarredArticles()) ?? 0,
|
||||
unreadArticles: unread.sorted(by: { $0.pubDate > $1.pubDate }),
|
||||
starredArticles: starred.sorted(by: { $0.pubDate > $1.pubDate }),
|
||||
todayArticles: today.sorted(by: { $0.pubDate > $1.pubDate }),
|
||||
lastUpdateTime: Date())
|
||||
completion(latestData)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func fileExists() -> Bool {
|
||||
FileManager.default.fileExists(atPath: dataURL!.path)
|
||||
}
|
||||
|
||||
private func writeImageDataToSharedContainer(_ imageData: Data?) -> String? {
|
||||
if imageData == nil { return nil }
|
||||
// Each image gets a UUID
|
||||
let uuid = UUID().uuidString
|
||||
if let imagePath = imageContainer?.appendingPathComponent(uuid, isDirectory: false) {
|
||||
let latestData: WidgetData
|
||||
do {
|
||||
try imageData!.write(to: imagePath)
|
||||
return imagePath.path
|
||||
latestData = try await fetchWidgetData()
|
||||
} catch {
|
||||
return nil
|
||||
Self.logger.error("WidgetDataEncoder: error fetching widget data: \(error.localizedDescription)")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
let encodedData: Data
|
||||
do {
|
||||
encodedData = try JSONEncoder().encode(latestData)
|
||||
} catch {
|
||||
Self.logger.error("WidgetDataEncoder: error encoding widget data: \(error.localizedDescription)")
|
||||
return
|
||||
}
|
||||
|
||||
private func flushSharedContainer() {
|
||||
if let imageContainer = imageContainer {
|
||||
try? FileManager.default.removeItem(atPath: imageContainer.path)
|
||||
try? FileManager.default.createDirectory(at: imageContainer, withIntermediateDirectories: true, attributes: nil)
|
||||
if fileExists() {
|
||||
try? FileManager.default.removeItem(at: dataURL)
|
||||
Self.logger.debug("WidgetDataEncoder: removed widget data from container")
|
||||
}
|
||||
|
||||
if FileManager.default.createFile(atPath: dataURL.path, contents: encodedData, attributes: nil) {
|
||||
Self.logger.debug("WidgetDataEncoder: wrote data to container")
|
||||
WidgetCenter.shared.reloadAllTimelines()
|
||||
} else {
|
||||
Self.logger.error("WidgetDataEncoder: could not write data to container")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@MainActor private extension WidgetDataEncoder {
|
||||
|
||||
func fetchWidgetData() async throws -> WidgetData {
|
||||
let fetchedUnreadArticles = try await AccountManager.shared.fetchArticlesAsync(.unread(fetchLimit))
|
||||
let unreadArticles = sortedLatestArticles(fetchedUnreadArticles)
|
||||
|
||||
let fetchedStarredArticles = try await AccountManager.shared.fetchArticlesAsync(.starred(fetchLimit))
|
||||
let starredArticles = sortedLatestArticles(fetchedStarredArticles)
|
||||
|
||||
let fetchedTodayArticles = try await AccountManager.shared.fetchArticlesAsync(.today(fetchLimit))
|
||||
let todayArticles = sortedLatestArticles(fetchedTodayArticles)
|
||||
|
||||
let latestData = WidgetData(currentUnreadCount: SmartFeedsController.shared.unreadFeed.unreadCount,
|
||||
currentTodayCount: SmartFeedsController.shared.todayFeed.unreadCount,
|
||||
currentStarredCount: (try? AccountManager.shared.fetchCountForStarredArticles()) ?? 0,
|
||||
unreadArticles: unreadArticles,
|
||||
starredArticles: starredArticles,
|
||||
todayArticles: todayArticles,
|
||||
lastUpdateTime: Date())
|
||||
return latestData
|
||||
}
|
||||
|
||||
func fileExists() -> Bool {
|
||||
FileManager.default.fileExists(atPath: dataURL.path)
|
||||
}
|
||||
|
||||
func writeImageDataToSharedContainer(_ imageData: Data?) -> String? {
|
||||
guard let imageData else {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Each image gets a UUID
|
||||
let uuid = UUID().uuidString
|
||||
|
||||
let imagePath = imageContainer.appendingPathComponent(uuid, isDirectory: false)
|
||||
do {
|
||||
try imageData.write(to: imagePath)
|
||||
return imagePath.path
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func flushSharedContainer() {
|
||||
try? FileManager.default.removeItem(atPath: imageContainer.path)
|
||||
try? FileManager.default.createDirectory(at: imageContainer, withIntermediateDirectories: true, attributes: nil)
|
||||
}
|
||||
|
||||
func createLatestArticle(_ article: Article) -> LatestArticle {
|
||||
let truncatedTitle = ArticleStringFormatter.truncatedTitle(article)
|
||||
let articleTitle = truncatedTitle.isEmpty ? ArticleStringFormatter.truncatedSummary(article) : truncatedTitle
|
||||
|
||||
// TODO: It looks like we write images each time, but we’re probably over-writing unchanged images sometimes.
|
||||
let feedIconPath = writeImageDataToSharedContainer(article.iconImage()?.image.dataRepresentation())
|
||||
|
||||
let pubDate = article.datePublished?.description ?? ""
|
||||
|
||||
let latestArticle = LatestArticle(id: article.sortableArticleID,
|
||||
feedTitle: article.sortableName,
|
||||
articleTitle: articleTitle,
|
||||
articleSummary: article.summary,
|
||||
feedIconPath: feedIconPath,
|
||||
pubDate: pubDate)
|
||||
return latestArticle
|
||||
}
|
||||
|
||||
func sortedLatestArticles(_ fetchedArticles: Set<Article>) -> [LatestArticle] {
|
||||
let latestArticles = fetchedArticles.map(createLatestArticle)
|
||||
return latestArticles.sorted(by: { $0.pubDate > $1.pubDate })
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user