-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
index.tsx
3714 lines (3435 loc) · 130 KB
/
index.tsx
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 * as BotsGen from '../bots-gen'
import * as Chat2Gen from '../chat2-gen'
import * as ConfigGen from '../config-gen'
import * as DeeplinksGen from '../deeplinks-gen'
import * as EngineGen from '../engine-gen-gen'
import * as TeamBuildingGen from '../team-building-gen'
import * as Constants from '../../constants/chat2'
import * as GregorGen from '../gregor-gen'
import * as FsConstants from '../../constants/fs'
import * as Flow from '../../util/flow'
import * as NotificationsGen from '../notifications-gen'
import * as RPCChatTypes from '../../constants/types/rpc-chat-gen'
import * as RPCTypes from '../../constants/types/rpc-gen'
import * as RouteTreeGen from '../route-tree-gen'
import * as WalletsGen from '../wallets-gen'
import * as Saga from '../../util/saga'
import * as TeamsGen from '../teams-gen'
import * as Types from '../../constants/types/chat2'
import * as FsTypes from '../../constants/types/fs'
import * as WalletTypes from '../../constants/types/wallets'
import * as Tabs from '../../constants/tabs'
import * as UsersGen from '../users-gen'
import * as WaitingGen from '../waiting-gen'
import * as Router2Constants from '../../constants/router2'
import commonTeamBuildingSaga, {filterForNs} from '../team-building'
import * as TeamsConstants from '../../constants/teams'
import logger from '../../logger'
import {NotifyPopup} from '../../native/notifications'
import {saveAttachmentToCameraRoll, showShareActionSheet} from '../platform-specific'
import {privateFolderWithUsers, teamFolder} from '../../constants/config'
import {RPCError} from '../../util/errors'
import * as Container from '../../util/container'
const onConnect = async () => {
try {
await RPCTypes.delegateUiCtlRegisterChatUIRpcPromise()
console.log('Registered Chat UI')
} catch (error) {
console.warn('Error in registering Chat UI:', error)
}
}
const onGetInboxUnverifiedConvs = (action: EngineGen.Chat1ChatUiChatInboxUnverifiedPayload) => {
const inbox = action.payload.params.inbox
const result: RPCChatTypes.UnverifiedInboxUIItems = JSON.parse(inbox)
const items: Array<RPCChatTypes.UnverifiedInboxUIItem> = result.items ?? []
// We get a subset of meta information from the cache even in the untrusted payload
const metas = items.reduce<Array<Types.ConversationMeta>>((arr, item) => {
const m = Constants.unverifiedInboxUIItemToConversationMeta(item)
m && arr.push(m)
return arr
}, [])
// Check if some of our existing stored metas might no longer be valid
return Chat2Gen.createMetasReceived({
fromInboxRefresh: true,
initialTrustedLoad: true,
metas,
})
}
// Ask the service to refresh the inbox
const inboxRefresh = (
state: Container.TypedState,
action: Chat2Gen.InboxRefreshPayload | EngineGen.Chat1NotifyChatChatInboxStalePayload
) => {
if (!state.config.loggedIn) {
return false
}
const {username} = state.config
if (!username) {
return false
}
const actions: Array<Container.TypedActions> = []
let reason: string = ''
let clearExistingMetas = false
let clearExistingMessages = false
switch (action.type) {
case Chat2Gen.inboxRefresh:
reason = action.payload.reason
clearExistingMetas = reason === 'inboxSyncedClear'
clearExistingMessages = reason === 'inboxSyncedClear'
break
case EngineGen.chat1NotifyChatChatInboxStale:
reason = 'inboxStale'
break
default:
Flow.ifFlowComplainsAboutThisFunctionYouHaventHandledAllCasesInASwitch(action)
}
logger.info(`Inbox refresh due to ${reason ?? '???'}`)
if (clearExistingMetas) {
actions.push(Chat2Gen.createClearMetas())
}
if (clearExistingMessages) {
actions.push(Chat2Gen.createClearMessages())
}
const reselectMode =
state.chat2.inboxHasLoaded || Container.isMobile
? RPCChatTypes.InboxLayoutReselectMode.default
: RPCChatTypes.InboxLayoutReselectMode.force
RPCChatTypes.localRequestInboxLayoutRpcPromise({reselectMode})
return actions
}
const inboxLoadMoreSmalls = async () => {
try {
await RPCChatTypes.localRequestInboxSmallIncreaseRpcPromise()
} catch (err) {
logger.info(`inboxLoadMoreSmalls: failed to increase smalls: ${err.message}`)
}
}
const inboxResetSmalls = async () => {
try {
await RPCChatTypes.localRequestInboxSmallResetRpcPromise()
} catch (err) {
logger.info(`inboxResetSmalls: failed to reset smalls: ${err.message}`)
}
}
// Only get the untrusted conversations out
const untrustedConversationIDKeys = (state: Container.TypedState, ids: Array<Types.ConversationIDKey>) =>
ids.filter(id => (state.chat2.metaMap.get(id) ?? {trustedState: 'untrusted'}).trustedState === 'untrusted')
// We keep a set of conversations to unbox
let metaQueue = new Set<Types.ConversationIDKey>()
const queueMetaToRequest = (
state: Container.TypedState,
action: Chat2Gen.MetaNeedsUpdatingPayload,
logger: Saga.SagaLogger
) => {
let added = false
untrustedConversationIDKeys(state, action.payload.conversationIDKeys).forEach(k => {
if (!metaQueue.has(k)) {
added = true
metaQueue.add(k)
}
})
if (added) {
// only unboxMore if something changed
return Chat2Gen.createMetaHandleQueue()
} else {
logger.info('skipping meta queue run, queue unchanged')
return false
}
}
// Watch the meta queue and take up to 10 items. Choose the last items first since they're likely still visible
function* requestMeta(state: Container.TypedState, _: Chat2Gen.MetaHandleQueuePayload) {
const maxToUnboxAtATime = 10
const ar = [...metaQueue]
const maybeUnbox = ar.slice(0, maxToUnboxAtATime)
metaQueue = new Set(ar.slice(maxToUnboxAtATime))
const conversationIDKeys = untrustedConversationIDKeys(state, maybeUnbox)
const toUnboxActions = conversationIDKeys.length
? [Saga.put(Chat2Gen.createMetaRequestTrusted({conversationIDKeys, reason: 'scroll'}))]
: []
const unboxSomeMoreActions = metaQueue.size ? [Saga.put(Chat2Gen.createMetaHandleQueue())] : []
const delayBeforeUnboxingMoreActions =
toUnboxActions.length && unboxSomeMoreActions.length ? [Saga.delay(100)] : []
const nextActions = [...toUnboxActions, ...delayBeforeUnboxingMoreActions, ...unboxSomeMoreActions]
if (nextActions.length) {
yield Saga.sequentially(nextActions)
}
}
// Get valid keys that we aren't already loading or have loaded
const rpcMetaRequestConversationIDKeys = (
state: Container.TypedState,
action: Chat2Gen.MetaRequestTrustedPayload | Chat2Gen.SelectConversationPayload
) => {
let keys: Array<Types.ConversationIDKey>
switch (action.type) {
case Chat2Gen.metaRequestTrusted:
keys = action.payload.conversationIDKeys
if (action.payload.force) {
return keys.filter(Constants.isValidConversationIDKey)
}
break
case Chat2Gen.selectConversation:
keys = [action.payload.conversationIDKey].filter(Constants.isValidConversationIDKey)
break
default:
Flow.ifFlowComplainsAboutThisFunctionYouHaventHandledAllCasesInASwitch(action)
throw new Error('Invalid action passed to unboxRows')
}
return Constants.getConversationIDKeyMetasToLoad(keys, state.chat2.metaMap)
}
const onGetInboxConvsUnboxed = (
state: Container.TypedState,
action: EngineGen.Chat1ChatUiChatInboxConversationPayload
) => {
const infoMap = state.users.infoMap
const actions: Array<Container.TypedActions> = []
const convs = action.payload.params.convs
const inboxUIItems: Array<RPCChatTypes.InboxUIItem> = JSON.parse(convs)
const metas: Array<Types.ConversationMeta> = []
let added = false
const usernameToFullname: {[username: string]: string} = {}
inboxUIItems.forEach(inboxUIItem => {
const meta = Constants.inboxUIItemToConversationMeta(state, inboxUIItem)
if (meta) {
metas.push(meta)
}
;(inboxUIItem.participants ?? []).forEach((part: RPCChatTypes.UIParticipant) => {
if (!infoMap.get(part.assertion) && part.fullName) {
added = true
usernameToFullname[part.assertion] = part.fullName
}
})
})
if (added) {
actions.push(UsersGen.createUpdateFullnames({usernameToFullname}))
}
if (metas.length > 0) {
actions.push(Chat2Gen.createMetasReceived({metas}))
}
return actions
}
const onGetInboxConvFailed = (
state: Container.TypedState,
action: EngineGen.Chat1ChatUiChatInboxFailedPayload,
logger: Saga.SagaLogger
) => {
const {convID, error} = action.payload.params
const conversationIDKey = Types.conversationIDToKey(convID)
switch (error.typ) {
case RPCChatTypes.ConversationErrorType.transient:
logger.info(
`onFailed: ignoring transient error for convID: ${conversationIDKey} error: ${error.message}`
)
return false
default:
logger.info(`onFailed: displaying error for convID: ${conversationIDKey} error: ${error.message}`)
return Chat2Gen.createMetaReceivedError({
conversationIDKey: conversationIDKey,
error,
username: state.config.username,
})
}
}
const maybeChangeSelectedConv = (
state: Container.TypedState,
_: EngineGen.Chat1ChatUiChatInboxLayoutPayload,
logger: Saga.SagaLogger
) => {
const {inboxLayout, selectedConversation} = state.chat2
if (!inboxLayout || !inboxLayout.reselectInfo) {
return false
}
if (
!Constants.isValidConversationIDKey(selectedConversation) ||
state.chat2.selectedConversation === inboxLayout.reselectInfo.oldConvID
) {
if (Container.isMobile) {
// on mobile just head back to the inbox if we have something selected
if (Constants.isValidConversationIDKey(selectedConversation)) {
logger.info(`maybeChangeSelectedConv: mobile: navigating up on conv change`)
return Chat2Gen.createNavigateToInbox()
}
logger.info(`maybeChangeSelectedConv: mobile: ignoring conv change, no conv selected`)
return false
}
if (inboxLayout.reselectInfo.newConvID) {
logger.info(`maybeChangeSelectedConv: selecting new conv: ${inboxLayout.reselectInfo.newConvID}`)
return Chat2Gen.createSelectConversation({
conversationIDKey: inboxLayout.reselectInfo.newConvID,
reason: 'findNewestConversation',
})
} else {
logger.info(`maybeChangeSelectedConv: deselecting conv, service provided no new conv`)
return Chat2Gen.createSelectConversation({
conversationIDKey: Constants.noConversationIDKey,
reason: 'clearSelected',
})
}
} else {
logger.info(
`maybeChangeSelectedConv: selected conv mismatch on reselect (ignoring): selected: ${selectedConversation} srvold: ${inboxLayout.reselectInfo.oldConvID}`
)
return false
}
}
// We want to unbox rows that have scroll into view
const unboxRows = (
state: Container.TypedState,
action: Chat2Gen.MetaRequestTrustedPayload | Chat2Gen.SelectConversationPayload,
logger: Saga.SagaLogger
) => {
if (!state.config.loggedIn) {
return false
}
switch (action.type) {
case Chat2Gen.metaRequestTrusted:
logger.info(`unboxRows: metaRequestTrusted: reason: ${action.payload.reason}`)
break
case Chat2Gen.selectConversation:
logger.info(`unboxRows: selectConversation`)
break
}
const conversationIDKeys = rpcMetaRequestConversationIDKeys(state, action)
if (!conversationIDKeys.length) {
return
}
logger.info(`unboxRows: unboxing len: ${conversationIDKeys.length} convs: ${conversationIDKeys.join(',')}`)
RPCChatTypes.localRequestInboxUnboxRpcPromise({
convIDs: conversationIDKeys.map(k => {
return Types.keyToConversationID(k)
}),
})
return Chat2Gen.createMetaRequestingTrusted({conversationIDKeys})
}
// We get an incoming message streamed to us
const onIncomingMessage = (
state: Container.TypedState,
incoming: RPCChatTypes.IncomingMessage,
logger: Saga.SagaLogger
) => {
const {message: cMsg} = incoming
const actions: Array<Container.TypedActions> = []
const {modifiedMessage, convID, displayDesktopNotification, desktopNotificationSnippet} = incoming
if (convID && cMsg) {
const conversationIDKey = Types.conversationIDToKey(convID)
const shouldAddMessage = state.chat2.containsLatestMessageMap.get(conversationIDKey) || false
const message = Constants.uiMessageToMessage(state, conversationIDKey, cMsg)
if (message) {
// The attachmentuploaded call is like an 'edit' of an attachment. We get the placeholder, then its replaced by the actual image
if (
cMsg.state === RPCChatTypes.MessageUnboxedState.valid &&
cMsg.valid?.messageBody.messageType === RPCChatTypes.MessageType.attachmentuploaded &&
cMsg.valid?.messageBody.attachmentuploaded &&
message.type === 'attachment'
) {
actions.push(
Chat2Gen.createMessageAttachmentUploaded({
conversationIDKey,
message,
placeholderID: cMsg.valid.messageBody.attachmentuploaded.messageID,
})
)
} else if (shouldAddMessage) {
// A normal message
actions.push(Chat2Gen.createMessagesAdd({context: {type: 'incoming'}, messages: [message]}))
}
} else if (cMsg.state === RPCChatTypes.MessageUnboxedState.valid && cMsg.valid) {
const valid = cMsg.valid
const body = valid.messageBody
logger.info(`Got chat incoming message of messageType: ${body.messageType}`)
// Types that are mutations
switch (body.messageType) {
case RPCChatTypes.MessageType.edit:
if (modifiedMessage) {
const modMessage = Constants.uiMessageToMessage(state, conversationIDKey, modifiedMessage)
if (modMessage) {
actions.push(Chat2Gen.createMessagesAdd({context: {type: 'incoming'}, messages: [modMessage]}))
}
}
break
case RPCChatTypes.MessageType.delete:
if (body.delete && body.delete.messageIDs) {
// check if the delete is acting on an exploding message
const messageIDs = body.delete.messageIDs
const messages = state.chat2.messageMap.get(conversationIDKey)
const isExplodeNow =
!!messages &&
messageIDs.some(_id => {
const id = Types.numberToOrdinal(_id)
const message = messages.get(id) ?? [...messages.values()].find(msg => msg.id === id)
if ((message?.type === 'text' || message?.type === 'attachment') && message?.exploding) {
return true
}
return false
})
actions.push(
isExplodeNow
? Chat2Gen.createMessagesExploded({
conversationIDKey,
explodedBy: valid.senderUsername,
messageIDs: messageIDs,
})
: Chat2Gen.createMessagesWereDeleted({conversationIDKey, messageIDs})
)
}
break
}
}
if (
!Container.isMobile &&
displayDesktopNotification &&
desktopNotificationSnippet &&
cMsg.state === RPCChatTypes.MessageUnboxedState.valid &&
cMsg.valid
) {
actions.push(
Chat2Gen.createDesktopNotification({
author: cMsg.valid.senderUsername,
body: desktopNotificationSnippet,
conversationIDKey,
})
)
}
}
return actions
}
// Helper to handle incoming inbox updates that piggy back on various calls
const chatActivityToMetasAction = (
state: Container.TypedState,
payload: {
readonly conv?: RPCChatTypes.InboxUIItem | null
}
) => {
const conv = payload ? payload.conv : null
const meta = conv && Constants.inboxUIItemToConversationMeta(state, conv)
const usernameToFullname = ((conv && conv.participants) || []).reduce((map, part) => {
if (part.fullName) {
map[part.assertion] = part.fullName
}
return map
}, {})
return meta
? [Chat2Gen.createMetasReceived({metas: [meta]}), UsersGen.createUpdateFullnames({usernameToFullname})]
: []
}
// We got errors from the service
const onErrorMessage = (outboxRecords: Array<RPCChatTypes.OutboxRecord>) => {
const actions = outboxRecords.reduce<Array<Container.TypedActions>>((arr, outboxRecord) => {
const s = outboxRecord.state
if (s.state === RPCChatTypes.OutboxStateType.error) {
const error = s.error
const conversationIDKey = Types.conversationIDToKey(outboxRecord.convID)
const outboxID = Types.rpcOutboxIDToOutboxID(outboxRecord.outboxID)
if (error) {
// This is temp until fixed by CORE-7112. We get this error but not the call to let us show the red banner
const reason = Constants.rpcErrorToString(error)
let tempForceRedBox: string | null = null
if (error.typ === RPCChatTypes.OutboxErrorType.identify) {
// Find out the user who failed identify
const match = error.message.match(/"(.*)"/)
tempForceRedBox = match && match[1]
}
arr.push(Chat2Gen.createMessageErrored({conversationIDKey, errorTyp: error.typ, outboxID, reason}))
if (tempForceRedBox) {
arr.push(UsersGen.createUpdateBrokenState({newlyBroken: [tempForceRedBox], newlyFixed: []}))
}
}
}
return arr
}, [])
return actions
}
// Some participants are broken/fixed now
const onChatIdentifyUpdate = (action: EngineGen.Chat1NotifyChatChatIdentifyUpdatePayload) => {
const {update} = action.payload.params
const usernames = update.CanonicalName.split(',')
const broken = (update.breaks.breaks || []).map(b => b.user.username)
const newlyBroken: Array<string> = []
const newlyFixed: Array<string> = []
usernames.forEach(name => {
if (broken.includes(name)) {
newlyBroken.push(name)
} else {
newlyFixed.push(name)
}
})
return UsersGen.createUpdateBrokenState({newlyBroken, newlyFixed})
}
// Get actions to update messagemap / metamap when retention policy expunge happens
const expungeToActions = (state: Container.TypedState, expunge: RPCChatTypes.ExpungeInfo) => {
const actions: Array<Container.TypedActions> = []
const conversationIDKey = Types.conversationIDToKey(expunge.convID)
actions.push(
Chat2Gen.createMessagesWereDeleted({
conversationIDKey,
deletableMessageTypes: Constants.getDeletableByDeleteHistory(state),
upToMessageID: expunge.expunge.upto,
})
)
return actions
}
// Get actions to update messagemap / metamap when ephemeral messages expire
const ephemeralPurgeToActions = (info: RPCChatTypes.EphemeralPurgeNotifInfo) => {
const actions: Array<Container.TypedActions> = []
const conversationIDKey = Types.conversationIDToKey(info.convID)
const messageIDs =
!!info.msgs &&
info.msgs.reduce<Array<Types.MessageID>>((arr, msg) => {
const msgID = Constants.getMessageID(msg)
if (msgID) {
arr.push(msgID)
}
return arr
}, [])
!!messageIDs && actions.push(Chat2Gen.createMessagesExploded({conversationIDKey, messageIDs}))
return actions
}
const messagesUpdatedToActions = (state: Container.TypedState, info: RPCChatTypes.MessagesUpdated) => {
const conversationIDKey = Types.conversationIDToKey(info.convID)
const messages = (info.updates ?? []).reduce<
Array<{
message: Types.Message
messageID: Types.MessageID
}>
>((l, msg) => {
const messageID = Constants.getMessageID(msg)
if (!messageID) {
return l
}
const uiMsg = Constants.uiMessageToMessage(state, conversationIDKey, msg)
if (!uiMsg) {
return l
}
return l.concat({
message: uiMsg,
messageID: Types.numberToMessageID(messageID),
})
}, [])
return [Chat2Gen.createUpdateMessages({conversationIDKey, messages})]
}
// Get actions to update the messagemap when reactions are updated
const reactionUpdateToActions = (info: RPCChatTypes.ReactionUpdateNotif) => {
const conversationIDKey = Types.conversationIDToKey(info.convID)
if (!info.reactionUpdates || info.reactionUpdates.length === 0) {
logger.warn(`Got ReactionUpdateNotif with no reactionUpdates for convID=${conversationIDKey}`)
return null
}
const updates = info.reactionUpdates.map(ru => ({
reactions: Constants.reactionMapToReactions(ru.reactions),
targetMsgID: ru.targetMsgID,
}))
logger.info(`Got ${updates.length} reaction updates for convID=${conversationIDKey}`)
return [
Chat2Gen.createUpdateReactions({conversationIDKey, updates}),
Chat2Gen.createUpdateUserReacjis({userReacjis: info.userReacjis}),
]
}
const onChatPromptUnfurl = (action: EngineGen.Chat1NotifyChatChatPromptUnfurlPayload) => {
const {convID, domain, msgID} = action.payload.params
return Chat2Gen.createUnfurlTogglePrompt({
conversationIDKey: Types.conversationIDToKey(convID),
domain,
messageID: Types.numberToMessageID(msgID),
show: true,
})
}
const onChatAttachmentUploadProgress = (
action: EngineGen.Chat1NotifyChatChatAttachmentUploadProgressPayload
) => {
const {convID, outboxID, bytesComplete, bytesTotal} = action.payload.params
return Chat2Gen.createAttachmentUploading({
conversationIDKey: Types.conversationIDToKey(convID),
outboxID: Types.rpcOutboxIDToOutboxID(outboxID),
ratio: bytesComplete / bytesTotal,
})
}
const onChatAttachmentUploadStart = (action: EngineGen.Chat1NotifyChatChatAttachmentUploadStartPayload) => {
const {convID, outboxID} = action.payload.params
return Chat2Gen.createAttachmentUploading({
conversationIDKey: Types.conversationIDToKey(convID),
outboxID: Types.rpcOutboxIDToOutboxID(outboxID),
ratio: 0.01,
})
}
const onChatInboxSyncStarted = () =>
WaitingGen.createIncrementWaiting({key: Constants.waitingKeyInboxSyncStarted})
// Service tells us it's done syncing
const onChatInboxSynced = (
state: Container.TypedState,
action: EngineGen.Chat1NotifyChatChatInboxSyncedPayload
) => {
const {syncRes} = action.payload.params
const actions: Array<Container.TypedActions> = [
WaitingGen.createClearWaiting({key: Constants.waitingKeyInboxSyncStarted}),
]
switch (syncRes.syncType) {
// Just clear it all
case RPCChatTypes.SyncInboxResType.clear:
actions.push(Chat2Gen.createInboxRefresh({reason: 'inboxSyncedClear'}))
break
// We're up to date
case RPCChatTypes.SyncInboxResType.current:
break
// We got some new messages appended
case RPCChatTypes.SyncInboxResType.incremental: {
const selectedConversation = Constants.getSelectedConversation(state)
const items = (syncRes.incremental && syncRes.incremental.items) || []
const metas = items.reduce<Array<Types.ConversationMeta>>((arr, i) => {
const meta = Constants.unverifiedInboxUIItemToConversationMeta(i.conv)
if (meta) {
if (meta.conversationIDKey === selectedConversation) {
// First thing load the messages
actions.unshift(
Chat2Gen.createMarkConversationsStale({
conversationIDKeys: [selectedConversation],
updateType: RPCChatTypes.StaleUpdateType.newactivity,
})
)
}
arr.push(meta)
}
return arr
}, [])
const removals = (
(syncRes.incremental === null || syncRes.incremental === undefined
? undefined
: syncRes.incremental.removals) || []
).map(Types.stringToConversationIDKey)
// Update new untrusted
if (metas.length || removals.length) {
actions.push(Chat2Gen.createMetasReceived({metas, removals}))
}
// Unbox items
actions.push(
Chat2Gen.createMetaRequestTrusted({
conversationIDKeys: items
.filter(i => i.shouldUnbox)
.map(i => Types.stringToConversationIDKey(i.conv.convID)),
force: true,
reason: 'inboxSynced',
})
)
break
}
default:
actions.push(Chat2Gen.createInboxRefresh({reason: 'inboxSyncedUnknown'}))
}
return actions
}
const onChatPaymentInfo = (
action: EngineGen.Chat1NotifyChatChatPaymentInfoPayload,
logger: Saga.SagaLogger
) => {
const {convID, info, msgID} = action.payload.params
const conversationIDKey = convID ? Types.conversationIDToKey(convID) : Constants.noConversationIDKey
const paymentInfo = Constants.uiPaymentInfoToChatPaymentInfo([info])
if (!paymentInfo) {
// This should never happen
const errMsg = `got 'NotifyChat.ChatPaymentInfo' with no valid paymentInfo for convID ${conversationIDKey} messageID: ${msgID}. The local version may be absent or out of date.`
logger.error(errMsg)
throw new Error(errMsg)
}
return Chat2Gen.createPaymentInfoReceived({conversationIDKey, messageID: msgID, paymentInfo})
}
const onChatRequestInfo = (
action: EngineGen.Chat1NotifyChatChatRequestInfoPayload,
logger: Saga.SagaLogger
) => {
const {convID, info, msgID} = action.payload.params
const conversationIDKey = Types.conversationIDToKey(convID)
const requestInfo = Constants.uiRequestInfoToChatRequestInfo(info)
if (!requestInfo) {
// This should never happen
const errMsg = `got 'NotifyChat.ChatRequestInfo' with no valid requestInfo for convID ${conversationIDKey} messageID: ${msgID}. The local version may be absent or out of date.`
logger.error(errMsg)
throw new Error(errMsg)
}
return Chat2Gen.createRequestInfoReceived({conversationIDKey, messageID: msgID, requestInfo})
}
const onChatSetConvRetention = (
state: Container.TypedState,
action: EngineGen.Chat1NotifyChatChatSetConvRetentionPayload,
logger: Saga.SagaLogger
) => {
const {conv, convID} = action.payload.params
if (!conv) {
logger.warn('onChatSetConvRetention: no conv given')
return false
}
const meta = Constants.inboxUIItemToConversationMeta(state, conv)
if (!meta) {
logger.warn(`onChatSetConvRetention: no meta found for ${convID}`)
return false
}
if (conv) {
return Chat2Gen.createUpdateConvRetentionPolicy({meta})
}
logger.warn('got NotifyChat.ChatSetConvRetention with no attached InboxUIItem. Forcing update.')
// force to get the new retention policy
return Chat2Gen.createMetaRequestTrusted({
conversationIDKeys: [Types.conversationIDToKey(convID)],
force: true,
reason: 'setConvRetention',
})
}
const onChatSetConvSettings = (
action: EngineGen.Chat1NotifyChatChatSetConvSettingsPayload,
logger: Saga.SagaLogger
) => {
const {conv, convID} = action.payload.params
const conversationIDKey = Types.conversationIDToKey(convID)
const newRole =
(conv?.convSettings && conv.convSettings.minWriterRoleInfo && conv.convSettings.minWriterRoleInfo.role) ||
null
const role = newRole && TeamsConstants.teamRoleByEnum[newRole]
const cannotWrite =
(conv?.convSettings &&
conv.convSettings.minWriterRoleInfo &&
conv.convSettings.minWriterRoleInfo.cannotWrite) ||
false
logger.info(
`got new minWriterRole ${role || ''} for convID ${conversationIDKey}, cannotWrite ${cannotWrite}`
)
if (role && role !== 'none' && cannotWrite !== undefined) {
return Chat2Gen.createSaveMinWriterRole({cannotWrite, conversationIDKey, role})
}
logger.warn(
`got NotifyChat.ChatSetConvSettings with no valid minWriterRole for convID ${conversationIDKey}. The local version may be out of date.`
)
return false
}
const onChatSetTeamRetention = (
state: Container.TypedState,
action: EngineGen.Chat1NotifyChatChatSetTeamRetentionPayload,
logger: Saga.SagaLogger
) => {
const {convs} = action.payload.params
const metas = (convs ?? []).reduce<Array<Types.ConversationMeta>>((l, c) => {
const meta = Constants.inboxUIItemToConversationMeta(state, c)
if (meta) {
l.push(meta)
}
return l
}, [])
if (metas) {
return Chat2Gen.createUpdateTeamRetentionPolicy({metas})
}
// this is a more serious problem, but we don't need to bug the user about it
logger.error(
'got NotifyChat.ChatSetTeamRetention with no attached InboxUIItems. The local version may be out of date'
)
return false
}
const onChatSubteamRename = (action: EngineGen.Chat1NotifyChatChatSubteamRenamePayload) => {
const {convs} = action.payload.params
const conversationIDKeys = (convs ?? []).map(c => Types.stringToConversationIDKey(c.convID))
return Chat2Gen.createMetaRequestTrusted({
conversationIDKeys,
force: true,
reason: 'subTeamRename',
})
}
const onChatChatTLFFinalizePayload = (action: EngineGen.Chat1NotifyChatChatTLFFinalizePayload) => {
const {convID} = action.payload.params
return Chat2Gen.createMetaRequestTrusted({
conversationIDKeys: [Types.conversationIDToKey(convID)],
reason: 'tlfFinalize',
})
}
const onChatThreadStale = (
action: EngineGen.Chat1NotifyChatChatThreadsStalePayload,
logger: Saga.SagaLogger
) => {
const {updates} = action.payload.params
let actions: Array<Container.TypedActions> = []
Object.keys(RPCChatTypes.StaleUpdateType)
.filter(k => typeof RPCChatTypes.StaleUpdateType[k] === 'number')
.forEach(function(key) {
const conversationIDKeys = (updates || []).reduce<Array<string>>((arr, u) => {
if (u.updateType === RPCChatTypes.StaleUpdateType[key]) {
arr.push(Types.conversationIDToKey(u.convID))
}
return arr
}, [])
// load the inbox instead
if (key === 'convupdate') {
logger.info(
`onChatThreadStale: dispatching inbox unbox actions for ${conversationIDKeys.length} convs of type ${key}`
)
actions = actions.concat([
Chat2Gen.createMetaRequestTrusted({
conversationIDKeys,
force: true,
reason: 'threadStale',
}),
])
} else if (conversationIDKeys.length > 0) {
logger.info(
`onChatThreadStale: dispatching thread reload actions for ${conversationIDKeys.length} convs of type ${key}`
)
actions = actions.concat([
Chat2Gen.createMarkConversationsStale({
conversationIDKeys,
updateType: RPCChatTypes.StaleUpdateType[key],
}),
Chat2Gen.createMetaRequestTrusted({conversationIDKeys, force: true, reason: 'threadStale'}),
])
}
})
return actions
}
const onChatShowManageChannels = (action: EngineGen.Chat1ChatUiChatShowManageChannelsPayload) => {
const {teamname} = action.payload.params
return RouteTreeGen.createNavigateAppend({path: [{props: {teamname}, selected: 'chatManageChannels'}]})
}
const onNewChatActivity = (
state: Container.TypedState,
action: EngineGen.Chat1NotifyChatNewChatActivityPayload,
logger: Saga.SagaLogger
) => {
const {activity} = action.payload.params
logger.info(`Got new chat activity of type: ${activity.activityType}`)
let actions: Array<Container.TypedActions> | null = null
switch (activity.activityType) {
case RPCChatTypes.ChatActivityType.incomingMessage: {
const {incomingMessage} = activity
actions = [
...(onIncomingMessage(state, incomingMessage, logger) as any),
...(chatActivityToMetasAction(state, incomingMessage) as any),
]
break
}
case RPCChatTypes.ChatActivityType.setStatus:
actions = chatActivityToMetasAction(state, activity.setStatus)
break
case RPCChatTypes.ChatActivityType.readMessage:
actions = chatActivityToMetasAction(state, activity.readMessage)
break
case RPCChatTypes.ChatActivityType.newConversation:
actions = chatActivityToMetasAction(state, activity.newConversation)
break
case RPCChatTypes.ChatActivityType.failedMessage: {
const {failedMessage} = activity
const {outboxRecords} = failedMessage
if (outboxRecords) {
actions = [
...(onErrorMessage(outboxRecords) as any),
...(chatActivityToMetasAction(state, failedMessage) as any),
]
}
break
}
case RPCChatTypes.ChatActivityType.membersUpdate:
actions = [
Chat2Gen.createMetaRequestTrusted({
conversationIDKeys: [Types.conversationIDToKey(activity.membersUpdate.convID)],
force: true,
reason: 'membersUpdate',
}),
]
break
case RPCChatTypes.ChatActivityType.setAppNotificationSettings:
{
const {setAppNotificationSettings} = activity
actions = [
Chat2Gen.createNotificationSettingsUpdated({
conversationIDKey: Types.conversationIDToKey(setAppNotificationSettings.convID),
settings: setAppNotificationSettings.settings,
}),
]
}
break
case RPCChatTypes.ChatActivityType.expunge: {
actions = expungeToActions(state, activity.expunge)
break
}
case RPCChatTypes.ChatActivityType.ephemeralPurge:
actions = ephemeralPurgeToActions(activity.ephemeralPurge)
break
case RPCChatTypes.ChatActivityType.reactionUpdate:
actions = reactionUpdateToActions(activity.reactionUpdate)
break
case RPCChatTypes.ChatActivityType.messagesUpdated: {
actions = messagesUpdatedToActions(state, activity.messagesUpdated)
break
}
}
return actions
}
const onChatConvUpdate = (
state: Container.TypedState,
action: EngineGen.Chat1NotifyChatChatConvUpdatePayload
) => {
const {conv} = action.payload.params
if (conv) {
const meta = Constants.inboxUIItemToConversationMeta(state, conv)
if (meta) {
return [Chat2Gen.createMetasReceived({metas: [meta]})]
}
}
return []
}
const loadThreadMessageTypes = Object.keys(RPCChatTypes.MessageType)
.filter(k => typeof RPCChatTypes.MessageType[k] === 'number')
.reduce<Array<number>>((arr, key) => {
switch (key) {
case 'none':
case 'edit': // daemon filters this out for us so we can ignore
case 'delete':
case 'attachmentuploaded':
case 'reaction':
case 'unfurl':
case 'tlfname':
break
default:
arr.push(RPCChatTypes.MessageType[key])
break
}
return arr
}, [])
const reasonToRPCReason = (reason: string): RPCChatTypes.GetThreadReason => {
switch (reason) {
case 'extension':
case 'push':
return RPCChatTypes.GetThreadReason.push
case 'foregrounding':
return RPCChatTypes.GetThreadReason.foreground
default:
return RPCChatTypes.GetThreadReason.general
}
}
type ScrollDirection = 'none' | 'back' | 'forward'
const scrollDirectionToPagination = (sd: ScrollDirection, numberOfMessagesToLoad: number) => {
const pagination = {
last: false,
next: '',
num: numberOfMessagesToLoad,
previous: '',
}
switch (sd) {
case 'none':
break
case 'back':
pagination.next = 'deadbeef'
break
case 'forward':
pagination.previous = 'deadbeef'
}
return pagination
}
// Load new messages on a thread. We call this when you select a conversation,
// we get a thread-is-stale notification, or when you scroll up and want more
// messages
function* loadMoreMessages(
state: Container.TypedState,
action:
| Chat2Gen.SelectConversationPayload
| Chat2Gen.JumpToRecentPayload
| Chat2Gen.LoadOlderMessagesDueToScrollPayload
| Chat2Gen.LoadNewerMessagesDueToScrollPayload
| Chat2Gen.LoadMessagesCenteredPayload
| Chat2Gen.MarkConversationsStalePayload
| ConfigGen.ChangedFocusPayload,
logger: Saga.SagaLogger
) {
// Get the conversationIDKey
let key: Types.ConversationIDKey | null = null
let reason: string = ''
let sd: ScrollDirection = 'none'
let messageIDControl: RPCChatTypes.MessageIDControl | null = null
let forceClear = false
let forceContainsLatestCalc = false
const centeredMessageIDs: Array<{
conversationIDKey: Types.ConversationIDKey
messageID: Types.MessageID
highlightMode: Types.CenterOrdinalHighlightMode
}> = []