Compare commits

..

2 Commits

Author SHA1 Message Date
Akash Nimare
be869a52d5 release: v4.0.3. 2020-02-28 10:14:22 +05:30
Akash Nimare
fcbb5da18e webview: Update web security preference.
Electron docs suggests that we should not use
`disablewebsecurity` thus removing the same.
2020-02-28 10:13:30 +05:30
104 changed files with 11667 additions and 10635 deletions

2
.gitattributes vendored
View File

@@ -1,5 +1,7 @@
* text=auto eol=lf * text=auto eol=lf
package-lock.json binary
app/package-lock.json binary
*.gif binary *.gif binary
*.jpg binary *.jpg binary
*.jpeg binary *.jpeg binary

4
.gitignore vendored
View File

@@ -1,5 +1,5 @@
# Dependency directory # Dependency directories
/node_modules/ node_modules/
# npm cache directory # npm cache directory
.npm .npm

View File

@@ -1,3 +1,6 @@
sudo: required
dist: trusty
os: os:
- osx - osx
- linux - linux
@@ -12,12 +15,23 @@ addons:
language: node_js language: node_js
node_js: node_js:
- '10' - '8'
- '12'
before_install:
- ./scripts/travis-xvfb.sh
- npm install -g gulp
- npm install
cache: cache:
directories: directories:
- node_modules - node_modules
- app/node_modules
script: script:
- npm run test - npm run travis
notifications:
webhooks:
urls:
- https://zulip.org/zulipbot/travis
on_success: always
on_failure: always

View File

@@ -1,11 +1,11 @@
import {app, dialog} from 'electron'; 'use strict';
import {UpdateDownloadedEvent, UpdateInfo, autoUpdater} from 'electron-updater'; import { app, dialog, shell } from 'electron';
import {linuxUpdateNotification} from './linuxupdater'; // Required only in case of linux import { autoUpdater } from 'electron-updater';
import { linuxUpdateNotification } from './linuxupdater'; // Required only in case of linux
import log from 'electron-log'; import log = require('electron-log');
import isDev from 'electron-is-dev'; import isDev = require('electron-is-dev');
import * as ConfigUtil from '../renderer/js/utils/config-util'; import ConfigUtil = require('../renderer/js/utils/config-util');
import * as LinkUtil from '../renderer/js/utils/link-util';
export function appUpdater(updateFromMenu = false): void { export function appUpdater(updateFromMenu = false): void {
// Don't initiate auto-updates in development // Don't initiate auto-updates in development
@@ -34,73 +34,73 @@ 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', async (info: UpdateInfo) => { autoUpdater.on('update-available', info => {
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', async () => { autoUpdater.on('update-not-available', () => {
if (updateFromMenu) { if (updateFromMenu) {
// Remove all autoUpdator listeners so that next time autoUpdator is manually called these dialog.showMessageBox({
// 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()}`
}); });
}
});
autoUpdater.on('error', async (error: Error) => {
if (updateFromMenu) {
// 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();
}
});
autoUpdater.on('error', error => {
if (updateFromMenu) {
const messageText = (updateAvailable) ? ('Unable to download the updates') : ('Unable to check for updates'); const messageText = (updateAvailable) ? ('Unable to download the updates') : ('Unable to check for updates');
const {response} = await dialog.showMessageBox({ dialog.showMessageBox({
type: 'error', type: 'error',
buttons: ['Manual Download', 'Cancel'], buttons: ['Manual Download', 'Cancel'],
message: messageText, message: messageText,
detail: `Error: ${error.message}\n\nThe latest version of Zulip Desktop is available at -\nhttps://zulipchat.com/apps/.\n detail: (error).toString() + `\n\nThe latest version of Zulip Desktop is available at -\nhttps://zulipchat.com/apps/.\n
Current Version: ${app.getVersion()}` Current Version: ${app.getVersion()}`
}); }, response => {
if (response === 0) { if (response === 0) {
await LinkUtil.openBrowser(new URL('https://zulipchat.com/apps/')); shell.openExternal('https://zulipchat.com/apps/');
} }
});
// Remove all autoUpdator listeners so that next time autoUpdator is manually called these
// listeners don't trigger multiple times.
autoUpdater.removeAllListeners();
} }
}); });
// Ask the user if update is available // Ask the user if update is available
autoUpdater.on('update-downloaded', async (event: UpdateDownloadedEvent) => { autoUpdater.on('update-downloaded', event => {
// Ask user to update the app // Ask user to update the app
const {response} = await dialog.showMessageBox({ dialog.showMessageBox({
type: 'question', type: 'question',
buttons: ['Install and Relaunch', 'Install Later'], buttons: ['Install and Relaunch', 'Install Later'],
defaultId: 0, defaultId: 0,
message: `A new update ${event.version} has been downloaded`, message: `A new update ${event.version} has been downloaded`,
detail: 'It will be installed the next time you restart the application' detail: 'It will be installed the next time you restart the application'
}); }, response => {
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
(async () => autoUpdater.checkForUpdates())(); autoUpdater.checkForUpdates();
} }

View File

@@ -1,17 +1,19 @@
import {sentryInit} from '../renderer/js/utils/sentry-util'; 'use strict';
import {appUpdater} from './autoupdater'; import { sentryInit } from '../renderer/js/utils/sentry-util';
import {setAutoLaunch} from './startup'; import { appUpdater } from './autoupdater';
import { setAutoLaunch } from './startup';
import windowStateKeeper from 'electron-window-state'; import windowStateKeeper = require('electron-window-state');
import path from 'path'; import path = require('path');
import fs from 'fs'; import fs = require('fs');
import electron, {app, dialog, ipcMain, session} from 'electron'; import isDev = require('electron-is-dev');
import electron = require('electron');
const { app, ipcMain, session } = electron;
import * as AppMenu from './menu'; import AppMenu = require('./menu');
import * as BadgeSettings from '../renderer/js/pages/preference/badge-settings'; import BadgeSettings = require('../renderer/js/pages/preference/badge-settings');
import * as CertificateUtil from '../renderer/js/utils/certificate-util'; import ConfigUtil = require('../renderer/js/utils/config-util');
import * as ConfigUtil from '../renderer/js/utils/config-util'; import ProxyUtil = require('../renderer/js/utils/proxy-util');
import * as ProxyUtil from '../renderer/js/utils/proxy-util';
interface PatchedGlobal extends NodeJS.Global { interface PatchedGlobal extends NodeJS.Global {
mainWindowState: windowStateKeeper.State; mainWindowState: windowStateKeeper.State;
@@ -19,6 +21,12 @@ interface PatchedGlobal extends NodeJS.Global {
const globalPatched = global as PatchedGlobal; const globalPatched = global as PatchedGlobal;
// Adds debug features like hotkeys for triggering dev tools and reload
// in development mode
if (isDev) {
require('electron-debug')();
}
// Prevent window being garbage collected // Prevent window being garbage collected
let mainWindow: Electron.BrowserWindow; let mainWindow: Electron.BrowserWindow;
let badgeCount: number; let badgeCount: number;
@@ -43,34 +51,12 @@ 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
const toggleApp = (): void => {
if (!mainWindow.isVisible() || mainWindow.isMinimized()) {
mainWindow.show();
} else {
mainWindow.hide();
}
};
function createMainWindow(): Electron.BrowserWindow { function createMainWindow(): Electron.BrowserWindow {
// Load the previous state with fallback to defaults // Load the previous state with fallback to defaults
const mainWindowState: windowStateKeeper.State = windowStateKeeper({ const mainWindowState: windowStateKeeper.State = windowStateKeeper({
@@ -95,8 +81,7 @@ function createMainWindow(): Electron.BrowserWindow {
webPreferences: { webPreferences: {
plugins: true, plugins: true,
nodeIntegration: true, nodeIntegration: true,
partition: 'persist:webviewsession', partition: 'persist:webviewsession'
webviewTag: true
}, },
show: false show: false
}); });
@@ -105,16 +90,15 @@ function createMainWindow(): Electron.BrowserWindow {
win.webContents.send('focus'); win.webContents.send('focus');
}); });
(async () => win.loadURL(mainURL))(); 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', e => {
if (ConfigUtil.getConfigItem('quitOnClose')) { if (ConfigUtil.getConfigItem("quitOnClose")) {
app.quit(); app.quit();
} }
if (!isQuitting) { if (!isQuitting) {
event.preventDefault(); e.preventDefault();
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
app.hide(); app.hide();
@@ -135,8 +119,8 @@ function createMainWindow(): Electron.BrowserWindow {
}); });
// To destroy tray icon when navigate to a new URL // To destroy tray icon when navigate to a new URL
win.webContents.on('will-navigate', event => { win.webContents.on('will-navigate', e => {
if (event) { if (e) {
win.webContents.send('destroytray'); win.webContents.send('destroytray');
} }
}); });
@@ -156,20 +140,19 @@ 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');
// This event is only available on macOS. Triggers when you click on the dock icon. // eslint-disable-next-line max-params
app.on('certificate-error', (event: Event, _webContents: Electron.WebContents, _url: string, _error: string, _certificate: any, callback) => {
event.preventDefault();
callback(true);
});
app.on('activate', () => { app.on('activate', () => {
if (mainWindow) { if (!mainWindow) {
// If there is already a window show it
mainWindow.show();
} else {
mainWindow = createMainWindow(); mainWindow = createMainWindow();
} }
}); });
app.on('ready', () => { app.on('ready', () => {
const ses = session.fromPartition('persist:webviewsession');
ses.setUserAgent(`ZulipElectron/${app.getVersion()} ${ses.getUserAgent()}`);
AppMenu.setMenu({ AppMenu.setMenu({
tabs: [] tabs: []
}); });
@@ -178,7 +161,7 @@ app.on('ready', () => {
// Auto-hide menu bar on Windows + Linux // Auto-hide menu bar on Windows + Linux
if (process.platform !== 'darwin') { if (process.platform !== 'darwin') {
const shouldHideMenu = ConfigUtil.getConfigItem('autoHideMenubar') || false; const shouldHideMenu = ConfigUtil.getConfigItem('autoHideMenubar') || false;
mainWindow.autoHideMenuBar = shouldHideMenu; mainWindow.setAutoHideMenuBar(shouldHideMenu);
mainWindow.setMenuBarVisibility(!shouldHideMenu); mainWindow.setMenuBarVisibility(!shouldHideMenu);
} }
@@ -191,7 +174,7 @@ app.on('ready', () => {
const isSystemProxy = ConfigUtil.getConfigItem('useSystemProxy'); const isSystemProxy = ConfigUtil.getConfigItem('useSystemProxy');
if (isSystemProxy) { if (isSystemProxy) {
(async () => ProxyUtil.resolveSystemProxy(mainWindow))(); ProxyUtil.resolveSystemProxy(mainWindow);
} }
const page = mainWindow.webContents; const page = mainWindow.webContents;
@@ -202,10 +185,10 @@ app.on('ready', () => {
} else { } else {
mainWindow.show(); mainWindow.show();
} }
}); if (!ConfigUtil.isConfigItemExists('userAgent')) {
const userAgent = session.fromPartition('webview:persistsession').getUserAgent();
ipcMain.on('fetch-user-agent', event => { ConfigUtil.setConfigItem('userAgent', userAgent);
event.returnValue = session.fromPartition('persist:webviewsession').getUserAgent(); }
}); });
page.once('did-frame-finish-load', () => { page.once('did-frame-finish-load', () => {
@@ -215,64 +198,6 @@ app.on('ready', () => {
} }
}); });
app.on('certificate-error', (
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) => {
const {origin} = new URL(details.requestingUrl);
page.send('permission-request', {
webContentsId: webContents.id === mainWindow.webContents.id ?
null :
webContents.id,
origin,
permission
}, makeRendererCallback(callback));
});
// Temporarily remove this event // Temporarily remove this event
// electron.powerMonitor.on('resume', () => { // electron.powerMonitor.on('resume', () => {
// mainWindow.reload(); // mainWindow.reload();
@@ -326,34 +251,38 @@ ${error}`
}); });
ipcMain.on('toggle-app', () => { ipcMain.on('toggle-app', () => {
toggleApp(); if (!mainWindow.isVisible() || mainWindow.isMinimized()) {
mainWindow.show();
} else {
mainWindow.hide();
}
}); });
ipcMain.on('toggle-badge-option', () => { ipcMain.on('toggle-badge-option', () => {
BadgeSettings.updateBadge(badgeCount, mainWindow); BadgeSettings.updateBadge(badgeCount, mainWindow);
}); });
ipcMain.on('toggle-menubar', (_event: Electron.IpcMainEvent, showMenubar: boolean) => { ipcMain.on('toggle-menubar', (_event: Electron.IpcMessageEvent, showMenubar: boolean) => {
mainWindow.autoHideMenuBar = showMenubar; mainWindow.setAutoHideMenuBar(showMenubar);
mainWindow.setMenuBarVisibility(!showMenubar); mainWindow.setMenuBarVisibility(!showMenubar);
page.send('toggle-autohide-menubar', showMenubar, true); page.send('toggle-autohide-menubar', showMenubar, true);
}); });
ipcMain.on('update-badge', (_event: Electron.IpcMainEvent, messageCount: number) => { ipcMain.on('update-badge', (_event: Electron.IpcMessageEvent, messageCount: number) => {
badgeCount = messageCount; badgeCount = messageCount;
BadgeSettings.updateBadge(badgeCount, mainWindow); BadgeSettings.updateBadge(badgeCount, mainWindow);
page.send('tray', messageCount); page.send('tray', messageCount);
}); });
ipcMain.on('update-taskbar-icon', (_event: Electron.IpcMainEvent, data: string, text: string) => { ipcMain.on('update-taskbar-icon', (_event: Electron.IpcMessageEvent, data: any, text: string) => {
BadgeSettings.updateTaskbarIcon(data, text, mainWindow); BadgeSettings.updateTaskbarIcon(data, text, mainWindow);
}); });
ipcMain.on('forward-message', (_event: Electron.IpcMainEvent, listener: string, ...parameters: unknown[]) => { ipcMain.on('forward-message', (_event: Electron.IpcMessageEvent, listener: any, ...params: any[]) => {
page.send(listener, ...parameters); page.send(listener, ...params);
}); });
ipcMain.on('update-menu', (_event: Electron.IpcMainEvent, props: AppMenu.MenuProps) => { ipcMain.on('update-menu', (_event: Electron.IpcMessageEvent, props: any) => {
AppMenu.setMenu(props); AppMenu.setMenu(props);
const activeTab = props.tabs[props.activeTabIndex]; const activeTab = props.tabs[props.activeTabIndex];
if (activeTab) { if (activeTab) {
@@ -361,20 +290,16 @@ ${error}`
} }
}); });
ipcMain.on('toggleAutoLauncher', async (_event: Electron.IpcMainEvent, AutoLaunchValue: boolean) => { ipcMain.on('toggleAutoLauncher', (_event: Electron.IpcMessageEvent, AutoLaunchValue: boolean) => {
await setAutoLaunch(AutoLaunchValue); setAutoLaunch(AutoLaunchValue);
}); });
ipcMain.on('downloadFile', (_event: Electron.IpcMainEvent, url: string, downloadPath: string) => { ipcMain.on('downloadFile', (_event: Electron.IpcMessageEvent, url: string, downloadPath: string) => {
page.downloadURL(url); page.downloadURL(url);
page.session.once('will-download', async (_event: Event, item) => { page.session.once('will-download', (_event: Event, item) => {
if (ConfigUtil.getConfigItem('promptDownload', false)) { const filePath = path.join(downloadPath, item.getFilename());
const showDialogOptions: object = {
defaultPath: path.join(downloadPath, item.getFilename()) const getTimeStamp = (): any => {
};
item.setSaveDialogOptions(showDialogOptions);
} else {
const getTimeStamp = (): number => {
const date = new Date(); const date = new Date();
return date.getTime(); return date.getTime();
}; };
@@ -385,15 +310,15 @@ ${error}`
return `${baseName}-${getTimeStamp()}${fileExtension}`; return `${baseName}-${getTimeStamp()}${fileExtension}`;
}; };
const filePath = path.join(downloadPath, item.getFilename());
// 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 setFilePath: string = fs.existsSync(filePath) ? updatedFilePath : filePath;
item.setSavePath(setFilePath);
}
const updatedListener = (_event: Event, state: string): void => { const updatedFilePath = path.join(downloadPath, formatFile(filePath));
const setFilePath = fs.existsSync(filePath) ? updatedFilePath : filePath;
item.setSavePath(setFilePath);
item.on('updated', (_event: Event, state) => {
switch (state) { switch (state) {
case 'interrupted': { case 'interrupted': {
// Can interrupted to due to network error, cancel download then // Can interrupted to due to network error, cancel download then
@@ -401,52 +326,47 @@ ${error}`
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.once('done', (_event: Event, state) => { item.once('done', (_event: Event, state) => {
const getFileName = fs.existsSync(filePath) ? formatFile(filePath) : item.getFilename();
if (state === 'completed') { if (state === 'completed') {
page.send('downloadFileCompleted', item.getSavePath(), path.basename(item.getSavePath())); page.send('downloadFileCompleted', item.getSavePath(), getFileName);
} else { } else {
console.log('Download failed state:', state); console.log('Download failed state: ', state);
page.send('downloadFileFailed', state); page.send('downloadFileFailed');
} }
// 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.removeAllListeners('updated');
}); });
}); });
}); });
ipcMain.on('realm-name-changed', (_event: Electron.IpcMainEvent, serverURL: string, realmName: string) => { ipcMain.on('realm-name-changed', (_event: Electron.IpcMessageEvent, serverURL: string, realmName: string) => {
page.send('update-realm-name', serverURL, realmName); page.send('update-realm-name', serverURL, realmName);
}); });
ipcMain.on('realm-icon-changed', (_event: Electron.IpcMainEvent, serverURL: string, iconURL: string) => { ipcMain.on('realm-icon-changed', (_event: Electron.IpcMessageEvent, serverURL: string, iconURL: string) => {
page.send('update-realm-icon', serverURL, iconURL); page.send('update-realm-icon', serverURL, iconURL);
}); });
// Using event.sender.send instead of page.send here to // Using event.sender.send instead of page.send here to
// make sure the value of errorReporting is sent only once on load. // make sure the value of errorReporting is sent only once on load.
ipcMain.on('error-reporting', (event: Electron.IpcMainEvent) => { ipcMain.on('error-reporting', (event: Electron.IpcMessageEvent) => {
event.sender.send('error-reporting-val', errorReporting); event.sender.send('error-reporting-val', errorReporting);
}); });
ipcMain.on('save-last-tab', (_event: Electron.IpcMainEvent, index: number) => { ipcMain.on('save-last-tab', (_event: Electron.IpcMessageEvent, index: number) => {
ConfigUtil.setConfigItem('lastActiveTab', index); ConfigUtil.setConfigItem('lastActiveTab', index);
}); });
@@ -455,12 +375,19 @@ ${error}`
setInterval(() => { setInterval(() => {
// Set user idle if no activity in 1 second (idleThresholdSeconds) // Set user idle if no activity in 1 second (idleThresholdSeconds)
const idleThresholdSeconds = 1; // 1 second const idleThresholdSeconds = 1; // 1 second
const idleState = electron.powerMonitor.getSystemIdleState(idleThresholdSeconds);
// TODO: Remove typecast to any when types get added
// TODO: use powerMonitor.getSystemIdleState when upgrading electron
// powerMonitor.querySystemIdleState is deprecated in current electron
// version at the time of writing.
const powerMonitor = electron.powerMonitor as any;
powerMonitor.querySystemIdleState(idleThresholdSeconds, (idleState: string) => {
if (idleState === 'active') { if (idleState === 'active') {
page.send('set-active'); page.send('set-active');
} else { } else {
page.send('set-idle'); page.send('set-idle');
} }
});
}, idleCheckInterval); }, idleCheckInterval);
}); });

View File

@@ -1,11 +1,11 @@
import {app, Notification} from 'electron'; import { app, Notification } from 'electron';
import request from 'request'; import request = require('request');
import semver from 'semver'; import semver = require('semver');
import * as ConfigUtil from '../renderer/js/utils/config-util'; import ConfigUtil = require('../renderer/js/utils/config-util');
import * as ProxyUtil from '../renderer/js/utils/proxy-util'; import ProxyUtil = require('../renderer/js/utils/proxy-util');
import * as LinuxUpdateUtil from '../renderer/js/utils/linux-update-util'; import LinuxUpdateUtil = require('../renderer/js/utils/linux-update-util');
import Logger from '../renderer/js/utils/logger-util'; import Logger = require('../renderer/js/utils/logger-util');
const logger = new Logger({ const logger = new Logger({
file: 'linux-update-util.log', file: 'linux-update-util.log',
@@ -24,24 +24,20 @@ export function linuxUpdateNotification(): void {
ecdhCurve: 'auto' ecdhCurve: 'auto'
}; };
request(options, (error, response: request.Response, body: string) => { request(options, (error: any, response: any, body: any) => {
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);
} }
} }

View File

@@ -1,62 +1,56 @@
import {app, shell, BrowserWindow, Menu, dialog} from 'electron'; 'use strict';
import {appUpdater} from './autoupdater'; import { app, shell, BrowserWindow, Menu, dialog } from 'electron';
import { appUpdater } from './autoupdater';
import AdmZip from 'adm-zip'; import AdmZip = require('adm-zip');
import fs from 'fs-extra'; import fs = require('fs-extra');
import path from 'path'; import path = require('path');
import * as DNDUtil from '../renderer/js/utils/dnd-util'; import DNDUtil = require('../renderer/js/utils/dnd-util');
import Logger from '../renderer/js/utils/logger-util'; import Logger = require('../renderer/js/utils/logger-util');
import * as ConfigUtil from '../renderer/js/utils/config-util'; import ConfigUtil = require('../renderer/js/utils/config-util');
import * as LinkUtil from '../renderer/js/utils/link-util'; import t = require('../renderer/js/utils/translation-util');
import * as t from '../renderer/js/utils/translation-util';
import type {ServerOrFunctionalTab} from '../renderer/js/main';
export interface MenuProps { const appName = app.getName();
tabs: ServerOrFunctionalTab[];
activeTabIndex?: number;
enableMenu?: boolean;
}
const appName = app.name;
const logger = new Logger({ const logger = new Logger({
file: 'errors.log', file: 'errors.log',
timestamp: true timestamp: true
}); });
function getHistorySubmenu(enableMenu: boolean): Electron.MenuItemConstructorOptions[] { class AppMenu {
getHistorySubmenu(enableMenu: boolean): Electron.MenuItemConstructorOptions[] {
return [{ return [{
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, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('back'); AppMenu.sendAction('back');
} }
} }
}, { }, {
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, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('forward'); AppMenu.sendAction('forward');
} }
} }
}]; }];
} }
function getToolsSubmenu(): Electron.MenuItemConstructorOptions[] { getToolsSubmenu(): Electron.MenuItemConstructorOptions[] {
return [{ return [{
label: t.__('Check for Updates'), label: t.__(`Check for Updates`),
click() { click() {
checkForUpdate(); AppMenu.checkForUpdate();
} }
}, },
{ {
label: t.__('Release Notes'), label: t.__(`Release Notes`),
async click() { click() {
await LinkUtil.openBrowser(new URL(`https://github.com/zulip/zulip-desktop/releases/tag/v${app.getVersion()}`)); shell.openExternal(`https://github.com/zulip/zulip-desktop/releases/tag/v${app.getVersion()}`);
} }
}, },
{ {
@@ -65,8 +59,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',
async click() { click() {
await resetAppSettings(); AppMenu.resetAppSettings();
} }
}, },
{ {
@@ -94,7 +88,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, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
focusedWindow.webContents.openDevTools({mode: 'undocked'}); focusedWindow.webContents.openDevTools({mode: 'undocked'});
} }
@@ -103,29 +97,29 @@ 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, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('tab-devtools'); AppMenu.sendAction('tab-devtools');
} }
} }
}]; }];
} }
function getViewSubmenu(): Electron.MenuItemConstructorOptions[] { getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
return [{ return [{
label: t.__('Reload'), label: t.__('Reload'),
accelerator: 'CommandOrControl+R', accelerator: 'CommandOrControl+R',
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('reload-current-viewer'); AppMenu.sendAction('reload-current-viewer');
} }
} }
}, { }, {
label: t.__('Hard Reload'), label: t.__('Hard Reload'),
accelerator: 'CommandOrControl+Shift+R', accelerator: 'CommandOrControl+Shift+R',
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('hard-reload'); AppMenu.sendAction('hard-reload');
} }
} }
}, { }, {
@@ -135,35 +129,33 @@ function getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
role: 'togglefullscreen' role: 'togglefullscreen'
}, { }, {
label: t.__('Zoom In'), label: t.__('Zoom In'),
role: 'zoomIn', role: 'zoomin',
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('zoomIn'); AppMenu.sendAction('zoomIn');
} }
} }
}, { }, {
label: t.__('Zoom Out'), label: t.__('Zoom Out'),
role: 'zoomOut',
accelerator: 'CommandOrControl+-', accelerator: 'CommandOrControl+-',
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('zoomOut'); AppMenu.sendAction('zoomOut');
} }
} }
}, { }, {
label: t.__('Actual Size'), label: t.__('Actual Size'),
role: 'resetZoom',
accelerator: 'CommandOrControl+0', accelerator: 'CommandOrControl+0',
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('zoomActualSize'); AppMenu.sendAction('zoomActualSize');
} }
} }
}, { }, {
type: 'separator' type: 'separator'
}, { }, {
label: t.__('Toggle Tray Icon'), label: t.__('Toggle Tray Icon'),
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
focusedWindow.webContents.send('toggletray'); focusedWindow.webContents.send('toggletray');
} }
@@ -171,7 +163,7 @@ function getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
}, { }, {
label: t.__('Toggle Sidebar'), label: t.__('Toggle Sidebar'),
accelerator: 'CommandOrControl+Shift+S', accelerator: 'CommandOrControl+Shift+S',
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
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);
@@ -182,10 +174,10 @@ 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, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
const newValue = !ConfigUtil.getConfigItem('autoHideMenubar'); const newValue = !ConfigUtil.getConfigItem('autoHideMenubar');
focusedWindow.autoHideMenuBar = newValue; focusedWindow.setAutoHideMenuBar(newValue);
focusedWindow.setMenuBarVisibility(!newValue); focusedWindow.setMenuBarVisibility(!newValue);
focusedWindow.webContents.send('toggle-autohide-menubar', newValue); focusedWindow.webContents.send('toggle-autohide-menubar', newValue);
ConfigUtil.setConfigItem('autoHideMenubar', newValue); ConfigUtil.setConfigItem('autoHideMenubar', newValue);
@@ -193,9 +185,9 @@ function getViewSubmenu(): Electron.MenuItemConstructorOptions[] {
}, },
type: 'checkbox' type: 'checkbox'
}]; }];
} }
function getHelpSubmenu(): Electron.MenuItemConstructorOptions[] { getHelpSubmenu(): Electron.MenuItemConstructorOptions[] {
return [ return [
{ {
label: `${appName + ' Desktop'} v${app.getVersion()}`, label: `${appName + ' Desktop'} v${app.getVersion()}`,
@@ -203,24 +195,24 @@ function getHelpSubmenu(): Electron.MenuItemConstructorOptions[] {
}, },
{ {
label: t.__('About Zulip'), label: t.__('About Zulip'),
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('open-about'); AppMenu.sendAction('open-about');
} }
} }
}, },
{ {
label: t.__('Help Center'), label: t.__(`Help Center`),
click(focusedWindow) { click(focusedWindow) {
if (focusedWindow) { if (focusedWindow) {
sendAction('open-help'); AppMenu.sendAction('open-help');
} }
} }
}, },
{ {
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');
@@ -228,10 +220,10 @@ function getHelpSubmenu(): Electron.MenuItemConstructorOptions[] {
} }
} }
]; ];
} }
function getWindowSubmenu(tabs: ServerOrFunctionalTab[], activeTabIndex: number): Electron.MenuItemConstructorOptions[] { getWindowSubmenu(tabs: any[], activeTabIndex: number, enableMenu: boolean): Electron.MenuItemConstructorOptions[] {
const initialSubmenu: Electron.MenuItemConstructorOptions[] = [{ const initialSubmenu: any[] = [{
label: t.__('Minimize'), label: t.__('Minimize'),
role: 'minimize' role: 'minimize'
}, { }, {
@@ -254,9 +246,9 @@ function getWindowSubmenu(tabs: ServerOrFunctionalTab[], activeTabIndex: number)
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, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('switch-server-tab', tab.props.index); AppMenu.sendAction('switch-server-tab', tab.props.index);
} }
}, },
type: 'checkbox' type: 'checkbox'
@@ -267,39 +259,39 @@ function getWindowSubmenu(tabs: ServerOrFunctionalTab[], activeTabIndex: number)
}); });
initialSubmenu.push({ initialSubmenu.push({
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, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('switch-server-tab', getNextServer(tabs, activeTabIndex)); AppMenu.sendAction('switch-server-tab', AppMenu.getNextServer(tabs, activeTabIndex));
} }
} }
}, { }, {
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, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('switch-server-tab', getPreviousServer(tabs, activeTabIndex)); AppMenu.sendAction('switch-server-tab', AppMenu.getPreviousServer(tabs, activeTabIndex));
} }
} }
}); });
} }
return initialSubmenu; return initialSubmenu;
} }
function getDarwinTpl(props: MenuProps): Electron.MenuItemConstructorOptions[] { getDarwinTpl(props: any): Electron.MenuItemConstructorOptions[] {
const {tabs, activeTabIndex, enableMenu} = props; const { tabs, activeTabIndex, enableMenu } = props;
return [{ return [{
label: app.name, label: `${app.getName()}`,
submenu: [{ submenu: [{
label: t.__('Add Organization'), label: t.__('Add Organization'),
accelerator: 'Cmd+Shift+N', accelerator: 'Cmd+Shift+N',
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('new-server'); AppMenu.sendAction('new-server');
} }
} }
}, { }, {
@@ -307,23 +299,23 @@ function getDarwinTpl(props: MenuProps): Electron.MenuItemConstructorOptions[] {
accelerator: 'Cmd+Shift+M', accelerator: 'Cmd+Shift+M',
click() { click() {
const dndUtil = DNDUtil.toggle(); const dndUtil = DNDUtil.toggle();
sendAction('toggle-dnd', dndUtil.dnd, dndUtil.newSettings); AppMenu.sendAction('toggle-dnd', dndUtil.dnd, dndUtil.newSettings);
} }
}, { }, {
label: t.__('Desktop Settings'), label: t.__('Desktop Settings'),
accelerator: 'Cmd+,', accelerator: 'Cmd+,',
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('open-settings'); AppMenu.sendAction('open-settings');
} }
} }
}, { }, {
label: t.__('Keyboard Shortcuts'), label: t.__('Keyboard Shortcuts'),
accelerator: 'Cmd+Shift+K', accelerator: 'Cmd+Shift+K',
enabled: enableMenu, enabled: enableMenu,
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('shortcut'); AppMenu.sendAction('shortcut');
} }
} }
}, { }, {
@@ -332,18 +324,18 @@ function getDarwinTpl(props: MenuProps): 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, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('copy-zulip-url'); AppMenu.sendAction('copy-zulip-url');
} }
} }
}, { }, {
label: t.__('Log Out of Organization'), label: t.__('Log Out of Organization'),
accelerator: 'Cmd+L', accelerator: 'Cmd+L',
enabled: enableMenu, enabled: enableMenu,
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('log-out'); AppMenu.sendAction('log-out');
} }
} }
}, { }, {
@@ -359,7 +351,7 @@ function getDarwinTpl(props: MenuProps): Electron.MenuItemConstructorOptions[] {
role: 'hide' role: 'hide'
}, { }, {
label: t.__('Hide Others'), label: t.__('Hide Others'),
role: 'hideOthers' role: 'hideothers'
}, { }, {
label: t.__('Unhide'), label: t.__('Unhide'),
role: 'unhide' role: 'unhide'
@@ -379,20 +371,10 @@ function getDarwinTpl(props: MenuProps): Electron.MenuItemConstructorOptions[] {
label: t.__('Edit'), label: t.__('Edit'),
submenu: [{ submenu: [{
label: t.__('Undo'), label: t.__('Undo'),
accelerator: 'Cmd+Z', role: 'undo'
click(_item, focusedWindow) {
if (focusedWindow) {
sendAction('undo');
}
}
}, { }, {
label: t.__('Redo'), label: t.__('Redo'),
accelerator: 'Cmd+Shift+Z', role: 'redo'
click(_item, focusedWindow) {
if (focusedWindow) {
sendAction('redo');
}
}
}, { }, {
type: 'separator' type: 'separator'
}, { }, {
@@ -406,40 +388,40 @@ function getDarwinTpl(props: MenuProps): Electron.MenuItemConstructorOptions[] {
role: 'paste' role: 'paste'
}, { }, {
label: t.__('Paste and Match Style'), label: t.__('Paste and Match Style'),
role: 'pasteAndMatchStyle' role: 'pasteandmatchstyle'
}, { }, {
label: t.__('Select All'), label: t.__('Select All'),
role: 'selectAll' role: 'selectall'
}] }]
}, { }, {
label: t.__('View'), label: t.__('View'),
submenu: getViewSubmenu() submenu: this.getViewSubmenu()
}, { }, {
label: t.__('History'), label: t.__('History'),
submenu: getHistorySubmenu(enableMenu) submenu: this.getHistorySubmenu(enableMenu)
}, { }, {
label: t.__('Window'), label: t.__('Window'),
submenu: getWindowSubmenu(tabs, activeTabIndex) submenu: this.getWindowSubmenu(tabs, activeTabIndex, enableMenu)
}, { }, {
label: t.__('Tools'), label: t.__('Tools'),
submenu: getToolsSubmenu() submenu: this.getToolsSubmenu()
}, { }, {
label: t.__('Help'), label: t.__('Help'),
role: 'help', role: 'help',
submenu: getHelpSubmenu() submenu: this.getHelpSubmenu()
}]; }];
} }
function getOtherTpl(props: MenuProps): Electron.MenuItemConstructorOptions[] { getOtherTpl(props: any): 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, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('new-server'); AppMenu.sendAction('new-server');
} }
} }
}, { }, {
@@ -449,23 +431,23 @@ function getOtherTpl(props: MenuProps): Electron.MenuItemConstructorOptions[] {
accelerator: 'Ctrl+Shift+M', accelerator: 'Ctrl+Shift+M',
click() { click() {
const dndUtil = DNDUtil.toggle(); const dndUtil = DNDUtil.toggle();
sendAction('toggle-dnd', dndUtil.dnd, dndUtil.newSettings); AppMenu.sendAction('toggle-dnd', dndUtil.dnd, dndUtil.newSettings);
} }
}, { }, {
label: t.__('Desktop Settings'), label: t.__('Desktop Settings'),
accelerator: 'Ctrl+,', accelerator: 'Ctrl+,',
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('open-settings'); AppMenu.sendAction('open-settings');
} }
} }
}, { }, {
label: t.__('Keyboard Shortcuts'), label: t.__('Keyboard Shortcuts'),
accelerator: 'Ctrl+Shift+K', accelerator: 'Ctrl+Shift+K',
enabled: enableMenu, enabled: enableMenu,
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('shortcut'); AppMenu.sendAction('shortcut');
} }
} }
}, { }, {
@@ -474,18 +456,18 @@ function getOtherTpl(props: MenuProps): 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, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('copy-zulip-url'); AppMenu.sendAction('copy-zulip-url');
} }
} }
}, { }, {
label: t.__('Log Out of Organization'), label: t.__('Log Out of Organization'),
accelerator: 'Ctrl+L', accelerator: 'Ctrl+L',
enabled: enableMenu, enabled: enableMenu,
click(_item, focusedWindow) { click(_item: any, focusedWindow: any) {
if (focusedWindow) { if (focusedWindow) {
sendAction('log-out'); AppMenu.sendAction('log-out');
} }
} }
}, { }, {
@@ -522,96 +504,98 @@ function getOtherTpl(props: MenuProps): Electron.MenuItemConstructorOptions[] {
role: 'paste' role: 'paste'
}, { }, {
label: t.__('Paste and Match Style'), label: t.__('Paste and Match Style'),
role: 'pasteAndMatchStyle' role: 'pasteandmatchstyle'
}, { }, {
type: 'separator' type: 'separator'
}, { }, {
label: t.__('Select All'), label: t.__('Select All'),
role: 'selectAll' role: 'selectall'
}] }]
}, { }, {
label: t.__('View'), label: t.__('View'),
submenu: getViewSubmenu() submenu: this.getViewSubmenu()
}, { }, {
label: t.__('History'), label: t.__('History'),
submenu: getHistorySubmenu(enableMenu) submenu: this.getHistorySubmenu(enableMenu)
}, { }, {
label: t.__('Window'), label: t.__('Window'),
submenu: getWindowSubmenu(tabs, activeTabIndex) submenu: this.getWindowSubmenu(tabs, activeTabIndex, enableMenu)
}, { }, {
label: t.__('Tools'), label: t.__('Tools'),
submenu: getToolsSubmenu() submenu: this.getToolsSubmenu()
}, { }, {
label: t.__('Help'), label: t.__('Help'),
role: 'help', role: 'help',
submenu: getHelpSubmenu() submenu: this.getHelpSubmenu()
}]; }];
} }
function sendAction(action: string, ...parameters: unknown[]): void { static sendAction(action: any, ...params: any[]): void {
const win = BrowserWindow.getAllWindows()[0]; const win = BrowserWindow.getAllWindows()[0];
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
win.restore(); win.restore();
} }
win.webContents.send(action, ...parameters); win.webContents.send(action, ...params);
} }
function checkForUpdate(): void { static checkForUpdate(): void {
appUpdater(true); appUpdater(true);
} }
function getNextServer(tabs: ServerOrFunctionalTab[], activeTabIndex: number): number { static getNextServer(tabs: any[], 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: ServerOrFunctionalTab[], activeTabIndex: number): number { static getPreviousServer(tabs: any[], 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;
} }
async function resetAppSettings(): Promise<void> { static resetAppSettings(): void {
const resetAppSettingsMessage = 'By proceeding you will be removing all connected organizations and preferences from Zulip.'; const resetAppSettingsMessage = 'By proceeding you will be removing all connected organizations and preferences from Zulip.';
// 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({ dialog.showMessageBox({
type: 'warning', type: 'warning',
buttons: ['YES', 'NO'], buttons: ['YES', 'NO'],
defaultId: 0, defaultId: 0,
message: 'Are you sure?', message: 'Are you sure?',
detail: resetAppSettingsMessage detail: resetAppSettingsMessage
}); }, response => {
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: NodeJS.ErrnoException) => { fs.access(getSettingFilesPath, (error: any) => {
if (error) { if (error) {
logger.error('Error while resetting app settings.'); logger.error('Error while resetting app settings.');
logger.error(error); logger.error(error);
} else { } else {
fs.unlink(getSettingFilesPath, () => { fs.unlink(getSettingFilesPath, () => {
sendAction('clear-app-data'); AppMenu.sendAction('clear-app-data');
}); });
} }
}); });
}); });
} }
});
}
setMenu(props: any): void {
const tpl = process.platform === 'darwin' ? this.getDarwinTpl(props) : this.getOtherTpl(props);
const menu = Menu.buildFromTemplate(tpl);
Menu.setApplicationMenu(menu);
}
} }
export function setMenu(props: MenuProps): void { export = new AppMenu();
const tpl = process.platform === 'darwin' ? getDarwinTpl(props) : getOtherTpl(props);
const menu = Menu.buildFromTemplate(tpl);
Menu.setApplicationMenu(menu);
}

