// // APIService+Notification.swift // Mastodon // // Created by sxiaojian on 2021/4/13. // import Foundation import Combine import CoreData import CoreDataStack import MastodonSDK import OSLog extension APIService { func allNotifications( domain: String, query: Mastodon.API.Notifications.Query, mastodonAuthenticationBox: AuthenticationService.MastodonAuthenticationBox ) -> AnyPublisher, Error> { let authorization = mastodonAuthenticationBox.userAuthorization return Mastodon.API.Notifications.getNotifications( session: session, domain: domain, query: query, authorization: authorization) .flatMap { response -> AnyPublisher, Error> in let log = OSLog.api return self.backgroundManagedObjectContext.performChanges { response.value.forEach { notification in let (mastodonUser,isCreated) = APIService.CoreData.createOrMergeMastodonUser(into: self.backgroundManagedObjectContext, for: nil, in: domain, entity: notification.account, userCache: nil, networkDate: Date(), log: log) let flag = isCreated ? "+" : "-" os_log(.info, log: log, "%{public}s[%{public}ld], %{public}s: fetch mastodon user [%s](%s)%s", (#file as NSString).lastPathComponent, #line, #function, flag, mastodonUser.id, mastodonUser.username) var status: Status? if let statusEntity = notification.status { let (statusInCoreData,_,_) = APIService.CoreData.createOrMergeStatus( into: self.backgroundManagedObjectContext, for: nil, domain: domain, entity: statusEntity, statusCache: nil, userCache: nil, networkDate: Date(), log: log) status = statusInCoreData } // use constrain to avoid repeated save _ = MastodonNotification.insert(into: self.backgroundManagedObjectContext, domain: domain, property: MastodonNotification.Property(id: notification.id, type: notification.type.rawValue, account: mastodonUser, status: status, createdAt: Date())) } } .setFailureType(to: Error.self) .tryMap { result -> Mastodon.Response.Content<[Mastodon.Entity.Notification]> in switch result { case .success: return response case .failure(let error): throw error } } .eraseToAnyPublisher() } .eraseToAnyPublisher() } }