main.dart 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. import 'dart:async';
  2. import 'dart:io';
  3. import 'dart:isolate';
  4. import 'package:background_fetch/background_fetch.dart';
  5. import 'package:firebase_messaging/firebase_messaging.dart';
  6. import 'package:flutter/foundation.dart';
  7. import 'package:flutter/material.dart';
  8. import 'package:flutter_easyloading/flutter_easyloading.dart';
  9. import 'package:flutter_gen/gen_l10n/app_localizations.dart';
  10. import 'package:flutter_localizations/flutter_localizations.dart';
  11. import 'package:in_app_purchase/in_app_purchase.dart';
  12. import 'package:logging/logging.dart';
  13. import 'package:path_provider/path_provider.dart';
  14. import 'package:photos/core/configuration.dart';
  15. import 'package:photos/core/constants.dart';
  16. import 'package:photos/core/network.dart';
  17. import 'package:photos/db/upload_locks_db.dart';
  18. import 'package:photos/l10n/l10n.dart';
  19. import 'package:photos/services/app_lifecycle_service.dart';
  20. import 'package:photos/services/billing_service.dart';
  21. import 'package:photos/services/collections_service.dart';
  22. import 'package:photos/services/feature_flag_service.dart';
  23. import 'package:photos/services/local_sync_service.dart';
  24. import 'package:photos/services/memories_service.dart';
  25. import 'package:photos/services/notification_service.dart';
  26. import 'package:photos/services/push_service.dart';
  27. import 'package:photos/services/remote_sync_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/ui/app_lock.dart';
  32. import 'package:photos/ui/home_widget.dart';
  33. import 'package:photos/ui/lock_screen.dart';
  34. import 'package:photos/utils/crypto_util.dart';
  35. import 'package:photos/utils/file_uploader.dart';
  36. import 'package:photos/utils/local_settings.dart';
  37. import 'package:shared_preferences/shared_preferences.dart';
  38. import 'package:super_logging/super_logging.dart';
  39. import 'package:visibility_detector/visibility_detector.dart';
  40. final _logger = Logger("main");
  41. Completer<void> _initializationStatus;
  42. const kLastBGTaskHeartBeatTime = "bg_task_hb_time";
  43. const kLastFGTaskHeartBeatTime = "fg_task_hb_time";
  44. const kHeartBeatFrequency = Duration(seconds: 1);
  45. const kFGSyncFrequency = Duration(minutes: 5);
  46. const kBGTaskTimeout = Duration(seconds: 25);
  47. const kBGPushTimeout = Duration(seconds: 28);
  48. const kFGTaskDeathTimeoutInMicroseconds = 5000000;
  49. final themeData = ThemeData(
  50. fontFamily: 'Ubuntu',
  51. brightness: Brightness.dark,
  52. hintColor: Colors.grey,
  53. accentColor: Color.fromRGBO(45, 194, 98, 0.2),
  54. buttonColor: Color.fromRGBO(45, 194, 98, 1.0),
  55. buttonTheme: ButtonThemeData().copyWith(
  56. buttonColor: Color.fromRGBO(45, 194, 98, 1.0),
  57. ),
  58. toggleableActiveColor: Colors.green[400],
  59. scaffoldBackgroundColor: Colors.black,
  60. backgroundColor: Colors.black,
  61. appBarTheme: AppBarTheme().copyWith(
  62. color: Color.fromRGBO(10, 20, 20, 1.0),
  63. ),
  64. cardColor: Color.fromRGBO(10, 15, 15, 1.0),
  65. dialogTheme: DialogTheme().copyWith(
  66. backgroundColor: Color.fromRGBO(10, 15, 15, 1.0),
  67. ),
  68. textSelectionTheme: TextSelectionThemeData().copyWith(
  69. cursorColor: Colors.white.withOpacity(0.5),
  70. ),
  71. inputDecorationTheme: InputDecorationTheme().copyWith(
  72. focusedBorder: UnderlineInputBorder(
  73. borderSide: BorderSide(
  74. color: Color.fromRGBO(45, 194, 98, 1.0),
  75. ),
  76. ),
  77. ),
  78. );
  79. void main() async {
  80. WidgetsFlutterBinding.ensureInitialized();
  81. await _runInForeground();
  82. BackgroundFetch.registerHeadlessTask(_headlessTaskHandler);
  83. }
  84. Future<void> _runInForeground() async {
  85. return await _runWithLogs(() async {
  86. _logger.info("Starting app in foreground");
  87. await _init(false);
  88. _scheduleFGSync();
  89. runApp(AppLock(
  90. builder: (args) => EnteApp(),
  91. lockScreen: LockScreen(),
  92. enabled: Configuration.instance.shouldShowLockScreen(),
  93. themeData: themeData,
  94. ));
  95. });
  96. }
  97. Future _runInBackground(String taskId) async {
  98. if (_initializationStatus == null) {
  99. _runWithLogs(() async {
  100. _backgroundTask(taskId);
  101. }, prefix: "[bg]");
  102. } else {
  103. _backgroundTask(taskId);
  104. }
  105. }
  106. void _backgroundTask(String taskId) async {
  107. await Future.delayed(Duration(seconds: 3));
  108. if (await _isRunningInForeground()) {
  109. _logger.info("FG task running, skipping BG task");
  110. BackgroundFetch.finish(taskId);
  111. return;
  112. } else {
  113. _logger.info("FG task is not running");
  114. }
  115. _logger.info("[BackgroundFetch] Event received: $taskId");
  116. _scheduleBGTaskKill(taskId);
  117. if (Platform.isIOS) {
  118. _scheduleSuicide(kBGTaskTimeout); // To prevent OS from punishing us
  119. }
  120. await _init(true);
  121. UpdateService.instance.showUpdateNotification();
  122. await _sync();
  123. BackgroundFetch.finish(taskId);
  124. }
  125. void _headlessTaskHandler(HeadlessTask task) {
  126. if (task.timeout) {
  127. BackgroundFetch.finish(task.taskId);
  128. } else {
  129. _runInBackground(task.taskId);
  130. }
  131. }
  132. Future<void> _init(bool isBackground) async {
  133. if (_initializationStatus != null) {
  134. return _initializationStatus.future;
  135. }
  136. _initializationStatus = Completer<void>();
  137. _logger.info("Initializing...");
  138. _scheduleHeartBeat(isBackground);
  139. if (isBackground) {
  140. AppLifecycleService.instance.onAppInBackground();
  141. } else {
  142. AppLifecycleService.instance.onAppInForeground();
  143. }
  144. InAppPurchaseConnection.enablePendingPurchases();
  145. CryptoUtil.init();
  146. await NotificationService.instance.init();
  147. await Network.instance.init();
  148. await Configuration.instance.init();
  149. await UpdateService.instance.init();
  150. await BillingService.instance.init();
  151. await CollectionsService.instance.init();
  152. await FileUploader.instance.init(isBackground);
  153. await LocalSyncService.instance.init();
  154. await TrashSyncService.instance.init();
  155. await RemoteSyncService.instance.init();
  156. await SyncService.instance.init();
  157. await MemoriesService.instance.init();
  158. await LocalSettings.instance.init();
  159. PushService.instance.init().then((_) {
  160. FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  161. });
  162. FeatureFlagService.instance.init();
  163. _logger.info("Initialization done");
  164. _initializationStatus.complete();
  165. }
  166. Future<void> _sync() async {
  167. if (SyncService.instance.isSyncInProgress()) {
  168. _logger.info("Sync is already in progress, skipping");
  169. return;
  170. }
  171. if (!AppLifecycleService.instance.isForeground) {
  172. _logger.info("Syncing in background");
  173. }
  174. try {
  175. await SyncService.instance.sync();
  176. } catch (e, s) {
  177. _logger.severe("Sync error", e, s);
  178. }
  179. }
  180. Future _runWithLogs(Function() function, {String prefix = ""}) async {
  181. await SuperLogging.main(LogConfig(
  182. body: function,
  183. logDirPath: (await getTemporaryDirectory()).path + "/logs",
  184. maxLogFiles: 5,
  185. sentryDsn: kDebugMode ? kSentryDebugDSN : kSentryDSN,
  186. enableInDebugMode: true,
  187. prefix: prefix,
  188. ));
  189. }
  190. Future<void> _scheduleHeartBeat(bool isBackground) async {
  191. final prefs = await SharedPreferences.getInstance();
  192. await prefs.setInt(
  193. isBackground ? kLastBGTaskHeartBeatTime : kLastFGTaskHeartBeatTime,
  194. DateTime.now().microsecondsSinceEpoch);
  195. Future.delayed(kHeartBeatFrequency, () async {
  196. _scheduleHeartBeat(isBackground);
  197. });
  198. }
  199. Future<void> _scheduleFGSync() async {
  200. await _sync();
  201. Future.delayed(kFGSyncFrequency, () async {
  202. _scheduleFGSync();
  203. });
  204. }
  205. void _scheduleBGTaskKill(String taskId) async {
  206. if (await _isRunningInForeground()) {
  207. _logger.info("Found app in FG, committing seppuku.");
  208. await _killBGTask(taskId);
  209. return;
  210. }
  211. Future.delayed(kHeartBeatFrequency, () async {
  212. _scheduleBGTaskKill(taskId);
  213. });
  214. }
  215. Future<bool> _isRunningInForeground() async {
  216. final prefs = await SharedPreferences.getInstance();
  217. await prefs.reload();
  218. final currentTime = DateTime.now().microsecondsSinceEpoch;
  219. return (prefs.getInt(kLastFGTaskHeartBeatTime) ?? 0) >
  220. (currentTime - kFGTaskDeathTimeoutInMicroseconds);
  221. }
  222. Future<void> _killBGTask([String taskId]) async {
  223. await UploadLocksDB.instance.releaseLocksAcquiredByOwnerBefore(
  224. ProcessType.background.toString(), DateTime.now().microsecondsSinceEpoch);
  225. final prefs = await SharedPreferences.getInstance();
  226. prefs.remove(kLastBGTaskHeartBeatTime);
  227. if (taskId != null) {
  228. BackgroundFetch.finish(taskId);
  229. }
  230. Isolate.current.kill(priority: Isolate.immediate);
  231. }
  232. class EnteApp extends StatefulWidget {
  233. static const _homeWidget = HomeWidget();
  234. @override
  235. _EnteAppState createState() => _EnteAppState();
  236. }
  237. class _EnteAppState extends State<EnteApp> with WidgetsBindingObserver {
  238. @override
  239. void initState() {
  240. super.initState();
  241. WidgetsBinding.instance.addObserver(this);
  242. _configureBackgroundFetch();
  243. }
  244. @override
  245. Widget build(BuildContext context) {
  246. return VisibilityDetector(
  247. key: GlobalKey(),
  248. onVisibilityChanged: (visibility) {
  249. if (visibility.visibleFraction == 1) {
  250. Logger("EnteApp").info("App is in foreground");
  251. AppLifecycleService.instance.onAppInForeground();
  252. } else {
  253. Logger("EnteApp").info("App is in background");
  254. AppLifecycleService.instance.onAppInBackground();
  255. }
  256. },
  257. child: MaterialApp(
  258. title: "ente",
  259. theme: themeData,
  260. home: EnteApp._homeWidget,
  261. debugShowCheckedModeBanner: false,
  262. navigatorKey: Network.instance.getAlice().getNavigatorKey(),
  263. builder: EasyLoading.init(),
  264. supportedLocales: L10n.all,
  265. localizationsDelegates: const [
  266. AppLocalizations.delegate,
  267. GlobalMaterialLocalizations.delegate,
  268. GlobalCupertinoLocalizations.delegate,
  269. GlobalWidgetsLocalizations.delegate,
  270. ],
  271. ),
  272. );
  273. }
  274. @override
  275. void didChangeAppLifecycleState(AppLifecycleState state) {
  276. if (state == AppLifecycleState.resumed) {
  277. AppLifecycleService.instance.onAppInForeground();
  278. _sync();
  279. } else {
  280. AppLifecycleService.instance.onAppInBackground();
  281. }
  282. }
  283. void _configureBackgroundFetch() {
  284. BackgroundFetch.configure(
  285. BackgroundFetchConfig(
  286. minimumFetchInterval: 15,
  287. forceAlarmManager: false,
  288. stopOnTerminate: false,
  289. startOnBoot: true,
  290. enableHeadless: true,
  291. requiresBatteryNotLow: false,
  292. requiresCharging: false,
  293. requiresStorageNotLow: false,
  294. requiresDeviceIdle: false,
  295. requiredNetworkType: NetworkType.NONE,
  296. ), (String taskId) async {
  297. await _runInBackground(taskId);
  298. }, (taskId) {
  299. _logger.info("BG task timeout");
  300. _killBGTask(taskId);
  301. }).then((int status) {
  302. _logger.info('[BackgroundFetch] configure success: $status');
  303. }).catchError((e) {
  304. _logger.info('[BackgroundFetch] configure ERROR: $e');
  305. });
  306. }
  307. }
  308. Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  309. if (_initializationStatus == null) {
  310. // App is dead
  311. _runWithLogs(() async {
  312. _logger.info("Background push received");
  313. if (Platform.isIOS) {
  314. _scheduleSuicide(kBGPushTimeout); // To prevent OS from punishing us
  315. }
  316. await _init(true);
  317. if (PushService.shouldSync(message)) {
  318. await _sync();
  319. }
  320. }, prefix: "[bg]");
  321. } else {
  322. _logger.info("Background push received when app is alive");
  323. if (PushService.shouldSync(message)) {
  324. await _sync();
  325. }
  326. }
  327. }
  328. void _scheduleSuicide(Duration duration, [String taskID]) {
  329. Future.delayed(duration, () {
  330. _logger.warning("TLE");
  331. _killBGTask(taskID);
  332. });
  333. }