View File

@@ -1,32 +1,31 @@
import {app} from 'electron'; 'use strict';
import { app } from 'electron';
import AutoLaunch from 'auto-launch'; import AutoLaunch = require('auto-launch');
import isDev from 'electron-is-dev'; import isDev = require('electron-is-dev');
import * as ConfigUtil from '../renderer/js/utils/config-util'; import ConfigUtil = require('../renderer/js/utils/config-util');
export const setAutoLaunch = async (AutoLaunchValue: boolean): Promise<void> => { export const setAutoLaunch = (AutoLaunchValue: boolean): void => {
// Don't run this in development // Don't run this in development
if (isDev) { if (isDev) {
return; return;
} }
const autoLaunchOption = ConfigUtil.getConfigItem('startAtLogin', AutoLaunchValue); // On Mac, work around a bug in auto-launch where it opens a Terminal window
// See https://github.com/Teamwork/node-auto-launch/issues/28#issuecomment-222194437
const appPath = process.platform === 'darwin' ? app.getPath('exe').replace(/\.app\/Content.*/, '.app') : undefined; // Use the default
// `setLoginItemSettings` doesn't support linux
if (process.platform === 'linux') {
const ZulipAutoLauncher = new AutoLaunch({ const ZulipAutoLauncher = new AutoLaunch({
name: 'Zulip', name: 'Zulip',
path: appPath,
isHidden: false isHidden: false
}); });
const autoLaunchOption = ConfigUtil.getConfigItem('startAtLogin', AutoLaunchValue);
if (autoLaunchOption) { if (autoLaunchOption) {
await ZulipAutoLauncher.enable(); ZulipAutoLauncher.enable();
} else { } else {
await ZulipAutoLauncher.disable(); ZulipAutoLauncher.disable();
}
} else {
app.setLoginItemSettings({
openAtLogin: autoLaunchOption,
openAsHidden: false
});
} }
}; };

1940
app/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

51
app/package.json Normal file
View File

@@ -0,0 +1,51 @@
{
"name": "zulip",
"productName": "Zulip",
"version": "4.0.3",
"desktopName": "zulip.desktop",
"description": "Zulip Desktop App",
"license": "Apache-2.0",
"copyright": "Kandra Labs, Inc.",
"author": {
"name": "Kandra Labs, Inc.",
"email": "support@zulipchat.com"
},
"repository": {
"type": "git",
"url": "https://github.com/zulip/zulip-desktop.git"
},
"bugs": {
"url": "https://github.com/zulip/zulip-desktop/issues"
},
"main": "main/index.js",
"keywords": [
"Zulip",
"Group Chat app",
"electron-app",
"electron",
"Desktop app",
"InstantMessaging"
],
"dependencies": {
"@electron-elements/send-feedback": "1.0.8",
"@sentry/electron": "0.14.0",
"adm-zip": "0.4.11",
"auto-launch": "5.0.5",
"backoff": "2.5.0",
"dotenv": "8.0.0",
"electron-is-dev": "0.3.0",
"electron-log": "2.2.14",
"electron-spellchecker": "1.1.2",
"electron-updater": "4.0.6",
"electron-window-state": "5.0.3",
"escape-html": "1.0.3",
"i18n": "0.8.3",
"node-json-db": "0.9.2",
"request": "2.85.0",
"semver": "5.4.1",
"wurl": "2.5.0"
},
"optionalDependencies": {
"node-mac-notifier": "1.1.0"
}
}

View File

@@ -14,19 +14,33 @@
<div class="maintenance-info"> <div class="maintenance-info">
<p class="detail maintainer"> <p class="detail maintainer">
Maintained by Maintained by
<a href="https://zulipchat.com" target="_blank" rel="noopener noreferrer">Zulip</a> <a onclick="linkInBrowser('website')">Zulip</a>
</p> </p>
<p class="detail license"> <p class="detail license">
Available under the Available under the
<a href="https://github.com/zulip/zulip-desktop/blob/master/LICENSE" target="_blank" rel="noopener noreferrer">Apache 2.0 License</a> <a onclick="linkInBrowser('license')">Apache 2.0 License</a>
</p> </p>
</div> </div>
</div> </div>
<script> <script>
const { app } = require('electron').remote; const { app } = require('electron').remote;
const { shell } = require('electron');
const version_tag = document.querySelector('#version'); const version_tag = document.querySelector('#version');
version_tag.innerHTML = 'v' + app.getVersion(); version_tag.innerHTML = 'v' + app.getVersion();
function linkInBrowser(type) {
let url;
switch (type) {
case 'website':
url = "https://zulipchat.com";
break;
case 'license':
url = "https://github.com/zulip/zulip-desktop/blob/master/LICENSE";
break;
}
shell.openExternal(url);
}
</script> </script>
<script>require('./js/shared/preventdrag.js')</script> <script>require('./js/shared/preventdrag.js')</script>
</body> </body>

View File

@@ -724,13 +724,3 @@ i.open-network-button {
margin-top: 10px; margin-top: 10px;
} }
} }
.lang-menu {
font-size: 13px;
font-weight: bold;
background: rgba(78, 191, 172, 1.000);
width: 100px;
height: 38px;
color: rgba(255, 255, 255, 1.000);
border-color: rgba(0, 0, 0, 0);
}

View File

@@ -1,82 +0,0 @@
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 users 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
// dont leak anything from the users 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 hasnt 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();
}
});
}
}

View File

@@ -1,7 +1,11 @@
export default class BaseComponent { 'use strict';
class BaseComponent {
generateNodeFromTemplate(template: string): Element | null { generateNodeFromTemplate(template: string): Element | null {
const wrapper = document.createElement('div'); const wrapper = document.createElement('div');
wrapper.innerHTML = template; wrapper.innerHTML = template;
return wrapper.firstElementChild; return wrapper.firstElementChild;
} }
} }
export = BaseComponent;

View File

@@ -1,13 +1,9 @@
import Tab, {TabProps} from './tab'; 'use strict';
export default class FunctionalTab extends Tab { import Tab = require('./tab');
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">
@@ -19,6 +15,12 @@ export default class FunctionalTab extends Tab {
</div>`; </div>`;
} }
// TODO: Typescript - This type for props should be TabProps
constructor(props: any) {
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') {
@@ -39,9 +41,11 @@ export default class FunctionalTab extends Tab {
this.$closeButton.classList.remove('active'); this.$closeButton.classList.remove('active');
}); });
this.$closeButton.addEventListener('click', (event: Event) => { this.$closeButton.addEventListener('click', (e: Event) => {
this.props.onDestroy(); this.props.onDestroy();
event.stopPropagation(); e.stopPropagation();
}); });
} }
} }
export = FunctionalTab;

View File

@@ -1,60 +1,83 @@
import {ipcRenderer, remote} from 'electron'; import { ipcRenderer, remote } from 'electron';
import * as LinkUtil from '../utils/link-util'; import LinkUtil = require('../utils/link-util');
import * as ConfigUtil from '../utils/config-util'; import DomainUtil = require('../utils/domain-util');
import type WebView from './webview'; import ConfigUtil = require('../utils/config-util');
const {shell, app} = remote; const { shell, app } = remote;
const dingSound = new Audio('../resources/sounds/ding.ogg'); const dingSound = new Audio('../resources/sounds/ding.ogg');
export default function handleExternalLink(this: WebView, event: Electron.NewWindowEvent): void { // TODO: TypeScript - Figure out a way to pass correct type here.
function handleExternalLink(this: any, event: any): void {
const { url } = event;
const domainPrefix = DomainUtil.getDomain(this.props.index).url;
const downloadPath = ConfigUtil.getConfigItem('downloadsPath', `${app.getPath('downloads')}`);
const shouldShowInFolder = ConfigUtil.getConfigItem('showDownloadFolder', false);
// Whitelist URLs which are allowed to be opened in the app
const {
isInternalUrl: isWhiteListURL,
isUploadsUrl: isUploadsURL
} = LinkUtil.isInternal(domainPrefix, url);
if (isWhiteListURL) {
event.preventDefault(); event.preventDefault();
const url = new URL(event.url); // Code to show pdf in a new BrowserWindow (currently commented out due to bug-upstream)
const downloadPath = ConfigUtil.getConfigItem('downloadsPath', `${app.getPath('downloads')}`); // Show pdf attachments in a new window
// if (LinkUtil.isPDF(url) && isUploadsURL) {
// ipcRenderer.send('pdf-view', url);
// return;
// }
if (LinkUtil.isUploadsUrl(this.props.url, url)) { // download txt, mp3, mp4 etc.. by using downloadURL in the
ipcRenderer.send('downloadFile', url.href, downloadPath); // main process which allows the user to save the files to their desktop
ipcRenderer.once('downloadFileCompleted', async (_event: Event, filePath: string, fileName: string) => { // and not trigger webview reload while image in webview will
// do nothing and will not save it
// Code to show pdf in a new BrowserWindow (currently commented out due to bug-upstream)
// if (!LinkUtil.isImage(url) && !LinkUtil.isPDF(url) && isUploadsURL) {
if (!LinkUtil.isImage(url) && isUploadsURL) {
ipcRenderer.send('downloadFile', url, downloadPath);
ipcRenderer.once('downloadFileCompleted', (_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: shouldShowInFolder ? `Click to show ${fileName} in folder` : `Click to open ${fileName}`,
silent: true // We'll play our own sound - ding.ogg silent: true // We'll play our own sound - ding.ogg
}); });
downloadNotification.addEventListener('click', () => {
// Reveal file in download folder
shell.showItemInFolder(filePath);
});
ipcRenderer.removeAllListeners('downloadFileFailed');
// Play sound to indicate download complete // Play sound to indicate download complete
if (!ConfigUtil.getConfigItem('silent')) { if (!ConfigUtil.getConfigItem('silent')) {
await dingSound.play(); dingSound.play();
}
downloadNotification.addEventListener('click', () => {
if (shouldShowInFolder) {
// Reveal file in download folder
shell.showItemInFolder(filePath);
} else {
// Open file in the default native app
shell.openItem(filePath);
} }
}); });
ipcRenderer.removeAllListeners('downloadFileFailed');
});
ipcRenderer.once('downloadFileFailed', (_event: Event, state: string) => { ipcRenderer.once('downloadFileFailed', () => {
// 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 this.$el.downloadURL(url);
// prompts right after each other)
// Check that the download is not cancelled by user
if (state !== 'cancelled') {
if (ConfigUtil.getConfigItem('promptDownload', false)) {
// We need to create a "new Notification" to display it, but just `Notification(...)` on its own
// doesn't work
new Notification('Download Complete', { // eslint-disable-line no-new
body: 'Download failed'
});
} else {
this.$el.downloadURL(url.href);
}
}
ipcRenderer.removeAllListeners('downloadFileCompleted'); ipcRenderer.removeAllListeners('downloadFileCompleted');
}); });
return;
}
// open internal urls inside the current webview.
this.$el.loadURL(url);
} else { } else {
(async () => LinkUtil.openBrowser(url))(); event.preventDefault();
shell.openExternal(url);
} }
} }
export = handleExternalLink;

View File

@@ -1,16 +1,13 @@
import {ipcRenderer} from 'electron'; 'use strict';
import Tab, {TabProps} from './tab'; import { ipcRenderer } from 'electron';
import * as SystemUtil from '../utils/system-util';
export default class ServerTab extends Tab { import Tab = require('./tab');
import SystemUtil = require('../utils/system-util');
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>
@@ -22,6 +19,12 @@ export default class ServerTab extends Tab {
</div>`; </div>`;
} }
// TODO: Typescript - This type for props should be TabProps
constructor(props: any) {
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);
@@ -61,3 +64,5 @@ export default class ServerTab extends Tab {
return shortcutText; return shortcutText;
} }
} }
export = ServerTab;

View File

@@ -1,22 +1,14 @@
import WebView from './webview'; 'use strict';
import BaseComponent from './base';
export interface TabProps { import WebView = require('./webview');
role: string; import BaseComponent = require('./base');
icon?: string;
name: string; // TODO: TypeScript - Type annotate props
$root: Element; interface TabProps {
onClick: () => void; [key: string]: any;
index: number;
tabIndex: number;
onHover?: () => void;
onHoverOut?: () => void;
webview: WebView;
materialIcon?: string;
onDestroy?: () => void;
} }
export default class Tab extends BaseComponent { class Tab extends BaseComponent {
props: TabProps; props: TabProps;
webview: WebView; webview: WebView;
$el: Element; $el: Element;
@@ -48,7 +40,9 @@ export default class Tab extends BaseComponent {
} }
destroy(): void { destroy(): void {
this.$el.remove(); this.$el.parentNode.removeChild(this.$el);
this.webview.$el.remove(); this.webview.$el.parentNode.removeChild(this.webview.$el);
} }
} }
export = Tab;

View File

