ente/mobile/lib/main.dart

385 lines
13 KiB
Dart
Raw Normal View History

2020-05-02 11:46:59 +00:00
import 'dart:async';
import 'dart:io';
2020-05-02 11:46:59 +00:00
import "package:adaptive_theme/adaptive_theme.dart";
2021-01-13 17:39:45 +00:00
import 'package:background_fetch/background_fetch.dart';
import "package:computer/computer.dart";
2021-10-13 05:24:49 +00:00
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
2020-03-24 19:59:36 +00:00
import 'package:flutter/material.dart';
import "package:flutter/rendering.dart";
import "package:flutter_displaymode/flutter_displaymode.dart";
2021-07-21 20:47:43 +00:00
import 'package:logging/logging.dart';
import "package:media_kit/media_kit.dart";
2020-05-02 16:28:54 +00:00
import 'package:path_provider/path_provider.dart';
2021-11-24 07:26:07 +00:00
import 'package:photos/app.dart';
import 'package:photos/core/configuration.dart';
2021-07-21 20:47:43 +00:00
import 'package:photos/core/constants.dart';
import 'package:photos/core/error-reporting/super_logging.dart';
import 'package:photos/core/errors.dart';
2023-02-03 07:39:04 +00:00
import 'package:photos/core/network/network.dart';
import 'package:photos/db/upload_locks_db.dart';
2022-06-21 14:37:17 +00:00
import 'package:photos/ente_theme_data.dart';
2023-04-10 11:26:44 +00:00
import "package:photos/l10n/l10n.dart";
import 'package:photos/services/app_lifecycle_service.dart';
2021-01-08 06:38:45 +00:00
import 'package:photos/services/billing_service.dart';
import 'package:photos/services/collections_service.dart';
2023-04-04 08:48:54 +00:00
import "package:photos/services/entity_service.dart";
import 'package:photos/services/favorites_service.dart';
import 'package:photos/services/feature_flag_service.dart';
import 'package:photos/services/home_widget_service.dart';
2022-08-01 11:05:16 +00:00
import 'package:photos/services/local_file_update_service.dart';
import 'package:photos/services/local_sync_service.dart';
2023-03-07 02:12:54 +00:00
import "package:photos/services/location_service.dart";
2024-02-17 13:10:20 +00:00
import "package:photos/services/machine_learning/machine_learning_controller.dart";
import 'package:photos/services/machine_learning/semantic_search/semantic_search_service.dart';
2020-10-03 17:56:18 +00:00
import 'package:photos/services/memories_service.dart';
2021-10-12 09:12:28 +00:00
import 'package:photos/services/push_service.dart';
import 'package:photos/services/remote_sync_service.dart';
import 'package:photos/services/search_service.dart';
2023-02-15 16:47:40 +00:00
import "package:photos/services/storage_bonus_service.dart";
2020-10-03 17:58:26 +00:00
import 'package:photos/services/sync_service.dart';
2021-10-12 19:27:11 +00:00
import 'package:photos/services/trash_sync_service.dart';
2021-05-22 18:29:09 +00:00
import 'package:photos/services/update_service.dart';
2022-09-20 06:05:34 +00:00
import 'package:photos/services/user_remote_flag_service.dart';
import 'package:photos/services/user_service.dart';
2022-07-01 14:39:02 +00:00
import 'package:photos/ui/tools/app_lock.dart';
import 'package:photos/ui/tools/lock_screen.dart';
import 'package:photos/utils/crypto_util.dart';
import 'package:photos/utils/file_uploader.dart';
import 'package:photos/utils/local_settings.dart';
import 'package:shared_preferences/shared_preferences.dart';
2021-08-15 19:35:16 +00:00
2020-08-21 23:28:52 +00:00
final _logger = Logger("main");
2021-03-01 22:09:15 +00:00
2021-11-27 15:45:56 +00:00
bool _isProcessRunning = false;
const kLastBGTaskHeartBeatTime = "bg_task_hb_time";
const kLastFGTaskHeartBeatTime = "fg_task_hb_time";
const kHeartBeatFrequency = Duration(seconds: 1);
2023-06-30 13:18:38 +00:00
const kFGSyncFrequency = Duration(minutes: 5);
const kFGHomeWidgetSyncFrequency = Duration(minutes: 15);
const kBGTaskTimeout = Duration(seconds: 25);
const kBGPushTimeout = Duration(seconds: 28);
const kFGTaskDeathTimeoutInMicroseconds = 5000000;
const kBackgroundLockLatency = Duration(seconds: 3);
2020-03-24 19:59:36 +00:00
void main() async {
debugRepaintRainbowEnabled = false;
2020-03-24 19:59:36 +00:00
WidgetsFlutterBinding.ensureInitialized();
MediaKit.ensureInitialized();
2024-02-09 18:50:31 +00:00
final savedThemeMode = await AdaptiveTheme.getThemeMode();
await _runInForeground(savedThemeMode);
2023-12-02 11:42:52 +00:00
unawaited(BackgroundFetch.registerHeadlessTask(_headlessTaskHandler));
if (Platform.isAndroid) FlutterDisplayMode.setHighRefreshRate().ignore();
2020-05-02 16:28:54 +00:00
}
Future<void> _runInForeground(AdaptiveThemeMode? savedThemeMode) async {
2021-03-01 23:36:58 +00:00
return await _runWithLogs(() async {
2021-03-01 22:09:15 +00:00
_logger.info("Starting app in foreground");
2022-03-07 20:18:50 +00:00
await _init(false, via: 'mainMethod');
2023-04-10 11:26:44 +00:00
final Locale locale = await getLocale();
if (Platform.isAndroid) {
unawaited(_scheduleFGHomeWidgetSync());
}
2022-11-06 10:36:33 +00:00
unawaited(_scheduleFGSync('appStart in FG'));
2024-02-09 18:50:31 +00:00
2022-06-11 08:23:52 +00:00
runApp(
AppLock(
builder: (args) =>
2023-04-10 11:26:44 +00:00
EnteApp(_runBackgroundTask, _killBGTask, locale, savedThemeMode),
lockScreen: const LockScreen(),
2022-06-11 08:23:52 +00:00
enabled: Configuration.instance.shouldShowLockScreen(),
2023-04-10 11:26:44 +00:00
locale: locale,
2022-06-11 08:23:52 +00:00
lightTheme: lightThemeData,
darkTheme: darkThemeData,
backgroundLockLatency: kBackgroundLockLatency,
savedThemeMode: _themeMode(savedThemeMode),
2022-06-11 08:23:52 +00:00
),
);
2021-03-01 22:09:15 +00:00
});
}
2020-05-02 11:46:59 +00:00
ThemeMode _themeMode(AdaptiveThemeMode? savedThemeMode) {
if (savedThemeMode == null) return ThemeMode.system;
if (savedThemeMode.isLight) return ThemeMode.light;
if (savedThemeMode.isDark) return ThemeMode.dark;
return ThemeMode.system;
}
Future<void> _homeWidgetSync() async {
if (!Platform.isAndroid) return;
try {
if (await HomeWidgetService.instance.countHomeWidgets() != 0) {
await HomeWidgetService.instance.initHomeWidget();
}
} catch (e, s) {
_logger.severe("Error in initSlideshowWidget", e, s);
}
}
2022-10-18 08:08:09 +00:00
Future<void> _runBackgroundTask(String taskId, {String mode = 'normal'}) async {
if (_isProcessRunning) {
_logger.info("Background task triggered when process was already running");
2022-03-08 07:17:19 +00:00
await _sync('bgTaskActiveProcess');
BackgroundFetch.finish(taskId);
} else {
2023-12-16 21:04:26 +00:00
// ignore: unawaited_futures
2022-06-11 08:23:52 +00:00
_runWithLogs(
() async {
2022-10-18 08:08:09 +00:00
_logger.info("Starting background task in $mode mode");
2023-12-16 21:04:26 +00:00
// ignore: unawaited_futures
2022-06-11 08:23:52 +00:00
_runInBackground(taskId);
},
prefix: "[bg]",
);
}
}
Future<void> _runInBackground(String taskId) async {
2022-07-04 06:02:17 +00:00
await Future.delayed(const Duration(seconds: 3));
if (await _isRunningInForeground()) {
2022-03-07 20:18:50 +00:00
_logger.info("FG task running, skipping BG taskID: $taskId");
2021-03-01 22:09:15 +00:00
BackgroundFetch.finish(taskId);
return;
} else {
_logger.info("FG task is not running");
2021-03-01 22:09:15 +00:00
}
_logger.info("[BackgroundFetch] Event received: $taskId");
_scheduleBGTaskKill(taskId);
if (Platform.isIOS) {
2022-03-07 20:18:50 +00:00
_scheduleSuicide(kBGTaskTimeout, taskId); // To prevent OS from punishing us
}
2022-03-07 20:18:50 +00:00
await _init(true, via: 'runViaBackgroundTask');
await Future.wait(
[
_homeWidgetSync(),
() async {
UpdateService.instance.showUpdateNotification().ignore();
await _sync('bgSync');
}(),
],
);
BackgroundFetch.finish(taskId);
2021-03-01 22:09:15 +00:00
}
2020-05-02 11:46:59 +00:00
// https://stackoverflow.com/a/73796478/546896
@pragma('vm:entry-point')
2021-03-01 22:09:15 +00:00
void _headlessTaskHandler(HeadlessTask task) {
2023-03-07 15:09:11 +00:00
debugPrint("_headlessTaskHandler");
2021-03-01 22:09:15 +00:00
if (task.timeout) {
BackgroundFetch.finish(task.taskId);
} else {
2022-10-18 08:08:09 +00:00
_runBackgroundTask(task.taskId, mode: "headless");
2021-03-01 22:09:15 +00:00
}
2021-01-13 17:39:45 +00:00
}
2022-03-07 20:18:50 +00:00
Future<void> _init(bool isBackground, {String via = ''}) async {
2021-11-27 15:45:56 +00:00
_isProcessRunning = true;
2022-03-07 20:18:50 +00:00
_logger.info("Initializing... inBG =$isBackground via: $via");
final SharedPreferences preferences = await SharedPreferences.getInstance();
2022-03-07 20:18:50 +00:00
await _logFGHeartBeatInfo();
2023-12-16 21:04:26 +00:00
unawaited(_scheduleHeartBeat(preferences, isBackground));
2023-06-26 07:51:31 +00:00
AppLifecycleService.instance.init(preferences);
2021-11-15 15:35:07 +00:00
if (isBackground) {
2022-03-07 20:18:50 +00:00
AppLifecycleService.instance.onAppInBackground('init via: $via');
2021-11-15 15:35:07 +00:00
} else {
2022-03-07 20:18:50 +00:00
AppLifecycleService.instance.onAppInForeground('init via: $via');
2021-11-15 15:35:07 +00:00
}
2023-04-29 07:05:18 +00:00
// Start workers asynchronously. No need to wait for them to start
2023-12-16 11:21:53 +00:00
Computer.shared().turnOn(workersCount: 4).ignore();
CryptoUtil.init();
2021-01-13 17:39:45 +00:00
await Configuration.instance.init();
await NetworkClient.instance.init();
2022-06-23 13:17:31 +00:00
await UserService.instance.init();
2023-04-04 08:48:54 +00:00
await EntityService.instance.init();
2023-04-03 10:08:53 +00:00
LocationService.instance.init(preferences);
2023-04-04 08:48:54 +00:00
2022-09-20 06:05:34 +00:00
await UserRemoteFlagService.instance.init();
2021-05-22 18:29:09 +00:00
await UpdateService.instance.init();
BillingService.instance.init();
await CollectionsService.instance.init(preferences);
FavoritesService.instance.initFav().ignore();
await FileUploader.instance.init(preferences, isBackground);
await LocalSyncService.instance.init(preferences);
TrashSyncService.instance.init(preferences);
RemoteSyncService.instance.init(preferences);
await SyncService.instance.init(preferences);
MemoriesService.instance.init(preferences);
LocalSettings.instance.init(preferences);
LocalFileUpdateService.instance.init(preferences);
SearchService.instance.init();
2023-02-15 16:47:40 +00:00
StorageBonusService.instance.init(preferences);
if (!isBackground &&
Platform.isAndroid &&
await HomeWidgetService.instance.countHomeWidgets() == 0) {
unawaited(HomeWidgetService.instance.initHomeWidget());
}
2021-11-25 10:35:38 +00:00
if (Platform.isIOS) {
2023-12-16 21:04:26 +00:00
// ignore: unawaited_futures
2021-11-25 10:35:38 +00:00
PushService.instance.init().then((_) {
FirebaseMessaging.onBackgroundMessage(
2022-06-11 08:23:52 +00:00
_firebaseMessagingBackgroundHandler,
);
2021-11-25 10:35:38 +00:00
});
}
2023-12-16 21:04:26 +00:00
unawaited(FeatureFlagService.instance.init());
2024-01-05 11:21:54 +00:00
unawaited(SemanticSearchService.instance.init());
2024-02-17 13:10:20 +00:00
MachineLearningController.instance.init();
2023-05-10 10:01:38 +00:00
// Can not including existing tf/ml binaries as they are not being built
// from source.
// See https://gitlab.com/fdroid/fdroiddata/-/merge_requests/12671#note_1294346819
// if (!UpdateService.instance.isFdroidFlavor()) {
// unawaited(ObjectDetectionService.instance.init());
// }
2021-02-06 16:11:27 +00:00
_logger.info("Initialization done");
2020-05-02 11:46:59 +00:00
}
2022-03-08 07:17:19 +00:00
Future<void> _sync(String caller) async {
2021-11-15 15:35:07 +00:00
if (!AppLifecycleService.instance.isForeground) {
2022-03-08 07:17:19 +00:00
_logger.info("Syncing in background caller $caller");
} else {
_logger.info("Syncing in foreground caller $caller");
2021-02-26 14:09:45 +00:00
}
2021-01-13 17:39:45 +00:00
try {
await SyncService.instance.sync();
2021-01-13 17:39:45 +00:00
} catch (e, s) {
if (!isHandledSyncError(e)) {
_logger.severe("Sync error", e, s);
}
2021-01-13 17:39:45 +00:00
}
}
Future _runWithLogs(Function() function, {String prefix = ""}) async {
2022-06-11 08:23:52 +00:00
await SuperLogging.main(
LogConfig(
body: function,
logDirPath: (await getApplicationSupportDirectory()).path + "/logs",
2022-06-11 08:23:52 +00:00
maxLogFiles: 5,
sentryDsn: kDebugMode ? sentryDebugDSN : sentryDSN,
tunnel: sentryTunnel,
2022-06-11 08:23:52 +00:00
enableInDebugMode: true,
prefix: prefix,
),
);
}
Future<void> _scheduleHeartBeat(
SharedPreferences prefs,
bool isBackground,
) async {
await prefs.setInt(
2022-06-11 08:23:52 +00:00
isBackground ? kLastBGTaskHeartBeatTime : kLastFGTaskHeartBeatTime,
DateTime.now().microsecondsSinceEpoch,
);
Future.delayed(kHeartBeatFrequency, () async {
2023-12-16 21:04:26 +00:00
// ignore: unawaited_futures
_scheduleHeartBeat(prefs, isBackground);
});
}
Future<void> _scheduleFGHomeWidgetSync() async {
Future.delayed(kFGHomeWidgetSyncFrequency, () async {
unawaited(_homeWidgetSyncPeriodic());
});
}
Future<void> _homeWidgetSyncPeriodic() async {
await _homeWidgetSync();
Future.delayed(kFGHomeWidgetSyncFrequency, () async {
unawaited(_homeWidgetSyncPeriodic());
});
}
2022-03-08 07:17:19 +00:00
Future<void> _scheduleFGSync(String caller) async {
await _sync(caller);
Future.delayed(kFGSyncFrequency, () async {
2022-11-06 10:36:33 +00:00
unawaited(_scheduleFGSync('fgSyncCron'));
});
}
void _scheduleBGTaskKill(String taskId) async {
if (await _isRunningInForeground()) {
2022-03-07 20:18:50 +00:00
_logger.info("Found app in FG, committing seppuku. $taskId");
2021-05-07 17:44:19 +00:00
await _killBGTask(taskId);
return;
}
Future.delayed(kHeartBeatFrequency, () async {
_scheduleBGTaskKill(taskId);
});
}
Future<bool> _isRunningInForeground() async {
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
final currentTime = DateTime.now().microsecondsSinceEpoch;
2023-03-31 12:41:08 +00:00
final lastFGHeartBeatTime = DateTime.fromMicrosecondsSinceEpoch(
prefs.getInt(kLastFGTaskHeartBeatTime) ?? 0,
);
return lastFGHeartBeatTime.microsecondsSinceEpoch >
(currentTime - kFGTaskDeathTimeoutInMicroseconds);
}
Future<void> _killBGTask([String? taskId]) async {
2021-05-07 17:44:19 +00:00
await UploadLocksDB.instance.releaseLocksAcquiredByOwnerBefore(
2022-06-11 08:23:52 +00:00
ProcessType.background.toString(),
DateTime.now().microsecondsSinceEpoch,
);
2021-05-07 17:44:19 +00:00
final prefs = await SharedPreferences.getInstance();
2023-12-16 21:04:26 +00:00
await prefs.remove(kLastBGTaskHeartBeatTime);
if (taskId != null) {
BackgroundFetch.finish(taskId);
}
2021-05-07 17:44:19 +00:00
}
2021-10-13 05:24:49 +00:00
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
2022-08-29 14:43:31 +00:00
final bool isRunningInFG = await _isRunningInForeground(); // hb
final bool isInForeground = AppLifecycleService.instance.isForeground;
2021-11-27 15:45:56 +00:00
if (_isProcessRunning) {
2022-03-07 20:18:50 +00:00
_logger.info(
2022-06-11 08:23:52 +00:00
"Background push received when app is alive and runningInFS: $isRunningInFG inForeground: $isInForeground",
);
2021-11-27 15:45:56 +00:00
if (PushService.shouldSync(message)) {
2022-03-08 07:17:19 +00:00
await _sync('firebaseBgSyncActiveProcess');
2021-11-27 15:45:56 +00:00
}
} else {
2021-10-13 05:24:49 +00:00
// App is dead
2023-12-16 21:04:26 +00:00
// ignore: unawaited_futures
2022-06-11 08:23:52 +00:00
_runWithLogs(
() async {
_logger.info("Background push received");
if (Platform.isIOS) {
_scheduleSuicide(kBGPushTimeout); // To prevent OS from punishing us
}
await _init(true, via: 'firebasePush');
if (PushService.shouldSync(message)) {
await _sync('firebaseBgSyncNoActiveProcess');
}
},
prefix: "[fbg]",
);
2021-10-13 05:24:49 +00:00
}
}
2022-03-07 20:18:50 +00:00
Future<void> _logFGHeartBeatInfo() async {
2022-08-29 14:43:31 +00:00
final bool isRunningInFG = await _isRunningInForeground();
2022-03-07 20:18:50 +00:00
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
2022-08-29 14:43:31 +00:00
final lastFGTaskHeartBeatTime = prefs.getInt(kLastFGTaskHeartBeatTime) ?? 0;
final String lastRun = lastFGTaskHeartBeatTime == 0
2022-03-07 20:18:50 +00:00
? 'never'
: DateTime.fromMicrosecondsSinceEpoch(lastFGTaskHeartBeatTime).toString();
_logger.info('isAlreaduunningFG: $isRunningInFG, last Beat: $lastRun');
}
void _scheduleSuicide(Duration duration, [String? taskID]) {
2022-08-29 14:43:31 +00:00
final taskIDVal = taskID ?? 'no taskID';
2022-03-07 20:18:50 +00:00
_logger.warning("Schedule seppuku taskID: $taskIDVal");
Future.delayed(duration, () {
2022-03-07 20:18:50 +00:00
_logger.warning("TLE, committing seppuku for taskID: $taskIDVal");
_killBGTask(taskID);
});
}