Skip to content

Commit 6fab899

Browse files
authored
Merge pull request #1073 from TriliumNext/refactor_utils-isPlatform
refactor(server/utils): turn isMac/isWin/isElectron/isDev into boolean
2 parents fd53d49 + 31c4675 commit 6fab899

23 files changed

+54
-75
lines changed

src/app.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ app.use((req, res, next) => {
3535
return next();
3636
});
3737

38-
if (!utils.isElectron()) {
38+
if (!utils.isElectron) {
3939
app.use(compression()); // HTTP compression
4040
}
4141

@@ -77,7 +77,7 @@ await import("./services/scheduler.js");
7777

7878
startScheduledCleanup();
7979

80-
if (utils.isElectron()) {
80+
if (utils.isElectron) {
8181
(await import("@electron/remote/main/index.js")).initialize();
8282
}
8383

src/routes/api/clipper.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -195,7 +195,7 @@ function processContent(images: Image[], note: BNote, content: string) {
195195
}
196196

197197
function openNote(req: Request) {
198-
if (utils.isElectron()) {
198+
if (utils.isElectron) {
199199
ws.sendMessageToAllClients({
200200
type: "openNote",
201201
noteId: req.params.noteId

src/routes/api/files.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -181,7 +181,7 @@ function saveToTmpDir(fileName: string, content: string | Buffer, entityType: st
181181

182182
log.info(`Saved temporary file ${tmpObj.name}`);
183183

184-
if (utils.isElectron()) {
184+
if (utils.isElectron) {
185185
chokidar.watch(tmpObj.name).on("change", (path, stats) => {
186186
ws.sendMessageToAllClients({
187187
type: "openedFileUpdated",

src/routes/assets.ts

+3-3
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,11 @@ import assetPath from "../services/asset_path.js";
22
import path from "path";
33
import { fileURLToPath } from "url";
44
import express from "express";
5-
import env from "../services/env.js";
5+
import { isDev } from "../services/utils.js";
66
import type serveStatic from "serve-static";
77

88
const persistentCacheStatic = (root: string, options?: serveStatic.ServeStaticOptions<express.Response<any, Record<string, any>>>) => {
9-
if (!env.isDev()) {
9+
if (!isDev) {
1010
options = {
1111
maxAge: "1y",
1212
...options
@@ -17,7 +17,7 @@ const persistentCacheStatic = (root: string, options?: serveStatic.ServeStaticOp
1717

1818
async function register(app: express.Application) {
1919
const srcRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), "..");
20-
if (env.isDev()) {
20+
if (isDev) {
2121
const webpack = (await import("webpack")).default;
2222
const webpackMiddleware = (await import("webpack-dev-middleware")).default;
2323
const productionConfig = (await import("../../webpack.config.js")).default;

src/routes/csrf_protection.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ const doubleCsrfUtilities = doubleCsrf({
88
path: "", // empty, so cookie is valid only for the current path
99
secure: false,
1010
sameSite: "strict",
11-
httpOnly: !isElectron() // set to false for Electron, see https://github.com/TriliumNext/Notes/pull/966
11+
httpOnly: !isElectron // set to false for Electron, see https://github.com/TriliumNext/Notes/pull/966
1212
},
1313
cookieName: "_csrf"
1414
});

src/routes/index.ts

+3-5
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@ import attributeService from "../services/attributes.js";
55
import config from "../services/config.js";
66
import optionService from "../services/options.js";
77
import log from "../services/log.js";
8-
import env from "../services/env.js";
9-
import utils from "../services/utils.js";
8+
import { isDev, isElectron } from "../services/utils.js";
109
import protectedSessionService from "../services/protected_session.js";
1110
import packageJson from "../../package.json" with { type: "json" };
1211
import assetPath from "../services/asset_path.js";
@@ -19,7 +18,7 @@ import type BNote from "../becca/entities/bnote.js";
1918
function index(req: Request, res: Response) {
2019
const options = optionService.getOptionMap();
2120

22-
const view = !utils.isElectron() && req.cookies["trilium-device"] === "mobile" ? "mobile" : "desktop";
21+
const view = !isElectron && req.cookies["trilium-device"] === "mobile" ? "mobile" : "desktop";
2322

2423
//'overwrite' set to false (default) => the existing token will be re-used and validated
2524
//'validateOnReuse' set to false => if validation fails, generate a new token instead of throwing an error
@@ -34,7 +33,6 @@ function index(req: Request, res: Response) {
3433
const theme = options.theme;
3534
const themeNote = attributeService.getNoteWithLabel("appTheme", theme);
3635

37-
const isElectron = utils.isElectron();
3836
res.render(view, {
3937
device: view,
4038
csrfToken: csrfToken,
@@ -53,7 +51,7 @@ function index(req: Request, res: Response) {
5351
maxEntityChangeSyncIdAtLoad: sql.getValue("SELECT COALESCE(MAX(id), 0) FROM entity_changes WHERE isSynced = 1"),
5452
instanceName: config.General ? config.General.instanceName : null,
5553
appCssNoteIds: getAppCssNoteIds(),
56-
isDev: env.isDev(),
54+
isDev,
5755
isMainWindow: view === "mobile" ? true : !req.query.extraWindow,
5856
isProtectedSessionAvailable: protectedSessionService.isProtectedSessionAvailable(),
5957
maxContentWidth: Math.max(640, parseInt(options.maxContentWidth)),

src/routes/routes.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
"use strict";
22

3-
import utils from "../services/utils.js";
3+
import { isElectron } from "../services/utils.js";
44
import multer from "multer";
55
import log from "../services/log.js";
66
import express from "express";
@@ -280,7 +280,7 @@ function register(app: express.Application) {
280280
apiRoute(DEL, "/api/etapi-tokens/:etapiTokenId", etapiTokensApiRoutes.deleteToken);
281281

282282
// in case of local electron, local calls are allowed unauthenticated, for server they need auth
283-
const clipperMiddleware = utils.isElectron() ? [] : [auth.checkEtapiToken];
283+
const clipperMiddleware = isElectron ? [] : [auth.checkEtapiToken];
284284

285285
route(GET, "/api/clipper/handshake", clipperMiddleware, clipperRoute.handshake, apiResultHandler);
286286
route(PST, "/api/clipper/clippings", clipperMiddleware, clipperRoute.addClipping, apiResultHandler);

src/routes/setup.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,14 @@
22

33
import sqlInit from "../services/sql_init.js";
44
import setupService from "../services/setup.js";
5-
import utils from "../services/utils.js";
5+
import { isElectron } from "../services/utils.js";
66
import assetPath from "../services/asset_path.js";
77
import appPath from "../services/app_path.js";
88
import type { Request, Response } from "express";
99

1010
function setupPage(req: Request, res: Response) {
1111
if (sqlInit.isDbInitialized()) {
12-
if (utils.isElectron()) {
12+
if (isElectron) {
1313
handleElectronRedirect();
1414
} else {
1515
res.redirect(".");

src/services/app_icon.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ Terminal=false
2323
* We overwrite this file during every run as it might have been updated.
2424
*/
2525
function installLocalAppIcon() {
26-
if (!isElectron() || ["win32", "darwin"].includes(os.platform()) || (config.General && config.General.noDesktopIcon)) {
26+
if (!isElectron || ["win32", "darwin"].includes(os.platform()) || (config.General && config.General.noDesktopIcon)) {
2727
return;
2828
}
2929

src/services/app_path.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
import assetPath from "./asset_path.js";
2-
import env from "./env.js";
2+
import { isDev } from "./utils.js";
33

4-
export default env.isDev() ? assetPath + "/app" : assetPath + "/app-dist";
4+
export default isDev ? assetPath + "/app" : assetPath + "/app-dist";

src/services/auth.ts

+4-4
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ const noAuthentication = config.General && config.General.noAuthentication === t
1414
function checkAuth(req: Request, res: Response, next: NextFunction) {
1515
if (!sqlInit.isDbInitialized()) {
1616
res.redirect("setup");
17-
} else if (!req.session.loggedIn && !isElectron() && !noAuthentication) {
17+
} else if (!req.session.loggedIn && !isElectron && !noAuthentication) {
1818
res.redirect("login");
1919
} else {
2020
next();
@@ -24,7 +24,7 @@ function checkAuth(req: Request, res: Response, next: NextFunction) {
2424
// for electron things which need network stuff
2525
// currently, we're doing that for file upload because handling form data seems to be difficult
2626
function checkApiAuthOrElectron(req: Request, res: Response, next: NextFunction) {
27-
if (!req.session.loggedIn && !isElectron() && !noAuthentication) {
27+
if (!req.session.loggedIn && !isElectron && !noAuthentication) {
2828
reject(req, res, "Logged in session not found");
2929
} else {
3030
next();
@@ -48,15 +48,15 @@ function checkAppInitialized(req: Request, res: Response, next: NextFunction) {
4848
}
4949

5050
function checkPasswordSet(req: Request, res: Response, next: NextFunction) {
51-
if (!isElectron() && !passwordService.isPasswordSet()) {
51+
if (!isElectron && !passwordService.isPasswordSet()) {
5252
res.redirect("set-password");
5353
} else {
5454
next();
5555
}
5656
}
5757

5858
function checkPasswordNotSet(req: Request, res: Response, next: NextFunction) {
59-
if (!isElectron() && passwordService.isPasswordSet()) {
59+
if (!isElectron && passwordService.isPasswordSet()) {
6060
res.redirect("login");
6161
} else {
6262
next();

src/services/code_block_theme.ts

+2-3
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@ import fs from "fs";
88
import themeNames from "./code_block_theme_names.json" with { type: "json" };
99
import { t } from "i18next";
1010
import { join } from "path";
11-
import { isElectron, getResourceDir } from "./utils.js";
12-
import env from "./env.js";
11+
import { isDev, isElectron, getResourceDir } from "./utils.js";
1312

1413
/**
1514
* Represents a color scheme for the code block syntax highlight.
@@ -46,7 +45,7 @@ export function listSyntaxHighlightingThemes() {
4645
}
4746

4847
function getStylesDirectory() {
49-
if (isElectron() && !env.isDev()) {
48+
if (isElectron && !isDev) {
5049
return "styles";
5150
}
5251

src/services/env.ts

-7
This file was deleted.

src/services/keyboard_actions.ts

+1-4
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,10 @@
22

33
import optionService from "./options.js";
44
import log from "./log.js";
5-
import { isElectron as getIsElectron, isMac as getIsMac } from "./utils.js";
5+
import { isElectron, isMac } from "./utils.js";
66
import type { KeyboardShortcut } from "./keyboard_actions_interface.js";
77
import { t } from "i18next";
88

9-
const isMac = getIsMac();
10-
const isElectron = getIsElectron();
11-
129
function getDefaultKeyboardActions() {
1310
if (!t("keyboard_actions.note-navigation")) {
1411
throw new Error("Keyboard actions loaded before translations.");

src/services/log.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ const MINUTE = 60 * SECOND;
1717
const HOUR = 60 * MINUTE;
1818
const DAY = 24 * HOUR;
1919

20-
const NEW_LINE = isWindows() ? "\r\n" : "\n";
20+
const NEW_LINE = isWindows ? "\r\n" : "\n";
2121

2222
let todaysMidnight!: Date;
2323

src/services/options_init.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ const defaultOptions: DefaultOption[] = [
7777
{ name: "revisionSnapshotTimeInterval", value: "600", isSynced: true },
7878
{ name: "revisionSnapshotNumberLimit", value: "-1", isSynced: true },
7979
{ name: "protectedSessionTimeout", value: "600", isSynced: true },
80-
{ name: "zoomFactor", value: isWindows() ? "0.9" : "1.0", isSynced: false },
80+
{ name: "zoomFactor", value: isWindows ? "0.9" : "1.0", isSynced: false },
8181
{ name: "overrideThemeFonts", value: "false", isSynced: false },
8282
{ name: "mainFontFamily", value: "theme", isSynced: false },
8383
{ name: "mainFontSize", value: "100", isSynced: false },

src/services/port.ts

+3-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
import config from "./config.js";
2-
import { isElectron } from "./utils.js";
3-
import env from "./env.js";
2+
import { isDev, isElectron } from "./utils.js";
43
import dataDir from "./data_dir.js";
54

65
function parseAndValidate(portStr: string, source: string) {
@@ -18,8 +17,8 @@ let port: number;
1817

1918
if (process.env.TRILIUM_PORT) {
2019
port = parseAndValidate(process.env.TRILIUM_PORT, "environment variable TRILIUM_PORT");
21-
} else if (isElectron()) {
22-
port = env.isDev() ? 37740 : 37840;
20+
} else if (isElectron) {
21+
port = isDev ? 37740 : 37840;
2322
} else {
2423
port = parseAndValidate(config["Network"]["port"] || "3000", `Network.port in ${dataDir.CONFIG_INI_PATH}`);
2524
}

src/services/request.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -206,7 +206,7 @@ async function getProxyAgent(opts: ClientOpts) {
206206
async function getClient(opts: ClientOpts): Promise<Client> {
207207
// it's not clear how to explicitly configure proxy (as opposed to system proxy),
208208
// so in that case, we always use node's modules
209-
if (isElectron() && !opts.proxy) {
209+
if (isElectron && !opts.proxy) {
210210
return (await import("electron")).net as Client;
211211
} else {
212212
const { protocol } = url.parse(opts.url);

src/services/sql_init.ts

+1-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ function isDbInitialized() {
3737

3838
async function initDbConnection() {
3939
if (!isDbInitialized()) {
40-
log.info(`DB not initialized, please visit setup page` + (isElectron() ? "" : ` - http://[your-server-host]:${port} to see instructions on how to initialize Trilium.`));
40+
log.info(`DB not initialized, please visit setup page` + (isElectron ? "" : ` - http://[your-server-host]:${port} to see instructions on how to initialize Trilium.`));
4141

4242
return;
4343
}

src/services/utils.ts

+10-15
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,18 @@ import sanitize from "sanitize-filename";
88
import mimeTypes from "mime-types";
99
import path from "path";
1010
import { fileURLToPath } from "url";
11-
import env from "./env.js";
1211
import { dirname, join } from "path";
1312

1413
const randtoken = generator({ source: "crypto" });
1514

15+
export const isMac = process.platform === "darwin";
16+
17+
export const isWindows = process.platform === "win32";
18+
19+
export const isElectron = !!process.versions["electron"];
20+
21+
export const isDev = !!(process.env.TRILIUM_ENV && process.env.TRILIUM_ENV === "dev");
22+
1623
export function newEntityId() {
1724
return randomString(12);
1825
}
@@ -58,10 +65,6 @@ export function hmac(secret: any, value: any) {
5865
return hmac.digest("base64");
5966
}
6067

61-
export function isElectron() {
62-
return !!process.versions["electron"];
63-
}
64-
6568
export function hash(text: string) {
6669
text = text.normalize();
6770

@@ -128,7 +131,7 @@ export function escapeRegExp(str: string) {
128131
}
129132

130133
export async function crash() {
131-
if (isElectron()) {
134+
if (isElectron) {
132135
(await import("electron")).app.exit(1);
133136
} else {
134137
process.exit(1);
@@ -314,21 +317,13 @@ export function envToBoolean(val: string | undefined) {
314317
* @returns the resource dir.
315318
*/
316319
export function getResourceDir() {
317-
if (isElectron() && !env.isDev()) {
320+
if (isElectron && !isDev) {
318321
return process.resourcesPath;
319322
} else {
320323
return join(dirname(fileURLToPath(import.meta.url)), "..", "..");
321324
}
322325
}
323326

324-
export function isMac() {
325-
return process.platform === "darwin";
326-
}
327-
328-
export function isWindows() {
329-
return process.platform === "win32";
330-
}
331-
332327
export default {
333328
randomSecureToken,
334329
randomString,

src/services/window.ts

+5-6
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,14 @@ import path from "path";
22
import url from "url";
33
import port from "./port.js";
44
import optionService from "./options.js";
5-
import env from "./env.js";
65
import log from "./log.js";
76
import sqlInit from "./sql_init.js";
87
import cls from "./cls.js";
98
import keyboardActionsService from "./keyboard_actions.js";
109
import remoteMain from "@electron/remote/main/index.js";
1110
import type { App, BrowserWindow, BrowserWindowConstructorOptions, WebContents } from "electron";
1211
import { ipcMain } from "electron";
13-
import { isMac, isWindows } from "./utils.js";
12+
import { isDev, isMac, isWindows } from "./utils.js";
1413

1514
import { fileURLToPath } from "url";
1615
import { dirname } from "path";
@@ -116,10 +115,10 @@ function getWindowExtraOpts() {
116115
const extraOpts: Partial<BrowserWindowConstructorOptions> = {};
117116

118117
if (!optionService.getOptionBool("nativeTitleBarVisible")) {
119-
if (isMac()) {
118+
if (isMac) {
120119
extraOpts.titleBarStyle = "hiddenInset";
121120
extraOpts.titleBarOverlay = true;
122-
} else if (isWindows()) {
121+
} else if (isWindows) {
123122
extraOpts.titleBarStyle = "hidden";
124123
extraOpts.titleBarOverlay = true;
125124
} else {
@@ -129,7 +128,7 @@ function getWindowExtraOpts() {
129128
}
130129

131130
// Window effects (Mica)
132-
if (optionService.getOptionBool("backgroundEffects") && isWindows()) {
131+
if (optionService.getOptionBool("backgroundEffects") && isWindows) {
133132
extraOpts.backgroundMaterial = "auto";
134133
}
135134

@@ -169,7 +168,7 @@ function configureWebContents(webContents: WebContents, spellcheckEnabled: boole
169168
}
170169

171170
function getIcon() {
172-
return path.join(dirname(fileURLToPath(import.meta.url)), "../../images/app-icons/png/256x256" + (env.isDev() ? "-dev" : "") + ".png");
171+
return path.join(dirname(fileURLToPath(import.meta.url)), "../../images/app-icons/png/256x256" + (isDev ? "-dev" : "") + ".png");
173172
}
174173

175174
async function createSetupWindow() {

0 commit comments

Comments
 (0)