Switch to per-app BG update tasks

This commit is contained in:
Imran Remtulla
2023-08-21 20:10:30 -04:00
parent 03bb1ad9a6
commit 3eb25c4060
14 changed files with 129 additions and 196 deletions

View File

@@ -1,4 +1,4 @@
{
{
"invalidURLForSource": "Nije važeći URL aplikacije {}",
"noReleaseFound": "Nije moguće pronaći odgovarajuće izdanje",
"noVersionFound": "Nije moguće odrediti verziju izdanja",
@@ -11,12 +11,6 @@
"unexpectedError": "Neočekivana greška",
"ok": "Dobro",
"and": "i",
"startedBgUpdateTask": "Započeo je pozadinski zadatak provjere ažuriranja",
"bgUpdateIgnoreAfterIs": "ignoreAfter pozadinskog zadataka je {}",
"startedActualBGUpdateCheck": "Započela je stvarna provjera ažuriranja",
"bgUpdateTaskFinished": "Završen zadatak provjere ažuriranja",
"firstRun": "Ovo je prvi put da pokrećete Obtainium",
"settingUpdateCheckIntervalTo": "Podešavanje intervala ažuriranja na {}",
"githubPATLabel": "GitHub token za lični pristup (eng. PAT, povećava ograničenje stope)",
"githubPATHint": "PAT mora biti u ovom formatu: korisničko_ime:token",
"githubPATFormat": "korisničko_ime:token",
@@ -249,7 +243,7 @@
"customLinkFilterRegex": "Custom Link Filter by Regular Expression (Default '.apk$')",
"appsPossiblyUpdated": "App Updates Attempted",
"appsPossiblyUpdatedNotifDescription": "Notifies the user that updates to one or more Apps were potentially applied in the background",
"xWasPossiblyUpdatedToY": "An attempt was made to update {} to {}.",
"xWasPossiblyUpdatedToY": "{} may have been updated to {}.",
"removeAppQuestion": {
"one": "Želite li ukloniti aplikaciju?",
"other": "Želite li ukloniti aplikacije?"
@@ -299,7 +293,7 @@
"other": "{} i još {} aplikacija je ažurirano."
},
"xAndNMoreUpdatesPossiblyInstalled": {
"one": "Attempts were made to update {} and 1 more app.",
"other": "Attempts were made to update {} and {} more apps."
"one": "{} and 1 more app may have been updated.",
"other": "{} and {} more apps may have been updated."
}
}

View File

@@ -11,12 +11,6 @@
"unexpectedError": "Unerwarteter Fehler",
"ok": "Okay",
"and": "und",
"startedBgUpdateTask": "Hintergrundaktualisierungsprüfung gestartet",
"bgUpdateIgnoreAfterIs": "Hintergrundaktualisierung 'ignoreAfter' ist {}",
"startedActualBGUpdateCheck": "Überprüfung der Hintergrundaktualisierung gestartet",
"bgUpdateTaskFinished": "Hintergrundaktualisierungsprüfung abgeschlossen",
"firstRun": "Dies ist der erste Start von Obtainium überhaupt",
"settingUpdateCheckIntervalTo": "Aktualisierungsintervall auf {} stellen",
"githubPATLabel": "GitHub Personal Access Token (Erhöht das Ratenlimit)",
"githubPATHint": "PAT muss in diesem Format sein: Benutzername:Token",
"githubPATFormat": "Benutzername:Token",
@@ -249,7 +243,7 @@
"customLinkFilterRegex": "Benutzerdefinierter Link Filter nach Regulärem Ausdruck (Standard '.apk$')",
"appsPossiblyUpdated": "App Updates Attempted",
"appsPossiblyUpdatedNotifDescription": "Notifies the user that updates to one or more Apps were potentially applied in the background",
"xWasPossiblyUpdatedToY": "An attempt was made to update {} to {}.",
"xWasPossiblyUpdatedToY": "{} may have been updated to {}.",
"removeAppQuestion": {
"one": "App entfernen?",
"other": "Apps entfernen?"
@@ -299,7 +293,7 @@
"other": "{} und {} weitere Anwendungen wurden aktualisiert."
},
"xAndNMoreUpdatesPossiblyInstalled": {
"one": "Attempts were made to update {} and 1 more app.",
"other": "Attempts were made to update {} and {} more apps."
"one": "{} and 1 more app may have been updated.",
"other": "{} and {} more apps may have been updated."
}
}

