Skip to content

Commit

Permalink
[Fix] server web dynamic api url (#2780)
Browse files Browse the repository at this point in the history
* fix: server web dynamic api using server setting value

* fix: apply dynamic api on desktop server web

* fix: dialog restart server on save setting

* fix: server web application menu

* fix: replace config setting on windows os

* style: clean code
  • Loading branch information
syns2191 authored Jul 22, 2024
1 parent f0282ec commit c45ed80
Show file tree
Hide file tree
Showing 12 changed files with 209 additions and 106 deletions.
3 changes: 2 additions & 1 deletion apps/server-web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@
"i18next-resources-to-backend": "^1.2.1",
"react-i18next": "^14.1.0",
"@radix-ui/react-switch": "^1.1.0",
"classnames": "^2.5.1"
"classnames": "^2.5.1",
"fast-glob": "^3.3.2"
},
"devDependencies": {
"electron": "28.1.0",
Expand Down
3 changes: 2 additions & 1 deletion apps/server-web/src/locales/i18n/bg/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@
"INFO": "Информация",
"UPDATE_AVAILABLE": "Налична е нова актуализация! Моля, щракнете върху бутона Изтегляне сега по-долу.",
"EXIT_MESSAGE": "Мрежата на сървъра все още работи, сигурни ли сте, че ще излезете от приложението?",
"UPDATE_SUCCESS": "Актуализирайте успешно"
"UPDATE_SUCCESS": "Актуализирайте успешно",
"SERVER_RUN_DIALOG": "Сървърната мрежа работи в момента, искате ли да рестартирате сървъра?"
},
"LANGUAGES": {
"en": "Английски",
Expand Down
3 changes: 2 additions & 1 deletion apps/server-web/src/locales/i18n/en/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,8 @@
"INFO": "Info",
"UPDATE_AVAILABLE": "New Update is available! Please click button Download Now below.",
"EXIT_MESSAGE": "Server web still running, Are you sure to exit the app ?",
"UPDATE_SUCCESS": "Update Successfully"
"UPDATE_SUCCESS": "Update Successfully",
"SERVER_RUN_DIALOG": "Server web currently running, You want to restart the server ?"
},
"LANGUAGES": {
"en": "English",
Expand Down
6 changes: 4 additions & 2 deletions apps/server-web/src/main/helpers/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ export const EventLists = {
UPDATE_CANCELLED: 'UPDATE_CANCELLED',
CHANGE_LANGUAGE: 'CHANGE_LANGUAGE',
OPEN_WEB: 'OPEN_WEB',
SERVER_WINDOW: 'SERVER_WINDOW'
SERVER_WINDOW: 'SERVER_WINDOW',
RESTART_SERVER: 'RESTART_SERVER'
}

export const SettingPageTypeMessage = {
Expand All @@ -33,7 +34,8 @@ export const SettingPageTypeMessage = {
langChange: 'lang',
updateSetting: 'update-setting',
updateSettingResponse: 'update-setting-response',
updateCancel: 'update-cancel'
updateCancel: 'update-cancel',
restartServer: 'restart-server'
}

export const ServerPageTypeMessage = {
Expand Down
3 changes: 2 additions & 1 deletion apps/server-web/src/main/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export * from './create-window'
export * from './create-window';
export * from './replace-config';
44 changes: 44 additions & 0 deletions apps/server-web/src/main/helpers/replace-config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import fs from 'fs';
import path from 'path';
import fg from 'fast-glob';
import os from 'os';

type EnvOptions = {
before: {
NEXT_PUBLIC_GAUZY_API_SERVER_URL?: string
},
after: {
NEXT_PUBLIC_GAUZY_API_SERVER_URL?: string
}
}

const scanAllFiles = async (files: string[], oldConfig: string, newConfig: string) => {
files.forEach((file) => {
if (path.extname(file) === '.js') {
try {
const data = fs.readFileSync(file, 'utf-8');
const result = data.replace(new RegExp(oldConfig, 'g'), newConfig);
fs.writeFileSync(file, result, 'utf8');
} catch (error) {
console.log('error replace', error);
}
}
});
}
export const replaceConfig = async (folderPath: string, envOptions: EnvOptions) => {
try {
console.log('all files path', folderPath);
if (os.platform() === 'win32') {
folderPath = folderPath.replace(/\\/g, '/');
}
console.log('final path', folderPath);
const NEXT_PUBLIC_GAUZY_API_SERVER_URL_BEFORE = `"NEXT_PUBLIC_GAUZY_API_SERVER_URL","${envOptions.before.NEXT_PUBLIC_GAUZY_API_SERVER_URL}"`;
const NEXT_PUBLIC_GAUZY_API_SERVER_URL_AFTER = `"NEXT_PUBLIC_GAUZY_API_SERVER_URL","${envOptions.after.NEXT_PUBLIC_GAUZY_API_SERVER_URL}"`;
const NEXT_PUBLIC_GAUZY_API_SERVER_URL_DEFAULT = `"NEXT_PUBLIC_GAUZY_API_SERVER_URL","https://api.ever.team"`;
const files = await fg(`${folderPath}/**/*`, { onlyFiles: true });
await scanAllFiles(files, NEXT_PUBLIC_GAUZY_API_SERVER_URL_BEFORE, NEXT_PUBLIC_GAUZY_API_SERVER_URL_AFTER);
await scanAllFiles(files, NEXT_PUBLIC_GAUZY_API_SERVER_URL_DEFAULT, NEXT_PUBLIC_GAUZY_API_SERVER_URL_AFTER);
} catch (error) {
console.log('error on replacing file', error);
}
}
66 changes: 60 additions & 6 deletions apps/server-web/src/main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,11 @@ import { mainBindings } from 'i18next-electron-fs-backend';
import i18nextMainBackend from '../configs/i18n.mainconfig';
import fs from 'fs';
import { WebServer } from './helpers/interfaces';
import { replaceConfig } from './helpers';
import Log from 'electron-log';
import MenuBuilder from './menu';


console.log = Log.log;
Object.assign(console, Log.functions);

Expand All @@ -32,8 +36,10 @@ let intervalUpdate: NodeJS.Timeout;
let tray: Tray;
let settingWindow: BrowserWindow | null = null;
let logWindow: BrowserWindow | null = null;
let SettingMenu: any = null;
let ServerWindowMenu: any = null;

Log.hooks.push((message:any, transport) => {
Log.hooks.push((message: any, transport) => {
if (transport !== Log.transports.file) {
return message;
}
Expand Down Expand Up @@ -167,7 +173,12 @@ const createWindow = async (type: 'SETTING_WINDOW' | 'LOG_WINDOW') => {
mainBindings(ipcMain, settingWindow, fs);
settingWindow.on('closed', () => {
settingWindow = null;
SettingMenu = null
});
if (!SettingMenu) {
SettingMenu = new MenuBuilder(settingWindow);
}
SettingMenu.buildMenu();
break;
case 'LOG_WINDOW':
logWindow = new BrowserWindow(defaultOptionWindow);
Expand All @@ -176,7 +187,12 @@ const createWindow = async (type: 'SETTING_WINDOW' | 'LOG_WINDOW') => {
mainBindings(ipcMain, logWindow, fs);
logWindow.on('closed', () => {
logWindow = null;
ServerWindowMenu = null
})
if (!ServerWindowMenu) {
ServerWindowMenu = new MenuBuilder(logWindow);
}
ServerWindowMenu.buildMenu();
break;
default:
break;
Expand Down Expand Up @@ -207,6 +223,16 @@ const stopServer = async () => {
await desktopServer.stop();
};

const restartServer = async () => {
await desktopServer.stop();
const waitingForServerStop = setInterval(async () => {
if (!isServerRun) {
clearInterval(waitingForServerStop);
await runServer()
}
}, 1000)
}

const getEnvApi = () => {
const setting: WebServer = LocalStore.getStore('config')
return setting.server;
Expand Down Expand Up @@ -237,15 +263,19 @@ const onInitApplication = () => {
})

eventEmitter.on(EventLists.webServerStop, async () => {
isServerRun = false;
await stopServer();
isServerRun = false;
})

eventEmitter.on(EventLists.RESTART_SERVER, async () => {
await restartServer();
})

eventEmitter.on(EventLists.webServerStarted, () => {
console.log(EventLists.webServerStarted)
updateTrayMenu('SERVER_START', { enabled: false }, eventEmitter, tray, trayMenuItems, i18nextMainBackend);
updateTrayMenu('SERVER_STOP', { enabled: true }, eventEmitter, tray, trayMenuItems, i18nextMainBackend);
updateTrayMenu('OPEN_WEB', { enabled: true}, eventEmitter, tray, trayMenuItems, i18nextMainBackend);
updateTrayMenu('OPEN_WEB', { enabled: true }, eventEmitter, tray, trayMenuItems, i18nextMainBackend);
updateTrayMenu('SERVER_STATUS', { label: 'MENU.SERVER_STATUS_STARTED' }, eventEmitter, tray, trayMenuItems, i18nextMainBackend);
if (logWindow) {
logWindow.webContents.send(IPC_TYPES.SERVER_PAGE, {
Expand All @@ -262,7 +292,7 @@ const onInitApplication = () => {
console.log(EventLists.webServerStopped);
updateTrayMenu('SERVER_STOP', { enabled: false }, eventEmitter, tray, trayMenuItems, i18nextMainBackend);
updateTrayMenu('SERVER_START', { enabled: true }, eventEmitter, tray, trayMenuItems, i18nextMainBackend);
updateTrayMenu('OPEN_WEB', { enabled: false}, eventEmitter, tray, trayMenuItems, i18nextMainBackend);
updateTrayMenu('OPEN_WEB', { enabled: false }, eventEmitter, tray, trayMenuItems, i18nextMainBackend);
updateTrayMenu('SERVER_STATUS', { label: 'MENU.SERVER_STATUS_STOPPED' }, eventEmitter, tray, trayMenuItems, i18nextMainBackend);
if (logWindow) {
logWindow.webContents.send(IPC_TYPES.SERVER_PAGE, {
Expand Down Expand Up @@ -385,14 +415,35 @@ ipcMain.on('message', async (event, arg) => {
event.reply('message', `${arg} World!`)
})

ipcMain.on(IPC_TYPES.SETTING_PAGE, (event, arg) => {
ipcMain.on(IPC_TYPES.SETTING_PAGE, async (event, arg) => {
console.log('main setting page', arg);
switch (arg.type) {
case SettingPageTypeMessage.saveSetting:
const existingConfig = getEnvApi();
LocalStore.updateConfigSetting({
server: arg.data
});
event.sender.send(IPC_TYPES.SETTING_PAGE, { type: SettingPageTypeMessage.mainResponse, data: true });
const dirFiles = 'standalone/apps/web/.next';
const devDirFilesPath = path.join(__dirname, resourceDir.webServer, dirFiles);
const packDirFilesPath = path.join(process.resourcesPath, 'release', 'app', 'dist', dirFiles)
const diFilesPath = isPack ? packDirFilesPath : devDirFilesPath;
await replaceConfig(
diFilesPath,
{
before: {
NEXT_PUBLIC_GAUZY_API_SERVER_URL: existingConfig?.NEXT_PUBLIC_GAUZY_API_SERVER_URL
},
after: {
NEXT_PUBLIC_GAUZY_API_SERVER_URL: arg.data.NEXT_PUBLIC_GAUZY_API_SERVER_URL
}
}
)
event.sender.send(IPC_TYPES.SETTING_PAGE, {
type: SettingPageTypeMessage.mainResponse, data: {
status: true,
isServerRun: isServerRun
}
});
break;
case SettingPageTypeMessage.checkUpdate:
updater.checkUpdate();
Expand All @@ -408,6 +459,9 @@ ipcMain.on(IPC_TYPES.SETTING_PAGE, (event, arg) => {
event.sender.send('languageSignal', arg.data);
eventEmitter.emit(EventLists.CHANGE_LANGUAGE, { code: arg.data })
break;
case SettingPageTypeMessage.restartServer:
eventEmitter.emit(EventLists.RESTART_SERVER)
break;
default:
break;
}
Expand Down
Loading

0 comments on commit c45ed80

Please sign in to comment.