@capgo/capacitor-updater 4.41.0 → 4.43.5

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 (67) hide show
  1. package/CapgoCapacitorUpdater.podspec +7 -5
  2. package/Package.swift +40 -0
  3. package/README.md +1913 -303
  4. package/android/build.gradle +41 -8
  5. package/android/proguard-rules.pro +45 -0
  6. package/android/src/main/AndroidManifest.xml +1 -3
  7. package/android/src/main/java/ee/forgr/capacitor_updater/AppLifecycleObserver.java +88 -0
  8. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +223 -195
  9. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +23 -23
  10. package/android/src/main/java/ee/forgr/capacitor_updater/Callback.java +13 -0
  11. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +2720 -1242
  12. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +1854 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +359 -121
  14. package/android/src/main/java/ee/forgr/capacitor_updater/DataManager.java +28 -0
  15. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +44 -49
  16. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +4 -4
  17. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUpdateUtils.java +296 -0
  18. package/android/src/main/java/ee/forgr/capacitor_updater/DeviceIdHelper.java +215 -0
  19. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +858 -117
  20. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +156 -0
  21. package/android/src/main/java/ee/forgr/capacitor_updater/InternalUtils.java +45 -0
  22. package/android/src/main/java/ee/forgr/capacitor_updater/Logger.java +360 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeDetector.java +72 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/ShakeMenu.java +603 -0
  25. package/dist/docs.json +3022 -765
  26. package/dist/esm/definitions.d.ts +1717 -198
  27. package/dist/esm/definitions.js +103 -1
  28. package/dist/esm/definitions.js.map +1 -1
  29. package/dist/esm/history.d.ts +1 -0
  30. package/dist/esm/history.js +283 -0
  31. package/dist/esm/history.js.map +1 -0
  32. package/dist/esm/index.d.ts +3 -2
  33. package/dist/esm/index.js +5 -4
  34. package/dist/esm/index.js.map +1 -1
  35. package/dist/esm/web.d.ts +43 -42
  36. package/dist/esm/web.js +122 -37
  37. package/dist/esm/web.js.map +1 -1
  38. package/dist/plugin.cjs.js +512 -37
  39. package/dist/plugin.cjs.js.map +1 -1
  40. package/dist/plugin.js +512 -37
  41. package/dist/plugin.js.map +1 -1
  42. package/ios/Sources/CapacitorUpdaterPlugin/AES.swift +87 -0
  43. package/ios/Sources/CapacitorUpdaterPlugin/BigInt.swift +55 -0
  44. package/ios/Sources/CapacitorUpdaterPlugin/BundleInfo.swift +177 -0
  45. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/BundleStatus.swift +12 -12
  46. package/ios/Sources/CapacitorUpdaterPlugin/CapacitorUpdaterPlugin.swift +2020 -0
  47. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +1959 -0
  48. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +313 -0
  49. package/ios/Sources/CapacitorUpdaterPlugin/DelayUpdateUtils.swift +257 -0
  50. package/ios/Sources/CapacitorUpdaterPlugin/DeviceIdHelper.swift +120 -0
  51. package/ios/Sources/CapacitorUpdaterPlugin/InternalUtils.swift +392 -0
  52. package/ios/Sources/CapacitorUpdaterPlugin/Logger.swift +310 -0
  53. package/ios/Sources/CapacitorUpdaterPlugin/RSA.swift +274 -0
  54. package/ios/Sources/CapacitorUpdaterPlugin/ShakeMenu.swift +441 -0
  55. package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/UserDefaultsExtension.swift +1 -2
  56. package/package.json +49 -41
  57. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +0 -1131
  58. package/ios/Plugin/BundleInfo.swift +0 -113
  59. package/ios/Plugin/CapacitorUpdater.swift +0 -850
  60. package/ios/Plugin/CapacitorUpdaterPlugin.h +0 -10
  61. package/ios/Plugin/CapacitorUpdaterPlugin.m +0 -27
  62. package/ios/Plugin/CapacitorUpdaterPlugin.swift +0 -678
  63. package/ios/Plugin/CryptoCipher.swift +0 -240
  64. /package/{LICENCE → LICENSE} +0 -0
  65. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayCondition.swift +0 -0
  66. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/DelayUntilNext.swift +0 -0
  67. /package/ios/{Plugin → Sources/CapacitorUpdaterPlugin}/Info.plist +0 -0
