mirror of
https://github.com/zulip/zulip-desktop.git
synced 2025-11-04 14:03:27 +00:00
Compare commits
38 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e03de26137 | ||
|
|
983254c310 | ||
|
|
b6059077d8 | ||
|
|
cafff9a008 | ||
|
|
190204b2e5 | ||
|
|
4c25c99abc | ||
|
|
55be93b906 | ||
|
|
34e2b3a3d0 | ||
|
|
e5ece8db9e | ||
|
|
40b26dbb0e | ||
|
|
ae4f03f4ba | ||
|
|
8ea32a7a96 | ||
|
|
6b7cce0366 | ||
|
|
73fec72e6d | ||
|
|
920adfb169 | ||
|
|
98174fdcaf | ||
|
|
a0c033431e | ||
|
|
82421d843a | ||
|
|
d9afee3330 | ||
|
|
a46f2ed618 | ||
|
|
9f3b4ff408 | ||
|
|
fb800f7862 | ||
|
|
ba191c3699 | ||
|
|
e49a880ed6 | ||
|
|
4bfa7c9265 | ||
|
|
39c6fa4ace | ||
|
|
963c2e5388 | ||
|
|
849df4adaf | ||
|
|
fc6ff83485 | ||
|
|
5ae2a717fa | ||
|
|
cfdc08a038 | ||
|
|
b76467529d | ||
|
|
bb88a7b7a8 | ||
|
|
0225778050 | ||
|
|
2154b191c8 | ||
|
|
4093304b4d | ||
|
|
2e03f779e8 | ||
|
|
9464390070 |
16
.travis.yml
16
.travis.yml
@@ -1,6 +1,3 @@
|
|||||||
sudo: required
|
|
||||||
dist: trusty
|
|
||||||
|
|
||||||
os:
|
os:
|
||||||
- osx
|
- osx
|
||||||
- linux
|
- linux
|
||||||
@@ -18,20 +15,9 @@ node_js:
|
|||||||
- '10'
|
- '10'
|
||||||
- '12'
|
- '12'
|
||||||
|
|
||||||
before_install:
|
|
||||||
- ./scripts/travis-xvfb.sh
|
|
||||||
- npm install -g gulp
|
|
||||||
- npm ci
|
|
||||||
|
|
||||||
cache:
|
cache:
|
||||||
directories:
|
directories:
|
||||||
- node_modules
|
- node_modules
|
||||||
|
|
||||||
script:
|
script:
|
||||||
- npm run travis
|
- npm run test
|
||||||
notifications:
|
|
||||||
webhooks:
|
|
||||||
urls:
|
|
||||||
- https://zulip.org/zulipbot/travis
|
|
||||||
on_success: always
|
|
||||||
on_failure: always
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { app, dialog } from 'electron';
|
import {app, dialog} from 'electron';
|
||||||
import { autoUpdater } from 'electron-updater';
|
import {UpdateDownloadedEvent, UpdateInfo, autoUpdater} from 'electron-updater';
|
||||||
import { linuxUpdateNotification } from './linuxupdater'; // Required only in case of linux
|
import {linuxUpdateNotification} from './linuxupdater'; // Required only in case of linux
|
||||||
|
|
||||||
import log from 'electron-log';
|
import log from 'electron-log';
|
||||||
import isDev from 'electron-is-dev';
|
import isDev from 'electron-is-dev';
|
||||||
@@ -34,57 +34,59 @@ export function appUpdater(updateFromMenu = false): void {
|
|||||||
autoUpdater.allowPrerelease = isBetaUpdate || false;
|
autoUpdater.allowPrerelease = isBetaUpdate || false;
|
||||||
|
|
||||||
const eventsListenerRemove = ['update-available', 'update-not-available'];
|
const eventsListenerRemove = ['update-available', 'update-not-available'];
|
||||||
autoUpdater.on('update-available', info => {
|
autoUpdater.on('update-available', async (info: UpdateInfo) => {
|
||||||
if (updateFromMenu) {
|
if (updateFromMenu) {
|
||||||
dialog.showMessageBox({
|
|
||||||
message: `A new version ${info.version}, of Zulip Desktop is available`,
|
|
||||||
detail: 'The update will be downloaded in the background. You will be notified when it is ready to be installed.'
|
|
||||||
});
|
|
||||||
|
|
||||||
updateAvailable = true;
|
updateAvailable = true;
|
||||||
|
|
||||||
// This is to prevent removal of 'update-downloaded' and 'error' event listener.
|
// This is to prevent removal of 'update-downloaded' and 'error' event listener.
|
||||||
eventsListenerRemove.forEach(event => {
|
eventsListenerRemove.forEach(event => {
|
||||||
autoUpdater.removeAllListeners(event);
|
autoUpdater.removeAllListeners(event);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
await dialog.showMessageBox({
|
||||||
|
message: `A new version ${info.version}, of Zulip Desktop is available`,
|
||||||
|
detail: 'The update will be downloaded in the background. You will be notified when it is ready to be installed.'
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
autoUpdater.on('update-not-available', () => {
|
autoUpdater.on('update-not-available', async () => {
|
||||||
if (updateFromMenu) {
|
if (updateFromMenu) {
|
||||||
dialog.showMessageBox({
|
// Remove all autoUpdator listeners so that next time autoUpdator is manually called these
|
||||||
|
// listeners don't trigger multiple times.
|
||||||
|
autoUpdater.removeAllListeners();
|
||||||
|
|
||||||
|
await dialog.showMessageBox({
|
||||||
message: 'No updates available',
|
message: 'No updates available',
|
||||||
detail: `You are running the latest version of Zulip Desktop.\nVersion: ${app.getVersion()}`
|
detail: `You are running the latest version of Zulip Desktop.\nVersion: ${app.getVersion()}`
|
||||||
});
|
});
|
||||||
// Remove all autoUpdator listeners so that next time autoUpdator is manually called these
|
|
||||||
// listeners don't trigger multiple times.
|
|
||||||
autoUpdater.removeAllListeners();
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
autoUpdater.on('error', async error => {
|
autoUpdater.on('error', async (error: Error) => {
|
||||||
if (updateFromMenu) {
|
if (updateFromMenu) {
|
||||||
const messageText = (updateAvailable) ? ('Unable to download the updates') : ('Unable to check for updates');
|
|
||||||
const { response } = await dialog.showMessageBox({
|
|
||||||
type: 'error',
|
|
||||||
buttons: ['Manual Download', 'Cancel'],
|
|
||||||
message: messageText,
|
|
||||||
detail: (error).toString() + `\n\nThe latest version of Zulip Desktop is available at -\nhttps://zulipchat.com/apps/.\n
|
|
||||||
Current Version: ${app.getVersion()}`
|
|
||||||
});
|
|
||||||
if (response === 0) {
|
|
||||||
LinkUtil.openBrowser(new URL('https://zulipchat.com/apps/'));
|
|
||||||
}
|
|
||||||
// Remove all autoUpdator listeners so that next time autoUpdator is manually called these
|
// Remove all autoUpdator listeners so that next time autoUpdator is manually called these
|
||||||
// listeners don't trigger multiple times.
|
// listeners don't trigger multiple times.
|
||||||
autoUpdater.removeAllListeners();
|
autoUpdater.removeAllListeners();
|
||||||
|
|
||||||
|
const messageText = (updateAvailable) ? ('Unable to download the updates') : ('Unable to check for updates');
|
||||||
|
const {response} = await dialog.showMessageBox({
|
||||||
|
type: 'error',
|
||||||
|
buttons: ['Manual Download', 'Cancel'],
|
||||||
|
message: messageText,
|
||||||
|
detail: `Error: ${error.message}\n\nThe latest version of Zulip Desktop is available at -\nhttps://zulipchat.com/apps/.\n
|
||||||
|
Current Version: ${app.getVersion()}`
|
||||||
|
});
|
||||||
|
if (response === 0) {
|
||||||
|
await LinkUtil.openBrowser(new URL('https://zulipchat.com/apps/'));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Ask the user if update is available
|
// Ask the user if update is available
|
||||||
autoUpdater.on('update-downloaded', async event => {
|
autoUpdater.on('update-downloaded', async (event: UpdateDownloadedEvent) => {
|
||||||
// Ask user to update the app
|
// Ask user to update the app
|
||||||
const { response } = await dialog.showMessageBox({
|
const {response} = await dialog.showMessageBox({
|
||||||
type: 'question',
|
type: 'question',
|
||||||
buttons: ['Install and Relaunch', 'Install Later'],
|
buttons: ['Install and Relaunch', 'Install Later'],
|
||||||
defaultId: 0,
|
defaultId: 0,
|
||||||
@@ -94,11 +96,11 @@ export function appUpdater(updateFromMenu = false): void {
|
|||||||
if (response === 0) {
|
if (response === 0) {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
autoUpdater.quitAndInstall();
|
autoUpdater.quitAndInstall();
|
||||||
// force app to quit. This is just a workaround, ideally autoUpdater.quitAndInstall() should relaunch the app.
|
// Force app to quit. This is just a workaround, ideally autoUpdater.quitAndInstall() should relaunch the app.
|
||||||
app.quit();
|
app.quit();
|
||||||
}, 1000);
|
}, 1000);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// Init for updates
|
// Init for updates
|
||||||
autoUpdater.checkForUpdates();
|
(async () => autoUpdater.checkForUpdates())();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,14 +1,15 @@
|
|||||||
import { sentryInit } from '../renderer/js/utils/sentry-util';
|
import {sentryInit} from '../renderer/js/utils/sentry-util';
|
||||||
import { appUpdater } from './autoupdater';
|
import {appUpdater} from './autoupdater';
|
||||||
import { setAutoLaunch } from './startup';
|
import {setAutoLaunch} from './startup';
|
||||||
|
|
||||||
import windowStateKeeper from 'electron-window-state';
|
import windowStateKeeper from 'electron-window-state';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import electron, { app, ipcMain, session, dialog } from 'electron';
|
import electron, {app, dialog, ipcMain, session} from 'electron';
|
||||||
|
|
||||||
import * as AppMenu from './menu';
|
import * as AppMenu from './menu';
|
||||||
import * as BadgeSettings from '../renderer/js/pages/preference/badge-settings';
|
import * as BadgeSettings from '../renderer/js/pages/preference/badge-settings';
|
||||||
|
import * as CertificateUtil from '../renderer/js/utils/certificate-util';
|
||||||
import * as ConfigUtil from '../renderer/js/utils/config-util';
|
import * as ConfigUtil from '../renderer/js/utils/config-util';
|
||||||
import * as ProxyUtil from '../renderer/js/utils/proxy-util';
|
import * as ProxyUtil from '../renderer/js/utils/proxy-util';
|
||||||
|
|
||||||
@@ -42,13 +43,26 @@ if (singleInstanceLock) {
|
|||||||
app.quit();
|
app.quit();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const rendererCallbacks = new Map();
|
||||||
|
let nextRendererCallbackId = 0;
|
||||||
|
|
||||||
|
ipcMain.on('renderer-callback', (event: Event, rendererCallbackId: number, ...args: any[]) => {
|
||||||
|
rendererCallbacks.get(rendererCallbackId)(...args);
|
||||||
|
rendererCallbacks.delete(rendererCallbackId);
|
||||||
|
});
|
||||||
|
|
||||||
|
function makeRendererCallback(callback: (...args: any[]) => void): number {
|
||||||
|
rendererCallbacks.set(nextRendererCallbackId, callback);
|
||||||
|
return nextRendererCallbackId++;
|
||||||
|
}
|
||||||
|
|
||||||
const APP_ICON = path.join(__dirname, '../resources', 'Icon');
|
const APP_ICON = path.join(__dirname, '../resources', 'Icon');
|
||||||
|
|
||||||
const iconPath = (): string => {
|
const iconPath = (): string => {
|
||||||
return APP_ICON + (process.platform === 'win32' ? '.ico' : '.png');
|
return APP_ICON + (process.platform === 'win32' ? '.ico' : '.png');
|
||||||
};
|
};
|
||||||
|
|
||||||
// toggle the app window
|
// Toggle the app window
|
||||||
const toggleApp = (): void => {
|
const toggleApp = (): void => {
|
||||||
if (!mainWindow.isVisible() || mainWindow.isMinimized()) {
|
if (!mainWindow.isVisible() || mainWindow.isMinimized()) {
|
||||||
mainWindow.show();
|
mainWindow.show();
|
||||||
@@ -91,13 +105,14 @@ function createMainWindow(): Electron.BrowserWindow {
|
|||||||
win.webContents.send('focus');
|
win.webContents.send('focus');
|
||||||
});
|
});
|
||||||
|
|
||||||
win.loadURL(mainURL);
|
(async () => win.loadURL(mainURL))();
|
||||||
|
|
||||||
// Keep the app running in background on close event
|
// Keep the app running in background on close event
|
||||||
win.on('close', event => {
|
win.on('close', event => {
|
||||||
if (ConfigUtil.getConfigItem('quitOnClose')) {
|
if (ConfigUtil.getConfigItem('quitOnClose')) {
|
||||||
app.quit();
|
app.quit();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!isQuitting) {
|
if (!isQuitting) {
|
||||||
event.preventDefault();
|
event.preventDefault();
|
||||||
|
|
||||||
@@ -141,16 +156,10 @@ app.disableHardwareAcceleration();
|
|||||||
// More info here - https://github.com/electron/electron/issues/10732
|
// More info here - https://github.com/electron/electron/issues/10732
|
||||||
app.commandLine.appendSwitch('force-color-profile', 'srgb');
|
app.commandLine.appendSwitch('force-color-profile', 'srgb');
|
||||||
|
|
||||||
// eslint-disable-next-line max-params
|
// This event is only available on macOS. Triggers when you click on the dock icon.
|
||||||
app.on('certificate-error', (event: Event, _webContents: Electron.WebContents, _url: string, _error: string, _certificate: any, callback) => {
|
|
||||||
event.preventDefault();
|
|
||||||
callback(true);
|
|
||||||
});
|
|
||||||
|
|
||||||
// this event is only available on macOS. Triggers when you click on the dock icon.
|
|
||||||
app.on('activate', () => {
|
app.on('activate', () => {
|
||||||
if (mainWindow) {
|
if (mainWindow) {
|
||||||
// if there is already a window show it
|
// If there is already a window show it
|
||||||
mainWindow.show();
|
mainWindow.show();
|
||||||
} else {
|
} else {
|
||||||
mainWindow = createMainWindow();
|
mainWindow = createMainWindow();
|
||||||
@@ -182,7 +191,7 @@ app.on('ready', () => {
|
|||||||
const isSystemProxy = ConfigUtil.getConfigItem('useSystemProxy');
|
const isSystemProxy = ConfigUtil.getConfigItem('useSystemProxy');
|
||||||
|
|
||||||
if (isSystemProxy) {
|
if (isSystemProxy) {
|
||||||
ProxyUtil.resolveSystemProxy(mainWindow);
|
(async () => ProxyUtil.resolveSystemProxy(mainWindow))();
|
||||||
}
|
}
|
||||||
|
|
||||||
const page = mainWindow.webContents;
|
const page = mainWindow.webContents;
|
||||||
@@ -206,25 +215,62 @@ app.on('ready', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
const permissionCallbacks = new Map();
|
app.on('certificate-error', (
|
||||||
let nextPermissionId = 0;
|
event: Event,
|
||||||
|
webContents: Electron.WebContents,
|
||||||
|
url: string,
|
||||||
|
error: string,
|
||||||
|
certificate: Electron.Certificate,
|
||||||
|
callback: (isTrusted: boolean) => void
|
||||||
|
) /* eslint-disable-line max-params */ => {
|
||||||
|
// TODO: The entire concept of selectively ignoring certificate errors
|
||||||
|
// is ill-conceived, and this handler needs to be deleted.
|
||||||
|
event.preventDefault();
|
||||||
|
|
||||||
|
const {origin} = new URL(url);
|
||||||
|
const filename = CertificateUtil.getCertificate(encodeURIComponent(origin));
|
||||||
|
if (filename !== undefined) {
|
||||||
|
try {
|
||||||
|
const savedCertificate = fs.readFileSync(
|
||||||
|
path.join(`${app.getPath('userData')}/certificates`, filename),
|
||||||
|
'utf8'
|
||||||
|
);
|
||||||
|
if (certificate.data.replace(/[\r\n]/g, '') ===
|
||||||
|
savedCertificate.replace(/[\r\n]/g, '')) {
|
||||||
|
callback(true);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Error reading certificate file ${filename}:`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
page.send(
|
||||||
|
'certificate-error',
|
||||||
|
webContents.id === mainWindow.webContents.id ? null : webContents.id,
|
||||||
|
makeRendererCallback(ignore => {
|
||||||
|
callback(ignore);
|
||||||
|
if (!ignore) {
|
||||||
|
dialog.showErrorBox(
|
||||||
|
'Certificate error',
|
||||||
|
`The server presented an invalid certificate for ${origin}:
|
||||||
|
|
||||||
|
${error}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
page.session.setPermissionRequestHandler((webContents, permission, callback, details) => {
|
page.session.setPermissionRequestHandler((webContents, permission, callback, details) => {
|
||||||
const {origin} = new URL(details.requestingUrl);
|
const {origin} = new URL(details.requestingUrl);
|
||||||
permissionCallbacks.set(nextPermissionId, callback);
|
page.send('permission-request', {
|
||||||
page.send('permission-request', nextPermissionId, {
|
|
||||||
webContentsId: webContents.id === mainWindow.webContents.id ?
|
webContentsId: webContents.id === mainWindow.webContents.id ?
|
||||||
null :
|
null :
|
||||||
webContents.id,
|
webContents.id,
|
||||||
origin,
|
origin,
|
||||||
permission
|
permission
|
||||||
});
|
}, makeRendererCallback(callback));
|
||||||
nextPermissionId++;
|
|
||||||
});
|
|
||||||
|
|
||||||
ipcMain.on('permission-response', (event: Event, permissionId: number, grant: boolean) => {
|
|
||||||
permissionCallbacks.get(permissionId)(grant);
|
|
||||||
permissionCallbacks.delete(permissionId);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// Temporarily remove this event
|
// Temporarily remove this event
|
||||||
@@ -303,11 +349,11 @@ app.on('ready', () => {
|
|||||||
BadgeSettings.updateTaskbarIcon(data, text, mainWindow);
|
BadgeSettings.updateTaskbarIcon(data, text, mainWindow);
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.on('forward-message', (_event: Electron.IpcMainEvent, listener: string, ...parameters: any[]) => {
|
ipcMain.on('forward-message', (_event: Electron.IpcMainEvent, listener: string, ...parameters: unknown[]) => {
|
||||||
page.send(listener, ...parameters);
|
page.send(listener, ...parameters);
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.on('update-menu', (_event: Electron.IpcMainEvent, props: any) => {
|
ipcMain.on('update-menu', (_event: Electron.IpcMainEvent, props: AppMenu.MenuProps) => {
|
||||||
AppMenu.setMenu(props);
|
AppMenu.setMenu(props);
|
||||||
const activeTab = props.tabs[props.activeTabIndex];
|
const activeTab = props.tabs[props.activeTabIndex];
|
||||||
if (activeTab) {
|
if (activeTab) {
|
||||||
@@ -315,27 +361,18 @@ app.on('ready', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.on('toggleAutoLauncher', (_event: Electron.IpcMainEvent, AutoLaunchValue: boolean) => {
|
ipcMain.on('toggleAutoLauncher', async (_event: Electron.IpcMainEvent, AutoLaunchValue: boolean) => {
|
||||||
setAutoLaunch(AutoLaunchValue);
|
await setAutoLaunch(AutoLaunchValue);
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcMain.on('downloadFile', (_event: Electron.IpcMainEvent, url: string, downloadPath: string) => {
|
ipcMain.on('downloadFile', (_event: Electron.IpcMainEvent, url: string, downloadPath: string) => {
|
||||||
page.downloadURL(url);
|
page.downloadURL(url);
|
||||||
page.session.once('will-download', async (_event: Event, item) => {
|
page.session.once('will-download', async (_event: Event, item) => {
|
||||||
let setFilePath: string;
|
|
||||||
let shortFileName: string;
|
|
||||||
if (ConfigUtil.getConfigItem('promptDownload', false)) {
|
if (ConfigUtil.getConfigItem('promptDownload', false)) {
|
||||||
const showDialogOptions: object = {
|
const showDialogOptions: object = {
|
||||||
defaultPath: path.join(downloadPath, item.getFilename())
|
defaultPath: path.join(downloadPath, item.getFilename())
|
||||||
};
|
};
|
||||||
|
item.setSaveDialogOptions(showDialogOptions);
|
||||||
const result = await dialog.showSaveDialog(mainWindow, showDialogOptions);
|
|
||||||
if (result.canceled) {
|
|
||||||
item.cancel();
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setFilePath = result.filePath;
|
|
||||||
shortFileName = path.basename(setFilePath);
|
|
||||||
} else {
|
} else {
|
||||||
const getTimeStamp = (): number => {
|
const getTimeStamp = (): number => {
|
||||||
const date = new Date();
|
const date = new Date();
|
||||||
@@ -352,12 +389,10 @@ app.on('ready', () => {
|
|||||||
|
|
||||||
// Update the name and path of the file if it already exists
|
// Update the name and path of the file if it already exists
|
||||||
const updatedFilePath = path.join(downloadPath, formatFile(filePath));
|
const updatedFilePath = path.join(downloadPath, formatFile(filePath));
|
||||||
setFilePath = fs.existsSync(filePath) ? updatedFilePath : filePath;
|
const setFilePath: string = fs.existsSync(filePath) ? updatedFilePath : filePath;
|
||||||
shortFileName = fs.existsSync(filePath) ? formatFile(filePath) : item.getFilename();
|
item.setSavePath(setFilePath);
|
||||||
}
|
}
|
||||||
|
|
||||||
item.setSavePath(setFilePath);
|
|
||||||
|
|
||||||
const updatedListener = (_event: Event, state: string): void => {
|
const updatedListener = (_event: Event, state: string): void => {
|
||||||
switch (state) {
|
switch (state) {
|
||||||
case 'interrupted': {
|
case 'interrupted': {
|
||||||
@@ -366,26 +401,31 @@ app.on('ready', () => {
|
|||||||
item.cancel();
|
item.cancel();
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'progressing': {
|
case 'progressing': {
|
||||||
if (item.isPaused()) {
|
if (item.isPaused()) {
|
||||||
item.cancel();
|
item.cancel();
|
||||||
}
|
}
|
||||||
|
|
||||||
// This event can also be used to show progress in percentage in future.
|
// This event can also be used to show progress in percentage in future.
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
default: {
|
default: {
|
||||||
console.info('Unknown updated state of download item');
|
console.info('Unknown updated state of download item');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
item.on('updated', updatedListener);
|
item.on('updated', updatedListener);
|
||||||
item.once('done', (_event: Event, state) => {
|
item.once('done', (_event: Event, state) => {
|
||||||
if (state === 'completed') {
|
if (state === 'completed') {
|
||||||
page.send('downloadFileCompleted', item.getSavePath(), shortFileName);
|
page.send('downloadFileCompleted', item.getSavePath(), path.basename(item.getSavePath()));
|
||||||
} else {
|
} else {
|
||||||
console.log('Download failed state:', state);
|
console.log('Download failed state:', state);
|
||||||
page.send('downloadFileFailed');
|
page.send('downloadFileFailed', state);
|
||||||
}
|
}
|
||||||
|
|
||||||
// To stop item for listening to updated events of this file
|
// To stop item for listening to updated events of this file
|
||||||
item.removeListener('updated', updatedListener);
|
item.removeListener('updated', updatedListener);
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { app, Notification } from 'electron';
|
import {app, Notification} from 'electron';
|
||||||
|
|
||||||
import request from 'request';
|
import request from 'request';
|
||||||
import semver from 'semver';
|
import semver from 'semver';
|
||||||
@@ -24,20 +24,24 @@ export function linuxUpdateNotification(): void {
|
|||||||
ecdhCurve: 'auto'
|
ecdhCurve: 'auto'
|
||||||
};
|
};
|
||||||
|
|
||||||
request(options, (error: any, response: any, body: any) => {
|
request(options, (error, response: request.Response, body: string) => {
|
||||||
if (error) {
|
if (error) {
|
||||||
logger.error('Linux update error.');
|
logger.error('Linux update error.');
|
||||||
logger.error(error);
|
logger.error(error);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (response.statusCode < 400) {
|
if (response.statusCode < 400) {
|
||||||
const data = JSON.parse(body);
|
const data = JSON.parse(body);
|
||||||
const latestVersion = ConfigUtil.getConfigItem('betaUpdate') ? data[0].tag_name : data.tag_name;
|
const latestVersion = ConfigUtil.getConfigItem('betaUpdate') ? data[0].tag_name : data.tag_name;
|
||||||
|
if (typeof latestVersion !== 'string') {
|
||||||
|
throw new TypeError('Expected string for tag_name');
|
||||||
|
}
|
||||||
|
|
||||||
if (semver.gt(latestVersion, app.getVersion())) {
|
if (semver.gt(latestVersion, app.getVersion())) {
|
||||||
const notified = LinuxUpdateUtil.getUpdateItem(latestVersion);
|
const notified = LinuxUpdateUtil.getUpdateItem(latestVersion);
|
||||||
if (notified === null) {
|
if (notified === null) {
|
||||||
new Notification({title: 'Zulip Update', body: 'A new version ' + latestVersion + ' is available. Please update using your package manager.'}).show();
|
new Notification({title: 'Zulip Update', body: `A new version ${latestVersion} is available. Please update using your package manager.`}).show();
|
||||||
LinuxUpdateUtil.setUpdateItem(latestVersion, true);
|
LinuxUpdateUtil.setUpdateItem(latestVersion, true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
105
app/main/menu.ts
105
app/main/menu.ts
@@ -1,5 +1,5 @@
|
|||||||
import { app, shell, BrowserWindow, Menu, dialog } from 'electron';
|
import {app, shell, BrowserWindow, Menu, dialog} from 'electron';
|
||||||
import { appUpdater } from './autoupdater';
|
import {appUpdater} from './autoupdater';
|
||||||
|
|
||||||
import AdmZip from 'adm-zip';
|
import AdmZip from 'adm-zip';
|
||||||
import fs from 'fs-extra';
|
import fs from 'fs-extra';
|
||||||
@@ -9,6 +9,13 @@ import Logger from '../renderer/js/utils/logger-util';
|
|||||||
import * as ConfigUtil from '../renderer/js/utils/config-util';
|
import * as ConfigUtil from '../renderer/js/utils/config-util';
|
||||||
import * as LinkUtil from '../renderer/js/utils/link-util';
|
import * as LinkUtil from '../renderer/js/utils/link-util';
|
||||||
import * as t from '../renderer/js/utils/translation-util';
|
import * as t from '../renderer/js/utils/translation-util';
|
||||||
|
import type {ServerOrFunctionalTab} from '../renderer/js/main';
|
||||||
|
|
||||||
|
export interface MenuProps {
|
||||||
|
tabs: ServerOrFunctionalTab[];
|
||||||
|
activeTabIndex?: number;
|
||||||
|
enableMenu?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
const appName = app.name;
|
const appName = app.name;
|
||||||
|
|
||||||
@@ -22,7 +29,7 @@ function getHistorySubmenu(enableMenu: boolean): Electron.MenuItemConstructorOpt
|
|||||||
label: t.__('Back'),
|
label: t.__('Back'),
|
||||||
accelerator: process.platform === 'darwin' ? 'Command+Left' : 'Alt+Left',
|
accelerator: process.platform === 'darwin' ? 'Command+Left' : 'Alt+Left',
|
||||||
enabled: enableMenu,
|
enabled: enableMenu,
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('back');
|
sendAction('back');
|
||||||
}
|
}
|
||||||
@@ -31,7 +38,7 @@ function getHistorySubmenu(enableMenu: boolean): Electron.MenuItemConstructorOpt
|
|||||||
label: t.__('Forward'),
|
label: t.__('Forward'),
|
||||||
accelerator: process.platform === 'darwin' ? 'Command+Right' : 'Alt+Right',
|
accelerator: process.platform === 'darwin' ? 'Command+Right' : 'Alt+Right',
|
||||||
enabled: enableMenu,
|
enabled: enableMenu,
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('forward');
|
sendAction('forward');
|
||||||
}
|
}
|
||||||
@@ -48,8 +55,8 @@ function getToolsSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: t.__('Release Notes'),
|
label: t.__('Release Notes'),
|
||||||
click() {
|
async click() {
|
||||||
LinkUtil.openBrowser(new URL(`https://github.com/zulip/zulip-desktop/releases/tag/v${app.getVersion()}`));
|
await LinkUtil.openBrowser(new URL(`https://github.com/zulip/zulip-desktop/releases/tag/v${app.getVersion()}`));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -58,8 +65,8 @@ function getToolsSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
{
|
{
|
||||||
label: t.__('Factory Reset'),
|
label: t.__('Factory Reset'),
|
||||||
accelerator: process.platform === 'darwin' ? 'Command+Shift+D' : 'Ctrl+Shift+D',
|
accelerator: process.platform === 'darwin' ? 'Command+Shift+D' : 'Ctrl+Shift+D',
|
||||||
click() {
|
async click() {
|
||||||
resetAppSettings();
|
await resetAppSettings();
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
@@ -87,7 +94,7 @@ function getToolsSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
{
|
{
|
||||||
label: t.__('Toggle DevTools for Zulip App'),
|
label: t.__('Toggle DevTools for Zulip App'),
|
||||||
accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
|
accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
focusedWindow.webContents.openDevTools({mode: 'undocked'});
|
focusedWindow.webContents.openDevTools({mode: 'undocked'});
|
||||||
}
|
}
|
||||||
@@ -96,7 +103,7 @@ function getToolsSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
{
|
{
|
||||||
label: t.__('Toggle DevTools for Active Tab'),
|
label: t.__('Toggle DevTools for Active Tab'),
|
||||||
accelerator: process.platform === 'darwin' ? 'Alt+Command+U' : 'Ctrl+Shift+U',
|
accelerator: process.platform === 'darwin' ? 'Alt+Command+U' : 'Ctrl+Shift+U',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('tab-devtools');
|
sendAction('tab-devtools');
|
||||||
}
|
}
|
||||||
@@ -108,7 +115,7 @@ function getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
return [{
|
return [{
|
||||||
label: t.__('Reload'),
|
label: t.__('Reload'),
|
||||||
accelerator: 'CommandOrControl+R',
|
accelerator: 'CommandOrControl+R',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('reload-current-viewer');
|
sendAction('reload-current-viewer');
|
||||||
}
|
}
|
||||||
@@ -116,7 +123,7 @@ function getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
}, {
|
}, {
|
||||||
label: t.__('Hard Reload'),
|
label: t.__('Hard Reload'),
|
||||||
accelerator: 'CommandOrControl+Shift+R',
|
accelerator: 'CommandOrControl+Shift+R',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('hard-reload');
|
sendAction('hard-reload');
|
||||||
}
|
}
|
||||||
@@ -129,7 +136,7 @@ function getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
}, {
|
}, {
|
||||||
label: t.__('Zoom In'),
|
label: t.__('Zoom In'),
|
||||||
role: 'zoomIn',
|
role: 'zoomIn',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('zoomIn');
|
sendAction('zoomIn');
|
||||||
}
|
}
|
||||||
@@ -138,7 +145,7 @@ function getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
label: t.__('Zoom Out'),
|
label: t.__('Zoom Out'),
|
||||||
role: 'zoomOut',
|
role: 'zoomOut',
|
||||||
accelerator: 'CommandOrControl+-',
|
accelerator: 'CommandOrControl+-',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('zoomOut');
|
sendAction('zoomOut');
|
||||||
}
|
}
|
||||||
@@ -147,7 +154,7 @@ function getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
label: t.__('Actual Size'),
|
label: t.__('Actual Size'),
|
||||||
role: 'resetZoom',
|
role: 'resetZoom',
|
||||||
accelerator: 'CommandOrControl+0',
|
accelerator: 'CommandOrControl+0',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('zoomActualSize');
|
sendAction('zoomActualSize');
|
||||||
}
|
}
|
||||||
@@ -156,7 +163,7 @@ function getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
type: 'separator'
|
type: 'separator'
|
||||||
}, {
|
}, {
|
||||||
label: t.__('Toggle Tray Icon'),
|
label: t.__('Toggle Tray Icon'),
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
focusedWindow.webContents.send('toggletray');
|
focusedWindow.webContents.send('toggletray');
|
||||||
}
|
}
|
||||||
@@ -164,7 +171,7 @@ function getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
}, {
|
}, {
|
||||||
label: t.__('Toggle Sidebar'),
|
label: t.__('Toggle Sidebar'),
|
||||||
accelerator: 'CommandOrControl+Shift+S',
|
accelerator: 'CommandOrControl+Shift+S',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
const newValue = !ConfigUtil.getConfigItem('showSidebar');
|
const newValue = !ConfigUtil.getConfigItem('showSidebar');
|
||||||
focusedWindow.webContents.send('toggle-sidebar', newValue);
|
focusedWindow.webContents.send('toggle-sidebar', newValue);
|
||||||
@@ -175,7 +182,7 @@ function getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
label: t.__('Auto hide Menu bar'),
|
label: t.__('Auto hide Menu bar'),
|
||||||
checked: ConfigUtil.getConfigItem('autoHideMenubar', false),
|
checked: ConfigUtil.getConfigItem('autoHideMenubar', false),
|
||||||
visible: process.platform !== 'darwin',
|
visible: process.platform !== 'darwin',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
const newValue = !ConfigUtil.getConfigItem('autoHideMenubar');
|
const newValue = !ConfigUtil.getConfigItem('autoHideMenubar');
|
||||||
focusedWindow.autoHideMenuBar = newValue;
|
focusedWindow.autoHideMenuBar = newValue;
|
||||||
@@ -196,7 +203,7 @@ function getHelpSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
},
|
},
|
||||||
{
|
{
|
||||||
label: t.__('About Zulip'),
|
label: t.__('About Zulip'),
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('open-about');
|
sendAction('open-about');
|
||||||
}
|
}
|
||||||
@@ -213,7 +220,7 @@ function getHelpSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
{
|
{
|
||||||
label: t.__('Report an Issue'),
|
label: t.__('Report an Issue'),
|
||||||
click() {
|
click() {
|
||||||
// the goal is to notify the main.html BrowserWindow
|
// The goal is to notify the main.html BrowserWindow
|
||||||
// which may not be the focused window.
|
// which may not be the focused window.
|
||||||
BrowserWindow.getAllWindows().forEach(window => {
|
BrowserWindow.getAllWindows().forEach(window => {
|
||||||
window.webContents.send('open-feedback-modal');
|
window.webContents.send('open-feedback-modal');
|
||||||
@@ -223,7 +230,7 @@ function getHelpSubmenu(): Electron.MenuItemConstructorOptions[] {
|
|||||||
];
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
function getWindowSubmenu(tabs: any[], activeTabIndex: number, enableMenu: boolean): Electron.MenuItemConstructorOptions[] {
|
function getWindowSubmenu(tabs: ServerOrFunctionalTab[], activeTabIndex: number): Electron.MenuItemConstructorOptions[] {
|
||||||
const initialSubmenu: Electron.MenuItemConstructorOptions[] = [{
|
const initialSubmenu: Electron.MenuItemConstructorOptions[] = [{
|
||||||
label: t.__('Minimize'),
|
label: t.__('Minimize'),
|
||||||
role: 'minimize'
|
role: 'minimize'
|
||||||
@@ -247,7 +254,7 @@ function getWindowSubmenu(tabs: any[], activeTabIndex: number, enableMenu: boole
|
|||||||
label: tab.props.name,
|
label: tab.props.name,
|
||||||
accelerator: tab.props.role === 'function' ? '' : `${ShortcutKey} + ${tab.props.index + 1}`,
|
accelerator: tab.props.role === 'function' ? '' : `${ShortcutKey} + ${tab.props.index + 1}`,
|
||||||
checked: tab.props.index === activeTabIndex,
|
checked: tab.props.index === activeTabIndex,
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('switch-server-tab', tab.props.index);
|
sendAction('switch-server-tab', tab.props.index);
|
||||||
}
|
}
|
||||||
@@ -262,7 +269,7 @@ function getWindowSubmenu(tabs: any[], activeTabIndex: number, enableMenu: boole
|
|||||||
label: t.__('Switch to Next Organization'),
|
label: t.__('Switch to Next Organization'),
|
||||||
accelerator: 'Ctrl+Tab',
|
accelerator: 'Ctrl+Tab',
|
||||||
enabled: tabs.length > 1,
|
enabled: tabs.length > 1,
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('switch-server-tab', getNextServer(tabs, activeTabIndex));
|
sendAction('switch-server-tab', getNextServer(tabs, activeTabIndex));
|
||||||
}
|
}
|
||||||
@@ -271,7 +278,7 @@ function getWindowSubmenu(tabs: any[], activeTabIndex: number, enableMenu: boole
|
|||||||
label: t.__('Switch to Previous Organization'),
|
label: t.__('Switch to Previous Organization'),
|
||||||
accelerator: 'Ctrl+Shift+Tab',
|
accelerator: 'Ctrl+Shift+Tab',
|
||||||
enabled: tabs.length > 1,
|
enabled: tabs.length > 1,
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('switch-server-tab', getPreviousServer(tabs, activeTabIndex));
|
sendAction('switch-server-tab', getPreviousServer(tabs, activeTabIndex));
|
||||||
}
|
}
|
||||||
@@ -282,15 +289,15 @@ function getWindowSubmenu(tabs: any[], activeTabIndex: number, enableMenu: boole
|
|||||||
return initialSubmenu;
|
return initialSubmenu;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getDarwinTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
function getDarwinTpl(props: MenuProps): Electron.MenuItemConstructorOptions[] {
|
||||||
const { tabs, activeTabIndex, enableMenu } = props;
|
const {tabs, activeTabIndex, enableMenu} = props;
|
||||||
|
|
||||||
return [{
|
return [{
|
||||||
label: app.name,
|
label: app.name,
|
||||||
submenu: [{
|
submenu: [{
|
||||||
label: t.__('Add Organization'),
|
label: t.__('Add Organization'),
|
||||||
accelerator: 'Cmd+Shift+N',
|
accelerator: 'Cmd+Shift+N',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('new-server');
|
sendAction('new-server');
|
||||||
}
|
}
|
||||||
@@ -305,7 +312,7 @@ function getDarwinTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
}, {
|
}, {
|
||||||
label: t.__('Desktop Settings'),
|
label: t.__('Desktop Settings'),
|
||||||
accelerator: 'Cmd+,',
|
accelerator: 'Cmd+,',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('open-settings');
|
sendAction('open-settings');
|
||||||
}
|
}
|
||||||
@@ -314,7 +321,7 @@ function getDarwinTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
label: t.__('Keyboard Shortcuts'),
|
label: t.__('Keyboard Shortcuts'),
|
||||||
accelerator: 'Cmd+Shift+K',
|
accelerator: 'Cmd+Shift+K',
|
||||||
enabled: enableMenu,
|
enabled: enableMenu,
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('shortcut');
|
sendAction('shortcut');
|
||||||
}
|
}
|
||||||
@@ -325,7 +332,7 @@ function getDarwinTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
label: t.__('Copy Zulip URL'),
|
label: t.__('Copy Zulip URL'),
|
||||||
accelerator: 'Cmd+Shift+C',
|
accelerator: 'Cmd+Shift+C',
|
||||||
enabled: enableMenu,
|
enabled: enableMenu,
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('copy-zulip-url');
|
sendAction('copy-zulip-url');
|
||||||
}
|
}
|
||||||
@@ -334,7 +341,7 @@ function getDarwinTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
label: t.__('Log Out of Organization'),
|
label: t.__('Log Out of Organization'),
|
||||||
accelerator: 'Cmd+L',
|
accelerator: 'Cmd+L',
|
||||||
enabled: enableMenu,
|
enabled: enableMenu,
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('log-out');
|
sendAction('log-out');
|
||||||
}
|
}
|
||||||
@@ -373,7 +380,7 @@ function getDarwinTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
submenu: [{
|
submenu: [{
|
||||||
label: t.__('Undo'),
|
label: t.__('Undo'),
|
||||||
accelerator: 'Cmd+Z',
|
accelerator: 'Cmd+Z',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('undo');
|
sendAction('undo');
|
||||||
}
|
}
|
||||||
@@ -381,7 +388,7 @@ function getDarwinTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
}, {
|
}, {
|
||||||
label: t.__('Redo'),
|
label: t.__('Redo'),
|
||||||
accelerator: 'Cmd+Shift+Z',
|
accelerator: 'Cmd+Shift+Z',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('redo');
|
sendAction('redo');
|
||||||
}
|
}
|
||||||
@@ -412,7 +419,7 @@ function getDarwinTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
submenu: getHistorySubmenu(enableMenu)
|
submenu: getHistorySubmenu(enableMenu)
|
||||||
}, {
|
}, {
|
||||||
label: t.__('Window'),
|
label: t.__('Window'),
|
||||||
submenu: getWindowSubmenu(tabs, activeTabIndex, enableMenu)
|
submenu: getWindowSubmenu(tabs, activeTabIndex)
|
||||||
}, {
|
}, {
|
||||||
label: t.__('Tools'),
|
label: t.__('Tools'),
|
||||||
submenu: getToolsSubmenu()
|
submenu: getToolsSubmenu()
|
||||||
@@ -423,14 +430,14 @@ function getDarwinTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
function getOtherTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
function getOtherTpl(props: MenuProps): Electron.MenuItemConstructorOptions[] {
|
||||||
const { tabs, activeTabIndex, enableMenu } = props;
|
const {tabs, activeTabIndex, enableMenu} = props;
|
||||||
return [{
|
return [{
|
||||||
label: t.__('File'),
|
label: t.__('File'),
|
||||||
submenu: [{
|
submenu: [{
|
||||||
label: t.__('Add Organization'),
|
label: t.__('Add Organization'),
|
||||||
accelerator: 'Ctrl+Shift+N',
|
accelerator: 'Ctrl+Shift+N',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('new-server');
|
sendAction('new-server');
|
||||||
}
|
}
|
||||||
@@ -447,7 +454,7 @@ function getOtherTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
}, {
|
}, {
|
||||||
label: t.__('Desktop Settings'),
|
label: t.__('Desktop Settings'),
|
||||||
accelerator: 'Ctrl+,',
|
accelerator: 'Ctrl+,',
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('open-settings');
|
sendAction('open-settings');
|
||||||
}
|
}
|
||||||
@@ -456,7 +463,7 @@ function getOtherTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
label: t.__('Keyboard Shortcuts'),
|
label: t.__('Keyboard Shortcuts'),
|
||||||
accelerator: 'Ctrl+Shift+K',
|
accelerator: 'Ctrl+Shift+K',
|
||||||
enabled: enableMenu,
|
enabled: enableMenu,
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('shortcut');
|
sendAction('shortcut');
|
||||||
}
|
}
|
||||||
@@ -467,7 +474,7 @@ function getOtherTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
label: t.__('Copy Zulip URL'),
|
label: t.__('Copy Zulip URL'),
|
||||||
accelerator: 'Ctrl+Shift+C',
|
accelerator: 'Ctrl+Shift+C',
|
||||||
enabled: enableMenu,
|
enabled: enableMenu,
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('copy-zulip-url');
|
sendAction('copy-zulip-url');
|
||||||
}
|
}
|
||||||
@@ -476,7 +483,7 @@ function getOtherTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
label: t.__('Log Out of Organization'),
|
label: t.__('Log Out of Organization'),
|
||||||
accelerator: 'Ctrl+L',
|
accelerator: 'Ctrl+L',
|
||||||
enabled: enableMenu,
|
enabled: enableMenu,
|
||||||
click(_item: any, focusedWindow: any) {
|
click(_item, focusedWindow) {
|
||||||
if (focusedWindow) {
|
if (focusedWindow) {
|
||||||
sendAction('log-out');
|
sendAction('log-out');
|
||||||
}
|
}
|
||||||
@@ -530,7 +537,7 @@ function getOtherTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
submenu: getHistorySubmenu(enableMenu)
|
submenu: getHistorySubmenu(enableMenu)
|
||||||
}, {
|
}, {
|
||||||
label: t.__('Window'),
|
label: t.__('Window'),
|
||||||
submenu: getWindowSubmenu(tabs, activeTabIndex, enableMenu)
|
submenu: getWindowSubmenu(tabs, activeTabIndex)
|
||||||
}, {
|
}, {
|
||||||
label: t.__('Tools'),
|
label: t.__('Tools'),
|
||||||
submenu: getToolsSubmenu()
|
submenu: getToolsSubmenu()
|
||||||
@@ -541,7 +548,7 @@ function getOtherTpl(props: any): Electron.MenuItemConstructorOptions[] {
|
|||||||
}];
|
}];
|
||||||
}
|
}
|
||||||
|
|
||||||
function sendAction(action: string, ...parameters: any[]): void {
|
function sendAction(action: string, ...parameters: unknown[]): void {
|
||||||
const win = BrowserWindow.getAllWindows()[0];
|
const win = BrowserWindow.getAllWindows()[0];
|
||||||
|
|
||||||
if (process.platform === 'darwin') {
|
if (process.platform === 'darwin') {
|
||||||
@@ -555,19 +562,21 @@ function checkForUpdate(): void {
|
|||||||
appUpdater(true);
|
appUpdater(true);
|
||||||
}
|
}
|
||||||
|
|
||||||
function getNextServer(tabs: any[], activeTabIndex: number): number {
|
function getNextServer(tabs: ServerOrFunctionalTab[], activeTabIndex: number): number {
|
||||||
do {
|
do {
|
||||||
activeTabIndex = (activeTabIndex + 1) % tabs.length;
|
activeTabIndex = (activeTabIndex + 1) % tabs.length;
|
||||||
}
|
}
|
||||||
while (tabs[activeTabIndex].props.role !== 'server');
|
while (tabs[activeTabIndex].props.role !== 'server');
|
||||||
|
|
||||||
return activeTabIndex;
|
return activeTabIndex;
|
||||||
}
|
}
|
||||||
|
|
||||||
function getPreviousServer(tabs: any[], activeTabIndex: number): number {
|
function getPreviousServer(tabs: ServerOrFunctionalTab[], activeTabIndex: number): number {
|
||||||
do {
|
do {
|
||||||
activeTabIndex = (activeTabIndex - 1 + tabs.length) % tabs.length;
|
activeTabIndex = (activeTabIndex - 1 + tabs.length) % tabs.length;
|
||||||
}
|
}
|
||||||
while (tabs[activeTabIndex].props.role !== 'server');
|
while (tabs[activeTabIndex].props.role !== 'server');
|
||||||
|
|
||||||
return activeTabIndex;
|
return activeTabIndex;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -577,7 +586,7 @@ async function resetAppSettings(): Promise<void> {
|
|||||||
// We save App's settings/configurations in following files
|
// We save App's settings/configurations in following files
|
||||||
const settingFiles = ['config/window-state.json', 'config/domain.json', 'config/settings.json', 'config/certificates.json'];
|
const settingFiles = ['config/window-state.json', 'config/domain.json', 'config/settings.json', 'config/certificates.json'];
|
||||||
|
|
||||||
const { response } = await dialog.showMessageBox({
|
const {response} = await dialog.showMessageBox({
|
||||||
type: 'warning',
|
type: 'warning',
|
||||||
buttons: ['YES', 'NO'],
|
buttons: ['YES', 'NO'],
|
||||||
defaultId: 0,
|
defaultId: 0,
|
||||||
@@ -587,7 +596,7 @@ async function resetAppSettings(): Promise<void> {
|
|||||||
if (response === 0) {
|
if (response === 0) {
|
||||||
settingFiles.forEach(settingFileName => {
|
settingFiles.forEach(settingFileName => {
|
||||||
const getSettingFilesPath = path.join(app.getPath('appData'), appName, settingFileName);
|
const getSettingFilesPath = path.join(app.getPath('appData'), appName, settingFileName);
|
||||||
fs.access(getSettingFilesPath, (error: any) => {
|
fs.access(getSettingFilesPath, (error: NodeJS.ErrnoException) => {
|
||||||
if (error) {
|
if (error) {
|
||||||
logger.error('Error while resetting app settings.');
|
logger.error('Error while resetting app settings.');
|
||||||
logger.error(error);
|
logger.error(error);
|
||||||
@@ -601,7 +610,7 @@ async function resetAppSettings(): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setMenu(props: any): void {
|
export function setMenu(props: MenuProps): void {
|
||||||
const tpl = process.platform === 'darwin' ? getDarwinTpl(props) : getOtherTpl(props);
|
const tpl = process.platform === 'darwin' ? getDarwinTpl(props) : getOtherTpl(props);
|
||||||
const menu = Menu.buildFromTemplate(tpl);
|
const menu = Menu.buildFromTemplate(tpl);
|
||||||
Menu.setApplicationMenu(menu);
|
Menu.setApplicationMenu(menu);
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { app } from 'electron';
|
import {app} from 'electron';
|
||||||
|
|
||||||
import AutoLaunch from 'auto-launch';
|
import AutoLaunch from 'auto-launch';
|
||||||
import isDev from 'electron-is-dev';
|
import isDev from 'electron-is-dev';
|
||||||
import * as ConfigUtil from '../renderer/js/utils/config-util';
|
import * as ConfigUtil from '../renderer/js/utils/config-util';
|
||||||
|
|
||||||
export const setAutoLaunch = (AutoLaunchValue: boolean): void => {
|
export const setAutoLaunch = async (AutoLaunchValue: boolean): Promise<void> => {
|
||||||
// Don't run this in development
|
// Don't run this in development
|
||||||
if (isDev) {
|
if (isDev) {
|
||||||
return;
|
return;
|
||||||
@@ -12,16 +12,16 @@ export const setAutoLaunch = (AutoLaunchValue: boolean): void => {
|
|||||||
|
|
||||||
const autoLaunchOption = ConfigUtil.getConfigItem('startAtLogin', AutoLaunchValue);
|
const autoLaunchOption = ConfigUtil.getConfigItem('startAtLogin', AutoLaunchValue);
|
||||||
|
|
||||||
// setLoginItemSettings doesn't support linux
|
// `setLoginItemSettings` doesn't support linux
|
||||||
if (process.platform === 'linux') {
|
if (process.platform === 'linux') {
|
||||||
const ZulipAutoLauncher = new AutoLaunch({
|
const ZulipAutoLauncher = new AutoLaunch({
|
||||||
name: 'Zulip',
|
name: 'Zulip',
|
||||||
isHidden: false
|
isHidden: false
|
||||||
});
|
});
|
||||||
if (autoLaunchOption) {
|
if (autoLaunchOption) {
|
||||||
ZulipAutoLauncher.enable();
|
await ZulipAutoLauncher.enable();
|
||||||
} else {
|
} else {
|
||||||
ZulipAutoLauncher.disable();
|
await ZulipAutoLauncher.disable();
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
app.setLoginItemSettings({
|
app.setLoginItemSettings({
|
||||||
|
|||||||
82
app/renderer/js/clipboard-decrypter.ts
Normal file
82
app/renderer/js/clipboard-decrypter.ts
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
import {clipboard} from 'electron';
|
||||||
|
import crypto from 'crypto';
|
||||||
|
|
||||||
|
// This helper is exposed via electron_bridge for use in the social
|
||||||
|
// login flow.
|
||||||
|
//
|
||||||
|
// It consists of a key and a promised token. The in-app page sends
|
||||||
|
// the key to the server, and opens the user’s browser to a page where
|
||||||
|
// they can log in and get a token encrypted to that key. When the
|
||||||
|
// user copies the encrypted token from their browser to the
|
||||||
|
// clipboard, we decrypt it and resolve the promise. The in-app page
|
||||||
|
// then uses the decrypted token to log the user in within the app.
|
||||||
|
//
|
||||||
|
// The encryption is authenticated (AES-GCM) to guarantee that we
|
||||||
|
// don’t leak anything from the user’s clipboard other than the token
|
||||||
|
// intended for us.
|
||||||
|
|
||||||
|
export class ClipboardDecrypterImpl implements ClipboardDecrypter {
|
||||||
|
version: number;
|
||||||
|
key: Uint8Array;
|
||||||
|
pasted: Promise<string>;
|
||||||
|
|
||||||
|
constructor(_: number) {
|
||||||
|
// At this time, the only version is 1.
|
||||||
|
this.version = 1;
|
||||||
|
this.key = crypto.randomBytes(32);
|
||||||
|
this.pasted = new Promise(resolve => {
|
||||||
|
let interval: NodeJS.Timeout | null = null;
|
||||||
|
const startPolling = () => {
|
||||||
|
if (interval === null) {
|
||||||
|
interval = setInterval(poll, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
poll();
|
||||||
|
};
|
||||||
|
|
||||||
|
const stopPolling = () => {
|
||||||
|
if (interval !== null) {
|
||||||
|
clearInterval(interval);
|
||||||
|
interval = null;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const poll = () => {
|
||||||
|
let plaintext;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const data = Buffer.from(clipboard.readText(), 'hex');
|
||||||
|
const iv = data.slice(0, 12);
|
||||||
|
const ciphertext = data.slice(12, -16);
|
||||||
|
const authTag = data.slice(-16);
|
||||||
|
const decipher = crypto.createDecipheriv(
|
||||||
|
'aes-256-gcm',
|
||||||
|
this.key,
|
||||||
|
iv,
|
||||||
|
{authTagLength: 16}
|
||||||
|
);
|
||||||
|
decipher.setAuthTag(authTag);
|
||||||
|
plaintext =
|
||||||
|
decipher.update(ciphertext, undefined, 'utf8') +
|
||||||
|
decipher.final('utf8');
|
||||||
|
} catch (_) {
|
||||||
|
// If the parsing or decryption failed in any way,
|
||||||
|
// the correct token hasn’t been copied yet; try
|
||||||
|
// again next time.
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.removeEventListener('focus', startPolling);
|
||||||
|
window.removeEventListener('blur', stopPolling);
|
||||||
|
stopPolling();
|
||||||
|
resolve(plaintext);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.addEventListener('focus', startPolling);
|
||||||
|
window.addEventListener('blur', stopPolling);
|
||||||
|
if (document.hasFocus()) {
|
||||||
|
startPolling();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,13 @@
|
|||||||
import Tab, { TabProps } from './tab';
|
import Tab, {TabProps} from './tab';
|
||||||
|
|
||||||
export default class FunctionalTab extends Tab {
|
export default class FunctionalTab extends Tab {
|
||||||
$closeButton: Element;
|
$closeButton: Element;
|
||||||
|
|
||||||
|
constructor(props: TabProps) {
|
||||||
|
super(props);
|
||||||
|
this.init();
|
||||||
|
}
|
||||||
|
|
||||||
template(): string {
|
template(): string {
|
||||||
return `<div class="tab functional-tab" data-tab-id="${this.props.tabIndex}">
|
return `<div class="tab functional-tab" data-tab-id="${this.props.tabIndex}">
|
||||||
<div class="server-tab-badge close-button">
|
<div class="server-tab-badge close-button">
|
||||||
@@ -13,11 +19,6 @@ export default class FunctionalTab extends Tab {
|
|||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor(props: TabProps) {
|
|
||||||
super(props);
|
|
||||||
this.init();
|
|
||||||
}
|
|
||||||
|
|
||||||
init(): void {
|
init(): void {
|
||||||
this.$el = this.generateNodeFromTemplate(this.template());
|
this.$el = this.generateNodeFromTemplate(this.template());
|
||||||
if (this.props.name !== 'Settings') {
|
if (this.props.name !== 'Settings') {
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { ipcRenderer, remote } from 'electron';
|
import {ipcRenderer, remote} from 'electron';
|
||||||
|
|
||||||
import * as LinkUtil from '../utils/link-util';
|
import * as LinkUtil from '../utils/link-util';
|
||||||
import * as ConfigUtil from '../utils/config-util';
|
import * as ConfigUtil from '../utils/config-util';
|
||||||
import type WebView from './webview';
|
import type WebView from './webview';
|
||||||
|
|
||||||
const { shell, app } = remote;
|
const {shell, app} = remote;
|
||||||
|
|
||||||
const dingSound = new Audio('../resources/sounds/ding.ogg');
|
const dingSound = new Audio('../resources/sounds/ding.ogg');
|
||||||
|
|
||||||
@@ -16,41 +16,45 @@ export default function handleExternalLink(this: WebView, event: Electron.NewWin
|
|||||||
|
|
||||||
if (LinkUtil.isUploadsUrl(this.props.url, url)) {
|
if (LinkUtil.isUploadsUrl(this.props.url, url)) {
|
||||||
ipcRenderer.send('downloadFile', url.href, downloadPath);
|
ipcRenderer.send('downloadFile', url.href, downloadPath);
|
||||||
ipcRenderer.once('downloadFileCompleted', (_event: Event, filePath: string, fileName: string) => {
|
ipcRenderer.once('downloadFileCompleted', async (_event: Event, filePath: string, fileName: string) => {
|
||||||
const downloadNotification = new Notification('Download Complete', {
|
const downloadNotification = new Notification('Download Complete', {
|
||||||
body: `Click to show ${fileName} in folder`,
|
body: `Click to show ${fileName} in folder`,
|
||||||
silent: true // We'll play our own sound - ding.ogg
|
silent: true // We'll play our own sound - ding.ogg
|
||||||
});
|
});
|
||||||
|
|
||||||
// Play sound to indicate download complete
|
|
||||||
if (!ConfigUtil.getConfigItem('silent')) {
|
|
||||||
dingSound.play();
|
|
||||||
}
|
|
||||||
|
|
||||||
downloadNotification.addEventListener('click', () => {
|
downloadNotification.addEventListener('click', () => {
|
||||||
// Reveal file in download folder
|
// Reveal file in download folder
|
||||||
shell.showItemInFolder(filePath);
|
shell.showItemInFolder(filePath);
|
||||||
});
|
});
|
||||||
ipcRenderer.removeAllListeners('downloadFileFailed');
|
ipcRenderer.removeAllListeners('downloadFileFailed');
|
||||||
|
|
||||||
|
// Play sound to indicate download complete
|
||||||
|
if (!ConfigUtil.getConfigItem('silent')) {
|
||||||
|
await dingSound.play();
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.once('downloadFileFailed', () => {
|
ipcRenderer.once('downloadFileFailed', (_event: Event, state: string) => {
|
||||||
// Automatic download failed, so show save dialog prompt and download
|
// Automatic download failed, so show save dialog prompt and download
|
||||||
// through webview
|
// through webview
|
||||||
// Only do this if it is the automatic download, otherwise show an error (so we aren't showing two save
|
// Only do this if it is the automatic download, otherwise show an error (so we aren't showing two save
|
||||||
// prompts right after each other)
|
// prompts right after each other)
|
||||||
if (ConfigUtil.getConfigItem('promptDownload', false)) {
|
// Check that the download is not cancelled by user
|
||||||
// We need to create a "new Notification" to display it, but just `Notification(...)` on its own
|
if (state !== 'cancelled') {
|
||||||
// doesn't work
|
if (ConfigUtil.getConfigItem('promptDownload', false)) {
|
||||||
new Notification('Download Complete', { // eslint-disable-line no-new
|
// We need to create a "new Notification" to display it, but just `Notification(...)` on its own
|
||||||
body: 'Download failed'
|
// doesn't work
|
||||||
});
|
new Notification('Download Complete', { // eslint-disable-line no-new
|
||||||
} else {
|
body: 'Download failed'
|
||||||
this.$el.downloadURL(url.href);
|
});
|
||||||
|
} else {
|
||||||
|
this.$el.downloadURL(url.href);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
ipcRenderer.removeAllListeners('downloadFileCompleted');
|
ipcRenderer.removeAllListeners('downloadFileCompleted');
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
LinkUtil.openBrowser(url);
|
(async () => LinkUtil.openBrowser(url))();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,16 @@
|
|||||||
import { ipcRenderer } from 'electron';
|
import {ipcRenderer} from 'electron';
|
||||||
|
|
||||||
import Tab, { TabProps } from './tab';
|
import Tab, {TabProps} from './tab';
|
||||||
import * as SystemUtil from '../utils/system-util';
|
import * as SystemUtil from '../utils/system-util';
|
||||||
|
|
||||||
export default class ServerTab extends Tab {
|
export default class ServerTab extends Tab {
|
||||||
$badge: Element;
|
$badge: Element;
|
||||||
|
|
||||||
|
constructor(props: TabProps) {
|
||||||
|
super(props);
|
||||||
|
this.init();
|
||||||
|
}
|
||||||
|
|
||||||
template(): string {
|
template(): string {
|
||||||
return `<div class="tab" data-tab-id="${this.props.tabIndex}">
|
return `<div class="tab" data-tab-id="${this.props.tabIndex}">
|
||||||
<div class="server-tooltip" style="display:none">${this.props.name}</div>
|
<div class="server-tooltip" style="display:none">${this.props.name}</div>
|
||||||
@@ -17,11 +22,6 @@ export default class ServerTab extends Tab {
|
|||||||
</div>`;
|
</div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
constructor(props: TabProps) {
|
|
||||||
super(props);
|
|
||||||
this.init();
|
|
||||||
}
|
|
||||||
|
|
||||||
init(): void {
|
init(): void {
|
||||||
this.$el = this.generateNodeFromTemplate(this.template());
|
this.$el = this.generateNodeFromTemplate(this.template());
|
||||||
this.props.$root.append(this.$el);
|
this.props.$root.append(this.$el);
|
||||||
|
|||||||
@@ -48,7 +48,7 @@ export default class Tab extends BaseComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
destroy(): void {
|
destroy(): void {
|
||||||
this.$el.parentNode.removeChild(this.$el);
|
this.$el.remove();
|
||||||
this.webview.$el.parentNode.removeChild(this.webview.$el);
|
this.webview.$el.remove();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ipcRenderer, remote } from 'electron';
|
import {ipcRenderer, remote} from 'electron';
|
||||||
|
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
@@ -7,7 +7,7 @@ import * as SystemUtil from '../utils/system-util';
|
|||||||
import BaseComponent from './base';
|
import BaseComponent from './base';
|
||||||
import handleExternalLink from './handle-external-link';
|
import handleExternalLink from './handle-external-link';
|
||||||
|
|
||||||
const { app, dialog } = remote;
|
const {app, dialog} = remote;
|
||||||
|
|
||||||
const shouldSilentWebview = ConfigUtil.getConfigItem('silent');
|
const shouldSilentWebview = ConfigUtil.getConfigItem('silent');
|
||||||
|
|
||||||
@@ -15,15 +15,16 @@ interface WebViewProps {
|
|||||||
$root: Element;
|
$root: Element;
|
||||||
index: number;
|
index: number;
|
||||||
tabIndex: number;
|
tabIndex: number;
|
||||||
url: any;
|
url: string;
|
||||||
role: string;
|
role: string;
|
||||||
name: string;
|
name: string;
|
||||||
isActive: () => boolean;
|
isActive: () => boolean;
|
||||||
switchLoading: (loading: any, url: string) => void;
|
switchLoading: (loading: boolean, url: string) => void;
|
||||||
onNetworkError: (index: number) => void;
|
onNetworkError: (index: number) => void;
|
||||||
nodeIntegration: boolean;
|
nodeIntegration: boolean;
|
||||||
preload: boolean;
|
preload: boolean;
|
||||||
onTitleChange: any;
|
onTitleChange: () => void;
|
||||||
|
ignoreCerts?: boolean;
|
||||||
hasPermission?: (origin: string, permission: string) => boolean;
|
hasPermission?: (origin: string, permission: string) => boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,10 +38,6 @@ export default class WebView extends BaseComponent {
|
|||||||
$el: Electron.WebviewTag;
|
$el: Electron.WebviewTag;
|
||||||
domReady?: Promise<void>;
|
domReady?: Promise<void>;
|
||||||
|
|
||||||
// This is required because in main.js we access WebView.method as
|
|
||||||
// webview[method].
|
|
||||||
[key: string]: any;
|
|
||||||
|
|
||||||
constructor(props: WebViewProps) {
|
constructor(props: WebViewProps) {
|
||||||
super();
|
super();
|
||||||
|
|
||||||
@@ -87,7 +84,7 @@ export default class WebView extends BaseComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
this.$el.addEventListener('page-title-updated', event => {
|
this.$el.addEventListener('page-title-updated', event => {
|
||||||
const { title } = event;
|
const {title} = event;
|
||||||
this.badgeCount = this.getBadgeCount(title);
|
this.badgeCount = this.getBadgeCount(title);
|
||||||
this.props.onTitleChange();
|
this.props.onTitleChange();
|
||||||
});
|
});
|
||||||
@@ -97,6 +94,7 @@ export default class WebView extends BaseComponent {
|
|||||||
if (isSettingPage) {
|
if (isSettingPage) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.canGoBackButton();
|
this.canGoBackButton();
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -105,14 +103,14 @@ export default class WebView extends BaseComponent {
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.$el.addEventListener('page-favicon-updated', event => {
|
this.$el.addEventListener('page-favicon-updated', event => {
|
||||||
const { favicons } = event;
|
const {favicons} = event;
|
||||||
|
|
||||||
// This returns a string of favicons URL. If there is a PM counts in unread messages then the URL would be like
|
// This returns a string of favicons URL. If there is a PM counts in unread messages then the URL would be like
|
||||||
// https://chat.zulip.org/static/images/favicon/favicon-pms.png
|
// https://chat.zulip.org/static/images/favicon/favicon-pms.png
|
||||||
if (favicons[0].indexOf('favicon-pms') > 0 && process.platform === 'darwin') {
|
if (favicons[0].indexOf('favicon-pms') > 0 && process.platform === 'darwin') {
|
||||||
// This api is only supported on macOS
|
// This api is only supported on macOS
|
||||||
app.dock.setBadge('●');
|
app.dock.setBadge('●');
|
||||||
// bounce the dock
|
// Bounce the dock
|
||||||
if (ConfigUtil.getConfigItem('dockBouncing')) {
|
if (ConfigUtil.getConfigItem('dockBouncing')) {
|
||||||
app.dock.bounce();
|
app.dock.bounce();
|
||||||
}
|
}
|
||||||
@@ -123,6 +121,7 @@ export default class WebView extends BaseComponent {
|
|||||||
if (this.props.role === 'server') {
|
if (this.props.role === 'server') {
|
||||||
this.$el.classList.add('onload');
|
this.$el.classList.add('onload');
|
||||||
}
|
}
|
||||||
|
|
||||||
this.loading = false;
|
this.loading = false;
|
||||||
this.props.switchLoading(false, this.props.url);
|
this.props.switchLoading(false, this.props.url);
|
||||||
this.show();
|
this.show();
|
||||||
@@ -134,7 +133,7 @@ export default class WebView extends BaseComponent {
|
|||||||
});
|
});
|
||||||
|
|
||||||
this.$el.addEventListener('did-fail-load', event => {
|
this.$el.addEventListener('did-fail-load', event => {
|
||||||
const { errorDescription } = event;
|
const {errorDescription} = event;
|
||||||
const hasConnectivityErr = SystemUtil.connectivityERR.includes(errorDescription);
|
const hasConnectivityErr = SystemUtil.connectivityERR.includes(errorDescription);
|
||||||
if (hasConnectivityErr) {
|
if (hasConnectivityErr) {
|
||||||
console.error('error', errorDescription);
|
console.error('error', errorDescription);
|
||||||
@@ -188,9 +187,9 @@ export default class WebView extends BaseComponent {
|
|||||||
this.focus();
|
this.focus();
|
||||||
this.props.onTitleChange();
|
this.props.onTitleChange();
|
||||||
// Injecting preload css in webview to override some css rules
|
// Injecting preload css in webview to override some css rules
|
||||||
this.$el.insertCSS(fs.readFileSync(path.join(__dirname, '/../../css/preload.css'), 'utf8'));
|
(async () => this.$el.insertCSS(fs.readFileSync(path.join(__dirname, '/../../css/preload.css'), 'utf8')))();
|
||||||
|
|
||||||
// get customCSS again from config util to avoid warning user again
|
// Get customCSS again from config util to avoid warning user again
|
||||||
this.customCSS = ConfigUtil.getConfigItem('customCSS');
|
this.customCSS = ConfigUtil.getConfigItem('customCSS');
|
||||||
if (this.customCSS) {
|
if (this.customCSS) {
|
||||||
if (!fs.existsSync(this.customCSS)) {
|
if (!fs.existsSync(this.customCSS)) {
|
||||||
@@ -202,12 +201,12 @@ export default class WebView extends BaseComponent {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.$el.insertCSS(fs.readFileSync(path.resolve(__dirname, this.customCSS), 'utf8'));
|
(async () => this.$el.insertCSS(fs.readFileSync(path.resolve(__dirname, this.customCSS), 'utf8')))();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
focus(): void {
|
focus(): void {
|
||||||
// focus Webview and it's contents when Window regain focus.
|
// Focus Webview and it's contents when Window regain focus.
|
||||||
const webContents = this.$el.getWebContents();
|
const webContents = this.$el.getWebContents();
|
||||||
// HACK: webContents.isFocused() seems to be true even without the element
|
// HACK: webContents.isFocused() seems to be true even without the element
|
||||||
// being in focus. So, we check against `document.activeElement`.
|
// being in focus. So, we check against `document.activeElement`.
|
||||||
@@ -296,8 +295,8 @@ export default class WebView extends BaseComponent {
|
|||||||
this.init();
|
this.init();
|
||||||
}
|
}
|
||||||
|
|
||||||
async send(channel: string, ...parameters: any[]): Promise<void> {
|
async send(channel: string, ...parameters: unknown[]): Promise<void> {
|
||||||
await this.domReady;
|
await this.domReady;
|
||||||
this.$el.send(channel, ...parameters);
|
await this.$el.send(channel, ...parameters);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { ipcRenderer } from 'electron';
|
import {ipcRenderer} from 'electron';
|
||||||
|
|
||||||
import { EventEmitter } from 'events';
|
import {EventEmitter} from 'events';
|
||||||
|
|
||||||
import { NotificationData, newNotification } from './notification';
|
import {ClipboardDecrypterImpl} from './clipboard-decrypter';
|
||||||
|
import {NotificationData, newNotification} from './notification';
|
||||||
|
|
||||||
type ListenerType = ((...args: any[]) => void);
|
type ListenerType = ((...args: any[]) => void);
|
||||||
|
|
||||||
class ElectronBridge extends EventEmitter {
|
class ElectronBridgeImpl extends EventEmitter implements ElectronBridge {
|
||||||
send_notification_reply_message_supported: boolean;
|
send_notification_reply_message_supported: boolean;
|
||||||
idle_on_system: boolean;
|
idle_on_system: boolean;
|
||||||
last_active_on_system: number;
|
last_active_on_system: number;
|
||||||
@@ -21,7 +22,7 @@ class ElectronBridge extends EventEmitter {
|
|||||||
this.last_active_on_system = Date.now();
|
this.last_active_on_system = Date.now();
|
||||||
}
|
}
|
||||||
|
|
||||||
send_event = (eventName: string | symbol, ...args: any[]): void => {
|
send_event = (eventName: string | symbol, ...args: unknown[]): void => {
|
||||||
this.emit(eventName, ...args);
|
this.emit(eventName, ...args);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -46,9 +47,12 @@ class ElectronBridge extends EventEmitter {
|
|||||||
set_send_notification_reply_message_supported = (value: boolean): void => {
|
set_send_notification_reply_message_supported = (value: boolean): void => {
|
||||||
this.send_notification_reply_message_supported = value;
|
this.send_notification_reply_message_supported = value;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
decrypt_clipboard = (version: number): ClipboardDecrypterImpl =>
|
||||||
|
new ClipboardDecrypterImpl(version);
|
||||||
}
|
}
|
||||||
|
|
||||||
const electron_bridge = new ElectronBridge();
|
const electron_bridge = new ElectronBridgeImpl();
|
||||||
|
|
||||||
electron_bridge.on('total_unread_count', (...args) => {
|
electron_bridge.on('total_unread_count', (...args) => {
|
||||||
ipcRenderer.send('unread-count', ...args);
|
ipcRenderer.send('unread-count', ...args);
|
||||||
@@ -59,13 +63,17 @@ electron_bridge.on('realm_name', realmName => {
|
|||||||
ipcRenderer.send('realm-name-changed', serverURL, realmName);
|
ipcRenderer.send('realm-name-changed', serverURL, realmName);
|
||||||
});
|
});
|
||||||
|
|
||||||
electron_bridge.on('realm_icon_url', iconURL => {
|
electron_bridge.on('realm_icon_url', (iconURL: unknown) => {
|
||||||
|
if (typeof iconURL !== 'string') {
|
||||||
|
throw new TypeError('Expected string for iconURL');
|
||||||
|
}
|
||||||
|
|
||||||
const serverURL = location.origin;
|
const serverURL = location.origin;
|
||||||
iconURL = iconURL.includes('http') ? iconURL : `${serverURL}${iconURL}`;
|
iconURL = iconURL.includes('http') ? iconURL : `${serverURL}${iconURL}`;
|
||||||
ipcRenderer.send('realm-icon-changed', serverURL, iconURL);
|
ipcRenderer.send('realm-icon-changed', serverURL, iconURL);
|
||||||
});
|
});
|
||||||
|
|
||||||
// this follows node's idiomatic implementation of event
|
// This follows node's idiomatic implementation of event
|
||||||
// emitters to make event handling more simpler instead of using
|
// emitters to make event handling more simpler instead of using
|
||||||
// functions zulip side will emit event using ElectronBrigde.send_event
|
// functions zulip side will emit event using ElectronBrigde.send_event
|
||||||
// which is alias of .emit and on this side we can handle the data by adding
|
// which is alias of .emit and on this side we can handle the data by adding
|
||||||
|
|||||||
@@ -1,19 +1,17 @@
|
|||||||
import { remote } from 'electron';
|
import {remote} from 'electron';
|
||||||
import SendFeedback from '@electron-elements/send-feedback';
|
import SendFeedback from '@electron-elements/send-feedback';
|
||||||
|
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
|
|
||||||
const { app } = remote;
|
const {app} = remote;
|
||||||
|
|
||||||
interface SendFeedback extends HTMLElement {
|
customElements.define('send-feedback', SendFeedback);
|
||||||
[key: string]: any;
|
export const sendFeedback: SendFeedback = document.querySelector('send-feedback');
|
||||||
}
|
export const feedbackHolder = sendFeedback.parentElement;
|
||||||
|
|
||||||
type SendFeedbackType = SendFeedback;
|
// Make the button color match zulip app's theme
|
||||||
|
sendFeedback.customStyles = `
|
||||||
// make the button color match zulip app's theme
|
|
||||||
SendFeedback.customStyles = `
|
|
||||||
button:hover, button:focus {
|
button:hover, button:focus {
|
||||||
border-color: #4EBFAC;
|
border-color: #4EBFAC;
|
||||||
color: #4EBFAC;
|
color: #4EBFAC;
|
||||||
@@ -30,10 +28,6 @@ button {
|
|||||||
}
|
}
|
||||||
`;
|
`;
|
||||||
|
|
||||||
customElements.define('send-feedback', SendFeedback);
|
|
||||||
export const sendFeedback: SendFeedbackType = document.querySelector('send-feedback');
|
|
||||||
export const feedbackHolder = sendFeedback.parentElement;
|
|
||||||
|
|
||||||
/* eslint-disable no-multi-str */
|
/* eslint-disable no-multi-str */
|
||||||
|
|
||||||
// customize the fields of custom elements
|
// customize the fields of custom elements
|
||||||
@@ -62,7 +56,7 @@ sendFeedback.useReporter('emailReporter', {
|
|||||||
});
|
});
|
||||||
|
|
||||||
feedbackHolder.addEventListener('click', (event: Event) => {
|
feedbackHolder.addEventListener('click', (event: Event) => {
|
||||||
// only remove the class if the grey out faded
|
// Only remove the class if the grey out faded
|
||||||
// part is clicked and not the feedback element itself
|
// part is clicked and not the feedback element itself
|
||||||
if (event.target === event.currentTarget) {
|
if (event.target === event.currentTarget) {
|
||||||
feedbackHolder.classList.remove('show');
|
feedbackHolder.classList.remove('show');
|
||||||
|
|||||||
@@ -1,25 +1,36 @@
|
|||||||
'use strict';
|
'use strict';
|
||||||
|
|
||||||
|
interface CompatElectronBridge extends ElectronBridge {
|
||||||
|
readonly idle_on_system: boolean;
|
||||||
|
readonly last_active_on_system: number;
|
||||||
|
send_notification_reply_message_supported: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
(() => {
|
(() => {
|
||||||
const zulipWindow = window as typeof window & {
|
const zulipWindow = window as typeof window & {
|
||||||
electron_bridge: any;
|
electron_bridge: CompatElectronBridge;
|
||||||
narrow: any;
|
narrow: {
|
||||||
page_params: any;
|
by_subject?: (target_id: number, opts: {trigger?: string}) => void;
|
||||||
raw_electron_bridge: any;
|
by_topic?: (target_id: number, opts: {trigger?: string}) => void;
|
||||||
|
};
|
||||||
|
page_params?: {
|
||||||
|
default_language?: string;
|
||||||
|
};
|
||||||
|
raw_electron_bridge: ElectronBridge;
|
||||||
};
|
};
|
||||||
|
|
||||||
const electron_bridge = {
|
const electron_bridge: CompatElectronBridge = {
|
||||||
...zulipWindow.raw_electron_bridge,
|
...zulipWindow.raw_electron_bridge,
|
||||||
|
|
||||||
get idle_on_system() {
|
get idle_on_system(): boolean {
|
||||||
return this.get_idle_on_system();
|
return this.get_idle_on_system();
|
||||||
},
|
},
|
||||||
|
|
||||||
get last_active_on_system() {
|
get last_active_on_system(): number {
|
||||||
return this.get_last_active_on_system();
|
return this.get_last_active_on_system();
|
||||||
},
|
},
|
||||||
|
|
||||||
get send_notification_reply_message_supported() {
|
get send_notification_reply_message_supported(): boolean {
|
||||||
return this.get_send_notification_reply_message_supported();
|
return this.get_send_notification_reply_message_supported();
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -39,7 +50,7 @@
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const { page_params } = zulipWindow;
|
const {page_params} = zulipWindow;
|
||||||
if (page_params) {
|
if (page_params) {
|
||||||
electron_bridge.send_event('zulip-loaded', {
|
electron_bridge.send_event('zulip-loaded', {
|
||||||
serverLanguage: page_params.default_language
|
serverLanguage: page_params.default_language
|
||||||
@@ -47,10 +58,10 @@
|
|||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
|
|
||||||
electron_bridge.on_event('narrow-by-topic', (id: string) => {
|
electron_bridge.on_event('narrow-by-topic', (id: number) => {
|
||||||
const { narrow } = zulipWindow;
|
const {narrow} = zulipWindow;
|
||||||
const narrowByTopic = narrow.by_topic || narrow.by_subject;
|
const narrowByTopic = narrow.by_topic || narrow.by_subject;
|
||||||
narrowByTopic(id, { trigger: 'notification' });
|
narrowByTopic(id, {trigger: 'notification'});
|
||||||
});
|
});
|
||||||
|
|
||||||
function attributeListener<T extends EventTarget>(type: string): PropertyDescriptor {
|
function attributeListener<T extends EventTarget>(type: string): PropertyDescriptor {
|
||||||
@@ -73,6 +84,7 @@
|
|||||||
if (!(symbol in this)) {
|
if (!(symbol in this)) {
|
||||||
this.addEventListener(type, listener);
|
this.addEventListener(type, listener);
|
||||||
}
|
}
|
||||||
|
|
||||||
(this as any)[symbol] = value;
|
(this as any)[symbol] = value;
|
||||||
} else if (symbol in this) {
|
} else if (symbol in this) {
|
||||||
this.removeEventListener(type, listener);
|
this.removeEventListener(type, listener);
|
||||||
@@ -107,6 +119,7 @@
|
|||||||
if (callback) {
|
if (callback) {
|
||||||
callback(await Promise.resolve(NativeNotification.permission));
|
callback(await Promise.resolve(NativeNotification.permission));
|
||||||
}
|
}
|
||||||
|
|
||||||
return NativeNotification.permission;
|
return NativeNotification.permission;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,10 +1,10 @@
|
|||||||
import { ipcRenderer, remote, clipboard } from 'electron';
|
import {ipcRenderer, remote, clipboard} from 'electron';
|
||||||
import { feedbackHolder } from './feedback';
|
import {feedbackHolder} from './feedback';
|
||||||
|
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import escape from 'escape-html';
|
import escape from 'escape-html';
|
||||||
import isDev from 'electron-is-dev';
|
import isDev from 'electron-is-dev';
|
||||||
const { session, app, Menu, dialog } = remote;
|
const {session, app, Menu, dialog} = remote;
|
||||||
|
|
||||||
// eslint-disable-next-line import/no-unassigned-import
|
// eslint-disable-next-line import/no-unassigned-import
|
||||||
import './tray';
|
import './tray';
|
||||||
@@ -21,6 +21,7 @@ import * as CommonUtil from './utils/common-util';
|
|||||||
import * as EnterpriseUtil from './utils/enterprise-util';
|
import * as EnterpriseUtil from './utils/enterprise-util';
|
||||||
import * as LinkUtil from './utils/link-util';
|
import * as LinkUtil from './utils/link-util';
|
||||||
import * as Messages from '../../resources/messages';
|
import * as Messages from '../../resources/messages';
|
||||||
|
import type {DNDSettings} from './utils/dnd-util';
|
||||||
|
|
||||||
interface FunctionalTabProps {
|
interface FunctionalTabProps {
|
||||||
name: string;
|
name: string;
|
||||||
@@ -28,11 +29,7 @@ interface FunctionalTabProps {
|
|||||||
url: string;
|
url: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface AnyObject {
|
interface SettingsOptions extends DNDSettings {
|
||||||
[key: string]: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface SettingsOptions {
|
|
||||||
autoHideMenubar: boolean;
|
autoHideMenubar: boolean;
|
||||||
trayIcon: boolean;
|
trayIcon: boolean;
|
||||||
useManualProxy: boolean;
|
useManualProxy: boolean;
|
||||||
@@ -42,25 +39,17 @@ interface SettingsOptions {
|
|||||||
startAtLogin: boolean;
|
startAtLogin: boolean;
|
||||||
startMinimized: boolean;
|
startMinimized: boolean;
|
||||||
enableSpellchecker: boolean;
|
enableSpellchecker: boolean;
|
||||||
showNotification: boolean;
|
|
||||||
autoUpdate: boolean;
|
autoUpdate: boolean;
|
||||||
betaUpdate: boolean;
|
betaUpdate: boolean;
|
||||||
errorReporting: boolean;
|
errorReporting: boolean;
|
||||||
customCSS: boolean;
|
customCSS: boolean;
|
||||||
silent: boolean;
|
|
||||||
lastActiveTab: number;
|
lastActiveTab: number;
|
||||||
dnd: boolean;
|
dnd: boolean;
|
||||||
dndPreviousSettings: {
|
dndPreviousSettings: DNDSettings;
|
||||||
showNotification: boolean;
|
|
||||||
silent: boolean;
|
|
||||||
flashTaskbarOnMessage?: boolean;
|
|
||||||
};
|
|
||||||
downloadsPath: string;
|
downloadsPath: string;
|
||||||
quitOnClose: boolean;
|
quitOnClose: boolean;
|
||||||
promptDownload: boolean;
|
promptDownload: boolean;
|
||||||
flashTaskbarOnMessage?: boolean;
|
|
||||||
dockBouncing?: boolean;
|
dockBouncing?: boolean;
|
||||||
loading?: AnyObject;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
const logger = new Logger({
|
const logger = new Logger({
|
||||||
@@ -69,7 +58,7 @@ const logger = new Logger({
|
|||||||
});
|
});
|
||||||
|
|
||||||
const rendererDirectory = path.resolve(__dirname, '..');
|
const rendererDirectory = path.resolve(__dirname, '..');
|
||||||
type ServerOrFunctionalTab = ServerTab | FunctionalTab;
|
export type ServerOrFunctionalTab = ServerTab | FunctionalTab;
|
||||||
|
|
||||||
class ServerManagerView {
|
class ServerManagerView {
|
||||||
$addServerButton: HTMLButtonElement;
|
$addServerButton: HTMLButtonElement;
|
||||||
@@ -90,10 +79,10 @@ class ServerManagerView {
|
|||||||
$sidebar: Element;
|
$sidebar: Element;
|
||||||
$fullscreenPopup: Element;
|
$fullscreenPopup: Element;
|
||||||
$fullscreenEscapeKey: string;
|
$fullscreenEscapeKey: string;
|
||||||
loading: AnyObject;
|
loading: Set<string>;
|
||||||
activeTabIndex: number;
|
activeTabIndex: number;
|
||||||
tabs: ServerOrFunctionalTab[];
|
tabs: ServerOrFunctionalTab[];
|
||||||
functionalTabs: AnyObject;
|
functionalTabs: Map<string, number>;
|
||||||
tabIndex: number;
|
tabIndex: number;
|
||||||
presetOrgs: string[];
|
presetOrgs: string[];
|
||||||
constructor() {
|
constructor() {
|
||||||
@@ -128,11 +117,11 @@ class ServerManagerView {
|
|||||||
this.$fullscreenEscapeKey = process.platform === 'darwin' ? '^⌘F' : 'F11';
|
this.$fullscreenEscapeKey = process.platform === 'darwin' ? '^⌘F' : 'F11';
|
||||||
this.$fullscreenPopup.innerHTML = `Press ${this.$fullscreenEscapeKey} to exit full screen`;
|
this.$fullscreenPopup.innerHTML = `Press ${this.$fullscreenEscapeKey} to exit full screen`;
|
||||||
|
|
||||||
this.loading = {};
|
this.loading = new Set();
|
||||||
this.activeTabIndex = -1;
|
this.activeTabIndex = -1;
|
||||||
this.tabs = [];
|
this.tabs = [];
|
||||||
this.presetOrgs = [];
|
this.presetOrgs = [];
|
||||||
this.functionalTabs = {};
|
this.functionalTabs = new Map();
|
||||||
this.tabIndex = 0;
|
this.tabIndex = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,10 +130,11 @@ class ServerManagerView {
|
|||||||
this.initDefaultSettings();
|
this.initDefaultSettings();
|
||||||
this.initSidebar();
|
this.initSidebar();
|
||||||
this.removeUAfromDisk();
|
this.removeUAfromDisk();
|
||||||
if (EnterpriseUtil.configFile) {
|
if (EnterpriseUtil.hasConfigFile()) {
|
||||||
this.initPresetOrgs();
|
await this.initPresetOrgs();
|
||||||
}
|
}
|
||||||
this.initTabs();
|
|
||||||
|
await this.initTabs();
|
||||||
this.initActions();
|
this.initActions();
|
||||||
this.registerIpcs();
|
this.registerIpcs();
|
||||||
}
|
}
|
||||||
@@ -157,6 +147,7 @@ class ServerManagerView {
|
|||||||
if (proxyEnableOldState) {
|
if (proxyEnableOldState) {
|
||||||
ConfigUtil.setConfigItem('useManualProxy', true);
|
ConfigUtil.setConfigItem('useManualProxy', true);
|
||||||
}
|
}
|
||||||
|
|
||||||
ConfigUtil.removeConfigItem('useProxy');
|
ConfigUtil.removeConfigItem('useProxy');
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -226,7 +217,7 @@ class ServerManagerView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
for (const [setting, value] of Object.entries(settingOptions)) {
|
for (const [setting, value] of Object.entries(settingOptions)) {
|
||||||
// give preference to defaults defined in global_config.json
|
// Give preference to defaults defined in global_config.json
|
||||||
if (EnterpriseUtil.configItemExists(setting)) {
|
if (EnterpriseUtil.configItemExists(setting)) {
|
||||||
ConfigUtil.setConfigItem(setting, EnterpriseUtil.getConfigItem(setting), true);
|
ConfigUtil.setConfigItem(setting, EnterpriseUtil.getConfigItem(setting), true);
|
||||||
} else if (ConfigUtil.getConfigItem(setting) === null) {
|
} else if (ConfigUtil.getConfigItem(setting) === null) {
|
||||||
@@ -246,41 +237,43 @@ class ServerManagerView {
|
|||||||
ConfigUtil.removeConfigItem('userAgent');
|
ConfigUtil.removeConfigItem('userAgent');
|
||||||
}
|
}
|
||||||
|
|
||||||
async queueDomain(domain: any): Promise<boolean> {
|
async queueDomain(domain: string): Promise<boolean> {
|
||||||
// allows us to start adding multiple domains to the app simultaneously
|
// Allows us to start adding multiple domains to the app simultaneously
|
||||||
// promise of addition resolves in both cases, but we consider it rejected
|
// promise of addition resolves in both cases, but we consider it rejected
|
||||||
// if the resolved value is false
|
// if the resolved value is false
|
||||||
try {
|
try {
|
||||||
const serverConf = await DomainUtil.checkDomain(domain);
|
const serverConf = await DomainUtil.checkDomain(domain);
|
||||||
await DomainUtil.addDomain(serverConf);
|
await DomainUtil.addDomain(serverConf);
|
||||||
return true;
|
return true;
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
logger.error(err);
|
logger.error(error);
|
||||||
logger.error('Could not add ' + domain + '. Please contact your system administrator.');
|
logger.error(`Could not add ${domain}. Please contact your system administrator.`);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async initPresetOrgs(): Promise<void> {
|
async initPresetOrgs(): Promise<void> {
|
||||||
// read preset organizations from global_config.json and queues them
|
// Read preset organizations from global_config.json and queues them
|
||||||
// for addition to the app's domains
|
// for addition to the app's domains
|
||||||
const preAddedDomains = DomainUtil.getDomains();
|
const preAddedDomains = DomainUtil.getDomains();
|
||||||
this.presetOrgs = EnterpriseUtil.getConfigItem('presetOrganizations', []);
|
this.presetOrgs = EnterpriseUtil.getConfigItem('presetOrganizations', []);
|
||||||
// set to true if at least one new domain is added
|
// Set to true if at least one new domain is added
|
||||||
const domainPromises = [];
|
const domainPromises = [];
|
||||||
for (const url of this.presetOrgs) {
|
for (const url of this.presetOrgs) {
|
||||||
if (DomainUtil.duplicateDomain(url)) {
|
if (DomainUtil.duplicateDomain(url)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
domainPromises.push(this.queueDomain(url));
|
domainPromises.push(this.queueDomain(url));
|
||||||
}
|
}
|
||||||
|
|
||||||
const domainsAdded = await Promise.all(domainPromises);
|
const domainsAdded = await Promise.all(domainPromises);
|
||||||
if (domainsAdded.includes(true)) {
|
if (domainsAdded.includes(true)) {
|
||||||
// at least one domain was resolved
|
// At least one domain was resolved
|
||||||
if (preAddedDomains.length > 0) {
|
if (preAddedDomains.length > 0) {
|
||||||
// user already has servers added
|
// User already has servers added
|
||||||
// ask them before reloading the app
|
// ask them before reloading the app
|
||||||
const { response } = await dialog.showMessageBox({
|
const {response} = await dialog.showMessageBox({
|
||||||
type: 'question',
|
type: 'question',
|
||||||
buttons: ['Yes', 'Later'],
|
buttons: ['Yes', 'Later'],
|
||||||
defaultId: 0,
|
defaultId: 0,
|
||||||
@@ -293,57 +286,62 @@ class ServerManagerView {
|
|||||||
ipcRenderer.send('reload-full-app');
|
ipcRenderer.send('reload-full-app');
|
||||||
}
|
}
|
||||||
} else if (domainsAdded.length > 0) {
|
} else if (domainsAdded.length > 0) {
|
||||||
// find all orgs that failed
|
// Find all orgs that failed
|
||||||
const failedDomains: string[] = [];
|
const failedDomains: string[] = [];
|
||||||
for (const org of this.presetOrgs) {
|
for (const org of this.presetOrgs) {
|
||||||
if (DomainUtil.duplicateDomain(org)) {
|
if (DomainUtil.duplicateDomain(org)) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
failedDomains.push(org);
|
failedDomains.push(org);
|
||||||
}
|
}
|
||||||
const { title, content } = Messages.enterpriseOrgError(domainsAdded.length, failedDomains);
|
|
||||||
|
const {title, content} = Messages.enterpriseOrgError(domainsAdded.length, failedDomains);
|
||||||
dialog.showErrorBox(title, content);
|
dialog.showErrorBox(title, content);
|
||||||
if (DomainUtil.getDomains().length === 0) {
|
if (DomainUtil.getDomains().length === 0) {
|
||||||
// no orgs present, stop showing loading gif
|
// No orgs present, stop showing loading gif
|
||||||
await this.openSettings('AddServer');
|
await this.openSettings('AddServer');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
initTabs(): void {
|
async initTabs(): Promise<void> {
|
||||||
const servers = DomainUtil.getDomains();
|
const servers = DomainUtil.getDomains();
|
||||||
if (servers.length > 0) {
|
if (servers.length > 0) {
|
||||||
for (const [i, server] of servers.entries()) {
|
for (const [i, server] of servers.entries()) {
|
||||||
this.initServer(server, i);
|
this.initServer(server, i);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Open last active tab
|
// Open last active tab
|
||||||
let lastActiveTab = ConfigUtil.getConfigItem('lastActiveTab');
|
let lastActiveTab = ConfigUtil.getConfigItem('lastActiveTab');
|
||||||
if (lastActiveTab >= servers.length) {
|
if (lastActiveTab >= servers.length) {
|
||||||
lastActiveTab = 0;
|
lastActiveTab = 0;
|
||||||
}
|
}
|
||||||
// checkDomain() and webview.load() for lastActiveTab before the others
|
|
||||||
DomainUtil.updateSavedServer(servers[lastActiveTab].url, lastActiveTab);
|
// `checkDomain()` and `webview.load()` for lastActiveTab before the others
|
||||||
|
await DomainUtil.updateSavedServer(servers[lastActiveTab].url, lastActiveTab);
|
||||||
this.activateTab(lastActiveTab);
|
this.activateTab(lastActiveTab);
|
||||||
for (const [i, server] of servers.entries()) {
|
await Promise.all(servers.map(async (server, i) => {
|
||||||
// after the lastActiveTab is activated, we load the others in the background
|
// After the lastActiveTab is activated, we load the others in the background
|
||||||
// without activating them, to prevent flashing of server icons
|
// without activating them, to prevent flashing of server icons
|
||||||
if (i === lastActiveTab) {
|
if (i === lastActiveTab) {
|
||||||
continue;
|
return;
|
||||||
}
|
}
|
||||||
DomainUtil.updateSavedServer(server.url, i);
|
|
||||||
|
await DomainUtil.updateSavedServer(server.url, i);
|
||||||
this.tabs[i].webview.load();
|
this.tabs[i].webview.load();
|
||||||
}
|
}));
|
||||||
// Remove focus from the settings icon at sidebar bottom
|
// Remove focus from the settings icon at sidebar bottom
|
||||||
this.$settingsButton.classList.remove('active');
|
this.$settingsButton.classList.remove('active');
|
||||||
} else if (this.presetOrgs.length === 0) {
|
} else if (this.presetOrgs.length === 0) {
|
||||||
// not attempting to add organisations in the background
|
// Not attempting to add organisations in the background
|
||||||
this.openSettings('AddServer');
|
await this.openSettings('AddServer');
|
||||||
} else {
|
} else {
|
||||||
this.showLoading(true);
|
this.showLoading(true);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
initServer(server: any, index: number): void {
|
initServer(server: DomainUtil.ServerConf, index: number): void {
|
||||||
const tabIndex = this.getTabIndex();
|
const tabIndex = this.getTabIndex();
|
||||||
this.tabs.push(new ServerTab({
|
this.tabs.push(new ServerTab({
|
||||||
role: 'server',
|
role: 'server',
|
||||||
@@ -362,18 +360,20 @@ class ServerManagerView {
|
|||||||
url: server.url,
|
url: server.url,
|
||||||
role: 'server',
|
role: 'server',
|
||||||
name: CommonUtil.decodeString(server.alias),
|
name: CommonUtil.decodeString(server.alias),
|
||||||
|
ignoreCerts: server.ignoreCerts,
|
||||||
hasPermission: (origin: string, permission: string) =>
|
hasPermission: (origin: string, permission: string) =>
|
||||||
origin === server.url && permission === 'notifications',
|
origin === server.url && permission === 'notifications',
|
||||||
isActive: () => {
|
isActive: () => {
|
||||||
return index === this.activeTabIndex;
|
return index === this.activeTabIndex;
|
||||||
},
|
},
|
||||||
switchLoading: (loading: boolean, url: string) => {
|
switchLoading: (loading: boolean, url: string) => {
|
||||||
if (!loading && this.loading[url]) {
|
if (loading) {
|
||||||
this.loading[url] = false;
|
this.loading.add(url);
|
||||||
} else if (loading && !this.loading[url]) {
|
} else {
|
||||||
this.loading[url] = true;
|
this.loading.delete(url);
|
||||||
}
|
}
|
||||||
this.showLoading(this.loading[this.tabs[this.activeTabIndex].webview.props.url]);
|
|
||||||
|
this.showLoading(this.loading.has(this.tabs[this.activeTabIndex].webview.props.url));
|
||||||
},
|
},
|
||||||
onNetworkError: (index: number) => this.openNetworkTroubleshooting(index),
|
onNetworkError: (index: number) => this.openNetworkTroubleshooting(index),
|
||||||
onTitleChange: this.updateBadge.bind(this),
|
onTitleChange: this.updateBadge.bind(this),
|
||||||
@@ -381,7 +381,7 @@ class ServerManagerView {
|
|||||||
preload: true
|
preload: true
|
||||||
})
|
})
|
||||||
}));
|
}));
|
||||||
this.loading[server.url] = true;
|
this.loading.add(server.url);
|
||||||
}
|
}
|
||||||
|
|
||||||
initActions(): void {
|
initActions(): void {
|
||||||
@@ -397,6 +397,7 @@ class ServerManagerView {
|
|||||||
if ($serverImg.src.includes('img/icon.png')) {
|
if ($serverImg.src.includes('img/icon.png')) {
|
||||||
this.displayInitialCharLogo($serverImg, index);
|
this.displayInitialCharLogo($serverImg, index);
|
||||||
}
|
}
|
||||||
|
|
||||||
$serverImg.addEventListener('error', () => {
|
$serverImg.addEventListener('error', () => {
|
||||||
this.displayInitialCharLogo($serverImg, index);
|
this.displayInitialCharLogo($serverImg, index);
|
||||||
});
|
});
|
||||||
@@ -411,11 +412,11 @@ class ServerManagerView {
|
|||||||
this.$reloadButton.addEventListener('click', () => {
|
this.$reloadButton.addEventListener('click', () => {
|
||||||
this.tabs[this.activeTabIndex].webview.reload();
|
this.tabs[this.activeTabIndex].webview.reload();
|
||||||
});
|
});
|
||||||
this.$addServerButton.addEventListener('click', () => {
|
this.$addServerButton.addEventListener('click', async () => {
|
||||||
this.openSettings('AddServer');
|
await this.openSettings('AddServer');
|
||||||
});
|
});
|
||||||
this.$settingsButton.addEventListener('click', () => {
|
this.$settingsButton.addEventListener('click', async () => {
|
||||||
this.openSettings('General');
|
await this.openSettings('General');
|
||||||
});
|
});
|
||||||
this.$backButton.addEventListener('click', () => {
|
this.$backButton.addEventListener('click', () => {
|
||||||
this.tabs[this.activeTabIndex].webview.back();
|
this.tabs[this.activeTabIndex].webview.back();
|
||||||
@@ -445,10 +446,9 @@ class ServerManagerView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
displayInitialCharLogo($img: HTMLImageElement, index: number): void {
|
displayInitialCharLogo($img: HTMLImageElement, index: number): void {
|
||||||
/*
|
// The index parameter is needed because webview[data-tab-id] can
|
||||||
index parameter needed because webview[data-tab-id] can increment
|
// increment beyond the size of the sidebar org array and throw an
|
||||||
beyond size of sidebar org array and throw error
|
// error
|
||||||
*/
|
|
||||||
|
|
||||||
const $altIcon = document.createElement('div');
|
const $altIcon = document.createElement('div');
|
||||||
const $parent = $img.parentElement;
|
const $parent = $img.parentElement;
|
||||||
@@ -480,8 +480,8 @@ class ServerManagerView {
|
|||||||
// as that of its parent element.
|
// as that of its parent element.
|
||||||
// This needs to handled only for the add server tooltip and not others.
|
// This needs to handled only for the add server tooltip and not others.
|
||||||
if (addServer) {
|
if (addServer) {
|
||||||
const { top } = SidebarButton.getBoundingClientRect();
|
const {top} = SidebarButton.getBoundingClientRect();
|
||||||
SidebarTooltip.style.top = top + 'px';
|
SidebarTooltip.style.top = `${top}px`;
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
SidebarButton.addEventListener('mouseout', () => {
|
SidebarButton.addEventListener('mouseout', () => {
|
||||||
@@ -490,14 +490,14 @@ class ServerManagerView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
onHover(index: number): void {
|
onHover(index: number): void {
|
||||||
// this.$serverIconTooltip[index].innerHTML already has realm name, so we are just
|
// `this.$serverIconTooltip[index].innerHTML` already has realm name, so we are just
|
||||||
// removing the style.
|
// removing the style.
|
||||||
this.$serverIconTooltip[index].removeAttribute('style');
|
this.$serverIconTooltip[index].removeAttribute('style');
|
||||||
// To handle position of servers' tooltip due to scrolling of list of organizations
|
// To handle position of servers' tooltip due to scrolling of list of organizations
|
||||||
// This could not be handled using CSS, hence the top of the tooltip is made same
|
// This could not be handled using CSS, hence the top of the tooltip is made same
|
||||||
// as that of its parent element.
|
// as that of its parent element.
|
||||||
const { top } = this.$serverIconTooltip[index].parentElement.getBoundingClientRect();
|
const {top} = this.$serverIconTooltip[index].parentElement.getBoundingClientRect();
|
||||||
this.$serverIconTooltip[index].style.top = top + 'px';
|
this.$serverIconTooltip[index].style.top = `${top}px`;
|
||||||
}
|
}
|
||||||
|
|
||||||
onHoverOut(index: number): void {
|
onHoverOut(index: number): void {
|
||||||
@@ -505,12 +505,12 @@ class ServerManagerView {
|
|||||||
}
|
}
|
||||||
|
|
||||||
openFunctionalTab(tabProps: FunctionalTabProps): void {
|
openFunctionalTab(tabProps: FunctionalTabProps): void {
|
||||||
if (this.functionalTabs[tabProps.name] !== undefined) {
|
if (this.functionalTabs.has(tabProps.name)) {
|
||||||
this.activateTab(this.functionalTabs[tabProps.name]);
|
this.activateTab(this.functionalTabs.get(tabProps.name));
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.functionalTabs[tabProps.name] = this.tabs.length;
|
this.functionalTabs.set(tabProps.name, this.tabs.length);
|
||||||
|
|
||||||
const tabIndex = this.getTabIndex();
|
const tabIndex = this.getTabIndex();
|
||||||
|
|
||||||
@@ -519,27 +519,28 @@ class ServerManagerView {
|
|||||||
materialIcon: tabProps.materialIcon,
|
materialIcon: tabProps.materialIcon,
|
||||||
name: tabProps.name,
|
name: tabProps.name,
|
||||||
$root: this.$tabsContainer,
|
$root: this.$tabsContainer,
|
||||||
index: this.functionalTabs[tabProps.name],
|
index: this.functionalTabs.get(tabProps.name),
|
||||||
tabIndex,
|
tabIndex,
|
||||||
onClick: this.activateTab.bind(this, this.functionalTabs[tabProps.name]),
|
onClick: this.activateTab.bind(this, this.functionalTabs.get(tabProps.name)),
|
||||||
onDestroy: this.destroyTab.bind(this, tabProps.name, this.functionalTabs[tabProps.name]),
|
onDestroy: this.destroyTab.bind(this, tabProps.name, this.functionalTabs.get(tabProps.name)),
|
||||||
webview: new WebView({
|
webview: new WebView({
|
||||||
$root: this.$webviewsContainer,
|
$root: this.$webviewsContainer,
|
||||||
index: this.functionalTabs[tabProps.name],
|
index: this.functionalTabs.get(tabProps.name),
|
||||||
tabIndex,
|
tabIndex,
|
||||||
url: tabProps.url,
|
url: tabProps.url,
|
||||||
role: 'function',
|
role: 'function',
|
||||||
name: tabProps.name,
|
name: tabProps.name,
|
||||||
isActive: () => {
|
isActive: () => {
|
||||||
return this.functionalTabs[tabProps.name] === this.activeTabIndex;
|
return this.functionalTabs.get(tabProps.name) === this.activeTabIndex;
|
||||||
},
|
},
|
||||||
switchLoading: (loading: AnyObject, url: string) => {
|
switchLoading: (loading: boolean, url: string) => {
|
||||||
if (!loading && this.loading[url]) {
|
if (loading) {
|
||||||
this.loading[url] = false;
|
this.loading.add(url);
|
||||||
} else if (loading && !this.loading[url]) {
|
} else {
|
||||||
this.loading[url] = true;
|
this.loading.delete(url);
|
||||||
}
|
}
|
||||||
this.showLoading(this.loading[this.tabs[this.activeTabIndex].webview.props.url]);
|
|
||||||
|
this.showLoading(this.loading.has(this.tabs[this.activeTabIndex].webview.props.url));
|
||||||
},
|
},
|
||||||
onNetworkError: (index: number) => this.openNetworkTroubleshooting(index),
|
onNetworkError: (index: number) => this.openNetworkTroubleshooting(index),
|
||||||
onTitleChange: this.updateBadge.bind(this),
|
onTitleChange: this.updateBadge.bind(this),
|
||||||
@@ -552,7 +553,7 @@ class ServerManagerView {
|
|||||||
// closed when the functional tab DOM is ready, handled in webview.js
|
// closed when the functional tab DOM is ready, handled in webview.js
|
||||||
this.$webviewsContainer.classList.remove('loaded');
|
this.$webviewsContainer.classList.remove('loaded');
|
||||||
|
|
||||||
this.activateTab(this.functionalTabs[tabProps.name]);
|
this.activateTab(this.functionalTabs.get(tabProps.name));
|
||||||
}
|
}
|
||||||
|
|
||||||
async openSettings(nav = 'General'): Promise<void> {
|
async openSettings(nav = 'General'): Promise<void> {
|
||||||
@@ -562,7 +563,7 @@ class ServerManagerView {
|
|||||||
url: `file://${rendererDirectory}/preference.html#${nav}`
|
url: `file://${rendererDirectory}/preference.html#${nav}`
|
||||||
});
|
});
|
||||||
this.$settingsButton.classList.add('active');
|
this.$settingsButton.classList.add('active');
|
||||||
await this.tabs[this.functionalTabs.Settings].webview.send('switch-settings-nav', nav);
|
await this.tabs[this.functionalTabs.get('Settings')].webview.send('switch-settings-nav', nav);
|
||||||
}
|
}
|
||||||
|
|
||||||
openAbout(): void {
|
openAbout(): void {
|
||||||
@@ -587,7 +588,7 @@ class ServerManagerView {
|
|||||||
ipcRenderer.send('save-last-tab', index);
|
ipcRenderer.send('save-last-tab', index);
|
||||||
}
|
}
|
||||||
|
|
||||||
// returns this.tabs in an way that does
|
// Returns this.tabs in an way that does
|
||||||
// not crash app when this.tabs is passed into
|
// not crash app when this.tabs is passed into
|
||||||
// ipcRenderer. Something about webview, and props.webview
|
// ipcRenderer. Something about webview, and props.webview
|
||||||
// properties in ServerTab causes the app to crash.
|
// properties in ServerTab causes the app to crash.
|
||||||
@@ -597,7 +598,7 @@ class ServerManagerView {
|
|||||||
const proto = Object.create(Object.getPrototypeOf(tab));
|
const proto = Object.create(Object.getPrototypeOf(tab));
|
||||||
const tabClone = Object.assign(proto, tab);
|
const tabClone = Object.assign(proto, tab);
|
||||||
|
|
||||||
tabClone.webview = { props: {} };
|
tabClone.webview = {props: {}};
|
||||||
tabClone.webview.props.name = tab.webview.props.name;
|
tabClone.webview.props.name = tab.webview.props.name;
|
||||||
delete tabClone.props.webview;
|
delete tabClone.props.webview;
|
||||||
tabs.push(tabClone);
|
tabs.push(tabClone);
|
||||||
@@ -614,24 +615,27 @@ class ServerManagerView {
|
|||||||
if (this.activeTabIndex !== -1) {
|
if (this.activeTabIndex !== -1) {
|
||||||
if (this.activeTabIndex === index) {
|
if (this.activeTabIndex === index) {
|
||||||
return;
|
return;
|
||||||
} else if (hideOldTab) {
|
}
|
||||||
|
|
||||||
|
if (hideOldTab) {
|
||||||
// If old tab is functional tab Settings, remove focus from the settings icon at sidebar bottom
|
// If old tab is functional tab Settings, remove focus from the settings icon at sidebar bottom
|
||||||
if (this.tabs[this.activeTabIndex].props.role === 'function' && this.tabs[this.activeTabIndex].props.name === 'Settings') {
|
if (this.tabs[this.activeTabIndex].props.role === 'function' && this.tabs[this.activeTabIndex].props.name === 'Settings') {
|
||||||
this.$settingsButton.classList.remove('active');
|
this.$settingsButton.classList.remove('active');
|
||||||
}
|
}
|
||||||
|
|
||||||
this.tabs[this.activeTabIndex].deactivate();
|
this.tabs[this.activeTabIndex].deactivate();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
this.tabs[index].webview.canGoBackButton();
|
this.tabs[index].webview.canGoBackButton();
|
||||||
} catch (err) {
|
} catch (_) {
|
||||||
}
|
}
|
||||||
|
|
||||||
this.activeTabIndex = index;
|
this.activeTabIndex = index;
|
||||||
this.tabs[index].activate();
|
this.tabs[index].activate();
|
||||||
|
|
||||||
this.showLoading(this.loading[this.tabs[this.activeTabIndex].webview.props.url]);
|
this.showLoading(this.loading.has(this.tabs[this.activeTabIndex].webview.props.url));
|
||||||
|
|
||||||
ipcRenderer.send('update-menu', {
|
ipcRenderer.send('update-menu', {
|
||||||
// JSON stringify this.tabs to avoid a crash
|
// JSON stringify this.tabs to avoid a crash
|
||||||
@@ -661,7 +665,7 @@ class ServerManagerView {
|
|||||||
this.tabs[index].destroy();
|
this.tabs[index].destroy();
|
||||||
|
|
||||||
delete this.tabs[index];
|
delete this.tabs[index];
|
||||||
delete this.functionalTabs[name];
|
this.functionalTabs.delete(name);
|
||||||
|
|
||||||
// Issue #188: If the functional tab was not focused, do not activate another tab.
|
// Issue #188: If the functional tab was not focused, do not activate another tab.
|
||||||
if (this.activeTabIndex === index) {
|
if (this.activeTabIndex === index) {
|
||||||
@@ -676,21 +680,21 @@ class ServerManagerView {
|
|||||||
// Clear global variables
|
// Clear global variables
|
||||||
this.activeTabIndex = -1;
|
this.activeTabIndex = -1;
|
||||||
this.tabs = [];
|
this.tabs = [];
|
||||||
this.functionalTabs = {};
|
this.functionalTabs.clear();
|
||||||
|
|
||||||
// Clear DOM elements
|
// Clear DOM elements
|
||||||
this.$tabsContainer.innerHTML = '';
|
this.$tabsContainer.innerHTML = '';
|
||||||
this.$webviewsContainer.innerHTML = '';
|
this.$webviewsContainer.innerHTML = '';
|
||||||
}
|
}
|
||||||
|
|
||||||
reloadView(): void {
|
async reloadView(): Promise<void> {
|
||||||
// Save and remember the index of last active tab so that we can use it later
|
// Save and remember the index of last active tab so that we can use it later
|
||||||
const lastActiveTab = this.tabs[this.activeTabIndex].props.index;
|
const lastActiveTab = this.tabs[this.activeTabIndex].props.index;
|
||||||
ConfigUtil.setConfigItem('lastActiveTab', lastActiveTab);
|
ConfigUtil.setConfigItem('lastActiveTab', lastActiveTab);
|
||||||
|
|
||||||
// Destroy the current view and re-initiate it
|
// Destroy the current view and re-initiate it
|
||||||
this.destroyView();
|
this.destroyView();
|
||||||
this.initTabs();
|
await this.initTabs();
|
||||||
this.initServerActions();
|
this.initServerActions();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -713,7 +717,7 @@ class ServerManagerView {
|
|||||||
ipcRenderer.send('update-badge', messageCountAll);
|
ipcRenderer.send('update-badge', messageCountAll);
|
||||||
}
|
}
|
||||||
|
|
||||||
updateGeneralSettings(setting: string, value: any): void {
|
updateGeneralSettings(setting: string, value: unknown): void {
|
||||||
if (this.getActiveWebview()) {
|
if (this.getActiveWebview()) {
|
||||||
const webContents = this.getActiveWebview().getWebContents();
|
const webContents = this.getActiveWebview().getWebContents();
|
||||||
webContents.send(setting, value);
|
webContents.send(setting, value);
|
||||||
@@ -752,7 +756,7 @@ class ServerManagerView {
|
|||||||
{
|
{
|
||||||
label: 'Disconnect organization',
|
label: 'Disconnect organization',
|
||||||
click: async () => {
|
click: async () => {
|
||||||
const { response } = await dialog.showMessageBox({
|
const {response} = await dialog.showMessageBox({
|
||||||
type: 'warning',
|
type: 'warning',
|
||||||
buttons: ['YES', 'NO'],
|
buttons: ['YES', 'NO'],
|
||||||
defaultId: 0,
|
defaultId: 0,
|
||||||
@@ -762,7 +766,7 @@ class ServerManagerView {
|
|||||||
if (DomainUtil.removeDomain(index)) {
|
if (DomainUtil.removeDomain(index)) {
|
||||||
ipcRenderer.send('reload-full-app');
|
ipcRenderer.send('reload-full-app');
|
||||||
} else {
|
} else {
|
||||||
const { title, content } = Messages.orgRemovalError(DomainUtil.getDomain(index).url);
|
const {title, content} = Messages.orgRemovalError(DomainUtil.getDomain(index).url);
|
||||||
dialog.showErrorBox(title, content);
|
dialog.showErrorBox(title, content);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -772,7 +776,7 @@ class ServerManagerView {
|
|||||||
label: 'Notification settings',
|
label: 'Notification settings',
|
||||||
enabled: this.isLoggedIn(index),
|
enabled: this.isLoggedIn(index),
|
||||||
click: () => {
|
click: () => {
|
||||||
// switch to tab whose icon was right-clicked
|
// Switch to tab whose icon was right-clicked
|
||||||
this.activateTab(index);
|
this.activateTab(index);
|
||||||
this.tabs[index].webview.showNotificationSettings();
|
this.tabs[index].webview.showNotificationSettings();
|
||||||
}
|
}
|
||||||
@@ -785,46 +789,62 @@ class ServerManagerView {
|
|||||||
}
|
}
|
||||||
];
|
];
|
||||||
const contextMenu = Menu.buildFromTemplate(template);
|
const contextMenu = Menu.buildFromTemplate(template);
|
||||||
contextMenu.popup({ window: remote.getCurrentWindow() });
|
contextMenu.popup({window: remote.getCurrentWindow()});
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
registerIpcs(): void {
|
registerIpcs(): void {
|
||||||
const webviewListeners: AnyObject = {
|
const webviewListeners: Array<[string, (webview: WebView) => void]> = [
|
||||||
'webview-reload': 'reload',
|
['webview-reload', webview => webview.reload()],
|
||||||
back: 'back',
|
['back', webview => webview.back()],
|
||||||
focus: 'focus',
|
['focus', webview => webview.focus()],
|
||||||
forward: 'forward',
|
['forward', webview => webview.forward()],
|
||||||
zoomIn: 'zoomIn',
|
['zoomIn', webview => webview.zoomIn()],
|
||||||
zoomOut: 'zoomOut',
|
['zoomOut', webview => webview.zoomOut()],
|
||||||
zoomActualSize: 'zoomActualSize',
|
['zoomActualSize', webview => webview.zoomActualSize()],
|
||||||
'log-out': 'logOut',
|
['log-out', webview => webview.logOut()],
|
||||||
shortcut: 'showShortcut',
|
['shortcut', webview => webview.showShortcut()],
|
||||||
'tab-devtools': 'openDevTools'
|
['tab-devtools', webview => webview.openDevTools()]
|
||||||
};
|
];
|
||||||
|
|
||||||
for (const [key, method] of Object.entries(webviewListeners)) {
|
for (const [channel, listener] of webviewListeners) {
|
||||||
ipcRenderer.on(key, () => {
|
ipcRenderer.on(channel, () => {
|
||||||
const activeWebview = this.tabs[this.activeTabIndex].webview;
|
const activeWebview = this.tabs[this.activeTabIndex].webview;
|
||||||
if (activeWebview) {
|
if (activeWebview) {
|
||||||
activeWebview[method]();
|
listener(activeWebview);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ipcRenderer.on('certificate-error', (
|
||||||
|
event: Event,
|
||||||
|
webContentsId: number | null,
|
||||||
|
rendererCallbackId: number
|
||||||
|
) => {
|
||||||
|
const ignore = webContentsId !== null &&
|
||||||
|
this.tabs.some(
|
||||||
|
({webview}) =>
|
||||||
|
!webview.loading &&
|
||||||
|
webview.$el.getWebContentsId() === webContentsId &&
|
||||||
|
webview.props.ignoreCerts
|
||||||
|
);
|
||||||
|
ipcRenderer.send('renderer-callback', rendererCallbackId, ignore);
|
||||||
|
});
|
||||||
|
|
||||||
ipcRenderer.on('permission-request', (
|
ipcRenderer.on('permission-request', (
|
||||||
event: Event,
|
event: Event,
|
||||||
permissionId: number,
|
|
||||||
{webContentsId, origin, permission}: {
|
{webContentsId, origin, permission}: {
|
||||||
webContentsId: number | null;
|
webContentsId: number | null;
|
||||||
origin: string;
|
origin: string;
|
||||||
permission: string;
|
permission: string;
|
||||||
}
|
},
|
||||||
|
rendererCallbackId: number
|
||||||
) => {
|
) => {
|
||||||
const grant = webContentsId === null ?
|
const grant = webContentsId === null ?
|
||||||
origin === 'null' && permission === 'notifications' :
|
origin === 'null' && permission === 'notifications' :
|
||||||
this.tabs.some(
|
this.tabs.some(
|
||||||
({webview}) =>
|
({webview}) =>
|
||||||
|
!webview.loading &&
|
||||||
webview.$el.getWebContentsId() === webContentsId &&
|
webview.$el.getWebContentsId() === webContentsId &&
|
||||||
webview.props.hasPermission?.(origin, permission)
|
webview.props.hasPermission?.(origin, permission)
|
||||||
);
|
);
|
||||||
@@ -832,22 +852,22 @@ class ServerManagerView {
|
|||||||
grant ? 'Granted' : 'Denied', 'permissions request for',
|
grant ? 'Granted' : 'Denied', 'permissions request for',
|
||||||
permission, 'from', origin
|
permission, 'from', origin
|
||||||
);
|
);
|
||||||
ipcRenderer.send('permission-response', permissionId, grant);
|
ipcRenderer.send('renderer-callback', rendererCallbackId, grant);
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.on('show-network-error', (event: Event, index: number) => {
|
ipcRenderer.on('show-network-error', (event: Event, index: number) => {
|
||||||
this.openNetworkTroubleshooting(index);
|
this.openNetworkTroubleshooting(index);
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.on('open-settings', (event: Event, settingNav: string) => {
|
ipcRenderer.on('open-settings', async (event: Event, settingNav: string) => {
|
||||||
this.openSettings(settingNav);
|
await this.openSettings(settingNav);
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.on('open-about', this.openAbout.bind(this));
|
ipcRenderer.on('open-about', this.openAbout.bind(this));
|
||||||
|
|
||||||
ipcRenderer.on('open-help', () => {
|
ipcRenderer.on('open-help', async () => {
|
||||||
// Open help page of current active server
|
// Open help page of current active server
|
||||||
LinkUtil.openBrowser(new URL('/help', this.getCurrentActiveServer()));
|
await LinkUtil.openBrowser(new URL('https://zulipchat.com/help/'));
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.on('reload-viewer', this.reloadView.bind(this, this.tabs[this.activeTabIndex].props.index));
|
ipcRenderer.on('reload-viewer', this.reloadView.bind(this, this.tabs[this.activeTabIndex].props.index));
|
||||||
@@ -866,14 +886,17 @@ class ServerManagerView {
|
|||||||
this.activateLastTab(index);
|
this.activateLastTab(index);
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.on('open-org-tab', () => {
|
ipcRenderer.on('open-org-tab', async () => {
|
||||||
this.openSettings('AddServer');
|
await this.openSettings('AddServer');
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.on('reload-proxy', async (event: Event, showAlert: boolean) => {
|
ipcRenderer.on('reload-proxy', async (event: Event, showAlert: boolean) => {
|
||||||
await this.loadProxy();
|
await this.loadProxy();
|
||||||
if (showAlert) {
|
if (showAlert) {
|
||||||
alert('Proxy settings saved!');
|
await dialog.showMessageBox({
|
||||||
|
message: 'Proxy settings saved!',
|
||||||
|
buttons: ['OK']
|
||||||
|
});
|
||||||
ipcRenderer.send('reload-full-app');
|
ipcRenderer.send('reload-full-app');
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -891,8 +914,8 @@ class ServerManagerView {
|
|||||||
webviews.forEach(webview => {
|
webviews.forEach(webview => {
|
||||||
try {
|
try {
|
||||||
webview.setAudioMuted(state);
|
webview.setAudioMuted(state);
|
||||||
} catch (err) {
|
} catch (_) {
|
||||||
// webview is not ready yet
|
// Webview is not ready yet
|
||||||
webview.addEventListener('dom-ready', () => {
|
webview.addEventListener('dom-ready', () => {
|
||||||
webview.setAudioMuted(state);
|
webview.setAudioMuted(state);
|
||||||
});
|
});
|
||||||
@@ -908,10 +931,11 @@ class ServerManagerView {
|
|||||||
});
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.updateGeneralSettings('toggle-menubar-setting', autoHideMenubar);
|
this.updateGeneralSettings('toggle-menubar-setting', autoHideMenubar);
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.on('toggle-dnd', (event: Event, state: boolean, newSettings: SettingsOptions) => {
|
ipcRenderer.on('toggle-dnd', (event: Event, state: boolean, newSettings: DNDSettings) => {
|
||||||
this.toggleDNDButton(state);
|
this.toggleDNDButton(state);
|
||||||
ipcRenderer.send('forward-message', 'toggle-silent', newSettings.silent);
|
ipcRenderer.send('forward-message', 'toggle-silent', newSettings.silent);
|
||||||
const webContents = this.getActiveWebview().getWebContents();
|
const webContents = this.getActiveWebview().getWebContents();
|
||||||
@@ -928,8 +952,7 @@ class ServerManagerView {
|
|||||||
this.tabs[index].webview.props.name = realmName;
|
this.tabs[index].webview.props.name = realmName;
|
||||||
|
|
||||||
domain.alias = escape(realmName);
|
domain.alias = escape(realmName);
|
||||||
DomainUtil.db.push(`/domains[${index}]`, domain, true);
|
DomainUtil.updateDomain(index, domain);
|
||||||
DomainUtil.reloadDB();
|
|
||||||
// Update the realm name also on the Window menu
|
// Update the realm name also on the Window menu
|
||||||
ipcRenderer.send('update-menu', {
|
ipcRenderer.send('update-menu', {
|
||||||
tabs: this.tabsForIpc,
|
tabs: this.tabsForIpc,
|
||||||
@@ -950,8 +973,7 @@ class ServerManagerView {
|
|||||||
const serverImgs: NodeListOf<HTMLImageElement> = document.querySelectorAll(serverImgsSelector);
|
const serverImgs: NodeListOf<HTMLImageElement> = document.querySelectorAll(serverImgsSelector);
|
||||||
serverImgs[index].src = localIconUrl;
|
serverImgs[index].src = localIconUrl;
|
||||||
domain.icon = localIconUrl;
|
domain.icon = localIconUrl;
|
||||||
DomainUtil.db.push(`/domains[${index}]`, domain, true);
|
DomainUtil.updateDomain(index, domain);
|
||||||
DomainUtil.reloadDB();
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -1001,8 +1023,10 @@ class ServerManagerView {
|
|||||||
ctx.font = '85px Helvetica';
|
ctx.font = '85px Helvetica';
|
||||||
ctx.fillText(String(Math.min(99, messageCount)), 64, 90);
|
ctx.fillText(String(Math.min(99, messageCount)), 64, 90);
|
||||||
}
|
}
|
||||||
|
|
||||||
return canvas;
|
return canvas;
|
||||||
}
|
}
|
||||||
|
|
||||||
ipcRenderer.send('update-taskbar-icon', createOverlayIcon(messageCount).toDataURL(), String(messageCount));
|
ipcRenderer.send('update-taskbar-icon', createOverlayIcon(messageCount).toDataURL(), String(messageCount));
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -1014,8 +1038,8 @@ class ServerManagerView {
|
|||||||
clipboard.writeText(this.getCurrentActiveServer());
|
clipboard.writeText(this.getCurrentActiveServer());
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.on('new-server', () => {
|
ipcRenderer.on('new-server', async () => {
|
||||||
this.openSettings('AddServer');
|
await this.openSettings('AddServer');
|
||||||
});
|
});
|
||||||
|
|
||||||
// Redo and undo functionality since the default API doesn't work on macOS
|
// Redo and undo functionality since the default API doesn't work on macOS
|
||||||
@@ -1027,37 +1051,33 @@ class ServerManagerView {
|
|||||||
return this.getActiveWebview().redo();
|
return this.getActiveWebview().redo();
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.on('set-active', () => {
|
ipcRenderer.on('set-active', async () => {
|
||||||
const webviews: NodeListOf<Electron.WebviewTag> = document.querySelectorAll('webview');
|
const webviews: NodeListOf<Electron.WebviewTag> = document.querySelectorAll('webview');
|
||||||
webviews.forEach(webview => {
|
await Promise.all([...webviews].map(async webview => webview.send('set-active')));
|
||||||
webview.send('set-active');
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.on('set-idle', () => {
|
ipcRenderer.on('set-idle', async () => {
|
||||||
const webviews: NodeListOf<Electron.WebviewTag> = document.querySelectorAll('webview');
|
const webviews: NodeListOf<Electron.WebviewTag> = document.querySelectorAll('webview');
|
||||||
webviews.forEach(webview => {
|
await Promise.all([...webviews].map(async webview => webview.send('set-idle')));
|
||||||
webview.send('set-idle');
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.on('open-network-settings', () => {
|
ipcRenderer.on('open-network-settings', async () => {
|
||||||
this.openSettings('Network');
|
await this.openSettings('Network');
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
window.addEventListener('load', () => {
|
window.addEventListener('load', async () => {
|
||||||
const serverManagerView = new ServerManagerView();
|
// Only start electron-connect (auto reload on change) when its ran
|
||||||
serverManagerView.init();
|
|
||||||
// only start electron-connect (auto reload on change) when its ran
|
|
||||||
// from `npm run dev` or `gulp dev` and not from `npm start` when
|
// from `npm run dev` or `gulp dev` and not from `npm start` when
|
||||||
// app is started `npm start` main process's proces.argv will have
|
// app is started `npm start` main process's proces.argv will have
|
||||||
// `--no-electron-connect`
|
// `--no-electron-connect`
|
||||||
const mainProcessArgv = remote.getGlobal('process').argv;
|
if (isDev && !remote.getGlobal('process').argv.includes('--no-electron-connect')) {
|
||||||
if (isDev && !mainProcessArgv.includes('--no-electron-connect')) {
|
|
||||||
require('electron-connect').client.create();
|
require('electron-connect').client.create();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const serverManagerView = new ServerManagerView();
|
||||||
|
await serverManagerView.init();
|
||||||
});
|
});
|
||||||
|
|
||||||
export {};
|
export {};
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ipcRenderer } from 'electron';
|
import {ipcRenderer} from 'electron';
|
||||||
import {
|
import {
|
||||||
appId, customReply, focusCurrentServer, parseReply
|
appId, customReply, focusCurrentServer, parseReply
|
||||||
} from './helpers';
|
} from './helpers';
|
||||||
@@ -17,14 +17,14 @@ interface NotificationHandlerArgs {
|
|||||||
}
|
}
|
||||||
|
|
||||||
class DarwinNotification {
|
class DarwinNotification {
|
||||||
tag: string;
|
tag: number;
|
||||||
|
|
||||||
constructor(title: string, options: NotificationOptions) {
|
constructor(title: string, options: NotificationOptions) {
|
||||||
const silent: boolean = ConfigUtil.getConfigItem('silent') || false;
|
const silent: boolean = ConfigUtil.getConfigItem('silent') || false;
|
||||||
const { icon } = options;
|
const {icon} = options;
|
||||||
const profilePic = new URL(icon, location.href).href;
|
const profilePic = new URL(icon, location.href).href;
|
||||||
|
|
||||||
this.tag = options.tag;
|
this.tag = Number.parseInt(options.tag, 10);
|
||||||
const notification = new MacNotifier(title, Object.assign(options, {
|
const notification = new MacNotifier(title, Object.assign(options, {
|
||||||
bundleId: appId,
|
bundleId: appId,
|
||||||
canReply: true,
|
canReply: true,
|
||||||
@@ -33,7 +33,7 @@ class DarwinNotification {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
notification.addEventListener('click', () => {
|
notification.addEventListener('click', () => {
|
||||||
// focus to the server who sent the
|
// Focus to the server who sent the
|
||||||
// notification if not focused already
|
// notification if not focused already
|
||||||
if (clickHandler) {
|
if (clickHandler) {
|
||||||
clickHandler();
|
clickHandler();
|
||||||
@@ -71,7 +71,7 @@ class DarwinNotification {
|
|||||||
clickHandler = handler;
|
clickHandler = handler;
|
||||||
}
|
}
|
||||||
|
|
||||||
// not something that is common or
|
// Not something that is common or
|
||||||
// used by zulip server but added to be
|
// used by zulip server but added to be
|
||||||
// future proff.
|
// future proff.
|
||||||
addEventListener(event: string, handler: ClickHandler | ReplyHandler): void {
|
addEventListener(event: string, handler: ClickHandler | ReplyHandler): void {
|
||||||
@@ -84,7 +84,7 @@ class DarwinNotification {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async notificationHandler({ response }: NotificationHandlerArgs): Promise<void> {
|
async notificationHandler({response}: NotificationHandlerArgs): Promise<void> {
|
||||||
response = await parseReply(response);
|
response = await parseReply(response);
|
||||||
focusCurrentServer();
|
focusCurrentServer();
|
||||||
if (electron_bridge.send_notification_reply_message_supported) {
|
if (electron_bridge.send_notification_reply_message_supported) {
|
||||||
@@ -101,7 +101,7 @@ class DarwinNotification {
|
|||||||
customReply(response);
|
customReply(response);
|
||||||
}
|
}
|
||||||
|
|
||||||
// method specific to notification api
|
// Method specific to notification api
|
||||||
// used by zulip
|
// used by zulip
|
||||||
close(): void {
|
close(): void {
|
||||||
return; // eslint-disable-line no-useless-return
|
return; // eslint-disable-line no-useless-return
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { ipcRenderer } from 'electron';
|
import {ipcRenderer} from 'electron';
|
||||||
import { focusCurrentServer } from './helpers';
|
import {focusCurrentServer} from './helpers';
|
||||||
|
|
||||||
import * as ConfigUtil from '../utils/config-util';
|
import * as ConfigUtil from '../utils/config-util';
|
||||||
|
|
||||||
@@ -10,7 +10,7 @@ export default class BaseNotification extends NativeNotification {
|
|||||||
super(title, options);
|
super(title, options);
|
||||||
|
|
||||||
this.addEventListener('click', () => {
|
this.addEventListener('click', () => {
|
||||||
// focus to the server who sent the
|
// Focus to the server who sent the
|
||||||
// notification if not focused already
|
// notification if not focused already
|
||||||
focusCurrentServer();
|
focusCurrentServer();
|
||||||
ipcRenderer.send('focus-app');
|
ipcRenderer.send('focus-app');
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { remote } from 'electron';
|
import {remote} from 'electron';
|
||||||
|
|
||||||
import Logger from '../utils/logger-util';
|
import Logger from '../utils/logger-util';
|
||||||
|
|
||||||
@@ -14,16 +14,16 @@ export type BotListItem = [string, string];
|
|||||||
const botsList: BotListItem[] = [];
|
const botsList: BotListItem[] = [];
|
||||||
let botsListLoaded = false;
|
let botsListLoaded = false;
|
||||||
|
|
||||||
// this function load list of bots from the server
|
// This function load list of bots from the server
|
||||||
// in case botsList isn't already completely loaded when required in parseRely
|
// in case botsList isn't already completely loaded when required in parseRely
|
||||||
export async function loadBots(): Promise<void> {
|
export async function loadBots(): Promise<void> {
|
||||||
botsList.length = 0;
|
botsList.length = 0;
|
||||||
const response = await fetch('/json/users');
|
const response = await fetch('/json/users');
|
||||||
if (response.ok) {
|
if (response.ok) {
|
||||||
const { members } = await response.json();
|
const {members} = await response.json();
|
||||||
members.forEach((membersRow: any) => {
|
members.forEach(({is_bot, full_name}: {[key: string]: unknown}) => {
|
||||||
if (membersRow.is_bot) {
|
if (is_bot && typeof full_name === 'string') {
|
||||||
const bot = `@${membersRow.full_name}`;
|
const bot = `@${full_name}`;
|
||||||
const mention = `@**${bot.replace(/^@/, '')}**`;
|
const mention = `@**${bot.replace(/^@/, '')}**`;
|
||||||
botsList.push([bot, mention]);
|
botsList.push([bot, mention]);
|
||||||
}
|
}
|
||||||
@@ -35,7 +35,7 @@ export async function loadBots(): Promise<void> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function checkElements(...elements: any[]): boolean {
|
export function checkElements(...elements: unknown[]): boolean {
|
||||||
let status = true;
|
let status = true;
|
||||||
elements.forEach(element => {
|
elements.forEach(element => {
|
||||||
if (element === null || element === undefined) {
|
if (element === null || element === undefined) {
|
||||||
@@ -46,14 +46,14 @@ export function checkElements(...elements: any[]): boolean {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function customReply(reply: string): void {
|
export function customReply(reply: string): void {
|
||||||
// server does not support notification reply yet.
|
// Server does not support notification reply yet.
|
||||||
const buttonSelector = '.messagebox #send_controls button[type=submit]';
|
const buttonSelector = '.messagebox #send_controls button[type=submit]';
|
||||||
const messageboxSelector = '.selected_message .messagebox .messagebox-border .messagebox-content';
|
const messageboxSelector = '.selected_message .messagebox .messagebox-border .messagebox-content';
|
||||||
const textarea: HTMLInputElement = document.querySelector('#compose-textarea');
|
const textarea: HTMLInputElement = document.querySelector('#compose-textarea');
|
||||||
const messagebox: HTMLButtonElement = document.querySelector(messageboxSelector);
|
const messagebox: HTMLButtonElement = document.querySelector(messageboxSelector);
|
||||||
const sendButton: HTMLButtonElement = document.querySelector(buttonSelector);
|
const sendButton: HTMLButtonElement = document.querySelector(buttonSelector);
|
||||||
|
|
||||||
// sanity check for old server versions
|
// Sanity check for old server versions
|
||||||
const elementsExists = checkElements(textarea, messagebox, sendButton);
|
const elementsExists = checkElements(textarea, messagebox, sendButton);
|
||||||
if (!elementsExists) {
|
if (!elementsExists) {
|
||||||
return;
|
return;
|
||||||
@@ -68,12 +68,13 @@ const currentWindow = remote.getCurrentWindow();
|
|||||||
const webContents = remote.getCurrentWebContents();
|
const webContents = remote.getCurrentWebContents();
|
||||||
const webContentsId = webContents.id;
|
const webContentsId = webContents.id;
|
||||||
|
|
||||||
// this function will focus the server that sent
|
// This function will focus the server that sent
|
||||||
// the notification. Main function implemented in main.js
|
// the notification. Main function implemented in main.js
|
||||||
export function focusCurrentServer(): void {
|
export function focusCurrentServer(): void {
|
||||||
currentWindow.webContents.send('focus-webview-with-id', webContentsId);
|
currentWindow.webContents.send('focus-webview-with-id', webContentsId);
|
||||||
}
|
}
|
||||||
// this function parses the reply from to notification
|
|
||||||
|
// This function parses the reply from to notification
|
||||||
// making it easier to reply from notification eg
|
// making it easier to reply from notification eg
|
||||||
// @username in reply will be converted to @**username**
|
// @username in reply will be converted to @**username**
|
||||||
// #stream in reply will be converted to #**stream**
|
// #stream in reply will be converted to #**stream**
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { remote } from 'electron';
|
import {remote} from 'electron';
|
||||||
import electron_bridge from '../electron-bridge';
|
import electron_bridge from '../electron-bridge';
|
||||||
import { appId, loadBots } from './helpers';
|
import {appId, loadBots} from './helpers';
|
||||||
|
|
||||||
import DefaultNotification from './default-notification';
|
import DefaultNotification from './default-notification';
|
||||||
const { app } = remote;
|
const {app} = remote;
|
||||||
|
|
||||||
// From https://github.com/felixrieseberg/electron-windows-notifications#appusermodelid
|
// From https://github.com/felixrieseberg/electron-windows-notifications#appusermodelid
|
||||||
// On windows 8 we have to explicitly set the appUserModelId otherwise notification won't work.
|
// On windows 8 we have to explicitly set the appUserModelId otherwise notification won't work.
|
||||||
@@ -16,7 +16,7 @@ if (process.platform === 'darwin') {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export interface NotificationData {
|
export interface NotificationData {
|
||||||
close(): void;
|
close: () => void;
|
||||||
title: string;
|
title: string;
|
||||||
dir: NotificationDirection;
|
dir: NotificationDirection;
|
||||||
lang: string;
|
lang: string;
|
||||||
@@ -47,6 +47,7 @@ export function newNotification(
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
close: () => notification.close(),
|
close: () => notification.close(),
|
||||||
title: notification.title,
|
title: notification.title,
|
||||||
@@ -67,6 +68,6 @@ export function newNotification(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
electron_bridge.once('zulip-loaded', () => {
|
electron_bridge.once('zulip-loaded', async () => {
|
||||||
loadBots();
|
await loadBots();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ipcRenderer } from 'electron';
|
import {ipcRenderer} from 'electron';
|
||||||
|
|
||||||
export function init($reconnectButton: Element, $settingsButton: Element): void {
|
export function init($reconnectButton: Element, $settingsButton: Element): void {
|
||||||
$reconnectButton.addEventListener('click', () => {
|
$reconnectButton.addEventListener('click', () => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
'use-strict';
|
'use-strict';
|
||||||
|
|
||||||
import { remote, OpenDialogOptions } from 'electron';
|
import {remote, OpenDialogOptions} from 'electron';
|
||||||
|
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import BaseComponent from '../../components/base';
|
import BaseComponent from '../../components/base';
|
||||||
@@ -12,7 +12,7 @@ interface AddCertificateProps {
|
|||||||
$root: Element;
|
$root: Element;
|
||||||
}
|
}
|
||||||
|
|
||||||
const { dialog } = remote;
|
const {dialog} = remote;
|
||||||
|
|
||||||
export default class AddCertificate extends BaseComponent {
|
export default class AddCertificate extends BaseComponent {
|
||||||
props: AddCertificateProps;
|
props: AddCertificateProps;
|
||||||
@@ -49,7 +49,7 @@ export default class AddCertificate extends BaseComponent {
|
|||||||
this.initListeners();
|
this.initListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
validateAndAdd(): void {
|
async validateAndAdd(): Promise<void> {
|
||||||
const certificate = this._certFile;
|
const certificate = this._certFile;
|
||||||
const serverUrl = this.serverUrl.value;
|
const serverUrl = this.serverUrl.value;
|
||||||
if (certificate !== '' && serverUrl !== '') {
|
if (certificate !== '' && serverUrl !== '') {
|
||||||
@@ -59,12 +59,13 @@ export default class AddCertificate extends BaseComponent {
|
|||||||
if (!copy) {
|
if (!copy) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
CertificateUtil.setCertificate(server, fileName);
|
CertificateUtil.setCertificate(server, fileName);
|
||||||
dialog.showMessageBox({
|
this.serverUrl.value = '';
|
||||||
|
await dialog.showMessageBox({
|
||||||
title: 'Success',
|
title: 'Success',
|
||||||
message: 'Certificate saved!'
|
message: 'Certificate saved!'
|
||||||
});
|
});
|
||||||
this.serverUrl.value = '';
|
|
||||||
} else {
|
} else {
|
||||||
dialog.showErrorBox('Error', `Please, ${serverUrl === '' ?
|
dialog.showErrorBox('Error', `Please, ${serverUrl === '' ?
|
||||||
'Enter an Organization URL' : 'Choose certificate file'}`);
|
'Enter an Organization URL' : 'Choose certificate file'}`);
|
||||||
@@ -75,23 +76,23 @@ export default class AddCertificate extends BaseComponent {
|
|||||||
const showDialogOptions: OpenDialogOptions = {
|
const showDialogOptions: OpenDialogOptions = {
|
||||||
title: 'Select file',
|
title: 'Select file',
|
||||||
properties: ['openFile'],
|
properties: ['openFile'],
|
||||||
filters: [{ name: 'crt, pem', extensions: ['crt', 'pem'] }]
|
filters: [{name: 'crt, pem', extensions: ['crt', 'pem']}]
|
||||||
};
|
};
|
||||||
const { filePaths, canceled } = await dialog.showOpenDialog(showDialogOptions);
|
const {filePaths, canceled} = await dialog.showOpenDialog(showDialogOptions);
|
||||||
if (!canceled) {
|
if (!canceled) {
|
||||||
this._certFile = filePaths[0] || '';
|
this._certFile = filePaths[0] || '';
|
||||||
this.validateAndAdd();
|
await this.validateAndAdd();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
initListeners(): void {
|
initListeners(): void {
|
||||||
this.addCertificateButton.addEventListener('click', () => {
|
this.addCertificateButton.addEventListener('click', async () => {
|
||||||
this.addHandler();
|
await this.addHandler();
|
||||||
});
|
});
|
||||||
|
|
||||||
this.serverUrl.addEventListener('keypress', event => {
|
this.serverUrl.addEventListener('keypress', async event => {
|
||||||
if (event.key === 'Enter') {
|
if (event.key === 'Enter') {
|
||||||
this.addHandler();
|
await this.addHandler();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import electron, { app } from 'electron';
|
import electron, {app} from 'electron';
|
||||||
|
|
||||||
import * as ConfigUtil from '../../utils/config-util';
|
import * as ConfigUtil from '../../utils/config-util';
|
||||||
|
|
||||||
@@ -30,6 +30,7 @@ function updateOverlayIcon(messageCount: number, mainWindow: electron.BrowserWin
|
|||||||
if (!mainWindow.isFocused()) {
|
if (!mainWindow.isFocused()) {
|
||||||
mainWindow.flashFrame(ConfigUtil.getConfigItem('flashTaskbarOnMessage'));
|
mainWindow.flashFrame(ConfigUtil.getConfigItem('flashTaskbarOnMessage'));
|
||||||
}
|
}
|
||||||
|
|
||||||
if (messageCount === 0) {
|
if (messageCount === 0) {
|
||||||
mainWindow.setOverlayIcon(null, '');
|
mainWindow.setOverlayIcon(null, '');
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ipcRenderer } from 'electron';
|
import {ipcRenderer} from 'electron';
|
||||||
import escape from 'escape-html';
|
import escape from 'escape-html';
|
||||||
|
|
||||||
import BaseComponent from '../../components/base';
|
import BaseComponent from '../../components/base';
|
||||||
@@ -35,8 +35,9 @@ export default class BaseSection extends BaseComponent {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
} else {
|
}
|
||||||
return `
|
|
||||||
|
return `
|
||||||
<div class="action">
|
<div class="action">
|
||||||
<div class="switch">
|
<div class="switch">
|
||||||
<input class="toggle toggle-round" type="checkbox">
|
<input class="toggle toggle-round" type="checkbox">
|
||||||
@@ -44,10 +45,9 @@ export default class BaseSection extends BaseComponent {
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
`;
|
`;
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/* a method that in future can be used to create dropdown menus using <select> <option> tags.
|
/* A method that in future can be used to create dropdown menus using <select> <option> tags.
|
||||||
it needs an object which has ``key: value`` pairs and will return a string that can be appended to HTML
|
it needs an object which has ``key: value`` pairs and will return a string that can be appended to HTML
|
||||||
*/
|
*/
|
||||||
generateSelectTemplate(options: {[key: string]: string}, className?: string, idName?: string): string {
|
generateSelectTemplate(options: {[key: string]: string}, className?: string, idName?: string): string {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ipcRenderer } from 'electron';
|
import {ipcRenderer} from 'electron';
|
||||||
|
|
||||||
import BaseSection from './base-section';
|
import BaseSection from './base-section';
|
||||||
import * as DomainUtil from '../../utils/domain-util';
|
import * as DomainUtil from '../../utils/domain-util';
|
||||||
|
|||||||
@@ -40,19 +40,21 @@ export default class FindAccounts extends BaseComponent {
|
|||||||
this.initListeners();
|
this.initListeners();
|
||||||
}
|
}
|
||||||
|
|
||||||
findAccounts(url: string): void {
|
async findAccounts(url: string): Promise<void> {
|
||||||
if (!url) {
|
if (!url) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!url.startsWith('http')) {
|
if (!url.startsWith('http')) {
|
||||||
url = 'https://' + url;
|
url = 'https://' + url;
|
||||||
}
|
}
|
||||||
LinkUtil.openBrowser(new URL('/accounts/find', url));
|
|
||||||
|
await LinkUtil.openBrowser(new URL('/accounts/find', url));
|
||||||
}
|
}
|
||||||
|
|
||||||
initListeners(): void {
|
initListeners(): void {
|
||||||
this.$findAccountsButton.addEventListener('click', () => {
|
this.$findAccountsButton.addEventListener('click', async () => {
|
||||||
this.findAccounts(this.$serverUrlField.value);
|
await this.findAccounts(this.$serverUrlField.value);
|
||||||
});
|
});
|
||||||
|
|
||||||
this.$serverUrlField.addEventListener('click', () => {
|
this.$serverUrlField.addEventListener('click', () => {
|
||||||
@@ -61,9 +63,9 @@ export default class FindAccounts extends BaseComponent {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
this.$serverUrlField.addEventListener('keypress', event => {
|
this.$serverUrlField.addEventListener('keypress', async event => {
|
||||||
if (event.key === 'Enter') {
|
if (event.key === 'Enter') {
|
||||||
this.findAccounts(this.$serverUrlField.value);
|
await this.findAccounts(this.$serverUrlField.value);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import { ipcRenderer, remote, OpenDialogOptions } from 'electron';
|
import {ipcRenderer, remote, OpenDialogOptions} from 'electron';
|
||||||
|
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import fs from 'fs-extra';
|
import fs from 'fs-extra';
|
||||||
|
|
||||||
const { app, dialog } = remote;
|
const {app, dialog} = remote;
|
||||||
const currentBrowserWindow = remote.getCurrentWindow();
|
const currentBrowserWindow = remote.getCurrentWindow();
|
||||||
|
|
||||||
import BaseSection from './base-section';
|
import BaseSection from './base-section';
|
||||||
@@ -101,7 +101,7 @@ export default class GeneralSection extends BaseSection {
|
|||||||
<div class="setting-description">${t.__('Enable error reporting (requires restart)')}</div>
|
<div class="setting-description">${t.__('Enable error reporting (requires restart)')}</div>
|
||||||
<div class="setting-control"></div>
|
<div class="setting-control"></div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="setting-row" id="app-language">
|
<div class="setting-row" id="app-language">
|
||||||
<div class="setting-description">${t.__('App language (requires restart)')}</div>
|
<div class="setting-description">${t.__('App language (requires restart)')}</div>
|
||||||
<div id="lang-div" class="lang-div"></div>
|
<div id="lang-div" class="lang-div"></div>
|
||||||
@@ -115,7 +115,7 @@ export default class GeneralSection extends BaseSection {
|
|||||||
</div>
|
</div>
|
||||||
<div class="setting-row" id="remove-custom-css">
|
<div class="setting-row" id="remove-custom-css">
|
||||||
<div class="setting-description">
|
<div class="setting-description">
|
||||||
<div class="selected-css-path" id="custom-css-path">${ConfigUtil.getConfigItem('customCSS')}</div>
|
<div class="selected-css-path" id="custom-css-path">${ConfigUtil.getConfigString('customCSS', '')}</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="action red" id="css-delete-action">
|
<div class="action red" id="css-delete-action">
|
||||||
<i class="material-icons">indeterminate_check_box</i>
|
<i class="material-icons">indeterminate_check_box</i>
|
||||||
@@ -130,7 +130,7 @@ export default class GeneralSection extends BaseSection {
|
|||||||
</div>
|
</div>
|
||||||
<div class="setting-row">
|
<div class="setting-row">
|
||||||
<div class="setting-description">
|
<div class="setting-description">
|
||||||
<div class="download-folder-path">${ConfigUtil.getConfigItem('downloadsPath', `${app.getPath('downloads')}`)}</div>
|
<div class="download-folder-path">${ConfigUtil.getConfigString('downloadsPath', app.getPath('downloads'))}</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div class="setting-row" id="prompt-download">
|
<div class="setting-row" id="prompt-download">
|
||||||
@@ -178,6 +178,7 @@ export default class GeneralSection extends BaseSection {
|
|||||||
if (process.platform === 'win32') {
|
if (process.platform === 'win32') {
|
||||||
this.updateFlashTaskbar();
|
this.updateFlashTaskbar();
|
||||||
}
|
}
|
||||||
|
|
||||||
// Dock bounce on macOS
|
// Dock bounce on macOS
|
||||||
if (process.platform === 'darwin') {
|
if (process.platform === 'darwin') {
|
||||||
this.updateDockBouncing();
|
this.updateDockBouncing();
|
||||||
@@ -264,6 +265,7 @@ export default class GeneralSection extends BaseSection {
|
|||||||
ConfigUtil.setConfigItem('betaUpdate', false);
|
ConfigUtil.setConfigItem('betaUpdate', false);
|
||||||
this.betaUpdateOption();
|
this.betaUpdateOption();
|
||||||
}
|
}
|
||||||
|
|
||||||
this.autoUpdateOption();
|
this.autoUpdateOption();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -374,7 +376,7 @@ export default class GeneralSection extends BaseSection {
|
|||||||
const clearAppDataMessage = 'By clicking proceed you will be removing all added accounts and preferences from Zulip. When the application restarts, it will be as if you are starting Zulip for the first time.';
|
const clearAppDataMessage = 'By clicking proceed you will be removing all added accounts and preferences from Zulip. When the application restarts, it will be as if you are starting Zulip for the first time.';
|
||||||
const getAppPath = path.join(app.getPath('appData'), app.name);
|
const getAppPath = path.join(app.getPath('appData'), app.name);
|
||||||
|
|
||||||
const { response } = await dialog.showMessageBox({
|
const {response} = await dialog.showMessageBox({
|
||||||
type: 'warning',
|
type: 'warning',
|
||||||
buttons: ['YES', 'NO'],
|
buttons: ['YES', 'NO'],
|
||||||
defaultId: 0,
|
defaultId: 0,
|
||||||
@@ -382,8 +384,8 @@ export default class GeneralSection extends BaseSection {
|
|||||||
detail: clearAppDataMessage
|
detail: clearAppDataMessage
|
||||||
});
|
});
|
||||||
if (response === 0) {
|
if (response === 0) {
|
||||||
fs.remove(getAppPath);
|
await fs.remove(getAppPath);
|
||||||
setTimeout(() => ipcRenderer.send('forward-message', 'hard-reload'), 1000);
|
ipcRenderer.send('forward-message', 'hard-reload');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -391,10 +393,10 @@ export default class GeneralSection extends BaseSection {
|
|||||||
const showDialogOptions: OpenDialogOptions = {
|
const showDialogOptions: OpenDialogOptions = {
|
||||||
title: 'Select file',
|
title: 'Select file',
|
||||||
properties: ['openFile'],
|
properties: ['openFile'],
|
||||||
filters: [{ name: 'CSS file', extensions: ['css'] }]
|
filters: [{name: 'CSS file', extensions: ['css']}]
|
||||||
};
|
};
|
||||||
|
|
||||||
const { filePaths, canceled } = await dialog.showOpenDialog(showDialogOptions);
|
const {filePaths, canceled} = await dialog.showOpenDialog(showDialogOptions);
|
||||||
if (!canceled) {
|
if (!canceled) {
|
||||||
ConfigUtil.setConfigItem('customCSS', filePaths[0]);
|
ConfigUtil.setConfigItem('customCSS', filePaths[0]);
|
||||||
ipcRenderer.send('forward-message', 'hard-reload');
|
ipcRenderer.send('forward-message', 'hard-reload');
|
||||||
@@ -403,8 +405,8 @@ export default class GeneralSection extends BaseSection {
|
|||||||
|
|
||||||
updateResetDataOption(): void {
|
updateResetDataOption(): void {
|
||||||
const resetDataButton = document.querySelector('#resetdata-option .reset-data-button');
|
const resetDataButton = document.querySelector('#resetdata-option .reset-data-button');
|
||||||
resetDataButton.addEventListener('click', () => {
|
resetDataButton.addEventListener('click', async () => {
|
||||||
this.clearAppDataDialog();
|
await this.clearAppDataDialog();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -413,7 +415,7 @@ export default class GeneralSection extends BaseSection {
|
|||||||
// This path is for the JSON file that stores key: value pairs for supported locales
|
// This path is for the JSON file that stores key: value pairs for supported locales
|
||||||
const langList = this.generateSelectTemplate(supportedLocales, 'lang-menu');
|
const langList = this.generateSelectTemplate(supportedLocales, 'lang-menu');
|
||||||
langDiv.innerHTML += langList;
|
langDiv.innerHTML += langList;
|
||||||
// langMenu is the select-option dropdown menu formed after executing the previous command
|
// `langMenu` is the select-option dropdown menu formed after executing the previous command
|
||||||
const langMenu: HTMLSelectElement = document.querySelector('.lang-menu');
|
const langMenu: HTMLSelectElement = document.querySelector('.lang-menu');
|
||||||
|
|
||||||
// The next three lines set the selected language visible on the dropdown button
|
// The next three lines set the selected language visible on the dropdown button
|
||||||
@@ -440,8 +442,8 @@ export default class GeneralSection extends BaseSection {
|
|||||||
|
|
||||||
addCustomCSS(): void {
|
addCustomCSS(): void {
|
||||||
const customCSSButton = document.querySelector('#add-custom-css .custom-css-button');
|
const customCSSButton = document.querySelector('#add-custom-css .custom-css-button');
|
||||||
customCSSButton.addEventListener('click', () => {
|
customCSSButton.addEventListener('click', async () => {
|
||||||
this.customCssDialog();
|
await this.customCssDialog();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -466,7 +468,7 @@ export default class GeneralSection extends BaseSection {
|
|||||||
properties: ['openDirectory']
|
properties: ['openDirectory']
|
||||||
};
|
};
|
||||||
|
|
||||||
const { filePaths, canceled } = await dialog.showOpenDialog(showDialogOptions);
|
const {filePaths, canceled} = await dialog.showOpenDialog(showDialogOptions);
|
||||||
if (!canceled) {
|
if (!canceled) {
|
||||||
ConfigUtil.setConfigItem('downloadsPath', filePaths[0]);
|
ConfigUtil.setConfigItem('downloadsPath', filePaths[0]);
|
||||||
const downloadFolderPath: HTMLElement = document.querySelector('.download-folder-path');
|
const downloadFolderPath: HTMLElement = document.querySelector('.download-folder-path');
|
||||||
@@ -476,8 +478,8 @@ export default class GeneralSection extends BaseSection {
|
|||||||
|
|
||||||
downloadFolder(): void {
|
downloadFolder(): void {
|
||||||
const downloadFolder = document.querySelector('#download-folder .download-folder-button');
|
const downloadFolder = document.querySelector('#download-folder .download-folder-button');
|
||||||
downloadFolder.addEventListener('click', () => {
|
downloadFolder.addEventListener('click', async () => {
|
||||||
this.downloadFolderDialog();
|
await this.downloadFolderDialog();
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ipcRenderer } from 'electron';
|
import {ipcRenderer} from 'electron';
|
||||||
|
|
||||||
import BaseSection from './base-section';
|
import BaseSection from './base-section';
|
||||||
import * as ConfigUtil from '../../utils/config-util';
|
import * as ConfigUtil from '../../utils/config-util';
|
||||||
@@ -105,11 +105,13 @@ export default class NetworkSection extends BaseSection {
|
|||||||
ConfigUtil.setConfigItem('useManualProxy', !manualProxyValue);
|
ConfigUtil.setConfigItem('useManualProxy', !manualProxyValue);
|
||||||
this.toggleManualProxySettings(!manualProxyValue);
|
this.toggleManualProxySettings(!manualProxyValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!newValue) {
|
if (!newValue) {
|
||||||
// Remove proxy system proxy settings
|
// Remove proxy system proxy settings
|
||||||
ConfigUtil.setConfigItem('proxyRules', '');
|
ConfigUtil.setConfigItem('proxyRules', '');
|
||||||
ipcRenderer.send('forward-message', 'reload-proxy', false);
|
ipcRenderer.send('forward-message', 'reload-proxy', false);
|
||||||
}
|
}
|
||||||
|
|
||||||
ConfigUtil.setConfigItem('useSystemProxy', newValue);
|
ConfigUtil.setConfigItem('useSystemProxy', newValue);
|
||||||
this.updateProxyOption();
|
this.updateProxyOption();
|
||||||
}
|
}
|
||||||
@@ -124,6 +126,7 @@ export default class NetworkSection extends BaseSection {
|
|||||||
if (systemProxyValue && newValue) {
|
if (systemProxyValue && newValue) {
|
||||||
ConfigUtil.setConfigItem('useSystemProxy', !systemProxyValue);
|
ConfigUtil.setConfigItem('useSystemProxy', !systemProxyValue);
|
||||||
}
|
}
|
||||||
|
|
||||||
ConfigUtil.setConfigItem('proxyRules', '');
|
ConfigUtil.setConfigItem('proxyRules', '');
|
||||||
ConfigUtil.setConfigItem('useManualProxy', newValue);
|
ConfigUtil.setConfigItem('useManualProxy', newValue);
|
||||||
// Reload app only when turning manual proxy off, hence !newValue
|
// Reload app only when turning manual proxy off, hence !newValue
|
||||||
|
|||||||
@@ -1,10 +1,12 @@
|
|||||||
import { ipcRenderer } from 'electron';
|
import {ipcRenderer, remote} from 'electron';
|
||||||
|
|
||||||
import BaseComponent from '../../components/base';
|
import BaseComponent from '../../components/base';
|
||||||
import * as DomainUtil from '../../utils/domain-util';
|
import * as DomainUtil from '../../utils/domain-util';
|
||||||
import * as LinkUtil from '../../utils/link-util';
|
import * as LinkUtil from '../../utils/link-util';
|
||||||
import * as t from '../../utils/translation-util';
|
import * as t from '../../utils/translation-util';
|
||||||
|
|
||||||
|
const {dialog} = remote;
|
||||||
|
|
||||||
interface NewServerFormProps {
|
interface NewServerFormProps {
|
||||||
$root: Element;
|
$root: Element;
|
||||||
onChange: () => void;
|
onChange: () => void;
|
||||||
@@ -66,11 +68,16 @@ export default class NewServerForm extends BaseComponent {
|
|||||||
let serverConf;
|
let serverConf;
|
||||||
try {
|
try {
|
||||||
serverConf = await DomainUtil.checkDomain(this.$newServerUrl.value);
|
serverConf = await DomainUtil.checkDomain(this.$newServerUrl.value);
|
||||||
} catch (errorMessage) {
|
} catch (error) {
|
||||||
this.$saveServerButton.innerHTML = 'Connect';
|
this.$saveServerButton.innerHTML = 'Connect';
|
||||||
alert(errorMessage);
|
await dialog.showMessageBox({
|
||||||
|
type: 'error',
|
||||||
|
message: error.toString(),
|
||||||
|
buttons: ['OK']
|
||||||
|
});
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await DomainUtil.addDomain(serverConf);
|
await DomainUtil.addDomain(serverConf);
|
||||||
this.props.onChange();
|
this.props.onChange();
|
||||||
}
|
}
|
||||||
@@ -78,8 +85,8 @@ export default class NewServerForm extends BaseComponent {
|
|||||||
openCreateNewOrgExternalLink(): void {
|
openCreateNewOrgExternalLink(): void {
|
||||||
const link = 'https://zulipchat.com/new/';
|
const link = 'https://zulipchat.com/new/';
|
||||||
const externalCreateNewOrgElement = document.querySelector('#open-create-org-link');
|
const externalCreateNewOrgElement = document.querySelector('#open-create-org-link');
|
||||||
externalCreateNewOrgElement.addEventListener('click', () => {
|
externalCreateNewOrgElement.addEventListener('click', async () => {
|
||||||
LinkUtil.openBrowser(new URL(link));
|
await LinkUtil.openBrowser(new URL(link));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -89,15 +96,15 @@ export default class NewServerForm extends BaseComponent {
|
|||||||
}
|
}
|
||||||
|
|
||||||
initActions(): void {
|
initActions(): void {
|
||||||
this.$saveServerButton.addEventListener('click', () => {
|
this.$saveServerButton.addEventListener('click', async () => {
|
||||||
this.submitFormHandler();
|
await this.submitFormHandler();
|
||||||
});
|
});
|
||||||
this.$newServerUrl.addEventListener('keypress', event => {
|
this.$newServerUrl.addEventListener('keypress', async event => {
|
||||||
if (event.key === 'Enter') {
|
if (event.key === 'Enter') {
|
||||||
this.submitFormHandler();
|
await this.submitFormHandler();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// open create new org link in default browser
|
// Open create new org link in default browser
|
||||||
this.openCreateNewOrgExternalLink();
|
this.openCreateNewOrgExternalLink();
|
||||||
this.networkSettingsLink();
|
this.networkSettingsLink();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ipcRenderer } from 'electron';
|
import {ipcRenderer} from 'electron';
|
||||||
|
|
||||||
import BaseComponent from '../../components/base';
|
import BaseComponent from '../../components/base';
|
||||||
import Nav from './nav';
|
import Nav from './nav';
|
||||||
@@ -7,6 +7,7 @@ import GeneralSection from './general-section';
|
|||||||
import NetworkSection from './network-section';
|
import NetworkSection from './network-section';
|
||||||
import ConnectedOrgSection from './connected-org-section';
|
import ConnectedOrgSection from './connected-org-section';
|
||||||
import ShortcutsSection from './shortcuts-section';
|
import ShortcutsSection from './shortcuts-section';
|
||||||
|
import type {DNDSettings} from '../../utils/dnd-util';
|
||||||
|
|
||||||
type Section = ServersSection | GeneralSection | NetworkSection | ConnectedOrgSection | ShortcutsSection;
|
type Section = ServersSection | GeneralSection | NetworkSection | ConnectedOrgSection | ShortcutsSection;
|
||||||
|
|
||||||
@@ -37,6 +38,7 @@ export default class PreferenceView extends BaseComponent {
|
|||||||
if (hasTag) {
|
if (hasTag) {
|
||||||
nav = hasTag.slice(1);
|
nav = hasTag.slice(1);
|
||||||
}
|
}
|
||||||
|
|
||||||
this.handleNavigation(nav);
|
this.handleNavigation(nav);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,32 +51,38 @@ export default class PreferenceView extends BaseComponent {
|
|||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'General': {
|
case 'General': {
|
||||||
this.section = new GeneralSection({
|
this.section = new GeneralSection({
|
||||||
$root: this.$settingsContainer
|
$root: this.$settingsContainer
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'Organizations': {
|
case 'Organizations': {
|
||||||
this.section = new ConnectedOrgSection({
|
this.section = new ConnectedOrgSection({
|
||||||
$root: this.$settingsContainer
|
$root: this.$settingsContainer
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'Network': {
|
case 'Network': {
|
||||||
this.section = new NetworkSection({
|
this.section = new NetworkSection({
|
||||||
$root: this.$settingsContainer
|
$root: this.$settingsContainer
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case 'Shortcuts': {
|
case 'Shortcuts': {
|
||||||
this.section = new ShortcutsSection({
|
this.section = new ShortcutsSection({
|
||||||
$root: this.$settingsContainer
|
$root: this.$settingsContainer
|
||||||
});
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
default: break;
|
default: break;
|
||||||
}
|
}
|
||||||
|
|
||||||
this.section.init();
|
this.section.init();
|
||||||
window.location.hash = `#${navItem}`;
|
window.location.hash = `#${navItem}`;
|
||||||
}
|
}
|
||||||
@@ -105,7 +113,7 @@ export default class PreferenceView extends BaseComponent {
|
|||||||
this.handleToggle('tray-option', state);
|
this.handleToggle('tray-option', state);
|
||||||
});
|
});
|
||||||
|
|
||||||
ipcRenderer.on('toggle-dnd', (_event: Event, _state: boolean, newSettings: any) => {
|
ipcRenderer.on('toggle-dnd', (_event: Event, _state: boolean, newSettings: DNDSettings) => {
|
||||||
this.handleToggle('show-notification-option', newSettings.showNotification);
|
this.handleToggle('show-notification-option', newSettings.showNotification);
|
||||||
this.handleToggle('silent-option', newSettings.silent);
|
this.handleToggle('silent-option', newSettings.silent);
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
import { remote, ipcRenderer } from 'electron';
|
import {remote, ipcRenderer} from 'electron';
|
||||||
|
|
||||||
import BaseComponent from '../../components/base';
|
import BaseComponent from '../../components/base';
|
||||||
import * as DomainUtil from '../../utils/domain-util';
|
import * as DomainUtil from '../../utils/domain-util';
|
||||||
import * as Messages from '../../../../resources/messages';
|
import * as Messages from '../../../../resources/messages';
|
||||||
import * as t from '../../utils/translation-util';
|
import * as t from '../../utils/translation-util';
|
||||||
|
|
||||||
const { dialog } = remote;
|
const {dialog} = remote;
|
||||||
|
|
||||||
interface ServerInfoFormProps {
|
interface ServerInfoFormProps {
|
||||||
$root: Element;
|
$root: Element;
|
||||||
@@ -66,7 +66,7 @@ export default class ServerInfoForm extends BaseComponent {
|
|||||||
|
|
||||||
initActions(): void {
|
initActions(): void {
|
||||||
this.$deleteServerButton.addEventListener('click', async () => {
|
this.$deleteServerButton.addEventListener('click', async () => {
|
||||||
const { response } = await dialog.showMessageBox({
|
const {response} = await dialog.showMessageBox({
|
||||||
type: 'warning',
|
type: 'warning',
|
||||||
buttons: [t.__('YES'), t.__('NO')],
|
buttons: [t.__('YES'), t.__('NO')],
|
||||||
defaultId: 0,
|
defaultId: 0,
|
||||||
@@ -76,7 +76,7 @@ export default class ServerInfoForm extends BaseComponent {
|
|||||||
if (DomainUtil.removeDomain(this.props.index)) {
|
if (DomainUtil.removeDomain(this.props.index)) {
|
||||||
ipcRenderer.send('reload-full-app');
|
ipcRenderer.send('reload-full-app');
|
||||||
} else {
|
} else {
|
||||||
const { title, content } = Messages.orgRemovalError(DomainUtil.getDomain(this.props.index).url);
|
const {title, content} = Messages.orgRemovalError(DomainUtil.getDomain(this.props.index).url);
|
||||||
dialog.showErrorBox(title, content);
|
dialog.showErrorBox(title, content);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -332,8 +332,8 @@ export default class ShortcutsSection extends BaseSection {
|
|||||||
openHotkeysExternalLink(): void {
|
openHotkeysExternalLink(): void {
|
||||||
const link = 'https://zulipchat.com/help/keyboard-shortcuts';
|
const link = 'https://zulipchat.com/help/keyboard-shortcuts';
|
||||||
const externalCreateNewOrgElement = document.querySelector('#open-hotkeys-link');
|
const externalCreateNewOrgElement = document.querySelector('#open-hotkeys-link');
|
||||||
externalCreateNewOrgElement.addEventListener('click', () => {
|
externalCreateNewOrgElement.addEventListener('click', async () => {
|
||||||
LinkUtil.openBrowser(new URL(link));
|
await LinkUtil.openBrowser(new URL(link));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { contextBridge, ipcRenderer, webFrame } from 'electron';
|
import {contextBridge, ipcRenderer, webFrame} from 'electron';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import * as SetupSpellChecker from './spellchecker';
|
import * as SetupSpellChecker from './spellchecker';
|
||||||
|
|
||||||
@@ -48,19 +48,20 @@ ipcRenderer.on('show-notification-settings', () => {
|
|||||||
|
|
||||||
const notificationItem: NodeListOf<HTMLElement> = document.querySelectorAll('.normal-settings-list li div');
|
const notificationItem: NodeListOf<HTMLElement> = document.querySelectorAll('.normal-settings-list li div');
|
||||||
|
|
||||||
// wait until the notification dom element shows up
|
// Wait until the notification dom element shows up
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
notificationItem[2].click();
|
notificationItem[2].click();
|
||||||
}, 100);
|
}, 100);
|
||||||
});
|
});
|
||||||
|
|
||||||
electron_bridge.once('zulip-loaded', ({ serverLanguage }) => {
|
electron_bridge.once('zulip-loaded', ({serverLanguage}) => {
|
||||||
// Get the default language of the server
|
// Get the default language of the server
|
||||||
if (serverLanguage) {
|
if (serverLanguage) {
|
||||||
// Init spellchecker
|
// Init spellchecker
|
||||||
SetupSpellChecker.init(serverLanguage);
|
SetupSpellChecker.init(serverLanguage);
|
||||||
}
|
}
|
||||||
// redirect users to network troubleshooting page
|
|
||||||
|
// Redirect users to network troubleshooting page
|
||||||
const getRestartButton = document.querySelector('.restart_get_events_button');
|
const getRestartButton = document.querySelector('.restart_get_events_button');
|
||||||
if (getRestartButton) {
|
if (getRestartButton) {
|
||||||
getRestartButton.addEventListener('click', () => {
|
getRestartButton.addEventListener('click', () => {
|
||||||
@@ -79,12 +80,13 @@ window.addEventListener('load', (event: any): void => {
|
|||||||
if (!event.target.URL.includes('app/renderer/network.html')) {
|
if (!event.target.URL.includes('app/renderer/network.html')) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const $reconnectButton = document.querySelector('#reconnect');
|
const $reconnectButton = document.querySelector('#reconnect');
|
||||||
const $settingsButton = document.querySelector('#settings');
|
const $settingsButton = document.querySelector('#settings');
|
||||||
NetworkError.init($reconnectButton, $settingsButton);
|
NetworkError.init($reconnectButton, $settingsButton);
|
||||||
});
|
});
|
||||||
|
|
||||||
// electron's globalShortcut can cause unexpected results
|
// Electron's globalShortcut can cause unexpected results
|
||||||
// so adding the reload shortcut in the old-school way
|
// so adding the reload shortcut in the old-school way
|
||||||
// Zoom from numpad keys is not supported by electron, so adding it through listeners.
|
// Zoom from numpad keys is not supported by electron, so adding it through listeners.
|
||||||
document.addEventListener('keydown', event => {
|
document.addEventListener('keydown', event => {
|
||||||
@@ -105,6 +107,7 @@ ipcRenderer.on('set-active', () => {
|
|||||||
if (isDev) {
|
if (isDev) {
|
||||||
console.log('active');
|
console.log('active');
|
||||||
}
|
}
|
||||||
|
|
||||||
electron_bridge.idle_on_system = false;
|
electron_bridge.idle_on_system = false;
|
||||||
electron_bridge.last_active_on_system = Date.now();
|
electron_bridge.last_active_on_system = Date.now();
|
||||||
});
|
});
|
||||||
@@ -114,9 +117,10 @@ ipcRenderer.on('set-idle', () => {
|
|||||||
if (isDev) {
|
if (isDev) {
|
||||||
console.log('idle');
|
console.log('idle');
|
||||||
}
|
}
|
||||||
|
|
||||||
electron_bridge.idle_on_system = true;
|
electron_bridge.idle_on_system = true;
|
||||||
});
|
});
|
||||||
|
|
||||||
webFrame.executeJavaScript(
|
(async () => webFrame.executeJavaScript(
|
||||||
fs.readFileSync(require.resolve('./injected'), 'utf8')
|
fs.readFileSync(require.resolve('./injected'), 'utf8')
|
||||||
);
|
))();
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { Subject } from 'rxjs';
|
import type {Subject} from 'rxjs';
|
||||||
import { SpellCheckHandler, ContextMenuListener, ContextMenuBuilder } from 'electron-spellchecker';
|
import {SpellCheckHandler, ContextMenuListener, ContextMenuBuilder} from 'electron-spellchecker';
|
||||||
|
|
||||||
import * as ConfigUtil from './utils/config-util';
|
import * as ConfigUtil from './utils/config-util';
|
||||||
import Logger from './utils/logger-util';
|
import Logger from './utils/logger-util';
|
||||||
@@ -23,14 +23,15 @@ export function init(serverLanguage: string): void {
|
|||||||
if (ConfigUtil.getConfigItem('enableSpellchecker')) {
|
if (ConfigUtil.getConfigItem('enableSpellchecker')) {
|
||||||
enableSpellChecker();
|
enableSpellChecker();
|
||||||
}
|
}
|
||||||
|
|
||||||
enableContextMenu(serverLanguage);
|
enableContextMenu(serverLanguage);
|
||||||
}
|
}
|
||||||
|
|
||||||
function enableSpellChecker(): void {
|
function enableSpellChecker(): void {
|
||||||
try {
|
try {
|
||||||
spellCheckHandler = new SpellCheckHandler();
|
spellCheckHandler = new SpellCheckHandler();
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
logger.error(err);
|
logger.error(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,6 +54,7 @@ export function unsubscribeSpellChecker(): void {
|
|||||||
if (spellCheckHandler) {
|
if (spellCheckHandler) {
|
||||||
spellCheckHandler.unsubscribe();
|
spellCheckHandler.unsubscribe();
|
||||||
}
|
}
|
||||||
|
|
||||||
if (contextMenuListener) {
|
if (contextMenuListener) {
|
||||||
contextMenuListener.unsubscribe();
|
contextMenuListener.unsubscribe();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
import { ipcRenderer, remote, WebviewTag, NativeImage } from 'electron';
|
import {ipcRenderer, remote, WebviewTag, NativeImage} from 'electron';
|
||||||
|
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import * as ConfigUtil from './utils/config-util';
|
import * as ConfigUtil from './utils/config-util';
|
||||||
|
|
||||||
const { Tray, Menu, nativeImage, BrowserWindow, nativeTheme } = remote;
|
const {Tray, Menu, nativeImage, BrowserWindow, nativeTheme} = remote;
|
||||||
|
|
||||||
let tray: Electron.Tray;
|
let tray: Electron.Tray;
|
||||||
|
|
||||||
// get the theme on macOS
|
// Get the theme on macOS
|
||||||
const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
|
const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
|
||||||
|
|
||||||
const ICON_DIR = process.platform === 'darwin' ? `../../resources/tray/${theme}` : '../../resources/tray';
|
const ICON_DIR = process.platform === 'darwin' ? `../../resources/tray/${theme}` : '../../resources/tray';
|
||||||
@@ -20,6 +20,7 @@ const iconPath = (): string => {
|
|||||||
if (process.platform === 'linux') {
|
if (process.platform === 'linux') {
|
||||||
return APP_ICON + 'linux.png';
|
return APP_ICON + 'linux.png';
|
||||||
}
|
}
|
||||||
|
|
||||||
return APP_ICON + (process.platform === 'win32' ? 'win.ico' : 'osx.png');
|
return APP_ICON + (process.platform === 'win32' ? 'win.ico' : 'osx.png');
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -92,6 +93,7 @@ const renderCanvas = function (arg: number): HTMLCanvasElement {
|
|||||||
|
|
||||||
return canvas;
|
return canvas;
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Renders the tray icon as a native image
|
* Renders the tray icon as a native image
|
||||||
* @param arg: Unread count
|
* @param arg: Unread count
|
||||||
@@ -168,6 +170,7 @@ ipcRenderer.on('tray', (_event: Event, arg: number): void => {
|
|||||||
if (!tray) {
|
if (!tray) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// We don't want to create tray from unread messages on macOS since it already has dock badges.
|
// We don't want to create tray from unread messages on macOS since it already has dock badges.
|
||||||
if (process.platform === 'linux' || process.platform === 'win32') {
|
if (process.platform === 'linux' || process.platform === 'win32') {
|
||||||
if (arg === 0) {
|
if (arg === 0) {
|
||||||
@@ -178,7 +181,7 @@ ipcRenderer.on('tray', (_event: Event, arg: number): void => {
|
|||||||
unread = arg;
|
unread = arg;
|
||||||
const image = renderNativeImage(arg);
|
const image = renderNativeImage(arg);
|
||||||
tray.setImage(image);
|
tray.setImage(image);
|
||||||
tray.setToolTip(arg + ' unread messages');
|
tray.setToolTip(`${arg} unread messages`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -191,6 +194,7 @@ function toggleTray(): void {
|
|||||||
if (tray.isDestroyed()) {
|
if (tray.isDestroyed()) {
|
||||||
tray = null;
|
tray = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
ConfigUtil.setConfigItem('trayIcon', false);
|
ConfigUtil.setConfigItem('trayIcon', false);
|
||||||
} else {
|
} else {
|
||||||
state = true;
|
state = true;
|
||||||
@@ -198,10 +202,12 @@ function toggleTray(): void {
|
|||||||
if (process.platform === 'linux' || process.platform === 'win32') {
|
if (process.platform === 'linux' || process.platform === 'win32') {
|
||||||
const image = renderNativeImage(unread);
|
const image = renderNativeImage(unread);
|
||||||
tray.setImage(image);
|
tray.setImage(image);
|
||||||
tray.setToolTip(unread + ' unread messages');
|
tray.setToolTip(`${unread} unread messages`);
|
||||||
}
|
}
|
||||||
|
|
||||||
ConfigUtil.setConfigItem('trayIcon', true);
|
ConfigUtil.setConfigItem('trayIcon', true);
|
||||||
}
|
}
|
||||||
|
|
||||||
const selector = 'webview:not([class*=disabled])';
|
const selector = 'webview:not([class*=disabled])';
|
||||||
const webview: WebviewTag = document.querySelector(selector);
|
const webview: WebviewTag = document.querySelector(selector);
|
||||||
const webContents = webview.getWebContents();
|
const webContents = webview.getWebContents();
|
||||||
|
|||||||
@@ -1,12 +1,13 @@
|
|||||||
import { remote } from 'electron';
|
import electron from 'electron';
|
||||||
import { JsonDB } from 'node-json-db';
|
import {JsonDB} from 'node-json-db';
|
||||||
import { initSetUp } from './default-util';
|
import {initSetUp} from './default-util';
|
||||||
|
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import Logger from './logger-util';
|
import Logger from './logger-util';
|
||||||
|
|
||||||
const { app, dialog } = remote;
|
const {app, dialog} =
|
||||||
|
process.type === 'renderer' ? electron.remote : electron;
|
||||||
|
|
||||||
initSetUp();
|
initSetUp();
|
||||||
|
|
||||||
@@ -21,14 +22,9 @@ let db: JsonDB;
|
|||||||
|
|
||||||
reloadDB();
|
reloadDB();
|
||||||
|
|
||||||
export function getCertificate(server: string, defaultValue: any = null): any {
|
export function getCertificate(server: string): string | undefined {
|
||||||
reloadDB();
|
reloadDB();
|
||||||
const value = db.getData('/')[server];
|
return db.getData('/')[server];
|
||||||
if (value === undefined) {
|
|
||||||
return defaultValue;
|
|
||||||
} else {
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Function to copy the certificate to userData folder
|
// Function to copy the certificate to userData folder
|
||||||
@@ -38,14 +34,15 @@ export function copyCertificate(_server: string, location: string, fileName: str
|
|||||||
try {
|
try {
|
||||||
fs.copyFileSync(location, filePath);
|
fs.copyFileSync(location, filePath);
|
||||||
copied = true;
|
copied = true;
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
dialog.showErrorBox(
|
dialog.showErrorBox(
|
||||||
'Error saving certificate',
|
'Error saving certificate',
|
||||||
'We encountered error while saving the certificate.'
|
'We encountered error while saving the certificate.'
|
||||||
);
|
);
|
||||||
logger.error('Error while copying the certificate to certificates folder.');
|
logger.error('Error while copying the certificate to certificates folder.');
|
||||||
logger.error(err);
|
logger.error(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
return copied;
|
return copied;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -65,7 +62,7 @@ function reloadDB(): void {
|
|||||||
try {
|
try {
|
||||||
const file = fs.readFileSync(settingsJsonPath, 'utf8');
|
const file = fs.readFileSync(settingsJsonPath, 'utf8');
|
||||||
JSON.parse(file);
|
JSON.parse(file);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
if (fs.existsSync(settingsJsonPath)) {
|
if (fs.existsSync(settingsJsonPath)) {
|
||||||
fs.unlinkSync(settingsJsonPath);
|
fs.unlinkSync(settingsJsonPath);
|
||||||
dialog.showErrorBox(
|
dialog.showErrorBox(
|
||||||
@@ -73,8 +70,9 @@ function reloadDB(): void {
|
|||||||
'We encountered error while saving the certificate.'
|
'We encountered error while saving the certificate.'
|
||||||
);
|
);
|
||||||
logger.error('Error while JSON parsing certificates.json: ');
|
logger.error('Error while JSON parsing certificates.json: ');
|
||||||
logger.error(err);
|
logger.error(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
db = new JsonDB(settingsJsonPath, true, true);
|
db = new JsonDB(settingsJsonPath, true, true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
// unescape already encoded/escaped strings
|
// Unescape already encoded/escaped strings
|
||||||
export function decodeString(stringInput: string): string {
|
export function decodeString(stringInput: string): string {
|
||||||
const parser = new DOMParser();
|
const parser = new DOMParser();
|
||||||
const dom = parser.parseFromString(
|
const dom = parser.parseFromString(
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { JsonDB } from 'node-json-db';
|
import {JsonDB} from 'node-json-db';
|
||||||
|
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
@@ -16,7 +16,7 @@ let app: Electron.App = null;
|
|||||||
|
|
||||||
/* To make the util runnable in both main and renderer process */
|
/* To make the util runnable in both main and renderer process */
|
||||||
if (process.type === 'renderer') {
|
if (process.type === 'renderer') {
|
||||||
const { remote } = electron;
|
const {remote} = electron;
|
||||||
dialog = remote.dialog;
|
dialog = remote.dialog;
|
||||||
app = remote.app;
|
app = remote.app;
|
||||||
} else {
|
} else {
|
||||||
@@ -28,39 +28,52 @@ let db: JsonDB;
|
|||||||
|
|
||||||
reloadDB();
|
reloadDB();
|
||||||
|
|
||||||
export function getConfigItem(key: string, defaultValue: any = null): any {
|
export function getConfigItem(key: string, defaultValue: unknown = null): any {
|
||||||
try {
|
try {
|
||||||
db.reload();
|
db.reload();
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
logger.error('Error while reloading settings.json: ');
|
logger.error('Error while reloading settings.json: ');
|
||||||
logger.error(err);
|
logger.error(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
const value = db.getData('/')[key];
|
const value = db.getData('/')[key];
|
||||||
if (value === undefined) {
|
if (value === undefined) {
|
||||||
setConfigItem(key, defaultValue);
|
setConfigItem(key, defaultValue);
|
||||||
return defaultValue;
|
return defaultValue;
|
||||||
} else {
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getConfigString(key: string, defaultValue: string): string {
|
||||||
|
const value = getConfigItem(key, defaultValue);
|
||||||
|
if (typeof value === 'string') {
|
||||||
return value;
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setConfigItem(key, defaultValue);
|
||||||
|
return defaultValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// This function returns whether a key exists in the configuration file (settings.json)
|
// This function returns whether a key exists in the configuration file (settings.json)
|
||||||
export function isConfigItemExists(key: string): boolean {
|
export function isConfigItemExists(key: string): boolean {
|
||||||
try {
|
try {
|
||||||
db.reload();
|
db.reload();
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
logger.error('Error while reloading settings.json: ');
|
logger.error('Error while reloading settings.json: ');
|
||||||
logger.error(err);
|
logger.error(error);
|
||||||
}
|
}
|
||||||
|
|
||||||
const value = db.getData('/')[key];
|
const value = db.getData('/')[key];
|
||||||
return (value !== undefined);
|
return (value !== undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setConfigItem(key: string, value: any, override? : boolean): void {
|
export function setConfigItem(key: string, value: unknown, override? : boolean): void {
|
||||||
if (EnterpriseUtil.configItemExists(key) && !override) {
|
if (EnterpriseUtil.configItemExists(key) && !override) {
|
||||||
// if item is in global config and we're not trying to override
|
// If item is in global config and we're not trying to override
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
db.push(`/${key}`, value, true);
|
db.push(`/${key}`, value, true);
|
||||||
db.save();
|
db.save();
|
||||||
}
|
}
|
||||||
@@ -75,7 +88,7 @@ function reloadDB(): void {
|
|||||||
try {
|
try {
|
||||||
const file = fs.readFileSync(settingsJsonPath, 'utf8');
|
const file = fs.readFileSync(settingsJsonPath, 'utf8');
|
||||||
JSON.parse(file);
|
JSON.parse(file);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
if (fs.existsSync(settingsJsonPath)) {
|
if (fs.existsSync(settingsJsonPath)) {
|
||||||
fs.unlinkSync(settingsJsonPath);
|
fs.unlinkSync(settingsJsonPath);
|
||||||
dialog.showErrorBox(
|
dialog.showErrorBox(
|
||||||
@@ -83,9 +96,10 @@ function reloadDB(): void {
|
|||||||
'We encountered an error while saving the settings.'
|
'We encountered an error while saving the settings.'
|
||||||
);
|
);
|
||||||
logger.error('Error while JSON parsing settings.json: ');
|
logger.error('Error while JSON parsing settings.json: ');
|
||||||
logger.error(err);
|
logger.error(error);
|
||||||
logger.reportSentry(err);
|
logger.reportSentry(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
db = new JsonDB(settingsJsonPath, true, true);
|
db = new JsonDB(settingsJsonPath, true, true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ const logDir = `${zulipDir}/Logs/`;
|
|||||||
const certificatesDir = `${zulipDir}/certificates/`;
|
const certificatesDir = `${zulipDir}/certificates/`;
|
||||||
const configDir = `${zulipDir}/config/`;
|
const configDir = `${zulipDir}/config/`;
|
||||||
export const initSetUp = (): void => {
|
export const initSetUp = (): void => {
|
||||||
// if it is the first time the app is running
|
// If it is the first time the app is running
|
||||||
// create zulip dir in userData folder to
|
// create zulip dir in userData folder to
|
||||||
// avoid errors
|
// avoid errors
|
||||||
if (!setupCompleted) {
|
if (!setupCompleted) {
|
||||||
@@ -63,7 +63,7 @@ export const initSetUp = (): void => {
|
|||||||
fs.unlinkSync(data.path);
|
fs.unlinkSync(data.path);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
// window-state.json is only deleted not moved, as the electron-window-state
|
// `window-state.json` is only deleted not moved, as the electron-window-state
|
||||||
// package will recreate the file in the config folder.
|
// package will recreate the file in the config folder.
|
||||||
if (fs.existsSync(windowStateJson)) {
|
if (fs.existsSync(windowStateJson)) {
|
||||||
fs.unlinkSync(windowStateJson);
|
fs.unlinkSync(windowStateJson);
|
||||||
|
|||||||
@@ -1,28 +1,28 @@
|
|||||||
import * as ConfigUtil from './config-util';
|
import * as ConfigUtil from './config-util';
|
||||||
|
|
||||||
// TODO: TypeScript - add to Setting interface
|
type SettingName = 'showNotification' | 'silent' | 'flashTaskbarOnMessage';
|
||||||
// the list of settings since we have fixed amount of them
|
|
||||||
// We want to do this by creating a new module that exports
|
export interface DNDSettings {
|
||||||
// this interface
|
showNotification?: boolean;
|
||||||
interface Setting {
|
silent?: boolean;
|
||||||
[key: string]: boolean;
|
flashTaskbarOnMessage?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface Toggle {
|
interface Toggle {
|
||||||
dnd: boolean;
|
dnd: boolean;
|
||||||
newSettings: Setting;
|
newSettings: DNDSettings;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function toggle(): Toggle {
|
export function toggle(): Toggle {
|
||||||
const dnd = !ConfigUtil.getConfigItem('dnd', false);
|
const dnd = !ConfigUtil.getConfigItem('dnd', false);
|
||||||
const dndSettingList = ['showNotification', 'silent'];
|
const dndSettingList: SettingName[] = ['showNotification', 'silent'];
|
||||||
if (process.platform === 'win32') {
|
if (process.platform === 'win32') {
|
||||||
dndSettingList.push('flashTaskbarOnMessage');
|
dndSettingList.push('flashTaskbarOnMessage');
|
||||||
}
|
}
|
||||||
|
|
||||||
let newSettings: Setting;
|
let newSettings: DNDSettings;
|
||||||
if (dnd) {
|
if (dnd) {
|
||||||
const oldSettings: Setting = {};
|
const oldSettings: DNDSettings = {};
|
||||||
newSettings = {};
|
newSettings = {};
|
||||||
|
|
||||||
// Iterate through the dndSettingList.
|
// Iterate through the dndSettingList.
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
import { JsonDB } from 'node-json-db';
|
import {JsonDB} from 'node-json-db';
|
||||||
|
|
||||||
import escape from 'escape-html';
|
import escape from 'escape-html';
|
||||||
import request from 'request';
|
import request from 'request';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
import Logger from './logger-util';
|
import Logger from './logger-util';
|
||||||
import { remote } from 'electron';
|
import {remote} from 'electron';
|
||||||
|
|
||||||
import * as RequestUtil from './request-util';
|
import * as RequestUtil from './request-util';
|
||||||
import * as EnterpriseUtil from './enterprise-util';
|
import * as EnterpriseUtil from './enterprise-util';
|
||||||
import * as Messages from '../../../resources/messages';
|
import * as Messages from '../../../resources/messages';
|
||||||
|
|
||||||
const { app, dialog } = remote;
|
const {app, dialog} = remote;
|
||||||
|
|
||||||
export interface ServerConf {
|
export interface ServerConf {
|
||||||
url: string;
|
url: string;
|
||||||
@@ -27,25 +27,27 @@ const logger = new Logger({
|
|||||||
|
|
||||||
const defaultIconUrl = '../renderer/img/icon.png';
|
const defaultIconUrl = '../renderer/img/icon.png';
|
||||||
|
|
||||||
export let db: JsonDB;
|
let db: JsonDB;
|
||||||
|
|
||||||
reloadDB();
|
reloadDB();
|
||||||
// Migrate from old schema
|
// Migrate from old schema
|
||||||
if (db.getData('/').domain) {
|
if (db.getData('/').domain) {
|
||||||
addDomain({
|
(async () => {
|
||||||
alias: 'Zulip',
|
await addDomain({
|
||||||
url: db.getData('/domain')
|
alias: 'Zulip',
|
||||||
});
|
url: db.getData('/domain')
|
||||||
db.delete('/domain');
|
});
|
||||||
|
db.delete('/domain');
|
||||||
|
})();
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getDomains(): ServerConf[] {
|
export function getDomains(): ServerConf[] {
|
||||||
reloadDB();
|
reloadDB();
|
||||||
if (db.getData('/').domains === undefined) {
|
if (db.getData('/').domains === undefined) {
|
||||||
return [];
|
return [];
|
||||||
} else {
|
|
||||||
return db.getData('/domains');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return db.getData('/domains');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getDomain(index: number): ServerConf {
|
export function getDomain(index: number): ServerConf {
|
||||||
@@ -60,16 +62,17 @@ export function shouldIgnoreCerts(url: string): boolean {
|
|||||||
return domain.ignoreCerts;
|
return domain.ignoreCerts;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
function updateDomain(index: number, server: ServerConf): void {
|
export function updateDomain(index: number, server: ServerConf): void {
|
||||||
reloadDB();
|
reloadDB();
|
||||||
db.push(`/domains[${index}]`, server, true);
|
db.push(`/domains[${index}]`, server, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function addDomain(server: ServerConf): Promise<void> {
|
export async function addDomain(server: ServerConf): Promise<void> {
|
||||||
const { ignoreCerts } = server;
|
const {ignoreCerts} = server;
|
||||||
if (server.icon) {
|
if (server.icon) {
|
||||||
const localIconUrl = await saveServerIcon(server, ignoreCerts);
|
const localIconUrl = await saveServerIcon(server, ignoreCerts);
|
||||||
server.icon = localIconUrl;
|
server.icon = localIconUrl;
|
||||||
@@ -91,6 +94,7 @@ export function removeDomain(index: number): boolean {
|
|||||||
if (EnterpriseUtil.isPresetOrg(getDomain(index).url)) {
|
if (EnterpriseUtil.isPresetOrg(getDomain(index).url)) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
db.delete(`/domains[${index}]`);
|
db.delete(`/domains[${index}]`);
|
||||||
reloadDB();
|
reloadDB();
|
||||||
return true;
|
return true;
|
||||||
@@ -102,38 +106,39 @@ export function duplicateDomain(domain: string): boolean {
|
|||||||
return getDomains().some(server => server.url === domain);
|
return getDomains().some(server => server.url === domain);
|
||||||
}
|
}
|
||||||
|
|
||||||
async function checkCertError(domain: string, serverConf: ServerConf, error: string, silent: boolean): Promise<ServerConf> {
|
async function checkCertError(domain: string, serverConf: ServerConf, error: any, silent: boolean): Promise<ServerConf> {
|
||||||
if (silent) {
|
if (silent) {
|
||||||
// since getting server settings has already failed
|
// Since getting server settings has already failed
|
||||||
return serverConf;
|
return serverConf;
|
||||||
} else {
|
}
|
||||||
// Report error to sentry to get idea of possible certificate errors
|
|
||||||
// users get when adding the servers
|
|
||||||
logger.reportSentry(new Error(error).toString());
|
|
||||||
const certErrorMessage = Messages.certErrorMessage(domain, error);
|
|
||||||
const certErrorDetail = Messages.certErrorDetail();
|
|
||||||
|
|
||||||
const { response } = await dialog.showMessageBox({
|
// Report error to sentry to get idea of possible certificate errors
|
||||||
type: 'warning',
|
// users get when adding the servers
|
||||||
buttons: ['Yes', 'No'],
|
logger.reportSentry(error);
|
||||||
defaultId: 1,
|
const certErrorMessage = Messages.certErrorMessage(domain, error);
|
||||||
message: certErrorMessage,
|
const certErrorDetail = Messages.certErrorDetail();
|
||||||
detail: certErrorDetail
|
|
||||||
});
|
const {response} = await dialog.showMessageBox({
|
||||||
if (response === 0) {
|
type: 'warning',
|
||||||
// set ignoreCerts parameter to true in case user responds with yes
|
buttons: ['Yes', 'No'],
|
||||||
serverConf.ignoreCerts = true;
|
defaultId: 1,
|
||||||
try {
|
message: certErrorMessage,
|
||||||
return await getServerSettings(domain, serverConf.ignoreCerts);
|
detail: certErrorDetail
|
||||||
} catch (_) {
|
});
|
||||||
if (error === Messages.noOrgsError(domain)) {
|
if (response === 0) {
|
||||||
throw new Error(error);
|
// Set ignoreCerts parameter to true in case user responds with yes
|
||||||
}
|
serverConf.ignoreCerts = true;
|
||||||
return serverConf;
|
try {
|
||||||
|
return await getServerSettings(domain, serverConf.ignoreCerts);
|
||||||
|
} catch (_) {
|
||||||
|
if (error === Messages.noOrgsError(domain)) {
|
||||||
|
throw new Error(error);
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
throw new Error('Untrusted certificate.');
|
return serverConf;
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
throw new Error('Untrusted certificate.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -156,18 +161,18 @@ export async function checkDomain(domain: string, ignoreCerts = false, silent =
|
|||||||
|
|
||||||
try {
|
try {
|
||||||
return await getServerSettings(domain, serverConf.ignoreCerts);
|
return await getServerSettings(domain, serverConf.ignoreCerts);
|
||||||
} catch (err) {
|
} catch (error_) {
|
||||||
// Make sure that error is an error or string not undefined
|
// Make sure that error is an error or string not undefined
|
||||||
// so validation does not throw error.
|
// so validation does not throw error.
|
||||||
const error = err || '';
|
const error = error_ || '';
|
||||||
|
|
||||||
const certsError = error.toString().includes('certificate');
|
const certsError = error.toString().includes('certificate');
|
||||||
if (certsError) {
|
if (certsError) {
|
||||||
const result = await checkCertError(domain, serverConf, error, silent);
|
const result = await checkCertError(domain, serverConf, error, silent);
|
||||||
return result;
|
return result;
|
||||||
} else {
|
|
||||||
throw new Error(Messages.invalidZulipServerError(domain));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
throw new Error(Messages.invalidZulipServerError(domain));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,16 +183,20 @@ async function getServerSettings(domain: string, ignoreCerts = false): Promise<S
|
|||||||
};
|
};
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
request(serverSettingsOptions, (error: string, response: any) => {
|
request(serverSettingsOptions, (error: Error, response: request.Response) => {
|
||||||
if (!error && response.statusCode === 200) {
|
if (!error && response.statusCode === 200) {
|
||||||
const data = JSON.parse(response.body);
|
const {realm_name, realm_uri, realm_icon} = JSON.parse(response.body);
|
||||||
if (Object.prototype.hasOwnProperty.call(data, 'realm_icon') && data.realm_icon) {
|
if (
|
||||||
|
typeof realm_name === 'string' &&
|
||||||
|
typeof realm_uri === 'string' &&
|
||||||
|
typeof realm_icon === 'string'
|
||||||
|
) {
|
||||||
resolve({
|
resolve({
|
||||||
// Some Zulip Servers use absolute URL for server icon whereas others use relative URL
|
// Some Zulip Servers use absolute URL for server icon whereas others use relative URL
|
||||||
// Following check handles both the cases
|
// Following check handles both the cases
|
||||||
icon: data.realm_icon.startsWith('/') ? data.realm_uri + data.realm_icon : data.realm_icon,
|
icon: realm_icon.startsWith('/') ? realm_uri + realm_icon : realm_icon,
|
||||||
url: data.realm_uri,
|
url: realm_uri,
|
||||||
alias: escape(data.realm_name),
|
alias: escape(realm_name),
|
||||||
ignoreCerts
|
ignoreCerts
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
@@ -214,8 +223,8 @@ export async function saveServerIcon(server: ServerConf, ignoreCerts = false): P
|
|||||||
const filePath = generateFilePath(url);
|
const filePath = generateFilePath(url);
|
||||||
const file = fs.createWriteStream(filePath);
|
const file = fs.createWriteStream(filePath);
|
||||||
try {
|
try {
|
||||||
request(serverIconOptions).on('response', (response: any) => {
|
request(serverIconOptions).on('response', (response: request.Response) => {
|
||||||
response.on('error', (err: string) => {
|
response.on('error', (err: Error) => {
|
||||||
logger.log('Could not get server icon.');
|
logger.log('Could not get server icon.');
|
||||||
logger.log(err);
|
logger.log(err);
|
||||||
logger.reportSentry(err);
|
logger.reportSentry(err);
|
||||||
@@ -224,16 +233,16 @@ export async function saveServerIcon(server: ServerConf, ignoreCerts = false): P
|
|||||||
response.pipe(file).on('finish', () => {
|
response.pipe(file).on('finish', () => {
|
||||||
resolve(filePath);
|
resolve(filePath);
|
||||||
});
|
});
|
||||||
}).on('error', (err: string) => {
|
}).on('error', (err: Error) => {
|
||||||
logger.log('Could not get server icon.');
|
logger.log('Could not get server icon.');
|
||||||
logger.log(err);
|
logger.log(err);
|
||||||
logger.reportSentry(err);
|
logger.reportSentry(err);
|
||||||
resolve(defaultIconUrl);
|
resolve(defaultIconUrl);
|
||||||
});
|
});
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
logger.log('Could not get server icon.');
|
logger.log('Could not get server icon.');
|
||||||
logger.log(err);
|
logger.log(error);
|
||||||
logger.reportSentry(err);
|
logger.reportSentry(error);
|
||||||
resolve(defaultIconUrl);
|
resolve(defaultIconUrl);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -242,7 +251,7 @@ export async function saveServerIcon(server: ServerConf, ignoreCerts = false): P
|
|||||||
export async function updateSavedServer(url: string, index: number): Promise<void> {
|
export async function updateSavedServer(url: string, index: number): Promise<void> {
|
||||||
// Does not promise successful update
|
// Does not promise successful update
|
||||||
const oldIcon = getDomain(index).icon;
|
const oldIcon = getDomain(index).icon;
|
||||||
const { ignoreCerts } = getDomain(index);
|
const {ignoreCerts} = getDomain(index);
|
||||||
try {
|
try {
|
||||||
const newServerConf = await checkDomain(url, ignoreCerts, true);
|
const newServerConf = await checkDomain(url, ignoreCerts, true);
|
||||||
const localIconUrl = await saveServerIcon(newServerConf, ignoreCerts);
|
const localIconUrl = await saveServerIcon(newServerConf, ignoreCerts);
|
||||||
@@ -251,19 +260,19 @@ export async function updateSavedServer(url: string, index: number): Promise<voi
|
|||||||
updateDomain(index, newServerConf);
|
updateDomain(index, newServerConf);
|
||||||
reloadDB();
|
reloadDB();
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
logger.log('Could not update server icon.');
|
logger.log('Could not update server icon.');
|
||||||
logger.log(err);
|
logger.log(error);
|
||||||
logger.reportSentry(err);
|
logger.reportSentry(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function reloadDB(): void {
|
function reloadDB(): void {
|
||||||
const domainJsonPath = path.join(app.getPath('userData'), 'config/domain.json');
|
const domainJsonPath = path.join(app.getPath('userData'), 'config/domain.json');
|
||||||
try {
|
try {
|
||||||
const file = fs.readFileSync(domainJsonPath, 'utf8');
|
const file = fs.readFileSync(domainJsonPath, 'utf8');
|
||||||
JSON.parse(file);
|
JSON.parse(file);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
if (fs.existsSync(domainJsonPath)) {
|
if (fs.existsSync(domainJsonPath)) {
|
||||||
fs.unlinkSync(domainJsonPath);
|
fs.unlinkSync(domainJsonPath);
|
||||||
dialog.showErrorBox(
|
dialog.showErrorBox(
|
||||||
@@ -272,10 +281,11 @@ export function reloadDB(): void {
|
|||||||
'you may have to re-add your previous organizations back.'
|
'you may have to re-add your previous organizations back.'
|
||||||
);
|
);
|
||||||
logger.error('Error while JSON parsing domain.json: ');
|
logger.error('Error while JSON parsing domain.json: ');
|
||||||
logger.error(err);
|
logger.error(error);
|
||||||
logger.reportSentry(err);
|
logger.reportSentry(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
db = new JsonDB(domainJsonPath, true, true);
|
db = new JsonDB(domainJsonPath, true, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -284,7 +294,7 @@ function generateFilePath(url: string): string {
|
|||||||
const extension = path.extname(url).split('?')[0];
|
const extension = path.extname(url).split('?')[0];
|
||||||
|
|
||||||
let hash = 5381;
|
let hash = 5381;
|
||||||
let { length } = url;
|
let {length} = url;
|
||||||
|
|
||||||
while (length) {
|
while (length) {
|
||||||
hash = (hash * 33) ^ url.charCodeAt(--length);
|
hash = (hash * 33) ^ url.charCodeAt(--length);
|
||||||
@@ -302,8 +312,10 @@ export function formatUrl(domain: string): string {
|
|||||||
if (domain.startsWith('http://') || domain.startsWith('https://')) {
|
if (domain.startsWith('http://') || domain.startsWith('https://')) {
|
||||||
return domain;
|
return domain;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (domain.startsWith('localhost:')) {
|
if (domain.startsWith('localhost:')) {
|
||||||
return `http://${domain}`;
|
return `http://${domain}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return `https://${domain}`;
|
return `https://${domain}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,9 +8,9 @@ const logger = new Logger({
|
|||||||
timestamp: true
|
timestamp: true
|
||||||
});
|
});
|
||||||
|
|
||||||
// todo: replace enterpriseSettings type with an interface once settings are final
|
// TODO: replace enterpriseSettings type with an interface once settings are final
|
||||||
export let enterpriseSettings: any;
|
let enterpriseSettings: {[key: string]: unknown};
|
||||||
export let configFile: boolean;
|
let configFile: boolean;
|
||||||
|
|
||||||
reloadDB();
|
reloadDB();
|
||||||
|
|
||||||
@@ -26,23 +26,29 @@ function reloadDB(): void {
|
|||||||
try {
|
try {
|
||||||
const file = fs.readFileSync(enterpriseFile, 'utf8');
|
const file = fs.readFileSync(enterpriseFile, 'utf8');
|
||||||
enterpriseSettings = JSON.parse(file);
|
enterpriseSettings = JSON.parse(file);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
logger.log('Error while JSON parsing global_config.json: ');
|
logger.log('Error while JSON parsing global_config.json: ');
|
||||||
logger.log(err);
|
logger.log(error);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
configFile = false;
|
configFile = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getConfigItem(key: string, defaultValue?: any): any {
|
export function hasConfigFile(): boolean {
|
||||||
|
return configFile;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function getConfigItem(key: string, defaultValue?: unknown): any {
|
||||||
reloadDB();
|
reloadDB();
|
||||||
if (!configFile) {
|
if (!configFile) {
|
||||||
return defaultValue;
|
return defaultValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (defaultValue === undefined) {
|
if (defaultValue === undefined) {
|
||||||
defaultValue = null;
|
defaultValue = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
return configItemExists(key) ? enterpriseSettings[key] : defaultValue;
|
return configItemExists(key) ? enterpriseSettings[key] : defaultValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,6 +57,7 @@ export function configItemExists(key: string): boolean {
|
|||||||
if (!configFile) {
|
if (!configFile) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
return (enterpriseSettings[key] !== undefined);
|
return (enterpriseSettings[key] !== undefined);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -58,11 +65,17 @@ export function isPresetOrg(url: string): boolean {
|
|||||||
if (!configFile || !configItemExists('presetOrganizations')) {
|
if (!configFile || !configItemExists('presetOrganizations')) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
const presetOrgs = enterpriseSettings.presetOrganizations;
|
const presetOrgs = enterpriseSettings.presetOrganizations;
|
||||||
|
if (!Array.isArray(presetOrgs)) {
|
||||||
|
throw new TypeError('Expected array for presetOrgs');
|
||||||
|
}
|
||||||
|
|
||||||
for (const org of presetOrgs) {
|
for (const org of presetOrgs) {
|
||||||
if (url.includes(org)) {
|
if (url.includes(org)) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { shell } from 'electron';
|
import {shell} from 'electron';
|
||||||
import escape from 'escape-html';
|
import escape from 'escape-html';
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
@@ -8,9 +8,9 @@ export function isUploadsUrl(server: string, url: URL): boolean {
|
|||||||
return url.origin === server && url.pathname.startsWith('/user_uploads/');
|
return url.origin === server && url.pathname.startsWith('/user_uploads/');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function openBrowser(url: URL): void {
|
export async function openBrowser(url: URL): Promise<void> {
|
||||||
if (['http:', 'https:', 'mailto:'].includes(url.protocol)) {
|
if (['http:', 'https:', 'mailto:'].includes(url.protocol)) {
|
||||||
shell.openExternal(url.href);
|
await shell.openExternal(url.href);
|
||||||
} else {
|
} else {
|
||||||
// For security, indirect links to non-whitelisted protocols
|
// For security, indirect links to non-whitelisted protocols
|
||||||
// through a real web browser via a local HTML file.
|
// through a real web browser via a local HTML file.
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { JsonDB } from 'node-json-db';
|
import {JsonDB} from 'node-json-db';
|
||||||
|
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
@@ -14,24 +14,24 @@ const logger = new Logger({
|
|||||||
});
|
});
|
||||||
|
|
||||||
/* To make the util runnable in both main and renderer process */
|
/* To make the util runnable in both main and renderer process */
|
||||||
const { dialog, app } = remote;
|
const {dialog, app} = remote;
|
||||||
|
|
||||||
let db: JsonDB;
|
let db: JsonDB;
|
||||||
|
|
||||||
reloadDB();
|
reloadDB();
|
||||||
|
|
||||||
export function getUpdateItem(key: string, defaultValue: any = null): any {
|
export function getUpdateItem(key: string, defaultValue: unknown = null): any {
|
||||||
reloadDB();
|
reloadDB();
|
||||||
const value = db.getData('/')[key];
|
const value = db.getData('/')[key];
|
||||||
if (value === undefined) {
|
if (value === undefined) {
|
||||||
setUpdateItem(key, defaultValue);
|
setUpdateItem(key, defaultValue);
|
||||||
return defaultValue;
|
return defaultValue;
|
||||||
} else {
|
|
||||||
return value;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return value;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function setUpdateItem(key: string, value: any): void {
|
export function setUpdateItem(key: string, value: unknown): void {
|
||||||
db.push(`/${key}`, value, true);
|
db.push(`/${key}`, value, true);
|
||||||
reloadDB();
|
reloadDB();
|
||||||
}
|
}
|
||||||
@@ -46,7 +46,7 @@ function reloadDB(): void {
|
|||||||
try {
|
try {
|
||||||
const file = fs.readFileSync(linuxUpdateJsonPath, 'utf8');
|
const file = fs.readFileSync(linuxUpdateJsonPath, 'utf8');
|
||||||
JSON.parse(file);
|
JSON.parse(file);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
if (fs.existsSync(linuxUpdateJsonPath)) {
|
if (fs.existsSync(linuxUpdateJsonPath)) {
|
||||||
fs.unlinkSync(linuxUpdateJsonPath);
|
fs.unlinkSync(linuxUpdateJsonPath);
|
||||||
dialog.showErrorBox(
|
dialog.showErrorBox(
|
||||||
@@ -54,8 +54,9 @@ function reloadDB(): void {
|
|||||||
'We encountered an error while saving the update notifications.'
|
'We encountered an error while saving the update notifications.'
|
||||||
);
|
);
|
||||||
logger.error('Error while JSON parsing updates.json: ');
|
logger.error('Error while JSON parsing updates.json: ');
|
||||||
logger.error(err);
|
logger.error(error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
db = new JsonDB(linuxUpdateJsonPath, true, true);
|
db = new JsonDB(linuxUpdateJsonPath, true, true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,11 @@
|
|||||||
import { Console as NodeConsole } from 'console'; // eslint-disable-line node/prefer-global/console
|
import {Console} from 'console'; // eslint-disable-line node/prefer-global/console
|
||||||
import { initSetUp } from './default-util';
|
import {initSetUp} from './default-util';
|
||||||
import { sentryInit, captureException } from './sentry-util';
|
import {sentryInit, captureException} from './sentry-util';
|
||||||
|
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
import isDev from 'electron-is-dev';
|
import isDev from 'electron-is-dev';
|
||||||
import electron from 'electron';
|
import electron from 'electron';
|
||||||
// this interface adds [key: string]: any so
|
|
||||||
// we can do console[type] later on in the code
|
|
||||||
interface PatchedConsole extends Console {
|
|
||||||
[key: string]: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface LoggerOptions {
|
interface LoggerOptions {
|
||||||
timestamp?: true | (() => string);
|
timestamp?: true | (() => string);
|
||||||
@@ -29,9 +24,9 @@ if (process.type === 'renderer') {
|
|||||||
// Report Errors to Sentry only if it is enabled in settings
|
// Report Errors to Sentry only if it is enabled in settings
|
||||||
// Gets the value of reportErrors from config-util for renderer process
|
// Gets the value of reportErrors from config-util for renderer process
|
||||||
// For main process, sentryInit() is handled in index.js
|
// For main process, sentryInit() is handled in index.js
|
||||||
const { ipcRenderer } = electron;
|
const {ipcRenderer} = electron;
|
||||||
ipcRenderer.send('error-reporting');
|
ipcRenderer.send('error-reporting');
|
||||||
ipcRenderer.on('error-reporting-val', (_event: any, errorReporting: boolean) => {
|
ipcRenderer.on('error-reporting-val', (_event: Event, errorReporting: boolean) => {
|
||||||
reportErrors = errorReporting;
|
reportErrors = errorReporting;
|
||||||
if (reportErrors) {
|
if (reportErrors) {
|
||||||
sentryInit();
|
sentryInit();
|
||||||
@@ -41,15 +36,23 @@ if (process.type === 'renderer') {
|
|||||||
app = electron.app;
|
app = electron.app;
|
||||||
}
|
}
|
||||||
|
|
||||||
const browserConsole: PatchedConsole = console;
|
|
||||||
const logDir = `${app.getPath('userData')}/Logs`;
|
const logDir = `${app.getPath('userData')}/Logs`;
|
||||||
|
|
||||||
|
type Level = 'log' | 'debug' | 'info' | 'warn' | 'error';
|
||||||
|
const levels: Level[] = ['log', 'debug', 'info', 'warn', 'error'];
|
||||||
|
type LogMethod = (...args: unknown[]) => void;
|
||||||
|
|
||||||
export default class Logger {
|
export default class Logger {
|
||||||
nodeConsole: PatchedConsole;
|
log: LogMethod;
|
||||||
|
debug: LogMethod;
|
||||||
|
info: LogMethod;
|
||||||
|
warn: LogMethod;
|
||||||
|
error: LogMethod;
|
||||||
|
|
||||||
|
nodeConsole: Console;
|
||||||
timestamp?: () => string;
|
timestamp?: () => string;
|
||||||
level: boolean;
|
level: boolean;
|
||||||
logInDevMode: boolean;
|
logInDevMode: boolean;
|
||||||
[key: string]: any;
|
|
||||||
|
|
||||||
constructor(options: LoggerOptions = {}) {
|
constructor(options: LoggerOptions = {}) {
|
||||||
let {
|
let {
|
||||||
@@ -71,8 +74,8 @@ export default class Logger {
|
|||||||
process.nextTick(() => this.trimLog(file));
|
process.nextTick(() => this.trimLog(file));
|
||||||
}
|
}
|
||||||
|
|
||||||
const fileStream = fs.createWriteStream(file, { flags: 'a' });
|
const fileStream = fs.createWriteStream(file, {flags: 'a'});
|
||||||
const nodeConsole = new NodeConsole(fileStream);
|
const nodeConsole = new Console(fileStream);
|
||||||
|
|
||||||
this.nodeConsole = nodeConsole;
|
this.nodeConsole = nodeConsole;
|
||||||
this.timestamp = timestamp;
|
this.timestamp = timestamp;
|
||||||
@@ -81,11 +84,10 @@ export default class Logger {
|
|||||||
this.setUpConsole();
|
this.setUpConsole();
|
||||||
}
|
}
|
||||||
|
|
||||||
_log(type: string, ...args: any[]): void {
|
_log(type: Level, ...args: unknown[]): void {
|
||||||
const {
|
const {
|
||||||
nodeConsole, timestamp, level, logInDevMode
|
nodeConsole, timestamp, level, logInDevMode
|
||||||
} = this;
|
} = this;
|
||||||
let nodeConsoleLog;
|
|
||||||
|
|
||||||
/* eslint-disable no-fallthrough */
|
/* eslint-disable no-fallthrough */
|
||||||
switch (true) {
|
switch (true) {
|
||||||
@@ -96,27 +98,23 @@ export default class Logger {
|
|||||||
args.unshift(type.toUpperCase() + ' |');
|
args.unshift(type.toUpperCase() + ' |');
|
||||||
|
|
||||||
case isDev || logInDevMode:
|
case isDev || logInDevMode:
|
||||||
nodeConsoleLog = nodeConsole[type] || nodeConsole.log;
|
nodeConsole[type](...args);
|
||||||
nodeConsoleLog.apply(null, args); // eslint-disable-line prefer-spread
|
|
||||||
|
|
||||||
default: break;
|
default: break;
|
||||||
}
|
}
|
||||||
/* eslint-enable no-fallthrough */
|
/* eslint-enable no-fallthrough */
|
||||||
|
|
||||||
browserConsole[type].apply(null, args);
|
console[type](...args);
|
||||||
}
|
}
|
||||||
|
|
||||||
setUpConsole(): void {
|
setUpConsole(): void {
|
||||||
for (const type of Object.keys(browserConsole)) {
|
for (const type of levels) {
|
||||||
this.setupConsoleMethod(type);
|
this.setupConsoleMethod(type);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
setupConsoleMethod(type: string): void {
|
setupConsoleMethod(type: Level): void {
|
||||||
this[type] = (...args: any[]) => {
|
this[type] = (...args: unknown[]) => this._log(type, ...args);
|
||||||
const log = this._log.bind(this, type, ...args);
|
|
||||||
log();
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
getTimestamp(): string {
|
getTimestamp(): string {
|
||||||
@@ -127,7 +125,7 @@ export default class Logger {
|
|||||||
return timestamp;
|
return timestamp;
|
||||||
}
|
}
|
||||||
|
|
||||||
reportSentry(err: string): void {
|
reportSentry(err: unknown): void {
|
||||||
if (reportErrors) {
|
if (reportErrors) {
|
||||||
captureException(err);
|
captureException(err);
|
||||||
}
|
}
|
||||||
@@ -138,6 +136,7 @@ export default class Logger {
|
|||||||
if (err) {
|
if (err) {
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
|
|
||||||
const MAX_LOG_FILE_LINES = 500;
|
const MAX_LOG_FILE_LINES = 500;
|
||||||
const logs = data.split(os.EOL);
|
const logs = data.split(os.EOL);
|
||||||
const logLength = logs.length - 1;
|
const logLength = logs.length - 1;
|
||||||
|
|||||||
@@ -10,7 +10,7 @@ export function getProxy(_uri: string): ProxyRule | void {
|
|||||||
let uri;
|
let uri;
|
||||||
try {
|
try {
|
||||||
uri = new URL(_uri);
|
uri = new URL(_uri);
|
||||||
} catch (err) {
|
} catch (_) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,12 +55,13 @@ export async function resolveSystemProxy(mainWindow: Electron.BrowserWindow): Pr
|
|||||||
const proxy = await ses.resolveProxy('http://' + resolveProxyUrl);
|
const proxy = await ses.resolveProxy('http://' + resolveProxyUrl);
|
||||||
let httpString = '';
|
let httpString = '';
|
||||||
if (proxy !== 'DIRECT') {
|
if (proxy !== 'DIRECT') {
|
||||||
// in case of proxy HTTPS url:port, windows gives first word as HTTPS while linux gives PROXY
|
// In case of proxy HTTPS url:port, windows gives first word as HTTPS while linux gives PROXY
|
||||||
// for all other HTTP or direct url:port both uses PROXY
|
// for all other HTTP or direct url:port both uses PROXY
|
||||||
if (proxy.includes('PROXY') || proxy.includes('HTTPS')) {
|
if (proxy.includes('PROXY') || proxy.includes('HTTPS')) {
|
||||||
httpString = 'http=' + proxy.split('PROXY')[1] + ';';
|
httpString = 'http=' + proxy.split('PROXY')[1] + ';';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return httpString;
|
return httpString;
|
||||||
})();
|
})();
|
||||||
// Check HTTPS Proxy
|
// Check HTTPS Proxy
|
||||||
@@ -68,12 +69,13 @@ export async function resolveSystemProxy(mainWindow: Electron.BrowserWindow): Pr
|
|||||||
const proxy = await ses.resolveProxy('https://' + resolveProxyUrl);
|
const proxy = await ses.resolveProxy('https://' + resolveProxyUrl);
|
||||||
let httpsString = '';
|
let httpsString = '';
|
||||||
if (proxy !== 'DIRECT' || proxy.includes('HTTPS')) {
|
if (proxy !== 'DIRECT' || proxy.includes('HTTPS')) {
|
||||||
// in case of proxy HTTPS url:port, windows gives first word as HTTPS while linux gives PROXY
|
// In case of proxy HTTPS url:port, windows gives first word as HTTPS while linux gives PROXY
|
||||||
// for all other HTTP or direct url:port both uses PROXY
|
// for all other HTTP or direct url:port both uses PROXY
|
||||||
if (proxy.includes('PROXY') || proxy.includes('HTTPS')) {
|
if (proxy.includes('PROXY') || proxy.includes('HTTPS')) {
|
||||||
httpsString += 'https=' + proxy.split('PROXY')[1] + ';';
|
httpsString += 'https=' + proxy.split('PROXY')[1] + ';';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return httpsString;
|
return httpsString;
|
||||||
})();
|
})();
|
||||||
|
|
||||||
@@ -86,6 +88,7 @@ export async function resolveSystemProxy(mainWindow: Electron.BrowserWindow): Pr
|
|||||||
ftpString += 'ftp=' + proxy.split('PROXY')[1] + ';';
|
ftpString += 'ftp=' + proxy.split('PROXY')[1] + ';';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ftpString;
|
return ftpString;
|
||||||
})();
|
})();
|
||||||
|
|
||||||
@@ -102,6 +105,7 @@ export async function resolveSystemProxy(mainWindow: Electron.BrowserWindow): Pr
|
|||||||
socksString += 'socks=' + proxy.split('PROXY')[1] + ';';
|
socksString += 'socks=' + proxy.split('PROXY')[1] + ';';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return socksString;
|
return socksString;
|
||||||
})();
|
})();
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ipcRenderer } from 'electron';
|
import {ipcRenderer} from 'electron';
|
||||||
|
|
||||||
import type WebView from '../components/webview';
|
import type WebView from '../components/webview';
|
||||||
import backoff from 'backoff';
|
import backoff from 'backoff';
|
||||||
@@ -39,19 +39,20 @@ export default class ReconnectUtil {
|
|||||||
if (ignoreCerts === null) {
|
if (ignoreCerts === null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
request(
|
request(
|
||||||
{
|
{
|
||||||
url: `${this.url}/static/favicon.ico`,
|
url: `${this.url}/static/favicon.ico`,
|
||||||
...RequestUtil.requestOptions(this.url, ignoreCerts)
|
...RequestUtil.requestOptions(this.url, ignoreCerts)
|
||||||
},
|
},
|
||||||
(error: Error, response: any) => {
|
(error: Error, response: request.Response) => {
|
||||||
const isValidResponse =
|
const isValidResponse =
|
||||||
!error && response.statusCode >= 200 && response.statusCode < 400;
|
!error && response.statusCode >= 200 && response.statusCode < 400;
|
||||||
resolve(isValidResponse);
|
resolve(isValidResponse);
|
||||||
}
|
}
|
||||||
);
|
);
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
logger.log(err);
|
logger.log(error);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -71,11 +72,13 @@ export default class ReconnectUtil {
|
|||||||
if (this.alreadyReloaded) {
|
if (this.alreadyReloaded) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (await this.isOnline()) {
|
if (await this.isOnline()) {
|
||||||
ipcRenderer.send('forward-message', 'reload-viewer');
|
ipcRenderer.send('forward-message', 'reload-viewer');
|
||||||
logger.log('You\'re back online.');
|
logger.log('You\'re back online.');
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
logger.log('There is no internet connection, try checking network cables, modem and router.');
|
logger.log('There is no internet connection, try checking network cables, modem and router.');
|
||||||
const errorMessageHolder = document.querySelector('#description');
|
const errorMessageHolder = document.querySelector('#description');
|
||||||
if (errorMessageHolder) {
|
if (errorMessageHolder) {
|
||||||
@@ -83,6 +86,7 @@ export default class ReconnectUtil {
|
|||||||
<div>Your internet connection doesn't seem to work properly!</div>
|
<div>Your internet connection doesn't seem to work properly!</div>
|
||||||
<div>Verify that it works and then click try again.</div>`;
|
<div>Verify that it works and then click try again.</div>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { remote } from 'electron';
|
import {remote} from 'electron';
|
||||||
|
|
||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
@@ -8,7 +8,7 @@ import * as ProxyUtil from './proxy-util';
|
|||||||
import * as CertificateUtil from './certificate-util';
|
import * as CertificateUtil from './certificate-util';
|
||||||
import * as SystemUtil from './system-util';
|
import * as SystemUtil from './system-util';
|
||||||
|
|
||||||
const { app } = remote;
|
const {app} = remote;
|
||||||
|
|
||||||
const logger = new Logger({
|
const logger = new Logger({
|
||||||
file: 'request-util.log',
|
file: 'request-util.log',
|
||||||
@@ -33,7 +33,7 @@ export function requestOptions(domain: string, ignoreCerts: boolean): RequestUti
|
|||||||
|
|
||||||
let certificateFile = null;
|
let certificateFile = null;
|
||||||
if (certificate?.includes('/')) {
|
if (certificate?.includes('/')) {
|
||||||
// certificate saved using old app version
|
// Certificate saved using old app version
|
||||||
certificateFile = certificate;
|
certificateFile = certificate;
|
||||||
} else if (certificate) {
|
} else if (certificate) {
|
||||||
certificateFile = path.join(`${app.getPath('userData')}/certificates`, certificate);
|
certificateFile = path.join(`${app.getPath('userData')}/certificates`, certificate);
|
||||||
@@ -44,10 +44,11 @@ export function requestOptions(domain: string, ignoreCerts: boolean): RequestUti
|
|||||||
// To handle case where certificate has been moved from the location in certificates.json
|
// To handle case where certificate has been moved from the location in certificates.json
|
||||||
try {
|
try {
|
||||||
certificateLocation = fs.readFileSync(certificateFile, 'utf8');
|
certificateLocation = fs.readFileSync(certificateFile, 'utf8');
|
||||||
} catch (err) {
|
} catch (error) {
|
||||||
logger.warn(`Error while trying to get certificate: ${err}`);
|
logger.warn('Error while trying to get certificate:', error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const proxyEnabled = ConfigUtil.getConfigItem('useManualProxy') || ConfigUtil.getConfigItem('useSystemProxy');
|
const proxyEnabled = ConfigUtil.getConfigItem('useManualProxy') || ConfigUtil.getConfigItem('useSystemProxy');
|
||||||
// If certificate for the domain exists add it as a ca key in the request's parameter else consider only domain as the parameter for request
|
// If certificate for the domain exists add it as a ca key in the request's parameter else consider only domain as the parameter for request
|
||||||
// Add proxy as a parameter if it is being used.
|
// Add proxy as a parameter if it is being used.
|
||||||
@@ -55,7 +56,7 @@ export function requestOptions(domain: string, ignoreCerts: boolean): RequestUti
|
|||||||
ca: certificateLocation ? certificateLocation : '',
|
ca: certificateLocation ? certificateLocation : '',
|
||||||
proxy: proxyEnabled ? ProxyUtil.getProxy(domain) : '',
|
proxy: proxyEnabled ? ProxyUtil.getProxy(domain) : '',
|
||||||
ecdhCurve: 'auto',
|
ecdhCurve: 'auto',
|
||||||
headers: { 'User-Agent': SystemUtil.getUserAgent() },
|
headers: {'User-Agent': SystemUtil.getUserAgent()},
|
||||||
rejectUnauthorized: !ignoreCerts
|
rejectUnauthorized: !ignoreCerts
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -64,7 +65,7 @@ function formatUrl(domain: string): string {
|
|||||||
const hasPrefix = domain.startsWith('http', 0);
|
const hasPrefix = domain.startsWith('http', 0);
|
||||||
if (hasPrefix) {
|
if (hasPrefix) {
|
||||||
return domain;
|
return domain;
|
||||||
} else {
|
|
||||||
return domain.includes('localhost:') ? `http://${domain}` : `https://${domain}`;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return domain.includes('localhost:') ? `http://${domain}` : `https://${domain}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { init } from '@sentry/electron';
|
import {init} from '@sentry/electron';
|
||||||
|
|
||||||
import isDev from 'electron-is-dev';
|
import isDev from 'electron-is-dev';
|
||||||
|
|
||||||
@@ -10,9 +10,9 @@ export const sentryInit = (): void => {
|
|||||||
// This error mainly comes from the console logs.
|
// This error mainly comes from the console logs.
|
||||||
// This is a temp solution until Sentry supports disabling the console logs
|
// This is a temp solution until Sentry supports disabling the console logs
|
||||||
ignoreErrors: ['does not appear to be a valid Zulip server']
|
ignoreErrors: ['does not appear to be a valid Zulip server']
|
||||||
// sendTimeout: 30 // wait 30 seconds before considering the sending capture to have failed, default is 1 second
|
/// sendTimeout: 30 // wait 30 seconds before considering the sending capture to have failed, default is 1 second
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export { captureException } from '@sentry/electron';
|
export {captureException} from '@sentry/electron';
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import { ipcRenderer } from 'electron';
|
import {ipcRenderer} from 'electron';
|
||||||
|
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
|
|
||||||
@@ -17,18 +17,23 @@ export function getOS(): string {
|
|||||||
const platform = os.platform();
|
const platform = os.platform();
|
||||||
if (platform === 'darwin') {
|
if (platform === 'darwin') {
|
||||||
return 'Mac';
|
return 'Mac';
|
||||||
} else if (platform === 'linux') {
|
|
||||||
return 'Linux';
|
|
||||||
} else if (platform === 'win32') {
|
|
||||||
if (parseFloat(os.release()) < 6.2) {
|
|
||||||
return 'Windows 7';
|
|
||||||
} else {
|
|
||||||
return 'Windows 10';
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return '';
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (platform === 'linux') {
|
||||||
|
return 'Linux';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (platform === 'win32') {
|
||||||
|
if (Number.parseFloat(os.release()) < 6.2) {
|
||||||
|
return 'Windows 7';
|
||||||
|
}
|
||||||
|
|
||||||
|
return 'Windows 10';
|
||||||
|
}
|
||||||
|
|
||||||
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getUserAgent(): string {
|
export function getUserAgent(): string {
|
||||||
return userAgent;
|
return userAgent;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,10 +6,10 @@ i18n.configure({
|
|||||||
directory: path.join(__dirname, '../../../translations/')
|
directory: path.join(__dirname, '../../../translations/')
|
||||||
});
|
});
|
||||||
|
|
||||||
/* fetches the current appLocale from settings.json */
|
/* Fetches the current appLocale from settings.json */
|
||||||
const appLocale = ConfigUtil.getConfigItem('appLanguage');
|
const appLocale = ConfigUtil.getConfigItem('appLanguage');
|
||||||
|
|
||||||
/* if no locale present in the json, en is set default */
|
/* If no locale present in the json, en is set default */
|
||||||
export function __(phrase: string): string {
|
export function __(phrase: string): string {
|
||||||
return i18n.__({ phrase, locale: appLocale ? appLocale : 'en' });
|
return i18n.__({phrase, locale: appLocale ? appLocale : 'en'});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ export function enterpriseOrgError(length: number, domains: string[]): DialogBox
|
|||||||
for (const domain of domains) {
|
for (const domain of domains) {
|
||||||
domainList += `• ${domain}\n`;
|
domainList += `• ${domain}\n`;
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
title: `Could not add the following ${length === 1 ? 'organization' : 'organizations'}`,
|
title: `Could not add the following ${length === 1 ? 'organization' : 'organizations'}`,
|
||||||
content: `${domainList}\nPlease contact your system administrator.`
|
content: `${domainList}\nPlease contact your system administrator.`
|
||||||
|
|||||||
@@ -14,8 +14,7 @@ install:
|
|||||||
- node --version
|
- node --version
|
||||||
- npm --version
|
- npm --version
|
||||||
- python --version
|
- python --version
|
||||||
- npm install
|
- npm ci
|
||||||
- npm install -g gulp
|
|
||||||
|
|
||||||
build: off
|
build: off
|
||||||
|
|
||||||
|
|||||||
28
changelog.md
28
changelog.md
@@ -2,6 +2,34 @@
|
|||||||
|
|
||||||
All notable changes to the Zulip desktop app are documented in this file.
|
All notable changes to the Zulip desktop app are documented in this file.
|
||||||
|
|
||||||
|
### v5.2.0 --2020-05-04
|
||||||
|
|
||||||
|
**Security fixes**:
|
||||||
|
* CVE-2020-12637: Do not ignore certificate errors in webviews unless the (unsupported, deprecated) `ignoreCerts` option is enabled.
|
||||||
|
|
||||||
|
**Fixes**:
|
||||||
|
* Avoid opening the file chooser dialog twice when downloading a file.
|
||||||
|
|
||||||
|
**New features**:
|
||||||
|
* Provide clipboard decryption helper for use in new social login flow.
|
||||||
|
|
||||||
|
**Dependencies**:
|
||||||
|
* Upgrade all dependencies, including Electron 8.2.5.
|
||||||
|
|
||||||
|
### v5.1.0 --2020-04-29
|
||||||
|
|
||||||
|
**Fixes**:
|
||||||
|
* macOS: If the app is in foreground, the app will no longer hide upon clicking on dock again.
|
||||||
|
* Synchronise debian scripts with electron-builder 22.4.1, thus fixing SUID sandbox binary issues.
|
||||||
|
* Dock icon on macOS used to be larger than the other applications, which is now updated to the appropriate size.
|
||||||
|
* Upon catching error in updating the server icon, the app will log the error and make a sentry report instead of triggering user-facing network error
|
||||||
|
|
||||||
|
**New features**:
|
||||||
|
* User can now set application language without changing the language on their operating system.
|
||||||
|
|
||||||
|
**Dependencies**:
|
||||||
|
* Upgrade all dependencies, including Electron 8.2.3.
|
||||||
|
|
||||||
### v5.0.0 --2020-03-30
|
### v5.0.0 --2020-03-30
|
||||||
|
|
||||||
**Security fixes**:
|
**Security fixes**:
|
||||||
|
|||||||
1253
package-lock.json
generated
1253
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
40
package.json
40
package.json
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "zulip",
|
"name": "zulip",
|
||||||
"productName": "Zulip",
|
"productName": "Zulip",
|
||||||
"version": "5.1.0",
|
"version": "5.2.0",
|
||||||
"main": "./app/main",
|
"main": "./app/main",
|
||||||
"description": "Zulip Desktop App",
|
"description": "Zulip Desktop App",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
@@ -21,7 +21,7 @@
|
|||||||
"node": ">=10.0.0"
|
"node": ">=10.0.0"
|
||||||
},
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"start": "node tools/run-dev",
|
"start": "tsc && electron .",
|
||||||
"clean-ts-files": "git clean app/*.js -e node_modules -xf",
|
"clean-ts-files": "git clean app/*.js -e node_modules -xf",
|
||||||
"watch-ts": "tsc -w",
|
"watch-ts": "tsc -w",
|
||||||
"reinstall": "node ./tools/reinstall-node-modules.js",
|
"reinstall": "node ./tools/reinstall-node-modules.js",
|
||||||
@@ -36,7 +36,6 @@
|
|||||||
"pack": "tsc && electron-builder --dir",
|
"pack": "tsc && electron-builder --dir",
|
||||||
"dist": "tsc && electron-builder",
|
"dist": "tsc && electron-builder",
|
||||||
"mas": "tsc && electron-builder --mac mas",
|
"mas": "tsc && electron-builder --mac mas",
|
||||||
"travis": "cd ./scripts && ./travis-build-test.sh",
|
|
||||||
"build-locales": "node tools/locale-helper"
|
"build-locales": "node tools/locale-helper"
|
||||||
},
|
},
|
||||||
"pre-commit": [
|
"pre-commit": [
|
||||||
@@ -149,13 +148,13 @@
|
|||||||
"auto-launch": "^5.0.5",
|
"auto-launch": "^5.0.5",
|
||||||
"backoff": "^2.5.0",
|
"backoff": "^2.5.0",
|
||||||
"electron-is-dev": "^1.2.0",
|
"electron-is-dev": "^1.2.0",
|
||||||
"electron-log": "^4.1.1",
|
"electron-log": "^4.1.2",
|
||||||
"electron-spellchecker": "^2.2.1",
|
"electron-spellchecker": "^2.2.1",
|
||||||
"electron-updater": "^4.2.5",
|
"electron-updater": "^4.3.1",
|
||||||
"electron-window-state": "^5.0.3",
|
"electron-window-state": "^5.0.3",
|
||||||
"escape-html": "^1.0.3",
|
"escape-html": "^1.0.3",
|
||||||
"fs-extra": "^9.0.0",
|
"fs-extra": "^9.0.0",
|
||||||
"i18n": "^0.9.0",
|
"i18n": "^0.9.1",
|
||||||
"node-json-db": "^1.1.0",
|
"node-json-db": "^1.1.0",
|
||||||
"request": "^2.88.2",
|
"request": "^2.88.2",
|
||||||
"rxjs": "^5.5.12",
|
"rxjs": "^5.5.12",
|
||||||
@@ -172,19 +171,19 @@
|
|||||||
"@types/escape-html": "0.0.20",
|
"@types/escape-html": "0.0.20",
|
||||||
"@types/fs-extra": "^8.1.0",
|
"@types/fs-extra": "^8.1.0",
|
||||||
"@types/i18n": "^0.8.6",
|
"@types/i18n": "^0.8.6",
|
||||||
"@types/node": "^13.13.2",
|
"@types/node": "^13.13.4",
|
||||||
"@types/request": "^2.48.4",
|
"@types/request": "^2.48.4",
|
||||||
"@types/requestidlecallback": "^0.3.1",
|
"@types/requestidlecallback": "^0.3.1",
|
||||||
"@typescript-eslint/eslint-plugin": "^2.29.0",
|
"@typescript-eslint/eslint-plugin": "^2.30.0",
|
||||||
"@typescript-eslint/parser": "^2.29.0",
|
"@typescript-eslint/parser": "^2.30.0",
|
||||||
"@vitalets/google-translate-api": "^3.0.0",
|
"@vitalets/google-translate-api": "^3.0.0",
|
||||||
"devtron": "^1.4.0",
|
"devtron": "^1.4.0",
|
||||||
"dotenv": "^8.2.0",
|
"dotenv": "^8.2.0",
|
||||||
"electron": "^8.2.3",
|
"electron": "^8.2.5",
|
||||||
"electron-builder": "^22.5.1",
|
"electron-builder": "^22.6.0",
|
||||||
"electron-connect": "^0.6.3",
|
"electron-connect": "^0.6.3",
|
||||||
"electron-notarize": "^0.3.0",
|
"electron-notarize": "^0.3.0",
|
||||||
"eslint-config-xo-typescript": "^0.26.0",
|
"eslint-config-xo-typescript": "^0.28.0",
|
||||||
"glob": "^7.1.6",
|
"glob": "^7.1.6",
|
||||||
"gulp": "^4.0.2",
|
"gulp": "^4.0.2",
|
||||||
"gulp-tape": "^1.0.0",
|
"gulp-tape": "^1.0.0",
|
||||||
@@ -198,17 +197,12 @@
|
|||||||
"tap-colorize": "^1.2.0",
|
"tap-colorize": "^1.2.0",
|
||||||
"tape": "^5.0.0",
|
"tape": "^5.0.0",
|
||||||
"typescript": "^3.8.3",
|
"typescript": "^3.8.3",
|
||||||
"xo": "^0.28.3"
|
"xo": "^0.30.0"
|
||||||
},
|
},
|
||||||
"xo": {
|
"xo": {
|
||||||
"rules": {
|
"rules": {
|
||||||
"@typescript-eslint/member-ordering": "off",
|
|
||||||
"@typescript-eslint/no-dynamic-delete": "off",
|
"@typescript-eslint/no-dynamic-delete": "off",
|
||||||
"@typescript-eslint/no-unused-vars": "off",
|
"@typescript-eslint/prefer-readonly-parameter-types": "off",
|
||||||
"@typescript-eslint/restrict-plus-operands": "off",
|
|
||||||
"@typescript-eslint/restrict-template-expressions": "off",
|
|
||||||
"capitalized-comments": "off",
|
|
||||||
"import/no-mutable-exports": "off",
|
|
||||||
"import/unambiguous": "error",
|
"import/unambiguous": "error",
|
||||||
"max-lines": [
|
"max-lines": [
|
||||||
"warn",
|
"warn",
|
||||||
@@ -218,14 +212,8 @@
|
|||||||
"skipComments": true
|
"skipComments": true
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
"no-alert": "off",
|
|
||||||
"no-else-return": "off",
|
|
||||||
"no-warning-comments": "off",
|
"no-warning-comments": "off",
|
||||||
"object-curly-spacing": "off",
|
"strict": "error"
|
||||||
"padding-line-between-statements": "off",
|
|
||||||
"strict": "error",
|
|
||||||
"unicorn/catch-error-name": "off",
|
|
||||||
"unicorn/string-content": "off"
|
|
||||||
},
|
},
|
||||||
"envs": [
|
"envs": [
|
||||||
"node",
|
"node",
|
||||||
|
|||||||
@@ -18,6 +18,7 @@ exports.default = async function (context) {
|
|||||||
appBundleId: 'org.zulip.zulip-electron',
|
appBundleId: 'org.zulip.zulip-electron',
|
||||||
appPath: `${appOutDir}/${appName}.app`,
|
appPath: `${appOutDir}/${appName}.app`,
|
||||||
appleId: process.env.APPLE_ID,
|
appleId: process.env.APPLE_ID,
|
||||||
appleIdPassword: process.env.APPLE_ID_PASS
|
appleIdPassword: process.env.APPLE_ID_PASS,
|
||||||
|
ascProvider: process.env.ASC_PROVIDER // Team short name
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,20 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
# exit script if fails
|
|
||||||
set -e;
|
|
||||||
|
|
||||||
if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then
|
|
||||||
export {no_proxy,NO_PROXY}="127.0.0.1,localhost"
|
|
||||||
export DISPLAY=:99.0
|
|
||||||
sh -e /etc/init.d/xvfb start
|
|
||||||
sleep 3
|
|
||||||
|
|
||||||
echo 'Travis Screen Resolution:'
|
|
||||||
xdpyinfo | grep dimensions
|
|
||||||
fi
|
|
||||||
|
|
||||||
npm run test
|
|
||||||
|
|
||||||
# if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then
|
|
||||||
# npm run test-e2e
|
|
||||||
# fi
|
|
||||||
@@ -1,5 +0,0 @@
|
|||||||
#!/usr/bin/env bash
|
|
||||||
|
|
||||||
if [[ "$TRAVIS_OS_NAME" == "linux" ]]; then
|
|
||||||
/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_99.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :99 -ac -screen 0 1280x1024x16
|
|
||||||
fi
|
|
||||||
@@ -1,89 +0,0 @@
|
|||||||
#!/usr/bin/env node
|
|
||||||
|
|
||||||
const path = require('path');
|
|
||||||
const glob = require('glob');
|
|
||||||
const chalk = require('chalk');
|
|
||||||
const { spawn } = require('child_process');
|
|
||||||
|
|
||||||
async function run(task, commandToRun, opts = {}) {
|
|
||||||
const args = commandToRun.split(' ');
|
|
||||||
let cmd = args[0];
|
|
||||||
args.splice(0, 1);
|
|
||||||
|
|
||||||
if (process.platform === 'win32' && /np(m|x)/.test(cmd)) {
|
|
||||||
cmd = cmd + '.cmd';
|
|
||||||
}
|
|
||||||
|
|
||||||
const defaults = {
|
|
||||||
cwd: path.resolve(__dirname, '..'),
|
|
||||||
env: process.env,
|
|
||||||
stdio: 'pipe'
|
|
||||||
};
|
|
||||||
|
|
||||||
opts = { ...defaults, ...opts };
|
|
||||||
task = ' ' + task + ' ';
|
|
||||||
|
|
||||||
const colors = [
|
|
||||||
{ bg: 'bold.bgGreen', color: 'bold.green' },
|
|
||||||
{ bg: 'bold.bgMagenta', color: 'bold.magenta' },
|
|
||||||
{ bg: 'bold.bgBlue', color: 'bold.blue' },
|
|
||||||
{ bg: 'bold.bgYellow', color: 'bold.yellow' },
|
|
||||||
{ bg: 'bold.bgCyan', color: 'bold.cyan' },
|
|
||||||
{ bg: 'bold.bgKeyword("rebeccapurple")', color: 'bold.keyword("rebeccapurple")' },
|
|
||||||
{ bg: 'bold.bgKeyword("darkslategray")', color: 'bold.keyword("darkslategray")' },
|
|
||||||
];
|
|
||||||
|
|
||||||
const randomColorIndex = Math.floor((Math.random() * (colors.length * 1000)) / 1000);
|
|
||||||
const randomColor = colors[randomColorIndex];
|
|
||||||
console.log(chalk`{${randomColor.bg} ${ task }} {${randomColor.color} ${commandToRun}}`);
|
|
||||||
|
|
||||||
const proc = spawn(cmd, args, opts);
|
|
||||||
proc.stderr.on('data', data => console.log(data.toString()));
|
|
||||||
proc.stdout.on('data', data => console.log(data.toString()));
|
|
||||||
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
function check(code) {
|
|
||||||
if (code !== 0) {
|
|
||||||
reject(chalk`{bgRed ERROR!} Running {red ${commandToRun}} failed with exit code: ${code}`);
|
|
||||||
} else {
|
|
||||||
resolve();
|
|
||||||
}
|
|
||||||
|
|
||||||
// we don't want to exit after compiling typescript files
|
|
||||||
// but instead want to do it if the tsc -w or electron app died.
|
|
||||||
if (commandToRun !== 'npx tsc') {
|
|
||||||
process.exit(0);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
proc.on('exit', check);
|
|
||||||
proc.on('close', check);
|
|
||||||
proc.on('error', () => {
|
|
||||||
reject();
|
|
||||||
process.exit(0);
|
|
||||||
});
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
async function main() {
|
|
||||||
const baseFilePattern = 'app/+(main|renderer)/**/*';
|
|
||||||
const globOptions = { cwd: path.resolve(__dirname, '..') };
|
|
||||||
const jsFiles = glob.sync(baseFilePattern + '.js', globOptions);
|
|
||||||
const tsFiles = glob.sync(baseFilePattern + '.ts', globOptions);
|
|
||||||
|
|
||||||
|
|
||||||
// if the are missing compiled js file for typescript files
|
|
||||||
// run the typescript compiler before starting the app
|
|
||||||
if (jsFiles.length !== tsFiles.length) {
|
|
||||||
console.log('Compiling typescript files...');
|
|
||||||
await run('TypeScript', 'npx tsc');
|
|
||||||
}
|
|
||||||
|
|
||||||
await Promise.all([
|
|
||||||
run('Electron app', 'npx electron . --disable-http-cache --no-electron-connect'),
|
|
||||||
run('TypeScript watch mode', 'npx tsc --watch --pretty')
|
|
||||||
]);
|
|
||||||
}
|
|
||||||
|
|
||||||
main()
|
|
||||||
.catch(err => console.error(err));
|
|
||||||
37
typings.d.ts
vendored
37
typings.d.ts
vendored
@@ -1,2 +1,37 @@
|
|||||||
declare module '@electron-elements/send-feedback';
|
declare module '@electron-elements/send-feedback' {
|
||||||
|
class SendFeedback extends HTMLElement {
|
||||||
|
customStyles: string;
|
||||||
|
titleLabel: string;
|
||||||
|
titlePlaceholder: string;
|
||||||
|
textareaLabel: string;
|
||||||
|
textareaPlaceholder: string;
|
||||||
|
buttonLabel: string;
|
||||||
|
loaderSuccessText: string;
|
||||||
|
logs: string[];
|
||||||
|
useReporter: (reporter: string, data: object) => void;
|
||||||
|
}
|
||||||
|
export = SendFeedback;
|
||||||
|
}
|
||||||
|
|
||||||
declare module 'node-mac-notifier';
|
declare module 'node-mac-notifier';
|
||||||
|
|
||||||
|
interface ClipboardDecrypter {
|
||||||
|
version: number;
|
||||||
|
key: Uint8Array;
|
||||||
|
pasted: Promise<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ElectronBridge {
|
||||||
|
send_event: (eventName: string | symbol, ...args: unknown[]) => void;
|
||||||
|
on_event: (eventName: string, listener: ListenerType) => void;
|
||||||
|
new_notification: (
|
||||||
|
title: string,
|
||||||
|
options: NotificationOptions | undefined,
|
||||||
|
dispatch: (type: string, eventInit: EventInit) => boolean
|
||||||
|
) => NotificationData;
|
||||||
|
get_idle_on_system: () => boolean;
|
||||||
|
get_last_active_on_system: () => number;
|
||||||
|
get_send_notification_reply_message_supported: () => boolean;
|
||||||
|
set_send_notification_reply_message_supported: (value: boolean) => void;
|
||||||
|
decrypt_clipboard: (version: number) => ClipboardDecrypter;
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user