-
-
Notifications
You must be signed in to change notification settings - Fork 262
/
upgrader.dart
860 lines (728 loc) · 26.6 KB
/
upgrader.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
/*
* Copyright (c) 2018-2023 Larry Aasen. All rights reserved.
*/
import 'dart:async';
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:version/version.dart';
import 'appcast.dart';
import 'itunes_search_api.dart';
import 'play_store_search_api.dart';
import 'upgrade_os.dart';
import 'upgrade_messages.dart';
/// Signature of callbacks that have no arguments and return bool.
typedef BoolCallback = bool Function();
/// Signature of callbacks that have a bool argument and no return.
typedef VoidBoolCallback = void Function(bool value);
/// Signature of callback for willDisplayUpgrade. Includes display,
/// minAppVersion, installedVersion, and appStoreVersion.
typedef WillDisplayUpgradeCallback = void Function(
{required bool display,
String? minAppVersion,
String? installedVersion,
String? appStoreVersion});
/// The type of data in the stream.
typedef UpgraderEvaluateNeed = bool;
/// There are two different dialog styles: Cupertino and Material
enum UpgradeDialogStyle { cupertino, material }
/// A class to define the configuration for the appcast. The configuration
/// contains two parts: a URL to the appcast, and a list of supported OS
/// names, such as "android", "fuchsia", "ios", "linux" "macos", "web", "windows".
class AppcastConfiguration {
final List<String>? supportedOS;
final String? url;
AppcastConfiguration({
this.supportedOS,
this.url,
});
}
/// Creates a shared instance of [Upgrader].
Upgrader _sharedInstance = Upgrader();
/// A class to configure the upgrade dialog.
class Upgrader with WidgetsBindingObserver {
/// Provide an Appcast that can be replaced for mock testing.
final Appcast? appcast;
/// The appcast configuration ([AppcastConfiguration]) used by [Appcast].
/// When an appcast is configured for iOS, the iTunes lookup is not used.
final AppcastConfiguration? appcastConfig;
/// Can alert dialog be dismissed on tap outside of the alert dialog. Not used by [UpgradeCard]. (default: false)
bool canDismissDialog;
/// Provide an HTTP Client that can be replaced for mock testing.
final http.Client client;
/// The country code that will override the system locale. Optional.
final String? countryCode;
/// The country code that will override the system locale. Optional. Used only for Android.
final String? languageCode;
/// For debugging, always force the upgrade to be available.
bool debugDisplayAlways;
/// For debugging, display the upgrade at least once once.
bool debugDisplayOnce;
/// Enable print statements for debugging.
bool debugLogging;
/// The upgrade dialog style. Used only on UpgradeAlert. (default: material)
UpgradeDialogStyle dialogStyle;
/// Duration until alerting user again
final Duration durationUntilAlertAgain;
/// The localized messages used for display in upgrader.
UpgraderMessages messages;
/// The minimum app version supported by this app. Earlier versions of this app
/// will be forced to update to the current version. Optional.
String? minAppVersion;
/// Called when the ignore button is tapped or otherwise activated.
/// Return false when the default behavior should not execute.
BoolCallback? onIgnore;
/// Called when the later button is tapped or otherwise activated.
/// Return false when the default behavior should not execute.
BoolCallback? onLater;
/// Called when the update button is tapped or otherwise activated.
/// Return false when the default behavior should not execute.
BoolCallback? onUpdate;
/// Called when the user taps outside of the dialog and [canDismissDialog]
/// is false. Also called when the back button is pressed. Return true for
/// the screen to be popped. Not used by [UpgradeCard].
BoolCallback? shouldPopScope;
/// Hide or show Ignore button on dialog (default: true)
bool showIgnore;
/// Hide or show Later button on dialog (default: true)
bool showLater;
/// Hide or show release notes (default: true)
bool showReleaseNotes;
/// The text style for the cupertino dialog buttons. Used only for
/// [UpgradeDialogStyle.cupertino]. Optional.
TextStyle? cupertinoButtonTextStyle;
/// Called when [Upgrader] determines that an upgrade may or may not be
/// displayed. The [value] parameter will be true when it should be displayed,
/// and false when it should not be displayed. One good use for this callback
/// is logging metrics for your app.
WillDisplayUpgradeCallback? willDisplayUpgrade;
/// Provides information on which OS this code is running on.
final UpgraderOS upgraderOS;
bool _displayed = false;
bool _initCalled = false;
PackageInfo? _packageInfo;
String? _installedVersion;
String? _appStoreVersion;
String? _appStoreListingURL;
String? _releaseNotes;
String? _updateAvailable;
DateTime? _lastTimeAlerted;
String? _lastVersionAlerted;
String? _userIgnoredVersion;
bool _hasAlerted = false;
bool _isCriticalUpdate = false;
/// Track the initialization future so that [initialize] can be called multiple times.
Future<bool>? _futureInit;
/// A stream that provides a series of values each time an evaluation should be performed.
/// The values will always be null or true.
final _streamController = StreamController<UpgraderEvaluateNeed>();
Stream<UpgraderEvaluateNeed> get evaluationStream => _streamController.stream;
final notInitializedExceptionMessage =
'initialize() not called. Must be called first.';
Upgrader({
this.appcastConfig,
this.appcast,
UpgraderMessages? messages,
this.debugDisplayAlways = false,
this.debugDisplayOnce = false,
this.debugLogging = false,
this.durationUntilAlertAgain = const Duration(days: 3),
this.onIgnore,
this.onLater,
this.onUpdate,
this.shouldPopScope,
this.willDisplayUpgrade,
http.Client? client,
this.showIgnore = true,
this.showLater = true,
this.showReleaseNotes = true,
this.canDismissDialog = false,
this.countryCode,
this.languageCode,
this.minAppVersion,
this.dialogStyle = UpgradeDialogStyle.material,
this.cupertinoButtonTextStyle,
UpgraderOS? upgraderOS,
}) : client = client ?? http.Client(),
messages = messages ?? UpgraderMessages(),
upgraderOS = upgraderOS ?? UpgraderOS() {
if (debugLogging) print("upgrader: instantiated.");
}
/// A shared instance of [Upgrader].
static Upgrader get sharedInstance => _sharedInstance;
void installPackageInfo({PackageInfo? packageInfo}) {
_packageInfo = packageInfo;
_initCalled = false;
}
void installAppStoreVersion(String version) {
_appStoreVersion = version;
}
void installAppStoreListingURL(String url) {
_appStoreListingURL = url;
}
/// Initialize [Upgrader] by getting saved preferences, getting platform package info, and getting
/// released version info.
Future<bool> initialize() async {
if (debugLogging) {
print('upgrader: initialize called');
}
if (_futureInit != null) return _futureInit!;
_futureInit = Future(() async {
if (debugLogging) {
print('upgrader: initializing');
}
if (_initCalled) {
assert(false, 'This should never happen.');
return true;
}
_initCalled = true;
if (messages.languageCode.isEmpty) {
print('upgrader: error -> languageCode is empty');
} else if (debugLogging) {
print('upgrader: languageCode: ${messages.languageCode}');
}
await _getSavedPrefs();
if (debugLogging) {
print('upgrader: default operatingSystem: '
'${upgraderOS.operatingSystem} ${upgraderOS.operatingSystemVersion}');
print('upgrader: operatingSystem: ${upgraderOS.operatingSystem}');
print('upgrader: '
'isAndroid: ${upgraderOS.isAndroid}, '
'isIOS: ${upgraderOS.isIOS}, '
'isLinux: ${upgraderOS.isLinux}, '
'isMacOS: ${upgraderOS.isMacOS}, '
'isWindows: ${upgraderOS.isWindows}, '
'isFuchsia: ${upgraderOS.isFuchsia}, '
'isWeb: ${upgraderOS.isWeb}');
}
if (_packageInfo == null) {
_packageInfo = await PackageInfo.fromPlatform();
if (debugLogging) {
print(
'upgrader: package info packageName: ${_packageInfo!.packageName}');
print('upgrader: package info appName: ${_packageInfo!.appName}');
print('upgrader: package info version: ${_packageInfo!.version}');
}
}
_installedVersion = _packageInfo!.version;
await _updateVersionInfo();
// Add an observer of application events.
WidgetsBinding.instance.addObserver(this);
/// Trigger the stream to indicate an evaluation should be performed.
/// The value will always be true.
_streamController.add(true);
return true;
});
return _futureInit!;
}
/// Remove any resources allocated.
void dispose() {
// Remove the observer of application events.
WidgetsBinding.instance.removeObserver(this);
}
/// Handle application events.
@override
Future<void> didChangeAppLifecycleState(AppLifecycleState state) async {
super.didChangeAppLifecycleState(state);
// When app has resumed from background.
if (state == AppLifecycleState.resumed) {
await _updateVersionInfo();
/// Trigger the stream to indicate another evaluation should be performed.
/// The value will always be true.
_streamController.add(true);
}
}
Future<bool> _updateVersionInfo() async {
// If there is an appcast for this platform
if (_isAppcastThisPlatform()) {
if (debugLogging) {
print('upgrader: appcast is available for this platform');
}
final appcast = this.appcast ?? Appcast(client: client);
await appcast.parseAppcastItemsFromUri(appcastConfig!.url!);
if (debugLogging) {
var count = appcast.items == null ? 0 : appcast.items!.length;
print('upgrader: appcast item count: $count');
}
final criticalUpdateItem = appcast.bestCriticalItem();
final criticalVersion = criticalUpdateItem?.versionString ?? '';
final bestItem = appcast.bestItem();
if (bestItem != null &&
bestItem.versionString != null &&
bestItem.versionString!.isNotEmpty) {
if (debugLogging) {
print(
'upgrader: appcast best item version: ${bestItem.versionString}');
print(
'upgrader: appcast critical update item version: ${criticalUpdateItem?.versionString}');
}
try {
if (criticalVersion.isNotEmpty &&
Version.parse(_installedVersion!) <
Version.parse(criticalVersion)) {
_isCriticalUpdate = true;
}
} catch (e) {
print('upgrader: updateVersionInfo could not parse version info $e');
_isCriticalUpdate = false;
}
_appStoreVersion = bestItem.versionString;
_appStoreListingURL = bestItem.fileURL;
_releaseNotes = bestItem.itemDescription;
}
} else {
if (_packageInfo == null || _packageInfo!.packageName.isEmpty) {
return false;
}
// The country code of the locale, defaulting to `US`.
final country = countryCode ?? findCountryCode();
if (debugLogging) {
print('upgrader: countryCode: $country');
}
// The language code of the locale, defaulting to `en`.
final language = languageCode ?? findLanguageCode();
if (debugLogging) {
print('upgrader: languageCode: $language');
}
// Get Android version from Google Play Store, or
// get iOS version from iTunes Store.
if (upgraderOS.isAndroid) {
await _getAndroidStoreVersion(country: country, language: language);
} else if (upgraderOS.isIOS) {
final iTunes = ITunesSearchAPI();
iTunes.debugEnabled = debugLogging;
iTunes.client = client;
final response = await (iTunes
.lookupByBundleId(_packageInfo!.packageName, country: country));
if (response != null) {
_appStoreVersion = ITunesResults.version(response);
_appStoreListingURL = ITunesResults.trackViewUrl(response);
_releaseNotes ??= ITunesResults.releaseNotes(response);
final mav = ITunesResults.minAppVersion(response);
if (mav != null) {
minAppVersion = mav.toString();
if (debugLogging) {
print('upgrader: ITunesResults.minAppVersion: $minAppVersion');
}
}
}
}
}
return true;
}
/// Android info is fetched by parsing the html of the app store page.
Future<bool?> _getAndroidStoreVersion(
{String? country, String? language}) async {
final id = _packageInfo!.packageName;
final playStore = PlayStoreSearchAPI(client: client);
playStore.debugEnabled = debugLogging;
final response =
await (playStore.lookupById(id, country: country, language: language));
if (response != null) {
_appStoreVersion ??= PlayStoreResults.version(response);
_appStoreListingURL ??=
playStore.lookupURLById(id, language: language, country: country);
_releaseNotes ??= PlayStoreResults.releaseNotes(response);
final mav = PlayStoreResults.minAppVersion(response);
if (mav != null) {
minAppVersion = mav.toString();
if (debugLogging) {
print('upgrader: PlayStoreResults.minAppVersion: $minAppVersion');
}
}
}
return true;
}
bool _isAppcastThisPlatform() {
if (appcastConfig == null ||
appcastConfig!.url == null ||
appcastConfig!.url!.isEmpty) {
return false;
}
// Since this appcast config contains a URL, this appcast is valid.
// However, if the supported OS is not listed, it is not supported.
// When there are no supported OSes listed, they are all supported.
var supported = true;
if (appcastConfig!.supportedOS != null) {
supported =
appcastConfig!.supportedOS!.contains(upgraderOS.operatingSystem);
}
return supported;
}
bool _verifyInit() {
if (!_initCalled) {
throw (notInitializedExceptionMessage);
}
return true;
}
String appName() {
_verifyInit();
return _packageInfo?.appName ?? '';
}
String? currentAppStoreListingURL() => _appStoreListingURL;
String? currentAppStoreVersion() => _appStoreVersion;
String? currentInstalledVersion() => _installedVersion;
String? get releaseNotes => _releaseNotes;
String message() {
var msg = messages.message(UpgraderMessage.body)!;
msg = msg.replaceAll('{{appName}}', appName());
msg = msg.replaceAll(
'{{currentAppStoreVersion}}', currentAppStoreVersion() ?? '');
msg = msg.replaceAll(
'{{currentInstalledVersion}}', currentInstalledVersion() ?? '');
return msg;
}
/// Only called by [UpgradeAlert].
void checkVersion({required BuildContext context}) {
if (!_displayed) {
final shouldDisplay = shouldDisplayUpgrade();
if (debugLogging) {
print(
'upgrader: shouldDisplayReleaseNotes: ${shouldDisplayReleaseNotes()}');
}
if (shouldDisplay) {
_displayed = true;
Future.delayed(const Duration(milliseconds: 0), () {
_showDialog(
context: context,
title: messages.message(UpgraderMessage.title),
message: message(),
releaseNotes: shouldDisplayReleaseNotes() ? _releaseNotes : null,
canDismissDialog: canDismissDialog);
});
}
}
}
bool blocked() {
return belowMinAppVersion() || _isCriticalUpdate;
}
bool shouldDisplayUpgrade() {
final isBlocked = blocked();
if (debugLogging) {
print('upgrader: blocked: $isBlocked');
print('upgrader: debugDisplayAlways: $debugDisplayAlways');
print('upgrader: debugDisplayOnce: $debugDisplayOnce');
print('upgrader: hasAlerted: $_hasAlerted');
}
// If installed version is below minimum app version, or is a critical update,
// disable ignore and later buttons.
if (isBlocked) {
showIgnore = false;
showLater = false;
}
bool rv = true;
if (debugDisplayAlways || (debugDisplayOnce && !_hasAlerted)) {
rv = true;
} else if (!isUpdateAvailable()) {
rv = false;
} else if (isBlocked) {
rv = true;
} else if (isTooSoon() || alreadyIgnoredThisVersion()) {
rv = false;
}
if (debugLogging) {
print('upgrader: shouldDisplayUpgrade: $rv');
}
// Call the [willDisplayUpgrade] callback when available.
if (willDisplayUpgrade != null) {
willDisplayUpgrade!(
display: rv,
minAppVersion: minAppVersion,
installedVersion: _installedVersion,
appStoreVersion: _appStoreVersion);
}
return rv;
}
/// Is installed version below minimum app version?
bool belowMinAppVersion() {
var rv = false;
if (minAppVersion != null) {
try {
final minVersion = Version.parse(minAppVersion!);
final installedVersion = Version.parse(_installedVersion!);
rv = installedVersion < minVersion;
} catch (e) {
print(e);
}
}
return rv;
}
bool isTooSoon() {
if (_lastTimeAlerted == null) {
return false;
}
final lastAlertedDuration = DateTime.now().difference(_lastTimeAlerted!);
final rv = lastAlertedDuration < durationUntilAlertAgain;
if (rv && debugLogging) {
print('upgrader: isTooSoon: true');
}
return rv;
}
bool alreadyIgnoredThisVersion() {
final rv =
_userIgnoredVersion != null && _userIgnoredVersion == _appStoreVersion;
if (rv && debugLogging) {
print('upgrader: alreadyIgnoredThisVersion: true');
}
return rv;
}
bool isUpdateAvailable() {
if (debugLogging) {
print('upgrader: appStoreVersion: $_appStoreVersion');
print('upgrader: installedVersion: $_installedVersion');
print('upgrader: minAppVersion: $minAppVersion');
}
if (_appStoreVersion == null || _installedVersion == null) {
if (debugLogging) print('upgrader: isUpdateAvailable: false');
return false;
}
try {
final appStoreVersion = Version.parse(_appStoreVersion!);
final installedVersion = Version.parse(_installedVersion!);
final available = appStoreVersion > installedVersion;
_updateAvailable = available ? _appStoreVersion : null;
} on Exception catch (e) {
print('upgrader: isUpdateAvailable: $e');
}
final isAvailable = _updateAvailable != null;
if (debugLogging) print('upgrader: isUpdateAvailable: $isAvailable');
return isAvailable;
}
bool shouldDisplayReleaseNotes() {
return showReleaseNotes && (_releaseNotes?.isNotEmpty ?? false);
}
/// Determine the current country code, either from the context, or
/// from the system-reported default locale of the device. The default
/// is `US`.
String? findCountryCode({BuildContext? context}) {
Locale? locale;
if (context != null) {
locale = Localizations.maybeLocaleOf(context);
} else {
// Get the system locale
locale = PlatformDispatcher.instance.locale;
}
final code = locale == null || locale.countryCode == null
? 'US'
: locale.countryCode;
return code;
}
/// Determine the current language code, either from the context, or
/// from the system-reported default locale of the device. The default
/// is `en`.
String? findLanguageCode({BuildContext? context}) {
Locale? locale;
if (context != null) {
locale = Localizations.maybeLocaleOf(context);
} else {
// Get the system locale
locale = PlatformDispatcher.instance.locale;
}
final code = locale == null ? 'en' : locale.languageCode;
return code;
}
void _showDialog(
{required BuildContext context,
required String? title,
required String message,
required String? releaseNotes,
required bool canDismissDialog}) {
if (debugLogging) {
print('upgrader: showDialog title: $title');
print('upgrader: showDialog message: $message');
print('upgrader: showDialog releaseNotes: $releaseNotes');
}
// Save the date/time as the last time alerted.
saveLastAlerted();
showDialog(
barrierDismissible: canDismissDialog,
context: context,
builder: (BuildContext context) {
return WillPopScope(
onWillPop: () async => _shouldPopScope(),
child: _alertDialog(title ?? '', message, releaseNotes, context,
dialogStyle == UpgradeDialogStyle.cupertino));
},
);
}
/// Called when the user taps outside of the dialog and [canDismissDialog]
/// is false. Also called when the back button is pressed. Return true for
/// the screen to be popped. Defaults to false.
bool _shouldPopScope() {
if (debugLogging) {
print('upgrader: onWillPop called');
}
if (shouldPopScope != null) {
final should = shouldPopScope!();
if (debugLogging) {
print('upgrader: shouldPopScope=$should');
}
return should;
}
return false;
}
Widget _alertDialog(String title, String message, String? releaseNotes,
BuildContext context, bool cupertino) {
Widget? notes;
if (releaseNotes != null) {
notes = Padding(
padding: const EdgeInsets.only(top: 15.0),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(messages.message(UpgraderMessage.releaseNotes) ?? '',
style: const TextStyle(fontWeight: FontWeight.bold)),
Text(releaseNotes),
],
));
}
final textTitle = Text(title, key: const Key('upgrader.dialog.title'));
final content = Container(
constraints: const BoxConstraints(maxHeight: 400),
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(message),
Padding(
padding: const EdgeInsets.only(top: 15.0),
child: Text(messages.message(UpgraderMessage.prompt) ?? '')),
if (notes != null) notes,
],
)));
final actions = <Widget>[
if (showIgnore)
_button(cupertino, messages.message(UpgraderMessage.buttonTitleIgnore),
context, () => onUserIgnored(context, true)),
if (showLater)
_button(cupertino, messages.message(UpgraderMessage.buttonTitleLater),
context, () => onUserLater(context, true)),
_button(cupertino, messages.message(UpgraderMessage.buttonTitleUpdate),
context, () => onUserUpdated(context, !blocked())),
];
return cupertino
? CupertinoAlertDialog(
title: textTitle, content: content, actions: actions)
: AlertDialog(title: textTitle, content: content, actions: actions);
}
Widget _button(bool cupertino, String? text, BuildContext context,
VoidCallback? onPressed) {
return cupertino
? CupertinoDialogAction(
textStyle: cupertinoButtonTextStyle,
onPressed: onPressed,
child: Text(text ?? ''))
: TextButton(onPressed: onPressed, child: Text(text ?? ''));
}
void onUserIgnored(BuildContext context, bool shouldPop) {
if (debugLogging) {
print('upgrader: button tapped: ignore');
}
// If this callback has been provided, call it.
var doProcess = true;
if (onIgnore != null) {
doProcess = onIgnore!();
}
if (doProcess) {
_saveIgnored();
}
if (shouldPop) {
popNavigator(context);
}
}
void onUserLater(BuildContext context, bool shouldPop) {
if (debugLogging) {
print('upgrader: button tapped: later');
}
// If this callback has been provided, call it.
var doProcess = true;
if (onLater != null) {
doProcess = onLater!();
}
if (doProcess) {}
if (shouldPop) {
popNavigator(context);
}
}
void onUserUpdated(BuildContext context, bool shouldPop) {
if (debugLogging) {
print('upgrader: button tapped: update now');
}
// If this callback has been provided, call it.
var doProcess = true;
if (onUpdate != null) {
doProcess = onUpdate!();
}
if (doProcess) {
_sendUserToAppStore();
}
if (shouldPop) {
popNavigator(context);
}
}
static Future<void> clearSavedSettings() async {
var prefs = await SharedPreferences.getInstance();
await prefs.remove('userIgnoredVersion');
await prefs.remove('lastTimeAlerted');
await prefs.remove('lastVersionAlerted');
return;
}
void popNavigator(BuildContext context) {
Navigator.of(context).pop();
_displayed = false;
}
Future<bool> _saveIgnored() async {
var prefs = await SharedPreferences.getInstance();
_userIgnoredVersion = _appStoreVersion;
await prefs.setString('userIgnoredVersion', _userIgnoredVersion ?? '');
return true;
}
Future<bool> saveLastAlerted() async {
var prefs = await SharedPreferences.getInstance();
_lastTimeAlerted = DateTime.now();
await prefs.setString('lastTimeAlerted', _lastTimeAlerted.toString());
_lastVersionAlerted = _appStoreVersion;
await prefs.setString('lastVersionAlerted', _lastVersionAlerted ?? '');
_hasAlerted = true;
return true;
}
Future<bool> _getSavedPrefs() async {
var prefs = await SharedPreferences.getInstance();
final lastTimeAlerted = prefs.getString('lastTimeAlerted');
if (lastTimeAlerted != null) {
_lastTimeAlerted = DateTime.parse(lastTimeAlerted);
}
_lastVersionAlerted = prefs.getString('lastVersionAlerted');
_userIgnoredVersion = prefs.getString('userIgnoredVersion');
return true;
}
void _sendUserToAppStore() async {
if (_appStoreListingURL == null || _appStoreListingURL!.isEmpty) {
if (debugLogging) {
print('upgrader: empty _appStoreListingURL');
}
return;
}
if (debugLogging) {
print('upgrader: launching: $_appStoreListingURL');
}
if (await canLaunchUrl(Uri.parse(_appStoreListingURL!))) {
try {
await launchUrl(Uri.parse(_appStoreListingURL!),
mode: upgraderOS.isAndroid
? LaunchMode.externalNonBrowserApplication
: LaunchMode.platformDefault);
} catch (e) {
if (debugLogging) {
print('upgrader: launch to app store failed: $e');
}
}
} else {}
}
}