Skip to content

Commit

Permalink
Add - Puedes hacer backup de tu app data
Browse files Browse the repository at this point in the history
  • Loading branch information
GalletaOreo98 committed Sep 14, 2023
1 parent 0e8214b commit 8787893
Show file tree
Hide file tree
Showing 5 changed files with 169 additions and 18 deletions.
2 changes: 1 addition & 1 deletion lain_chikita/lib/functions/write_read_files_functions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ Future<void> writeAThankUTxt() async {
directory!.path;
Directory outputDir = await Directory("${directory.path}/${AppFolders.readme}").create();
final File file = File('${outputDir.path}/THANKS.txt');
await file.writeAsString("${languageDataManager.getLabel('thank-you-for-installing')} $username");
await file.writeAsString("${languageDataManager.getLabel('thank-you-for-installing')} $userName");
}

Future<void> createAppFolders() async {
Expand Down
4 changes: 2 additions & 2 deletions lain_chikita/lib/global_vars.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import 'classes/language_data_manager.dart';
//User vars
int level = 0;
int progress = 0;
String username = "NULLUSER";
String userName = "NULLUSER";
String accessoryName = "null";
String userUuid = "";
String userIv = "";
Expand Down Expand Up @@ -37,7 +37,7 @@ List<Map<String, dynamic>> unlockedInventory = [
];

//User vars (sin backup)
int coins = 2;
int coins = 0;

//Preferencias y Configuraciones en general
String language = 'en';
Expand Down
22 changes: 14 additions & 8 deletions lain_chikita/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,9 @@ class _MyAppState extends State<MyApp> {
setState(() {
level = prefs.getInt('level') ?? 0;
progress = prefs.getInt('progress') ?? 0;
username = prefs.getString('username') ?? "NULLUSER";
userName = prefs.getString('userName') ?? "NULLUSER";
accessoryName = prefs.getString('accessoryName') ?? "null";
coins = prefs.getInt('coins') ?? 2;
coins = prefs.getInt('coins') ?? 0;
});
}

Expand All @@ -125,7 +125,7 @@ class _MyAppState extends State<MyApp> {
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('level', level);
await prefs.setInt('progress', progress);
await prefs.setString('username', username);
await prefs.setString('userName', userName);
await prefs.setInt('coins', coins);
}

Expand Down Expand Up @@ -189,6 +189,12 @@ class _MyAppState extends State<MyApp> {
});
}

void _updateUI() {
setState(() {
print("UI");
});
}