@@ -1,48 +1,40 @@
import {ipcRenderer, remote} from 'electron'; 'use strict';
import { remote } from 'electron';
import path from 'path'; import path = require('path');
import fs from 'fs'; import fs = require('fs');
import * as ConfigUtil from '../utils/config-util'; import ConfigUtil = require('../utils/config-util');
import * as SystemUtil from '../utils/system-util'; import SystemUtil = require('../utils/system-util');
import BaseComponent from './base'; import BaseComponent = require('../components/base');
import handleExternalLink from './handle-external-link'; import handleExternalLink = require('../components/handle-external-link');
const {app, dialog} = remote; const { app, dialog } = remote;
const shouldSilentWebview = ConfigUtil.getConfigItem('silent'); const shouldSilentWebview = ConfigUtil.getConfigItem('silent');
// TODO: TypeScript - Type annotate WebViewProps.
interface WebViewProps { interface WebViewProps {
$root: Element; [key: string]: any;
index: number;
tabIndex: number;
url: string;
role: string;
name: string;
isActive: () => boolean;
switchLoading: (loading: boolean, url: string) => void;
onNetworkError: (index: number) => void;
nodeIntegration: boolean;
preload: boolean;
onTitleChange: () => void;
ignoreCerts?: boolean;
hasPermission?: (origin: string, permission: string) => boolean;
} }
export default class WebView extends BaseComponent { class WebView extends BaseComponent {
props: WebViewProps; props: any;
zoomFactor: number; zoomFactor: number;
badgeCount: number; badgeCount: number;
loading: boolean; loading: boolean;
customCSS: string; customCSS: string;
$webviewsContainer: DOMTokenList; $webviewsContainer: DOMTokenList;
$el: Electron.WebviewTag; $el: Electron.WebviewTag;
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();
this.props = props; this.props = props;
this.zoomFactor = 1; this.zoomFactor = 1.0;
this.loading = true; this.loading = true;
this.badgeCount = 0; this.badgeCount = 0;
this.customCSS = ConfigUtil.getConfigItem('customCSS'); this.customCSS = ConfigUtil.getConfigItem('customCSS');
@@ -58,15 +50,12 @@ export default class WebView extends BaseComponent {
${this.props.preload ? 'preload="js/preload.js"' : ''} ${this.props.preload ? 'preload="js/preload.js"' : ''}
partition="persist:webviewsession" partition="persist:webviewsession"
name="${this.props.name}" name="${this.props.name}"
webpreferences="${this.props.nodeIntegration ? '' : 'contextIsolation, '}javascript=yes"> webpreferences="allowRunningInsecureContent, javascript=yes">
</webview>`; </webview>`;
} }
init(): void { init(): void {
this.$el = this.generateNodeFromTemplate(this.template()) as Electron.WebviewTag; this.$el = this.generateNodeFromTemplate(this.template()) as Electron.WebviewTag;
this.domReady = new Promise(resolve => {
this.$el.addEventListener('dom-ready', () => resolve(), true);
});
this.props.$root.append(this.$el); this.props.$root.append(this.$el);
this.registerListeners(); this.registerListeners();
@@ -84,7 +73,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();
}); });
@@ -94,7 +83,6 @@ export default class WebView extends BaseComponent {
if (isSettingPage) { if (isSettingPage) {
return; return;
} }
this.canGoBackButton(); this.canGoBackButton();
}); });
@@ -103,14 +91,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();
} }
@@ -121,7 +109,6 @@ 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();
@@ -133,7 +120,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);
@@ -148,6 +135,12 @@ export default class WebView extends BaseComponent {
if (!isSettingPage) { if (!isSettingPage) {
this.props.switchLoading(true, this.props.url); this.props.switchLoading(true, this.props.url);
} }
let userAgent = SystemUtil.getUserAgent();
if (!userAgent) {
SystemUtil.setUserAgent(this.$el.getUserAgent());
userAgent = SystemUtil.getUserAgent();
}
this.$el.setUserAgent(userAgent);
}); });
this.$el.addEventListener('did-stop-loading', () => { this.$el.addEventListener('did-stop-loading', () => {
@@ -161,7 +154,7 @@ export default class WebView extends BaseComponent {
} }
showNotificationSettings(): void { showNotificationSettings(): void {
ipcRenderer.sendTo(this.$el.getWebContentsId(), 'show-notification-settings'); this.$el.executeJavaScript('showNotificationSettings()');
} }
show(): void { show(): void {
@@ -187,26 +180,26 @@ 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
(async () => this.$el.insertCSS(fs.readFileSync(path.join(__dirname, '/../../css/preload.css'), 'utf8')))(); 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)) {
this.customCSS = null; this.customCSS = null;
ConfigUtil.setConfigItem('customCSS', null); ConfigUtil.setConfigItem('customCSS', null);
const errorMessage = 'The custom css previously set is deleted!'; const errMsg = 'The custom css previously set is deleted!';
dialog.showErrorBox('custom css file deleted!', errorMessage); dialog.showErrorBox('custom css file deleted!', errMsg);
return; return;
} }
(async () => this.$el.insertCSS(fs.readFileSync(path.resolve(__dirname, this.customCSS), 'utf8')))(); 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`.
@@ -244,16 +237,16 @@ export default class WebView extends BaseComponent {
} }
zoomActualSize(): void { zoomActualSize(): void {
this.zoomFactor = 1; this.zoomFactor = 1.0;
this.$el.setZoomFactor(this.zoomFactor); this.$el.setZoomFactor(this.zoomFactor);
} }
logOut(): void { logOut(): void {
ipcRenderer.sendTo(this.$el.getWebContentsId(), 'logout'); this.$el.executeJavaScript('logout()');
} }
showShortcut(): void { showShortcut(): void {
ipcRenderer.sendTo(this.$el.getWebContentsId(), 'shortcut'); this.$el.executeJavaScript('shortcut()');
} }
openDevTools(): void { openDevTools(): void {
@@ -295,8 +288,9 @@ export default class WebView extends BaseComponent {
this.init(); this.init();
} }
async send(channel: string, ...parameters: unknown[]): Promise<void> { send(channel: string, ...param: any[]): void {
await this.domReady; this.$el.send(channel, ...param);
await this.$el.send(channel, ...parameters);
} }
} }
export = WebView;

View File

@@ -1,13 +1,14 @@
import {ipcRenderer} from 'electron'; import { ipcRenderer } from 'electron';
import {EventEmitter} from 'events'; import events = require('events');
import {ClipboardDecrypterImpl} from './clipboard-decrypter';
import {NotificationData, newNotification} from './notification';
type ListenerType = ((...args: any[]) => void); type ListenerType = ((...args: any[]) => void);
class ElectronBridgeImpl extends EventEmitter implements ElectronBridge { // we have and will have some non camelcase stuff
// while working with zulip so just turning the rule off
// for the whole file.
/* eslint-disable @typescript-eslint/camelcase */
class ElectronBridge extends events {
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;
@@ -22,37 +23,16 @@ class ElectronBridgeImpl extends EventEmitter implements ElectronBridge {
this.last_active_on_system = Date.now(); this.last_active_on_system = Date.now();
} }
send_event = (eventName: string | symbol, ...args: unknown[]): void => { send_event(eventName: string | symbol, ...args: any[]): void {
this.emit(eventName, ...args); this.emit(eventName, ...args);
}; }
on_event = (eventName: string, listener: ListenerType): void => { on_event(eventName: string, listener: ListenerType): void {
this.on(eventName, listener); this.on(eventName, listener);
}; }
new_notification = (
title: string,
options: NotificationOptions | undefined,
dispatch: (type: string, eventInit: EventInit) => boolean
): NotificationData =>
newNotification(title, options, dispatch);
get_idle_on_system = (): boolean => this.idle_on_system;
get_last_active_on_system = (): number => this.last_active_on_system;
get_send_notification_reply_message_supported = (): boolean =>
this.send_notification_reply_message_supported;
set_send_notification_reply_message_supported = (value: boolean): void => {
this.send_notification_reply_message_supported = value;
};
decrypt_clipboard = (version: number): ClipboardDecrypterImpl =>
new ClipboardDecrypterImpl(version);
} }
const electron_bridge = new ElectronBridgeImpl(); const electron_bridge = new ElectronBridge();
electron_bridge.on('total_unread_count', (...args) => { electron_bridge.on('total_unread_count', (...args) => {
ipcRenderer.send('unread-count', ...args); ipcRenderer.send('unread-count', ...args);
@@ -63,19 +43,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: unknown) => { electron_bridge.on('realm_icon_url', iconURL => {
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
// a listener for the event. // a listener for the event.
export default electron_bridge; export = electron_bridge;
/* eslint-enable @typescript-eslint/camelcase */

View File

@@ -1,17 +1,19 @@
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 = require('path');
import fs from 'fs'; import fs = require('fs');
const {app} = remote; const { app } = remote;
customElements.define('send-feedback', SendFeedback); interface SendFeedback extends HTMLElement {
export const sendFeedback: SendFeedback = document.querySelector('send-feedback'); [key: string]: any;
export const feedbackHolder = sendFeedback.parentElement; }
// Make the button color match zulip app's theme type SendFeedbackType = SendFeedback;
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;
@@ -28,26 +30,16 @@ button {
} }
`; `;
/* eslint-disable no-multi-str */ customElements.define('send-feedback', SendFeedback);
export const sendFeedback: SendFeedbackType = document.querySelector('send-feedback');
export const feedbackHolder = sendFeedback.parentElement;
// customize the fields of custom elements // customize the fields of custom elements
sendFeedback.title = 'Report Issue'; sendFeedback.title = 'Report Issue';
sendFeedback.titleLabel = 'Issue title:'; sendFeedback.titleLabel = 'Issue title:';
sendFeedback.titlePlaceholder = 'Enter issue title'; sendFeedback.titlePlaceholder = 'Enter issue title';
sendFeedback.textareaLabel = 'Describe the issue:'; sendFeedback.textareaLabel = 'Describe the issue:';
sendFeedback.textareaPlaceholder = 'Succinctly describe your issue and steps to reproduce it...\n\n\ sendFeedback.textareaPlaceholder = 'Succinctly describe your issue and steps to reproduce it...';
---\n\
<!-- Please Include: -->\n\
- **Operating System**:\n\
- [ ] Windows\n\
- [ ] Linux/Ubuntu\n\
- [ ] macOS\n\
- **Clear steps to reproduce the issue**:\n\
- **Relevant error messages and/or screenshots**:\n\
';
/* eslint-enable no-multi-str */
sendFeedback.buttonLabel = 'Report Issue'; sendFeedback.buttonLabel = 'Report Issue';
sendFeedback.loaderSuccessText = ''; sendFeedback.loaderSuccessText = '';
@@ -55,10 +47,10 @@ sendFeedback.useReporter('emailReporter', {
email: 'akash@zulipchat.com' email: 'akash@zulipchat.com'
}); });
feedbackHolder.addEventListener('click', (event: Event) => { feedbackHolder.addEventListener('click', (e: 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 (e.target === e.currentTarget) {
feedbackHolder.classList.remove('show'); feedbackHolder.classList.remove('show');
} }
}); });

View File

@@ -1,135 +0,0 @@
'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 & {
electron_bridge: CompatElectronBridge;
narrow: {
by_subject?: (target_id: number, opts: {trigger?: string}) => void;
by_topic?: (target_id: number, opts: {trigger?: string}) => void;
};
page_params?: {
default_language?: string;
};
raw_electron_bridge: ElectronBridge;
};
const electron_bridge: CompatElectronBridge = {
...zulipWindow.raw_electron_bridge,
get idle_on_system(): boolean {
return this.get_idle_on_system();
},
get last_active_on_system(): number {
return this.get_last_active_on_system();
},
get send_notification_reply_message_supported(): boolean {
return this.get_send_notification_reply_message_supported();
},
set send_notification_reply_message_supported(value: boolean) {
this.set_send_notification_reply_message_supported(value);
}
};
zulipWindow.electron_bridge = electron_bridge;
(async () => {
if (document.readyState === 'loading') {
await new Promise(resolve => {
document.addEventListener('DOMContentLoaded', () => {
resolve();
});
});
}
const {page_params} = zulipWindow;
if (page_params) {
electron_bridge.send_event('zulip-loaded', {
serverLanguage: page_params.default_language
});
}
})();
electron_bridge.on_event('narrow-by-topic', (id: number) => {
const {narrow} = zulipWindow;
const narrowByTopic = narrow.by_topic || narrow.by_subject;
narrowByTopic(id, {trigger: 'notification'});
});
function attributeListener<T extends EventTarget>(type: string): PropertyDescriptor {
const symbol = Symbol('on' + type);
function listener(this: T, ev: Event): void {
if ((this as any)[symbol].call(this, ev) === false) {
ev.preventDefault();
}
}
return {
configurable: true,
enumerable: true,
get(this: T) {
return (this as any)[symbol];
},
set(this: T, value: unknown) {
if (typeof value === 'function') {
if (!(symbol in this)) {
this.addEventListener(type, listener);
}
(this as any)[symbol] = value;
} else if (symbol in this) {
this.removeEventListener(type, listener);
delete (this as any)[symbol];
}
}
};
}
const NativeNotification = Notification;
class InjectedNotification extends EventTarget {
constructor(title: string, options?: NotificationOptions) {
super();
Object.assign(
this,
electron_bridge.new_notification(title, options, (type: string, eventInit: EventInit) =>
this.dispatchEvent(new Event(type, eventInit))
)
);
}
static get maxActions(): number {
return NativeNotification.maxActions;
}
static get permission(): NotificationPermission {
return NativeNotification.permission;
}
static async requestPermission(callback?: NotificationPermissionCallback): Promise<NotificationPermission> {
if (callback) {
callback(await Promise.resolve(NativeNotification.permission));
}
return NativeNotification.permission;
}
}
Object.defineProperties(InjectedNotification.prototype, {
onclick: attributeListener('click'),
onclose: attributeListener('close'),
onerror: attributeListener('error'),
onshow: attributeListener('show')
});
window.Notification = InjectedNotification as any;
})();

View File

@@ -1,27 +1,27 @@
import {ipcRenderer, remote, clipboard} from 'electron'; 'use strict';
import {feedbackHolder} from './feedback';
import path from 'path'; import { ipcRenderer, remote, clipboard, shell } from 'electron';
import escape from 'escape-html'; import { feedbackHolder } from './feedback';
import isDev from 'electron-is-dev';
const {session, app, Menu, dialog} = remote; import path = require('path');
import escape = require('escape-html');
import isDev = require('electron-is-dev');
const { session, app, Menu, dialog } = remote;
// eslint-disable-next-line import/no-unassigned-import // eslint-disable-next-line import/no-unassigned-import
import './tray'; require('./tray');
import * as DomainUtil from './utils/domain-util'; import DomainUtil = require('./utils/domain-util');
import WebView from './components/webview'; import WebView = require('./components/webview');
import ServerTab from './components/server-tab'; import ServerTab = require('./components/server-tab');
import FunctionalTab from './components/functional-tab'; import FunctionalTab = require('./components/functional-tab');
import * as ConfigUtil from './utils/config-util'; import ConfigUtil = require('./utils/config-util');
import * as DNDUtil from './utils/dnd-util'; import DNDUtil = require('./utils/dnd-util');
import ReconnectUtil from './utils/reconnect-util'; import ReconnectUtil = require('./utils/reconnect-util');
import Logger from './utils/logger-util'; import Logger = require('./utils/logger-util');
import * as CommonUtil from './utils/common-util'; import CommonUtil = require('./utils/common-util');
import * as EnterpriseUtil from './utils/enterprise-util'; import EnterpriseUtil = require('./utils/enterprise-util');
import * as LinkUtil from './utils/link-util'; import Messages = require('./../../resources/messages');
import * as Messages from '../../resources/messages';
import type {DNDSettings} from './utils/dnd-util';
interface FunctionalTabProps { interface FunctionalTabProps {
name: string; name: string;
@@ -29,7 +29,11 @@ interface FunctionalTabProps {
url: string; url: string;
} }
interface SettingsOptions extends DNDSettings { interface AnyObject {
[key: string]: any;
}
interface SettingsOptions {
autoHideMenubar: boolean; autoHideMenubar: boolean;
trayIcon: boolean; trayIcon: boolean;
useManualProxy: boolean; useManualProxy: boolean;
@@ -39,17 +43,25 @@ interface SettingsOptions extends DNDSettings {
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: DNDSettings; dndPreviousSettings: {
showNotification: boolean;
silent: boolean;
flashTaskbarOnMessage?: boolean;
};
downloadsPath: string; downloadsPath: string;
showDownloadFolder: boolean;
quitOnClose: boolean; quitOnClose: boolean;
promptDownload: boolean; flashTaskbarOnMessage?: boolean;
dockBouncing?: boolean; dockBouncing?: boolean;
loading?: AnyObject;
} }
const logger = new Logger({ const logger = new Logger({
@@ -58,7 +70,7 @@ const logger = new Logger({
}); });
const rendererDirectory = path.resolve(__dirname, '..'); const rendererDirectory = path.resolve(__dirname, '..');
export type ServerOrFunctionalTab = ServerTab | FunctionalTab; type ServerOrFunctionalTab = ServerTab | FunctionalTab;
class ServerManagerView { class ServerManagerView {
$addServerButton: HTMLButtonElement; $addServerButton: HTMLButtonElement;
@@ -79,10 +91,10 @@ class ServerManagerView {
$sidebar: Element; $sidebar: Element;
$fullscreenPopup: Element; $fullscreenPopup: Element;
$fullscreenEscapeKey: string; $fullscreenEscapeKey: string;
loading: Set<string>; loading: AnyObject;
activeTabIndex: number; activeTabIndex: number;
tabs: ServerOrFunctionalTab[]; tabs: ServerOrFunctionalTab[];
functionalTabs: Map<string, number>; functionalTabs: AnyObject;
tabIndex: number; tabIndex: number;
presetOrgs: string[]; presetOrgs: string[];
constructor() { constructor() {
@@ -117,29 +129,29 @@ 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 = new Set(); this.loading = {};
this.activeTabIndex = -1; this.activeTabIndex = -1;
this.tabs = []; this.tabs = [];
this.presetOrgs = []; this.presetOrgs = [];
this.functionalTabs = new Map(); this.functionalTabs = {};
this.tabIndex = 0; this.tabIndex = 0;
} }
async init(): Promise<void> { init(): void {
await this.loadProxy(); this.loadProxy().then(() => {
this.initDefaultSettings(); this.initDefaultSettings();
this.initSidebar(); this.initSidebar();
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();
});
} }
async loadProxy(): Promise<void> { loadProxy(): Promise<boolean> {
return new Promise(resolve => {
// To change proxyEnable to useManualProxy in older versions // To change proxyEnable to useManualProxy in older versions
const proxyEnabledOld = ConfigUtil.isConfigItemExists('useProxy'); const proxyEnabledOld = ConfigUtil.isConfigItemExists('useProxy');
if (proxyEnabledOld) { if (proxyEnabledOld) {
@@ -147,24 +159,24 @@ class ServerManagerView {
if (proxyEnableOldState) { if (proxyEnableOldState) {
ConfigUtil.setConfigItem('useManualProxy', true); ConfigUtil.setConfigItem('useManualProxy', true);
} }
ConfigUtil.removeConfigItem('useProxy'); ConfigUtil.removeConfigItem('useProxy');
} }
const proxyEnabled = ConfigUtil.getConfigItem('useManualProxy') || ConfigUtil.getConfigItem('useSystemProxy'); const proxyEnabled = ConfigUtil.getConfigItem('useManualProxy') || ConfigUtil.getConfigItem('useSystemProxy');
if (proxyEnabled) { if (proxyEnabled) {
await session.fromPartition('persist:webviewsession').setProxy({ session.fromPartition('persist:webviewsession').setProxy({
pacScript: ConfigUtil.getConfigItem('proxyPAC', ''), pacScript: ConfigUtil.getConfigItem('proxyPAC', ''),
proxyRules: ConfigUtil.getConfigItem('proxyRules', ''), proxyRules: ConfigUtil.getConfigItem('proxyRules', ''),
proxyBypassRules: ConfigUtil.getConfigItem('proxyBypass', '') proxyBypassRules: ConfigUtil.getConfigItem('proxyBypass', '')
}); }, resolve);
} else { } else {
await session.fromPartition('persist:webviewsession').setProxy({ session.fromPartition('persist:webviewsession').setProxy({
pacScript: '', pacScript: '',
proxyRules: '', proxyRules: '',
proxyBypassRules: '' proxyBypassRules: ''
}); }, resolve);
} }
});
} }
// Settings are initialized only when user clicks on General/Server/Network section settings // Settings are initialized only when user clicks on General/Server/Network section settings
@@ -195,8 +207,8 @@ class ServerManagerView {
silent: false silent: false
}, },
downloadsPath: `${app.getPath('downloads')}`, downloadsPath: `${app.getPath('downloads')}`,
quitOnClose: false, showDownloadFolder: false,
promptDownload: false quitOnClose: false
}; };
// Platform specific settings // Platform specific settings
@@ -216,12 +228,13 @@ class ServerManagerView {
settingOptions.autoHideMenubar = false; settingOptions.autoHideMenubar = false;
} }
for (const [setting, value] of Object.entries(settingOptions)) { for (const i in settingOptions) {
// Give preference to defaults defined in global_config.json const setting = i as keyof SettingsOptions;
// 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) {
ConfigUtil.setConfigItem(setting, value); ConfigUtil.setConfigItem(setting, settingOptions[setting]);
} }
} }
} }
@@ -231,122 +244,110 @@ class ServerManagerView {
this.toggleSidebar(showSidebar); this.toggleSidebar(showSidebar);
} }
// Remove the stale UA string from the disk if the app is not freshly async queueDomain(domain: any): Promise<boolean> {
// installed. This should be removed in a further release. // allows us to start adding multiple domains to the app simultaneously
removeUAfromDisk(): void {
ConfigUtil.removeConfigItem('userAgent');
}
async queueDomain(domain: string): Promise<boolean> {
// 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 (error) { } catch (err) {
logger.error(error); logger.error(err);
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({ dialog.showMessageBox({
type: 'question', type: 'question',
buttons: ['Yes', 'Later'], buttons: ['Yes', 'Later'],
defaultId: 0, defaultId: 0,
message: 'New server' + (domainsAdded.length > 1 ? 's' : '') + ' added. Reload app now?' message: 'New server' + (domainsAdded.length > 1 ? 's' : '') + ' added. Reload app now?'
}); }, response => {
if (response === 0) { if (response === 0) {
ipcRenderer.send('reload-full-app'); ipcRenderer.send('reload-full-app');
} }
});
} else { } else {
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'); this.openSettings('AddServer');
} }
} }
} }
async initTabs(): Promise<void> { initTabs(): 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 (let i = 0; i < servers.length; i++) {
this.initServer(server, i); this.initServer(servers[i], 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
// `checkDomain()` and `webview.load()` for lastActiveTab before the others DomainUtil.updateSavedServer(servers[lastActiveTab].url, lastActiveTab);
await DomainUtil.updateSavedServer(servers[lastActiveTab].url, lastActiveTab);
this.activateTab(lastActiveTab); this.activateTab(lastActiveTab);
await Promise.all(servers.map(async (server, i) => { for (let i = 0; i < servers.length; 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) {
return; continue;
} }
DomainUtil.updateSavedServer(servers[i].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
await this.openSettings('AddServer'); this.openSettings('AddServer');
} else { } else {
this.showLoading(true); this.showLoading(true);
} }
} }
initServer(server: DomainUtil.ServerConf, index: number): void { initServer(server: any, 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',
icon: server.icon, icon: server.icon,
name: CommonUtil.decodeString(server.alias), name: server.alias,
$root: this.$tabsContainer, $root: this.$tabsContainer,
onClick: this.activateLastTab.bind(this, index), onClick: this.activateLastTab.bind(this, index),
index, index,
@@ -360,20 +361,16 @@ 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) =>
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) { if (!loading && this.loading[url]) {
this.loading.add(url); this.loading[url] = false;
} else { } else if (loading && !this.loading[url]) {
this.loading.delete(url); this.loading[url] = true;
} }
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 +378,7 @@ class ServerManagerView {
preload: true preload: true
}) })
})); }));
this.loading.add(server.url); this.loading[server.url] = true;
} }
initActions(): void { initActions(): void {
@@ -397,7 +394,6 @@ 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);
}); });
@@ -412,11 +408,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', async () => { this.$addServerButton.addEventListener('click', () => {
await this.openSettings('AddServer'); this.openSettings('AddServer');
}); });
this.$settingsButton.addEventListener('click', async () => { this.$settingsButton.addEventListener('click', () => {
await this.openSettings('General'); this.openSettings('General');
}); });
this.$backButton.addEventListener('click', () => { this.$backButton.addEventListener('click', () => {
this.tabs[this.activeTabIndex].webview.back(); this.tabs[this.activeTabIndex].webview.back();
@@ -446,9 +442,10 @@ 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 /*
// increment beyond the size of the sidebar org array and throw an index parameter needed because webview[data-tab-id] can increment
// error beyond size of sidebar org array and throw error
*/
const $altIcon = document.createElement('div'); const $altIcon = document.createElement('div');
const $parent = $img.parentElement; const $parent = $img.parentElement;
@@ -466,7 +463,7 @@ class ServerManagerView {
$altIcon.classList.add('server-icon'); $altIcon.classList.add('server-icon');
$altIcon.classList.add('alt-icon'); $altIcon.classList.add('alt-icon');
$img.remove(); $parent.removeChild($img);
$parent.append($altIcon); $parent.append($altIcon);
this.addContextMenu($altIcon as HTMLImageElement, index); this.addContextMenu($altIcon as HTMLImageElement, index);
@@ -480,8 +477,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 +487,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 +502,12 @@ class ServerManagerView {
} }
openFunctionalTab(tabProps: FunctionalTabProps): void { openFunctionalTab(tabProps: FunctionalTabProps): void {
if (this.functionalTabs.has(tabProps.name)) { if (this.functionalTabs[tabProps.name] !== undefined) {
this.activateTab(this.functionalTabs.get(tabProps.name)); this.activateTab(this.functionalTabs[tabProps.name]);
return; return;
} }
this.functionalTabs.set(tabProps.name, this.tabs.length); this.functionalTabs[tabProps.name] = this.tabs.length;
const tabIndex = this.getTabIndex(); const tabIndex = this.getTabIndex();
@@ -519,28 +516,27 @@ class ServerManagerView {
materialIcon: tabProps.materialIcon, materialIcon: tabProps.materialIcon,
name: tabProps.name, name: tabProps.name,
$root: this.$tabsContainer, $root: this.$tabsContainer,
index: this.functionalTabs.get(tabProps.name), index: this.functionalTabs[tabProps.name],
tabIndex, tabIndex,
onClick: this.activateTab.bind(this, this.functionalTabs.get(tabProps.name)), onClick: this.activateTab.bind(this, this.functionalTabs[tabProps.name]),
onDestroy: this.destroyTab.bind(this, tabProps.name, this.functionalTabs.get(tabProps.name)), onDestroy: this.destroyTab.bind(this, tabProps.name, this.functionalTabs[tabProps.name]),
webview: new WebView({ webview: new WebView({
$root: this.$webviewsContainer, $root: this.$webviewsContainer,
index: this.functionalTabs.get(tabProps.name), index: this.functionalTabs[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.get(tabProps.name) === this.activeTabIndex; return this.functionalTabs[tabProps.name] === this.activeTabIndex;
}, },
switchLoading: (loading: boolean, url: string) => { switchLoading: (loading: AnyObject, url: string) => {
if (loading) { if (!loading && this.loading[url]) {
this.loading.add(url); this.loading[url] = false;
} else { } else if (loading && !this.loading[url]) {
this.loading.delete(url); this.loading[url] = true;
} }
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),
@@ -553,17 +549,17 @@ 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.get(tabProps.name)); this.activateTab(this.functionalTabs[tabProps.name]);
} }
async openSettings(nav = 'General'): Promise<void> { openSettings(nav = 'General'): void {
this.openFunctionalTab({ this.openFunctionalTab({
name: 'Settings', name: 'Settings',
materialIcon: 'settings', materialIcon: 'settings',
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.get('Settings')].webview.send('switch-settings-nav', nav); this.tabs[this.functionalTabs.Settings].webview.send('switch-settings-nav', nav);
} }
openAbout(): void { openAbout(): void {
@@ -588,7 +584,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.
@@ -598,7 +594,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);
@@ -615,27 +611,24 @@ 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 (_) { } catch (err) {
} }
this.activeTabIndex = index; this.activeTabIndex = index;
this.tabs[index].activate(); this.tabs[index].activate();
this.showLoading(this.loading.has(this.tabs[this.activeTabIndex].webview.props.url)); this.showLoading(this.loading[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
@@ -665,7 +658,7 @@ class ServerManagerView {
this.tabs[index].destroy(); this.tabs[index].destroy();
delete this.tabs[index]; delete this.tabs[index];
this.functionalTabs.delete(name); delete this.functionalTabs[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) {
@@ -680,21 +673,21 @@ class ServerManagerView {
// Clear global variables // Clear global variables
this.activeTabIndex = -1; this.activeTabIndex = -1;
this.tabs = []; this.tabs = [];
this.functionalTabs.clear(); this.functionalTabs = {};
// Clear DOM elements // Clear DOM elements
this.$tabsContainer.innerHTML = ''; this.$tabsContainer.innerHTML = '';
this.$webviewsContainer.innerHTML = ''; this.$webviewsContainer.innerHTML = '';
} }
async reloadView(): Promise<void> { reloadView(): 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();
await this.initTabs(); this.initTabs();
this.initServerActions(); this.initServerActions();
} }
@@ -717,9 +710,11 @@ class ServerManagerView {
ipcRenderer.send('update-badge', messageCountAll); ipcRenderer.send('update-badge', messageCountAll);
} }
updateGeneralSettings(setting: string, value: unknown): void { updateGeneralSettings(setting: string, value: any): void {
if (this.getActiveWebview()) { const selector = 'webview:not([class*=disabled])';
const webContents = this.getActiveWebview().getWebContents(); const webview: Electron.WebviewTag = document.querySelector(selector);
if (webview) {
const webContents = webview.getWebContents();
webContents.send(setting, value); webContents.send(setting, value);
} }
} }
@@ -743,40 +738,35 @@ class ServerManagerView {
return !(url.endsWith('/login/') || this.tabs[tabIndex].webview.loading); return !(url.endsWith('/login/') || this.tabs[tabIndex].webview.loading);
} }
getActiveWebview(): Electron.WebviewTag {
const selector = 'webview:not(.disabled)';
const webview: Electron.WebviewTag = document.querySelector(selector);
return webview;
}
addContextMenu($serverImg: HTMLImageElement, index: number): void { addContextMenu($serverImg: HTMLImageElement, index: number): void {
$serverImg.addEventListener('contextmenu', event => { $serverImg.addEventListener('contextmenu', e => {
event.preventDefault(); e.preventDefault();
const template = [ const template = [
{ {
label: 'Disconnect organization', label: 'Disconnect organization',
click: async () => { click: () => {
const {response} = await dialog.showMessageBox({ dialog.showMessageBox({
type: 'warning', type: 'warning',
buttons: ['YES', 'NO'], buttons: ['YES', 'NO'],
defaultId: 0, defaultId: 0,
message: 'Are you sure you want to disconnect this organization?' message: 'Are you sure you want to disconnect this organization?'
}); }, response => {
if (response === 0) { if (response === 0) {
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);
} }
} }
});
} }
}, },
{ {
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();
} }
@@ -789,85 +779,47 @@ 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: Array<[string, (webview: WebView) => void]> = [ const webviewListeners: AnyObject = {
['webview-reload', webview => webview.reload()], 'webview-reload': 'reload',
['back', webview => webview.back()], back: 'back',
['focus', webview => webview.focus()], focus: 'focus',
['forward', webview => webview.forward()], forward: 'forward',
['zoomIn', webview => webview.zoomIn()], zoomIn: 'zoomIn',
['zoomOut', webview => webview.zoomOut()], zoomOut: 'zoomOut',
['zoomActualSize', webview => webview.zoomActualSize()], zoomActualSize: 'zoomActualSize',
['log-out', webview => webview.logOut()], 'log-out': 'logOut',
['shortcut', webview => webview.showShortcut()], shortcut: 'showShortcut',
['tab-devtools', webview => webview.openDevTools()] 'tab-devtools': 'openDevTools'
]; };
for (const [channel, listener] of webviewListeners) { for (const key in webviewListeners) {
ipcRenderer.on(channel, () => { ipcRenderer.on(key, () => {
const activeWebview = this.tabs[this.activeTabIndex].webview; const activeWebview = this.tabs[this.activeTabIndex].webview;
if (activeWebview) { if (activeWebview) {
listener(activeWebview); activeWebview[webviewListeners[key] as string]();
} }
}); });
} }
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', (
event: Event,
{webContentsId, origin, permission}: {
webContentsId: number | null;
origin: string;
permission: string;
},
rendererCallbackId: number
) => {
const grant = webContentsId === null ?
origin === 'null' && permission === 'notifications' :
this.tabs.some(
({webview}) =>
!webview.loading &&
webview.$el.getWebContentsId() === webContentsId &&
webview.props.hasPermission?.(origin, permission)
);
console.log(
grant ? 'Granted' : 'Denied', 'permissions request for',
permission, 'from', origin
);
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', async (event: Event, settingNav: string) => { ipcRenderer.on('open-settings', (event: Event, settingNav: string) => {
await this.openSettings(settingNav); this.openSettings(settingNav);
}); });
ipcRenderer.on('open-about', this.openAbout.bind(this)); ipcRenderer.on('open-about', this.openAbout.bind(this));
ipcRenderer.on('open-help', async () => { ipcRenderer.on('open-help', () => {
// Open help page of current active server // Open help page of current active server
await LinkUtil.openBrowser(new URL('https://zulipchat.com/help/')); const helpPage = this.getCurrentActiveServer() + '/help';
shell.openExternal(helpPage);
}); });
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));
@@ -886,20 +838,18 @@ class ServerManagerView {
this.activateLastTab(index); this.activateLastTab(index);
}); });
ipcRenderer.on('open-org-tab', async () => { ipcRenderer.on('open-org-tab', () => {
await this.openSettings('AddServer'); this.openSettings('AddServer');
}); });
ipcRenderer.on('reload-proxy', async (event: Event, showAlert: boolean) => { ipcRenderer.on('reload-proxy', (event: Event, showAlert: boolean) => {
await this.loadProxy(); this.loadProxy().then(() => {
if (showAlert) { if (showAlert) {
await dialog.showMessageBox({ alert('Proxy settings saved!');
message: 'Proxy settings saved!',
buttons: ['OK']
});
ipcRenderer.send('reload-full-app'); ipcRenderer.send('reload-full-app');
} }
}); });
});
ipcRenderer.on('toggle-sidebar', (event: Event, show: boolean) => { ipcRenderer.on('toggle-sidebar', (event: Event, show: boolean) => {
// Toggle the left sidebar // Toggle the left sidebar
@@ -914,8 +864,8 @@ class ServerManagerView {
webviews.forEach(webview => { webviews.forEach(webview => {
try { try {
webview.setAudioMuted(state); webview.setAudioMuted(state);
} catch (_) { } catch (err) {
// Webview is not ready yet // webview is not ready yet
webview.addEventListener('dom-ready', () => { webview.addEventListener('dom-ready', () => {
webview.setAudioMuted(state); webview.setAudioMuted(state);
}); });
@@ -931,28 +881,31 @@ 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: DNDSettings) => { ipcRenderer.on('toggle-dnd', (event: Event, state: boolean, newSettings: SettingsOptions) => {
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 selector = 'webview:not([class*=disabled])';
const webview: Electron.WebviewTag = document.querySelector(selector);
const webContents = webview.getWebContents();
webContents.send('toggle-dnd', state, newSettings); webContents.send('toggle-dnd', state, newSettings);
}); });
ipcRenderer.on('update-realm-name', (event: Event, serverURL: string, realmName: string) => { ipcRenderer.on('update-realm-name', (event: Event, serverURL: string, realmName: string) => {
DomainUtil.getDomains().forEach((domain: DomainUtil.ServerConf, index: number) => { // TODO: TypeScript - Type annotate getDomains() or this domain paramter.
DomainUtil.getDomains().forEach((domain: any, index: number) => {
if (domain.url.includes(serverURL)) { if (domain.url.includes(serverURL)) {
const serverTooltipSelector = '.tab .server-tooltip'; const serverTooltipSelector = `.tab .server-tooltip`;
const serverTooltips = document.querySelectorAll(serverTooltipSelector); const serverTooltips = document.querySelectorAll(serverTooltipSelector);
serverTooltips[index].innerHTML = escape(realmName); serverTooltips[index].innerHTML = escape(realmName);
this.tabs[index].props.name = escape(realmName); this.tabs[index].props.name = escape(realmName);
this.tabs[index].webview.props.name = realmName; this.tabs[index].webview.props.name = realmName;
domain.alias = escape(realmName); domain.alias = escape(realmName);
DomainUtil.updateDomain(index, domain); DomainUtil.db.push(`/domains[${index}]`, domain, true);
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,
@@ -963,17 +916,18 @@ class ServerManagerView {
}); });
ipcRenderer.on('update-realm-icon', (event: Event, serverURL: string, iconURL: string) => { ipcRenderer.on('update-realm-icon', (event: Event, serverURL: string, iconURL: string) => {
DomainUtil.getDomains().forEach(async (domain, index) => { // TODO: TypeScript - Type annotate getDomains() or this domain paramter.
DomainUtil.getDomains().forEach((domain: any, index: number) => {
if (domain.url.includes(serverURL)) { if (domain.url.includes(serverURL)) {
const localIconUrl: string = await DomainUtil.saveServerIcon({ DomainUtil.saveServerIcon(iconURL).then((localIconUrl: string) => {
url: serverURL, const serverImgsSelector = `.tab .server-icons`;
icon: iconURL
});
const serverImgsSelector = '.tab .server-icons';
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.updateDomain(index, domain); DomainUtil.db.push(`/domains[${index}]`, domain, true);
DomainUtil.reloadDB();
});
} }
}); });
}); });
@@ -1023,10 +977,8 @@ 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));
}); });
@@ -1038,46 +990,41 @@ class ServerManagerView {
clipboard.writeText(this.getCurrentActiveServer()); clipboard.writeText(this.getCurrentActiveServer());
}); });
ipcRenderer.on('new-server', async () => { ipcRenderer.on('new-server', () => {
await this.openSettings('AddServer'); this.openSettings('AddServer');
}); });
// Redo and undo functionality since the default API doesn't work on macOS ipcRenderer.on('set-active', () => {
ipcRenderer.on('undo', () => {
return this.getActiveWebview().undo();
});
ipcRenderer.on('redo', () => {
return this.getActiveWebview().redo();
});
ipcRenderer.on('set-active', async () => {
const webviews: NodeListOf<Electron.WebviewTag> = document.querySelectorAll('webview'); const webviews: NodeListOf<Electron.WebviewTag> = document.querySelectorAll('webview');
await Promise.all([...webviews].map(async webview => webview.send('set-active'))); webviews.forEach(webview => {
webview.send('set-active');
});
}); });
ipcRenderer.on('set-idle', async () => { ipcRenderer.on('set-idle', () => {
const webviews: NodeListOf<Electron.WebviewTag> = document.querySelectorAll('webview'); const webviews: NodeListOf<Electron.WebviewTag> = document.querySelectorAll('webview');
await Promise.all([...webviews].map(async webview => webview.send('set-idle'))); webviews.forEach(webview => {
webview.send('set-idle');
});
}); });
ipcRenderer.on('open-network-settings', async () => { ipcRenderer.on('open-network-settings', () => {
await this.openSettings('Network'); this.openSettings('Network');
}); });
} }
} }
window.addEventListener('load', async () => { window.addEventListener('load', () => {
// Only start electron-connect (auto reload on change) when its ran const serverManagerView = new ServerManagerView();
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`
if (isDev && !remote.getGlobal('process').argv.includes('--no-electron-connect')) { const mainProcessArgv = remote.getGlobal('process').argv;
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 = new ServerManagerView();

View File

@@ -1,31 +1,34 @@
import {ipcRenderer} from 'electron'; 'use strict';
import { ipcRenderer } from 'electron';
import { import {
appId, customReply, focusCurrentServer, parseReply appId, customReply, focusCurrentServer, parseReply, setupReply
} from './helpers'; } from './helpers';
import MacNotifier from 'node-mac-notifier'; import url = require('url');
import * as ConfigUtil from '../utils/config-util'; import MacNotifier = require('node-mac-notifier');
import electron_bridge from '../electron-bridge'; import ConfigUtil = require('../utils/config-util');
type ReplyHandler = (response: string) => void; type ReplyHandler = (response: string) => void;
type ClickHandler = () => void; type ClickHandler = () => void;
let replyHandler: ReplyHandler; let replyHandler: ReplyHandler;
let clickHandler: ClickHandler; let clickHandler: ClickHandler;
declare const window: ZulipWebWindow;
interface NotificationHandlerArgs { interface NotificationHandlerArgs {
response: string; response: string;
} }
class DarwinNotification { class DarwinNotification {
tag: number; tag: string;
constructor(title: string, options: NotificationOptions) { constructor(title: string, opts: NotificationOptions) {
const silent: boolean = ConfigUtil.getConfigItem('silent') || false; const silent: boolean = ConfigUtil.getConfigItem('silent') || false;
const {icon} = options; const { host, protocol } = location;
const profilePic = new URL(icon, location.href).href; const { icon } = opts;
const profilePic = url.resolve(`${protocol}//${host}`, icon);
this.tag = Number.parseInt(options.tag, 10); this.tag = opts.tag;
const notification = new MacNotifier(title, Object.assign(options, { const notification = new MacNotifier(title, Object.assign(opts, {
bundleId: appId, bundleId: appId,
canReply: true, canReply: true,
silent, silent,
@@ -33,7 +36,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();
@@ -55,23 +58,23 @@ class DarwinNotification {
return ConfigUtil.getConfigItem('showNotification') ? 'granted' : 'denied'; return ConfigUtil.getConfigItem('showNotification') ? 'granted' : 'denied';
} }
get onreply(): ReplyHandler {
return replyHandler;
}
set onreply(handler: ReplyHandler) { set onreply(handler: ReplyHandler) {
replyHandler = handler; replyHandler = handler;
} }
get onclick(): ClickHandler { get onreply(): ReplyHandler {
return clickHandler; return replyHandler;
} }
set onclick(handler: ClickHandler) { set onclick(handler: ClickHandler) {
clickHandler = handler; clickHandler = handler;
} }
// Not something that is common or get onclick(): ClickHandler {
return clickHandler;
}
// 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,15 +87,15 @@ class DarwinNotification {
} }
} }
async notificationHandler({response}: NotificationHandlerArgs): Promise<void> { notificationHandler({ response }: NotificationHandlerArgs): void {
response = await parseReply(response); response = parseReply(response);
focusCurrentServer(); focusCurrentServer();
if (electron_bridge.send_notification_reply_message_supported) { if (window.electron_bridge.send_notification_reply_message_supported) {
electron_bridge.send_event('send_notification_reply_message', this.tag, response); window.electron_bridge.send_event('send_notification_reply_message', this.tag, response);
return; return;
} }
electron_bridge.emit('narrow-by-topic', this.tag); setupReply(this.tag);
if (replyHandler) { if (replyHandler) {
replyHandler(response); replyHandler(response);
return; return;
@@ -101,7 +104,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

View File

@@ -1,24 +1,26 @@
import {ipcRenderer} from 'electron'; 'use strict';
import {focusCurrentServer} from './helpers';
import * as ConfigUtil from '../utils/config-util'; import { ipcRenderer } from 'electron';
import { focusCurrentServer } from './helpers';
import ConfigUtil = require('../utils/config-util');
const NativeNotification = window.Notification; const NativeNotification = window.Notification;
export default class BaseNotification extends NativeNotification { class BaseNotification extends NativeNotification {
constructor(title: string, options: NotificationOptions) { constructor(title: string, opts: NotificationOptions) {
options.silent = true; opts.silent = true;
super(title, options); super(title, opts);
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');
}); });
} }
static async requestPermission(): Promise<NotificationPermission> { static requestPermission(): void {
return this.permission; return; // eslint-disable-line no-useless-return
} }
// Override default Notification permission // Override default Notification permission
@@ -26,3 +28,5 @@ export default class BaseNotification extends NativeNotification {
return ConfigUtil.getConfigItem('showNotification') ? 'granted' : 'denied'; return ConfigUtil.getConfigItem('showNotification') ? 'granted' : 'denied';
} }
} }
export = BaseNotification;

View File

@@ -1,6 +1,6 @@
import {remote} from 'electron'; import { remote } from 'electron';
import Logger from '../utils/logger-util'; import Logger = require('../utils/logger-util');
const logger = new Logger({ const logger = new Logger({
file: 'errors.log', file: 'errors.log',
@@ -14,28 +14,37 @@ 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
// sync=True for a synchronous getJSON request
// 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 function loadBots(sync = false): void {
const { $ } = window;
botsList.length = 0; botsList.length = 0;
const response = await fetch('/json/users'); if (sync) {
if (response.ok) { $.ajaxSetup({async: false});
const {members} = await response.json(); }
members.forEach(({is_bot, full_name}: {[key: string]: unknown}) => { $.getJSON('/json/users')
if (is_bot && typeof full_name === 'string') { .done((data: any) => {
const bot = `@${full_name}`; const { members } = data;
members.forEach((membersRow: any) => {
if (membersRow.is_bot) {
const bot = `@${membersRow.full_name}`;
const mention = `@**${bot.replace(/^@/, '')}**`; const mention = `@**${bot.replace(/^@/, '')}**`;
botsList.push([bot, mention]); botsList.push([bot, mention]);
} }
}); });
botsListLoaded = true; botsListLoaded = true;
} else { })
logger.log('Load bots request failed: ', await response.text()); .fail((error: any) => {
logger.log('Load bots request status: ', response.status); logger.log('Load bots request failed: ', error.responseText);
logger.log('Load bots request status: ', error.statusText);
});
if (sync) {
$.ajaxSetup({async: true});
} }
} }
export function checkElements(...elements: unknown[]): boolean { export function checkElements(...elements: any[]): 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 +55,14 @@ export function checkElements(...elements: unknown[]): 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,18 +77,19 @@ 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); // TODO: TypeScript: currentWindow of type BrowserWindow doesn't
// have a .send() property per typescript.
(currentWindow as any).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**
// bot mentions are not yet supported // bot mentions are not yet supported
export async function parseReply(reply: string): Promise<string> { export function parseReply(reply: string): string {
const usersDiv = document.querySelectorAll('#user_presences li'); const usersDiv = document.querySelectorAll('#user_presences li');
const streamHolder = document.querySelectorAll('#stream_filters li'); const streamHolder = document.querySelectorAll('#stream_filters li');
@@ -118,9 +128,9 @@ export async function parseReply(reply: string): Promise<string> {
reply = reply.replace(regex, streamMention); reply = reply.replace(regex, streamMention);
}); });
// If botsList isn't completely loaded yet, make a request for list // If botsList isn't completely loaded yet, make a synchronous getJSON request for list
if (!botsListLoaded) { if (botsListLoaded === false) {
await loadBots(); loadBots(true);
} }
// Iterate for every bot name and replace in reply // Iterate for every bot name and replace in reply
@@ -135,3 +145,9 @@ export async function parseReply(reply: string): Promise<string> {
reply = reply.replace(/\\n/, '\n'); reply = reply.replace(/\\n/, '\n');
return reply; return reply;
} }
export function setupReply(id: string): void {
const { narrow } = window;
const narrowByTopic = narrow.by_topic || narrow.by_subject;
narrowByTopic(id, { trigger: 'notification' });
}

View File

@@ -1,73 +1,25 @@
import {remote} from 'electron'; 'use strict';
import electron_bridge from '../electron-bridge';
import {appId, loadBots} from './helpers';
import DefaultNotification from './default-notification'; import { remote } from 'electron';
const {app} = remote; import * as params from '../utils/params-util';
import { appId, loadBots } from './helpers';
import DefaultNotification = require('./default-notification');
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.
app.setAppUserModelId(appId); app.setAppUserModelId(appId);
let Notification = DefaultNotification; window.Notification = DefaultNotification;
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
Notification = require('./darwin-notifications'); window.Notification = require('./darwin-notifications');
} }
export interface NotificationData { window.addEventListener('load', () => {
close: () => void; // eslint-disable-next-line no-undef, @typescript-eslint/camelcase
title: string; if (params.isPageParams() && page_params.realm_uri) {
dir: NotificationDirection; loadBots();
lang: string;
body: string;
tag: string;
image: string;
icon: string;
badge: string;
vibrate: readonly number[];
timestamp: number;
renotify: boolean;
silent: boolean;
requireInteraction: boolean;
data: unknown;
actions: readonly NotificationAction[];
}
export function newNotification(
title: string,
options: NotificationOptions | undefined,
dispatch: (type: string, eventInit: EventInit) => boolean
): NotificationData {
const notification = new Notification(title, options);
for (const type of ['click', 'close', 'error', 'show']) {
notification.addEventListener(type, (ev: Event) => {
if (!dispatch(type, ev)) {
ev.preventDefault();
} }
});
}
return {
close: () => notification.close(),
title: notification.title,
dir: notification.dir,
lang: notification.lang,
body: notification.body,
tag: notification.tag,
image: notification.image,
icon: notification.icon,
badge: notification.badge,
vibrate: notification.vibrate,
timestamp: notification.timestamp,
renotify: notification.renotify,
silent: notification.silent,
requireInteraction: notification.requireInteraction,
data: notification.data,
actions: notification.actions
};
}
electron_bridge.once('zulip-loaded', async () => {
await loadBots();
}); });

View File

@@ -1,10 +1,16 @@
import {ipcRenderer} from 'electron'; 'use strict';
export function init($reconnectButton: Element, $settingsButton: Element): void { import { ipcRenderer } from 'electron';
class NetworkTroubleshootingView {
init($reconnectButton: Element, $settingsButton: Element): void {
$reconnectButton.addEventListener('click', () => { $reconnectButton.addEventListener('click', () => {
ipcRenderer.send('forward-message', 'reload-viewer'); ipcRenderer.send('forward-message', 'reload-viewer');
}); });
$settingsButton.addEventListener('click', () => { $settingsButton.addEventListener('click', () => {
ipcRenderer.send('forward-message', 'open-settings'); ipcRenderer.send('forward-message', 'open-settings');
}); });
}
} }
export = new NetworkTroubleshootingView();

View File

@@ -1,26 +1,23 @@
'use-strict'; 'use-strict';
import {remote, OpenDialogOptions} from 'electron'; import { remote, OpenDialogOptions } from 'electron';
import path from 'path'; import path = require('path');
import BaseComponent from '../../components/base'; import BaseComponent = require('../../components/base');
import * as CertificateUtil from '../../utils/certificate-util'; import CertificateUtil = require('../../utils/certificate-util');
import * as DomainUtil from '../../utils/domain-util'; import DomainUtil = require('../../utils/domain-util');
import * as t from '../../utils/translation-util'; import t = require('../../utils/translation-util');
interface AddCertificateProps { const { dialog } = remote;
$root: Element;
}
const {dialog} = remote; class AddCertificate extends BaseComponent {
// TODO: TypeScript - Here props should be object type
export default class AddCertificate extends BaseComponent { props: any;
props: AddCertificateProps;
_certFile: string; _certFile: string;
$addCertificate: Element | null; $addCertificate: Element | null;
addCertificateButton: Element | null; addCertificateButton: Element | null;
serverUrl: HTMLInputElement | null; serverUrl: HTMLInputElement | null;
constructor(props: AddCertificateProps) { constructor(props: any) {
super(); super();
this.props = props; this.props = props;
this._certFile = ''; this._certFile = '';
@@ -49,7 +46,7 @@ export default class AddCertificate extends BaseComponent {
this.initListeners(); this.initListeners();
} }
async validateAndAdd(): Promise<void> { validateAndAdd(): 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,41 +56,45 @@ export default class AddCertificate extends BaseComponent {
if (!copy) { if (!copy) {
return; return;
} }
CertificateUtil.setCertificate(server, fileName); CertificateUtil.setCertificate(server, fileName);
this.serverUrl.value = ''; dialog.showMessageBox({
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'}`);
} }
} }
async addHandler(): Promise<void> { addHandler(): void {
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); dialog.showOpenDialog(showDialogOptions, selectedFile => {
if (!canceled) { if (selectedFile) {
this._certFile = filePaths[0] || ''; this._certFile = selectedFile[0] || '';
await this.validateAndAdd(); this.validateAndAdd();
} }
});
} }
initListeners(): void { initListeners(): void {
this.addCertificateButton.addEventListener('click', async () => { this.addCertificateButton.addEventListener('click', () => {
await this.addHandler(); this.addHandler();
}); });
this.serverUrl.addEventListener('keypress', async event => { this.serverUrl.addEventListener('keypress', event => {
if (event.key === 'Enter') { const EnterkeyCode = event.keyCode;
await this.addHandler();
if (EnterkeyCode === 13) {
this.addHandler();
} }
}); });
} }
} }
export = AddCertificate;

View File

@@ -1,44 +1,63 @@
import electron, {app} from 'electron'; 'use strict';
import { app } from 'electron';
import * as ConfigUtil from '../../utils/config-util'; import electron = require('electron');
import ConfigUtil = require('../../utils/config-util');
function showBadgeCount(messageCount: number, mainWindow: electron.BrowserWindow): void { let instance: BadgeSettings | any = null;
if (process.platform === 'win32') {
updateOverlayIcon(messageCount, mainWindow); class BadgeSettings {
constructor() {
if (instance) {
return instance;
} else { } else {
app.badgeCount = messageCount; instance = this;
} }
}
function hideBadgeCount(mainWindow: electron.BrowserWindow): void { return instance;
}
showBadgeCount(messageCount: number, mainWindow: electron.BrowserWindow): void {
if (process.platform === 'win32') {
this.updateOverlayIcon(messageCount, mainWindow);
} else {
// This should work on both macOS and Linux
app.setBadgeCount(messageCount);
}
}
hideBadgeCount(mainWindow: electron.BrowserWindow): void {
if (process.platform === 'darwin') {
app.setBadgeCount(0);
}
if (process.platform === 'win32') { if (process.platform === 'win32') {
mainWindow.setOverlayIcon(null, ''); mainWindow.setOverlayIcon(null, '');
} else {
app.badgeCount = 0;
} }
} }
export function updateBadge(badgeCount: number, mainWindow: electron.BrowserWindow): void { updateBadge(badgeCount: number, mainWindow: electron.BrowserWindow): void {
if (ConfigUtil.getConfigItem('badgeOption', true)) { if (ConfigUtil.getConfigItem('badgeOption', true)) {
showBadgeCount(badgeCount, mainWindow); this.showBadgeCount(badgeCount, mainWindow);
} else { } else {
hideBadgeCount(mainWindow); this.hideBadgeCount(mainWindow);
}
} }
}
function updateOverlayIcon(messageCount: number, mainWindow: electron.BrowserWindow): void { updateOverlayIcon(messageCount: number, mainWindow: electron.BrowserWindow): void {
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 {
mainWindow.webContents.send('render-taskbar-icon', messageCount); mainWindow.webContents.send('render-taskbar-icon', messageCount);
} }
} }
export function updateTaskbarIcon(data: string, text: string, mainWindow: electron.BrowserWindow): void { updateTaskbarIcon(data: string, text: string, mainWindow: electron.BrowserWindow): void {
const img = electron.nativeImage.createFromDataURL(data); const img = electron.nativeImage.createFromDataURL(data);
mainWindow.setOverlayIcon(img, text); mainWindow.setOverlayIcon(img, text);
}
} }
export = new BadgeSettings();

View File

@@ -1,17 +1,12 @@
import {ipcRenderer} from 'electron'; 'use strict';
import escape from 'escape-html';
import BaseComponent from '../../components/base'; import { ipcRenderer } from 'electron';
interface BaseSectionProps { import BaseComponent = require('../../components/base');
$element: HTMLElement;
disabled?: boolean;
value: boolean;
clickHandler: () => void;
}
export default class BaseSection extends BaseComponent { class BaseSection extends BaseComponent {
generateSettingOption(props: BaseSectionProps): void { // TODO: TypeScript - Here props should be object type
generateSettingOption(props: any): void {
const {$element, disabled, value, clickHandler} = props; const {$element, disabled, value, clickHandler} = props;
$element.innerHTML = ''; $element.innerHTML = '';
@@ -24,8 +19,8 @@ export default class BaseSection extends BaseComponent {
} }
} }
generateOptionTemplate(settingOption: boolean, disabled?: boolean): string { generateOptionTemplate(settingOption: boolean, disabled: boolean): string {
const label = disabled ? '<label class="disallowed" title="Setting locked by system administrator."/>' : '<label/>'; const label = disabled ? `<label class="disallowed" title="Setting locked by system administrator."/>` : `<label/>`;
if (settingOption) { if (settingOption) {
return ` return `
<div class="action"> <div class="action">
@@ -35,8 +30,7 @@ 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">
@@ -46,20 +40,11 @@ export default class BaseSection extends BaseComponent {
</div> </div>
`; `;
} }
/* 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
*/
generateSelectTemplate(options: {[key: string]: string}, className?: string, idName?: string): string {
let select = `<select class="${escape(className)}" id="${escape(idName)}">\n`;
Object.keys(options).forEach(key => {
select += `<option name="${escape(key)}" value="${escape(key)}">${escape(options[key])}</option>\n`;
});
select += '</select>';
return select;
} }
reloadApp(): void { reloadApp(): void {
ipcRenderer.send('forward-message', 'reload-viewer'); ipcRenderer.send('forward-message', 'reload-viewer');
} }
} }
export = BaseSection;

View File

@@ -1,24 +1,23 @@
import {ipcRenderer} from 'electron'; 'use strict';
import BaseSection from './base-section'; import { ipcRenderer } from 'electron';
import * as DomainUtil from '../../utils/domain-util';
import ServerInfoForm from './server-info-form';
import AddCertificate from './add-certificate';
import FindAccounts from './find-accounts';
import * as t from '../../utils/translation-util';
interface ConnectedOrgSectionProps { import BaseSection = require('./base-section');
$root: Element; import DomainUtil = require('../../utils/domain-util');
} import ServerInfoForm = require('./server-info-form');
import AddCertificate = require('./add-certificate');
import FindAccounts = require('./find-accounts');
import t = require('../../utils/translation-util');
export default class ConnectedOrgSection extends BaseSection { class ConnectedOrgSection extends BaseSection {
props: ConnectedOrgSectionProps; // TODO: TypeScript - Here props should be object type
props: any;
$serverInfoContainer: Element | null; $serverInfoContainer: Element | null;
$existingServers: Element | null; $existingServers: Element | null;
$newOrgButton: HTMLButtonElement | null; $newOrgButton: HTMLButtonElement | null;
$addCertificateContainer: Element | null; $addCertificateContainer: Element | null;
$findAccountsContainer: Element | null; $findAccountsContainer: Element | null;
constructor(props: ConnectedOrgSectionProps) { constructor(props: any) {
super(); super();
this.props = props; this.props = props;
} }
@@ -58,10 +57,10 @@ export default class ConnectedOrgSection extends BaseSection {
// Show noServerText if no servers are there otherwise hide it // Show noServerText if no servers are there otherwise hide it
this.$existingServers.innerHTML = servers.length === 0 ? noServerText : ''; this.$existingServers.innerHTML = servers.length === 0 ? noServerText : '';
for (const [i, server] of servers.entries()) { for (let i = 0; i < servers.length; i++) {
new ServerInfoForm({ new ServerInfoForm({
$root: this.$serverInfoContainer, $root: this.$serverInfoContainer,
server, server: servers[i],
index: i, index: i,
onChange: this.reloadApp onChange: this.reloadApp
}).init(); }).init();
@@ -87,3 +86,5 @@ export default class ConnectedOrgSection extends BaseSection {
}).init(); }).init();
} }
} }
export = ConnectedOrgSection;

View File

@@ -1,19 +1,17 @@
'use-strict'; 'use-strict';
import BaseComponent from '../../components/base'; import { shell } from 'electron';
import * as LinkUtil from '../../utils/link-util';
import * as t from '../../utils/translation-util';
interface FindAccountsProps { import BaseComponent = require('../../components/base');
$root: Element; import t = require('../../utils/translation-util');
}
export default class FindAccounts extends BaseComponent { class FindAccounts extends BaseComponent {
props: FindAccountsProps; // TODO: TypeScript - Here props should be object type
props: any;
$findAccounts: Element | null; $findAccounts: Element | null;
$findAccountsButton: Element | null; $findAccountsButton: Element | null;
$serverUrlField: HTMLInputElement | null; $serverUrlField: HTMLInputElement | null;
constructor(props: FindAccountsProps) { constructor(props: any) {
super(); super();
this.props = props; this.props = props;
} }
@@ -40,21 +38,19 @@ export default class FindAccounts extends BaseComponent {
this.initListeners(); this.initListeners();
} }
async findAccounts(url: string): Promise<void> { findAccounts(url: string): void {
if (!url) { if (!url) {
return; return;
} }
if (!url.startsWith('http')) { if (!url.startsWith('http')) {
url = 'https://' + url; url = 'https://' + url;
} }
shell.openExternal(url + '/accounts/find');
await LinkUtil.openBrowser(new URL('/accounts/find', url));
} }
initListeners(): void { initListeners(): void {
this.$findAccountsButton.addEventListener('click', async () => { this.$findAccountsButton.addEventListener('click', () => {
await this.findAccounts(this.$serverUrlField.value); this.findAccounts(this.$serverUrlField.value);
}); });
this.$serverUrlField.addEventListener('click', () => { this.$serverUrlField.addEventListener('click', () => {
@@ -63,9 +59,9 @@ export default class FindAccounts extends BaseComponent {
} }
}); });
this.$serverUrlField.addEventListener('keypress', async event => { this.$serverUrlField.addEventListener('keypress', event => {
if (event.key === 'Enter') { if (event.keyCode === 13) {
await this.findAccounts(this.$serverUrlField.value); this.findAccounts(this.$serverUrlField.value);
} }
}); });
@@ -78,3 +74,5 @@ export default class FindAccounts extends BaseComponent {
}); });
} }
} }
export = FindAccounts;

