ente/lib/main.dart

254 lines
7.7 KiB
Dart
Raw Normal View History

2020-05-02 11:46:59 +00:00
import 'dart:async';
2021-01-13 17:39:45 +00:00
import 'package:background_fetch/background_fetch.dart';
import 'package:flutter/foundation.dart';
2020-03-24 19:59:36 +00:00
import 'package:flutter/material.dart';
2021-01-08 17:11:32 +00:00
import 'package:in_app_purchase/in_app_purchase.dart';
2020-05-02 16:28:54 +00:00
import 'package:path_provider/path_provider.dart';
import 'package:photos/core/constants.dart';
import 'package:photos/core/configuration.dart';
2021-04-04 17:19:46 +00:00
import 'package:photos/core/network.dart';
import 'package:photos/db/upload_locks_db.dart';
2021-01-08 06:38:45 +00:00
import 'package:photos/services/billing_service.dart';
import 'package:photos/services/collections_service.dart';
2020-10-03 17:56:18 +00:00
import 'package:photos/services/memories_service.dart';
import 'package:photos/services/notification_service.dart';
2020-10-03 17:58:26 +00:00
import 'package:photos/services/sync_service.dart';
2021-05-22 18:29:09 +00:00
import 'package:photos/services/update_service.dart';
2021-03-21 08:32:10 +00:00
import 'package:photos/ui/app_lock.dart';
import 'package:photos/ui/home_widget.dart';
2021-03-21 08:32:10 +00:00
import 'package:photos/ui/lock_screen.dart';
import 'package:photos/utils/crypto_util.dart';
import 'package:photos/utils/file_uploader.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:super_logging/super_logging.dart';
2020-05-02 16:28:54 +00:00
import 'package:logging/logging.dart';
2020-08-21 23:28:52 +00:00
final _logger = Logger("main");
2021-03-01 22:09:15 +00:00
Completer<void> _initializationStatus;
const kLastBGTaskHeartBeatTime = "bg_task_hb_time";
const kLastFGTaskHeartBeatTime = "fg_task_hb_time";
const kHeartBeatFrequency = Duration(seconds: 1);
const kFGSyncFrequency = Duration(minutes: 5);
const kFGTaskDeathTimeoutInMicroseconds = 5000000;
2020-03-24 19:59:36 +00:00
2021-03-21 08:32:10 +00:00
final themeData = ThemeData(
fontFamily: 'Ubuntu',
brightness: Brightness.dark,
hintColor: Colors.grey,
2021-05-12 15:59:07 +00:00
accentColor: Color.fromRGBO(45, 194, 98, 0.2),
2021-03-21 08:32:10 +00:00
buttonColor: Color.fromRGBO(45, 194, 98, 1.0),
buttonTheme: ButtonThemeData().copyWith(
buttonColor: Color.fromRGBO(45, 194, 98, 1.0),
),
toggleableActiveColor: Colors.green[400],
scaffoldBackgroundColor: Colors.black,
backgroundColor: Colors.black,
appBarTheme: AppBarTheme().copyWith(
color: Color.fromRGBO(10, 20, 20, 1.0),
),
2021-05-12 16:42:15 +00:00
cardColor: Color.fromRGBO(10, 15, 15, 1.0),
2021-03-21 08:32:10 +00:00
dialogTheme: DialogTheme().copyWith(
2021-05-12 15:11:57 +00:00
backgroundColor: Color.fromRGBO(10, 15, 15, 1.0),
2021-03-21 08:32:10 +00:00
),
2021-05-12 19:34:13 +00:00
textSelectionTheme: TextSelectionThemeData().copyWith(
cursorColor: Colors.white.withOpacity(0.5),
),
2021-03-21 08:32:10 +00:00
);
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");
await _init(false);
_scheduleFGSync();
2021-03-21 08:32:10 +00:00
runApp(AppLock(
builder: (args) => EnteApp(),
lockScreen: LockScreen(),
enabled: Configuration.instance.shouldShowLockScreen(),
themeData: themeData,
));
2021-03-01 22:09:15 +00:00
});
}
2020-05-02 11:46:59 +00:00
2021-03-01 22:09:15 +00:00
Future _runInBackground(String taskId) async {
if (_initializationStatus == null) {
_runWithLogs(() async {
_backgroundTask(taskId);
}, prefix: "[bg]");
2021-03-01 22:09:15 +00:00
} else {
_backgroundTask(taskId);
}
}
void _backgroundTask(String taskId) async {
await Future.delayed(Duration(seconds: 3));
if (await _isRunningInForeground()) {
_logger.info("FG task running, skipping BG task");
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);
await _init(true);
await _sync(isAppInBackground: true);
BackgroundFetch.finish(taskId);
2021-03-01 22:09:15 +00:00
}
2020-05-02 11:46:59 +00:00
2021-03-01 22:09:15 +00:00
void _headlessTaskHandler(HeadlessTask task) {
if (task.timeout) {
BackgroundFetch.finish(task.taskId);
} else {
_runInBackground(task.taskId);
}
2021-01-13 17:39:45 +00:00
}
Future<void> _init(bool isBackground) async {
2021-03-01 22:09:15 +00:00
if (_initializationStatus != null) {
return _initializationStatus.future;
}
_initializationStatus = Completer<void>();
_scheduleHeartBeat(isBackground);
2021-03-02 06:08:29 +00:00
_logger.info("Initializing...");
2021-01-13 17:39:45 +00:00
InAppPurchaseConnection.enablePendingPurchases();
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();
2021-05-22 18:29:09 +00:00
await UpdateService.instance.init();
await BillingService.instance.init();
2021-01-13 17:39:45 +00:00
await CollectionsService.instance.init();
await FileUploader.instance.init(isBackground);
await SyncService.instance.init(isBackground);
2021-01-13 17:39:45 +00:00
await MemoriesService.instance.init();
2021-02-06 16:11:27 +00:00
_logger.info("Initialization done");
2021-03-01 22:09:15 +00:00
_initializationStatus.complete();
2020-05-02 11:46:59 +00:00
}
2021-01-13 17:39:45 +00:00
Future<void> _sync({bool isAppInBackground = false}) async {
2021-02-26 09:50:52 +00:00
if (SyncService.instance.isSyncInProgress()) {
2021-03-01 23:36:58 +00:00
_logger.info("Sync is already in progress, skipping");
2021-02-26 09:50:52 +00:00
return;
}
2021-02-26 14:09:45 +00:00
if (isAppInBackground) {
_logger.info("Syncing in background");
}
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 {
2021-01-13 17:39:45 +00:00
await SuperLogging.main(LogConfig(
body: function,
logDirPath: (await getTemporaryDirectory()).path + "/logs",
maxLogFiles: 5,
2021-03-01 22:09:15 +00:00
sentryDsn: kDebugMode ? SENTRY_DEBUG_DSN : SENTRY_DSN,
enableInDebugMode: true,
prefix: prefix,
2021-01-13 17:39:45 +00:00
));
}
Future<void> _scheduleHeartBeat(bool isBackground) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt(
isBackground ? kLastBGTaskHeartBeatTime : kLastFGTaskHeartBeatTime,
DateTime.now().microsecondsSinceEpoch);
Future.delayed(kHeartBeatFrequency, () async {
_scheduleHeartBeat(isBackground);
});
}
Future<void> _scheduleFGSync() async {
await _sync();
Future.delayed(kFGSyncFrequency, () async {
_scheduleFGSync();
});
}
void _scheduleBGTaskKill(String taskId) async {
if (await _isRunningInForeground()) {
_logger.info("Found app in FG, committing seppuku.");
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);
}
2021-05-07 17:44:19 +00:00
Future<void> _killBGTask(String taskId) async {
await UploadLocksDB.instance.releaseLocksAcquiredByOwnerBefore(
ProcessType.background.toString(), DateTime.now().microsecondsSinceEpoch);
2021-05-07 17:44:19 +00:00
final prefs = await SharedPreferences.getInstance();
prefs.remove(kLastBGTaskHeartBeatTime);
BackgroundFetch.finish(taskId);
}
2021-03-21 08:32:10 +00:00
class EnteApp extends StatelessWidget with WidgetsBindingObserver {
static const _homeWidget = const HomeWidget();
2020-04-05 08:31:01 +00:00
@override
Widget build(BuildContext context) {
2020-04-27 13:02:29 +00:00
WidgetsBinding.instance.addObserver(this);
2021-03-21 08:32:10 +00:00
_configureBackgroundFetch();
return MaterialApp(
title: "ente",
theme: themeData,
home: _homeWidget,
debugShowCheckedModeBanner: false,
2021-03-21 08:32:10 +00:00
);
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_logger.info("App resumed");
_sync();
}
}
2020-04-27 13:02:29 +00:00
2021-03-21 08:32:10 +00:00
void _configureBackgroundFetch() {
2021-01-13 17:39:45 +00:00
BackgroundFetch.configure(
BackgroundFetchConfig(
minimumFetchInterval: 15,
forceAlarmManager: false,
stopOnTerminate: false,
startOnBoot: true,
enableHeadless: true,
requiresBatteryNotLow: false,
requiresCharging: false,
requiresStorageNotLow: false,
requiresDeviceIdle: false,
requiredNetworkType: NetworkType.NONE,
), (String taskId) async {
2021-03-01 22:09:15 +00:00
await _runInBackground(taskId);
}, (taskId) {
2021-05-07 17:44:19 +00:00
_logger.info("BG task timeout");
_killBGTask(taskId);
2021-01-13 17:39:45 +00:00
}).then((int status) {
2021-02-26 11:05:54 +00:00
_logger.info('[BackgroundFetch] configure success: $status');
2021-01-13 17:39:45 +00:00
}).catchError((e) {
2021-02-26 11:05:54 +00:00
_logger.info('[BackgroundFetch] configure ERROR: $e');
2021-01-13 17:39:45 +00:00
});
2020-04-27 13:02:29 +00:00
}
2020-04-05 08:31:01 +00:00
}