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