View File

@@ -1,24 +1,21 @@
import {ipcRenderer, remote, OpenDialogOptions} from 'electron'; 'use strict';
import { ipcRenderer, remote, OpenDialogOptions } from 'electron';
import path from 'path'; import path = require('path');
import fs from 'fs-extra'; import fs = require('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 = require('./base-section');
import * as ConfigUtil from '../../utils/config-util'; import ConfigUtil = require('../../utils/config-util');
import * as EnterpriseUtil from '../../utils/enterprise-util'; import EnterpriseUtil = require('./../../utils/enterprise-util');
import * as t from '../../utils/translation-util'; import t = require('../../utils/translation-util');
import supportedLocales from '../../../../translations/supported-locales.json';
interface GeneralSectionProps { class GeneralSection extends BaseSection {
$root: Element; // TODO: TypeScript - Here props should be object type
} props: any;
constructor(props: any) {
export default class GeneralSection extends BaseSection {
props: GeneralSectionProps;
constructor(props: GeneralSectionProps) {
super(); super();
this.props = props; this.props = props;
} }
@@ -96,17 +93,14 @@ export default class GeneralSection extends BaseSection {
</div> </div>
<div class="title">${t.__('Advanced')}</div> <div class="title">${t.__('Advanced')}</div>
<div class="settings-card"> <div class="settings-card">
<div class="setting-row" id="enable-error-reporting"> <div class="setting-row" id="enable-error-reporting">
<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="show-download-folder">
<div class="setting-row" id="app-language"> <div class="setting-description">${t.__('Show downloaded files in file manager')}</div>
<div class="setting-description">${t.__('App language (requires restart)')}</div> <div class="setting-control"></div>
<div id="lang-div" class="lang-div"></div>
</div> </div>
<div class="setting-row" id="add-custom-css"> <div class="setting-row" id="add-custom-css">
<div class="setting-description"> <div class="setting-description">
${t.__('Add custom CSS')} ${t.__('Add custom CSS')}
@@ -115,7 +109,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.getConfigString('customCSS', '')}</div> <div class="selected-css-path" id="custom-css-path">${ConfigUtil.getConfigItem('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,13 +124,10 @@ 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.getConfigString('downloadsPath', app.getPath('downloads'))}</div> <div class="download-folder-path">${ConfigUtil.getConfigItem('downloadsPath', `${app.getPath('downloads')}`)}</div>
</div> </div>
</div> </div>
<div class="setting-row" id="prompt-download">
<div class="setting-description">${t.__('Ask where to save files before downloading')}</div>
<div class="setting-control"></div>
</div>
</div> </div>
<div class="title">${t.__('Reset Application Data')}</div> <div class="title">${t.__('Reset Application Data')}</div>
<div class="settings-card"> <div class="settings-card">
@@ -167,10 +158,9 @@ export default class GeneralSection extends BaseSection {
this.showCustomCSSPath(); this.showCustomCSSPath();
this.removeCustomCSS(); this.removeCustomCSS();
this.downloadFolder(); this.downloadFolder();
this.showDownloadFolder();
this.updateQuitOnCloseOption(); this.updateQuitOnCloseOption();
this.updatePromptDownloadOption();
this.enableErrorReporting(); this.enableErrorReporting();
this.setLocale();
// Platform specific settings // Platform specific settings
@@ -178,7 +168,6 @@ 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();
@@ -265,7 +254,6 @@ export default class GeneralSection extends BaseSection {
ConfigUtil.setConfigItem('betaUpdate', false); ConfigUtil.setConfigItem('betaUpdate', false);
this.betaUpdateOption(); this.betaUpdateOption();
} }
this.autoUpdateOption(); this.autoUpdateOption();
} }
}); });
@@ -293,7 +281,9 @@ export default class GeneralSection extends BaseSection {
const newValue = !ConfigUtil.getConfigItem('silent', true); const newValue = !ConfigUtil.getConfigItem('silent', true);
ConfigUtil.setConfigItem('silent', newValue); ConfigUtil.setConfigItem('silent', newValue);
this.updateSilentOption(); this.updateSilentOption();
currentBrowserWindow.webContents.send('toggle-silent', newValue); // TODO: TypeScript: currentWindow of type BrowserWindow doesn't
// have a .send() property per typescript.
(currentBrowserWindow as any).send('toggle-silent', newValue);
} }
}); });
} }
@@ -372,59 +362,43 @@ export default class GeneralSection extends BaseSection {
}); });
} }
async clearAppDataDialog(): Promise<void> { clearAppDataDialog(): void {
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.getName());
const {response} = await dialog.showMessageBox({ dialog.showMessageBox({
type: 'warning', type: 'warning',
buttons: ['YES', 'NO'], buttons: ['YES', 'NO'],
defaultId: 0, defaultId: 0,
message: 'Are you sure', message: 'Are you sure',
detail: clearAppDataMessage detail: clearAppDataMessage
}); }, response => {
if (response === 0) { if (response === 0) {
await fs.remove(getAppPath); fs.remove(getAppPath);
ipcRenderer.send('forward-message', 'hard-reload'); setTimeout(() => ipcRenderer.send('forward-message', 'hard-reload'), 1000);
} }
});
} }
async customCssDialog(): Promise<void> { customCssDialog(): void {
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); dialog.showOpenDialog(showDialogOptions, selectedFile => {
if (!canceled) { if (selectedFile) {
ConfigUtil.setConfigItem('customCSS', filePaths[0]); ConfigUtil.setConfigItem('customCSS', selectedFile[0]);
ipcRenderer.send('forward-message', 'hard-reload'); ipcRenderer.send('forward-message', 'hard-reload');
} }
});
} }
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', async () => { resetDataButton.addEventListener('click', () => {
await this.clearAppDataDialog(); this.clearAppDataDialog();
});
}
setLocale(): void {
const langDiv: HTMLSelectElement = document.querySelector('.lang-div');
// This path is for the JSON file that stores key: value pairs for supported locales
const langList = this.generateSelectTemplate(supportedLocales, 'lang-menu');
langDiv.innerHTML += langList;
// `langMenu` is the select-option dropdown menu formed after executing the previous command
const langMenu: HTMLSelectElement = document.querySelector('.lang-menu');
// The next three lines set the selected language visible on the dropdown button
let language = ConfigUtil.getConfigItem('appLanguage');
language = language && langMenu.options.namedItem(language) ? language : 'en-US';
langMenu.options.namedItem(language).selected = true;
langMenu.addEventListener('change', (event: Event) => {
ConfigUtil.setConfigItem('appLanguage', (event.target as HTMLSelectElement).value);
}); });
} }
@@ -442,8 +416,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', async () => { customCSSButton.addEventListener('click', () => {
await this.customCssDialog(); this.customCssDialog();
}); });
} }
@@ -457,41 +431,43 @@ export default class GeneralSection extends BaseSection {
removeCustomCSS(): void { removeCustomCSS(): void {
const removeCSSButton = document.querySelector('#css-delete-action'); const removeCSSButton = document.querySelector('#css-delete-action');
removeCSSButton.addEventListener('click', () => { removeCSSButton.addEventListener('click', () => {
ConfigUtil.setConfigItem('customCSS', ''); ConfigUtil.setConfigItem('customCSS', "");
ipcRenderer.send('forward-message', 'hard-reload'); ipcRenderer.send('forward-message', 'hard-reload');
}); });
} }
async downloadFolderDialog(): Promise<void> { downloadFolderDialog(): void {
const showDialogOptions: OpenDialogOptions = { const showDialogOptions: OpenDialogOptions = {
title: 'Select Download Location', title: 'Select Download Location',
properties: ['openDirectory'] properties: ['openDirectory']
}; };
const {filePaths, canceled} = await dialog.showOpenDialog(showDialogOptions); dialog.showOpenDialog(showDialogOptions, selectedFolder => {
if (!canceled) { if (selectedFolder) {
ConfigUtil.setConfigItem('downloadsPath', filePaths[0]); ConfigUtil.setConfigItem('downloadsPath', selectedFolder[0]);
const downloadFolderPath: HTMLElement = document.querySelector('.download-folder-path'); const downloadFolderPath: HTMLElement = document.querySelector('.download-folder-path');
downloadFolderPath.textContent = filePaths[0]; downloadFolderPath.innerText = selectedFolder[0];
} }
});
} }
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', async () => { downloadFolder.addEventListener('click', () => {
await this.downloadFolderDialog(); this.downloadFolderDialog();
}); });
} }
updatePromptDownloadOption(): void { showDownloadFolder(): void {
this.generateSettingOption({ this.generateSettingOption({
$element: document.querySelector('#prompt-download .setting-control'), $element: document.querySelector('#show-download-folder .setting-control'),
value: ConfigUtil.getConfigItem('promptDownload', false), value: ConfigUtil.getConfigItem('showDownloadFolder', false),
clickHandler: () => { clickHandler: () => {
const newValue = !ConfigUtil.getConfigItem('promptDownload'); const newValue = !ConfigUtil.getConfigItem('showDownloadFolder');
ConfigUtil.setConfigItem('promptDownload', newValue); ConfigUtil.setConfigItem('showDownloadFolder', newValue);
this.updatePromptDownloadOption(); this.showDownloadFolder();
} }
}); });
} }
} }
export = GeneralSection;

