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