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