View File

@@ -1,16 +1,14 @@
import BaseComponent from '../../components/base'; 'use strict';
import * as t from '../../utils/translation-util';
interface PreferenceNavProps { import BaseComponent = require('../../components/base');
$root: Element; import t = require('../../utils/translation-util');
onItemSelected: (navItem: string) => void;
}
export default class PreferenceNav extends BaseComponent { class PreferenceNav extends BaseComponent {
props: PreferenceNavProps; // TODO: TypeScript - Here props should be object type
props: any;
navItems: string[]; navItems: string[];
$el: Element; $el: Element;
constructor(props: PreferenceNavProps) { constructor(props: any) {
super(); super();
this.props = props; this.props = props;
this.navItems = ['General', 'Network', 'AddServer', 'Organizations', 'Shortcuts']; this.navItems = ['General', 'Network', 'AddServer', 'Organizations', 'Shortcuts'];
@@ -66,3 +64,5 @@ export default class PreferenceNav extends BaseComponent {
$item.classList.remove('active'); $item.classList.remove('active');
} }
} }
export = PreferenceNav;

View File

@@ -1,21 +1,20 @@
import {ipcRenderer} from 'electron'; 'use strict';
import BaseSection from './base-section'; import { ipcRenderer } from 'electron';
import * as ConfigUtil from '../../utils/config-util';
import * as t from '../../utils/translation-util';
interface NetworkSectionProps { import BaseSection = require('./base-section');
$root: Element; import ConfigUtil = require('../../utils/config-util');
} import t = require('../../utils/translation-util');
export default class NetworkSection extends BaseSection { class NetworkSection extends BaseSection {
props: NetworkSectionProps; // TODO: TypeScript - Here props should be object type
props: any;
$proxyPAC: HTMLInputElement; $proxyPAC: HTMLInputElement;
$proxyRules: HTMLInputElement; $proxyRules: HTMLInputElement;
$proxyBypass: HTMLInputElement; $proxyBypass: HTMLInputElement;
$proxySaveAction: Element; $proxySaveAction: Element;
$manualProxyBlock: Element; $manualProxyBlock: Element;
constructor(props: NetworkSectionProps) { constructor(props: any) {
super(); super();
this.props = props; this.props = props;
} }
@@ -105,13 +104,11 @@ export default class NetworkSection extends BaseSection {
ConfigUtil.setConfigItem('useManualProxy', !manualProxyValue); ConfigUtil.setConfigItem('useManualProxy', !manualProxyValue);
this.toggleManualProxySettings(!manualProxyValue); this.toggleManualProxySettings(!manualProxyValue);
} }
if (newValue === false) {
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();
} }
@@ -126,7 +123,6 @@ 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
@@ -136,3 +132,5 @@ export default class NetworkSection extends BaseSection {
}); });
} }
} }
export = NetworkSection;

View File

@@ -1,23 +1,18 @@
import {ipcRenderer, remote} from 'electron'; 'use strict';
import BaseComponent from '../../components/base'; import { shell, ipcRenderer } from 'electron';
import * as DomainUtil from '../../utils/domain-util';
import * as LinkUtil from '../../utils/link-util';
import * as t from '../../utils/translation-util';
const {dialog} = remote; import BaseComponent = require('../../components/base');
import DomainUtil = require('../../utils/domain-util');
import t = require('../../utils/translation-util');
interface NewServerFormProps { class NewServerForm extends BaseComponent {
$root: Element; // TODO: TypeScript - Here props should be object type
onChange: () => void; props: any;
}
export default class NewServerForm extends BaseComponent {
props: NewServerFormProps;
$newServerForm: Element; $newServerForm: Element;
$saveServerButton: HTMLButtonElement; $saveServerButton: HTMLButtonElement;
$newServerUrl: HTMLInputElement; $newServerUrl: HTMLInputElement;
constructor(props: NewServerFormProps) { constructor(props: any) {
super(); super();
this.props = props; this.props = props;
} }
@@ -30,16 +25,20 @@ export default class NewServerForm extends BaseComponent {
<input class="setting-input-value" autofocus placeholder="your-organization.zulipchat.com or zulip.your-organization.com"/> <input class="setting-input-value" autofocus placeholder="your-organization.zulipchat.com or zulip.your-organization.com"/>
</div> </div>
<div class="server-center"> <div class="server-center">
<div class="server-save-action">
<button id="connect">${t.__('Connect')}</button> <button id="connect">${t.__('Connect')}</button>
</div> </div>
</div>
<div class="server-center"> <div class="server-center">
<div class="divider"> <div class="divider">
<hr class="left"/>${t.__('OR')}<hr class="right" /> <hr class="left"/>${t.__('OR')}<hr class="right" />
</div> </div>
</div> </div>
<div class="server-center"> <div class="server-center">
<div class="server-save-action">
<button id="open-create-org-link">${t.__('Create a new organization')}</button> <button id="open-create-org-link">${t.__('Create a new organization')}</button>
</div> </div>
</div>
<div class="server-center"> <div class="server-center">
<div class="server-network-option"> <div class="server-network-option">
<span id="open-network-settings">${t.__('Network and Proxy Settings')}</span> <span id="open-network-settings">${t.__('Network and Proxy Settings')}</span>
@@ -57,36 +56,29 @@ export default class NewServerForm extends BaseComponent {
initForm(): void { initForm(): void {
this.$newServerForm = this.generateNodeFromTemplate(this.template()); this.$newServerForm = this.generateNodeFromTemplate(this.template());
this.$saveServerButton = this.$newServerForm.querySelector('#connect'); this.$saveServerButton = this.$newServerForm.querySelectorAll('.server-save-action')[0] as HTMLButtonElement;
this.props.$root.innerHTML = ''; this.props.$root.innerHTML = '';
this.props.$root.append(this.$newServerForm); this.props.$root.append(this.$newServerForm);
this.$newServerUrl = this.$newServerForm.querySelectorAll('input.setting-input-value')[0] as HTMLInputElement; this.$newServerUrl = this.$newServerForm.querySelectorAll('input.setting-input-value')[0] as HTMLInputElement;
} }
async submitFormHandler(): Promise<void> { submitFormHandler(): void {
this.$saveServerButton.innerHTML = 'Connecting...'; this.$saveServerButton.children[0].innerHTML = 'Connecting...';
let serverConf; DomainUtil.checkDomain(this.$newServerUrl.value).then(serverConf => {
try { DomainUtil.addDomain(serverConf).then(() => {
serverConf = await DomainUtil.checkDomain(this.$newServerUrl.value); this.props.onChange(this.props.index);
} catch (error) { });
this.$saveServerButton.innerHTML = 'Connect'; }, errorMessage => {
await dialog.showMessageBox({ this.$saveServerButton.children[0].innerHTML = 'Connect';
type: 'error', alert(errorMessage);
message: error.toString(),
buttons: ['OK']
}); });
return;
}
await DomainUtil.addDomain(serverConf);
this.props.onChange();
} }
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 externalCreateNewOrgEl = document.querySelector('#open-create-org-link');
externalCreateNewOrgElement.addEventListener('click', async () => { externalCreateNewOrgEl.addEventListener('click', () => {
await LinkUtil.openBrowser(new URL(link)); shell.openExternal(link);
}); });
} }
@@ -96,16 +88,20 @@ export default class NewServerForm extends BaseComponent {
} }
initActions(): void { initActions(): void {
this.$saveServerButton.addEventListener('click', async () => { this.$saveServerButton.addEventListener('click', () => {
await this.submitFormHandler(); this.submitFormHandler();
}); });
this.$newServerUrl.addEventListener('keypress', async event => { this.$newServerUrl.addEventListener('keypress', event => {
if (event.key === 'Enter') { const EnterkeyCode = event.keyCode;
await this.submitFormHandler(); // Submit form when Enter key is pressed
if (EnterkeyCode === 13) {
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();
} }
} }
export = NewServerForm;

View File

@@ -1,17 +1,18 @@
import {ipcRenderer} from 'electron'; 'use strict';
import BaseComponent from '../../components/base'; import { ipcRenderer } from 'electron';
import Nav from './nav';
import ServersSection from './servers-section'; import BaseComponent = require('../../components/base');
import GeneralSection from './general-section'; import Nav = require('./nav');
import NetworkSection from './network-section'; import ServersSection = require('./servers-section');
import ConnectedOrgSection from './connected-org-section'; import GeneralSection = require('./general-section');
import ShortcutsSection from './shortcuts-section'; import NetworkSection = require('./network-section');
import type {DNDSettings} from '../../utils/dnd-util'; import ConnectedOrgSection = require('./connected-org-section');
import ShortcutsSection = require('./shortcuts-section');
type Section = ServersSection | GeneralSection | NetworkSection | ConnectedOrgSection | ShortcutsSection; type Section = ServersSection | GeneralSection | NetworkSection | ConnectedOrgSection | ShortcutsSection;
export default class PreferenceView extends BaseComponent { class PreferenceView extends BaseComponent {
$sidebarContainer: Element; $sidebarContainer: Element;
$settingsContainer: Element; $settingsContainer: Element;
nav: Nav; nav: Nav;
@@ -36,9 +37,8 @@ export default class PreferenceView extends BaseComponent {
let nav = 'General'; let nav = 'General';
const hasTag = window.location.hash; const hasTag = window.location.hash;
if (hasTag) { if (hasTag) {
nav = hasTag.slice(1); nav = hasTag.substring(1);
} }
this.handleNavigation(nav); this.handleNavigation(nav);
} }
@@ -51,38 +51,32 @@ 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}`;
} }
@@ -113,7 +107,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: DNDSettings) => { ipcRenderer.on('toggle-dnd', (_event: Event, _state: boolean, newSettings: any) => {
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);
@@ -128,3 +122,5 @@ window.addEventListener('load', () => {
const preferenceView = new PreferenceView(); const preferenceView = new PreferenceView();
preferenceView.init(); preferenceView.init();
}); });
export = PreferenceView;

View File

@@ -1,27 +1,23 @@
import {remote, ipcRenderer} from 'electron'; 'use strict';
import BaseComponent from '../../components/base'; import { remote, ipcRenderer } from 'electron';
import * as DomainUtil from '../../utils/domain-util';
import * as Messages from '../../../../resources/messages';
import * as t from '../../utils/translation-util';
const {dialog} = remote; import BaseComponent = require('../../components/base');
import DomainUtil = require('../../utils/domain-util');
import Messages = require('./../../../../resources/messages');
import t = require('../../utils/translation-util');
interface ServerInfoFormProps { const { dialog } = remote;
$root: Element;
server: DomainUtil.ServerConf;
index: number;
onChange: () => void;
}
export default class ServerInfoForm extends BaseComponent { class ServerInfoForm extends BaseComponent {
props: ServerInfoFormProps; // TODO: TypeScript - Here props should be object type
props: any;
$serverInfoForm: Element; $serverInfoForm: Element;
$serverInfoAlias: Element; $serverInfoAlias: Element;
$serverIcon: Element; $serverIcon: Element;
$deleteServerButton: Element; $deleteServerButton: Element;
$openServerButton: Element; $openServerButton: Element;
constructor(props: ServerInfoFormProps) { constructor(props: any) {
super(); super();
this.props = props; this.props = props;
} }
@@ -65,22 +61,23 @@ export default class ServerInfoForm extends BaseComponent {
} }
initActions(): void { initActions(): void {
this.$deleteServerButton.addEventListener('click', async () => { this.$deleteServerButton.addEventListener('click', () => {
const {response} = await dialog.showMessageBox({ dialog.showMessageBox({
type: 'warning', type: 'warning',
buttons: [t.__('YES'), t.__('NO')], buttons: [t.__('YES'), t.__('NO')],
defaultId: 0, defaultId: 0,
message: t.__('Are you sure you want to disconnect this organization?') message: t.__('Are you sure you want to disconnect this organization?')
}); }, response => {
if (response === 0) { if (response === 0) {
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);
} }
} }
}); });
});
this.$openServerButton.addEventListener('click', () => { this.$openServerButton.addEventListener('click', () => {
ipcRenderer.send('forward-message', 'switch-server-tab', this.props.index); ipcRenderer.send('forward-message', 'switch-server-tab', this.props.index);
@@ -95,3 +92,5 @@ export default class ServerInfoForm extends BaseComponent {
}); });
} }
} }
export = ServerInfoForm;

View File

@@ -1,15 +1,14 @@
import BaseSection from './base-section'; 'use strict';
import NewServerForm from './new-server-form';
import * as t from '../../utils/translation-util';
interface ServersSectionProps { import BaseSection = require('./base-section');
$root: Element; import NewServerForm = require('./new-server-form');
} import t = require('../../utils/translation-util');
export default class ServersSection extends BaseSection { class ServersSection extends BaseSection {
props: ServersSectionProps; // TODO: TypeScript - Here props should be object type
props: any;
$newServerContainer: Element; $newServerContainer: Element;
constructor(props: ServersSectionProps) { constructor(props: any) {
super(); super();
this.props = props; this.props = props;
} }
@@ -47,3 +46,5 @@ export default class ServersSection extends BaseSection {
}).init(); }).init();
} }
} }
export = ServersSection;

View File

@@ -1,18 +1,17 @@
import BaseSection from './base-section'; 'use strict';
import * as LinkUtil from '../../utils/link-util';
import * as t from '../../utils/translation-util';
interface ShortcutsSectionProps { import { shell } from 'electron';
$root: Element;
}
export default class ShortcutsSection extends BaseSection { import BaseSection = require('./base-section');
props: ShortcutsSectionProps; import t = require('../../utils/translation-util');
constructor(props: ShortcutsSectionProps) {
class ShortcutsSection extends BaseSection {
// TODO: TypeScript - Here props should be object type
props: any;
constructor(props: any) {
super(); super();
this.props = props; this.props = props;
} }
// TODO - Deduplicate templateMac and templateWinLin functions. In theory // TODO - Deduplicate templateMac and templateWinLin functions. In theory
// they both should be the same the only thing different should be the userOSKey // they both should be the same the only thing different should be the userOSKey
// variable but there seems to be inconsistences between both function, one has more // variable but there seems to be inconsistences between both function, one has more
@@ -331,15 +330,16 @@ 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 externalCreateNewOrgEl = document.querySelector('#open-hotkeys-link');
externalCreateNewOrgElement.addEventListener('click', async () => { externalCreateNewOrgEl.addEventListener('click', () => {
await LinkUtil.openBrowser(new URL(link)); shell.openExternal(link);
}); });
} }
init(): void { init(): void {
this.props.$root.innerHTML = (process.platform === 'darwin') ? this.props.$root.innerHTML = (process.platform === 'darwin') ?
this.templateMac() : this.templateWinLin(); this.templateMac() : this.templateWinLin();
this.openHotkeysExternalLink(); this.openHotkeysExternalLink();
} }
} }
export = ShortcutsSection;

View File

@@ -1,31 +1,47 @@
import {contextBridge, ipcRenderer, webFrame} from 'electron'; // we have and will have some non camelcase stuff
import fs from 'fs'; // while working with zulip and electron bridge
import * as SetupSpellChecker from './spellchecker'; // so turning the rule off for the whole file.
/* eslint-disable @typescript-eslint/camelcase */
import isDev from 'electron-is-dev'; 'use strict';
import * as NetworkError from './pages/network'; import { ipcRenderer, shell } from 'electron';
import SetupSpellChecker from './spellchecker';
import isDev = require('electron-is-dev');
import LinkUtil = require('./utils/link-util');
import params = require('./utils/params-util');
import NetworkError = require('./pages/network');
interface PatchedGlobal extends NodeJS.Global {
logout: () => void;
shortcut: () => void;
showNotificationSettings: () => void;
}
const globalPatched = global as PatchedGlobal;
// eslint-disable-next-line import/no-unassigned-import // eslint-disable-next-line import/no-unassigned-import
import './notification'; require('./notification');
// Prevent drag and drop event in main process which prevents remote code executaion // Prevent drag and drop event in main process which prevents remote code executaion
// eslint-disable-next-line import/no-unassigned-import require(__dirname + '/shared/preventdrag.js');
import './shared/preventdrag';
import electron_bridge from './electron-bridge'; declare let window: ZulipWebWindow;
contextBridge.exposeInMainWorld('raw_electron_bridge', electron_bridge);
ipcRenderer.on('logout', () => { window.electron_bridge = require('./electron-bridge');
const logout = (): void => {
// Create the menu for the below // Create the menu for the below
const dropdown: HTMLElement = document.querySelector('.dropdown-toggle'); const dropdown: HTMLElement = document.querySelector('.dropdown-toggle');
dropdown.click(); dropdown.click();
const nodes: NodeListOf<HTMLElement> = document.querySelectorAll('.dropdown-menu li:last-child a'); const nodes: NodeListOf<HTMLElement> = document.querySelectorAll('.dropdown-menu li:last-child a');
nodes[nodes.length - 1].click(); nodes[nodes.length - 1].click();
}); };
ipcRenderer.on('shortcut', () => { const shortcut = (): void => {
// Create the menu for the below // Create the menu for the below
const node: HTMLElement = document.querySelector('a[data-overlay-trigger=keyboard-shortcuts]'); const node: HTMLElement = document.querySelector('a[data-overlay-trigger=keyboard-shortcuts]');
// Additional check // Additional check
@@ -36,9 +52,9 @@ ipcRenderer.on('shortcut', () => {
const dropdown: HTMLElement = document.querySelector('.dropdown-toggle'); const dropdown: HTMLElement = document.querySelector('.dropdown-toggle');
dropdown.click(); dropdown.click();
} }
}); };
ipcRenderer.on('show-notification-settings', () => { const showNotificationSettings = (): void => {
// Create the menu for the below // Create the menu for the below
const dropdown: HTMLElement = document.querySelector('.dropdown-toggle'); const dropdown: HTMLElement = document.querySelector('.dropdown-toggle');
dropdown.click(); dropdown.click();
@@ -48,26 +64,56 @@ 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);
};
process.once('loaded', (): void => {
globalPatched.logout = logout;
globalPatched.shortcut = shortcut;
globalPatched.showNotificationSettings = showNotificationSettings;
}); });
electron_bridge.once('zulip-loaded', ({serverLanguage}) => { // To prevent failing this script on linux we need to load it after the document loaded
document.addEventListener('DOMContentLoaded', (): void => {
if (params.isPageParams()) {
// Get the default language of the server // Get the default language of the server
const serverLanguage = page_params.default_language; // eslint-disable-line no-undef
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', () => {
ipcRenderer.send('forward-message', 'reload-viewer'); ipcRenderer.send('forward-message', 'reload-viewer');
}); });
} }
// Open image attachment link in the lightbox instead of opening in the default browser
const { $, lightbox } = window;
$('#main_div').on('click', '.message_content p a', function (this: HTMLElement, e: Event) {
const url = $(this).attr('href');
if (LinkUtil.isImage(url)) {
const $img = $(this).parent().siblings('.message_inline_image').find('img');
// prevent the image link from opening in a new page.
e.preventDefault();
// prevent the message compose dialog from happening.
e.stopPropagation();
// Open image in the default browser if image preview is unavailable
if (!$img[0]) {
shell.openExternal(window.location.origin + url);
}
// Open image in lightbox
lightbox.open($img);
}
});
}
}); });
// Clean up spellchecker events after you navigate away from this page; // Clean up spellchecker events after you navigate away from this page;
@@ -80,13 +126,12 @@ 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 => {
@@ -107,9 +152,8 @@ ipcRenderer.on('set-active', () => {
if (isDev) { if (isDev) {
console.log('active'); console.log('active');
} }
window.electron_bridge.idle_on_system = false;
electron_bridge.idle_on_system = false; window.electron_bridge.last_active_on_system = Date.now();
electron_bridge.last_active_on_system = Date.now();
}); });
// Set user as idle and time of last activity is left unchanged // Set user as idle and time of last activity is left unchanged
@@ -117,10 +161,5 @@ ipcRenderer.on('set-idle', () => {
if (isDev) { if (isDev) {
console.log('idle'); console.log('idle');
} }
window.electron_bridge.idle_on_system = true;
electron_bridge.idle_on_system = true;
}); });
(async () => webFrame.executeJavaScript(
fs.readFileSync(require.resolve('./injected'), 'utf8')
))();

View File

@@ -1,3 +1,5 @@
'use strict';
// This is a security fix. Following function prevents drag and drop event in the app // This is a security fix. Following function prevents drag and drop event in the app
// so that attackers can't execute any remote code within the app // so that attackers can't execute any remote code within the app
// It doesn't affect the compose box so that users can still // It doesn't affect the compose box so that users can still
@@ -13,5 +15,3 @@ const preventDragAndDrop = (): void => {
}; };
preventDragAndDrop(); preventDragAndDrop();
export {};

View File

@@ -1,61 +1,56 @@
import type {Subject} from 'rxjs'; 'use strict';
import {SpellCheckHandler, ContextMenuListener, ContextMenuBuilder} from 'electron-spellchecker';
import * as ConfigUtil from './utils/config-util'; import { SpellCheckHandler, ContextMenuListener, ContextMenuBuilder } from 'electron-spellchecker';
import Logger from './utils/logger-util';
declare module 'electron-spellchecker' { import ConfigUtil = require('./utils/config-util');
interface SpellCheckHandler { import Logger = require('./utils/logger-util');
currentSpellcheckerChanged: Subject<true>;
currentSpellcheckerLanguage: string;
}
}
const logger = new Logger({ const logger = new Logger({
file: 'errors.log', file: 'errors.log',
timestamp: true timestamp: true
}); });
let spellCheckHandler: SpellCheckHandler; class SetupSpellChecker {
let contextMenuListener: ContextMenuListener; SpellCheckHandler: typeof SpellCheckHandler;
contextMenuListener: typeof ContextMenuListener;
export function init(serverLanguage: string): void { init(serverLanguage: string): void {
if (ConfigUtil.getConfigItem('enableSpellchecker')) { if (ConfigUtil.getConfigItem('enableSpellchecker')) {
enableSpellChecker(); this.enableSpellChecker();
}
this.enableContextMenu(serverLanguage);
} }
enableContextMenu(serverLanguage); enableSpellChecker(): void {
}
function enableSpellChecker(): void {
try { try {
spellCheckHandler = new SpellCheckHandler(); this.SpellCheckHandler = new SpellCheckHandler();
} catch (error) { } catch (err) {
logger.error(error); logger.error(err);
}
} }
}
function enableContextMenu(serverLanguage: string): void { enableContextMenu(serverLanguage: string): void {
if (spellCheckHandler) { if (this.SpellCheckHandler) {
spellCheckHandler.attachToInput(); this.SpellCheckHandler.attachToInput();
spellCheckHandler.switchLanguage(serverLanguage); this.SpellCheckHandler.switchLanguage(serverLanguage);
spellCheckHandler.currentSpellcheckerChanged.subscribe(() => { this.SpellCheckHandler.currentSpellcheckerChanged.subscribe(() => {
spellCheckHandler.switchLanguage(spellCheckHandler.currentSpellcheckerLanguage); this.SpellCheckHandler.switchLanguage(this.SpellCheckHandler.currentSpellcheckerLanguage);
}); });
} }
const contextMenuBuilder = new ContextMenuBuilder(spellCheckHandler); const contextMenuBuilder = new ContextMenuBuilder(this.SpellCheckHandler);
contextMenuListener = new ContextMenuListener(info => { this.contextMenuListener = new ContextMenuListener((info: object) => {
contextMenuBuilder.showPopupMenu(info); contextMenuBuilder.showPopupMenu(info);
}); });
}
export function unsubscribeSpellChecker(): void {
if (spellCheckHandler) {
spellCheckHandler.unsubscribe();
} }
if (contextMenuListener) { unsubscribeSpellChecker(): void {
contextMenuListener.unsubscribe(); if (this.SpellCheckHandler) {
this.SpellCheckHandler.unsubscribe();
}
if (this.contextMenuListener) {
this.contextMenuListener.unsubscribe();
}
} }
} }
export = new SetupSpellChecker();

View File

@@ -1,26 +1,18 @@
import {ipcRenderer, remote, WebviewTag, NativeImage} from 'electron'; 'use strict';
import { ipcRenderer, remote, WebviewTag, NativeImage } from 'electron';
import path from 'path'; import path = require('path');
import * as ConfigUtil from './utils/config-util'; import ConfigUtil = require('./utils/config-util.js');
const { Tray, Menu, nativeImage, BrowserWindow } = remote;
const {Tray, Menu, nativeImage, BrowserWindow, nativeTheme} = remote; const APP_ICON = path.join(__dirname, '../../resources/tray', 'tray');
let tray: Electron.Tray; declare let window: ZulipWebWindow;
// Get the theme on macOS
const theme = nativeTheme.shouldUseDarkColors ? 'dark' : 'light';
const ICON_DIR = process.platform === 'darwin' ? `../../resources/tray/${theme}` : '../../resources/tray';
const TRAY_SUFFIX = 'tray';
const APP_ICON = path.join(__dirname, ICON_DIR, TRAY_SUFFIX);
const iconPath = (): string => { 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');
}; };
@@ -51,9 +43,10 @@ const config = {
thick: process.platform === 'win32' thick: process.platform === 'win32'
}; };
const renderCanvas = function (arg: number): HTMLCanvasElement { const renderCanvas = function (arg: number): Promise<HTMLCanvasElement> {
config.unreadCount = arg; config.unreadCount = arg;
return new Promise(resolve => {
const SIZE = config.size * config.pixelRatio; const SIZE = config.size * config.pixelRatio;
const PADDING = SIZE * 0.05; const PADDING = SIZE * 0.05;
const CENTER = SIZE / 2; const CENTER = SIZE / 2;
@@ -84,26 +77,34 @@ const renderCanvas = function (arg: number): HTMLCanvasElement {
ctx.fillText('99+', CENTER, CENTER + (SIZE * 0.15)); ctx.fillText('99+', CENTER, CENTER + (SIZE * 0.15));
} else if (config.unreadCount < 10) { } else if (config.unreadCount < 10) {
ctx.font = `${config.thick ? 'bold ' : ''}${SIZE * 0.5}px Helvetica`; ctx.font = `${config.thick ? 'bold ' : ''}${SIZE * 0.5}px Helvetica`;
ctx.fillText(String(config.unreadCount), CENTER, CENTER + (SIZE * 0.2)); ctx.fillText(String(config.unreadCount), CENTER, CENTER + (SIZE * 0.20));
} else { } else {
ctx.font = `${config.thick ? 'bold ' : ''}${SIZE * 0.5}px Helvetica`; ctx.font = `${config.thick ? 'bold ' : ''}${SIZE * 0.5}px Helvetica`;
ctx.fillText(String(config.unreadCount), CENTER, CENTER + (SIZE * 0.15)); ctx.fillText(String(config.unreadCount), CENTER, CENTER + (SIZE * 0.15));
} }
resolve(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
* @return the native image * @return the native image
*/ */
const renderNativeImage = function (arg: number): NativeImage { const renderNativeImage = function (arg: number): Promise<NativeImage> {
const canvas = renderCanvas(arg); return Promise.resolve()
.then(() => renderCanvas(arg))
.then(canvas => {
const pngData = nativeImage.createFromDataURL(canvas.toDataURL('image/png')).toPNG(); const pngData = nativeImage.createFromDataURL(canvas.toDataURL('image/png')).toPNG();
return nativeImage.createFromBuffer(pngData, {
// TODO: Fix the function to correctly use Promise correctly.
// the Promise.resolve().then(...) above is useless we should
// start with renderCanvas(arg).then
// eslint-disable-next-line promise/no-return-wrap
return Promise.resolve(nativeImage.createFromBuffer(pngData, {
scaleFactor: config.pixelRatio scaleFactor: config.pixelRatio
}));
}); });
}; };
@@ -118,6 +119,7 @@ function sendAction(action: string): void {
} }
const createTray = function (): void { const createTray = function (): void {
window.tray = new Tray(iconPath());
const contextMenu = Menu.buildFromTemplate([ const contextMenu = Menu.buildFromTemplate([
{ {
label: 'Zulip', label: 'Zulip',
@@ -142,23 +144,22 @@ const createTray = function (): void {
} }
} }
]); ]);
tray = new Tray(iconPath()); window.tray.setContextMenu(contextMenu);
tray.setContextMenu(contextMenu);
if (process.platform === 'linux' || process.platform === 'win32') { if (process.platform === 'linux' || process.platform === 'win32') {
tray.on('click', () => { window.tray.on('click', () => {
ipcRenderer.send('toggle-app'); ipcRenderer.send('toggle-app');
}); });
} }
}; };
ipcRenderer.on('destroytray', (event: Event): Event => { ipcRenderer.on('destroytray', (event: Event): Event => {
if (!tray) { if (!window.tray) {
return undefined; return undefined;
} }
tray.destroy(); window.tray.destroy();
if (tray.isDestroyed()) { if (window.tray.isDestroyed()) {
tray = null; window.tray = null;
} else { } else {
throw new Error('Tray icon not properly destroyed.'); throw new Error('Tray icon not properly destroyed.');
} }
@@ -167,47 +168,45 @@ ipcRenderer.on('destroytray', (event: Event): Event => {
}); });
ipcRenderer.on('tray', (_event: Event, arg: number): void => { ipcRenderer.on('tray', (_event: Event, arg: number): void => {
if (!tray) { if (!window.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) {
unread = arg; unread = arg;
tray.setImage(iconPath()); window.tray.setImage(iconPath());
tray.setToolTip('No unread messages'); window.tray.setToolTip('No unread messages');
} else { } else {
unread = arg; unread = arg;
const image = renderNativeImage(arg); renderNativeImage(arg).then(image => {
tray.setImage(image); window.tray.setImage(image);
tray.setToolTip(`${arg} unread messages`); window.tray.setToolTip(arg + ' unread messages');
});
} }
} }
}); });
function toggleTray(): void { function toggleTray(): void {
let state; let state;
if (tray) { if (window.tray) {
state = false; state = false;
tray.destroy(); window.tray.destroy();
if (tray.isDestroyed()) { if (window.tray.isDestroyed()) {
tray = null; window.tray = null;
} }
ConfigUtil.setConfigItem('trayIcon', false); ConfigUtil.setConfigItem('trayIcon', false);
} else { } else {
state = true; state = true;
createTray(); createTray();
if (process.platform === 'linux' || process.platform === 'win32') { if (process.platform === 'linux' || process.platform === 'win32') {
const image = renderNativeImage(unread); renderNativeImage(unread).then(image => {
tray.setImage(image); window.tray.setImage(image);
tray.setToolTip(`${unread} unread messages`); window.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();
@@ -219,5 +218,3 @@ ipcRenderer.on('toggletray', toggleTray);
if (ConfigUtil.getConfigItem('trayIcon', true)) { if (ConfigUtil.getConfigItem('trayIcon', true)) {
createTray(); createTray();
} }
export {};

View File

@@ -1,68 +1,84 @@
import electron from 'electron'; 'use strict';
import {JsonDB} from 'node-json-db';
import {initSetUp} from './default-util';
import fs from 'fs'; import { remote } from 'electron';
import path from 'path'; import JsonDB from 'node-json-db';
import Logger from './logger-util'; import { initSetUp } from './default-util';
const {app, dialog} = import fs = require('fs');
process.type === 'renderer' ? electron.remote : electron; import path = require('path');
import Logger = require('./logger-util');
const { app, dialog } = remote;
initSetUp(); initSetUp();
const logger = new Logger({ const logger = new Logger({
file: 'certificate-util.log', file: `certificate-util.log`,
timestamp: true timestamp: true
}); });
let instance: null | CertificateUtil = null;
const certificatesDir = `${app.getPath('userData')}/certificates`; const certificatesDir = `${app.getPath('userData')}/certificates`;
let db: JsonDB; class CertificateUtil {
db: JsonDB;
reloadDB(); constructor() {
if (instance) {
return instance;
} else {
instance = this;
}
export function getCertificate(server: string): string | undefined { this.reloadDB();
reloadDB(); return instance;
return db.getData('/')[server]; }
}
// Function to copy the certificate to userData folder getCertificate(server: string, defaultValue: any = null): any {
export function copyCertificate(_server: string, location: string, fileName: string): boolean { this.reloadDB();
const value = this.db.getData('/')[server];
if (value === undefined) {
return defaultValue;
} else {
return value;
}
}
// Function to copy the certificate to userData folder
copyCertificate(_server: string, location: string, fileName: string): boolean {
let copied = false; let copied = false;
const filePath = `${certificatesDir}/${fileName}`; const filePath = `${certificatesDir}/${fileName}`;
try { try {
fs.copyFileSync(location, filePath); fs.copyFileSync(location, filePath);
copied = true; copied = true;
} catch (error) { } catch (err) {
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(error); logger.error(err);
}
return copied;
} }
return copied; setCertificate(server: string, fileName: string): void {
}
export function setCertificate(server: string, fileName: string): void {
const filePath = `${fileName}`; const filePath = `${fileName}`;
db.push(`/${server}`, filePath, true); this.db.push(`/${server}`, filePath, true);
reloadDB(); this.reloadDB();
} }
export function removeCertificate(server: string): void { removeCertificate(server: string): void {
db.delete(`/${server}`); this.db.delete(`/${server}`);
reloadDB(); this.reloadDB();
} }
function reloadDB(): void { reloadDB(): void {
const settingsJsonPath = path.join(app.getPath('userData'), '/config/certificates.json'); const settingsJsonPath = path.join(app.getPath('userData'), '/config/certificates.json');
try { try {
const file = fs.readFileSync(settingsJsonPath, 'utf8'); const file = fs.readFileSync(settingsJsonPath, 'utf8');
JSON.parse(file); JSON.parse(file);
} catch (error) { } catch (err) {
if (fs.existsSync(settingsJsonPath)) { if (fs.existsSync(settingsJsonPath)) {
fs.unlinkSync(settingsJsonPath); fs.unlinkSync(settingsJsonPath);
dialog.showErrorBox( dialog.showErrorBox(
@@ -70,9 +86,11 @@ 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(error); logger.error(err);
} }
} }
this.db = new JsonDB(settingsJsonPath, true, true);
db = new JsonDB(settingsJsonPath, true, true); }
} }
export = new CertificateUtil();

View File

@@ -1,8 +1,25 @@
// Unescape already encoded/escaped strings 'use strict';
export function decodeString(stringInput: string): string {
let instance: null | CommonUtil = null;
class CommonUtil {
constructor() {
if (instance) {
return instance;
} else {
instance = this;
}
return instance;
}
// unescape already encoded/escaped strings
decodeString(stringInput: string): string {
const parser = new DOMParser(); const parser = new DOMParser();
const dom = parser.parseFromString( const dom = parser.parseFromString(
'<!doctype html><body>' + stringInput, '<!doctype html><body>' + stringInput,
'text/html'); 'text/html');
return dom.body.textContent; return dom.body.textContent;
}
} }
export = new CommonUtil();

View File

@@ -1,22 +1,24 @@
import {JsonDB} from 'node-json-db'; 'use strict';
import JsonDB from 'node-json-db';
import fs from 'fs'; import fs = require('fs');
import path from 'path'; import path = require('path');
import electron from 'electron'; import electron = require('electron');
import Logger from './logger-util'; import Logger = require('./logger-util');
import * as EnterpriseUtil from './enterprise-util'; import EnterpriseUtil = require('./enterprise-util');
const logger = new Logger({ const logger = new Logger({
file: 'config-util.log', file: 'config-util.log',
timestamp: true timestamp: true
}); });
let instance: null | ConfigUtil = null;
let dialog: Electron.Dialog = null; let dialog: Electron.Dialog = null;
let app: Electron.App = null; 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 {
@@ -24,71 +26,68 @@ if (process.type === 'renderer') {
app = electron.app; app = electron.app;
} }
let db: JsonDB; class ConfigUtil {
db: JsonDB;
reloadDB(); constructor() {
if (instance) {
export function getConfigItem(key: string, defaultValue: unknown = null): any { return instance;
try { } else {
db.reload(); instance = this;
} catch (error) {
logger.error('Error while reloading settings.json: ');
logger.error(error);
} }
const value = db.getData('/')[key]; this.reloadDB();
return instance;
}
getConfigItem(key: string, defaultValue: any = null): any {
try {
this.db.reload();
} catch (err) {
logger.error('Error while reloading settings.json: ');
logger.error(err);
}
const value = this.db.getData('/')[key];
if (value === undefined) { if (value === undefined) {
setConfigItem(key, defaultValue); this.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); // This function returns whether a key exists in the configuration file (settings.json)
return defaultValue; isConfigItemExists(key: string): boolean {
}
// This function returns whether a key exists in the configuration file (settings.json)
export function isConfigItemExists(key: string): boolean {
try { try {
db.reload(); this.db.reload();
} catch (error) { } catch (err) {
logger.error('Error while reloading settings.json: '); logger.error('Error while reloading settings.json: ');
logger.error(error); logger.error(err);
}
const value = this.db.getData('/')[key];
return (value !== undefined);
} }
const value = db.getData('/')[key]; setConfigItem(key: string, value: any, override? : boolean): void {
return (value !== undefined);
}
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;
} }
this.db.push(`/${key}`, value, true);
this.db.save();
}
db.push(`/${key}`, value, true); removeConfigItem(key: string): void {
db.save(); this.db.delete(`/${key}`);
} this.db.save();
}
export function removeConfigItem(key: string): void { reloadDB(): void {
db.delete(`/${key}`);
db.save();
}
function reloadDB(): void {
const settingsJsonPath = path.join(app.getPath('userData'), '/config/settings.json'); const settingsJsonPath = path.join(app.getPath('userData'), '/config/settings.json');
try { try {
const file = fs.readFileSync(settingsJsonPath, 'utf8'); const file = fs.readFileSync(settingsJsonPath, 'utf8');
JSON.parse(file); JSON.parse(file);
} catch (error) { } catch (err) {
if (fs.existsSync(settingsJsonPath)) { if (fs.existsSync(settingsJsonPath)) {
fs.unlinkSync(settingsJsonPath); fs.unlinkSync(settingsJsonPath);
dialog.showErrorBox( dialog.showErrorBox(
@@ -96,10 +95,12 @@ 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(error); logger.error(err);
logger.reportSentry(error); logger.reportSentry(err);
} }
} }
this.db = new JsonDB(settingsJsonPath, true, true);
db = new JsonDB(settingsJsonPath, true, true); }
} }
export = new ConfigUtil();

View File

@@ -1,12 +1,11 @@
import electron from 'electron'; import fs = require('fs');
import fs from 'fs';
let app: Electron.App = null; let app: Electron.App = null;
let setupCompleted = false; let setupCompleted = false;
if (process.type === 'renderer') { if (process.type === 'renderer') {
app = electron.remote.app; app = require('electron').remote.app;
} else { } else {
app = electron.app; app = require('electron').app;
} }
const zulipDir = app.getPath('userData'); const zulipDir = app.getPath('userData');
@@ -14,7 +13,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) {
@@ -42,19 +41,19 @@ export const initSetUp = (): void => {
const configData = [ const configData = [
{ {
path: domainJson, path: domainJson,
fileName: 'domain.json' fileName: `domain.json`
}, },
{ {
path: certificatesJson, path: certificatesJson,
fileName: 'certificates.json' fileName: `certificates.json`
}, },
{ {
path: settingsJson, path: settingsJson,
fileName: 'settings.json' fileName: `settings.json`
}, },
{ {
path: updatesJson, path: updatesJson,
fileName: 'updates.json' fileName: `updates.json`
} }
]; ];
configData.forEach(data => { configData.forEach(data => {
@@ -63,7 +62,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);

View File

@@ -1,28 +1,30 @@
import * as ConfigUtil from './config-util'; 'use strict';
type SettingName = 'showNotification' | 'silent' | 'flashTaskbarOnMessage'; import ConfigUtil = require('./config-util');
export interface DNDSettings { // TODO: TypeScript - add to Setting interface
showNotification?: boolean; // the list of settings since we have fixed amount of them
silent?: boolean; // We want to do this by creating a new module that exports
flashTaskbarOnMessage?: boolean; // this interface
interface Setting {
[key: string]: any;
} }
interface Toggle { interface Toggle {
dnd: boolean; dnd: boolean;
newSettings: DNDSettings; newSettings: Setting;
} }
export function toggle(): Toggle { export function toggle(): Toggle {
const dnd = !ConfigUtil.getConfigItem('dnd', false); const dnd = !ConfigUtil.getConfigItem('dnd', false);
const dndSettingList: SettingName[] = ['showNotification', 'silent']; const dndSettingList = ['showNotification', 'silent'];
if (process.platform === 'win32') { if (process.platform === 'win32') {
dndSettingList.push('flashTaskbarOnMessage'); dndSettingList.push('flashTaskbarOnMessage');
} }
let newSettings: DNDSettings; let newSettings: Setting;
if (dnd) { if (dnd) {
const oldSettings: DNDSettings = {}; const oldSettings: Setting = {};
newSettings = {}; newSettings = {};
// Iterate through the dndSettingList. // Iterate through the dndSettingList.

View File

@@ -1,156 +1,169 @@
import {JsonDB} from 'node-json-db'; 'use strict';
import JsonDB from 'node-json-db';
import escape from 'escape-html'; import escape = require('escape-html');
import request from 'request'; import request = require('request');
import fs from 'fs'; import fs = require('fs');
import path from 'path'; import path = require('path');
import Logger from './logger-util'; import Logger = require('./logger-util');
import {remote} from 'electron'; import electron = require('electron');
import * as RequestUtil from './request-util'; import RequestUtil = require('./request-util');
import * as EnterpriseUtil from './enterprise-util'; import EnterpriseUtil = require('./enterprise-util');
import * as Messages from '../../../resources/messages'; import Messages = require('../../../resources/messages');
const {app, dialog} = remote; const { ipcRenderer } = electron;
const { app, dialog } = electron.remote;
export interface ServerConf {
url: string;
alias?: string;
icon?: string;
ignoreCerts?: boolean;
}
const logger = new Logger({ const logger = new Logger({
file: 'domain-util.log', file: `domain-util.log`,
timestamp: true timestamp: true
}); });
let instance: null | DomainUtil = null;
const defaultIconUrl = '../renderer/img/icon.png'; const defaultIconUrl = '../renderer/img/icon.png';
let db: JsonDB; class DomainUtil {
db: JsonDB;
reloadDB(); constructor() {
// Migrate from old schema if (instance) {
if (db.getData('/').domain) { return instance;
(async () => { } else {
await addDomain({ instance = this;
alias: 'Zulip',
url: db.getData('/domain')
});
db.delete('/domain');
})();
}
export function getDomains(): ServerConf[] {
reloadDB();
if (db.getData('/').domains === undefined) {
return [];
} }
return db.getData('/domains'); this.reloadDB();
} // Migrate from old schema
if (this.db.getData('/').domain) {
this.addDomain({
alias: 'Zulip',
url: this.db.getData('/domain')
});
this.db.delete('/domain');
}
export function getDomain(index: number): ServerConf { return instance;
reloadDB(); }
return db.getData(`/domains[${index}]`);
}
export function shouldIgnoreCerts(url: string): boolean { getDomains(): any {
const domains = getDomains(); this.reloadDB();
if (this.db.getData('/').domains === undefined) {
return [];
} else {
return this.db.getData('/domains');
}
}
getDomain(index: number): any {
this.reloadDB();
return this.db.getData(`/domains[${index}]`);
}
shouldIgnoreCerts(url: string): boolean {
const domains = this.getDomains();
for (const domain of domains) { for (const domain of domains) {
if (domain.url === url) { if (domain.url === url) {
return domain.ignoreCerts; return domain.ignoreCerts;
} }
} }
return null; return null;
} }
export function updateDomain(index: number, server: ServerConf): void { updateDomain(index: number, server: object): void {
reloadDB(); this.reloadDB();
db.push(`/domains[${index}]`, server, true); this.db.push(`/domains[${index}]`, server, true);
} }
export async function addDomain(server: ServerConf): Promise<void> { addDomain(server: any): Promise<void> {
const {ignoreCerts} = server; const { ignoreCerts } = server;
return new Promise(resolve => {
if (server.icon) { if (server.icon) {
const localIconUrl = await saveServerIcon(server, ignoreCerts); this.saveServerIcon(server, ignoreCerts).then(localIconUrl => {
server.icon = localIconUrl; server.icon = localIconUrl;
db.push('/domains[]', server, true); this.db.push('/domains[]', server, true);
reloadDB(); this.reloadDB();
resolve();
});
} else { } else {
server.icon = defaultIconUrl; server.icon = defaultIconUrl;
db.push('/domains[]', server, true); this.db.push('/domains[]', server, true);
reloadDB(); this.reloadDB();
resolve();
}
});
} }
}
export function removeDomains(): void { removeDomains(): void {
db.delete('/domains'); this.db.delete('/domains');
reloadDB(); this.reloadDB();
} }
export function removeDomain(index: number): boolean { removeDomain(index: number): boolean {
if (EnterpriseUtil.isPresetOrg(getDomain(index).url)) { if (EnterpriseUtil.isPresetOrg(this.getDomain(index).url)) {
return false;
}
this.db.delete(`/domains[${index}]`);
this.reloadDB();
return true;
}
// Check if domain is already added
duplicateDomain(domain: any): boolean {
domain = this.formatUrl(domain);
const servers = this.getDomains();
for (const i in servers) {
if (servers[i].url === domain) {
return true;
}
}
return false; return false;
} }
db.delete(`/domains[${index}]`); async checkCertError(domain: any, serverConf: any, error: string, silent: boolean): Promise<string | object> {
reloadDB();
return true;
}
// Check if domain is already added
export function duplicateDomain(domain: string): boolean {
domain = formatUrl(domain);
return getDomains().some(server => server.url === domain);
}
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 // Report error to sentry to get idea of possible certificate errors
// users get when adding the servers // users get when adding the servers
logger.reportSentry(error); logger.reportSentry(new Error(error).toString());
const certErrorMessage = Messages.certErrorMessage(domain, error); const certErrorMessage = Messages.certErrorMessage(domain, error);
const certErrorDetail = Messages.certErrorDetail(); const certErrorDetail = Messages.certErrorDetail();
const {response} = await dialog.showMessageBox({ const response = await (dialog.showMessageBox({
type: 'warning', type: 'warning',
buttons: ['Yes', 'No'], buttons: ['Yes', 'No'],
defaultId: 1, defaultId: 1,
message: certErrorMessage, message: certErrorMessage,
detail: certErrorDetail detail: certErrorDetail
}); }) as any); // TODO: TypeScript - Figure this out
if (response === 0) { if (response === 0) {
// Set ignoreCerts parameter to true in case user responds with yes // set ignoreCerts parameter to true in case user responds with yes
serverConf.ignoreCerts = true; serverConf.ignoreCerts = true;
try { try {
return await getServerSettings(domain, serverConf.ignoreCerts); return await this.getServerSettings(domain, serverConf.ignoreCerts);
} catch (_) { } catch (_) {
if (error === Messages.noOrgsError(domain)) { if (error === Messages.noOrgsError(domain)) {
throw new Error(error); throw new Error(error);
} }
return serverConf; return serverConf;
} }
} else { } else {
throw new Error('Untrusted certificate.'); throw new Error('Untrusted certificate.');
} }
} }
}
// ignoreCerts parameter helps in fetching server icon and // ignoreCerts parameter helps in fetching server icon and
// other server details when user chooses to ignore certificate warnings // other server details when user chooses to ignore certificate warnings
export async function checkDomain(domain: string, ignoreCerts = false, silent = false): Promise<ServerConf> { async checkDomain(domain: any, ignoreCerts = false, silent = false): Promise<any> {
if (!silent && duplicateDomain(domain)) { if (!silent && this.duplicateDomain(domain)) {
// Do not check duplicate in silent mode // Do not check duplicate in silent mode
throw new Error('This server has been added.'); throw new Error('This server has been added.');
} }
domain = formatUrl(domain); domain = this.formatUrl(domain);
const serverConf = { const serverConf = {
icon: defaultIconUrl, icon: defaultIconUrl,
@@ -160,43 +173,43 @@ export async function checkDomain(domain: string, ignoreCerts = false, silent =
}; };
try { try {
return await getServerSettings(domain, serverConf.ignoreCerts); return await this.getServerSettings(domain, serverConf.ignoreCerts);
} catch (error_) { } catch (err) {
// Make sure that error is an error or string not undefined // If the domain contains following strings we just bypass the server
const whitelistDomains = [
'zulipdev.org'
];
// 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 = error_ || ''; const error = err || '';
const certsError = error.toString().includes('certificate'); const certsError = error.toString().includes('certificate');
if (certsError) { if (domain.indexOf(whitelistDomains) >= 0 || certsError) {
const result = await checkCertError(domain, serverConf, error, silent); return this.checkCertError(domain, serverConf, error, silent);
return result; } else {
throw Messages.invalidZulipServerError(domain);
}
}
} }
throw new Error(Messages.invalidZulipServerError(domain)); getServerSettings(domain: any, ignoreCerts = false): Promise<object | string> {
}
}
async function getServerSettings(domain: string, ignoreCerts = false): Promise<ServerConf> {
const serverSettingsOptions = { const serverSettingsOptions = {
url: domain + '/api/v1/server_settings', url: domain + '/api/v1/server_settings',
...RequestUtil.requestOptions(domain, ignoreCerts) ...RequestUtil.requestOptions(domain, ignoreCerts)
}; };
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
request(serverSettingsOptions, (error: Error, response: request.Response) => { request(serverSettingsOptions, (error: string, response: any) => {
if (!error && response.statusCode === 200) { if (!error && response.statusCode === 200) {
const {realm_name, realm_uri, realm_icon} = JSON.parse(response.body); const data = JSON.parse(response.body);
if ( if (data.hasOwnProperty('realm_icon') && data.realm_icon) {
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: realm_icon.startsWith('/') ? realm_uri + realm_icon : realm_icon, icon: data.realm_icon.startsWith('/') ? data.realm_uri + data.realm_icon : data.realm_icon,
url: realm_uri, url: data.realm_uri,
alias: escape(realm_name), alias: escape(data.realm_name),
ignoreCerts ignoreCerts
}); });
} else { } else {
@@ -207,9 +220,9 @@ async function getServerSettings(domain: string, ignoreCerts = false): Promise<S
} }
}); });
}); });
} }
export async function saveServerIcon(server: ServerConf, ignoreCerts = false): Promise<string> { saveServerIcon(server: any, ignoreCerts = false): Promise<string> {
const url = server.icon; const url = server.icon;
const domain = server.url; const domain = server.url;
@@ -220,11 +233,11 @@ export async function saveServerIcon(server: ServerConf, ignoreCerts = false): P
// The save will always succeed. If url is invalid, downgrade to default icon. // The save will always succeed. If url is invalid, downgrade to default icon.
return new Promise(resolve => { return new Promise(resolve => {
const filePath = generateFilePath(url); const filePath = this.generateFilePath(url);
const file = fs.createWriteStream(filePath); const file = fs.createWriteStream(filePath);
try { try {
request(serverIconOptions).on('response', (response: request.Response) => { request(serverIconOptions).on('response', (response: any) => {
response.on('error', (err: Error) => { response.on('error', (err: string) => {
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);
@@ -233,46 +246,44 @@ 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: Error) => { }).on('error', (err: string) => {
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 (error) { } catch (err) {
logger.log('Could not get server icon.'); logger.log('Could not get server icon.');
logger.log(error); logger.log(err);
logger.reportSentry(error); logger.reportSentry(err);
resolve(defaultIconUrl); resolve(defaultIconUrl);
} }
}); });
} }
export async function updateSavedServer(url: string, index: number): Promise<void> { async updateSavedServer(url: string, index: number): Promise<void> {
// Does not promise successful update // Does not promise successful update
const oldIcon = getDomain(index).icon; const oldIcon = this.getDomain(index).icon;
const {ignoreCerts} = getDomain(index); const { ignoreCerts } = this.getDomain(index);
try { try {
const newServerConf = await checkDomain(url, ignoreCerts, true); const newServerConf = await this.checkDomain(url, ignoreCerts, true);
const localIconUrl = await saveServerIcon(newServerConf, ignoreCerts); const localIconUrl = await this.saveServerIcon(newServerConf, ignoreCerts);
if (!oldIcon || localIconUrl !== '../renderer/img/icon.png') { if (!oldIcon || localIconUrl !== '../renderer/img/icon.png') {
newServerConf.icon = localIconUrl; newServerConf.icon = localIconUrl;
updateDomain(index, newServerConf); this.updateDomain(index, newServerConf);
reloadDB(); this.reloadDB();
}
} catch (err) {
ipcRenderer.send('forward-message', 'show-network-error', index);
} }
} catch (error) {
logger.log('Could not update server icon.');
logger.log(error);
logger.reportSentry(error);
} }
}
function reloadDB(): void { 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 (error) { } catch (err) {
if (fs.existsSync(domainJsonPath)) { if (fs.existsSync(domainJsonPath)) {
fs.unlinkSync(domainJsonPath); fs.unlinkSync(domainJsonPath);
dialog.showErrorBox( dialog.showErrorBox(
@@ -281,23 +292,22 @@ 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(error); logger.error(err);
logger.reportSentry(error); logger.reportSentry(err);
} }
} }
this.db = new JsonDB(domainJsonPath, true, true);
}
db = new JsonDB(domainJsonPath, true, true); generateFilePath(url: string): string {
}
function generateFilePath(url: string): string {
const dir = `${app.getPath('userData')}/server-icons`; const dir = `${app.getPath('userData')}/server-icons`;
const extension = path.extname(url).split('?')[0]; const extension = path.extname(url).split('?')[0];
let hash = 5381; let hash = 5381;
let {length} = url; let len = url.length;
while (length) { while (len) {
hash = (hash * 33) ^ url.charCodeAt(--length); hash = (hash * 33) ^ url.charCodeAt(--len);
} }
// Create 'server-icons' directory if not existed // Create 'server-icons' directory if not existed
@@ -306,16 +316,16 @@ function generateFilePath(url: string): string {
} }
return `${dir}/${hash >>> 0}${extension}`; return `${dir}/${hash >>> 0}${extension}`;
} }
export function formatUrl(domain: string): string { formatUrl(domain: any): string {
if (domain.startsWith('http://') || domain.startsWith('https://')) { const hasPrefix = (domain.indexOf('http') === 0);
if (hasPrefix) {
return domain; return domain;
} else {
return (domain.indexOf('localhost:') >= 0) ? `http://${domain}` : `https://${domain}`;
} }
if (domain.startsWith('localhost:')) {
return `http://${domain}`;
} }
return `https://${domain}`;
} }
export = new DomainUtil();

