update models to TS part2

pull/1495/head
Audric Ackermann 4 years ago
parent 65ed81e980
commit b76ce0f2ff
No known key found for this signature in database
GPG Key ID: 999F434D76324AD4

@ -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)"

@ -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"

@ -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"

@ -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');

@ -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,
});
}

@ -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',
});

@ -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 (

@ -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(

@ -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(

@ -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',

@ -767,8 +767,7 @@ class MessageInner extends React.PureComponent<MessageRegularProps, State> {
const regex = new RegExp(`@${PubKey.regexForPubkeys}`, 'g');
const mentions = (text ? text.match(regex) : []) as Array<string>;
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;

@ -96,14 +96,14 @@ export const MessageMetadata = (props: Props) => {
theme={theme}
/>
) : (
<Timestamp
timestamp={serverTimestamp || timestamp}
extended={true}
withImageNoCaption={withImageNoCaption}
isConversationListItem={false}
theme={theme}
/>
)}
<Timestamp
timestamp={serverTimestamp || timestamp}
extended={true}
withImageNoCaption={withImageNoCaption}
isConversationListItem={false}
theme={theme}
/>
)}
<MetadataBadges
direction={direction}
isPublic={isPublic}

@ -1,6 +1,7 @@
import React from 'react';
import { Provider } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getMessageById } from '../../../js/modules/data';
import { MessageModel } from '../../models/message';
import { getMessageQueue } from '../../session';
import { ConversationController } from '../../session/conversations';
@ -13,6 +14,7 @@ import { actions as conversationActions } from '../../state/ducks/conversations'
import { actions as userActions } from '../../state/ducks/user';
import { SmartLeftPane } from '../../state/smart/LeftPane';
import { SmartSessionConversation } from '../../state/smart/SessionConversation';
import { makeLookup } from '../../util';
import {
SessionSettingCategory,
SmartSettingsView,
@ -116,10 +118,21 @@ export class SessionInboxView extends React.Component<Props, State> {
}
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<Props, State> {
(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'),

@ -375,7 +375,6 @@ export class SessionCompositionBox extends React.Component<Props, State> {
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<Props, State> {
}
// 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;

@ -428,7 +428,7 @@ export class ConversationModel extends Backbone.Model<ConversationAttributes> {
serverId: any,
serverTimestamp: any
) {
const registeredMessage = window.getMessageController().get(identifier);
const registeredMessage = MessageController.getInstance().get(identifier);
if (!registeredMessage || !registeredMessage.message) {
return null;

@ -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

@ -41,7 +41,6 @@ export async function onError(ev: any) {
messageModel: message,
});
if (ev.confirm) {
ev.confirm();
}

@ -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<void> {
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');

@ -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) {

@ -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,

@ -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);

@ -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({

@ -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 => {

@ -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'));
}

@ -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;
}

3
ts/window.d.ts vendored

@ -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;

Loading…
Cancel
Save