Line data Source code
1 : // Copyright 2023 The terCAD team. All rights reserved.
2 : // Use of this source code is governed by a CC BY-NC-ND 4.0 license that can be found in the LICENSE file.
3 :
4 : import 'dart:convert';
5 : import 'dart:async';
6 : import 'package:app_finance/_classes/controller/encryption_handler.dart';
7 : import 'package:app_finance/_classes/storage/app_data.dart';
8 : import 'package:app_finance/_classes/storage/transaction_log/abstract_storage_web.dart'
9 : if (dart.library.io) 'package:app_finance/_classes/storage/transaction_log/abstract_storage.dart';
10 : import 'package:app_finance/_classes/storage/transaction_log/interface_storage.dart';
11 : import 'package:app_finance/_ext/data_ext.dart';
12 :
13 : class TransactionLog extends AbstractStorage implements InterfaceStorage {
14 : static int amount = 0;
15 :
16 0 : static Future<String> getSize() => AbstractStorage.getSize();
17 :
18 0 : static void clear() => AbstractStorage.clear();
19 :
20 2 : static Stream<String> read() => AbstractStorage.read();
21 :
22 2 : static void saveRaw(String line) => AbstractStorage.saveRaw(line);
23 :
24 0 : static void rewrite(List<String> lines) {
25 0 : clear();
26 0 : for (final line in lines) {
27 0 : saveRaw(line);
28 : }
29 0 : amount = lines.length;
30 : }
31 :
32 1 : static void save(dynamic content) {
33 1 : String line = content.toString();
34 1 : if (EncryptionHandler.doEncrypt()) {
35 1 : line = EncryptionHandler.encrypt(line);
36 : }
37 1 : saveRaw(line);
38 1 : amount++;
39 : }
40 :
41 0 : static void init(AppData store, String type, Map<String, dynamic> data) {
42 0 : final obj = type.toDataObject(data, store);
43 : if (obj != null) {
44 0 : store.update(obj.uuid ?? '', obj, true);
45 : }
46 : }
47 :
48 1 : static Future<bool> load(AppData store) async {
49 1 : bool isEncrypted = EncryptionHandler.doEncrypt();
50 : bool isOK = true;
51 : amount = 0;
52 2 : await for (var line in read()) {
53 0 : isOK &= add(store, line, isEncrypted);
54 0 : amount++;
55 : }
56 : return isOK;
57 : }
58 :
59 0 : static bool add(AppData store, String line, bool isEncrypted, [bool onlyNew = false]) {
60 : bool isOK = true;
61 0 : if (line == '') {
62 : return isOK;
63 : }
64 : try {
65 : if (isEncrypted) {
66 0 : line = EncryptionHandler.decrypt(line);
67 : }
68 0 : var obj = json.decode(line);
69 : // FIXME: hash is not always the same for Web
70 : if ( // EncryptionHandler.getHash(obj['data']) == obj['type']['hash'] &&
71 0 : (!onlyNew || store.getByUuid(obj['data']['uuid']) == null)) {
72 0 : init(store, obj['type']['name'], obj['data']);
73 : } else {
74 : // Corrupted data... skip
75 : }
76 : // ignore: unused_catch_stack
77 : } catch (e, stackTrace) {
78 : // print([e, stackTrace]);
79 : isOK = false;
80 : }
81 : return isOK;
82 : }
83 : }
|