@capgo/capacitor-updater 6.14.26 → 6.14.29

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 (54) hide show
  1. package/CapgoCapacitorUpdater.podspec +3 -2
  2. package/Package.swift +2 -2
  3. package/README.md +341 -74
  4. package/android/build.gradle +20 -8
  5. package/android/proguard-rules.pro +22 -5
  6. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +52 -16
  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 +1196 -508
  9. package/android/src/main/java/ee/forgr/capacitor_updater/{CapacitorUpdater.java → CapgoUpdater.java} +522 -154
  10. package/android/src/main/java/ee/forgr/capacitor_updater/{CryptoCipher.java → CryptoCipherV1.java} +17 -9
  11. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipherV2.java +15 -26
  12. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +0 -3
  13. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +260 -0
  14. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +300 -119
  15. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +63 -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 +652 -63
  20. package/dist/esm/definitions.d.ts +265 -15
  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/{Plugin → Sources/CapacitorUpdaterPlugin}/AES.swift +6 -3
  36. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +1575 -0
  37. package/ios/{Plugin/CapacitorUpdater.swift → Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift} +365 -139
  38. package/ios/{Plugin/CryptoCipher.swift → Sources/CapacitorUpdaterPlugin/CryptoCipherV1.swift} +13 -6
  39. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/CryptoCipherV2.swift +33 -27
  40. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +220 -0
  41. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/InternalUtils.swift +47 -0
  42. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +310 -0
  43. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/RSA.swift +1 -0
  44. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +112 -0
  45. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +0 -2
  46. package/package.json +20 -16
  47. package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -1030
  48. /package/{LICENCE → LICENSE} +0 -0
  49. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/BigInt.swift +0 -0
  50. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/BundleInfo.swift +0 -0
  51. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/BundleStatus.swift +0 -0
  52. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
  53. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
  54. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
