From 76b9d07acf000ddf1339f1baafc8708b34af35d3 Mon Sep 17 00:00:00 2001 From: Jamie Kyle <113370520+jamiebuilds-signal@users.noreply.github.com> Date: Mon, 10 Apr 2023 20:54:43 -0700 Subject: [PATCH] Remove Signal.Util --- test/test.js | 4 +- ts/background.ts | 87 +++++++++++---------- ts/groups.ts | 6 +- ts/jobs/helpers/sendDeleteForEveryone.ts | 3 +- ts/jobs/helpers/sendGroupUpdate.ts | 3 +- ts/jobs/helpers/sendProfileKey.ts | 3 +- ts/jobs/helpers/sendReaction.ts | 3 +- ts/messageModifiers/MessageReceipts.ts | 3 +- ts/messageModifiers/ReadSyncs.ts | 3 +- ts/messageModifiers/ViewSyncs.ts | 3 +- ts/models/conversations.ts | 30 ++++--- ts/models/messages.ts | 28 +++---- ts/services/calling.ts | 5 +- ts/signal.ts | 43 ---------- ts/sql/Client.ts | 3 +- ts/state/getInitialState.ts | 25 ++---- ts/state/smart/InstallScreen.tsx | 3 +- ts/textsecure/MessageReceiver.ts | 3 +- ts/textsecure/RotateSignedPreKeyListener.ts | 3 +- ts/util/createIPCEvents.ts | 9 ++- ts/util/downloadOnboardingStory.ts | 3 +- ts/util/handleRetry.ts | 3 +- ts/util/longRunningTaskWrapper.tsx | 3 +- ts/window.d.ts | 47 +---------- ts/windows/main/preload_test.ts | 8 ++ 25 files changed, 132 insertions(+), 202 deletions(-) diff --git a/test/test.js b/test/test.js index d82d45ccd..3176eed07 100644 --- a/test/test.js +++ b/test/test.js @@ -20,7 +20,7 @@ function deleteIndexedDB() { /* Delete the database before running any tests */ before(async () => { - window.Signal.Util.MessageController.install(); + window.testUtilities.installMessageController(); await deleteIndexedDB(); try { @@ -34,7 +34,7 @@ before(async () => { err && err.stack ? err.stack : err ); } - await window.Signal.Util.initializeMessageCounter(); + await window.testUtilities.initializeMessageCounter(); await window.Signal.Data.removeAll(); await window.storage.fetch(); }); diff --git a/ts/background.ts b/ts/background.ts index 9d6914f82..934d3ea36 100644 --- a/ts/background.ts +++ b/ts/background.ts @@ -8,6 +8,7 @@ import { render } from 'react-dom'; import { batch as batchDispatch } from 'react-redux'; import PQueue from 'p-queue'; +import * as Registration from './util/registration'; import MessageReceiver from './textsecure/MessageReceiver'; import type { SessionResetsType, @@ -175,6 +176,15 @@ import { showConfirmationDialog } from './util/showConfirmationDialog'; import { onCallEventSync } from './util/onCallEventSync'; import { sleeper } from './util/sleeper'; import { MINUTE } from './util/durations'; +import { + flushMessageCounter, + incrementMessageCounter, + initializeMessageCounter, +} from './util/incrementMessageCounter'; +import { RetryPlaceholders } from './util/retryPlaceholders'; +import { setBatchingStrategy } from './util/messageBatcher'; +import { parseRemoteClientExpiration } from './util/parseRemoteClientExpiration'; +import { makeLookup } from './util/makeLookup'; export function isOverHourIntoPast(timestamp: number): boolean { const HOUR = 1000 * 60 * 60; @@ -218,15 +228,12 @@ export async function startApp(): Promise { storage: window.storage, }); - await window.Signal.Util.initializeMessageCounter(); + await initializeMessageCounter(); let initialBadgesState: BadgesStateType = { byId: {} }; async function loadInitialBadgesState(): Promise { initialBadgesState = { - byId: window.Signal.Util.makeLookup( - await window.Signal.Data.getAllBadges(), - 'id' - ), + byId: makeLookup(await window.Signal.Data.getAllBadges(), 'id'), }; } @@ -487,25 +494,24 @@ export async function startApp(): Promise { timeout: durations.MINUTE * 30, }); window.Whisper.deliveryReceiptQueue.pause(); - window.Whisper.deliveryReceiptBatcher = - window.Signal.Util.createBatcher({ - name: 'Whisper.deliveryReceiptBatcher', - wait: 500, - maxSize: 100, - processBatch: async deliveryReceipts => { - const groups = groupBy(deliveryReceipts, 'conversationId'); - await Promise.all( - Object.keys(groups).map(async conversationId => { - await conversationJobQueue.add({ - type: conversationQueueJobEnum.enum.Receipts, - conversationId, - receiptsType: ReceiptType.Delivery, - receipts: groups[conversationId], - }); - }) - ); - }, - }); + window.Whisper.deliveryReceiptBatcher = createBatcher({ + name: 'Whisper.deliveryReceiptBatcher', + wait: 500, + maxSize: 100, + processBatch: async deliveryReceipts => { + const groups = groupBy(deliveryReceipts, 'conversationId'); + await Promise.all( + Object.keys(groups).map(async conversationId => { + await conversationJobQueue.add({ + type: conversationQueueJobEnum.enum.Receipts, + conversationId, + receiptsType: ReceiptType.Delivery, + receipts: groups[conversationId], + }); + }) + ); + }, + }); if (window.platform === 'darwin') { window.addEventListener('dblclick', (event: Event) => { @@ -603,7 +609,7 @@ export async function startApp(): Promise { accountManager.addEventListener('registration', () => { window.Whisper.events.trigger('userChanged', false); - drop(window.Signal.Util.Registration.markDone()); + drop(Registration.markDone()); log.info('dispatching registration event'); window.Whisper.events.trigger('registration_done'); }); @@ -710,7 +716,7 @@ export async function startApp(): Promise { shutdown: async () => { log.info('background/shutdown'); - window.Signal.Util.flushMessageCounter(); + flushMessageCounter(); // Stop background processing void AttachmentDownloads.stop(); @@ -1007,7 +1013,7 @@ export async function startApp(): Promise { ); } - const retryPlaceholders = new window.Signal.Util.RetryPlaceholders({ + const retryPlaceholders = new RetryPlaceholders({ retryReceiptLifespan, }); window.Signal.Services.retryPlaceholders = retryPlaceholders; @@ -1052,8 +1058,7 @@ export async function startApp(): Promise { window.ConversationController.get(conversationId); if (conversation) { const receivedAt = Date.now(); - const receivedAtCounter = - window.Signal.Util.incrementMessageCounter(); + const receivedAtCounter = incrementMessageCounter(); drop( conversation.queueJob('addDeliveryIssue', () => conversation.addDeliveryIssue({ @@ -1865,7 +1870,7 @@ export async function startApp(): Promise { ); window.Whisper.events.on('mightBeUnlinked', () => { - if (window.Signal.Util.Registration.everDone()) { + if (Registration.everDone()) { throttledEnqueueReconnectToWebSocket(); } }); @@ -2003,7 +2008,7 @@ export async function startApp(): Promise { window.ConversationController.getOurConversation() ); - if (isCoreDataValid && window.Signal.Util.Registration.everDone()) { + if (isCoreDataValid && Registration.everDone()) { void connect(); window.reduxActions.app.openInbox(); } else { @@ -2058,8 +2063,9 @@ export async function startApp(): Promise { window.Signal.RemoteConfig.onChange( 'desktop.clientExpiration', ({ value }) => { - const remoteBuildExpirationTimestamp = - window.Signal.Util.parseRemoteClientExpiration(value as string); + const remoteBuildExpirationTimestamp = parseRemoteClientExpiration( + value as string + ); if (remoteBuildExpirationTimestamp) { drop( window.storage.put( @@ -2218,7 +2224,7 @@ export async function startApp(): Promise { return; } - if (!window.Signal.Util.Registration.everDone()) { + if (!Registration.everDone()) { return; } @@ -2240,10 +2246,9 @@ export async function startApp(): Promise { 'desktop.clientExpiration' ); if (expiration) { - const remoteBuildExpirationTimestamp = - window.Signal.Util.parseRemoteClientExpiration( - expiration as string - ); + const remoteBuildExpirationTimestamp = parseRemoteClientExpiration( + expiration as string + ); if (remoteBuildExpirationTimestamp) { await window.storage.put( 'remoteBuildExpiration', @@ -2601,7 +2606,7 @@ export async function startApp(): Promise { log.info('App loaded - messages:', processedCount); } - window.Signal.Util.setBatchingStrategy(false); + setBatchingStrategy(false); StartupQueue.flush(); await flushAttachmentDownloadQueue(); @@ -3594,7 +3599,7 @@ export async function startApp(): Promise { void onEmpty(); - void window.Signal.Util.Registration.remove(); + void Registration.remove(); const NUMBER_ID_KEY = 'number_id'; const UUID_ID_KEY = 'uuid_id'; @@ -3660,7 +3665,7 @@ export async function startApp(): Promise { Errors.toLogFormat(eraseError) ); } finally { - await window.Signal.Util.Registration.markEverDone(); + await Registration.markEverDone(); } } diff --git a/ts/groups.ts b/ts/groups.ts index 2c1ccefa1..45a5e945f 100644 --- a/ts/groups.ts +++ b/ts/groups.ts @@ -85,6 +85,7 @@ import { } from './jobs/conversationJobQueue'; import { ReadStatus } from './messages/MessageReadStatus'; import { SeenStatus } from './MessageSeenStatus'; +import { incrementMessageCounter } from './util/incrementMessageCounter'; type AccessRequiredEnum = Proto.AccessControl.AccessRequired; @@ -1969,7 +1970,7 @@ export async function createGroupV2( sourceUuid: ourACI, conversationId: conversation.id, readStatus: ReadStatus.Read, - received_at: window.Signal.Util.incrementMessageCounter(), + received_at: incrementMessageCounter(), received_at_ms: timestamp, timestamp, seenStatus: SeenStatus.Seen, @@ -3034,8 +3035,7 @@ async function updateGroup( // Ensure that all generated messages are ordered properly. // Before the provided timestamp so update messages appear before the // initiating message, or after now(). - const finalReceivedAt = - receivedAt || window.Signal.Util.incrementMessageCounter(); + const finalReceivedAt = receivedAt || incrementMessageCounter(); const initialSentAt = sentAt || Date.now(); // GroupV1 -> GroupV2 migration changes the groupId, and we need to update our id-based diff --git a/ts/jobs/helpers/sendDeleteForEveryone.ts b/ts/jobs/helpers/sendDeleteForEveryone.ts index cff869120..2a4315b58 100644 --- a/ts/jobs/helpers/sendDeleteForEveryone.ts +++ b/ts/jobs/helpers/sendDeleteForEveryone.ts @@ -35,6 +35,7 @@ import { SendMessageProtoError } from '../../textsecure/Errors'; import { strictAssert } from '../../util/assert'; import type { LoggerType } from '../../types/Logging'; import { isStory } from '../../messages/helpers'; +import { sendToGroup } from '../../util/sendToGroup'; export async function sendDeleteForEveryone( conversation: ConversationModel, @@ -225,7 +226,7 @@ export async function sendDeleteForEveryone( logId, messageIds, send: async () => - window.Signal.Util.sendToGroup({ + sendToGroup({ abortSignal, contentHint, groupSendOptions: { diff --git a/ts/jobs/helpers/sendGroupUpdate.ts b/ts/jobs/helpers/sendGroupUpdate.ts index b22e386b1..da1819c4c 100644 --- a/ts/jobs/helpers/sendGroupUpdate.ts +++ b/ts/jobs/helpers/sendGroupUpdate.ts @@ -20,6 +20,7 @@ import type { ConversationQueueJobBundle, } from '../conversationJobQueue'; import { getUntrustedConversationUuids } from './getUntrustedConversationUuids'; +import { sendToGroup } from '../../util/sendToGroup'; // Note: because we don't have a recipient map, if some sends fail, we will resend this // message to folks that got it on the first go-round. This is okay, because receivers @@ -118,7 +119,7 @@ export async function sendGroupUpdate( logId, messageIds: [], send: async () => - window.Signal.Util.sendToGroup({ + sendToGroup({ abortSignal, groupSendOptions: { groupV2, diff --git a/ts/jobs/helpers/sendProfileKey.ts b/ts/jobs/helpers/sendProfileKey.ts index a6bb79d8a..470c92c8a 100644 --- a/ts/jobs/helpers/sendProfileKey.ts +++ b/ts/jobs/helpers/sendProfileKey.ts @@ -32,6 +32,7 @@ import { UnregisteredUserError, } from '../../textsecure/Errors'; import { shouldSendToConversation } from './shouldSendToConversation'; +import { sendToGroup } from '../../util/sendToGroup'; export function canAllErrorsBeIgnored( conversation: ConversationAttributesType, @@ -147,7 +148,7 @@ export async function sendProfileKey( groupV2Info.revision = revision; } - sendPromise = window.Signal.Util.sendToGroup({ + sendPromise = sendToGroup({ contentHint, groupSendOptions: { flags: Proto.DataMessage.Flags.PROFILE_KEY_UPDATE, diff --git a/ts/jobs/helpers/sendReaction.ts b/ts/jobs/helpers/sendReaction.ts index b4b7b94d6..dfc74c789 100644 --- a/ts/jobs/helpers/sendReaction.ts +++ b/ts/jobs/helpers/sendReaction.ts @@ -37,6 +37,7 @@ import type { import { isConversationAccepted } from '../../util/isConversationAccepted'; import { isConversationUnregistered } from '../../util/isConversationUnregistered'; import type { LoggerType } from '../../types/Logging'; +import { sendToGroup } from '../../util/sendToGroup'; export async function sendReaction( conversation: ConversationModel, @@ -250,7 +251,7 @@ export async function sendReaction( groupV2Info.revision = revision; } - return window.Signal.Util.sendToGroup({ + return sendToGroup({ abortSignal, contentHint: ContentHint.RESENDABLE, groupSendOptions: { diff --git a/ts/messageModifiers/MessageReceipts.ts b/ts/messageModifiers/MessageReceipts.ts index c930897d6..d2b9bf27f 100644 --- a/ts/messageModifiers/MessageReceipts.ts +++ b/ts/messageModifiers/MessageReceipts.ts @@ -23,6 +23,7 @@ import type { DeleteSentProtoRecipientOptionsType } from '../sql/Interface'; import dataInterface from '../sql/Client'; import * as log from '../logging/log'; import { getSourceUuid } from '../messages/helpers'; +import { queueUpdateMessage } from '../util/messageBatcher'; const { deleteSentProtoRecipient } = dataInterface; @@ -232,7 +233,7 @@ export class MessageReceipts extends Collection { [sourceConversationId]: newSendState, }); - window.Signal.Util.queueUpdateMessage(message.attributes); + queueUpdateMessage(message.attributes); // notify frontend listeners const conversation = window.ConversationController.get( diff --git a/ts/messageModifiers/ReadSyncs.ts b/ts/messageModifiers/ReadSyncs.ts index 9ee8642c0..2b0ad7f2a 100644 --- a/ts/messageModifiers/ReadSyncs.ts +++ b/ts/messageModifiers/ReadSyncs.ts @@ -12,6 +12,7 @@ import { notificationService } from '../services/notifications'; import * as log from '../logging/log'; import * as Errors from '../types/errors'; import { StartupQueue } from '../util/StartupQueue'; +import { queueUpdateMessage } from '../util/messageBatcher'; export type ReadSyncAttributesType = { senderId: string; @@ -146,7 +147,7 @@ export class ReadSyncs extends Collection { message.set({ expirationStartTimestamp }); } - window.Signal.Util.queueUpdateMessage(message.attributes); + queueUpdateMessage(message.attributes); this.remove(sync); } catch (error) { diff --git a/ts/messageModifiers/ViewSyncs.ts b/ts/messageModifiers/ViewSyncs.ts index 425ed92b8..112f47dd4 100644 --- a/ts/messageModifiers/ViewSyncs.ts +++ b/ts/messageModifiers/ViewSyncs.ts @@ -15,6 +15,7 @@ import { notificationService } from '../services/notifications'; import { queueAttachmentDownloads } from '../util/queueAttachmentDownloads'; import * as log from '../logging/log'; import { GiftBadgeStates } from '../components/conversation/Message'; +import { queueUpdateMessage } from '../util/messageBatcher'; export type ViewSyncAttributesType = { senderId: string; @@ -122,7 +123,7 @@ export class ViewSyncs extends Collection { } if (didChangeMessage) { - window.Signal.Util.queueUpdateMessage(message.attributes); + queueUpdateMessage(message.attributes); } this.remove(sync); diff --git a/ts/models/conversations.ts b/ts/models/conversations.ts index 8ab3948dd..acb531935 100644 --- a/ts/models/conversations.ts +++ b/ts/models/conversations.ts @@ -140,6 +140,7 @@ import * as log from '../logging/log'; import * as Errors from '../types/errors'; import { isMessageUnread } from '../util/isMessageUnread'; import type { SenderKeyTargetType } from '../util/sendToGroup'; +import { sendContentMessageToGroup } from '../util/sendToGroup'; import { singleProtoJobQueue } from '../jobs/singleProtoJobQueue'; import { TimelineMessageLoadingState } from '../util/timelineUtil'; import { SeenStatus } from '../MessageSeenStatus'; @@ -156,6 +157,8 @@ import { ReceiptType } from '../types/Receipt'; import { getQuoteAttachment } from '../util/makeQuote'; import { stripNewlinesForLeftPane } from '../util/stripNewlinesForLeftPane'; import { findAndFormatContact } from '../util/findAndFormatContact'; +import { deriveProfileKeyVersion } from '../util/zkgroup'; +import { incrementMessageCounter } from '../util/incrementMessageCounter'; const EMPTY_ARRAY: Readonly<[]> = []; const EMPTY_GROUP_COLLISIONS: GroupNameCollisionsWithIdsByTitle = {}; @@ -163,7 +166,6 @@ const EMPTY_GROUP_COLLISIONS: GroupNameCollisionsWithIdsByTitle = {}; /* eslint-disable more/no-then */ window.Whisper = window.Whisper || {}; -const { Util } = window.Signal; const { Message } = window.Signal.Types; const { deleteAttachmentData, @@ -1432,7 +1434,7 @@ export class ConversationModel extends window.Backbone ); } else { await handleMessageSend( - window.Signal.Util.sendContentMessageToGroup({ + sendContentMessageToGroup({ contentHint: ContentHint.IMPLICIT, contentMessage, messageId: undefined, @@ -3237,7 +3239,7 @@ export class ConversationModel extends window.Backbone type: 'keychange', sent_at: timestamp, timestamp, - received_at: window.Signal.Util.incrementMessageCounter(), + received_at: incrementMessageCounter(), received_at_ms: timestamp, key_changed: keyChangedIdString, readStatus: ReadStatus.Read, @@ -3311,7 +3313,7 @@ export class ConversationModel extends window.Backbone type: 'conversation-merge', sent_at: timestamp, timestamp, - received_at: window.Signal.Util.incrementMessageCounter(), + received_at: incrementMessageCounter(), received_at_ms: timestamp, conversationMerge: { renderInfo, @@ -3363,7 +3365,7 @@ export class ConversationModel extends window.Backbone local: Boolean(options.local), readStatus: shouldBeUnseen ? ReadStatus.Unread : ReadStatus.Read, received_at_ms: timestamp, - received_at: window.Signal.Util.incrementMessageCounter(), + received_at: incrementMessageCounter(), seenStatus: shouldBeUnseen ? SeenStatus.Unseen : SeenStatus.Unseen, sent_at: lastMessage, timestamp, @@ -3455,8 +3457,7 @@ export class ConversationModel extends window.Backbone type: 'call-history', sent_at: timestamp, timestamp, - received_at: - receivedAtCounter || window.Signal.Util.incrementMessageCounter(), + received_at: receivedAtCounter || incrementMessageCounter(), received_at_ms: timestamp, readStatus: unread ? ReadStatus.Unread : ReadStatus.Read, seenStatus: unread ? SeenStatus.Unseen : SeenStatus.NotApplicable, @@ -3554,7 +3555,7 @@ export class ConversationModel extends window.Backbone conversationId: this.id, type: 'profile-change', sent_at: now, - received_at: window.Signal.Util.incrementMessageCounter(), + received_at: incrementMessageCounter(), received_at_ms: now, readStatus: ReadStatus.Read, seenStatus: SeenStatus.NotApplicable, @@ -3597,7 +3598,7 @@ export class ConversationModel extends window.Backbone conversationId: this.id, type, sent_at: now, - received_at: window.Signal.Util.incrementMessageCounter(), + received_at: incrementMessageCounter(), received_at_ms: now, readStatus: ReadStatus.Read, seenStatus: SeenStatus.NotApplicable, @@ -4265,7 +4266,7 @@ export class ConversationModel extends window.Backbone preview, attachments: attachmentsToSend, sent_at: now, - received_at: window.Signal.Util.incrementMessageCounter(), + received_at: incrementMessageCounter(), received_at_ms: now, expirationStartTimestamp, expireTimer, @@ -4879,7 +4880,7 @@ export class ConversationModel extends window.Backbone flags: Proto.DataMessage.Flags.EXPIRATION_TIMER_UPDATE, readStatus: shouldBeRead ? ReadStatus.Read : ReadStatus.Unread, received_at_ms: receivedAtMS, - received_at: receivedAt ?? window.Signal.Util.incrementMessageCounter(), + received_at: receivedAt ?? incrementMessageCounter(), seenStatus: shouldBeRead ? SeenStatus.Seen : SeenStatus.Unseen, sent_at: sentAt, type: 'timer-notification', @@ -4937,7 +4938,7 @@ export class ConversationModel extends window.Backbone group_update: { left: 'You' }, readStatus: ReadStatus.Read, received_at_ms: now, - received_at: window.Signal.Util.incrementMessageCounter(), + received_at: incrementMessageCounter(), seenStatus: SeenStatus.NotApplicable, sent_at: now, type: 'group', @@ -5216,10 +5217,7 @@ export class ConversationModel extends window.Backbone return lastProfile.profileKeyVersion; } - const profileKeyVersion = Util.zkgroup.deriveProfileKeyVersion( - profileKey, - uuid - ); + const profileKeyVersion = deriveProfileKeyVersion(profileKey, uuid); if (!profileKeyVersion) { log.warn( 'deriveProfileKeyVersion: Failed to derive profile key version, ' + diff --git a/ts/models/messages.ts b/ts/models/messages.ts index 0604eb3c4..3e9cd4c3d 100644 --- a/ts/models/messages.ts +++ b/ts/models/messages.ts @@ -31,6 +31,7 @@ import { repeat, zipObject, } from '../util/iterables'; +import * as GoogleChrome from '../util/GoogleChrome'; import type { DeleteModel } from '../messageModifiers/Deletes'; import type { SentEventData } from '../textsecure/messageReceiverEvents'; import { isNotNil } from '../util/isNotNil'; @@ -188,6 +189,12 @@ import { shouldReplyNotifyUser } from '../util/shouldReplyNotifyUser'; import { isConversationAccepted } from '../util/isConversationAccepted'; import type { RawBodyRange } from '../types/BodyRange'; import { BodyRange, applyRangesForText } from '../types/BodyRange'; +import { deleteForEveryone } from '../util/deleteForEveryone'; +import { getStringForProfileChange } from '../util/getStringForProfileChange'; +import { + queueUpdateMessage, + saveNewMessageBatcher, +} from '../util/messageBatcher'; /* eslint-disable more/no-then */ @@ -195,7 +202,6 @@ window.Whisper = window.Whisper || {}; const { Message: TypedMessage } = window.Signal.Types; const { upgradeMessageSchema } = window.Signal.Migrations; -const { GoogleChrome } = window.Signal.Util; const { getMessageBySender } = window.Signal.Data; export class MessageModel extends window.Backbone.Model { @@ -486,11 +492,7 @@ export class MessageModel extends window.Backbone.Model { } return { - text: window.Signal.Util.getStringForProfileChange( - change, - changedContact, - window.i18n - ), + text: getStringForProfileChange(change, changedContact, window.i18n), }; } @@ -959,12 +961,8 @@ export class MessageModel extends window.Backbone.Model { const firstAttachment = attachments[0]; if ( - !window.Signal.Util.GoogleChrome.isImageTypeSupported( - firstAttachment.contentType - ) && - !window.Signal.Util.GoogleChrome.isVideoTypeSupported( - firstAttachment.contentType - ) + !GoogleChrome.isImageTypeSupported(firstAttachment.contentType) && + !GoogleChrome.isVideoTypeSupported(firstAttachment.contentType) ) { return false; } @@ -1113,7 +1111,7 @@ export class MessageModel extends window.Backbone.Model { referencedMessageNotFound: false, }, }); - window.Signal.Util.queueUpdateMessage(this.attributes); + queueUpdateMessage(this.attributes); } } @@ -3032,7 +3030,7 @@ export class MessageModel extends window.Backbone.Model { conversation: ConversationModel, confirm: () => void ): Promise { - await window.Signal.Util.saveNewMessageBatcher.add(this.attributes); + await saveNewMessageBatcher.add(this.attributes); log.info('Message saved', this.get('sent_at')); @@ -3279,7 +3277,7 @@ export class MessageModel extends window.Backbone.Model { const deletes = Deletes.getSingleton().forMessage(message); await Promise.all( deletes.map(async del => { - await window.Signal.Util.deleteForEveryone(message, del, false); + await deleteForEveryone(message, del, false); changed = true; }) ); diff --git a/ts/services/calling.ts b/ts/services/calling.ts index e8f67ecfb..a19bb3a19 100644 --- a/ts/services/calling.ts +++ b/ts/services/calling.ts @@ -105,6 +105,7 @@ import { } from './notifications'; import * as log from '../logging/log'; import { assertDev } from '../util/assert'; +import { sendContentMessageToGroup, sendToGroup } from '../util/sendToGroup'; const { processGroupCallRingCancellation, @@ -1056,7 +1057,7 @@ export class CallingClass { messageIds: [], send: () => conversation.queueJob('sendGroupCallUpdateMessage', () => - window.Signal.Util.sendToGroup({ + sendToGroup({ contentHint: ContentHint.DEFAULT, groupSendOptions: { groupCallUpdate: { eraId }, @@ -1696,7 +1697,7 @@ export class CallingClass { const { ContentHint } = Proto.UnidentifiedSenderMessage.Message; await conversation.queueJob('handleSendCallMessageToGroup', async () => handleMessageSend( - window.Signal.Util.sendContentMessageToGroup({ + sendContentMessageToGroup({ contentHint: ContentHint.DEFAULT, contentMessage, isPartialSend: false, diff --git a/ts/signal.ts b/ts/signal.ts index 2f2f8c25e..e3bab2d9c 100644 --- a/ts/signal.ts +++ b/ts/signal.ts @@ -10,9 +10,6 @@ import Data from './sql/Client'; import * as Groups from './groups'; import * as OS from './OS'; import * as RemoteConfig from './RemoteConfig'; -import * as GoogleChrome from './util/GoogleChrome'; -import * as Registration from './util/registration'; -import * as zkgroup from './util/zkgroup'; // Components import { ConfirmationDialog } from './components/ConfirmationDialog'; @@ -49,25 +46,6 @@ import type { EmbeddedContactType } from './types/EmbeddedContact'; import type { ContactWithHydratedAvatar } from './textsecure/SendMessage'; import type { LinkPreviewType } from './types/message/LinkPreviews'; import type { StickerType, StickerWithHydratedData } from './types/Stickers'; -import { MessageController } from './util/MessageController'; -import { - flushMessageCounter, - incrementMessageCounter, - initializeMessageCounter, -} from './util/incrementMessageCounter'; -import { sleep } from './util/sleep'; -import { - queueUpdateMessage, - saveNewMessageBatcher, - setBatchingStrategy, -} from './util/messageBatcher'; -import { sendContentMessageToGroup, sendToGroup } from './util/sendToGroup'; -import { makeLookup } from './util/makeLookup'; -import { getStringForProfileChange } from './util/getStringForProfileChange'; -import { deleteForEveryone } from './util/deleteForEveryone'; -import { RetryPlaceholders } from './util/retryPlaceholders'; -import { parseRemoteClientExpiration } from './util/parseRemoteClientExpiration'; -import { createBatcher } from './util/batcher'; type MigrationsModuleType = { attachmentsPath: string; @@ -422,26 +400,5 @@ export const setup = (options: { Services, State, Types, - Util: { - createBatcher, - deleteForEveryone, - flushMessageCounter, - getStringForProfileChange, - GoogleChrome, - incrementMessageCounter, - initializeMessageCounter, - makeLookup, - MessageController, - parseRemoteClientExpiration, - queueUpdateMessage, - Registration, - RetryPlaceholders, - saveNewMessageBatcher, - sendContentMessageToGroup, - sendToGroup, - setBatchingStrategy, - sleep, - zkgroup, - }, }; }; diff --git a/ts/sql/Client.ts b/ts/sql/Client.ts index 67a8423d3..0c05db1c0 100644 --- a/ts/sql/Client.ts +++ b/ts/sql/Client.ts @@ -70,6 +70,7 @@ import { parseSqliteError, SqliteErrorKind } from './errors'; import { MINUTE } from '../util/durations'; import { getMessageIdForLogging } from '../util/idForLogging'; import type { MessageAttributesType } from '../model-types'; +import { incrementMessageCounter } from '../util/incrementMessageCounter'; const getRealPath = pify(fs.realpath); @@ -253,7 +254,7 @@ export function _cleanMessageData(data: MessageType): MessageType { // Ensure that all messages have the received_at set properly if (!data.received_at) { assertDev(false, 'received_at was not set on the message'); - result.received_at = window.Signal.Util.incrementMessageCounter(); + result.received_at = incrementMessageCounter(); } if (data.attachments) { const logId = getMessageIdForLogging(data); diff --git a/ts/state/getInitialState.ts b/ts/state/getInitialState.ts index b8ace8bf3..e65736c58 100644 --- a/ts/state/getInitialState.ts +++ b/ts/state/getInitialState.ts @@ -38,6 +38,7 @@ import { getEmojiReducerState as emojis } from '../util/loadRecentEmojis'; import { getInitialState as stickers } from '../types/Stickers'; import { getThemeType } from '../util/getThemeType'; import { getInteractionMode } from '../services/InteractionMode'; +import { makeLookup } from '../util/makeLookup'; export function getInitialState({ badges, @@ -91,26 +92,14 @@ export function getInitialState({ composer: composer(), conversations: { ...conversations(), - conversationLookup: window.Signal.Util.makeLookup( - formattedConversations, - 'id' - ), - conversationsByE164: window.Signal.Util.makeLookup( - formattedConversations, - 'e164' - ), + conversationLookup: makeLookup(formattedConversations, 'id'), + conversationsByE164: makeLookup(formattedConversations, 'e164'), conversationsByUuid: { - ...window.Signal.Util.makeLookup(formattedConversations, 'uuid'), - ...window.Signal.Util.makeLookup(formattedConversations, 'pni'), + ...makeLookup(formattedConversations, 'uuid'), + ...makeLookup(formattedConversations, 'pni'), }, - conversationsByGroupId: window.Signal.Util.makeLookup( - formattedConversations, - 'groupId' - ), - conversationsByUsername: window.Signal.Util.makeLookup( - formattedConversations, - 'username' - ), + conversationsByGroupId: makeLookup(formattedConversations, 'groupId'), + conversationsByUsername: makeLookup(formattedConversations, 'username'), }, crashReports: crashReports(), emojis: emojis(), diff --git a/ts/state/smart/InstallScreen.tsx b/ts/state/smart/InstallScreen.tsx index cf92c9121..0ba05672e 100644 --- a/ts/state/smart/InstallScreen.tsx +++ b/ts/state/smart/InstallScreen.tsx @@ -16,6 +16,7 @@ import { LoadingState } from '../../util/loadable'; import { assertDev } from '../../util/assert'; import { explodePromise } from '../../util/explodePromise'; import { missingCaseError } from '../../util/missingCaseError'; +import * as Registration from '../../util/registration'; import { InstallScreen, InstallScreenStep, @@ -186,7 +187,7 @@ export function SmartInstallScreen(): ReactElement { // Delete all data from the database unless we're in the middle of a re-link. // Without this, the app restarts at certain times and can cause weird things to // happen, like data from a previous light import showing up after a new install. - const shouldRetainData = window.Signal.Util.Registration.everDone(); + const shouldRetainData = Registration.everDone(); if (!shouldRetainData) { try { await window.textsecure.storage.protocol.removeAllData(); diff --git a/ts/textsecure/MessageReceiver.ts b/ts/textsecure/MessageReceiver.ts index 3df91ea66..3544ed2ed 100644 --- a/ts/textsecure/MessageReceiver.ts +++ b/ts/textsecure/MessageReceiver.ts @@ -124,6 +124,7 @@ import { isNotNil } from '../util/isNotNil'; import { chunk } from '../util/iterables'; import { isOlderThan } from '../util/timestamp'; import { inspectUnknownFieldTags } from '../util/inspectProtobufs'; +import { incrementMessageCounter } from '../util/incrementMessageCounter'; const GROUPV1_ID_LENGTH = 16; const GROUPV2_ID_LENGTH = 32; @@ -378,7 +379,7 @@ export default class MessageReceiver // Make non-private envelope IDs dashless so they don't get redacted // from logs id: getGuid().replace(/-/g, ''), - receivedAtCounter: window.Signal.Util.incrementMessageCounter(), + receivedAtCounter: incrementMessageCounter(), receivedAtDate: Date.now(), // Calculate the message age (time on server). messageAgeSec: this.calculateMessageAge(headers, serverTimestamp), diff --git a/ts/textsecure/RotateSignedPreKeyListener.ts b/ts/textsecure/RotateSignedPreKeyListener.ts index 7c77a5515..fb2a871dc 100644 --- a/ts/textsecure/RotateSignedPreKeyListener.ts +++ b/ts/textsecure/RotateSignedPreKeyListener.ts @@ -3,6 +3,7 @@ import * as durations from '../util/durations'; import { clearTimeoutIfNecessary } from '../util/clearTimeoutIfNecessary'; +import * as Registration from '../util/registration'; import { UUIDKind } from '../types/UUID'; import * as log from '../logging/log'; @@ -95,7 +96,7 @@ export class RotateSignedPreKeyListener { listener.setTimeoutForNextRun(); events.on('timetravel', () => { - if (window.Signal.Util.Registration.isDone()) { + if (Registration.isDone()) { listener.setTimeoutForNextRun(); } }); diff --git a/ts/util/createIPCEvents.ts b/ts/util/createIPCEvents.ts index 42945fc41..30fe81370 100644 --- a/ts/util/createIPCEvents.ts +++ b/ts/util/createIPCEvents.ts @@ -33,6 +33,7 @@ import { strictAssert, assertDev } from './assert'; import * as durations from './durations'; import type { DurationInSeconds } from './durations'; import { isPhoneNumberSharingEnabled } from './isPhoneNumberSharingEnabled'; +import * as Registration from './registration'; import { parseE164FromSignalDotMeHash, parseUsernameFromSignalDotMeHash, @@ -453,7 +454,7 @@ export function createIPCEvents( }, authorizeArtCreator: (data: AuthorizeArtCreatorDataType) => { // We can get these events even if the user has never linked this instance. - if (!window.Signal.Util.Registration.everDone()) { + if (!Registration.everDone()) { log.warn('authorizeArtCreator: Not registered, returning early'); return; } @@ -481,7 +482,7 @@ export function createIPCEvents( showStickerPack: (packId, key) => { // We can get these events even if the user has never linked this instance. - if (!window.Signal.Util.Registration.everDone()) { + if (!Registration.everDone()) { log.warn('showStickerPack: Not registered, returning early'); return; } @@ -489,7 +490,7 @@ export function createIPCEvents( }, showGroupViaLink: async hash => { // We can get these events even if the user has never linked this instance. - if (!window.Signal.Util.Registration.everDone()) { + if (!Registration.everDone()) { log.warn('showGroupViaLink: Not registered, returning early'); return; } @@ -507,7 +508,7 @@ export function createIPCEvents( } }, async showConversationViaSignalDotMe(hash: string) { - if (!window.Signal.Util.Registration.everDone()) { + if (!Registration.everDone()) { log.info( 'showConversationViaSignalDotMe: Not registered, returning early' ); diff --git a/ts/util/downloadOnboardingStory.ts b/ts/util/downloadOnboardingStory.ts index e87ab33b7..09dbbb2b3 100644 --- a/ts/util/downloadOnboardingStory.ts +++ b/ts/util/downloadOnboardingStory.ts @@ -13,6 +13,7 @@ import { findAndDeleteOnboardingStoryIfExists } from './findAndDeleteOnboardingS import { runStorageServiceSyncJob } from '../services/storage'; import { saveNewMessageBatcher } from './messageBatcher'; import { strictAssert } from './assert'; +import { incrementMessageCounter } from './incrementMessageCounter'; // * Check if we've viewed onboarding story. Short circuit. // * Run storage service sync (just in case) and check again. @@ -106,7 +107,7 @@ async function continueDownloadingOnboardingStory(): Promise { conversationId: signalConversation.id, id: UUID.generate().toString(), readStatus: ReadStatus.Unread, - received_at: window.Signal.Util.incrementMessageCounter(), + received_at: incrementMessageCounter(), received_at_ms: timestamp, seenStatus: SeenStatus.Unseen, sent_at: timestamp, diff --git a/ts/util/handleRetry.ts b/ts/util/handleRetry.ts index b4084fa90..d5f931d42 100644 --- a/ts/util/handleRetry.ts +++ b/ts/util/handleRetry.ts @@ -39,6 +39,7 @@ import type MessageSender from '../textsecure/SendMessage'; import type { StoryDistributionListDataType } from '../state/ducks/storyDistributionLists'; import { drop } from './drop'; import { conversationJobQueue } from '../jobs/conversationJobQueue'; +import { incrementMessageCounter } from './incrementMessageCounter'; const RETRY_LIMIT = 5; @@ -668,7 +669,7 @@ export function startAutomaticSessionReset( } const receivedAt = Date.now(); - const receivedAtCounter = window.Signal.Util.incrementMessageCounter(); + const receivedAtCounter = incrementMessageCounter(); drop( conversation.queueJob('addChatSessionRefreshed', async () => { await conversation.addChatSessionRefreshed({ diff --git a/ts/util/longRunningTaskWrapper.tsx b/ts/util/longRunningTaskWrapper.tsx index d1c457720..d8592c790 100644 --- a/ts/util/longRunningTaskWrapper.tsx +++ b/ts/util/longRunningTaskWrapper.tsx @@ -8,6 +8,7 @@ import * as Errors from '../types/errors'; import * as log from '../logging/log'; import { ProgressModal } from '../components/ProgressModal'; import { clearTimeoutIfNecessary } from './clearTimeoutIfNecessary'; +import { sleep } from './sleep'; export async function longRunningTaskWrapper({ name, @@ -49,7 +50,7 @@ export async function longRunningTaskWrapper({ log.info( `longRunningTaskWrapper/${idLog}: Spinner shown for less than second, showing for another second` ); - await window.Signal.Util.sleep(ONE_SECOND); + await sleep(ONE_SECOND); } unmountComponentAtNode(progressNode); progressNode = undefined; diff --git a/ts/window.d.ts b/ts/window.d.ts index eb85703fa..dd9f1767b 100644 --- a/ts/window.d.ts +++ b/ts/window.d.ts @@ -9,8 +9,6 @@ import type * as Backbone from 'backbone'; import type PQueue from 'p-queue/dist'; import type { assert } from 'chai'; import type { PhoneNumber, PhoneNumberFormat } from 'google-libphonenumber'; -import type * as Registration from './util/registration'; -import type * as zkgroup from './util/zkgroup'; import type { ConversationModelCollectionType, @@ -41,7 +39,7 @@ import type { createApp } from './state/roots/createApp'; import type Data from './sql/Client'; import type { MessageModel } from './models/messages'; import type { ConversationModel } from './models/conversations'; -import type { BatcherType, createBatcher } from './util/batcher'; +import type { BatcherType } from './util/batcher'; import type { ConfirmationDialog } from './components/ConfirmationDialog'; import type { SignalProtocolStore } from './SignalProtocolStore'; import type { SocketStatus } from './types/SocketStatus'; @@ -57,27 +55,7 @@ import type { IPCEventsType } from './util/createIPCEvents'; import type { SignalContextType } from './windows/context'; import type * as Message2 from './types/Message2'; import type { initializeMigrations } from './signal'; -import type { - flushMessageCounter, - incrementMessageCounter, - initializeMessageCounter, -} from './util/incrementMessageCounter'; import type { RetryPlaceholders } from './util/retryPlaceholders'; -import type { sleep } from './util/sleep'; -import type { - queueUpdateMessage, - saveNewMessageBatcher, - setBatchingStrategy, -} from './util/messageBatcher'; -import type { - sendContentMessageToGroup, - sendToGroup, -} from './util/sendToGroup'; -import type * as GoogleChrome from './util/GoogleChrome'; -import type { makeLookup } from './util/makeLookup'; -import type { getStringForProfileChange } from './util/getStringForProfileChange'; -import type { deleteForEveryone } from './util/deleteForEveryone'; -import type { parseRemoteClientExpiration } from './util/parseRemoteClientExpiration'; export { Long } from 'long'; @@ -155,27 +133,6 @@ export type SignalCoreType = { Address: typeof Address; QualifiedAddress: typeof QualifiedAddress; }; - Util: { - createBatcher: typeof createBatcher; - deleteForEveryone: typeof deleteForEveryone; - flushMessageCounter: typeof flushMessageCounter; - getStringForProfileChange: typeof getStringForProfileChange; - GoogleChrome: typeof GoogleChrome; - incrementMessageCounter: typeof incrementMessageCounter; - initializeMessageCounter: typeof initializeMessageCounter; - makeLookup: typeof makeLookup; - MessageController: typeof MessageController; - parseRemoteClientExpiration: typeof parseRemoteClientExpiration; - queueUpdateMessage: typeof queueUpdateMessage; - Registration: typeof Registration; - RetryPlaceholders: typeof RetryPlaceholders; - saveNewMessageBatcher: typeof saveNewMessageBatcher; - sendContentMessageToGroup: typeof sendContentMessageToGroup; - sendToGroup: typeof sendToGroup; - setBatchingStrategy: typeof setBatchingStrategy; - sleep: typeof sleep; - zkgroup: typeof zkgroup; - }; Components: { ConfirmationDialog: typeof ConfirmationDialog; }; @@ -298,6 +255,8 @@ declare global { testUtilities: { onComplete: (info: unknown) => void; prepareTests: () => void; + installMessageController: () => void; + initializeMessageCounter: () => Promise; }; } diff --git a/ts/windows/main/preload_test.ts b/ts/windows/main/preload_test.ts index 22e9179ab..a8299f6c5 100644 --- a/ts/windows/main/preload_test.ts +++ b/ts/windows/main/preload_test.ts @@ -10,6 +10,8 @@ import { sync } from 'fast-glob'; import { assert } from 'chai'; import { getSignalProtocolStore } from '../../SignalProtocolStore'; +import { MessageController } from '../../util/MessageController'; +import { initializeMessageCounter } from '../../util/incrementMessageCounter'; window.assert = assert; @@ -27,6 +29,12 @@ window.testUtilities = { cwd: __dirname, }).forEach(require); }, + installMessageController() { + MessageController.install(); + }, + initializeMessageCounter() { + return initializeMessageCounter(); + }, }; window.getSignalProtocolStore = getSignalProtocolStore;