Line data Source code
1 : // Copyright 2026 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 'package:app_finance/_classes/integration/notification/notification_channel.dart';
5 : import 'package:app_finance/_classes/integration/notification/notification_importer.dart';
6 : import 'package:app_finance/_classes/integration/notification/notification_parser.dart';
7 : import 'package:app_finance/_classes/integration/notification/notification_settings.dart';
8 : import 'package:app_finance/_classes/storage/app_data.dart';
9 : import 'package:app_finance/_classes/storage/transaction_log.dart';
10 : import 'package:app_finance/_classes/structure/account_app_data.dart';
11 : import 'package:flutter/services.dart';
12 : import 'package:flutter_currency_picker/flutter_currency_picker.dart';
13 : import 'package:flutter/widgets.dart';
14 :
15 : class NotificationController with WidgetsBindingObserver {
16 : static NotificationController? _instance;
17 :
18 12 : static NotificationController get instance => _instance ??= NotificationController();
19 :
20 1 : @visibleForTesting
21 : static set instance(NotificationController? value) => _instance = value;
22 :
23 : final NotificationChannel channel;
24 : // Changed after each automatic import, to refresh the views
25 : final revision = ValueNotifier<int>(0);
26 : void Function(int added)? onImported;
27 : AppData? _state;
28 : bool _isBackground = false;
29 : Future<void>? _running;
30 : bool _isRepeated = false;
31 :
32 6 : NotificationController({this.channel = const NotificationChannel()});
33 :
34 0 : bool get isAttached => _state != null;
35 :
36 6 : void attach(AppData state) {
37 6 : if (!NotificationChannel.isSupported) {
38 : return;
39 : }
40 6 : final isFirst = _state == null;
41 6 : _state = state;
42 : if (isFirst) {
43 12 : WidgetsBinding.instance.addObserver(this);
44 12 : NotificationChannel.channel.setMethodCallHandler(_handle);
45 6 : syncAutoPackages();
46 6 : run();
47 : }
48 : }
49 :
50 1 : Future<void> attachBackground(AppData state) async {
51 1 : _isBackground = true;
52 1 : _state = state;
53 : var added = 0;
54 : var generation = 0;
55 3 : onImported = (value) => added += value;
56 1 : Future<void> drain() async {
57 1 : final current = ++generation;
58 1 : await run();
59 1 : if (current == generation) {
60 2 : await channel.done(added);
61 : }
62 : }
63 :
64 2 : NotificationChannel.channel.setMethodCallHandler((call) async {
65 2 : if (call.method == 'onCaptured') {
66 1 : await drain();
67 : }
68 : });
69 1 : await drain();
70 : }
71 :
72 1 : void detach() {
73 1 : if (_state == null) {
74 : return;
75 : }
76 2 : WidgetsBinding.instance.removeObserver(this);
77 1 : NotificationChannel.channel.setMethodCallHandler(null);
78 1 : _state = null;
79 : }
80 :
81 1 : Future<void> _handle(MethodCall call) async {
82 1 : switch (call.method) {
83 1 : case 'onCaptured':
84 1 : await run();
85 0 : case 'onReload':
86 0 : final added = (call.arguments as Map?)?['added'] as int? ?? 0;
87 0 : if (added > 0) {
88 0 : await _state?.flush();
89 0 : revision.value++;
90 0 : onImported?.call(added);
91 : }
92 0 : await run();
93 : }
94 : }
95 :
96 6 : Future<void> syncAutoPackages() async {
97 : try {
98 27 : final apps = NotificationSettings.load().apps.entries.where((e) => e.value.isLinked);
99 20 : await channel.setAutoPackages(apps.map((e) => e.key));
100 0 : } on PlatformException {
101 : // Not critical: the background import would be skipped
102 0 : } on MissingPluginException {
103 : // Not supported
104 : }
105 : }
106 :
107 1 : @override
108 : void didChangeAppLifecycleState(AppLifecycleState state) {
109 1 : if (state == AppLifecycleState.resumed) {
110 1 : run();
111 : }
112 : }
113 :
114 6 : Future<void> run() {
115 6 : if (_running != null) {
116 1 : _isRepeated = true;
117 1 : return _running!;
118 : }
119 30 : return _running = _run().whenComplete(() => _running = null);
120 : }
121 :
122 6 : Future<void> _run() async {
123 : do {
124 6 : _isRepeated = false;
125 6 : final state = _state;
126 6 : final settings = NotificationSettings.load();
127 27 : final apps = settings.apps.entries.where((e) => e.value.isLinked).toList();
128 6 : if (state == null || apps.isEmpty) {
129 : return;
130 : }
131 : try {
132 3 : if (!_isBackground && await channel.isBusy()) {
133 : return;
134 : }
135 2 : if (!await channel.isGranted()) {
136 : return;
137 : }
138 2 : final records = await channel.getNotifications();
139 : var added = 0;
140 2 : for (final app in apps) {
141 1 : final summary = await importApp(
142 : state,
143 1 : channel,
144 1 : package: app.key,
145 1 : link: app.value,
146 : records: records,
147 1 : from: DateTime.fromMillisecondsSinceEpoch(0),
148 1 : income: settings.income,
149 1 : balance: settings.balance,
150 1 : merchant: settings.merchant,
151 1 : accounts: settings.accounts,
152 : );
153 1 : added += summary.added;
154 : }
155 1 : if (added > 0) {
156 3 : revision.value++;
157 2 : onImported?.call(added);
158 : }
159 0 : } on PlatformException {
160 : return;
161 0 : } on MissingPluginException {
162 : return;
163 : }
164 1 : } while (_isRepeated);
165 : }
166 :
167 1 : static Future<NotificationImportResult> importApp(
168 : AppData state,
169 : NotificationChannel channel, {
170 : required String package,
171 : required NotificationApp link,
172 : required List<NotificationRecord> records,
173 : required DateTime from,
174 : List<String> income = NotificationParser.incomeKeywords,
175 : List<String> balance = NotificationParser.balanceKeywords,
176 : List<String> merchant = NotificationParser.merchantLabels,
177 : Map<String, List<String>> accounts = const {},
178 : }) async {
179 2 : final account = state.getByUuid(link.account!);
180 1 : final importer = NotificationImporter(
181 2 : exists: (uuid) => state.getByUuid(uuid) != null,
182 3 : add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
183 : );
184 1 : final summary = importer.run(
185 5 : records: records.where((e) => e.package == package).toList(),
186 1 : account: link.account!,
187 1 : category: link.category!,
188 : from: from,
189 2 : currency: account is AccountAppData ? account.currency : null,
190 1 : appCurrency: link.currency != null ? CurrencyProvider.find(link.currency!) : null,
191 : income: income,
192 : balance: balance,
193 : merchant: merchant,
194 : accounts: accounts,
195 0 : currencyOf: (uuid) => switch (state.getByUuid(uuid)) { AccountAppData item => item.currency, _ => null },
196 1 : prediction: state.prediction,
197 : );
198 1 : if (summary.added > 0) {
199 1 : await state.restate();
200 : }
201 1 : if (summary.processed.isNotEmpty) {
202 1 : await channel.removeNotifications(summary.processed);
203 : }
204 : return summary;
205 : }
206 : }
|