ente/lib/main.dart

288 lines
9.6 KiB
Dart
Raw Normal View History

// @dart=2.9
2020-05-02 11:46:59 +00:00
import 'dart:async';
import 'dart:io';
2020-05-02 11:46:59 +00:00
2021-01-13 17:39:45 +00:00
import 'package:background_fetch/background_fetch.dart';
2021-10-13 05:24:49 +00:00
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
2020-03-24 19:59:36 +00:00
import 'package:flutter/material.dart';
2021-07-21 20:47:43 +00:00
import 'package:logging/logging.dart';
2020-05-02 16:28:54 +00:00
import 'package:path_provider/path_provider.dart';
2021-11-24 07:26:07 +00:00
import 'package:photos/app.dart';
import 'package:photos/core/configuration.dart';
2021-07-21 20:47:43 +00:00
import 'package:photos/core/constants.dart';
import 'package:photos/core/error-reporting/super_logging.dart';
2021-04-04 17:19:46 +00:00
import 'package:photos/core/network.dart';
import 'package:photos/db/upload_locks_db.dart';
2022-06-21 14:37:17 +00:00
import 'package:photos/ente_theme_data.dart';
import 'package:photos/services/app_lifecycle_service.dart';
2021-01-08 06:38:45 +00:00
import 'package:photos/services/billing_service.dart';
import 'package:photos/services/collections_service.dart';
import 'package:photos/services/feature_flag_service.dart';
2022-08-01 11:05:16 +00:00
import 'package:photos/services/local_file_update_service.dart';
import 'package:photos/services/local_sync_service.dart';
2020-10-03 17:56:18 +00:00
import 'package:photos/services/memories_service.dart';
import 'package:photos/services/notification_service.dart';
2021-10-12 09:12:28 +00:00
import 'package:photos/services/push_service.dart';
import 'package:photos/services/remote_sync_service.dart';
import 'package:photos/services/search_service.dart';
2020-10-03 17:58:26 +00:00
import 'package:photos/services/sync_service.dart';
2021-10-12 19:27:11 +00:00
import 'package:photos/services/trash_sync_service.dart';
2021-05-22 18:29:09 +00:00
import 'package:photos/services/update_service.dart';
2022-09-20 06:05:34 +00:00
import 'package:photos/services/user_remote_flag_service.dart';
import 'package:photos/services/user_service.dart';
2022-07-01 14:39:02 +00:00
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-15 19:35:16 +00:00
2020-08-21 23:28:52 +00:00
final _logger = Logger("main");
2021-03-01 22:09:15 +00:00
2021-11-27 15:45:56 +00:00
bool _isProcessRunning = false;
const kLastBGTaskHeartBeatTime = "bg_task_hb_time";
const kLastFGTaskHeartBeatTime = "fg_task_hb_time";
const kHeartBeatFrequency = Duration(seconds: 1);
const kFGSyncFrequency = Duration(minutes: 5);
const kBGTaskTimeout = Duration(seconds: 25);
const kBGPushTimeout = Duration(seconds: 28);
const kFGTaskDeathTimeoutInMicroseconds = 5000000;
2020-03-24 19:59:36 +00:00
void main() async {
WidgetsFlutterBinding.ensureInitialized();
2021-03-01 23:36:58 +00:00
await _runInForeground();
2021-03-03 16:07:15 +00:00
BackgroundFetch.registerHeadlessTask(_headlessTaskHandler);
2020-05-02 16:28:54 +00:00
}
2021-03-01 23:36:58 +00:00
Future<void> _runInForeground() async {
return await _runWithLogs(() async {
2021-03-01 22:09:15 +00:00
_logger.info("Starting app in foreground");
2022-03-07 20:18:50 +00:00
await _init(false, via: 'mainMethod');
2022-11-06 10:36:33 +00:00
unawaited(_scheduleFGSync('appStart in FG'));
2022-06-11 08:23:52 +00:00
runApp(
AppLock(
builder: (args) => const EnteApp(_runBackgroundTask, _killBGTask),
lockScreen: const LockScreen(),
2022-06-11 08:23:52 +00:00
enabled: Configuration.instance.shouldShowLockScreen(),
lightTheme: lightThemeData,
darkTheme: darkThemeData,
),
);
2021-03-01 22:09:15 +00:00
});
}
2020-05-02 11:46:59 +00:00
2022-10-18 08:08:09 +00:00
Future<void> _runBackgroundTask(String taskId, {String mode = 'normal'}) async {
if (_isProcessRunning) {
_logger.info("Background task triggered when process was already running");
2022-03-08 07:17:19 +00:00
await _sync('bgTaskActiveProcess');
BackgroundFetch.finish(taskId);
} else {
2022-06-11 08:23:52 +00:00
_runWithLogs(
() async {
2022-10-18 08:08:09 +00:00
_logger.info("Starting background task in $mode mode");
2022-06-11 08:23:52 +00:00
_runInBackground(taskId);
},
prefix: "[bg]",
);
}
}
Future<void> _runInBackground(String taskId) async {
2022-07-04 06:02:17 +00:00
await Future.delayed(const Duration(seconds: 3));
if (await _isRunningInForeground()) {
2022-03-07 20:18:50 +00:00
_logger.info("FG task running, skipping BG taskID: $taskId");
2021-03-01 22:09:15 +00:00
BackgroundFetch.finish(taskId);
return;
} else {
_logger.info("FG task is not running");
2021-03-01 22:09:15 +00:00
}
_logger.info("[BackgroundFetch] Event received: $taskId");
_scheduleBGTaskKill(taskId);
if (Platform.isIOS) {
2022-03-07 20:18:50 +00:00
_scheduleSuicide(kBGTaskTimeout, taskId); // To prevent OS from punishing us
}
2022-03-07 20:18:50 +00:00
await _init(true, via: 'runViaBackgroundTask');
UpdateService.instance.showUpdateNotification();
2022-03-08 07:17:19 +00:00
await _sync('bgSync');
BackgroundFetch.finish(taskId);
2021-03-01 22:09:15 +00:00
}
2020-05-02 11:46:59 +00:00
// https://stackoverflow.com/a/73796478/546896
@pragma('vm:entry-point')
2021-03-01 22:09:15 +00:00
void _headlessTaskHandler(HeadlessTask task) {
2022-10-18 08:00:29 +00:00
print("_headlessTaskHandler");
2021-03-01 22:09:15 +00:00
if (task.timeout) {
BackgroundFetch.finish(task.taskId);
} else {
2022-10-18 08:08:09 +00:00
_runBackgroundTask(task.taskId, mode: "headless");
2021-03-01 22:09:15 +00:00
}
2021-01-13 17:39:45 +00:00
}
2022-03-07 20:18:50 +00:00
Future<void> _init(bool isBackground, {String via = ''}) async {
2021-11-27 15:45:56 +00:00
_isProcessRunning = true;
2022-03-07 20:18:50 +00:00
_logger.info("Initializing... inBG =$isBackground via: $via");
final SharedPreferences preferences = await SharedPreferences.getInstance();
2022-03-07 20:18:50 +00:00
await _logFGHeartBeatInfo();
_scheduleHeartBeat(preferences, isBackground);
2021-11-15 15:35:07 +00:00
if (isBackground) {
2022-03-07 20:18:50 +00:00
AppLifecycleService.instance.onAppInBackground('init via: $via');
2021-11-15 15:35:07 +00:00
} else {
2022-03-07 20:18:50 +00:00
AppLifecycleService.instance.onAppInForeground('init via: $via');
2021-11-15 15:35:07 +00:00
}
CryptoUtil.init();
await NotificationService.instance.init();
2021-04-04 17:19:46 +00:00
await Network.instance.init();
2021-01-13 17:39:45 +00:00
await Configuration.instance.init();
2022-06-23 13:17:31 +00:00
await UserService.instance.init();
2022-09-20 06:05:34 +00:00
await UserRemoteFlagService.instance.init();
2021-05-22 18:29:09 +00:00
await UpdateService.instance.init();
BillingService.instance.init();
await CollectionsService.instance.init(preferences);
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();
LocalSettings.instance.init(preferences);
LocalFileUpdateService.instance.init(preferences);
SearchService.instance.init();
2021-11-25 10:35:38 +00:00
if (Platform.isIOS) {
PushService.instance.init().then((_) {
FirebaseMessaging.onBackgroundMessage(
2022-06-11 08:23:52 +00:00
_firebaseMessagingBackgroundHandler,
);
2021-11-25 10:35:38 +00:00
});
}
FeatureFlagService.instance.init();
2021-02-06 16:11:27 +00:00
_logger.info("Initialization done");
2020-05-02 11:46:59 +00:00
}
2022-03-08 07:17:19 +00:00
Future<void> _sync(String caller) async {
2021-11-15 15:35:07 +00:00
if (!AppLifecycleService.instance.isForeground) {
2022-03-08 07:17:19 +00:00
_logger.info("Syncing in background caller $caller");
} else {
_logger.info("Syncing in foreground caller $caller");
2021-02-26 14:09:45 +00:00
}
2021-01-13 17:39:45 +00:00
try {
await SyncService.instance.sync();
2021-01-13 17:39:45 +00:00
} catch (e, s) {
2020-10-12 20:34:34 +00:00
_logger.severe("Sync error", e, s);
2021-01-13 17:39:45 +00:00
}
}
Future _runWithLogs(Function() function, {String prefix = ""}) async {
2022-06-11 08:23:52 +00:00
await SuperLogging.main(
LogConfig(
body: function,
logDirPath: (await getApplicationSupportDirectory()).path + "/logs",
2022-06-11 08:23:52 +00:00
maxLogFiles: 5,
sentryDsn: kDebugMode ? sentryDebugDSN : sentryDSN,
tunnel: sentryTunnel,
2022-06-11 08:23:52 +00:00
enableInDebugMode: true,
prefix: prefix,
),
);
}
Future<void> _scheduleHeartBeat(
SharedPreferences prefs,
bool isBackground,
) async {
await prefs.setInt(
2022-06-11 08:23:52 +00:00
isBackground ? kLastBGTaskHeartBeatTime : kLastFGTaskHeartBeatTime,
DateTime.now().microsecondsSinceEpoch,
);
Future.delayed(kHeartBeatFrequency, () async {
_scheduleHeartBeat(prefs, isBackground);
});
}
2022-03-08 07:17:19 +00:00
Future<void> _scheduleFGSync(String caller) async {
await _sync(caller);
Future.delayed(kFGSyncFrequency, () async {
2022-11-06 10:36:33 +00:00
unawaited(_scheduleFGSync('fgSyncCron'));
});
}
void _scheduleBGTaskKill(String taskId) async {
if (await _isRunningInForeground()) {
2022-03-07 20:18:50 +00:00
_logger.info("Found app in FG, committing seppuku. $taskId");
2021-05-07 17:44:19 +00:00
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;
return (prefs.getInt(kLastFGTaskHeartBeatTime) ?? 0) >
(currentTime - kFGTaskDeathTimeoutInMicroseconds);
}
Future<void> _killBGTask([String taskId]) async {
2021-05-07 17:44:19 +00:00
await UploadLocksDB.instance.releaseLocksAcquiredByOwnerBefore(
2022-06-11 08:23:52 +00:00
ProcessType.background.toString(),
DateTime.now().microsecondsSinceEpoch,
);
2021-05-07 17:44:19 +00:00
final prefs = await SharedPreferences.getInstance();
prefs.remove(kLastBGTaskHeartBeatTime);
if (taskId != null) {
BackgroundFetch.finish(taskId);
}
2021-05-07 17:44:19 +00:00
}
2021-10-13 05:24:49 +00:00
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
2022-08-29 14:43:31 +00:00
final bool isRunningInFG = await _isRunningInForeground(); // hb
final bool isInForeground = AppLifecycleService.instance.isForeground;
2021-11-27 15:45:56 +00:00
if (_isProcessRunning) {
2022-03-07 20:18:50 +00:00
_logger.info(
2022-06-11 08:23:52 +00:00
"Background push received when app is alive and runningInFS: $isRunningInFG inForeground: $isInForeground",
);
2021-11-27 15:45:56 +00:00
if (PushService.shouldSync(message)) {
2022-03-08 07:17:19 +00:00
await _sync('firebaseBgSyncActiveProcess');
2021-11-27 15:45:56 +00:00
}
} else {
2021-10-13 05:24:49 +00:00
// App is dead
2022-06-11 08:23:52 +00:00
_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 05:24:49 +00:00
}
}
2022-03-07 20:18:50 +00:00
Future<void> _logFGHeartBeatInfo() async {
2022-08-29 14:43:31 +00:00
final bool isRunningInFG = await _isRunningInForeground();
2022-03-07 20:18:50 +00:00
final prefs = await SharedPreferences.getInstance();
await prefs.reload();
2022-08-29 14:43:31 +00:00
final lastFGTaskHeartBeatTime = prefs.getInt(kLastFGTaskHeartBeatTime) ?? 0;
final String lastRun = lastFGTaskHeartBeatTime == 0
2022-03-07 20:18:50 +00:00
? 'never'
: DateTime.fromMicrosecondsSinceEpoch(lastFGTaskHeartBeatTime).toString();
_logger.info('isAlreaduunningFG: $isRunningInFG, last Beat: $lastRun');
}
void _scheduleSuicide(Duration duration, [String taskID]) {
2022-08-29 14:43:31 +00:00
final taskIDVal = taskID ?? 'no taskID';
2022-03-07 20:18:50 +00:00
_logger.warning("Schedule seppuku taskID: $taskIDVal");
Future.delayed(duration, () {
2022-03-07 20:18:50 +00:00
_logger.warning("TLE, committing seppuku for taskID: $taskIDVal");
_killBGTask(taskID);
});
}