@capgo/capacitor-updater 9.0.0 → 9.0.2

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 +2406 -291
  4. package/android/build.gradle +37 -17
  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 +7927 -1243
  14. package/android/src/main/java/ee/forgr/capacitor_updater/CapgoUpdater.java +5785 -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 +2041 -118
  22. package/android/src/main/java/ee/forgr/capacitor_updater/DownloadWorkerManager.java +301 -0
  23. package/android/src/main/java/ee/forgr/capacitor_updater/HeadlessUpdateWorker.java +569 -0
  24. package/android/src/main/java/ee/forgr/capacitor_updater/Http3.java +436 -0
  25. package/android/src/main/java/ee/forgr/capacitor_updater/HttpEngineTransport.java +604 -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 +963 -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 +2641 -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 +6813 -0
  56. package/ios/Sources/CapacitorUpdaterPlugin/CapgoRawRsa.swift +36 -0
  57. package/ios/Sources/CapacitorUpdaterPlugin/CapgoSemanticVersion.swift +200 -0
  58. package/ios/Sources/CapacitorUpdaterPlugin/CapgoUpdater.swift +5099 -0
  59. package/ios/Sources/CapacitorUpdaterPlugin/CryptoCipher.swift +387 -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 +876 -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 +6533 -0
  76. package/ios/Tests/CapacitorUpdaterPluginTests/CapgoSemanticVersionTests.swift +64 -0
  77. package/ios/Tests/CapacitorUpdaterPluginTests/ChecksumRequiredTests.swift +156 -0
  78. package/ios/Tests/CapacitorUpdaterPluginTests/CliCryptoFixtureTests.swift +314 -0
  79. package/ios/Tests/CapacitorUpdaterPluginTests/HttpsOnlyBuiltinMinimumTests.swift +653 -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 +1109 -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 +196 -0
  89. package/ios/Tests/CapacitorUpdaterPluginTests/TestZipWriter.swift +235 -0
  90. package/ios/Tests/CapacitorUpdaterPluginTests/UpdateLifecycleTests.swift +470 -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
