-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathnotification_service.dart
More file actions
189 lines (171 loc) · 7 KB
/
notification_service.dart
File metadata and controls
189 lines (171 loc) · 7 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
import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:mixin_bot_sdk_dart/mixin_bot_sdk_dart.dart';
import 'package:stream_transform/stream_transform.dart';
import '../blaze/vo/pin_message_minimal.dart';
import '../db/database_event_bus.dart';
import '../enum/message_category.dart';
import '../generated/l10n.dart';
import '../ui/provider/conversation_provider.dart';
import '../ui/provider/mention_cache_provider.dart';
import '../ui/provider/slide_category_provider.dart';
import '../utils/app_lifecycle.dart';
import '../utils/extension/extension.dart';
import '../utils/load_balancer_utils.dart';
import '../utils/local_notification_center.dart';
import '../utils/logger.dart';
import '../utils/message_optimize.dart';
import '../utils/reg_exp_utils.dart';
import '../widgets/message/item/pin_message.dart';
import '../widgets/message/item/system_message.dart';
const _keyConversationId = 'conversationId';
class NotificationService {
NotificationService({
required BuildContext context,
}) {
streamSubscriptions
..add(DataBaseEventBus.instance.notificationMessageStream
.where((event) => event.type == MessageCategory.messageRecall)
.listen((event) {
try {
dismissByMessageId(event.messageId, event.conversationId);
} catch (e) {
w('dismiss notification error: $e');
}
}))
..add(DataBaseEventBus.instance.notificationMessageStream
.where((event) => event.type != MessageCategory.messageRecall)
.where((event) => event.senderId != context.accountServer.userId)
.where((event) =>
event.createdAt != null &&
event.createdAt!
.isAfter(DateTime.now().subtract(const Duration(minutes: 2))))
.where((event) {
if (isAppActive) {
final conversationState =
context.providerContainer.read(conversationProvider);
return event.conversationId !=
(conversationState?.conversationId ??
conversationState?.conversation?.conversationId);
}
return true;
})
.asyncMapBuffer((event) => context.database.messageDao
.notificationMessage(event.map((e) => e.messageId).toList())
.get())
.expand((event) => event)
.asyncWhere((event) async {
final account = context.account!;
bool mentionedCurrentUser() => mentionNumberRegExp
.allMatchesAndSort(event.content ?? '')
.any((element) => element[1] == account.identityNumber);
// mention current user
if (event.type.isText && mentionedCurrentUser()) return true;
Future<bool> quotedCurrentUser() async {
if (event.quoteContent?.isEmpty ?? true) return false;
try {
final json =
await jsonDecodeWithIsolate(event.quoteContent ?? '') ?? {};
// ignore: avoid_dynamic_calls
return json['user_id'] == account.userId;
} catch (_) {
// json decode failed
return false;
}
}
// quote current user
if (await quotedCurrentUser()) return true;
return event.muteUntil?.isAfter(DateTime.now()) != true;
})
.asyncMap((event) async {
String? body;
if (context.settingChangeNotifier.messagePreview) {
final mentionCache =
context.providerContainer.read(mentionCacheProvider);
if (event.type == MessageCategory.systemConversation) {
body = generateSystemText(
actionName: event.actionName,
participantUserId: event.participantUserId,
senderId: event.senderId,
currentUserId: context.accountServer.userId,
participantFullName: event.participantFullName,
senderFullName: event.senderFullName,
expireIn: int.tryParse(event.content ?? '0'),
);
} else if (event.type.isPin) {
final pinMessageMinimal =
PinMessageMinimal.fromJsonString(event.content ?? '');
if (pinMessageMinimal == null) {
body = Localization.current.chatPinMessage(
event.senderFullName ?? '',
Localization.current.aMessage);
} else {
final preview = await generatePinPreviewText(
pinMessageMinimal: pinMessageMinimal,
mentionCache: mentionCache,
);
body = Localization.current
.chatPinMessage(event.senderFullName ?? '', preview);
}
} else {
final isGroup = event.category == ConversationCategory.group ||
event.senderId != event.ownerUserId;
if (event.type.isText) {
body = mentionCache.replaceMention(
event.content,
await mentionCache.checkMentionCache({event.content}),
);
}
body = messagePreviewOptimize(
event.status,
event.type,
body ?? event.content,
false,
isGroup,
event.senderFullName,
);
}
body ??= Localization.current.messageNotSupport;
} else {
body = Localization.current.aMessage;
}
await showNotification(
title: event.name ?? '',
body: body,
uri: Uri(
scheme: enumConvertToString(NotificationScheme.conversation),
host: event.conversationId,
path: event.messageId,
queryParameters: {
// use queryParameters to avoid case transform.
_keyConversationId: event.conversationId,
},
),
messageId: event.messageId,
conversationId: event.conversationId,
);
})
.listen((_) {}))
..add(
notificationSelectEvent(NotificationScheme.conversation).listen(
(event) {
i('select notification $event');
context.providerContainer
.read(slideCategoryStateProvider.notifier)
.switchToChatsIfSettings();
final conversationId =
event.queryParameters[_keyConversationId] ?? event.host;
ConversationStateNotifier.selectConversation(
context,
conversationId,
initIndexMessageId: event.path,
);
},
),
);
}
List<StreamSubscription> streamSubscriptions = [];
Future<void> close() async {
await Future.wait(streamSubscriptions.map((e) => e.cancel()));
}
}