main.dart 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. import 'dart:async';
  2. import 'dart:io';
  3. import "package:adaptive_theme/adaptive_theme.dart";
  4. import 'package:background_fetch/background_fetch.dart';
  5. import "package:computer/computer.dart";
  6. import 'package:firebase_messaging/firebase_messaging.dart';
  7. import 'package:flutter/foundation.dart';
  8. import 'package:flutter/material.dart';
  9. import "package:flutter/rendering.dart";
  10. import "package:flutter_displaymode/flutter_displaymode.dart";
  11. import 'package:logging/logging.dart';
  12. import "package:media_kit/media_kit.dart";
  13. import 'package:path_provider/path_provider.dart';
  14. import 'package:photos/app.dart';
  15. import 'package:photos/core/configuration.dart';
  16. import 'package:photos/core/constants.dart';
  17. import 'package:photos/core/error-reporting/super_logging.dart';
  18. import 'package:photos/core/errors.dart';
  19. import 'package:photos/core/network/network.dart';
  20. import 'package:photos/db/upload_locks_db.dart';
  21. import 'package:photos/ente_theme_data.dart';
  22. import "package:photos/l10n/l10n.dart";
  23. import 'package:photos/services/app_lifecycle_service.dart';
  24. import 'package:photos/services/billing_service.dart';
  25. import 'package:photos/services/collections_service.dart';
  26. import "package:photos/services/entity_service.dart";
  27. import 'package:photos/services/favorites_service.dart';
  28. import 'package:photos/services/feature_flag_service.dart';
  29. import 'package:photos/services/local_file_update_service.dart';
  30. import 'package:photos/services/local_sync_service.dart';
  31. import "package:photos/services/location_service.dart";
  32. import 'package:photos/services/memories_service.dart';
  33. import 'package:photos/services/push_service.dart';
  34. import 'package:photos/services/remote_sync_service.dart';
  35. import 'package:photos/services/search_service.dart';
  36. import 'package:photos/services/semantic_search/semantic_search_service.dart';
  37. import "package:photos/services/storage_bonus_service.dart";
  38. import 'package:photos/services/sync_service.dart';
  39. import 'package:photos/services/trash_sync_service.dart';
  40. import 'package:photos/services/update_service.dart';
  41. import 'package:photos/services/user_remote_flag_service.dart';
  42. import 'package:photos/services/user_service.dart';
  43. import 'package:photos/ui/tools/app_lock.dart';
  44. import 'package:photos/ui/tools/lock_screen.dart';
  45. import 'package:photos/utils/crypto_util.dart';
  46. import 'package:photos/utils/file_uploader.dart';
  47. import 'package:photos/utils/local_settings.dart';
  48. import 'package:shared_preferences/shared_preferences.dart';
  49. final _logger = Logger("main");
  50. bool _isProcessRunning = false;
  51. const kLastBGTaskHeartBeatTime = "bg_task_hb_time";
  52. const kLastFGTaskHeartBeatTime = "fg_task_hb_time";
  53. const kHeartBeatFrequency = Duration(seconds: 1);
  54. const kFGSyncFrequency = Duration(minutes: 5);
  55. const kBGTaskTimeout = Duration(seconds: 25);
  56. const kBGPushTimeout = Duration(seconds: 28);
  57. const kFGTaskDeathTimeoutInMicroseconds = 5000000;
  58. const kBackgroundLockLatency = Duration(seconds: 3);
  59. void main() async {
  60. debugRepaintRainbowEnabled = false;
  61. WidgetsFlutterBinding.ensureInitialized();
  62. MediaKit.ensureInitialized();
  63. final savedThemeMode = await AdaptiveTheme.getThemeMode();
  64. await _runInForeground(savedThemeMode);
  65. unawaited(BackgroundFetch.registerHeadlessTask(_headlessTaskHandler));
  66. if (Platform.isAndroid) FlutterDisplayMode.setHighRefreshRate().ignore();
  67. }
  68. Future<void> _runInForeground(AdaptiveThemeMode? savedThemeMode) async {
  69. return await _runWithLogs(() async {
  70. _logger.info("Starting app in foreground");
  71. await _init(false, via: 'mainMethod');
  72. final Locale locale = await getLocale();
  73. unawaited(_scheduleFGSync('appStart in FG'));
  74. runApp(
  75. AppLock(
  76. builder: (args) =>
  77. EnteApp(_runBackgroundTask, _killBGTask, locale, savedThemeMode),
  78. lockScreen: const LockScreen(),
  79. enabled: Configuration.instance.shouldShowLockScreen(),
  80. locale: locale,
  81. lightTheme: lightThemeData,
  82. darkTheme: darkThemeData,
  83. backgroundLockLatency: kBackgroundLockLatency,
  84. savedThemeMode: _themeMode(savedThemeMode),
  85. ),
  86. );
  87. });
  88. }
  89. ThemeMode _themeMode(AdaptiveThemeMode? savedThemeMode) {
  90. if (savedThemeMode == null) return ThemeMode.system;
  91. if (savedThemeMode.isLight) return ThemeMode.light;
  92. if (savedThemeMode.isDark) return ThemeMode.dark;
  93. return ThemeMode.system;
  94. }
  95. Future<void> _runBackgroundTask(String taskId, {String mode = 'normal'}) async {
  96. if (_isProcessRunning) {
  97. _logger.info("Background task triggered when process was already running");
  98. await _sync('bgTaskActiveProcess');
  99. BackgroundFetch.finish(taskId);
  100. } else {
  101. // ignore: unawaited_futures
  102. _runWithLogs(
  103. () async {
  104. _logger.info("Starting background task in $mode mode");
  105. // ignore: unawaited_futures
  106. _runInBackground(taskId);
  107. },
  108. prefix: "[bg]",
  109. );
  110. }
  111. }
  112. Future<void> _runInBackground(String taskId) async {
  113. await Future.delayed(const Duration(seconds: 3));
  114. if (await _isRunningInForeground()) {
  115. _logger.info("FG task running, skipping BG taskID: $taskId");
  116. BackgroundFetch.finish(taskId);
  117. return;
  118. } else {
  119. _logger.info("FG task is not running");
  120. }
  121. _logger.info("[BackgroundFetch] Event received: $taskId");
  122. _scheduleBGTaskKill(taskId);
  123. if (Platform.isIOS) {
  124. _scheduleSuicide(kBGTaskTimeout, taskId); // To prevent OS from punishing us
  125. }
  126. await _init(true, via: 'runViaBackgroundTask');
  127. UpdateService.instance.showUpdateNotification().ignore();
  128. await _sync('bgSync');
  129. BackgroundFetch.finish(taskId);
  130. }
  131. // https://stackoverflow.com/a/73796478/546896
  132. @pragma('vm:entry-point')
  133. void _headlessTaskHandler(HeadlessTask task) {
  134. debugPrint("_headlessTaskHandler");
  135. if (task.timeout) {
  136. BackgroundFetch.finish(task.taskId);
  137. } else {
  138. _runBackgroundTask(task.taskId, mode: "headless");
  139. }
  140. }
  141. Future<void> _init(bool isBackground, {String via = ''}) async {
  142. _isProcessRunning = true;
  143. _logger.info("Initializing... inBG =$isBackground via: $via");
  144. final SharedPreferences preferences = await SharedPreferences.getInstance();
  145. await _logFGHeartBeatInfo();
  146. unawaited(_scheduleHeartBeat(preferences, isBackground));
  147. AppLifecycleService.instance.init(preferences);
  148. if (isBackground) {
  149. AppLifecycleService.instance.onAppInBackground('init via: $via');
  150. } else {
  151. AppLifecycleService.instance.onAppInForeground('init via: $via');
  152. }
  153. // Start workers asynchronously. No need to wait for them to start
  154. Computer.shared().turnOn(workersCount: 4).ignore();
  155. CryptoUtil.init();
  156. await NetworkClient.instance.init();
  157. await Configuration.instance.init();
  158. await UserService.instance.init();
  159. await EntityService.instance.init();
  160. LocationService.instance.init(preferences);
  161. await UserRemoteFlagService.instance.init();
  162. await UpdateService.instance.init();
  163. BillingService.instance.init();
  164. await CollectionsService.instance.init(preferences);
  165. FavoritesService.instance.initFav().ignore();
  166. await FileUploader.instance.init(preferences, isBackground);
  167. await LocalSyncService.instance.init(preferences);
  168. TrashSyncService.instance.init(preferences);
  169. RemoteSyncService.instance.init(preferences);
  170. await SyncService.instance.init(preferences);
  171. MemoriesService.instance.init(preferences);
  172. LocalSettings.instance.init(preferences);
  173. LocalFileUpdateService.instance.init(preferences);
  174. SearchService.instance.init();
  175. StorageBonusService.instance.init(preferences);
  176. if (Platform.isIOS) {
  177. // ignore: unawaited_futures
  178. PushService.instance.init().then((_) {
  179. FirebaseMessaging.onBackgroundMessage(
  180. _firebaseMessagingBackgroundHandler,
  181. );
  182. });
  183. }
  184. unawaited(FeatureFlagService.instance.init());
  185. unawaited(SemanticSearchService.instance.init());
  186. // Can not including existing tf/ml binaries as they are not being built
  187. // from source.
  188. // See https://gitlab.com/fdroid/fdroiddata/-/merge_requests/12671#note_1294346819
  189. // if (!UpdateService.instance.isFdroidFlavor()) {
  190. // unawaited(ObjectDetectionService.instance.init());
  191. // }
  192. _logger.info("Initialization done");
  193. }
  194. Future<void> _sync(String caller) async {
  195. if (!AppLifecycleService.instance.isForeground) {
  196. _logger.info("Syncing in background caller $caller");
  197. } else {
  198. _logger.info("Syncing in foreground caller $caller");
  199. }
  200. try {
  201. await SyncService.instance.sync();
  202. } catch (e, s) {
  203. if (!isHandledSyncError(e)) {
  204. _logger.severe("Sync error", e, s);
  205. }
  206. }
  207. }
  208. Future _runWithLogs(Function() function, {String prefix = ""}) async {
  209. await SuperLogging.main(
  210. LogConfig(
  211. body: function,
  212. logDirPath: (await getApplicationSupportDirectory()).path + "/logs",
  213. maxLogFiles: 5,
  214. sentryDsn: kDebugMode ? sentryDebugDSN : sentryDSN,
  215. tunnel: sentryTunnel,
  216. enableInDebugMode: true,
  217. prefix: prefix,
  218. ),
  219. );
  220. }
  221. Future<void> _scheduleHeartBeat(
  222. SharedPreferences prefs,
  223. bool isBackground,
  224. ) async {
  225. await prefs.setInt(
  226. isBackground ? kLastBGTaskHeartBeatTime : kLastFGTaskHeartBeatTime,
  227. DateTime.now().microsecondsSinceEpoch,
  228. );
  229. Future.delayed(kHeartBeatFrequency, () async {
  230. // ignore: unawaited_futures
  231. _scheduleHeartBeat(prefs, isBackground);
  232. });
  233. }
  234. Future<void> _scheduleFGSync(String caller) async {
  235. await _sync(caller);
  236. Future.delayed(kFGSyncFrequency, () async {
  237. unawaited(_scheduleFGSync('fgSyncCron'));
  238. });
  239. }
  240. void _scheduleBGTaskKill(String taskId) async {
  241. if (await _isRunningInForeground()) {
  242. _logger.info("Found app in FG, committing seppuku. $taskId");
  243. await _killBGTask(taskId);
  244. return;
  245. }
  246. Future.delayed(kHeartBeatFrequency, () async {
  247. _scheduleBGTaskKill(taskId);
  248. });
  249. }
  250. Future<bool> _isRunningInForeground() async {
  251. final prefs = await SharedPreferences.getInstance();
  252. await prefs.reload();
  253. final currentTime = DateTime.now().microsecondsSinceEpoch;
  254. final lastFGHeartBeatTime = DateTime.fromMicrosecondsSinceEpoch(
  255. prefs.getInt(kLastFGTaskHeartBeatTime) ?? 0,
  256. );
  257. return lastFGHeartBeatTime.microsecondsSinceEpoch >
  258. (currentTime - kFGTaskDeathTimeoutInMicroseconds);
  259. }
  260. Future<void> _killBGTask([String? taskId]) async {
  261. await UploadLocksDB.instance.releaseLocksAcquiredByOwnerBefore(
  262. ProcessType.background.toString(),
  263. DateTime.now().microsecondsSinceEpoch,
  264. );
  265. final prefs = await SharedPreferences.getInstance();
  266. await prefs.remove(kLastBGTaskHeartBeatTime);
  267. if (taskId != null) {
  268. BackgroundFetch.finish(taskId);
  269. }
  270. }
  271. Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  272. final bool isRunningInFG = await _isRunningInForeground(); // hb
  273. final bool isInForeground = AppLifecycleService.instance.isForeground;
  274. if (_isProcessRunning) {
  275. _logger.info(
  276. "Background push received when app is alive and runningInFS: $isRunningInFG inForeground: $isInForeground",
  277. );
  278. if (PushService.shouldSync(message)) {
  279. await _sync('firebaseBgSyncActiveProcess');
  280. }
  281. } else {
  282. // App is dead
  283. // ignore: unawaited_futures
  284. _runWithLogs(
  285. () async {
  286. _logger.info("Background push received");
  287. if (Platform.isIOS) {
  288. _scheduleSuicide(kBGPushTimeout); // To prevent OS from punishing us
  289. }
  290. await _init(true, via: 'firebasePush');
  291. if (PushService.shouldSync(message)) {
  292. await _sync('firebaseBgSyncNoActiveProcess');
  293. }
  294. },
  295. prefix: "[fbg]",
  296. );
  297. }
  298. }
  299. Future<void> _logFGHeartBeatInfo() async {
  300. final bool isRunningInFG = await _isRunningInForeground();
  301. final prefs = await SharedPreferences.getInstance();
  302. await prefs.reload();
  303. final lastFGTaskHeartBeatTime = prefs.getInt(kLastFGTaskHeartBeatTime) ?? 0;
  304. final String lastRun = lastFGTaskHeartBeatTime == 0
  305. ? 'never'
  306. : DateTime.fromMicrosecondsSinceEpoch(lastFGTaskHeartBeatTime).toString();
  307. _logger.info('isAlreaduunningFG: $isRunningInFG, last Beat: $lastRun');
  308. }
  309. void _scheduleSuicide(Duration duration, [String? taskID]) {
  310. final taskIDVal = taskID ?? 'no taskID';
  311. _logger.warning("Schedule seppuku taskID: $taskIDVal");
  312. Future.delayed(duration, () {
  313. _logger.warning("TLE, committing seppuku for taskID: $taskIDVal");
  314. _killBGTask(taskID);
  315. });
  316. }