@capgo/capacitor-updater 8.0.1 → 8.2.0

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.
Files changed (55) hide show
  1. package/CapgoCapacitorUpdater.podspec +7 -5
  2. package/Package.swift +9 -7
  3. package/README.md +984 -215
  4. package/android/build.gradle +24 -12
  5. package/android/proguard-rules.pro +22 -5
  6. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +110 -22
  7. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +2 -2
  8. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +1316 -489
  9. package/android/src/main/java/ee/forgr/capacitor_updater/{CapacitorUpdater.java → CapgoUpdater.java} +662 -203
  10. package/android/src/main/java/ee/forgr/capacitor_updater/{CryptoCipherV2.java → CryptoCipher.java} +138 -33
  11. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +0 -3
  12. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +260 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +221 -0
  14. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +497 -133
  15. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +80 -25
  16. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +338 -0
  17. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
  18. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +169 -0
  19. package/dist/docs.json +873 -154
  20. package/dist/esm/definitions.d.ts +881 -114
  21. package/dist/esm/definitions.js.map +1 -1
  22. package/dist/esm/history.d.ts +1 -0
  23. package/dist/esm/history.js +283 -0
  24. package/dist/esm/history.js.map +1 -0
  25. package/dist/esm/index.d.ts +1 -0
  26. package/dist/esm/index.js +1 -0
  27. package/dist/esm/index.js.map +1 -1
  28. package/dist/esm/web.d.ts +12 -1
  29. package/dist/esm/web.js +29 -2
  30. package/dist/esm/web.js.map +1 -1
  31. package/dist/plugin.cjs.js +311 -2
  32. package/dist/plugin.cjs.js.map +1 -1
  33. package/dist/plugin.js +311 -2
  34. package/dist/plugin.js.map +1 -1
  35. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +69 -0
  36. package/ios/Sources/CapacitorUpdaterPlugin/BigInt.swift +55 -0
  37. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/BundleInfo.swift +37 -10
  38. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/BundleStatus.swift +1 -1
  39. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1610 -0
  40. package/ios/{Plugin/CapacitorUpdater.swift → Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift} +541 -231
  41. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +286 -0
  42. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +220 -0
  43. package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
  44. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/InternalUtils.swift +54 -0
  45. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +310 -0
  46. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +274 -0
  47. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +112 -0
  48. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
  49. package/package.json +21 -19
  50. package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -975
  51. package/ios/Plugin/CryptoCipherV2.swift +0 -310
  52. /package/{LICENCE → LICENSE} +0 -0
  53. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
  54. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
  55. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
