Skip to content

Commit

Permalink
Merge branch 'Sang/backup/auth_firebase' into Sang/backup/use_fireStore
Browse files Browse the repository at this point in the history
  • Loading branch information
ppupha committed Jan 23, 2024
2 parents 6f64b1a + cf0d1aa commit 7a9d39c
Show file tree
Hide file tree
Showing 25 changed files with 476 additions and 238 deletions.
5 changes: 4 additions & 1 deletion lib/common/injector.dart
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import 'package:autonomy_flutter/service/activation_service.dart';
import 'package:autonomy_flutter/service/address_service.dart';
import 'package:autonomy_flutter/service/airdrop_service.dart';
import 'package:autonomy_flutter/service/audit_service.dart';
import 'package:autonomy_flutter/service/auth_firebase_service.dart';
import 'package:autonomy_flutter/service/auth_service.dart';
import 'package:autonomy_flutter/service/autonomy_service.dart';
import 'package:autonomy_flutter/service/backup_service.dart';
Expand Down Expand Up @@ -170,8 +171,10 @@ Future<void> setup() async {
() => NftCollection.database.predefinedCollectionDao);
injector.registerLazySingleton(() => cloudDB);

injector
.registerLazySingleton<AuthFirebaseService>(() => AuthFirebaseService());
injector.registerLazySingleton<CloudFirestoreService>(
() => CloudFirestoreService(FirebaseFirestore.instance));
() => CloudFirestoreService(FirebaseFirestore.instance, injector()));

injector.registerLazySingleton<FirestorePersonaDao>(
() => FirestorePersonaDaoImp(injector()));
Expand Down
15 changes: 11 additions & 4 deletions lib/database/dao/firestore_persona_dao.dart
Original file line number Diff line number Diff line change
Expand Up @@ -46,10 +46,17 @@ class FirestorePersonaDaoImp implements FirestorePersonaDao {
);

@override
Future<List<Persona>> getDefaultPersonas() async =>
_collectionRef.where('defaultAccount', isEqualTo: 1).get().then(
(snapshot) => snapshot.docs.map((e) => e.data()).toList(),
);
Future<List<Persona>> getDefaultPersonas() async {
try {
final personas =
await _collectionRef.where('defaultAccount', isEqualTo: 1).get().then(
(snapshot) => snapshot.docs.map((e) => e.data()).toList(),
);
return personas;
} catch (e) {
return [];
}
}