View File

@@ -11,12 +11,6 @@
"unexpectedError": "Unexpected Error",
"ok": "Okay",
"and": "and",
"startedBgUpdateTask": "Started BG update check task",
"bgUpdateIgnoreAfterIs": "Bg update ignoreAfter is {}",
"startedActualBGUpdateCheck": "Started actual BG update checking",
"bgUpdateTaskFinished": "Finished BG update check task",
"firstRun": "This is the first ever run of Obtainium",
"settingUpdateCheckIntervalTo": "Setting update interval to {}",
"githubPATLabel": "GitHub Personal Access Token (Increases Rate Limit)",
"githubPATHint": "PAT must be in this format: username:token",
"githubPATFormat": "username:token",
@@ -249,7 +243,7 @@
"customLinkFilterRegex": "Custom Link Filter by Regular Expression (Default '.apk$')",
"appsPossiblyUpdated": "App Updates Attempted",
"appsPossiblyUpdatedNotifDescription": "Notifies the user that updates to one or more Apps were potentially applied in the background",
"xWasPossiblyUpdatedToY": "An attempt was made to update {} to {}.",
"xWasPossiblyUpdatedToY": "{} may have been updated to {}.",
"removeAppQuestion": {
"one": "Remove App?",
"other": "Remove Apps?"
@@ -295,11 +289,11 @@
"other": "{} and {} more apps have updates."
},
"xAndNMoreUpdatesInstalled": {
"one": "{} and 1 more app were updated.",
"one": "{} and 1 more app was updated.",
"other": "{} and {} more apps were updated."
},
"xAndNMoreUpdatesPossiblyInstalled": {
"one": "Attempts were made to update {} and 1 more app.",
"other": "Attempts were made to update {} and {} more apps."
"one": "{} and 1 more app may have been updated.",
"other": "{} and {} more apps may have been updated."
}
}

View File

@@ -11,12 +11,6 @@
"unexpectedError": "Error Inesperado",
"ok": "Correcto",
"and": "y",
"startedBgUpdateTask": "Empezada la tarea de comprobación de actualizaciones en segundo plano",
"bgUpdateIgnoreAfterIs": "El parámetro ignoreAfter de la actualización en segundo plano es {}",
"startedActualBGUpdateCheck": "Ha comenzado la comprobación de actualizaciones en segundo plano",
"bgUpdateTaskFinished": "Ha finalizado la comprobación de actualizaciones en segundo plano",
"firstRun": "Esta es la primera ejecución de Obtainium",
"settingUpdateCheckIntervalTo": "Cambiando intervalo de actualización a {}",
"githubPATLabel": "Token de Acceso Personal de GitHub (Reduce tiempos de espera)",
"githubPATHint": "El TAP debe tener este formato: nombre_de_usuario:token",
"githubPATFormat": "nombre_de_usuario:token",
@@ -249,7 +243,7 @@
"customLinkFilterRegex": "Custom Link Filter by Regular Expression (Default '.apk$')",
"appsPossiblyUpdated": "App Updates Attempted",
"appsPossiblyUpdatedNotifDescription": "Notifies the user that updates to one or more Apps were potentially applied in the background",
"xWasPossiblyUpdatedToY": "An attempt was made to update {} to {}.",
"xWasPossiblyUpdatedToY": "{} may have been updated to {}.",
"removeAppQuestion": {
"one": "¿Eliminar Aplicación?",
"other": "¿Eliminar Aplicaciones?"
@@ -299,7 +293,7 @@
"other": "{} y {} aplicaciones más han sido actualizadas."
},
"xAndNMoreUpdatesPossiblyInstalled": {
"one": "Attempts were made to update {} and 1 more app.",
"other": "Attempts were made to update {} and {} more apps."
"one": "{} and 1 more app may have been updated.",
"other": "{} and {} more apps may have been updated."
}
}

View File

