FlippyPass/project/backend/store.c
2024-08-30 09:06:47 -04:00

115 lines
No EOL
2.9 KiB
C

// Header
#include "store.h"
#include <flipper_format.h>
// Functions - Private
void store_folder_init() {
// Opening storage record
Storage* storage = furi_record_open(RECORD_STORAGE);
// DEBUG
FURI_LOG_I(TAG, "Creating FlipperPass Folder");
// Creating folder
if (storage_simply_mkdir(storage, DIR)) {
FURI_LOG_I(TAG, "Created FPass Directory");
} else {
FURI_LOG_I(TAG, "FPass Directory already exists");
}
// Cleanup
furi_record_close(RECORD_STORAGE);
}
// Functions
char* store_load(char* type) {
// Init Folders
store_folder_init();
// Allocating memory for storage struct
char* result = malloc(sizeof(char));
// Reading storage
Storage* _storage = furi_record_open(RECORD_STORAGE);
FlipperFormat* _format = flipper_format_file_alloc(_storage);
FuriString* _data = furi_string_alloc();
// Memory issue?
if (!_format || !_data) {
FURI_LOG_E(TAG, "Storage Memory Allication Issue");
return NULL;
}
// Opening file
if (!flipper_format_file_open_existing(_format, PATH)) {
FURI_LOG_E(TAG, "Sorry, please register.");
// Cleaning up
furi_string_free(_data);
flipper_format_free(_format);
furi_record_close(RECORD_STORAGE);
return NULL;
}
// Reading data from file
if (!flipper_format_read_string(_format, type, _data)) {
FURI_LOG_E(TAG, "Couldn't read data");
return NULL;
}
// Copy data into result
const char* _cstr_data = furi_string_get_cstr(_data);
result = malloc(strlen(_cstr_data) + 1);
strcpy(result, _cstr_data);
// Free the original string
furi_string_free(_data);
// Cleanup
flipper_format_free(_format);
furi_record_close(RECORD_STORAGE);
// Returning result
return result;
}
void store_save(char* type, char* data) {
// Creating new file
Storage* _storage = furi_record_open(RECORD_STORAGE);
FlipperFormat* _format = flipper_format_file_alloc(_storage);
FuriString* _data = furi_string_alloc();
// Memory issue?
if (!_storage || !_format || !_data) {
FURI_LOG_E(TAG, "Memory Allocation Issue!");
return;
}
// Setting furi string data
furi_string_set_str(_data, data);
// Opening new file
if (!flipper_format_file_open_always(_format, PATH)) {
// DEBUG
FURI_LOG_E(TAG, "Failed to create/open file at %s", PATH);
// Cleanup
furi_string_free(_data);
flipper_format_free(_format);
furi_record_close(RECORD_STORAGE);
return;
}
// Writing string
if (!flipper_format_write_string(_format, type, _data)) {
FURI_LOG_E(TAG, "Failed to write to file at %s", PATH);
return;
} else {
FURI_LOG_I(TAG, "Successfully wrote to file at %s", PATH);
}
// Closing file
furi_string_free(_data);
flipper_format_free(_format);
furi_record_close(RECORD_STORAGE);
}