/
xmpp.dart
1854 lines (1662 loc) · 60.2 KB
/
xmpp.dart
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:async';
import 'dart:io';
import 'dart:ui';
import 'package:collection/collection.dart';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:get_it/get_it.dart';
import 'package:logging/logging.dart';
import 'package:mime/mime.dart';
import 'package:moxlib/moxlib.dart';
import 'package:moxxmpp/moxxmpp.dart';
import 'package:moxxy_native/moxxy_native.dart';
import 'package:moxxyv2/i18n/strings.g.dart';
import 'package:moxxyv2/service/avatars.dart';
import 'package:moxxyv2/service/blocking.dart';
import 'package:moxxyv2/service/connectivity.dart';
import 'package:moxxyv2/service/connectivity_watcher.dart';
import 'package:moxxyv2/service/contacts.dart';
import 'package:moxxyv2/service/conversation.dart';
import 'package:moxxyv2/service/files.dart';
import 'package:moxxyv2/service/groupchat.dart';
import 'package:moxxyv2/service/helpers.dart';
import 'package:moxxyv2/service/httpfiletransfer/helpers.dart';
import 'package:moxxyv2/service/httpfiletransfer/httpfiletransfer.dart';
import 'package:moxxyv2/service/httpfiletransfer/jobs.dart';
import 'package:moxxyv2/service/httpfiletransfer/location.dart';
import 'package:moxxyv2/service/lifecycle.dart';
import 'package:moxxyv2/service/message.dart';
import 'package:moxxyv2/service/not_specified.dart';
import 'package:moxxyv2/service/notifications.dart';
import 'package:moxxyv2/service/omemo/omemo.dart';
import 'package:moxxyv2/service/preferences.dart';
import 'package:moxxyv2/service/reactions.dart';
import 'package:moxxyv2/service/roster.dart';
import 'package:moxxyv2/service/service.dart';
import 'package:moxxyv2/service/share.dart';
import 'package:moxxyv2/service/xmpp_state.dart';
import 'package:moxxyv2/shared/error_types.dart';
import 'package:moxxyv2/shared/eventhandler.dart';
import 'package:moxxyv2/shared/events.dart';
import 'package:moxxyv2/shared/helpers.dart';
import 'package:moxxyv2/shared/models/conversation.dart';
import 'package:moxxyv2/shared/models/file_metadata.dart';
import 'package:moxxyv2/shared/models/message.dart';
import 'package:moxxyv2/shared/models/sticker.dart' as sticker;
import 'package:omemo_dart/omemo_dart.dart';
import 'package:path/path.dart' as pathlib;
import 'package:permission_handler/permission_handler.dart';
class XmppService {
XmppService() {
_eventHandler.addMatchers([
EventTypeMatcher<ConnectionStateChangedEvent>(_onConnectionStateChanged),
EventTypeMatcher<StreamNegotiationsDoneEvent>(_onStreamNegotiationsDone),
EventTypeMatcher<ResourceBoundEvent>(_onResourceBound),
EventTypeMatcher<SubscriptionRequestReceivedEvent>(
_onSubscriptionRequestReceived,
),
EventTypeMatcher<DeliveryReceiptReceivedEvent>(
_onDeliveryReceiptReceived,
),
EventTypeMatcher<ChatMarkerEvent>(_onChatMarker),
EventTypeMatcher<UserAvatarUpdatedEvent>(_onAvatarUpdated),
EventTypeMatcher<StanzaAckedEvent>(_onStanzaAcked),
EventTypeMatcher<MessageEvent>(_onMessage),
EventTypeMatcher<BlocklistBlockPushEvent>(_onBlocklistBlockPush),
EventTypeMatcher<BlocklistUnblockPushEvent>(_onBlocklistUnblockPush),
EventTypeMatcher<BlocklistUnblockAllPushEvent>(
_onBlocklistUnblockAllPush,
),
EventTypeMatcher<StanzaSendingCancelledEvent>(_onStanzaSendingCancelled),
EventTypeMatcher<NonRecoverableErrorEvent>(_onUnrecoverableError),
EventTypeMatcher<NewFASTTokenReceivedEvent>(_onNewFastToken),
EventTypeMatcher<MemberJoinedEvent>(_handleMucJoin),
EventTypeMatcher<MemberLeftEvent>(_handleMucLeave),
EventTypeMatcher<MemberChangedNickEvent>(_handleMucNickChange),
]);
}
/// Logger.
final Logger _log = Logger('XmppService');
/// EventHandler for XmppEvents
final EventHandler _eventHandler = EventHandler();
/// Flag indicating whether a login was triggered from the UI or not.
bool _loginTriggeredFromUI = false;
/// Subscription to events by the XmppConnection
StreamSubscription<dynamic>? _xmppConnectionSubscription;
Future<ConnectionSettings?> getConnectionSettings() async {
final xss = GetIt.I.get<XmppStateService>();
final accountJid = await xss.getAccountJid();
if (accountJid == null) return null;
final state = await GetIt.I.get<XmppStateService>().state;
if (state.jid == null || state.password == null) {
return null;
}
return ConnectionSettings(
jid: JID.fromString(state.jid!),
password: state.password!,
);
}
/// Marks the conversation with jid [jid] as open and resets its unread counter if it is
/// greater than 0.
Future<void> setCurrentlyOpenedChatJid(String jid) async {
final accountJid = await GetIt.I.get<XmppStateService>().getAccountJid();
final cs = GetIt.I.get<ConversationService>()..activeConversationJid = jid;
_log.finest('Set active conversation to "$jid"');
final conversation = await cs.createOrUpdateConversation(
jid,
accountJid!,
update: (c) async {
if (c.unreadCounter > 0) {
return cs.updateConversation(
jid,
accountJid,
unreadCounter: 0,
);
}
return c;
},
);
if (conversation != null) {
sendEvent(
ConversationUpdatedEvent(conversation: conversation),
);
}
}
/// Sends a message correction to [recipient] regarding the message with stanza id
/// [oldId]. The old message's body gets corrected to [newBody]. [id] is the message's
/// id. [chatState] can be optionally specified to also include a chat state
/// in the message.
///
/// This function handles updating the message and optionally the corresponding
/// conversation.
Future<void> sendMessageCorrection(
String id,
String conversationJid,
String accountJid,
String newBody,
String oldId,
String recipient,
ChatState? chatState,
) async {
final ms = GetIt.I.get<MessageService>();
final cs = GetIt.I.get<ConversationService>();
final conn = GetIt.I.get<XmppConnection>();
final timestamp = DateTime.now().millisecondsSinceEpoch;
// Update the database
final msg = await ms.updateMessage(
id,
accountJid,
isEdited: true,
body: newBody,
);
sendEvent(MessageUpdatedEvent(message: msg));
final conversation = await cs.createOrUpdateConversation(
recipient,
accountJid,
update: (c) async {
if (c.lastMessage?.id == id) {
return cs.updateConversation(
c.jid,
accountJid,
lastChangeTimestamp: timestamp,
lastMessage: msg,
);
}
return c;
},
);
if (conversation != null) {
sendEvent(ConversationUpdatedEvent(conversation: conversation));
}
if (conversation?.type != ConversationType.note) {
// Send the correction
final manager = conn.getManagerById<MessageManager>(messageManager)!;
await manager.sendMessage(
JID.fromString(recipient),
TypedMap<StanzaHandlerExtension>.fromList([
MessageBodyData(newBody),
LastMessageCorrectionData(oldId),
if (chatState != null) chatState,
]),
);
}
await GetIt.I.get<ShareService>().recordSentMessage(
conversation!,
);
}
/// Sends a message to JIDs in [recipients] with the body of [body].
Future<void> sendMessage({
required String accountJid,
required String body,
required List<String> recipients,
String? currentConversationJid,
Message? quotedMessage,
String? commandId,
ChatState? chatState,
sticker.Sticker? sticker,
}) async {
final ms = GetIt.I.get<MessageService>();
final cs = GetIt.I.get<ConversationService>();
final conn = GetIt.I.get<XmppConnection>();
final timestamp = DateTime.now().millisecondsSinceEpoch;
for (final recipient in recipients) {
final sid = conn.generateId();
final originId = conn.generateId();
Message? message;
final conversation = await cs.createOrUpdateConversation(
recipient,
accountJid,
update: (c) async {
message = await ms.addMessageFromData(
accountJid,
body,
timestamp,
conn.connectionSettings.jid.toString(),
recipient,
sid,
false,
c.type == ConversationType.note ? true : c.encrypted,
// TODO(Unknown): Maybe make this depend on some setting
false,
originId: originId,
quoteId: quotedMessage?.sid,
stickerPackId: sticker?.stickerPackId,
fileMetadata: sticker?.fileMetadata,
received: c.type == ConversationType.note ? true : false,
displayed: c.type == ConversationType.note ? true : false,
);
final newConversation = await cs.updateConversation(
recipient,
accountJid,
lastMessage: message,
lastChangeTimestamp: timestamp,
);
return newConversation;
},
);
assert(conversation != null, 'The conversation must exist');
assert(message != null, 'The message must be non-null');
// Using the same ID should be fine.
if (recipient == currentConversationJid) {
sendEvent(
MessageAddedEvent(message: message!),
id: commandId,
);
}
if (conversation?.type != ConversationType.note) {
final moxxmppSticker = sticker?.toMoxxmpp();
final manager = conn.getManagerById<MessageManager>(messageManager)!;
await manager.sendMessage(
JID.fromString(recipient),
TypedMap<StanzaHandlerExtension>.fromList([
MessageBodyData(body),
const MarkableData(true),
MessageIdData(sid),
StableIdData(originId, null),
if (sticker != null && moxxmppSticker != null)
StickersData(
sticker.stickerPackId,
StatelessFileSharingData(
moxxmppSticker.metadata,
moxxmppSticker.sources,
),
),
// Optional chat state
if (chatState != null) chatState,
// Prepare the appropriate quote
if (quotedMessage != null)
ReplyData.fromQuoteData(
quotedMessage.sid,
QuoteData.fromBodies(
createFallbackBodyForQuotedMessage(quotedMessage),
body,
),
),
]),
type: conversation!.type.value,
);
}
sendEvent(
ConversationUpdatedEvent(conversation: conversation!),
);
// Tell the system to show the chat in the direct share list.
await GetIt.I.get<ShareService>().recordSentMessage(
conversation,
);
}
}
MediaFileLocation? _getEmbeddedFile(MessageEvent event) {
final sfs = event.extensions.get<StatelessFileSharingData>();
final oob = event.extensions.get<OOBData>();
if (sfs?.sources.isNotEmpty ?? false) {
// final source = firstWhereOrNull(
// event.sfs!.sources,
// (StatelessFileSharingSource source) {
// return source is StatelessFileSharingUrlSource ||
// source is StatelessFileSharingEncryptedSource;
// },
// );
final hasUrlSource = sfs!.sources.firstWhereOrNull(
(src) => src is StatelessFileSharingUrlSource,
) !=
null;
final name = sfs.metadata.name;
if (hasUrlSource) {
final sources = sfs.sources
.whereType<StatelessFileSharingUrlSource>()
.map((src) => src.url)
.toList();
return MediaFileLocation(
sources,
name != null ? escapeFilename(name) : filenameFromUrl(sources.first),
null,
null,
null,
sfs.metadata.hashes,
null,
sfs.metadata.size,
);
} else {
final encryptedSource = sfs.sources.firstWhereOrNull(
(src) => src is StatelessFileSharingEncryptedSource,
)! as StatelessFileSharingEncryptedSource;
return MediaFileLocation(
[encryptedSource.source.url],
name != null
? escapeFilename(name)
: filenameFromUrl(encryptedSource.source.url),
encryptedSource.encryption.toNamespace(),
encryptedSource.key,
encryptedSource.iv,
sfs.metadata.hashes,
encryptedSource.hashes,
sfs.metadata.size,
);
}
} else if (oob != null) {
return MediaFileLocation(
[oob.url!],
filenameFromUrl(oob.url!),
null,
null,
null,
null,
null,
null,
);
}
return null;
}
Future<void> _acknowledgeMessage(MessageEvent event) async {
final result = await GetIt.I
.get<XmppConnection>()
.getDiscoManager()!
.discoInfoQuery(event.from);
if (result.isType<DiscoError>()) return;
final info = result.get<DiscoInfo>();
final isMarkable =
event.extensions.get<MarkableData>()?.isMarkable ?? false;
final deliveryReceiptRequested =
event.extensions.get<MessageDeliveryReceiptData>()?.receiptRequested ??
false;
final originId = event.extensions.get<StableIdData>()?.originId;
final manager = GetIt.I
.get<XmppConnection>()
.getManagerById<MessageManager>(messageManager)!;
final hasId = originId != null || event.id != null;
if (isMarkable && info.features.contains(chatMarkersXmlns) && hasId) {
await manager.sendMessage(
event.from.toBare(),
TypedMap<StanzaHandlerExtension>.fromList([
ChatMarkerData(
ChatMarker.received,
originId ?? event.id!,
),
]),
);
} else if (deliveryReceiptRequested &&
info.features.contains(deliveryXmlns) &&
hasId) {
await manager.sendMessage(
event.from.toBare(),
TypedMap<StanzaHandlerExtension>.fromList([
MessageDeliveryReceivedData(originId ?? event.id!),
]),
);
}
}
/// Send a read marker to [to] in order to mark the message with stanza id [sid]
/// as read. If sending chat markers is disabled in the preferences, then this
/// function will do nothing.
Future<void> sendReadMarker(String to, String sid) async {
final prefs = await GetIt.I.get<PreferencesService>().getPreferences();
if (!prefs.sendChatMarkers) return;
final manager = GetIt.I
.get<XmppConnection>()
.getManagerById<MessageManager>(messageManager)!;
await manager.sendMessage(
JID.fromString(to),
TypedMap<StanzaHandlerExtension>.fromList([
ChatMarkerData(ChatMarker.displayed, sid),
]),
);
}
/// Returns true if we are allowed to automatically download a file
Future<bool> _automaticFileDownloadAllowed() async {
final prefs = await GetIt.I.get<PreferencesService>().getPreferences();
final currentConnection = GetIt.I.get<ConnectivityService>().currentState;
return prefs.autoDownloadWifi &&
currentConnection == ConnectivityResult.wifi ||
prefs.autoDownloadMobile &&
currentConnection == ConnectivityResult.mobile;
}
void installEventHandlers() {
_xmppConnectionSubscription?.cancel();
_xmppConnectionSubscription = GetIt.I
.get<XmppConnection>()
.asBroadcastStream()
.listen(_eventHandler.run);
}
Future<void> connect(
ConnectionSettings settings,
bool triggeredFromUI,
) async {
final xss = GetIt.I.get<XmppStateService>();
final state = await xss.state;
final conn = GetIt.I.get<XmppConnection>();
final lastResource = state.resource ?? '';
_loginTriggeredFromUI = triggeredFromUI;
conn
..connectionSettings = settings
..getNegotiatorById<StreamManagementNegotiator>(
streamManagementNegotiator,
)!
.resource = lastResource
..getNegotiatorById<Sasl2Negotiator>(sasl2Negotiator)!.userAgent =
await xss.userAgent
..getNegotiatorById<FASTSaslNegotiator>(saslFASTNegotiator)!.fastToken =
state.fastToken;
await conn.connect(
waitForConnection: true,
shouldReconnect: true,
);
installEventHandlers();
}
Future<Result<bool, XmppError>> connectAwaitable(
ConnectionSettings settings,
bool triggeredFromUI,
) async {
final xss = GetIt.I.get<XmppStateService>();
final conn = GetIt.I.get<XmppConnection>();
final state = await xss.state;
final lastResource = state.resource ?? '';
_loginTriggeredFromUI = triggeredFromUI;
conn
..connectionSettings = settings
..getNegotiatorById<StreamManagementNegotiator>(
streamManagementNegotiator,
)!
.resource = lastResource
..getNegotiatorById<Sasl2Negotiator>(sasl2Negotiator)!.userAgent =
await xss.userAgent
..getNegotiatorById<FASTSaslNegotiator>(saslFASTNegotiator)!.fastToken =
state.fastToken;
installEventHandlers();
return conn.connect(
waitForConnection: true,
waitUntilLogin: true,
);
}
Future<void> sendFiles(
String accountJid,
List<String> paths,
List<String> recipients,
) async {
// Create a new message
final ms = GetIt.I.get<MessageService>();
final cs = GetIt.I.get<ConversationService>();
final css = GetIt.I.get<ContactsService>();
final prefs = await GetIt.I.get<PreferencesService>().getPreferences();
// Path -> Recipient -> Message
final messages = <String, Map<String, Message>>{};
// Path -> Thumbnails
final thumbnails = <String, List<JingleContentThumbnail>>{};
// Path -> Dimensions
final dimensions = <String, Size>{};
// Recipient -> Should encrypt
final encrypt = <String, bool>{};
// Recipient -> Last message Id
final lastMessages = <String, Message>{};
// Path -> Metadata Id
final metadataMap = <String, String>{};
// Recipient -> Conversation
final conversationsMap = <String, Conversation>{};
// Create the messages and shared media entries
final conn = GetIt.I.get<XmppConnection>();
for (final path in paths) {
final pathMime = lookupMimeType(path);
// TODO(Unknown): Do the same for videos
if (pathMime != null && pathMime.startsWith('image/')) {
final imageSize = await getImageSizeFromPath(path);
if (imageSize != null) {
dimensions[path] = Size(
imageSize.width,
imageSize.height,
);
} else {
_log.warning('Failed to get image dimensions for $path');
}
}
final metadata =
await GetIt.I.get<FilesService>().addFileMetadataFromData(
FileMetadata(
DateTime.now().millisecondsSinceEpoch.toString(),
path,
null,
pathMime,
File(path).lengthSync(),
null,
null,
dimensions[path]?.width.toInt(),
dimensions[path]?.height.toInt(),
null,
null,
null,
null,
null,
pathlib.basename(path),
),
);
metadataMap[path] = metadata.id;
for (final recipient in recipients) {
final conversation =
await cs.getConversationByJid(recipient, accountJid);
encrypt[recipient] =
conversation?.encrypted ?? prefs.enableOmemoByDefault;
final msg = await ms.addMessageFromData(
accountJid,
'',
DateTime.now().millisecondsSinceEpoch,
conn.connectionSettings.jid.toString(),
recipient,
conn.generateId(),
false,
conversation?.type == ConversationType.note
? true
: encrypt[recipient]!,
// TODO(Unknown): Maybe make this depend on some setting
false,
fileMetadata: metadata,
originId: conn.generateId(),
isUploading:
conversation?.type != ConversationType.note ? true : false,
received: conversation?.type == ConversationType.note ? true : false,
displayed: conversation?.type == ConversationType.note ? true : false,
);
if (messages.containsKey(path)) {
messages[path]![recipient] = msg;
} else {
messages[path] = {recipient: msg};
}
if (path == paths.last) {
lastMessages[recipient] = msg;
}
sendEvent(MessageAddedEvent(message: msg));
}
}
final rs = GetIt.I.get<RosterService>();
final gs = GetIt.I.get<GroupchatService>();
for (final recipient in recipients) {
conversationsMap[recipient] = (await cs.createOrUpdateConversation(
recipient,
accountJid,
create: () async {
// Create
final rosterItem = await rs.getRosterItemByJid(recipient, accountJid);
final contactId = await css.getContactIdForJid(recipient);
final groupchatDetails = await gs.getGroupchatDetailsByJid(
recipient,
accountJid,
);
final newConversation = await cs.addConversationFromData(
accountJid,
// TODO(Unknown): Should we use the JID parser?
rosterItem?.title ?? recipient.split('@').first,
lastMessages[recipient],
ConversationType.chat,
rosterItem?.avatarPath,
recipient,
0,
DateTime.now().millisecondsSinceEpoch,
true,
prefs.defaultMuteState,
prefs.enableOmemoByDefault,
contactId,
await css.getProfilePicturePathForJid(recipient),
await css.getContactDisplayName(contactId),
groupchatDetails,
);
// Update the cache
cs.setConversation(newConversation);
// Notify the UI
sendEvent(ConversationAddedEvent(conversation: newConversation));
return newConversation;
},
update: (c) async {
// Update
final newConversation = await cs.updateConversation(
c.jid,
accountJid,
lastMessage: lastMessages[recipient],
lastChangeTimestamp: DateTime.now().millisecondsSinceEpoch,
open: true,
);
// Update the cache
cs.setConversation(newConversation);
// Notify the UI
sendEvent(ConversationUpdatedEvent(conversation: newConversation));
return newConversation;
},
))!;
}
// Requesting Upload slots and uploading
final hfts = GetIt.I.get<HttpFileTransferService>();
final manager = conn.getManagerById<MessageManager>(messageManager)!;
for (final path in paths) {
final pathMime = lookupMimeType(path);
for (final recipient in recipients) {
// TODO(PapaTutuWawa): Do this for videos
// TODO(PapaTutuWawa): Maybe do this in a separate isolate
if ((pathMime ?? '').startsWith('image/')) {
// Generate a thumbnail only when we have to
if (!thumbnails.containsKey(path)) {
final thumbnail = await generateBlurhashThumbnail(path);
if (thumbnail != null) {
thumbnails[path] = [
JingleContentThumbnail(
// Just like Cheogram does it
// https://git.singpolyma.net/cheogram/commit/7adfc96853fec0648145c9d52a4a91b7bac1189f
Uri.parse('data:image/blurhash,$thumbnail'),
null,
null,
null,
),
];
} else {
_log.warning('Failed to generate thumbnail for $path');
}
}
}
if (recipient != '') {
await manager.sendMessage(
JID.fromString(recipient),
TypedMap<StanzaHandlerExtension>.fromList([
MessageIdData(messages[path]![recipient]!.sid),
FileUploadNotificationData(
FileMetadataData(
// TODO(Unknown): Maybe add media type specific metadata
mediaType: lookupMimeType(path),
name: pathlib.basename(path),
size: File(path).statSync().size,
thumbnails: thumbnails[path] ?? [],
),
),
]),
);
}
// Notify the system to update the direct shares.
await GetIt.I.get<ShareService>().recordSentMessage(
conversationsMap[recipient]!,
);
}
recipients.remove('');
if (recipients.isNotEmpty) {
await hfts.uploadFile(
FileUploadJob(
accountJid,
recipients,
path,
pathMime,
encrypt,
messages[path]!,
metadataMap[path]!,
thumbnails[path] ?? [],
),
);
_log.finest('File upload submitted');
}
}
}
Future<void> _initializeOmemoService(String jid) async {
await GetIt.I.get<OmemoService>().initializeIfNeeded(jid);
final result = await GetIt.I.get<OmemoService>().publishDeviceIfNeeded();
if (result != null) {
_log.warning('Failed to publish OMEMO device because of $result');
// Notify the user that we could not publish the Omemo ~identity~ titty
await GetIt.I.get<NotificationsService>().showWarningNotification(
t.notifications.titles.error,
t.errors.omemo.couldNotPublish,
);
}
}
/// Sets the permanent notification's title to the corresponding one for the
/// XmppConnection's state [state].
void setNotificationText(XmppConnectionState state) {
switch (state) {
case XmppConnectionState.connected:
GetIt.I.get<BackgroundService>().setNotificationBody(
t.notifications.permanent.ready,
);
case XmppConnectionState.connecting:
GetIt.I.get<BackgroundService>().setNotificationBody(
t.notifications.permanent.connecting,
);
case XmppConnectionState.notConnected:
GetIt.I.get<BackgroundService>().setNotificationBody(
t.notifications.permanent.disconnect,
);
case XmppConnectionState.error:
GetIt.I.get<BackgroundService>().setNotificationBody(
t.notifications.permanent.error,
);
}
}
Future<void> _onStreamNegotiationsDone(
StreamNegotiationsDoneEvent event, {
dynamic extra,
}) async {
final connection = GetIt.I.get<XmppConnection>();
// TODO(Unknown): Maybe have something better
final settings = connection.connectionSettings;
await GetIt.I.get<XmppStateService>().modifyXmppState(
(state) => state.copyWith(
jid: settings.jid.toString(),
password: settings.password,
),
);
_log.finest('Connection connected. Is resumed? ${event.resumed}');
unawaited(_initializeOmemoService(settings.jid.toString()));
if (!event.resumed) {
// Reset the avatar service's cache
GetIt.I.get<AvatarService>().resetCache();
// Reset the blocking service's cache
GetIt.I.get<BlocklistService>().onNewConnection();
// Reset the OMEMO cache
unawaited(
GetIt.I.get<OmemoService>().onNewConnection(),
);
// Enable carbons, if they're not already enabled (e.g. by using SASL2)
final cm = connection.getManagerById<CarbonsManager>(carbonsManager)!;
if (!cm.isEnabled) {
final carbonsResult = await cm.enableCarbons();
if (!carbonsResult) {
_log.warning('Failed to enable carbons');
}
} else {
_log.info('Not enabling carbons as they are already enabled');
}
// In section 5 of XEP-0198 it says that a client should not request the roster
// in case of a stream resumption.
await connection
.getManagerById<RosterManager>(rosterManager)!
.requestRoster();
await GetIt.I.get<BlocklistService>().getBlocklist(
(await GetIt.I.get<XmppStateService>().getAccountJid())!,
);
}
if (_loginTriggeredFromUI) {
// TODO(Unknown): Trigger another event so the UI can see this aswell
await GetIt.I.get<XmppStateService>().modifyXmppState(
(state) => state.copyWith(
jid: connection.connectionSettings.jid.toString(),
displayName: connection.connectionSettings.jid.local,
avatarUrl: null,
avatarHash: null,
),
);
}
sendEvent(
StreamNegotiationsCompletedEvent(resumed: event.resumed),
);
}
Future<void> _onConnectionStateChanged(
ConnectionStateChangedEvent event, {
dynamic extra,
}) async {
setNotificationText(event.state);
await GetIt.I.get<ConnectivityWatcherService>().onConnectionStateChanged(
event.before,
event.state,
);
}
Future<void> _onResourceBound(
ResourceBoundEvent event, {
dynamic extra,
}) async {
await GetIt.I.get<XmppStateService>().modifyXmppState(
(state) => state.copyWith(
resource: event.resource,
),
);
}
Future<void> _onSubscriptionRequestReceived(
SubscriptionRequestReceivedEvent event, {
dynamic extra,
}) async {
final jid = event.from.toBare();
// Auto-accept if the JID is in the roster
final rs = GetIt.I.get<RosterService>();
final rosterItem = await rs.getRosterItemByJid(
jid.toString(),
(await GetIt.I.get<XmppStateService>().getAccountJid())!,
);
if (rosterItem != null) {
final pm = GetIt.I
.get<XmppConnection>()
.getManagerById<PresenceManager>(presenceManager)!;
switch (rosterItem.subscription) {
case 'from':
await pm.acceptSubscriptionRequest(jid);
}
return;
}
}
Future<void> _onDeliveryReceiptReceived(
DeliveryReceiptReceivedEvent event, {
dynamic extra,
}) async {
_log.finest('Received delivery receipt from ${event.from}');
final ms = GetIt.I.get<MessageService>();
final cs = GetIt.I.get<ConversationService>();
final sender = event.from.toBare().toString();
final accountJid = await GetIt.I.get<XmppStateService>().getAccountJid();
final dbMsg = await ms.getMessageByStanzaId(
event.id,
accountJid!,
queryReactionPreview: false,
);
if (dbMsg == null) {
_log.warning(
'Did not find the message with id ${event.id} in the database!',
);
return;
}
final msg = await ms.updateMessage(
dbMsg.id,
accountJid,
received: true,
);
sendEvent(MessageUpdatedEvent(message: msg));
// Update the conversation
final conv = await cs.getConversationByJid(sender, accountJid);
if (conv != null && conv.lastMessage?.id == msg.id) {
final newConv = conv.copyWith(lastMessage: msg);
cs.setConversation(newConv);
_log.finest('Updating conversation');
sendEvent(ConversationUpdatedEvent(conversation: newConv));
}
}
Future<void> _onChatMarker(ChatMarkerEvent event, {dynamic extra}) async {
_log.finest('Chat marker from ${event.from}');
final ms = GetIt.I.get<MessageService>();
final cs = GetIt.I.get<ConversationService>();
final sender = event.from.toBare().toString();
final accountJid = await GetIt.I.get<XmppStateService>().getAccountJid();
// TODO(Unknown): With groupchats, we should use the groupchat assigned stanza-id
final dbMsg = await ms.getMessageByStanzaId(event.id, accountJid!);
if (dbMsg == null) {
_log.warning('Did not find the message in the database!');
return;
}
final msg = await ms.updateMessage(
dbMsg.id,
accountJid,
received: dbMsg.received ||
event.type == ChatMarker.received ||
event.type == ChatMarker.displayed ||
event.type == ChatMarker.acknowledged,
displayed: dbMsg.displayed ||
event.type == ChatMarker.displayed ||
event.type == ChatMarker.acknowledged,
);
sendEvent(MessageUpdatedEvent(message: msg));
// Update the conversation
final conv = await cs.getConversationByJid(sender, accountJid);
if (conv != null && conv.lastMessage?.id == msg.id) {
final newConv = conv.copyWith(lastMessage: msg);
cs.setConversation(newConv);
_log.finest('Updating conversation');
sendEvent(ConversationUpdatedEvent(conversation: newConv));
}
}
Future<void> _onChatState(ChatState state, String jid) async {
final cs = GetIt.I.get<ConversationService>();
final conversation = await cs.getConversationByJid(
jid,
(await GetIt.I.get<XmppStateService>().getAccountJid())!,
);
if (conversation == null) return;
final newConversation = conversation.copyWith(chatState: state);