mastodon-ios/Mastodon/Service/APIService/APIService+Notification.swift

68 lines
3.1 KiB
Swift
Raw Normal View History

2021-04-12 10:31:53 +02:00
//
// APIService+Notification.swift
// Mastodon
//
// Created by sxiaojian on 2021/4/13.
//
import Combine
import CoreData
import CoreDataStack
2021-04-15 04:16:30 +02:00
import Foundation
2021-04-12 10:31:53 +02:00
import MastodonSDK
import OSLog
extension APIService {
func allNotifications(
domain: String,
query: Mastodon.API.Notifications.Query,
2021-04-16 07:45:54 +02:00
mastodonAuthenticationBox: AuthenticationService.MastodonAuthenticationBox
) -> AnyPublisher<Mastodon.Response.Content<[Mastodon.Entity.Notification]>, Error> {
2021-04-12 10:31:53 +02:00
let authorization = mastodonAuthenticationBox.userAuthorization
2021-04-16 07:45:54 +02:00
let userID = mastodonAuthenticationBox.userID
2021-04-12 10:31:53 +02:00
return Mastodon.API.Notifications.getNotifications(
session: session,
domain: domain,
query: query,
2021-04-16 07:45:54 +02:00
authorization: authorization
)
.flatMap { response -> AnyPublisher<Mastodon.Response.Content<[Mastodon.Entity.Notification]>, Error> in
let log = OSLog.api
return self.backgroundManagedObjectContext.performChanges {
response.value.forEach { notification in
let (mastodonUser, _) = APIService.CoreData.createOrMergeMastodonUser(into: self.backgroundManagedObjectContext, for: nil, in: domain, entity: notification.account, userCache: nil, networkDate: Date(), log: log)
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
2021-04-12 10:31:53 +02:00
}
2021-04-16 07:45:54 +02:00
// use constrain to avoid repeated save
let property = MastodonNotification.Property(id: notification.id, typeRaw: notification.type.rawValue, account: mastodonUser, status: status, createdAt: notification.createdAt)
let notification = MastodonNotification.insert(into: self.backgroundManagedObjectContext, domain: domain, userID: userID, networkDate: response.networkDate, property: property)
os_log(.info, log: log, "%{public}s[%{public}ld], %{public}s: fetch mastodon user [%s](%s)", (#file as NSString).lastPathComponent, #line, #function, notification.typeRaw, notification.account.username)
2021-04-12 10:31:53 +02:00
}
2021-04-16 07:45:54 +02:00
}
.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
2021-04-12 10:31:53 +02:00
}
}
.eraseToAnyPublisher()
2021-04-16 07:45:54 +02:00
}
.eraseToAnyPublisher()
2021-04-12 10:31:53 +02:00
}
}