@capgo/capacitor-updater 9.0.0 → 9.0.1

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