View File

@@ -1,20 +1,29 @@
import fs from 'fs'; import fs = require('fs');
import path from 'path'; import path = require('path');
import Logger from './logger-util'; import Logger = require('./logger-util');
const logger = new Logger({ const logger = new Logger({
file: 'enterprise-util.log', file: 'enterprise-util.log',
timestamp: true timestamp: true
}); });
// TODO: replace enterpriseSettings type with an interface once settings are final let instance: null | EnterpriseUtil = null;
let enterpriseSettings: {[key: string]: unknown};
let configFile: boolean;
reloadDB(); class EnterpriseUtil {
// todo: replace enterpriseSettings type with an interface once settings are final
enterpriseSettings: any;
configFile: boolean;
constructor() {
if (instance) {
return instance;
}
instance = this;
function reloadDB(): void { this.reloadDB();
}
reloadDB(): void {
let enterpriseFile = '/etc/zulip-desktop-config/global_config.json'; let enterpriseFile = '/etc/zulip-desktop-config/global_config.json';
if (process.platform === 'win32') { if (process.platform === 'win32') {
enterpriseFile = 'C:\\Program Files\\Zulip-Desktop-Config\\global_config.json'; enterpriseFile = 'C:\\Program Files\\Zulip-Desktop-Config\\global_config.json';
@@ -22,60 +31,50 @@ function reloadDB(): void {
enterpriseFile = path.resolve(enterpriseFile); enterpriseFile = path.resolve(enterpriseFile);
if (fs.existsSync(enterpriseFile)) { if (fs.existsSync(enterpriseFile)) {
configFile = true; this.configFile = true;
try { try {
const file = fs.readFileSync(enterpriseFile, 'utf8'); const file = fs.readFileSync(enterpriseFile, 'utf8');
enterpriseSettings = JSON.parse(file); this.enterpriseSettings = JSON.parse(file);
} catch (error) { } catch (err) {
logger.log('Error while JSON parsing global_config.json: '); logger.log('Error while JSON parsing global_config.json: ');
logger.log(error); logger.log(err);
} }
} else { } else {
configFile = false; this.configFile = false;
}
} }
}
export function hasConfigFile(): boolean { getConfigItem(key: string, defaultValue?: any): any {
return configFile; this.reloadDB();
} if (!this.configFile) {
export function getConfigItem(key: string, defaultValue?: unknown): any {
reloadDB();
if (!configFile) {
return defaultValue; return defaultValue;
} }
if (defaultValue === undefined) { if (defaultValue === undefined) {
defaultValue = null; defaultValue = null;
} }
return this.configItemExists(key) ? this.enterpriseSettings[key] : defaultValue;
}
return configItemExists(key) ? enterpriseSettings[key] : defaultValue; configItemExists(key: string): boolean {
} this.reloadDB();
if (!this.configFile) {
export function configItemExists(key: string): boolean {
reloadDB();
if (!configFile) {
return false; return false;
} }
return (this.enterpriseSettings[key] !== undefined);
}
return (enterpriseSettings[key] !== undefined); isPresetOrg(url: string): boolean {
} if (!this.configFile || !this.configItemExists('presetOrganizations')) {
export function isPresetOrg(url: string): boolean {
if (!configFile || !configItemExists('presetOrganizations')) {
return false; return false;
} }
const presetOrgs = this.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;
}
} }
export = new EnterpriseUtil();

View File

@@ -1,45 +1,51 @@
import {shell} from 'electron'; 'use strict';
import escape from 'escape-html';
import fs from 'fs';
import os from 'os';
import path from 'path';
export function isUploadsUrl(server: string, url: URL): boolean { // TODO: TypeScript - Add @types/
return url.origin === server && url.pathname.startsWith('/user_uploads/'); import wurl = require('wurl');
let instance: null | LinkUtil = null;
interface IsInternalResponse {
isInternalUrl: boolean;
isUploadsUrl: boolean;
} }
export async function openBrowser(url: URL): Promise<void> { class LinkUtil {
if (['http:', 'https:', 'mailto:'].includes(url.protocol)) { constructor() {
await shell.openExternal(url.href); if (instance) {
return instance;
} else { } else {
// For security, indirect links to non-whitelisted protocols instance = this;
// through a real web browser via a local HTML file.
const dir = fs.mkdtempSync(
path.join(os.tmpdir(), 'zulip-redirect-')
);
const file = path.join(dir, 'redirect.html');
fs.writeFileSync(file, `\
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<meta http-equiv="Refresh" content="0; url=${escape(url.href)}" />
<title>Redirecting</title>
<style>
html {
font-family: menu, "Helvetica Neue", sans-serif;
} }
</style>
</head> return instance;
<body> }
<p>Opening <a href="${escape(url.href)}">${escape(url.href)}</a>…</p>
</body> isInternal(currentUrl: string, newUrl: string): IsInternalResponse {
</html> const currentDomain = wurl('hostname', currentUrl);
`); const newDomain = wurl('hostname', newUrl);
shell.openItem(file);
setTimeout(() => { const sameDomainUrl = (currentDomain === newDomain || newUrl === currentUrl + '/');
fs.unlinkSync(file); const isUploadsUrl = newUrl.includes(currentUrl + '/user_uploads/');
fs.rmdirSync(dir); const isInternalUrl = newUrl.includes('/#narrow') || isUploadsUrl;
}, 15000);
return {
isInternalUrl: sameDomainUrl && isInternalUrl,
isUploadsUrl
};
}
isImage(url: string): boolean {
// test for images extension as well as urls like .png?s=100
const isImageUrl = /\.(bmp|gif|jpg|jpeg|png|webp)\?*.*$/i;
return isImageUrl.test(url);
}
isPDF(url: string): boolean {
// test for pdf extension
const isPDFUrl = /\.(pdf)\?*.*$/i;
return isPDFUrl.test(url);
} }
} }
export = new LinkUtil();

View File

@@ -1,9 +1,10 @@
import {JsonDB} from 'node-json-db'; 'use strict';
import JsonDB from 'node-json-db';
import fs from 'fs'; import fs = require('fs');
import path from 'path'; import path = require('path');
import electron from 'electron'; import electron = require('electron');
import Logger from './logger-util'; import Logger = require('./logger-util');
const remote = const remote =
process.type === 'renderer' ? electron.remote : electron; process.type === 'renderer' ? electron.remote : electron;
@@ -14,39 +15,50 @@ 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 instance: null | LinuxUpdateUtil = null;
let db: JsonDB; class LinuxUpdateUtil {
db: JsonDB;
reloadDB(); constructor() {
if (instance) {
export function getUpdateItem(key: string, defaultValue: unknown = null): any { return instance;
reloadDB(); } else {
const value = db.getData('/')[key]; instance = this;
if (value === undefined) {
setUpdateItem(key, defaultValue);
return defaultValue;
} }
this.reloadDB();
return instance;
}
getUpdateItem(key: string, defaultValue: any = null): any {
this.reloadDB();
const value = this.db.getData('/')[key];
if (value === undefined) {
this.setUpdateItem(key, defaultValue);
return defaultValue;
} else {
return value; return value;
} }
}
export function setUpdateItem(key: string, value: unknown): void { setUpdateItem(key: string, value: any): void {
db.push(`/${key}`, value, true); this.db.push(`/${key}`, value, true);
reloadDB(); this.reloadDB();
} }
export function removeUpdateItem(key: string): void { removeUpdateItem(key: string): void {
db.delete(`/${key}`); this.db.delete(`/${key}`);
reloadDB(); this.reloadDB();
} }
function reloadDB(): void { reloadDB(): void {
const linuxUpdateJsonPath = path.join(app.getPath('userData'), '/config/updates.json'); const linuxUpdateJsonPath = path.join(app.getPath('userData'), '/config/updates.json');
try { try {
const file = fs.readFileSync(linuxUpdateJsonPath, 'utf8'); const file = fs.readFileSync(linuxUpdateJsonPath, 'utf8');
JSON.parse(file); JSON.parse(file);
} catch (error) { } catch (err) {
if (fs.existsSync(linuxUpdateJsonPath)) { if (fs.existsSync(linuxUpdateJsonPath)) {
fs.unlinkSync(linuxUpdateJsonPath); fs.unlinkSync(linuxUpdateJsonPath);
dialog.showErrorBox( dialog.showErrorBox(
@@ -54,9 +66,11 @@ 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(error); logger.error(err);
} }
} }
this.db = new JsonDB(linuxUpdateJsonPath, true, true);
db = new JsonDB(linuxUpdateJsonPath, true, true); }
} }
export = new LinuxUpdateUtil();

View File

@@ -1,14 +1,19 @@
import {Console} from 'console'; // eslint-disable-line node/prefer-global/console import { Console as NodeConsole } 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 = require('fs');
import os from 'os'; import os = require('os');
import isDev from 'electron-is-dev'; import isDev = require('electron-is-dev');
import electron from 'electron'; import electron = require('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?: any;
file?: string; file?: string;
level?: boolean; level?: boolean;
logInDevMode?: boolean; logInDevMode?: boolean;
@@ -24,9 +29,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: Event, errorReporting: boolean) => { ipcRenderer.on('error-reporting-val', (_event: any, errorReporting: boolean) => {
reportErrors = errorReporting; reportErrors = errorReporting;
if (reportErrors) { if (reportErrors) {
sentryInit(); sentryInit();
@@ -36,31 +41,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'; class Logger {
const levels: Level[] = ['log', 'debug', 'info', 'warn', 'error']; nodeConsole: PatchedConsole;
type LogMethod = (...args: unknown[]) => void; timestamp: any; // TODO: TypeScript - Figure out how to make this work with string | Function.
export default class Logger {
log: LogMethod;
debug: LogMethod;
info: LogMethod;
warn: LogMethod;
error: LogMethod;
nodeConsole: Console;
timestamp?: () => string;
level: boolean; level: boolean;
logInDevMode: boolean; logInDevMode: boolean;
[key: string]: any;
constructor(options: LoggerOptions = {}) { constructor(opts: LoggerOptions = {}) {
let { let {
timestamp = true, timestamp = true,
file = 'console.log', file = 'console.log',
level = true, level = true,
logInDevMode = false logInDevMode = false
} = options; } = opts;
file = `${logDir}/${file}`; file = `${logDir}/${file}`;
if (timestamp === true) { if (timestamp === true) {
@@ -74,8 +71,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 Console(fileStream); const nodeConsole = new NodeConsole(fileStream);
this.nodeConsole = nodeConsole; this.nodeConsole = nodeConsole;
this.timestamp = timestamp; this.timestamp = timestamp;
@@ -84,37 +81,42 @@ export default class Logger {
this.setUpConsole(); this.setUpConsole();
} }
_log(type: Level, ...args: unknown[]): void { _log(type: string, ...args: any[]): 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) {
case typeof timestamp === 'function': case typeof timestamp === 'function':
args.unshift(timestamp() + ' |\t'); args.unshift(timestamp() + ' |\t');
case (level): case (level !== false):
args.unshift(type.toUpperCase() + ' |'); args.unshift(type.toUpperCase() + ' |');
case isDev || logInDevMode: case isDev || logInDevMode:
nodeConsole[type](...args); nodeConsoleLog = nodeConsole[type] || nodeConsole.log;
nodeConsoleLog.apply(null, args); // eslint-disable-line prefer-spread
default: break; default: break;
} }
/* eslint-enable no-fallthrough */ /* eslint-enable no-fallthrough */
console[type](...args); browserConsole[type].apply(null, args);
} }
setUpConsole(): void { setUpConsole(): void {
for (const type of levels) { for (const type in browserConsole) {
this.setupConsoleMethod(type); this.setupConsoleMethod(type);
} }
} }
setupConsoleMethod(type: Level): void { setupConsoleMethod(type: string): void {
this[type] = (...args: unknown[]) => this._log(type, ...args); this[type] = (...args: any[]) => {
const log = this._log.bind(this, type, ...args);
log();
};
} }
getTimestamp(): string { getTimestamp(): string {
@@ -125,7 +127,7 @@ export default class Logger {
return timestamp; return timestamp;
} }
reportSentry(err: unknown): void { reportSentry(err: string): void {
if (reportErrors) { if (reportErrors) {
captureException(err); captureException(err);
} }
@@ -136,7 +138,6 @@ 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;
@@ -150,3 +151,5 @@ export default class Logger {
}); });
} }
} }
export = Logger;

View File

@@ -0,0 +1,11 @@
// This util function returns the page params if they're present else returns null
export function isPageParams(): null | object {
let webpageParams = null;
try {
// eslint-disable-next-line no-undef, @typescript-eslint/camelcase
webpageParams = page_params;
} catch (_) {
webpageParams = null;
}
return webpageParams;
}

View File

@@ -1,19 +1,35 @@
import * as ConfigUtil from './config-util'; 'use strict';
export interface ProxyRule { import url = require('url');
import ConfigUtil = require('./config-util');
let instance: null | ProxyUtil = null;
interface ProxyRule {
hostname?: string; hostname?: string;
port?: number; port?: number;
} }
// Return proxy to be used for a particular uri, to be used for request class ProxyUtil {
export function getProxy(_uri: string): ProxyRule | void { constructor() {
let uri; if (instance) {
try { return instance;
uri = new URL(_uri); } else {
} catch (_) { instance = this;
}
return instance;
}
// Return proxy to be used for a particular uri, to be used for request
getProxy(_uri: string): ProxyRule | void {
const parsedUri = url.parse(_uri);
if (parsedUri === null) {
return; return;
} }
const uri = parsedUri;
const proxyRules = ConfigUtil.getConfigItem('proxyRules', '').split(';'); const proxyRules = ConfigUtil.getConfigItem('proxyRules', '').split(';');
// If SPS is on and system uses no proxy then request should not try to use proxy from // If SPS is on and system uses no proxy then request should not try to use proxy from
// environment. NO_PROXY = '*' makes request ignore all environment proxy variables. // environment. NO_PROXY = '*' makes request ignore all environment proxy variables.
@@ -42,59 +58,59 @@ export function getProxy(_uri: string): ProxyRule | void {
}); });
return proxyRule; return proxyRule;
} }
} }
// TODO: Refactor to async function // TODO: Refactor to async function
export async function resolveSystemProxy(mainWindow: Electron.BrowserWindow): Promise<void> { resolveSystemProxy(mainWindow: Electron.BrowserWindow): void {
const page = mainWindow.webContents; const page = mainWindow.webContents;
const ses = page.session; const ses = page.session;
const resolveProxyUrl = 'www.example.com'; const resolveProxyUrl = 'www.example.com';
// Check HTTP Proxy // Check HTTP Proxy
const httpProxy = (async () => { const httpProxy = new Promise(resolve => {
const proxy = await ses.resolveProxy('http://' + resolveProxyUrl); ses.resolveProxy('http://' + resolveProxyUrl, (proxy: string) => {
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] + ';';
} }
} }
resolve(httpString);
return httpString; });
})(); });
// Check HTTPS Proxy // Check HTTPS Proxy
const httpsProxy = (async () => { const httpsProxy = new Promise(resolve => {
const proxy = await ses.resolveProxy('https://' + resolveProxyUrl); ses.resolveProxy('https://' + resolveProxyUrl, (proxy: string) => {
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] + ';';
} }
} }
resolve(httpsString);
return httpsString; });
})(); });
// Check FTP Proxy // Check FTP Proxy
const ftpProxy = (async () => { const ftpProxy = new Promise(resolve => {
const proxy = await ses.resolveProxy('ftp://' + resolveProxyUrl); ses.resolveProxy('ftp://' + resolveProxyUrl, (proxy: string) => {
let ftpString = ''; let ftpString = '';
if (proxy !== 'DIRECT') { if (proxy !== 'DIRECT') {
if (proxy.includes('PROXY')) { if (proxy.includes('PROXY')) {
ftpString += 'ftp=' + proxy.split('PROXY')[1] + ';'; ftpString += 'ftp=' + proxy.split('PROXY')[1] + ';';
} }
} }
resolve(ftpString);
return ftpString; });
})(); });
// Check SOCKS Proxy // Check SOCKS Proxy
const socksProxy = (async () => { const socksProxy = new Promise(resolve => {
const proxy = await ses.resolveProxy('socks4://' + resolveProxyUrl); ses.resolveProxy('socks4://' + resolveProxyUrl, (proxy: string) => {
let socksString = ''; let socksString = '';
if (proxy !== 'DIRECT') { if (proxy !== 'DIRECT') {
if (proxy.includes('SOCKS5')) { if (proxy.includes('SOCKS5')) {
@@ -105,11 +121,11 @@ export async function resolveSystemProxy(mainWindow: Electron.BrowserWindow): Pr
socksString += 'socks=' + proxy.split('PROXY')[1] + ';'; socksString += 'socks=' + proxy.split('PROXY')[1] + ';';
} }
} }
resolve(socksString);
});
});
return socksString; Promise.all([httpProxy, httpsProxy, ftpProxy, socksProxy]).then(values => {
})();
const values = await Promise.all([httpProxy, httpsProxy, ftpProxy, socksProxy]);
let proxyString = ''; let proxyString = '';
values.forEach(proxy => { values.forEach(proxy => {
proxyString += proxy; proxyString += proxy;
@@ -119,4 +135,8 @@ export async function resolveSystemProxy(mainWindow: Electron.BrowserWindow): Pr
if (useSystemProxy) { if (useSystemProxy) {
ConfigUtil.setConfigItem('proxyRules', proxyString); ConfigUtil.setConfigItem('proxyRules', proxyString);
} }
});
}
} }
export = new ProxyUtil();

View File

@@ -1,24 +1,26 @@
import {ipcRenderer} from 'electron'; import { ipcRenderer } from 'electron';
import type WebView from '../components/webview'; import backoff = require('backoff');
import backoff from 'backoff'; import request = require('request');
import request from 'request'; import Logger = require('./logger-util');
import Logger from './logger-util'; import RequestUtil = require('./request-util');
import * as RequestUtil from './request-util'; import DomainUtil = require('./domain-util');
import * as DomainUtil from './domain-util';
const logger = new Logger({ const logger = new Logger({
file: 'domain-util.log', file: `domain-util.log`,
timestamp: true timestamp: true
}); });
export default class ReconnectUtil { class ReconnectUtil {
webview: WebView; // TODO: TypeScript - Figure out how to annotate webview
// it should be WebView; maybe make it a generic so we can
// pass the class from main.ts
webview: any;
url: string; url: string;
alreadyReloaded: boolean; alreadyReloaded: boolean;
fibonacciBackoff: backoff.Backoff; fibonacciBackoff: any;
constructor(webview: WebView) { constructor(webview: any) {
this.webview = webview; this.webview = webview;
this.url = webview.props.url; this.url = webview.props.url;
this.alreadyReloaded = false; this.alreadyReloaded = false;
@@ -32,61 +34,69 @@ export default class ReconnectUtil {
}); });
} }
async isOnline(): Promise<boolean> { isOnline(): Promise<boolean> {
return new Promise(resolve => { return new Promise(resolve => {
try { try {
const ignoreCerts = DomainUtil.shouldIgnoreCerts(this.url); const ignoreCerts = DomainUtil.shouldIgnoreCerts(this.url);
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: request.Response) => { (error: Error, response: any) => {
const isValidResponse = const isValidResponse =
!error && response.statusCode >= 200 && response.statusCode < 400; !error && response.statusCode >= 200 && response.statusCode < 400;
resolve(isValidResponse); resolve(isValidResponse);
} }
); );
} catch (error) { } catch (err) {
logger.log(error); logger.log(err);
} }
}); });
} }
pollInternetAndReload(): void { pollInternetAndReload(): void {
this.fibonacciBackoff.backoff(); this.fibonacciBackoff.backoff();
this.fibonacciBackoff.on('ready', async () => { this.fibonacciBackoff.on('ready', () => {
if (await this._checkAndReload()) { this._checkAndReload().then(status => {
if (status) {
this.fibonacciBackoff.reset(); this.fibonacciBackoff.reset();
} else { } else {
this.fibonacciBackoff.backoff(); this.fibonacciBackoff.backoff();
} }
}); });
});
} }
async _checkAndReload(): Promise<boolean> { // TODO: Make this a async function
if (this.alreadyReloaded) { _checkAndReload(): Promise<boolean> {
return true; return new Promise(resolve => {
} if (!this.alreadyReloaded) { // eslint-disable-line no-negated-condition
this.isOnline()
if (await this.isOnline()) { .then((online: boolean) => {
if (online) {
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 resolve(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 errMsgHolder = document.querySelector('#description');
if (errorMessageHolder) { if (errMsgHolder) {
errorMessageHolder.innerHTML = ` errMsgHolder.innerHTML = `
<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 resolve(false);
return false; });
} else {
return resolve(true);
}
});
} }
} }
export = ReconnectUtil;

View File

@@ -1,39 +1,52 @@
import {remote} from 'electron'; import { remote } from 'electron';
import fs from 'fs'; import fs = require('fs');
import path from 'path'; import path = require('path');
import * as ConfigUtil from './config-util'; import ConfigUtil = require('./config-util');
import Logger from './logger-util'; import Logger = require('./logger-util');
import * as ProxyUtil from './proxy-util'; import ProxyUtil = require('./proxy-util');
import * as CertificateUtil from './certificate-util'; import CertificateUtil = require('./certificate-util');
import * as SystemUtil from './system-util'; import SystemUtil = require('./system-util');
const {app} = remote; const { app } = remote;
const logger = new Logger({ const logger = new Logger({
file: 'request-util.log', file: `request-util.log`,
timestamp: true timestamp: true
}); });
let instance: null | RequestUtil = null;
// TODO: TypeScript - Use ProxyRule for the proxy property
// we can do this now since we use export = ProxyUtil syntax
interface RequestUtilResponse { interface RequestUtilResponse {
ca: string; ca: string;
proxy: string | void | ProxyUtil.ProxyRule; proxy: string | void | object;
ecdhCurve: 'auto'; ecdhCurve: 'auto';
headers: { 'User-Agent': string }; headers: { 'User-Agent': string };
rejectUnauthorized: boolean; rejectUnauthorized: boolean;
} }
// ignoreCerts parameter helps in fetching server icon and class RequestUtil {
// other server details when user chooses to ignore certificate warnings constructor() {
export function requestOptions(domain: string, ignoreCerts: boolean): RequestUtilResponse { if (!instance) {
domain = formatUrl(domain); instance = this;
}
return instance;
}
// ignoreCerts parameter helps in fetching server icon and
// other server details when user chooses to ignore certificate warnings
requestOptions(domain: string, ignoreCerts: boolean): RequestUtilResponse {
domain = this.formatUrl(domain);
const certificate = CertificateUtil.getCertificate( const certificate = CertificateUtil.getCertificate(
encodeURIComponent(domain) encodeURIComponent(domain)
); );
let certificateFile = null; let certificateFile = null;
if (certificate?.includes('/')) { if (certificate && 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,11 +57,10 @@ 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 (error) { } catch (err) {
logger.warn('Error while trying to get certificate:', error); logger.warn(`Error while trying to get certificate: ${err}`);
} }
} }
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.
@@ -56,16 +68,20 @@ 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
}; };
} }
function formatUrl(domain: string): string { 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}`;
}
}
} }
const requestUtil = new RequestUtil();
export = requestUtil;

View File

@@ -1,18 +1,21 @@
import {init} from '@sentry/electron'; import { init } from '@sentry/electron';
import isDev from 'electron-is-dev'; import isDev = require('electron-is-dev');
import path = require('path');
import dotenv = require('dotenv');
dotenv.config({ path: path.resolve(__dirname, '/../../../../.env') });
export const sentryInit = (): void => { export const sentryInit = (): void => {
if (!isDev) { if (!isDev) {
init({ init({
dsn: 'https://628dc2f2864243a08ead72e63f94c7b1@sentry.io/204668', dsn: process.env.SENTRY_DSN,
// We should ignore this error since it's harmless and we know the reason behind this // We should ignore this error since it's harmless and we know the reason behind this
// 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';

View File

@@ -1,39 +1,64 @@
import {ipcRenderer} from 'electron'; 'use strict';
import { remote } from 'electron';
import os from 'os'; import os = require('os');
import ConfigUtil = require('./config-util');
export const connectivityERR: string[] = [ const { app } = remote;
let instance: null | SystemUtil = null;
class SystemUtil {
connectivityERR: string[];
userAgent: string | null;
constructor() {
if (instance) {
return instance;
} else {
instance = this;
}
this.connectivityERR = [
'ERR_INTERNET_DISCONNECTED', 'ERR_INTERNET_DISCONNECTED',
'ERR_PROXY_CONNECTION_FAILED', 'ERR_PROXY_CONNECTION_FAILED',
'ERR_CONNECTION_RESET', 'ERR_CONNECTION_RESET',
'ERR_NOT_CONNECTED', 'ERR_NOT_CONNECTED',
'ERR_NAME_NOT_RESOLVED', 'ERR_NAME_NOT_RESOLVED',
'ERR_NETWORK_CHANGED' 'ERR_NETWORK_CHANGED'
]; ];
this.userAgent = null;
const userAgent = ipcRenderer.sendSync('fetch-user-agent'); return instance;
}
export function getOS(): string { getOS(): string {
const platform = os.platform(); const platform = os.platform();
if (platform === 'darwin') { if (platform === 'darwin') {
return 'Mac'; return 'Mac';
} } else if (platform === 'linux') {
if (platform === 'linux') {
return 'Linux'; return 'Linux';
} } else if (platform === 'win32') {
if (parseFloat(os.release()) < 6.2) {
if (platform === 'win32') {
if (Number.parseFloat(os.release()) < 6.2) {
return 'Windows 7'; return 'Windows 7';
} } else {
return 'Windows 10'; return 'Windows 10';
} }
} else {
return ''; return '';
}
}
setUserAgent(webViewUserAgent: string): void {
this.userAgent = `ZulipElectron/${app.getVersion()} ${webViewUserAgent}`;
}
getUserAgent(): string | null {
if (!this.userAgent) {
this.setUserAgent(ConfigUtil.getConfigItem('userAgent', null));
}
return this.userAgent;
}
} }
export function getUserAgent(): string { export = new SystemUtil();
return userAgent;
}

View File

@@ -1,15 +1,35 @@
import path from 'path'; 'use strict';
import i18n from 'i18n';
import * as ConfigUtil from './config-util';
i18n.configure({ import path = require('path');
directory: path.join(__dirname, '../../../translations/') import electron = require('electron');
}); import i18n = require('i18n');
/* Fetches the current appLocale from settings.json */ let instance: TranslationUtil = null;
const appLocale = ConfigUtil.getConfigItem('appLanguage'); let app: Electron.App = null;
/* If no locale present in the json, en is set default */ /* To make the util runnable in both main and renderer process */
export function __(phrase: string): string { if (process.type === 'renderer') {
return i18n.__({phrase, locale: appLocale ? appLocale : 'en'}); app = electron.remote.app;
} else {
app = electron.app;
} }
class TranslationUtil {
constructor() {
if (instance) {
return this;
}
instance = this;
i18n.configure({
directory: path.join(__dirname, '../../../translations/'),
register: this
});
}
__(phrase: string): string {
return i18n.__({ phrase, locale: app.getLocale() ? app.getLocale() : 'en' });
}
}
export = new TranslationUtil();

View File

@@ -23,4 +23,7 @@
</div> </div>
</div> </div>
</body> </body>
<script>var exports = {};</script>
<script src="js/preload.js"></script>
<script>require('./js/shared/preventdrag.js')</script>
</html> </html>

Binary file not shown.

View File

@@ -3,7 +3,8 @@ interface DialogBoxError {
content: string; content: string;
} }
export function invalidZulipServerError(domain: string): string { class Messages {
invalidZulipServerError(domain: string): string {
return `${domain} does not appear to be a valid Zulip server. Make sure that return `${domain} does not appear to be a valid Zulip server. Make sure that
\n • You can connect to that URL in a web browser.\ \n • You can connect to that URL in a web browser.\
\n • If you need a proxy to connect to the Internet, that you've configured your proxy in the Network settings.\ \n • If you need a proxy to connect to the Internet, that you've configured your proxy in the Network settings.\
@@ -11,39 +12,41 @@ export function invalidZulipServerError(domain: string): string {
\n • The server has a valid certificate. (You can add custom certificates in Settings > Organizations). \ \n • The server has a valid certificate. (You can add custom certificates in Settings > Organizations). \
\n • The SSL is correctly configured for the certificate. Check out the SSL troubleshooting guide - \n • The SSL is correctly configured for the certificate. Check out the SSL troubleshooting guide -
\n https://zulip.readthedocs.io/en/stable/production/ssl-certificates.html`; \n https://zulip.readthedocs.io/en/stable/production/ssl-certificates.html`;
} }
export function noOrgsError(domain: string): string { noOrgsError(domain: string): string {
return `${domain} does not have any organizations added.\ return `${domain} does not have any organizations added.\
\nPlease contact your server administrator.`; \nPlease contact your server administrator.`;
} }
export function certErrorMessage(domain: string, error: string): string { certErrorMessage(domain: string, error: string): string {
return `Do you trust certificate from ${domain}? \n ${error}`; return `Do you trust certificate from ${domain}? \n ${error}`;
} }
export function certErrorDetail(): string { certErrorDetail(): string {
return `The organization you're connecting to is either someone impersonating the Zulip server you entered, or the server you're trying to connect to is configured in an insecure way. return `The organization you're connecting to is either someone impersonating the Zulip server you entered, or the server you're trying to connect to is configured in an insecure way.
\nIf you have a valid certificate please add it from Settings>Organizations and try to add the organization again. \nIf you have a valid certificate please add it from Settings>Organizations and try to add the organization again.
\nUnless you have a good reason to believe otherwise, you should not proceed. \nUnless you have a good reason to believe otherwise, you should not proceed.
\nYou can click here if you'd like to proceed with the connection.`; \nYou can click here if you'd like to proceed with the connection.`;
} }
export function enterpriseOrgError(length: number, domains: string[]): DialogBoxError { enterpriseOrgError(length: number, domains: string[]): DialogBoxError {
let domainList = ''; let domainList = '';
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.`
}; };
} }
export function orgRemovalError(url: string): DialogBoxError { orgRemovalError(url: string): DialogBoxError {
return { return {
title: `Removing ${url} is a restricted operation.`, title: `Removing ${url} is a restricted operation.`,
content: 'Please contact your system administrator.' content: `Please contact your system administrator.`
}; };
}
} }
export = new Messages();

