eslintify background.js

pull/1/head
Scott Nonnenberg 7 years ago
parent 41c8dbc4f9
commit 9400d1a538

@ -1,5 +1,3 @@
/* eslint-disable */
/* global Backbone: false */ /* global Backbone: false */
/* global $: false */ /* global $: false */
@ -10,7 +8,9 @@
/* global textsecure: false */ /* global textsecure: false */
/* global Whisper: false */ /* global Whisper: false */
/* global wrapDeferred: false */ /* global wrapDeferred: false */
/* global _: false */
// eslint-disable-next-line func-names
(async function() { (async function() {
'use strict'; 'use strict';
@ -22,54 +22,52 @@
// Implicitly used in `indexeddb-backbonejs-adapter`: // Implicitly used in `indexeddb-backbonejs-adapter`:
// https://github.com/signalapp/Signal-Desktop/blob/4033a9f8137e62ed286170ed5d4941982b1d3a64/components/indexeddb-backbonejs-adapter/backbone-indexeddb.js#L569 // https://github.com/signalapp/Signal-Desktop/blob/4033a9f8137e62ed286170ed5d4941982b1d3a64/components/indexeddb-backbonejs-adapter/backbone-indexeddb.js#L569
window.onInvalidStateError = function(e) { window.onInvalidStateError = e => console.log(e);
console.log(e);
};
console.log('background page reloaded'); console.log('background page reloaded');
console.log('environment:', window.config.environment); console.log('environment:', window.config.environment);
var initialLoadComplete = false; let initialLoadComplete = false;
window.owsDesktopApp = {}; window.owsDesktopApp = {};
var title = window.config.name; let title = window.config.name;
if (window.config.environment !== 'production') { if (window.config.environment !== 'production') {
title += ' - ' + window.config.environment; title += ` - ${window.config.environment}`;
} }
if (window.config.appInstance) { if (window.config.appInstance) {
title += ' - ' + window.config.appInstance; title += ` - ${window.config.appInstance}`;
} }
window.config.title = window.document.title = title; window.config.title = title;
window.document.title = title;
// start a background worker for ecc // start a background worker for ecc
textsecure.startWorker('js/libsignal-protocol-worker.js'); textsecure.startWorker('js/libsignal-protocol-worker.js');
Whisper.KeyChangeListener.init(textsecure.storage.protocol); Whisper.KeyChangeListener.init(textsecure.storage.protocol);
textsecure.storage.protocol.on('removePreKey', function() { textsecure.storage.protocol.on('removePreKey', () => {
getAccountManager().refreshPreKeys(); getAccountManager().refreshPreKeys();
}); });
var SERVER_URL = window.config.serverUrl; const SERVER_URL = window.config.serverUrl;
var CDN_URL = window.config.cdnUrl; const CDN_URL = window.config.cdnUrl;
var messageReceiver; let messageReceiver;
window.getSocketStatus = function() { window.getSocketStatus = () => {
if (messageReceiver) { if (messageReceiver) {
return messageReceiver.getStatus(); return messageReceiver.getStatus();
} else {
return -1;
} }
return -1;
}; };
Whisper.events = _.clone(Backbone.Events); Whisper.events = _.clone(Backbone.Events);
var accountManager; let accountManager;
window.getAccountManager = function() { window.getAccountManager = () => {
if (!accountManager) { if (!accountManager) {
var USERNAME = storage.get('number_id'); const USERNAME = storage.get('number_id');
var PASSWORD = storage.get('password'); const PASSWORD = storage.get('password');
accountManager = new textsecure.AccountManager( accountManager = new textsecure.AccountManager(
SERVER_URL, SERVER_URL,
USERNAME, USERNAME,
PASSWORD PASSWORD
); );
accountManager.addEventListener('registration', function() { accountManager.addEventListener('registration', () => {
Whisper.Registration.markDone(); Whisper.Registration.markDone();
console.log('dispatching registration event'); console.log('dispatching registration event');
Whisper.events.trigger('registration_done'); Whisper.events.trigger('registration_done');
@ -78,7 +76,6 @@
return accountManager; return accountManager;
}; };
/* eslint-enable */
const cancelInitializationMessage = Views.Initialization.setMessage(); const cancelInitializationMessage = Views.Initialization.setMessage();
console.log('Start IndexedDB migrations'); console.log('Start IndexedDB migrations');
@ -125,57 +122,57 @@
idleDetector.stop(); idleDetector.stop();
} }
}); });
/* eslint-disable */
// We need this 'first' check because we don't want to start the app up any other time // We need this 'first' check because we don't want to start the app up any other time
// than the first time. And storage.fetch() will cause onready() to fire. // than the first time. And storage.fetch() will cause onready() to fire.
var first = true; let first = true;
storage.onready(function() { storage.onready(async () => {
if (!first) { if (!first) {
return; return;
} }
first = false; first = false;
ConversationController.load().then(start, start); try {
await ConversationController.load();
} finally {
start();
}
}); });
Whisper.events.on('shutdown', function() { Whisper.events.on('shutdown', async () => {
idleDetector.stop(); idleDetector.stop();
if (messageReceiver) { if (messageReceiver) {
messageReceiver.close().then(function() { await messageReceiver.close();
Whisper.events.trigger('shutdown-complete');
});
} else {
Whisper.events.trigger('shutdown-complete');
} }
Whisper.events.trigger('shutdown-complete');
}); });
Whisper.events.on('setupWithImport', function() { Whisper.events.on('setupWithImport', () => {
var appView = window.owsDesktopApp.appView; const { appView } = window.owsDesktopApp;
if (appView) { if (appView) {
appView.openImporter(); appView.openImporter();
} }
}); });
Whisper.events.on('setupAsNewDevice', function() { Whisper.events.on('setupAsNewDevice', () => {
var appView = window.owsDesktopApp.appView; const { appView } = window.owsDesktopApp;
if (appView) { if (appView) {
appView.openInstaller(); appView.openInstaller();
} }
}); });
Whisper.events.on('setupAsStandalone', function() { Whisper.events.on('setupAsStandalone', () => {
var appView = window.owsDesktopApp.appView; const { appView } = window.owsDesktopApp;
if (appView) { if (appView) {
appView.openStandalone(); appView.openStandalone();
} }
}); });
function start() { function start() {
var currentVersion = window.config.version; const currentVersion = window.config.version;
var lastVersion = storage.get('version'); const lastVersion = storage.get('version');
var newVersion = !lastVersion || currentVersion !== lastVersion; const newVersion = !lastVersion || currentVersion !== lastVersion;
storage.put('version', currentVersion); storage.put('version', currentVersion);
if (newVersion) { if (newVersion) {
@ -185,16 +182,17 @@
window.dispatchEvent(new Event('storage_ready')); window.dispatchEvent(new Event('storage_ready'));
console.log('listening for registration events'); console.log('listening for registration events');
Whisper.events.on('registration_done', function() { Whisper.events.on('registration_done', () => {
console.log('handling registration event'); console.log('handling registration event');
Whisper.RotateSignedPreKeyListener.init(Whisper.events, newVersion); Whisper.RotateSignedPreKeyListener.init(Whisper.events, newVersion);
connect(true); connect(true);
}); });
cancelInitializationMessage(); cancelInitializationMessage();
var appView = (window.owsDesktopApp.appView = new Whisper.AppView({ const appView = new Whisper.AppView({
el: $('body'), el: $('body'),
})); });
window.owsDesktopApp.appView = appView;
Whisper.WallClockListener.init(Whisper.events); Whisper.WallClockListener.init(Whisper.events);
Whisper.ExpiringMessagesListener.init(Whisper.events); Whisper.ExpiringMessagesListener.init(Whisper.events);
@ -206,7 +204,7 @@
Whisper.RotateSignedPreKeyListener.init(Whisper.events, newVersion); Whisper.RotateSignedPreKeyListener.init(Whisper.events, newVersion);
connect(); connect();
appView.openInbox({ appView.openInbox({
initialLoadComplete: initialLoadComplete, initialLoadComplete,
}); });
} else if (window.config.importMode) { } else if (window.config.importMode) {
appView.openImporter(); appView.openImporter();
@ -214,7 +212,7 @@
appView.openInstaller(); appView.openInstaller();
} }
Whisper.events.on('showDebugLog', function() { Whisper.events.on('showDebugLog', () => {
appView.openDebugLog(); appView.openDebugLog();
}); });
Whisper.events.on('showSettings', () => { Whisper.events.on('showSettings', () => {
@ -227,13 +225,13 @@
} }
appView.inboxView.showSettings(); appView.inboxView.showSettings();
}); });
Whisper.events.on('unauthorized', function() { Whisper.events.on('unauthorized', () => {
appView.inboxView.networkStatusView.update(); appView.inboxView.networkStatusView.update();
}); });
Whisper.events.on('reconnectTimer', function() { Whisper.events.on('reconnectTimer', () => {
appView.inboxView.networkStatusView.setSocketReconnectInterval(60000); appView.inboxView.networkStatusView.setSocketReconnectInterval(60000);
}); });
Whisper.events.on('contactsync', function() { Whisper.events.on('contactsync', () => {
if (appView.installView) { if (appView.installView) {
appView.openInbox(); appView.openInbox();
} }
@ -242,39 +240,35 @@
window.addEventListener('focus', () => Whisper.Notifications.clear()); window.addEventListener('focus', () => Whisper.Notifications.clear());
window.addEventListener('unload', () => Whisper.Notifications.fastClear()); window.addEventListener('unload', () => Whisper.Notifications.fastClear());
Whisper.events.on('showConversation', function(conversation) { Whisper.events.on('showConversation', conversation => {
if (appView) { if (appView) {
appView.openConversation(conversation); appView.openConversation(conversation);
} }
}); });
Whisper.Notifications.on('click', function(conversation) { Whisper.Notifications.on('click', conversation => {
showWindow(); window.showWindow();
if (conversation) { if (conversation) {
appView.openConversation(conversation); appView.openConversation(conversation);
} else { } else {
appView.openInbox({ appView.openInbox({
initialLoadComplete: initialLoadComplete, initialLoadComplete,
}); });
} }
}); });
} }
window.getSyncRequest = function() { window.getSyncRequest = () =>
return new textsecure.SyncRequest(textsecure.messaging, messageReceiver); new textsecure.SyncRequest(textsecure.messaging, messageReceiver);
};
Whisper.events.on('start-shutdown', function() { Whisper.events.on('start-shutdown', async () => {
if (messageReceiver) { if (messageReceiver) {
messageReceiver.close().then(function() { await messageReceiver.close();
Whisper.events.trigger('shutdown-complete');
});
} else {
Whisper.events.trigger('shutdown-complete');
} }
Whisper.events.trigger('shutdown-complete');
}); });
var disconnectTimer = null; let disconnectTimer = null;
function onOffline() { function onOffline() {
console.log('offline'); console.log('offline');
@ -308,7 +302,7 @@
} }
function isSocketOnline() { function isSocketOnline() {
var socketStatus = window.getSocketStatus(); const socketStatus = window.getSocketStatus();
return ( return (
socketStatus === WebSocket.CONNECTING || socketStatus === WebSocket.OPEN socketStatus === WebSocket.CONNECTING || socketStatus === WebSocket.OPEN
); );
@ -325,7 +319,7 @@
} }
} }
var connectCount = 0; let connectCount = 0;
async function connect(firstRun) { async function connect(firstRun) {
console.log('connect'); console.log('connect');
@ -353,12 +347,12 @@
messageReceiver.close(); messageReceiver.close();
} }
var USERNAME = storage.get('number_id'); const USERNAME = storage.get('number_id');
var PASSWORD = storage.get('password'); const PASSWORD = storage.get('password');
var mySignalingKey = storage.get('signaling_key'); const mySignalingKey = storage.get('signaling_key');
connectCount += 1; connectCount += 1;
var options = { const options = {
retryCached: connectCount === 1, retryCached: connectCount === 1,
}; };
@ -395,16 +389,16 @@
// Because v0.43.2 introduced a bug that lost contact details, v0.43.4 introduces // Because v0.43.2 introduced a bug that lost contact details, v0.43.4 introduces
// a one-time contact sync to restore all lost contact/group information. We // a one-time contact sync to restore all lost contact/group information. We
// disable this checking if a user is first registering. // disable this checking if a user is first registering.
var key = 'chrome-contact-sync-v0.43.4'; const key = 'chrome-contact-sync-v0.43.4';
if (!storage.get(key)) { if (!storage.get(key)) {
storage.put(key, true); storage.put(key, true);
// eslint-disable-next-line eqeqeq
if (!firstRun && textsecure.storage.user.getDeviceId() != '1') { if (!firstRun && textsecure.storage.user.getDeviceId() != '1') {
window.getSyncRequest(); window.getSyncRequest();
} }
} }
/* eslint-enable */
const deviceId = textsecure.storage.user.getDeviceId(); const deviceId = textsecure.storage.user.getDeviceId();
const { sendRequestConfigurationSyncMessage } = textsecure.messaging; const { sendRequestConfigurationSyncMessage } = textsecure.messaging;
const status = await Signal.Startup.syncReadReceiptConfiguration({ const status = await Signal.Startup.syncReadReceiptConfiguration({
@ -455,10 +449,9 @@
idleDetector.start(); idleDetector.start();
}); });
} }
/* eslint-disable */
function onChangeTheme() { function onChangeTheme() {
var view = window.owsDesktopApp.appView; const view = window.owsDesktopApp.appView;
if (view) { if (view) {
view.applyTheme(); view.applyTheme();
} }
@ -466,8 +459,8 @@
function onEmpty() { function onEmpty() {
initialLoadComplete = true; initialLoadComplete = true;
var interval = setInterval(function() { let interval = setInterval(() => {
var view = window.owsDesktopApp.appView; const view = window.owsDesktopApp.appView;
if (view) { if (view) {
clearInterval(interval); clearInterval(interval);
interval = null; interval = null;
@ -478,9 +471,9 @@
Whisper.Notifications.enable(); Whisper.Notifications.enable();
} }
function onProgress(ev) { function onProgress(ev) {
var count = ev.count; const { count } = ev;
var view = window.owsDesktopApp.appView; const view = window.owsDesktopApp.appView;
if (view) { if (view) {
view.onProgress(count); view.onProgress(count);
} }
@ -489,10 +482,10 @@
storage.put('read-receipt-setting', ev.configuration.readReceipts); storage.put('read-receipt-setting', ev.configuration.readReceipts);
} }
function onContactReceived(ev) { async function onContactReceived(ev) {
var details = ev.contactDetails; const details = ev.contactDetails;
var id = details.number; const id = details.number;
if (id === textsecure.storage.user.getNumber()) { if (id === textsecure.storage.user.getNumber()) {
// special case for syncing details about ourselves // special case for syncing details about ourselves
@ -502,138 +495,137 @@
} }
} }
var c = new Whisper.Conversation({ const c = new Whisper.Conversation({
id: id, id,
}); });
var error = c.validateNumber(); const validationError = c.validateNumber();
if (error) { if (validationError) {
console.log('Invalid contact received:', Errors.toLogFormat(error)); console.log(
'Invalid contact received:',
Errors.toLogFormat(validationError)
);
return; return;
} }
return ConversationController.getOrCreateAndWait(id, 'private') try {
.then(function(conversation) { const conversation = await ConversationController.getOrCreateAndWait(
var activeAt = conversation.get('active_at'); id,
'private'
);
let activeAt = conversation.get('active_at');
// The idea is to make any new contact show up in the left pane. If // The idea is to make any new contact show up in the left pane. If
// activeAt is null, then this contact has been purposefully hidden. // activeAt is null, then this contact has been purposefully hidden.
if (activeAt !== null) { if (activeAt !== null) {
activeAt = activeAt || Date.now(); activeAt = activeAt || Date.now();
} }
if (details.profileKey) { if (details.profileKey) {
conversation.set({ profileKey: details.profileKey }); conversation.set({ profileKey: details.profileKey });
} }
if (typeof details.blocked !== 'undefined') { if (typeof details.blocked !== 'undefined') {
if (details.blocked) { if (details.blocked) {
storage.addBlockedNumber(id); storage.addBlockedNumber(id);
} else { } else {
storage.removeBlockedNumber(id); storage.removeBlockedNumber(id);
}
} }
}
return wrapDeferred( await wrapDeferred(
conversation.save({ conversation.save({
name: details.name, name: details.name,
avatar: details.avatar, avatar: details.avatar,
color: details.color, color: details.color,
active_at: activeAt, active_at: activeAt,
}) })
).then(function() { );
const { expireTimer } = details; const { expireTimer } = details;
const isValidExpireTimer = typeof expireTimer === 'number'; const isValidExpireTimer = typeof expireTimer === 'number';
if (!isValidExpireTimer) { if (!isValidExpireTimer) {
console.log( console.log(
'Ignore invalid expire timer.', 'Ignore invalid expire timer.',
'Expected numeric `expireTimer`, got:', 'Expected numeric `expireTimer`, got:',
expireTimer expireTimer
); );
return; return;
} }
var source = textsecure.storage.user.getNumber(); const source = textsecure.storage.user.getNumber();
var receivedAt = Date.now(); const receivedAt = Date.now();
return conversation.updateExpirationTimer(
expireTimer, await conversation.updateExpirationTimer(
source, expireTimer,
receivedAt, source,
{ fromSync: true } receivedAt,
); { fromSync: true }
}); );
})
.then(function() { if (details.verified) {
if (details.verified) { const { verified } = details;
var verified = details.verified; const verifiedEvent = new Event('verified');
var ev = new Event('verified'); verifiedEvent.verified = {
ev.verified = { state: verified.state,
state: verified.state, destination: verified.destination,
destination: verified.destination, identityKey: verified.identityKey.toArrayBuffer(),
identityKey: verified.identityKey.toArrayBuffer(), };
}; verifiedEvent.viaContactSync = true;
ev.viaContactSync = true; await onVerified(verifiedEvent);
return onVerified(ev); }
}
}) ev.confirm();
.then(ev.confirm) } catch (error) {
.catch(function(error) { console.log('onContactReceived error:', Errors.toLogFormat(error));
console.log('onContactReceived error:', Errors.toLogFormat(error)); }
});
} }
function onGroupReceived(ev) { async function onGroupReceived(ev) {
var details = ev.groupDetails; const details = ev.groupDetails;
var id = details.id; const { id } = details;
return ConversationController.getOrCreateAndWait(id, 'group').then(function( const conversation = await ConversationController.getOrCreateAndWait(
conversation id,
) { 'group'
var updates = { );
name: details.name, const updates = {
members: details.members, name: details.name,
avatar: details.avatar, members: details.members,
type: 'group', avatar: details.avatar,
}; type: 'group',
if (details.active) { };
var activeAt = conversation.get('active_at'); if (details.active) {
const activeAt = conversation.get('active_at');
// The idea is to make any new group show up in the left pane. If // The idea is to make any new group show up in the left pane. If
// activeAt is null, then this group has been purposefully hidden. // activeAt is null, then this group has been purposefully hidden.
if (activeAt !== null) { if (activeAt !== null) {
updates.active_at = activeAt || Date.now(); updates.active_at = activeAt || Date.now();
}
updates.left = false;
} else {
updates.left = true;
} }
updates.left = false;
} else {
updates.left = true;
}
return wrapDeferred(conversation.save(updates)) await wrapDeferred(conversation.save(updates));
.then(function() { const { expireTimer } = details;
const { expireTimer } = details; const isValidExpireTimer = typeof expireTimer === 'number';
const isValidExpireTimer = typeof expireTimer === 'number'; if (!isValidExpireTimer) {
if (!isValidExpireTimer) { console.log(
console.log( 'Ignore invalid expire timer.',
'Ignore invalid expire timer.', 'Expected numeric `expireTimer`, got:',
'Expected numeric `expireTimer`, got:', expireTimer
expireTimer );
); return;
return; }
}
const source = textsecure.storage.user.getNumber();
var source = textsecure.storage.user.getNumber(); const receivedAt = Date.now();
var receivedAt = Date.now(); await conversation.updateExpirationTimer(expireTimer, source, receivedAt, {
return conversation.updateExpirationTimer( fromSync: true,
expireTimer,
source,
receivedAt,
{ fromSync: true }
);
})
.then(ev.confirm);
}); });
}
/* eslint-enable */ ev.confirm();
}
// Descriptors // Descriptors
const getGroupDescriptor = group => ({ const getGroupDescriptor = group => ({
@ -741,12 +733,11 @@
getMessageDescriptor: getDescriptorForSent, getMessageDescriptor: getDescriptorForSent,
createMessage: createSentMessage, createMessage: createSentMessage,
}); });
/* eslint-disable */
function isMessageDuplicate(message) { function isMessageDuplicate(message) {
return new Promise(function(resolve) { return new Promise(resolve => {
var fetcher = new Whisper.Message(); const fetcher = new Whisper.Message();
var options = { const options = {
index: { index: {
name: 'unique', name: 'unique',
value: [ value: [
@ -757,21 +748,21 @@
}, },
}; };
fetcher.fetch(options).always(function() { fetcher.fetch(options).always(() => {
if (fetcher.get('id')) { if (fetcher.get('id')) {
return resolve(true); return resolve(true);
} }
return resolve(false); return resolve(false);
}); });
}).catch(function(error) { }).catch(error => {
console.log('isMessageDuplicate error:', Errors.toLogFormat(error)); console.log('isMessageDuplicate error:', Errors.toLogFormat(error));
return false; return false;
}); });
} }
function initIncomingMessage(data) { function initIncomingMessage(data) {
var message = new Whisper.Message({ const message = new Whisper.Message({
source: data.source, source: data.source,
sourceDevice: data.sourceDevice, sourceDevice: data.sourceDevice,
sent_at: data.timestamp, sent_at: data.timestamp,
@ -784,13 +775,13 @@
return message; return message;
} }
function onError(ev) { async function onError(ev) {
var error = ev.error; const { error } = ev;
console.log('background onError:', Errors.toLogFormat(error)); console.log('background onError:', Errors.toLogFormat(error));
if ( if (
error.name === 'HTTPError' && error.name === 'HTTPError' &&
(error.code == 401 || error.code == 403) (error.code === 401 || error.code === 403)
) { ) {
Whisper.events.trigger('unauthorized'); Whisper.events.trigger('unauthorized');
@ -798,28 +789,26 @@
'Client is no longer authorized; deleting local configuration' 'Client is no longer authorized; deleting local configuration'
); );
Whisper.Registration.remove(); Whisper.Registration.remove();
var previousNumberId = textsecure.storage.get('number_id'); const previousNumberId = textsecure.storage.get('number_id');
textsecure.storage.protocol.removeAllConfiguration().then( try {
function() { await textsecure.storage.protocol.removeAllConfiguration();
// These two bits of data are important to ensure that the app loads up // These two bits of data are important to ensure that the app loads up
// the conversation list, instead of showing just the QR code screen. // the conversation list, instead of showing just the QR code screen.
Whisper.Registration.markEverDone(); Whisper.Registration.markEverDone();
textsecure.storage.put('number_id', previousNumberId); textsecure.storage.put('number_id', previousNumberId);
console.log('Successfully cleared local configuration'); console.log('Successfully cleared local configuration');
}, } catch (eraseError) {
function(error) { console.log(
console.log( 'Something went wrong clearing local configuration',
'Something went wrong clearing local configuration', eraseError && eraseError.stack ? eraseError.stack : eraseError
error && error.stack ? error.stack : error );
); }
}
);
return; return;
} }
if (error.name === 'HTTPError' && error.code == -1) { if (error.name === 'HTTPError' && error.code === -1) {
// Failed to connect to server // Failed to connect to server
if (navigator.onLine) { if (navigator.onLine) {
console.log('retrying in 1 minute'); console.log('retrying in 1 minute');
@ -839,59 +828,53 @@
// because the server lost our ack the first time. // because the server lost our ack the first time.
return; return;
} }
var envelope = ev.proto; const envelope = ev.proto;
var message = initIncomingMessage(envelope); const message = initIncomingMessage(envelope);
return message.saveErrors(error).then(function() { await message.saveErrors(error);
var id = message.get('conversationId'); const id = message.get('conversationId');
return ConversationController.getOrCreateAndWait(id, 'private').then( const conversation = await ConversationController.getOrCreateAndWait(
function(conversation) { id,
conversation.set({ 'private'
active_at: Date.now(), );
unreadCount: conversation.get('unreadCount') + 1, conversation.set({
}); active_at: Date.now(),
unreadCount: conversation.get('unreadCount') + 1,
var conversation_timestamp = conversation.get('timestamp');
var message_timestamp = message.get('timestamp');
if (
!conversation_timestamp ||
message_timestamp > conversation_timestamp
) {
conversation.set({ timestamp: message.get('sent_at') });
}
conversation.trigger('newmessage', message);
conversation.notify(message);
if (ev.confirm) {
ev.confirm();
}
return new Promise(function(resolve, reject) {
conversation.save().then(resolve, reject);
});
}
);
}); });
const conversationTimestamp = conversation.get('timestamp');
const messageTimestamp = message.get('timestamp');
if (!conversationTimestamp || messageTimestamp > conversationTimestamp) {
conversation.set({ timestamp: message.get('sent_at') });
}
conversation.trigger('newmessage', message);
conversation.notify(message);
if (ev.confirm) {
ev.confirm();
}
await wrapDeferred(conversation.save());
} }
throw error; throw error;
} }
function onReadReceipt(ev) { function onReadReceipt(ev) {
var read_at = ev.timestamp; const readAt = ev.timestamp;
var timestamp = ev.read.timestamp; const { timestamp } = ev.read;
var reader = ev.read.reader; const { reader } = ev.read;
console.log('read receipt', reader, timestamp); console.log('read receipt', reader, timestamp);
if (!storage.get('read-receipt-setting')) { if (!storage.get('read-receipt-setting')) {
return ev.confirm(); return ev.confirm();
} }
var receipt = Whisper.ReadReceipts.add({ const receipt = Whisper.ReadReceipts.add({
reader: reader, reader,
timestamp: timestamp, timestamp,
read_at: read_at, read_at: readAt,
}); });
receipt.on('remove', ev.confirm); receipt.on('remove', ev.confirm);
@ -901,15 +884,15 @@
} }
function onReadSync(ev) { function onReadSync(ev) {
var read_at = ev.timestamp; const readAt = ev.timestamp;
var timestamp = ev.read.timestamp; const { timestamp } = ev.read;
var sender = ev.read.sender; const { sender } = ev.read;
console.log('read sync', sender, timestamp); console.log('read sync', sender, timestamp);
var receipt = Whisper.ReadSyncs.add({ const receipt = Whisper.ReadSyncs.add({
sender: sender, sender,
timestamp: timestamp, timestamp,
read_at: read_at, read_at: readAt,
}); });
receipt.on('remove', ev.confirm); receipt.on('remove', ev.confirm);
@ -918,15 +901,15 @@
return Whisper.ReadSyncs.onReceipt(receipt); return Whisper.ReadSyncs.onReceipt(receipt);
} }
function onVerified(ev) { async function onVerified(ev) {
var number = ev.verified.destination; const number = ev.verified.destination;
var key = ev.verified.identityKey; const key = ev.verified.identityKey;
var state; let state;
var c = new Whisper.Conversation({ const c = new Whisper.Conversation({
id: number, id: number,
}); });
var error = c.validateNumber(); const error = c.validateNumber();
if (error) { if (error) {
console.log('Invalid verified sync received:', Errors.toLogFormat(error)); console.log('Invalid verified sync received:', Errors.toLogFormat(error));
return; return;
@ -942,6 +925,8 @@
case textsecure.protobuf.Verified.State.UNVERIFIED: case textsecure.protobuf.Verified.State.UNVERIFIED:
state = 'UNVERIFIED'; state = 'UNVERIFIED';
break; break;
default:
console.log(`Got unexpected verified state: ${ev.verified.state}`);
} }
console.log( console.log(
@ -951,34 +936,38 @@
ev.viaContactSync ? 'via contact sync' : '' ev.viaContactSync ? 'via contact sync' : ''
); );
return ConversationController.getOrCreateAndWait(number, 'private').then( const contact = await ConversationController.getOrCreateAndWait(
function(contact) { number,
var options = { 'private'
viaSyncMessage: true,
viaContactSync: ev.viaContactSync,
key: key,
};
if (state === 'VERIFIED') {
return contact.setVerified(options).then(ev.confirm);
} else if (state === 'DEFAULT') {
return contact.setVerifiedDefault(options).then(ev.confirm);
} else {
return contact.setUnverified(options).then(ev.confirm);
}
}
); );
const options = {
viaSyncMessage: true,
viaContactSync: ev.viaContactSync,
key,
};
if (state === 'VERIFIED') {
await contact.setVerified(options);
} else if (state === 'DEFAULT') {
await contact.setVerifiedDefault(options);
} else {
await contact.setUnverified(options);
}
if (ev.confirm) {
ev.confirm();
}
} }
function onDeliveryReceipt(ev) { function onDeliveryReceipt(ev) {
var deliveryReceipt = ev.deliveryReceipt; const { deliveryReceipt } = ev;
console.log( console.log(
'delivery receipt from', 'delivery receipt from',
deliveryReceipt.source + '.' + deliveryReceipt.sourceDevice, `${deliveryReceipt.source}.${deliveryReceipt.sourceDevice}`,
deliveryReceipt.timestamp deliveryReceipt.timestamp
); );
var receipt = Whisper.DeliveryReceipts.add({ const receipt = Whisper.DeliveryReceipts.add({
timestamp: deliveryReceipt.timestamp, timestamp: deliveryReceipt.timestamp,
source: deliveryReceipt.source, source: deliveryReceipt.source,
}); });

Loading…
Cancel
Save