@capgo/capacitor-updater 5.0.0-alpha.0 → 5.0.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 (38) hide show
  1. package/CapgoCapacitorUpdater.podspec +1 -1
  2. package/LICENCE +373 -661
  3. package/README.md +339 -75
  4. package/android/build.gradle +13 -12
  5. package/android/src/main/AndroidManifest.xml +4 -2
  6. package/android/src/main/java/ee/forgr/capacitor_updater/BundleInfo.java +205 -121
  7. package/android/src/main/java/ee/forgr/capacitor_updater/BundleStatus.java +32 -24
  8. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdater.java +1041 -441
  9. package/android/src/main/java/ee/forgr/capacitor_updater/CapacitorUpdaterPlugin.java +1220 -536
  10. package/android/src/main/java/ee/forgr/capacitor_updater/CryptoCipher.java +153 -0
  11. package/android/src/main/java/ee/forgr/capacitor_updater/DelayCondition.java +62 -0
  12. package/android/src/main/java/ee/forgr/capacitor_updater/DelayUntilNext.java +14 -0
  13. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadService.java +126 -0
  14. package/dist/docs.json +727 -171
  15. package/dist/esm/definitions.d.ts +234 -45
  16. package/dist/esm/definitions.js +5 -0
  17. package/dist/esm/definitions.js.map +1 -1
  18. package/dist/esm/index.d.ts +2 -2
  19. package/dist/esm/index.js +9 -4
  20. package/dist/esm/index.js.map +1 -1
  21. package/dist/esm/web.d.ts +12 -6
  22. package/dist/esm/web.js +64 -20
  23. package/dist/esm/web.js.map +1 -1
  24. package/dist/plugin.cjs.js +70 -23
  25. package/dist/plugin.cjs.js.map +1 -1
  26. package/dist/plugin.js +70 -23
  27. package/dist/plugin.js.map +1 -1
  28. package/ios/Plugin/BundleInfo.swift +38 -19
  29. package/ios/Plugin/BundleStatus.swift +11 -4
  30. package/ios/Plugin/CapacitorUpdater.swift +520 -192
  31. package/ios/Plugin/CapacitorUpdaterPlugin.m +8 -1
  32. package/ios/Plugin/CapacitorUpdaterPlugin.swift +449 -190
  33. package/ios/Plugin/CryptoCipher.swift +240 -0
  34. package/ios/Plugin/DelayCondition.swift +74 -0
  35. package/ios/Plugin/DelayUntilNext.swift +30 -0
  36. package/ios/Plugin/UserDefaultsExtension.swift +48 -0
  37. package/package.json +26 -20
  38. package/ios/Plugin/ObjectPreferences.swift +0 -97
@@ -1,18 +1,23 @@
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
+
1
7
  package ee.forgr.capacitor_updater;
2
8
 
3
9
  import android.app.Activity;
10
+ import android.app.ActivityManager;
4
11
  import android.app.Application;
12
+ import android.content.Context;
5
13
  import android.content.SharedPreferences;
6
14
  import android.content.pm.PackageInfo;
7
15
  import android.content.pm.PackageManager;
8
16
  import android.os.Build;
9
17
  import android.os.Bundle;
10
- import android.provider.Settings;
11
18
  import android.util.Log;
12
-
13
19
  import androidx.annotation.NonNull;
14
20
  import androidx.annotation.Nullable;
15
-
16
21
  import com.android.volley.toolbox.Volley;
17
22
  import com.getcapacitor.CapConfig;
18
23
  import com.getcapacitor.JSArray;
@@ -22,605 +27,1284 @@ import com.getcapacitor.PluginCall;
22
27
  import com.getcapacitor.PluginMethod;
23
28
  import com.getcapacitor.annotation.CapacitorPlugin;
24
29
  import com.getcapacitor.plugin.WebView;
25
-
30
+ import com.google.gson.Gson;
31
+ import com.google.gson.reflect.TypeToken;
26
32
  import io.github.g00fy2.versioncompare.Version;
27
-
28
- import org.json.JSONException;
29
-
30
33
  import java.io.IOException;
34
+ import java.lang.reflect.Type;
35
+ import java.net.MalformedURLException;
36
+ import java.net.URL;
37
+ import java.text.SimpleDateFormat;
38
+ import java.util.ArrayList;
39
+ import java.util.Date;
40
+ import java.util.Iterator;
31
41
  import java.util.List;
42
+ import java.util.UUID;
43
+ import org.json.JSONException;
32
44
 
33
45
  @CapacitorPlugin(name = "CapacitorUpdater")