Binary file not shown.

Before

Width:  |  Height:  |  Size: 436 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 900 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 KiB

View File

Before

Width:  |  Height:  |  Size: 737 B

After

Width:  |  Height:  |  Size: 737 B

View File

Before

Width:  |  Height:  |  Size: 1.7 KiB

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

Before

Width:  |  Height:  |  Size: 2.8 KiB

After

Width:  |  Height:  |  Size: 2.8 KiB

View File

Before

Width:  |  Height:  |  Size: 3.8 KiB

After

Width:  |  Height:  |  Size: 3.8 KiB

View File

@@ -114,9 +114,5 @@
"Emoji & Symbols": "Emoji & Symbols", "Emoji & Symbols": "Emoji & Symbols",
"View Shortcuts": "View Shortcuts", "View Shortcuts": "View Shortcuts",
"Enter Full Screen": "Enter Full Screen", "Enter Full Screen": "Enter Full Screen",
"History Shortcuts": "History Shortcuts", "History Shortcuts": "History Shortcuts"
"Quit when the window is closed": "Quit when the window is closed",
"File": "File",
"Network and Proxy Settings": "Network and Proxy Settings",
"Ask where to save files before downloading": "Ask where to save files before downloading"
} }

View File

@@ -104,16 +104,5 @@
"Edit Shortcuts": "Edit Shortcuts", "Edit Shortcuts": "Edit Shortcuts",
"View Shortcuts": "View Shortcuts", "View Shortcuts": "View Shortcuts",
"History Shortcuts": "History Shortcuts", "History Shortcuts": "History Shortcuts",
"Window Shortcuts": "Window Shortcuts", "Window Shortcuts": "Window Shortcuts"
"Quit when the window is closed": "Quit when the window is closed",
"Force social login in app instead of browser": "Force social login in app instead of browser",
"Ask where to save files before downloading": "Ask where to save files before downloading",
"Add a Zulip organization": "Add a Zulip organization",
"Connect": "Connect",
"OR": "OR",
"Create a new organization": "Create a new organization",
"Network and Proxy Settings": "Network and Proxy Settings",
"YES": "YES",
"NO": "NO",
"Are you sure you want to disconnect this organization?": "Are you sure you want to disconnect this organization?"
} }

View File

@@ -114,6 +114,5 @@
"Zulip Help": "Zulip Help", "Zulip Help": "Zulip Help",
"keyboard shortcuts": "keyboard shortcuts", "keyboard shortcuts": "keyboard shortcuts",
"script": "script", "script": "script",
"Quit when the window is closed": "Quit when the window is closed", "Quit when the window is closed": "Quit when the window is closed"
"Ask where to save files before downloading": "Ask where to save files before downloading"
} }

View File

@@ -1,23 +0,0 @@
{
"bg": "Bulgarian",
"cs": "Czech",
"de": "Deutsch",
"en-GB": "English (UK)",
"en-US": "English (US)",
"en": "English",
"es": "Español",
"fr": "French",
"hi": "Hindi",
"hu": "Hungarian",
"id": "Indonesian",
"ja": "Japanese",
"ko": "Korean",
"ml": "Malayalam",
"nl": "Dutch",
"pl": "Polish",
"pt": "Portuguese",
"ru": "Russian",
"sr": "Macedonian",
"ta": "Tamil",
"tr": "Turkish"
}

View File

@@ -5,16 +5,17 @@ platform:
os: Previous Visual Studio 2015 os: Previous Visual Studio 2015
cache: cache:
- node_modules -> appveyor.yml - node_modules
install: install:
- ps: Install-Product node 10 x64 - ps: Install-Product node 8 x64
- git reset --hard HEAD - git reset --hard HEAD
- npm install npm -g - npm install npm -g
- node --version - node --version
- npm --version - npm --version
- python --version - python --version
- npm ci - npm install
- npm install -g gulp
build: off build: off

Binary file not shown.

View File

@@ -2,94 +2,6 @@
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
**Security fixes**:
* CVE-2020-10856: Enable Electron context isolation. (Reported by Matt Austin.)
* CVE-2020-10857: Fix unsafe use of `shell.openExternal`/`shell.openItem`. (Reported by Matt Austin.)
* Downloaded files will no longer be opened directly; the previous option to show downloaded files in the file manager is now always on.
* CVE-2020-10858: Add permission request handler to guard against audio/video recording by a malicious server. (Reported by Matt Austin.)
**New features**:
* Add an option to prompt for the location to save each downloaded file.
**Fixes**:
* Fix automatic launching at startup.
* Fix Undo and Redo functionality on macOS.
**Dependencies**:
* Upgrade all dependencies, including Electron 8.0.3.
* Remove `assert`, `cp-file`, `dotenv`, `electron-debug`, and `wurl`.
**Deprecations**:
* Since Electron upstream has discontinued support for 32-bit Linux, we will only provide 32-bit Linux builds on a best effort basis, and they will likely be removed in a future release.
### v4.0.3 --2020-02-29
**Security fixes**:
* CVE-2020-9443: Do not disable web security in the Electron webview. (Reported by Matt Austin.)
### v4.0.2-beta --2019-11-13
**New features**:
* Add support for MSI installers.
* Show badge count on Linux.
* Sync system presence info to web app.
* Add option to open notification settings from the context menu of organization icons in the sidebar.
* Tackle network issues with each Zulip organization independently.
* Add option to quit on closing the window.
* Make certificate location dynamic.
* Add option to specify network settings when adding a new organization.
**Enhancements**:
* Load last active tab before others, speeding up user experience and eliminating flashing of server icons.
* Improve UX for notification settings.
* Set User-Agent from the main process for communication with the Zulip API.
* Add SSL troubleshooting guide in error message when adding an organization fails.
**Fixes**:
* Fix translations for `ru` locales.
* Fix trailing brackets in settings page.
* Fix broken icon issue faced by the snap package on Linux.
* Reactivate `network.js` script.
* Enable notarization for macOS Catalina.
**Documentation**:
* Document enterprise configuration features.
* Update the Electron tutorial guide.
* Explicitly address where to report bugs in `README.md`.
* Fix typo in the link to server/webapp repository in `README.md`.
* Add documentation for translation.
### v4.0.0 --2019-08-08 ### v4.0.0 --2019-08-08
**New features**: **New features**:

