main.dart 12 KB

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