34
- public class CapacitorUpdaterPlugin extends Plugin implements Application.ActivityLifecycleCallbacks {
35
- private static final String autoUpdateUrlDefault = "https://xvwzpoazmxkqosrdewyv.functions.supabase.co/updates";
36
- private static final String statsUrlDefault = "https://xvwzpoazmxkqosrdewyv.functions.supabase.co/stats";
37
- private static final String DELAY_UPDATE = "delayUpdate";
38
-
39
- private SharedPreferences.Editor editor;
40
- private SharedPreferences prefs;
41
- private CapacitorUpdater implementation;
42
-
43
- private Integer appReadyTimeout = 10000;
44
- private Boolean autoDeleteFailed = true;
45
- private Boolean autoDeletePrevious = true;
46
- private Boolean autoUpdate = false;
47
- private String autoUpdateUrl = "";
48
- private Version currentVersionNative;
49
- private Boolean resetWhenUpdate = true;
50
-
51
- private volatile Thread appReadyCheck;
52
-
53
- @Override
54
- public void load() {
55
- super.load();
56
- this.prefs = this.getContext().getSharedPreferences(WebView.WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE);
57
- this.editor = this.prefs.edit();
58
-
59
- try {
60
- this.implementation = new CapacitorUpdater() {
61
- @Override
62
- public void notifyDownload(final String id, final int percent) {
63
- CapacitorUpdaterPlugin.this.notifyDownload(id, percent);
64
- }
65
- };
66
- final PackageInfo pInfo = this.getContext().getPackageManager().getPackageInfo(this.getContext().getPackageName(), 0);
67
- this.implementation.versionBuild = pInfo.versionName;
68
- this.implementation.versionCode = Integer.toString(pInfo.versionCode);
69
- this.implementation.requestQueue = Volley.newRequestQueue(this.getContext());
70
- this.currentVersionNative = new Version(pInfo.versionName);
71
- } catch (final PackageManager.NameNotFoundException e) {
72
- Log.e(CapacitorUpdater.TAG, "Error instantiating implementation", e);
73
- return;
74
- } catch (final Exception e) {
75
- Log.e(CapacitorUpdater.TAG, "Error getting current native app version", e);
76
- return;
77
- }
78
-
79
- final CapConfig config = CapConfig.loadDefault(this.getActivity());
80
- this.implementation.appId = config.getString("appId", "");
81
- this.implementation.statsUrl = this.getConfig().getString("statsUrl", statsUrlDefault);
82
- this.implementation.documentsDir = this.getContext().getFilesDir();
83
- this.implementation.prefs = this.getContext().getSharedPreferences(WebView.WEBVIEW_PREFS_NAME, Activity.MODE_PRIVATE);
84
- this.implementation.editor = this.prefs.edit();
85
- this.implementation.versionOs = Build.VERSION.RELEASE;
86
- this.implementation.deviceID = Settings.Secure.getString(this.getContext().getContentResolver(), Settings.Secure.ANDROID_ID);
87
-
88
- this.autoDeleteFailed = this.getConfig().getBoolean("autoDeleteFailed", true);
89
- this.autoDeletePrevious = this.getConfig().getBoolean("autoDeletePrevious", true);
90
- this.autoUpdateUrl = this.getConfig().getString("autoUpdateUrl", autoUpdateUrlDefault);
91
- this.autoUpdate = this.getConfig().getBoolean("autoUpdate", false);
92
- this.appReadyTimeout = this.getConfig().getInt("appReadyTimeout", 10000);
93
- this.resetWhenUpdate = this.getConfig().getBoolean("resetWhenUpdate", true);
94
-
95
- if (this.resetWhenUpdate) {
96
- this.cleanupObsoleteVersions();
97
- }
98
- final Application application = (Application) this.getContext().getApplicationContext();
99
- application.registerActivityLifecycleCallbacks(this);
100
-
101
- this.onActivityStarted(this.getActivity());
46
+ public class CapacitorUpdaterPlugin
47
+ extends Plugin
48
+ implements Application.ActivityLifecycleCallbacks {
49
+
50
+ private static final String updateUrlDefault =
51
+ "https://api.capgo.app/updates";
52
+ private static final String statsUrlDefault = "https://api.capgo.app/stats";
53
+ private static final String defaultPrivateKey =
54
+ "-----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";
55
+ private static final String channelUrlDefault =
56
+ "https://api.capgo.app/channel_self";
57
+
58
+ private final String PLUGIN_VERSION = "5.0.0";
59
+ private static final String DELAY_CONDITION_PREFERENCES = "";
60
+
61
+ private SharedPreferences.Editor editor;
62
+ private SharedPreferences prefs;
63
+ private CapacitorUpdater implementation;
64
+
65
+ private Integer appReadyTimeout = 10000;
66
+ private Integer counterActivityCreate = 0;
67
+ private Boolean autoDeleteFailed = true;
68
+ private Boolean autoDeletePrevious = true;
69
+ private Boolean autoUpdate = false;
70
+ private String updateUrl = "";
71
+ private Version currentVersionNative;
72
+ private Boolean resetWhenUpdate = true;
73
+ private Thread backgroundTask;
74
+ private Boolean taskRunning = false;
75
+
76
+ private Boolean isPreviousMainActivity = true;
77
+
78
+ private volatile Thread appReadyCheck;
79
+
80
+ @Override
81
+ public void load() {
82
+ super.load();
83
+ this.prefs =
84
+ this.getContext()
85
+ .getSharedPreferences(
86
+ WebView.WEBVIEW_PREFS_NAME,
87
+ Activity.MODE_PRIVATE
88
+ );
89
+ this.editor = this.prefs.edit();
90
+
91
+ try {
92
+ this.implementation =
93
+ new CapacitorUpdater() {
94
+ @Override
95
+ public void notifyDownload(final String id, final int percent) {
96
+ CapacitorUpdaterPlugin.this.notifyDownload(id, percent);
97
+ }
98
+
99
+ @Override
100
+ public void notifyListeners(final String id, final JSObject res) {
101
+ CapacitorUpdaterPlugin.this.notifyListeners(id, res);
102
+ }
103
+ };
104
+ final PackageInfo pInfo =
105
+ this.getContext()
106
+ .getPackageManager()
107
+ .getPackageInfo(this.getContext().getPackageName(), 0);
108
+ this.implementation.activity = this.getActivity();
109
+ this.implementation.versionBuild =
110
+ this.getConfig().getString("version", pInfo.versionName);
111
+ this.implementation.PLUGIN_VERSION = this.PLUGIN_VERSION;
112
+ this.implementation.versionCode = Integer.toString(pInfo.versionCode);
113
+ this.implementation.requestQueue =
114
+ Volley.newRequestQueue(this.getContext());
115
+ this.currentVersionNative =
116
+ new Version(this.getConfig().getString("version", pInfo.versionName));
117
+ } catch (final PackageManager.NameNotFoundException e) {
118
+ Log.e(CapacitorUpdater.TAG, "Error instantiating implementation", e);
119
+ return;
120
+ } catch (final Exception e) {
121
+ Log.e(
122
+ CapacitorUpdater.TAG,
123
+ "Error getting current native app version",
124
+ e
125
+ );
126
+ return;
102
127
  }
103
128
 
104
- private void cleanupObsoleteVersions() {
105
- try {
106
- final Version previous = new Version(this.prefs.getString("LatestVersionNative", ""));
129
+ final CapConfig config = CapConfig.loadDefault(this.getActivity());
130
+ this.implementation.appId = config.getString("appId", "");
131
+ this.implementation.privateKey =
132
+ this.getConfig().getString("privateKey", defaultPrivateKey);
133
+ this.implementation.statsUrl =
134
+ this.getConfig().getString("statsUrl", statsUrlDefault);
135
+ this.implementation.channelUrl =
136
+ this.getConfig().getString("channelUrl", channelUrlDefault);
137
+ this.implementation.documentsDir = this.getContext().getFilesDir();
138
+ this.implementation.prefs = this.prefs;
139
+ this.implementation.editor = this.editor;
140
+ this.implementation.versionOs = Build.VERSION.RELEASE;
141
+ this.implementation.deviceID =
142
+ this.prefs.getString("appUUID", UUID.randomUUID().toString());
143
+ this.editor.putString("appUUID", this.implementation.deviceID);
144
+ Log.i(
145
+ CapacitorUpdater.TAG,
146
+ "init for device " + this.implementation.deviceID
147
+ );
148
+ Log.i(
149
+ CapacitorUpdater.TAG,
150
+ "version native " + this.currentVersionNative.getOriginalString()
151
+ );
152
+ this.autoDeleteFailed =
153
+ this.getConfig().getBoolean("autoDeleteFailed", true);
154
+ this.autoDeletePrevious =
155
+ this.getConfig().getBoolean("autoDeletePrevious", true);
156
+ this.updateUrl = this.getConfig().getString("updateUrl", updateUrlDefault);
157
+ this.autoUpdate = this.getConfig().getBoolean("autoUpdate", true);
158
+ this.appReadyTimeout = this.getConfig().getInt("appReadyTimeout", 10000);
159
+ this.resetWhenUpdate = this.getConfig().getBoolean("resetWhenUpdate", true);
160
+
161
+ if (this.resetWhenUpdate) {
162
+ this.cleanupObsoleteVersions();
163
+ }
164
+ final Application application = (Application) this.getContext()
165
+ .getApplicationContext();
166
+ application.registerActivityLifecycleCallbacks(this);
167
+ }
168
+
169
+ private void cleanupObsoleteVersions() {
170
+ try {
171
+ final Version previous = new Version(
172
+ this.prefs.getString("LatestVersionNative", "")
173
+ );
174
+ try {
175
+ if (
176
+ !"".equals(previous.getOriginalString()) &&
177
+ !this.currentVersionNative.getOriginalString()
178
+ .equals(previous.getOriginalString())
179
+ ) {
180
+ Log.i(
181
+ CapacitorUpdater.TAG,
182
+ "New native version detected: " + this.currentVersionNative
183
+ );
184
+ this.implementation.reset(true);
185
+ final List<BundleInfo> installed = this.implementation.list();
186
+ for (final BundleInfo bundle : installed) {
107
187
  try {
108
- if (!"".equals(previous.getOriginalString()) && this.currentVersionNative.getMajor() > previous.getMajor()) {
109
-
110
- Log.i(CapacitorUpdater.TAG, "New native major version detected: " + this.currentVersionNative);
111
- this.implementation.reset(true);
112
- final List<BundleInfo> installed = this.implementation.list();
113
- for (final BundleInfo bundle: installed) {
114
- try {
115
- Log.i(CapacitorUpdater.TAG, "Deleting obsolete bundle: " + bundle.getId());
116
- this.implementation.delete(bundle.getId());
117
- } catch (final Exception e) {
118
- Log.e(CapacitorUpdater.TAG, "Failed to delete: " + bundle.getId(), e);
119
- }
120
- }
121
- }
188
+ Log.i(
189
+ CapacitorUpdater.TAG,
190
+ "Deleting obsolete bundle: " + bundle.getId()
191
+ );
192
+ this.implementation.delete(bundle.getId());
122
193
  } catch (final Exception e) {
123
- Log.e(CapacitorUpdater.TAG, "Could not determine the current version", e);
194
+ Log.e(
195
+ CapacitorUpdater.TAG,
196
+ "Failed to delete: " + bundle.getId(),
197
+ e
198
+ );
124
199
  }
125
- } catch(final Exception e) {
126
- Log.e(CapacitorUpdater.TAG, "Error calculating previous native version", e);
200
+ }
127
201
  }
128
- this.editor.putString("LatestVersionNative", this.currentVersionNative.toString());
129
- this.editor.commit();
202
+ } catch (final Exception e) {
203
+ Log.e(
204
+ CapacitorUpdater.TAG,
205
+ "Could not determine the current version",
206
+ e
207
+ );
208
+ }
209
+ } catch (final Exception e) {
210
+ Log.e(
211
+ CapacitorUpdater.TAG,
212
+ "Error calculating previous native version",
213
+ e
214
+ );
130
215
  }
131
-
132
- public void notifyDownload(final String id, final int percent) {
133
- try {
134
- final JSObject ret = new JSObject();
135
- ret.put("percent", percent);
136
- var bundle = this.implementation.getBundleInfo(id).toJSON();
137
- ret.put("bundle", bundle);
138
- this.notifyListeners("download", ret);
139
- if (percent == 100) {
140
- this.notifyListeners("downloadComplete", bundle);
141
- }
142
- } catch (final Exception e) {
143
- Log.e(CapacitorUpdater.TAG, "Could not notify listeners", e);
144
- }
216
+ this.editor.putString(
217
+ "LatestVersionNative",
218
+ this.currentVersionNative.toString()
219
+ );
220
+ this.editor.commit();
221
+ }
222
+
223
+ public void notifyDownload(final String id, final int percent) {
224
+ try {
225
+ final JSObject ret = new JSObject();
226
+ ret.put("percent", percent);
227
+ final BundleInfo bundleInfo = this.implementation.getBundleInfo(id);
228
+ ret.put("bundle", bundleInfo.toJSON());
229
+ this.notifyListeners("download", ret);
230
+ if (percent == 100) {
231
+ this.notifyListeners("downloadComplete", bundleInfo.toJSON());
232
+ this.implementation.sendStats(
233
+ "download_complete",
234
+ bundleInfo.getVersionName()
235
+ );
236
+ } else if (percent % 10 == 0) {
237
+ this.implementation.sendStats(
238
+ "download_" + percent,
239
+ bundleInfo.getVersionName()
240
+ );
241
+ }
242
+ } catch (final Exception e) {
243
+ Log.e(CapacitorUpdater.TAG, "Could not notify listeners", e);
145
244
  }
146
-
147
-
148
- @PluginMethod
149
- public void getId(final PluginCall call) {
150
- try {
151
- final JSObject ret = new JSObject();
152
- ret.put("id", this.implementation.deviceID);
153
- call.resolve(ret);
154
- } catch (final Exception e) {
155
- Log.e(CapacitorUpdater.TAG, "Could not get device id", e);
156
- call.reject("Could not get device id", e);
157
- }
245
+ }
246
+
247
+ @PluginMethod
248
+ public void getDeviceId(final PluginCall call) {
249
+ try {
250
+ final JSObject ret = new JSObject();
251
+ ret.put("deviceId", this.implementation.deviceID);
252
+ call.resolve(ret);
253
+ } catch (final Exception e) {
254
+ Log.e(CapacitorUpdater.TAG, "Could not get device id", e);
255
+ call.reject("Could not get device id", e);
158
256
  }
159
-
160
- @PluginMethod
161
- public void getPluginVersion(final PluginCall call) {
162
- try {
163
- final JSObject ret = new JSObject();
164
- ret.put("version", CapacitorUpdater.pluginVersion);
165
- call.resolve(ret);
166
- } catch (final Exception e) {
167
- Log.e(CapacitorUpdater.TAG, "Could not get plugin version", e);
168
- call.reject("Could not get plugin version", e);
169
- }
257
+ }
258
+
259
+ @PluginMethod
260
+ public void setCustomId(final PluginCall call) {
261
+ final String customId = call.getString("customId");
262
+ if (customId == null) {
263
+ Log.e(CapacitorUpdater.TAG, "setCustomId called without customId");
264
+ call.reject("setCustomId called without customId");
265
+ return;
170
266
  }
171
-
172
- @PluginMethod
173
- public void download(final PluginCall call) {
174
- final String url = call.getString("url");
175
- final String version = call.getString("version");
176
- if (url == null || version == null) {
177
- call.reject("missing url or version");
178
- return;
179
- }
180
- try {
181
- Log.i(CapacitorUpdater.TAG, "Downloading " + url);
182
- new Thread(new Runnable(){
183
- @Override
184
- public void run() {
185
- try {
186
-
187
- final BundleInfo downloaded = CapacitorUpdaterPlugin.this.implementation.download(url, version);
188
- call.resolve(downloaded.toJSON());
189
- } catch (final IOException e) {
190
- Log.e(CapacitorUpdater.TAG, "download failed", e);
191
- call.reject("download failed", e);
192
- }
267
+ this.implementation.customId = customId;
268
+ }
269
+
270
+ @PluginMethod
271
+ public void getPluginVersion(final PluginCall call) {
272
+ try {
273
+ final JSObject ret = new JSObject();
274
+ ret.put("version", this.PLUGIN_VERSION);
275
+ call.resolve(ret);
276
+ } catch (final Exception e) {
277
+ Log.e(CapacitorUpdater.TAG, "Could not get plugin version", e);
278
+ call.reject("Could not get plugin version", e);
279
+ }
280
+ }
281
+
282
+ @PluginMethod
283
+ public void setChannel(final PluginCall call) {
284
+ final String channel = call.getString("channel");
285
+ if (channel == null) {
286
+ Log.e(CapacitorUpdater.TAG, "setChannel called without channel");
287
+ call.reject("setChannel called without channel");
288
+ return;
289
+ }
290
+ try {
291
+ Log.i(CapacitorUpdater.TAG, "setChannel " + channel);
292
+ new Thread(
293
+ new Runnable() {
294
+ @Override
295
+ public void run() {
296
+ CapacitorUpdaterPlugin.this.implementation.setChannel(
297
+ channel,
298
+ res -> {
299
+ if (res.has("error")) {
300
+ call.reject(res.getString("error"));
301
+ } else {
302
+ call.resolve(res);
303
+ }
193
304
  }
194
- }).start();
195
- } catch (final Exception e) {
196
- Log.e(CapacitorUpdater.TAG, "Failed to download " + url, e);
197
- call.reject("Failed to download " + url, e);
305
+ );
306
+ }
198
307
  }
308
+ )
309
+ .start();
310
+ } catch (final Exception e) {
311
+ Log.e(CapacitorUpdater.TAG, "Failed to setChannel: " + channel, e);
312
+ call.reject("Failed to setChannel: " + channel, e);
199
313
  }
200
-
201
- private boolean _reload() {
202
- final String path = this.implementation.getCurrentBundlePath();
203
- Log.i(CapacitorUpdater.TAG, "Reloading: " + path);
204
- if(this.implementation.isUsingBuiltin()) {
205
- this.bridge.setServerAssetPath(path);
206
- } else {
207
- this.bridge.setServerBasePath(path);
314
+ }
315
+
316
+ @PluginMethod
317
+ public void getChannel(final PluginCall call) {
318
+ try {
319
+ Log.i(CapacitorUpdater.TAG, "getChannel");
320
+ new Thread(
321
+ new Runnable() {
322
+ @Override
323
+ public void run() {
324
+ CapacitorUpdaterPlugin.this.implementation.getChannel(res -> {
325
+ if (res.has("error")) {
326
+ call.reject(res.getString("error"));
327
+ } else {
328
+ call.resolve(res);
329
+ }
330
+ });
331
+ }
208
332
  }
209
- this.checkAppReady();
210
- return true;
333
+ )
334
+ .start();
335
+ } catch (final Exception e) {
336
+ Log.e(CapacitorUpdater.TAG, "Failed to getChannel", e);
337
+ call.reject("Failed to getChannel", e);
211
338
  }
212
-
213
- @PluginMethod
214
- public void reload(final PluginCall call) {
215
- try {
216
- if (this._reload()) {
217
- call.resolve();
218
- } else {
219
- call.reject("Reload failed");
220
- }
221
- } catch(final Exception e) {
222
- Log.e(CapacitorUpdater.TAG, "Could not reload", e);
223
- call.reject("Could not reload", e);
224
- }
339
+ }
340
+
341
+ @PluginMethod
342
+ public void download(final PluginCall call) {
343
+ final String url = call.getString("url");
344
+ final String version = call.getString("version");
345
+ final String sessionKey = call.getString("sessionKey", "");
346
+ final String checksum = call.getString("checksum", "");
347
+ if (url == null) {
348
+ Log.e(CapacitorUpdater.TAG, "Download called without url");
349
+ call.reject("Download called without url");
350
+ return;
225
351
  }
226
-
227
- @PluginMethod
228
- public void next(final PluginCall call) {
229
- final String id = call.getString("id");
230
-
231
- try {
232
- Log.i(CapacitorUpdater.TAG, "Setting next active id " + id);
233
- if (!this.implementation.setNextVersion(id)) {
234
- call.reject("Set next id failed. Bundle " + id + " does not exist.");
235
- } else {
236
- call.resolve(this.implementation.getBundleInfo(id).toJSON());
237
- }
238
- } catch (final Exception e) {
239
- Log.e(CapacitorUpdater.TAG, "Could not set next id " + id, e);
240
- call.reject("Could not set next id " + id, e);
241
- }
352
+ if (version == null) {
353
+ Log.e(CapacitorUpdater.TAG, "Download called without version");
354
+ call.reject("Download called without version");
355
+ return;
242
356
  }
243
-
244
- @PluginMethod
245
- public void set(final PluginCall call) {
246
- final String id = call.getString("id");
247
-
248
- try {
249
- Log.i(CapacitorUpdater.TAG, "Setting active bundle " + id);
250
- if (!this.implementation.set(id)) {
251
- Log.i(CapacitorUpdater.TAG, "No such bundle " + id);
252
- call.reject("Update failed, id " + id + " does not exist.");
253
- } else {
254
- Log.i(CapacitorUpdater.TAG, "Bundle successfully set to" + id);
255
- this.reload(call);
357
+ try {
358
+ Log.i(CapacitorUpdater.TAG, "Downloading " + url);
359
+ new Thread(
360
+ new Runnable() {
361
+ @Override
362
+ public void run() {
363
+ try {
364
+ final BundleInfo downloaded =
365
+ CapacitorUpdaterPlugin.this.implementation.download(
366
+ url,
367
+ version,
368
+ sessionKey,
369
+ checksum
370
+ );
371
+
372
+ call.resolve(downloaded.toJSON());
373
+ } catch (final IOException e) {
374
+ Log.e(CapacitorUpdater.TAG, "Failed to download from: " + url, e);
375
+ call.reject("Failed to download from: " + url, e);
376
+ final JSObject ret = new JSObject();
377
+ ret.put("version", version);
378
+ CapacitorUpdaterPlugin.this.notifyListeners(
379
+ "downloadFailed",
380
+ ret
381
+ );
382
+ final BundleInfo current =
383
+ CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
384
+ CapacitorUpdaterPlugin.this.implementation.sendStats(
385
+ "download_fail",
386
+ current.getVersionName()
387
+ );
256
388
  }
257
- } catch(final Exception e) {
258
- Log.e(CapacitorUpdater.TAG, "Could not set id " + id, e);
259
- call.reject("Could not set id " + id, e);
389
+ }
260
390
  }
391
+ )
392
+ .start();
393
+ } catch (final Exception e) {
394
+ Log.e(CapacitorUpdater.TAG, "Failed to download from: " + url, e);
395
+ call.reject("Failed to download from: " + url, e);
396
+ final JSObject ret = new JSObject();
397
+ ret.put("version", version);
398
+ CapacitorUpdaterPlugin.this.notifyListeners("downloadFailed", ret);
399
+ final BundleInfo current =
400
+ CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
401
+ CapacitorUpdaterPlugin.this.implementation.sendStats(
402
+ "download_fail",
403
+ current.getVersionName()
404
+ );
261
405
  }
262
-
263
- @PluginMethod
264
- public void delete(final PluginCall call) {
265
- final String id = call.getString("id");
266
- Log.i(CapacitorUpdater.TAG, "Deleting id: " + id);
267
- try {
268
- final Boolean res = this.implementation.delete(id);
269
- if (res) {
270
- call.resolve();
271
- } else {
272
- call.reject("Delete failed, id " + id + " does not exist");
273
- }
274
- } catch(final Exception e) {
275
- Log.e(CapacitorUpdater.TAG, "Could not delete id " + id, e);
276
- call.reject("Could not delete id " + id, e);
277
- }
406
+ }
407
+
408
+ private boolean _reload() {
409
+ final String path = this.implementation.getCurrentBundlePath();
410
+ Log.i(CapacitorUpdater.TAG, "Reloading: " + path);
411
+ if (this.implementation.isUsingBuiltin()) {
412
+ this.bridge.setServerAssetPath(path);
413
+ } else {
414
+ this.bridge.setServerBasePath(path);
278
415
  }
279
-
280
-
281
- @PluginMethod
282
- public void list(final PluginCall call) {
283
- try {
284
- final List<BundleInfo> res = this.implementation.list();
285
- final JSObject ret = new JSObject();
286
- final JSArray values = new JSArray();
287
- for (final BundleInfo bundle : res) {
288
- values.put(bundle.toJSON());
289
- }
290
- ret.put("bundles", values);
291
- call.resolve(ret);
292
- }
293
- catch(final Exception e) {
294
- Log.e(CapacitorUpdater.TAG, "Could not list bundles", e);
295
- call.reject("Could not list bundles", e);
416
+ this.checkAppReady();
417
+ this.notifyListeners("appReloaded", new JSObject());
418
+ return true;
419
+ }
420
+
421
+ @PluginMethod
422
+ public void reload(final PluginCall call) {
423
+ try {
424
+ if (this._reload()) {
425
+ call.resolve();
426
+ } else {
427
+ Log.e(CapacitorUpdater.TAG, "Reload failed");
428
+ call.reject("Reload failed");
429
+ }
430
+ } catch (final Exception e) {
431
+ Log.e(CapacitorUpdater.TAG, "Could not reload", e);
432
+ call.reject("Could not reload", e);
433
+ }
434
+ }
435
+
436
+ @PluginMethod
437
+ public void next(final PluginCall call) {
438
+ final String id = call.getString("id");
439
+ if (id == null) {
440
+ Log.e(CapacitorUpdater.TAG, "Next called without id");
441
+ call.reject("Next called without id");
442
+ return;
443
+ }
444
+ try {
445
+ Log.i(CapacitorUpdater.TAG, "Setting next active id " + id);
446
+ if (!this.implementation.setNextBundle(id)) {
447
+ Log.e(
448
+ CapacitorUpdater.TAG,
449
+ "Set next id failed. Bundle " + id + " does not exist."
450
+ );
451
+ call.reject("Set next id failed. Bundle " + id + " does not exist.");
452
+ } else {
453
+ call.resolve(this.implementation.getBundleInfo(id).toJSON());
454
+ }
455
+ } catch (final Exception e) {
456
+ Log.e(CapacitorUpdater.TAG, "Could not set next id " + id, e);
457
+ call.reject("Could not set next id: " + id, e);
458
+ }
459
+ }
460
+
461
+ @PluginMethod
462
+ public void set(final PluginCall call) {
463
+ final String id = call.getString("id");
464
+ if (id == null) {
465
+ Log.e(CapacitorUpdater.TAG, "Set called without id");
466
+ call.reject("Set called without id");
467
+ return;
468
+ }
469
+ try {
470
+ Log.i(CapacitorUpdater.TAG, "Setting active bundle " + id);
471
+ if (!this.implementation.set(id)) {
472
+ Log.i(CapacitorUpdater.TAG, "No such bundle " + id);
473
+ call.reject("Update failed, id " + id + " does not exist.");
474
+ } else {
475
+ Log.i(CapacitorUpdater.TAG, "Bundle successfully set to " + id);
476
+ this.reload(call);
477
+ }
478
+ } catch (final Exception e) {
479
+ Log.e(CapacitorUpdater.TAG, "Could not set id " + id, e);
480
+ call.reject("Could not set id " + id, e);
481
+ }
482
+ }
483
+
484
+ @PluginMethod
485
+ public void delete(final PluginCall call) {
486
+ final String id = call.getString("id");
487
+ if (id == null) {
488
+ Log.e(CapacitorUpdater.TAG, "missing id");
489
+ call.reject("missing id");
490
+ return;
491
+ }
492
+ Log.i(CapacitorUpdater.TAG, "Deleting id " + id);
493
+ try {
494
+ final Boolean res = this.implementation.delete(id);
495
+ if (res) {
496
+ call.resolve();
497
+ } else {
498
+ Log.e(
499
+ CapacitorUpdater.TAG,
500
+ "Delete failed, id " + id + " does not exist"
501
+ );
502
+ call.reject("Delete failed, id " + id + " does not exist");
503
+ }
504
+ } catch (final Exception e) {
505
+ Log.e(CapacitorUpdater.TAG, "Could not delete id " + id, e);
506
+ call.reject("Could not delete id " + id, e);
507
+ }
508
+ }
509
+
510
+ @PluginMethod
511
+ public void list(final PluginCall call) {
512
+ try {
513
+ final List<BundleInfo> res = this.implementation.list();
514
+ final JSObject ret = new JSObject();
515
+ final JSArray values = new JSArray();
516
+ for (final BundleInfo bundle : res) {
517
+ values.put(bundle.toJSON());
518
+ }
519
+ ret.put("bundles", values);
520
+ call.resolve(ret);
521
+ } catch (final Exception e) {
522
+ Log.e(CapacitorUpdater.TAG, "Could not list bundles", e);
523
+ call.reject("Could not list bundles", e);
524
+ }
525
+ }
526
+
527
+ @PluginMethod
528
+ public void getLatest(final PluginCall call) {
529
+ try {
530
+ new Thread(
531
+ new Runnable() {
532
+ @Override
533
+ public void run() {
534
+ CapacitorUpdaterPlugin.this.implementation.getLatest(
535
+ CapacitorUpdaterPlugin.this.updateUrl,
536
+ res -> {
537
+ if (res.has("error")) {
538
+ call.reject(res.getString("error"));
539
+ return;
540
+ } else if (res.has("message")) {
541
+ call.reject(res.getString("message"));
542
+ return;
543
+ } else {
544
+ call.resolve(res);
545
+ }
546
+ final JSObject ret = new JSObject();
547
+ Iterator<String> keys = res.keys();
548
+ while (keys.hasNext()) {
549
+ String key = keys.next();
550
+ if (res.has(key)) {
551
+ try {
552
+ ret.put(key, res.get(key));
553
+ } catch (JSONException e) {
554
+ e.printStackTrace();
555
+ }
556
+ }
557
+ }
558
+ call.resolve(ret);
559
+ }
560
+ );
561
+ }
296
562
  }
563
+ )
564
+ .start();
565
+ } catch (final Exception e) {
566
+ Log.e(CapacitorUpdater.TAG, "Failed to getLatest", e);
567
+ call.reject("Failed to getLatest", e);
297
568
  }
569
+ }
298
570
 
299
- private boolean _reset(final Boolean toLastSuccessful) {
300
- final BundleInfo fallback = this.implementation.getFallbackVersion();
301
- this.implementation.reset();
302
-
303
- if (toLastSuccessful && !fallback.isBuiltin()) {
304
- Log.i(CapacitorUpdater.TAG, "Resetting to: " + fallback);
305
- return this.implementation.set(fallback) && this._reload();
306
- }
571
+ private boolean _reset(final Boolean toLastSuccessful) {
572
+ final BundleInfo fallback = this.implementation.getFallbackBundle();
573
+ this.implementation.reset();
307
574
 
308
- Log.i(CapacitorUpdater.TAG, "Resetting to native.");
309
- return this._reload();
575
+ if (toLastSuccessful && !fallback.isBuiltin()) {
576
+ Log.i(CapacitorUpdater.TAG, "Resetting to: " + fallback);
577
+ return this.implementation.set(fallback) && this._reload();
310
578
  }
311
579
 
312
- @PluginMethod
313
- public void reset(final PluginCall call) {
314
- try {
315
- final Boolean toLastSuccessful = call.getBoolean("toLastSuccessful", false);
316
- if (this._reset(toLastSuccessful)) {
317
- call.resolve();
318
- return;
319
- }
320
- call.reject("Reset failed");
321
- }
322
- catch(final Exception e) {
323
- Log.e(CapacitorUpdater.TAG, "Reset failed", e);
324
- call.reject("Reset failed", e);
325
- }
580
+ Log.i(CapacitorUpdater.TAG, "Resetting to native.");
581
+ return this._reload();
582
+ }
583
+
584
+ @PluginMethod
585
+ public void reset(final PluginCall call) {
586
+ try {
587
+ final Boolean toLastSuccessful = call.getBoolean(
588
+ "toLastSuccessful",
589
+ false
590
+ );
591
+ if (this._reset(toLastSuccessful)) {
592
+ call.resolve();
593
+ return;
594
+ }
595
+ Log.e(CapacitorUpdater.TAG, "Reset failed");
596
+ call.reject("Reset failed");
597
+ } catch (final Exception e) {
598
+ Log.e(CapacitorUpdater.TAG, "Reset failed", e);
599
+ call.reject("Reset failed", e);
326
600
  }
327
-
328
- @PluginMethod
329
- public void current(final PluginCall call) {
330
- try {
331
- final JSObject ret = new JSObject();
332
- final BundleInfo bundle = this.implementation.getCurrentBundle();
333
- ret.put("bundle", bundle.toJSON());
334
- ret.put("native", this.currentVersionNative);
335
- call.resolve(ret);
336
- }
337
- catch(final Exception e) {
338
- Log.e(CapacitorUpdater.TAG, "Could not get current bundle", e);
339
- call.reject("Could not get current bundle", e);
340
- }
601
+ }
602
+
603
+ @PluginMethod
604
+ public void current(final PluginCall call) {
605
+ try {
606
+ final JSObject ret = new JSObject();
607
+ final BundleInfo bundle = this.implementation.getCurrentBundle();
608
+ ret.put("bundle", bundle.toJSON());
609
+ ret.put("native", this.currentVersionNative);
610
+ call.resolve(ret);
611
+ } catch (final Exception e) {
612
+ Log.e(CapacitorUpdater.TAG, "Could not get current bundle", e);
613
+ call.reject("Could not get current bundle", e);
341
614
  }
342
-
343
- @PluginMethod
344
- public void notifyAppReady(final PluginCall call) {
345
- try {
346
- Log.i(CapacitorUpdater.TAG, "Current bundle loaded successfully. ['notifyAppReady()' was called]");
347
- final BundleInfo bundle = this.implementation.getCurrentBundle();
348
- this.implementation.commit(bundle);
349
- call.resolve();
350
- }
351
- catch(final Exception e) {
352
- Log.e(CapacitorUpdater.TAG, "Failed to notify app ready state. [Error calling 'notifyAppReady()']", e);
353
- call.reject("Failed to commit app ready state.", e);
354
- }
615
+ }
616
+
617
+ @PluginMethod
618
+ public void notifyAppReady(final PluginCall call) {
619
+ try {
620
+ final BundleInfo bundle = this.implementation.getCurrentBundle();
621
+ this.implementation.setSuccess(bundle, this.autoDeletePrevious);
622
+ Log.i(
623
+ CapacitorUpdater.TAG,
624
+ "Current bundle loaded successfully. ['notifyAppReady()' was called] " +
625
+ bundle
626
+ );
627
+ call.resolve();
628
+ } catch (final Exception e) {
629
+ Log.e(
630
+ CapacitorUpdater.TAG,
631
+ "Failed to notify app ready state. [Error calling 'notifyAppReady()']",
632
+ e
633
+ );
634
+ call.reject("Failed to commit app ready state.", e);
355
635
  }
356
-
357
- @PluginMethod
358
- public void delayUpdate(final PluginCall call) {
359
- try {
360
- Log.i(CapacitorUpdater.TAG, "Delay update.");
361
- this.editor.putBoolean(DELAY_UPDATE, true);
362
- this.editor.commit();
363
- call.resolve();
364
- }
365
- catch(final Exception e) {
366
- Log.e(CapacitorUpdater.TAG, "Failed to delay update", e);
367
- call.reject("Failed to delay update", e);
368
- }
636
+ }
637
+
638
+ @PluginMethod
639
+ public void setMultiDelay(final PluginCall call) {
640
+ try {
641
+ final Object delayConditions = call.getData().opt("delayConditions");
642
+ if (delayConditions == null) {
643
+ Log.e(
644
+ CapacitorUpdater.TAG,
645
+ "setMultiDelay called without delayCondition"
646
+ );
647
+ call.reject("setMultiDelay called without delayCondition");
648
+ return;
649
+ }
650
+ if (_setMultiDelay(delayConditions.toString())) {
651
+ call.resolve();
652
+ } else {
653
+ call.reject("Failed to delay update");
654
+ }
655
+ } catch (final Exception e) {
656
+ Log.e(
657
+ CapacitorUpdater.TAG,
658
+ "Failed to delay update, [Error calling 'setMultiDelay()']",
659
+ e
660
+ );
661
+ call.reject("Failed to delay update", e);
369
662
  }
370
-
371
- @PluginMethod
372
- public void cancelDelay(final PluginCall call) {
373
- try {
374
- Log.i(CapacitorUpdater.TAG, "Cancel update delay.");
375
- this.editor.putBoolean(DELAY_UPDATE, false);
376
- this.editor.commit();
377
- call.resolve();
378
- }
379
- catch(final Exception e) {
380
- Log.e(CapacitorUpdater.TAG, "Failed to cancel update delay", e);
381
- call.reject("Failed to cancel update delay", e);
382
- }
663
+ }
664
+
665
+ private Boolean _setMultiDelay(String delayConditions) {
666
+ try {
667
+ this.editor.putString(DELAY_CONDITION_PREFERENCES, delayConditions);
668
+ this.editor.commit();
669
+ Log.i(CapacitorUpdater.TAG, "Delay update saved");
670
+ return true;
671
+ } catch (final Exception e) {
672
+ Log.e(
673
+ CapacitorUpdater.TAG,
674
+ "Failed to delay update, [Error calling '_setMultiDelay()']",
675
+ e
676
+ );
677
+ return false;
383
678
  }
384
-
385
- private Boolean _isAutoUpdateEnabled() {
386
- return CapacitorUpdaterPlugin.this.autoUpdate && !"".equals(CapacitorUpdaterPlugin.this.autoUpdateUrl);
679
+ }
680
+
681
+ private boolean _cancelDelay(String source) {
682
+ try {
683
+ this.editor.remove(DELAY_CONDITION_PREFERENCES);
684
+ this.editor.commit();
685
+ Log.i(CapacitorUpdater.TAG, "All delays canceled from " + source);
686
+ return true;
687
+ } catch (final Exception e) {
688
+ Log.e(CapacitorUpdater.TAG, "Failed to cancel update delay", e);
689
+ return false;
387
690
  }
388
-
389
- @PluginMethod
390
- public void isAutoUpdateEnabled(final PluginCall call) {
391
- try {
392
- final JSObject ret = new JSObject();
393
- ret.put("enabled", this._isAutoUpdateEnabled());
394
- call.resolve(ret);
395
- } catch (final Exception e) {
396
- Log.e(CapacitorUpdater.TAG, "Could not get autoUpdate status", e);
397
- call.reject("Could not get autoUpdate status", e);
398
- }
691
+ }
692
+
693
+ @PluginMethod
694
+ public void cancelDelay(final PluginCall call) {
695
+ if (this._cancelDelay("JS")) {
696
+ call.resolve();
697
+ } else {
698
+ call.reject("Failed to cancel delay");
399
699
  }
400
-
401
- private void checkAppReady() {
402
- try {
403
- if(this.appReadyCheck != null) {
404
- this.appReadyCheck.interrupt();
700
+ }
701
+
702
+ private void _checkCancelDelay(Boolean killed) {
703
+ Gson gson = new Gson();
704
+ String delayUpdatePreferences = prefs.getString(
705
+ DELAY_CONDITION_PREFERENCES,
706
+ "[]"
707
+ );
708
+ Type type = new TypeToken<ArrayList<DelayCondition>>() {}.getType();
709
+ ArrayList<DelayCondition> delayConditionList = gson.fromJson(
710
+ delayUpdatePreferences,
711
+ type
712
+ );
713
+ for (DelayCondition condition : delayConditionList) {
714
+ String kind = condition.getKind().toString();
715
+ String value = condition.getValue();
716
+ if (!"".equals(kind)) {
717
+ switch (kind) {
718
+ case "background":
719
+ if (!killed) {
720
+ this._cancelDelay("background check");
405
721
  }
406
- this.appReadyCheck = new Thread(new DeferredNotifyAppReadyCheck());
407
- this.appReadyCheck.start();
408
- } catch (final Exception e) {
409
- Log.e(CapacitorUpdater.TAG, "Failed to start " + DeferredNotifyAppReadyCheck.class.getName(), e);
410
- }
411
- }
412
-
413
- @Override // appMovedToForeground
414
- public void onActivityStarted(@NonNull final Activity activity) {
415
- if (CapacitorUpdaterPlugin.this._isAutoUpdateEnabled()) {
416
- new Thread(new Runnable(){
417
- @Override
418
- public void run() {
419
-
420
- Log.i(CapacitorUpdater.TAG, "Check for update via: " + CapacitorUpdaterPlugin.this.autoUpdateUrl);
421
- CapacitorUpdaterPlugin.this.implementation.getLatest(CapacitorUpdaterPlugin.this.autoUpdateUrl, (res) -> {
422
- try {
423
- if (res.has("message")) {
424
- Log.i(CapacitorUpdater.TAG, "message: " + res.get("message"));
425
- if (res.has("major") && res.getBoolean("major") && res.has("version")) {
426
- final JSObject majorAvailable = new JSObject();
427
- majorAvailable.put("version", (String) res.get("version"));
428
- CapacitorUpdaterPlugin.this.notifyListeners("majorAvailable", majorAvailable);
429
- }
430
- return;
431
- }
432
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
433
- final String latestVersionName = (String) res.get("version");
434
-
435
- if (latestVersionName != null && !"".equals(latestVersionName) && !current.getVersionName().equals(latestVersionName)) {
436
-
437
- final BundleInfo latest = CapacitorUpdaterPlugin.this.implementation.getBundleInfoByName(latestVersionName);
438
- if(latest != null) {
439
- if(latest.isErrorStatus()) {
440
- Log.e(CapacitorUpdater.TAG, "Latest bundle already exists, and is in error state. Aborting update.");
441
- return;
442
- }
443
- if(latest.isDownloaded()){
444
- Log.e(CapacitorUpdater.TAG, "Latest bundle already exists and download is NOT required. Update will occur next time app moves to background.");
445
- CapacitorUpdaterPlugin.this.implementation.setNextVersion(latest.getId());
446
- return;
447
- }
448
- }
449
-
450
-
451
- new Thread(new Runnable(){
452
- @Override
453
- public void run() {
454
- try {
455
- Log.i(CapacitorUpdater.TAG, "New bundle: " + latestVersionName + " found. Current is: " + current.getVersionName() + ". Update will occur next time app moves to background.");
456
-
457
- final String url = (String) res.get("url");
458
- final BundleInfo next = CapacitorUpdaterPlugin.this.implementation.download(url, latestVersionName);
459
-
460
- CapacitorUpdaterPlugin.this.implementation.setNextVersion(next.getId());
461
- } catch (final Exception e) {
462
- Log.e(CapacitorUpdater.TAG, "error downloading file", e);
463
- }
464
- }
465
- }).start();
466
- } else {
467
- Log.i(CapacitorUpdater.TAG, "No need to update, " + current + " is the latest bundle.");
468
- }
469
- } catch (final JSONException e) {
470
- Log.e(CapacitorUpdater.TAG, "error parsing JSON", e);
471
- }
472
- });
722
+ break;
723
+ case "kill":
724
+ if (killed) {
725
+ this._cancelDelay("kill check");
726
+ this.installNext();
727
+ }
728
+ break;
729
+ case "date":
730
+ if (!"".equals(value)) {
731
+ try {
732
+ final SimpleDateFormat sdf = new SimpleDateFormat(
733
+ "yyyy-MM-dd'T'HH:mm:ss.SSS"
734
+ );
735
+ Date date = sdf.parse(value);
736
+ assert date != null;
737
+ if (new Date().compareTo(date) > 0) {
738
+ this._cancelDelay("date expired");
473
739
  }
474
- }).start();
740
+ } catch (final Exception e) {
741
+ this._cancelDelay("date parsing issue");
742
+ }
743
+ } else {
744
+ this._cancelDelay("delayVal absent");
745
+ }
746
+ break;
747
+ case "nativeVersion":
748
+ if (!"".equals(value)) {
749
+ try {
750
+ final Version versionLimit = new Version(value);
751
+ if (this.currentVersionNative.isAtLeast(versionLimit)) {
752
+ this._cancelDelay("nativeVersion above limit");
753
+ }
754
+ } catch (final Exception e) {
755
+ this._cancelDelay("nativeVersion parsing issue");
756
+ }
757
+ } else {
758
+ this._cancelDelay("delayVal absent");
759
+ }
760
+ break;
475
761
  }
476
-
477
- this.checkAppReady();
762
+ }
478
763
  }
764
+ }
765
+
766
+ private Boolean _isAutoUpdateEnabled() {
767
+ final CapConfig config = CapConfig.loadDefault(this.getActivity());
768
+ String serverUrl = config.getServerUrl();
769
+ if (serverUrl != null && !"".equals(serverUrl)) {
770
+ // log warning autoupdate disabled when serverUrl is set
771
+ Log.w(
772
+ CapacitorUpdater.TAG,
773
+ "AutoUpdate is automatic disabled when serverUrl is set."
774
+ );
775
+ }
776
+ return (
777
+ CapacitorUpdaterPlugin.this.autoUpdate &&
778
+ !"".equals(CapacitorUpdaterPlugin.this.updateUrl) &&
779
+ serverUrl == null &&
780
+ !"".equals(serverUrl)
781
+ );
782
+ }
783
+
784
+ @PluginMethod
785
+ public void isAutoUpdateEnabled(final PluginCall call) {
786
+ try {
787
+ final JSObject ret = new JSObject();
788
+ ret.put("enabled", this._isAutoUpdateEnabled());
789
+ call.resolve(ret);
790
+ } catch (final Exception e) {
791
+ Log.e(CapacitorUpdater.TAG, "Could not get autoUpdate status", e);
792
+ call.reject("Could not get autoUpdate status", e);
793
+ }
794
+ }
795
+
796
+ private void checkAppReady() {
797
+ try {
798
+ if (this.appReadyCheck != null) {
799
+ this.appReadyCheck.interrupt();
800
+ }
801
+ this.appReadyCheck = new Thread(new DeferredNotifyAppReadyCheck());
802
+ this.appReadyCheck.start();
803
+ } catch (final Exception e) {
804
+ Log.e(
805
+ CapacitorUpdater.TAG,
806
+ "Failed to start " + DeferredNotifyAppReadyCheck.class.getName(),
807
+ e
808
+ );
809
+ }
810
+ }
811
+
812
+ private boolean isValidURL(String urlStr) {
813
+ try {
814
+ URL url = new URL(urlStr);
815
+ return true;
816
+ } catch (MalformedURLException e) {
817
+ return false;
818
+ }
819
+ }
479
820
 
480
- @Override // appMovedToBackground
481
- public void onActivityStopped(@NonNull final Activity activity) {
482
- Log.i(CapacitorUpdater.TAG, "Checking for pending update");
483
- try {
484
- final Boolean delayUpdate = this.prefs.getBoolean(DELAY_UPDATE, false);
485
- this.editor.putBoolean(DELAY_UPDATE, false);
486
- this.editor.commit();
487
-
488
- if (delayUpdate) {
489
- Log.i(CapacitorUpdater.TAG, "Update delayed to next backgrounding");
490
- return;
491
- }
492
-
493
- final BundleInfo fallback = this.implementation.getFallbackVersion();
494
- final BundleInfo current = this.implementation.getCurrentBundle();
495
- final BundleInfo next = this.implementation.getNextVersion();
496
-
497
- final Boolean success = current.getStatus() == BundleStatus.SUCCESS;
498
-
499
- Log.d(CapacitorUpdater.TAG, "Fallback bundle is: " + fallback);
500
- Log.d(CapacitorUpdater.TAG, "Current bundle is: " + current);
501
-
502
- if (next != null && !next.isErrorStatus() && (next.getId() != current.getId())) {
503
- // There is a next bundle waiting for activation
504
- Log.d(CapacitorUpdater.TAG, "Next bundle is: " + next.getVersionName());
505
- if (this.implementation.set(next) && this._reload()) {
506
- Log.i(CapacitorUpdater.TAG, "Updated to bundle: " + next.getVersionName());
507
- this.implementation.setNextVersion(null);
508
- } else {
509
- Log.e(CapacitorUpdater.TAG, "Update to bundle: " + next.getVersionName() + " Failed!");
510
- }
511
- } else if (!success) {
512
- // There is a no next bundle, and the current bundle has failed
513
-
514
- if(!current.isBuiltin()) {
515
- // Don't try to roll back the builtin bundle. Nothing we can do.
516
-
517
- this.implementation.rollback(current);
518
-
519
- Log.i(CapacitorUpdater.TAG, "Update failed: 'notifyAppReady()' was never called.");
520
- Log.i(CapacitorUpdater.TAG, "Bundle: " + current + ", is in error state.");
521
- Log.i(CapacitorUpdater.TAG, "Will fallback to: " + fallback + " on application restart.");
522
- Log.i(CapacitorUpdater.TAG, "Did you forget to call 'notifyAppReady()' in your Capacitor App code?");
523
- final JSObject ret = new JSObject();
524
- ret.put("bundle", current);
525
- this.notifyListeners("updateFailed", ret);
526
- this.implementation.sendStats("revert", current);
527
- if (!fallback.isBuiltin() && !fallback.equals(current)) {
528
- final Boolean res = this.implementation.set(fallback);
529
- if (res && this._reload()) {
530
- Log.i(CapacitorUpdater.TAG, "Revert to bundle: " + fallback.getVersionName());
531
- } else {
532
- Log.e(CapacitorUpdater.TAG, "Revert to bundle: " + fallback.getVersionName() + " Failed!");
533
- }
534
- } else {
535
- if (this._reset(false)) {
536
- Log.i(CapacitorUpdater.TAG, "Reverted to 'builtin' bundle.");
537
- }
821
+ private void backgroundDownload() {
822
+ new Thread(
823
+ new Runnable() {
824
+ @Override
825
+ public void run() {
826
+ Log.i(
827
+ CapacitorUpdater.TAG,
828
+ "Check for update via: " + CapacitorUpdaterPlugin.this.updateUrl
829
+ );
830
+ CapacitorUpdaterPlugin.this.implementation.getLatest(
831
+ CapacitorUpdaterPlugin.this.updateUrl,
832
+ res -> {
833
+ final BundleInfo current =
834
+ CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
835
+ try {
836
+ if (res.has("message")) {
837
+ Log.i(
838
+ CapacitorUpdater.TAG,
839
+ "message " + res.get("message")
840
+ );
841
+ if (
842
+ res.has("major") &&
843
+ res.getBoolean("major") &&
844
+ res.has("version")
845
+ ) {
846
+ final JSObject majorAvailable = new JSObject();
847
+ majorAvailable.put("version", res.getString("version"));
848
+ CapacitorUpdaterPlugin.this.notifyListeners(
849
+ "majorAvailable",
850
+ majorAvailable
851
+ );
538
852
  }
539
-
540
- if (this.autoDeleteFailed) {
541
- Log.i(CapacitorUpdater.TAG, "Deleting failing bundle: " + current.getVersionName());
853
+ final JSObject retNoNeed = new JSObject();
854
+ retNoNeed.put("bundle", current.toJSON());
855
+ CapacitorUpdaterPlugin.this.notifyListeners(
856
+ "noNeedUpdate",
857
+ retNoNeed
858
+ );
859
+ return;
860
+ }
861
+
862
+ if (
863
+ !res.has("url") ||
864
+ !CapacitorUpdaterPlugin.this.isValidURL(
865
+ res.getString("url")
866
+ )
867
+ ) {
868
+ Log.e(CapacitorUpdater.TAG, "Error no url or wrong format");
869
+ final JSObject retNoNeed = new JSObject();
870
+ retNoNeed.put("bundle", current.toJSON());
871
+ CapacitorUpdaterPlugin.this.notifyListeners(
872
+ "noNeedUpdate",
873
+ retNoNeed
874
+ );
875
+ }
876
+ final String latestVersionName = res.getString("version");
877
+
878
+ if (
879
+ latestVersionName != null &&
880
+ !"".equals(latestVersionName) &&
881
+ !current.getVersionName().equals(latestVersionName)
882
+ ) {
883
+ final BundleInfo latest =
884
+ CapacitorUpdaterPlugin.this.implementation.getBundleInfoByName(
885
+ latestVersionName
886
+ );
887
+ if (latest != null) {
888
+ if (latest.isErrorStatus()) {
889
+ Log.e(
890
+ CapacitorUpdater.TAG,
891
+ "Latest bundle already exists, and is in error state. Aborting update."
892
+ );
893
+ final JSObject retNoNeed = new JSObject();
894
+ retNoNeed.put("bundle", current.toJSON());
895
+ CapacitorUpdaterPlugin.this.notifyListeners(
896
+ "noNeedUpdate",
897
+ retNoNeed
898
+ );
899
+ return;
900
+ }
901
+ if (latest.isDownloaded()) {
902
+ Log.i(
903
+ CapacitorUpdater.TAG,
904
+ "Latest bundle already exists and download is NOT required. Update will occur next time app moves to background."
905
+ );
906
+ final JSObject ret = new JSObject();
907
+ ret.put("bundle", latest.toJSON());
908
+ CapacitorUpdaterPlugin.this.notifyListeners(
909
+ "updateAvailable",
910
+ ret
911
+ );
912
+ CapacitorUpdaterPlugin.this.implementation.setNextBundle(
913
+ latest.getId()
914
+ );
915
+ return;
916
+ }
917
+ if (latest.isDeleted()) {
918
+ Log.i(
919
+ CapacitorUpdater.TAG,
920
+ "Latest bundle already exists and will be deleted, download will overwrite it."
921
+ );
542
922
  try {
543
- final Boolean res = this.implementation.delete(current.getId());
544
- if (res) {
545
- Log.i(CapacitorUpdater.TAG, "Failed bundle deleted: " + current.getVersionName());
546
- }
923
+ final Boolean deleted =
924
+ CapacitorUpdaterPlugin.this.implementation.delete(
925
+ latest.getId(),
926
+ true
927
+ );
928
+ if (deleted) {
929
+ Log.i(
930
+ CapacitorUpdater.TAG,
931
+ "Failed bundle deleted: " +
932
+ latest.getVersionName()
933
+ );
934
+ }
547
935
  } catch (final IOException e) {
548
- Log.e(CapacitorUpdater.TAG, "Failed to delete failed bundle: " + current.getVersionName(), e);
936
+ Log.e(
937
+ CapacitorUpdater.TAG,
938
+ "Failed to delete failed bundle: " +
939
+ latest.getVersionName(),
940
+ e
941
+ );
549
942
  }
943
+ }
550
944
  }
551
- } else {
552
- // Nothing we can/should do by default if the 'builtin' bundle fails to call 'notifyAppReady()'.
553
- }
554
-
555
- } else if (!fallback.isBuiltin()) {
556
- // There is a no next bundle, and the current bundle has succeeded
557
- this.implementation.commit(current);
558
945
 
559
- if(this.autoDeletePrevious) {
560
- Log.i(CapacitorUpdater.TAG, "Bundle successfully loaded: " + current);
561
- try {
562
- final Boolean res = this.implementation.delete(fallback.getVersionName());
563
- if (res) {
564
- Log.i(CapacitorUpdater.TAG, "Deleted previous bundle: " + fallback.getVersionName());
946
+ new Thread(
947
+ new Runnable() {
948
+ @Override
949
+ public void run() {
950
+ try {
951
+ Log.i(
952
+ CapacitorUpdater.TAG,
953
+ "New bundle: " +
954
+ latestVersionName +
955
+ " found. Current is: " +
956
+ current.getVersionName() +
957
+ ". Update will occur next time app moves to background."
958
+ );
959
+
960
+ final String url = res.getString("url");
961
+ final String sessionKey = res.has("sessionKey")
962
+ ? res.getString("sessionKey")
963
+ : "";
964
+ final String checksum = res.has("checksum")
965
+ ? res.getString("checksum")
966
+ : "";
967
+ CapacitorUpdaterPlugin.this.implementation.downloadBackground(
968
+ url,
969
+ latestVersionName,
970
+ sessionKey,
971
+ checksum
972
+ );
973
+ } catch (final Exception e) {
974
+ Log.e(
975
+ CapacitorUpdater.TAG,
976
+ "error downloading file",
977
+ e
978
+ );
979
+ final JSObject ret = new JSObject();
980
+ ret.put("version", latestVersionName);
981
+ CapacitorUpdaterPlugin.this.notifyListeners(
982
+ "downloadFailed",
983
+ ret
984
+ );
985
+ final BundleInfo current =
986
+ CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
987
+ CapacitorUpdaterPlugin.this.implementation.sendStats(
988
+ "download_fail",
989
+ current.getVersionName()
990
+ );
991
+ final JSObject retNoNeed = new JSObject();
992
+ retNoNeed.put("bundle", current.toJSON());
993
+ CapacitorUpdaterPlugin.this.notifyListeners(
994
+ "noNeedUpdate",
995
+ retNoNeed
996
+ );
997
+ }
565
998
  }
566
- } catch (final IOException e) {
567
- Log.e(CapacitorUpdater.TAG, "Failed to delete previous bundle: " + fallback.getVersionName(), e);
568
- }
999
+ }
1000
+ )
1001
+ .start();
1002
+ } else {
1003
+ Log.i(
1004
+ CapacitorUpdater.TAG,
1005
+ "No need to update, " +
1006
+ current.getId() +
1007
+ " is the latest bundle."
1008
+ );
1009
+ final JSObject retNoNeed = new JSObject();
1010
+ retNoNeed.put("bundle", current.toJSON());
1011
+ CapacitorUpdaterPlugin.this.notifyListeners(
1012
+ "noNeedUpdate",
1013
+ retNoNeed
1014
+ );
1015
+ }
1016
+ } catch (final JSONException e) {
1017
+ Log.e(CapacitorUpdater.TAG, "error parsing JSON", e);
1018
+ final JSObject retNoNeed = new JSObject();
1019
+ retNoNeed.put("bundle", current.toJSON());
1020
+ CapacitorUpdaterPlugin.this.notifyListeners(
1021
+ "noNeedUpdate",
1022
+ retNoNeed
1023
+ );
569
1024
  }
570
- }
1025
+ }
1026
+ );
571
1027
  }
572
- catch(final Exception e) {
573
- Log.e(CapacitorUpdater.TAG, "Error during onActivityStopped", e);
1028
+ }
1029
+ )
1030
+ .start();
1031
+ }
1032
+
1033
+ private void installNext() {
1034
+ try {
1035
+ Gson gson = new Gson();
1036
+ String delayUpdatePreferences = prefs.getString(
1037
+ DELAY_CONDITION_PREFERENCES,
1038
+ "[]"
1039
+ );
1040
+ Type type = new TypeToken<ArrayList<DelayCondition>>() {}.getType();
1041
+ ArrayList<DelayCondition> delayConditionList = gson.fromJson(
1042
+ delayUpdatePreferences,
1043
+ type
1044
+ );
1045
+ if (delayConditionList != null && delayConditionList.size() != 0) {
1046
+ Log.i(CapacitorUpdater.TAG, "Update delayed to next backgrounding");
1047
+ return;
1048
+ }
1049
+ final BundleInfo current = this.implementation.getCurrentBundle();
1050
+ final BundleInfo next = this.implementation.getNextBundle();
1051
+
1052
+ if (
1053
+ next != null &&
1054
+ !next.isErrorStatus() &&
1055
+ !next.getId().equals(current.getId())
1056
+ ) {
1057
+ // There is a next bundle waiting for activation
1058
+ Log.d(CapacitorUpdater.TAG, "Next bundle is: " + next.getVersionName());
1059
+ if (this.implementation.set(next) && this._reload()) {
1060
+ Log.i(
1061
+ CapacitorUpdater.TAG,
1062
+ "Updated to bundle: " + next.getVersionName()
1063
+ );
1064
+ this.implementation.setNextBundle(null);
1065
+ } else {
1066
+ Log.e(
1067
+ CapacitorUpdater.TAG,
1068
+ "Update to bundle: " + next.getVersionName() + " Failed!"
1069
+ );
574
1070
  }
1071
+ }
1072
+ } catch (final Exception e) {
1073
+ Log.e(CapacitorUpdater.TAG, "Error during onActivityStopped", e);
575
1074
  }
1075
+ }
576
1076
 
577
- private class DeferredNotifyAppReadyCheck implements Runnable {
578
- @Override
579
- public void run() {
580
- try {
581
- Log.i(CapacitorUpdater.TAG, "Wait for " + CapacitorUpdaterPlugin.this.appReadyTimeout + "ms, then check for notifyAppReady");
582
- Thread.sleep(CapacitorUpdaterPlugin.this.appReadyTimeout);
583
- // Automatically roll back to fallback version if notifyAppReady has not been called yet
584
- final BundleInfo current = CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
585
- if(current.isBuiltin()) {
586
- Log.i(CapacitorUpdater.TAG, "Built-in bundle is active. Nothing to do.");
587
- return;
588
- }
589
-
590
- if(BundleStatus.SUCCESS != current.getStatus()) {
591
- Log.e(CapacitorUpdater.TAG, "notifyAppReady was not called, roll back current bundle: " + current.getId());
592
- CapacitorUpdaterPlugin.this.implementation.rollback(current);
593
- CapacitorUpdaterPlugin.this._reset(true);
594
- } else {
595
- Log.i(CapacitorUpdater.TAG, "notifyAppReady was called. This is fine: " + current.getId());
596
- }
1077
+ private void checkRevert() {
1078
+ // Automatically roll back to fallback version if notifyAppReady has not been called yet
1079
+ final BundleInfo current = this.implementation.getCurrentBundle();
597
1080
 
598
- CapacitorUpdaterPlugin.this.appReadyCheck = null;
599
- } catch (final InterruptedException e) {
600
- Log.e(CapacitorUpdater.TAG, DeferredNotifyAppReadyCheck.class.getName() + " was interrupted.");
601
- }
1081
+ if (current.isBuiltin()) {
1082
+ Log.i(CapacitorUpdater.TAG, "Built-in bundle is active. Nothing to do.");
1083
+ return;
1084
+ }
1085
+ Log.d(CapacitorUpdater.TAG, "Current bundle is: " + current);
1086
+
1087
+ if (BundleStatus.SUCCESS != current.getStatus()) {
1088
+ Log.e(
1089
+ CapacitorUpdater.TAG,
1090
+ "notifyAppReady was not called, roll back current bundle: " +
1091
+ current.getId()
1092
+ );
1093
+ Log.i(
1094
+ CapacitorUpdater.TAG,
1095
+ "Did you forget to call 'notifyAppReady()' in your Capacitor App code?"
1096
+ );
1097
+ final JSObject ret = new JSObject();
1098
+ ret.put("bundle", current.toJSON());
1099
+ this.notifyListeners("updateFailed", ret);
1100
+ this.implementation.sendStats("update_fail", current.getVersionName());
1101
+ this.implementation.setError(current);
1102
+ this._reset(true);
1103
+ if (
1104
+ CapacitorUpdaterPlugin.this.autoDeleteFailed && !current.isBuiltin()
1105
+ ) {
1106
+ Log.i(
1107
+ CapacitorUpdater.TAG,
1108
+ "Deleting failing bundle: " + current.getVersionName()
1109
+ );
1110
+ try {
1111
+ final Boolean res =
1112
+ this.implementation.delete(current.getId(), false);
1113
+ if (res) {
1114
+ Log.i(
1115
+ CapacitorUpdater.TAG,
1116
+ "Failed bundle deleted: " + current.getVersionName()
1117
+ );
1118
+ }
1119
+ } catch (final IOException e) {
1120
+ Log.e(
1121
+ CapacitorUpdater.TAG,
1122
+ "Failed to delete failed bundle: " + current.getVersionName(),
1123
+ e
1124
+ );
602
1125
  }
1126
+ }
1127
+ } else {
1128
+ Log.i(
1129
+ CapacitorUpdater.TAG,
1130
+ "notifyAppReady was called. This is fine: " + current.getId()
1131
+ );
603
1132
  }
1133
+ }
604
1134
 
605
- // not use but necessary here to remove warnings
606
- @Override
607
- public void onActivityResumed(@NonNull final Activity activity) {
608
- // TODO: Implement background updating based on `backgroundUpdate` and `backgroundUpdateDelay` capacitor.config.ts settings
609
- }
1135
+ private class DeferredNotifyAppReadyCheck implements Runnable {
610
1136
 
611
1137
  @Override
612
- public void onActivityPaused(@NonNull final Activity activity) {
613
- // TODO: Implement background updating based on `backgroundUpdate` and `backgroundUpdateDelay` capacitor.config.ts settings
1138
+ public void run() {
1139
+ try {
1140
+ Log.i(
1141
+ CapacitorUpdater.TAG,
1142
+ "Wait for " +
1143
+ CapacitorUpdaterPlugin.this.appReadyTimeout +
1144
+ "ms, then check for notifyAppReady"
1145
+ );
1146
+ Thread.sleep(CapacitorUpdaterPlugin.this.appReadyTimeout);
1147
+ CapacitorUpdaterPlugin.this.checkRevert();
1148
+ CapacitorUpdaterPlugin.this.appReadyCheck = null;
1149
+ } catch (final InterruptedException e) {
1150
+ Log.i(
1151
+ CapacitorUpdater.TAG,
1152
+ DeferredNotifyAppReadyCheck.class.getName() + " was interrupted."
1153
+ );
1154
+ }
614
1155
  }
615
- @Override
616
- public void onActivityCreated(@NonNull final Activity activity, @Nullable final Bundle savedInstanceState) {
1156
+ }
1157
+
1158
+ public void appMovedToForeground() {
1159
+ final BundleInfo current =
1160
+ CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
1161
+ CapacitorUpdaterPlugin.this.implementation.sendStats(
1162
+ "app_moved_to_foreground",
1163
+ current.getVersionName()
1164
+ );
1165
+ if (CapacitorUpdaterPlugin.this._isAutoUpdateEnabled()) {
1166
+ this.backgroundDownload();
1167
+ }
1168
+ this.checkAppReady();
1169
+ }
1170
+
1171
+ public void appMovedToBackground() {
1172
+ final BundleInfo current =
1173
+ CapacitorUpdaterPlugin.this.implementation.getCurrentBundle();
1174
+ CapacitorUpdaterPlugin.this.implementation.sendStats(
1175
+ "app_moved_to_background",
1176
+ current.getVersionName()
1177
+ );
1178
+ Log.i(CapacitorUpdater.TAG, "Checking for pending update");
1179
+ try {
1180
+ Gson gson = new Gson();
1181
+ String delayUpdatePreferences = prefs.getString(
1182
+ DELAY_CONDITION_PREFERENCES,
1183
+ "[]"
1184
+ );
1185
+ Type type = new TypeToken<ArrayList<DelayCondition>>() {}.getType();
1186
+ ArrayList<DelayCondition> delayConditionList = gson.fromJson(
1187
+ delayUpdatePreferences,
1188
+ type
1189
+ );
1190
+ String backgroundValue = null;
1191
+ for (DelayCondition delayCondition : delayConditionList) {
1192
+ if (delayCondition.getKind().toString().equals("background")) {
1193
+ String value = delayCondition.getValue();
1194
+ backgroundValue = (value != null && !value.isEmpty()) ? value : "0";
1195
+ }
1196
+ }
1197
+ if (backgroundValue != null) {
1198
+ taskRunning = true;
1199
+ final Long timeout = Long.parseLong(backgroundValue);
1200
+ if (backgroundTask != null) {
1201
+ backgroundTask.interrupt();
1202
+ }
1203
+ backgroundTask =
1204
+ new Thread(
1205
+ new Runnable() {
1206
+ @Override
1207
+ public void run() {
1208
+ try {
1209
+ Thread.sleep(timeout);
1210
+ taskRunning = false;
1211
+ _checkCancelDelay(false);
1212
+ installNext();
1213
+ } catch (InterruptedException e) {
1214
+ Log.i(
1215
+ CapacitorUpdater.TAG,
1216
+ "Background Task canceled, Activity resumed before timer completes"
1217
+ );
1218
+ }
1219
+ }
1220
+ }
1221
+ );
1222
+ backgroundTask.start();
1223
+ } else {
1224
+ this._checkCancelDelay(false);
1225
+ this.installNext();
1226
+ }
1227
+ } catch (final Exception e) {
1228
+ Log.e(CapacitorUpdater.TAG, "Error during onActivityStopped", e);
617
1229
  }
1230
+ }
618
1231
 
619
- @Override
620
- public void onActivitySaveInstanceState(@NonNull final Activity activity, @NonNull final Bundle outState) {
1232
+ private boolean isMainActivity() {
1233
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
1234
+ return false;
1235
+ }
1236
+ Context mContext = this.getContext();
1237
+ ActivityManager activityManager =
1238
+ (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
1239
+ List<ActivityManager.AppTask> runningTasks = activityManager.getAppTasks();
1240
+ ActivityManager.RecentTaskInfo runningTask = runningTasks
1241
+ .get(0)
1242
+ .getTaskInfo();
1243
+ String className = runningTask.baseIntent.getComponent().getClassName();
1244
+ String runningActivity = runningTask.topActivity.getClassName();
1245
+ boolean isThisAppActivity = className.equals(runningActivity);
1246
+ return isThisAppActivity;
1247
+ }
1248
+
1249
+ private void appKilled() {
1250
+ Log.d(CapacitorUpdater.TAG, "onActivityDestroyed: all activity destroyed");
1251
+ this._checkCancelDelay(true);
1252
+ }
1253
+
1254
+ @Override
1255
+ public void onActivityStarted(@NonNull final Activity activity) {
1256
+ if (isPreviousMainActivity) {
1257
+ this.appMovedToForeground();
1258
+ }
1259
+ isPreviousMainActivity = true;
1260
+ }
1261
+
1262
+ @Override
1263
+ public void onActivityStopped(@NonNull final Activity activity) {
1264
+ isPreviousMainActivity = isMainActivity();
1265
+ if (isPreviousMainActivity) {
1266
+ this.appMovedToBackground();
621
1267
  }
1268
+ }
622
1269
 
623
- @Override
624
- public void onActivityDestroyed(@NonNull final Activity activity) {
1270
+ @Override
1271
+ public void onActivityResumed(@NonNull final Activity activity) {
1272
+ if (backgroundTask != null && taskRunning) {
1273
+ backgroundTask.interrupt();
1274
+ }
1275
+ this.implementation.activity = activity;
1276
+ this.implementation.onResume();
1277
+ }
1278
+
1279
+ @Override
1280
+ public void onActivityPaused(@NonNull final Activity activity) {
1281
+ this.implementation.activity = activity;
1282
+ this.implementation.onPause();
1283
+ }
1284
+
1285
+ @Override
1286
+ public void onActivityCreated(
1287
+ @NonNull final Activity activity,
1288
+ @Nullable final Bundle savedInstanceState
1289
+ ) {
1290
+ this.implementation.activity = activity;
1291
+ this.counterActivityCreate++;
1292
+ }
1293
+
1294
+ @Override
1295
+ public void onActivitySaveInstanceState(
1296
+ @NonNull final Activity activity,
1297
+ @NonNull final Bundle outState
1298
+ ) {
1299
+ this.implementation.activity = activity;
1300
+ }
1301
+
1302
+ @Override
1303
+ public void onActivityDestroyed(@NonNull final Activity activity) {
1304
+ this.implementation.activity = activity;
1305
+ counterActivityCreate--;
1306
+ if (counterActivityCreate == 0) {
1307
+ this.appKilled();
625
1308
  }
1309
+ }
626
1310
  }