@@ -11,12 +11,6 @@
"unexpectedError": "خطای غیرمنتظره",
"ok": "باشه",
"and": "و",
"startedBgUpdateTask": "شروع بررسی بروزرسانی BG",
"bgUpdateIgnoreAfterIs": "نادیده گرفتن بروزرسانی BG بعد از {} است",
"startedActualBGUpdateCheck": "بررسی به‌روزرسانی واقعی BG آغاز شد",
"bgUpdateTaskFinished": "کار بررسی به‌روزرسانی BG تمام شد",
"firstRun": "این اولین اجرای Obtainium است",
"settingUpdateCheckIntervalTo": "تنظیم فاصله به‌روزرسانی روی {}",
"githubPATLabel": "توکن دسترسی شخصی گیت هاب(محدودیت نرخ را افزایش میدهد)",
"githubPATHint": "PAT باید در این قالب باشد: username:token",
"githubPATFormat": "username:token",
@@ -249,7 +243,7 @@
"customLinkFilterRegex": "فیلتر پیوند سفارشی بر اساس عبارت منظم (پیش‌فرض '.apk$')",
"appsPossiblyUpdated": "App Updates Attempted",
"appsPossiblyUpdatedNotifDescription": "Notifies the user that updates to one or more Apps were potentially applied in the background",
"xWasPossiblyUpdatedToY": "An attempt was made to update {} to {}.",
"xWasPossiblyUpdatedToY": "{} may have been updated to {}.",
"removeAppQuestion": {
"one": "برنامه حذف شود؟",
"other": "برنامه ها حذف شوند؟"
@@ -299,7 +293,7 @@
"other": "{} و {} برنامه دیگر به روز شدند."
},
"xAndNMoreUpdatesPossiblyInstalled": {
"one": "Attempts were made to update {} and 1 more app.",
"other": "Attempts were made to update {} and {} more apps."
"one": "{} and 1 more app may have been updated.",
"other": "{} and {} more apps may have been updated."
}
}

View File

@@ -11,12 +11,6 @@
"unexpectedError": "Erreur inattendue",
"ok": "Okay",
"and": "et",
"startedBgUpdateTask": "Démarrage de la tâche de vérification de mise à jour en arrière-plan",
"bgUpdateIgnoreAfterIs": "Mise à jour en arrière-plan est ignoré après {}",
"startedActualBGUpdateCheck": "Démarrage de la vérification de la mise à jour en arrière-plan",
"bgUpdateTaskFinished": "Tâche de vérification de la mise à jour en arrière-plan terminée",
"firstRun": "Il s'agit de la toute première exécution d'Obtainium",
"settingUpdateCheckIntervalTo": "Définition de l'intervalle de mise à jour sur {}",
"githubPATLabel": "Jeton d'Accès Personnel GitHub (Augmente la limite de débit)",
"githubPATHint": "Le JAP doit être dans ce format : username:token",
"githubPATFormat": "username:token",
@@ -249,7 +243,7 @@
"customLinkFilterRegex": "Custom Link Filter by Regular Expression (Default '.apk$')",
"appsPossiblyUpdated": "App Updates Attempted",
"appsPossiblyUpdatedNotifDescription": "Notifies the user that updates to one or more Apps were potentially applied in the background",
"xWasPossiblyUpdatedToY": "An attempt was made to update {} to {}.",
"xWasPossiblyUpdatedToY": "{} may have been updated to {}.",
"removeAppQuestion": {
"one": "Supprimer l'application ?",
"other": "Supprimer les applications ?"
@@ -299,7 +293,7 @@
"other": "{} et {} autres applications ont été mises à jour."
},
"xAndNMoreUpdatesPossiblyInstalled": {
"one": "Attempts were made to update {} and 1 more app.",
"other": "Attempts were made to update {} and {} more apps."
"one": "{} and 1 more app may have been updated.",
"other": "{} and {} more apps may have been updated."
}
}

View File

