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 2 : static NotificationController get instance => _instance ??= NotificationController();
19 :
20 0 : @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 1 : NotificationController({this.channel = const NotificationChannel()});
33 :
34 0 : bool get isAttached => _state != null;
35 :
36 1 : void attach(AppData state) {
37 1 : if (!NotificationChannel.isSupported) {
38 : return;
39 : }
40 1 : final isFirst = _state == null;
41 1 : _state = state;
42 : if (isFirst) {
43 2 : WidgetsBinding.instance.addObserver(this);
44 2 : NotificationChannel.channel.setMethodCallHandler(_handle);
45 1 : syncAutoPackages();
46 1 : run();
47 : }
48 : }
49 :
50 0 : Future<void> attachBackground(AppData state) async {
51 0 : _isBackground = true;
52 0 : _state = state;
53 : var added = 0;
54 : var generation = 0;
55 0 : onImported = (value) => added += value;
56 0 : Future<void> drain() async {
57 0 : final current = ++generation;
58 0 : await run();
59 0 : if (current == generation) {
60 0 : await channel.done(added);
61 : }
62 : }
63 :
64 0 : NotificationChannel.channel.setMethodCallHandler((call) async {
65 0 : if (call.method == 'onCaptured') {
66 0 : await drain();
67 : }
68 : });
69 0 : await drain();
70 : }
71 :
72 0 : void detach() {
73 0 : if (_state == null) {
74 : return;
75 : }
76 0 : WidgetsBinding.instance.removeObserver(this);
77 0 : NotificationChannel.channel.setMethodCallHandler(null);
78 0 : _state = null;
79 : }
80 :
81 0 : Future<void> _handle(MethodCall call) async {
82 0 : switch (call.method) {
83 0 : case 'onCaptured':
84 0 : 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 1 : Future<void> syncAutoPackages() async {
97 : try {
98 4 : final apps = NotificationSettings.load().apps.entries.where((e) => e.value.isLinked);
99 3 : 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 0 : @override
108 : void didChangeAppLifecycleState(AppLifecycleState state) {
109 0 : if (state == AppLifecycleState.resumed) {
110 0 : run();
111 : }
112 : }
113 :
114 1 : Future<void> run() {
115 1 : if (_running != null) {
116 0 : _isRepeated = true;
117 0 : return _running!;
118 : }
119 5 : return _running = _run().whenComplete(() => _running = null);
120 : }
121 :
122 1 : Future<void> _run() async {
123 : do {
124 1 : _isRepeated = false;
125 1 : final state = _state;
126 1 : final settings = NotificationSettings.load();
127 4 : final apps = settings.apps.entries.where((e) => e.value.isLinked).toList();
128 1 : if (state == null || apps.isEmpty) {
129 : return;
130 : }
131 : try {
132 0 : if (!_isBackground && await channel.isBusy()) {
133 : return;
134 : }
135 0 : if (!await channel.isGranted()) {
136 : return;
137 : }
138 0 : final records = await channel.getNotifications();
139 : var added = 0;
140 0 : for (final app in apps) {
141 0 : final summary = await importApp(
142 : state,
143 0 : channel,
144 0 : package: app.key,
145 0 : link: app.value,
146 : records: records,
147 0 : from: DateTime.fromMillisecondsSinceEpoch(0),
148 0 : income: settings.income,
149 0 : balance: settings.balance,
150 0 : merchant: settings.merchant,
151 0 : accounts: settings.accounts,
152 : );
153 0 : added += summary.added;
154 : }
155 0 : if (added > 0) {
156 0 : revision.value++;
157 0 : onImported?.call(added);
158 : }
159 0 : } on PlatformException {
160 : return;
161 0 : } on MissingPluginException {
162 : return;
163 : }
164 0 : } while (_isRepeated);
165 : }
166 :
167 0 : 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 0 : final account = state.getByUuid(link.account!);
180 0 : final importer = NotificationImporter(
181 0 : exists: (uuid) => state.getByUuid(uuid) != null,
182 0 : add: (value, uuid) => TransactionLog.save(state.add(value, uuid)),
183 : );
184 0 : final summary = importer.run(
185 0 : records: records.where((e) => e.package == package).toList(),
186 0 : account: link.account!,
187 0 : category: link.category!,
188 : from: from,
189 0 : currency: account is AccountAppData ? account.currency : null,
190 0 : 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 0 : prediction: state.prediction,
197 : );
198 0 : if (summary.added > 0) {
199 0 : await state.restate();
200 : }
201 0 : if (summary.processed.isNotEmpty) {
202 0 : await channel.removeNotifications(summary.processed);
203 : }
204 : return summary;
205 : }
206 : }
|