@@ -1,1030 +0,0 @@
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
- public let identifier = "CapacitorUpdaterPlugin"
18
- public let jsName = "CapacitorUpdater"
19
- public let pluginMethods: [CAPPluginMethod] = [
20
- CAPPluginMethod(name: "download", returnType: CAPPluginReturnPromise),
21
- CAPPluginMethod(name: "setUpdateUrl", returnType: CAPPluginReturnPromise),
22
- CAPPluginMethod(name: "setStatsUrl", returnType: CAPPluginReturnPromise),
23
- CAPPluginMethod(name: "setChannelUrl", returnType: CAPPluginReturnPromise),
24
- CAPPluginMethod(name: "set", returnType: CAPPluginReturnPromise),
25
- CAPPluginMethod(name: "list", returnType: CAPPluginReturnPromise),
26
- CAPPluginMethod(name: "delete", returnType: CAPPluginReturnPromise),
27
- CAPPluginMethod(name: "reset", returnType: CAPPluginReturnPromise),
28
- CAPPluginMethod(name: "current", returnType: CAPPluginReturnPromise),
29
- CAPPluginMethod(name: "reload", returnType: CAPPluginReturnPromise),
30
- CAPPluginMethod(name: "notifyAppReady", returnType: CAPPluginReturnPromise),
31
- CAPPluginMethod(name: "setDelay", returnType: CAPPluginReturnPromise),
32
- CAPPluginMethod(name: "setMultiDelay", returnType: CAPPluginReturnPromise),
33
- CAPPluginMethod(name: "cancelDelay", returnType: CAPPluginReturnPromise),
34
- CAPPluginMethod(name: "getLatest", returnType: CAPPluginReturnPromise),
35
- CAPPluginMethod(name: "setChannel", returnType: CAPPluginReturnPromise),
36
- CAPPluginMethod(name: "unsetChannel", returnType: CAPPluginReturnPromise),
37
- CAPPluginMethod(name: "getChannel", returnType: CAPPluginReturnPromise),
38
- CAPPluginMethod(name: "setCustomId", returnType: CAPPluginReturnPromise),
39
- CAPPluginMethod(name: "getDeviceId", returnType: CAPPluginReturnPromise),
40
- CAPPluginMethod(name: "getPluginVersion", returnType: CAPPluginReturnPromise),
41
- CAPPluginMethod(name: "next", returnType: CAPPluginReturnPromise),
42
- CAPPluginMethod(name: "isAutoUpdateEnabled", returnType: CAPPluginReturnPromise),
43
- CAPPluginMethod(name: "getBuiltinVersion", returnType: CAPPluginReturnPromise),
44
- CAPPluginMethod(name: "isAutoUpdateAvailable", returnType: CAPPluginReturnPromise),
45
- CAPPluginMethod(name: "getNextBundle", returnType: CAPPluginReturnPromise)
46
- ]
47
- public var implementation = CapacitorUpdater()
48
- private let PLUGIN_VERSION: String = "6.14.26"
49
- static let updateUrlDefault = "https://plugin.capgo.app/updates"
50
- static let statsUrlDefault = "https://plugin.capgo.app/stats"
51
- static let channelUrlDefault = "https://plugin.capgo.app/channel_self"
52
- let DELAY_CONDITION_PREFERENCES = ""
53
- private var updateUrl = ""
54
- private var statsUrl = ""
55
- private var backgroundTaskID: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid
56
- private var currentVersionNative: Version = "0.0.0"
57
- private var autoUpdate = false
58
- private var appReadyTimeout = 10000
59
- private var appReadyCheck: DispatchWorkItem?
60
- private var resetWhenUpdate = true
61
- private var directUpdate = false
62
- private var autoDeleteFailed = false
63
- private var autoDeletePrevious = false
64
- private var keepUrlPathAfterReload = false
65
- private var backgroundWork: DispatchWorkItem?
66
- private var taskRunning = false
67
- private var periodCheckDelay = 0
68
- let semaphoreReady = DispatchSemaphore(value: 0)
69
-
70
- override public func load() {
71
- #if targetEnvironment(simulator)
72
- print("\(CapacitorUpdater.TAG) ::::: SIMULATOR :::::")
73
- print("\(CapacitorUpdater.TAG) Application directory: \(NSHomeDirectory())")
74
- #endif
75
-
76
- self.semaphoreUp()
77
- self.implementation.deviceID = (UserDefaults.standard.string(forKey: "appUUID") ?? UUID().uuidString).lowercased()
78
- UserDefaults.standard.set( self.implementation.deviceID, forKey: "appUUID")
79
- UserDefaults.standard.synchronize()
80
- print("\(CapacitorUpdater.TAG) init for device \(self.implementation.deviceID)")
81
- guard let versionName = getConfig().getString("version", Bundle.main.versionName) else {
82
- print("\(CapacitorUpdater.TAG) Cannot get version name")
83
- // crash the app
84
- fatalError("Cannot get version name")
85
- }
86
- do {
87
- currentVersionNative = try Version(versionName)
88
- } catch {
89
- print("\(CapacitorUpdater.TAG) Cannot parse versionName \(versionName)")
90
- }
91
- print("\(CapacitorUpdater.TAG) version native \(self.currentVersionNative.description)")
92
- implementation.versionBuild = getConfig().getString("version", Bundle.main.versionName)!
93
- autoDeleteFailed = getConfig().getBoolean("autoDeleteFailed", true)
94
- autoDeletePrevious = getConfig().getBoolean("autoDeletePrevious", true)
95
- keepUrlPathAfterReload = getConfig().getBoolean("keepUrlPathAfterReload", false)
96
- directUpdate = getConfig().getBoolean("directUpdate", false)
97
- updateUrl = getConfig().getString("updateUrl", CapacitorUpdaterPlugin.updateUrlDefault)!
98
- autoUpdate = getConfig().getBoolean("autoUpdate", true)
99
- appReadyTimeout = getConfig().getInt("appReadyTimeout", 10000)
100
- implementation.timeout = Double(getConfig().getInt("responseTimeout", 20))
101
- resetWhenUpdate = getConfig().getBoolean("resetWhenUpdate", true)
102
- let periodCheckDelayValue = getConfig().getInt("periodCheckDelay", 0)
103
- if periodCheckDelayValue >= 0 && periodCheckDelayValue > 600 {
104
- periodCheckDelay = 600
105
- } else {
106
- periodCheckDelay = periodCheckDelayValue
107
- }
108
-
109
- implementation.privateKey = getConfig().getString("privateKey", "")!
110
- implementation.publicKey = getConfig().getString("publicKey", "")!
111
- if !implementation.privateKey.isEmpty {
112
- implementation.hasOldPrivateKeyPropertyInConfig = true
113
- }
114
- implementation.notifyDownloadRaw = notifyDownload
115
- implementation.PLUGIN_VERSION = self.PLUGIN_VERSION
116
- let config = (self.bridge?.viewController as? CAPBridgeViewController)?.instanceDescriptor().legacyConfig
117
- implementation.appId = Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String ?? ""
118
- implementation.appId = config?["appId"] as? String ?? implementation.appId
119
- implementation.appId = getConfig().getString("appId", implementation.appId)!
120
- if implementation.appId == "" {
121
- 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")
122
- }
123
- print("\(CapacitorUpdater.TAG) appId \(implementation.appId)")
124
- implementation.statsUrl = getConfig().getString("statsUrl", CapacitorUpdaterPlugin.statsUrlDefault)!
125
- implementation.channelUrl = getConfig().getString("channelUrl", CapacitorUpdaterPlugin.channelUrlDefault)!
126
- implementation.defaultChannel = getConfig().getString("defaultChannel", "")!
127
- self.implementation.autoReset()
128
-
129
- if resetWhenUpdate {
130
- self.cleanupObsoleteVersions()
131
- }
132
-
133
- // Load the server
134
- // This is very much swift specific, android does not do that
135
- // In android we depend on the serverBasePath capacitor property
136
- // In IOS we do not. Instead during the plugin initialization we try to call setServerBasePath
137
- // The idea is to prevent having to store the bundle in 2 locations for hot reload and persisten storage
138
- // According to martin it is not possible to use serverBasePath on ios in a way that allows us to store the bundle once
139
-
140
- if !self.initialLoad() {
141
- print("\(CapacitorUpdater.TAG) unable to force reload, the plugin might fallback to the builtin version")
142
- }
143
-
144
- let nc = NotificationCenter.default
145
- nc.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
146
- nc.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
147
-
148
- // Check for 'kill' delay condition on app launch
149
- // This handles cases where the app was killed (willTerminateNotification is not reliable for system kills)
150
- self._checkCancelDelay(killed: true)
151
-
152
- self.appMovedToForeground()
153
- self.checkForUpdateAfterDelay()
154
- }
155
-
156
- private func initialLoad() -> Bool {
157
- guard let bridge = self.bridge else { return false }
158
-
159
- let id = self.implementation.getCurrentBundleId()
160
- var dest: URL
161
- if BundleInfo.ID_BUILTIN == id {
162
- dest = Bundle.main.resourceURL!.appendingPathComponent("public")
163
- } else {
164
- dest = self.implementation.getBundleDirectory(id: id)
165
- }
166
-
167
- if !FileManager.default.fileExists(atPath: dest.path) {
168
- print("\(CapacitorUpdater.TAG) Initial load fail - file at path \(dest.path) doesn't exist. Defaulting to buildin!! \(id)")
169
- dest = Bundle.main.resourceURL!.appendingPathComponent("public")
170
- }
171
-
172
- print("\(CapacitorUpdater.TAG) Initial load \(id)")
173
- // We don't use the viewcontroller here as it does not work during the initial load state
174
- bridge.setServerBasePath(dest.path)
175
- return true
176
- }
177
-
178
- private func semaphoreWait(waitTime: Int) {
179
- print("\(CapacitorUpdater.TAG) semaphoreWait \(waitTime)")
180
- _ = semaphoreReady.wait(timeout: .now() + .milliseconds(waitTime))
181
- }
182
-
183
- private func semaphoreUp() {
184
- DispatchQueue.global().async {
185
- self.semaphoreWait(waitTime: 0)
186
- }
187
- }
188
-
189
- private func semaphoreDown() {
190
- semaphoreReady.signal()
191
- }
192
-
193
- private func cleanupObsoleteVersions() {
194
- var LatestVersionNative: Version = "0.0.0"
195
- do {
196
- LatestVersionNative = try Version(UserDefaults.standard.string(forKey: "LatestVersionNative") ?? "0.0.0")
197
- } catch {
198
- print("\(CapacitorUpdater.TAG) Cannot get version native \(currentVersionNative)")
199
- }
200
- if LatestVersionNative != "0.0.0" && self.currentVersionNative.description != LatestVersionNative.description {
201
- _ = self._reset(toLastSuccessful: false)
202
- let res = implementation.list()
203
- res.forEach { version in
204
- print("\(CapacitorUpdater.TAG) Deleting obsolete bundle: \(version.getId())")
205
- let res = implementation.delete(id: version.getId())
206
- if !res {
207
- print("\(CapacitorUpdater.TAG) Delete failed, id \(version.getId()) doesn't exist")
208
- }
209
- }
210
- }
211
- UserDefaults.standard.set( self.currentVersionNative.description, forKey: "LatestVersionNative")
212
- UserDefaults.standard.synchronize()
213
- }
214
-
215
- @objc func notifyDownload(id: String, percent: Int, ignoreMultipleOfTen: Bool = false) {
216
- let bundle = self.implementation.getBundleInfo(id: id)
217
- self.notifyListeners("download", data: ["percent": percent, "bundle": bundle.toJSON()])
218
- if percent == 100 {
219
- self.notifyListeners("downloadComplete", data: ["bundle": bundle.toJSON()])
220
- self.implementation.sendStats(action: "download_complete", versionName: bundle.getVersionName())
221
- } else if percent.isMultiple(of: 10) || ignoreMultipleOfTen {
222
- self.implementation.sendStats(action: "download_\(percent)", versionName: bundle.getVersionName())
223
- }
224
- }
225
-
226
- @objc func setUpdateUrl(_ call: CAPPluginCall) {
227
- if !getConfig().getBoolean("allowModifyUrl", false) {
228
- print("\(CapacitorUpdater.TAG) setUpdateUrl called without allowModifyUrl")
229
- call.reject("setUpdateUrl called without allowModifyUrl set allowModifyUrl in your config to true to allow it")
230
- return
231
- }
232
- guard let url = call.getString("url") else {
233
- print("\(CapacitorUpdater.TAG) setUpdateUrl called without url")
234
- call.reject("setUpdateUrl called without url")
235
- return
236
- }
237
- self.updateUrl = url
238
- call.resolve()
239
- }
240
-
241
- @objc func setStatsUrl(_ call: CAPPluginCall) {
242
- if !getConfig().getBoolean("allowModifyUrl", false) {
243
- print("\(CapacitorUpdater.TAG) setStatsUrl called without allowModifyUrl")
244
- call.reject("setStatsUrl called without allowModifyUrl set allowModifyUrl in your config to true to allow it")
245
- return
246
- }
247
- guard let url = call.getString("url") else {
248
- print("\(CapacitorUpdater.TAG) setStatsUrl called without url")
249
- call.reject("setStatsUrl called without url")
250
- return
251
- }
252
- self.statsUrl = url
253
- call.resolve()
254
- }
255
-
256
- @objc func setChannelUrl(_ call: CAPPluginCall) {
257
- if !getConfig().getBoolean("allowModifyUrl", false) {
258
- print("\(CapacitorUpdater.TAG) setChannelUrl called without allowModifyUrl")
259
- call.reject("setChannelUrl called without allowModifyUrl set allowModifyUrl in your config to true to allow it")
260
- return
261
- }
262
- guard let url = call.getString("url") else {
263
- print("\(CapacitorUpdater.TAG) setChannelUrl called without url")
264
- call.reject("setChannelUrl called without url")
265
- return
266
- }
267
- self.implementation.channelUrl = url
268
- call.resolve()
269
- }
270
-
271
- @objc func getBuiltinVersion(_ call: CAPPluginCall) {
272
- call.resolve(["version": implementation.versionBuild])
273
- }
274
-
275
- @objc func getDeviceId(_ call: CAPPluginCall) {
276
- call.resolve(["deviceId": implementation.deviceID])
277
- }
278
-
279
- @objc func getPluginVersion(_ call: CAPPluginCall) {
280
- call.resolve(["version": self.PLUGIN_VERSION])
281
- }
282
-
283
- @objc func download(_ call: CAPPluginCall) {
284
- guard let urlString = call.getString("url") else {
285
- print("\(CapacitorUpdater.TAG) Download called without url")
286
- call.reject("Download called without url")
287
- return
288
- }
289
- guard let version = call.getString("version") else {
290
- print("\(CapacitorUpdater.TAG) Download called without version")
291
- call.reject("Download called without version")
292
- return
293
- }
294
-
295
- let sessionKey = call.getString("sessionKey", "")
296
- var checksum = call.getString("checksum", "")
297
- let url = URL(string: urlString)
298
- print("\(CapacitorUpdater.TAG) Downloading \(String(describing: url))")
299
- DispatchQueue.global(qos: .background).async {
300
- do {
301
- let next = try self.implementation.download(url: url!, version: version, sessionKey: sessionKey)
302
- if !self.implementation.hasOldPrivateKeyPropertyInConfig {
303
- do {
304
- checksum = try CryptoCipherV2.decryptChecksum(checksum: checksum, publicKey: self.implementation.publicKey, version: version)
305
- } catch {
306
- self.implementation.sendStats(action: "decrypt_fail", versionName: version)
307
- throw error
308
- }
309
- }
310
- if (checksum != "" || self.implementation.publicKey != "") && next.getChecksum() != checksum {
311
- print("\(CapacitorUpdater.TAG) Error checksum", next.getChecksum(), checksum)
312
- self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
313
- let id = next.getId()
314
- let resDel = self.implementation.delete(id: id)
315
- if !resDel {
316
- print("\(CapacitorUpdater.TAG) Delete failed, id \(id) doesn't exist")
317
- }
318
- throw ObjectSavableError.checksum
319
- } else {
320
- print("\(CapacitorUpdater.TAG) Good checksum", next.getChecksum(), checksum)
321
- }
322
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
323
- call.resolve(next.toJSON())
324
- } catch {
325
- print("\(CapacitorUpdater.TAG) Failed to download from: \(String(describing: url)) \(error.localizedDescription)")
326
- self.notifyListeners("downloadFailed", data: ["version": version])
327
- self.implementation.sendStats(action: "download_fail")
328
- call.reject("Failed to download from: \(url!)", error.localizedDescription)
329
- }
330
- }
331
- }
332
-
333
- public func _reload() -> Bool {
334
- guard let bridge = self.bridge else { return false }
335
- self.semaphoreUp()
336
- let id = self.implementation.getCurrentBundleId()
337
- let dest: URL
338
- if BundleInfo.ID_BUILTIN == id {
339
- dest = Bundle.main.resourceURL!.appendingPathComponent("public")
340
- } else {
341
- dest = self.implementation.getBundleDirectory(id: id)
342
- }
343
- print("\(CapacitorUpdater.TAG) Reloading \(id)")
344
- if let vc = bridge.viewController as? CAPBridgeViewController {
345
- guard let capBridge = vc.bridge else {
346
- print("\(CapacitorUpdater.TAG) Cannot get capBridge")
347
- return false
348
- }
349
- if keepUrlPathAfterReload {
350
- DispatchQueue.main.async {
351
- guard let url = vc.webView?.url else {
352
- print("\(CapacitorUpdater.TAG) vc.webView?.url is null?")
353
- return
354
- }
355
- capBridge.setServerBasePath(dest.path)
356
- var urlComponents = URLComponents(url: capBridge.config.serverURL, resolvingAgainstBaseURL: false)!
357
- urlComponents.path = url.path
358
- if let finalUrl = urlComponents.url {
359
- _ = vc.webView?.load(URLRequest(url: finalUrl))
360
- vc.webView?.backForwardList.perform(Selector(("_removeAllItems")))
361
- }
362
- }
363
- } else {
364
- vc.setServerBasePath(path: dest.path)
365
-
366
- }
367
-
368
- self.checkAppReady()
369
- self.notifyListeners("appReloaded", data: [:])
370
- return true
371
- }
372
- return false
373
- }
374
-
375
- @objc func reload(_ call: CAPPluginCall) {
376
- if self._reload() {
377
- call.resolve()
378
- } else {
379
- print("\(CapacitorUpdater.TAG) Reload failed")
380
- call.reject("Reload failed")
381
- }
382
- }
383
-
384
- @objc func next(_ call: CAPPluginCall) {
385
- guard let id = call.getString("id") else {
386
- print("\(CapacitorUpdater.TAG) Next called without id")
387
- call.reject("Next called without id")
388
- return
389
- }
390
- print("\(CapacitorUpdater.TAG) Setting next active id \(id)")
391
- if !self.implementation.setNextBundle(next: id) {
392
- print("\(CapacitorUpdater.TAG) Set next version failed. id \(id) does not exist.")
393
- call.reject("Set next version failed. id \(id) does not exist.")
394
- } else {
395
- call.resolve(self.implementation.getBundleInfo(id: id).toJSON())
396
- }
397
- }
398
-
399
- @objc func set(_ call: CAPPluginCall) {
400
- guard let id = call.getString("id") else {
401
- print("\(CapacitorUpdater.TAG) Set called without id")
402
- call.reject("Set called without id")
403
- return
404
- }
405
- let res = implementation.set(id: id)
406
- print("\(CapacitorUpdater.TAG) Set active bundle: \(id)")
407
- if !res {
408
- print("\(CapacitorUpdater.TAG) Bundle successfully set to: \(id) ")
409
- call.reject("Update failed, id \(id) doesn't exist")
410
- } else {
411
- self.reload(call)
412
- }
413
- }
414
-
415
- @objc func delete(_ call: CAPPluginCall) {
416
- guard let id = call.getString("id") else {
417
- print("\(CapacitorUpdater.TAG) Delete called without version")
418
- call.reject("Delete called without id")
419
- return
420
- }
421
- let res = implementation.delete(id: id)
422
- if res {
423
- call.resolve()
424
- } else {
425
- print("\(CapacitorUpdater.TAG) Delete failed, id \(id) doesn't exist or it cannot be deleted (perhaps it is the 'next' bundle)")
426
- call.reject("Delete failed, id \(id) does not exist or it cannot be deleted (perhaps it is the 'next' bundle)")
427
- }
428
- }
429
-
430
- @objc func list(_ call: CAPPluginCall) {
431
- let raw = call.getBool("raw", false)
432
- let res = implementation.list(raw: raw)
433
- var resArr: [[String: String]] = []
434
- for v in res {
435
- resArr.append(v.toJSON())
436
- }
437
- call.resolve([
438
- "bundles": resArr
439
- ])
440
- }
441
-
442
- @objc func getLatest(_ call: CAPPluginCall) {
443
- let channel = call.getString("channel")
444
- DispatchQueue.global(qos: .background).async {
445
- let res = self.implementation.getLatest(url: URL(string: self.updateUrl)!, channel: channel)
446
- if res.error != nil {
447
- call.reject( res.error!)
448
- } else if res.message != nil {
449
- call.reject( res.message!)
450
- } else {
451
- call.resolve(res.toDict())
452
- }
453
- }
454
- }
455
-
456
- @objc func unsetChannel(_ call: CAPPluginCall) {
457
- let triggerAutoUpdate = call.getBool("triggerAutoUpdate", false)
458
- DispatchQueue.global(qos: .background).async {
459
- let res = self.implementation.unsetChannel()
460
- if res.error != "" {
461
- call.reject(res.error)
462
- } else {
463
- if self._isAutoUpdateEnabled() && triggerAutoUpdate {
464
- print("\(CapacitorUpdater.TAG) Calling autoupdater after channel change!")
465
- self.backgroundDownload()
466
- }
467
- call.resolve(res.toDict())
468
- }
469
- }
470
- }
471
-
472
- @objc func setChannel(_ call: CAPPluginCall) {
473
- guard let channel = call.getString("channel") else {
474
- print("\(CapacitorUpdater.TAG) setChannel called without channel")
475
- call.reject("setChannel called without channel")
476
- return
477
- }
478
- let triggerAutoUpdate = call.getBool("triggerAutoUpdate") ?? false
479
- DispatchQueue.global(qos: .background).async {
480
- let res = self.implementation.setChannel(channel: channel)
481
- if res.error != "" {
482
- call.reject(res.error)
483
- } else {
484
- if self._isAutoUpdateEnabled() && triggerAutoUpdate {
485
- print("\(CapacitorUpdater.TAG) Calling autoupdater after channel change!")
486
- self.backgroundDownload()
487
- }
488
- call.resolve(res.toDict())
489
- }
490
- }
491
- }
492
-
493
- @objc func getChannel(_ call: CAPPluginCall) {
494
- DispatchQueue.global(qos: .background).async {
495
- let res = self.implementation.getChannel()
496
- if res.error != "" {
497
- call.reject(res.error)
498
- } else {
499
- call.resolve(res.toDict())
500
- }
501
- }
502
- }
503
- @objc func setCustomId(_ call: CAPPluginCall) {
504
- guard let customId = call.getString("customId") else {
505
- print("\(CapacitorUpdater.TAG) setCustomId called without customId")
506
- call.reject("setCustomId called without customId")
507
- return
508
- }
509
- self.implementation.customId = customId
510
- }
511
-
512
- @objc func _reset(toLastSuccessful: Bool) -> Bool {
513
- guard let bridge = self.bridge else { return false }
514
-
515
- if (bridge.viewController as? CAPBridgeViewController) != nil {
516
- let fallback: BundleInfo = self.implementation.getFallbackBundle()
517
-
518
- // If developer wants to reset to the last successful bundle, and that bundle is not
519
- // the built-in bundle, set it as the bundle to use and reload.
520
- if toLastSuccessful && !fallback.isBuiltin() {
521
- print("\(CapacitorUpdater.TAG) Resetting to: \(fallback.toString())")
522
- return self.implementation.set(bundle: fallback) && self._reload()
523
- }
524
-
525
- print("\(CapacitorUpdater.TAG) Resetting to builtin version")
526
-
527
- // Otherwise, reset back to the built-in bundle and reload.
528
- self.implementation.reset()
529
- return self._reload()
530
- }
531
-
532
- return false
533
- }
534
-
535
- @objc func reset(_ call: CAPPluginCall) {
536
- let toLastSuccessful = call.getBool("toLastSuccessful") ?? false
537
- if self._reset(toLastSuccessful: toLastSuccessful) {
538
- call.resolve()
539
- } else {
540
- print("\(CapacitorUpdater.TAG) Reset failed")
541
- call.reject("\(CapacitorUpdater.TAG) Reset failed")
542
- }
543
- }
544
-
545
- @objc func current(_ call: CAPPluginCall) {
546
- let bundle: BundleInfo = self.implementation.getCurrentBundle()
547
- call.resolve([
548
- "bundle": bundle.toJSON(),
549
- "native": self.currentVersionNative.description
550
- ])
551
- }
552
-
553
- @objc func notifyAppReady(_ call: CAPPluginCall) {
554
- self.semaphoreDown()
555
- let bundle = self.implementation.getCurrentBundle()
556
- self.implementation.setSuccess(bundle: bundle, autoDeletePrevious: self.autoDeletePrevious)
557
- print("\(CapacitorUpdater.TAG) Current bundle loaded successfully. ['notifyAppReady()' was called] \(bundle.toString())")
558
- call.resolve(["bundle": bundle.toJSON()])
559
- }
560
-
561
- @objc func setMultiDelay(_ call: CAPPluginCall) {
562
- guard let delayConditionList = call.getValue("delayConditions") else {
563
- print("\(CapacitorUpdater.TAG) setMultiDelay called without delayCondition")
564
- call.reject("setMultiDelay called without delayCondition")
565
- return
566
- }
567
- let delayConditions: String = toJson(object: delayConditionList)
568
- if _setMultiDelay(delayConditions: delayConditions) {
569
- call.resolve()
570
- } else {
571
- call.reject("Failed to delay update")
572
- }
573
- }
574
-
575
- private func _setMultiDelay(delayConditions: String?) -> Bool {
576
- if delayConditions != nil && "" != delayConditions {
577
- UserDefaults.standard.set(delayConditions, forKey: DELAY_CONDITION_PREFERENCES)
578
- UserDefaults.standard.synchronize()
579
- print("\(CapacitorUpdater.TAG) Delay update saved.")
580
- return true
581
- } else {
582
- print("\(CapacitorUpdater.TAG) Failed to delay update, [Error calling '_setMultiDelay()']")
583
- return false
584
- }
585
- }
586
-
587
- private func _cancelDelay(source: String) {
588
- print("\(CapacitorUpdater.TAG) delay Canceled from \(source)")
589
- UserDefaults.standard.removeObject(forKey: DELAY_CONDITION_PREFERENCES)
590
- UserDefaults.standard.synchronize()
591
- }
592
-
593
- @objc func cancelDelay(_ call: CAPPluginCall) {
594
- self._cancelDelay(source: "JS")
595
- call.resolve()
596
- }
597
-
598
- private func _checkCancelDelay(killed: Bool) {
599
- let delayUpdatePreferences = UserDefaults.standard.string(forKey: DELAY_CONDITION_PREFERENCES) ?? "[]"
600
- let delayConditionList: [DelayCondition] = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
601
- let kind: String = obj.value(forKey: "kind") as! String
602
- let value: String? = obj.value(forKey: "value") as? String
603
- return DelayCondition(kind: kind, value: value)
604
- }
605
- for condition in delayConditionList {
606
- let kind: String? = condition.getKind()
607
- let value: String? = condition.getValue()
608
- if kind != nil {
609
- switch kind {
610
- case "background":
611
- if !killed {
612
- self._cancelDelay(source: "background check")
613
- }
614
- case "kill":
615
- if killed {
616
- self._cancelDelay(source: "kill check")
617
- // instant install for kill action
618
- self.installNext()
619
- }
620
- case "date":
621
- if value != nil && value != "" {
622
- let dateFormatter = ISO8601DateFormatter()
623
- dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
624
- guard let ExpireDate = dateFormatter.date(from: value!) else {
625
- self._cancelDelay(source: "date parsing issue")
626
- return
627
- }
628
- if ExpireDate < Date() {
629
- self._cancelDelay(source: "date expired")
630
- }
631
- } else {
632
- self._cancelDelay(source: "delayVal absent")
633
- }
634
- case "nativeVersion":
635
- if value != nil && value != "" {
636
- do {
637
- let versionLimit = try Version(value!)
638
- if self.currentVersionNative >= versionLimit {
639
- self._cancelDelay(source: "nativeVersion above limit")
640
- }
641
- } catch {
642
- self._cancelDelay(source: "nativeVersion parsing issue")
643
- }
644
- } else {
645
- self._cancelDelay(source: "delayVal absent")
646
- }
647
- case .none:
648
- print("\(CapacitorUpdater.TAG) _checkCancelDelay switch case none error")
649
- case .some:
650
- print("\(CapacitorUpdater.TAG) _checkCancelDelay switch case some error")
651
- }
652
- }
653
- }
654
- // self.checkAppReady() why this here?
655
- }
656
-
657
- private func _isAutoUpdateEnabled() -> Bool {
658
- let instanceDescriptor = (self.bridge?.viewController as? CAPBridgeViewController)?.instanceDescriptor()
659
- if instanceDescriptor?.serverURL != nil {
660
- print("⚠️ \(CapacitorUpdater.TAG) AutoUpdate is automatic disabled when serverUrl is set.")
661
- }
662
- return self.autoUpdate && self.updateUrl != "" && instanceDescriptor?.serverURL == nil
663
- }
664
-
665
- @objc func isAutoUpdateEnabled(_ call: CAPPluginCall) {
666
- call.resolve([
667
- "enabled": self._isAutoUpdateEnabled()
668
- ])
669
- }
670
-
671
- @objc func isAutoUpdateAvailable(_ call: CAPPluginCall) {
672
- let instanceDescriptor = (self.bridge?.viewController as? CAPBridgeViewController)?.instanceDescriptor()
673
- let isAvailable = instanceDescriptor?.serverURL == nil
674
- call.resolve([
675
- "available": isAvailable
676
- ])
677
- }
678
-
679
- func checkAppReady() {
680
- self.appReadyCheck?.cancel()
681
- self.appReadyCheck = DispatchWorkItem(block: {
682
- self.DeferredNotifyAppReadyCheck()
683
- })
684
- print("\(CapacitorUpdater.TAG) Wait for \(self.appReadyTimeout) ms, then check for notifyAppReady")
685
- DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(self.appReadyTimeout), execute: self.appReadyCheck!)
686
- }
687
-
688
- func checkRevert() {
689
- // Automatically roll back to fallback version if notifyAppReady has not been called yet
690
- let current: BundleInfo = self.implementation.getCurrentBundle()
691
- if current.isBuiltin() {
692
- print("\(CapacitorUpdater.TAG) Built-in bundle is active. We skip the check for notifyAppReady.")
693
- return
694
- }
695
-
696
- print("\(CapacitorUpdater.TAG) Current bundle is: \(current.toString())")
697
-
698
- if BundleStatus.SUCCESS.localizedString != current.getStatus() {
699
- print("\(CapacitorUpdater.TAG) notifyAppReady was not called, roll back current bundle: \(current.toString())")
700
- print("\(CapacitorUpdater.TAG) Did you forget to call 'notifyAppReady()' in your Capacitor App code?")
701
- self.notifyListeners("updateFailed", data: [
702
- "bundle": current.toJSON()
703
- ])
704
- self.implementation.sendStats(action: "update_fail", versionName: current.getVersionName())
705
- self.implementation.setError(bundle: current)
706
- _ = self._reset(toLastSuccessful: true)
707
- if self.autoDeleteFailed && !current.isBuiltin() {
708
- print("\(CapacitorUpdater.TAG) Deleting failing bundle: \(current.toString())")
709
- let res = self.implementation.delete(id: current.getId(), removeInfo: false)
710
- if !res {
711
- print("\(CapacitorUpdater.TAG) Delete version deleted: \(current.toString())")
712
- } else {
713
- print("\(CapacitorUpdater.TAG) Failed to delete failed bundle: \(current.toString())")
714
- }
715
- }
716
- } else {
717
- print("\(CapacitorUpdater.TAG) notifyAppReady was called. This is fine: \(current.toString())")
718
- }
719
- }
720
-
721
- func DeferredNotifyAppReadyCheck() {
722
- self.checkRevert()
723
- self.appReadyCheck = nil
724
- }
725
-
726
- func endBackGroundTask() {
727
- UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
728
- self.backgroundTaskID = UIBackgroundTaskIdentifier.invalid
729
- }
730
-
731
- func sendReadyToJs(current: BundleInfo, msg: String) {
732
- print("\(CapacitorUpdater.TAG) sendReadyToJs")
733
- DispatchQueue.global().async {
734
- self.semaphoreWait(waitTime: self.appReadyTimeout)
735
- self.notifyListeners("appReady", data: ["bundle": current.toJSON(), "status": msg])
736
- }
737
- }
738
-
739
- func endBackGroundTaskWithNotif(
740
- msg: String,
741
- latestVersionName: String,
742
- current: BundleInfo,
743
- error: Bool = true,
744
- failureAction: String = "download_fail",
745
- failureEvent: String = "downloadFailed"
746
- ) {
747
- if error {
748
- self.implementation.sendStats(action: failureAction, versionName: current.getVersionName())
749
- self.notifyListeners(failureEvent, data: ["version": latestVersionName])
750
- }
751
- self.notifyListeners("noNeedUpdate", data: ["bundle": current.toJSON()])
752
- self.sendReadyToJs(current: current, msg: msg)
753
- print("\(CapacitorUpdater.TAG) endBackGroundTaskWithNotif \(msg) current: \(current.getVersionName()) latestVersionName: \(latestVersionName)")
754
- self.endBackGroundTask()
755
- }
756
-
757
- func backgroundDownload() {
758
- let messageUpdate = self.directUpdate ? "Update will occur now." : "Update will occur next time app moves to background."
759
- guard let url = URL(string: self.updateUrl) else {
760
- print("\(CapacitorUpdater.TAG) Error no url or wrong format")
761
- return
762
- }
763
- DispatchQueue.global(qos: .background).async {
764
- self.backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Finish Download Tasks") {
765
- // End the task if time expires.
766
- self.endBackGroundTask()
767
- }
768
- print("\(CapacitorUpdater.TAG) Check for update via \(self.updateUrl)")
769
- let res = self.implementation.getLatest(url: url, channel: nil)
770
- let current = self.implementation.getCurrentBundle()
771
-
772
- if let backendError = res.error, !backendError.isEmpty {
773
- print("\(CapacitorUpdater.TAG) getLatest failed with error: \(backendError)")
774
- let latestVersionName = res.version.isEmpty ? current.getVersionName() : res.version
775
- if backendError == "response_error" {
776
- self.endBackGroundTaskWithNotif(
777
- msg: "Network error: \(backendError)",
778
- latestVersionName: latestVersionName,
779
- current: current,
780
- error: true
781
- )
782
- } else {
783
- self.endBackGroundTaskWithNotif(
784
- msg: backendError,
785
- latestVersionName: latestVersionName,
786
- current: current,
787
- error: true,
788
- failureAction: "backend_refusal",
789
- failureEvent: "backendRefused"
790
- )
791
- }
792
- return
793
- }
794
-
795
- if let message = res.message, !message.isEmpty {
796
- print("\(CapacitorUpdater.TAG) API message: \(message)")
797
- if res.major == true {
798
- self.notifyListeners("majorAvailable", data: ["version": res.version])
799
- }
800
- let latestVersionName = res.version.isEmpty ? current.getVersionName() : res.version
801
- self.endBackGroundTaskWithNotif(
802
- msg: message,
803
- latestVersionName: latestVersionName,
804
- current: current,
805
- error: true,
806
- failureAction: "backend_refusal",
807
- failureEvent: "backendRefused"
808
- )
809
- return
810
- }
811
- if res.version == "builtin" {
812
- print("\(CapacitorUpdater.TAG) Latest version is builtin")
813
- if self.directUpdate {
814
- print("\(CapacitorUpdater.TAG) Direct update to builtin version")
815
- _ = self._reset(toLastSuccessful: false)
816
- self.endBackGroundTaskWithNotif(msg: "Updated to builtin version", latestVersionName: res.version, current: self.implementation.getCurrentBundle(), error: false)
817
- } else {
818
- print("\(CapacitorUpdater.TAG) Setting next bundle to builtin")
819
- _ = self.implementation.setNextBundle(next: BundleInfo.ID_BUILTIN)
820
- self.endBackGroundTaskWithNotif(msg: "Next update will be to builtin version", latestVersionName: res.version, current: current, error: false)
821
- }
822
- return
823
- }
824
- let sessionKey = res.sessionKey ?? ""
825
- guard let downloadUrl = URL(string: res.url) else {
826
- print("\(CapacitorUpdater.TAG) Error no url or wrong format")
827
- self.endBackGroundTaskWithNotif(msg: "Error no url or wrong format", latestVersionName: res.version, current: current)
828
- return
829
- }
830
- let latestVersionName = res.version
831
- if latestVersionName != "" && current.getVersionName() != latestVersionName {
832
- do {
833
- print("\(CapacitorUpdater.TAG) New bundle: \(latestVersionName) found. Current is: \(current.getVersionName()). \(messageUpdate)")
834
- var nextImpl = self.implementation.getBundleInfoByVersionName(version: latestVersionName)
835
- if nextImpl == nil || nextImpl?.isDeleted() == true {
836
- if nextImpl?.isDeleted() == true {
837
- print("\(CapacitorUpdater.TAG) Latest bundle already exists and will be deleted, download will overwrite it.")
838
- let res = self.implementation.delete(id: nextImpl!.getId(), removeInfo: true)
839
- if res {
840
- print("\(CapacitorUpdater.TAG) Failed bundle deleted: \(nextImpl!.toString())")
841
- } else {
842
- print("\(CapacitorUpdater.TAG) Failed to delete failed bundle: \(nextImpl!.toString())")
843
- }
844
- }
845
- if res.manifest != nil {
846
- nextImpl = try self.implementation.downloadManifest(manifest: res.manifest!, version: latestVersionName, sessionKey: sessionKey)
847
- } else {
848
- nextImpl = try self.implementation.download(url: downloadUrl, version: latestVersionName, sessionKey: sessionKey)
849
- }
850
- }
851
- guard let next = nextImpl else {
852
- print("\(CapacitorUpdater.TAG) Error downloading file")
853
- self.endBackGroundTaskWithNotif(msg: "Error downloading file", latestVersionName: latestVersionName, current: current)
854
- return
855
- }
856
- if next.isErrorStatus() {
857
- print("\(CapacitorUpdater.TAG) Latest bundle already exists and is in error state. Aborting update.")
858
- self.endBackGroundTaskWithNotif(msg: "Latest version is in error state. Aborting update.", latestVersionName: latestVersionName, current: current)
859
- return
860
- }
861
- if !self.implementation.hasOldPrivateKeyPropertyInConfig {
862
- do {
863
- res.checksum = try CryptoCipherV2.decryptChecksum(checksum: res.checksum, publicKey: self.implementation.publicKey, version: latestVersionName)
864
- } catch {
865
- self.implementation.sendStats(action: "decrypt_fail", versionName: latestVersionName)
866
- throw error
867
- }
868
- }
869
- if res.checksum != "" && next.getChecksum() != res.checksum && res.manifest == nil {
870
- print("\(CapacitorUpdater.TAG) Error checksum", next.getChecksum(), res.checksum)
871
- self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
872
- let id = next.getId()
873
- let resDel = self.implementation.delete(id: id)
874
- if !resDel {
875
- print("\(CapacitorUpdater.TAG) Delete failed, id \(id) doesn't exist")
876
- }
877
- self.endBackGroundTaskWithNotif(msg: "Error checksum", latestVersionName: latestVersionName, current: current)
878
- return
879
- }
880
- if self.directUpdate {
881
- _ = self.implementation.set(bundle: next)
882
- _ = self._reload()
883
- self.directUpdate = false
884
- self.endBackGroundTaskWithNotif(msg: "update installed", latestVersionName: latestVersionName, current: current, error: false)
885
- } else {
886
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
887
- _ = self.implementation.setNextBundle(next: next.getId())
888
- self.endBackGroundTaskWithNotif(msg: "update downloaded, will install next background", latestVersionName: latestVersionName, current: current, error: false)
889
- }
890
- return
891
- } catch {
892
- print("\(CapacitorUpdater.TAG) Error downloading file", error.localizedDescription)
893
- let current: BundleInfo = self.implementation.getCurrentBundle()
894
- self.endBackGroundTaskWithNotif(msg: "Error downloading file", latestVersionName: latestVersionName, current: current)
895
- return
896
- }
897
- } else {
898
- print("\(CapacitorUpdater.TAG) No need to update, \(current.getId()) is the latest bundle.")
899
- self.endBackGroundTaskWithNotif(msg: "No need to update, \(current.getId()) is the latest bundle.", latestVersionName: latestVersionName, current: current, error: false)
900
- return
901
- }
902
- }
903
- }
904
-
905
- private func installNext() {
906
- let delayUpdatePreferences = UserDefaults.standard.string(forKey: DELAY_CONDITION_PREFERENCES) ?? "[]"
907
- let delayConditionList: [DelayCondition]? = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
908
- let kind: String = obj.value(forKey: "kind") as! String
909
- let value: String? = obj.value(forKey: "value") as? String
910
- return DelayCondition(kind: kind, value: value)
911
- }
912
- if delayConditionList != nil && delayConditionList?.capacity != 0 {
913
- print("\(CapacitorUpdater.TAG) Update delayed until delay conditions met")
914
- return
915
- }
916
- let current: BundleInfo = self.implementation.getCurrentBundle()
917
- let next: BundleInfo? = self.implementation.getNextBundle()
918
-
919
- if next != nil && !next!.isErrorStatus() && next!.getVersionName() != current.getVersionName() {
920
- print("\(CapacitorUpdater.TAG) Next bundle is: \(next!.toString())")
921
- if self.implementation.set(bundle: next!) && self._reload() {
922
- print("\(CapacitorUpdater.TAG) Updated to bundle: \(next!.toString())")
923
- _ = self.implementation.setNextBundle(next: Optional<String>.none)
924
- } else {
925
- print("\(CapacitorUpdater.TAG) Update to bundle: \(next!.toString()) Failed!")
926
- }
927
- }
928
- }
929
-
930
- @objc private func toJson(object: Any) -> String {
931
- guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
932
- return ""
933
- }
934
- return String(data: data, encoding: String.Encoding.utf8) ?? ""
935
- }
936
-
937
- @objc private func fromJsonArr(json: String) -> [NSObject] {
938
- guard let jsonData = json.data(using: .utf8) else {
939
- return []
940
- }
941
- let object = try? JSONSerialization.jsonObject(
942
- with: jsonData,
943
- options: .mutableContainers
944
- ) as? [NSObject]
945
- return object ?? []
946
- }
947
-
948
- @objc func appMovedToForeground() {
949
- let current: BundleInfo = self.implementation.getCurrentBundle()
950
- self.implementation.sendStats(action: "app_moved_to_foreground", versionName: current.getVersionName())
951
- if backgroundWork != nil && taskRunning {
952
- backgroundWork!.cancel()
953
- print("\(CapacitorUpdater.TAG) Background Timer Task canceled, Activity resumed before timer completes")
954
- }
955
- if self._isAutoUpdateEnabled() {
956
- self.backgroundDownload()
957
- } else {
958
- print("\(CapacitorUpdater.TAG) Auto update is disabled")
959
- self.sendReadyToJs(current: current, msg: "disabled")
960
- }
961
- self.checkAppReady()
962
- }
963
-
964
- @objc func checkForUpdateAfterDelay() {
965
- if periodCheckDelay == 0 || !self._isAutoUpdateEnabled() {
966
- return
967
- }
968
- guard let url = URL(string: self.updateUrl) else {
969
- print("\(CapacitorUpdater.TAG) Error no url or wrong format")
970
- return
971
- }
972
- let timer = Timer.scheduledTimer(withTimeInterval: TimeInterval(periodCheckDelay), repeats: true) { _ in
973
- DispatchQueue.global(qos: .background).async {
974
- let res = self.implementation.getLatest(url: url, channel: nil)
975
- let current = self.implementation.getCurrentBundle()
976
-
977
- if res.version != current.getVersionName() {
978
- print("\(CapacitorUpdater.TAG) New version found: \(res.version)")
979
- self.backgroundDownload()
980
- }
981
- }
982
- }
983
- RunLoop.current.add(timer, forMode: .default)
984
- }
985
-
986
- @objc func appMovedToBackground() {
987
- self.implementation.sendStats(action: "app_moved_to_background")
988
- print("\(CapacitorUpdater.TAG) Check for pending update")
989
- let delayUpdatePreferences = UserDefaults.standard.string(forKey: DELAY_CONDITION_PREFERENCES) ?? "[]"
990
-
991
- let delayConditionList: [DelayCondition] = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
992
- let kind: String = obj.value(forKey: "kind") as! String
993
- let value: String? = obj.value(forKey: "value") as? String
994
- return DelayCondition(kind: kind, value: value)
995
- }
996
- var backgroundValue: String?
997
- for delayCondition in delayConditionList {
998
- if delayCondition.getKind() == "background" {
999
- let value: String? = delayCondition.getValue()
1000
- backgroundValue = (value != nil && value != "") ? value! : "0"
1001
- }
1002
- }
1003
- if backgroundValue != nil {
1004
- self.taskRunning = true
1005
- let interval: Double = (Double(backgroundValue!) ?? 0.0) / 1000
1006
- self.backgroundWork?.cancel()
1007
- self.backgroundWork = DispatchWorkItem(block: {
1008
- // IOS never executes this task in background
1009
- self.taskRunning = false
1010
- self._checkCancelDelay(killed: false)
1011
- self.installNext()
1012
- })
1013
- DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + interval, execute: self.backgroundWork!)
1014
- } else {
1015
- self._checkCancelDelay(killed: false)
1016
- self.installNext()
1017
- }
1018
-
1019
- }
1020
-
1021
- @objc func getNextBundle(_ call: CAPPluginCall) {
1022
- let bundle = self.implementation.getNextBundle()
1023
- if bundle == nil || bundle?.isUnknown() == true {
1024
- call.resolve()
1025
- return
1026
- }
1027
-
1028
- call.resolve(bundle!.toJSON())
1029
- }
1030
- }