@@ -11,12 +11,6 @@
"unexpectedError": "Váratlan hiba",
"ok": "Oké",
"and": "és",
"startedBgUpdateTask": "Háttérfrissítés ellenőrzési feladat elindítva",
"bgUpdateIgnoreAfterIs": "Háttérfrissítés ignoreAfter a következő: {}",
"startedActualBGUpdateCheck": "Elkezdődött a tényleges háttérfrissítés ellenőrzése",
"bgUpdateTaskFinished": "A háttérfrissítés ellenőrzési feladat befejeződött",
"firstRun": "Ez az Obtainium első futása",
"settingUpdateCheckIntervalTo": "A frissítési intervallum beállítása erre: {}",
"githubPATLabel": "GitHub Personal Access Token (megnöveli a díjkorlátot)",
"githubPATHint": "A PAT-nak a következő formátumban kell lennie: felhasználónév:token",
"githubPATFormat": "felhasználónév:token",
@@ -248,7 +242,7 @@
"customLinkFilterRegex": "Custom Link Filter by Regular Expression (Default '.apk$')",
"appsPossiblyUpdated": "App Updates Attempted",
"appsPossiblyUpdatedNotifDescription": "Notifies the user that updates to one or more Apps were potentially applied in the background",
"xWasPossiblyUpdatedToY": "An attempt was made to update {} to {}.",
"xWasPossiblyUpdatedToY": "{} may have been updated to {}.",
"removeAppQuestion": {
"one": "Eltávolítja az alkalmazást?",
"other": "Eltávolítja az alkalmazást?"
@@ -298,7 +292,7 @@
"other": "{} és {} további alkalmazás frissítve."
},
"xAndNMoreUpdatesPossiblyInstalled": {
"one": "Attempts were made to update {} and 1 more app.",
"other": "Attempts were made to update {} and {} more apps."
"one": "{} and 1 more app may have been updated.",
"other": "{} and {} more apps may have been updated."
}
}

View File

@@ -11,12 +11,6 @@
"unexpectedError": "Errore imprevisto",
"ok": "Va bene",
"and": "e",
"startedBgUpdateTask": "Avviata l'attività di controllo degli aggiornamenti in secondo piano",
"bgUpdateIgnoreAfterIs": "Il parametro di agg. in secondo piano 'ignoreAfter' è {}",
"startedActualBGUpdateCheck": "Avviato il controllo effettivo degli aggiornamenti in secondo piano",
"bgUpdateTaskFinished": "Terminata l'attività di controllo degli aggiornamenti in secondo piano",
"firstRun": "Questo è il primo avvio di sempre di Obtainium",
"settingUpdateCheckIntervalTo": "Fissato intervallo di aggiornamento a {}",
"githubPATLabel": "GitHub Personal Access Token (diminuisce limite di traffico)",
"githubPATHint": "PAT deve seguire questo formato: nomeutente:token",
"githubPATFormat": "nomeutente:token",
@@ -249,7 +243,7 @@
"customLinkFilterRegex": "Custom Link Filter by Regular Expression (Default '.apk$')",
"appsPossiblyUpdated": "App Updates Attempted",
"appsPossiblyUpdatedNotifDescription": "Notifies the user that updates to one or more Apps were potentially applied in the background",
"xWasPossiblyUpdatedToY": "An attempt was made to update {} to {}.",
"xWasPossiblyUpdatedToY": "{} may have been updated to {}.",
"removeAppQuestion": {
"one": "Rimuovere l'app?",
"other": "Rimuovere le app?"
@@ -299,7 +293,7 @@
"other": "{} e altre {} app sono state aggiornate."
},
"xAndNMoreUpdatesPossiblyInstalled": {
"one": "Attempts were made to update {} and 1 more app.",
"other": "Attempts were made to update {} and {} more apps."
"one": "{} and 1 more app may have been updated.",
"other": "{} and {} more apps may have been updated."
}
}

View File

