Refactor task usage and profile auto update

This commit is contained in:
世界
2023-09-22 11:32:51 +08:00
parent 390e063f20
commit 3374f8e727
49 changed files with 823 additions and 636 deletions
@@ -4,37 +4,49 @@ import Library
#if os(iOS) || os(tvOS)
public class UIProfileUpdateTask: BGAppRefreshTask {
public static let taskSchedulerPermittedIdentifier = "\(FilePath.packageName).update_profiles"
private static let taskSchedulerPermittedIdentifier = "\(FilePath.packageName).update_profiles"
public static func setup() async throws {
public static func configure() async throws {
let success = BGTaskScheduler.shared.register(forTaskWithIdentifier: taskSchedulerPermittedIdentifier, using: nil) { task in
NSLog("profile update task started")
do {
let success = try ProfileUpdateTask.updateProfiles()
try? scheduleUpdate(Date(timeIntervalSinceNow: ProfileUpdateTask.taskInterval))
task.setTaskCompleted(success: success)
NSLog("profile update task succeed")
} catch {
try? scheduleUpdate(nil)
task.setTaskCompleted(success: false)
NSLog("profile update task failed: \(error.localizedDescription)")
}
task.expirationHandler = {
try? scheduleUpdate(nil)
NSLog("profile update task expired")
Task {
await getAndupdateProfiles(task)
}
}
if !success {
throw NSError(domain: "register failed", code: 0)
}
if await BGTaskScheduler.shared.pendingTaskRequests().isEmpty {
var earliestBeginDate: Date? = nil
if let updatedAt = try ProfileUpdateTask.oldestUpdated() {
if updatedAt > Date(timeIntervalSinceNow: -ProfileUpdateTask.taskInterval) {
earliestBeginDate = updatedAt.addingTimeInterval(ProfileUpdateTask.taskInterval)
}
}
try scheduleUpdate(earliestBeginDate)
BGTaskScheduler.shared.cancelAllTaskRequests()
let profiles = try await ProfileManager.listAutoUpdateEnabled()
if profiles.isEmpty {
return
}
try scheduleUpdate(ProfileUpdateTask.calculateEarliestBeginDate(profiles))
}
private nonisolated static func getAndupdateProfiles(_ task: BGTask) async {
let profiles: [Profile]
do {
profiles = try await ProfileManager.listAutoUpdateEnabled()
} catch {
return
}
if profiles.isEmpty {
return
}
do {
let success = try await ProfileUpdateTask.updateProfiles(profiles)
try? scheduleUpdate(ProfileUpdateTask.calculateEarliestBeginDate(profiles))
task.setTaskCompleted(success: success)
NSLog("profile update task succeed")
} catch {
try? scheduleUpdate(nil)
task.setTaskCompleted(success: false)
NSLog("profile update task failed: \(error.localizedDescription)")
}
task.expirationHandler = {
try? scheduleUpdate(nil)
NSLog("profile update task expired")
}
}