Init commit

This commit is contained in:
世界
2023-07-15 15:03:45 +08:00
commit f441b89efb
122 changed files with 7355 additions and 0 deletions
@@ -0,0 +1,50 @@
import Foundation
import Library
public enum ProfileUpdateTask {
private static var timer: Timer?
public static func setup() throws {
var earliestBeginDate: Date?
if let updatedAt = try oldestUpdated() {
if updatedAt > Date(timeIntervalSinceNow: -taskInterval) {
earliestBeginDate = updatedAt.addingTimeInterval(taskInterval)
}
}
timer = Timer(fire: earliestBeginDate ?? Date.now, interval: taskInterval, repeats: true, block: { _ in
do {
_ = try updateProfiles()
NSLog("profile update task succeed")
} catch {
NSLog("profile update task failed: \(error.localizedDescription)")
}
})
}
static let taskInterval: TimeInterval = 15 * 60
static func oldestUpdated() throws -> Date? {
let profiles = try ProfileManager.listAutoUpdateEnabled()
return profiles.map { profile in
profile.lastUpdated!
}
.min()
}
static func updateProfiles() throws -> Bool {
let profiles = try ProfileManager.listAutoUpdateEnabled()
var success = true
for profile in profiles {
if profile.lastUpdated! > Date(timeIntervalSinceNow: -taskInterval) {
continue
}
do {
try profile.updateRemoteProfile()
} catch {
NSLog("Update profile \(profile.name) failed: \(error.localizedDescription)")
success = false
}
}
return success
}
}
@@ -0,0 +1,47 @@
import BackgroundTasks
import Foundation
import Library
#if os(iOS)
public class UIProfileUpdateTask: BGAppRefreshTask {
public static let taskSchedulerPermittedIdentifier = "\(FilePath.packageName).update_profiles"
public static func setup() 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")
}
}
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)
}
}
private static func scheduleUpdate(_ earliestBeginDate: Date?) throws {
let request = BGAppRefreshTaskRequest(identifier: taskSchedulerPermittedIdentifier)
request.earliestBeginDate = earliestBeginDate
try BGTaskScheduler.shared.submit(request)
}
}
#endif