@@ -11,12 +11,6 @@
"unexpectedError": "予期せぬエラーが発生しました",
"ok": "OK",
"and": "と",
"startedBgUpdateTask": "バックグラウンドのアップデート確認タスクを開始",
"bgUpdateIgnoreAfterIs": "Bg update ignoreAfter is {}",
"startedActualBGUpdateCheck": "実際のバックグラウンドのアップデート確認を開始",
"bgUpdateTaskFinished": "バックグラウンドのアップデート確認タスクを終了",
"firstRun": "これがObtainiumの最初の実行です",
"settingUpdateCheckIntervalTo": "確認間隔を{}に設定する",
"githubPATLabel": "GitHub パーソナルアクセストークン (レート制限の引き上げ)",
"githubPATHint": "PATは次の形式でなければなりません: ユーザー名:トークン",
"githubPATFormat": "ユーザー名:トークン",
@@ -249,7 +243,7 @@
"customLinkFilterRegex": "正規表現によるカスタムリンクフィルター (デフォルト '.apk$')",
"appsPossiblyUpdated": "App Updates Attempted",
"appsPossiblyUpdatedNotifDescription": "Notifies the user that updates to one or more Apps were potentially applied in the background",
"xWasPossiblyUpdatedToY": "An attempt was made to update {} to {}.",
"xWasPossiblyUpdatedToY": "{} may have been updated to {}.",
"removeAppQuestion": {
"one": "アプリを削除しますか?",
"other": "アプリを削除しますか?"
@@ -299,7 +293,7 @@
"other": "{} とさらに {} 個のアプリがアップデートされました"
},
"xAndNMoreUpdatesPossiblyInstalled": {
"one": "Attempts were made to update {} and 1 more app.",
"other": "Attempts were made to update {} and {} more apps."
"one": "{} and 1 more app may have been updated.",
"other": "{} and {} more apps may have been updated."
}
}

View File

@@ -19,12 +19,6 @@
"unexpectedError": "Nieoczekiwany błąd",
"ok": "Okej",
"and": "i",
"startedBgUpdateTask": "Rozpoczęto zadanie sprawdzania aktualizacji w tle",
"bgUpdateIgnoreAfterIs": "Parametr ignoreAfter aktualizacji w tle to {}",
"startedActualBGUpdateCheck": "Rozpoczęto sprawdzanie aktualizacji w tle",
"bgUpdateTaskFinished": "Zakończono zadanie sprawdzania aktualizacji w tle",
"firstRun": "Jest to pierwsze uruchomienie Obtainium",
"settingUpdateCheckIntervalTo": "Ustawianie interwału aktualizacji na {}",
"githubPATLabel": "Osobisty token dostępu GitHub (zwiększa limit zapytań)",
"githubPATHint": "Wymagany format: użytkownik:token",
"githubPATFormat": "użytkownik:token",
@@ -253,7 +247,7 @@
"customLinkFilterRegex": "Niestandardowy filtr linków wg. wyrażenia regularnego (domyślnie \".apk$\")",
"appsPossiblyUpdated": "App Updates Attempted",
"appsPossiblyUpdatedNotifDescription": "Notifies the user that updates to one or more Apps were potentially applied in the background",
"xWasPossiblyUpdatedToY": "An attempt was made to update {} to {}.",
"xWasPossiblyUpdatedToY": "{} may have been updated to {}.",
"removeAppQuestion": {
"one": "Usunąć aplikację?",
"other": "Usunąć aplikacje?"
@@ -299,7 +293,7 @@
"other": "Zaktualizowano {} i {} aplik."
},
"xAndNMoreUpdatesPossiblyInstalled": {
"one": "Attempts were made to update {} and 1 more app.",
"other": "Attempts were made to update {} and {} more apps."
"one": "{} and 1 more app may have been updated.",
"other": "{} and {} more apps may have been updated."
}
}

View File

@@ -11,12 +11,6 @@
"unexpectedError": "Неожиданная ошибка",
"ok": "Окей",
"and": "и",
"startedBgUpdateTask": "Запущена задача фоновой проверки обновлений",
"bgUpdateIgnoreAfterIs": "Параметр игнорирования фоновых обновлений: {}",
"startedActualBGUpdateCheck": "Запущена фактическая проверка фоновых обновлений",
"bgUpdateTaskFinished": "Завершена задача фоновой проверки обновлений",
"firstRun": "Это первый запуск Obtainium",
"settingUpdateCheckIntervalTo": "Установка интервала проверки обновлений: {}",
"githubPATLabel": "Персональный токен доступа GitHub (увеличивает лимит запросов)",
"githubPATHint": "Токен доступа должен быть в формате: имя_пользователя:токен",
"githubPATFormat": "имя_пользователя:токен",
@@ -249,7 +243,7 @@
"customLinkFilterRegex": "Custom Link Filter by Regular Expression (Default '.apk$')",
"appsPossiblyUpdated": "App Updates Attempted",
"appsPossiblyUpdatedNotifDescription": "Notifies the user that updates to one or more Apps were potentially applied in the background",
"xWasPossiblyUpdatedToY": "An attempt was made to update {} to {}.",
"xWasPossiblyUpdatedToY": "{} may have been updated to {}.",
"removeAppQuestion": {
"one": "Удалить приложение?",
"other": "Удалить приложения?"
@@ -299,7 +293,7 @@
"other": "{} и еще {} приложений были обновлены."
},
"xAndNMoreUpdatesPossiblyInstalled": {
"one": "Attempts were made to update {} and 1 more app.",
"other": "Attempts were made to update {} and {} more apps."
"one": "{} and 1 more app may have been updated.",
"other": "{} and {} more apps may have been updated."
}
}

