From b76ce0f2ff928202dd8f6d47f9cf4e8d30321c75 Mon Sep 17 00:00:00 2001 From: Audric Ackermann Date: Mon, 8 Feb 2021 16:18:36 +1100 Subject: [PATCH] update models to TS part2 --- _locales/en/messages.json | 4 --- _locales/fr/messages.json | 4 --- _locales/ru/messages.json | 4 --- js/modules/attachment_downloads.js | 2 +- js/modules/backup.js | 2 +- libtextsecure/account_manager.js | 2 +- preload.js | 14 ++++----- test/backup_test.js | 2 +- test/fixtures.js | 2 +- test/models/conversations_test.js | 14 ++++----- ts/components/conversation/Message.tsx | 3 +- .../conversation/message/MessageMetadata.tsx | 16 +++++----- ts/components/session/SessionInboxView.tsx | 31 +++++++++++-------- .../conversation/SessionCompositionBox.tsx | 5 --- ts/models/conversation.ts | 2 +- ts/receiver/closedGroups.ts | 3 +- ts/receiver/errors.ts | 1 - ts/receiver/queuedJob.ts | 20 ++++++------ ts/receiver/receiver.ts | 2 +- ts/session/constants.ts | 1 - ts/session/conversations/index.ts | 4 +-- ts/session/group/index.ts | 16 ++++++---- ts/session/messages/MessageController.ts | 4 ++- ts/session/utils/Toast.tsx | 4 --- ts/session/utils/User.ts | 4 +-- ts/window.d.ts | 3 +- 26 files changed, 76 insertions(+), 93 deletions(-) diff --git a/_locales/en/messages.json b/_locales/en/messages.json index d008c8873..eb3da2a75 100644 --- a/_locales/en/messages.json +++ b/_locales/en/messages.json @@ -1251,10 +1251,6 @@ "message": "MMM D", "description": "Timestamp format string for displaying month and day (but not the year) of a date within the current year, ex: use 'MMM D' for 'Aug 8', or 'D MMM' for '8 Aug'." }, - "messageBodyTooLong": { - "message": "Message body is too long.", - "description": "Shown if the user tries to send more than MAX_MESSAGE_BODY_LENGTH chars" - }, "messageBodyMissing": { "message": "Please enter a message body.", "description": "Shown if the user tries to send an empty message (and no attachments)" diff --git a/_locales/fr/messages.json b/_locales/fr/messages.json index 1b68565be..b31f5bf75 100644 --- a/_locales/fr/messages.json +++ b/_locales/fr/messages.json @@ -1519,10 +1519,6 @@ "message": "Votre horloge est désynchronisée. Merci de mettre à jour votre horloge et de réessayer.", "description": "Notifcation that user's clock is out of sync with Loki's servers." }, - "messageBodyTooLong": { - "message": "Corps de message trop long.", - "description": "Shown if the user tries to send more than 64kb of text" - }, "changeNickname": { "message": "Changer le surnom", "description": "Conversation menu option to change user nickname" diff --git a/_locales/ru/messages.json b/_locales/ru/messages.json index 06233c395..d44d669ff 100644 --- a/_locales/ru/messages.json +++ b/_locales/ru/messages.json @@ -1519,10 +1519,6 @@ "message": "Your clock is out of sync. Please update your clock and try again.", "description": "Notifcation that user's clock is out of sync with Loki's servers." }, - "messageBodyTooLong": { - "message": "Message body is too long.", - "description": "Shown if the user tries to send more than 64kb of text" - }, "changeNickname": { "message": "Change Nickname", "description": "Conversation menu option to change user nickname" diff --git a/js/modules/attachment_downloads.js b/js/modules/attachment_downloads.js index 88a38de38..a0ece355a 100644 --- a/js/modules/attachment_downloads.js +++ b/js/modules/attachment_downloads.js @@ -1,4 +1,4 @@ -/* global Whisper, Signal, setTimeout, clearTimeout, getMessageController, NewReceiver */ +/* global Signal, setTimeout, clearTimeout, getMessageController, NewReceiver */ const { isNumber, omit } = require('lodash'); const getGuid = require('uuid/v4'); diff --git a/js/modules/backup.js b/js/modules/backup.js index 0675978dd..833e80f91 100644 --- a/js/modules/backup.js +++ b/js/modules/backup.js @@ -198,7 +198,7 @@ async function importConversationsFromJSON(conversations, options) { ); // eslint-disable-next-line no-await-in-loop await window.Signal.Data.saveConversation(migrated, { - Conversation: Whisper.Conversation, + Conversation: window.Wh, }); } diff --git a/libtextsecure/account_manager.js b/libtextsecure/account_manager.js index ee94a13ad..c6d699f4e 100644 --- a/libtextsecure/account_manager.js +++ b/libtextsecure/account_manager.js @@ -170,7 +170,7 @@ this.dispatchEvent(new Event('registration')); }, validatePubKeyHex(pubKey) { - const c = new Whisper.Conversation({ + const c = new window.models.Conversation({ id: pubKey, type: 'private', }); diff --git a/preload.js b/preload.js index 6224bfd2c..60b87b9f2 100644 --- a/preload.js +++ b/preload.js @@ -85,7 +85,7 @@ window.isBeforeVersion = (toCheck, baseVersion) => { }; // eslint-disable-next-line func-names -window.CONSTANTS = new (function () { +window.CONSTANTS = new (function() { this.MAX_LOGIN_TRIES = 3; this.MAX_PASSWORD_LENGTH = 64; this.MAX_USERNAME_LENGTH = 20; @@ -183,9 +183,6 @@ window.setPassword = (passPhrase, oldPhrase) => window.libsession = require('./ts/session'); -window.getMessageController = - window.libsession.Messages.MessageController.getInstance; - window.getConversationController = window.libsession.Conversations.ConversationController.getInstance; @@ -382,7 +379,7 @@ window.callWorker = (fnName, ...args) => utilWorker.callWorker(fnName, ...args); // Linux seems to periodically let the event loop stop, so this is a global workaround setInterval(() => { - window.nodeSetImmediate(() => { }); + window.nodeSetImmediate(() => {}); }, 1000); const { autoOrientImage } = require('./js/modules/auto_orient_image'); @@ -408,6 +405,8 @@ window.i18n = i18n.setup(locale, localeMessages); // moment does not support es-419 correctly (and cause white screen on app start) const localeForMoment = locale === 'es-419' ? 'es' : locale; +window.moment = require('moment'); + window.moment.updateLocale(localeForMoment, { relativeTime: { s: window.i18n('timestamp_s'), @@ -458,11 +457,10 @@ if (process.env.USE_STUBBED_NETWORK) { window.SwarmPolling = new SwarmPolling(); } - // eslint-disable-next-line no-extend-native,func-names -Promise.prototype.ignore = function () { +Promise.prototype.ignore = function() { // eslint-disable-next-line more/no-then - this.then(() => { }); + this.then(() => {}); }; if ( diff --git a/test/backup_test.js b/test/backup_test.js index 346d5d499..97d8eeff5 100644 --- a/test/backup_test.js +++ b/test/backup_test.js @@ -513,7 +513,7 @@ describe('Backup', () => { }; console.log({ conversation }); await window.Signal.Data.saveConversation(conversation, { - Conversation: Whisper.Conversation, + Conversation: window.models.Conversation.ConversationModel, }); console.log( diff --git a/test/fixtures.js b/test/fixtures.js index 1a0cd8162..fef03d72e 100644 --- a/test/fixtures.js +++ b/test/fixtures.js @@ -235,7 +235,7 @@ Whisper.Fixtures = () => { Promise.all( this.map(async (convo) => { await window.Signal.Data.saveConversation(convo.attributes, { - Conversation: Whisper.Conversation, + Conversation: window.models.Conversation.ConversationModel, }); await Promise.all( diff --git a/test/models/conversations_test.js b/test/models/conversations_test.js index be5e7a41f..203c47749 100644 --- a/test/models/conversations_test.js +++ b/test/models/conversations_test.js @@ -30,7 +30,7 @@ describe('ConversationCollection', () => { // before(async () => { // const convo = new window.models.Conversation.ConversationCollection().add(attributes); // await window.Signal.Data.saveConversation(convo.attributes, { - // Conversation: Whisper.Conversation, + // Conversation: window.models.Conversation.ConversationModel, // }); // // const message = convo.messageCollection.add({ // // body: 'hello world', @@ -88,12 +88,12 @@ describe('ConversationCollection', () => { // }); // describe('when set to private', () => { // it('correctly validates hex numbers', () => { - // const regularId = new Whisper.Conversation({ + // const regularId = new window.models.Conversation.ConversationModel({ // type: 'private', // id: // '051d11d01e56d9bfc3d74115c33225a632321b509ac17a13fdeac71165d09b94ab', // }); - // const invalidId = new Whisper.Conversation({ + // const invalidId = new window.models.Conversation.ConversationModel({ // type: 'private', // id: // 'j71d11d01e56d9bfc3d74115c33225a632321b509ac17a13fdeac71165d09b94ab', @@ -102,20 +102,20 @@ describe('ConversationCollection', () => { // assert.notOk(invalidId.isValid()); // }); // it('correctly validates length', () => { - // const regularId33 = new Whisper.Conversation({ + // const regularId33 = new window.models.Conversation.ConversationModel({ // type: 'private', // id: // '051d11d01e56d9bfc3d74115c33225a632321b509ac17a13fdeac71165d09b94ab', // }); - // const regularId32 = new Whisper.Conversation({ + // const regularId32 = new window.models.Conversation.ConversationModel({ // type: 'private', // id: '1d11d01e56d9bfc3d74115c33225a632321b509ac17a13fdeac71165d09b94ab', // }); - // const shortId = new Whisper.Conversation({ + // const shortId = new window.models.Conversation.ConversationModel({ // type: 'private', // id: '771d11d', // }); - // const longId = new Whisper.Conversation({ + // const longId = new window.models.Conversation.ConversationModel({ // type: 'private', // id: // '771d11d01e56d9bfc3d74115c33225a632321b509ac17a13fdeac71165d09b94abaa', diff --git a/ts/components/conversation/Message.tsx b/ts/components/conversation/Message.tsx index ebe031946..81c41f9c8 100644 --- a/ts/components/conversation/Message.tsx +++ b/ts/components/conversation/Message.tsx @@ -767,8 +767,7 @@ class MessageInner extends React.PureComponent { const regex = new RegExp(`@${PubKey.regexForPubkeys}`, 'g'); const mentions = (text ? text.match(regex) : []) as Array; const mentionMe = - mentions && - mentions.some(m => m.slice(1) === UserUtils.getOurPubKeyStrFromCache()); + mentions && mentions.some(m => UserUtils.isUsFromCache(m.slice(1))); const isIncoming = direction === 'incoming'; const shouldHightlight = mentionMe && isIncoming && isPublic; diff --git a/ts/components/conversation/message/MessageMetadata.tsx b/ts/components/conversation/message/MessageMetadata.tsx index ea1f62e7a..f11b87b06 100644 --- a/ts/components/conversation/message/MessageMetadata.tsx +++ b/ts/components/conversation/message/MessageMetadata.tsx @@ -96,14 +96,14 @@ export const MessageMetadata = (props: Props) => { theme={theme} /> ) : ( - - )} + + )} { } private async fetchHandleMessageSentData(m: RawMessage | OpenGroupMessage) { - const msg = window.getMessageController().get(m.identifier); + // if a message was sent and this message was created after the last app restart, + // this message is still in memory in the MessageController + const msg = MessageController.getInstance().get(m.identifier); if (!msg || !msg.message) { - return null; + // otherwise, look for it in the database + // nobody is listening to this freshly fetched message .trigger calls + const dbMessage = await getMessageById(m.identifier, { + Message: MessageModel, + }); + + if (!dbMessage) { + return null; + } + return { msg: dbMessage }; } return { msg: msg.message }; @@ -158,23 +171,15 @@ export class SessionInboxView extends React.Component { (conversation: any) => conversation.cachedProps ); - const filledConversations = conversations.map(async (conv: any) => { - const messages = await MessageController.getInstance().getMessagesByKeyFromDb( - conv.id - ); - return { ...conv, messages }; + const filledConversations = conversations.map((conv: any) => { + return { ...conv, messages: [] }; }); const fullFilledConversations = await Promise.all(filledConversations); - console.warn('fullFilledConversations', fullFilledConversations); - const initialState = { conversations: { - conversationLookup: window.Signal.Util.makeLookup( - fullFilledConversations, - 'id' - ), + conversationLookup: makeLookup(fullFilledConversations, 'id'), }, user: { ourPrimary: window.storage.get('primaryDevicePubKey'), diff --git a/ts/components/session/conversation/SessionCompositionBox.tsx b/ts/components/session/conversation/SessionCompositionBox.tsx index 71ee59a1d..fb3b723c5 100644 --- a/ts/components/session/conversation/SessionCompositionBox.tsx +++ b/ts/components/session/conversation/SessionCompositionBox.tsx @@ -375,7 +375,6 @@ export class SessionCompositionBox extends React.Component { spellCheck={true} inputRef={this.textarea} disabled={!typingEnabled} - // maxLength={Constants.CONVERSATION.MAX_MESSAGE_BODY_LENGTH} rows={1} style={sendMessageStyle} suggestionsPortalHost={this.container} @@ -827,10 +826,6 @@ export class SessionCompositionBox extends React.Component { } // Verify message length const msgLen = messagePlaintext?.length || 0; - // if (msgLen > Constants.CONVERSATION.MAX_MESSAGE_BODY_LENGTH) { - // ToastUtils.pushMessageBodyTooLong(); - // return; - // } if (msgLen === 0 && this.props.stagedAttachments?.length === 0) { ToastUtils.pushMessageBodyMissing(); return; diff --git a/ts/models/conversation.ts b/ts/models/conversation.ts index 0b19c2638..46bb00d23 100644 --- a/ts/models/conversation.ts +++ b/ts/models/conversation.ts @@ -428,7 +428,7 @@ export class ConversationModel extends Backbone.Model { serverId: any, serverTimestamp: any ) { - const registeredMessage = window.getMessageController().get(identifier); + const registeredMessage = MessageController.getInstance().get(identifier); if (!registeredMessage || !registeredMessage.message) { return null; diff --git a/ts/receiver/closedGroups.ts b/ts/receiver/closedGroups.ts index 2ba001321..60a29d636 100644 --- a/ts/receiver/closedGroups.ts +++ b/ts/receiver/closedGroups.ts @@ -22,6 +22,7 @@ import { ECKeyPair } from './keypairs'; import { UserUtils } from '../session/utils'; import { ConversationModel } from '../models/conversation'; import _ from 'lodash'; +import { MessageController } from '../session/messages'; export async function handleClosedGroupControlMessage( envelope: EnvelopePlus, @@ -733,7 +734,7 @@ export async function createClosedGroup( groupDiff, 'outgoing' ); - window.getMessageController().register(dbMessage.id, dbMessage); + MessageController.getInstance().register(dbMessage.id, dbMessage); // be sure to call this before sending the message. // the sending pipeline needs to know from GroupUtils when a message is for a medium group diff --git a/ts/receiver/errors.ts b/ts/receiver/errors.ts index dc51bf4b9..63515a689 100644 --- a/ts/receiver/errors.ts +++ b/ts/receiver/errors.ts @@ -41,7 +41,6 @@ export async function onError(ev: any) { messageModel: message, }); - if (ev.confirm) { ev.confirm(); } diff --git a/ts/receiver/queuedJob.ts b/ts/receiver/queuedJob.ts index 8b04e3f1a..2e3e166d9 100644 --- a/ts/receiver/queuedJob.ts +++ b/ts/receiver/queuedJob.ts @@ -8,6 +8,8 @@ import { StringUtils, UserUtils } from '../session/utils'; import { ConversationController } from '../session/conversations'; import { ConversationModel } from '../models/conversation'; import { MessageCollection, MessageModel } from '../models/message'; +import { MessageController } from '../session/messages'; +import { getMessageById } from '../../js/modules/data'; async function handleGroups( conversation: ConversationModel, @@ -87,7 +89,6 @@ async function copyFromQuotedMessage( quote: Quote, attemptCount: number = 1 ): Promise { - const { Whisper, getMessageController } = window; const { upgradeMessageSchema } = window.Signal.Migrations; const { Message: TypedMessage, Errors } = window.Signal.Types; @@ -129,7 +130,10 @@ async function copyFromQuotedMessage( window.log.info(`Found quoted message id: ${id}`); quote.referencedMessageNotFound = false; - const queryMessage = getMessageController().register(found.id, found); + const queryMessage = MessageController.getInstance().register( + found.id, + found + ); quote.text = queryMessage.get('body') || ''; if (attemptCount > 1) { @@ -526,14 +530,13 @@ export async function handleMessageJob( ourNumber ); } - const { Whisper, getMessageController } = window; const id = await message.commit(); message.set({ id }); window.Whisper.events.trigger('messageAdded', { conversationKey: conversation.id, messageModel: message, }); - getMessageController().register(message.id, message); + MessageController.getInstance().register(message.id, message); // Note that this can save the message again, if jobs were queued. We need to // call it after we have an id for this message, because the jobs refer back @@ -551,12 +554,9 @@ export async function handleMessageJob( // We go to the database here because, between the message save above and // the previous line's trigger() call, we might have marked all messages // unread in the database. This message might already be read! - const fetched = await window.Signal.Data.getMessageById( - message.get('id'), - { - Message: MessageModel, - } - ); + const fetched = await getMessageById(message.get('id'), { + Message: MessageModel, + }); const previousUnread = message.get('unread'); diff --git a/ts/receiver/receiver.ts b/ts/receiver/receiver.ts index ef2b90af6..a2ef5ecee 100644 --- a/ts/receiver/receiver.ts +++ b/ts/receiver/receiver.ts @@ -111,7 +111,7 @@ async function handleRequestDetail( // The message is for a medium size group if (options.conversationId) { - const ourNumber = textsecure.storage.user.getNumber(); + const ourNumber = UserUtils.getOurPubKeyStrFromCache(); const senderIdentity = envelope.source; if (senderIdentity === ourNumber) { diff --git a/ts/session/constants.ts b/ts/session/constants.ts index 06c57392b..9a0b53daa 100644 --- a/ts/session/constants.ts +++ b/ts/session/constants.ts @@ -9,7 +9,6 @@ export const TTL_DEFAULT = { // User Interface export const CONVERSATION = { - // MAX_MESSAGE_BODY_LENGTH: 2000, DEFAULT_MEDIA_FETCH_COUNT: 50, DEFAULT_DOCUMENTS_FETCH_COUNT: 150, DEFAULT_MESSAGE_FETCH_COUNT: 30, diff --git a/ts/session/conversations/index.ts b/ts/session/conversations/index.ts index 6830585b7..6694847e4 100644 --- a/ts/session/conversations/index.ts +++ b/ts/session/conversations/index.ts @@ -101,7 +101,7 @@ export class ConversationController { try { await window.Signal.Data.saveConversation(conversation.attributes, { - Conversation: window.Whisper.Conversation, + Conversation: ConversationModel, }); } catch (error) { window.log.error( @@ -229,7 +229,7 @@ export class ConversationController { await conversation.destroyMessages(); await window.Signal.Data.removeConversation(id, { - Conversation: window.Whisper.Conversation, + Conversation: ConversationModel, }); conversation.off('change', this.updateReduxConvoChanged); this.conversations.remove(conversation); diff --git a/ts/session/group/index.ts b/ts/session/group/index.ts index 8a2c76565..8867961ef 100644 --- a/ts/session/group/index.ts +++ b/ts/session/group/index.ts @@ -26,6 +26,7 @@ import { import { ConversationModel } from '../../models/conversation'; import { MessageModel } from '../../models/message'; import { MessageModelType } from '../../models/messageType'; +import { MessageController } from '../messages'; export interface GroupInfo { id: string; @@ -100,6 +101,8 @@ export async function initiateGroupUpdate( throw new Error('Legacy group are not supported anymore.'); } + // do not give an admins field here. We don't want to be able to update admins and + // updateOrCreateClosedGroup() will update them if given the choice. const groupDetails = { id: groupId, name: groupName, @@ -128,7 +131,7 @@ export async function initiateGroupUpdate( nameOnlyDiff, 'outgoing' ); - window.getMessageController().register(dbMessageName.id, dbMessageName); + MessageController.getInstance().register(dbMessageName.id, dbMessageName); await sendNewName(convo, diff.newName, dbMessageName.id); } @@ -139,7 +142,7 @@ export async function initiateGroupUpdate( joiningOnlyDiff, 'outgoing' ); - window.getMessageController().register(dbMessageAdded.id, dbMessageAdded); + MessageController.getInstance().register(dbMessageAdded.id, dbMessageAdded); await sendAddedMembers( convo, diff.joiningMembers, @@ -155,9 +158,10 @@ export async function initiateGroupUpdate( leavingOnlyDiff, 'outgoing' ); - window - .getMessageController() - .register(dbMessageLeaving.id, dbMessageLeaving); + MessageController.getInstance().register( + dbMessageLeaving.id, + dbMessageLeaving + ); const stillMembers = members; await sendRemovedMembers( convo, @@ -345,7 +349,7 @@ export async function leaveClosedGroup(groupId: string) { received_at: now, expireTimer: 0, }); - window.getMessageController().register(dbMessage.id, dbMessage); + MessageController.getInstance().register(dbMessage.id, dbMessage); const existingExpireTimer = convo.get('expireTimer') || 0; // Send the update to the group const ourLeavingMessage = new ClosedGroupMemberLeftMessage({ diff --git a/ts/session/messages/MessageController.ts b/ts/session/messages/MessageController.ts index b9ca30491..0aa6c9031 100644 --- a/ts/session/messages/MessageController.ts +++ b/ts/session/messages/MessageController.ts @@ -51,7 +51,9 @@ export class MessageController { } public cleanup() { - window.log.warn('Cleaning up getMessageController() oldest messages...'); + window.log.warn( + 'Cleaning up MessageController singleton oldest messages...' + ); const now = Date.now(); (this.messageLookup || []).forEach(messageEntry => { diff --git a/ts/session/utils/Toast.tsx b/ts/session/utils/Toast.tsx index 0ffcf7a59..50570251d 100644 --- a/ts/session/utils/Toast.tsx +++ b/ts/session/utils/Toast.tsx @@ -116,10 +116,6 @@ export function pushMaximumAttachmentsError() { pushToastError('maximumAttachments', window.i18n('maximumAttachments')); } -export function pushMessageBodyTooLong() { - pushToastError('messageBodyTooLong', window.i18n('messageBodyTooLong')); -} - export function pushMessageBodyMissing() { pushToastError('messageBodyMissing', window.i18n('messageBodyMissing')); } diff --git a/ts/session/utils/User.ts b/ts/session/utils/User.ts index ac27091b4..ab3478d7b 100644 --- a/ts/session/utils/User.ts +++ b/ts/session/utils/User.ts @@ -12,15 +12,13 @@ export type HexKeyPair = { /** * Check if this pubkey is us, using the cache. + * Throws an error if our pubkey is not set */ export function isUsFromCache(pubKey: string | PubKey | undefined): boolean { if (!pubKey) { throw new Error('pubKey is not set'); } const ourNumber = UserUtils.getOurPubKeyStrFromCache(); - if (!ourNumber) { - throw new Error('ourNumber is not set'); - } const pubKeyStr = pubKey instanceof PubKey ? pubKey.key : pubKey; return pubKeyStr === ourNumber; } diff --git a/ts/window.d.ts b/ts/window.d.ts index 637441565..afc4dafe2 100644 --- a/ts/window.d.ts +++ b/ts/window.d.ts @@ -12,7 +12,7 @@ import { LibTextsecure } from '../libtextsecure'; import { ConversationType } from '../js/modules/data'; import { RecoveryPhraseUtil } from '../libloki/modules/mnemonic'; import { ConfirmationDialogParams } from '../background'; -import { } from 'styled-components/cssprop'; +import {} from 'styled-components/cssprop'; import { ConversationControllerType } from '../js/ConversationController'; import { any } from 'underscore'; @@ -36,7 +36,6 @@ declare global { LokiFileServerAPI: any; LokiPublicChatAPI: any; LokiSnodeAPI: any; - getMessageController: () => MessageController; Session: any; Signal: SignalInterface; StringView: any;