ente/lib/main.dart

339 lines
12 KiB
Dart
Raw Normal View History

2020-05-02 17:16:59 +05:30
import 'dart:async';
import 'dart:io';
2020-05-02 17:16:59 +05:30
import "package:adaptive_theme/adaptive_theme.dart";
2021-01-13 23:09:45 +05:30
import 'package:background_fetch/background_fetch.dart';
import "package:computer/computer.dart";
2021-10-13 10:54:49 +05:30
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
2020-03-25 01:29:36 +05:30
import 'package:flutter/material.dart';
import "package:flutter/rendering.dart";
import "package:flutter_displaymode/flutter_displaymode.dart";
2021-07-22 02:17:43 +05:30
import 'package:logging/logging.dart';
import "package:media_kit/media_kit.dart";
2020-05-02 21:58:54 +05:30
import 'package:path_provider/path_provider.dart';
2021-11-24 12:56:07 +05:30
import 'package:photos/app.dart';
import 'package:photos/core/configuration.dart';
2021-07-22 02:17:43 +05:30
import 'package:photos/core/constants.dart';
import 'package:photos/core/error-reporting/super_logging.dart';
import 'package:photos/core/errors.dart';
2023-02-03 13:09:04 +05:30
import 'package:photos/core/network/network.dart';
import 'package:photos/db/upload_locks_db.dart';
2022-06-21 20:07:17 +05:30
import 'package:photos/ente_theme_data.dart';
2023-04-10 16:56:44 +05:30
import "package:photos/l10n/l10n.dart";
import 'package:photos/services/app_lifecycle_service.dart';
2021-01-08 12:08:45 +05:30
import 'package:photos/services/billing_service.dart';
import 'package:photos/services/collections_service.dart';
2023-04-04 14:18:54 +05:30
import "package:photos/services/entity_service.dart";
import 'package:photos/services/favorites_service.dart';
import 'package:photos/services/feature_flag_service.dart';
2022-08-01 16:35:16 +05:30
import 'package:photos/services/local_file_update_service.dart';
import 'package:photos/services/local_sync_service.dart';
2023-03-07 07:42:54 +05:30
import "package:photos/services/location_service.dart";
2020-10-03 23:26:18 +05:30
import 'package:photos/services/memories_service.dart';
2021-10-12 14:42:28 +05:30
import 'package:photos/services/push_service.dart';
import 'package:photos/services/remote_sync_service.dart';
import 'package:photos/services/search_service.dart';
2023-10-03 22:38:18 +05:30
import 'package:photos/services/semantic_search/semantic_search_service.dart';
2023-02-15 22:17:40 +05:30
import "package:photos/services/storage_bonus_service.dart";
2020-10-03 23:28:26 +05:30
import 'package:photos/services/sync_service.dart';
2021-10-13 00:57:11 +05:30
import 'package:photos/services/trash_sync_service.dart';
2021-05-22 23:59:09 +05:30
import 'package:photos/services/update_service.dart';
2022-09-20 11:35:34 +05:30
import 'package:photos/services/user_remote_flag_service.dart';
import 'package:photos/services/user_service.dart';
2022-07-01 20:09:02 +05:30
import 'package:photos/ui/tools/app_lock.dart';
import 'package:photos/ui/tools/lock_screen.dart';
import 'package:photos/utils/crypto_util.dart';
import 'package:photos/utils/file_uploader.dart';
import 'package:photos/utils/local_settings.dart';
import 'package:shared_preferences/shared_preferences.dart';
2021-08-16 01:05:16 +05:30
2020-08-22 04:58:52 +05:30
final _logger = Logger("main");
2021-03-02 03:39:15 +05:30
2021-11-27 21:15:56 +05:30
bool _isProcessRunning = false;
const kLastBGTaskHeartBeatTime = "bg_task_hb_time";
const kLastFGTaskHeartBeatTime = "fg_task_hb_time";
const kHeartBeatFrequency = Duration(seconds: 1);
2023-06-30 18:48:38 +05:30
const kFGSyncFrequency = Duration(minutes: 5);
const kBGTaskTimeout = Duration(seconds: 25);
const kBGPushTimeout = Duration(seconds: 28);
const kFGTaskDeathTimeoutInMicroseconds = 5000000;
const kBackgroundLockLatency = Duration(seconds: 3);
2020-03-25 01:29:36 +05:30
void main() async {
debugRepaintRainbowEnabled = false;
2020-03-25 01:29:36 +05:30
WidgetsFlutterBinding.ensureInitialized();
MediaKit.ensureInitialized();
final savedThemeMode = await AdaptiveTheme.getThemeMode();
await _runInForeground(savedThemeMode);
2023-12-02 17:12:52 +05:30
unawaited(BackgroundFetch.registerHeadlessTask(_headlessTaskHandler));
FlutterDisplayMode.setHighRefreshRate().ignore();
2020-05-02 21:58:54 +05:30
}
Future<void> _runInForeground(AdaptiveThemeMode? savedThemeMode) async {
2021-03-02 05:06:58 +05:30
return await _runWithLogs(() async {
2021-03-02 03:39:15 +05:30
_logger.info("Starting app in foreground");
2022-03-08 01:48:50 +05:30
await _init(false, via: 'mainMethod');
2023-04-10 16:56:44 +05:30
final Locale locale = await getLocale();
2022-11-06 16:06:33 +05:30
unawaited(_scheduleFGSync('appStart in FG'));
2022-06-11 13:53:52 +05:30
runApp(
AppLock(
builder: (args) =>
2023-04-10 16:56:44 +05:30
EnteApp(_runBackgroundTask, _killBGTask, locale, savedThemeMode),
lockScreen: const LockScreen(),
2022-06-11 13:53:52 +05:30
enabled: Configuration.instance.shouldShowLockScreen(),
2023-04-10 16:56:44 +05:30
locale: locale,
2022-06-11 13:53:52 +05:30
lightTheme: lightThemeData,
darkTheme: darkThemeData,
backgroundLockLatency: kBackgroundLockLatency,
savedThemeMode: _themeMode(savedThemeMode),
2022-06-11 13:53:52 +05:30
),
);
2021-03-02 03:39:15 +05:30
});
}
2020-05-02 17:16:59 +05:30
ThemeMode _themeMode(AdaptiveThemeMode? savedThemeMode) {
if (savedThemeMode == null) return ThemeMode.system;
if (savedThemeMode.isLight) return ThemeMode.light;
if (savedThemeMode.isDark) return ThemeMode.dark;
return ThemeMode.system;
}
2022-10-18 13:38:09 +05:30
Future<void> _runBackgroundTask(String taskId, {String mode = 'normal'}) async {
if (_isProcessRunning) {
_logger.info("Background task triggered when process was already running");
2022-03-08 12:47:19 +05:30
await _sync('bgTaskActiveProcess');
BackgroundFetch.finish(taskId);
} else {
2023-12-17 02:34:26 +05:30
// ignore: unawaited_futures
2022-06-11 13:53:52 +05:30
_runWithLogs(
() async {
2022-10-18 13:38:09 +05:30
_logger.info("Starting background task in $mode mode");
2023-12-17 02:34:26 +05:30
// ignore: unawaited_futures
2022-06-11 13:53:52 +05:30
_runInBackground(taskId);
},
prefix: "[bg]",
);
}
}
Future<void> _runInBackground(String taskId) async {
2022-07-04 11:32:17 +05:30
await Future.delayed(const Duration(seconds: 3));
if (await _isRunningInForeground()) {
2022-03-08 01:48:50 +05:30
_logger.info("FG task running, skipping BG taskID: $taskId");
2021-03-02 03:39:15 +05:30
BackgroundFetch.finish(taskId);
return;
} else {
_logger.info("FG task is not running");
2021-03-02 03:39:15 +05:30
}
_logger.info("[BackgroundFetch] Event received: $taskId");
_scheduleBGTaskKill(taskId);
if (Platform.isIOS) {
2022-03-08 01:48:50 +05:30
_scheduleSuicide(kBGTaskTimeout, taskId); // To prevent OS from punishing us
}
2022-03-08 01:48:50 +05:30
await _init(true, via: 'runViaBackgroundTask');
2023-12-02 17:12:52 +05:30
UpdateService.instance.showUpdateNotification().ignore();
2022-03-08 12:47:19 +05:30
await _sync('bgSync');
BackgroundFetch.finish(taskId);
2021-03-02 03:39:15 +05:30
}
2020-05-02 17:16:59 +05:30
// https://stackoverflow.com/a/73796478/546896
@pragma('vm:entry-point')
2021-03-02 03:39:15 +05:30
void _headlessTaskHandler(HeadlessTask task) {
2023-03-07 20:39:11 +05:30
debugPrint("_headlessTaskHandler");
2021-03-02 03:39:15 +05:30
if (task.timeout) {
BackgroundFetch.finish(task.taskId);
} else {
2022-10-18 13:38:09 +05:30
_runBackgroundTask(task.taskId, mode: "headless");
2021-03-02 03:39:15 +05:30
}
2021-01-13 23:09:45 +05:30
}
2022-03-08 01:48:50 +05:30
Future<void> _init(bool isBackground, {String via = ''}) async {
2021-11-27 21:15:56 +05:30
_isProcessRunning = true;
2022-03-08 01:48:50 +05:30
_logger.info("Initializing... inBG =$isBackground via: $via");
final SharedPreferences preferences = await SharedPreferences.getInstance();
2022-03-08 01:48:50 +05:30
await _logFGHeartBeatInfo();
2023-12-17 02:34:26 +05:30
unawaited(_scheduleHeartBeat(preferences, isBackground));
2023-06-26 13:21:31 +05:30
AppLifecycleService.instance.init(preferences);
2021-11-15 21:05:07 +05:30
if (isBackground) {
2022-03-08 01:48:50 +05:30
AppLifecycleService.instance.onAppInBackground('init via: $via');
2021-11-15 21:05:07 +05:30
} else {
2022-03-08 01:48:50 +05:30
AppLifecycleService.instance.onAppInForeground('init via: $via');
2021-11-15 21:05:07 +05:30
}
2023-04-29 12:35:18 +05:30
// Start workers asynchronously. No need to wait for them to start
2023-12-16 16:51:53 +05:30
Computer.shared().turnOn(workersCount: 4).ignore();
CryptoUtil.init();
2023-02-03 13:09:04 +05:30
await NetworkClient.instance.init();
2021-01-13 23:09:45 +05:30
await Configuration.instance.init();
2022-06-23 18:47:31 +05:30
await UserService.instance.init();
2023-04-04 14:18:54 +05:30
await EntityService.instance.init();
2023-04-03 15:38:53 +05:30
LocationService.instance.init(preferences);
2023-04-04 14:18:54 +05:30
2022-09-20 11:35:34 +05:30
await UserRemoteFlagService.instance.init();
2021-05-22 23:59:09 +05:30
await UpdateService.instance.init();
BillingService.instance.init();
await CollectionsService.instance.init(preferences);
FavoritesService.instance.initFav().ignore();
await FileUploader.instance.init(preferences, isBackground);
await LocalSyncService.instance.init(preferences);
TrashSyncService.instance.init(preferences);
RemoteSyncService.instance.init(preferences);
await SyncService.instance.init(preferences);
MemoriesService.instance.init(preferences);
LocalSettings.instance.init(preferences);
LocalFileUpdateService.instance.init(preferences);
SearchService.instance.init();
2023-02-15 22:17:40 +05:30
StorageBonusService.instance.init(preferences);
2021-11-25 16:05:38 +05:30
if (Platform.isIOS) {
2023-12-17 02:34:26 +05:30
// ignore: unawaited_futures
2021-11-25 16:05:38 +05:30
PushService.instance.init().then((_) {
FirebaseMessaging.onBackgroundMessage(
2022-06-11 13:53:52 +05:30
_firebaseMessagingBackgroundHandler,
);
2021-11-25 16:05:38 +05:30
});
}
2023-12-17 02:34:26 +05:30
unawaited(FeatureFlagService.instance.init());
unawaited(SemanticSearchService.instance.init(isInBackground: isBackground));
2023-05-10 15:31:38 +05:30
// Can not including existing tf/ml binaries as they are not being built
// from source.
// See https://gitlab.com/fdroid/fdroiddata/-/merge_requests/12671#note_1294346819
// if (!UpdateService.instance.isFdroidFlavor()) {
// unawaited(ObjectDetectionService.instance.init());
// }
2021-02-06 21:41:27 +05:30
_logger.info("Initialization done");
2020-05-02 17:16:59 +05:30
}
2022-03-08 12:47:19 +05:30
Future<void> _sync(String caller) async {
2021-11-15 21:05:07 +05:30
if (!AppLifecycleService.instance.isForeground) {
2022-03-08 12:47:19 +05:30
_logger.info("Syncing in background caller $caller");
} else {
_logger.info("Syncing in foreground caller $caller");
2021-02-26 19:39:45 +05:30
}
2021-01-13 23:09:45 +05:30
try {
await SyncService.instance.sync();
2021-01-13 23:09:45 +05:30
} catch (e, s) {
if (!isHandledSyncError(e)) {
_logger.severe("Sync error", e, s);
}
2021-01-13 23:09:45 +05:30
}
}
Future _runWithLogs(Function() function, {String prefix = ""}) async {
2022-06-11 13:53:52 +05:30
await SuperLogging.main(
LogConfig(
body: function,
logDirPath: (await getApplicationSupportDirectory()).path + "/logs",
2022-06-11 13:53:52 +05:30
maxLogFiles: 5,
sentryDsn: kDebugMode ? sentryDebugDSN : sentryDSN,
tunnel: sentryTunnel,
2022-06-11 13:53:52 +05:30
enableInDebugMode: true,
prefix: prefix,
),
);
}
Future<void> _scheduleHeartBeat(
SharedPreferences prefs,
bool isBackground,
) async {
await prefs.setInt(
2022-06-11 13:53:52 +05:30
isBackground ? kLastBGTaskHeartBeatTime : kLastFGTaskHeartBeatTime,
DateTime.now().microsecondsSinceEpoch,
);
Future.delayed(kHeartBeatFrequency, () async {
2023-12-17 02:34:26 +05:30
// ignore: unawaited_futures
_scheduleHeartBeat(prefs, isBackground);
});
}
2022-03-08 12:47:19 +05:30
Future<void> _scheduleFGSync(String caller) async {
await _sync(caller);
Future.delayed(kFGSyncFrequency, () async {
2022-11-06 16:06:33 +05:30
unawaited(_scheduleFGSync('fgSyncCron'));
});
}
void _scheduleBGTaskKill(String taskId) async {
if (await _isRunningInForeground()) {
2022-03-08 01:48:50 +05:30
_logger.info("Found app in FG, committing seppuku. $taskId");
2021-05-07 23:14:19 +05:30
await _killBGTask(taskId);
return;
}
Future.delayed(kHeartBeatFrequency, () async {
_scheduleBGTaskKill(taskId);
});
}
Future<bool> _isRunningInForeground() async {
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
final currentTime = DateTime.now().microsecondsSinceEpoch;
2023-03-31 18:11:08 +05:30
final lastFGHeartBeatTime = DateTime.fromMicrosecondsSinceEpoch(
prefs.getInt(kLastFGTaskHeartBeatTime) ?? 0,
);
return lastFGHeartBeatTime.microsecondsSinceEpoch >
(currentTime - kFGTaskDeathTimeoutInMicroseconds);
}
Future<void> _killBGTask([String? taskId]) async {
2021-05-07 23:14:19 +05:30
await UploadLocksDB.instance.releaseLocksAcquiredByOwnerBefore(
2022-06-11 13:53:52 +05:30
ProcessType.background.toString(),
DateTime.now().microsecondsSinceEpoch,
);
2021-05-07 23:14:19 +05:30
final prefs = await SharedPreferences.getInstance();
2023-12-17 02:34:26 +05:30
await prefs.remove(kLastBGTaskHeartBeatTime);
if (taskId != null) {
BackgroundFetch.finish(taskId);
}
2021-05-07 23:14:19 +05:30
}
2021-10-13 10:54:49 +05:30
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
2022-08-29 20:13:31 +05:30
final bool isRunningInFG = await _isRunningInForeground(); // hb
final bool isInForeground = AppLifecycleService.instance.isForeground;
2021-11-27 21:15:56 +05:30
if (_isProcessRunning) {
2022-03-08 01:48:50 +05:30
_logger.info(
2022-06-11 13:53:52 +05:30
"Background push received when app is alive and runningInFS: $isRunningInFG inForeground: $isInForeground",
);
2021-11-27 21:15:56 +05:30
if (PushService.shouldSync(message)) {
2022-03-08 12:47:19 +05:30
await _sync('firebaseBgSyncActiveProcess');
2021-11-27 21:15:56 +05:30
}
} else {
2021-10-13 10:54:49 +05:30
// App is dead
2023-12-17 02:34:26 +05:30
// ignore: unawaited_futures
2022-06-11 13:53:52 +05:30
_runWithLogs(
() async {
_logger.info("Background push received");
if (Platform.isIOS) {
_scheduleSuicide(kBGPushTimeout); // To prevent OS from punishing us
}
await _init(true, via: 'firebasePush');
if (PushService.shouldSync(message)) {
await _sync('firebaseBgSyncNoActiveProcess');
}
},
prefix: "[fbg]",
);
2021-10-13 10:54:49 +05:30
}
}
2022-03-08 01:48:50 +05:30
Future<void> _logFGHeartBeatInfo() async {
2022-08-29 20:13:31 +05:30
final bool isRunningInFG = await _isRunningInForeground();
2022-03-08 01:48:50 +05:30
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
2022-08-29 20:13:31 +05:30
final lastFGTaskHeartBeatTime = prefs.getInt(kLastFGTaskHeartBeatTime) ?? 0;
final String lastRun = lastFGTaskHeartBeatTime == 0
2022-03-08 01:48:50 +05:30
? 'never'
: DateTime.fromMicrosecondsSinceEpoch(lastFGTaskHeartBeatTime).toString();
_logger.info('isAlreaduunningFG: $isRunningInFG, last Beat: $lastRun');
}
void _scheduleSuicide(Duration duration, [String? taskID]) {
2022-08-29 20:13:31 +05:30
final taskIDVal = taskID ?? 'no taskID';
2022-03-08 01:48:50 +05:30
_logger.warning("Schedule seppuku taskID: $taskIDVal");
Future.delayed(duration, () {
2022-03-08 01:48:50 +05:30
_logger.warning("TLE, committing seppuku for taskID: $taskIDVal");
_killBGTask(taskID);
});
}