View File

@@ -11,12 +11,6 @@
"unexpectedError": "意外错误",
"ok": "好的",
"and": "和",
"startedBgUpdateTask": "后台更新检查任务已启动",
"bgUpdateIgnoreAfterIs": "后台更新检查间隔为 {}",
"startedActualBGUpdateCheck": "开始后台更新检查",
"bgUpdateTaskFinished": "后台更新检查任务已完成",
"firstRun": "这是 Obtainium 首次启动",
"settingUpdateCheckIntervalTo": "更新检查间隔设置为 {}",
"githubPATLabel": "GitHub 个人访问令牌(提升 API 请求限额)",
"githubPATHint": "个人访问令牌必须为“username:token”的格式",
"githubPATFormat": "username:token",
@@ -249,7 +243,7 @@
"customLinkFilterRegex": "用正则表达式自定义链接筛选(默认 '.apk$'",
"appsPossiblyUpdated": "App Updates Attempted",
"appsPossiblyUpdatedNotifDescription": "Notifies the user that updates to one or more Apps were potentially applied in the background",
"xWasPossiblyUpdatedToY": "An attempt was made to update {} to {}.",
"xWasPossiblyUpdatedToY": "{} may have been updated to {}.",
"removeAppQuestion": {
"one": "是否删除应用?",
"other": "是否删除应用?"
@@ -299,7 +293,7 @@
"other": "{} 和另外 {} 个应用已更新。"
},
"xAndNMoreUpdatesPossiblyInstalled": {
"one": "Attempts were made to update {} and 1 more app.",
"other": "Attempts were made to update {} and {} more apps."
"one": "{} and 1 more app may have been updated.",
"other": "{} and {} more apps may have been updated."
}
}

View File

