-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathpush_utils.dart
More file actions
336 lines (296 loc) · 13 KB
/
push_utils.dart
File metadata and controls
336 lines (296 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import 'dart:async';
import 'dart:convert';
import 'dart:ui';
import 'package:account_repository/account_repository.dart';
import 'package:built_collection/built_collection.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:flutter_svg/flutter_svg.dart' show SvgBytesLoader, vg;
import 'package:http/http.dart' as http;
import 'package:image/image.dart' as img;
import 'package:logging/logging.dart';
import 'package:neon_framework/l10n/localizations.dart';
import 'package:neon_framework/src/bloc/result.dart';
import 'package:neon_framework/src/storage/keys.dart';
import 'package:neon_framework/src/storage/sqlite_persistence.dart';
import 'package:neon_framework/src/theme/colors.dart';
import 'package:neon_framework/src/utils/account_client_extension.dart';
import 'package:neon_framework/src/utils/image_utils.dart';
import 'package:neon_framework/src/utils/localizations.dart';
import 'package:neon_framework/src/utils/request_manager.dart';
import 'package:neon_framework/src/utils/user_agent.dart';
import 'package:neon_framework/storage.dart';
import 'package:nextcloud/notifications.dart' as notifications;
import 'package:notifications_push_repository/notifications_push_repository.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:rxdart/rxdart.dart';
import 'package:timezone/timezone.dart' as tz;
/// Signature of the callback which called when a new push notification is received.
typedef OnPushNotificationReceivedCallback = Future<void> Function(String accountID);
/// Signature of the callback which called when the user clicks on a local notification.
typedef OnLocalNotificationClickedCallback = Future<void> Function(PushNotification notification);
final _log = Logger('PushUtils');
@internal
@immutable
class PushUtils {
const PushUtils._(); // coverage:ignore-line
/// Called when a new push notification was received.
///
/// The callback will only be set if the current flutter engine was opened in the foreground.
static OnPushNotificationReceivedCallback? onPushNotificationReceived;
/// Called when a local notification was clicked on by the user.
///
/// The callback will only be set if the current flutter engine was opened in the foreground.
static OnLocalNotificationClickedCallback? onLocalNotificationClicked;
static Future<FlutterLocalNotificationsPlugin> initLocalNotifications({
required NeonLocalizations localizations,
DidReceiveNotificationResponseCallback? onDidReceiveNotificationResponse,
}) async {
final localNotificationsPlugin = FlutterLocalNotificationsPlugin();
await localNotificationsPlugin.initialize(
InitializationSettings(
android: const AndroidInitializationSettings('@drawable/ic_launcher_outline'),
linux: LinuxInitializationSettings(
defaultActionName: localizations.actionOpen,
defaultIcon: AssetsLinuxIcon('assets/logo.svg'),
),
),
onDidReceiveNotificationResponse: onDidReceiveNotificationResponse,
);
return localNotificationsPlugin;
}
static Future<void> onMessage(
PushMessage encryptedPushNotifications,
String accountID, {
@visibleForTesting http.Client? httpClient,
}) async {
_log.fine('Received a push notification.');
await onPushNotificationReceived?.call(accountID);
WidgetsFlutterBinding.ensureInitialized();
final localizations = await appLocalizationsFromSystem();
final localNotificationsPlugin = await initLocalNotifications(
localizations: localizations,
onDidReceiveNotificationResponse: (notification) async {
if (onLocalNotificationClicked != null && notification.payload != null) {
await onLocalNotificationClicked!(
PushNotification.fromJson(
json.decode(notification.payload!) as Map<String, dynamic>,
),
);
}
},
);
await NeonStorage().init();
final storage = NotificationsPushStorage(
devicePrivateKeyPersistence: NeonStorage().singleValueStore(StorageKeys.notificationsDevicePrivateKey),
pushSubscriptionsPersistence: SQLiteCachedPersistence(
prefix: 'notifications-push-subscriptions',
),
);
// These are used in the loop, but not every push notification needs them, so we only initialize them when needed.
PackageInfo? packageInfo;
AccountStorage? accountStorage;
AccountRepository? accountRepository;
BuiltList<Account>? accounts;
Account? account;
final pushNotifications = await parseEncryptedPushNotifications(
storage,
encryptedPushNotifications.content,
accountID,
);
for (final pushNotification in pushNotifications) {
if (pushNotification.type == 'background') {
if (pushNotification.subject.delete ?? false) {
await localNotificationsPlugin.cancel(getNotificationID(accountID, pushNotification.subject.nid!));
} else if (pushNotification.subject.deleteMultiple ?? false) {
await Future.wait([
for (final nid in pushNotification.subject.nids!)
localNotificationsPlugin.cancel(getNotificationID(accountID, nid)),
]);
} else if (pushNotification.subject.deleteAll ?? false) {
await localNotificationsPlugin.cancelAll();
} else {
_log.fine('Got unknown background notification ${json.encode(pushNotification.toJson())}');
}
if (defaultTargetPlatform == TargetPlatform.android) {
final groups = <String, List<int>>{};
// Count how many notifications per group still exist.
final activeNotifications = await localNotificationsPlugin.getActiveNotifications();
for (final activeNotification in activeNotifications) {
final id = activeNotification.id;
final groupKey = activeNotification.groupKey;
if (id != null && groupKey != null) {
groups[groupKey] ??= [];
groups[groupKey]!.add(id);
}
}
for (final entry in groups.entries) {
// If there is only one notification left it has to be the summary,
// because the child notifications are automatically canceled when the user cancels the summary notification.
if (entry.value.length == 1) {
await localNotificationsPlugin.cancel(getGroupSummaryID(accountID, entry.key));
}
}
}
} else {
packageInfo ??= await PackageInfo.fromPlatform();
accountStorage ??= AccountStorage(
accountsPersistence: NeonStorage().singleValueStore(StorageKeys.accounts),
lastAccountPersistence: NeonStorage().singleValueStore(StorageKeys.lastUsedAccount),
);
if (accountRepository == null) {
accountRepository = AccountRepository(
userAgent: buildUserAgent(packageInfo),
httpClient: httpClient ?? http.Client(),
storage: accountStorage,
);
await accountRepository.loadAccounts();
}
accounts ??= (await accountRepository.accounts.first).accounts;
account ??= accountRepository.accountByID(accountID);
notifications.Notification? notification;
AndroidBitmap<Object>? largeIconBitmap;
if (account != null) {
notification = await _fetchNotification(account, pushNotification.subject.nid!);
final icon = notification?.icon;
// Only SVG icons are supported right now (should be most of them)
if (icon != null && icon.endsWith('.svg')) {
final uri = Uri.parse(icon);
final rawImage = await _fetchIcon(account, uri);
if (rawImage != null) {
largeIconBitmap = await _decodeAndroidBitmap(rawImage);
}
}
}
if (notification?.shouldNotify ?? true) {
final appID = notification?.app ?? pushNotification.subject.app ?? 'nextcloud';
String? appName = localizations.appImplementationName(appID);
if (appName.isEmpty) {
_log.warning('Missing app name for $appID');
appName = null;
}
final title = (notification?.subject ?? pushNotification.subject.subject)!;
final message = (notification?.message.isNotEmpty ?? false) ? notification!.message : null;
final when = notification != null ? tz.TZDateTime.parse(tz.UTC, notification.datetime) : null;
await localNotificationsPlugin.show(
getNotificationID(accountID, pushNotification.subject.nid!),
message != null && appName != null ? '$appName: $title' : title,
message,
NotificationDetails(
android: AndroidNotificationDetails(
appID,
appName ?? appID,
subText: accounts.length > 1 && account != null ? account.humanReadableID : null,
groupKey: appID,
largeIcon: largeIconBitmap,
when: when?.millisecondsSinceEpoch,
color: NcColors.primary,
category: pushNotification.type == 'voip' ? AndroidNotificationCategory.call : null,
importance: Importance.max,
priority: pushNotification.priority == 'high'
? (pushNotification.type == 'voip' ? Priority.max : Priority.high)
: Priority.defaultPriority,
styleInformation: message != null ? BigTextStyleInformation(message) : null,
),
),
payload: json.encode(pushNotification.toJson()),
);
// Other platforms don't support grouping, so don't send another notification there.
if (defaultTargetPlatform == TargetPlatform.android) {
// Since we only support Android SDK 24+, we can just generate an empty summary notification as it will not be shown anyway.
await localNotificationsPlugin.show(
getGroupSummaryID(accountID, appID),
null,
null,
NotificationDetails(
android: AndroidNotificationDetails(
appID,
appName ?? appID,
groupKey: appID,
setAsGroupSummary: true,
styleInformation: InboxStyleInformation(
[],
summaryText: appName ?? appID,
),
color: NcColors.primary,
),
),
);
}
}
}
}
}
static Future<notifications.Notification?> _fetchNotification(Account account, int id) async {
try {
final response = await account.client.notifications.endpoint.getNotification(
id: id,
);
return response.body.ocs.data;
} on http.ClientException catch (error, stackTrace) {
_log.warning(
'Error loading notification $id.',
error,
stackTrace,
);
return null;
}
}
static Future<Uint8List?> _fetchIcon(Account account, Uri uri) async {
final subject = BehaviorSubject<Result<Uint8List>>();
final headers = account.getAuthorizationHeaders(uri);
await RequestManager.instance.wrap(
account: account,
getCacheHeaders: () async {
final response = await account.client.head(
uri,
headers: headers,
);
return response.headers;
},
getRequest: () {
final request = http.Request('GET', uri);
if (headers != null) {
request.headers.addAll(headers);
}
return request;
},
converter: const BinaryResponseConverter(),
unwrap: (data) {
try {
return utf8.encode(ImageUtils.rewriteSvgDimensions(utf8.decode(data)));
} catch (_) {}
return data;
},
subject: subject,
);
final rawImage = subject.valueOrNull?.data;
unawaited(subject.close());
return rawImage;
}
static Future<ByteArrayAndroidBitmap?> _decodeAndroidBitmap(Uint8List rawImage) async {
final pictureInfo = await vg.loadPicture(SvgBytesLoader(rawImage), null);
const largeIconSize = 256;
final scale = largeIconSize / pictureInfo.size.longestSide;
final scaledSize = pictureInfo.size * scale;
final recorder = PictureRecorder();
Canvas(recorder)
..scale(scale)
..drawPicture(pictureInfo.picture)
..drawColor(NcColors.primary, BlendMode.srcIn);
pictureInfo.picture.dispose();
final image = recorder.endRecording().toImageSync(scaledSize.width.toInt(), scaledSize.height.toInt());
final bytes = await image.toByteData(format: ImageByteFormat.png);
return ByteArrayAndroidBitmap(img.encodeBmp(img.decodePng(bytes!.buffer.asUint8List())!));
}
@visibleForTesting
static int getNotificationID(String accountID, int nid) {
return sha256.convert(utf8.encode('$accountID$nid')).bytes.reduce((a, b) => a + b);
}
@visibleForTesting
static int getGroupSummaryID(String accountID, String app) {
return sha256.convert(utf8.encode('$accountID$app')).bytes.reduce((a, b) => a + b);
}
}