main.dart 9.8 KB

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