Various QoL fixes for Desktop App (#2999)

* Some ESLint fixes

* Add login/logout signal to API, clear mentions on logout and flush cookies on login/logout

* Fix issue where local and HTTP-only servers would not validate correctly

* Reduce noise of renderer logging, adjust a few local renderer logs to be louder when needed

* Fallback to beginning of hostname for servers that don't change the site name

* Fix Save Image crash

* Update the name for insecure servers too

* Fix test

* Fix lint

* Reduce repetition
This commit is contained in:
Devin Binnie
2024-04-08 09:12:35 -04:00
committed by GitHub
parent 2456e68ae9
commit e1c957e774
21 changed files with 116 additions and 74 deletions

View File

@@ -417,6 +417,26 @@ describe('app/serverViewState', () => {
expect(result.validatedURL).toBe('http://server.com/');
});
it('should be able to recognize localhost with a port and add the appropriate prefix', async () => {
ServerInfo.mockImplementation(({url}) => ({
fetchConfigData: jest.fn().mockImplementation(() => {
if (url.startsWith('https:')) {
return undefined;
}
return {
serverVersion: '7.8.0',
siteName: 'Mattermost',
siteURL: url,
};
}),
}));
const result = await serverViewState.handleServerURLValidation({}, 'localhost:8065');
expect(result.status).toBe(URLValidationStatus.Insecure);
expect(result.validatedURL).toBe('http://localhost:8065/');
});
it('should show a warning when the ping request times out', async () => {
ServerInfo.mockImplementation(() => ({
fetchConfigData: jest.fn().mockImplementation(() => {

View File

@@ -233,7 +233,7 @@ export class ServerViewState {
if (!isValidURL(url)) {
// If it already includes the protocol, tell them it's invalid
if (isValidURI(url)) {
httpUrl = url.replace(/^(.+):/, 'https:');
httpUrl = url.replace(/^((.+):\/\/)?/, 'https://');
} else {
// Otherwise add HTTPS for them
httpUrl = `https://${url}`;
@@ -260,11 +260,13 @@ export class ServerViewState {
// Try and get remote info from the most secure URL, otherwise use the insecure one
let remoteURL = secureURL;
const insecureURL = parseURL(secureURL.toString().replace(/^https:/, 'http:'));
let remoteInfo = await this.testRemoteServer(secureURL);
if (!remoteInfo) {
if (secureURL.toString() !== parsedURL.toString()) {
remoteURL = parsedURL;
remoteInfo = await this.testRemoteServer(parsedURL);
if (!remoteInfo && insecureURL) {
// Try to fall back to HTTP
remoteInfo = await this.testRemoteServer(insecureURL);
if (remoteInfo) {
remoteURL = insecureURL;
}
}
@@ -274,9 +276,11 @@ export class ServerViewState {
return {status: URLValidationStatus.NotMattermost, validatedURL: parsedURL.toString()};
}
const remoteServerName = remoteInfo.siteName === 'Mattermost' ? remoteURL.host.split('.')[0] : remoteInfo.siteName;
// If we were only able to connect via HTTP, warn the user that the connection is not secure
if (remoteURL.protocol === 'http:') {
return {status: URLValidationStatus.Insecure, serverVersion: remoteInfo.serverVersion, validatedURL: remoteURL.toString()};
return {status: URLValidationStatus.Insecure, serverVersion: remoteInfo.serverVersion, serverName: remoteServerName, validatedURL: remoteURL.toString()};
}
// If the URL doesn't match the Site URL, set the URL to the correct one
@@ -292,15 +296,15 @@ export class ServerViewState {
// If we can't reach the remote Site URL, there's probably a configuration issue
const remoteSiteURLInfo = await this.testRemoteServer(parsedSiteURL);
if (!remoteSiteURLInfo) {
return {status: URLValidationStatus.URLNotMatched, serverVersion: remoteInfo.serverVersion, serverName: remoteInfo.siteName, validatedURL: remoteURL.toString()};
return {status: URLValidationStatus.URLNotMatched, serverVersion: remoteInfo.serverVersion, serverName: remoteServerName, validatedURL: remoteURL.toString()};
}
}
// Otherwise fix it for them and return
return {status: URLValidationStatus.URLUpdated, serverVersion: remoteInfo.serverVersion, serverName: remoteInfo.siteName, validatedURL: remoteInfo.siteURL};
return {status: URLValidationStatus.URLUpdated, serverVersion: remoteInfo.serverVersion, serverName: remoteServerName, validatedURL: remoteInfo.siteURL};
}
return {status: URLValidationStatus.OK, serverVersion: remoteInfo.serverVersion, serverName: remoteInfo.siteName, validatedURL: remoteURL.toString()};
return {status: URLValidationStatus.OK, serverVersion: remoteInfo.serverVersion, serverName: remoteServerName, validatedURL: remoteURL.toString()};
};
private handleCloseView = (event: IpcMainEvent, viewId: string) => {

View File

@@ -49,6 +49,8 @@ export class AppState extends EventEmitter {
this.expired.delete(viewId);
this.mentions.delete(viewId);
this.unreads.delete(viewId);
this.emitStatusForView(viewId);
};
emitStatus = () => {

View File

@@ -87,9 +87,9 @@ import {
shouldShowTrayIcon,
updateSpellCheckerLocales,
wasUpdated,
initCookieManager,
migrateMacAppStore,
updateServerInfos,
flushCookiesStore,
} from './utils';
import {
handleClose,
@@ -200,6 +200,12 @@ function initializeAppEventListeners() {
app.on('child-process-gone', handleChildProcessGone);
app.on('login', AuthManager.handleAppLogin);
app.on('will-finish-launching', handleAppWillFinishLaunching);
// Somehow cookies are not immediately saved to disk.
// So manually flush cookie store to disk on closing the app.
// https://github.com/electron/electron/issues/8416
// TODO: We can remove this once every server supported will flush on login/logout
app.on('before-quit', flushCookiesStore);
}
function initializeBeforeAppReady() {
@@ -347,7 +353,6 @@ async function initializeAfterAppReady() {
catch((err) => log.error('An error occurred: ', err));
}
initCookieManager(defaultSession);
MainWindow.show();
let deeplinkingURL;

View File

@@ -4,7 +4,7 @@
import fs from 'fs';
import path from 'path';
import type {BrowserWindow, Rectangle, Session} from 'electron';
import type {BrowserWindow, Rectangle} from 'electron';
import {app, Menu, session, dialog, nativeImage, screen} from 'electron';
import isDev from 'electron-is-dev';
@@ -166,26 +166,13 @@ export function resizeScreen(browserWindow: BrowserWindow) {
handle();
}
export function flushCookiesStore(session: Session) {
export function flushCookiesStore() {
log.debug('flushCookiesStore');
session.cookies.flushStore().catch((err) => {
session.defaultSession.cookies.flushStore().catch((err) => {
log.error(`There was a problem flushing cookies:\n${err}`);
});
}
export function initCookieManager(session: Session) {
// Somehow cookies are not immediately saved to disk.
// So manually flush cookie store to disk on closing the app.
// https://github.com/electron/electron/issues/8416
app.on('before-quit', () => {
flushCookiesStore(session);
});
app.on('browser-window-blur', () => {
flushCookiesStore(session);
});
}
export function migrateMacAppStore() {
const migrationPrefs = new JsonFileManager<MigrationInfo>(migrationInfoPath);
const oldPath = path.join(app.getPath('userData'), '../../../../../../../Library/Application Support/Mattermost');

View File

@@ -70,6 +70,9 @@ const desktopAPI: DesktopAPI = {
setSessionExpired: (isExpired) => ipcRenderer.send(SESSION_EXPIRED, isExpired),
onUserActivityUpdate: (listener) => createListener(USER_ACTIVITY_UPDATE, listener),
onLogin: () => ipcRenderer.send(APP_LOGGED_IN),
onLogout: () => ipcRenderer.send(APP_LOGGED_OUT),
// Unreads/mentions/notifications
sendNotification: (title, body, channelId, teamId, url, silent, soundName) =>
ipcRenderer.invoke(NOTIFY_MENTION, title, body, channelId, teamId, url, silent, soundName),
@@ -178,11 +181,11 @@ setInterval(() => {
const onLoad = () => {
if (document.getElementById('root') === null) {
console.log('The guest is not assumed as mattermost-webapp');
console.warn('The guest is not assumed as mattermost-webapp');
return;
}
watchReactAppUntilInitialized(() => {
console.log('Legacy preload initialized');
console.warn('Legacy preload initialized');
ipcRenderer.send(REACT_APP_INITIALIZED);
ipcRenderer.invoke(REQUEST_BROWSER_HISTORY_STATUS).then(sendHistoryButtonReturn);
});

View File

@@ -56,6 +56,10 @@ jest.mock('common/utils/url', () => ({
equalUrlsIgnoringSubpath: jest.fn(),
}));
jest.mock('main/app/utils', () => ({
flushCookiesStore: jest.fn(),
}));
jest.mock('main/i18nManager', () => ({
localizeMessage: jest.fn(),
}));

View File

@@ -43,6 +43,7 @@ import {getFormattedPathName, parseURL} from 'common/utils/url';
import Utils from 'common/utils/util';
import type {MattermostView} from 'common/views/View';
import {TAB_MESSAGING} from 'common/views/View';
import {flushCookiesStore} from 'main/app/utils';
import {localizeMessage} from 'main/i18nManager';
import MainWindow from 'main/windows/mainWindow';
@@ -471,11 +472,24 @@ export class ViewManager {
};
private handleAppLoggedIn = (event: IpcMainEvent) => {
this.getViewByWebContentsId(event.sender.id)?.onLogin(true);
log.debug('handleAppLoggedIn', event.sender.id);
const view = this.getViewByWebContentsId(event.sender.id);
if (!view) {
return;
}
view.onLogin(true);
flushCookiesStore();
};
private handleAppLoggedOut = (event: IpcMainEvent) => {
this.getViewByWebContentsId(event.sender.id)?.onLogin(false);
log.debug('handleAppLoggedOut', event.sender.id);
const view = this.getViewByWebContentsId(event.sender.id);
if (!view) {
return;
}
view.onLogin(false);
AppState.clear(view.id);
flushCookiesStore();
};
private handleBrowserHistoryPush = (e: IpcMainEvent, pathName: string) => {

View File

@@ -245,8 +245,7 @@ describe('main/views/webContentsEvents', () => {
const logObject = {
error: jest.fn(),
warn: jest.fn(),
info: jest.fn(),
verbose: jest.fn(),
debug: jest.fn(),
withPrefix: jest.fn().mockReturnThis(),
};
webContentsEventManager.log = jest.fn().mockReturnValue(logObject);
@@ -258,10 +257,10 @@ describe('main/views/webContentsEvents', () => {
it('should respect logging levels', () => {
consoleMessage({}, 0, 'test0', 0, '');
expect(logObject.verbose).toHaveBeenCalledWith('test0');
expect(logObject.debug).toHaveBeenCalledWith('test0');
consoleMessage({}, 1, 'test1', 0, '');
expect(logObject.info).toHaveBeenCalledWith('test1');
expect(logObject.debug).toHaveBeenCalledWith('test1');
consoleMessage({}, 2, 'test2', 0, '');
expect(logObject.warn).toHaveBeenCalledWith('test2');
@@ -273,11 +272,11 @@ describe('main/views/webContentsEvents', () => {
it('should only add line numbers for debug and silly', () => {
getLevel.mockReturnValue('debug');
consoleMessage({}, 0, 'test1', 42, 'meaning_of_life.js');
expect(logObject.verbose).toHaveBeenCalledWith('test1', '(meaning_of_life.js:42)');
expect(logObject.debug).toHaveBeenCalledWith('test1', '(meaning_of_life.js:42)');
getLevel.mockReturnValue('info');
getLevel.mockReturnValue('warn');
consoleMessage({}, 0, 'test2', 42, 'meaning_of_life.js');
expect(logObject.verbose).not.toHaveBeenCalledWith('test2', '(meaning_of_life.js:42)');
expect(logObject.warn).not.toHaveBeenCalledWith('test2', '(meaning_of_life.js:42)');
});
});
});

View File

@@ -4,7 +4,7 @@
import path from 'path';
import type {WebContents, Event} from 'electron';
import {BrowserWindow, session, shell} from 'electron';
import {BrowserWindow, shell} from 'electron';
import Config from 'common/config';
import {Logger, getLevel} from 'common/log';
@@ -116,7 +116,7 @@ export class WebContentsEventManager {
return;
}
if (this.customLogins[webContentsId]?.inProgress) {
flushCookiesStore(session.defaultSession);
flushCookiesStore();
return;
}
@@ -298,7 +298,7 @@ export class WebContentsEventManager {
private generateHandleConsoleMessage = (webContentsId: number) => (_: Event, level: number, message: string, line: number, sourceId: string) => {
const wcLog = this.log(webContentsId).withPrefix('renderer');
let logFn = wcLog.verbose;
let logFn = wcLog.debug;
switch (level) {
case ConsoleMessageLevel.Error:
logFn = wcLog.error;
@@ -306,9 +306,6 @@ export class WebContentsEventManager {
case ConsoleMessageLevel.Warning:
logFn = wcLog.warn;
break;
case ConsoleMessageLevel.Info:
logFn = wcLog.info;
break;
}
// Only include line entries if we're debugging

View File

@@ -162,7 +162,7 @@ class MainPage extends React.PureComponent<Props, State> {
// set page on retry
window.desktop.onLoadRetry((viewId, retry, err, loadUrl) => {
console.log(`${viewId}: failed to load ${err}, but retrying`);
console.error(`${viewId}: failed to load ${err}, but retrying`);
const statusValue = {
status: Status.RETRY,
extra: {
@@ -179,7 +179,7 @@ class MainPage extends React.PureComponent<Props, State> {
});
window.desktop.onLoadFailed((viewId, err, loadUrl) => {
console.log(`${viewId}: failed to load ${err}`);
console.error(`${viewId}: failed to load ${err}`);
const statusValue = {
status: Status.FAILED,
extra: {

View File

@@ -56,7 +56,7 @@ class Root extends React.PureComponent<Record<string, never>, State> {
const configRequest = await window.desktop.getConfiguration() as CombinedConfig;
return configRequest;
} catch (err: any) {
console.log(`there was an error with the config: ${err}`);
console.error(`there was an error with the config: ${err}`);
if (exitOnError) {
window.desktop.quit(`unable to load configuration: ${err}`, err.stack);
}