This commit is contained in:
jantunesmessias 2024-09-25 15:23:23 -03:00
parent 43f5839db0
commit 12535eb7e8
7 changed files with 686 additions and 378 deletions

View File

@ -132,7 +132,6 @@ class SignInTemplateComponentModel
await checkLocals(context: context, model: model).then((value) {
SecureStorageHelper().haveLocal = value;
SecureStorageHelper().isLogged = isLogged;
SecureStorageHelper().update(() {});
toggleApp(context);
});
} else {

View File

@ -18,33 +18,63 @@ import 'package:hub/flutter_flow/nav/nav.dart';
import 'package:hub/shared/helpers/secure_storage_helper.dart';
import 'package:hub/shared/helpers/shared_preferences_storage_helper.dart';
import 'package:hub/shared/helpers/sqlite_storage_helper.dart';
import 'package:provider/provider.dart';
import 'package:responsive_framework/responsive_framework.dart';
final GlobalKey<NavigatorState> navigatorKey = GlobalKey<NavigatorState>();
Future<void> initializeApp() async {
WidgetsFlutterBinding.ensureInitialized();
await SQLiteStorageHelper().database;
SQLiteStorageHelper().deleteDatabaseDB();
final SharedPreferencesStorageHelper sharedPreferencesHelper =
SharedPreferencesStorageHelper();
final SecureStorageHelper secureStorageHelper = SecureStorageHelper();
void main() async {
await _initializeApp();
runApp(const App());
}
Future<void> _initializeApp() async {
WidgetsFlutterBinding.ensureInitialized();
await _initializeStorageHelpers();
await _initializeTracking();
await _initializeFirebase();
await _initializeNotificationService();
_initializeUrlStrategy();
_initializeSystemSettings();
await _initializeFlutterFlow();
}
Future<void> _initializeStorageHelpers() async {
final SharedPreferencesStorageHelper sharedPreferencesHelper = SharedPreferencesStorageHelper();
final SecureStorageHelper secureStorageHelper = SecureStorageHelper();
final SQLiteStorageHelper sqLiteStorageHelper = SQLiteStorageHelper();
await sqLiteStorageHelper.ensureInitialization();
await sharedPreferencesHelper.ensureInitialization();
await secureStorageHelper.ensureInitilization();
await secureStorageHelper.ensureInitialization();
if (sharedPreferencesHelper.isFirstRun) {
sharedPreferencesHelper.isFirstRun = false;
secureStorageHelper.purge();
}
}
Future<void> _initializeTracking() async {
await AppTrackingTransparency.requestTrackingAuthorization();
}
Future<void> _initializeFirebase() async {
await Firebase.initializeApp();
await NotificationService.initialize();
}
Future<void> _initializeNotificationService() async {
await NotificationService.initialize();
}
void _initializeUrlStrategy() {
setUrlStrategy(const PathUrlStrategy());
}
void _initializeSystemSettings() {
SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
if (kDebugMode) {
log("Aplicativo em Debug Mode, crashlytics desabilitado!");
@ -54,14 +84,16 @@ Future<void> initializeApp() async {
FlutterError.onError = crashlyticsInstance.recordFlutterError;
}
}
}
Future<void> _initializeFlutterFlow() async {
await FlutterFlowTheme.initialize();
await FFLocalizations.initialize();
GoRouter.optionURLReflectsImperativeAPIs = true;
usePathUrlStrategy();
}
Future<void> foregroundHandleMessage(RemoteMessage message) async {
Future<void> _foregroundHandleMessage(RemoteMessage message) async {
if (message.data['click_action'] == 'enroll_cond') {
SecureStorageHelper().haveLocal = true;
SecureStorageHelper().context?.go('/homePage');
@ -81,15 +113,12 @@ Future<void> _backgroundHandleMessage(RemoteMessage message) async {
}
}
void main() async {
await initializeApp();
runApp(const App());
}
class App extends StatefulWidget {
const App({super.key});
@override
State<App> createState() => _AppState();
static _AppState of(BuildContext context) =>
context.findAncestorStateOfType<_AppState>()!;
}
@ -101,32 +130,86 @@ class _AppState extends State<App> {
late GoRouter _router;
bool displaySplashImage = true;
final ThemeData _darkTheme = ThemeData(
brightness: Brightness.dark,
scrollbarTheme: ScrollbarThemeData(
thumbVisibility: WidgetStateProperty.all(false),
interactive: false,
thumbColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.dragged)) {
return const Color(0xff1aab5f);
}
if (states.contains(WidgetState.hovered)) {
return const Color(0xff1aab5f);
}
return const Color(0xff1aab5f);
}),
),
);
final ThemeData _theme = ThemeData(
brightness: Brightness.light,
scrollbarTheme: ScrollbarThemeData(
thumbVisibility: WidgetStateProperty.all(false),
interactive: false,
thumbColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.dragged)) {
return const Color(0xff1aab5f);
}
if (states.contains(WidgetState.hovered)) {
return const Color(0xff1aab5f);
}
return const Color(0xff1aab5f);
}),
),
);
final Iterable<LocalizationsDelegate<dynamic>>? localizationsDelegates = const [
FFLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
];
final Iterable<Locale> supportedLocales = const [
Locale('pt'),
Locale('en'),
];
Widget Function(BuildContext, Widget?)? builder = (context, widget) {
final breakpoints = [
const Breakpoint(start: 0, end: 450, name: MOBILE),
const Breakpoint(start: 451, end: 800, name: TABLET),
const Breakpoint(start: 801, end: 1920, name: DESKTOP),
const Breakpoint(start: 1921, end: double.infinity, name: '4K'),
];
return ResponsiveBreakpoints.builder(
child: BouncingScrollWrapper.builder(context, widget!),
breakpoints: breakpoints,
);
};
@override
void initState() {
super.initState();
FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
// WidgetsFlutterBinding.ensureInitialized().addPostFrameCallback((_) => initializeTracking());
_appStateNotifier = AppStateNotifier.instance;
_router = createRouter(_appStateNotifier);
Future.delayed(const Duration(milliseconds: 1000),
() => setState(() => _appStateNotifier.stopShowingSplashImage()));
FirebaseMessaging.onMessage.listen(foregroundHandleMessage);
FirebaseMessaging.onMessage.listen(_foregroundHandleMessage);
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
onMessageReceived(message.data, message.notification!.body,
message.data['click_action']);
});
FirebaseMessaging.onBackgroundMessage(_backgroundHandleMessage);
FirebaseMessaging.instance.getInitialMessage().then((message) {
if (message != null) {
_backgroundHandleMessage(message);
}
});
// SecureStorageHelper().isLogged = false;
}
void setLocale(String language) {
@ -145,58 +228,12 @@ class _AppState extends State<App> {
Widget build(BuildContext context) {
return MaterialApp.router(
title: 'FRE ACCESS HUB',
builder: (context, widget) => ResponsiveBreakpoints.builder(
child: BouncingScrollWrapper.builder(context, widget!),
breakpoints: [
const Breakpoint(start: 0, end: 450, name: MOBILE),
const Breakpoint(start: 451, end: 800, name: TABLET),
const Breakpoint(start: 801, end: 1920, name: DESKTOP),
const Breakpoint(start: 1921, end: double.infinity, name: '4K'),
],
),
localizationsDelegates: const [
FFLocalizationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
builder: builder,
localizationsDelegates: localizationsDelegates,
locale: _locale,
supportedLocales: const [
Locale('pt'),
Locale('en'),
],
theme: ThemeData(
brightness: Brightness.light,
scrollbarTheme: ScrollbarThemeData(
thumbVisibility: WidgetStateProperty.all(false),
interactive: false,
thumbColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.dragged)) {
return const Color(0xff1aab5f);
}
if (states.contains(WidgetState.hovered)) {
return const Color(0xff1aab5f);
}
return const Color(0xff1aab5f);
}),
),
),
darkTheme: ThemeData(
brightness: Brightness.dark,
scrollbarTheme: ScrollbarThemeData(
thumbVisibility: WidgetStateProperty.all(false),
interactive: false,
thumbColor: WidgetStateProperty.resolveWith((states) {
if (states.contains(WidgetState.dragged)) {
return const Color(0xff1aab5f);
}
if (states.contains(WidgetState.hovered)) {
return const Color(0xff1aab5f);
}
return const Color(0xff1aab5f);
}),
),
),
supportedLocales: supportedLocales,
theme: _theme,
darkTheme: _darkTheme,
themeMode: _themeMode,
routerConfig: _router,
);

