/* eslint-disable class-methods-use-this */ /* eslint-disable camelcase */ import { MessageModelCollectionType, WhatIsThis, MessageAttributesType, ConversationAttributesType, VerificationOptions, } from '../model-types.d'; import { CallbackResultType } from '../textsecure/SendMessage'; import { ConversationType, ConversationTypeType, } from '../state/ducks/conversations'; import { ColorType } from '../types/Colors'; import { MessageModel } from './messages'; import { sniffImageMimeType } from '../util/sniffImageMimeType'; import { MIMEType, IMAGE_WEBP } from '../types/MIME'; import { arrayBufferToBase64, base64ToArrayBuffer, deriveAccessKey, fromEncodedBinaryToArrayBuffer, getRandomBytes, stringFromBytes, verifyAccessKey, } from '../Crypto'; /* eslint-disable more/no-then */ window.Whisper = window.Whisper || {}; const SEALED_SENDER = { UNKNOWN: 0, ENABLED: 1, DISABLED: 2, UNRESTRICTED: 3, }; const { Services, Util } = window.Signal; const { Contact, Message } = window.Signal.Types; const { deleteAttachmentData, doesAttachmentExist, getAbsoluteAttachmentPath, loadAttachmentData, readStickerData, upgradeMessageSchema, writeNewAttachmentData, } = window.Signal.Migrations; const { addStickerPackReference } = window.Signal.Data; const COLORS = [ 'red', 'deep_orange', 'brown', 'pink', 'purple', 'indigo', 'blue', 'teal', 'green', 'light_green', 'blue_grey', 'ultramarine', ]; const THREE_HOURS = 3 * 60 * 60 * 1000; interface CustomError extends Error { identifier?: string; number?: string; } export class ConversationModel extends window.Backbone.Model< ConversationAttributesType > { static COLORS: string; cachedProps?: ConversationType | null; contactTypingTimers?: Record< string, { senderId: string; timer: NodeJS.Timer } >; contactCollection?: Backbone.Collection; debouncedUpdateLastMessage?: () => void; // backbone ensures this exists in initialize() // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore generateProps: () => void; // backbone ensures this exists // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore id: string; initialPromise?: Promise; inProgressFetch?: Promise; incomingMessageQueue?: typeof window.PQueueType; jobQueue?: typeof window.PQueueType; messageCollection?: MessageModelCollectionType; // backbone ensures this exists in initialize() // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore messageRequestEnum: typeof window.textsecure.protobuf.SyncMessage.MessageRequestResponse.Type; ourNumber?: string; ourUuid?: string; storeName?: string | null; throttledBumpTyping: unknown; typingRefreshTimer?: NodeJS.Timer | null; typingPauseTimer?: NodeJS.Timer | null; verifiedEnum?: typeof window.textsecure.storage.protocol.VerifiedStatus; // eslint-disable-next-line class-methods-use-this defaults(): Partial { return { unreadCount: 0, verified: window.textsecure.storage.protocol.VerifiedStatus.DEFAULT, messageCount: 0, sentMessageCount: 0, }; } idForLogging(): string { if (this.isPrivate()) { const uuid = this.get('uuid'); const e164 = this.get('e164'); return `${uuid || e164} (${this.id})`; } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (this.get('groupVersion')! > 1) { return `groupv2(${this.get('groupId')})`; } const groupId = this.get('groupId'); return `group(${groupId})`; } debugID(): string { const uuid = this.get('uuid'); const e164 = this.get('e164'); const groupId = this.get('groupId'); return `group(${groupId}), sender(${uuid || e164}), id(${this.id})`; } // This is one of the few times that we want to collapse our uuid/e164 pair down into // just one bit of data. If we have a UUID, we'll send using it. getSendTarget(): string | undefined { return this.get('uuid') || this.get('e164'); } handleMessageError(message: unknown, errors: unknown): void { this.trigger('messageError', message, errors); } // eslint-disable-next-line class-methods-use-this getContactCollection(): Backbone.Collection { const collection = new window.Backbone.Collection(); const collator = new Intl.Collator(); collection.comparator = ( left: ConversationModel, right: ConversationModel ) => { const leftLower = left.getTitle().toLowerCase(); const rightLower = right.getTitle().toLowerCase(); return collator.compare(leftLower, rightLower); }; return collection; } initialize(attributes: Partial = {}): void { if (window.isValidE164(attributes.id)) { this.set({ id: window.getGuid(), e164: attributes.id }); } this.storeName = 'conversations'; this.ourNumber = window.textsecure.storage.user.getNumber(); this.ourUuid = window.textsecure.storage.user.getUuid(); this.verifiedEnum = window.textsecure.storage.protocol.VerifiedStatus; this.messageRequestEnum = window.textsecure.protobuf.SyncMessage.MessageRequestResponse.Type; // This may be overridden by window.ConversationController.getOrCreate, and signify // our first save to the database. Or first fetch from the database. this.initialPromise = Promise.resolve(); this.contactCollection = this.getContactCollection(); this.messageCollection = new window.Whisper.MessageCollection([], { conversation: this, }); this.messageCollection.on('change:errors', this.handleMessageError, this); this.messageCollection.on('send-error', this.onMessageError, this); this.throttledBumpTyping = window._.throttle(this.bumpTyping, 300); this.debouncedUpdateLastMessage = window._.debounce( this.updateLastMessage.bind(this), 200 ); this.listenTo( this.messageCollection, 'add remove destroy content-changed', this.debouncedUpdateLastMessage ); this.listenTo(this.messageCollection, 'sent', this.updateLastMessage); this.listenTo(this.messageCollection, 'send-error', this.updateLastMessage); this.on('newmessage', this.onNewMessage); this.on('change:profileKey', this.onChangeProfileKey); // Listening for out-of-band data updates this.on('delivered', this.updateAndMerge); this.on('read', this.updateAndMerge); this.on('expiration-change', this.updateAndMerge); this.on('expired', this.onExpired); const sealedSender = this.get('sealedSender'); if (sealedSender === undefined) { this.set({ sealedSender: SEALED_SENDER.UNKNOWN }); } this.unset('unidentifiedDelivery'); this.unset('unidentifiedDeliveryUnrestricted'); this.unset('hasFetchedProfile'); this.unset('tokens'); this.typingRefreshTimer = null; this.typingPauseTimer = null; // Keep props ready this.generateProps = () => { this.cachedProps = this.getProps(); }; this.on('change', this.generateProps); this.generateProps(); } isMe(): boolean { const e164 = this.get('e164'); const uuid = this.get('uuid'); return ((e164 && e164 === this.ourNumber) || (uuid && uuid === this.ourUuid)) as boolean; } isGroupV1(): boolean { const groupID = this.get('groupId'); if (!groupID) { return false; } return fromEncodedBinaryToArrayBuffer(groupID).byteLength === 16; } isEverUnregistered(): boolean { return Boolean(this.get('discoveredUnregisteredAt')); } isUnregistered(): boolean { const now = Date.now(); const sixHoursAgo = now - 1000 * 60 * 60 * 6; const discoveredUnregisteredAt = this.get('discoveredUnregisteredAt'); if (discoveredUnregisteredAt && discoveredUnregisteredAt > sixHoursAgo) { return true; } return false; } setUnregistered(): void { window.log.info(`Conversation ${this.idForLogging()} is now unregistered`); this.set({ discoveredUnregisteredAt: Date.now(), }); window.Signal.Data.updateConversation(this.attributes); } setRegistered(): void { window.log.info( `Conversation ${this.idForLogging()} is registered once again` ); this.set({ discoveredUnregisteredAt: undefined, }); window.Signal.Data.updateConversation(this.attributes); } isBlocked(): boolean { const uuid = this.get('uuid'); if (uuid) { return window.storage.isUuidBlocked(uuid); } const e164 = this.get('e164'); if (e164) { return window.storage.isBlocked(e164); } const groupId = this.get('groupId'); if (groupId) { return window.storage.isGroupBlocked(groupId); } return false; } block({ viaStorageServiceSync = false } = {}): void { let blocked = false; const isBlocked = this.isBlocked(); const uuid = this.get('uuid'); if (uuid) { window.storage.addBlockedUuid(uuid); blocked = true; } const e164 = this.get('e164'); if (e164) { window.storage.addBlockedNumber(e164); blocked = true; } const groupId = this.get('groupId'); if (groupId) { window.storage.addBlockedGroup(groupId); blocked = true; } if (!viaStorageServiceSync && !isBlocked && blocked) { this.captureChange(); } } unblock({ viaStorageServiceSync = false } = {}): boolean { let unblocked = false; const isBlocked = this.isBlocked(); const uuid = this.get('uuid'); if (uuid) { window.storage.removeBlockedUuid(uuid); unblocked = true; } const e164 = this.get('e164'); if (e164) { window.storage.removeBlockedNumber(e164); unblocked = true; } const groupId = this.get('groupId'); if (groupId) { window.storage.removeBlockedGroup(groupId); unblocked = true; } if (!viaStorageServiceSync && isBlocked && unblocked) { this.captureChange(); } return unblocked; } enableProfileSharing({ viaStorageServiceSync = false } = {}): void { const before = this.get('profileSharing'); this.set({ profileSharing: true }); const after = this.get('profileSharing'); if (!viaStorageServiceSync && Boolean(before) !== Boolean(after)) { this.captureChange(); } } disableProfileSharing({ viaStorageServiceSync = false } = {}): void { const before = this.get('profileSharing'); this.set({ profileSharing: false }); const after = this.get('profileSharing'); if (!viaStorageServiceSync && Boolean(before) !== Boolean(after)) { this.captureChange(); } } hasDraft(): boolean { const draftAttachments = this.get('draftAttachments') || []; return (this.get('draft') || this.get('quotedMessageId') || draftAttachments.length > 0) as boolean; } getDraftPreview(): string { const draft = this.get('draft'); if (draft) { return draft; } const draftAttachments = this.get('draftAttachments') || []; if (draftAttachments.length > 0) { return window.i18n('Conversation--getDraftPreview--attachment'); } const quotedMessageId = this.get('quotedMessageId'); if (quotedMessageId) { return window.i18n('Conversation--getDraftPreview--quote'); } return window.i18n('Conversation--getDraftPreview--draft'); } bumpTyping(): void { // We don't send typing messages if the setting is disabled if (!window.storage.get('typingIndicators')) { return; } if (!this.typingRefreshTimer) { const isTyping = true; this.setTypingRefreshTimer(); this.sendTypingMessage(isTyping); } this.setTypingPauseTimer(); } setTypingRefreshTimer(): void { if (this.typingRefreshTimer) { clearTimeout(this.typingRefreshTimer); } this.typingRefreshTimer = setTimeout( this.onTypingRefreshTimeout.bind(this), 10 * 1000 ); } onTypingRefreshTimeout(): void { const isTyping = true; this.sendTypingMessage(isTyping); // This timer will continue to reset itself until the pause timer stops it this.setTypingRefreshTimer(); } setTypingPauseTimer(): void { if (this.typingPauseTimer) { clearTimeout(this.typingPauseTimer); } this.typingPauseTimer = setTimeout( this.onTypingPauseTimeout.bind(this), 3 * 1000 ); } onTypingPauseTimeout(): void { const isTyping = false; this.sendTypingMessage(isTyping); this.clearTypingTimers(); } clearTypingTimers(): void { if (this.typingPauseTimer) { clearTimeout(this.typingPauseTimer); this.typingPauseTimer = null; } if (this.typingRefreshTimer) { clearTimeout(this.typingRefreshTimer); this.typingRefreshTimer = null; } } async fetchLatestGroupV2Data(): Promise { if (this.get('groupVersion') !== 2) { return; } await window.Signal.Groups.waitThenMaybeUpdateGroup({ conversation: this, }); } maybeRepairGroupV2(data: { masterKey: string; secretParams: string; publicParams: string; }): void { if ( this.get('groupVersion') && this.get('masterKey') && this.get('secretParams') && this.get('publicParams') ) { return; } window.log.info(`Repairing GroupV2 conversation ${this.idForLogging()}`); const { masterKey, secretParams, publicParams } = data; this.set({ masterKey, secretParams, publicParams, groupVersion: 2 }); window.Signal.Data.updateConversation(this.attributes); } getGroupV2Info(groupChange?: ArrayBuffer): WhatIsThis { if (this.isPrivate() || this.get('groupVersion') !== 2) { return undefined; } return { masterKey: window.Signal.Crypto.base64ToArrayBuffer( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.get('masterKey')! ), // eslint-disable-next-line @typescript-eslint/no-non-null-assertion revision: this.get('revision')!, members: this.getRecipients(), groupChange, }; } getGroupV1Info(): WhatIsThis { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (this.isPrivate() || this.get('groupVersion')! > 0) { return undefined; } return { id: this.get('groupId'), members: this.getRecipients(), }; } sendTypingMessage(isTyping: boolean): void { if (!window.textsecure.messaging) { return; } // We don't send typing messages to our other devices if (this.isMe()) { return; } const recipientId = this.isPrivate() ? this.getSendTarget() : undefined; const groupId = !this.isPrivate() ? this.get('groupId') : undefined; const groupMembers = this.getRecipients(); // We don't send typing messages if our recipients list is empty if (!this.isPrivate() && !groupMembers.length) { return; } const sendOptions = this.getSendOptions(); this.wrapSend( window.textsecure.messaging.sendTypingMessage( { isTyping, recipientId, groupId, groupMembers, }, sendOptions ) ); } async cleanup(): Promise { await window.Signal.Types.Conversation.deleteExternalFiles( this.attributes, { deleteAttachmentData, } ); } async updateAndMerge(message: MessageModel): Promise { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.debouncedUpdateLastMessage!(); const mergeMessage = () => { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const existing = this.messageCollection!.get(message.id); if (!existing) { return; } existing.merge(message.attributes); }; await this.inProgressFetch; mergeMessage(); } async onExpired(message: MessageModel): Promise { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.debouncedUpdateLastMessage!(); const removeMessage = () => { const { id } = message; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const existing = this.messageCollection!.get(id); if (!existing) { return; } window.log.info('Remove expired message from collection', { sentAt: existing.get('sent_at'), }); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.messageCollection!.remove(id); existing.trigger('expired'); existing.cleanup(); // An expired message only counts as decrementing the message count, not // the sent message count this.decrementMessageCount(); }; // If a fetch is in progress, then we need to wait until that's complete to // do this removal. Otherwise we could remove from messageCollection, then // the async database fetch could include the removed message. await this.inProgressFetch; removeMessage(); } async onNewMessage(message: WhatIsThis): Promise { const uuid = message.get ? message.get('sourceUuid') : message.sourceUuid; const e164 = message.get ? message.get('source') : message.source; const sourceDevice = message.get ? message.get('sourceDevice') : message.sourceDevice; const sourceId = window.ConversationController.ensureContactIds({ uuid, e164, }); const typingToken = `${sourceId}.${sourceDevice}`; // Clear typing indicator for a given contact if we receive a message from them this.clearContactTypingTimer(typingToken); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.debouncedUpdateLastMessage!(); } // For outgoing messages, we can call this directly. We're already loaded. addSingleMessage(message: MessageModel): MessageModel { const { id } = message; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const existing = this.messageCollection!.get(id); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const model = this.messageCollection!.add(message, { merge: true }); model.setToExpire(); if (!existing) { const { messagesAdded } = window.reduxActions.conversations; const isNewMessage = true; messagesAdded( this.id, [model.getReduxData()], isNewMessage, window.isActive() ); } return model; } // For incoming messages, they might arrive while we're in the middle of a bulk fetch // from the database. We'll wait until that is done to process this newly-arrived // message. addIncomingMessage(message: MessageModel): void { if (!this.incomingMessageQueue) { this.incomingMessageQueue = new window.PQueue({ concurrency: 1, timeout: 1000 * 60 * 2, }); } // We use a queue here to ensure messages are added to the UI in the order received this.incomingMessageQueue.add(async () => { await this.inProgressFetch; this.addSingleMessage(message); }); } format(): ConversationType | null | undefined { return this.cachedProps; } getProps(): ConversationType | null { // This is to prevent race conditions on startup; Conversation models are created // but the full window.ConversationController.load() sequence isn't complete. So, we // don't cache props on create, but we do later when load() calls generateProps() // for us. if (!window.ConversationController.isFetchComplete()) { return null; } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const color = this.getColor()!; const typingValues = window._.values(this.contactTypingTimers || {}); const typingMostRecent = window._.first( window._.sortBy(typingValues, 'timestamp') ); const typingContact = typingMostRecent ? window.ConversationController.get(typingMostRecent.senderId) : null; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const timestamp = this.get('timestamp')!; const draftTimestamp = this.get('draftTimestamp'); const draftPreview = this.getDraftPreview(); const draftText = this.get('draft'); const shouldShowDraft = (this.hasDraft() && draftTimestamp && draftTimestamp >= timestamp) as boolean; const inboxPosition = this.get('inbox_position'); const messageRequestsEnabled = window.Signal.RemoteConfig.isEnabled( 'desktop.messageRequests' ); // TODO: DESKTOP-720 /* eslint-disable @typescript-eslint/no-non-null-assertion */ const result = { id: this.id, uuid: this.get('uuid'), e164: this.get('e164'), acceptedMessageRequest: this.getAccepted(), activeAt: this.get('active_at')!, avatarPath: this.getAvatarPath()!, color, draftPreview, draftText, firstName: this.get('profileName')!, inboxPosition, isAccepted: this.getAccepted(), isArchived: this.get('isArchived')!, isBlocked: this.isBlocked(), isMe: this.isMe(), isPinned: this.get('isPinned'), isVerified: this.isVerified(), lastMessage: { status: this.get('lastMessageStatus')!, text: this.get('lastMessage')!, deletedForEveryone: this.get('lastMessageDeletedForEveryone')!, }, lastUpdated: this.get('timestamp')!, membersCount: this.isPrivate() ? undefined : (this.get('membersV2')! || this.get('members')! || []).length, messageRequestsEnabled, muteExpiresAt: this.get('muteExpiresAt')!, name: this.get('name')!, phoneNumber: this.getNumber()!, pinIndex: this.get('pinIndex'), profileName: this.getProfileName()!, sharedGroupNames: this.get('sharedGroupNames')!, shouldShowDraft, timestamp, title: this.getTitle()!, type: (this.isPrivate() ? 'direct' : 'group') as ConversationTypeType, typingContact: typingContact ? typingContact.format() : null, unreadCount: this.get('unreadCount')! || 0, }; /* eslint-enable @typescript-eslint/no-non-null-assertion */ return result; } updateE164(e164?: string | null): void { const oldValue = this.get('e164'); if (e164 && e164 !== oldValue) { this.set('e164', e164); window.Signal.Data.updateConversation(this.attributes); this.trigger('idUpdated', this, 'e164', oldValue); } } updateUuid(uuid?: string): void { const oldValue = this.get('uuid'); if (uuid && uuid !== oldValue) { this.set('uuid', uuid.toLowerCase()); window.Signal.Data.updateConversation(this.attributes); this.trigger('idUpdated', this, 'uuid', oldValue); } } updateGroupId(groupId?: string): void { const oldValue = this.get('groupId'); if (groupId && groupId !== oldValue) { this.set('groupId', groupId); window.Signal.Data.updateConversation(this.attributes); this.trigger('idUpdated', this, 'groupId', oldValue); } } incrementMessageCount(): void { this.set({ messageCount: (this.get('messageCount') || 0) + 1, }); window.Signal.Data.updateConversation(this.attributes); } decrementMessageCount(): void { this.set({ messageCount: Math.max((this.get('messageCount') || 0) - 1, 0), }); window.Signal.Data.updateConversation(this.attributes); } incrementSentMessageCount(): void { this.set({ messageCount: (this.get('messageCount') || 0) + 1, sentMessageCount: (this.get('sentMessageCount') || 0) + 1, }); window.Signal.Data.updateConversation(this.attributes); } decrementSentMessageCount(): void { this.set({ messageCount: Math.max((this.get('messageCount') || 0) - 1, 0), sentMessageCount: Math.max((this.get('sentMessageCount') || 0) - 1, 0), }); window.Signal.Data.updateConversation(this.attributes); } /** * This function is called when a message request is accepted in order to * handle sending read receipts and download any pending attachments. */ async handleReadAndDownloadAttachments(): Promise { let messages: MessageModelCollectionType | undefined; do { const first = messages ? messages.first() : undefined; // eslint-disable-next-line no-await-in-loop messages = await window.Signal.Data.getOlderMessagesByConversation( this.get('id'), { MessageCollection: window.Whisper.MessageCollection, limit: 100, receivedAt: first ? first.get('received_at') : undefined, messageId: first ? first.id : undefined, } ); if (!messages.length) { return; } const readMessages = messages.filter( m => !m.hasErrors() && m.isIncoming() ); const receiptSpecs = readMessages.map(m => ({ senderE164: m.get('source'), senderUuid: m.get('sourceUuid'), senderId: window.ConversationController.ensureContactIds({ e164: m.get('source'), uuid: m.get('sourceUuid'), }), timestamp: m.get('sent_at'), hasErrors: m.hasErrors(), })); // eslint-disable-next-line no-await-in-loop await this.sendReadReceiptsFor(receiptSpecs); // eslint-disable-next-line no-await-in-loop await Promise.all(readMessages.map(m => m.queueAttachmentDownloads())); } while (messages.length > 0); } async applyMessageRequestResponse( response: number, { fromSync = false, viaStorageServiceSync = false } = {} ): Promise { // Apply message request response locally this.set({ messageRequestResponseType: response, }); window.Signal.Data.updateConversation(this.attributes); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (response === this.messageRequestEnum!.ACCEPT) { this.unblock({ viaStorageServiceSync }); this.enableProfileSharing({ viaStorageServiceSync }); if (!fromSync) { this.sendProfileKeyUpdate(); // Locally accepted await this.handleReadAndDownloadAttachments(); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion } else if (response === this.messageRequestEnum!.BLOCK) { // Block locally, other devices should block upon receiving the sync message this.block({ viaStorageServiceSync }); this.disableProfileSharing({ viaStorageServiceSync }); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion } else if (response === this.messageRequestEnum!.DELETE) { // Delete messages locally, other devices should delete upon receiving // the sync message this.destroyMessages(); this.disableProfileSharing({ viaStorageServiceSync }); this.updateLastMessage(); if (!fromSync) { this.trigger('unload', 'deleted from message request'); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion } else if (response === this.messageRequestEnum!.BLOCK_AND_DELETE) { // Delete messages locally, other devices should delete upon receiving // the sync message this.destroyMessages(); this.disableProfileSharing({ viaStorageServiceSync }); this.updateLastMessage(); // Block locally, other devices should block upon receiving the sync message this.block({ viaStorageServiceSync }); // Leave group if this was a local action if (!fromSync) { // TODO: DESKTOP-721 // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore this.leaveGroup(); this.trigger('unload', 'blocked and deleted from message request'); } } } async syncMessageRequestResponse(response: number): Promise { // Let this run, no await this.applyMessageRequestResponse(response); const { ourNumber, ourUuid } = this; const { wrap, sendOptions } = window.ConversationController.prepareForSend( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion ourNumber || ourUuid!, { syncMessage: true, } ); await wrap( window.textsecure.messaging.syncMessageRequestResponse( { threadE164: this.get('e164'), threadUuid: this.get('uuid'), groupId: this.get('groupId'), type: response, }, sendOptions ) ); } onMessageError(): void { this.updateVerified(); } async safeGetVerified(): Promise { const promise = window.textsecure.storage.protocol.getVerified(this.id); return promise.catch( () => window.textsecure.storage.protocol.VerifiedStatus.DEFAULT ); } async updateVerified(): Promise { if (this.isPrivate()) { await this.initialPromise; const verified = await this.safeGetVerified(); if (this.get('verified') !== verified) { this.set({ verified }); window.Signal.Data.updateConversation(this.attributes); } return; } this.fetchContacts(); await Promise.all( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.contactCollection!.map(async contact => { if (!contact.isMe()) { await contact.updateVerified(); } }) ); this.onMemberVerifiedChange(); } setVerifiedDefault(options?: VerificationOptions): Promise { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { DEFAULT } = this.verifiedEnum!; return this.queueJob(() => this._setVerified(DEFAULT, options)); } setVerified(options?: VerificationOptions): Promise { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { VERIFIED } = this.verifiedEnum!; return this.queueJob(() => this._setVerified(VERIFIED, options)); } setUnverified(options: VerificationOptions): Promise { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { UNVERIFIED } = this.verifiedEnum!; return this.queueJob(() => this._setVerified(UNVERIFIED, options)); } async _setVerified( verified: number, providedOptions?: VerificationOptions ): Promise { const options = providedOptions || {}; window._.defaults(options, { viaStorageServiceSync: false, viaSyncMessage: false, viaContactSync: false, key: null, }); // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const { VERIFIED, UNVERIFIED } = this.verifiedEnum!; if (!this.isPrivate()) { throw new Error( 'You cannot verify a group conversation. ' + 'You must verify individual contacts.' ); } const beginningVerified = this.get('verified'); let keyChange; if (options.viaSyncMessage) { // handle the incoming key from the sync messages - need different // behavior if that key doesn't match the current key keyChange = await window.textsecure.storage.protocol.processVerifiedMessage( this.id, verified, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion options.key! ); } else { keyChange = await window.textsecure.storage.protocol.setVerified( this.id, verified ); } this.set({ verified }); window.Signal.Data.updateConversation(this.attributes); if ( !options.viaStorageServiceSync && !keyChange && beginningVerified !== verified ) { this.captureChange(); } // Three situations result in a verification notice in the conversation: // 1) The message came from an explicit verification in another client (not // a contact sync) // 2) The verification value received by the contact sync is different // from what we have on record (and it's not a transition to UNVERIFIED) // 3) Our local verification status is VERIFIED and it hasn't changed, // but the key did change (Key1/VERIFIED to Key2/VERIFIED - but we don't // want to show DEFAULT->DEFAULT or UNVERIFIED->UNVERIFIED) if ( !options.viaContactSync || (beginningVerified !== verified && verified !== UNVERIFIED) || (keyChange && verified === VERIFIED) ) { await this.addVerifiedChange(this.id, verified === VERIFIED, { local: !options.viaSyncMessage, }); } if (!options.viaSyncMessage) { await this.sendVerifySyncMessage( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.get('e164')!, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.get('uuid')!, verified ); } return keyChange; } async sendVerifySyncMessage( e164: string, uuid: string, state: number ): Promise { // Because syncVerification sends a (null) message to the target of the verify and // a sync message to our own devices, we need to send the accessKeys down for both // contacts. So we merge their sendOptions. const { sendOptions } = window.ConversationController.prepareForSend( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.ourNumber || this.ourUuid!, { syncMessage: true } ); const contactSendOptions = this.getSendOptions(); const options = { ...sendOptions, ...contactSendOptions }; const promise = window.textsecure.storage.protocol.loadIdentityKey(e164); return promise.then(key => this.wrapSend( window.textsecure.messaging.syncVerification( e164, uuid, state, // eslint-disable-next-line @typescript-eslint/no-non-null-assertion key!, options ) ) ); } isVerified(): boolean { if (this.isPrivate()) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return this.get('verified') === this.verifiedEnum!.VERIFIED; } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (!this.contactCollection!.length) { return false; } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return this.contactCollection!.every(contact => { if (contact.isMe()) { return true; } return contact.isVerified(); }); } isUnverified(): boolean { if (this.isPrivate()) { const verified = this.get('verified'); return ( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion verified !== this.verifiedEnum!.VERIFIED && // eslint-disable-next-line @typescript-eslint/no-non-null-assertion verified !== this.verifiedEnum!.DEFAULT ); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (!this.contactCollection!.length) { return true; } // Array.any does not exist. This is probably broken. // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore // eslint-disable-next-line @typescript-eslint/no-non-null-assertion return this.contactCollection!.any(contact => { if (contact.isMe()) { return false; } return contact.isUnverified(); }); } getUnverified(): Backbone.Collection { if (this.isPrivate()) { return this.isUnverified() ? new window.Backbone.Collection([this]) : new window.Backbone.Collection(); } return new window.Backbone.Collection( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.contactCollection!.filter(contact => { if (contact.isMe()) { return false; } return contact.isUnverified(); }) ); } setApproved(): boolean | void { if (!this.isPrivate()) { throw new Error( 'You cannot set a group conversation as trusted. ' + 'You must set individual contacts as trusted.' ); } return window.textsecure.storage.protocol.setApproval(this.id, true); } async safeIsUntrusted(): Promise { return window.textsecure.storage.protocol .isUntrusted(this.id) .catch(() => false); } async isUntrusted(): Promise { if (this.isPrivate()) { return this.safeIsUntrusted(); } // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (!this.contactCollection!.length) { return Promise.resolve(false); } return Promise.all( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.contactCollection!.map(contact => { if (contact.isMe()) { return false; } return contact.safeIsUntrusted(); }) ).then(results => window._.any(results, result => result)); } async getUntrusted(): Promise { // This is a bit ugly because isUntrusted() is async. Could do the work to cache // it locally, but we really only need it for this call. if (this.isPrivate()) { return this.isUntrusted().then(untrusted => { if (untrusted) { return new window.Backbone.Collection([this]); } return new window.Backbone.Collection(); }); } return Promise.all( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.contactCollection!.map(contact => { if (contact.isMe()) { return [false, contact]; } return Promise.all([contact.isUntrusted(), contact]); }) ).then(results => { const filtered = window._.filter(results, result => { const untrusted = result[0]; return untrusted; }); return new window.Backbone.Collection( window._.map(filtered, result => { const contact = result[1]; return contact; }) ); }); } getSentMessageCount(): number { return this.get('sentMessageCount') || 0; } getMessageRequestResponseType(): number { return this.get('messageRequestResponseType') || 0; } /** * Determine if this conversation should be considered "accepted" in terms * of message requests */ getAccepted(): boolean { const messageRequestsEnabled = window.Signal.RemoteConfig.isEnabled( 'desktop.messageRequests' ); if (!messageRequestsEnabled) { return true; } if (this.isMe()) { return true; } if ( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.getMessageRequestResponseType() === this.messageRequestEnum!.ACCEPT ) { return true; } const isFromOrAddedByTrustedContact = this.isFromOrAddedByTrustedContact(); const hasSentMessages = this.getSentMessageCount() > 0; const hasMessagesBeforeMessageRequests = (this.get('messageCountBeforeMessageRequests') || 0) > 0; const hasNoMessages = (this.get('messageCount') || 0) === 0; const isEmptyPrivateConvo = hasNoMessages && this.isPrivate(); const isEmptyWhitelistedGroup = hasNoMessages && !this.isPrivate() && this.get('profileSharing'); return ( isFromOrAddedByTrustedContact || hasSentMessages || hasMessagesBeforeMessageRequests || // an empty group is the scenario where we need to rely on // whether the profile has already been shared or not isEmptyPrivateConvo || isEmptyWhitelistedGroup ); } onMemberVerifiedChange(): void { // If the verified state of a member changes, our aggregate state changes. // We trigger both events to replicate the behavior of window.Backbone.Model.set() this.trigger('change:verified', this); this.trigger('change', this); } async toggleVerified(): Promise { if (this.isVerified()) { return this.setVerifiedDefault(); } return this.setVerified(); } async addKeyChange(keyChangedId: string): Promise { window.log.info( 'adding key change advisory for', this.idForLogging(), keyChangedId, this.get('timestamp') ); const timestamp = Date.now(); const message = ({ conversationId: this.id, type: 'keychange', sent_at: this.get('timestamp'), received_at: timestamp, key_changed: keyChangedId, unread: 1, // TODO: DESKTOP-722 // this type does not fully implement the interface it is expected to } as unknown) as typeof window.Whisper.MessageAttributesType; const id = await window.Signal.Data.saveMessage(message, { Message: window.Whisper.Message, }); const model = window.MessageController.register( id, new window.Whisper.Message({ ...message, id, }) ); this.trigger('newmessage', model); } async addVerifiedChange( verifiedChangeId: string, verified: boolean, providedOptions: Record ): Promise { const options = providedOptions || {}; window._.defaults(options, { local: true }); if (this.isMe()) { window.log.info( 'refusing to add verified change advisory for our own number' ); return; } const lastMessage = this.get('timestamp') || Date.now(); window.log.info( 'adding verified change advisory for', this.idForLogging(), verifiedChangeId, lastMessage ); const timestamp = Date.now(); const message = ({ conversationId: this.id, type: 'verified-change', sent_at: lastMessage, received_at: timestamp, verifiedChanged: verifiedChangeId, verified, local: options.local, unread: 1, // TODO: DESKTOP-722 } as unknown) as typeof window.Whisper.MessageAttributesType; const id = await window.Signal.Data.saveMessage(message, { Message: window.Whisper.Message, }); const model = window.MessageController.register( id, new window.Whisper.Message({ ...message, id, }) ); this.trigger('newmessage', model); if (this.isPrivate()) { window.ConversationController.getAllGroupsInvolvingId(this.id).then( groups => { window._.forEach(groups, group => { group.addVerifiedChange(this.id, verified, options); }); } ); } } async addCallHistory( callHistoryDetails: Record ): Promise { const { acceptedTime, endedTime, wasDeclined } = callHistoryDetails; const message = ({ conversationId: this.id, type: 'call-history', sent_at: endedTime, received_at: endedTime, unread: !wasDeclined && !acceptedTime, callHistoryDetails, // TODO: DESKTOP-722 } as unknown) as typeof window.Whisper.MessageAttributesType; const id = await window.Signal.Data.saveMessage(message, { Message: window.Whisper.Message, }); const model = window.MessageController.register( id, new window.Whisper.Message({ ...message, id, }) ); this.trigger('newmessage', model); } async addProfileChange( profileChange: unknown, conversationId?: string ): Promise { const message = ({ conversationId: this.id, type: 'profile-change', sent_at: Date.now(), received_at: Date.now(), unread: true, changedId: conversationId || this.id, profileChange, // TODO: DESKTOP-722 } as unknown) as typeof window.Whisper.MessageAttributesType; const id = await window.Signal.Data.saveMessage(message, { Message: window.Whisper.Message, }); const model = window.MessageController.register( id, new window.Whisper.Message({ ...message, id, }) ); this.trigger('newmessage', model); if (this.isPrivate()) { window.ConversationController.getAllGroupsInvolvingId(this.id).then( groups => { window._.forEach(groups, group => { group.addProfileChange(profileChange, this.id); }); } ); } } async onReadMessage( message: MessageModel, readAt?: number ): Promise { // We mark as read everything older than this message - to clean up old stuff // still marked unread in the database. If the user generally doesn't read in // the desktop app, so the desktop app only gets read syncs, we can very // easily end up with messages never marked as read (our previous early read // sync handling, read syncs never sent because app was offline) // We queue it because we often get a whole lot of read syncs at once, and // their markRead calls could very easily overlap given the async pull from DB. // Lastly, we don't send read syncs for any message marked read due to a read // sync. That's a notification explosion we don't need. return this.queueJob(() => // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.markRead(message.get('received_at')!, { sendReadReceipts: false, readAt, }) ); } getUnread(): Promise { return window.Signal.Data.getUnreadByConversation(this.id, { MessageCollection: window.Whisper.MessageCollection, }); } validate(attributes = this.attributes): string | null { const required = ['type']; const missing = window._.filter(required, attr => !attributes[attr]); if (missing.length) { return `Conversation must have ${missing}`; } if (attributes.type !== 'private' && attributes.type !== 'group') { return `Invalid conversation type: ${attributes.type}`; } const atLeastOneOf = ['e164', 'uuid', 'groupId']; const hasAtLeastOneOf = window._.filter(atLeastOneOf, attr => attributes[attr]).length > 0; if (!hasAtLeastOneOf) { return 'Missing one of e164, uuid, or groupId'; } const error = this.validateNumber() || this.validateUuid(); if (error) { return error; } return null; } validateNumber(): string | null { if (this.isPrivate() && this.get('e164')) { const regionCode = window.storage.get('regionCode'); const number = window.libphonenumber.util.parseNumber( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.get('e164')!, regionCode ); // TODO: DESKTOP-723 // This is valid, but the typing thinks it's a function. // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore if (number.isValidNumber) { this.set({ e164: number.e164 }); return null; } return number.error || 'Invalid phone number'; } return null; } validateUuid(): string | null { if (this.isPrivate() && this.get('uuid')) { // eslint-disable-next-line @typescript-eslint/no-non-null-assertion if (window.isValidGuid(this.get('uuid')!)) { return null; } return 'Invalid UUID'; } return null; } queueJob(callback: () => unknown | Promise): Promise { this.jobQueue = this.jobQueue || new window.PQueue({ concurrency: 1 }); const taskWithTimeout = window.textsecure.createTaskWithTimeout( callback, `conversation ${this.idForLogging()}` ); return this.jobQueue.add(taskWithTimeout); } getMembers(): Array { if (this.isPrivate()) { return [this]; } if (this.get('membersV2')) { return window._.compact( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.get('membersV2')!.map(member => { const c = window.ConversationController.get(member.conversationId); // In groups we won't sent to contacts we believe are unregistered if (c && c.isUnregistered()) { return null; } return c; }) ); } if (this.get('members')) { return window._.compact( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion this.get('members')!.map(id => { const c = window.ConversationController.get(id); // In groups we won't sent to contacts we believe are unregistered if (c && c.isUnregistered()) { return null; } return c; }) ); } window.log.warn( 'getMembers: Group conversation had neither membersV2 nor members' ); return []; } getMemberIds(): Array { const members = this.getMembers(); return members.map(member => member.id); } getRecipients(): Array { const members = this.getMembers(); // Eliminate our return window._.compact( members.map(member => (member.isMe() ? null : member.getSendTarget())) ); } async getQuoteAttachment( attachments: Array, preview: Array, sticker: WhatIsThis ): Promise { if (attachments && attachments.length) { return Promise.all( attachments .filter( attachment => attachment && attachment.contentType && !attachment.pending && !attachment.error ) .slice(0, 1) .map(async attachment => { const { fileName, thumbnail, contentType } = attachment; return { contentType, // Our protos library complains about this field being undefined, so we // force it to null fileName: fileName || null, thumbnail: thumbnail ? { ...(await loadAttachmentData(thumbnail)), objectUrl: getAbsoluteAttachmentPath(thumbnail.path), } : null, }; }) ); } if (preview && preview.length) { return Promise.all( preview .filter(item => item && item.image) .slice(0, 1) .map(async attachment => { const { image } = attachment; const { contentType } = image; return { contentType, // Our protos library complains about this field being undefined, so we // force it to null fileName: null, thumbnail: image ? { ...(await loadAttachmentData(image)), objectUrl: getAbsoluteAttachmentPath(image.path), } : null, }; }) ); } if (sticker && sticker.data && sticker.data.path) { const { path, contentType } = sticker.data; return [ { contentType, // Our protos library complains about this field being undefined, so we // force it to null fileName: null, thumbnail: { ...(await loadAttachmentData(sticker.data)), objectUrl: getAbsoluteAttachmentPath(path), }, }, ]; } return []; } async makeQuote( quotedMessage: typeof window.Whisper.MessageType ): Promise { const { getName } = Contact; // eslint-disable-next-line @typescript-eslint/no-non-null-assertion const contact = quotedMessage.getContact()!; const attachments = quotedMessage.get('attachments'); const preview = quotedMessage.get('preview'); const sticker = quotedMessage.get('sticker'); const body = quotedMessage.get('body'); const embeddedContact = quotedMessage.get('contact'); const embeddedContactName = embeddedContact && embeddedContact.length > 0 ? getName(embeddedContact[0]) : ''; return { author: contact.get('e164'), authorUuid: contact.get('uuid'), bodyRanges: quotedMessage.get('bodyRanges'), id: quotedMessage.get('sent_at'), text: body || embeddedContactName, attachments: quotedMessage.isTapToView() ? [{ contentType: 'image/jpeg', fileName: null }] : await this.getQuoteAttachment(attachments, preview, sticker), }; } async sendStickerMessage(packId: string, stickerId: number): Promise { const packData = window.Signal.Stickers.getStickerPack(packId); const stickerData = window.Signal.Stickers.getSticker(packId, stickerId); if (!stickerData || !packData) { window.log.warn( `Attempted to send nonexistent (${packId}, ${stickerId}) sticker!` ); return; } const { key } = packData; const { path, width, height } = stickerData; const arrayBuffer = await readStickerData(path); // We need this content type to be an image so we can display an `` instead of a // `