-
Notifications
You must be signed in to change notification settings - Fork 305
/
Copy pathexample_data.dart
989 lines (921 loc) · 31.9 KB
/
example_data.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
import 'dart:convert';
import 'dart:math';
import 'package:zulip/api/exception.dart';
import 'package:zulip/api/model/events.dart';
import 'package:zulip/api/model/initial_snapshot.dart';
import 'package:zulip/api/model/model.dart';
import 'package:zulip/api/model/submessage.dart';
import 'package:zulip/api/route/messages.dart';
import 'package:zulip/api/route/realm.dart';
import 'package:zulip/api/route/channels.dart';
import 'package:zulip/model/database.dart';
import 'package:zulip/model/narrow.dart';
import 'package:zulip/model/settings.dart';
import 'package:zulip/model/store.dart';
import 'model/test_store.dart';
import 'stdlib_checks.dart';
void _checkPositive(int? value, String description) {
assert(value == null || value > 0, '$description should be positive');
}
////////////////////////////////////////////////////////////////
// Error objects.
//
Object nullCheckError() {
try { null!; } catch (e) { return e; } // ignore: null_check_always_fails
}
/// A Zulip API error with the generic "BAD_REQUEST" error code.
///
/// The server returns this error code for a wide range of error conditions;
/// it's the default within the server code when no more-specific code is chosen.
ZulipApiException apiBadRequest({
String routeName = 'someRoute', String message = 'Something failed'}) {
return ZulipApiException(
routeName: routeName,
httpStatus: 400, code: 'BAD_REQUEST',
data: {}, message: message);
}
/// The error for the "events" route when the target event queue has been
/// garbage collected.
///
/// https://zulip.com/api/get-events#bad_event_queue_id-errors
ZulipApiException apiExceptionBadEventQueueId({
String queueId = 'fb67bf8a-c031-47cc-84cf-ed80accacda8',
}) {
return ZulipApiException(
routeName: 'events', httpStatus: 400, code: 'BAD_EVENT_QUEUE_ID',
data: {'queue_id': queueId}, message: 'Bad event queue ID: $queueId');
}
/// The error the server gives when the client's credentials
/// (API key together with email and realm URL) are no longer valid.
///
/// This isn't really documented, but comes from experiment and from
/// reading the server implementation. See:
/// https://github.com/zulip/zulip-flutter/pull/1183#discussion_r1945865983
/// https://chat.zulip.org/#narrow/channel/378-api-design/topic/general.20handling.20HTTP.20status.20code.20401/near/2090024
ZulipApiException apiExceptionUnauthorized({String routeName = 'someRoute'}) {
return ZulipApiException(
routeName: routeName,
httpStatus: 401, code: 'UNAUTHORIZED',
data: {}, message: 'Invalid API key');
}
////////////////////////////////////////////////////////////////
// Realm-wide (or server-wide) metadata.
//
final Uri realmUrl = Uri.parse('https://chat.example/');
Uri get _realmUrl => realmUrl;
const String recentZulipVersion = '9.0';
const int recentZulipFeatureLevel = 278;
const int futureZulipFeatureLevel = 9999;
GetServerSettingsResult serverSettings({
Map<String, bool>? authenticationMethods,
List<ExternalAuthenticationMethod>? externalAuthenticationMethods,
int? zulipFeatureLevel,
String? zulipVersion,
String? zulipMergeBase,
bool? pushNotificationsEnabled,
bool? isIncompatible,
bool? emailAuthEnabled,
bool? requireEmailFormatUsernames,
Uri? realmUrl,
String? realmName,
String? realmIcon,
String? realmDescription,
bool? realmWebPublicAccessEnabled,
}) {
return GetServerSettingsResult(
authenticationMethods: authenticationMethods ?? {},
externalAuthenticationMethods: externalAuthenticationMethods ?? [],
zulipFeatureLevel: zulipFeatureLevel ?? recentZulipFeatureLevel,
zulipVersion: zulipVersion ?? recentZulipVersion,
zulipMergeBase: zulipMergeBase ?? recentZulipVersion,
pushNotificationsEnabled: pushNotificationsEnabled ?? true,
isIncompatible: isIncompatible ?? false,
emailAuthEnabled: emailAuthEnabled ?? true,
requireEmailFormatUsernames: requireEmailFormatUsernames ?? true,
realmUrl: realmUrl ?? _realmUrl,
realmName: realmName ?? 'Example Zulip organization',
realmIcon: realmIcon ?? '$realmUrl/icon.png',
realmDescription: realmDescription ?? 'An example Zulip organization',
realmWebPublicAccessEnabled: realmWebPublicAccessEnabled ?? false,
);
}
RealmEmojiItem realmEmojiItem({
required String emojiCode,
required String emojiName,
String? sourceUrl,
String? stillUrl,
bool deactivated = false,
int? authorId,
}) {
assert(RegExp(r'^[1-9][0-9]*$').hasMatch(emojiCode));
return RealmEmojiItem(
emojiCode: emojiCode,
name: emojiName,
sourceUrl: sourceUrl ?? '/emoji/$emojiCode.png',
stillUrl: stillUrl,
deactivated: deactivated,
authorId: authorId ?? user().userId,
);
}
////////////////////////////////////////////////////////////////
// Users and accounts.
//
/// A fresh user ID, from a random but always strictly increasing sequence.
int _nextUserId() => (_lastUserId += 1 + Random().nextInt(100));
int _lastUserId = 1000;
/// A random email address, different from previously generated ones.
String _nextEmail() => 'mail${_lastEmailSuffix += 1 + Random().nextInt(1000)}@example.com';
int _lastEmailSuffix = 1000;
/// Construct an example user.
///
/// If user ID `userId` is not given, it will be generated from a random
/// but increasing sequence.
/// Use an explicit `userId` only if the ID needs to correspond to some
/// other data in the test, or if the IDs need to increase in a different order
/// from the calls to [user].
///
/// If `email` is not given, it defaults to `deliveryEmail` if given,
/// or else to a value resembling the Zulip server's generated fake emails.
User user({
int? userId,
String? deliveryEmail,
String? email,
String? fullName,
String? dateJoined,
bool? isActive,
bool? isBot,
UserRole? role,
String? avatarUrl,
Map<int, ProfileFieldUserData>? profileData,
}) {
_checkPositive(userId, 'user ID');
final effectiveUserId = userId ?? _nextUserId();
return User(
userId: effectiveUserId,
deliveryEmail: deliveryEmail,
email: email ?? deliveryEmail ?? 'user$effectiveUserId@${realmUrl.host}',
fullName: fullName ?? 'A user', // TODO generate example names
dateJoined: dateJoined ?? '2024-02-24T11:18+00:00',
isActive: isActive ?? true,
isBillingAdmin: false,
isBot: isBot ?? false,
botType: null,
botOwnerId: null,
role: role ?? UserRole.member,
timezone: 'UTC',
avatarUrl: avatarUrl,
avatarVersion: 0,
profileData: profileData,
isSystemBot: false,
);
}
Account account({
int? id,
Uri? realmUrl,
required User user,
String? apiKey,
int? zulipFeatureLevel,
String? zulipVersion,
String? zulipMergeBase,
String? ackedPushToken,
}) {
_checkPositive(id, 'account ID');
// When `user.deliveryEmail` is null, using `user.email`
// wouldn't be realistic: it's going to be a fake email address
// generated to serve as a "Zulip API email".
final email = user.deliveryEmail ?? _nextEmail();
return Account(
id: id ?? 1000, // TODO generate example IDs
realmUrl: realmUrl ?? _realmUrl,
email: email,
apiKey: apiKey ?? 'aeouasdf',
userId: user.userId,
zulipFeatureLevel: zulipFeatureLevel ?? recentZulipFeatureLevel,
zulipVersion: zulipVersion ?? recentZulipVersion,
zulipMergeBase: zulipMergeBase ?? recentZulipVersion,
ackedPushToken: ackedPushToken,
);
}
final User selfUser = user(fullName: 'Self User');
final Account selfAccount = account(
id: 1001,
user: selfUser,
apiKey: 'dQcEJWTq3LczosDkJnRTwf31zniGvMrO', // A Zulip API key is 32 digits of base64.
);
final User otherUser = user(fullName: 'Other User');
final Account otherAccount = account(
id: 1002,
user: otherUser,
apiKey: '6dxT4b73BYpCTU+i4BB9LAKC5h/CufqY', // A Zulip API key is 32 digits of base64.
);
final User thirdUser = user(fullName: 'Third User');
final User fourthUser = user(fullName: 'Fourth User');
////////////////////////////////////////////////////////////////
// Streams and subscriptions.
//
/// A fresh stream ID, from a random but always strictly increasing sequence.
int _nextStreamId() => (_lastStreamId += 1 + Random().nextInt(10));
int _lastStreamId = 200;
/// Construct an example stream.
///
/// If stream ID `streamId` is not given, it will be generated from a random
/// but increasing sequence.
/// Use an explicit `streamId` only if the ID needs to correspond to some
/// other data in the test, or if the IDs need to increase in a different order
/// from the calls to [stream].
ZulipStream stream({
int? streamId,
String? name,
String? description,
String? renderedDescription,
int? dateCreated,
int? firstMessageId,
bool? inviteOnly,
bool? isWebPublic,
bool? historyPublicToSubscribers,
int? messageRetentionDays,
ChannelPostPolicy? channelPostPolicy,
int? streamWeeklyTraffic,
}) {
_checkPositive(streamId, 'stream ID');
_checkPositive(firstMessageId, 'message ID');
var effectiveStreamId = streamId ?? _nextStreamId();
var effectiveName = name ?? 'stream $effectiveStreamId';
var effectiveDescription = description ?? 'Description of $effectiveName';
return ZulipStream(
streamId: effectiveStreamId,
name: effectiveName,
description: effectiveDescription,
renderedDescription: renderedDescription ?? '<p>$effectiveDescription</p>',
dateCreated: dateCreated ?? 1686774898,
firstMessageId: firstMessageId,
inviteOnly: inviteOnly ?? false,
isWebPublic: isWebPublic ?? false,
historyPublicToSubscribers: historyPublicToSubscribers ?? true,
messageRetentionDays: messageRetentionDays,
channelPostPolicy: channelPostPolicy ?? ChannelPostPolicy.any,
streamWeeklyTraffic: streamWeeklyTraffic,
);
}
const _stream = stream;
GetStreamTopicsEntry getStreamTopicsEntry({int? maxId, String? name}) {
maxId ??= 123;
return GetStreamTopicsEntry(maxId: maxId,
name: TopicName(name ?? 'Test Topic #$maxId'));
}
/// Construct an example subscription from a stream.
///
/// We only allow overrides of values specific to the [Subscription], all
/// other properties are copied from the [ZulipStream] provided.
Subscription subscription(
ZulipStream stream, {
bool? desktopNotifications,
bool? emailNotifications,
bool? wildcardMentionsNotify,
bool? pushNotifications,
bool? audibleNotifications,
bool? pinToTop,
bool? isMuted,
int? color,
}) {
return Subscription(
streamId: stream.streamId,
name: stream.name,
description: stream.description,
renderedDescription: stream.renderedDescription,
dateCreated: stream.dateCreated,
firstMessageId: stream.firstMessageId,
inviteOnly: stream.inviteOnly,
isWebPublic: stream.isWebPublic,
historyPublicToSubscribers: stream.historyPublicToSubscribers,
messageRetentionDays: stream.messageRetentionDays,
channelPostPolicy: stream.channelPostPolicy,
streamWeeklyTraffic: stream.streamWeeklyTraffic,
desktopNotifications: desktopNotifications ?? false,
emailNotifications: emailNotifications ?? false,
wildcardMentionsNotify: wildcardMentionsNotify ?? false,
pushNotifications: pushNotifications ?? false,
audibleNotifications: audibleNotifications ?? false,
pinToTop: pinToTop ?? false,
isMuted: isMuted ?? false,
color: color ?? 0xFFFF0000,
);
}
/// The [TopicName] constructor, but shorter.
///
/// Useful in test code that mentions a lot of topics in a compact format.
TopicName t(String apiName) => TopicName(apiName);
TopicNarrow topicNarrow(int channelId, String topicName, {int? with_}) {
return TopicNarrow(channelId, TopicName(topicName), with_: with_);
}
UserTopicItem userTopicItem(
ZulipStream stream, String topic, UserTopicVisibilityPolicy policy) {
return UserTopicItem(
streamId: stream.streamId,
topicName: TopicName(topic),
lastUpdated: 1234567890,
visibilityPolicy: policy,
);
}
////////////////////////////////////////////////////////////////
// Messages, and pieces of messages.
//
Reaction unicodeEmojiReaction = Reaction(
emojiName: 'thumbs_up',
emojiCode: '1f44d',
reactionType: ReactionType.unicodeEmoji,
userId: selfUser.userId,
);
Reaction realmEmojiReaction = Reaction(
emojiName: 'twocents',
emojiCode: '181',
reactionType: ReactionType.realmEmoji,
userId: selfUser.userId,
);
Reaction zulipExtraEmojiReaction = Reaction(
emojiName: 'zulip',
emojiCode: 'zulip',
reactionType: ReactionType.zulipExtraEmoji,
userId: selfUser.userId,
);
final _messagePropertiesBase = {
'is_me_message': false,
'recipient_id': 32, // obsolescent in API, and ignored
};
Map<String, dynamic> _messagePropertiesFromSender(User? sender) {
return {
'client': 'ExampleClient',
'sender_email': sender?.email ?? 'a-person@example',
'sender_full_name': sender?.fullName ?? 'A Person',
'sender_id': sender?.userId ?? 12345, // TODO generate example IDs
'sender_realm_str': 'zulip',
};
}
Map<String, dynamic> _messagePropertiesFromContent(String? content, String? contentMarkdown) {
if (contentMarkdown != null) {
assert(content == null);
return {
'content': contentMarkdown,
'content_type': 'text/x-markdown',
};
} else {
return {
'content': content ?? '<p>This is an example message.</p>',
'content_type': 'text/html',
};
}
}
/// A fresh message ID, from a random but always strictly increasing sequence.
int _nextMessageId() => (_lastMessageId += 1 + Random().nextInt(100));
int _lastMessageId = 1000;
const defaultStreamMessageStreamId = 123;
/// The default topic used by [streamMessage].
///
/// Tests generally shouldn't need this information directly.
/// Instead, either
/// * use [StreamMessage.topic] to read off an example message's topic;
/// * or pick an example topic, and pass it both to [streamMessage]
/// and wherever else the same topic is needed.
final _defaultTopic = 'example topic ${Random().nextInt(1000)}';
/// Construct an example stream message.
///
/// If the message ID `id` is not given, it will be generated from a random
/// but increasing sequence, which is shared with [dmMessage].
/// Use an explicit `id` only if the ID needs to correspond to some other data
/// in the test, or if the IDs need to increase in a different order from the
/// calls to [streamMessage] and [dmMessage].
///
/// The message will be in `stream` if given. Otherwise,
/// an example stream with ID `defaultStreamMessageStreamId` will be used.
///
/// If `topic` is not given, a default topic name is used.
/// The default is randomly chosen, but remains the same
/// for subsequent calls to this function.
///
/// See also:
/// * [dmMessage], to construct an example direct message.
StreamMessage streamMessage({
int? id,
User? sender,
ZulipStream? stream,
String? topic,
String? content,
String? contentMarkdown,
int? lastEditTimestamp,
List<Reaction>? reactions,
int? timestamp,
List<MessageFlag>? flags,
List<Submessage>? submessages,
}) {
_checkPositive(id, 'message ID');
final effectiveStream = stream ?? _stream(streamId: defaultStreamMessageStreamId);
// The use of JSON here is convenient in order to delegate parts of the data
// to helper functions. The main downside is that it loses static typing
// of the properties as we're constructing the data. That's probably OK
// because (a) this is only for tests; (b) the types do get checked
// dynamically in the constructor, so any ill-typing won't propagate further.
return StreamMessage.fromJson(deepToJson({
..._messagePropertiesBase,
..._messagePropertiesFromSender(sender),
..._messagePropertiesFromContent(content, contentMarkdown),
'display_recipient': effectiveStream.name,
'stream_id': effectiveStream.streamId,
'reactions': reactions == null ? <Reaction>[] : Reactions(reactions),
'flags': flags ?? [],
'id': id ?? _nextMessageId(),
'last_edit_timestamp': lastEditTimestamp,
'subject': topic ?? _defaultTopic,
'submessages': submessages ?? [],
'timestamp': timestamp ?? 1678139636,
'type': 'stream',
}) as Map<String, dynamic>);
}
/// Construct an example direct message.
///
/// If the message ID `id` is not given, it will be generated from a random
/// but increasing sequence, which is shared with [streamMessage].
/// Use an explicit `id` only if the ID needs to correspond to some other data
/// in the test, or if the IDs need to increase in a different order from the
/// calls to [streamMessage] and [dmMessage].
///
/// See also:
/// * [streamMessage], to construct an example stream message.
DmMessage dmMessage({
int? id,
required User from,
required List<User> to,
String? content,
String? contentMarkdown,
int? lastEditTimestamp,
int? timestamp,
List<MessageFlag>? flags,
List<Submessage>? submessages,
}) {
_checkPositive(id, 'message ID');
assert(!to.any((user) => user.userId == from.userId));
return DmMessage.fromJson(deepToJson({
..._messagePropertiesBase,
..._messagePropertiesFromSender(from),
..._messagePropertiesFromContent(content, contentMarkdown),
'display_recipient': [from, ...to]
.map((u) => {'id': u.userId, 'email': u.email, 'full_name': u.fullName})
.toList(growable: false),
'reactions': <Reaction>[],
'flags': flags ?? [],
'id': id ?? _nextMessageId(),
'last_edit_timestamp': lastEditTimestamp,
'subject': '',
'submessages': submessages ?? [],
'timestamp': timestamp ?? 1678139636,
'type': 'private',
}) as Map<String, dynamic>);
}
/// A GetMessagesResult the server might return on an `anchor=newest` request.
GetMessagesResult newestGetMessagesResult({
required bool foundOldest,
bool historyLimited = false,
required List<Message> messages,
}) {
return GetMessagesResult(
// These anchor, foundAnchor, and foundNewest values are what the server
// appears to always return when the request had `anchor=newest`.
anchor: 10000000000000000, // that's 16 zeros
foundAnchor: false,
foundNewest: true,
foundOldest: foundOldest,
historyLimited: historyLimited,
messages: messages,
);
}
/// A GetMessagesResult the server might return when we request older messages.
GetMessagesResult olderGetMessagesResult({
required int anchor,
bool foundAnchor = false, // the value if the server understood includeAnchor false
required bool foundOldest,
bool historyLimited = false,
required List<Message> messages,
}) {
return GetMessagesResult(
anchor: anchor,
foundAnchor: foundAnchor,
foundNewest: false, // empirically always this, even when anchor happens to be latest
foundOldest: foundOldest,
historyLimited: historyLimited,
messages: messages,
);
}
PollWidgetData pollWidgetData({
required String question,
required List<String> options,
}) {
return PollWidgetData(
extraData: PollWidgetExtraData(question: question, options: options));
}
Submessage submessage({
SubmessageType? msgType,
required SubmessageData? content,
int? senderId,
}) {
return Submessage(
msgType: msgType ?? SubmessageType.widget,
content: jsonEncode(content),
senderId: senderId ?? selfUser.userId,
);
}
////////////////////////////////////////////////////////////////
// Aggregate data structures.
//
UnreadChannelSnapshot unreadChannelMsgs({
required String topic,
required int streamId,
required List<int> unreadMessageIds,
}) {
return UnreadChannelSnapshot(
topic: TopicName(topic),
streamId: streamId,
unreadMessageIds: unreadMessageIds,
);
}
UnreadMessagesSnapshot unreadMsgs({
int? count,
List<UnreadDmSnapshot>? dms,
List<UnreadChannelSnapshot>? channels,
List<UnreadHuddleSnapshot>? huddles,
List<int>? mentions,
bool? oldUnreadsMissing,
}) {
return UnreadMessagesSnapshot(
count: count ?? 0,
dms: dms ?? [],
channels: channels ?? [],
huddles: huddles ?? [],
mentions: mentions ?? [],
oldUnreadsMissing: oldUnreadsMissing ?? false,
);
}
const _unreadMsgs = unreadMsgs;
////////////////////////////////////////////////////////////////
// Events.
//
UserTopicEvent userTopicEvent(
int streamId, String topic, UserTopicVisibilityPolicy visibilityPolicy) {
return UserTopicEvent(
id: 1,
streamId: streamId,
topicName: TopicName(topic),
lastUpdated: 1234567890,
visibilityPolicy: visibilityPolicy,
);
}
DeleteMessageEvent deleteMessageEvent(List<StreamMessage> messages) {
assert(messages.isNotEmpty);
final streamId = messages.first.streamId;
final topic = messages.first.topic;
assert(messages.every((m) => m.streamId == streamId));
assert(messages.every((m) => m.topic == topic));
return DeleteMessageEvent(
id: 0,
messageIds: messages.map((message) => message.id).toList(),
messageType: MessageType.stream,
streamId: messages[0].streamId,
topic: messages[0].topic,
);
}
UpdateMessageEvent updateMessageEditEvent(
Message origMessage, {
int? userId = -1, // null means null; default is [selfUser.userId]
bool? renderingOnly = false,
int? messageId,
List<MessageFlag>? flags,
int? editTimestamp,
String? renderedContent,
bool isMeMessage = false,
}) {
_checkPositive(messageId, 'message ID');
messageId ??= origMessage.id;
return UpdateMessageEvent(
id: 0,
userId: userId == -1 ? selfUser.userId : userId,
renderingOnly: renderingOnly,
messageId: messageId,
messageIds: [messageId],
flags: flags ?? origMessage.flags,
editTimestamp: editTimestamp ?? 1234567890, // TODO generate timestamp
moveData: null,
origContent: 'some probably-mismatched old Markdown',
origRenderedContent: origMessage.content,
content: 'some probably-mismatched new Markdown',
renderedContent: renderedContent ?? origMessage.content,
isMeMessage: isMeMessage,
);
}
UpdateMessageEvent _updateMessageMoveEvent(
List<int> messageIds, {
required int origStreamId,
int? newStreamId,
required TopicName origTopic,
TopicName? newTopic,
String? origContent,
String? newContent,
required List<MessageFlag> flags,
PropagateMode propagateMode = PropagateMode.changeOne,
}) {
_checkPositive(origStreamId, 'stream ID');
_checkPositive(newStreamId, 'stream ID');
assert(messageIds.isNotEmpty);
return UpdateMessageEvent(
id: 0,
userId: selfUser.userId,
renderingOnly: false,
messageId: messageIds.first,
messageIds: messageIds,
flags: flags,
editTimestamp: 1234567890, // TODO generate timestamp
moveData: UpdateMessageMoveData(
origStreamId: origStreamId,
newStreamId: newStreamId ?? origStreamId,
origTopic: origTopic,
newTopic: newTopic ?? origTopic,
propagateMode: propagateMode,
),
origContent: origContent,
origRenderedContent: origContent,
content: newContent,
renderedContent: newContent,
isMeMessage: false,
);
}
/// An [UpdateMessageEvent] where [origMessages] are moved to somewhere else.
UpdateMessageEvent updateMessageEventMoveFrom({
required List<StreamMessage> origMessages,
int? newStreamId,
TopicName? newTopic,
String? newTopicStr,
String? newContent,
PropagateMode propagateMode = PropagateMode.changeOne,
}) {
_checkPositive(newStreamId, 'stream ID');
assert(origMessages.isNotEmpty);
assert(newTopic == null || newTopicStr == null);
newTopic ??= newTopicStr == null ? null : TopicName(newTopicStr);
final origMessage = origMessages.first;
// Only present on content change.
final origContent = (newContent != null) ? origMessage.content : null;
return _updateMessageMoveEvent(origMessages.map((e) => e.id).toList(),
origStreamId: origMessage.streamId,
newStreamId: newStreamId,
origTopic: origMessage.topic,
newTopic: newTopic,
origContent: origContent,
newContent: newContent,
flags: origMessage.flags,
propagateMode: propagateMode,
);
}
/// An [UpdateMessageEvent] where [newMessages] are moved from somewhere.
UpdateMessageEvent updateMessageEventMoveTo({
required List<StreamMessage> newMessages,
int? origStreamId,
TopicName? origTopic,
String? origTopicStr,
String? origContent,
PropagateMode propagateMode = PropagateMode.changeOne,
}) {
_checkPositive(origStreamId, 'stream ID');
assert(newMessages.isNotEmpty);
assert(origTopic == null || origTopicStr == null);
origTopic ??= origTopicStr == null ? null : TopicName(origTopicStr);
final newMessage = newMessages.first;
// Only present on topic move.
final newTopic = (origTopic != null) ? newMessage.topic : null;
// Only present on channel move.
final newStreamId = (origStreamId != null) ? newMessage.streamId : null;
// Only present on content change.
final newContent = (origContent != null) ? newMessage.content : null;
return _updateMessageMoveEvent(newMessages.map((e) => e.id).toList(),
origStreamId: origStreamId ?? newMessage.streamId,
newStreamId: newStreamId,
origTopic: origTopic ?? newMessage.topic,
newTopic: newTopic,
origContent: origContent,
newContent: newContent,
flags: newMessage.flags,
propagateMode: propagateMode,
);
}
UpdateMessageFlagsRemoveEvent updateMessageFlagsRemoveEvent(
MessageFlag flag,
Iterable<Message> messages, {
int? selfUserId,
}) {
_checkPositive(selfUserId, 'user ID');
return UpdateMessageFlagsRemoveEvent(
id: 0,
flag: flag,
messages: messages.map((m) => m.id).toList(),
messageDetails: Map.fromEntries(messages.map((message) {
final mentioned = message.flags.contains(MessageFlag.mentioned)
|| message.flags.contains(MessageFlag.wildcardMentioned);
return MapEntry(
message.id,
switch (message) {
StreamMessage() => UpdateMessageFlagsMessageDetail(
type: MessageType.stream,
mentioned: mentioned,
streamId: message.streamId,
topic: message.topic,
userIds: null,
),
DmMessage() => UpdateMessageFlagsMessageDetail(
type: MessageType.direct,
mentioned: mentioned,
streamId: null,
topic: null,
userIds: DmNarrow.ofMessage(message, selfUserId: selfUserId ?? selfUser.userId)
.otherRecipientIds,
),
},
);
})));
}
SubmessageEvent submessageEvent(
int messageId,
int senderId, {
required SubmessageData? content,
}) {
return SubmessageEvent(
id: 0,
msgType: SubmessageType.widget,
content: jsonEncode(content),
messageId: messageId,
senderId: senderId,
submessageId: 100,
);
}
TypingEvent typingEvent(SendableNarrow narrow, TypingOp op, int senderId) {
switch (narrow) {
case TopicNarrow():
return TypingEvent(id: 0, op: op, senderId: senderId,
messageType: MessageType.stream,
streamId: narrow.streamId,
topic: narrow.topic,
recipientIds: null);
case DmNarrow():
return TypingEvent(id: 0, op: op, senderId: senderId,
messageType: MessageType.direct,
recipientIds: narrow.allRecipientIds,
streamId: null,
topic: null);
}
}
ReactionEvent reactionEvent(Reaction reaction, ReactionOp op, int messageId) {
return ReactionEvent(
id: 0,
op: op,
emojiName: reaction.emojiName,
emojiCode: reaction.emojiCode,
reactionType: reaction.reactionType,
userId: reaction.userId,
messageId: messageId,
);
}
ChannelUpdateEvent channelUpdateEvent(
ZulipStream stream, {
required ChannelPropertyName property,
required Object? value,
}) {
switch (property) {
case ChannelPropertyName.name:
case ChannelPropertyName.description:
assert(value is String);
case ChannelPropertyName.firstMessageId:
assert(value is int?);
case ChannelPropertyName.inviteOnly:
assert(value is bool);
case ChannelPropertyName.messageRetentionDays:
assert(value is int?);
case ChannelPropertyName.channelPostPolicy:
assert(value is ChannelPostPolicy);
case ChannelPropertyName.streamWeeklyTraffic:
assert(value is int?);
}
return ChannelUpdateEvent(
id: 1,
streamId: stream.streamId,
name: stream.name,
property: property,
value: value,
);
}
////////////////////////////////////////////////////////////////
// The entire per-account or global state.
//
TestGlobalStore globalStore({
GlobalSettingsData? globalSettings,
Map<BoolGlobalSetting, bool>? boolGlobalSettings,
List<Account> accounts = const [],
}) {
return TestGlobalStore(
globalSettings: globalSettings,
boolGlobalSettings: boolGlobalSettings,
accounts: accounts,
);
}
const _globalStore = globalStore;
const String defaultRealmEmptyTopicDisplayName = 'test general chat';
InitialSnapshot initialSnapshot({
String? queueId,
int? lastEventId,
int? zulipFeatureLevel,
String? zulipVersion,
String? zulipMergeBase,
List<String>? alertWords,
List<CustomProfileField>? customProfileFields,
int? maxTopicLength,
EmailAddressVisibility? emailAddressVisibility,
int? serverTypingStartedExpiryPeriodMilliseconds,
int? serverTypingStoppedWaitPeriodMilliseconds,
int? serverTypingStartedWaitPeriodMilliseconds,
Map<String, RealmEmojiItem>? realmEmoji,
List<RecentDmConversation>? recentPrivateConversations,
List<Subscription>? subscriptions,
UnreadMessagesSnapshot? unreadMsgs,
List<ZulipStream>? streams,
UserSettings? userSettings,
List<UserTopicItem>? userTopics,
RealmWildcardMentionPolicy? realmWildcardMentionPolicy,
bool? realmMandatoryTopics,
int? realmWaitingPeriodThreshold,
Map<String, RealmDefaultExternalAccount>? realmDefaultExternalAccounts,
int? maxFileUploadSizeMib,
Uri? serverEmojiDataUrl,
String? realmEmptyTopicDisplayName,
List<User>? realmUsers,
List<User>? realmNonActiveUsers,
List<User>? crossRealmBots,
}) {
return InitialSnapshot(
queueId: queueId ?? '1:2345',
lastEventId: lastEventId ?? -1,
zulipFeatureLevel: zulipFeatureLevel ?? recentZulipFeatureLevel,
zulipVersion: zulipVersion ?? recentZulipVersion,
zulipMergeBase: zulipMergeBase ?? recentZulipVersion,
alertWords: alertWords ?? ['klaxon'],
customProfileFields: customProfileFields ?? [],
maxTopicLength: maxTopicLength ?? 60,
emailAddressVisibility: emailAddressVisibility ?? EmailAddressVisibility.everyone,
serverTypingStartedExpiryPeriodMilliseconds:
serverTypingStartedExpiryPeriodMilliseconds ?? 15000,
serverTypingStoppedWaitPeriodMilliseconds:
serverTypingStoppedWaitPeriodMilliseconds ?? 5000,
serverTypingStartedWaitPeriodMilliseconds:
serverTypingStartedWaitPeriodMilliseconds ?? 10000,
realmEmoji: realmEmoji ?? {},
recentPrivateConversations: recentPrivateConversations ?? [],
subscriptions: subscriptions ?? [], // TODO add subscriptions to default
unreadMsgs: unreadMsgs ?? _unreadMsgs(),
streams: streams ?? [], // TODO add streams to default
userSettings: userSettings ?? UserSettings(
twentyFourHourTime: false,
displayEmojiReactionUsers: true,
emojiset: Emojiset.google,
),
userTopics: userTopics,
realmWildcardMentionPolicy: realmWildcardMentionPolicy ?? RealmWildcardMentionPolicy.everyone,
realmMandatoryTopics: realmMandatoryTopics ?? true,
realmWaitingPeriodThreshold: realmWaitingPeriodThreshold ?? 0,
realmDefaultExternalAccounts: realmDefaultExternalAccounts ?? {},
maxFileUploadSizeMib: maxFileUploadSizeMib ?? 25,
serverEmojiDataUrl: serverEmojiDataUrl
?? realmUrl.replace(path: '/static/emoji.json'),
realmEmptyTopicDisplayName: realmEmptyTopicDisplayName ?? defaultRealmEmptyTopicDisplayName,
realmUsers: realmUsers ?? [],
realmNonActiveUsers: realmNonActiveUsers ?? [],
crossRealmBots: crossRealmBots ?? [],
);
}
const _initialSnapshot = initialSnapshot;
PerAccountStore store({
GlobalStore? globalStore,
Account? account,
InitialSnapshot? initialSnapshot,
}) {
final effectiveAccount = account ?? selfAccount;
return PerAccountStore.fromInitialSnapshot(
globalStore: globalStore ?? _globalStore(accounts: [effectiveAccount]),
accountId: effectiveAccount.id,
initialSnapshot: initialSnapshot ?? _initialSnapshot(),
);
}
const _store = store;
UpdateMachine updateMachine({
GlobalStore? globalStore,
Account? account,
InitialSnapshot? initialSnapshot,
}) {
initialSnapshot ??= _initialSnapshot();
final store = _store(globalStore: globalStore,
account: account, initialSnapshot: initialSnapshot);
return UpdateMachine.fromInitialSnapshot(
store: store, initialSnapshot: initialSnapshot);
}