@@ -0,0 +1,40 @@
1
+ package ee.forgr.capacitor_updater;
2
+
3
+ import androidx.annotation.NonNull;
4
+ import okhttp3.HttpUrl;
5
+
6
+ final class StatsBatchFailureDiagnostics {
7
+
8
+ static final String STATUS_UNAVAILABLE = "unavailable";
9
+
10
+ private StatsBatchFailureDiagnostics() {}
11
+
12
+ @NonNull
13
+ private static String hostForOrigin(@NonNull final String host) {
14
+ if (host.indexOf(':') >= 0) {
15
+ return "[" + host + "]";
16
+ }
17
+ return host;
18
+ }
19
+
20
+ @NonNull
21
+ static String safeDestinationUrl(@NonNull HttpUrl url) {
22
+ final String scheme = url.scheme();
23
+ final int port = url.port();
24
+ final String host = hostForOrigin(url.host());
25
+ if (port == HttpUrl.defaultPort(scheme)) {
26
+ return scheme + "://" + host;
27
+ }
28
+ return scheme + "://" + host + ":" + port;
29
+ }
30
+
31
+ @NonNull
32
+ static String formatFailureMessage(
33
+ @NonNull final String messagePrefix,
34
+ @NonNull final String safeDestination,
35
+ @NonNull final String status,
36
+ final long elapsedMs
37
+ ) {
38
+ return messagePrefix + " destination=" + safeDestination + " status=" + status + " elapsedMs=" + elapsedMs;
39
+ }
40
+ }
@@ -0,0 +1,323 @@
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
+ package ee.forgr.capacitor_updater;
8
+
9
+ import android.view.ActionMode;
10
+ import android.view.KeyEvent;
11
+ import android.view.KeyboardShortcutGroup;
12
+ import android.view.Menu;
13
+ import android.view.MenuItem;
14
+ import android.view.MotionEvent;
15
+ import android.view.SearchEvent;
16
+ import android.view.View;
17
+ import android.view.Window;
18
+ import android.view.WindowManager;
19
+ import android.view.accessibility.AccessibilityEvent;
20
+ import com.getcapacitor.BridgeActivity;
21
+ import java.lang.ref.WeakReference;
22
+ import java.util.List;
23
+
24
+ public class ThreeFingerPinchDetector {
25
+
26
+ public interface Listener {
27
+ void onThreeFingerPinchDetected();
28
+ }
29
+
30
+ private static final int REQUIRED_POINTER_COUNT = 3;
31
+ private static final float MIN_SCALE_DELTA = 0.12f;
32
+ private static final long PINCH_TIMEOUT = 1000;
33
+
34
+ private final Listener listener;
35
+ private final Logger logger;
36
+ private Window targetWindow;
37
+ private Window.Callback previousWindowCallback;
38
+ private Window.Callback windowCallback;
39
+ private WeakReference<ThreeFingerPinchDetector> detectorReference;
40
+ private float initialSpan = 0;
41
+ private boolean tracking = false;
42
+ private boolean triggered = false;
43
+ private long lastPinchTime = 0;
44
+
45
+ public ThreeFingerPinchDetector(Listener listener, Logger logger) {
46
+ this.listener = listener;
47
+ this.logger = logger;
48
+ }
49
+
50
+ public void start(BridgeActivity activity) {
51
+ if (targetWindow != null) {
52
+ stop();
53
+ }
54
+
55
+ Window window = activity.getWindow();
56
+ if (window == null) {
57
+ logger.warn("Three finger pinch detector could not find a target window");
58
+ return;
59
+ }
60
+
61
+ this.targetWindow = window;
62
+ this.previousWindowCallback = window.getCallback();
63
+ this.detectorReference = new WeakReference<>(this);
64
+ this.windowCallback = new PinchWindowCallback(this.previousWindowCallback, this.detectorReference);
65
+ window.setCallback(this.windowCallback);
66
+ logger.info("Three finger pinch detector installed on activity window");
67
+ }
68
+
69
+ public void stop() {
70
+ if (targetWindow != null) {
71
+ if (windowCallback instanceof PinchWindowCallback) {
72
+ ((PinchWindowCallback) windowCallback).disable();
73
+ }
74
+ if (detectorReference != null) {
75
+ detectorReference.clear();
76
+ }
77
+ if (targetWindow.getCallback() == windowCallback) {
78
+ targetWindow.setCallback(previousWindowCallback);
79
+ }
80
+ targetWindow = null;
81
+ previousWindowCallback = null;
82
+ windowCallback = null;
83
+ detectorReference = null;
84
+ }
85
+ reset();
86
+ }
87
+
88
+ private void handleTouch(MotionEvent event) {
89
+ int action = event.getActionMasked();
90
+ if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_POINTER_UP) {
91
+ reset();
92
+ return;
93
+ }
94
+
95
+ if (event.getPointerCount() != REQUIRED_POINTER_COUNT) {
96
+ if (action == MotionEvent.ACTION_POINTER_DOWN) {
97
+ reset();
98
+ }
99
+ return;
100
+ }
101
+
102
+ float span = calculateSpan(event);
103
+ if (span <= 0) {
104
+ return;
105
+ }
106
+
107
+ if (!tracking || action == MotionEvent.ACTION_POINTER_DOWN) {
108
+ initialSpan = span;
109
+ tracking = true;
110
+ triggered = false;
111
+ logger.info("Three finger pinch tracking started");
112
+ return;
113
+ }
114
+
115
+ if (!triggered && Math.abs(span - initialSpan) / initialSpan >= MIN_SCALE_DELTA) {
116
+ long currentTime = System.currentTimeMillis();
117
+ if (currentTime - lastPinchTime > PINCH_TIMEOUT) {
118
+ triggered = true;
119
+ lastPinchTime = currentTime;
120
+ logger.info("Three finger pinch threshold reached");
121
+ if (listener != null) {
122
+ listener.onThreeFingerPinchDetected();
123
+ }
124
+ }
125
+ }
126
+ }
127
+
128
+ private float calculateSpan(MotionEvent event) {
129
+ float centerX = 0;
130
+ float centerY = 0;
131
+ for (int i = 0; i < REQUIRED_POINTER_COUNT; i++) {
132
+ centerX += event.getX(i);
133
+ centerY += event.getY(i);
134
+ }
135
+ centerX /= REQUIRED_POINTER_COUNT;
136
+ centerY /= REQUIRED_POINTER_COUNT;
137
+
138
+ float totalDistance = 0;
139
+ for (int i = 0; i < REQUIRED_POINTER_COUNT; i++) {
140
+ float dx = event.getX(i) - centerX;
141
+ float dy = event.getY(i) - centerY;
142
+ totalDistance += Math.sqrt(dx * dx + dy * dy);
143
+ }
144
+ return totalDistance / REQUIRED_POINTER_COUNT;
145
+ }
146
+
147
+ private void reset() {
148
+ initialSpan = 0;
149
+ tracking = false;
150
+ triggered = false;
151
+ }
152
+
153
+ private static class PinchWindowCallback implements Window.Callback {
154
+
155
+ private final Window.Callback delegate;
156
+ private final WeakReference<ThreeFingerPinchDetector> detectorReference;
157
+ private boolean enabled = true;
158
+
159
+ PinchWindowCallback(Window.Callback delegate, WeakReference<ThreeFingerPinchDetector> detectorReference) {
160
+ this.delegate = delegate;
161
+ this.detectorReference = detectorReference;
162
+ }
163
+
164
+ void disable() {
165
+ enabled = false;
166
+ if (detectorReference != null) {
167
+ detectorReference.clear();
168
+ }
169
+ }
170
+
171
+ @Override
172
+ public boolean dispatchKeyEvent(KeyEvent event) {
173
+ return delegate != null && delegate.dispatchKeyEvent(event);
174
+ }
175
+
176
+ @Override
177
+ public boolean dispatchKeyShortcutEvent(KeyEvent event) {
178
+ return delegate != null && delegate.dispatchKeyShortcutEvent(event);
179
+ }
180
+
181
+ @Override
182
+ public boolean dispatchTouchEvent(MotionEvent event) {
183
+ boolean handled = delegate != null && delegate.dispatchTouchEvent(event);
184
+ if (enabled) {
185
+ ThreeFingerPinchDetector detector = detectorReference == null ? null : detectorReference.get();
186
+ if (detector != null) {
187
+ detector.handleTouch(event);
188
+ }
189
+ }
190
+ return handled;
191
+ }
192
+
193
+ @Override
194
+ public boolean dispatchTrackballEvent(MotionEvent event) {
195
+ return delegate != null && delegate.dispatchTrackballEvent(event);
196
+ }
197
+
198
+ @Override
199
+ public boolean dispatchGenericMotionEvent(MotionEvent event) {
200
+ return delegate != null && delegate.dispatchGenericMotionEvent(event);
201
+ }
202
+
203
+ @Override
204
+ public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
205
+ return delegate != null && delegate.dispatchPopulateAccessibilityEvent(event);
206
+ }
207
+
208
+ @Override
209
+ public View onCreatePanelView(int featureId) {
210
+ return delegate == null ? null : delegate.onCreatePanelView(featureId);
211
+ }
212
+
213
+ @Override
214
+ public boolean onCreatePanelMenu(int featureId, Menu menu) {
215
+ return delegate != null && delegate.onCreatePanelMenu(featureId, menu);
216
+ }
217
+
218
+ @Override
219
+ public boolean onPreparePanel(int featureId, View view, Menu menu) {
220
+ return delegate != null && delegate.onPreparePanel(featureId, view, menu);
221
+ }
222
+
223
+ @Override
224
+ public boolean onMenuOpened(int featureId, Menu menu) {
225
+ return delegate != null && delegate.onMenuOpened(featureId, menu);
226
+ }
227
+
228
+ @Override
229
+ public boolean onMenuItemSelected(int featureId, MenuItem item) {
230
+ return delegate != null && delegate.onMenuItemSelected(featureId, item);
231
+ }
232
+
233
+ @Override
234
+ public void onWindowAttributesChanged(WindowManager.LayoutParams attrs) {
235
+ if (delegate != null) {
236
+ delegate.onWindowAttributesChanged(attrs);
237
+ }
238
+ }
239
+
240
+ @Override
241
+ public void onContentChanged() {
242
+ if (delegate != null) {
243
+ delegate.onContentChanged();
244
+ }
245
+ }
246
+
247
+ @Override
248
+ public void onWindowFocusChanged(boolean hasFocus) {
249
+ if (delegate != null) {
250
+ delegate.onWindowFocusChanged(hasFocus);
251
+ }
252
+ }
253
+
254
+ @Override
255
+ public void onAttachedToWindow() {
256
+ if (delegate != null) {
257
+ delegate.onAttachedToWindow();
258
+ }
259
+ }
260
+
261
+ @Override
262
+ public void onDetachedFromWindow() {
263
+ if (delegate != null) {
264
+ delegate.onDetachedFromWindow();
265
+ }
266
+ }
267
+
268
+ @Override
269
+ public void onPanelClosed(int featureId, Menu menu) {
270
+ if (delegate != null) {
271
+ delegate.onPanelClosed(featureId, menu);
272
+ }
273
+ }
274
+
275
+ @Override
276
+ public boolean onSearchRequested() {
277
+ return delegate != null && delegate.onSearchRequested();
278
+ }
279
+
280
+ @Override
281
+ public boolean onSearchRequested(SearchEvent searchEvent) {
282
+ return delegate != null && delegate.onSearchRequested(searchEvent);
283
+ }
284
+
285
+ @Override
286
+ public ActionMode onWindowStartingActionMode(ActionMode.Callback callback) {
287
+ return delegate == null ? null : delegate.onWindowStartingActionMode(callback);
288
+ }
289
+
290
+ @Override
291
+ public ActionMode onWindowStartingActionMode(ActionMode.Callback callback, int type) {
292
+ return delegate == null ? null : delegate.onWindowStartingActionMode(callback, type);
293
+ }
294
+
295
+ @Override
296
+ public void onActionModeStarted(ActionMode mode) {
297
+ if (delegate != null) {
298
+ delegate.onActionModeStarted(mode);
299
+ }
300
+ }
301
+
302
+ @Override
303
+ public void onActionModeFinished(ActionMode mode) {
304
+ if (delegate != null) {
305
+ delegate.onActionModeFinished(mode);
306
+ }
307
+ }
308
+
309
+ @Override
310
+ public void onProvideKeyboardShortcuts(List<KeyboardShortcutGroup> data, Menu menu, int deviceId) {
311
+ if (delegate != null) {
312
+ delegate.onProvideKeyboardShortcuts(data, menu, deviceId);
313
+ }
314
+ }
315
+
316
+ @Override
317
+ public void onPointerCaptureChanged(boolean hasCapture) {
318
+ if (delegate != null) {
319
+ delegate.onPointerCaptureChanged(hasCapture);
320
+ }
321
+ }
322
+ }
323
+ }
@@ -0,0 +1,306 @@
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
+ * Parsing and comparison logic ported from version-compare 1.5.0
7
+ * (https://github.com/G00fY2/version-compare), Copyright G00fY2,
8
+ * licensed under the Apache License, Version 2.0
9
+ * (https://www.apache.org/licenses/LICENSE-2.0).
10
+ */
11
+
12
+ package ee.forgr.capacitor_updater;
13
+
14
+ import androidx.annotation.NonNull;
15
+ import androidx.annotation.Nullable;
16
+ import java.util.ArrayList;
17
+ import java.util.List;
18
+ import java.util.Locale;
19
+
20
+ /**
21
+ * Lenient version parser and comparator.
22
+ *
23
+ * <p>Behavior-compatible port of {@code io.github.g00fy2:versioncompare:1.5.0} (Apache-2.0), kept in-repo so the
24
+ * plugin does not ship an extra third-party dependency. Parsing never throws for non-null input that starts with a
25
+ * digit; unparsable input (null or not starting with a digit) yields an empty version equal to {@code 0}.
26
+ *
27
+ * <p>Pre-release suffix ordering: {@code snapshot < pre-alpha < alpha < beta < rc < stable}, with an optional number
28
+ * right after the qualifier ({@code 1.0.0-rc2 > 1.0.0-rc1}).
29
+ */
30
+ public class Version implements Comparable<Version> {
31
+
32
+ enum ReleaseType {
33
+ SNAPSHOT,
34
+ PRE_ALPHA,
35
+ ALPHA,
36
+ BETA,
37
+ RC,
38
+ STABLE
39
+ }
40
+
41
+ private static final String SNAPSHOT_STRING = "snapshot";
42
+ private static final String PRE_STRING = "pre";
43
+ private static final String ALPHA_STRING = "alpha";
44
+ private static final String BETA_STRING = "beta";
45
+ private static final String RC_STRING = "rc";
46
+
47
+ @Nullable
48
+ private final String originalString;
49
+
50
+ private final List<Long> subversionNumbers = new ArrayList<>();
51
+ private final List<Long> trimmedSubversionNumbers = new ArrayList<>();
52
+ private final String suffix;
53
+ private final ReleaseType releaseType;
54
+ private final long preReleaseVersion;
55
+
56
+ public Version(@Nullable String versionString) {
57
+ originalString = versionString;
58
+ if (originalString != null && startsNumeric(originalString)) {
59
+ String[] versionTokens = originalString.replaceAll("\\s", "").split("\\.");
60
+ boolean suffixFound = false;
61
+ StringBuilder suffixSb = null;
62
+
63
+ for (String versionToken : versionTokens) {
64
+ if (suffixFound) {
65
+ suffixSb.append(".");
66
+ suffixSb.append(versionToken);
67
+ } else if (isNumeric(versionToken)) {
68
+ subversionNumbers.add(safeParseLong(versionToken));
69
+ } else {
70
+ for (int i = 0; i < versionToken.length(); i++) {
71
+ if (!Character.isDigit(versionToken.charAt(i))) {
72
+ suffixSb = new StringBuilder();
73
+ if (i > 0) {
74
+ subversionNumbers.add(safeParseLong(versionToken.substring(0, i)));
75
+ suffixSb.append(versionToken.substring(i));
76
+ } else {
77
+ suffixSb.append(versionToken);
78
+ }
79
+ suffixFound = true;
80
+ break;
81
+ }
82
+ }
83
+ }
84
+ }
85
+ suffix = suffixSb != null ? suffixSb.toString() : "";
86
+ trimmedSubversionNumbers.addAll(subversionNumbers);
87
+ while (!trimmedSubversionNumbers.isEmpty() && trimmedSubversionNumbers.get(trimmedSubversionNumbers.size() - 1) == 0L) {
88
+ trimmedSubversionNumbers.remove(trimmedSubversionNumbers.size() - 1);
89
+ }
90
+ } else {
91
+ suffix = "";
92
+ }
93
+ releaseType = qualifierToReleaseType(suffix);
94
+ preReleaseVersion = preReleaseVersion(suffix, releaseType);
95
+ }
96
+
97
+ public long getMajor() {
98
+ return trimmedSubversionNumbers.size() > 0 ? trimmedSubversionNumbers.get(0) : 0L;
99
+ }
100
+
101
+ public long getMinor() {
102
+ return trimmedSubversionNumbers.size() > 1 ? trimmedSubversionNumbers.get(1) : 0L;
103
+ }
104
+
105
+ public long getPatch() {
106
+ return trimmedSubversionNumbers.size() > 2 ? trimmedSubversionNumbers.get(2) : 0L;
107
+ }
108
+
109
+ @NonNull
110
+ public List<Long> getSubversionNumbers() {
111
+ return subversionNumbers;
112
+ }
113
+
114
+ @NonNull
115
+ public String getSuffix() {
116
+ return suffix;
117
+ }
118
+
119
+ @Nullable
120
+ public String getOriginalString() {
121
+ return originalString;
122
+ }
123
+
124
+ public boolean isHigherThan(String otherVersion) {
125
+ return isHigherThan(new Version(otherVersion));
126
+ }
127
+
128
+ public boolean isHigherThan(Version otherVersion) {
129
+ return compareTo(otherVersion) > 0;
130
+ }
131
+
132
+ public boolean isLowerThan(String otherVersion) {
133
+ return isLowerThan(new Version(otherVersion));
134
+ }
135
+
136
+ public boolean isLowerThan(Version otherVersion) {
137
+ return compareTo(otherVersion) < 0;
138
+ }
139
+
140
+ public boolean isEqual(String otherVersion) {
141
+ return isEqual(new Version(otherVersion));
142
+ }
143
+
144
+ public boolean isEqual(Version otherVersion) {
145
+ return compareTo(otherVersion) == 0;
146
+ }
147
+
148
+ public boolean isAtLeast(String otherVersion) {
149
+ return isAtLeast(new Version(otherVersion));
150
+ }
151
+
152
+ public boolean isAtLeast(Version otherVersion) {
153
+ return compareTo(otherVersion) >= 0;
154
+ }
155
+
156
+ public boolean isAtLeast(String otherVersion, boolean ignoreSuffix) {
157
+ return isAtLeast(new Version(otherVersion), ignoreSuffix);
158
+ }
159
+
160
+ public boolean isAtLeast(Version otherVersion, boolean ignoreSuffix) {
161
+ return compareTo(otherVersion, ignoreSuffix) >= 0;
162
+ }
163
+
164
+ @Override
165
+ public final int compareTo(@NonNull Version version) {
166
+ return compareTo(version, false);
167
+ }
168
+
169
+ private int compareTo(@NonNull Version version, boolean ignoreSuffix) {
170
+ int versionNumberResult = compareSubversionNumbers(trimmedSubversionNumbers, version.trimmedSubversionNumbers);
171
+ if (versionNumberResult != 0 || ignoreSuffix) {
172
+ return versionNumberResult;
173
+ }
174
+ int releaseTypeResult = releaseType.compareTo(version.releaseType);
175
+ if (releaseTypeResult != 0) {
176
+ return releaseTypeResult;
177
+ }
178
+ return Long.compare(preReleaseVersion, version.preReleaseVersion);
179
+ }
180
+
181
+ @Override
182
+ public final boolean equals(Object o) {
183
+ return o instanceof Version && isEqual((Version) o);
184
+ }
185
+
186
+ @Override
187
+ public final int hashCode() {
188
+ int result = trimmedSubversionNumbers.hashCode();
189
+ result = 31 * result + releaseType.hashCode();
190
+ result = 31 * result + (int) (preReleaseVersion ^ (preReleaseVersion >>> 32));
191
+ return result;
192
+ }
193
+
194
+ @NonNull
195
+ @Override
196
+ public String toString() {
197
+ return String.valueOf(originalString);
198
+ }
199
+
200
+ // helpers
201
+
202
+ private static int compareSubversionNumbers(@NonNull final List<Long> versionNumbersA, @NonNull final List<Long> versionNumbersB) {
203
+ final int numbersSizeA = versionNumbersA.size();
204
+ final int numbersSizeB = versionNumbersB.size();
205
+ final int maxSize = Math.max(numbersSizeA, numbersSizeB);
206
+
207
+ for (int i = 0; i < maxSize; i++) {
208
+ final long a = i < numbersSizeA ? versionNumbersA.get(i) : 0L;
209
+ final long b = i < numbersSizeB ? versionNumbersB.get(i) : 0L;
210
+ if (a > b) {
211
+ return 1;
212
+ } else if (a < b) {
213
+ return -1;
214
+ }
215
+ }
216
+ return 0;
217
+ }
218
+
219
+ static ReleaseType qualifierToReleaseType(@NonNull String suffix) {
220
+ if (suffix.length() > 0) {
221
+ suffix = suffix.toLowerCase(Locale.ROOT);
222
+ if (suffix.contains(RC_STRING)) return ReleaseType.RC;
223
+ if (suffix.contains(BETA_STRING)) return ReleaseType.BETA;
224
+ if (suffix.contains(ALPHA_STRING)) {
225
+ if (suffix.substring(0, suffix.indexOf(ALPHA_STRING)).contains(PRE_STRING)) {
226
+ return ReleaseType.PRE_ALPHA;
227
+ }
228
+ return ReleaseType.ALPHA;
229
+ }
230
+ if (suffix.contains(SNAPSHOT_STRING)) return ReleaseType.SNAPSHOT;
231
+ }
232
+ return ReleaseType.STABLE;
233
+ }
234
+
235
+ private static long preReleaseVersion(@NonNull final String suffix, final ReleaseType releaseType) {
236
+ if (releaseType == ReleaseType.STABLE || releaseType == ReleaseType.SNAPSHOT) return 0;
237
+
238
+ final int startIndex = indexOfQualifier(suffix, releaseType);
239
+ if (startIndex < suffix.length()) {
240
+ final int maxStartIndex = Math.min(startIndex + 2, suffix.length());
241
+ if (containsNumeric(suffix.substring(startIndex, maxStartIndex))) {
242
+ final StringBuilder versionNumber = new StringBuilder();
243
+ for (int i = startIndex; i < suffix.length(); i++) {
244
+ final char c = suffix.charAt(i);
245
+ if (Character.isDigit(c)) {
246
+ versionNumber.append(c);
247
+ } else if (i != startIndex) {
248
+ break;
249
+ }
250
+ }
251
+ return safeParseLong(versionNumber.toString());
252
+ }
253
+ }
254
+ return 0;
255
+ }
256
+
257
+ private static int indexOfQualifier(@NonNull String suffix, final ReleaseType releaseType) {
258
+ suffix = suffix.toLowerCase(Locale.ROOT);
259
+ switch (releaseType) {
260
+ case RC:
261
+ return suffix.indexOf(RC_STRING) + RC_STRING.length();
262
+ case BETA:
263
+ return suffix.indexOf(BETA_STRING) + BETA_STRING.length();
264
+ case ALPHA:
265
+ case PRE_ALPHA:
266
+ return suffix.indexOf(ALPHA_STRING) + ALPHA_STRING.length();
267
+ default:
268
+ return 0;
269
+ }
270
+ }
271
+
272
+ private static boolean startsNumeric(@NonNull String str) {
273
+ str = str.trim();
274
+ return str.length() > 0 && Character.isDigit(str.charAt(0));
275
+ }
276
+
277
+ private static long safeParseLong(@NonNull String numbers) {
278
+ if (numbers.length() > 19) {
279
+ numbers = numbers.substring(0, 19);
280
+ }
281
+ return Long.parseLong(numbers);
282
+ }
283
+
284
+ private static boolean isNumeric(@NonNull final CharSequence cs) {
285
+ final int sz = cs.length();
286
+ if (sz > 0) {
287
+ for (int i = 0; i < sz; i++) {
288
+ if (!Character.isDigit(cs.charAt(i))) {
289
+ return false;
290
+ }
291
+ }
292
+ return true;
293
+ }
294
+ return false;
295
+ }
296
+
297
+ private static boolean containsNumeric(@NonNull final CharSequence cs) {
298
+ final int sz = cs.length();
299
+ for (int i = 0; i < sz; i++) {
300
+ if (Character.isDigit(cs.charAt(i))) {
301
+ return true;
302
+ }
303
+ }
304
+ return false;
305
+ }
306
+ }