View File

@@ -9,7 +9,7 @@ To build and run the app from source, you'll need the following:
* [Git](http://git-scm.com/book/en/v2/Getting-Started-Installing-Git) * [Git](http://git-scm.com/book/en/v2/Getting-Started-Installing-Git)
* Use our [Git Guide](https://zulip.readthedocs.io/en/latest/git/setup.html) to get started with Git and GitHub. * Use our [Git Guide](https://zulip.readthedocs.io/en/latest/git/setup.html) to get started with Git and GitHub.
* [Node.js](https://nodejs.org) >= v10.16.3 * [Node.js](https://nodejs.org) >= v6.9.0
* [NPM](https://www.npmjs.com/get-npm) and * [NPM](https://www.npmjs.com/get-npm) and
[node-gyp](https://github.com/nodejs/node-gyp#installation), [node-gyp](https://github.com/nodejs/node-gyp#installation),
if they don't come bundled with your Node.js installation if they don't come bundled with your Node.js installation

View File

@@ -5,14 +5,14 @@ const electron = require('electron-connect').server.create({
}); });
const tape = require('gulp-tape'); const tape = require('gulp-tape');
const tapColorize = require('tap-colorize'); const tapColorize = require('tap-colorize');
const ts = require('gulp-typescript'); const ts = require("gulp-typescript");
const tsProject = ts.createProject('tsconfig.json'); const tsProject = ts.createProject("tsconfig.json");
const glob = require('glob'); const glob = require('glob');
const {execSync} = require('child_process'); const { execSync } = require('child_process');
const baseFilePattern = 'app/+(main|renderer)/**/*'; const baseFilePattern = 'app/+(main|renderer)/**/*';
const globOptions = {cwd: __dirname}; const globOptions = { cwd: __dirname };
const jsFiles = glob.sync(baseFilePattern + '.js', globOptions); const jsFiles = glob.sync(baseFilePattern + '.js', globOptions);
const tsFiles = glob.sync(baseFilePattern + '.ts', globOptions); const tsFiles = glob.sync(baseFilePattern + '.ts', globOptions);
if (jsFiles.length !== tsFiles.length) { if (jsFiles.length !== tsFiles.length) {
@@ -21,10 +21,10 @@ if (jsFiles.length !== tsFiles.length) {
execSync(`${npx} tsc`); execSync(`${npx} tsc`);
} }
gulp.task('compile', () => { gulp.task("compile", function () {
return tsProject.src() return tsProject.src()
.pipe(tsProject()) .pipe(tsProject())
.js.pipe(gulp.dest('app')); .js.pipe(gulp.dest("app"));
}); });
gulp.task('dev', () => { gulp.task('dev', () => {

13094
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
{ {
"name": "zulip", "name": "zulip",
"productName": "Zulip", "productName": "Zulip",
"version": "5.2.0", "version": "4.0.3",
"main": "./app/main", "main": "./app/main",
"description": "Zulip Desktop App", "description": "Zulip Desktop App",
"license": "Apache-2.0", "license": "Apache-2.0",
@@ -18,24 +18,25 @@
"url": "https://github.com/zulip/zulip-desktop/issues" "url": "https://github.com/zulip/zulip-desktop/issues"
}, },
"engines": { "engines": {
"node": ">=10.0.0" "node": ">=6.0.0"
}, },
"scripts": { "scripts": {
"start": "tsc && electron .", "start": "node tools/run-dev",
"clean-ts-files": "git clean app/*.js -e node_modules -xf", "clean-ts-files": "git clean app/*.js -xf",
"watch-ts": "tsc -w", "watch-ts": "tsc -w",
"reinstall": "node ./tools/reinstall-node-modules.js", "reinstall": "node ./tools/reinstall-node-modules.js",
"postinstall": "electron-builder install-app-deps", "postinstall": "electron-builder install-app-deps",
"lint-css": "stylelint app/renderer/css/*.css", "lint-css": "stylelint app/renderer/css/*.css",
"lint-html": "./node_modules/.bin/htmlhint \"app/renderer/*.html\" ", "lint-html": "./node_modules/.bin/htmlhint \"app/renderer/*.html\" ",
"lint-js": "xo", "lint-js": "xo",
"test": "tsc --noEmit && npm run lint-html && npm run lint-css && npm run lint-js", "test": "npm run lint-html && npm run lint-css && npm run lint-js",
"test-e2e": "gulp test-e2e", "test-e2e": "gulp test-e2e",
"compile": "gulp compile", "compile": "gulp compile",
"dev": "gulp dev && npm test", "dev": "gulp dev && npm test",
"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": [
@@ -49,8 +50,9 @@
"**/*.node" "**/*.node"
], ],
"files": [ "files": [
"app/**/*", "**/*",
"!**/node_modules/cld/deps/cld" "!docs${/*}",
"!node_modules/@paulcbetts/cld/deps/cld${/*}"
], ],
"copyright": "©2019 Kandra Labs, Inc.", "copyright": "©2019 Kandra Labs, Inc.",
"mac": { "mac": {
@@ -141,106 +143,97 @@
"Desktop app", "Desktop app",
"InstantMessaging" "InstantMessaging"
], ],
"dependencies": {
"@electron-elements/send-feedback": "^1.0.8",
"@sentry/electron": "^1.3.0",
"adm-zip": "^0.4.14",
"auto-launch": "^5.0.5",
"backoff": "^2.5.0",
"electron-is-dev": "^1.2.0",
"electron-log": "^4.1.2",
"electron-spellchecker": "^2.2.1",
"electron-updater": "^4.3.1",
"electron-window-state": "^5.0.3",
"escape-html": "^1.0.3",
"fs-extra": "^9.0.0",
"i18n": "^0.9.1",
"node-json-db": "^1.1.0",
"request": "^2.88.2",
"rxjs": "^5.5.12",
"semver": "^7.3.2"
},
"optionalDependencies": {
"node-mac-notifier": "^1.1.0"
},
"devDependencies": { "devDependencies": {
"@types/adm-zip": "^0.4.33", "@types/adm-zip": "^0.4.32",
"@types/auto-launch": "^5.0.1", "@types/dotenv": "6.1.1",
"@types/backoff": "^2.5.1", "@typescript-eslint/eslint-plugin": "1.10.2",
"@types/electron-spellchecker": "^1.1.2", "@typescript-eslint/parser": "1.10.2",
"@types/escape-html": "0.0.20", "@vitalets/google-translate-api": "2.8.0",
"@types/fs-extra": "^8.1.0", "assert": "1.4.1",
"@types/i18n": "^0.8.6", "cp-file": "5.0.0",
"@types/node": "^13.13.4", "devtron": "1.4.0",
"@types/request": "^2.48.4", "electron": "3.1.10",
"@types/requestidlecallback": "^0.3.1", "electron-builder": "20.43.0",
"@typescript-eslint/eslint-plugin": "^2.30.0", "electron-connect": "0.6.2",
"@typescript-eslint/parser": "^2.30.0", "electron-debug": "1.4.0",
"@vitalets/google-translate-api": "^3.0.0", "electron-notarize": "0.2.0",
"devtron": "^1.4.0", "eslint-config-xo-typescript": "0.14.0",
"dotenv": "^8.2.0", "fs-extra": "8.1.0",
"electron": "^8.2.5", "gulp": "4.0.0",
"electron-builder": "^22.6.0", "gulp-tape": "0.0.9",
"electron-connect": "^0.6.3", "gulp-typescript": "5.0.1",
"electron-notarize": "^0.3.0", "htmlhint": "0.11.0",
"eslint-config-xo-typescript": "^0.28.0", "is-ci": "1.0.10",
"glob": "^7.1.6", "nodemon": "1.14.11",
"gulp": "^4.0.2", "pre-commit": "1.2.2",
"gulp-tape": "^1.0.0", "spectron": "5.0.0",
"gulp-typescript": "^6.0.0-alpha.1", "stylelint": "9.10.1",
"htmlhint": "^0.11.0", "tap-colorize": "1.2.0",
"nodemon": "^2.0.3", "tape": "4.8.0",
"pre-commit": "^1.2.2", "typescript": "3.5.2",
"rimraf": "^3.0.2", "xo": "0.24.0"
"spectron": "^10.0.1",
"stylelint": "^13.3.3",
"tap-colorize": "^1.2.0",
"tape": "^5.0.0",
"typescript": "^3.8.3",
"xo": "^0.30.0"
}, },
"xo": { "xo": {
"extends": "xo-typescript",
"extensions": [
"ts"
],
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"globalReturn": true,
"modules": true
}
},
"esnext": true,
"overrides": [
{
"files": "app/**/*.ts",
"rules": { "rules": {
"@typescript-eslint/no-dynamic-delete": "off",
"@typescript-eslint/prefer-readonly-parameter-types": "off",
"import/unambiguous": "error",
"max-lines": [ "max-lines": [
"warn", "warn",
{ {
"max": 900, "max": 800,
"skipBlankLines": true, "skipBlankLines": true,
"skipComments": true "skipComments": true
} }
], ],
"no-warning-comments": "off", "no-warning-comments": 0,
"strict": "error" "object-curly-spacing": 0,
}, "capitalized-comments": 0,
"no-else-return": 0,
"no-path-concat": 0,
"no-alert": 0,
"guard-for-in": 0,
"prefer-promise-reject-errors": 0,
"import/no-unresolved": 0,
"import/no-extraneous-dependencies": 0,
"no-prototype-builtins": 0,
"lines-between-class-members": 0,
"padding-line-between-statements": 0,
"quotes": 0,
"unicorn/catch-error-name": 0,
"unicorn/no-console-spaces": 0,
"node/no-deprecated-api": 0,
"@typescript-eslint/member-ordering": "never",
"@typescript-eslint/restrict-plus-operands": "never",
"import/default": 0,
"@typescript-eslint/no-unused-vars": 0
}
}
],
"ignore": [
"tests/*.js",
"tools/locale-helper/*.js",
"*/**/*.js",
"*.js",
"typings.d.ts"
],
"envs": [ "envs": [
"node", "node",
"browser" "browser",
], "mocha"
"overrides": [
{
"files": [
"app/renderer/js/injected.ts",
"gulpfile.js",
"scripts/notarize.js",
"tests/**/*.js",
"tools/locale-helper/index.js",
"tools/reinstall-node-modules.js"
],
"parserOptions": {
"sourceType": "script"
}
},
{
"files": [
"**/*.d.ts"
],
"rules": {
"import/unambiguous": "off"
}
}
] ]
} }
} }

View File

@@ -3,13 +3,8 @@
# This script runs when user install the debian package # This script runs when user install the debian package
# Link to the binary # Link to the binary
ln -sf '/opt/${productFilename}/${executable}' '/usr/bin/${executable}' ln -sf '/opt/${productFilename}/${executable}' '/usr/local/bin/${executable}';
echo 'Successfully added /opt/${productFilename}/${executable} to /usr/local/bin/${executable}'
# SUID chrome-sandbox for Electron 5+
chmod 4755 '/opt/${productFilename}/chrome-sandbox' || true
update-mime-database /usr/share/mime || true
update-desktop-database /usr/share/applications || true
# Install apt repository source list if it does not exist # Install apt repository source list if it does not exist
if ! grep ^ /etc/apt/sources.list /etc/apt/sources.list.d/* | grep zulip.list; then if ! grep ^ /etc/apt/sources.list /etc/apt/sources.list.d/* | grep zulip.list; then

View File

@@ -31,4 +31,5 @@ if [ -d $appDirectory ]; then
fi fi
# Delete the link to the binary # Delete the link to the binary
rm -f '/usr/bin/${executable}' echo 'Removing binary link'
sudo rm -f '/usr/local/bin/${executable}';

View File

@@ -1,24 +1,22 @@
'use strict';
const path = require('path'); const path = require('path');
const dotenv = require('dotenv'); const dotenv = require('dotenv');
dotenv.config({path: path.join(__dirname, '/../.env')}); dotenv.config({ path: path.join(__dirname, '/../.env') });
const {notarize} = require('electron-notarize'); const { notarize } = require('electron-notarize');
exports.default = async function (context) { exports.default = async function notarizing(context) {
const {electronPlatformName, appOutDir} = context; const { electronPlatformName, appOutDir } = context;
if (electronPlatformName !== 'darwin') { if (electronPlatformName !== 'darwin') {
return; return;
} }
const appName = context.packager.appInfo.productFilename; const appName = context.packager.appInfo.productFilename;
return notarize({ return await notarize({
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
}); });
}; };

20
scripts/travis-build-test.sh Executable file
View File

@@ -0,0 +1,20 @@
#!/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

5
scripts/travis-xvfb.sh Executable file
View File

@@ -0,0 +1,5 @@
#!/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

View File

@@ -1,7 +1,7 @@
'use strict'; const path = require('path')
const TEST_APP_PRODUCT_NAME = 'ZulipTest'; const TEST_APP_PRODUCT_NAME = 'ZulipTest'
module.exports = { module.exports = {
TEST_APP_PRODUCT_NAME TEST_APP_PRODUCT_NAME
}; }

183
tests/e2e/package.json Normal file
View File

@@ -0,0 +1,183 @@
{
"name": "zulip",
"productName": "Zulip",
"version": "2.4.0",
"main": "../../app/main",
"description": "Zulip Desktop App",
"license": "Apache-2.0",
"copyright": "Kandra Labs, Inc.",
"author": {
"name": "Kandra Labs, Inc.",
"email": "support@zulipchat.com"
},
"repository": {
"type": "git",
"url": "https://github.com/zulip/zulip-electron.git"
},
"bugs": {
"url": "https://github.com/zulip/zulip-electron/issues"
},
"engines": {
"node": ">=6.0.0"
},
"scripts": {
"start": "electron app --disable-http-cache --no-electron-connect",
"reinstall": "node ./tools/reinstall-node-modules.js",
"postinstall": "electron-builder install-app-deps",
"test": "xo",
"test-e2e": "gulp test-e2e",
"dev": "gulp dev & nodemon --watch app/main --watch app/renderer --exec 'npm test' -e html,css,js",
"pack": "electron-builder --dir",
"dist": "electron-builder",
"mas": "electron-builder --mac mas",
"travis": "cd ./scripts && ./travis-build-test.sh",
"build-locales": "node tools/locale-helper"
},
"pre-commit": [
"test"
],
"build": {
"appId": "org.zulip.zulip-electron",
"asar": true,
"files": [
"**/*",
"!docs${/*}",
"!node_modules/@paulcbetts/cld/deps/cld${/*}"
],
"copyright": "©2017 Kandra Labs, Inc.",
"mac": {
"category": "public.app-category.productivity",
"artifactName": "${productName}-${version}-${arch}.${ext}"
},
"linux": {
"category": "Chat;GNOME;GTK;Network;InstantMessaging",
"packageCategory": "GNOME;GTK;Network;InstantMessaging",
"description": "Zulip Desktop Client for Linux",
"target": [
"deb",
"zip",
"AppImage",
"snap"
],
"maintainer": "Akash Nimare <svnitakash@gmail.com>",
"artifactName": "${productName}-${version}-${arch}.${ext}"
},
"deb": {
"synopsis": "Zulip Desktop App",
"afterInstall": "./scripts/debian-add-repo.sh",
"afterRemove": "./scripts/debian-uninstaller.sh"
},
"snap": {
"synopsis": "Zulip Desktop App"
},
"dmg": {
"background": "build/appdmg.png",
"icon": "build/icon.icns",
"iconSize": 100,
"contents": [
{
"x": 380,
"y": 280,
"type": "link",
"path": "/Applications"
},
{
"x": 110,
"y": 280,
"type": "file"
}
],
"window": {
"width": 500,
"height": 500
}
},
"win": {
"target": [
{
"target": "nsis-web",
"arch": [
"x64",
"ia32"
]
}
],
"icon": "build/icon.ico",
"publisherName": "Kandra Labs, Inc."
},
"nsis": {
"allowToChangeInstallationDirectory": true
}
},
"keywords": [
"Zulip",
"Group Chat app",
"electron-app",
"electron",
"Desktop app",
"InstantMessaging"
],
"devDependencies": {
"assert": "1.4.1",
"cp-file": "^5.0.0",
"devtron": "1.4.0",
"electron": "3.0.10",
"electron-builder": "20.38.4",
"electron-connect": "0.6.2",
"electron-debug": "1.4.0",
"google-translate-api": "2.3.0",
"gulp": "^4.0.0",
"gulp-tape": "0.0.9",
"is-ci": "^1.0.10",
"nodemon": "^1.14.11",
"pre-commit": "1.2.2",
"spectron": "3.8.0",
"tap-colorize": "^1.2.0",
"tape": "^4.8.0",
"xo": "0.18.2"
},
"xo": {
"parserOptions": {
"sourceType": "script",
"ecmaFeatures": {
"globalReturn": true
}
},
"esnext": true,
"overrides": [
{
"files": "app*/**/*.js",
"rules": {
"max-lines": [
"warn",
{
"max": 600,
"skipBlankLines": true,
"skipComments": true
}
],
"no-warning-comments": 0,
"object-curly-spacing": 0,
"capitalized-comments": 0,
"no-else-return": 0,
"no-path-concat": 0,
"no-alert": 0,
"guard-for-in": 0,
"prefer-promise-reject-errors": 0,
"import/no-unresolved": 0,
"import/no-extraneous-dependencies": 0,
"no-prototype-builtins": 0
}
}
],
"ignore": [
"tests/*.js",
"tools/locale-helper/*.js"
],
"envs": [
"node",
"browser",
"mocha"
]
}
}

View File

@@ -1,17 +1,13 @@
'use strict'; const test = require('tape')
const test = require('tape'); const setup = require('./setup')
const setup = require('./setup');
test('app runs', async t => { test('app runs', function (t) {
t.timeoutAfter(10e3); t.timeoutAfter(10e3)
setup.resetTestDataDir(); setup.resetTestDataDir()
const app = setup.createApp(); const app = setup.createApp()
try { setup.waitForLoad(app, t)
await setup.waitForLoad(app, t); .then(() => app.client.windowByIndex(1)) // focus on webview
await app.client.windowByIndex(1); // Focus on webview .then(() => app.client.waitForExist('//*[@id="connect"]')) // id of the connect button
await app.client.waitForExist('//*[@id="connect"]'); // Id of the connect button .then(() => setup.endTest(app, t),
await setup.endTest(app, t); (err) => setup.endTest(app, t, err || 'error'))
} catch (error) { })
await setup.endTest(app, t, error || 'error');
}
});

View File

@@ -1,10 +1,12 @@
'use strict'; const Application = require('spectron').Application
const {Application} = require('spectron'); const cpFile = require('cp-file')
const fs = require('fs'); const fs = require('fs')
const path = require('path'); const isCI = require('is-ci')
const rimraf = require('rimraf'); const mkdirp = require('mkdirp')
const path = require('path')
const rimraf = require('rimraf')
const config = require('./config'); const config = require('./config')
module.exports = { module.exports = {
createApp, createApp,
@@ -12,85 +14,86 @@ module.exports = {
waitForLoad, waitForLoad,
wait, wait,
resetTestDataDir resetTestDataDir
}; }
// Runs Zulip Desktop. // Runs Zulip Desktop.
// Returns a promise that resolves to a Spectron Application once the app has loaded. // Returns a promise that resolves to a Spectron Application once the app has loaded.
// Takes a Tape test. Makes some basic assertions to verify that the app loaded correctly. // Takes a Tape test. Makes some basic assertions to verify that the app loaded correctly.
function createApp() { function createApp (t) {
generateTestAppPackageJson(); generateTestAppPackageJson()
return new Application({ return new Application({
path: path.join(__dirname, '..', 'node_modules', '.bin', path: path.join(__dirname, '..', 'node_modules', '.bin',
'electron' + (process.platform === 'win32' ? '.cmd' : '')), 'electron' + (process.platform === 'win32' ? '.cmd' : '')),
args: [path.join(__dirname)], // Ensure this dir has a package.json file with a 'main' entry piont args: [path.join(__dirname)], // Ensure this dir has a package.json file with a 'main' entry piont
env: {NODE_ENV: 'test'}, env: {NODE_ENV: 'test'},
waitTimeout: 10e3 waitTimeout: 10e3
}); })
} }
// Generates package.json for test app // Generates package.json for test app
// Reads app package.json and updates the productName to config.TEST_APP_PRODUCT_NAME // Reads app package.json and updates the productName to config.TEST_APP_PRODUCT_NAME
// We do this so that the app integration doesn't doesn't share the same appDataDir as the dev application // We do this so that the app integration doesn't doesn't share the same appDataDir as the dev application
function generateTestAppPackageJson() { function generateTestAppPackageJson () {
const packageJson = require(path.join(__dirname, '../package.json')); let packageJson = require(path.join(__dirname, '../package.json'))
packageJson.productName = config.TEST_APP_PRODUCT_NAME; packageJson.productName = config.TEST_APP_PRODUCT_NAME
packageJson.main = '../app/main'; packageJson.main = '../app/main'
const testPackageJsonPath = path.join(__dirname, 'package.json'); const testPackageJsonPath = path.join(__dirname, 'package.json')
fs.writeFileSync(testPackageJsonPath, JSON.stringify(packageJson, null, ' '), 'utf-8'); fs.writeFileSync(testPackageJsonPath, JSON.stringify(packageJson, null, ' '), 'utf-8')
} }
// Starts the app, waits for it to load, returns a promise // Starts the app, waits for it to load, returns a promise
async function waitForLoad(app, t, options) { function waitForLoad (app, t, opts) {
if (!options) { if (!opts) opts = {}
options = {}; return app.start().then(function () {
} return app.client.waitUntilWindowLoaded()
})
await app.start(); .then(function() {
await app.client.waitUntilWindowLoaded(); return app.client.pause(2000);
await app.client.pause(2000); })
const title = await app.webContents.getTitle(); .then(function () {
t.equal(title, 'Zulip', 'html title'); return app.webContents.getTitle()
}).then(function (title) {
t.equal(title, 'Zulip', 'html title')
})
} }
// Returns a promise that resolves after 'ms' milliseconds. Default: 1 second // Returns a promise that resolves after 'ms' milliseconds. Default: 1 second
async function wait(ms) { function wait (ms) {
if (ms === undefined) { if (ms === undefined) ms = 1000 // Default: wait long enough for the UI to update
ms = 1000; return new Promise(function (resolve, reject) {
} // Default: wait long enough for the UI to update setTimeout(resolve, ms)
})
return new Promise((resolve => {
setTimeout(resolve, ms);
}));
} }
// Quit the app, end the test, either in success (!err) or failure (err) // Quit the app, end the test, either in success (!err) or failure (err)
async function endTest(app, t, err) { function endTest (app, t, err) {
await app.stop(); return app.stop().then(function () {
t.end(err); t.end(err)
})
} }
function getAppDataDir() { function getAppDataDir () {
let base; let base
if (process.platform === 'darwin') { if (process.platform === 'darwin') {
base = path.join(process.env.HOME, 'Library', 'Application Support'); base = path.join(process.env.HOME, 'Library', 'Application Support')
} else if (process.platform === 'linux') { } else if (process.platform === 'linux') {
base = process.env.XDG_CONFIG_HOME ? base = process.env.XDG_CONFIG_HOME ?
process.env.XDG_CONFIG_HOME : path.join(process.env.HOME, '.config'); process.env.XDG_CONFIG_HOME : path.join(process.env.HOME, '.config')
} else if (process.platform === 'win32') { } else if (process.platform === 'win32') {
base = process.env.APPDATA; base = process.env.APPDATA
} else { } else {
throw new Error('Could not detect app data dir base.'); console.log('Could not detect app data dir base. Exiting...')
process.exit(1)
} }
console.log('Detected App Data Dir base:', base)
console.log('Detected App Data Dir base:', base); return path.join(base, config.TEST_APP_PRODUCT_NAME)
return path.join(base, config.TEST_APP_PRODUCT_NAME);
} }
// Resets the test directory, containing domain.json, window-state.json, etc // Resets the test directory, containing domain.json, window-state.json, etc
function resetTestDataDir() { function resetTestDataDir () {
const appDataDir = getAppDataDir(); appDataDir = getAppDataDir()
rimraf.sync(appDataDir); rimraf.sync(appDataDir)
rimraf.sync(path.join(__dirname, 'package.json')); rimraf.sync(path.join(__dirname, 'package.json'))
} }

View File

@@ -1,22 +1,19 @@
'use strict'; const test = require('tape')
const test = require('tape'); const setup = require('./setup')
const setup = require('./setup');
test('add-organization', function (t) {
t.timeoutAfter(50e3)
setup.resetTestDataDir()
const app = setup.createApp()
setup.waitForLoad(app, t)
.then(() => app.client.windowByIndex(1)) // focus on webview
.then(() => app.client.setValue('.setting-input-value', 'chat.zulip.org'))
.then(() => app.client.click('.server-save-action'))
.then(() => setup.wait(5000))
.then(() => app.client.windowByIndex(0)) // Switch focus back to main win
.then(() => app.client.windowByIndex(1)) // Switch focus back to org webview
.then(() => app.client.waitForExist('//*[@id="id_username"]'))
.then(() => setup.endTest(app, t),
(err) => setup.endTest(app, t, err || 'error'))
})
test('add-organization', async t => {
t.timeoutAfter(50e3);
setup.resetTestDataDir();
const app = setup.createApp();
try {
await setup.waitForLoad(app, t);
await app.client.windowByIndex(1); // Focus on webview
await app.client.setValue('.setting-input-value', 'chat.zulip.org');
await app.client.click('#connect');
await setup.wait(5000);
await app.client.windowByIndex(0); // Switch focus back to main win
await app.client.windowByIndex(1); // Switch focus back to org webview
await app.client.waitForExist('//*[@id="id_username"]');
await setup.endTest(app, t);
} catch (error) {
await setup.endTest(app, t, error || 'error');
}
});

View File

@@ -1,20 +1,17 @@
'use strict'; const test = require('tape')
const test = require('tape'); const setup = require('./setup')
const setup = require('./setup');
// Create new org link should open in the default browser [WIP] // Create new org link should open in the default browser [WIP]
test('new-org-link', async t => { test('new-org-link', function (t) {
t.timeoutAfter(50e3); t.timeoutAfter(50e3)
setup.resetTestDataDir(); setup.resetTestDataDir()
const app = setup.createApp(); const app = setup.createApp()
try { setup.waitForLoad(app, t)
await setup.waitForLoad(app, t); .then(() => app.client.windowByIndex(1)) // focus on webview
await app.client.windowByIndex(1); // Focus on webview .then(() => app.client.click('#open-create-org-link')) // Click on new org link button
await app.client.click('#open-create-org-link'); // Click on new org link button .then(() => setup.wait(5000))
await setup.wait(5000); .then(() => setup.endTest(app, t),
await setup.endTest(app, t); (err) => setup.endTest(app, t, err || 'error'))
} catch (error) { })
await setup.endTest(app, t, error || 'error');
}
});

View File

@@ -1,4 +1,3 @@
'use strict';
const translate = require('@vitalets/google-translate-api'); const translate = require('@vitalets/google-translate-api');
const path = require('path'); const path = require('path');
const fs = require('fs'); const fs = require('fs');
@@ -10,17 +9,16 @@ function writeJSON(file, data) {
fs.writeFileSync(filePath, `${JSON.stringify(data, null, '\t')}\n`, 'utf8'); fs.writeFileSync(filePath, `${JSON.stringify(data, null, '\t')}\n`, 'utf8');
} }
const {phrases} = require('./locale-template'); const { phrases } = require('./locale-template');
const supportedLocales = require('./supported-locales.json'); const supportedLocales = require('./supported-locales');
phrases.sort(); phrases.sort();
for (const [locale, name] of Object.entries(supportedLocales)) { for (let locale in supportedLocales) {
console.log(`fetching translation for: ${name} - ${locale}..`); console.log(`fetching translation for: ${supportedLocales[locale]} - ${locale}..`);
(async () => { translate(phrases.join('\n'), { to: locale })
try { .then(res => {
const result = await translate(phrases.join('\n'), {to: locale});
const localeFile = `${locale}.json`; const localeFile = `${locale}.json`;
const translatedText = result.text.split('\n'); const translatedText = res.text.split('\n');
const translationJSON = {}; const translationJSON = {};
phrases.forEach((phrase, index) => { phrases.forEach((phrase, index) => {
translationJSON[phrase] = translatedText[index]; translationJSON[phrase] = translatedText[index];
@@ -28,8 +26,7 @@ for (const [locale, name] of Object.entries(supportedLocales)) {
writeJSON(localeFile, translationJSON); writeJSON(localeFile, translationJSON);
console.log(`create: ${localeFile}`); console.log(`create: ${localeFile}`);
} catch (error) { }).catch(err => {
console.error(error); console.error(err);
} });
})();
} }

View File

@@ -1,4 +1,4 @@
{ module.exports = {
"de": "Deutsch", "de": "Deutsch",
"pl": "polski", "pl": "polski",
"en": "English", "en": "English",
@@ -18,4 +18,4 @@
"es": "español", "es": "español",
"ko": "한국어", "ko": "한국어",
"fr": "français" "fr": "français"
} };

View File

@@ -2,8 +2,9 @@
set -e set -e
set -x set -x
echo "Removing node_modules" echo "Removing node_modules and app/node_modules"
rm -rf node_modules rm -rf node_modules
rm -rf app/node_modules
echo "node_modules removed reinstalling npm packages" echo "node_modules removed reinstalling npm packages"
npm i npm i

View File

@@ -1,7 +1,8 @@
@echo off @echo off
echo "Removing node_modules" echo "Removing node_modules and app/node_modules"
rmdir /s /q node_modules rmdir /s /q node_modules
rmdir /s /q app/node_modules
echo "node_modules removed reinstalling npm packages" echo "node_modules removed reinstalling npm packages"
npm i npm i

View File

@@ -1,5 +1,4 @@
#!/usr/bin/env node #!/usr/bin/env node
'use strict';
const {exec} = require('child_process'); const {exec} = require('child_process');
const path = require('path'); const path = require('path');

Some files were not shown because too many files have changed in this diff Show More