@@ -0,0 +1,1610 @@
1
+ /*
2
+ * This Source Code Form is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at https://mozilla.org/MPL/2.0/.
5
+ */
6
+
7
+ import Foundation
8
+ import Capacitor
9
+ import UIKit
10
+ import WebKit
11
+ import Version
12
+
13
+ /**
14
+ * Please read the Capacitor iOS Plugin Development Guide
15
+ * here: https://capacitorjs.com/docs/plugins/ios
16
+ */
17
+ @objc(CapacitorUpdaterPlugin)
18
+ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
19
+ let logger = Logger(withTag: "✨ CapgoUpdater")
20
+
21
+ public let identifier = "CapacitorUpdaterPlugin"
22
+ public let jsName = "CapacitorUpdater"
23
+ public let pluginMethods: [CAPPluginMethod] = [
24
+ CAPPluginMethod(name: "download", returnType: CAPPluginReturnPromise),
25
+ CAPPluginMethod(name: "setUpdateUrl", returnType: CAPPluginReturnPromise),
26
+ CAPPluginMethod(name: "setStatsUrl", returnType: CAPPluginReturnPromise),
27
+ CAPPluginMethod(name: "setChannelUrl", returnType: CAPPluginReturnPromise),
28
+ CAPPluginMethod(name: "set", returnType: CAPPluginReturnPromise),
29
+ CAPPluginMethod(name: "list", returnType: CAPPluginReturnPromise),
30
+ CAPPluginMethod(name: "delete", returnType: CAPPluginReturnPromise),
31
+ CAPPluginMethod(name: "setBundleError", returnType: CAPPluginReturnPromise),
32
+ CAPPluginMethod(name: "reset", returnType: CAPPluginReturnPromise),
33
+ CAPPluginMethod(name: "current", returnType: CAPPluginReturnPromise),
34
+ CAPPluginMethod(name: "reload", returnType: CAPPluginReturnPromise),
35
+ CAPPluginMethod(name: "notifyAppReady", returnType: CAPPluginReturnPromise),
36
+ CAPPluginMethod(name: "setDelay", returnType: CAPPluginReturnPromise),
37
+ CAPPluginMethod(name: "setMultiDelay", returnType: CAPPluginReturnPromise),
38
+ CAPPluginMethod(name: "cancelDelay", returnType: CAPPluginReturnPromise),
39
+ CAPPluginMethod(name: "getLatest", returnType: CAPPluginReturnPromise),
40
+ CAPPluginMethod(name: "setChannel", returnType: CAPPluginReturnPromise),
41
+ CAPPluginMethod(name: "unsetChannel", returnType: CAPPluginReturnPromise),
42
+ CAPPluginMethod(name: "getChannel", returnType: CAPPluginReturnPromise),
43
+ CAPPluginMethod(name: "listChannels", returnType: CAPPluginReturnPromise),
44
+ CAPPluginMethod(name: "setCustomId", returnType: CAPPluginReturnPromise),
45
+ CAPPluginMethod(name: "getDeviceId", returnType: CAPPluginReturnPromise),
46
+ CAPPluginMethod(name: "getPluginVersion", returnType: CAPPluginReturnPromise),
47
+ CAPPluginMethod(name: "next", returnType: CAPPluginReturnPromise),
48
+ CAPPluginMethod(name: "isAutoUpdateEnabled", returnType: CAPPluginReturnPromise),
49
+ CAPPluginMethod(name: "getBuiltinVersion", returnType: CAPPluginReturnPromise),
50
+ CAPPluginMethod(name: "isAutoUpdateAvailable", returnType: CAPPluginReturnPromise),
51
+ CAPPluginMethod(name: "getNextBundle", returnType: CAPPluginReturnPromise),
52
+ CAPPluginMethod(name: "getFailedUpdate", returnType: CAPPluginReturnPromise),
53
+ CAPPluginMethod(name: "setShakeMenu", returnType: CAPPluginReturnPromise),
54
+ CAPPluginMethod(name: "isShakeMenuEnabled", returnType: CAPPluginReturnPromise)
55
+ ]
56
+ public var implementation = CapgoUpdater()
57
+ private let pluginVersion: String = "8.2.0"
58
+ static let updateUrlDefault = "https://plugin.capgo.app/updates"
59
+ static let statsUrlDefault = "https://plugin.capgo.app/stats"
60
+ static let channelUrlDefault = "https://plugin.capgo.app/channel_self"
61
+ private let keepUrlPathFlagKey = "__capgo_keep_url_path_after_reload"
62
+ private let customIdDefaultsKey = "CapacitorUpdater.customId"
63
+ private let updateUrlDefaultsKey = "CapacitorUpdater.updateUrl"
64
+ private let statsUrlDefaultsKey = "CapacitorUpdater.statsUrl"
65
+ private let channelUrlDefaultsKey = "CapacitorUpdater.channelUrl"
66
+ private let defaultChannelDefaultsKey = "CapacitorUpdater.defaultChannel"
67
+ private let lastFailedBundleDefaultsKey = "CapacitorUpdater.lastFailedBundle"
68
+ // Note: DELAY_CONDITION_PREFERENCES is now defined in DelayUpdateUtils.DELAY_CONDITION_PREFERENCES
69
+ private var updateUrl = ""
70
+ private var backgroundTaskID: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid
71
+ private var currentVersionNative: Version = "0.0.0"
72
+ private var currentBuildVersion: String = "0"
73
+ private var autoUpdate = false
74
+ private var appReadyTimeout = 10000
75
+ private var appReadyCheck: DispatchWorkItem?
76
+ private var resetWhenUpdate = true
77
+ private var directUpdate = false
78
+ private var directUpdateMode: String = "false"
79
+ private var wasRecentlyInstalledOrUpdated = false
80
+ private var onLaunchDirectUpdateUsed = false
81
+ private var autoSplashscreen = false
82
+ private var autoSplashscreenLoader = false
83
+ private var autoSplashscreenTimeout = 10000
84
+ private var autoSplashscreenTimeoutWorkItem: DispatchWorkItem?
85
+ private var splashscreenLoaderView: UIActivityIndicatorView?
86
+ private var splashscreenLoaderContainer: UIView?
87
+ private var autoSplashscreenTimedOut = false
88
+ private var autoDeleteFailed = false
89
+ private var autoDeletePrevious = false
90
+ private var allowSetDefaultChannel = true
91
+ private var keepUrlPathAfterReload = false
92
+ private var backgroundWork: DispatchWorkItem?
93
+ private var taskRunning = false
94
+ private var periodCheckDelay = 0
95
+ private var persistCustomId = false
96
+ private var persistModifyUrl = false
97
+ private var allowManualBundleError = false
98
+ private var keepUrlPathFlagLastValue: Bool?
99
+ public var shakeMenuEnabled = false
100
+ let semaphoreReady = DispatchSemaphore(value: 0)
101
+
102
+ private var delayUpdateUtils: DelayUpdateUtils!
103
+
104
+ override public func load() {
105
+ let disableJSLogging = getConfig().getBoolean("disableJSLogging", false)
106
+ // Set webView for logging to JavaScript console
107
+ if let webView = self.bridge?.webView, !disableJSLogging {
108
+ logger.setWebView(webView: webView)
109
+ logger.info("WebView set successfully for logging")
110
+ } else {
111
+ logger.error("Failed to get webView for logging")
112
+ }
113
+ #if targetEnvironment(simulator)
114
+ logger.info("::::: SIMULATOR :::::")
115
+ logger.info("Application directory: \(NSHomeDirectory())")
116
+ #endif
117
+
118
+ self.semaphoreUp()
119
+ // Use DeviceIdHelper to get or create device ID that persists across reinstalls
120
+ self.implementation.deviceID = DeviceIdHelper.getOrCreateDeviceId()
121
+ persistCustomId = getConfig().getBoolean("persistCustomId", false)
122
+ allowSetDefaultChannel = getConfig().getBoolean("allowSetDefaultChannel", true)
123
+ if persistCustomId {
124
+ let storedCustomId = UserDefaults.standard.string(forKey: customIdDefaultsKey) ?? ""
125
+ if !storedCustomId.isEmpty {
126
+ implementation.customId = storedCustomId
127
+ logger.info("Loaded persisted customId")
128
+ }
129
+ }
130
+ persistModifyUrl = getConfig().getBoolean("persistModifyUrl", false)
131
+ allowManualBundleError = getConfig().getBoolean("allowManualBundleError", false)
132
+ logger.info("init for device \(self.implementation.deviceID)")
133
+ guard let versionName = getConfig().getString("version", Bundle.main.versionName) else {
134
+ logger.error("Cannot get version name")
135
+ // crash the app on purpose
136
+ fatalError("Cannot get version name")
137
+ }
138
+ do {
139
+ currentVersionNative = try Version(versionName)
140
+ } catch {
141
+ logger.error("Cannot parse versionName \(versionName)")
142
+ }
143
+ currentBuildVersion = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "0"
144
+ logger.info("version native \(self.currentVersionNative.description)")
145
+ implementation.versionBuild = getConfig().getString("version", Bundle.main.versionName)!
146
+ autoDeleteFailed = getConfig().getBoolean("autoDeleteFailed", true)
147
+ autoDeletePrevious = getConfig().getBoolean("autoDeletePrevious", true)
148
+ keepUrlPathAfterReload = getConfig().getBoolean("keepUrlPathAfterReload", false)
149
+ syncKeepUrlPathFlag(enabled: keepUrlPathAfterReload)
150
+
151
+ // Handle directUpdate configuration - support string values and backward compatibility
152
+ if let directUpdateString = getConfig().getString("directUpdate") {
153
+ // Handle backward compatibility for boolean true
154
+ if directUpdateString == "true" {
155
+ directUpdateMode = "always"
156
+ directUpdate = true
157
+ } else {
158
+ directUpdateMode = directUpdateString
159
+ directUpdate = directUpdateString == "always" || directUpdateString == "atInstall" || directUpdateString == "onLaunch"
160
+ // Validate directUpdate value
161
+ if directUpdateString != "false" && directUpdateString != "always" && directUpdateString != "atInstall" && directUpdateString != "onLaunch" {
162
+ logger.error("Invalid directUpdate value: \"\(directUpdateString)\". Supported values are: \"false\", \"true\", \"always\", \"atInstall\", \"onLaunch\". Defaulting to \"false\".")
163
+ directUpdateMode = "false"
164
+ directUpdate = false
165
+ }
166
+ }
167
+ } else {
168
+ let directUpdateBool = getConfig().getBoolean("directUpdate", false)
169
+ if directUpdateBool {
170
+ directUpdateMode = "always" // backward compatibility: true = always
171
+ directUpdate = true
172
+ } else {
173
+ directUpdateMode = "false"
174
+ directUpdate = false
175
+ }
176
+ }
177
+
178
+ autoSplashscreen = getConfig().getBoolean("autoSplashscreen", false)
179
+ autoSplashscreenLoader = getConfig().getBoolean("autoSplashscreenLoader", false)
180
+ let splashscreenTimeoutValue = getConfig().getInt("autoSplashscreenTimeout", 10000)
181
+ autoSplashscreenTimeout = max(0, splashscreenTimeoutValue)
182
+ updateUrl = getConfig().getString("updateUrl", CapacitorUpdaterPlugin.updateUrlDefault)!
183
+ if persistModifyUrl, let storedUpdateUrl = UserDefaults.standard.object(forKey: updateUrlDefaultsKey) as? String {
184
+ updateUrl = storedUpdateUrl
185
+ logger.info("Loaded persisted updateUrl")
186
+ }
187
+ autoUpdate = getConfig().getBoolean("autoUpdate", true)
188
+ appReadyTimeout = getConfig().getInt("appReadyTimeout", 10000)
189
+ implementation.timeout = Double(getConfig().getInt("responseTimeout", 20))
190
+ resetWhenUpdate = getConfig().getBoolean("resetWhenUpdate", true)
191
+ shakeMenuEnabled = getConfig().getBoolean("shakeMenu", false)
192
+ let periodCheckDelayValue = getConfig().getInt("periodCheckDelay", 0)
193
+ if periodCheckDelayValue >= 0 && periodCheckDelayValue > 600 {
194
+ periodCheckDelay = 600
195
+ } else {
196
+ periodCheckDelay = periodCheckDelayValue
197
+ }
198
+
199
+ implementation.setPublicKey(getConfig().getString("publicKey") ?? "")
200
+ implementation.notifyDownloadRaw = notifyDownload
201
+ implementation.pluginVersion = self.pluginVersion
202
+
203
+ // Set logger for shared classes
204
+ implementation.setLogger(logger)
205
+ CryptoCipher.setLogger(logger)
206
+
207
+ // Log public key prefix if encryption is enabled
208
+ if let keyId = implementation.getKeyId(), !keyId.isEmpty {
209
+ logger.info("Public key prefix: \(keyId)")
210
+ }
211
+
212
+ // Initialize DelayUpdateUtils
213
+ self.delayUpdateUtils = DelayUpdateUtils(currentVersionNative: currentVersionNative, logger: logger)
214
+ let config = (self.bridge?.viewController as? CAPBridgeViewController)?.instanceDescriptor().legacyConfig
215
+ implementation.appId = Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String ?? ""
216
+ implementation.appId = config?["appId"] as? String ?? implementation.appId
217
+ implementation.appId = getConfig().getString("appId", implementation.appId)!
218
+ if implementation.appId == "" {
219
+ // crash the app on purpose it should not happen
220
+ fatalError("appId is missing in capacitor.config.json or plugin config, and cannot be retrieved from the native app, please add it globally or in the plugin config")
221
+ }
222
+ logger.info("appId \(implementation.appId)")
223
+ implementation.statsUrl = getConfig().getString("statsUrl", CapacitorUpdaterPlugin.statsUrlDefault)!
224
+ implementation.channelUrl = getConfig().getString("channelUrl", CapacitorUpdaterPlugin.channelUrlDefault)!
225
+ if persistModifyUrl {
226
+ if let storedStatsUrl = UserDefaults.standard.object(forKey: statsUrlDefaultsKey) as? String {
227
+ implementation.statsUrl = storedStatsUrl
228
+ logger.info("Loaded persisted statsUrl")
229
+ }
230
+ if let storedChannelUrl = UserDefaults.standard.object(forKey: channelUrlDefaultsKey) as? String {
231
+ implementation.channelUrl = storedChannelUrl
232
+ logger.info("Loaded persisted channelUrl")
233
+ }
234
+ }
235
+
236
+ // Load defaultChannel: first try from persistent storage (set via setChannel), then fall back to config
237
+ if let storedDefaultChannel = UserDefaults.standard.object(forKey: defaultChannelDefaultsKey) as? String {
238
+ implementation.defaultChannel = storedDefaultChannel
239
+ logger.info("Loaded persisted defaultChannel from setChannel()")
240
+ } else {
241
+ implementation.defaultChannel = getConfig().getString("defaultChannel", "")!
242
+ }
243
+ self.implementation.autoReset()
244
+
245
+ // Check if app was recently installed/updated BEFORE cleanupObsoleteVersions updates LatestVersionNative
246
+ self.wasRecentlyInstalledOrUpdated = self.checkIfRecentlyInstalledOrUpdated()
247
+
248
+ if resetWhenUpdate {
249
+ self.cleanupObsoleteVersions()
250
+ }
251
+
252
+ // Load the server
253
+ // This is very much swift specific, android does not do that
254
+ // In android we depend on the serverBasePath capacitor property
255
+ // In IOS we do not. Instead during the plugin initialization we try to call setServerBasePath
256
+ // The idea is to prevent having to store the bundle in 2 locations for hot reload and persistent storage
257
+ // According to martin it is not possible to use serverBasePath on ios in a way that allows us to store the bundle once
258
+
259
+ if !self.initialLoad() {
260
+ logger.error("unable to force reload, the plugin might fallback to the builtin version")
261
+ }
262
+
263
+ let nc = NotificationCenter.default
264
+ nc.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
265
+ nc.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
266
+
267
+ // Check for 'kill' delay condition on app launch
268
+ // This handles cases where the app was killed (willTerminateNotification is not reliable for system kills)
269
+ self.delayUpdateUtils.checkCancelDelay(source: .killed)
270
+
271
+ self.appMovedToForeground()
272
+ self.checkForUpdateAfterDelay()
273
+ }
274
+
275
+ private func syncKeepUrlPathFlag(enabled: Bool) {
276
+ let script: String
277
+ if enabled {
278
+ script = "(function(){ try { localStorage.setItem('\(keepUrlPathFlagKey)', '1'); } catch (err) {} window.__capgoKeepUrlPathAfterReload = true; var evt; try { evt = new CustomEvent('CapacitorUpdaterKeepUrlPathAfterReload', { detail: { enabled: true } }); } catch (e) { evt = document.createEvent('CustomEvent'); evt.initCustomEvent('CapacitorUpdaterKeepUrlPathAfterReload', false, false, { enabled: true }); } window.dispatchEvent(evt); })();"
279
+ } else {
280
+ script = "(function(){ try { localStorage.removeItem('\(keepUrlPathFlagKey)'); } catch (err) {} delete window.__capgoKeepUrlPathAfterReload; var evt; try { evt = new CustomEvent('CapacitorUpdaterKeepUrlPathAfterReload', { detail: { enabled: false } }); } catch (e) { evt = document.createEvent('CustomEvent'); evt.initCustomEvent('CapacitorUpdaterKeepUrlPathAfterReload', false, false, { enabled: false }); } window.dispatchEvent(evt); })();"
281
+ }
282
+ DispatchQueue.main.async { [weak self] in
283
+ guard let self = self, let webView = self.bridge?.webView else {
284
+ return
285
+ }
286
+ if self.keepUrlPathFlagLastValue != enabled {
287
+ let userScript = WKUserScript(source: script, injectionTime: .atDocumentStart, forMainFrameOnly: true)
288
+ webView.configuration.userContentController.addUserScript(userScript)
289
+ self.keepUrlPathFlagLastValue = enabled
290
+ }
291
+ webView.evaluateJavaScript(script, completionHandler: nil)
292
+ }
293
+ }
294
+
295
+ private func persistLastFailedBundle(_ bundle: BundleInfo?) {
296
+ if let bundle = bundle {
297
+ do {
298
+ try UserDefaults.standard.setObj(bundle, forKey: lastFailedBundleDefaultsKey)
299
+ } catch {
300
+ logger.error("Failed to persist failed bundle info \(error.localizedDescription)")
301
+ }
302
+ } else {
303
+ UserDefaults.standard.removeObject(forKey: lastFailedBundleDefaultsKey)
304
+ }
305
+ UserDefaults.standard.synchronize()
306
+ }
307
+
308
+ private func readLastFailedBundle() -> BundleInfo? {
309
+ do {
310
+ let bundle: BundleInfo = try UserDefaults.standard.getObj(forKey: lastFailedBundleDefaultsKey, castTo: BundleInfo.self)
311
+ return bundle
312
+ } catch ObjectSavableError.noValue {
313
+ return nil
314
+ } catch {
315
+ logger.error("Failed to read failed bundle info \(error.localizedDescription)")
316
+ UserDefaults.standard.removeObject(forKey: lastFailedBundleDefaultsKey)
317
+ UserDefaults.standard.synchronize()
318
+ return nil
319
+ }
320
+ }
321
+
322
+ private func initialLoad() -> Bool {
323
+ guard let bridge = self.bridge else { return false }
324
+ if keepUrlPathAfterReload {
325
+ syncKeepUrlPathFlag(enabled: true)
326
+ }
327
+
328
+ let id = self.implementation.getCurrentBundleId()
329
+ var dest: URL
330
+ if BundleInfo.ID_BUILTIN == id {
331
+ dest = Bundle.main.resourceURL!.appendingPathComponent("public")
332
+ } else {
333
+ dest = self.implementation.getBundleDirectory(id: id)
334
+ }
335
+
336
+ if !FileManager.default.fileExists(atPath: dest.path) {
337
+ logger.error("Initial load fail - file at path \(dest.path) doesn't exist. Defaulting to buildin!! \(id)")
338
+ dest = Bundle.main.resourceURL!.appendingPathComponent("public")
339
+ }
340
+
341
+ logger.info("Initial load \(id)")
342
+ // We don't use the viewcontroller here as it does not work during the initial load state
343
+ bridge.setServerBasePath(dest.path)
344
+ return true
345
+ }
346
+
347
+ private func semaphoreWait(waitTime: Int) {
348
+ // print("\\(CapgoUpdater.TAG) semaphoreWait \\(waitTime)")
349
+ let result = semaphoreReady.wait(timeout: .now() + .milliseconds(waitTime))
350
+ if result == .timedOut {
351
+ logger.error("Semaphore wait timed out after \(waitTime)ms")
352
+ }
353
+ }
354
+
355
+ private func semaphoreUp() {
356
+ DispatchQueue.global().async {
357
+ self.semaphoreWait(waitTime: 0)
358
+ }
359
+ }
360
+
361
+ private func semaphoreDown() {
362
+ semaphoreReady.signal()
363
+ }
364
+
365
+ private func cleanupObsoleteVersions() {
366
+ let previous = UserDefaults.standard.string(forKey: "LatestNativeBuildVersion") ?? UserDefaults.standard.string(forKey: "LatestVersionNative") ?? "0"
367
+ if previous != "0" && self.currentBuildVersion != previous {
368
+ _ = self._reset(toLastSuccessful: false)
369
+ let res = implementation.list()
370
+ res.forEach { version in
371
+ logger.info("Deleting obsolete bundle: \(version.getId())")
372
+ let res = implementation.delete(id: version.getId())
373
+ if !res {
374
+ logger.error("Delete failed, id \(version.getId()) doesn't exist")
375
+ }
376
+ }
377
+
378
+ let storedBundles = implementation.list(raw: true)
379
+ let allowedIds = Set(storedBundles.compactMap { info -> String? in
380
+ let id = info.getId()
381
+ return id.isEmpty ? nil : id
382
+ })
383
+ implementation.cleanupDownloadDirectories(allowedIds: allowedIds)
384
+ implementation.cleanupDeltaCache()
385
+ }
386
+ UserDefaults.standard.set(self.currentBuildVersion, forKey: "LatestNativeBuildVersion")
387
+ UserDefaults.standard.synchronize()
388
+ }
389
+
390
+ @objc func notifyDownload(id: String, percent: Int, ignoreMultipleOfTen: Bool = false, bundle: BundleInfo? = nil) {
391
+ let bundleInfo = bundle ?? self.implementation.getBundleInfo(id: id)
392
+ self.notifyListeners("download", data: ["percent": percent, "bundle": bundleInfo.toJSON()])
393
+ if percent == 100 {
394
+ self.notifyListeners("downloadComplete", data: ["bundle": bundleInfo.toJSON()])
395
+ self.implementation.sendStats(action: "download_complete", versionName: bundleInfo.getVersionName())
396
+ } else if percent.isMultiple(of: 10) || ignoreMultipleOfTen {
397
+ self.implementation.sendStats(action: "download_\(percent)", versionName: bundleInfo.getVersionName())
398
+ }
399
+ }
400
+
401
+ @objc func setUpdateUrl(_ call: CAPPluginCall) {
402
+ if !getConfig().getBoolean("allowModifyUrl", false) {
403
+ logger.error("setUpdateUrl called without allowModifyUrl")
404
+ call.reject("setUpdateUrl called without allowModifyUrl set allowModifyUrl in your config to true to allow it")
405
+ return
406
+ }
407
+ guard let url = call.getString("url") else {
408
+ logger.error("setUpdateUrl called without url")
409
+ call.reject("setUpdateUrl called without url")
410
+ return
411
+ }
412
+ self.updateUrl = url
413
+ if persistModifyUrl {
414
+ UserDefaults.standard.set(url, forKey: updateUrlDefaultsKey)
415
+ UserDefaults.standard.synchronize()
416
+ }
417
+ call.resolve()
418
+ }
419
+
420
+ @objc func setStatsUrl(_ call: CAPPluginCall) {
421
+ if !getConfig().getBoolean("allowModifyUrl", false) {
422
+ logger.error("setStatsUrl called without allowModifyUrl")
423
+ call.reject("setStatsUrl called without allowModifyUrl set allowModifyUrl in your config to true to allow it")
424
+ return
425
+ }
426
+ guard let url = call.getString("url") else {
427
+ logger.error("setStatsUrl called without url")
428
+ call.reject("setStatsUrl called without url")
429
+ return
430
+ }
431
+ self.implementation.statsUrl = url
432
+ if persistModifyUrl {
433
+ UserDefaults.standard.set(url, forKey: statsUrlDefaultsKey)
434
+ UserDefaults.standard.synchronize()
435
+ }
436
+ call.resolve()
437
+ }
438
+
439
+ @objc func setChannelUrl(_ call: CAPPluginCall) {
440
+ if !getConfig().getBoolean("allowModifyUrl", false) {
441
+ logger.error("setChannelUrl called without allowModifyUrl")
442
+ call.reject("setChannelUrl called without allowModifyUrl set allowModifyUrl in your config to true to allow it")
443
+ return
444
+ }
445
+ guard let url = call.getString("url") else {
446
+ logger.error("setChannelUrl called without url")
447
+ call.reject("setChannelUrl called without url")
448
+ return
449
+ }
450
+ self.implementation.channelUrl = url
451
+ if persistModifyUrl {
452
+ UserDefaults.standard.set(url, forKey: channelUrlDefaultsKey)
453
+ UserDefaults.standard.synchronize()
454
+ }
455
+ call.resolve()
456
+ }
457
+
458
+ @objc func getBuiltinVersion(_ call: CAPPluginCall) {
459
+ call.resolve(["version": implementation.versionBuild])
460
+ }
461
+
462
+ @objc func getDeviceId(_ call: CAPPluginCall) {
463
+ call.resolve(["deviceId": implementation.deviceID])
464
+ }
465
+
466
+ @objc func getPluginVersion(_ call: CAPPluginCall) {
467
+ call.resolve(["version": self.pluginVersion])
468
+ }
469
+
470
+ @objc func download(_ call: CAPPluginCall) {
471
+ guard let urlString = call.getString("url") else {
472
+ logger.error("Download called without url")
473
+ call.reject("Download called without url")
474
+ return
475
+ }
476
+ guard let version = call.getString("version") else {
477
+ logger.error("Download called without version")
478
+ call.reject("Download called without version")
479
+ return
480
+ }
481
+
482
+ let sessionKey = call.getString("sessionKey", "")
483
+ var checksum = call.getString("checksum", "")
484
+ let manifestArray = call.getArray("manifest")
485
+ let url = URL(string: urlString)
486
+ logger.info("Downloading \(String(describing: url))")
487
+ DispatchQueue.global(qos: .background).async {
488
+ do {
489
+ let next: BundleInfo
490
+ if let manifestArray = manifestArray {
491
+ // Convert JSArray to [ManifestEntry]
492
+ var manifestEntries: [ManifestEntry] = []
493
+ for item in manifestArray {
494
+ if let manifestDict = item as? [String: Any] {
495
+ let entry = ManifestEntry(
496
+ file_name: manifestDict["file_name"] as? String,
497
+ file_hash: manifestDict["file_hash"] as? String,
498
+ download_url: manifestDict["download_url"] as? String
499
+ )
500
+ manifestEntries.append(entry)
501
+ }
502
+ }
503
+ next = try self.implementation.downloadManifest(manifest: manifestEntries, version: version, sessionKey: sessionKey)
504
+ } else {
505
+ next = try self.implementation.download(url: url!, version: version, sessionKey: sessionKey)
506
+ }
507
+ // If public key is present but no checksum provided, refuse installation
508
+ if self.implementation.publicKey != "" && checksum == "" {
509
+ self.logger.error("Public key present but no checksum provided")
510
+ self.implementation.sendStats(action: "checksum_required", versionName: next.getVersionName())
511
+ let id = next.getId()
512
+ let resDel = self.implementation.delete(id: id)
513
+ if !resDel {
514
+ self.logger.error("Delete failed, id \(id) doesn't exist")
515
+ }
516
+ throw ObjectSavableError.checksum
517
+ }
518
+
519
+ checksum = try CryptoCipher.decryptChecksum(checksum: checksum, publicKey: self.implementation.publicKey)
520
+ CryptoCipher.logChecksumInfo(label: "Bundle checksum", hexChecksum: next.getChecksum())
521
+ CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: checksum)
522
+ if (checksum != "" || self.implementation.publicKey != "") && next.getChecksum() != checksum {
523
+ self.logger.error("Error checksum \(next.getChecksum()) \(checksum)")
524
+ self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
525
+ let id = next.getId()
526
+ let resDel = self.implementation.delete(id: id)
527
+ if !resDel {
528
+ self.logger.error("Delete failed, id \(id) doesn't exist")
529
+ }
530
+ throw ObjectSavableError.checksum
531
+ } else {
532
+ self.logger.info("Good checksum \(next.getChecksum()) \(checksum)")
533
+ }
534
+ self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
535
+ call.resolve(next.toJSON())
536
+ } catch {
537
+ self.logger.error("Failed to download from: \(String(describing: url)) \(error.localizedDescription)")
538
+ self.notifyListeners("downloadFailed", data: ["version": version])
539
+ self.implementation.sendStats(action: "download_fail")
540
+ call.reject("Failed to download from: \(url!) - \(error.localizedDescription)")
541
+ }
542
+ }
543
+ }
544
+
545
+ public func _reload() -> Bool {
546
+ guard let bridge = self.bridge else { return false }
547
+ self.semaphoreUp()
548
+ let id = self.implementation.getCurrentBundleId()
549
+ let dest: URL
550
+ if BundleInfo.ID_BUILTIN == id {
551
+ dest = Bundle.main.resourceURL!.appendingPathComponent("public")
552
+ } else {
553
+ dest = self.implementation.getBundleDirectory(id: id)
554
+ }
555
+ logger.info("Reloading \(id)")
556
+
557
+ let performReload: () -> Bool = {
558
+ guard let vc = bridge.viewController as? CAPBridgeViewController else {
559
+ self.logger.error("Cannot get viewController")
560
+ return false
561
+ }
562
+ guard let capBridge = vc.bridge else {
563
+ self.logger.error("Cannot get capBridge")
564
+ return false
565
+ }
566
+ if self.keepUrlPathAfterReload {
567
+ if let currentURL = vc.webView?.url {
568
+ capBridge.setServerBasePath(dest.path)
569
+ var urlComponents = URLComponents(url: capBridge.config.serverURL, resolvingAgainstBaseURL: false)!
570
+ urlComponents.path = currentURL.path
571
+ urlComponents.query = currentURL.query
572
+ urlComponents.fragment = currentURL.fragment
573
+ if let finalUrl = urlComponents.url {
574
+ _ = vc.webView?.load(URLRequest(url: finalUrl))
575
+ } else {
576
+ self.logger.error("Unable to build final URL when keeping path after reload; falling back to base path")
577
+ vc.setServerBasePath(path: dest.path)
578
+ }
579
+ } else {
580
+ self.logger.error("vc.webView?.url is null? Falling back to base path reload.")
581
+ vc.setServerBasePath(path: dest.path)
582
+ }
583
+ } else {
584
+ vc.setServerBasePath(path: dest.path)
585
+ }
586
+ self.checkAppReady()
587
+ self.notifyListeners("appReloaded", data: [:])
588
+ return true
589
+ }
590
+
591
+ if Thread.isMainThread {
592
+ return performReload()
593
+ } else {
594
+ var result = false
595
+ DispatchQueue.main.sync {
596
+ result = performReload()
597
+ }
598
+ return result
599
+ }
600
+ }
601
+
602
+ @objc func reload(_ call: CAPPluginCall) {
603
+ if self._reload() {
604
+ call.resolve()
605
+ } else {
606
+ logger.error("Reload failed")
607
+ call.reject("Reload failed")
608
+ }
609
+ }
610
+
611
+ @objc func next(_ call: CAPPluginCall) {
612
+ guard let id = call.getString("id") else {
613
+ logger.error("Next called without id")
614
+ call.reject("Next called without id")
615
+ return
616
+ }
617
+ logger.info("Setting next active id \(id)")
618
+ if !self.implementation.setNextBundle(next: id) {
619
+ logger.error("Set next version failed. id \(id) does not exist.")
620
+ call.reject("Set next version failed. id \(id) does not exist.")
621
+ } else {
622
+ call.resolve(self.implementation.getBundleInfo(id: id).toJSON())
623
+ }
624
+ }
625
+
626
+ @objc func set(_ call: CAPPluginCall) {
627
+ guard let id = call.getString("id") else {
628
+ logger.error("Set called without id")
629
+ call.reject("Set called without id")
630
+ return
631
+ }
632
+ let res = implementation.set(id: id)
633
+ logger.info("Set active bundle: \(id)")
634
+ if !res {
635
+ logger.info("Bundle successfully set to: \(id) ")
636
+ call.reject("Update failed, id \(id) doesn't exist")
637
+ } else {
638
+ self.reload(call)
639
+ }
640
+ }
641
+
642
+ @objc func delete(_ call: CAPPluginCall) {
643
+ guard let id = call.getString("id") else {
644
+ logger.error("Delete called without version")
645
+ call.reject("Delete called without id")
646
+ return
647
+ }
648
+ let res = implementation.delete(id: id)
649
+ if res {
650
+ call.resolve()
651
+ } else {
652
+ logger.error("Delete failed, id \(id) doesn't exist or it cannot be deleted (perhaps it is the 'next' bundle)")
653
+ call.reject("Delete failed, id \(id) does not exist or it cannot be deleted (perhaps it is the 'next' bundle)")
654
+ }
655
+ }
656
+
657
+ @objc func setBundleError(_ call: CAPPluginCall) {
658
+ if !allowManualBundleError {
659
+ logger.error("setBundleError called without allowManualBundleError")
660
+ call.reject("setBundleError not allowed. Set allowManualBundleError to true in your config to enable it.")
661
+ return
662
+ }
663
+ guard let id = call.getString("id") else {
664
+ logger.error("setBundleError called without id")
665
+ call.reject("setBundleError called without id")
666
+ return
667
+ }
668
+ let bundle = implementation.getBundleInfo(id: id)
669
+ if bundle.isUnknown() {
670
+ logger.error("setBundleError called with unknown bundle \(id)")
671
+ call.reject("Bundle \(id) does not exist")
672
+ return
673
+ }
674
+ if bundle.isBuiltin() {
675
+ logger.error("setBundleError called on builtin bundle")
676
+ call.reject("Cannot set builtin bundle to error state")
677
+ return
678
+ }
679
+ if self._isAutoUpdateEnabled() {
680
+ logger.warn("setBundleError used while autoUpdate is enabled; this method is intended for manual mode")
681
+ }
682
+ implementation.setError(bundle: bundle)
683
+ let updated = implementation.getBundleInfo(id: id)
684
+ call.resolve(["bundle": updated.toJSON()])
685
+ }
686
+
687
+ @objc func list(_ call: CAPPluginCall) {
688
+ let raw = call.getBool("raw", false)
689
+ let res = implementation.list(raw: raw)
690
+ var resArr: [[String: String]] = []
691
+ for v in res {
692
+ resArr.append(v.toJSON())
693
+ }
694
+ call.resolve([
695
+ "bundles": resArr
696
+ ])
697
+ }
698
+
699
+ @objc func getLatest(_ call: CAPPluginCall) {
700
+ let channel = call.getString("channel")
701
+ DispatchQueue.global(qos: .background).async {
702
+ let res = self.implementation.getLatest(url: URL(string: self.updateUrl)!, channel: channel)
703
+ if res.error != nil {
704
+ call.reject( res.error!)
705
+ } else if res.message != nil {
706
+ call.reject( res.message!)
707
+ } else {
708
+ call.resolve(res.toDict())
709
+ }
710
+ }
711
+ }
712
+
713
+ @objc func unsetChannel(_ call: CAPPluginCall) {
714
+ let triggerAutoUpdate = call.getBool("triggerAutoUpdate", false)
715
+ DispatchQueue.global(qos: .background).async {
716
+ let configDefaultChannel = self.getConfig().getString("defaultChannel", "")!
717
+ let res = self.implementation.unsetChannel(defaultChannelKey: self.defaultChannelDefaultsKey, configDefaultChannel: configDefaultChannel)
718
+ if res.error != "" {
719
+ call.reject(res.error, "UNSETCHANNEL_FAILED", nil, [
720
+ "message": res.error,
721
+ "error": res.error.contains("Channel URL") ? "missing_config" : "request_failed"
722
+ ])
723
+ } else {
724
+ if self._isAutoUpdateEnabled() && triggerAutoUpdate {
725
+ self.logger.info("Calling autoupdater after channel change!")
726
+ self.backgroundDownload()
727
+ }
728
+ call.resolve(res.toDict())
729
+ }
730
+ }
731
+ }
732
+
733
+ @objc func setChannel(_ call: CAPPluginCall) {
734
+ guard let channel = call.getString("channel") else {
735
+ logger.error("setChannel called without channel")
736
+ call.reject("setChannel called without channel", "SETCHANNEL_INVALID_PARAMS", nil, [
737
+ "message": "setChannel called without channel",
738
+ "error": "missing_parameter"
739
+ ])
740
+ return
741
+ }
742
+ let triggerAutoUpdate = call.getBool("triggerAutoUpdate") ?? false
743
+ DispatchQueue.global(qos: .background).async {
744
+ let res = self.implementation.setChannel(channel: channel, defaultChannelKey: self.defaultChannelDefaultsKey, allowSetDefaultChannel: self.allowSetDefaultChannel)
745
+ if res.error != "" {
746
+ // Fire channelPrivate event if channel doesn't allow self-assignment
747
+ if res.error.contains("cannot_update_via_private_channel") || res.error.contains("channel_self_set_not_allowed") {
748
+ self.notifyListeners("channelPrivate", data: [
749
+ "channel": channel,
750
+ "message": res.error
751
+ ])
752
+ }
753
+ call.reject(res.error, "SETCHANNEL_FAILED", nil, [
754
+ "message": res.error,
755
+ "error": res.error.contains("Channel URL") ? "missing_config" : (res.error.contains("cannot_update_via_private_channel") || res.error.contains("channel_self_set_not_allowed")) ? "channel_private" : "request_failed"
756
+ ])
757
+ } else {
758
+ if self._isAutoUpdateEnabled() && triggerAutoUpdate {
759
+ self.logger.info("Calling autoupdater after channel change!")
760
+ self.backgroundDownload()
761
+ }
762
+ call.resolve(res.toDict())
763
+ }
764
+ }
765
+ }
766
+
767
+ @objc func getChannel(_ call: CAPPluginCall) {
768
+ DispatchQueue.global(qos: .background).async {
769
+ let res = self.implementation.getChannel()
770
+ if res.error != "" {
771
+ call.reject(res.error, "GETCHANNEL_FAILED", nil, [
772
+ "message": res.error,
773
+ "error": res.error.contains("Channel URL") ? "missing_config" : "request_failed"
774
+ ])
775
+ } else {
776
+ call.resolve(res.toDict())
777
+ }
778
+ }
779
+ }
780
+
781
+ @objc func listChannels(_ call: CAPPluginCall) {
782
+ DispatchQueue.global(qos: .background).async {
783
+ let res = self.implementation.listChannels()
784
+ if res.error != "" {
785
+ call.reject(res.error, "LISTCHANNELS_FAILED", nil, [
786
+ "message": res.error,
787
+ "error": res.error.contains("Channel URL") ? "missing_config" : "request_failed"
788
+ ])
789
+ } else {
790
+ call.resolve(res.toDict())
791
+ }
792
+ }
793
+ }
794
+
795
+ @objc func setCustomId(_ call: CAPPluginCall) {
796
+ guard let customId = call.getString("customId") else {
797
+ logger.error("setCustomId called without customId")
798
+ call.reject("setCustomId called without customId")
799
+ return
800
+ }
801
+ self.implementation.customId = customId
802
+ if persistCustomId {
803
+ if customId.isEmpty {
804
+ UserDefaults.standard.removeObject(forKey: customIdDefaultsKey)
805
+ } else {
806
+ UserDefaults.standard.set(customId, forKey: customIdDefaultsKey)
807
+ }
808
+ UserDefaults.standard.synchronize()
809
+ }
810
+ call.resolve()
811
+ }
812
+
813
+ @objc func _reset(toLastSuccessful: Bool) -> Bool {
814
+ guard let bridge = self.bridge else { return false }
815
+
816
+ if (bridge.viewController as? CAPBridgeViewController) != nil {
817
+ let fallback: BundleInfo = self.implementation.getFallbackBundle()
818
+
819
+ // If developer wants to reset to the last successful bundle, and that bundle is not
820
+ // the built-in bundle, set it as the bundle to use and reload.
821
+ if toLastSuccessful && !fallback.isBuiltin() {
822
+ logger.info("Resetting to: \(fallback.toString())")
823
+ return self.implementation.set(bundle: fallback) && self._reload()
824
+ }
825
+
826
+ logger.info("Resetting to builtin version")
827
+
828
+ // Otherwise, reset back to the built-in bundle and reload.
829
+ self.implementation.reset()
830
+ return self._reload()
831
+ }
832
+
833
+ return false
834
+ }
835
+
836
+ @objc func reset(_ call: CAPPluginCall) {
837
+ let toLastSuccessful = call.getBool("toLastSuccessful") ?? false
838
+ if self._reset(toLastSuccessful: toLastSuccessful) {
839
+ call.resolve()
840
+ } else {
841
+ logger.error("Reset failed")
842
+ call.reject("Reset failed")
843
+ }
844
+ }
845
+
846
+ @objc func current(_ call: CAPPluginCall) {
847
+ let bundle: BundleInfo = self.implementation.getCurrentBundle()
848
+ call.resolve([
849
+ "bundle": bundle.toJSON(),
850
+ "native": self.currentVersionNative.description
851
+ ])
852
+ }
853
+
854
+ @objc func notifyAppReady(_ call: CAPPluginCall) {
855
+ self.semaphoreDown()
856
+ let bundle = self.implementation.getCurrentBundle()
857
+ self.implementation.setSuccess(bundle: bundle, autoDeletePrevious: self.autoDeletePrevious)
858
+ logger.info("Current bundle loaded successfully. [notifyAppReady was called] \(bundle.toString())")
859
+ call.resolve(["bundle": bundle.toJSON()])
860
+ }
861
+
862
+ @objc func setMultiDelay(_ call: CAPPluginCall) {
863
+ guard let delayConditionList = call.getValue("delayConditions") else {
864
+ logger.error("setMultiDelay called without delayCondition")
865
+ call.reject("setMultiDelay called without delayCondition")
866
+ return
867
+ }
868
+
869
+ // Handle background conditions with empty value (set to "0")
870
+ if var modifiableList = delayConditionList as? [[String: Any]] {
871
+ for i in 0..<modifiableList.count {
872
+ if let kind = modifiableList[i]["kind"] as? String,
873
+ kind == "background",
874
+ let value = modifiableList[i]["value"] as? String,
875
+ value.isEmpty {
876
+ modifiableList[i]["value"] = "0"
877
+ }
878
+ }
879
+ let delayConditions: String = toJson(object: modifiableList)
880
+ if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
881
+ call.resolve()
882
+ } else {
883
+ call.reject("Failed to delay update")
884
+ }
885
+ } else {
886
+ let delayConditions: String = toJson(object: delayConditionList)
887
+ if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
888
+ call.resolve()
889
+ } else {
890
+ call.reject("Failed to delay update")
891
+ }
892
+ }
893
+ }
894
+
895
+ // Note: _setMultiDelay and _cancelDelay methods have been moved to DelayUpdateUtils class
896
+
897
+ @objc func cancelDelay(_ call: CAPPluginCall) {
898
+ if delayUpdateUtils.cancelDelay(source: "JS") {
899
+ call.resolve()
900
+ } else {
901
+ call.reject("Failed to cancel delay")
902
+ }
903
+ }
904
+
905
+ // Note: _checkCancelDelay method has been moved to DelayUpdateUtils class
906
+
907
+ private func _isAutoUpdateEnabled() -> Bool {
908
+ let instanceDescriptor = (self.bridge?.viewController as? CAPBridgeViewController)?.instanceDescriptor()
909
+ if instanceDescriptor?.serverURL != nil {
910
+ logger.warn("AutoUpdate is automatic disabled when serverUrl is set.")
911
+ }
912
+ return self.autoUpdate && self.updateUrl != "" && instanceDescriptor?.serverURL == nil
913
+ }
914
+
915
+ @objc func isAutoUpdateEnabled(_ call: CAPPluginCall) {
916
+ call.resolve([
917
+ "enabled": self._isAutoUpdateEnabled()
918
+ ])
919
+ }
920
+
921
+ @objc func isAutoUpdateAvailable(_ call: CAPPluginCall) {
922
+ let instanceDescriptor = (self.bridge?.viewController as? CAPBridgeViewController)?.instanceDescriptor()
923
+ let isAvailable = instanceDescriptor?.serverURL == nil
924
+ call.resolve([
925
+ "available": isAvailable
926
+ ])
927
+ }
928
+
929
+ func checkAppReady() {
930
+ self.appReadyCheck?.cancel()
931
+ self.appReadyCheck = DispatchWorkItem(block: {
932
+ self.DeferredNotifyAppReadyCheck()
933
+ })
934
+ logger.info("Wait for \(self.appReadyTimeout) ms, then check for notifyAppReady")
935
+ DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(self.appReadyTimeout), execute: self.appReadyCheck!)
936
+ }
937
+
938
+ func checkRevert() {
939
+ // Automatically roll back to fallback version if notifyAppReady has not been called yet
940
+ let current: BundleInfo = self.implementation.getCurrentBundle()
941
+ if current.isBuiltin() {
942
+ logger.info("Built-in bundle is active. We skip the check for notifyAppReady.")
943
+ return
944
+ }
945
+
946
+ logger.info("Current bundle is: \(current.toString())")
947
+
948
+ if BundleStatus.SUCCESS.localizedString != current.getStatus() {
949
+ logger.error("notifyAppReady was not called, roll back current bundle: \(current.toString())")
950
+ logger.error("Did you forget to call 'notifyAppReady()' in your Capacitor App code?")
951
+ self.notifyListeners("updateFailed", data: [
952
+ "bundle": current.toJSON()
953
+ ])
954
+ self.persistLastFailedBundle(current)
955
+ self.implementation.sendStats(action: "update_fail", versionName: current.getVersionName())
956
+ self.implementation.setError(bundle: current)
957
+ _ = self._reset(toLastSuccessful: true)
958
+ if self.autoDeleteFailed && !current.isBuiltin() {
959
+ logger.info("Deleting failing bundle: \(current.toString())")
960
+ let res = self.implementation.delete(id: current.getId(), removeInfo: false)
961
+ if !res {
962
+ logger.info("Delete version deleted: \(current.toString())")
963
+ } else {
964
+ logger.error("Failed to delete failed bundle: \(current.toString())")
965
+ }
966
+ }
967
+ } else {
968
+ logger.info("notifyAppReady was called. This is fine: \(current.toString())")
969
+ }
970
+ }
971
+
972
+ func DeferredNotifyAppReadyCheck() {
973
+ self.checkRevert()
974
+ self.appReadyCheck = nil
975
+ }
976
+
977
+ func endBackGroundTask() {
978
+ UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
979
+ self.backgroundTaskID = UIBackgroundTaskIdentifier.invalid
980
+ }
981
+
982
+ func sendReadyToJs(current: BundleInfo, msg: String) {
983
+ logger.info("sendReadyToJs")
984
+ DispatchQueue.global().async {
985
+ self.semaphoreWait(waitTime: self.appReadyTimeout)
986
+ self.notifyListeners("appReady", data: ["bundle": current.toJSON(), "status": msg], retainUntilConsumed: true)
987
+
988
+ // Auto hide splashscreen if enabled
989
+ // We show it on background when conditions are met, so we should hide it on foreground regardless of update outcome
990
+ if self.autoSplashscreen {
991
+ self.hideSplashscreen()
992
+ }
993
+ }
994
+ }
995
+
996
+ private func hideSplashscreen() {
997
+ if Thread.isMainThread {
998
+ self.performHideSplashscreen()
999
+ } else {
1000
+ DispatchQueue.main.async {
1001
+ self.performHideSplashscreen()
1002
+ }
1003
+ }
1004
+ }
1005
+
1006
+ private func performHideSplashscreen() {
1007
+ self.cancelSplashscreenTimeout()
1008
+ self.removeSplashscreenLoader()
1009
+
1010
+ guard let bridge = self.bridge else {
1011
+ self.logger.warn("Bridge not available for hiding splashscreen with autoSplashscreen")
1012
+ return
1013
+ }
1014
+
1015
+ // Create a plugin call for the hide method
1016
+ let call = CAPPluginCall(callbackId: "autoHideSplashscreen", options: [:], success: { (_, _) in
1017
+ self.logger.info("Splashscreen hidden automatically")
1018
+ }, error: { (_) in
1019
+ self.logger.error("Failed to auto-hide splashscreen")
1020
+ })
1021
+
1022
+ // Try to call the SplashScreen hide method directly through the bridge
1023
+ if let splashScreenPlugin = bridge.plugin(withName: "SplashScreen") {
1024
+ // Use runtime method invocation to call hide method
1025
+ let selector = NSSelectorFromString("hide:")
1026
+ if splashScreenPlugin.responds(to: selector) {
1027
+ _ = splashScreenPlugin.perform(selector, with: call)
1028
+ self.logger.info("Called SplashScreen hide method")
1029
+ } else {
1030
+ self.logger.warn("autoSplashscreen: SplashScreen plugin does not respond to hide: method. Make sure @capacitor/splash-screen plugin is properly installed.")
1031
+ }
1032
+ } else {
1033
+ self.logger.warn("autoSplashscreen: SplashScreen plugin not found. Install @capacitor/splash-screen plugin.")
1034
+ }
1035
+ }
1036
+
1037
+ private func showSplashscreen() {
1038
+ if Thread.isMainThread {
1039
+ self.performShowSplashscreen()
1040
+ } else {
1041
+ DispatchQueue.main.async {
1042
+ self.performShowSplashscreen()
1043
+ }
1044
+ }
1045
+ }
1046
+
1047
+ private func performShowSplashscreen() {
1048
+ self.cancelSplashscreenTimeout()
1049
+ self.autoSplashscreenTimedOut = false
1050
+
1051
+ guard let bridge = self.bridge else {
1052
+ self.logger.warn("Bridge not available for showing splashscreen with autoSplashscreen")
1053
+ return
1054
+ }
1055
+
1056
+ // Create a plugin call for the show method
1057
+ let call = CAPPluginCall(callbackId: "autoShowSplashscreen", options: [:], success: { (_, _) in
1058
+ self.logger.info("Splashscreen shown automatically")
1059
+ }, error: { (_) in
1060
+ self.logger.error("Failed to auto-show splashscreen")
1061
+ })
1062
+
1063
+ // Try to call the SplashScreen show method directly through the bridge
1064
+ if let splashScreenPlugin = bridge.plugin(withName: "SplashScreen") {
1065
+ // Use runtime method invocation to call show method
1066
+ let selector = NSSelectorFromString("show:")
1067
+ if splashScreenPlugin.responds(to: selector) {
1068
+ _ = splashScreenPlugin.perform(selector, with: call)
1069
+ self.logger.info("Called SplashScreen show method")
1070
+ } else {
1071
+ self.logger.warn("autoSplashscreen: SplashScreen plugin does not respond to show: method. Make sure @capacitor/splash-screen plugin is properly installed.")
1072
+ }
1073
+ } else {
1074
+ self.logger.warn("autoSplashscreen: SplashScreen plugin not found. Install @capacitor/splash-screen plugin.")
1075
+ }
1076
+
1077
+ self.addSplashscreenLoaderIfNeeded()
1078
+ self.scheduleSplashscreenTimeout()
1079
+ }
1080
+
1081
+ private func addSplashscreenLoaderIfNeeded() {
1082
+ guard self.autoSplashscreenLoader else {
1083
+ return
1084
+ }
1085
+
1086
+ let addLoader = {
1087
+ guard self.splashscreenLoaderContainer == nil else {
1088
+ return
1089
+ }
1090
+ guard let rootView = self.bridge?.viewController?.view else {
1091
+ self.logger.warn("autoSplashscreen: Unable to access root view for loader overlay")
1092
+ return
1093
+ }
1094
+
1095
+ let container = UIView()
1096
+ container.translatesAutoresizingMaskIntoConstraints = false
1097
+ container.backgroundColor = UIColor.clear
1098
+ container.isUserInteractionEnabled = false
1099
+
1100
+ let indicatorStyle: UIActivityIndicatorView.Style
1101
+ if #available(iOS 13.0, *) {
1102
+ indicatorStyle = .large
1103
+ } else {
1104
+ indicatorStyle = .whiteLarge
1105
+ }
1106
+
1107
+ let indicator = UIActivityIndicatorView(style: indicatorStyle)
1108
+ indicator.translatesAutoresizingMaskIntoConstraints = false
1109
+ indicator.hidesWhenStopped = false
1110
+ if #available(iOS 13.0, *) {
1111
+ indicator.color = UIColor.label
1112
+ }
1113
+ indicator.startAnimating()
1114
+
1115
+ container.addSubview(indicator)
1116
+ rootView.addSubview(container)
1117
+
1118
+ NSLayoutConstraint.activate([
1119
+ container.leadingAnchor.constraint(equalTo: rootView.leadingAnchor),
1120
+ container.trailingAnchor.constraint(equalTo: rootView.trailingAnchor),
1121
+ container.topAnchor.constraint(equalTo: rootView.topAnchor),
1122
+ container.bottomAnchor.constraint(equalTo: rootView.bottomAnchor),
1123
+ indicator.centerXAnchor.constraint(equalTo: container.centerXAnchor),
1124
+ indicator.centerYAnchor.constraint(equalTo: container.centerYAnchor)
1125
+ ])
1126
+
1127
+ self.splashscreenLoaderContainer = container
1128
+ self.splashscreenLoaderView = indicator
1129
+ }
1130
+
1131
+ if Thread.isMainThread {
1132
+ addLoader()
1133
+ } else {
1134
+ DispatchQueue.main.async {
1135
+ addLoader()
1136
+ }
1137
+ }
1138
+ }
1139
+
1140
+ private func removeSplashscreenLoader() {
1141
+ let removeLoader = {
1142
+ self.splashscreenLoaderView?.stopAnimating()
1143
+ self.splashscreenLoaderContainer?.removeFromSuperview()
1144
+ self.splashscreenLoaderView = nil
1145
+ self.splashscreenLoaderContainer = nil
1146
+ }
1147
+
1148
+ if Thread.isMainThread {
1149
+ removeLoader()
1150
+ } else {
1151
+ DispatchQueue.main.async {
1152
+ removeLoader()
1153
+ }
1154
+ }
1155
+ }
1156
+
1157
+ private func scheduleSplashscreenTimeout() {
1158
+ guard self.autoSplashscreenTimeout > 0 else {
1159
+ return
1160
+ }
1161
+
1162
+ let scheduleTimeout = {
1163
+ self.autoSplashscreenTimeoutWorkItem?.cancel()
1164
+
1165
+ let workItem = DispatchWorkItem { [weak self] in
1166
+ guard let self = self else { return }
1167
+ self.autoSplashscreenTimedOut = true
1168
+ self.logger.info("autoSplashscreen timeout reached, hiding splashscreen")
1169
+ self.hideSplashscreen()
1170
+ }
1171
+ self.autoSplashscreenTimeoutWorkItem = workItem
1172
+ DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(self.autoSplashscreenTimeout), execute: workItem)
1173
+ }
1174
+
1175
+ if Thread.isMainThread {
1176
+ scheduleTimeout()
1177
+ } else {
1178
+ DispatchQueue.main.async {
1179
+ scheduleTimeout()
1180
+ }
1181
+ }
1182
+ }
1183
+
1184
+ private func cancelSplashscreenTimeout() {
1185
+ let cancelTimeout = {
1186
+ self.autoSplashscreenTimeoutWorkItem?.cancel()
1187
+ self.autoSplashscreenTimeoutWorkItem = nil
1188
+ }
1189
+
1190
+ if Thread.isMainThread {
1191
+ cancelTimeout()
1192
+ } else {
1193
+ DispatchQueue.main.async {
1194
+ cancelTimeout()
1195
+ }
1196
+ }
1197
+ }
1198
+
1199
+ private func checkIfRecentlyInstalledOrUpdated() -> Bool {
1200
+ let userDefaults = UserDefaults.standard
1201
+ let currentVersion = self.currentBuildVersion
1202
+ let lastKnownVersion = userDefaults.string(forKey: "LatestNativeBuildVersion") ?? "0"
1203
+
1204
+ if lastKnownVersion == "0" {
1205
+ // First time running, consider it as recently installed
1206
+ return true
1207
+ } else if lastKnownVersion != currentVersion {
1208
+ // Version changed, consider it as recently updated
1209
+ return true
1210
+ }
1211
+
1212
+ return false
1213
+ }
1214
+
1215
+ private func shouldUseDirectUpdate() -> Bool {
1216
+ if self.autoSplashscreenTimedOut {
1217
+ return false
1218
+ }
1219
+ switch directUpdateMode {
1220
+ case "false":
1221
+ return false
1222
+ case "always":
1223
+ return true
1224
+ case "atInstall":
1225
+ if self.wasRecentlyInstalledOrUpdated {
1226
+ // Reset the flag after first use to prevent subsequent foreground events from using direct update
1227
+ self.wasRecentlyInstalledOrUpdated = false
1228
+ return true
1229
+ }
1230
+ return false
1231
+ case "onLaunch":
1232
+ if !self.onLaunchDirectUpdateUsed {
1233
+ return true
1234
+ }
1235
+ return false
1236
+ default:
1237
+ logger.error("Invalid directUpdateMode: \"\(self.directUpdateMode)\". Supported values are: \"false\", \"always\", \"atInstall\", \"onLaunch\". Defaulting to \"false\" behavior.")
1238
+ return false
1239
+ }
1240
+ }
1241
+
1242
+ private func notifyBreakingEvents(version: String) {
1243
+ guard !version.isEmpty else {
1244
+ return
1245
+ }
1246
+ let payload: [String: Any] = ["version": version]
1247
+ self.notifyListeners("breakingAvailable", data: payload)
1248
+ self.notifyListeners("majorAvailable", data: payload)
1249
+ }
1250
+
1251
+ func endBackGroundTaskWithNotif(
1252
+ msg: String,
1253
+ latestVersionName: String,
1254
+ current: BundleInfo,
1255
+ error: Bool = true,
1256
+ failureAction: String = "download_fail",
1257
+ failureEvent: String = "downloadFailed",
1258
+ sendStats: Bool = true
1259
+ ) {
1260
+ if error {
1261
+ if sendStats {
1262
+ self.implementation.sendStats(action: failureAction, versionName: current.getVersionName())
1263
+ }
1264
+ self.notifyListeners(failureEvent, data: ["version": latestVersionName])
1265
+ }
1266
+ self.notifyListeners("noNeedUpdate", data: ["bundle": current.toJSON()])
1267
+ self.sendReadyToJs(current: current, msg: msg)
1268
+ logger.info("endBackGroundTaskWithNotif \(msg) current: \(current.getVersionName()) latestVersionName: \(latestVersionName)")
1269
+ self.endBackGroundTask()
1270
+ }
1271
+
1272
+ func backgroundDownload() {
1273
+ let plannedDirectUpdate = self.shouldUseDirectUpdate()
1274
+ let messageUpdate = plannedDirectUpdate ? "Update will occur now." : "Update will occur next time app moves to background."
1275
+ guard let url = URL(string: self.updateUrl) else {
1276
+ logger.error("Error no url or wrong format")
1277
+ return
1278
+ }
1279
+ DispatchQueue.global(qos: .background).async {
1280
+ self.backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Finish Download Tasks") {
1281
+ // End the task if time expires.
1282
+ self.endBackGroundTask()
1283
+ }
1284
+ self.logger.info("Check for update via \(self.updateUrl)")
1285
+ let res = self.implementation.getLatest(url: url, channel: nil)
1286
+ let current = self.implementation.getCurrentBundle()
1287
+
1288
+ // Handle network errors and other failures first
1289
+ if let backendError = res.error, !backendError.isEmpty {
1290
+ self.logger.error("getLatest failed with error: \(backendError)")
1291
+ let statusCode = res.statusCode
1292
+ let responseIsOk = statusCode >= 200 && statusCode < 300
1293
+ self.endBackGroundTaskWithNotif(
1294
+ msg: res.message ?? backendError,
1295
+ latestVersionName: res.version,
1296
+ current: current,
1297
+ error: true,
1298
+ sendStats: !responseIsOk
1299
+ )
1300
+ return
1301
+ }
1302
+ if res.version == "builtin" {
1303
+ self.logger.info("Latest version is builtin")
1304
+ let directUpdateAllowed = plannedDirectUpdate && !self.autoSplashscreenTimedOut
1305
+ if directUpdateAllowed {
1306
+ self.logger.info("Direct update to builtin version")
1307
+ if self.directUpdateMode == "onLaunch" {
1308
+ self.onLaunchDirectUpdateUsed = true
1309
+ self.directUpdate = false
1310
+ }
1311
+ _ = self._reset(toLastSuccessful: false)
1312
+ self.endBackGroundTaskWithNotif(msg: "Updated to builtin version", latestVersionName: res.version, current: self.implementation.getCurrentBundle(), error: false)
1313
+ } else {
1314
+ if plannedDirectUpdate && !directUpdateAllowed {
1315
+ self.logger.info("Direct update skipped because splashscreen timeout occurred. Update will apply later.")
1316
+ }
1317
+ self.logger.info("Setting next bundle to builtin")
1318
+ _ = self.implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
1319
+ self.endBackGroundTaskWithNotif(msg: "Next update will be to builtin version", latestVersionName: res.version, current: current, error: false)
1320
+ }
1321
+ return
1322
+ }
1323
+ let sessionKey = res.sessionKey ?? ""
1324
+ guard let downloadUrl = URL(string: res.url) else {
1325
+ self.logger.error("Error no url or wrong format")
1326
+ self.endBackGroundTaskWithNotif(msg: "Error no url or wrong format", latestVersionName: res.version, current: current)
1327
+ return
1328
+ }
1329
+ let latestVersionName = res.version
1330
+ if latestVersionName != "" && current.getVersionName() != latestVersionName {
1331
+ do {
1332
+ self.logger.info("New bundle: \(latestVersionName) found. Current is: \(current.getVersionName()). \(messageUpdate)")
1333
+ var nextImpl = self.implementation.getBundleInfoByVersionName(version: latestVersionName)
1334
+ if nextImpl == nil || nextImpl?.isDeleted() == true {
1335
+ if nextImpl?.isDeleted() == true {
1336
+ self.logger.info("Latest bundle already exists and will be deleted, download will overwrite it.")
1337
+ let res = self.implementation.delete(id: nextImpl!.getId(), removeInfo: true)
1338
+ if res {
1339
+ self.logger.info("Failed bundle deleted: \(nextImpl!.toString())")
1340
+ } else {
1341
+ self.logger.error("Failed to delete failed bundle: \(nextImpl!.toString())")
1342
+ }
1343
+ }
1344
+ if res.manifest != nil {
1345
+ nextImpl = try self.implementation.downloadManifest(manifest: res.manifest!, version: latestVersionName, sessionKey: sessionKey, link: res.link, comment: res.comment)
1346
+ } else {
1347
+ nextImpl = try self.implementation.download(url: downloadUrl, version: latestVersionName, sessionKey: sessionKey, link: res.link, comment: res.comment)
1348
+ }
1349
+ }
1350
+ guard let next = nextImpl else {
1351
+ self.logger.error("Error downloading file")
1352
+ self.endBackGroundTaskWithNotif(msg: "Error downloading file", latestVersionName: latestVersionName, current: current)
1353
+ return
1354
+ }
1355
+ if next.isErrorStatus() {
1356
+ self.logger.error("Latest bundle already exists and is in error state. Aborting update.")
1357
+ self.endBackGroundTaskWithNotif(msg: "Latest version is in error state. Aborting update.", latestVersionName: latestVersionName, current: current)
1358
+ return
1359
+ }
1360
+ res.checksum = try CryptoCipher.decryptChecksum(checksum: res.checksum, publicKey: self.implementation.publicKey)
1361
+ CryptoCipher.logChecksumInfo(label: "Bundle checksum", hexChecksum: next.getChecksum())
1362
+ CryptoCipher.logChecksumInfo(label: "Expected checksum", hexChecksum: res.checksum)
1363
+ if res.checksum != "" && next.getChecksum() != res.checksum && res.manifest == nil {
1364
+ self.logger.error("Error checksum \(next.getChecksum()) \(res.checksum)")
1365
+ self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
1366
+ let id = next.getId()
1367
+ let resDel = self.implementation.delete(id: id)
1368
+ if !resDel {
1369
+ self.logger.error("Delete failed, id \(id) doesn't exist")
1370
+ }
1371
+ self.endBackGroundTaskWithNotif(msg: "Error checksum", latestVersionName: latestVersionName, current: current)
1372
+ return
1373
+ }
1374
+ let directUpdateAllowed = plannedDirectUpdate && !self.autoSplashscreenTimedOut
1375
+ if directUpdateAllowed {
1376
+ let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
1377
+ let delayConditionList: [DelayCondition] = self.fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
1378
+ let kind: String = obj.value(forKey: "kind") as! String
1379
+ let value: String? = obj.value(forKey: "value") as? String
1380
+ return DelayCondition(kind: kind, value: value)
1381
+ }
1382
+ if !delayConditionList.isEmpty {
1383
+ self.logger.info("Update delayed until delay conditions met")
1384
+ self.endBackGroundTaskWithNotif(msg: "Update delayed until delay conditions met", latestVersionName: latestVersionName, current: next, error: false)
1385
+ return
1386
+ }
1387
+ if self.directUpdateMode == "onLaunch" {
1388
+ self.onLaunchDirectUpdateUsed = true
1389
+ self.directUpdate = false
1390
+ }
1391
+ _ = self.implementation.set(bundle: next)
1392
+ _ = self._reload()
1393
+ self.endBackGroundTaskWithNotif(msg: "update installed", latestVersionName: latestVersionName, current: next, error: false)
1394
+ } else {
1395
+ if plannedDirectUpdate && !directUpdateAllowed {
1396
+ self.logger.info("Direct update skipped because splashscreen timeout occurred. Update will install on next app background.")
1397
+ }
1398
+ self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
1399
+ _ = self.implementation.setNextBundle(next: next.getId())
1400
+ self.endBackGroundTaskWithNotif(msg: "update downloaded, will install next background", latestVersionName: latestVersionName, current: current, error: false)
1401
+ }
1402
+ return
1403
+ } catch {
1404
+ self.logger.error("Error downloading file \(error.localizedDescription)")
1405
+ let current: BundleInfo = self.implementation.getCurrentBundle()
1406
+ self.endBackGroundTaskWithNotif(msg: "Error downloading file", latestVersionName: latestVersionName, current: current)
1407
+ return
1408
+ }
1409
+ } else {
1410
+ self.logger.info("No need to update, \(current.getId()) is the latest bundle.")
1411
+ self.endBackGroundTaskWithNotif(msg: "No need to update, \(current.getId()) is the latest bundle.", latestVersionName: latestVersionName, current: current, error: false)
1412
+ return
1413
+ }
1414
+ }
1415
+ }
1416
+
1417
+ private func installNext() {
1418
+ let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
1419
+ let delayConditionList: [DelayCondition] = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
1420
+ let kind: String = obj.value(forKey: "kind") as! String
1421
+ let value: String? = obj.value(forKey: "value") as? String
1422
+ return DelayCondition(kind: kind, value: value)
1423
+ }
1424
+ if !delayConditionList.isEmpty {
1425
+ logger.info("Update delayed until delay conditions met")
1426
+ return
1427
+ }
1428
+ let current: BundleInfo = self.implementation.getCurrentBundle()
1429
+ let next: BundleInfo? = self.implementation.getNextBundle()
1430
+
1431
+ if next != nil && !next!.isErrorStatus() && next!.getVersionName() != current.getVersionName() {
1432
+ logger.info("Next bundle is: \(next!.toString())")
1433
+ if self.implementation.set(bundle: next!) && self._reload() {
1434
+ logger.info("Updated to bundle: \(next!.toString())")
1435
+ _ = self.implementation.setNextBundle(next: Optional<String>.none)
1436
+ } else {
1437
+ logger.error("Update to bundle: \(next!.toString()) Failed!")
1438
+ }
1439
+ }
1440
+ }
1441
+
1442
+ @objc private func toJson(object: Any) -> String {
1443
+ guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
1444
+ return ""
1445
+ }
1446
+ return String(data: data, encoding: String.Encoding.utf8) ?? ""
1447
+ }
1448
+
1449
+ @objc private func fromJsonArr(json: String) -> [NSObject] {
1450
+ guard let jsonData = json.data(using: .utf8) else {
1451
+ return []
1452
+ }
1453
+ let object = try? JSONSerialization.jsonObject(
1454
+ with: jsonData,
1455
+ options: .mutableContainers
1456
+ ) as? [NSObject]
1457
+ return object ?? []
1458
+ }
1459
+
1460
+ @objc func appMovedToForeground() {
1461
+ let current: BundleInfo = self.implementation.getCurrentBundle()
1462
+ self.implementation.sendStats(action: "app_moved_to_foreground", versionName: current.getVersionName())
1463
+ self.delayUpdateUtils.checkCancelDelay(source: .foreground)
1464
+ self.delayUpdateUtils.unsetBackgroundTimestamp()
1465
+ if backgroundWork != nil && taskRunning {
1466
+ backgroundWork!.cancel()
1467
+ logger.info("Background Timer Task canceled, Activity resumed before timer completes")
1468
+ }
1469
+ if self._isAutoUpdateEnabled() {
1470
+ self.backgroundDownload()
1471
+ } else {
1472
+ let instanceDescriptor = (self.bridge?.viewController as? CAPBridgeViewController)?.instanceDescriptor()
1473
+ if instanceDescriptor?.serverURL != nil {
1474
+ self.implementation.sendStats(action: "blocked_by_server_url", versionName: current.getVersionName())
1475
+ }
1476
+ logger.info("Auto update is disabled")
1477
+ self.sendReadyToJs(current: current, msg: "disabled")
1478
+ }
1479
+ self.checkAppReady()
1480
+ }
1481
+
1482
+ private var periodicUpdateTimer: Timer?
1483
+
1484
+ @objc func checkForUpdateAfterDelay() {
1485
+ if periodCheckDelay == 0 || !self._isAutoUpdateEnabled() {
1486
+ return
1487
+ }
1488
+ guard let url = URL(string: self.updateUrl) else {
1489
+ logger.error("Error no url or wrong format")
1490
+ return
1491
+ }
1492
+
1493
+ // Clean up any existing timer
1494
+ periodicUpdateTimer?.invalidate()
1495
+
1496
+ periodicUpdateTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(periodCheckDelay), repeats: true) { [weak self] timer in
1497
+ guard let self = self else {
1498
+ timer.invalidate()
1499
+ return
1500
+ }
1501
+ DispatchQueue.global(qos: .background).async {
1502
+ let res = self.implementation.getLatest(url: url, channel: nil)
1503
+ let current = self.implementation.getCurrentBundle()
1504
+
1505
+ if res.version != current.getVersionName() {
1506
+ self.logger.info("New version found: \(res.version)")
1507
+ self.backgroundDownload()
1508
+ }
1509
+ }
1510
+ }
1511
+ RunLoop.current.add(periodicUpdateTimer!, forMode: .default)
1512
+ }
1513
+
1514
+ @objc func appMovedToBackground() {
1515
+ let current: BundleInfo = self.implementation.getCurrentBundle()
1516
+ self.implementation.sendStats(action: "app_moved_to_background", versionName: current.getVersionName())
1517
+ logger.info("Check for pending update")
1518
+
1519
+ // Show splashscreen only if autoSplashscreen is enabled AND autoUpdate is enabled AND directUpdate would be used
1520
+ if self.autoSplashscreen {
1521
+ var canShowSplashscreen = true
1522
+
1523
+ if !self._isAutoUpdateEnabled() {
1524
+ logger.warn("autoSplashscreen is enabled but autoUpdate is disabled. Splashscreen will not be shown. Enable autoUpdate or disable autoSplashscreen.")
1525
+ canShowSplashscreen = false
1526
+ }
1527
+
1528
+ if !self.shouldUseDirectUpdate() {
1529
+ if self.directUpdateMode == "false" {
1530
+ logger.warn("autoSplashscreen is enabled but directUpdate is not configured for immediate updates. Set directUpdate to 'always' or disable autoSplashscreen.")
1531
+ } else if self.directUpdateMode == "atInstall" || self.directUpdateMode == "onLaunch" {
1532
+ logger.info("autoSplashscreen is enabled but directUpdate is set to \"\(self.directUpdateMode)\". This is normal. Skipping autoSplashscreen logic.")
1533
+ }
1534
+ canShowSplashscreen = false
1535
+ }
1536
+
1537
+ if canShowSplashscreen {
1538
+ self.showSplashscreen()
1539
+ }
1540
+ }
1541
+
1542
+ // Set background timestamp
1543
+ let backgroundTimestamp = Int64(Date().timeIntervalSince1970 * 1000) // Convert to milliseconds
1544
+ self.delayUpdateUtils.setBackgroundTimestamp(backgroundTimestamp)
1545
+ self.delayUpdateUtils.checkCancelDelay(source: .background)
1546
+ self.installNext()
1547
+ }
1548
+
1549
+ @objc func getNextBundle(_ call: CAPPluginCall) {
1550
+ let bundle = self.implementation.getNextBundle()
1551
+ if bundle == nil || bundle?.isUnknown() == true {
1552
+ call.resolve()
1553
+ return
1554
+ }
1555
+
1556
+ call.resolve(bundle!.toJSON())
1557
+ }
1558
+
1559
+ @objc func getFailedUpdate(_ call: CAPPluginCall) {
1560
+ let bundle = self.readLastFailedBundle()
1561
+ if bundle == nil || bundle?.isUnknown() == true {
1562
+ call.resolve()
1563
+ return
1564
+ }
1565
+
1566
+ self.persistLastFailedBundle(nil)
1567
+ call.resolve([
1568
+ "bundle": bundle!.toJSON()
1569
+ ])
1570
+ }
1571
+
1572
+ @objc func setShakeMenu(_ call: CAPPluginCall) {
1573
+ guard let enabled = call.getBool("enabled") else {
1574
+ logger.error("setShakeMenu called without enabled parameter")
1575
+ call.reject("setShakeMenu called without enabled parameter")
1576
+ return
1577
+ }
1578
+
1579
+ self.shakeMenuEnabled = enabled
1580
+ logger.info("Shake menu \(enabled ? "enabled" : "disabled")")
1581
+ call.resolve()
1582
+ }
1583
+
1584
+ @objc func isShakeMenuEnabled(_ call: CAPPluginCall) {
1585
+ call.resolve([
1586
+ "enabled": self.shakeMenuEnabled
1587
+ ])
1588
+ }
1589
+
1590
+ @objc func getAppId(_ call: CAPPluginCall) {
1591
+ call.resolve([
1592
+ "appId": implementation.appId
1593
+ ])
1594
+ }
1595
+
1596
+ @objc func setAppId(_ call: CAPPluginCall) {
1597
+ if !getConfig().getBoolean("allowModifyAppId", false) {
1598
+ logger.error("setAppId called without allowModifyAppId")
1599
+ call.reject("setAppId called without allowModifyAppId set allowModifyAppId in your config to true to allow it")
1600
+ return
1601
+ }
1602
+ guard let appId = call.getString("appId") else {
1603
+ logger.error("setAppId called without appId")
1604
+ call.reject("setAppId called without appId")
1605
+ return
1606
+ }
1607
+ implementation.appId = appId
1608
+ call.resolve()
1609
+ }
1610
+ }