signal-desktop/preload.js

506 lines
15 KiB
JavaScript
Raw Normal View History

// Copyright 2017-2021 Signal Messenger, LLC
2020-10-30 20:34:04 +00:00
// SPDX-License-Identifier: AGPL-3.0-only
/* global Whisper, window */
2018-04-03 19:03:57 +00:00
/* eslint-disable global-require, no-inner-declarations */
2018-04-03 19:03:57 +00:00
2021-04-07 22:40:12 +00:00
const preloadStartTime = Date.now();
let preloadEndTime = 0;
try {
const electron = require('electron');
const semver = require('semver');
const _ = require('lodash');
2021-08-28 13:27:38 +00:00
const { strictAssert } = require('./ts/util/assert');
const { parseIntWithFallback } = require('./ts/util/parseIntWithFallback');
2021-08-18 20:08:14 +00:00
// It is important to call this as early as possible
require('./ts/windows/context');
const {
getEnvironment,
setEnvironment,
parseEnvironment,
Environment,
} = require('./ts/environment');
const ipc = electron.ipcRenderer;
2018-04-03 19:03:57 +00:00
const { remote } = electron;
const { app } = remote;
2021-03-04 21:44:57 +00:00
window.sqlInitializer = require('./ts/sql/initialize');
const config = require('url').parse(window.location.toString(), true).query;
2019-05-16 22:32:38 +00:00
setEnvironment(parseEnvironment(config.environment));
const log = require('./ts/logging/log');
let title = config.name;
if (getEnvironment() !== Environment.Production) {
title += ` - ${getEnvironment()}`;
}
if (config.appInstance) {
title += ` - ${config.appInstance}`;
}
2019-05-16 22:32:38 +00:00
// Flags for testing
window.GV2_ENABLE_SINGLE_CHANGE_PROCESSING = true;
window.GV2_ENABLE_CHANGE_PROCESSING = true;
window.GV2_ENABLE_STATE_PROCESSING = true;
window.GV2_MIGRATION_DISABLE_ADD = false;
window.GV2_MIGRATION_DISABLE_INVITE = false;
window.RETRY_DELAY = false;
window.platform = process.platform;
window.getTitle = () => title;
2021-02-18 16:40:26 +00:00
window.getLocale = () => config.locale;
window.getEnvironment = getEnvironment;
window.getAppInstance = () => config.appInstance;
window.getVersion = () => config.version;
window.getBuildCreation = () => parseIntWithFallback(config.buildCreation, 0);
window.getExpiration = () => {
2021-08-23 22:45:11 +00:00
const sixtyDays = 60 * 86400 * 1000;
const remoteBuildExpiration = window.storage.get('remoteBuildExpiration');
2021-08-23 22:45:11 +00:00
const localBuildExpiration = window.Events.getAutoDownloadUpdate()
? config.buildExpiration
: config.buildExpiration - sixtyDays;
if (remoteBuildExpiration) {
return remoteBuildExpiration < config.buildExpiration
? remoteBuildExpiration
2021-08-23 22:45:11 +00:00
: localBuildExpiration;
}
2021-08-23 22:45:11 +00:00
return localBuildExpiration;
};
window.getNodeVersion = () => config.node_version;
window.getHostName = () => config.hostname;
window.getServerTrustRoot = () => config.serverTrustRoot;
window.getServerPublicParams = () => config.serverPublicParams;
window.getSfuUrl = () => config.sfuUrl;
window.isBehindProxy = () => Boolean(config.proxyUrl);
window.getAutoLaunch = () => app.getLoginItemSettings().openAtLogin;
window.setAutoLaunch = value => {
app.setLoginItemSettings({ openAtLogin: Boolean(value) });
};
window.isBeforeVersion = (toCheck, baseVersion) => {
try {
return semver.lt(toCheck, baseVersion);
} catch (error) {
log.error(
`isBeforeVersion error: toCheck: ${toCheck}, baseVersion: ${baseVersion}`,
error && error.stack ? error.stack : error
);
return true;
}
};
window.isAfterVersion = (toCheck, baseVersion) => {
try {
return semver.gt(toCheck, baseVersion);
} catch (error) {
log.error(
`isBeforeVersion error: toCheck: ${toCheck}, baseVersion: ${baseVersion}`,
error && error.stack ? error.stack : error
);
return true;
}
};
const localeMessages = ipc.sendSync('locale-data');
2018-04-03 19:03:57 +00:00
window.setBadgeCount = count => ipc.send('set-badge-count', count);
2018-04-03 19:03:57 +00:00
2021-04-13 23:43:56 +00:00
let connectStartTime = 0;
window.logAuthenticatedConnect = () => {
2021-04-13 23:43:56 +00:00
if (connectStartTime === 0) {
connectStartTime = Date.now();
}
};
window.logAppLoadedEvent = ({ processedCount }) =>
2021-04-07 22:40:12 +00:00
ipc.send('signal-app-loaded', {
preloadTime: preloadEndTime - preloadStartTime,
2021-04-13 23:43:56 +00:00
connectTime: connectStartTime - preloadEndTime,
processedCount,
2021-04-07 22:40:12 +00:00
});
2021-01-15 17:30:58 +00:00
// We never do these in our code, so we'll prevent it everywhere
window.open = () => null;
// eslint-disable-next-line no-eval, no-multi-assign
window.eval = global.eval = () => null;
window.drawAttention = () => {
log.info('draw attention');
ipc.send('draw-attention');
};
window.showWindow = () => {
log.info('show window');
ipc.send('show-window');
};
2018-04-03 19:03:57 +00:00
2021-02-01 20:01:25 +00:00
window.titleBarDoubleClick = () => {
ipc.send('title-bar-double-click');
};
window.setAutoHideMenuBar = autoHide =>
ipc.send('set-auto-hide-menu-bar', autoHide);
2018-04-03 19:03:57 +00:00
window.setMenuBarVisibility = visibility =>
ipc.send('set-menu-bar-visibility', visibility);
2018-04-03 19:03:57 +00:00
window.updateSystemTraySetting = (
systemTraySetting /* : Readonly<SystemTraySetting> */
) => {
ipc.send('update-system-tray-setting', systemTraySetting);
};
window.restart = () => {
log.info('restart');
ipc.send('restart');
};
2020-04-28 21:18:41 +00:00
window.shutdown = () => {
log.info('shutdown');
2020-04-28 21:18:41 +00:00
ipc.send('shutdown');
};
window.showDebugLog = () => {
log.info('showDebugLog');
ipc.send('show-debug-log');
};
2018-04-03 19:03:57 +00:00
window.closeAbout = () => ipc.send('close-about');
window.readyForUpdates = () => ipc.send('ready-for-updates');
2018-04-03 19:03:57 +00:00
window.updateTrayIcon = unreadCount =>
ipc.send('update-tray-icon', unreadCount);
2018-04-03 19:03:57 +00:00
ipc.on('additional-log-data-request', async event => {
const ourConversation = window.ConversationController.getOurConversation();
const ourCapabilities = ourConversation
? ourConversation.get('capabilities')
: undefined;
const remoteConfig = window.storage.get('remoteConfig') || {};
let statistics;
try {
statistics = await window.Signal.Data.getStatisticsForLogging();
} catch (error) {
statistics = {};
}
const ourUuid = window.textsecure.storage.user.getUuid();
event.sender.send('additional-log-data-response', {
capabilities: ourCapabilities || {},
remoteConfig: _.mapValues(remoteConfig, ({ value, enabled }) => {
const enableString = enabled ? 'enabled' : 'disabled';
const valueString = value && value !== 'TRUE' ? ` ${value}` : '';
return `${enableString}${valueString}`;
}),
statistics,
user: {
deviceId: window.textsecure.storage.user.getDeviceId(),
e164: window.textsecure.storage.user.getNumber(),
uuid: ourUuid && ourUuid.toString(),
conversationId: ourConversation && ourConversation.id,
},
});
});
ipc.on('set-up-as-new-device', () => {
Whisper.events.trigger('setupAsNewDevice');
});
2018-04-03 19:03:57 +00:00
ipc.on('set-up-as-standalone', () => {
Whisper.events.trigger('setupAsStandalone');
});
2018-04-03 19:03:57 +00:00
ipc.on('challenge:response', (_event, response) => {
Whisper.events.trigger('challengeResponse', response);
});
2021-06-09 22:28:54 +00:00
ipc.on('power-channel:suspend', () => {
Whisper.events.trigger('powerMonitorSuspend');
});
ipc.on('power-channel:resume', () => {
Whisper.events.trigger('powerMonitorResume');
});
window.sendChallengeRequest = request =>
ipc.send('challenge:request', request);
2021-02-01 20:01:25 +00:00
{
let isFullScreen = config.isFullScreen === 'true';
window.isFullScreen = () => isFullScreen;
// This is later overwritten.
window.onFullScreenChange = _.noop;
ipc.on('full-screen-change', (_event, isFull) => {
isFullScreen = Boolean(isFull);
window.onFullScreenChange(isFullScreen);
});
}
// Settings-related events
window.showSettings = () => ipc.send('show-settings');
window.showPermissionsPopup = () => ipc.send('show-permissions-popup');
2020-06-04 18:16:19 +00:00
window.showCallingPermissionsPopup = forCamera =>
ipc.invoke('show-calling-permissions-popup', forCamera);
ipc.on('show-keyboard-shortcuts', () => {
window.Events.showKeyboardShortcuts();
});
ipc.on('add-dark-overlay', () => {
window.Events.addDarkOverlay();
});
ipc.on('remove-dark-overlay', () => {
window.Events.removeDarkOverlay();
});
2018-04-03 19:03:57 +00:00
2021-08-18 20:08:14 +00:00
require('./ts/windows/preload');
2020-06-04 18:16:19 +00:00
window.getBuiltInImages = () =>
new Promise((resolve, reject) => {
ipc.once('get-success-built-in-images', (_event, error, value) => {
if (error) {
return reject(new Error(error));
}
2019-10-04 18:06:17 +00:00
return resolve(value);
});
ipc.send('get-built-in-images');
2019-10-04 18:06:17 +00:00
});
ipc.on('delete-all-data', async () => {
const { deleteAllData } = window.Events;
if (!deleteAllData) {
return;
}
try {
await deleteAllData();
} catch (error) {
log.error('delete-all-data: error', error && error.stack);
}
2019-10-04 18:06:17 +00:00
});
ipc.on('show-sticker-pack', (_event, info) => {
const { packId, packKey } = info;
const { showStickerPack } = window.Events;
if (showStickerPack) {
showStickerPack(packId, packKey);
}
});
ipc.on('show-group-via-link', (_event, info) => {
const { hash } = info;
const { showGroupViaLink } = window.Events;
if (showGroupViaLink) {
showGroupViaLink(hash);
}
});
2021-08-28 13:27:38 +00:00
ipc.on('show-conversation-via-signal.me', (_event, info) => {
const { hash } = info;
strictAssert(typeof hash === 'string', 'Got an invalid hash over IPC');
const { showConversationViaSignalDotMe } = window.Events;
if (showConversationViaSignalDotMe) {
showConversationViaSignalDotMe(hash);
}
});
ipc.on('unknown-sgnl-link', () => {
const { unknownSignalLink } = window.Events;
if (unknownSignalLink) {
unknownSignalLink();
}
});
ipc.on('install-sticker-pack', (_event, info) => {
const { packId, packKey } = info;
const { installStickerPack } = window.Events;
if (installStickerPack) {
installStickerPack(packId, packKey);
}
});
2018-04-03 19:03:57 +00:00
ipc.on('get-ready-for-shutdown', async () => {
const { shutdown } = window.Events || {};
if (!shutdown) {
log.error('preload shutdown handler: shutdown method not found');
ipc.send('now-ready-for-shutdown');
return;
}
try {
await shutdown();
ipc.send('now-ready-for-shutdown');
} catch (error) {
ipc.send(
'now-ready-for-shutdown',
error && error.stack ? error.stack : error
);
}
});
window.addSetupMenuItems = () => ipc.send('add-setup-menu-items');
window.removeSetupMenuItems = () => ipc.send('remove-setup-menu-items');
// We pull these dependencies in now, from here, because they have Node.js dependencies
2018-04-03 19:03:57 +00:00
2021-03-04 21:44:57 +00:00
require('./ts/logging/set_up_renderer_logging').initialize();
2018-04-03 19:03:57 +00:00
if (config.proxyUrl) {
log.info('Using provided proxy url');
}
2018-04-03 19:03:57 +00:00
window.nodeSetImmediate = setImmediate;
2018-04-03 19:03:57 +00:00
window.Backbone = require('backbone');
window.textsecure = require('./ts/textsecure').default;
2019-08-19 22:26:45 +00:00
window.WebAPI = window.textsecure.WebAPI.initialize({
url: config.serverUrl,
storageUrl: config.storageUrl,
2020-09-04 01:25:19 +00:00
directoryUrl: config.directoryUrl,
directoryEnclaveId: config.directoryEnclaveId,
directoryTrustAnchor: config.directoryTrustAnchor,
cdnUrlObject: {
0: config.cdnUrl0,
2: config.cdnUrl2,
},
certificateAuthority: config.certificateAuthority,
contentProxyUrl: config.contentProxyUrl,
proxyUrl: config.proxyUrl,
version: config.version,
});
2019-08-19 22:26:45 +00:00
// Linux seems to periodically let the event loop stop, so this is a global workaround
setInterval(() => {
window.nodeSetImmediate(() => {});
}, 1000);
2020-05-27 21:37:06 +00:00
const { imageToBlurHash } = require('./ts/util/imageToBlurHash');
2021-06-22 14:46:42 +00:00
const { isValidGuid } = require('./ts/util/isValidGuid');
const { ActiveWindowService } = require('./ts/services/ActiveWindowService');
2020-05-27 21:37:06 +00:00
window.imageToBlurHash = imageToBlurHash;
window.emojiData = require('emoji-datasource');
window.libphonenumber = require('google-libphonenumber').PhoneNumberUtil.getInstance();
window.libphonenumber.PhoneNumberFormat = require('google-libphonenumber').PhoneNumberFormat;
window.getGuid = require('uuid/v4');
const activeWindowService = new ActiveWindowService();
activeWindowService.initialize(window.document, ipc);
window.isActive = activeWindowService.isActive.bind(activeWindowService);
window.registerForActive = activeWindowService.registerForActive.bind(
activeWindowService
);
window.unregisterForActive = activeWindowService.unregisterForActive.bind(
activeWindowService
);
2021-04-27 22:11:59 +00:00
window.Accessibility = {
reducedMotionSetting: Boolean(config.reducedMotionSetting),
};
2021-06-22 14:46:42 +00:00
window.isValidGuid = isValidGuid;
window.React = require('react');
window.ReactDOM = require('react-dom');
window.moment = require('moment');
window.PQueue = require('p-queue').default;
const Signal = require('./js/modules/signal');
2021-09-18 00:30:08 +00:00
const { setupI18n } = require('./ts/util/setupI18n');
const Attachments = require('./app/attachments');
const { locale } = config;
2021-09-18 00:30:08 +00:00
window.i18n = setupI18n(locale, localeMessages);
window.moment.updateLocale(locale, {
relativeTime: {
s: window.i18n('timestamp_s'),
m: window.i18n('timestamp_m'),
h: window.i18n('timestamp_h'),
},
});
window.moment.locale(locale);
const userDataPath = app.getPath('userData');
window.baseAttachmentsPath = Attachments.getPath(userDataPath);
window.baseStickersPath = Attachments.getStickersPath(userDataPath);
window.baseTempPath = Attachments.getTempPath(userDataPath);
window.baseDraftPath = Attachments.getDraftPath(userDataPath);
2021-06-01 18:15:23 +00:00
const { addSensitivePath } = require('./ts/util/privacy');
addSensitivePath(window.baseAttachmentsPath);
window.Signal = Signal.setup({
Attachments,
userDataPath,
getRegionCode: () => window.storage.get('regionCode'),
logger: log,
});
2021-08-11 19:29:07 +00:00
if (config.enableCI) {
const { CI, electronRequire } = require('./ts/CI');
window.CI = new CI(title);
window.electronRequire = electronRequire;
}
// these need access to window.Signal:
require('./ts/models/messages');
require('./ts/models/conversations');
require('./ts/backbone/views/whisper_view');
require('./ts/views/conversation_view');
require('./ts/views/inbox_view');
require('./ts/views/install_view');
require('./ts/views/recorder_view');
require('./ts/views/standalone_registration_view');
require('./ts/SignalProtocolStore');
require('./ts/background');
// Pulling these in separately since they access filesystem, electron
window.Signal.Debug = require('./js/modules/debug');
2020-03-20 21:00:11 +00:00
window.addEventListener('contextmenu', e => {
const editable = e.target.closest(
'textarea, input, [contenteditable="true"]'
);
const link = e.target.closest('a');
const selection = Boolean(window.getSelection().toString());
2021-09-07 16:12:26 +00:00
const image = e.target.closest('.Lightbox img');
if (!editable && !selection && !link && !image) {
2020-03-20 21:00:11 +00:00
e.preventDefault();
}
});
if (config.environment === 'test') {
2021-08-11 19:29:07 +00:00
require('./preload_test');
}
log.info('preload complete');
} catch (error) {
/* eslint-disable no-console */
if (console._log) {
console._log('preload error!', error.stack);
} else {
console.log('preload error!', error.stack);
}
/* eslint-enable no-console */
throw error;
2018-12-13 21:41:42 +00:00
}
2021-04-07 22:40:12 +00:00
preloadEndTime = Date.now();