@override
Future<int?> getPersonasCount() async => _collectionRef.get().then(
Expand Down
31 changes: 14 additions & 17 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import 'package:autonomy_flutter/common/injector.dart';
import 'package:autonomy_flutter/firebase_options.dart';
import 'package:autonomy_flutter/model/eth_pending_tx_amount.dart';
import 'package:autonomy_flutter/screen/app_router.dart';
import 'package:autonomy_flutter/service/auth_firebase_service.dart';
import 'package:autonomy_flutter/service/cloud_firestore_service.dart';
import 'package:autonomy_flutter/service/configuration_service.dart';
import 'package:autonomy_flutter/service/deeplink_service.dart';
Expand Down Expand Up @@ -83,7 +84,7 @@ void main() async {
await _setupApp();
}, (Object error, StackTrace stackTrace) async {
/// Check error is Database issue
if (error.toString().contains("DatabaseException")) {
if (error.toString().contains('DatabaseException')) {
log.info('[DatabaseException] Remove local database and resume app');

await _deleteLocalDatabase();
Expand All @@ -104,17 +105,18 @@ void _registerHiveAdapter() {
..registerAdapter(EthereumPendingTxListAdapter());
}

_setupApp() async {
Future<void> _setupApp() async {
await setup();

await DeviceInfo.instance.init();
await injector<CloudFirestoreService>().initService();
await injector<AuthFirebaseService>().initService();
final metricClient = injector.get<MetricClientService>();
await metricClient.initService();
await injector<RemoteConfigService>().loadConfigs();

final countOpenApp = injector<ConfigurationService>().countOpenApp() ?? 0;
injector<ConfigurationService>().setCountOpenApp(countOpenApp + 1);
unawaited(injector<ConfigurationService>().setCountOpenApp(countOpenApp + 1));
final packageInfo = await PackageInfo.fromPlatform();
await injector<ConfigurationService>().setVersionInfo(packageInfo.version);
final notificationService = injector<NotificationService>();
Expand All @@ -126,10 +128,11 @@ _setupApp() async {

await SentryFlutter.init(
(options) {
options.dsn = Environment.sentryDSN;
options.enableAutoSessionTracking = true;
options.tracesSampleRate = 0.25;
options.attachStacktrace = true;
options
..dsn = Environment.sentryDSN
..enableAutoSessionTracking = true
..tracesSampleRate = 0.25
..attachStacktrace = true;
},
appRunner: () => runApp(EasyLocalization(
supportedLocales: const [Locale('en', 'US')],
Expand All @@ -141,7 +144,7 @@ _setupApp() async {
Sentry.configureScope((scope) async {
final deviceID = await getDeviceID();
if (deviceID != null) {
scope.setUser(SentryUser(id: deviceID));
unawaited(scope.setUser(SentryUser(id: deviceID)));
}
});
FlutterNativeSplash.remove();
Expand All @@ -154,9 +157,9 @@ _setupApp() async {

Future<void> _deleteLocalDatabase() async {
String appDatabaseMainnet =
await sqfliteDatabaseFactory.getDatabasePath("app_database_mainnet.db");
await sqfliteDatabaseFactory.getDatabasePath('app_database_mainnet.db');
String appDatabaseTestnet =
await sqfliteDatabaseFactory.getDatabasePath("app_database_testnet.db");
await sqfliteDatabaseFactory.getDatabasePath('app_database_testnet.db');
await sqfliteDatabaseFactory.deleteDatabase(appDatabaseMainnet);
await sqfliteDatabaseFactory.deleteDatabase(appDatabaseTestnet);
}
Expand Down Expand Up @@ -196,7 +199,7 @@ class AutonomyApp extends StatelessWidget {
final RouteObserver<ModalRoute<void>> routeObserver =
CustomRouteObserver<ModalRoute<void>>();

var memoryValues = MemoryValues(
MemoryValues memoryValues = MemoryValues(
branchDeeplinkData: ValueNotifier(null),
deepLink: ValueNotifier(null),
irlLink: ValueNotifier(null));
Expand Down Expand Up @@ -233,10 +236,6 @@ class MemoryValues {
);
}

enum HomePageTab {
HOME,
}

enum HomeNavigatorTab {
collection,
organization,
Expand All @@ -251,5 +250,3 @@ void downloadCallback(String id, int status, int progress) {
IsolateNameServer.lookupPortByName('downloader_send_port');
send?.send([id, status, progress]);
}

void imageError(Object exception, StackTrace? stackTrace) {}
6 changes: 5 additions & 1 deletion lib/screen/app_router.dart
Original file line number Diff line number Diff line change
Expand Up @@ -886,7 +886,11 @@ class AppRouter {
return CupertinoPageRoute(
settings: settings,
builder: (context) => BlocProvider(
create: (_) => KeySyncBloc(injector(), injector()),
create: (_) => KeySyncBloc(
injector(),
injector(),
injector(),
),
child: const KeySyncPage(),
));

Expand Down
69 changes: 35 additions & 34 deletions lib/screen/bloc/router/router_bloc.dart
Original file line number Diff line number Diff line change
Expand Up @@ -63,42 +63,43 @@ class RouterBloc extends AuBloc<RouterEvent, RouterState> {
if (state.onboardingStep != OnboardingStep.undefined) {
return;
}
final defaultPersona = await _accountService.getDefaultPersona();
if (defaultPersona != null) {
await _cloudFirestoreService.authFiresabeService
.signInWithPersona(defaultPersona);
await migrationUtil.migrateIfNeeded();

await migrationUtil.migrateIfNeeded();

// Check and restore full accounts from cloud if existing
await migrationUtil.migrationFromKeychain();
await _accountService.androidRestoreKeys();
// Check and restore full accounts from cloud if existing
await migrationUtil.migrationFromKeychain();
await _accountService.androidRestoreKeys();

if (_configurationService.isDoneOnboarding()) {
emit(RouterState(onboardingStep: OnboardingStep.dashboard));
return;
}

//Soft delay 1s waiting for database synchronizing
await Future.delayed(const Duration(seconds: 1));

if (await hasAccounts()) {
unawaited(_configurationService.setOldUser());
final backupVersion = await _backupService
.fetchBackupVersion(await _accountService.getDefaultAccount());
if (backupVersion.isNotEmpty) {
log.info('[DefineViewRoutingEvent] have backup version');
//restore backup database
emit(RouterState(
onboardingStep: OnboardingStep.restore,
backupVersion: backupVersion));
add(RestoreCloudDatabaseRoutingEvent(backupVersion));
return;
} else {
await _cloudFirestoreService.setAlreadyBackupFromSqlite();
await _configurationService.setDoneOnboarding(true);
unawaited(injector<MetricClientService>()
.mixPanelClient
.initIfDefaultAccount());
if (_configurationService.isDoneOnboarding()) {
emit(RouterState(onboardingStep: OnboardingStep.dashboard));
return;
}

//Soft delay 1s waiting for database synchronizing
await Future.delayed(const Duration(seconds: 1));

if (await hasAccounts()) {
unawaited(_configurationService.setOldUser());
final backupVersion = await _backupService
.fetchBackupVersion(await _accountService.getDefaultAccount());
if (backupVersion.isNotEmpty) {
log.info('[DefineViewRoutingEvent] have backup version');
//restore backup database
emit(RouterState(
onboardingStep: OnboardingStep.restore,
backupVersion: backupVersion));
add(RestoreCloudDatabaseRoutingEvent(backupVersion));
return;
} else {
await _cloudFirestoreService.setAlreadyBackupFromSqlite();
await _configurationService.setDoneOnboarding(true);
emit(RouterState(onboardingStep: OnboardingStep.dashboard));
return;
}
}
} else {
emit(RouterState(onboardingStep: OnboardingStep.startScreen));
}
Expand Down Expand Up @@ -132,9 +133,9 @@ class RouterBloc extends AuBloc<RouterEvent, RouterState> {
return;
}
await _configurationService.setDoneOnboarding(true);
unawaited(injector<MetricClientService>()
.mixPanelClient
.initIfDefaultAccount());
// unawaited(injector<MetricClientService>()
// .mixPanelClient
// .initIfDefaultAccount());
emit(RouterState(onboardingStep: OnboardingStep.dashboard));
}
await migrationUtil.migrateIfNeeded();
Expand Down
29 changes: 17 additions & 12 deletions lib/screen/claim/activation/claim_activation_page.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
// ignore_for_file: discarded_futures, unawaited_futures

import 'dart:async';

import 'package:auto_size_text/auto_size_text.dart';
import 'package:autonomy_flutter/common/injector.dart';
import 'package:autonomy_flutter/gateway/activation_api.dart';
Expand Down Expand Up @@ -161,8 +163,8 @@ class _ClaimActivationPageState extends State<ClaimActivationPage> {
minFontSize: 14,
maxLines: 2,
),
onTap: () {
Navigator.push(
onTap: () async {
await Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
Expand Down Expand Up @@ -224,12 +226,12 @@ class _ClaimActivationPageState extends State<ClaimActivationPage> {
enabled: !_processing,
isProcessing: _processing,
onTap: () async {
_metricClient.addEvent(
unawaited(_metricClient.addEvent(
MixpanelEvent.acceptOwnership,
data: {
'id': widget.payload.assetToken.id,
},
);
));
setState(() {
_processing = true;
});
Expand All @@ -247,7 +249,7 @@ class _ClaimActivationPageState extends State<ClaimActivationPage> {
? WalletType.Tezos
: WalletType.Ethereum);
await _configService.setDoneOnboarding(true);
_metricClient.mixPanelClient.initIfDefaultAccount();
//_metricClient.mixPanelClient.initIfDefaultAccount();
await _configService.setPendingSettings(true);
address = walletAddress.first.address;
} else if (addresses.length == 1) {
Expand All @@ -267,7 +269,7 @@ class _ClaimActivationPageState extends State<ClaimActivationPage> {
}

if (address != null && mounted) {
_claimActivation(
await _claimActivation(
context: context,
activationID: widget.payload.activationID,
receiveAddress: address,
Expand Down Expand Up @@ -303,12 +305,12 @@ class _ClaimActivationPageState extends State<ClaimActivationPage> {
enabled: !_processing,
color: theme.colorScheme.primary,
onTap: () {
_metricClient.addEvent(
unawaited(_metricClient.addEvent(
MixpanelEvent.declineOwnership,
data: {
'id': widget.payload.assetToken.id,
},
);
));
memoryValues.branchDeeplinkData.value = null;
Navigator.of(context).pop(false);
},
Expand All @@ -334,12 +336,12 @@ class _ClaimActivationPageState extends State<ClaimActivationPage> {
),
assetToken: assetToken,
);
_metricClient.addEvent(
unawaited(_metricClient.addEvent(
MixpanelEvent.acceptOwnershipSuccess,
data: {
'id': widget.payload.assetToken.id,
},
);
));
} catch (e) {
setState(() {
_processing = false;
Expand All @@ -350,15 +352,18 @@ class _ClaimActivationPageState extends State<ClaimActivationPage> {
_processing = false;
});
if (mounted) {
Navigator.of(context).pushNamedAndRemoveUntil(
await Navigator.of(context).pushNamedAndRemoveUntil(
AppRouter.homePage,
(route) => false,
);
NftCollectionBloc.eventController
.add(GetTokensByOwnerEvent(pageKey: PageKey.init()));
final token = widget.payload.assetToken;
const caption = '';
Navigator.of(context).pushNamed(AppRouter.artworkDetailsPage,
if (!mounted) {
return;
}
await Navigator.of(context).pushNamed(AppRouter.artworkDetailsPage,
arguments: ArtworkDetailPayload(
[ArtworkIdentity(token.id, receiveAddress)], 0,
twitterCaption: caption));
Expand Down
11 changes: 5 additions & 6 deletions lib/screen/claim/airdrop/claim_airdrop_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -268,8 +268,7 @@ class _ClaimAirdropPageState extends State<ClaimAirdropPage> {
? WalletType.Tezos
: WalletType.Ethereum);
await _configService.setDoneOnboarding(true);
unawaited(_metricClient.mixPanelClient
.initIfDefaultAccount());
//_metricClient.mixPanelClient.initIfDefaultAccount();
await _configService.setPendingSettings(true);
address = walletAddress.first.address;
} else if (addresses.length == 1) {
Expand Down Expand Up @@ -323,8 +322,8 @@ class _ClaimAirdropPageState extends State<ClaimAirdropPage> {
theme.textTheme.ppMori400Grey12,
),
recognizer: TapGestureRecognizer()
..onTap = () {
_openFFArtistCollector();
..onTap = () async {
await _openFFArtistCollector();
}),
TextSpan(
text: '.',
Expand Down Expand Up @@ -409,10 +408,10 @@ class _ClaimAirdropPageState extends State<ClaimAirdropPage> {
}
}

void _openFFArtistCollector() {
Future<void> _openFFArtistCollector() async {
String uri = (widget.payload.series.exhibition?.id == null)
? FF_ARTIST_COLLECTOR
: '$FF_ARTIST_COLLECTOR/${widget.payload.series.exhibition?.id}';
unawaited(launchUrl(Uri.parse(uri), mode: LaunchMode.externalApplication));
await launchUrl(Uri.parse(uri), mode: LaunchMode.externalApplication);
}
}
Loading

0 comments on commit 7a9d39c

Please sign in to comment.