@@ -1,5 +1,4 @@
import 'dart:io';
import 'dart:math';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
@@ -73,80 +72,80 @@ Future<void> loadTranslations() async {
}
@pragma('vm:entry-point')
Future<void> bgUpdateCheck(int taskId, Map<String, dynamic>? params) async {
Future<void> bgUpdateCheckApps(int taskId, Map<String, dynamic>? params) async {
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
await AndroidAlarmManager.initialize();
await loadTranslations();
LogsProvider logs = LogsProvider();
logs.add(tr('startedBgUpdateTask'));
int? ignoreAfterMicroseconds = params?['ignoreAfterMicroseconds'];
AppsProvider appsProvider = AppsProvider();
await appsProvider.loadApps();
logs.add('BG update master task started.');
var appIds = appsProvider.getAppsSortedByUpdateCheckTime();
for (var id in appIds) {
AndroidAlarmManager.oneShot(
const Duration(minutes: 0), id.hashCode, bgUpdateCheckApp,
params: {'appId': id});
await Future.delayed(const Duration(seconds: 1));
}
logs.add('BG update master task - all $appIds child tasks started.');
}
@pragma('vm:entry-point')
Future<void> bgUpdateCheckApp(int taskId, Map<String, dynamic>? params) async {
WidgetsFlutterBinding.ensureInitialized();
await EasyLocalization.ensureInitialized();
await AndroidAlarmManager.initialize();
DateTime? ignoreAfter = ignoreAfterMicroseconds != null
? DateTime.fromMicrosecondsSinceEpoch(ignoreAfterMicroseconds)
: null;
logs.add(tr('bgUpdateIgnoreAfterIs', args: [ignoreAfter.toString()]));
var notificationsProvider = NotificationsProvider();
await loadTranslations();
LogsProvider logs = LogsProvider();
NotificationsProvider notificationsProvider = NotificationsProvider();
AppsProvider appsProvider = AppsProvider();
String appId = params!['appId'];
try {
var appsProvider = AppsProvider();
await appsProvider.loadApps();
List<String> existingUpdateIds =
appsProvider.findExistingUpdates(installedOnly: true);
DateTime nextIgnoreAfter = DateTime.now();
String? err;
try {
logs.add(tr('startedActualBGUpdateCheck'));
await appsProvider.checkUpdates(
ignoreAppsCheckedAfter: ignoreAfter,
throwErrorsForRetry: true,
notificationsProvider: notificationsProvider);
} catch (e) {
if (e is RateLimitError || e is ClientException) {
var remainingMinutes = e is RateLimitError ? e.remainingMinutes : 15;
logs.add(
plural('bgUpdateGotErrorRetryInMinutes', remainingMinutes, args: [
e is ClientException
? '${(e).message}, ${e.uri?.path}'
: e.toString(),
remainingMinutes.toString()
]));
AndroidAlarmManager.oneShot(Duration(minutes: remainingMinutes),
Random().nextInt(pow(2, 31) as int), bgUpdateCheck, params: {
'ignoreAfterMicroseconds': nextIgnoreAfter.microsecondsSinceEpoch
});
} else {
err = e.toString();
await appsProvider.loadApps(singleId: appId);
AppInMemory app = appsProvider.apps[appId]!;
App? newApp;
if (app.app.installedVersion == app.app.latestVersion &&
app.app.installedVersion != null) {
try {
notificationsProvider.notify(checkingUpdatesNotification,
cancelExisting: true);
newApp = await appsProvider.checkUpdate(appId);
} catch (e) {
logs.add('BG update check for $appId got error \'${e.toString()}\'.');
if (e is RateLimitError || e is ClientException) {
var remainingMinutes = e is RateLimitError ? e.remainingMinutes : 15;
logs.add(
'BG update check for $appId will be retried in $remainingMinutes minutes.');
AndroidAlarmManager.oneShot(
Duration(minutes: remainingMinutes), taskId, bgUpdateCheckApp,
params: params);
} else {
rethrow;
}
} finally {
notificationsProvider.cancel(checkingUpdatesNotification.id);
}
}
List<App> newUpdates = appsProvider
.findExistingUpdates(installedOnly: true)
.where((id) => !existingUpdateIds.contains(id))
.map((e) => appsProvider.apps[e]!.app)
.toList();
List<App> nonSilentUpdates = [];
List<App> silentUpdates = [];
for (var a in newUpdates) {
if (await appsProvider.canInstallSilently(a)) {
silentUpdates.add(a);
if (newApp != null) {
var canInstallSilently = await appsProvider.canInstallSilently(app.app);
if (!canInstallSilently) {
notificationsProvider
.notify(UpdateNotification([newApp], id: newApp.id.hashCode * 10));
} else {
nonSilentUpdates.add(a);
logs.add('Attempting to update $appId in the background.');
await appsProvider.downloadAndInstallLatestApps([appId], null,
notificationsProvider: notificationsProvider);
}
}
if (silentUpdates.isNotEmpty) {
await appsProvider.downloadAndInstallLatestApps(
silentUpdates.map((e) => e.id).toList(), null,
notificationsProvider: notificationsProvider);
}
logs.add(plural(
'bgCheckFoundUpdatesWillNotifyIfNeeded', nonSilentUpdates.length));
if (err != null) {
throw err;
}
} catch (e) {
logs.add('${tr('errorCheckingUpdates')}: ${e.toString()}');
} finally {
logs.add(tr('bgUpdateTaskFinished'));
notificationsProvider.notify(ErrorCheckingUpdatesNotification(
'$appId: ${e.toString()}',
id: appId.hashCode * 20));
}
}
@@ -207,7 +206,7 @@ class _ObtainiumState extends State<Obtainium> {
} else {
bool isFirstRun = settingsProvider.checkAndFlipFirstRun();
if (isFirstRun) {
logs.add(tr('firstRun'));
logs.add('This is the first ever run of Obtainium.');
// If this is the first run, ask for notification permissions and add Obtainium to the Apps list
Permission.notification.request();
appsProvider.saveApps([
@@ -236,8 +235,8 @@ class _ObtainiumState extends State<Obtainium> {
// Register the background update task according to the user's setting
if (existingUpdateInterval != settingsProvider.updateInterval) {
if (existingUpdateInterval != -1) {
logs.add(tr('settingUpdateCheckIntervalTo',
args: [settingsProvider.updateInterval.toString()]));
logs.add(
'Setting update interval to ${settingsProvider.updateInterval.toString()}');
}
existingUpdateInterval = settingsProvider.updateInterval;
if (existingUpdateInterval == 0) {
@@ -246,7 +245,8 @@ class _ObtainiumState extends State<Obtainium> {
AndroidAlarmManager.periodic(
Duration(minutes: existingUpdateInterval),
bgUpdateCheckAlarmId,
bgUpdateCheck,
bgUpdateCheckApps,
allowWhileIdle: true,
rescheduleOnReboot: true,
wakeup: true);
}

View File

@@ -765,7 +765,7 @@ class AppsProvider with ChangeNotifier {
: false;
}
Future<void> loadApps() async {
Future<void> loadApps({String? singleId}) async {
while (loadingApps) {
await Future.delayed(const Duration(microseconds: 1));
}
@@ -776,6 +776,10 @@ class AppsProvider with ChangeNotifier {
List<App?> newApps = (await getAppsDir()) // Parse Apps from JSON
.listSync()
.where((item) => item.path.toLowerCase().endsWith('.json'))
.where((item) =>
singleId == null ||
item.path.split('/').last.toLowerCase() ==
'${singleId.toLowerCase()}.json')
.map((e) {
try {
return App.fromJson(jsonDecode(File(e.path).readAsStringSync()));
@@ -986,26 +990,32 @@ class AppsProvider with ChangeNotifier {
return newApp.latestVersion != currentApp.latestVersion ? newApp : null;
}
List<String> getAppsSortedByUpdateCheckTime(
{DateTime? ignoreAppsCheckedAfter}) {
List<String> appIds = apps.values
.where((app) =>
app.app.lastUpdateCheck == null ||
ignoreAppsCheckedAfter == null ||
app.app.lastUpdateCheck!.isBefore(ignoreAppsCheckedAfter))
.map((e) => e.app.id)
.toList();
appIds.sort((a, b) =>
(apps[a]!.app.lastUpdateCheck ?? DateTime.fromMicrosecondsSinceEpoch(0))
.compareTo(apps[b]!.app.lastUpdateCheck ??
DateTime.fromMicrosecondsSinceEpoch(0)));
return appIds;
}
Future<List<App>> checkUpdates(
{DateTime? ignoreAppsCheckedAfter,
bool throwErrorsForRetry = false,
NotificationsProvider? notificationsProvider}) async {
bool throwErrorsForRetry = false}) async {
List<App> updates = [];
MultiAppMultiError errors = MultiAppMultiError();
if (!gettingUpdates) {
gettingUpdates = true;
try {
List<String> appIds = apps.values
.where((app) =>
app.app.lastUpdateCheck == null ||
ignoreAppsCheckedAfter == null ||
app.app.lastUpdateCheck!.isBefore(ignoreAppsCheckedAfter))
.map((e) => e.app.id)
.toList();
appIds.sort((a, b) => (apps[a]!.app.lastUpdateCheck ??
DateTime.fromMicrosecondsSinceEpoch(0))
.compareTo(apps[b]!.app.lastUpdateCheck ??
DateTime.fromMicrosecondsSinceEpoch(0)));
List<String> appIds = getAppsSortedByUpdateCheckTime(
ignoreAppsCheckedAfter: ignoreAppsCheckedAfter);
for (int i = 0; i < appIds.length; i++) {
App? newApp;
try {
@@ -1016,14 +1026,9 @@ class AppsProvider with ChangeNotifier {
rethrow;
}
errors.add(appIds[i], e.toString());
notificationsProvider?.notify(ErrorCheckingUpdatesNotification(
'${appIds[i]}: ${e.toString()}',
id: appIds[i].hashCode));
}
if (newApp != null) {
updates.add(newApp);
notificationsProvider
?.notify(UpdateNotification([newApp], id: newApp.id.hashCode));
}
}
} finally {