Skip to content

Commit

Permalink
fix: clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
syns2191 committed Nov 26, 2024
1 parent 48e6cbd commit 65147c4
Show file tree
Hide file tree
Showing 22 changed files with 209 additions and 157 deletions.
103 changes: 58 additions & 45 deletions .scripts/configure.electron.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,62 +3,75 @@ import * as path from 'path';
import { hideBin } from 'yargs/helpers';
import yargs from 'yargs';

const argv: any = yargs(hideBin(process.argv)).argv;
interface Arguments {
type: 'server' | 'constant'
}
const argv = yargs(hideBin(process.argv))
.options({
type: {
type: 'string',
choices: ['server', 'constant'],
demandOption: true,
description: 'Type of configuration to modify'
}
})
.parseSync() as Arguments;

function modifiedNextServer() {
const filePath = path.resolve(__dirname, '../apps/server-web/release/app/dist/standalone/apps/web/server.js');

let fileContent = fs.readFileSync(filePath, 'utf8');
const searchString = 'process.env.__NEXT_PRIVATE_STANDALONE_CONFIG';
const codeToInsert = `
nextConfig.serverRuntimeConfig = {
"GAUZY_API_SERVER_URL": process.env.GAUZY_API_SERVER_URL,
"NEXT_PUBLIC_GAUZY_API_SERVER_URL": process.env.NEXT_PUBLIC_GAUZY_API_SERVER_URL
}
`;

let lines = fileContent.split('\n');
const index = lines.findIndex((line) => line.includes(searchString));

if (index !== -1) {
lines.splice(index - 1, 0, codeToInsert);

fileContent = lines.join('\n');
fs.writeFileSync(filePath, fileContent, 'utf8');
console.log('Line of code successfully inserted.');
} else {
console.log(`The string "${searchString}" was not found in the file.`);
try {
let fileContent = fs.readFileSync(filePath, 'utf8');
const searchString = 'process.env.__NEXT_PRIVATE_STANDALONE_CONFIG';
const codeToInsert = `
nextConfig.serverRuntimeConfig = {
"GAUZY_API_SERVER_URL": process.env.GAUZY_API_SERVER_URL,
"NEXT_PUBLIC_GAUZY_API_SERVER_URL": process.env.NEXT_PUBLIC_GAUZY_API_SERVER_URL
}
`;

let lines = fileContent.split('\n');
const index = lines.findIndex((line) => line.includes(searchString));

if (index !== -1) {
lines.splice(index - 1, 0, codeToInsert);

fileContent = lines.join('\n');
fs.writeFileSync(filePath, fileContent, 'utf8');
console.log('Line of code successfully inserted.');
} else {
console.log(`The string "${searchString}" was not found in the file.`);
}
} catch (error) {
console.error('Failed to change static server configuration');
}
}

function modifiedWebConstant() {
const filePath = path.resolve(__dirname, '../apps/web/app/constants.ts');

let fileContent = fs.readFileSync(filePath, 'utf8');
const searchString = `export const IS_DESKTOP_APP = process.env.IS_DESKTOP_APP === 'true';`;
const codeToReplace = `export const IS_DESKTOP_APP = true;`;

fileContent = fileContent.replace(searchString, codeToReplace);

fs.writeFileSync(filePath, fileContent, 'utf8');
}

function revertWebConstant() {
function updateWebConstant(setDesktopApp) {
const filePath = path.resolve(__dirname, '../apps/web/app/constants.ts');

let fileContent = fs.readFileSync(filePath, 'utf8');
const codeToReplace = `export const IS_DESKTOP_APP = process.env.IS_DESKTOP_APP === 'true';`;
const searchString = `export const IS_DESKTOP_APP = true;`;

fileContent = fileContent.replace(searchString, codeToReplace);

fs.writeFileSync(filePath, fileContent, 'utf8');
try {
let fileContent = fs.readFileSync(filePath, 'utf8');
const envCheck = `export const IS_DESKTOP_APP = process.env.IS_DESKTOP_APP === 'true';`;
const hardcoded = `export const IS_DESKTOP_APP = true;`;

const [from, to] = setDesktopApp ? [envCheck, hardcoded] : [hardcoded, envCheck];

if (!fileContent.includes(from)) {
throw new Error(`Expected content not found in ${filePath}`);
}

fileContent = fileContent.replace(from, to);
fs.writeFileSync(filePath, fileContent, 'utf8');
console.log(`Successfully ${setDesktopApp ? 'set' : 'reverted'} IS_DESKTOP_APP`);
} catch (error) {
console.error('Failed to update constants:', error);
process.exit(1);
}
}


if (argv.type === 'server') {
modifiedNextServer();
revertWebConstant();
updateWebConstant(true);
} else if (argv.type === 'constant') {
modifiedWebConstant();
updateWebConstant(false);
}
34 changes: 34 additions & 0 deletions .scripts/copy-web-build.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { copy } from 'fs-extra';
import { join } from 'path';

async function copyWebBuild() {
const webDir = join(process.cwd(), 'apps/web');
const distDir = join(process.cwd(), 'apps/server-web/release/app/dist');

try {
// Copy standalone build
await copy(
join(webDir, '.next/standalone'),
join(distDir)
);

// Copy static files
await copy(
join(webDir, '.next/static'),
join(distDir, 'standalone/apps/web/.next/static')
);

// Copy public files
await copy(
join(webDir, 'public'),
join(distDir, 'standalone/apps/web/public')
);

console.log('Build files copied successfully');
} catch (error) {
console.error('Failed to copy build files:', error);
process.exit(1);
}
}

copyWebBuild();
3 changes: 1 addition & 2 deletions apps/server-web/src/main/helpers/constant.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,7 @@ export const SettingPageTypeMessage = {
updateSettingResponse: 'update-setting-response',
updateCancel: 'update-cancel',
restartServer: 'restart-server',
themeChange: 'theme-change',
autoUpdateSetting: 'auto-update-setting'
themeChange: 'theme-change'
}

export const ServerPageTypeMessage = {
Expand Down
24 changes: 12 additions & 12 deletions apps/server-web/src/main/helpers/interfaces/i-menu.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import { MenuItemConstructorOptions } from 'electron';
export interface AppMenu {
id?: string;
label?: string;
click?: () => void;
submenu?: AppSubMenu[]
}
label: string; // Menu label
submenu?: (AppMenu | ElectronMenuItem)[]; // Nested menus or Electron menu items
role?: 'appMenu' | 'fileMenu' | 'editMenu' | 'viewMenu' | 'windowMenu' | 'help'; // Predefined menu roles
type?: 'normal' | 'separator' | 'submenu' | 'checkbox' | 'radio'; // Menu item type
click?: () => void; // Click handler for the menu item
accelerator?: string; // Keyboard shortcut
enabled?: boolean; // Whether the item is enabled
visible?: boolean; // Whether the item is visible
checked?: boolean; // For 'checkbox' or 'radio' type
}

export interface AppSubMenu {
id?: string;
label?: string;
click?: () => void;
selector?: string;
type?: string;
accelerator?: string;
}
export type ElectronMenuItem = MenuItemConstructorOptions;
2 changes: 1 addition & 1 deletion apps/server-web/src/main/helpers/interfaces/i-server.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export interface GeneralConfig {
lang?: string
autoUpdate?: boolean
updateCheckPeriode?: string
updateCheckPeriod?: string
theme?: string
setup?: boolean
[key: string]: any
Expand Down
24 changes: 18 additions & 6 deletions apps/server-web/src/main/helpers/replace-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,26 @@ export const replaceConfig = async (folderPath: string, envOptions: EnvOptions)
}
}

export const clearDesktopConfig = (folderPath: string) => {
const fileNames = ['desktop-server.body', 'desktop-server.meta'];
export const clearDesktopConfig = async (folderPath: string): Promise<Boolean> => {
if (!folderPath || typeof folderPath !== 'string') {
throw new Error('Invalid folder path provided');
}
const DESKTOP_CONFIG_FILES = ['desktop-server.body', 'desktop-server.meta'] as const;
try {
// remove cached desktop server config
fileNames.forEach((file) => {
fs.unlinkSync(path.join(folderPath, file));
})
await Promise.all(
DESKTOP_CONFIG_FILES.map(async (file) => {
const filePath = path.join(folderPath, file);
try {
await fs.promises.unlink(filePath)
} catch (error: any) {
console.log('error unlink static web file', error.message)
}
})
)
return true;
} catch (error) {
console.log('skip unlink file on not exists');
console.log('Failed to clear static config');
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export class DesktopServerFactory {
if (!this.apiInstance && !!env) {
this.apiInstance = new WebService(path, env, win, signal, eventEmitter);
}
this.apiInstance.env = env;
this.apiInstance.updateEnv(env)
return this.apiInstance;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const DEFAULT_CONFIG:WebServer = {
general: {
lang: 'en',
autoUpdate: true,
updateCheckPeriode: '1140' // Time in minutes
updateCheckPeriod: '1140' // Time in minutes
}
}
export const LocalStore = {
Expand Down
8 changes: 6 additions & 2 deletions apps/server-web/src/main/helpers/services/web-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { EventEmitter } from 'stream';
export class WebService extends ServerTask {
constructor(
readonly path: string,
public env: any,
private env: any,
readonly window: BrowserWindow,
readonly signal: AbortSignal,
readonly eventEmitter: EventEmitter
Expand Down Expand Up @@ -41,4 +41,8 @@ export class WebService extends ServerTask {
public setApiConfig(): void {
Object.assign(this.args, {...this.env});
}
}

public updateEnv(env: any): void {
this.env = {...env};
}
}
57 changes: 29 additions & 28 deletions apps/server-web/src/main/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,13 +213,13 @@ const runServer = async () => {
try {
const envVal: ServerConfig | undefined = getEnvApi();
const folderPath = getWebDirPath();
clearDesktopConfig(folderPath);
await clearDesktopConfig(folderPath);

// Instantiate API and UI servers
await desktopServer.start(
{ api: serverPath },
{
...envVal,
...(envVal || {}),
IS_DESKTOP_APP: true
},
undefined,
Expand Down Expand Up @@ -462,7 +462,6 @@ const initTrayMenu = () => {
}
if (setupWindow) {
setupWindow?.show();
setupWindow?.
setupWindow?.webContents.once('did-finish-load', () => {
setTimeout(() => {
setupWindow?.webContents.send('languageSignal', storeConfig.general?.lang);
Expand Down Expand Up @@ -492,31 +491,33 @@ const getWebDirPath = () => {
ipcMain.on(IPC_TYPES.SETTING_PAGE, async (event, arg) => {
switch (arg.type) {
case SettingPageTypeMessage.saveSetting:
LocalStore.updateConfigSetting({
server: arg.data
});
const diFilesPath = getWebDirPath();
clearDesktopConfig(
diFilesPath
)
if (arg.isSetup) {
{
LocalStore.updateConfigSetting({
general: {
setup: true
}
});
setupWindow?.close();
eventEmitter.emit(EventLists.SERVER_WINDOW);
} else {
event.sender.send(IPC_TYPES.SETTING_PAGE, {
type: SettingPageTypeMessage.mainResponse, data: {
status: true,
isServerRun: isServerRun
}
server: arg.data
});
const diFilesPath = getWebDirPath();
await clearDesktopConfig(
diFilesPath
)
if (arg.isSetup) {
LocalStore.updateConfigSetting({
general: {
setup: true
}
});
setupWindow?.close();
eventEmitter.emit(EventLists.SERVER_WINDOW);
} else {
event.sender.send(IPC_TYPES.SETTING_PAGE, {
type: SettingPageTypeMessage.mainResponse, data: {
status: true,
isServerRun: isServerRun
}
});
}
break;
}
break;
case SettingPageTypeMessage.checkUpdate:
case SettingPageTypeMessage.checkUpdate:
updater.checkUpdate();
break;
case SettingPageTypeMessage.installUpdate:
Expand All @@ -540,7 +541,7 @@ ipcMain.on(IPC_TYPES.SETTING_PAGE, async (event, arg) => {
LocalStore.updateConfigSetting({
general: {
autoUpdate: arg.data.autoUpdate,
updateCheckPeriode: arg.data.updateCheckPeriode
updateCheckPeriod: arg.data.updateCheckPeriod
}
})
createIntervalAutoUpdate()
Expand Down Expand Up @@ -581,8 +582,8 @@ const createIntervalAutoUpdate = () => {
clearInterval(intervalUpdate)
}
const setting: WebServer = LocalStore.getStore('config');
if (setting.general?.autoUpdate && setting.general.updateCheckPeriode) {
const checkIntervalSecond = parseInt(setting.general.updateCheckPeriode);
if (setting.general?.autoUpdate && setting.general.updateCheckPeriod) {
const checkIntervalSecond = parseInt(setting.general.updateCheckPeriod);
if (!Number.isNaN(checkIntervalSecond)) {
const intervalMS = checkIntervalSecond * 60 * 1000;
intervalUpdate = setInterval(() => {
Expand Down
1 change: 0 additions & 1 deletion apps/server-web/src/main/menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ export default class MenuBuilder {
{
id: 'MENU_APP_ABOUT',
label: `MENU_APP.APP_ABOUT`,
selector: 'orderFrontStandardAboutPanel:',
click: () => {
this.eventEmitter.emit(EventLists.gotoAbout)
}
Expand Down
Loading

0 comments on commit 65147c4

Please sign in to comment.