@capgo/capacitor-updater 8.52.1 → 8.53.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +198 -66
- package/android/build.gradle +2 -1
- package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +414 -150
- package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +693 -217
- package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +2 -1
- package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +226 -105
- package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +30 -10
- package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +324 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +34 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/NativeUpdatePrompt.java +303 -0
- package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +4 -4
- package/android/src/main/java/ee/forgr/capacitor_updater/Version.java +1 -1
- package/dist/docs.json +378 -27
- package/dist/esm/definitions.d.ts +206 -7
- package/dist/esm/definitions.js.map +1 -1
- package/dist/plugin.cjs.js.map +1 -1
- package/dist/plugin.js.map +1 -1
- package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +104 -52
- package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +360 -104
- package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +166 -10
- package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +2 -1
- package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +202 -90
- package/ios/Sources/CapacitorUpdaterPlugin/NativeUpdatePrompt.swift +183 -0
- package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +5 -2
- package/package.json +7 -3
|
@@ -506,6 +506,18 @@ import UIKit
|
|
|
506
506
|
return cacheFolder.appendingPathComponent("partial_\(digest)_\(token).tmp")
|
|
507
507
|
}
|
|
508
508
|
|
|
509
|
+
private func removePartialManifestBundleDirectory(_ destFolder: URL) {
|
|
510
|
+
guard FileManager.default.fileExists(atPath: destFolder.path) else {
|
|
511
|
+
return
|
|
512
|
+
}
|
|
513
|
+
do {
|
|
514
|
+
try FileManager.default.removeItem(at: destFolder)
|
|
515
|
+
} catch {
|
|
516
|
+
logger.error("Failed to remove partial manifest bundle directory")
|
|
517
|
+
logger.debug("Path: \(destFolder.path), Error: \(error.localizedDescription)")
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
|
|
509
521
|
private func cleanupOldManifestPartials() {
|
|
510
522
|
let cutoff = Date().addingTimeInterval(-3600)
|
|
511
523
|
guard let files = try? FileManager.default.contentsOfDirectory(
|
|
@@ -981,6 +993,55 @@ import UIKit
|
|
|
981
993
|
// Symlink targets are paths; anything bigger than this is not a legitimate link.
|
|
982
994
|
private static let maxZipSymlinkTargetBytes = 64 * 1024
|
|
983
995
|
|
|
996
|
+
/// A zip symlink target must be a relative path without `..`, so a link can only point further down.
|
|
997
|
+
/// A lexical check alone is not enough: with `m -> .`, the target `m/..` normalizes to the link folder but
|
|
998
|
+
/// physically resolves to its parent.
|
|
999
|
+
static func isSafeZipSymlinkTarget(_ target: String) -> Bool {
|
|
1000
|
+
if target.isEmpty || target.contains("\0") || target.contains("\\") {
|
|
1001
|
+
return false
|
|
1002
|
+
}
|
|
1003
|
+
if (target as NSString).isAbsolutePath {
|
|
1004
|
+
return false
|
|
1005
|
+
}
|
|
1006
|
+
return !containsPathTraversalSegment(target)
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
private static func realPath(_ path: String) -> String? {
|
|
1010
|
+
guard let resolved = Darwin.realpath(path, nil) else {
|
|
1011
|
+
return nil
|
|
1012
|
+
}
|
|
1013
|
+
defer { free(resolved) }
|
|
1014
|
+
return String(cString: resolved)
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
/// Resolves symlinks on the deepest existing ancestor of `url` and throws when it is outside `root`.
|
|
1018
|
+
/// Run before creating anything, so a symlinked folder can never redirect a write out of the bundle.
|
|
1019
|
+
static func assertPhysicallyInsideDirectory(_ url: URL, root: URL) throws {
|
|
1020
|
+
guard let rootPath = realPath(root.path) else {
|
|
1021
|
+
throw SecurePathError.pathTraversal
|
|
1022
|
+
}
|
|
1023
|
+
let normalizedRoot = rootPath.hasSuffix("/") ? rootPath : "\(rootPath)/"
|
|
1024
|
+
var candidate = url.standardizedFileURL.path
|
|
1025
|
+
while true {
|
|
1026
|
+
if let resolved = realPath(candidate) {
|
|
1027
|
+
if resolved != rootPath && !resolved.hasPrefix(normalizedRoot) {
|
|
1028
|
+
throw SecurePathError.pathTraversal
|
|
1029
|
+
}
|
|
1030
|
+
return
|
|
1031
|
+
}
|
|
1032
|
+
let parent = (candidate as NSString).deletingLastPathComponent
|
|
1033
|
+
if parent == candidate || parent.isEmpty {
|
|
1034
|
+
throw SecurePathError.pathTraversal
|
|
1035
|
+
}
|
|
1036
|
+
candidate = parent
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
/// `fileExists` follows symlinks, so a dangling link would be missed; this does not follow the last component.
|
|
1041
|
+
private static func itemExistsWithoutFollowingLink(at url: URL) -> Bool {
|
|
1042
|
+
return (try? FileManager.default.attributesOfItem(atPath: url.path)) != nil
|
|
1043
|
+
}
|
|
1044
|
+
|
|
984
1045
|
private func extractZipEntry(_ archive: ZipArchiveReader, entry: ZipEntry, to destPath: URL, bufferSize: Int = CryptoCipher.ioBufferBytes()) throws {
|
|
985
1046
|
let fileManager = FileManager.default
|
|
986
1047
|
|
|
@@ -991,7 +1052,7 @@ import UIKit
|
|
|
991
1052
|
let parentDir = destPath.deletingLastPathComponent()
|
|
992
1053
|
try fileManager.createDirectory(at: parentDir, withIntermediateDirectories: true, attributes: nil)
|
|
993
1054
|
|
|
994
|
-
if
|
|
1055
|
+
if Self.itemExistsWithoutFollowingLink(at: destPath) {
|
|
995
1056
|
try fileManager.removeItem(at: destPath)
|
|
996
1057
|
}
|
|
997
1058
|
|
|
@@ -1012,7 +1073,10 @@ import UIKit
|
|
|
1012
1073
|
case .symlink:
|
|
1013
1074
|
let linkData = try archive.readSmallEntry(entry, maxBytes: Self.maxZipSymlinkTargetBytes, bufferSize: bufferSize)
|
|
1014
1075
|
|
|
1015
|
-
guard let linkPath = String(data: linkData, encoding: .utf8) else {
|
|
1076
|
+
guard let linkPath = String(data: linkData, encoding: .utf8), Self.isSafeZipSymlinkTarget(linkPath) else {
|
|
1077
|
+
logger.error("Unzip failed: unsafe symlink target")
|
|
1078
|
+
logger.debug("Entry: \(entry.path)")
|
|
1079
|
+
self.sendStats(action: "canonical_path_fail")
|
|
1016
1080
|
throw CustomError.cannotUnzip
|
|
1017
1081
|
}
|
|
1018
1082
|
|
|
@@ -1029,7 +1093,7 @@ import UIKit
|
|
|
1029
1093
|
throw CustomError.cannotUnzip
|
|
1030
1094
|
}
|
|
1031
1095
|
|
|
1032
|
-
if
|
|
1096
|
+
if Self.itemExistsWithoutFollowingLink(at: destPath) {
|
|
1033
1097
|
try fileManager.removeItem(at: destPath)
|
|
1034
1098
|
}
|
|
1035
1099
|
|
|
@@ -1064,6 +1128,15 @@ import UIKit
|
|
|
1064
1128
|
do {
|
|
1065
1129
|
for entry in archive.entries {
|
|
1066
1130
|
let destPath = try resolveZipEntry(path: entry.path, destUnZip: destUnZip)
|
|
1131
|
+
do {
|
|
1132
|
+
// Symlinks extracted earlier must not move this entry out of the bundle folder.
|
|
1133
|
+
try Self.assertPhysicallyInsideDirectory(destPath.deletingLastPathComponent(), root: destUnZip)
|
|
1134
|
+
} catch {
|
|
1135
|
+
logger.error("Unzip failed: entry resolves outside the bundle folder")
|
|
1136
|
+
logger.debug("Entry: \(entry.path)")
|
|
1137
|
+
self.sendStats(action: "canonical_path_fail")
|
|
1138
|
+
throw CustomError.cannotUnzip
|
|
1139
|
+
}
|
|
1067
1140
|
|
|
1068
1141
|
if entry.type == .directory {
|
|
1069
1142
|
try FileManager.default.createDirectory(at: destPath, withIntermediateDirectories: true, attributes: nil)
|
|
@@ -1755,17 +1828,26 @@ import UIKit
|
|
|
1755
1828
|
)
|
|
1756
1829
|
let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
|
|
1757
1830
|
self.saveBundleInfo(id: id, bundle: errorBundle)
|
|
1831
|
+
removePartialManifestBundleDirectory(destFolder)
|
|
1758
1832
|
throw resolvedError
|
|
1759
1833
|
}
|
|
1760
1834
|
|
|
1761
1835
|
var operations: [Operation] = []
|
|
1762
1836
|
|
|
1763
1837
|
for task in tasks {
|
|
1764
|
-
|
|
1765
|
-
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1838
|
+
do {
|
|
1839
|
+
try FileManager.default.createDirectory(
|
|
1840
|
+
at: task.destFilePath.deletingLastPathComponent(),
|
|
1841
|
+
withIntermediateDirectories: true,
|
|
1842
|
+
attributes: nil
|
|
1843
|
+
)
|
|
1844
|
+
} catch {
|
|
1845
|
+
let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
|
|
1846
|
+
self.saveBundleInfo(id: id, bundle: errorBundle)
|
|
1847
|
+
removePartialManifestBundleDirectory(destFolder)
|
|
1848
|
+
self.notifyDownload(id: id, percent: 0, bundle: errorBundle)
|
|
1849
|
+
throw error
|
|
1850
|
+
}
|
|
1769
1851
|
|
|
1770
1852
|
let operation = BlockOperation { [weak self] in
|
|
1771
1853
|
guard let self = self else { return }
|
|
@@ -1833,6 +1915,7 @@ import UIKit
|
|
|
1833
1915
|
// Update bundle status to ERROR if download failed
|
|
1834
1916
|
let errorBundle = bundleInfo.setStatus(status: BundleStatus.ERROR.storedValue)
|
|
1835
1917
|
self.saveBundleInfo(id: id, bundle: errorBundle)
|
|
1918
|
+
removePartialManifestBundleDirectory(destFolder)
|
|
1836
1919
|
throw resolvedError
|
|
1837
1920
|
}
|
|
1838
1921
|
|
|
@@ -2252,8 +2335,47 @@ import UIKit
|
|
|
2252
2335
|
return hasher.hex()
|
|
2253
2336
|
}
|
|
2254
2337
|
|
|
2338
|
+
/// Resolves the checksum a zip bundle must match: required, and RSA-decrypted when a public key is set.
|
|
2339
|
+
func resolveExpectedBundleChecksum(_ checksum: String, versionName: String) throws -> String {
|
|
2340
|
+
if checksum.isEmpty {
|
|
2341
|
+
logger.error("No checksum provided")
|
|
2342
|
+
self.sendStats(action: "checksum_required", versionName: versionName)
|
|
2343
|
+
throw NSError(domain: "ChecksumError", code: 2, userInfo: [NSLocalizedDescriptionKey: "Checksum required"])
|
|
2344
|
+
}
|
|
2345
|
+
return try CryptoCipher.decryptChecksum(checksum: checksum, publicKey: self.publicKey)
|
|
2346
|
+
}
|
|
2347
|
+
|
|
2348
|
+
/// Downloads and extracts a zip bundle without checking its checksum; the caller must verify it.
|
|
2349
|
+
/// Prefer `downloadVerified`, which rejects a bad archive before extracting it.
|
|
2255
2350
|
public func download(url: URL, version: String, sessionKey: String, link: String? = nil, comment: String? = nil) throws -> BundleInfo {
|
|
2351
|
+
return try self.downloadZip(url: url, version: version, sessionKey: sessionKey, link: link, comment: comment, expectedChecksum: nil)
|
|
2352
|
+
}
|
|
2353
|
+
|
|
2354
|
+
/// Downloads a zip bundle and extracts it only when it matches `expectedChecksum`, the checksum from the
|
|
2355
|
+
/// update response (required, RSA-decrypted when a public key is set). The SHA-256 of the downloaded and
|
|
2356
|
+
/// decrypted archive is compared before anything is extracted: a mismatch deletes the archive, reports
|
|
2357
|
+
/// `checksum_fail` and throws `ObjectSavableError.checksum`.
|
|
2358
|
+
public func downloadVerified(
|
|
2359
|
+
url: URL,
|
|
2360
|
+
version: String,
|
|
2361
|
+
sessionKey: String,
|
|
2362
|
+
expectedChecksum: String,
|
|
2363
|
+
link: String? = nil,
|
|
2364
|
+
comment: String? = nil
|
|
2365
|
+
) throws -> BundleInfo {
|
|
2366
|
+
return try self.downloadZip(url: url, version: version, sessionKey: sessionKey, link: link, comment: comment, expectedChecksum: expectedChecksum)
|
|
2367
|
+
}
|
|
2368
|
+
|
|
2369
|
+
private func downloadZip(
|
|
2370
|
+
url: URL,
|
|
2371
|
+
version: String,
|
|
2372
|
+
sessionKey: String,
|
|
2373
|
+
link: String?,
|
|
2374
|
+
comment: String?,
|
|
2375
|
+
expectedChecksum: String?
|
|
2376
|
+
) throws -> BundleInfo {
|
|
2256
2377
|
try self.requireSessionKeyForEncryptedUpdate(sessionKey: sessionKey, versionName: version)
|
|
2378
|
+
let expectedHash = try expectedChecksum.map { try self.resolveExpectedBundleChecksum($0, versionName: version) }
|
|
2257
2379
|
try self.runBeforeDownload()
|
|
2258
2380
|
let id: String = self.randomString(length: 10)
|
|
2259
2381
|
// Each download uses its own temp files keyed by bundle ID to prevent collisions
|
|
@@ -2362,9 +2484,22 @@ import UIKit
|
|
|
2362
2484
|
throw error
|
|
2363
2485
|
}
|
|
2364
2486
|
|
|
2487
|
+
checksum = CryptoCipher.calcChecksum(filePath: finalPath)
|
|
2488
|
+
CryptoCipher.logChecksumInfo(label: "Calculated bundle checksum", hexChecksum: checksum)
|
|
2489
|
+
if let expectedHash, checksum.isEmpty || checksum != expectedHash {
|
|
2490
|
+
// Never extract an archive that failed verification.
|
|
2491
|
+
logger.error("Checksum mismatch, bundle rejected before extraction")
|
|
2492
|
+
CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: expectedHash)
|
|
2493
|
+
self.sendStats(action: "checksum_fail", versionName: version)
|
|
2494
|
+
try? FileManager.default.removeItem(at: finalPath)
|
|
2495
|
+
self.saveBundleInfo(id: id, bundle: BundleInfo(id: id, version: version, status: BundleStatus.ERROR, downloaded: Date(), checksum: checksum, link: link, comment: comment))
|
|
2496
|
+
cleanDownloadData(for: id)
|
|
2497
|
+
// Drop it like the previous post-extraction check did, so the next update check downloads it again.
|
|
2498
|
+
_ = self.delete(id: id)
|
|
2499
|
+
throw ObjectSavableError.checksum
|
|
2500
|
+
}
|
|
2501
|
+
|
|
2365
2502
|
do {
|
|
2366
|
-
checksum = CryptoCipher.calcChecksum(filePath: finalPath)
|
|
2367
|
-
CryptoCipher.logChecksumInfo(label: "Calculated bundle checksum", hexChecksum: checksum)
|
|
2368
2503
|
logger.info("Downloading: 80% (unzipping)")
|
|
2369
2504
|
try self.saveDownloaded(sourceZip: finalPath, id: id, base: self.libraryDir.appendingPathComponent(self.bundleDirectory), notify: true)
|
|
2370
2505
|
self.populateDeltaCacheAsync(for: id)
|
|
@@ -2989,6 +3124,16 @@ import UIKit
|
|
|
2989
3124
|
return true
|
|
2990
3125
|
}
|
|
2991
3126
|
|
|
3127
|
+
/// Points the current bundle back at `bundle` without sending stats, after an
|
|
3128
|
+
/// install whose reload failed left the WebView on it.
|
|
3129
|
+
func restoreCurrentBundle(_ bundle: BundleInfo) {
|
|
3130
|
+
if bundle.isBuiltin() {
|
|
3131
|
+
self.setCurrentBundle(bundle: "")
|
|
3132
|
+
} else {
|
|
3133
|
+
_ = self.stagePendingReload(bundle: bundle)
|
|
3134
|
+
}
|
|
3135
|
+
}
|
|
3136
|
+
|
|
2992
3137
|
func stagePreviewFallbackReload(bundle: BundleInfo) -> Bool {
|
|
2993
3138
|
guard !bundle.isErrorStatus() else {
|
|
2994
3139
|
return false
|
|
@@ -3799,6 +3944,17 @@ import UIKit
|
|
|
3799
3944
|
return self.getBundleInfo(id: id)
|
|
3800
3945
|
}
|
|
3801
3946
|
|
|
3947
|
+
/// Clears the stored next bundle when it is already the running bundle, so nothing stays pending.
|
|
3948
|
+
@discardableResult
|
|
3949
|
+
public func clearNextBundleIfCurrent() -> Bool {
|
|
3950
|
+
guard let next = self.getNextBundle(), !next.isUnknown(), next.getId() == self.getCurrentBundle().getId() else {
|
|
3951
|
+
return false
|
|
3952
|
+
}
|
|
3953
|
+
logger?.info("Next bundle \(next.getId()) is already the current bundle. Clearing next.")
|
|
3954
|
+
_ = self.setNextBundle(next: Optional<String>.none)
|
|
3955
|
+
return true
|
|
3956
|
+
}
|
|
3957
|
+
|
|
3802
3958
|
public func getPreviewFallbackBundle() -> BundleInfo? {
|
|
3803
3959
|
guard let id = UserDefaults.standard.string(forKey: self.PREVIEW_FALLBACK_VERSION) else {
|
|
3804
3960
|
return nil
|
|
@@ -239,9 +239,10 @@ public struct CryptoCipher {
|
|
|
239
239
|
return
|
|
240
240
|
}
|
|
241
241
|
|
|
242
|
+
// The bundle is encrypted from here on: an unusable key must fail, never leave it encrypted.
|
|
242
243
|
if !publicKey.hasPrefix("-----BEGIN RSA PUBLIC KEY-----") {
|
|
243
244
|
logger.error("The public key is not a valid RSA Public key")
|
|
244
|
-
|
|
245
|
+
throw CustomError.cannotDecode
|
|
245
246
|
}
|
|
246
247
|
|
|
247
248
|
do {
|
|
@@ -18,6 +18,9 @@ public class DelayUpdateUtils {
|
|
|
18
18
|
|
|
19
19
|
// swiftlint:disable identifier_name
|
|
20
20
|
static let DELAY_CONDITION_PREFERENCES = "DELAY_CONDITION_PREFERENCES_CAPGO"
|
|
21
|
+
static let DELAY_CONDITION_MODE_PREFERENCES = "DELAY_CONDITION_MODE_PREFERENCES_CAPGO"
|
|
22
|
+
static let DELAY_CONDITION_MODE_AND = "and"
|
|
23
|
+
static let DELAY_CONDITION_MODE_OR = "or"
|
|
21
24
|
static let BACKGROUND_TIMESTAMP_KEY = "BACKGROUND_TIMESTAMP_KEY_CAPGO"
|
|
22
25
|
// swiftlint:enable identifier_name
|
|
23
26
|
private let logger: Logger
|
|
@@ -46,114 +49,219 @@ public class DelayUpdateUtils {
|
|
|
46
49
|
public func checkCancelDelay(source: CancelDelaySource) {
|
|
47
50
|
let delayUpdatePreferences = UserDefaults.standard.string(
|
|
48
51
|
forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
|
|
49
|
-
let delayConditionList
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
return DelayCondition(kind: kind, value: value)
|
|
52
|
+
let delayConditionList = DelayUpdateUtils.parseDelayConditions(json: delayUpdatePreferences)
|
|
53
|
+
if delayConditionList.isEmpty {
|
|
54
|
+
return
|
|
53
55
|
}
|
|
54
56
|
|
|
57
|
+
let useOrMode = isOrConditionMode()
|
|
55
58
|
var delayConditionListToKeep: [DelayCondition] = []
|
|
56
59
|
var index = 0
|
|
60
|
+
var anyConditionMet = false
|
|
57
61
|
|
|
58
62
|
for condition in delayConditionList {
|
|
59
|
-
let
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
if source == .foreground {
|
|
65
|
-
let backgroundedAt = getBackgroundTimestamp()
|
|
66
|
-
let now = Int64(Date().timeIntervalSince1970 * 1000) // Convert to milliseconds
|
|
67
|
-
let delta = max(0, now - backgroundedAt)
|
|
68
|
-
|
|
69
|
-
var longValue: Int64 = 0
|
|
70
|
-
if let value = value, !value.isEmpty {
|
|
71
|
-
longValue = Int64(value) ?? 0
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
if delta > longValue {
|
|
75
|
-
// swiftlint:disable:next line_length
|
|
76
|
-
logger.info("Background condition (value: \(value ?? "")) deleted at index \(index). Delta: \(delta), longValue: \(longValue)")
|
|
77
|
-
} else {
|
|
78
|
-
delayConditionListToKeep.append(condition)
|
|
79
|
-
// swiftlint:disable:next line_length
|
|
80
|
-
logger.info("Background delay (value: \(value ?? "")) condition kept at index \(index) (source: \(source.description))")
|
|
81
|
-
}
|
|
82
|
-
} else {
|
|
83
|
-
delayConditionListToKeep.append(condition)
|
|
84
|
-
// swiftlint:disable:next line_length
|
|
85
|
-
logger.info("Background delay (value: \(value ?? "")) condition kept at index \(index) (source: \(source.description))")
|
|
63
|
+
let result = evaluateCondition(condition, source: source, index: index)
|
|
64
|
+
if result.met {
|
|
65
|
+
anyConditionMet = true
|
|
66
|
+
if !useOrMode, let logMessage = result.logMessage {
|
|
67
|
+
logger.info(logMessage)
|
|
86
68
|
}
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
if source == .killed {
|
|
90
|
-
logger.info("Kill delay (value: \(value ?? "")) removed at index \(index) after app kill")
|
|
91
|
-
} else {
|
|
69
|
+
} else {
|
|
70
|
+
if result.keep {
|
|
92
71
|
delayConditionListToKeep.append(condition)
|
|
93
|
-
// swiftlint:disable:next line_length
|
|
94
|
-
logger.info("Kill delay (value: \(value ?? "")) condition kept at index \(index) (source: \(source.description))")
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
case "date":
|
|
98
|
-
if let value = value, !value.isEmpty {
|
|
99
|
-
if let date = parseDateCondition(value) {
|
|
100
|
-
if Date() > date {
|
|
101
|
-
// swiftlint:disable:next line_length
|
|
102
|
-
logger.info("Date delay (value: \(value)) condition removed due to expired date at index \(index)")
|
|
103
|
-
} else {
|
|
104
|
-
delayConditionListToKeep.append(condition)
|
|
105
|
-
logger.info("Date delay (value: \(value)) kept at index \(index)")
|
|
106
|
-
}
|
|
107
|
-
} else {
|
|
108
|
-
// swiftlint:disable:next line_length
|
|
109
|
-
logger.error("Date delay (value: \(value)) condition removed due to parsing issue at index \(index)")
|
|
110
|
-
}
|
|
111
|
-
} else {
|
|
112
|
-
// swiftlint:disable:next line_length
|
|
113
|
-
logger.error("Date delay (value: \(value ?? "")) condition removed due to empty value at index \(index)")
|
|
114
72
|
}
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
if currentVersionNative >= versionLimit {
|
|
121
|
-
// swiftlint:disable:next line_length
|
|
122
|
-
logger.info("Native version delay (value: \(value)) condition removed due to above limit at index \(index)")
|
|
123
|
-
} else {
|
|
124
|
-
delayConditionListToKeep.append(condition)
|
|
125
|
-
logger.info("Native version delay (value: \(value)) kept at index \(index)")
|
|
126
|
-
}
|
|
127
|
-
} catch {
|
|
128
|
-
// swiftlint:disable:next line_length
|
|
129
|
-
logger.error("Native version delay (value: \(value)) condition removed due to parsing issue at index \(index): \(error)")
|
|
73
|
+
if let logMessage = result.logMessage, !useOrMode || result.error {
|
|
74
|
+
if result.error {
|
|
75
|
+
logger.error(logMessage)
|
|
76
|
+
} else if !useOrMode {
|
|
77
|
+
logger.info(logMessage)
|
|
130
78
|
}
|
|
131
|
-
} else {
|
|
132
|
-
// swiftlint:disable:next line_length
|
|
133
|
-
logger.error("Native version delay (value: \(value ?? "")) condition removed due to empty value at index \(index)")
|
|
134
79
|
}
|
|
135
|
-
|
|
136
|
-
default:
|
|
137
|
-
logger.error("Unknown delay condition kind: \(kind) at index \(index)")
|
|
138
80
|
}
|
|
139
|
-
|
|
140
81
|
index += 1
|
|
141
82
|
}
|
|
142
83
|
|
|
84
|
+
if useOrMode {
|
|
85
|
+
if anyConditionMet {
|
|
86
|
+
logger.info("Delay condition met in OR mode (source: \(source.description)), canceling delay")
|
|
87
|
+
_ = cancelDelay(source: "checkCancelDelay")
|
|
88
|
+
} else if delayConditionListToKeep.isEmpty {
|
|
89
|
+
_ = cancelDelay(source: "checkCancelDelay")
|
|
90
|
+
} else if delayConditionListToKeep.count != delayConditionList.count {
|
|
91
|
+
let json = toJson(object: delayConditionListToKeep.map { $0.toJSON() })
|
|
92
|
+
_ = setMultiDelay(delayConditions: json)
|
|
93
|
+
}
|
|
94
|
+
return
|
|
95
|
+
}
|
|
96
|
+
|
|
143
97
|
if !delayConditionListToKeep.isEmpty {
|
|
144
98
|
let json = toJson(object: delayConditionListToKeep.map { $0.toJSON() })
|
|
145
99
|
_ = setMultiDelay(delayConditions: json)
|
|
146
100
|
} else {
|
|
147
|
-
// Clear all delay conditions if none are left to keep
|
|
148
101
|
_ = cancelDelay(source: "checkCancelDelay")
|
|
149
102
|
}
|
|
150
103
|
}
|
|
151
104
|
|
|
105
|
+
private struct ConditionCheckResult {
|
|
106
|
+
let met: Bool
|
|
107
|
+
let keep: Bool
|
|
108
|
+
let error: Bool
|
|
109
|
+
let logMessage: String?
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
private func evaluateCondition(_ condition: DelayCondition, source: CancelDelaySource, index: Int) -> ConditionCheckResult {
|
|
113
|
+
let kind = condition.getKind()
|
|
114
|
+
let value = condition.getValue()
|
|
115
|
+
|
|
116
|
+
switch kind {
|
|
117
|
+
case "background":
|
|
118
|
+
if source == .foreground {
|
|
119
|
+
let backgroundedAt = getBackgroundTimestamp()
|
|
120
|
+
let now = Int64(Date().timeIntervalSince1970 * 1000)
|
|
121
|
+
let delta = max(0, now - backgroundedAt)
|
|
122
|
+
var longValue: Int64 = 0
|
|
123
|
+
if let value = value, !value.isEmpty {
|
|
124
|
+
longValue = Int64(value) ?? 0
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if delta > longValue {
|
|
128
|
+
return ConditionCheckResult(
|
|
129
|
+
met: true,
|
|
130
|
+
keep: false,
|
|
131
|
+
error: false,
|
|
132
|
+
logMessage: "Background condition (value: \(value ?? "")) deleted at index \(index). Delta: \(delta), longValue: \(longValue)"
|
|
133
|
+
)
|
|
134
|
+
}
|
|
135
|
+
return ConditionCheckResult(
|
|
136
|
+
met: false,
|
|
137
|
+
keep: true,
|
|
138
|
+
error: false,
|
|
139
|
+
logMessage: "Background delay (value: \(value ?? "")) condition kept at index \(index) (source: \(source.description))"
|
|
140
|
+
)
|
|
141
|
+
}
|
|
142
|
+
return ConditionCheckResult(
|
|
143
|
+
met: false,
|
|
144
|
+
keep: true,
|
|
145
|
+
error: false,
|
|
146
|
+
logMessage: "Background delay (value: \(value ?? "")) condition kept at index \(index) (source: \(source.description))"
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
case "kill":
|
|
150
|
+
if source == .killed {
|
|
151
|
+
return ConditionCheckResult(
|
|
152
|
+
met: true,
|
|
153
|
+
keep: false,
|
|
154
|
+
error: false,
|
|
155
|
+
logMessage: "Kill delay (value: \(value ?? "")) removed at index \(index) after app kill"
|
|
156
|
+
)
|
|
157
|
+
}
|
|
158
|
+
return ConditionCheckResult(
|
|
159
|
+
met: false,
|
|
160
|
+
keep: true,
|
|
161
|
+
error: false,
|
|
162
|
+
logMessage: "Kill delay (value: \(value ?? "")) condition kept at index \(index) (source: \(source.description))"
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
case "date":
|
|
166
|
+
if let value = value, !value.isEmpty {
|
|
167
|
+
if let date = parseDateCondition(value) {
|
|
168
|
+
if Date() > date {
|
|
169
|
+
return ConditionCheckResult(
|
|
170
|
+
met: true,
|
|
171
|
+
keep: false,
|
|
172
|
+
error: false,
|
|
173
|
+
logMessage: "Date delay (value: \(value)) condition removed due to expired date at index \(index)"
|
|
174
|
+
)
|
|
175
|
+
}
|
|
176
|
+
return ConditionCheckResult(met: false, keep: true, error: false, logMessage: "Date delay (value: \(value)) kept at index \(index)")
|
|
177
|
+
}
|
|
178
|
+
return ConditionCheckResult(
|
|
179
|
+
met: false,
|
|
180
|
+
keep: false,
|
|
181
|
+
error: true,
|
|
182
|
+
logMessage: "Date delay (value: \(value)) condition removed due to parsing issue at index \(index)"
|
|
183
|
+
)
|
|
184
|
+
}
|
|
185
|
+
return ConditionCheckResult(
|
|
186
|
+
met: false,
|
|
187
|
+
keep: false,
|
|
188
|
+
error: true,
|
|
189
|
+
logMessage: "Date delay (value: \(value ?? "")) condition removed due to empty value at index \(index)"
|
|
190
|
+
)
|
|
191
|
+
|
|
192
|
+
case "nativeVersion":
|
|
193
|
+
if let value = value, !value.isEmpty {
|
|
194
|
+
do {
|
|
195
|
+
let versionLimit = try CapgoSemanticVersion(value)
|
|
196
|
+
if currentVersionNative >= versionLimit {
|
|
197
|
+
return ConditionCheckResult(
|
|
198
|
+
met: true,
|
|
199
|
+
keep: false,
|
|
200
|
+
error: false,
|
|
201
|
+
logMessage: "Native version delay (value: \(value)) condition removed due to above limit at index \(index)"
|
|
202
|
+
)
|
|
203
|
+
}
|
|
204
|
+
return ConditionCheckResult(met: false, keep: true, error: false, logMessage: "Native version delay (value: \(value)) kept at index \(index)")
|
|
205
|
+
} catch {
|
|
206
|
+
return ConditionCheckResult(
|
|
207
|
+
met: false,
|
|
208
|
+
keep: false,
|
|
209
|
+
error: true,
|
|
210
|
+
logMessage: "Native version delay (value: \(value)) condition removed due to parsing issue at index \(index): \(error)"
|
|
211
|
+
)
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return ConditionCheckResult(
|
|
215
|
+
met: false,
|
|
216
|
+
keep: false,
|
|
217
|
+
error: true,
|
|
218
|
+
logMessage: "Native version delay (value: \(value ?? "")) condition removed due to empty value at index \(index)"
|
|
219
|
+
)
|
|
220
|
+
|
|
221
|
+
default:
|
|
222
|
+
return ConditionCheckResult(met: false, keep: false, error: true, logMessage: "Unknown delay condition kind: \(kind) at index \(index)")
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
public func isOrConditionMode() -> Bool {
|
|
227
|
+
return getConditionMode() == DelayUpdateUtils.DELAY_CONDITION_MODE_OR
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
public func getConditionMode() -> String {
|
|
231
|
+
let mode = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_MODE_PREFERENCES)
|
|
232
|
+
?? DelayUpdateUtils.DELAY_CONDITION_MODE_AND
|
|
233
|
+
return mode == DelayUpdateUtils.DELAY_CONDITION_MODE_OR
|
|
234
|
+
? DelayUpdateUtils.DELAY_CONDITION_MODE_OR
|
|
235
|
+
: DelayUpdateUtils.DELAY_CONDITION_MODE_AND
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
public func setConditionMode(_ conditionMode: String) -> Bool {
|
|
239
|
+
let normalized = conditionMode == DelayUpdateUtils.DELAY_CONDITION_MODE_OR
|
|
240
|
+
? DelayUpdateUtils.DELAY_CONDITION_MODE_OR
|
|
241
|
+
: DelayUpdateUtils.DELAY_CONDITION_MODE_AND
|
|
242
|
+
if conditionMode != DelayUpdateUtils.DELAY_CONDITION_MODE_AND
|
|
243
|
+
&& conditionMode != DelayUpdateUtils.DELAY_CONDITION_MODE_OR {
|
|
244
|
+
logger.warn("Unknown delay condition mode '\(conditionMode)', defaulting to '\(DelayUpdateUtils.DELAY_CONDITION_MODE_AND)'")
|
|
245
|
+
}
|
|
246
|
+
UserDefaults.standard.set(normalized, forKey: DelayUpdateUtils.DELAY_CONDITION_MODE_PREFERENCES)
|
|
247
|
+
let synchronized = UserDefaults.standard.synchronize()
|
|
248
|
+
if synchronized {
|
|
249
|
+
logger.info("Delay condition mode saved: \(normalized)")
|
|
250
|
+
} else {
|
|
251
|
+
logger.error("Failed to save delay condition mode: synchronize returned false")
|
|
252
|
+
}
|
|
253
|
+
return synchronized
|
|
254
|
+
}
|
|
255
|
+
|
|
152
256
|
public func setMultiDelay(delayConditions: String) -> Bool {
|
|
153
257
|
UserDefaults.standard.set(delayConditions, forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES)
|
|
154
|
-
UserDefaults.standard.synchronize()
|
|
155
|
-
|
|
156
|
-
|
|
258
|
+
let synchronized = UserDefaults.standard.synchronize()
|
|
259
|
+
if synchronized {
|
|
260
|
+
logger.info("Delay update saved")
|
|
261
|
+
} else {
|
|
262
|
+
logger.error("Failed to delay update: synchronize returned false")
|
|
263
|
+
}
|
|
264
|
+
return synchronized
|
|
157
265
|
}
|
|
158
266
|
|
|
159
267
|
public func setBackgroundTimestamp(_ backgroundTimestamp: Int64) {
|
|
@@ -175,6 +283,7 @@ public class DelayUpdateUtils {
|
|
|
175
283
|
|
|
176
284
|
public func cancelDelay(source: String) -> Bool {
|
|
177
285
|
UserDefaults.standard.removeObject(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES)
|
|
286
|
+
UserDefaults.standard.removeObject(forKey: DelayUpdateUtils.DELAY_CONDITION_MODE_PREFERENCES)
|
|
178
287
|
UserDefaults.standard.synchronize()
|
|
179
288
|
logger.info("All delays canceled from \(source)")
|
|
180
289
|
return true
|
|
@@ -218,14 +327,17 @@ public class DelayUpdateUtils {
|
|
|
218
327
|
return String(data: data, encoding: String.Encoding.utf8) ?? ""
|
|
219
328
|
}
|
|
220
329
|
|
|
221
|
-
|
|
222
|
-
|
|
330
|
+
/// Parses stored delay conditions. Malformed JSON and entries without a string `kind` are dropped.
|
|
331
|
+
static func parseDelayConditions(json: String) -> [DelayCondition] {
|
|
332
|
+
guard let jsonData = json.data(using: .utf8),
|
|
333
|
+
let entries = (try? JSONSerialization.jsonObject(with: jsonData)) as? [Any] else {
|
|
223
334
|
return []
|
|
224
335
|
}
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
336
|
+
return entries.compactMap { entry in
|
|
337
|
+
guard let object = entry as? [String: Any], let kind = object["kind"] as? String else {
|
|
338
|
+
return nil
|
|
339
|
+
}
|
|
340
|
+
return DelayCondition(kind: kind, value: object["value"] as? String)
|
|
341
|
+
}
|
|
230
342
|
}
|
|
231
343
|
}
|