-
Notifications
You must be signed in to change notification settings - Fork 179
/
apps_provider.dart
2082 lines (1966 loc) · 75.8 KB
/
apps_provider.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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Manages state related to the list of Apps tracked by Obtainium,
// Exposes related functions such as those used to add, remove, download, and install Apps.
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:math';
import 'package:battery_plus/battery_plus.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:http/http.dart' as http;
import 'package:crypto/crypto.dart';
import 'package:android_intent_plus/flag.dart';
import 'package:android_package_installer/android_package_installer.dart';
import 'package:android_package_manager/android_package_manager.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:http/io_client.dart';
import 'package:obtainium/components/generated_form.dart';
import 'package:obtainium/components/generated_form_modal.dart';
import 'package:obtainium/custom_errors.dart';
import 'package:obtainium/main.dart';
import 'package:obtainium/providers/logs_provider.dart';
import 'package:obtainium/providers/notifications_provider.dart';
import 'package:obtainium/providers/settings_provider.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter_fgbg/flutter_fgbg.dart';
import 'package:obtainium/providers/source_provider.dart';
import 'package:http/http.dart';
import 'package:android_intent_plus/android_intent.dart';
import 'package:flutter_archive/flutter_archive.dart';
import 'package:share_plus/share_plus.dart';
import 'package:shared_storage/shared_storage.dart' as saf;
import 'package:shizuku_apk_installer/shizuku_apk_installer.dart';
final pm = AndroidPackageManager();
class AppInMemory {
late App app;
double? downloadProgress;
PackageInfo? installedInfo;
Uint8List? icon;
AppInMemory(this.app, this.downloadProgress, this.installedInfo, this.icon);
AppInMemory deepCopy() =>
AppInMemory(app.deepCopy(), downloadProgress, installedInfo, icon);
String get name => app.overrideName ?? app.finalName;
}
class DownloadedApk {
String appId;
File file;
DownloadedApk(this.appId, this.file);
}
class DownloadedXApkDir {
String appId;
File file;
Directory extracted;
DownloadedXApkDir(this.appId, this.file, this.extracted);
}
List<String> generateStandardVersionRegExStrings() {
// TODO: Look into RegEx for non-Latin characters / non-Arabic numerals
var basics = [
'[0-9]+',
'[0-9]+\\.[0-9]+',
'[0-9]+\\.[0-9]+\\.[0-9]+',
'[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+'
];
var preSuffixes = ['-', '\\+'];
var suffixes = ['alpha', 'beta', 'ose'];
var finals = ['\\+[0-9]+', '[0-9]+'];
List<String> results = [];
for (var b in basics) {
results.add(b);
for (var p in preSuffixes) {
for (var s in suffixes) {
results.add('$b$s');
results.add('$b$p$s');
for (var f in finals) {
results.add('$b$s$f');
results.add('$b$p$s$f');
}
}
}
}
return results;
}
List<String> standardVersionRegExStrings =
generateStandardVersionRegExStrings();
Set<String> findStandardFormatsForVersion(String version, bool strict) {
// If !strict, even a substring match is valid
Set<String> results = {};
for (var pattern in standardVersionRegExStrings) {
if (RegExp('${strict ? '^' : ''}$pattern${strict ? '\$' : ''}')
.hasMatch(version)) {
results.add(pattern);
}
}
return results;
}
moveStrToEnd(List<String> arr, String str, {String? strB}) {
String? temp;
arr.removeWhere((element) {
bool res = element == str || element == strB;
if (res) {
temp = element;
}
return res;
});
if (temp != null) {
arr = [...arr, temp!];
}
return arr;
}
List<MapEntry<String, int>> moveStrToEndMapEntryWithCount(
List<MapEntry<String, int>> arr, MapEntry<String, int> str,
{MapEntry<String, int>? strB}) {
MapEntry<String, int>? temp;
arr.removeWhere((element) {
bool resA = element.key == str.key;
bool resB = element.key == strB?.key;
if (resA) {
temp = str;
} else if (resB) {
temp = strB;
}
return resA || resB;
});
if (temp != null) {
arr = [...arr, temp!];
}
return arr;
}
Future<File> downloadFileWithRetry(String url, String fileName,
bool fileNameHasExt, Function? onProgress, String destDir,
{bool useExisting = true,
Map<String, String>? headers,
int retries = 3,
bool allowInsecure = false}) async {
try {
return await downloadFile(
url, fileName, fileNameHasExt, onProgress, destDir,
useExisting: useExisting,
headers: headers,
allowInsecure: allowInsecure);
} catch (e) {
if (retries > 0 && e is ClientException) {
await Future.delayed(const Duration(seconds: 5));
return await downloadFileWithRetry(
url, fileName, fileNameHasExt, onProgress, destDir,
useExisting: useExisting,
headers: headers,
retries: (retries - 1),
allowInsecure: allowInsecure);
} else {
rethrow;
}
}
}
String hashListOfLists(List<List<int>> data) {
var bytes = utf8.encode(jsonEncode(data));
var digest = sha256.convert(bytes);
var hash = digest.toString();
return hash.hashCode.toString();
}
Future<String> checkPartialDownloadHashDynamic(String url,
{int startingSize = 1024,
int lowerLimit = 128,
Map<String, String>? headers,
bool allowInsecure = false}) async {
for (int i = startingSize; i >= lowerLimit; i -= 256) {
List<String> ab = await Future.wait([
checkPartialDownloadHash(url, i,
headers: headers, allowInsecure: allowInsecure),
checkPartialDownloadHash(url, i,
headers: headers, allowInsecure: allowInsecure)
]);
if (ab[0] == ab[1]) {
return ab[0];
}
}
throw NoVersionError();
}
Future<String> checkPartialDownloadHash(String url, int bytesToGrab,
{Map<String, String>? headers, bool allowInsecure = false}) async {
var req = Request('GET', Uri.parse(url));
if (headers != null) {
req.headers.addAll(headers);
}
req.headers[HttpHeaders.rangeHeader] = 'bytes=0-$bytesToGrab';
var client = IOClient(createHttpClient(allowInsecure));
var response = await client.send(req);
if (response.statusCode < 200 || response.statusCode > 299) {
throw ObtainiumError(response.reasonPhrase ?? tr('unexpectedError'));
}
List<List<int>> bytes = await response.stream.take(bytesToGrab).toList();
return hashListOfLists(bytes);
}
Future<File> downloadFile(String url, String fileName, bool fileNameHasExt,
Function? onProgress, String destDir,
{bool useExisting = true,
Map<String, String>? headers,
bool allowInsecure = false}) async {
// Send the initial request but cancel it as soon as you have the headers
var reqHeaders = headers ?? {};
var req = Request('GET', Uri.parse(url));
req.headers.addAll(reqHeaders);
var client = IOClient(createHttpClient(allowInsecure));
StreamedResponse response = await client.send(req);
var resHeaders = response.headers;
// Use the headers to decide what the file extension is, and
// whether it supports partial downloads (range request), and
// what the total size of the file is (if provided)
String ext = resHeaders['content-disposition']?.split('.').last ?? 'apk';
if (ext.endsWith('"') || ext.endsWith("other")) {
ext = ext.substring(0, ext.length - 1);
}
if (((Uri.tryParse(url)?.path ?? url).toLowerCase().endsWith('.apk') ||
ext == 'attachment') &&
ext != 'apk') {
ext = 'apk';
}
fileName = fileNameHasExt
? fileName
: fileName.split('/').last; // Ensure the fileName is a file name
File downloadedFile = File('$destDir/$fileName.$ext');
if (fileNameHasExt) {
// If the user says the filename already has an ext, ignore whatever you inferred from above
downloadedFile = File('$destDir/$fileName');
}
bool rangeFeatureEnabled = false;
if (resHeaders['accept-ranges']?.isNotEmpty == true) {
rangeFeatureEnabled =
resHeaders['accept-ranges']?.trim().toLowerCase() == 'bytes';
}
// If you have an existing file that is usable,
// decide whether you can use it (either return full or resume partial)
var fullContentLength = response.contentLength;
if (useExisting && downloadedFile.existsSync()) {
var length = downloadedFile.lengthSync();
if (fullContentLength == null || !rangeFeatureEnabled) {
// If there is no content length reported, assume it the existing file is fully downloaded
// Also if the range feature is not supported, don't trust the content length if any (#1542)
client.close();
return downloadedFile;
} else {
// Check if resume needed/possible
if (length == fullContentLength) {
client.close();
return downloadedFile;
}
if (length > fullContentLength) {
useExisting = false;
}
}
}
// Download to a '.temp' file (to distinguish btn. complete/incomplete files)
File tempDownloadedFile = File('${downloadedFile.path}.part');
// If the range feature is not available (or you need to start a ranged req from 0),
// complete the already-started request, else cancel it and start a ranged request,
// and open the file for writing in the appropriate mode
var targetFileLength = useExisting && tempDownloadedFile.existsSync()
? tempDownloadedFile.lengthSync()
: null;
int rangeStart = targetFileLength ?? 0;
IOSink? sink;
if (rangeFeatureEnabled && fullContentLength != null && rangeStart > 0) {
client.close();
client = IOClient(createHttpClient(allowInsecure));
req = Request('GET', Uri.parse(url));
req.headers.addAll(reqHeaders);
req.headers.addAll({'range': 'bytes=$rangeStart-${fullContentLength - 1}'});
response = await client.send(req);
sink = tempDownloadedFile.openWrite(mode: FileMode.writeOnlyAppend);
} else if (tempDownloadedFile.existsSync()) {
tempDownloadedFile.deleteSync(recursive: true);
}
sink ??= tempDownloadedFile.openWrite(mode: FileMode.writeOnly);
// Perform the download
var received = 0;
double? progress;
if (rangeStart > 0 && fullContentLength != null) {
received = rangeStart;
}
await response.stream.map((s) {
received += s.length;
progress =
(fullContentLength != null ? (received / fullContentLength) * 100 : 30);
if (onProgress != null) {
onProgress(progress);
}
return s;
}).pipe(sink);
await sink.close();
progress = null;
if (onProgress != null) {
onProgress(progress);
}
if (response.statusCode < 200 || response.statusCode > 299) {
tempDownloadedFile.deleteSync(recursive: true);
throw response.reasonPhrase ?? tr('unexpectedError');
}
if (tempDownloadedFile.existsSync()) {
tempDownloadedFile.renameSync(downloadedFile.path);
}
client.close();
return downloadedFile;
}
Future<Map<String, String>> getHeaders(String url,
{Map<String, String>? headers, bool allowInsecure = false}) async {
var req = http.Request('GET', Uri.parse(url));
if (headers != null) {
req.headers.addAll(headers);
}
var client = IOClient(createHttpClient(allowInsecure));
var response = await client.send(req);
if (response.statusCode < 200 || response.statusCode > 299) {
throw ObtainiumError(response.reasonPhrase ?? tr('unexpectedError'));
}
var returnHeaders = response.headers;
client.close();
return returnHeaders;
}
Future<List<PackageInfo>> getAllInstalledInfo() async {
return await pm.getInstalledPackages() ?? [];
}
Future<PackageInfo?> getInstalledInfo(String? packageName,
{bool printErr = true}) async {
if (packageName != null) {
try {
return await pm.getPackageInfo(packageName: packageName);
} catch (e) {
if (printErr) {
print(e); // OK
}
}
}
return null;
}
class AppsProvider with ChangeNotifier {
// In memory App state (should always be kept in sync with local storage versions)
Map<String, AppInMemory> apps = {};
bool loadingApps = false;
bool gettingUpdates = false;
LogsProvider logs = LogsProvider();
// Variables to keep track of the app foreground status (installs can't run in the background)
bool isForeground = true;
late Stream<FGBGType>? foregroundStream;
late StreamSubscription<FGBGType>? foregroundSubscription;
late Directory APKDir;
late Directory iconsCacheDir;
late SettingsProvider settingsProvider = SettingsProvider();
Iterable<AppInMemory> getAppValues() => apps.values.map((a) => a.deepCopy());
AppsProvider({isBg = false}) {
// Subscribe to changes in the app foreground status
foregroundStream = FGBGEvents.instance.stream.asBroadcastStream();
foregroundSubscription = foregroundStream?.listen((event) async {
isForeground = event == FGBGType.foreground;
if (isForeground) {
await loadApps();
}
});
() async {
await settingsProvider.initializeSettings();
var cacheDirs = await getExternalCacheDirectories();
if (cacheDirs?.isNotEmpty ?? false) {
APKDir = cacheDirs!.first;
iconsCacheDir = Directory('${cacheDirs.first.path}/icons');
if (!iconsCacheDir.existsSync()) {
iconsCacheDir.createSync();
}
} else {
APKDir =
Directory('${(await getExternalStorageDirectory())!.path}/apks');
if (!APKDir.existsSync()) {
APKDir.createSync();
}
iconsCacheDir =
Directory('${(await getExternalStorageDirectory())!.path}/icons');
if (!iconsCacheDir.existsSync()) {
iconsCacheDir.createSync();
}
}
if (!isBg) {
// Load Apps into memory (in background processes, this is done later instead of in the constructor)
await loadApps();
// Delete any partial APKs (if safe to do so)
var cutoff = DateTime.now().subtract(const Duration(days: 7));
APKDir.listSync()
.where((element) =>
element.path.endsWith('.part') ||
element.statSync().modified.isBefore(cutoff))
.forEach((partialApk) {
if (!areDownloadsRunning()) {
partialApk.delete(recursive: true);
}
});
}
}();
}
Future<File> handleAPKIDChange(App app, PackageInfo newInfo,
File downloadedFile, String downloadUrl) async {
// If the APK package ID is different from the App ID, it is either new (using a placeholder ID) or the ID has changed
// The former case should be handled (give the App its real ID), the latter is a security issue
var isTempIdBool = isTempId(app);
if (app.id != newInfo.packageName) {
if (apps[app.id] != null && !isTempIdBool && !app.allowIdChange) {
throw IDChangedError(newInfo.packageName!);
}
var idChangeWasAllowed = app.allowIdChange;
app.allowIdChange = false;
var originalAppId = app.id;
app.id = newInfo.packageName!;
downloadedFile = downloadedFile.renameSync(
'${downloadedFile.parent.path}/${app.id}-${downloadUrl.hashCode}.${downloadedFile.path.split('.').last}');
if (apps[originalAppId] != null) {
await removeApps([originalAppId]);
await saveApps([app],
onlyIfExists: !isTempIdBool && !idChangeWasAllowed);
}
}
return downloadedFile;
}
Future<Object> downloadApp(App app, BuildContext? context,
{NotificationsProvider? notificationsProvider,
bool useExisting = true}) async {
var notifId = DownloadNotification(app.finalName, 0).id;
if (apps[app.id] != null) {
apps[app.id]!.downloadProgress = 0;
notifyListeners();
}
try {
AppSource source = SourceProvider()
.getSource(app.url, overrideSource: app.overrideSource);
String downloadUrl = await source.apkUrlPrefetchModifier(
app.apkUrls[app.preferredApkIndex].value,
app.url,
app.additionalSettings);
var notif = DownloadNotification(app.finalName, 100);
notificationsProvider?.cancel(notif.id);
int? prevProg;
var fileNameNoExt = '${app.id}-${downloadUrl.hashCode}';
if (source.urlsAlwaysHaveExtension) {
fileNameNoExt =
'$fileNameNoExt.${app.apkUrls[app.preferredApkIndex].key.split('.').last}';
}
var headers = await source.getRequestHeaders(app.additionalSettings,
forAPKDownload: true);
var downloadedFile = await downloadFileWithRetry(
downloadUrl, fileNameNoExt, source.urlsAlwaysHaveExtension,
headers: headers, (double? progress) {
int? prog = progress?.ceil();
if (apps[app.id] != null) {
apps[app.id]!.downloadProgress = progress;
notifyListeners();
}
notif = DownloadNotification(app.finalName, prog ?? 100);
if (prog != null && prevProg != prog) {
notificationsProvider?.notify(notif);
}
prevProg = prog;
}, APKDir.path,
useExisting: useExisting,
allowInsecure: app.additionalSettings['allowInsecure'] == true);
// Set to 90 for remaining steps, will make null in 'finally'
if (apps[app.id] != null) {
apps[app.id]!.downloadProgress = -1;
notifyListeners();
notif = DownloadNotification(app.finalName, -1);
notificationsProvider?.notify(notif);
}
PackageInfo? newInfo;
var isAPK = downloadedFile.path.toLowerCase().endsWith('.apk');
Directory? xapkDir;
if (isAPK) {
newInfo = await pm.getPackageArchiveInfo(
archiveFilePath: downloadedFile.path);
} else {
// Assume XAPK
String xapkDirPath = '${downloadedFile.path}-dir';
await unzipFile(downloadedFile.path, '${downloadedFile.path}-dir');
xapkDir = Directory(xapkDirPath);
var apks = xapkDir
.listSync()
.where((e) => e.path.toLowerCase().endsWith('.apk'))
.toList();
for (var i = 0; i < apks.length; i++) {
try {
newInfo = await pm.getPackageArchiveInfo(
archiveFilePath: apks.first.path);
break;
} catch (e) {
if (i == apks.length - 1) {
rethrow;
}
}
}
}
if (newInfo == null) {
downloadedFile.delete();
throw ObtainiumError('Could not get ID from APK');
}
downloadedFile =
await handleAPKIDChange(app, newInfo, downloadedFile, downloadUrl);
// Delete older versions of the file if any
for (var file in downloadedFile.parent.listSync()) {
var fn = file.path.split('/').last;
if (fn.startsWith('${app.id}-') &&
FileSystemEntity.isFileSync(file.path) &&
file.path != downloadedFile.path) {
file.delete(recursive: true);
}
}
if (isAPK) {
return DownloadedApk(app.id, downloadedFile);
} else {
return DownloadedXApkDir(app.id, downloadedFile, xapkDir!);
}
} finally {
notificationsProvider?.cancel(notifId);
if (apps[app.id] != null) {
apps[app.id]!.downloadProgress = null;
notifyListeners();
}
}
}
bool areDownloadsRunning() => apps.values
.where((element) => element.downloadProgress != null)
.isNotEmpty;
Future<bool> canInstallSilently(App app) async {
if (!settingsProvider.enableBackgroundUpdates) {
return false;
}
if (app.additionalSettings['exemptFromBackgroundUpdates'] == true) {
logs.add('Exempted from BG updates: ${app.id}');
return false;
}
if (app.apkUrls.length > 1) {
logs.add('Multiple APK URLs: ${app.id}');
return false; // Manual API selection means silent install is not possible
}
var osInfo = await DeviceInfoPlugin().androidInfo;
String? installerPackageName;
try {
installerPackageName = osInfo.version.sdkInt >= 30
? (await pm.getInstallSourceInfo(packageName: app.id))
?.installingPackageName
: (await pm.getInstallerPackageName(packageName: app.id));
} catch (e) {
logs.add(
'Failed to get installed package details: ${app.id} (${e.toString()})');
return false; // App probably not installed
}
int? targetSDK =
(await getInstalledInfo(app.id))?.applicationInfo?.targetSdkVersion;
// The APK should target a new enough API
// https://developer.android.com/reference/android/content/pm/PackageInstaller.SessionParams#setRequireUserAction(int)
if (!(targetSDK != null && targetSDK >= (osInfo.version.sdkInt - 3))) {
logs.add('Multiple APK URLs: ${app.id}');
return false;
}
if (settingsProvider.useShizuku) {
return true;
}
if (app.id == obtainiumId) {
return false;
}
if (installerPackageName != obtainiumId) {
// If we did not install the app, silent install is not possible
return false;
}
if (osInfo.version.sdkInt < 31) {
// The OS must also be new enough
logs.add('Android SDK too old: ${osInfo.version.sdkInt}');
return false;
}
return true;
}
Future<void> waitForUserToReturnToForeground(BuildContext context) async {
NotificationsProvider notificationsProvider =
context.read<NotificationsProvider>();
if (!isForeground) {
await notificationsProvider.notify(completeInstallationNotification,
cancelExisting: true);
while (await FGBGEvents.instance.stream.first != FGBGType.foreground) {}
await notificationsProvider.cancel(completeInstallationNotification.id);
}
}
Future<bool> canDowngradeApps() async =>
(await getInstalledInfo('com.berdik.letmedowngrade')) != null;
Future<void> unzipFile(String filePath, String destinationPath) async {
await ZipFile.extractToDirectory(
zipFile: File(filePath), destinationDir: Directory(destinationPath));
}
Future<bool> installXApkDir(
DownloadedXApkDir dir, BuildContext? firstTimeWithContext,
{bool needsBGWorkaround = false,
bool shizukuPretendToBeGooglePlay = false}) async {
// We don't know which APKs in an XAPK are supported by the user's device
// So we try installing all of them and assume success if at least one installed
// If 0 APKs installed, throw the first install error encountered
var somethingInstalled = false;
try {
MultiAppMultiError errors = MultiAppMultiError();
for (var file in dir.extracted
.listSync(recursive: true, followLinks: false)
.whereType<File>()) {
if (file.path.toLowerCase().endsWith('.apk')) {
try {
somethingInstalled = somethingInstalled ||
await installApk(
DownloadedApk(dir.appId, file), firstTimeWithContext,
needsBGWorkaround: needsBGWorkaround,
shizukuPretendToBeGooglePlay: shizukuPretendToBeGooglePlay);
} catch (e) {
logs.add(
'Could not install APK from XAPK \'${file.path}\': ${e.toString()}');
errors.add(dir.appId, e, appName: apps[dir.appId]?.name);
}
} else if (file.path.toLowerCase().endsWith('.obb')) {
await moveObbFile(file, dir.appId);
}
}
if (somethingInstalled) {
dir.file.delete(recursive: true);
} else if (errors.idsByErrorString.isNotEmpty) {
throw errors;
}
} finally {
dir.extracted.delete(recursive: true);
}
return somethingInstalled;
}
Future<bool> installApk(
DownloadedApk file, BuildContext? firstTimeWithContext,
{bool needsBGWorkaround = false,
bool shizukuPretendToBeGooglePlay = false}) async {
if (firstTimeWithContext != null &&
settingsProvider.beforeNewInstallsShareToAppVerifier &&
(await getInstalledInfo('dev.soupslurpr.appverifier')) != null) {
XFile f = XFile.fromData(file.file.readAsBytesSync(),
mimeType: 'application/vnd.android.package-archive');
Fluttertoast.showToast(
msg: tr('appVerifierInstructionToast'),
toastLength: Toast.LENGTH_LONG);
await Share.shareXFiles([f]);
}
var newInfo =
await pm.getPackageArchiveInfo(archiveFilePath: file.file.path);
if (newInfo == null) {
try {
file.file.deleteSync(recursive: true);
} catch (e) {
//
} finally {
throw ObtainiumError(tr('badDownload'));
}
}
PackageInfo? appInfo = await getInstalledInfo(apps[file.appId]!.app.id);
logs.add(
'Installing "${newInfo.packageName}" version "${newInfo.versionName}" versionCode "${newInfo.versionCode}"${appInfo != null ? ' (from existing version "${appInfo.versionName}" versionCode "${appInfo.versionCode}")' : ''}');
if (appInfo != null &&
newInfo.versionCode! < appInfo.versionCode! &&
!(await canDowngradeApps())) {
throw DowngradeError();
}
if (needsBGWorkaround) {
// The below 'await' will never return if we are in a background process
// To work around this, we should assume the install will be successful
// So we update the app's installed version first as we will never get to the later code
// We can't conditionally get rid of the 'await' as this causes install fails (BG process times out) - see #896
// TODO: When fixed, update this function and the calls to it accordingly
apps[file.appId]!.app.installedVersion =
apps[file.appId]!.app.latestVersion;
await saveApps([apps[file.appId]!.app],
attemptToCorrectInstallStatus: false);
}
int? code;
if (!settingsProvider.useShizuku) {
code =
await AndroidPackageInstaller.installApk(apkFilePath: file.file.path);
} else {
code = await ShizukuApkInstaller.installAPK(file.file.uri.toString(),
shizukuPretendToBeGooglePlay ? "com.android.vending" : "");
}
bool installed = false;
if (code != null && code != 0 && code != 3) {
try {
file.file.deleteSync(recursive: true);
} catch (e) {
//
} finally {
throw InstallError(code);
}
} else if (code == 0) {
installed = true;
apps[file.appId]!.app.installedVersion =
apps[file.appId]!.app.latestVersion;
file.file.delete(recursive: true);
}
await saveApps([apps[file.appId]!.app]);
return installed;
}
Future<String> getStorageRootPath() async {
return '/${(await getExternalStorageDirectory())!.uri.pathSegments.sublist(0, 3).join('/')}';
}
Future<void> moveObbFile(File file, String appId) async {
if (!file.path.toLowerCase().endsWith('.obb')) return;
// TODO: Does not support Android 11+
if ((await DeviceInfoPlugin().androidInfo).version.sdkInt <= 29) {
await Permission.storage.request();
}
String obbDirPath = "${await getStorageRootPath()}/Android/obb/$appId";
Directory(obbDirPath).createSync(recursive: true);
String obbFileName = file.path.split("/").last;
await file.copy("$obbDirPath/$obbFileName");
}
void uninstallApp(String appId) async {
var intent = AndroidIntent(
action: 'android.intent.action.DELETE',
data: 'package:$appId',
flags: <int>[Flag.FLAG_ACTIVITY_NEW_TASK],
package: 'vnd.android.package-archive');
await intent.launch();
}
Future<MapEntry<String, String>?> confirmAppFileUrl(
App app, BuildContext? context, bool pickAnyAsset,
{bool evenIfSingleChoice = false}) async {
var urlsToSelectFrom = app.apkUrls;
if (pickAnyAsset) {
urlsToSelectFrom = [...urlsToSelectFrom, ...app.otherAssetUrls];
}
// If the App has more than one APK, the user should pick one (if context provided)
MapEntry<String, String>? appFileUrl = urlsToSelectFrom[
app.preferredApkIndex >= 0 ? app.preferredApkIndex : 0];
// get device supported architecture
List<String> archs = (await DeviceInfoPlugin().androidInfo).supportedAbis;
if ((urlsToSelectFrom.length > 1 || evenIfSingleChoice) &&
context != null) {
appFileUrl = await showDialog(
// ignore: use_build_context_synchronously
context: context,
builder: (BuildContext ctx) {
return AppFilePicker(
app: app,
initVal: appFileUrl,
archs: archs,
pickAnyAsset: pickAnyAsset,
);
});
}
getHost(String url) {
var temp = Uri.parse(url).host.split('.');
return temp.sublist(temp.length - 2).join('.');
}
// If the picked APK comes from an origin different from the source, get user confirmation (if context provided)
if (appFileUrl != null &&
getHost(appFileUrl.value) != getHost(app.url) &&
context != null) {
if (!(settingsProvider.hideAPKOriginWarning) &&
await showDialog(
// ignore: use_build_context_synchronously
context: context,
builder: (BuildContext ctx) {
return APKOriginWarningDialog(
sourceUrl: app.url, apkUrl: appFileUrl!.value);
}) !=
true) {
appFileUrl = null;
}
}
return appFileUrl;
}
// Given a list of AppIds, uses stored info about the apps to download APKs and install them
// If the APKs can be installed silently, they are
// If no BuildContext is provided, apps that require user interaction are ignored
// If user input is needed and the App is in the background, a notification is sent to get the user's attention
// Returns an array of Ids for Apps that were successfully downloaded, regardless of installation result
Future<List<String>> downloadAndInstallLatestApps(
List<String> appIds, BuildContext? context,
{NotificationsProvider? notificationsProvider,
bool forceParallelDownloads = false,
bool useExisting = true}) async {
notificationsProvider =
notificationsProvider ?? context?.read<NotificationsProvider>();
List<String> appsToInstall = [];
List<String> trackOnlyAppsToUpdate = [];
// For all specified Apps, filter out those for which:
// 1. A URL cannot be picked
// 2. That cannot be installed silently (IF no buildContext was given for interactive install)
for (var id in appIds) {
if (apps[id] == null) {
throw ObtainiumError(tr('appNotFound'));
}
MapEntry<String, String>? apkUrl;
var trackOnly = apps[id]!.app.additionalSettings['trackOnly'] == true;
if (!trackOnly) {
// ignore: use_build_context_synchronously
apkUrl = await confirmAppFileUrl(apps[id]!.app, context, false);
}
if (apkUrl != null) {
int urlInd = apps[id]!
.app
.apkUrls
.map((e) => e.value)
.toList()
.indexOf(apkUrl.value);
if (urlInd >= 0 && urlInd != apps[id]!.app.preferredApkIndex) {
apps[id]!.app.preferredApkIndex = urlInd;
await saveApps([apps[id]!.app]);
}
if (context != null || await canInstallSilently(apps[id]!.app)) {
appsToInstall.add(id);
}
}
if (trackOnly) {
trackOnlyAppsToUpdate.add(id);
}
}
// Mark all specified track-only apps as latest
saveApps(trackOnlyAppsToUpdate.map((e) {
var a = apps[e]!.app;
a.installedVersion = a.latestVersion;
return a;
}).toList());
// Prepare to download+install Apps
MultiAppMultiError errors = MultiAppMultiError();
List<String> installedIds = [];
// Move Obtainium to the end of the line (let all other apps update first)
appsToInstall =
moveStrToEnd(appsToInstall, obtainiumId, strB: obtainiumTempId);
Future<void> installFn(String id, bool willBeSilent,
DownloadedApk? downloadedFile, DownloadedXApkDir? downloadedDir) async {
apps[id]?.downloadProgress = -1;
notifyListeners();
try {
bool sayInstalled = true;
var contextIfNewInstall =
apps[id]?.installedInfo == null ? context : null;
bool needBGWorkaround =
willBeSilent && context == null && !settingsProvider.useShizuku;
bool shizukuPretendToBeGooglePlay = settingsProvider
.shizukuPretendToBeGooglePlay ||
apps[id]!.app.additionalSettings['shizukuPretendToBeGooglePlay'] ==
true;
if (downloadedFile != null) {
if (needBGWorkaround) {
// ignore: use_build_context_synchronously
installApk(downloadedFile, contextIfNewInstall,
needsBGWorkaround: true,
shizukuPretendToBeGooglePlay: shizukuPretendToBeGooglePlay);
} else {
// ignore: use_build_context_synchronously
sayInstalled = await installApk(downloadedFile, contextIfNewInstall,
shizukuPretendToBeGooglePlay: shizukuPretendToBeGooglePlay);
}
} else {
if (needBGWorkaround) {
// ignore: use_build_context_synchronously
installXApkDir(downloadedDir!, contextIfNewInstall,
needsBGWorkaround: true);
} else {
// ignore: use_build_context_synchronously
sayInstalled = await installXApkDir(
downloadedDir!, contextIfNewInstall,
shizukuPretendToBeGooglePlay: shizukuPretendToBeGooglePlay);
}
}
if (willBeSilent && context == null) {
if (!settingsProvider.useShizuku) {
notificationsProvider?.notify(SilentUpdateAttemptNotification(
[apps[id]!.app],
id: id.hashCode));
} else {
notificationsProvider?.notify(SilentUpdateNotification(
[apps[id]!.app], sayInstalled,
id: id.hashCode));
}
}
if (sayInstalled) {
installedIds.add(id);
}
} finally {
apps[id]?.downloadProgress = null;
notifyListeners();
}
}
Future<Map<Object?, Object?>> downloadFn(String id,
{bool skipInstalls = false}) async {
bool willBeSilent = false;
DownloadedApk? downloadedFile;
DownloadedXApkDir? downloadedDir;
try {
var downloadedArtifact =
// ignore: use_build_context_synchronously
await downloadApp(apps[id]!.app, context,
notificationsProvider: notificationsProvider,
useExisting: useExisting);
if (downloadedArtifact is DownloadedApk) {
downloadedFile = downloadedArtifact;
} else {
downloadedDir = downloadedArtifact as DownloadedXApkDir;
}
id = downloadedFile?.appId ?? downloadedDir!.appId;
willBeSilent = await canInstallSilently(apps[id]!.app);
if (!settingsProvider.useShizuku) {
if (!(await settingsProvider.getInstallPermission(enforce: false))) {
throw ObtainiumError(tr('cancelled'));
}
} else {
switch ((await ShizukuApkInstaller.checkPermission())!) {
case 'binder_not_found':
throw ObtainiumError(tr('shizukuBinderNotFound'));
case 'old_shizuku':
throw ObtainiumError(tr('shizukuOld'));
case 'old_android_with_adb':
throw ObtainiumError(tr('shizukuOldAndroidWithADB'));
case 'denied':
throw ObtainiumError(tr('cancelled'));
}
}
if (!willBeSilent && context != null && !settingsProvider.useShizuku) {
// ignore: use_build_context_synchronously
await waitForUserToReturnToForeground(context);
}
} catch (e) {
errors.add(id, e, appName: apps[id]?.name);
}
return {
'id': id,
'willBeSilent': willBeSilent,
'downloadedFile': downloadedFile,
'downloadedDir': downloadedDir
};
}
List<Map<Object?, Object?>> downloadResults = [];
if (forceParallelDownloads || !settingsProvider.parallelDownloads) {
for (var id in appsToInstall) {
downloadResults.add(await downloadFn(id));
}
} else {
downloadResults = await Future.wait(