@capgo/capacitor-updater 7.13.16 → 7.14.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 (30) hide show
  1. package/CapgoCapacitorUpdater.podspec +1 -0
  2. package/README.md +51 -0
  3. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +30 -1
  4. package/dist/docs.json +107 -0
  5. package/dist/esm/definitions.d.ts +31 -0
  6. package/dist/esm/definitions.js.map +1 -1
  7. package/dist/esm/web.d.ts +6 -0
  8. package/dist/esm/web.js +8 -0
  9. package/dist/esm/web.js.map +1 -1
  10. package/dist/plugin.cjs.js +8 -0
  11. package/dist/plugin.cjs.js.map +1 -1
  12. package/dist/plugin.js +8 -0
  13. package/dist/plugin.js.map +1 -1
  14. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +69 -0
  15. package/ios/Sources/CapacitorUpdaterPlugin/BigInt.swift +55 -0
  16. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +113 -0
  17. package/ios/Sources/CapacitorUpdaterPlugin/BundleStatus.swift +48 -0
  18. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1203 -0
  19. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +1301 -0
  20. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +187 -0
  21. package/ios/Sources/CapacitorUpdaterPlugin/DelayCondition.swift +74 -0
  22. package/ios/Sources/CapacitorUpdaterPlugin/DelayUntilNext.swift +30 -0
  23. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +222 -0
  24. package/ios/Sources/CapacitorUpdaterPlugin/Info.plist +28 -0
  25. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +303 -0
  26. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +310 -0
  27. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +274 -0
  28. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +112 -0
  29. package/ios/Sources/CapacitorUpdaterPlugin/UserDefaultsExtension.swift +46 -0
  30. package/package.json +2 -2
