This repository has been archived by the owner on Jul 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
app_updater.dart
88 lines (72 loc) · 2.53 KB
/
app_updater.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
import 'dart:io';
import 'package:boorusphere/constant/app.dart';
import 'package:boorusphere/data/repository/booru/entity/post.dart';
import 'package:boorusphere/data/repository/downloads/entity/download_progress.dart';
import 'package:boorusphere/data/repository/version/app_version_repo.dart';
import 'package:boorusphere/data/repository/version/entity/app_version.dart';
import 'package:boorusphere/presentation/provider/download/download_state.dart';
import 'package:boorusphere/presentation/provider/download/downloader.dart';
import 'package:flutter_downloader/flutter_downloader.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';
part 'app_updater.g.dart';
@riverpod
AppUpdater appUpdater(AppUpdaterRef ref) {
return AppUpdater(ref);
}
@riverpod
DownloadProgress appUpdateProgress(AppUpdateProgressRef ref) {
final id = ref.watch(appUpdaterProvider.select((it) => it.id));
return ref.watch(downloadProgressStateProvider).getById(id);
}
class AppUpdater {
AppUpdater(this.ref);
final Ref ref;
String id = '';
String _fileNameOf(AppVersion version) {
return 'boorusphere-$version-$kAppArch.apk';
}
final updateDir = 'app-update';
Future<void> clear() async {
final tasks = await FlutterDownloader.loadTasksWithRawQuery(
query: 'SELECT * FROM task WHERE file_name LIKE \'%.apk\'');
if (tasks == null) return;
for (var task in tasks) {
await ref.read(downloadEntryStateProvider.notifier).remove(task.taskId);
await FlutterDownloader.remove(
taskId: task.taskId,
shouldDeleteContent: true,
);
}
id = '';
}
Future<void> start(AppVersion version) async {
await clear();
final fileName = _fileNameOf(version);
final url = '${AppVersionRepo.gitUrl}/releases/download/$version/$fileName';
final tmp = await getTemporaryDirectory();
if (!tmp.existsSync()) {
try {
tmp.createSync();
// ignore: empty_catches
} catch (e) {}
}
final apk = File(path.join(tmp.absolute.path, fileName));
if (apk.existsSync()) {
try {
apk.deleteSync();
// ignore: empty_catches
} catch (e) {}
}
final newId =
await ref.read(downloaderProvider).download(Post.appReserved, url: url);
if (newId != null) {
id = newId;
}
}
Future<void> install(AppVersion version) async {
ref.read(downloaderProvider).openFile(id: id);
}
}