main.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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. if (FeatureFlagService.instance.isInternalUserOrDebugBuild()) {
  180. await ObjectDetectionService.instance.init();
  181. }
  182. _logger.info("Initialization done");
  183. }
  184. Future<void> _sync(String caller) async {
  185. if (!AppLifecycleService.instance.isForeground) {
  186. _logger.info("Syncing in background caller $caller");
  187. } else {
  188. _logger.info("Syncing in foreground caller $caller");
  189. }
  190. try {
  191. await SyncService.instance.sync();
  192. } catch (e, s) {
  193. if (!isHandledSyncError(e)) {
  194. _logger.severe("Sync error", e, s);
  195. }
  196. }
  197. }
  198. Future _runWithLogs(Function() function, {String prefix = ""}) async {
  199. await SuperLogging.main(
  200. LogConfig(
  201. body: function,
  202. logDirPath: (await getApplicationSupportDirectory()).path + "/logs",
  203. maxLogFiles: 5,
  204. sentryDsn: kDebugMode ? sentryDebugDSN : sentryDSN,
  205. tunnel: sentryTunnel,
  206. enableInDebugMode: true,
  207. prefix: prefix,
  208. ),
  209. );
  210. }
  211. Future<void> _scheduleHeartBeat(
  212. SharedPreferences prefs,
  213. bool isBackground,
  214. ) async {
  215. await prefs.setInt(
  216. isBackground ? kLastBGTaskHeartBeatTime : kLastFGTaskHeartBeatTime,
  217. DateTime.now().microsecondsSinceEpoch,
  218. );
  219. Future.delayed(kHeartBeatFrequency, () async {
  220. _scheduleHeartBeat(prefs, isBackground);
  221. });
  222. }
  223. Future<void> _scheduleFGSync(String caller) async {
  224. await _sync(caller);
  225. Future.delayed(kFGSyncFrequency, () async {
  226. unawaited(_scheduleFGSync('fgSyncCron'));
  227. });
  228. }
  229. void _scheduleBGTaskKill(String taskId) async {
  230. if (await _isRunningInForeground()) {
  231. _logger.info("Found app in FG, committing seppuku. $taskId");
  232. await _killBGTask(taskId);
  233. return;
  234. }
  235. Future.delayed(kHeartBeatFrequency, () async {
  236. _scheduleBGTaskKill(taskId);
  237. });
  238. }
  239. Future<bool> _isRunningInForeground() async {
  240. final prefs = await SharedPreferences.getInstance();
  241. await prefs.reload();
  242. final currentTime = DateTime.now().microsecondsSinceEpoch;
  243. final lastFGHeartBeatTime = DateTime.fromMicrosecondsSinceEpoch(
  244. prefs.getInt(kLastFGTaskHeartBeatTime) ?? 0,
  245. );
  246. return lastFGHeartBeatTime.microsecondsSinceEpoch >
  247. (currentTime - kFGTaskDeathTimeoutInMicroseconds);
  248. }
  249. Future<void> _killBGTask([String? taskId]) async {
  250. await UploadLocksDB.instance.releaseLocksAcquiredByOwnerBefore(
  251. ProcessType.background.toString(),
  252. DateTime.now().microsecondsSinceEpoch,
  253. );
  254. final prefs = await SharedPreferences.getInstance();
  255. prefs.remove(kLastBGTaskHeartBeatTime);
  256. if (taskId != null) {
  257. BackgroundFetch.finish(taskId);
  258. }
  259. }
  260. Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  261. final bool isRunningInFG = await _isRunningInForeground(); // hb
  262. final bool isInForeground = AppLifecycleService.instance.isForeground;
  263. if (_isProcessRunning) {
  264. _logger.info(
  265. "Background push received when app is alive and runningInFS: $isRunningInFG inForeground: $isInForeground",
  266. );
  267. if (PushService.shouldSync(message)) {
  268. await _sync('firebaseBgSyncActiveProcess');
  269. }
  270. } else {
  271. // App is dead
  272. _runWithLogs(
  273. () async {
  274. _logger.info("Background push received");
  275. if (Platform.isIOS) {
  276. _scheduleSuicide(kBGPushTimeout); // To prevent OS from punishing us
  277. }
  278. await _init(true, via: 'firebasePush');
  279. if (PushService.shouldSync(message)) {
  280. await _sync('firebaseBgSyncNoActiveProcess');
  281. }
  282. },
  283. prefix: "[fbg]",
  284. );
  285. }
  286. }
  287. Future<void> _logFGHeartBeatInfo() async {
  288. final bool isRunningInFG = await _isRunningInForeground();
  289. final prefs = await SharedPreferences.getInstance();
  290. await prefs.reload();
  291. final lastFGTaskHeartBeatTime = prefs.getInt(kLastFGTaskHeartBeatTime) ?? 0;
  292. final String lastRun = lastFGTaskHeartBeatTime == 0
  293. ? 'never'
  294. : DateTime.fromMicrosecondsSinceEpoch(lastFGTaskHeartBeatTime).toString();
  295. _logger.info('isAlreaduunningFG: $isRunningInFG, last Beat: $lastRun');
  296. }
  297. void _scheduleSuicide(Duration duration, [String? taskID]) {
  298. final taskIDVal = taskID ?? 'no taskID';
  299. _logger.warning("Schedule seppuku taskID: $taskIDVal");
  300. Future.delayed(duration, () {
  301. _logger.warning("TLE, committing seppuku for taskID: $taskIDVal");
  302. _killBGTask(taskID);
  303. });
  304. }