@@ -0,0 +1,1203 @@
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 Version
10
+
11
+ /**
12
+ * Please read the Capacitor iOS Plugin Development Guide
13
+ * here: https://capacitorjs.com/docs/plugins/ios
14
+ */
15
+ @objc(CapacitorUpdaterPlugin)
16
+ public class CapacitorUpdaterPlugin: CAPPlugin, CAPBridgedPlugin {
17
+ let logger = Logger(withTag: "✨ CapgoUpdater")
18
+
19
+ public let identifier = "CapacitorUpdaterPlugin"
20
+ public let jsName = "CapacitorUpdater"
21
+ public let pluginMethods: [CAPPluginMethod] = [
22
+ CAPPluginMethod(name: "download", returnType: CAPPluginReturnPromise),
23
+ CAPPluginMethod(name: "setUpdateUrl", returnType: CAPPluginReturnPromise),
24
+ CAPPluginMethod(name: "setStatsUrl", returnType: CAPPluginReturnPromise),
25
+ CAPPluginMethod(name: "setChannelUrl", returnType: CAPPluginReturnPromise),
26
+ CAPPluginMethod(name: "set", returnType: CAPPluginReturnPromise),
27
+ CAPPluginMethod(name: "list", returnType: CAPPluginReturnPromise),
28
+ CAPPluginMethod(name: "delete", returnType: CAPPluginReturnPromise),
29
+ CAPPluginMethod(name: "reset", returnType: CAPPluginReturnPromise),
30
+ CAPPluginMethod(name: "current", returnType: CAPPluginReturnPromise),
31
+ CAPPluginMethod(name: "reload", returnType: CAPPluginReturnPromise),
32
+ CAPPluginMethod(name: "notifyAppReady", returnType: CAPPluginReturnPromise),
33
+ CAPPluginMethod(name: "setDelay", returnType: CAPPluginReturnPromise),
34
+ CAPPluginMethod(name: "setMultiDelay", returnType: CAPPluginReturnPromise),
35
+ CAPPluginMethod(name: "cancelDelay", returnType: CAPPluginReturnPromise),
36
+ CAPPluginMethod(name: "getLatest", returnType: CAPPluginReturnPromise),
37
+ CAPPluginMethod(name: "setChannel", returnType: CAPPluginReturnPromise),
38
+ CAPPluginMethod(name: "unsetChannel", returnType: CAPPluginReturnPromise),
39
+ CAPPluginMethod(name: "getChannel", returnType: CAPPluginReturnPromise),
40
+ CAPPluginMethod(name: "listChannels", returnType: CAPPluginReturnPromise),
41
+ CAPPluginMethod(name: "setCustomId", returnType: CAPPluginReturnPromise),
42
+ CAPPluginMethod(name: "getDeviceId", returnType: CAPPluginReturnPromise),
43
+ CAPPluginMethod(name: "getPluginVersion", returnType: CAPPluginReturnPromise),
44
+ CAPPluginMethod(name: "next", returnType: CAPPluginReturnPromise),
45
+ CAPPluginMethod(name: "isAutoUpdateEnabled", returnType: CAPPluginReturnPromise),
46
+ CAPPluginMethod(name: "getBuiltinVersion", returnType: CAPPluginReturnPromise),
47
+ CAPPluginMethod(name: "isAutoUpdateAvailable", returnType: CAPPluginReturnPromise),
48
+ CAPPluginMethod(name: "getNextBundle", returnType: CAPPluginReturnPromise),
49
+ CAPPluginMethod(name: "setShakeMenu", returnType: CAPPluginReturnPromise),
50
+ CAPPluginMethod(name: "isShakeMenuEnabled", returnType: CAPPluginReturnPromise)
51
+ ]
52
+ public var implementation = CapgoUpdater()
53
+ private let PLUGIN_VERSION: String = "7.14.0"
54
+ static let updateUrlDefault = "https://plugin.capgo.app/updates"
55
+ static let statsUrlDefault = "https://plugin.capgo.app/stats"
56
+ static let channelUrlDefault = "https://plugin.capgo.app/channel_self"
57
+ // Note: DELAY_CONDITION_PREFERENCES is now defined in DelayUpdateUtils.DELAY_CONDITION_PREFERENCES
58
+ private var updateUrl = ""
59
+ private var statsUrl = ""
60
+ private var backgroundTaskID: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid
61
+ private var currentVersionNative: Version = "0.0.0"
62
+ private var currentBuildVersion: String = "0"
63
+ private var autoUpdate = false
64
+ private var appReadyTimeout = 10000
65
+ private var appReadyCheck: DispatchWorkItem?
66
+ private var resetWhenUpdate = true
67
+ private var directUpdate = false
68
+ private var directUpdateMode: String = "false"
69
+ private var wasRecentlyInstalledOrUpdated = false
70
+ private var autoSplashscreen = false
71
+ private var autoDeleteFailed = false
72
+ private var autoDeletePrevious = false
73
+ private var keepUrlPathAfterReload = false
74
+ private var backgroundWork: DispatchWorkItem?
75
+ private var taskRunning = false
76
+ private var periodCheckDelay = 0
77
+ public var shakeMenuEnabled = false
78
+ let semaphoreReady = DispatchSemaphore(value: 0)
79
+
80
+ private var delayUpdateUtils: DelayUpdateUtils!
81
+
82
+ override public func load() {
83
+ let disableJSLogging = getConfig().getBoolean("disableJSLogging", false)
84
+ // Set webView for logging to JavaScript console
85
+ if let webView = self.bridge?.webView, !disableJSLogging {
86
+ logger.setWebView(webView: webView)
87
+ logger.info("WebView set successfully for logging")
88
+ } else {
89
+ logger.error("Failed to get webView for logging")
90
+ }
91
+ #if targetEnvironment(simulator)
92
+ logger.info("::::: SIMULATOR :::::")
93
+ logger.info("Application directory: \(NSHomeDirectory())")
94
+ #endif
95
+
96
+ self.semaphoreUp()
97
+ self.implementation.deviceID = (UserDefaults.standard.string(forKey: "appUUID") ?? UUID().uuidString).lowercased()
98
+ UserDefaults.standard.set( self.implementation.deviceID, forKey: "appUUID")
99
+ UserDefaults.standard.synchronize()
100
+ logger.info("init for device \(self.implementation.deviceID)")
101
+ guard let versionName = getConfig().getString("version", Bundle.main.versionName) else {
102
+ logger.error("Cannot get version name")
103
+ // crash the app on purpose
104
+ fatalError("Cannot get version name")
105
+ }
106
+ do {
107
+ currentVersionNative = try Version(versionName)
108
+ } catch {
109
+ logger.error("Cannot parse versionName \(versionName)")
110
+ }
111
+ currentBuildVersion = Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "0"
112
+ logger.info("version native \(self.currentVersionNative.description)")
113
+ implementation.versionBuild = getConfig().getString("version", Bundle.main.versionName)!
114
+ autoDeleteFailed = getConfig().getBoolean("autoDeleteFailed", true)
115
+ autoDeletePrevious = getConfig().getBoolean("autoDeletePrevious", true)
116
+ keepUrlPathAfterReload = getConfig().getBoolean("keepUrlPathAfterReload", false)
117
+
118
+ // Handle directUpdate configuration - support string values and backward compatibility
119
+ if let directUpdateString = getConfig().getString("directUpdate") {
120
+ directUpdateMode = directUpdateString
121
+ directUpdate = directUpdateString == "always" || directUpdateString == "atInstall"
122
+ } else {
123
+ let directUpdateBool = getConfig().getBoolean("directUpdate", false)
124
+ if directUpdateBool {
125
+ directUpdateMode = "always" // backward compatibility: true = always
126
+ directUpdate = true
127
+ } else {
128
+ directUpdateMode = "false"
129
+ directUpdate = false
130
+ }
131
+ }
132
+
133
+ autoSplashscreen = getConfig().getBoolean("autoSplashscreen", false)
134
+ updateUrl = getConfig().getString("updateUrl", CapacitorUpdaterPlugin.updateUrlDefault)!
135
+ autoUpdate = getConfig().getBoolean("autoUpdate", true)
136
+ appReadyTimeout = getConfig().getInt("appReadyTimeout", 10000)
137
+ implementation.timeout = Double(getConfig().getInt("responseTimeout", 20))
138
+ resetWhenUpdate = getConfig().getBoolean("resetWhenUpdate", true)
139
+ shakeMenuEnabled = getConfig().getBoolean("shakeMenu", false)
140
+ let periodCheckDelayValue = getConfig().getInt("periodCheckDelay", 0)
141
+ if periodCheckDelayValue >= 0 && periodCheckDelayValue > 600 {
142
+ periodCheckDelay = 600
143
+ } else {
144
+ periodCheckDelay = periodCheckDelayValue
145
+ }
146
+
147
+ implementation.publicKey = getConfig().getString("publicKey", "")!
148
+ implementation.notifyDownloadRaw = notifyDownload
149
+ implementation.PLUGIN_VERSION = self.PLUGIN_VERSION
150
+
151
+ // Set logger for shared classes
152
+ implementation.setLogger(logger)
153
+ CryptoCipher.setLogger(logger)
154
+
155
+ // Initialize DelayUpdateUtils
156
+ self.delayUpdateUtils = DelayUpdateUtils(currentVersionNative: currentVersionNative, installNext: { [weak self] in
157
+ self?.installNext()
158
+ }, logger: logger)
159
+ let config = (self.bridge?.viewController as? CAPBridgeViewController)?.instanceDescriptor().legacyConfig
160
+ implementation.appId = Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String ?? ""
161
+ implementation.appId = config?["appId"] as? String ?? implementation.appId
162
+ implementation.appId = getConfig().getString("appId", implementation.appId)!
163
+ if implementation.appId == "" {
164
+ // crash the app on purpose it should not happen
165
+ 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")
166
+ }
167
+ logger.info("appId \(implementation.appId)")
168
+ implementation.statsUrl = getConfig().getString("statsUrl", CapacitorUpdaterPlugin.statsUrlDefault)!
169
+ implementation.channelUrl = getConfig().getString("channelUrl", CapacitorUpdaterPlugin.channelUrlDefault)!
170
+ implementation.defaultChannel = getConfig().getString("defaultChannel", "")!
171
+ self.implementation.autoReset()
172
+
173
+ // Check if app was recently installed/updated BEFORE cleanupObsoleteVersions updates LatestVersionNative
174
+ self.wasRecentlyInstalledOrUpdated = self.checkIfRecentlyInstalledOrUpdated()
175
+
176
+ if resetWhenUpdate {
177
+ self.cleanupObsoleteVersions()
178
+ }
179
+
180
+ // Load the server
181
+ // This is very much swift specific, android does not do that
182
+ // In android we depend on the serverBasePath capacitor property
183
+ // In IOS we do not. Instead during the plugin initialization we try to call setServerBasePath
184
+ // The idea is to prevent having to store the bundle in 2 locations for hot reload and persisten storage
185
+ // According to martin it is not possible to use serverBasePath on ios in a way that allows us to store the bundle once
186
+
187
+ if !self.initialLoad() {
188
+ logger.error("unable to force reload, the plugin might fallback to the builtin version")
189
+ }
190
+
191
+ let nc = NotificationCenter.default
192
+ nc.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
193
+ nc.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
194
+ nc.addObserver(self, selector: #selector(appKilled), name: UIApplication.willTerminateNotification, object: nil)
195
+ self.appMovedToForeground()
196
+ self.checkForUpdateAfterDelay()
197
+ }
198
+
199
+ private func initialLoad() -> Bool {
200
+ guard let bridge = self.bridge else { return false }
201
+
202
+ let id = self.implementation.getCurrentBundleId()
203
+ var dest: URL
204
+ if BundleInfo.ID_BUILTIN == id {
205
+ dest = Bundle.main.resourceURL!.appendingPathComponent("public")
206
+ } else {
207
+ dest = self.implementation.getBundleDirectory(id: id)
208
+ }
209
+
210
+ if !FileManager.default.fileExists(atPath: dest.path) {
211
+ logger.error("Initial load fail - file at path \(dest.path) doesn't exist. Defaulting to buildin!! \(id)")
212
+ dest = Bundle.main.resourceURL!.appendingPathComponent("public")
213
+ }
214
+
215
+ logger.info("Initial load \(id)")
216
+ // We don't use the viewcontroller here as it does not work during the initial load state
217
+ bridge.setServerBasePath(dest.path)
218
+ return true
219
+ }
220
+
221
+ private func semaphoreWait(waitTime: Int) {
222
+ // print("\\(CapgoUpdater.TAG) semaphoreWait \\(waitTime)")
223
+ let result = semaphoreReady.wait(timeout: .now() + .milliseconds(waitTime))
224
+ if result == .timedOut {
225
+ logger.error("Semaphore wait timed out after \(waitTime)ms")
226
+ }
227
+ }
228
+
229
+ private func semaphoreUp() {
230
+ DispatchQueue.global().async {
231
+ self.semaphoreWait(waitTime: 0)
232
+ }
233
+ }
234
+
235
+ private func semaphoreDown() {
236
+ semaphoreReady.signal()
237
+ }
238
+
239
+ private func cleanupObsoleteVersions() {
240
+ let previous = UserDefaults.standard.string(forKey: "LatestNativeBuildVersion") ?? "0"
241
+ if previous != "0" && self.currentBuildVersion != previous {
242
+ _ = self._reset(toLastSuccessful: false)
243
+ let res = implementation.list()
244
+ res.forEach { version in
245
+ logger.info("Deleting obsolete bundle: \(version.getId())")
246
+ let res = implementation.delete(id: version.getId())
247
+ if !res {
248
+ logger.error("Delete failed, id \(version.getId()) doesn't exist")
249
+ }
250
+ }
251
+ }
252
+ UserDefaults.standard.set(self.currentBuildVersion, forKey: "LatestNativeBuildVersion")
253
+ UserDefaults.standard.synchronize()
254
+ }
255
+
256
+ @objc func notifyDownload(id: String, percent: Int, ignoreMultipleOfTen: Bool = false) {
257
+ let bundle = self.implementation.getBundleInfo(id: id)
258
+ self.notifyListeners("download", data: ["percent": percent, "bundle": bundle.toJSON()])
259
+ if percent == 100 {
260
+ self.notifyListeners("downloadComplete", data: ["bundle": bundle.toJSON()])
261
+ self.implementation.sendStats(action: "download_complete", versionName: bundle.getVersionName())
262
+ } else if percent.isMultiple(of: 10) || ignoreMultipleOfTen {
263
+ self.implementation.sendStats(action: "download_\(percent)", versionName: bundle.getVersionName())
264
+ }
265
+ }
266
+
267
+ @objc func setUpdateUrl(_ call: CAPPluginCall) {
268
+ if !getConfig().getBoolean("allowModifyUrl", false) {
269
+ logger.error("setUpdateUrl called without allowModifyUrl")
270
+ call.reject("setUpdateUrl called without allowModifyUrl set allowModifyUrl in your config to true to allow it")
271
+ return
272
+ }
273
+ guard let url = call.getString("url") else {
274
+ logger.error("setUpdateUrl called without url")
275
+ call.reject("setUpdateUrl called without url")
276
+ return
277
+ }
278
+ self.updateUrl = url
279
+ call.resolve()
280
+ }
281
+
282
+ @objc func setStatsUrl(_ call: CAPPluginCall) {
283
+ if !getConfig().getBoolean("allowModifyUrl", false) {
284
+ logger.error("setStatsUrl called without allowModifyUrl")
285
+ call.reject("setStatsUrl called without allowModifyUrl set allowModifyUrl in your config to true to allow it")
286
+ return
287
+ }
288
+ guard let url = call.getString("url") else {
289
+ logger.error("setStatsUrl called without url")
290
+ call.reject("setStatsUrl called without url")
291
+ return
292
+ }
293
+ self.statsUrl = url
294
+ call.resolve()
295
+ }
296
+
297
+ @objc func setChannelUrl(_ call: CAPPluginCall) {
298
+ if !getConfig().getBoolean("allowModifyUrl", false) {
299
+ logger.error("setChannelUrl called without allowModifyUrl")
300
+ call.reject("setChannelUrl called without allowModifyUrl set allowModifyUrl in your config to true to allow it")
301
+ return
302
+ }
303
+ guard let url = call.getString("url") else {
304
+ logger.error("setChannelUrl called without url")
305
+ call.reject("setChannelUrl called without url")
306
+ return
307
+ }
308
+ self.implementation.channelUrl = url
309
+ call.resolve()
310
+ }
311
+
312
+ @objc func getBuiltinVersion(_ call: CAPPluginCall) {
313
+ call.resolve(["version": implementation.versionBuild])
314
+ }
315
+
316
+ @objc func getDeviceId(_ call: CAPPluginCall) {
317
+ call.resolve(["deviceId": implementation.deviceID])
318
+ }
319
+
320
+ @objc func getPluginVersion(_ call: CAPPluginCall) {
321
+ call.resolve(["version": self.PLUGIN_VERSION])
322
+ }
323
+
324
+ @objc func download(_ call: CAPPluginCall) {
325
+ guard let urlString = call.getString("url") else {
326
+ logger.error("Download called without url")
327
+ call.reject("Download called without url")
328
+ return
329
+ }
330
+ guard let version = call.getString("version") else {
331
+ logger.error("Download called without version")
332
+ call.reject("Download called without version")
333
+ return
334
+ }
335
+
336
+ let sessionKey = call.getString("sessionKey", "")
337
+ var checksum = call.getString("checksum", "")
338
+ let manifestArray = call.getArray("manifest")
339
+ let url = URL(string: urlString)
340
+ logger.info("Downloading \(String(describing: url))")
341
+ DispatchQueue.global(qos: .background).async {
342
+ do {
343
+ let next: BundleInfo
344
+ if let manifestArray = manifestArray {
345
+ // Convert JSArray to [ManifestEntry]
346
+ var manifestEntries: [ManifestEntry] = []
347
+ for item in manifestArray {
348
+ if let manifestDict = item as? [String: Any] {
349
+ let entry = ManifestEntry(
350
+ file_name: manifestDict["file_name"] as? String,
351
+ file_hash: manifestDict["file_hash"] as? String,
352
+ download_url: manifestDict["download_url"] as? String
353
+ )
354
+ manifestEntries.append(entry)
355
+ }
356
+ }
357
+ next = try self.implementation.downloadManifest(manifest: manifestEntries, version: version, sessionKey: sessionKey)
358
+ } else {
359
+ next = try self.implementation.download(url: url!, version: version, sessionKey: sessionKey)
360
+ }
361
+ // If public key is present but no checksum provided, refuse installation
362
+ if self.implementation.publicKey != "" && checksum == "" {
363
+ self.logger.error("Public key present but no checksum provided")
364
+ self.implementation.sendStats(action: "checksum_required", versionName: next.getVersionName())
365
+ let id = next.getId()
366
+ let resDel = self.implementation.delete(id: id)
367
+ if !resDel {
368
+ self.logger.error("Delete failed, id \(id) doesn't exist")
369
+ }
370
+ throw ObjectSavableError.checksum
371
+ }
372
+
373
+ checksum = try CryptoCipher.decryptChecksum(checksum: checksum, publicKey: self.implementation.publicKey)
374
+ if (checksum != "" || self.implementation.publicKey != "") && next.getChecksum() != checksum {
375
+ self.logger.error("Error checksum \(next.getChecksum()) \(checksum)")
376
+ self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
377
+ let id = next.getId()
378
+ let resDel = self.implementation.delete(id: id)
379
+ if !resDel {
380
+ self.logger.error("Delete failed, id \(id) doesn't exist")
381
+ }
382
+ throw ObjectSavableError.checksum
383
+ } else {
384
+ self.logger.info("Good checksum \(next.getChecksum()) \(checksum)")
385
+ }
386
+ self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
387
+ call.resolve(next.toJSON())
388
+ } catch {
389
+ self.logger.error("Failed to download from: \(String(describing: url)) \(error.localizedDescription)")
390
+ self.notifyListeners("downloadFailed", data: ["version": version])
391
+ self.implementation.sendStats(action: "download_fail")
392
+ call.reject("Failed to download from: \(url!)", error.localizedDescription)
393
+ }
394
+ }
395
+ }
396
+
397
+ public func _reload() -> Bool {
398
+ guard let bridge = self.bridge else { return false }
399
+ self.semaphoreUp()
400
+ let id = self.implementation.getCurrentBundleId()
401
+ let dest: URL
402
+ if BundleInfo.ID_BUILTIN == id {
403
+ dest = Bundle.main.resourceURL!.appendingPathComponent("public")
404
+ } else {
405
+ dest = self.implementation.getBundleDirectory(id: id)
406
+ }
407
+ logger.info("Reloading \(id)")
408
+ if let vc = bridge.viewController as? CAPBridgeViewController {
409
+ guard let capBridge = vc.bridge else {
410
+ logger.error("Cannot get capBridge")
411
+ return false
412
+ }
413
+ if keepUrlPathAfterReload {
414
+ DispatchQueue.main.async {
415
+ guard let url = vc.webView?.url else {
416
+ self.logger.error("vc.webView?.url is null?")
417
+ return
418
+ }
419
+ capBridge.setServerBasePath(dest.path)
420
+ var urlComponents = URLComponents(url: capBridge.config.serverURL, resolvingAgainstBaseURL: false)!
421
+ urlComponents.path = url.path
422
+ if let finalUrl = urlComponents.url {
423
+ _ = vc.webView?.load(URLRequest(url: finalUrl))
424
+ }
425
+ }
426
+ } else {
427
+ vc.setServerBasePath(path: dest.path)
428
+
429
+ }
430
+
431
+ self.checkAppReady()
432
+ self.notifyListeners("appReloaded", data: [:])
433
+ return true
434
+ }
435
+ return false
436
+ }
437
+
438
+ @objc func reload(_ call: CAPPluginCall) {
439
+ if self._reload() {
440
+ call.resolve()
441
+ } else {
442
+ logger.error("Reload failed")
443
+ call.reject("Reload failed")
444
+ }
445
+ }
446
+
447
+ @objc func next(_ call: CAPPluginCall) {
448
+ guard let id = call.getString("id") else {
449
+ logger.error("Next called without id")
450
+ call.reject("Next called without id")
451
+ return
452
+ }
453
+ logger.info("Setting next active id \(id)")
454
+ if !self.implementation.setNextBundle(next: id) {
455
+ logger.error("Set next version failed. id \(id) does not exist.")
456
+ call.reject("Set next version failed. id \(id) does not exist.")
457
+ } else {
458
+ call.resolve(self.implementation.getBundleInfo(id: id).toJSON())
459
+ }
460
+ }
461
+
462
+ @objc func set(_ call: CAPPluginCall) {
463
+ guard let id = call.getString("id") else {
464
+ logger.error("Set called without id")
465
+ call.reject("Set called without id")
466
+ return
467
+ }
468
+ let res = implementation.set(id: id)
469
+ logger.info("Set active bundle: \(id)")
470
+ if !res {
471
+ logger.info("Bundle successfully set to: \(id) ")
472
+ call.reject("Update failed, id \(id) doesn't exist")
473
+ } else {
474
+ self.reload(call)
475
+ }
476
+ }
477
+
478
+ @objc func delete(_ call: CAPPluginCall) {
479
+ guard let id = call.getString("id") else {
480
+ logger.error("Delete called without version")
481
+ call.reject("Delete called without id")
482
+ return
483
+ }
484
+ let res = implementation.delete(id: id)
485
+ if res {
486
+ call.resolve()
487
+ } else {
488
+ logger.error("Delete failed, id \(id) doesn't exist or it cannot be deleted (perhaps it is the 'next' bundle)")
489
+ call.reject("Delete failed, id \(id) does not exist or it cannot be deleted (perhaps it is the 'next' bundle)")
490
+ }
491
+ }
492
+
493
+ @objc func list(_ call: CAPPluginCall) {
494
+ let raw = call.getBool("raw", false)
495
+ let res = implementation.list(raw: raw)
496
+ var resArr: [[String: String]] = []
497
+ for v in res {
498
+ resArr.append(v.toJSON())
499
+ }
500
+ call.resolve([
501
+ "bundles": resArr
502
+ ])
503
+ }
504
+
505
+ @objc func getLatest(_ call: CAPPluginCall) {
506
+ let channel = call.getString("channel")
507
+ DispatchQueue.global(qos: .background).async {
508
+ let res = self.implementation.getLatest(url: URL(string: self.updateUrl)!, channel: channel)
509
+ if res.error != nil {
510
+ call.reject( res.error!)
511
+ } else if res.message != nil {
512
+ call.reject( res.message!)
513
+ } else {
514
+ call.resolve(res.toDict())
515
+ }
516
+ }
517
+ }
518
+
519
+ @objc func unsetChannel(_ call: CAPPluginCall) {
520
+ let triggerAutoUpdate = call.getBool("triggerAutoUpdate", false)
521
+ DispatchQueue.global(qos: .background).async {
522
+ let res = self.implementation.unsetChannel()
523
+ if res.error != "" {
524
+ call.reject(res.error, "UNSETCHANNEL_FAILED", nil, [
525
+ "message": res.error,
526
+ "error": res.error.contains("Channel URL") ? "missing_config" : "request_failed"
527
+ ])
528
+ } else {
529
+ if self._isAutoUpdateEnabled() && triggerAutoUpdate {
530
+ self.logger.info("Calling autoupdater after channel change!")
531
+ self.backgroundDownload()
532
+ }
533
+ call.resolve(res.toDict())
534
+ }
535
+ }
536
+ }
537
+
538
+ @objc func setChannel(_ call: CAPPluginCall) {
539
+ guard let channel = call.getString("channel") else {
540
+ logger.error("setChannel called without channel")
541
+ call.reject("setChannel called without channel", "SETCHANNEL_INVALID_PARAMS", nil, [
542
+ "message": "setChannel called without channel",
543
+ "error": "missing_parameter"
544
+ ])
545
+ return
546
+ }
547
+ let triggerAutoUpdate = call.getBool("triggerAutoUpdate") ?? false
548
+ DispatchQueue.global(qos: .background).async {
549
+ let res = self.implementation.setChannel(channel: channel)
550
+ if res.error != "" {
551
+ call.reject(res.error, "SETCHANNEL_FAILED", nil, [
552
+ "message": res.error,
553
+ "error": res.error.contains("Channel URL") ? "missing_config" : "request_failed"
554
+ ])
555
+ } else {
556
+ if self._isAutoUpdateEnabled() && triggerAutoUpdate {
557
+ self.logger.info("Calling autoupdater after channel change!")
558
+ self.backgroundDownload()
559
+ }
560
+ call.resolve(res.toDict())
561
+ }
562
+ }
563
+ }
564
+
565
+ @objc func getChannel(_ call: CAPPluginCall) {
566
+ DispatchQueue.global(qos: .background).async {
567
+ let res = self.implementation.getChannel()
568
+ if res.error != "" {
569
+ call.reject(res.error, "GETCHANNEL_FAILED", nil, [
570
+ "message": res.error,
571
+ "error": res.error.contains("Channel URL") ? "missing_config" : "request_failed"
572
+ ])
573
+ } else {
574
+ call.resolve(res.toDict())
575
+ }
576
+ }
577
+ }
578
+
579
+ @objc func listChannels(_ call: CAPPluginCall) {
580
+ DispatchQueue.global(qos: .background).async {
581
+ let res = self.implementation.listChannels()
582
+ if res.error != "" {
583
+ call.reject(res.error, "LISTCHANNELS_FAILED", nil, [
584
+ "message": res.error,
585
+ "error": res.error.contains("Channel URL") ? "missing_config" : "request_failed"
586
+ ])
587
+ } else {
588
+ call.resolve(res.toDict())
589
+ }
590
+ }
591
+ }
592
+
593
+ @objc func setCustomId(_ call: CAPPluginCall) {
594
+ guard let customId = call.getString("customId") else {
595
+ logger.error("setCustomId called without customId")
596
+ call.reject("setCustomId called without customId")
597
+ return
598
+ }
599
+ self.implementation.customId = customId
600
+ }
601
+
602
+ @objc func _reset(toLastSuccessful: Bool) -> Bool {
603
+ guard let bridge = self.bridge else { return false }
604
+
605
+ if (bridge.viewController as? CAPBridgeViewController) != nil {
606
+ let fallback: BundleInfo = self.implementation.getFallbackBundle()
607
+
608
+ // If developer wants to reset to the last successful bundle, and that bundle is not
609
+ // the built-in bundle, set it as the bundle to use and reload.
610
+ if toLastSuccessful && !fallback.isBuiltin() {
611
+ logger.info("Resetting to: \(fallback.toString())")
612
+ return self.implementation.set(bundle: fallback) && self._reload()
613
+ }
614
+
615
+ logger.info("Resetting to builtin version")
616
+
617
+ // Otherwise, reset back to the built-in bundle and reload.
618
+ self.implementation.reset()
619
+ return self._reload()
620
+ }
621
+
622
+ return false
623
+ }
624
+
625
+ @objc func reset(_ call: CAPPluginCall) {
626
+ let toLastSuccessful = call.getBool("toLastSuccessful") ?? false
627
+ if self._reset(toLastSuccessful: toLastSuccessful) {
628
+ call.resolve()
629
+ } else {
630
+ logger.error("Reset failed")
631
+ call.reject("Reset failed")
632
+ }
633
+ }
634
+
635
+ @objc func current(_ call: CAPPluginCall) {
636
+ let bundle: BundleInfo = self.implementation.getCurrentBundle()
637
+ call.resolve([
638
+ "bundle": bundle.toJSON(),
639
+ "native": self.currentVersionNative.description
640
+ ])
641
+ }
642
+
643
+ @objc func notifyAppReady(_ call: CAPPluginCall) {
644
+ self.semaphoreDown()
645
+ let bundle = self.implementation.getCurrentBundle()
646
+ self.implementation.setSuccess(bundle: bundle, autoDeletePrevious: self.autoDeletePrevious)
647
+ logger.info("Current bundle loaded successfully. [notifyAppReady was called] \(bundle.toString())")
648
+ call.resolve(["bundle": bundle.toJSON()])
649
+ }
650
+
651
+ @objc func setMultiDelay(_ call: CAPPluginCall) {
652
+ guard let delayConditionList = call.getValue("delayConditions") else {
653
+ logger.error("setMultiDelay called without delayCondition")
654
+ call.reject("setMultiDelay called without delayCondition")
655
+ return
656
+ }
657
+
658
+ // Handle background conditions with empty value (set to "0")
659
+ if var modifiableList = delayConditionList as? [[String: Any]] {
660
+ for i in 0..<modifiableList.count {
661
+ if let kind = modifiableList[i]["kind"] as? String,
662
+ kind == "background",
663
+ let value = modifiableList[i]["value"] as? String,
664
+ value.isEmpty {
665
+ modifiableList[i]["value"] = "0"
666
+ }
667
+ }
668
+ let delayConditions: String = toJson(object: modifiableList)
669
+ if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
670
+ call.resolve()
671
+ } else {
672
+ call.reject("Failed to delay update")
673
+ }
674
+ } else {
675
+ let delayConditions: String = toJson(object: delayConditionList)
676
+ if delayUpdateUtils.setMultiDelay(delayConditions: delayConditions) {
677
+ call.resolve()
678
+ } else {
679
+ call.reject("Failed to delay update")
680
+ }
681
+ }
682
+ }
683
+
684
+ // Note: _setMultiDelay and _cancelDelay methods have been moved to DelayUpdateUtils class
685
+
686
+ @objc func cancelDelay(_ call: CAPPluginCall) {
687
+ if delayUpdateUtils.cancelDelay(source: "JS") {
688
+ call.resolve()
689
+ } else {
690
+ call.reject("Failed to cancel delay")
691
+ }
692
+ }
693
+
694
+ // Note: _checkCancelDelay method has been moved to DelayUpdateUtils class
695
+
696
+ private func _isAutoUpdateEnabled() -> Bool {
697
+ let instanceDescriptor = (self.bridge?.viewController as? CAPBridgeViewController)?.instanceDescriptor()
698
+ if instanceDescriptor?.serverURL != nil {
699
+ logger.warn("AutoUpdate is automatic disabled when serverUrl is set.")
700
+ }
701
+ return self.autoUpdate && self.updateUrl != "" && instanceDescriptor?.serverURL == nil
702
+ }
703
+
704
+ @objc func isAutoUpdateEnabled(_ call: CAPPluginCall) {
705
+ call.resolve([
706
+ "enabled": self._isAutoUpdateEnabled()
707
+ ])
708
+ }
709
+
710
+ @objc func isAutoUpdateAvailable(_ call: CAPPluginCall) {
711
+ let instanceDescriptor = (self.bridge?.viewController as? CAPBridgeViewController)?.instanceDescriptor()
712
+ let isAvailable = instanceDescriptor?.serverURL == nil
713
+ call.resolve([
714
+ "available": isAvailable
715
+ ])
716
+ }
717
+
718
+ func checkAppReady() {
719
+ self.appReadyCheck?.cancel()
720
+ self.appReadyCheck = DispatchWorkItem(block: {
721
+ self.DeferredNotifyAppReadyCheck()
722
+ })
723
+ logger.info("Wait for \(self.appReadyTimeout) ms, then check for notifyAppReady")
724
+ DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(self.appReadyTimeout), execute: self.appReadyCheck!)
725
+ }
726
+
727
+ func checkRevert() {
728
+ // Automatically roll back to fallback version if notifyAppReady has not been called yet
729
+ let current: BundleInfo = self.implementation.getCurrentBundle()
730
+ if current.isBuiltin() {
731
+ logger.info("Built-in bundle is active. We skip the check for notifyAppReady.")
732
+ return
733
+ }
734
+
735
+ logger.info("Current bundle is: \(current.toString())")
736
+
737
+ if BundleStatus.SUCCESS.localizedString != current.getStatus() {
738
+ logger.error("notifyAppReady was not called, roll back current bundle: \(current.toString())")
739
+ logger.error("Did you forget to call 'notifyAppReady()' in your Capacitor App code?")
740
+ self.notifyListeners("updateFailed", data: [
741
+ "bundle": current.toJSON()
742
+ ])
743
+ self.implementation.sendStats(action: "update_fail", versionName: current.getVersionName())
744
+ self.implementation.setError(bundle: current)
745
+ _ = self._reset(toLastSuccessful: true)
746
+ if self.autoDeleteFailed && !current.isBuiltin() {
747
+ logger.info("Deleting failing bundle: \(current.toString())")
748
+ let res = self.implementation.delete(id: current.getId(), removeInfo: false)
749
+ if !res {
750
+ logger.info("Delete version deleted: \(current.toString())")
751
+ } else {
752
+ logger.error("Failed to delete failed bundle: \(current.toString())")
753
+ }
754
+ }
755
+ } else {
756
+ logger.info("notifyAppReady was called. This is fine: \(current.toString())")
757
+ }
758
+ }
759
+
760
+ func DeferredNotifyAppReadyCheck() {
761
+ self.checkRevert()
762
+ self.appReadyCheck = nil
763
+ }
764
+
765
+ func endBackGroundTask() {
766
+ UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
767
+ self.backgroundTaskID = UIBackgroundTaskIdentifier.invalid
768
+ }
769
+
770
+ func sendReadyToJs(current: BundleInfo, msg: String) {
771
+ logger.info("sendReadyToJs")
772
+ DispatchQueue.global().async {
773
+ self.semaphoreWait(waitTime: self.appReadyTimeout)
774
+ self.notifyListeners("appReady", data: ["bundle": current.toJSON(), "status": msg], retainUntilConsumed: true)
775
+
776
+ // Auto hide splashscreen if enabled
777
+ // We show it on background when conditions are met, so we should hide it on foreground regardless of update outcome
778
+ if self.autoSplashscreen {
779
+ self.hideSplashscreen()
780
+ }
781
+ }
782
+ }
783
+
784
+ private func hideSplashscreen() {
785
+ DispatchQueue.main.async {
786
+ guard let bridge = self.bridge else {
787
+ self.logger.warn("Bridge not available for hiding splashscreen with autoSplashscreen")
788
+ return
789
+ }
790
+
791
+ // Create a plugin call for the hide method
792
+ let call = CAPPluginCall(callbackId: "autoHideSplashscreen", options: [:], success: { (_, _) in
793
+ self.logger.info("Splashscreen hidden automatically")
794
+ }, error: { (_) in
795
+ self.logger.error("Failed to auto-hide splashscreen")
796
+ })
797
+
798
+ // Try to call the SplashScreen hide method directly through the bridge
799
+ if let splashScreenPlugin = bridge.plugin(withName: "SplashScreen") {
800
+ // Use runtime method invocation to call hide method
801
+ let selector = NSSelectorFromString("hide:")
802
+ if splashScreenPlugin.responds(to: selector) {
803
+ _ = splashScreenPlugin.perform(selector, with: call)
804
+ self.logger.info("Called SplashScreen hide method")
805
+ } else {
806
+ self.logger.warn("autoSplashscreen: SplashScreen plugin does not respond to hide: method. Make sure @capacitor/splash-screen plugin is properly installed.")
807
+ }
808
+ } else {
809
+ self.logger.warn("autoSplashscreen: SplashScreen plugin not found. Install @capacitor/splash-screen plugin.")
810
+ }
811
+ }
812
+ }
813
+
814
+ private func showSplashscreen() {
815
+ DispatchQueue.main.async {
816
+ guard let bridge = self.bridge else {
817
+ self.logger.warn("Bridge not available for showing splashscreen with autoSplashscreen")
818
+ return
819
+ }
820
+
821
+ // Create a plugin call for the show method
822
+ let call = CAPPluginCall(callbackId: "autoShowSplashscreen", options: [:], success: { (_, _) in
823
+ self.logger.info("Splashscreen shown automatically")
824
+ }, error: { (_) in
825
+ self.logger.error("Failed to auto-show splashscreen")
826
+ })
827
+
828
+ // Try to call the SplashScreen show method directly through the bridge
829
+ if let splashScreenPlugin = bridge.plugin(withName: "SplashScreen") {
830
+ // Use runtime method invocation to call show method
831
+ let selector = NSSelectorFromString("show:")
832
+ if splashScreenPlugin.responds(to: selector) {
833
+ _ = splashScreenPlugin.perform(selector, with: call)
834
+ self.logger.info("Called SplashScreen show method")
835
+ } else {
836
+ self.logger.warn("autoSplashscreen: SplashScreen plugin does not respond to show: method. Make sure @capacitor/splash-screen plugin is properly installed.")
837
+ }
838
+ } else {
839
+ self.logger.warn("autoSplashscreen: SplashScreen plugin not found. Install @capacitor/splash-screen plugin.")
840
+ }
841
+ }
842
+ }
843
+
844
+ private func checkIfRecentlyInstalledOrUpdated() -> Bool {
845
+ let userDefaults = UserDefaults.standard
846
+ let currentVersion = self.currentBuildVersion
847
+ let lastKnownVersion = userDefaults.string(forKey: "LatestNativeBuildVersion") ?? "0"
848
+
849
+ if lastKnownVersion == "0" {
850
+ // First time running, consider it as recently installed
851
+ return true
852
+ } else if lastKnownVersion != currentVersion {
853
+ // Version changed, consider it as recently updated
854
+ return true
855
+ }
856
+
857
+ return false
858
+ }
859
+
860
+ private func shouldUseDirectUpdate() -> Bool {
861
+ switch directUpdateMode {
862
+ case "false":
863
+ return false
864
+ case "always":
865
+ return true
866
+ case "atInstall":
867
+ if self.wasRecentlyInstalledOrUpdated {
868
+ // Reset the flag after first use to prevent subsequent foreground events from using direct update
869
+ self.wasRecentlyInstalledOrUpdated = false
870
+ return true
871
+ }
872
+ return false
873
+ default:
874
+ return false
875
+ }
876
+ }
877
+
878
+ func endBackGroundTaskWithNotif(msg: String, latestVersionName: String, current: BundleInfo, error: Bool = true) {
879
+ if error {
880
+ self.implementation.sendStats(action: "download_fail", versionName: current.getVersionName())
881
+ self.notifyListeners("downloadFailed", data: ["version": latestVersionName])
882
+ }
883
+ self.notifyListeners("noNeedUpdate", data: ["bundle": current.toJSON()])
884
+ self.sendReadyToJs(current: current, msg: msg)
885
+ logger.info("endBackGroundTaskWithNotif \(msg) current: \(current.getVersionName()) latestVersionName: \(latestVersionName)")
886
+ self.endBackGroundTask()
887
+ }
888
+
889
+ func backgroundDownload() {
890
+ let shouldDirectUpdate = self.shouldUseDirectUpdate()
891
+ let messageUpdate = shouldDirectUpdate ? "Update will occur now." : "Update will occur next time app moves to background."
892
+ guard let url = URL(string: self.updateUrl) else {
893
+ logger.error("Error no url or wrong format")
894
+ return
895
+ }
896
+ DispatchQueue.global(qos: .background).async {
897
+ self.backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Finish Download Tasks") {
898
+ // End the task if time expires.
899
+ self.endBackGroundTask()
900
+ }
901
+ self.logger.info("Check for update via \(self.updateUrl)")
902
+ let res = self.implementation.getLatest(url: url, channel: nil)
903
+ let current = self.implementation.getCurrentBundle()
904
+
905
+ // Handle network errors and other failures first
906
+ if res.error != nil {
907
+ self.logger.error("getLatest failed with error: \(res.error ?? "")")
908
+ self.endBackGroundTaskWithNotif(msg: "Network error: \(res.error ?? "")", latestVersionName: res.version, current: current, error: true)
909
+ return
910
+ }
911
+
912
+ if (res.message) != nil {
913
+ self.logger.info("API message: \(res.message ?? "")")
914
+ if res.major == true {
915
+ self.notifyListeners("majorAvailable", data: ["version": res.version])
916
+ }
917
+ self.endBackGroundTaskWithNotif(msg: res.message ?? "", latestVersionName: res.version, current: current, error: true)
918
+ return
919
+ }
920
+ if res.version == "builtin" {
921
+ self.logger.info("Latest version is builtin")
922
+ if shouldDirectUpdate {
923
+ self.logger.info("Direct update to builtin version")
924
+ _ = self._reset(toLastSuccessful: false)
925
+ self.endBackGroundTaskWithNotif(msg: "Updated to builtin version", latestVersionName: res.version, current: self.implementation.getCurrentBundle(), error: false)
926
+ } else {
927
+ self.logger.info("Setting next bundle to builtin")
928
+ _ = self.implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
929
+ self.endBackGroundTaskWithNotif(msg: "Next update will be to builtin version", latestVersionName: res.version, current: current, error: false)
930
+ }
931
+ return
932
+ }
933
+ let sessionKey = res.sessionKey ?? ""
934
+ guard let downloadUrl = URL(string: res.url) else {
935
+ self.logger.error("Error no url or wrong format")
936
+ self.endBackGroundTaskWithNotif(msg: "Error no url or wrong format", latestVersionName: res.version, current: current)
937
+ return
938
+ }
939
+ let latestVersionName = res.version
940
+ if latestVersionName != "" && current.getVersionName() != latestVersionName {
941
+ do {
942
+ self.logger.info("New bundle: \(latestVersionName) found. Current is: \(current.getVersionName()). \(messageUpdate)")
943
+ var nextImpl = self.implementation.getBundleInfoByVersionName(version: latestVersionName)
944
+ if nextImpl == nil || nextImpl?.isDeleted() == true {
945
+ if nextImpl?.isDeleted() == true {
946
+ self.logger.info("Latest bundle already exists and will be deleted, download will overwrite it.")
947
+ let res = self.implementation.delete(id: nextImpl!.getId(), removeInfo: true)
948
+ if res {
949
+ self.logger.info("Failed bundle deleted: \(nextImpl!.toString())")
950
+ } else {
951
+ self.logger.error("Failed to delete failed bundle: \(nextImpl!.toString())")
952
+ }
953
+ }
954
+ if res.manifest != nil {
955
+ nextImpl = try self.implementation.downloadManifest(manifest: res.manifest!, version: latestVersionName, sessionKey: sessionKey)
956
+ } else {
957
+ nextImpl = try self.implementation.download(url: downloadUrl, version: latestVersionName, sessionKey: sessionKey)
958
+ }
959
+ }
960
+ guard let next = nextImpl else {
961
+ self.logger.error("Error downloading file")
962
+ self.endBackGroundTaskWithNotif(msg: "Error downloading file", latestVersionName: latestVersionName, current: current)
963
+ return
964
+ }
965
+ if next.isErrorStatus() {
966
+ self.logger.error("Latest bundle already exists and is in error state. Aborting update.")
967
+ self.endBackGroundTaskWithNotif(msg: "Latest version is in error state. Aborting update.", latestVersionName: latestVersionName, current: current)
968
+ return
969
+ }
970
+ res.checksum = try CryptoCipher.decryptChecksum(checksum: res.checksum, publicKey: self.implementation.publicKey)
971
+ if res.checksum != "" && next.getChecksum() != res.checksum && res.manifest == nil {
972
+ self.logger.error("Error checksum \(next.getChecksum()) \(res.checksum)")
973
+ self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
974
+ let id = next.getId()
975
+ let resDel = self.implementation.delete(id: id)
976
+ if !resDel {
977
+ self.logger.error("Delete failed, id \(id) doesn't exist")
978
+ }
979
+ self.endBackGroundTaskWithNotif(msg: "Error checksum", latestVersionName: latestVersionName, current: current)
980
+ return
981
+ }
982
+ if shouldDirectUpdate {
983
+ let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
984
+ let delayConditionList: [DelayCondition] = self.fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
985
+ let kind: String = obj.value(forKey: "kind") as! String
986
+ let value: String? = obj.value(forKey: "value") as? String
987
+ return DelayCondition(kind: kind, value: value)
988
+ }
989
+ if !delayConditionList.isEmpty {
990
+ self.logger.info("Update delayed until delay conditions met")
991
+ self.endBackGroundTaskWithNotif(msg: "Update delayed until delay conditions met", latestVersionName: latestVersionName, current: next, error: false)
992
+ return
993
+ }
994
+ _ = self.implementation.set(bundle: next)
995
+ _ = self._reload()
996
+ self.endBackGroundTaskWithNotif(msg: "update installed", latestVersionName: latestVersionName, current: next, error: false)
997
+ } else {
998
+ self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
999
+ _ = self.implementation.setNextBundle(next: next.getId())
1000
+ self.endBackGroundTaskWithNotif(msg: "update downloaded, will install next background", latestVersionName: latestVersionName, current: current, error: false)
1001
+ }
1002
+ return
1003
+ } catch {
1004
+ self.logger.error("Error downloading file \(error.localizedDescription)")
1005
+ let current: BundleInfo = self.implementation.getCurrentBundle()
1006
+ self.endBackGroundTaskWithNotif(msg: "Error downloading file", latestVersionName: latestVersionName, current: current)
1007
+ return
1008
+ }
1009
+ } else {
1010
+ self.logger.info("No need to update, \(current.getId()) is the latest bundle.")
1011
+ self.endBackGroundTaskWithNotif(msg: "No need to update, \(current.getId()) is the latest bundle.", latestVersionName: latestVersionName, current: current, error: false)
1012
+ return
1013
+ }
1014
+ }
1015
+ }
1016
+
1017
+ @objc func appKilled() {
1018
+ logger.info("onActivityDestroyed: all activity destroyed")
1019
+ self.delayUpdateUtils.checkCancelDelay(source: .killed)
1020
+
1021
+ // Clean up resources
1022
+ periodicUpdateTimer?.invalidate()
1023
+ periodicUpdateTimer = nil
1024
+ backgroundWork?.cancel()
1025
+ backgroundWork = nil
1026
+
1027
+ // Signal any waiting semaphores to prevent deadlocks
1028
+ semaphoreReady.signal()
1029
+ }
1030
+
1031
+ private func installNext() {
1032
+ let delayUpdatePreferences = UserDefaults.standard.string(forKey: DelayUpdateUtils.DELAY_CONDITION_PREFERENCES) ?? "[]"
1033
+ let delayConditionList: [DelayCondition] = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
1034
+ let kind: String = obj.value(forKey: "kind") as! String
1035
+ let value: String? = obj.value(forKey: "value") as? String
1036
+ return DelayCondition(kind: kind, value: value)
1037
+ }
1038
+ if !delayConditionList.isEmpty {
1039
+ logger.info("Update delayed until delay conditions met")
1040
+ return
1041
+ }
1042
+ let current: BundleInfo = self.implementation.getCurrentBundle()
1043
+ let next: BundleInfo? = self.implementation.getNextBundle()
1044
+
1045
+ if next != nil && !next!.isErrorStatus() && next!.getVersionName() != current.getVersionName() {
1046
+ logger.info("Next bundle is: \(next!.toString())")
1047
+ if self.implementation.set(bundle: next!) && self._reload() {
1048
+ logger.info("Updated to bundle: \(next!.toString())")
1049
+ _ = self.implementation.setNextBundle(next: Optional<String>.none)
1050
+ } else {
1051
+ logger.error("Update to bundle: \(next!.toString()) Failed!")
1052
+ }
1053
+ }
1054
+ }
1055
+
1056
+ @objc private func toJson(object: Any) -> String {
1057
+ guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
1058
+ return ""
1059
+ }
1060
+ return String(data: data, encoding: String.Encoding.utf8) ?? ""
1061
+ }
1062
+
1063
+ @objc private func fromJsonArr(json: String) -> [NSObject] {
1064
+ guard let jsonData = json.data(using: .utf8) else {
1065
+ return []
1066
+ }
1067
+ let object = try? JSONSerialization.jsonObject(
1068
+ with: jsonData,
1069
+ options: .mutableContainers
1070
+ ) as? [NSObject]
1071
+ return object ?? []
1072
+ }
1073
+
1074
+ @objc func appMovedToForeground() {
1075
+ let current: BundleInfo = self.implementation.getCurrentBundle()
1076
+ self.implementation.sendStats(action: "app_moved_to_foreground", versionName: current.getVersionName())
1077
+ self.delayUpdateUtils.checkCancelDelay(source: .foreground)
1078
+ self.delayUpdateUtils.unsetBackgroundTimestamp()
1079
+ if backgroundWork != nil && taskRunning {
1080
+ backgroundWork!.cancel()
1081
+ logger.info("Background Timer Task canceled, Activity resumed before timer completes")
1082
+ }
1083
+ if self._isAutoUpdateEnabled() {
1084
+ self.backgroundDownload()
1085
+ } else {
1086
+ logger.info("Auto update is disabled")
1087
+ self.sendReadyToJs(current: current, msg: "disabled")
1088
+ }
1089
+ self.checkAppReady()
1090
+ }
1091
+
1092
+ private var periodicUpdateTimer: Timer?
1093
+
1094
+ @objc func checkForUpdateAfterDelay() {
1095
+ if periodCheckDelay == 0 || !self._isAutoUpdateEnabled() {
1096
+ return
1097
+ }
1098
+ guard let url = URL(string: self.updateUrl) else {
1099
+ logger.error("Error no url or wrong format")
1100
+ return
1101
+ }
1102
+
1103
+ // Clean up any existing timer
1104
+ periodicUpdateTimer?.invalidate()
1105
+
1106
+ periodicUpdateTimer = Timer.scheduledTimer(withTimeInterval: TimeInterval(periodCheckDelay), repeats: true) { [weak self] timer in
1107
+ guard let self = self else {
1108
+ timer.invalidate()
1109
+ return
1110
+ }
1111
+ DispatchQueue.global(qos: .background).async {
1112
+ let res = self.implementation.getLatest(url: url, channel: nil)
1113
+ let current = self.implementation.getCurrentBundle()
1114
+
1115
+ if res.version != current.getVersionName() {
1116
+ self.logger.info("New version found: \(res.version)")
1117
+ self.backgroundDownload()
1118
+ }
1119
+ }
1120
+ }
1121
+ RunLoop.current.add(periodicUpdateTimer!, forMode: .default)
1122
+ }
1123
+
1124
+ @objc func appMovedToBackground() {
1125
+ let current: BundleInfo = self.implementation.getCurrentBundle()
1126
+ self.implementation.sendStats(action: "app_moved_to_background", versionName: current.getVersionName())
1127
+ logger.info("Check for pending update")
1128
+
1129
+ // Show splashscreen only if autoSplashscreen is enabled AND autoUpdate is enabled AND directUpdate would be used
1130
+ if self.autoSplashscreen {
1131
+ var canShowSplashscreen = true
1132
+
1133
+ if !self._isAutoUpdateEnabled() {
1134
+ logger.warn("autoSplashscreen is enabled but autoUpdate is disabled. Splashscreen will not be shown. Enable autoUpdate or disable autoSplashscreen.")
1135
+ canShowSplashscreen = false
1136
+ }
1137
+
1138
+ if !self.shouldUseDirectUpdate() {
1139
+ logger.warn("autoSplashscreen is enabled but directUpdate is not configured for immediate updates. Set directUpdate to 'always' or 'atInstall', or disable autoSplashscreen.")
1140
+ canShowSplashscreen = false
1141
+ }
1142
+
1143
+ if canShowSplashscreen {
1144
+ self.showSplashscreen()
1145
+ }
1146
+ }
1147
+
1148
+ // Set background timestamp
1149
+ let backgroundTimestamp = Int64(Date().timeIntervalSince1970 * 1000) // Convert to milliseconds
1150
+ self.delayUpdateUtils.setBackgroundTimestamp(backgroundTimestamp)
1151
+ self.delayUpdateUtils.checkCancelDelay(source: .background)
1152
+ self.installNext()
1153
+ }
1154
+
1155
+ @objc func getNextBundle(_ call: CAPPluginCall) {
1156
+ let bundle = self.implementation.getNextBundle()
1157
+ if bundle == nil || bundle?.isUnknown() == true {
1158
+ call.resolve()
1159
+ return
1160
+ }
1161
+
1162
+ call.resolve(bundle!.toJSON())
1163
+ }
1164
+
1165
+ @objc func setShakeMenu(_ call: CAPPluginCall) {
1166
+ guard let enabled = call.getBool("enabled") else {
1167
+ logger.error("setShakeMenu called without enabled parameter")
1168
+ call.reject("setShakeMenu called without enabled parameter")
1169
+ return
1170
+ }
1171
+
1172
+ self.shakeMenuEnabled = enabled
1173
+ logger.info("Shake menu \(enabled ? "enabled" : "disabled")")
1174
+ call.resolve()
1175
+ }
1176
+
1177
+ @objc func isShakeMenuEnabled(_ call: CAPPluginCall) {
1178
+ call.resolve([
1179
+ "enabled": self.shakeMenuEnabled
1180
+ ])
1181
+ }
1182
+
1183
+ @objc func getAppId(_ call: CAPPluginCall) {
1184
+ call.resolve([
1185
+ "appId": implementation.appId
1186
+ ])
1187
+ }
1188
+
1189
+ @objc func setAppId(_ call: CAPPluginCall) {
1190
+ if !getConfig().getBoolean("allowModifyAppId", false) {
1191
+ logger.error("setAppId called without allowModifyAppId")
1192
+ call.reject("setAppId called without allowModifyAppId set allowModifyAppId in your config to true to allow it")
1193
+ return
1194
+ }
1195
+ guard let appId = call.getString("appId") else {
1196
+ logger.error("setAppId called without appId")
1197
+ call.reject("setAppId called without appId")
1198
+ return
1199
+ }
1200
+ implementation.appId = appId
1201
+ call.resolve()
1202
+ }
1203
+ }