View File

@ -1,7 +1,9 @@
import 'dart:convert';
import 'dart:developer';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:hub/flutter_flow/flutter_flow_util.dart';
import 'package:hub/shared/utils/storage_util.dart';
import 'package:hub/shared/utils/cache_util.dart';
import 'package:synchronized/synchronized.dart';
class SecureStorageHelper extends ChangeNotifier implements Storage {
@ -13,165 +15,185 @@ class SecureStorageHelper extends ChangeNotifier implements Storage {
SecureStorageHelper._internal();
String _deviceDescription = '';
String get deviceDescription => _deviceDescription;
set deviceDescription(String value) {
_setString('deviceDescription', value);
_deviceDescription = value;
}
static SecureStorageHelper get instance => _instance;
String? _deviceDescription;
String get deviceDescription => _deviceDescription ?? '';
set deviceDescription(String value) => _setAndCacheString('deviceDescription', value, (v) => _deviceDescription = v);
BuildContext? _context;
BuildContext? get context => _context;
set context(BuildContext? value) {
_setString('ff_context', value.toString());
_context = value;
}
set context(BuildContext? value) => _setAndCacheObject('ff_context', value.toString(), (v) => _context = value);
bool? _haveLocal;
bool? get haveLocal => _haveLocal;
set haveLocal(bool? value) {
_setBool('ff_have_local', value);
_haveLocal = value;
}
set haveLocal(bool? value) => _setAndCacheBool('ff_have_local', value ?? false, (v) => _haveLocal = value);
String _fingerprintPass = '';
String get fingerprintPass => _fingerprintPass;
set fingerprintPass(String value) {
_setString('fingerprintPass', value);
_fingerprintPass = value;
}
String? _fingerprintPass;
String get fingerprintPass => _fingerprintPass ?? '';
set fingerprintPass(String value) => _setAndCacheString('fingerprintPass', value, (v) => _fingerprintPass = v);
String _accessPass = '';
String get accessPass => _accessPass;
set accessPass(String value) {
_setString('accessPass', value);
_accessPass = value;
}
String? _accessPass;
String get accessPass => _accessPass ?? '';
set accessPass(String value) => _setAndCacheString('accessPass', value, (v) => _accessPass = v);
String _panicPass = '';
String get panicPass => _panicPass;
set panicPass(String value) {
_setString('panicPass', value);
_panicPass = value;
}
String? _panicPass;
String get panicPass => _panicPass ?? '';
set panicPass(String value) => _setAndCacheString('panicPass', value, (v) => _panicPass = v);
String? _tokenAPNS = '';
String? _tokenAPNS;
String? get tokenAPNS => _tokenAPNS;
set tokenAPNS(String? value) {
_setString('ff_tokenAPNS', value ?? '');
_tokenAPNS = value;
}
set tokenAPNS(String? value) => _setAndCacheString('ff_tokenAPNS', value ?? '', (v) => _tokenAPNS = v);
String _email = '';
String get email => _email;
set email(String value) {
_setString('ff_email', value);
_email = value;
}
String? _email;
String get email => _email ?? '';
set email(String value) => _setAndCacheString('ff_email', value, (v) => _email = v);
String _passwd = '';
String get passwd => _passwd;
set passwd(String value) {
_setString('ff_passwd', value);
_passwd = value;
}
String? _passwd;
String get passwd => _passwd ?? '';
set passwd(String value) => _setAndCacheString('ff_passwd', value, (v) => _passwd = v);
String _deviceType = '';
String get deviceType => _deviceType;
set deviceType(String value) {
_setString('ff_deviceType', value);
_deviceType = value;
}
String? _deviceType;
String get deviceType => _deviceType ?? '';
set deviceType(String value) => _setAndCacheString('ff_deviceType', value, (v) => _deviceType = v);
bool _isLogged = false;
bool get isLogged => _isLogged;
set isLogged(bool value) {
_setBool('ff_isLogged', value);
_isLogged = value;
}
bool? _isLogged;
bool get isLogged => _isLogged ?? false;
set isLogged(bool value) => _setAndCacheBool('ff_isLogged', value, (v) => _isLogged = v);
String _token = '';
String get token => _token;
set token(String value) {
_setString('ff_token', value);
_token = value;
}
String? _token;
String get token => _token ?? '';
set token(String value) => _setAndCacheString('ff_token', value, (v) => _token = v);
Future<void> ensureInitilization() async {
await _safeInitAsync(() async {
_email = await _getString('ff_email');
_passwd = await _getString('ff_passwd');
_deviceType = await _getString('ff_deviceType');
_isLogged = await _getBool('ff_isLogged');
_tokenAPNS = await _getString('ff_tokenAPNS');
_accessPass = await _getString('accessPass');
_panicPass = await _getString('panicPass');
_fingerprintPass = await _getString('fingerprintPass');
_context = await _getObject('ff_context');
_haveLocal = await _getBool('ff_have_local');
_deviceDescription = await _getString('deviceDescription');
});
}
Future<void> _safeInitAsync(Future<void> Function() initFunction) async {
Future<void> ensureInitialization() async {
log('SecureStorageHelper: Starting initialization');
await _lock.synchronized(() async {
try {
await initFunction();
log('SecureStorageHelper: Calling initFunction');
_email = await _getString('ff_email');
log('SecureStorageHelper: _email = $_email');
_passwd = await _getString('ff_passwd');
log('SecureStorageHelper: _passwd = $_passwd');
_deviceType = await _getString('ff_deviceType');
log('SecureStorageHelper: _deviceType = $_deviceType');
_isLogged = await _getBool('ff_isLogged');
log('SecureStorageHelper: _isLogged = $_isLogged');
_tokenAPNS = await _getString('ff_tokenAPNS');
log('SecureStorageHelper: _tokenAPNS = $_tokenAPNS');
_accessPass = await _getString('accessPass');
log('SecureStorageHelper: _accessPass = $_accessPass');
_panicPass = await _getString('panicPass');
log('SecureStorageHelper: _panicPass = $_panicPass');
_fingerprintPass = await _getString('fingerprintPass');
log('SecureStorageHelper: _fingerprintPass = $_fingerprintPass');
_context = await _getObject('ff_context');
log('SecureStorageHelper: _context = $_context');
_haveLocal = await _getBool('ff_have_local');
log('SecureStorageHelper: _haveLocal = $_haveLocal');
_deviceDescription = await _getString('deviceDescription');
log('SecureStorageHelper: _deviceDescription = $_deviceDescription');
log('SecureStorageHelper: initFunction completed successfully');
} catch (e) {
// Log or handle the error
log('SecureStorageHelper: Error during initialization: $e');
}
});
log('SecureStorageHelper: Initialization complete');
}
Future<void> _setAndCacheString(String key, String value, Function(String) cacheSetter) async {
await _lock.synchronized(() async {
await _secureStorage.write(key: key, value: value);
CacheUtil.instance.set(key, value);
cacheSetter(value);
});
}
Future<String> _getString(String key) async {
return await _secureStorage.read(key: key) ?? '';
Future<void> _setAndCacheBool(String key, bool value, Function(bool) cacheSetter) async {
await _lock.synchronized(() async {
await _secureStorage.write(key: key, value: value.toString());
CacheUtil.instance.set(key, value);
cacheSetter(value);
});
}
Future<bool> _getBool(String key) async {
return (await _secureStorage.read(key: key))?.toLowerCase() == 'true';
Future<void> _setAndCacheObject(String key, String value, Function(String) cacheSetter) async {
await _lock.synchronized(() async {
await _secureStorage.write(key: key, value: value);
CacheUtil.instance.set(key, value);
cacheSetter(value);
});
}
Future<dynamic> _getObject(String key) async {
// Implement your object retrieval logic here
return null;
Future<String?> _getString(String key) async {
return await _lock.synchronized(() async {
var value = CacheUtil.instance.get(key);
if (value == null) {
value = await _secureStorage.read(key: key);
CacheUtil.instance.set(key, value);
}
return value;
});
}
void update(VoidCallback callback) {
callback();
notifyListeners();
Future<bool?> _getBool(String key) async {
return await _lock.synchronized(() async {
var value = CacheUtil.instance.get(key);
if (value == null) {
value = await _secureStorage.read(key: key);
CacheUtil.instance.set(key, value == 'true');
}
return value == 'true';
});
}
Future<void> _setString(String key, String value) async {
await _secureStorage.write(key: key, value: value);
}
Future<void> _setBool(String key, bool? value) async {
await _secureStorage.write(key: key, value: value.toString());
}
Future<void> purge() async {
_secureStorage.deleteAll();
await ensureInitilization();
Future<BuildContext?> _getObject(String key) async {
return await _lock.synchronized(() async {
var value = CacheUtil.instance.get(key);
if (value == null) {
value = await _secureStorage.read(key: key);
CacheUtil.instance.set(key, value);
}
return value as BuildContext?;
});
}
@override
Future<void> set(String key, dynamic value) async {
if (value is String) {
await _setString(key, value);
await _setAndCacheString(key, value, (v) {});
} else if (value is bool) {
await _setBool(key, value);
} else if (value is int || value is double) {
await _setString(key, value.toString());
await _setAndCacheBool(key, value, (v) {});
} else if (value is BuildContext) {
await _setAndCacheObject(key, value.toString(), (v) {});
}
}
@override
Future<dynamic> get(String key) async {
return await _secureStorage.read(key: key);
var stringValue = await _getString(key);
if (stringValue != null) return stringValue;
var boolValue = await _getBool(key);
if (boolValue != null) return boolValue;
var objectValue = await _getObject(key);
if (objectValue != null) return objectValue;
return null;
}
@override
Future<void> delete(String key) async {
await _secureStorage.delete(key: key);
await _lock.synchronized(() async {
await _secureStorage.delete(key: key);
CacheUtil.instance.delete(key);
});
}
}
Future<void> purge() async {
await _lock.synchronized(() async {
await _secureStorage.deleteAll();
CacheUtil.instance.clear();
});
}
}

View File

@ -1,66 +1,103 @@
import 'package:hub/shared/utils/storage_util.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:hub/shared/utils/cache_util.dart';
import 'package:synchronized/synchronized.dart';
class SharedPreferencesStorageHelper implements Storage {
late SharedPreferences _prefs;
static final SharedPreferencesStorageHelper _instance = SharedPreferencesStorageHelper._internal();
static final _lock = Lock();
SharedPreferences? _prefs;
static final SharedPreferencesStorageHelper _instance =
SharedPreferencesStorageHelper._internal();
factory SharedPreferencesStorageHelper() {
return _instance;
}
factory SharedPreferencesStorageHelper() => _instance;
SharedPreferencesStorageHelper._internal();
Future<void> ensureInitialization() async {
_prefs = await SharedPreferences.getInstance();
_isFirstRun = _prefs.getBool('first_run') ?? true;
}
static SharedPreferencesStorageHelper get instance => _instance;
bool _isFirstRun = true;
bool get isFirstRun => _isFirstRun;
set isFirstRun(bool value) {
_isFirstRun = value;
set('first_run', value);
set isFirstRun(bool value) => _setAndCacheBool('first_run', value, (v) => _isFirstRun = v);
Future<void> ensureInitialization() async {
await _lock.synchronized(() async {
if (_prefs == null) {
_prefs = await SharedPreferences.getInstance();
_isFirstRun = _prefs?.getBool('first_run') ?? true;
}
});
}
Future<void> _setAndCache<T>(String key, T value, Function(T) cacheSetter, Future<void> Function(String, T) setFunc) async {
await _lock.synchronized(() async {
await setFunc(key, value);
CacheUtil.instance.set(key, value);
cacheSetter(value);
});
}
Future<void> _setAndCacheString(String key, String value, Function(String) cacheSetter) async {
await _setAndCache(key, value, cacheSetter, _prefs!.setString);
}
Future<void> _setAndCacheBool(String key, bool value, Function(bool) cacheSetter) async {
await _setAndCache(key, value, cacheSetter, _prefs!.setBool);
}
Future<void> _setAndCacheInt(String key, int value, Function(int) cacheSetter) async {
await _setAndCache(key, value, cacheSetter, _prefs!.setInt);
}
Future<void> _setAndCacheDouble(String key, double value, Function(double) cacheSetter) async {
await _setAndCache(key, value, cacheSetter, _prefs!.setDouble);
}
Future<void> _setAndCacheStringList(String key, List<String> value, Function(List<String>) cacheSetter) async {
await _setAndCache(key, value, cacheSetter, _prefs!.setStringList);
}
@override
Future<void> set(String key, dynamic value) async {
if (value is bool) {
await _prefs.setBool(key, value);
} else if (value is String) {
await _prefs.setString(key, value);
} else if (value is int) {
await _prefs.setInt(key, value);
} else if (value is double) {
await _prefs.setDouble(key, value);
} else if (value is List<String>) {
await _prefs.setStringList(key, value);
}
await _lock.synchronized(() async {
if (value is bool) {
await _prefs?.setBool(key, value);
} else if (value is String) {
await _prefs?.setString(key, value);
} else if (value is int) {
await _prefs?.setInt(key, value);
} else if (value is double) {
await _prefs?.setDouble(key, value);
} else if (value is List<String>) {
await _prefs?.setStringList(key, value);
}
CacheUtil.instance.set(key, value);
});
}
@override
Future<dynamic> get(String key) async {
try {
return _prefs.get(key);
} catch (e) {
// Log or handle the error
return null;
}
return await _lock.synchronized(() async {
var value = CacheUtil.instance.get(key);
if (value == null) {
value = _prefs?.get(key);
CacheUtil.instance.set(key, value);
}
return value;
});
}
@override
Future<void> delete(String key) async {
try {
await _prefs.remove(key);
} catch (e) {
// Log or handle the error
}
await _lock.synchronized(() async {
await _prefs?.remove(key);
CacheUtil.instance.delete(key);
});
}
Future<void> purge() async {
await _prefs.clear();
await ensureInitialization();
await _lock.synchronized(() async {
await _prefs?.clear();
CacheUtil.instance.clear();
await ensureInitialization();
});
}
}
}

View File

@ -1,13 +1,7 @@
import 'package:hub/shared/utils/cache_util.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:developer';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
class DatabaseConfig {
static const String dbName = 'database.db';
@ -53,13 +47,19 @@ class SQLiteStorageHelper {
SQLiteStorageHelper._internal();
Future<Database> get database async {
static SQLiteStorageHelper get instance => _instance;
Future<Database> ensureInitialization() async {
log('Getting database instance');
if (_database != null) return _database!;
_database = await _initDatabase();
return _database!;
}
Future<String> _getDatabasePath() async {
log('Getting database path');
if (_databasePath != null) return _databasePath!;
final databasesPath = await getDatabasesPath();
_databasePath = join(databasesPath, DatabaseConfig.dbName);
@ -68,6 +68,7 @@ class SQLiteStorageHelper {
}
Future<Database> _initDatabase() async {
log('Initializing database');
final path = await _getDatabasePath();
return await openDatabase(
path,
@ -80,7 +81,10 @@ class SQLiteStorageHelper {
).catchError((error) {
log('Error initializing database: $error');
throw error;
}).whenComplete(() async => await setupLocalVariables());
}).whenComplete(() async {
log('Database initialization complete');
await setupLocalVariables();
});
}
Future<void> _onCreate(Database db, int version) async {
@ -100,15 +104,17 @@ class SQLiteStorageHelper {
}
Future<void> _insertInitialData(Database db) async {
log('Inserting initial data');
final batch = db.batch();
for (var data in DatabaseConfig.initialData) {
batch.insert(DatabaseConfig.tableKeychain, data);
}
await batch.commit(noResult: true);
log('Initial data inserted');
}
Future<void> _onOpen(Database db) async {
log('Checking existing data...');
log('Opening database');
await _checkExistingData(db);
}
@ -121,10 +127,11 @@ class SQLiteStorageHelper {
}
Future<void> _onConfigure(Database db) async {
log('Configuring database...');
log('Configuring database');
}
Future<void> _checkExistingData(Database db) async {
log('Checking existing data');
try {
final maps = await db.query(DatabaseConfig.tableKeychain);
log('Existing data: $maps');
@ -153,107 +160,259 @@ class SQLiteStorageHelper {
bool _person = false;
bool _requestOSnotification = false;
String get createdAt => '0000-00-00 00:00:00';
String get devUUID => _devUUID;
String get userUUID => _userUUID;
String get userDevUUID => _userDevUUID;
String get status => _status;
String get userName => _userName;
String get cliUUID => _cliUUID;
String get ownerUUID => _ownerUUID;
String get cliName => _cliName;
String get petAmountRegister => _petAmountRegister;
bool get whatsapp => _whatsapp;
bool get provisional => _provisional;
bool get pets => _pets;
bool get local => _local;
bool get notify => _notify;
bool get fingerprint => _fingerprint;
bool get access => _access;
bool get panic => _panic;
bool get person => _person;
bool get requestOSnotification => _requestOSnotification;
String get createdAt {
log('Getting createdAt');
return '0000-00-00 00:00:00';
}
set devUUID(String value) => set('devUUID', value);
set userUUID(String value) => set('userUUID', value);
set userDevUUID(String value) => set('userDevUUID', value);
set status(String value) => set('status', value);
set userName(String value) => set('userName', value);
set cliUUID(String value) => set('cliUUID', value);
set ownerUUID(String value) => set('ownerUUID', value);
set cliName(String value) => set('cliName', value);
set petAmountRegister(String value) => set('petAmountRegister', value);
set whatsapp(bool value) => set('whatsapp', value);
set provisional(bool value) => set('provisional', value);
set pets(bool value) => set('pets', value);
set local(bool value) => set('local', value);
set notify(bool value) => set('notify', value);
set fingerprint(bool value) => set('fingerprint', value);
set access(bool value) => set('access', value);
set panic(bool value) => set('panic', value);
set person(bool value) => set('person', value);
set requestOSnotification(bool value) => set('requestOSnotification', value);
String get devUUID {
log('Getting devUUID');
return _devUUID;
}
String get userUUID {
log('Getting userUUID');
return _userUUID;
}
String get userDevUUID {
log('Getting userDevUUID');
return _userDevUUID;
}
String get status {
log('Getting status');
return _status;
}
String get userName {
log('Getting userName');
return _userName;
}
String get cliUUID {
log('Getting cliUUID');
return _cliUUID;
}
String get ownerUUID {
log('Getting ownerUUID');
return _ownerUUID;
}
String get cliName {
log('Getting cliName');
return _cliName;
}
String get petAmountRegister {
log('Getting petAmountRegister');
return _petAmountRegister;
}
bool get whatsapp {
log('Getting whatsapp');
return _whatsapp;
}
bool get provisional {
log('Getting provisional');
return _provisional;
}
bool get pets {
log('Getting pets');
return _pets;
}
bool get local {
log('Getting local');
return _local;
}
bool get notify {
log('Getting notify');
return _notify;
}
bool get fingerprint {
log('Getting fingerprint');
return _fingerprint;
}
bool get access {
log('Getting access');
return _access;
}
bool get panic {
log('Getting panic');
return _panic;
}
bool get person {
log('Getting person');
return _person;
}
bool get requestOSnotification {
log('Getting requestOSnotification');
return _requestOSnotification;
}
set devUUID(String value) {
log('Setting devUUID to $value');
set('devUUID', value);
}
set userUUID(String value) {
log('Setting userUUID to $value');
set('userUUID', value);
}
set userDevUUID(String value) {
log('Setting userDevUUID to $value');
set('userDevUUID', value);
}
set status(String value) {
log('Setting status to $value');
set('status', value);
}
set userName(String value) {
log('Setting userName to $value');
set('userName', value);
}
set cliUUID(String value) {
log('Setting cliUUID to $value');
set('cliUUID', value);
}
set ownerUUID(String value) {
log('Setting ownerUUID to $value');
set('ownerUUID', value);
}
set cliName(String value) {
log('Setting cliName to $value');
set('cliName', value);
}
set petAmountRegister(String value) {
log('Setting petAmountRegister to $value');
set('petAmountRegister', value);
}
set whatsapp(bool value) {
log('Setting whatsapp to $value');
set('whatsapp', value);
}
set provisional(bool value) {
log('Setting provisional to $value');
set('provisional', value);
}
set pets(bool value) {
log('Setting pets to $value');
set('pets', value);
}
set local(bool value) {
log('Setting local to $value');
set('local', value);
}
set notify(bool value) {
log('Setting notify to $value');
set('notify', value);
}
set fingerprint(bool value) {
log('Setting fingerprint to $value');
set('fingerprint', value);
}
set access(bool value) {
log('Setting access to $value');
set('access', value);
}
set panic(bool value) {
log('Setting panic to $value');
set('panic', value);
}
set person(bool value) {
log('Setting person to $value');
set('person', value);
}
set requestOSnotification(bool value) {
log('Setting requestOSnotification to $value');
set('requestOSnotification', value);
}
Future<void> setupLocalVariables() async {
log('Setting up local variables...');
await _database?.transaction((txn) async {
final keys = [
'devUUID',
'userUUID',
'userDevUUID',
'status',
'userName',
'cliUUID',
'ownerUUID',
'cliName',
'whatsapp',
'provisional',
'pets',
'local',
'notify',
'fingerprint',
'access',
'panic',
'person',
'requestOSnotification'
];
log('Setting up local variables');
try {
await _database?.transaction((txn) async {
final keys = [
'devUUID',
'userUUID',
'userDevUUID',
'status',
'userName',
'cliUUID',
'ownerUUID',
'cliName',
'petAmountRegister',
'whatsapp',
'provisional',
'pets',
'local',
'notify',
'fingerprint',
'access',
'panic',
'person',
'requestOSnotification'
];
final results = await Future.wait(keys.map((key) => get(key)));
_devUUID = results[0]?.toString() ?? '';
_userUUID = results[1]?.toString() ?? '';
_userDevUUID = results[2]?.toString() ?? '';
_status = results[3]?.toString() ?? '';
_userName = results[4]?.toString() ?? '';
_cliUUID = results[5]?.toString() ?? '';
_ownerUUID = results[6]?.toString() ?? '';
_cliName = results[7]?.toString() ?? '';
_whatsapp = results[8] == 'true';
_provisional = results[9] == 'true';
_pets = results[10] == 'true';
_local = results[11] == 'true';
_notify = results[12] == 'true';
_fingerprint = results[13] == 'true';
_access = results[14] == 'true';
_panic = results[15] == 'true';
_person = results[16] == 'true';
_requestOSnotification = results[17] == 'true';
});
for (var key in keys) {
log('Fetching value for key: $key');
final result = await txn.query(
DatabaseConfig.tableKeychain,
where: '${DatabaseConfig.columnKey} = ?',
whereArgs: [key],
);
log('Result for key $key: $result');
}
});
log('Local variables setup complete');
} catch (error) {
log('Error setting up local variables: $error');
}
}
Future<bool> getBoolean(String key) async {
log('Getting boolean value for key: $key');
final value = await get(key);
return value == 'true';
}
Future<dynamic> get(String key) async {
final cachedValue = CacheUtil.get(key);
log('Getting value for key: $key');
final cachedValue = CacheUtil().get(key);
if (cachedValue != null) {
log('Found cached value for key: $key');
return cachedValue;
}
try {
final db = await database;
final db = await ensureInitialization();
final result = await db.query(
DatabaseConfig.tableKeychain,
columns: [DatabaseConfig.columnValue],
@ -263,9 +422,11 @@ class SQLiteStorageHelper {
if (result.isNotEmpty) {
final value = result.first[DatabaseConfig.columnValue];
CacheUtil.set(key, value);
CacheUtil().set(key, value);
log('Value for key $key: $value');
return value;
}
log('No value found for key: $key');
return null;
} catch (error) {
log('Error getting value for key $key: $error');
@ -274,8 +435,9 @@ class SQLiteStorageHelper {
}
Future<int> set(String key, dynamic value) async {
CacheUtil.set(key, value);
final db = await database;
log('Setting value for key: $key to $value');
CacheUtil().set(key, value);
final db = await ensureInitialization();
final data = {
DatabaseConfig.columnKey: key,
DatabaseConfig.columnValue: value.toString(),
@ -283,34 +445,53 @@ class SQLiteStorageHelper {
DatabaseConfig.columnCreatedAt: DateTime.now().toIso8601String(),
};
return await db.insert(
final result = await db.insert(
DatabaseConfig.tableKeychain,
data,
conflictAlgorithm: ConflictAlgorithm.replace,
);
log('Value set for key: $key');
return result;
}
Future<int> delete(String key) async {
final db = await database;
return await db.transaction((txn) async {
log('Deleting value for key: $key');
final db = await ensureInitialization();
final result = await db.transaction((txn) async {
return await txn.delete(
DatabaseConfig.tableKeychain,
where: '${DatabaseConfig.columnKey} = ?',
whereArgs: [key],
);
});
log('Value deleted for key: $key');
return result;
}
Future<void> purge() async {
log('Purging database');
await deleteDatabaseDB();
await database;
await ensureInitialization();
log('Database purged');
}
Future<void> deleteDatabaseDB() async {
log('Deleting database');
final path = await _getDatabasePath();
await deleteDatabase(path);
log('Database deleted');
_database = null;
}
}

View File

@ -1,19 +1,34 @@
class CacheUtil {
static final CacheUtil _instance = CacheUtil._internal();
static final Map<String, dynamic> _cache = {};
static void set(String key, dynamic value) {
CacheUtil._internal();
factory CacheUtil() => _instance;
static CacheUtil get instance => _instance;
void set(String key, dynamic value) {
_cache[key] = value;
}
static dynamic get(String key) {
dynamic get(String key) {
return _cache[key];
}
static void delete(String key) {
bool containsKey(String key) {
return _cache.containsKey(key);
}
dynamic getOrElse(String key, dynamic fallback) {
return _cache.containsKey(key) ? _cache[key] : fallback;
}
void delete(String key) {
_cache.remove(key);
}
static void clear() {
void clear() {
_cache.clear();
}
}
}

View File

@ -1,3 +1,5 @@
import 'dart:developer';
import 'package:hub/shared/helpers/secure_storage_helper.dart';
import 'package:hub/shared/helpers/shared_preferences_storage_helper.dart';
import 'package:hub/shared/helpers/sqlite_storage_helper.dart';
@ -21,65 +23,80 @@ enum StorageType { SecureStorage, SharedPreferences, SQLite3 }
class StorageManager {
static final SecureStorageHelper _secureStorage = SecureStorageHelper();
static final SharedPreferencesStorageHelper _sharedPreferences =
SharedPreferencesStorageHelper();
static final SharedPreferencesStorageHelper _sharedPreferences = SharedPreferencesStorageHelper();
static final SQLiteStorageHelper _sqliteStorage = SQLiteStorageHelper();
static Future<void> set(StorageData data) async {
switch (data.type) {
case StorageType.SecureStorage:
CacheUtil.set(data.key, data.value);
await _secureStorage.set(data.key, data.value);
break;
case StorageType.SharedPreferences:
await _sharedPreferences.set(data.key, data.value);
break;
case StorageType.SQLite3:
await _sqliteStorage.set(data.key, data.value);
break;
try {
switch (data.type) {
case StorageType.SecureStorage:
await _secureStorage.set(data.key, data.value);
break;
case StorageType.SharedPreferences:
await _sharedPreferences.set(data.key, data.value);
break;
case StorageType.SQLite3:
await _sqliteStorage.set(data.key, data.value);
break;
}
} catch (e) {
log('Error setting data: $e');
}
}
static Future<dynamic> get(StorageData data) async {
var value = CacheUtil.get(data.key);
if (value == null) {
switch (data.type) {
case StorageType.SecureStorage:
value = await _secureStorage.get(data.key);
break;
case StorageType.SharedPreferences:
value = await _sharedPreferences.get(data.key);
break;
case StorageType.SQLite3:
value = await _sqliteStorage.get(data.key);
break;
try {
var value = CacheUtil().get(data.key);
if (value == null) {
switch (data.type) {
case StorageType.SecureStorage:
value = await _secureStorage.get(data.key);
break;
case StorageType.SharedPreferences:
value = await _sharedPreferences.get(data.key);
break;
case StorageType.SQLite3:
value = await _sqliteStorage.get(data.key);
break;
}
CacheUtil().set(data.key, value);
}
CacheUtil.set(data.key, value);
return value;
} catch (e) {
log('Error getting data: $e');
return null;
}
return value;
}
static Future<void> delete(StorageData data) async {
switch (data.type) {
case StorageType.SecureStorage:
CacheUtil.delete(data.key);
await _secureStorage.delete(data.key);
break;
case StorageType.SharedPreferences:
await _sharedPreferences.delete(data.key);
break;
case StorageType.SQLite3:
await _sqliteStorage.delete(data.key);
break;
try {
switch (data.type) {
case StorageType.SecureStorage:
CacheUtil().delete(data.key);
await _secureStorage.delete(data.key);
break;
case StorageType.SharedPreferences:
await _sharedPreferences.delete(data.key);
break;
case StorageType.SQLite3:
await _sqliteStorage.delete(data.key);
break;
}
} catch (e) {
log('Error deleting data: $e');
}
}
static Future<void> purge() async {
// CacheUtil.purge();
await _secureStorage.purge();
await _sharedPreferences.purge();
await _sqliteStorage.purge();
try {
await _secureStorage.purge();
await _sharedPreferences.purge();
await _sqliteStorage.purge();
} catch (e) {
log('Error purging data: $e');
}
}
}
class StorageUtil {}
class StorageUtil {}