void _handleKeyEvent(RawKeyEvent event) {
if (event.runtimeType == RawKeyDownEvent) {
if (event.isKeyPressed(LogicalKeyboardKey.arrowRight)) {
Expand Down Expand Up @@ -222,14 +228,14 @@ class _MyAppState extends State<MyApp> {
),
child: Stack(
children: [
if (username == "NULLUSER")
if (userName == "NULLUSER")
Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 16),
Form(
child: TextFormField(
initialValue: username,
initialValue: userName,
textAlign: TextAlign.center,
style: TextStyle(color: appColors.nameLabel, fontSize: 34.0),
decoration: InputDecoration(
Expand All @@ -238,7 +244,7 @@ class _MyAppState extends State<MyApp> {
floatingLabelAlignment: FloatingLabelAlignment.center,
),
onFieldSubmitted: (value) =>
setState(() => {username = value, _saveProgress(), writeAThankUTxt()}),
setState(() => {userName = value, _saveProgress(), writeAThankUTxt()}),
),
)
],
Expand All @@ -250,7 +256,7 @@ class _MyAppState extends State<MyApp> {
children: [
const SizedBox(height: 16),
Text(
username,
userName,
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 48.0,
Expand Down Expand Up @@ -320,7 +326,7 @@ class _MyAppState extends State<MyApp> {
),
InventoryScreen(callback: _updateAccessory),
GachaScreen(callback: _saveInventaries),
const EncryptionScreen()
EncryptionScreen(callback: _updateUI),
],
),
),
Expand Down
151 changes: 148 additions & 3 deletions lain_chikita/lib/screens/encryption_screen.dart
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
import 'package:flutter/material.dart';
import 'dart:convert' show json, jsonDecode;
import 'package:flutter/services.dart' show Clipboard, ClipboardData;
import 'package:shared_preferences/shared_preferences.dart';

// My imports
import '../global_vars.dart';
import '../functions/encryption_functions.dart';
import '../functions/encryption_functions.dart' show decryptFiles, encryptFiles, encryptData, decryptData;
import '../private_keys.dart';

const secretKey = SECRET_KEY;

class EncryptionScreen extends StatefulWidget {
const EncryptionScreen({super.key});
final Function callback;
const EncryptionScreen({super.key, required this.callback});

@override
MyWidgetState createState() => MyWidgetState();
Expand All @@ -18,6 +22,13 @@ class MyWidgetState extends State<EncryptionScreen> {
String _informativeText = '';
String _currentAction = '';
bool _isWorking = false;
bool _showBackupTextBox = false;
final TextEditingController _backupDataTEC = TextEditingController(text: '');

void _updateUI() {
// Llamada a la función de callback
widget.callback();
}

void progressCallback(int i, int total) {
setState(() {
Expand Down Expand Up @@ -56,6 +67,96 @@ class MyWidgetState extends State<EncryptionScreen> {
});
}

void _backupMyData() {
//Formateo de los inventarios a json
final jsonInventory = json.encode(inventory);
final jsonUnlockedInventory = json.encode(unlockedInventory);
//Formateo de la data necesaria a encriptar para hacer el backup
final jsonData = json.encode({
'userName': userName,
'userUuid': userUuid,
'level': level,
'progress': progress,
'userIv': userIv,
'userSecretKey': userSecretKey,
'accessoryName': accessoryName,
'inventoryVersion': inventoryVersion,
'inventory': jsonInventory,
'unlockedInventory': jsonUnlockedInventory,
});
final encryptedData = encryptData(jsonData, secretKey);
// Copiar la data ya encriptada al clipboard
Clipboard.setData(ClipboardData(text: encryptedData));
setState(() {
_informativeText = languageDataManager.getLabel('clipboard-is-copied');
hideInformativeText(2);
});
}

void _applyBackup(String backupData) async {
String decryptedData;
try {
decryptedData = decryptData(backupData, secretKey);
Map<String, dynamic> decryptedDataMap = Map<String, dynamic>.from(json.decode(decryptedData));
String userNameD = decryptedDataMap['userName'] ?? '';
String userUuidD = decryptedDataMap['userUuid'] ?? '';
int levelD = decryptedDataMap['level'] ?? 0;
int progressD = decryptedDataMap['progress'] ?? 0;
String userIvD = decryptedDataMap['userIv'] ?? '';
String userSecretKeyD = decryptedDataMap['userSecretKey'] ?? '';
String accessoryNameD = decryptedDataMap['accessoryName'] ?? '';
int inventoryVersionD = decryptedDataMap['inventoryVersion'] ?? 0;
List<Map<String, dynamic>> inventoryD =
List<Map<String, dynamic>>.from(jsonDecode(decryptedDataMap['inventory'] ?? '[{}]'));
List<Map<String, dynamic>> unlockedInventoryD =
List<Map<String, dynamic>>.from(jsonDecode(decryptedDataMap['unlockedInventory'] ?? '[{}]'));
//Save all progress
final prefs = await SharedPreferences.getInstance();
await prefs.setInt('coins', 0);
await prefs.setString('userName', userNameD);
await prefs.setString('userUuid', userUuidD);
await prefs.setInt('level', levelD);
await prefs.setInt('progress', progressD);
await prefs.setString('userIv', userIvD);
await prefs.setString('userSecretKey', userSecretKeyD);
await prefs.setString('accessoryName', accessoryNameD);
await prefs.setInt('inventoryVersion', inventoryVersionD);
//Inventarios
final jsonInventory = json.encode(inventoryD);
await prefs.setString('inventory', jsonInventory);
final jsonUnlockedInventory = json.encode(unlockedInventoryD);
await prefs.setString('unlockedInventory', jsonUnlockedInventory);
//Actualizar UI
setState(() {
coins = 0;
userName = userNameD;
userUuid = userUuidD;
level = levelD;
progress = progressD;
userIv = userIvD;
userSecretKey = userSecretKeyD;
accessoryName = accessoryNameD;
inventoryVersion = inventoryVersionD;
inventory = inventoryD;
unlockedInventory = unlockedInventoryD;
_informativeText = languageDataManager.getLabel('BACKUP EXITOSA');
_updateUI();
});
} catch (e) {
setState(() {
_informativeText = languageDataManager.getLabel('error-invalid-data');
});
}
}

void hideInformativeText(int seconds) {
Future.delayed(Duration(seconds: seconds), () {
setState(() {
_informativeText = '';
});
});
}

@override
Widget build(BuildContext context) {
return Container(
Expand All @@ -64,6 +165,50 @@ class MyWidgetState extends State<EncryptionScreen> {
padding: const EdgeInsets.all(16.0),
child: SingleChildScrollView(
child: Column(children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
minimumSize: const Size(190, 80),
backgroundColor: appColors.secondaryBtn,
padding: const EdgeInsets.all(20.0)),
onPressed: _backupMyData,
onLongPress: () => setState(() {
_showBackupTextBox = true;
}),
child: Text(languageDataManager.getLabel('BACKUP'),
style: const TextStyle(
fontSize: 34.0,
),
textAlign: TextAlign.center)),
const SizedBox(height: 16),
if (_showBackupTextBox)
Column(
children: [
//Textbox de "Pegar datos de ticket a reclamar"
TextField(
controller: _backupDataTEC,
textAlign: TextAlign.center,
style: TextStyle(color: appColors.userInputText, fontSize: 35.0),
decoration: InputDecoration(
suffixIcon: IconButton(
onPressed: () => {
_applyBackup(_backupDataTEC.text),
_backupDataTEC.clear(),
FocusManager.instance.primaryFocus?.unfocus()
},
icon: const Icon(Icons.done),
color: appColors.userInputText),
labelText: languageDataManager.getLabel('YOUR BACKUP DATA'),
labelStyle: TextStyle(color: appColors.primaryText, fontSize: 20),
floatingLabelAlignment: FloatingLabelAlignment.center,
focusedBorder: UnderlineInputBorder(borderSide: BorderSide(color: appColors.focusItem)),
enabledBorder:
UnderlineInputBorder(borderSide: BorderSide(color: appColors.userInputText))),
onSubmitted: (value) => setState(() => {_applyBackup(value)}),
onTapOutside: (event) => FocusManager.instance.primaryFocus?.unfocus(),
),
const SizedBox(height: 16),
],
),
ElevatedButton(
style: ElevatedButton.styleFrom(
minimumSize: const Size(340, 80),
Expand All @@ -84,7 +229,7 @@ class MyWidgetState extends State<EncryptionScreen> {
style: const TextStyle(fontSize: 34.0), textAlign: TextAlign.center),
),
const SizedBox(height: 16),
if(_isWorking) Image.asset('assets/images/working.gif'),
if (_isWorking) Image.asset('assets/images/working.gif'),
const SizedBox(height: 16),
Text(_informativeText,
textAlign: TextAlign.center,
Expand Down
8 changes: 4 additions & 4 deletions lain_chikita/lib/screens/gacha_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ class MyWidgetState extends State<GachaScreen> {
// Formateo de la data necesaria a encriptar
final jsonUnlockedInventory = json.encode(unlockedInventory);
final jsonData =
json.encode({'username': username, 'useruuid': userUuid, 'unlockedinventory': jsonUnlockedInventory});
json.encode({'userName': userName, 'userUuid': userUuid, 'unlockedInventory': jsonUnlockedInventory});
final encryptedData = encryptData(jsonData, secretKey);
// Copiar la data ya encriptada al clipboard
Clipboard.setData(ClipboardData(text: encryptedData));
Expand Down Expand Up @@ -165,9 +165,9 @@ class MyWidgetState extends State<GachaScreen> {
try {
decryptedData = decryptData(publicData, secretKey);
Map<String, String> decryptedDataMap = Map<String, String>.from(json.decode(decryptedData));
_userName = decryptedDataMap['username'] ?? '';
_uuid = decryptedDataMap['useruuid'] ?? '';
_unlockedInventory = List<Map<String, dynamic>>.from(jsonDecode(decryptedDataMap['unlockedinventory'] ?? '[{}]'));
_userName = decryptedDataMap['userName'] ?? '';
_uuid = decryptedDataMap['userUuid'] ?? '';
_unlockedInventory = List<Map<String, dynamic>>.from(jsonDecode(decryptedDataMap['unlockedInventory'] ?? '[{}]'));
_readyToBuyTicket();
} catch (e) {
setState(() {
Expand Down

0 comments on commit 8787893

Please sign in to comment.