From 6295e4206d432b3959b05672af89d5fc71ed2b4f Mon Sep 17 00:00:00 2001 From: Maxim Shishmarev Date: Wed, 1 Jul 2020 11:23:33 +1000 Subject: [PATCH] Clean up imports --- ts/receiver/attachments.ts | 4 +--- ts/receiver/contentMessage.ts | 8 +++---- ts/receiver/dataMessage.ts | 22 +++++++------------ ts/receiver/groups.ts | 3 +-- ts/receiver/multidevice.ts | 13 +++++------ ts/receiver/queuedJob.ts | 33 ++++++++++++---------------- ts/receiver/syncMessages.ts | 20 ++++++++--------- ts/session/snode_api/proxy.ts | 10 +++++++-- ts/session/snode_api/swarmPolling.ts | 8 +------ 9 files changed, 52 insertions(+), 69 deletions(-) diff --git a/ts/receiver/attachments.ts b/ts/receiver/attachments.ts index 947d45dce..bf71c795a 100644 --- a/ts/receiver/attachments.ts +++ b/ts/receiver/attachments.ts @@ -1,4 +1,5 @@ import { MessageModel } from '../../js/models/messages'; +import _ from 'lodash'; import * as Data from '../../js/modules/data'; @@ -6,8 +7,6 @@ import * as Data from '../../js/modules/data'; let webAPI: any; export async function downloadAttachment(attachment: any) { - const _ = window.Lodash; - if (!webAPI) { webAPI = window.WebAPI.connect(); } @@ -204,7 +203,6 @@ async function processGroupAvatar(message: MessageModel): Promise { export async function queueAttachmentDownloads( message: MessageModel ): Promise { - const _ = window.Lodash; const { Whisper } = window; let count = 0; diff --git a/ts/receiver/contentMessage.ts b/ts/receiver/contentMessage.ts index 26fc791d3..46a5161ab 100644 --- a/ts/receiver/contentMessage.ts +++ b/ts/receiver/contentMessage.ts @@ -8,6 +8,8 @@ import { toNumber } from 'lodash'; import * as libsession from '../session'; import { handleSessionRequestMessage } from './sessionHandling'; import { handlePairingAuthorisationMessage } from './multidevice'; +import { MediumGroupRequestKeysMessage } from '../session/messages/outgoing'; +import { MultiDeviceProtocol } from '../session/protocols'; import { handleSyncMessage } from './syncMessages'; import { onError } from './errors'; @@ -288,9 +290,7 @@ async function decrypt(envelope: EnvelopePlus, ciphertext: any): Promise { groupId, }; - const requestKeysMessage = new libsession.Messages.Outgoing.MediumGroupRequestKeysMessage( - params - ); + const requestKeysMessage = new MediumGroupRequestKeysMessage(params); const senderPubKey = new libsession.Types.PubKey(senderIdentity); // tslint:disable-next-line no-floating-promises libsession.getMessageQueue().send(senderPubKey, requestKeysMessage); @@ -494,7 +494,7 @@ async function handleTypingMessage( // Groups don't have primary devices so we need to take that into consideration. const user = libsession.Types.PubKey.from(source); const primaryDevice = user - ? await libsession.Protocols.MultiDeviceProtocol.getPrimaryDevice(user) + ? await MultiDeviceProtocol.getPrimaryDevice(user) : null; const convoId = groupId || (primaryDevice && primaryDevice.key) || source; diff --git a/ts/receiver/dataMessage.ts b/ts/receiver/dataMessage.ts index be76cf25d..d2b2dc7a4 100644 --- a/ts/receiver/dataMessage.ts +++ b/ts/receiver/dataMessage.ts @@ -1,6 +1,5 @@ import { SignalService } from './../protobuf'; -import { addToCache, removeFromCache } from './cache'; -import { toNumber } from 'lodash'; +import { removeFromCache } from './cache'; import { MultiDeviceProtocol } from '../session/protocols'; import { EnvelopePlus } from './types'; import { ConversationType, getEnvelopeId } from './common'; @@ -13,6 +12,7 @@ import { handleEndSession } from './sessionHandling'; import { handleMediumGroupUpdate } from './mediumGroups'; import { handleUnpairRequest } from './multidevice'; import { downloadAttachment } from './attachments'; +import _ from 'lodash'; export async function updateProfile( conversation: any, @@ -79,7 +79,7 @@ export async function updateProfile( function cleanAttachment(attachment: any) { return { - ...window.Lodash.omit(attachment, 'thumbnail'), + ..._.omit(attachment, 'thumbnail'), id: attachment.id.toString(), key: attachment.key ? attachment.key.toString('base64') : null, digest: attachment.digest ? attachment.digest.toString('base64') : null, @@ -129,7 +129,7 @@ function cleanAttachments(decrypted: any) { if (quote) { if (quote.id) { - quote.id = toNumber(quote.id); + quote.id = _.toNumber(quote.id); } quote.attachments = (quote.attachments || []).map((item: any) => { @@ -227,8 +227,6 @@ export async function processDecrypted(envelope: EnvelopePlus, decrypted: any) { } function isMessageEmpty(message: SignalService.DataMessage) { - const { Lodash: _ } = window; - const { flags, body, @@ -261,14 +259,14 @@ export async function handleDataMessage( window.log.info('data message from', getEnvelopeId(envelope)); if (dataMessage.mediumGroupUpdate) { - handleMediumGroupUpdate(envelope, dataMessage.mediumGroupUpdate).ignore(); - // TODO: investigate the meaning of this return value + await handleMediumGroupUpdate(envelope, dataMessage.mediumGroupUpdate); return; } // tslint:disable-next-line no-bitwise if (dataMessage.flags & SignalService.DataMessage.Flags.END_SESSION) { await handleEndSession(envelope.source); + return; } const message = await processDecrypted(envelope, dataMessage); const ourPubKey = window.textsecure.storage.user.getNumber(); @@ -277,7 +275,6 @@ export async function handleDataMessage( const conversation = window.ConversationController.get(senderPubKey); const { UNPAIRING_REQUEST } = SignalService.DataMessage.Flags; - const { SESSION_REQUEST } = SignalService.Envelope.Type; // eslint-disable-next-line no-bitwise const isUnpairingRequest = Boolean(message.flags & UNPAIRING_REQUEST); @@ -328,7 +325,7 @@ export async function handleDataMessage( ev.data = { source, sourceDevice: envelope.sourceDevice, - timestamp: toNumber(envelope.timestamp), + timestamp: _.toNumber(envelope.timestamp), receivedAt: envelope.receivedAt, unidentifiedDeliveryReceived: envelope.unidentifiedDeliveryReceived, message, @@ -451,8 +448,6 @@ export function initIncomingMessage(data: MessageCreationData): MessageModel { } function createSentMessage(data: MessageCreationData): MessageModel { - const { Lodash: _ } = window; - const now = Date.now(); let sentTo = []; @@ -652,8 +647,7 @@ export async function handleMessageEvent(event: any): Promise { ourNumber, confirm, source, - isGroupMessage, - primarySource.key + primarySource ).ignore(); }); } diff --git a/ts/receiver/groups.ts b/ts/receiver/groups.ts index 8b5489ce9..6325a7f97 100644 --- a/ts/receiver/groups.ts +++ b/ts/receiver/groups.ts @@ -2,8 +2,7 @@ import { SignalService } from '../protobuf'; import { ClosedGroupRequestInfoMessage } from '../session/messages/outgoing/content/data/group/ClosedGroupRequestInfoMessage'; import { getMessageQueue } from '../session'; import { PubKey } from '../session/types'; - -const _ = window.Lodash; +import _ from 'lodash'; function isGroupBlocked(groupId: string) { return ( diff --git a/ts/receiver/multidevice.ts b/ts/receiver/multidevice.ts index 1c36dbec6..5004e00a2 100644 --- a/ts/receiver/multidevice.ts +++ b/ts/receiver/multidevice.ts @@ -9,6 +9,7 @@ import { updateProfile } from './receiver'; import { onVerified } from './syncMessages'; import { StringUtils } from '../session/utils'; +import { MultiDeviceProtocol, SessionProtocol } from '../session/protocols'; async function unpairingRequestIsLegit(source: string, ourPubKey: string) { const { textsecure, storage, lokiFileServerAPI } = window; @@ -110,7 +111,7 @@ async function handlePairingRequest( if (valid) { // Pairing dialog is open and is listening if (Whisper.events.isListenedTo('devicePairingRequestReceived')) { - await libsession.Protocols.MultiDeviceProtocol.savePairingAuthorisation( + await MultiDeviceProtocol.savePairingAuthorisation( pairingRequest as Data.PairingAuthorisation ); Whisper.events.trigger( @@ -162,7 +163,7 @@ async function handleAuthorisationForSelf( window.storage.remove('secondaryDeviceStatus'); window.storage.put('isSecondaryDevice', true); window.storage.put('primaryDevicePubKey', primaryDevicePubKey); - await libsession.Protocols.MultiDeviceProtocol.savePairingAuthorisation( + await MultiDeviceProtocol.savePairingAuthorisation( pairingAuthorisation as Data.PairingAuthorisation ); const primaryConversation = await ConversationController.getOrCreateAndWait( @@ -338,7 +339,7 @@ async function onContactReceived(details: any) { } const ourPrimaryKey = window.storage.get('primaryDevicePubKey'); if (ourPrimaryKey) { - const secondaryDevices = await libsession.Protocols.MultiDeviceProtocol.getSecondaryDevices( + const secondaryDevices = await MultiDeviceProtocol.getSecondaryDevices( ourPrimaryKey ); if (secondaryDevices.some(device => device.key === id)) { @@ -346,9 +347,7 @@ async function onContactReceived(details: any) { } } - const devices = await libsession.Protocols.MultiDeviceProtocol.getAllDevices( - id - ); + const devices = await MultiDeviceProtocol.getAllDevices(id); const deviceConversations = await Promise.all( devices.map(d => ConversationController.getOrCreateAndWait(d.key, 'private') @@ -358,7 +357,7 @@ async function onContactReceived(details: any) { // when we do not have a session with it already deviceConversations.forEach(device => { // tslint:disable-next-line: no-floating-promises - libsession.Protocols.SessionProtocol.sendSessionRequestIfNeeded( + SessionProtocol.sendSessionRequestIfNeeded( new libsession.Types.PubKey(device.id) ); }); diff --git a/ts/receiver/queuedJob.ts b/ts/receiver/queuedJob.ts index e18ac72f1..1898e7135 100644 --- a/ts/receiver/queuedJob.ts +++ b/ts/receiver/queuedJob.ts @@ -3,13 +3,15 @@ import { queueAttachmentDownloads } from './attachments'; import { Quote } from './types'; import { ConversationModel } from '../../js/models/conversations'; import { MessageModel } from '../../js/models/messages'; +import { PrimaryPubKey, PubKey } from '../session/types'; +import _ from 'lodash'; +import { MultiDeviceProtocol } from '../session/protocols'; async function handleGroups( conversation: ConversationModel, group: any, source: any ): Promise { - const _ = window.Lodash; const textsecure = window.textsecure; const GROUP_TYPES = textsecure.protobuf.GroupContext.Type; @@ -93,7 +95,6 @@ async function copyFromQuotedMessage( quote: Quote, attemptCount: number = 1 ): Promise { - const _ = window.Lodash; const { Whisper, MessageController } = window; const { upgradeMessageSchema } = window.Signal.Migrations; const { Message: TypedMessage, Errors } = window.Signal.Types; @@ -277,10 +278,10 @@ function processProfileKey( function handleMentions( message: MessageModel, conversation: ConversationModel, - ourPrimaryNumber: string + ourPrimaryNumber: PrimaryPubKey ) { const body = message.get('body'); - if (body && body.indexOf(`@${ourPrimaryNumber}`) !== -1) { + if (body && body.indexOf(`@${ourPrimaryNumber.key}`) !== -1) { conversation.set({ mentionedUs: true }); } } @@ -317,8 +318,6 @@ function handleSyncedReceipts( message: MessageModel, conversation: ConversationModel ) { - const _ = window.Lodash; - const readReceipts = window.Whisper.ReadReceipts.forMessage( conversation, message @@ -352,8 +351,6 @@ function handleSyncedReceipts( } function handleSyncDeliveryReceipts(message: MessageModel, receipts: any) { - const _ = window.Lodash; - const sources = receipts.map((receipt: any) => receipt.get('source')); const deliveredTo = _.union(message.get('delivered_to') || [], sources); @@ -371,11 +368,9 @@ async function handleRegularMessage( message: MessageModel, initialMessage: any, source: string, - isGroupMessage: boolean, ourNumber: any, - primarySource: any + primarySource: PubKey ) { - const _ = window.Lodash; const { ConversationController } = window; const { upgradeMessageSchema } = window.Signal.Migrations; @@ -429,7 +424,9 @@ async function handleRegularMessage( // Handle expireTimer found directly as part of a regular message handleExpireTimer(source, message, dataMessage.expireTimer, conversation); - handleMentions(message, conversation, ourNumber); + const ourPrimary = await MultiDeviceProtocol.getPrimaryDevice(ourNumber); + + handleMentions(message, conversation, ourPrimary); if (type === 'incoming') { updateReadStatus(message, conversation); @@ -465,7 +462,7 @@ async function handleRegularMessage( } if (source !== ourNumber && primarySource) { - message.set({ source: primarySource }); + message.set({ source: primarySource.key }); } } @@ -506,10 +503,9 @@ export async function handleMessageJob( conversation: ConversationModel, initialMessage: any, ourNumber: string, - confirm: any, + confirm: () => void, source: string, - isGroupMessage: any, - primarySource: any + primarySource: PubKey ) { window.log.info( `Starting handleDataMessage for message ${message.idForLogging()} in conversation ${conversation.idForLogging()}` @@ -529,13 +525,12 @@ export async function handleMessageJob( message, initialMessage, source, - isGroupMessage, ourNumber, - primarySource.key + primarySource ); } - const { Whisper, MessageController, ConversationController } = window; + const { Whisper, MessageController } = window; const id = await window.Signal.Data.saveMessage(message.attributes, { Message: Whisper.Message, diff --git a/ts/receiver/syncMessages.ts b/ts/receiver/syncMessages.ts index 5cc145b9d..a75f9b2f2 100644 --- a/ts/receiver/syncMessages.ts +++ b/ts/receiver/syncMessages.ts @@ -1,9 +1,8 @@ import { EnvelopePlus } from './types'; import { SignalService } from '../protobuf'; -import * as libsession from './../session'; import { removeFromCache } from './cache'; import { getEnvelopeId } from './common'; -import { toNumber } from 'lodash'; +import _ from 'lodash'; import { handleEndSession } from './sessionHandling'; import { handleMediumGroupUpdate } from './mediumGroups'; @@ -11,6 +10,7 @@ import { handleMessageEvent, processDecrypted } from './dataMessage'; import { updateProfile } from './receiver'; import { handleContacts } from './multidevice'; import { onGroupReceived } from './groups'; +import { MultiDeviceProtocol } from '../session/protocols'; export async function handleSyncMessage( envelope: EnvelopePlus, @@ -20,9 +20,7 @@ export async function handleSyncMessage( // We should only accept sync messages from our devices const ourNumber = textsecure.storage.user.getNumber(); - const ourDevices = await libsession.Protocols.MultiDeviceProtocol.getAllDevices( - ourNumber - ); + const ourDevices = await MultiDeviceProtocol.getAllDevices(ourNumber); const validSyncSender = ourDevices.some( device => device.key === envelope.source ); @@ -42,7 +40,7 @@ export async function handleSyncMessage( window.log.info( 'sent message to', to, - toNumber(sentMessage.timestamp), + _.toNumber(sentMessage.timestamp), 'from', getEnvelopeId(envelope) ); @@ -117,13 +115,13 @@ async function handleSentMessage( ev.confirm = removeFromCache.bind(null, envelope); ev.data = { destination, - timestamp: toNumber(timestamp), + timestamp: _.toNumber(timestamp), device: envelope.sourceDevice, unidentifiedStatus, message, }; if (expirationStartTimestamp) { - ev.data.expirationStartTimestamp = toNumber(expirationStartTimestamp); + ev.data.expirationStartTimestamp = _.toNumber(expirationStartTimestamp); } await handleMessageEvent(ev); @@ -158,7 +156,7 @@ async function handleBlocked( window.log.info('Setting these numbers as blocked:', blocked.numbers); window.textsecure.storage.put('blocked', blocked.numbers); - const groupIds = window.Lodash.map(blocked.groupIds, (groupId: any) => + const groupIds = _.map(blocked.groupIds, (groupId: any) => groupId.toBinary() ); window.log.info( @@ -189,9 +187,9 @@ async function handleRead( const results = []; for (const read of readArray) { const promise = onReadSync( - toNumber(envelope.timestamp), + _.toNumber(envelope.timestamp), read.sender, - toNumber(read.timestamp) + _.toNumber(read.timestamp) ); results.push(promise); } diff --git a/ts/session/snode_api/proxy.ts b/ts/session/snode_api/proxy.ts index 2e2a630e6..68a6902eb 100644 --- a/ts/session/snode_api/proxy.ts +++ b/ts/session/snode_api/proxy.ts @@ -4,6 +4,7 @@ import https from 'https'; import * as SnodePool from './snodePool'; import { sleepFor } from '../../../js/modules/loki_primitives'; import { SnodeResponse } from './onions'; +import _ from 'lodash'; const snodeHttpsAgent = new https.Agent({ rejectUnauthorized: false, @@ -197,7 +198,7 @@ export async function sendToProxy( targetNode: Snode, retryNumber: any = 0 ): Promise { - const { log, Lodash: _, StringView, libloki, libsignal } = window; + const { log, StringView, libloki, libsignal } = window; let snodePool = await SnodePool.getRandomSnodePool(); @@ -226,7 +227,12 @@ export async function sendToProxy( _.find(snodePool, { pubkey_ed25519: targetNode.pubkey_ed25519 }) ); - const randSnode = window.Lodash.sample(snodePoolSafe); + const randSnode = _.sample(snodePoolSafe); + + if (!randSnode) { + log.error('No snodes left for a proxy request'); + return false; + } // Don't allow arbitrary URLs, only snodes and loki servers const url = `https://${randSnode.ip}:${randSnode.port}/proxy`; diff --git a/ts/session/snode_api/swarmPolling.ts b/ts/session/snode_api/swarmPolling.ts index 3e48307d1..e09d0898c 100644 --- a/ts/session/snode_api/swarmPolling.ts +++ b/ts/session/snode_api/swarmPolling.ts @@ -3,7 +3,7 @@ import { getSnodesFor, Snode } from './snodePool'; import { retrieveNextMessages } from './serviceNodeAPI'; import { SignalService } from '../../protobuf'; import * as Receiver from '../../receiver/receiver'; -// import { retrieveNextMessages, getSnodesForPubkey } from './serviceNodeAPI'; +import _ from 'lodash'; import { StringUtils } from '../../session/utils'; @@ -104,8 +104,6 @@ export class SwarmPolling { } private async pollForAllKeys() { - const { Lodash: _ } = window; - const directPromises = this.pubkeys.map(async pk => { return this.pollOnceForKey(pk); }); @@ -170,8 +168,6 @@ export class SwarmPolling { ): Promise> { // console.warn('Polling node: ', node.pubkey_ed25519); - const { Lodash: _ } = window; - const edkey = node.pubkey_ed25519; const pkStr = pubkey.key ? pubkey.key : pubkey; @@ -197,8 +193,6 @@ export class SwarmPolling { } private async pollOnceForKey(pubkey: PubKey) { - const { Lodash: _ } = window; - // NOTE: sometimes pubkey is string, sometimes it is object, so // accept both until this is fixed: const pk = pubkey.key ? pubkey.key : pubkey;