@@ -1,678 +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 {
17
- private var implementation = CapacitorUpdater()
18
- private let PLUGIN_VERSION: String = "4.41.0"
19
- static let updateUrlDefault = "https://api.capgo.app/updates"
20
- static let statsUrlDefault = "https://api.capgo.app/stats"
21
- static let channelUrlDefault = "https://api.capgo.app/channel_self"
22
- let DELAY_CONDITION_PREFERENCES = ""
23
- private var updateUrl = ""
24
- private var statsUrl = ""
25
- private var defaultPrivateKey = "-----BEGIN RSA PRIVATE KEY-----\nMIIEpQIBAAKCAQEA4pW9olT0FBXXivRCzd3xcImlWZrqkwcF2xTkX/FwXmj9eh9H\nkBLrsQmfsC+PJisRXIOGq6a0z3bsGq6jBpp3/Jr9jiaW5VuPGaKeMaZZBRvi/N5f\nIMG3hZXSOcy0IYg+E1Q7RkYO1xq5GLHseqG+PXvJsNe4R8R/Bmd/ngq0xh/cvcrH\nHpXwO0Aj9tfprlb+rHaVV79EkVRWYPidOLnK1n0EFHFJ1d/MyDIp10TEGm2xHpf/\nBrlb1an8wXEuzoC0DgYaczgTjovwR+ewSGhSHJliQdM0Qa3o1iN87DldWtydImMs\nPjJ3DUwpsjAMRe5X8Et4+udFW2ciYnQo9H0CkwIDAQABAoIBAQCtjlMV/4qBxAU4\nu0ZcWA9yywwraX0aJ3v1xrfzQYV322Wk4Ea5dbSxA5UcqCE29DA1M824t1Wxv/6z\npWbcTP9xLuresnJMtmgTE7umfiubvTONy2sENT20hgDkIwcq1CfwOEm61zjQzPhQ\nkSB5AmEsyR/BZEsUNc+ygR6AWOUFB7tj4yMc32LOTWSbE/znnF2BkmlmnQykomG1\n2oVqM3lUFP7+m8ux1O7scO6IMts+Z/eFXjWfxpbebUSvSIR83GXPQZ34S/c0ehOg\nyHdmCSOel1r3VvInMe+30j54Jr+Ml/7Ee6axiwyE2e/bd85MsK9sVdp0OtelXaqA\nOZZqWvN5AoGBAP2Hn3lSq+a8GsDH726mHJw60xM0LPbVJTYbXsmQkg1tl3NKJTMM\nQqz41+5uys+phEgLHI9gVJ0r+HaGHXnJ4zewlFjsudstb/0nfctUvTqnhEhfNo9I\ny4kufVKPRF3sMEeo7CDVJs4GNBLycEyIBy6Mbv0VcO7VaZqggRwu4no9AoGBAOTK\n6NWYs1BWlkua2wmxexGOzehNGedInp0wGr2l4FDayWjkZLqvB+nNXUQ63NdHlSs4\nWB2Z1kQXZxVaI2tPYexGUKXEo2uFob63uflbuE029ovDXIIPFTPtGNdNXwhHT5a+\nPhmy3sMc+s2BSNM5qaNmfxQxhdd6gRU6oikE+c0PAoGAMn3cKNFqIt27hkFLUgIL\nGKIuf1iYy9/PNWNmEUaVj88PpopRtkTu0nwMpROzmH/uNFriKTvKHjMvnItBO4wV\nkHW+VadvrFL0Rrqituf9d7z8/1zXBNo+juePVe3qc7oiM2NVA4Tv4YAixtM5wkQl\nCgQ15nlqsGYYTg9BJ1e/CxECgYEAjEYPzO2reuUrjr0p8F59ev1YJ0YmTJRMk0ks\nC/yIdGo/tGzbiU3JB0LfHPcN8Xu07GPGOpfYM7U5gXDbaG6qNgfCaHAQVdr/mQPi\nJQ1kCQtay8QCkscWk9iZM1//lP7LwDtxraXqSCwbZSYP9VlUNZeg8EuQqNU2EUL6\nqzWexmcCgYEA0prUGNBacraTYEknB1CsbP36UPWsqFWOvevlz+uEC5JPxPuW5ZHh\nSQN7xl6+PHyjPBM7ttwPKyhgLOVTb3K7ex/PXnudojMUK5fh7vYfChVTSlx2p6r0\nDi58PdD+node08cJH+ie0Yphp7m+D4+R9XD0v0nEvnu4BtAW6DrJasw=\n-----END RSA PRIVATE KEY-----\n"
26
- private var backgroundTaskID: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier.invalid
27
- private var currentVersionNative: Version = "0.0.0"
28
- private var autoUpdate = false
29
- private var appReadyTimeout = 10000
30
- private var appReadyCheck: DispatchWorkItem?
31
- private var resetWhenUpdate = true
32
- private var autoDeleteFailed = false
33
- private var autoDeletePrevious = false
34
- private var backgroundWork: DispatchWorkItem?
35
- private var taskRunning = false
36
-
37
- override public func load() {
38
- print("\(self.implementation.TAG) init for device \(self.implementation.deviceID)")
39
- do {
40
- currentVersionNative = try Version(getConfig().getString("version", Bundle.main.versionName ?? "0.0.0")!)
41
- } catch {
42
- print("\(self.implementation.TAG) Cannot get version native \(currentVersionNative)")
43
- }
44
- autoDeleteFailed = getConfig().getBoolean("autoDeleteFailed", true)
45
- autoDeletePrevious = getConfig().getBoolean("autoDeletePrevious", true)
46
- updateUrl = getConfig().getString("updateUrl", CapacitorUpdaterPlugin.updateUrlDefault)!
47
- autoUpdate = getConfig().getBoolean("autoUpdate", true)
48
- appReadyTimeout = getConfig().getInt("appReadyTimeout", 10000)
49
- resetWhenUpdate = getConfig().getBoolean("resetWhenUpdate", true)
50
-
51
- implementation.privateKey = getConfig().getString("privateKey", self.defaultPrivateKey)!
52
- implementation.notifyDownload = notifyDownload
53
- implementation.PLUGIN_VERSION = self.PLUGIN_VERSION
54
- let config = (self.bridge?.viewController as? CAPBridgeViewController)?.instanceDescriptor().legacyConfig
55
- if config?["appId"] != nil {
56
- implementation.appId = config?["appId"] as! String
57
- }
58
- implementation.statsUrl = getConfig().getString("statsUrl", CapacitorUpdaterPlugin.statsUrlDefault)!
59
- implementation.channelUrl = getConfig().getString("channelUrl", CapacitorUpdaterPlugin.channelUrlDefault)!
60
- if resetWhenUpdate {
61
- self.cleanupObsoleteVersions()
62
- }
63
- let nc = NotificationCenter.default
64
- nc.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
65
- nc.addObserver(self, selector: #selector(appMovedToForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
66
- nc.addObserver(self, selector: #selector(appKilled), name: UIApplication.willTerminateNotification, object: nil)
67
- self.appMovedToForeground()
68
- }
69
-
70
- private func cleanupObsoleteVersions() {
71
- var LatestVersionNative: Version = "0.0.0"
72
- do {
73
- LatestVersionNative = try Version(UserDefaults.standard.string(forKey: "LatestVersionNative") ?? "0.0.0")
74
- } catch {
75
- print("\(self.implementation.TAG) Cannot get version native \(currentVersionNative)")
76
- }
77
- if LatestVersionNative != "0.0.0" && currentVersionNative.major > LatestVersionNative.major {
78
- _ = self._reset(toLastSuccessful: false)
79
- let res = implementation.list()
80
- res.forEach { version in
81
- print("\(self.implementation.TAG) Deleting obsolete bundle: \(version)")
82
- let res = implementation.delete(id: version.getId())
83
- if !res {
84
- print("\(self.implementation.TAG) Delete failed, id \(version.getId()) doesn't exist")
85
- }
86
- }
87
- }
88
- UserDefaults.standard.set( self.currentVersionNative.description, forKey: "LatestVersionNative")
89
- UserDefaults.standard.synchronize()
90
- }
91
-
92
- @objc func notifyDownload(id: String, percent: Int) {
93
- let bundle = self.implementation.getBundleInfo(id: id)
94
- self.notifyListeners("download", data: ["percent": percent, "bundle": bundle.toJSON()])
95
- if percent == 100 {
96
- self.notifyListeners("downloadComplete", data: ["bundle": bundle.toJSON()])
97
- self.implementation.sendStats(action: "download_complete", versionName: bundle.getVersionName())
98
- } else if percent.isMultiple(of: 10) {
99
- self.implementation.sendStats(action: "download_\(percent)", versionName: bundle.getVersionName())
100
- }
101
- }
102
-
103
- @objc func getDeviceId(_ call: CAPPluginCall) {
104
- call.resolve(["deviceId": implementation.deviceID])
105
- }
106
-
107
- @objc func getPluginVersion(_ call: CAPPluginCall) {
108
- call.resolve(["version": self.PLUGIN_VERSION])
109
- }
110
-
111
- @objc func download(_ call: CAPPluginCall) {
112
- guard let urlString = call.getString("url") else {
113
- print("\(self.implementation.TAG) Download called without url")
114
- call.reject("Download called without url")
115
- return
116
- }
117
- guard let version = call.getString("version") else {
118
- print("\(self.implementation.TAG) Download called without version")
119
- call.reject("Download called without version")
120
- return
121
- }
122
- let sessionKey = call.getString("sessionKey", "")
123
- let checksum = call.getString("checksum", "")
124
- let url = URL(string: urlString)
125
- print("\(self.implementation.TAG) Downloading \(String(describing: url))")
126
- DispatchQueue.global(qos: .background).async {
127
- do {
128
- let next = try self.implementation.download(url: url!, version: version, sessionKey: sessionKey)
129
- if checksum != "" && next.getChecksum() != checksum {
130
- print("\(self.implementation.TAG) Error checksum", next.getChecksum(), checksum)
131
- self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
132
- let resDel = self.implementation.delete(id: next.getId())
133
- if !resDel {
134
- print("\(self.implementation.TAG) Delete failed, id \(next.getId()) doesn't exist")
135
- }
136
- return
137
- }
138
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
139
- call.resolve(next.toJSON())
140
- } catch {
141
- print("\(self.implementation.TAG) Failed to download from: \(String(describing: url)) \(error.localizedDescription)")
142
- self.notifyListeners("downloadFailed", data: ["version": version])
143
- let current: BundleInfo = self.implementation.getCurrentBundle()
144
- self.implementation.sendStats(action: "download_fail", versionName: current.getVersionName())
145
- call.reject("Failed to download from: \(url!)", error.localizedDescription)
146
- }
147
- }
148
- }
149
-
150
- private func _reload() -> Bool {
151
- guard let bridge = self.bridge else { return false }
152
- let id = self.implementation.getCurrentBundleId()
153
- let destHot = self.implementation.getPathHot(id: id)
154
- print("\(self.implementation.TAG) Reloading \(id)")
155
- if let vc = bridge.viewController as? CAPBridgeViewController {
156
- vc.setServerBasePath(path: destHot.path)
157
- self.checkAppReady()
158
- self.notifyListeners("appReloaded", data: [:])
159
- return true
160
- }
161
- return false
162
- }
163
-
164
- @objc func reload(_ call: CAPPluginCall) {
165
- if self._reload() {
166
- call.resolve()
167
- } else {
168
- print("\(self.implementation.TAG) Reload failed")
169
- call.reject("Reload failed")
170
- }
171
- }
172
-
173
- @objc func next(_ call: CAPPluginCall) {
174
- guard let id = call.getString("id") else {
175
- print("\(self.implementation.TAG) Next called without id")
176
- call.reject("Next called without id")
177
- return
178
- }
179
- print("\(self.implementation.TAG) Setting next active id \(id)")
180
- if !self.implementation.setNextBundle(next: id) {
181
- print("\(self.implementation.TAG) Set next version failed. id \(id) does not exist.")
182
- call.reject("Set next version failed. id \(id) does not exist.")
183
- } else {
184
- call.resolve(self.implementation.getBundleInfo(id: id).toJSON())
185
- }
186
- }
187
-
188
- @objc func set(_ call: CAPPluginCall) {
189
- guard let id = call.getString("id") else {
190
- print("\(self.implementation.TAG) Set called without id")
191
- call.reject("Set called without id")
192
- return
193
- }
194
- let res = implementation.set(id: id)
195
- print("\(self.implementation.TAG) Set active bundle: \(id)")
196
- if !res {
197
- print("\(self.implementation.TAG) Bundle successfully set to: \(id) ")
198
- call.reject("Update failed, id \(id) doesn't exist")
199
- } else {
200
- self.reload(call)
201
- }
202
- }
203
-
204
- @objc func delete(_ call: CAPPluginCall) {
205
- guard let id = call.getString("id") else {
206
- print("\(self.implementation.TAG) Delete called without version")
207
- call.reject("Delete called without id")
208
- return
209
- }
210
- let res = implementation.delete(id: id)
211
- if res {
212
- call.resolve()
213
- } else {
214
- print("\(self.implementation.TAG) Delete failed, id \(id) doesn't exist")
215
- call.reject("Delete failed, id \(id) doesn't exist")
216
- }
217
- }
218
-
219
- @objc func list(_ call: CAPPluginCall) {
220
- let res = implementation.list()
221
- var resArr: [[String: String]] = []
222
- for v in res {
223
- resArr.append(v.toJSON())
224
- }
225
- call.resolve([
226
- "bundles": resArr
227
- ])
228
- }
229
-
230
- @objc func getLatest(_ call: CAPPluginCall) {
231
- DispatchQueue.global(qos: .background).async {
232
- let res = self.implementation.getLatest(url: URL(string: self.updateUrl)!)
233
- if res.error != nil {
234
- call.reject( res.error!)
235
- } else {
236
- call.resolve(res.toDict())
237
- }
238
- }
239
- }
240
-
241
- @objc func setChannel(_ call: CAPPluginCall) {
242
- guard let channel = call.getString("channel") else {
243
- print("\(self.implementation.TAG) setChannel called without channel")
244
- call.reject("setChannel called without channel")
245
- return
246
- }
247
- DispatchQueue.global(qos: .background).async {
248
- let res = self.implementation.setChannel(channel: channel)
249
- if res.error != "" {
250
- call.reject(res.error)
251
- } else {
252
- call.resolve(res.toDict())
253
- }
254
- }
255
- }
256
-
257
- @objc func getChannel(_ call: CAPPluginCall) {
258
- DispatchQueue.global(qos: .background).async {
259
- let res = self.implementation.getChannel()
260
- if res.error != "" {
261
- call.reject(res.error)
262
- } else {
263
- call.resolve(res.toDict())
264
- }
265
- }
266
- }
267
- @objc func setCustomId(_ call: CAPPluginCall) {
268
- guard let customId = call.getString("customId") else {
269
- print("\(self.implementation.TAG) setCustomId called without customId")
270
- call.reject("setCustomId called without customId")
271
- return
272
- }
273
- self.implementation.customId = customId
274
- }
275
-
276
- @objc func _reset(toLastSuccessful: Bool) -> Bool {
277
- guard let bridge = self.bridge else { return false }
278
-
279
- if (bridge.viewController as? CAPBridgeViewController) != nil {
280
- let fallback: BundleInfo = self.implementation.getFallbackBundle()
281
-
282
- // If developer wants to reset to the last successful bundle, and that bundle is not
283
- // the built-in bundle, set it as the bundle to use and reload.
284
- if toLastSuccessful && !fallback.isBuiltin() {
285
- print("\(self.implementation.TAG) Resetting to: \(fallback.toString())")
286
- return self.implementation.set(bundle: fallback) && self._reload()
287
- }
288
-
289
- print("\(self.implementation.TAG) Resetting to builtin version")
290
-
291
- // Otherwise, reset back to the built-in bundle and reload.
292
- self.implementation.reset()
293
- return self._reload()
294
- }
295
-
296
- return false
297
- }
298
-
299
- @objc func reset(_ call: CAPPluginCall) {
300
- let toLastSuccessful = call.getBool("toLastSuccessful") ?? false
301
- if self._reset(toLastSuccessful: toLastSuccessful) {
302
- call.resolve()
303
- } else {
304
- print("\(self.implementation.TAG) Reset failed")
305
- call.reject("\(self.implementation.TAG) Reset failed")
306
- }
307
- }
308
-
309
- @objc func current(_ call: CAPPluginCall) {
310
- let bundle: BundleInfo = self.implementation.getCurrentBundle()
311
- call.resolve([
312
- "bundle": bundle.toJSON(),
313
- "native": self.currentVersionNative.description
314
- ])
315
- }
316
-
317
- @objc func notifyAppReady(_ call: CAPPluginCall) {
318
- let version = self.implementation.getCurrentBundle()
319
- self.implementation.setSuccess(bundle: version, autoDeletePrevious: self.autoDeletePrevious)
320
- print("\(self.implementation.TAG) Current bundle loaded successfully. ['notifyAppReady()' was called] \(version.toString())")
321
- call.resolve()
322
- }
323
-
324
- @objc func setMultiDelay(_ call: CAPPluginCall) {
325
- guard let delayConditionList = call.getValue("delayConditions") else {
326
- print("\(self.implementation.TAG) setMultiDelay called without delayCondition")
327
- call.reject("setMultiDelay called without delayCondition")
328
- return
329
- }
330
- let delayConditions: String = toJson(object: delayConditionList)
331
- if _setMultiDelay(delayConditions: delayConditions) {
332
- call.resolve()
333
- } else {
334
- call.reject("Failed to delay update")
335
- }
336
- }
337
-
338
- @available(*, deprecated, message: "use SetMultiDelay instead")
339
- @objc func setDelay(_ call: CAPPluginCall) {
340
- let kind: String = call.getString("kind", "")
341
- let value: String? = call.getString("value", "")
342
- let delayConditions: String = "[{\"kind\":\"\(kind)\", \"value\":\"\(value ?? "")\"}]"
343
- if _setMultiDelay(delayConditions: delayConditions) {
344
- call.resolve()
345
- } else {
346
- call.reject("Failed to delay update")
347
- }
348
- }
349
-
350
- private func _setMultiDelay(delayConditions: String?) -> Bool {
351
- if delayConditions != nil && "" != delayConditions {
352
- UserDefaults.standard.set(delayConditions, forKey: DELAY_CONDITION_PREFERENCES)
353
- UserDefaults.standard.synchronize()
354
- print("\(self.implementation.TAG) Delay update saved.")
355
- return true
356
- } else {
357
- print("\(self.implementation.TAG) Failed to delay update, [Error calling '_setMultiDelay()']")
358
- return false
359
- }
360
- }
361
-
362
- private func _cancelDelay(source: String) {
363
- print("\(self.implementation.TAG) delay Canceled from \(source)")
364
- UserDefaults.standard.removeObject(forKey: DELAY_CONDITION_PREFERENCES)
365
- UserDefaults.standard.synchronize()
366
- }
367
-
368
- @objc func cancelDelay(_ call: CAPPluginCall) {
369
- self._cancelDelay(source: "JS")
370
- call.resolve()
371
- }
372
-
373
- private func _checkCancelDelay(killed: Bool) {
374
- let delayUpdatePreferences = UserDefaults.standard.string(forKey: DELAY_CONDITION_PREFERENCES) ?? "[]"
375
- let delayConditionList: [DelayCondition] = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
376
- let kind: String = obj.value(forKey: "kind") as! String
377
- let value: String? = obj.value(forKey: "value") as? String
378
- return DelayCondition(kind: kind, value: value)
379
- }
380
- for condition in delayConditionList {
381
- let kind: String? = condition.getKind()
382
- let value: String? = condition.getValue()
383
- if kind != nil {
384
- switch kind {
385
- case "background":
386
- if !killed {
387
- self._cancelDelay(source: "background check")
388
- }
389
- break
390
- case "kill":
391
- if killed {
392
- self._cancelDelay(source: "kill check")
393
- // instant install for kill action
394
- self.installNext()
395
- }
396
- break
397
- case "date":
398
- if value != nil && value != "" {
399
- let dateFormatter = ISO8601DateFormatter()
400
- dateFormatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
401
- guard let ExpireDate = dateFormatter.date(from: value!) else {
402
- self._cancelDelay(source: "date parsing issue")
403
- return
404
- }
405
- if ExpireDate < Date() {
406
- self._cancelDelay(source: "date expired")
407
- }
408
- } else {
409
- self._cancelDelay(source: "delayVal absent")
410
- }
411
- break
412
- case "nativeVersion":
413
- if value != nil && value != "" {
414
- do {
415
- let versionLimit = try Version(value!)
416
- if self.currentVersionNative >= versionLimit {
417
- self._cancelDelay(source: "nativeVersion above limit")
418
- }
419
- } catch {
420
- self._cancelDelay(source: "nativeVersion parsing issue")
421
- }
422
- } else {
423
- self._cancelDelay(source: "delayVal absent")
424
- }
425
- break
426
- case .none:
427
- print("\(self.implementation.TAG) _checkCancelDelay switch case none error")
428
- case .some:
429
- print("\(self.implementation.TAG) _checkCancelDelay switch case some error")
430
- }
431
- }
432
- }
433
- // self.checkAppReady() why this here?
434
- }
435
-
436
- private func _isAutoUpdateEnabled() -> Bool {
437
- let instanceDescriptor = (self.bridge?.viewController as? CAPBridgeViewController)?.instanceDescriptor()
438
- if instanceDescriptor?.serverURL != nil {
439
- print("⚠️ \(self.implementation.TAG) AutoUpdate is automatic disabled when serverUrl is set.")
440
- }
441
- return self.autoUpdate && self.updateUrl != "" && instanceDescriptor?.serverURL == nil
442
- }
443
-
444
- @objc func isAutoUpdateEnabled(_ call: CAPPluginCall) {
445
- call.resolve([
446
- "enabled": self._isAutoUpdateEnabled()
447
- ])
448
- }
449
-
450
- func checkAppReady() {
451
- self.appReadyCheck?.cancel()
452
- self.appReadyCheck = DispatchWorkItem(block: {
453
- self.DeferredNotifyAppReadyCheck()
454
- })
455
- print("\(self.implementation.TAG) Wait for \(self.appReadyTimeout) ms, then check for notifyAppReady")
456
- DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(self.appReadyTimeout), execute: self.appReadyCheck!)
457
- }
458
-
459
- func checkRevert() {
460
- // Automatically roll back to fallback version if notifyAppReady has not been called yet
461
- let current: BundleInfo = self.implementation.getCurrentBundle()
462
- if current.isBuiltin() {
463
- print("\(self.implementation.TAG) Built-in bundle is active. Nothing to do.")
464
- return
465
- }
466
-
467
- print("\(self.implementation.TAG) Current bundle is: \(current.toString())")
468
-
469
- if BundleStatus.SUCCESS.localizedString != current.getStatus() {
470
- print("\(self.implementation.TAG) notifyAppReady was not called, roll back current bundle: \(current.toString())")
471
- print("\(self.implementation.TAG) Did you forget to call 'notifyAppReady()' in your Capacitor App code?")
472
- self.notifyListeners("updateFailed", data: [
473
- "bundle": current.toJSON()
474
- ])
475
- self.implementation.sendStats(action: "update_fail", versionName: current.getVersionName())
476
- self.implementation.setError(bundle: current)
477
- _ = self._reset(toLastSuccessful: true)
478
- if self.autoDeleteFailed && !current.isBuiltin() {
479
- print("\(self.implementation.TAG) Deleting failing bundle: \(current.toString())")
480
- let res = self.implementation.delete(id: current.getId(), removeInfo: false)
481
- if !res {
482
- print("\(self.implementation.TAG) Delete version deleted: \(current.toString())")
483
- } else {
484
- print("\(self.implementation.TAG) Failed to delete failed bundle: \(current.toString())")
485
- }
486
- }
487
- } else {
488
- print("\(self.implementation.TAG) notifyAppReady was called. This is fine: \(current.toString())")
489
- }
490
- }
491
-
492
- func DeferredNotifyAppReadyCheck() {
493
- self.checkRevert()
494
- self.appReadyCheck = nil
495
- }
496
-
497
- func endBackGroundTask() {
498
- UIApplication.shared.endBackgroundTask(self.backgroundTaskID)
499
- self.backgroundTaskID = UIBackgroundTaskIdentifier.invalid
500
- }
501
-
502
- func backgroundDownload() {
503
- DispatchQueue.global(qos: .background).async {
504
- self.backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: "Finish Download Tasks") {
505
- // End the task if time expires.
506
- self.endBackGroundTask()
507
- }
508
- print("\(self.implementation.TAG) Check for update via \(self.updateUrl)")
509
- let url = URL(string: self.updateUrl)!
510
- let res = self.implementation.getLatest(url: url)
511
- let current = self.implementation.getCurrentBundle()
512
-
513
- if (res.message) != nil {
514
- print("\(self.implementation.TAG) message \(res.message ?? "")")
515
- if res.major == true {
516
- self.notifyListeners("majorAvailable", data: ["version": res.version])
517
- }
518
- self.notifyListeners("noNeedUpdate", data: ["bundle": current.toJSON()])
519
- self.endBackGroundTask()
520
- return
521
- }
522
- let sessionKey = res.sessionKey ?? ""
523
- guard let downloadUrl = URL(string: res.url) else {
524
- print("\(self.implementation.TAG) Error no url or wrong format")
525
- self.notifyListeners("noNeedUpdate", data: ["bundle": current.toJSON()])
526
- self.endBackGroundTask()
527
- return
528
- }
529
- let latestVersionName = res.version
530
- if latestVersionName != "" && current.getVersionName() != latestVersionName {
531
- let latest = self.implementation.getBundleInfoByVersionName(version: latestVersionName)
532
- if latest != nil {
533
- if latest!.isErrorStatus() {
534
- print("\(self.implementation.TAG) Latest version already exists, and is in error state. Aborting update.")
535
- self.notifyListeners("noNeedUpdate", data: ["bundle": current.toJSON()])
536
- self.endBackGroundTask()
537
- return
538
- }
539
- if latest!.isDownloaded() {
540
- print("\(self.implementation.TAG) Latest version already exists and download is NOT required. Update will occur next time app moves to background.")
541
- self.notifyListeners("updateAvailable", data: ["bundle": current.toJSON()])
542
- _ = self.implementation.setNextBundle(next: latest!.getId())
543
- self.endBackGroundTask()
544
- return
545
- }
546
- if latest!.isDeleted() {
547
- print("\(self.implementation.TAG) Latest bundle already exists and will be deleted, download will overwrite it.")
548
- let res = self.implementation.delete(id: latest!.getId(), removeInfo: true)
549
- if !res {
550
- print("\(self.implementation.TAG) Delete version deleted: \(latest!.toString())")
551
- } else {
552
- print("\(self.implementation.TAG) Failed to delete failed bundle: \(latest!.toString())")
553
- }
554
- }
555
- }
556
-
557
- do {
558
- print("\(self.implementation.TAG) New bundle: \(latestVersionName) found. Current is: \(current.getVersionName()). Update will occur next time app moves to background.")
559
- let next = try self.implementation.download(url: downloadUrl, version: latestVersionName, sessionKey: sessionKey)
560
- if res.checksum != "" && next.getChecksum() != res.checksum {
561
- print("\(self.implementation.TAG) Error checksum", next.getChecksum(), res.checksum)
562
- self.implementation.sendStats(action: "checksum_fail", versionName: next.getVersionName())
563
- let resDel = self.implementation.delete(id: next.getId())
564
- if !resDel {
565
- print("\(self.implementation.TAG) Delete failed, id \(next.getId()) doesn't exist")
566
- }
567
- self.endBackGroundTask()
568
- return
569
- }
570
- self.notifyListeners("updateAvailable", data: ["bundle": next.toJSON()])
571
- _ = self.implementation.setNextBundle(next: next.getId())
572
- } catch {
573
- print("\(self.implementation.TAG) Error downloading file", error.localizedDescription)
574
- let current: BundleInfo = self.implementation.getCurrentBundle()
575
- self.implementation.sendStats(action: "download_fail", versionName: current.getVersionName())
576
- self.notifyListeners("downloadFailed", data: ["version": latestVersionName])
577
- self.notifyListeners("noNeedUpdate", data: ["bundle": current.toJSON()])
578
- }
579
- } else {
580
- print("\(self.implementation.TAG) No need to update, \(current.getId()) is the latest bundle.")
581
- self.notifyListeners("noNeedUpdate", data: ["bundle": current.toJSON()])
582
- }
583
- self.endBackGroundTask()
584
- }
585
- }
586
-
587
- @objc func appKilled() {
588
- self._checkCancelDelay(killed: true)
589
- }
590
-
591
- private func installNext() {
592
- let delayUpdatePreferences = UserDefaults.standard.string(forKey: DELAY_CONDITION_PREFERENCES) ?? "[]"
593
- let delayConditionList: [DelayCondition]? = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
594
- let kind: String = obj.value(forKey: "kind") as! String
595
- let value: String? = obj.value(forKey: "value") as? String
596
- return DelayCondition(kind: kind, value: value)
597
- }
598
- if delayConditionList != nil && delayConditionList?.capacity != 0 {
599
- print("\(self.implementation.TAG) Update delayed to next backgrounding")
600
- return
601
- }
602
- let current: BundleInfo = self.implementation.getCurrentBundle()
603
- let next: BundleInfo? = self.implementation.getNextBundle()
604
-
605
- if next != nil && !next!.isErrorStatus() && next!.getVersionName() != current.getVersionName() {
606
- print("\(self.implementation.TAG) Next bundle is: \(next!.toString())")
607
- if self.implementation.set(bundle: next!) && self._reload() {
608
- print("\(self.implementation.TAG) Updated to bundle: \(next!.toString())")
609
- _ = self.implementation.setNextBundle(next: Optional<String>.none)
610
- } else {
611
- print("\(self.implementation.TAG) Update to bundle: \(next!.toString()) Failed!")
612
- }
613
- }
614
- }
615
-
616
- @objc private func toJson(object: Any) -> String {
617
- guard let data = try? JSONSerialization.data(withJSONObject: object, options: []) else {
618
- return ""
619
- }
620
- return String(data: data, encoding: String.Encoding.utf8) ?? ""
621
- }
622
-
623
- @objc private func fromJsonArr(json: String) -> [NSObject] {
624
- let jsonData = json.data(using: .utf8)!
625
- let object = try? JSONSerialization.jsonObject(
626
- with: jsonData,
627
- options: .mutableContainers
628
- ) as? [NSObject]
629
- return object ?? []
630
- }
631
-
632
- @objc func appMovedToForeground() {
633
- if backgroundWork != nil && taskRunning {
634
- backgroundWork!.cancel()
635
- print("\(self.implementation.TAG) Background Timer Task canceled, Activity resumed before timer completes")
636
- }
637
- if self._isAutoUpdateEnabled() {
638
- self.backgroundDownload()
639
- } else {
640
- print("\(self.implementation.TAG) Auto update is disabled")
641
- }
642
- self.checkAppReady()
643
- }
644
-
645
- @objc func appMovedToBackground() {
646
- print("\(self.implementation.TAG) Check for pending update")
647
- let delayUpdatePreferences = UserDefaults.standard.string(forKey: DELAY_CONDITION_PREFERENCES) ?? "[]"
648
-
649
- let delayConditionList: [DelayCondition] = fromJsonArr(json: delayUpdatePreferences).map { obj -> DelayCondition in
650
- let kind: String = obj.value(forKey: "kind") as! String
651
- let value: String? = obj.value(forKey: "value") as? String
652
- return DelayCondition(kind: kind, value: value)
653
- }
654
- var backgroundValue: String?
655
- for delayCondition in delayConditionList {
656
- if delayCondition.getKind() == "background" {
657
- let value: String? = delayCondition.getValue()
658
- backgroundValue = (value != nil && value != "") ? value! : "0"
659
- }
660
- }
661
- if backgroundValue != nil {
662
- self.taskRunning = true
663
- let interval: Double = (Double(backgroundValue!) ?? 0.0) / 1000
664
- self.backgroundWork?.cancel()
665
- self.backgroundWork = DispatchWorkItem(block: {
666
- // IOS never executes this task in background
667
- self.taskRunning = false
668
- self._checkCancelDelay(killed: false)
669
- self.installNext()
670
- })
671
- DispatchQueue.global(qos: .background).asyncAfter(deadline: .now() + interval, execute: self.backgroundWork!)
672
- } else {
673
- self._checkCancelDelay(killed: false)
674
- self.installNext()
675
- }
676
-
677
- }
678
- }