Skip to content

Commit

Permalink
Merge pull request #54 from zmzimpl/dev
Browse files Browse the repository at this point in the history
Dev
  • Loading branch information
zmzimpl authored Feb 20, 2025
2 parents 89758bc + 13c2d53 commit f314e1c
Show file tree
Hide file tree
Showing 10 changed files with 32 additions and 22 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "chrome-power",
"description": "The first open source multi-chrome manager tool.",
"version": "1.2.0",
"version": "1.2.1",
"private": true,
"author": {
"email": "zmzimpl@gmail.com",
Expand Down
5 changes: 5 additions & 0 deletions packages/main/src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import {getDbPath} from '../utils/get-db-path';
import {app} from 'electron';
import {join} from 'path';

export const DB_CONFIG = {
client: 'sqlite3',
Expand All @@ -17,3 +19,6 @@ export const WINDOW_LOGGER_LABEL = 'Window';
export const PROXY_LOGGER_LABEL = 'Proxy';
export const API_LOGGER_LABEL = 'Api';
export const MAIN_LOGGER_LABEL = 'Main';

export const CONFIG_FILE_PATH = join(app.getPath('userData'), 'chrome-power-config.json');
export const LOGS_PATH = join(app.getPath('userData'), 'logs');
7 changes: 7 additions & 0 deletions packages/main/src/db/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,12 @@ const deleteExtensionWindows = async (id: number, windowIds: number[]) => {
.delete();
};

const deleteWindowReleted = async (windowIds: number | number[]) => {
return await db('window_extension')
.whereIn('window_id', Array.isArray(windowIds) ? windowIds : [windowIds])
.delete();
};

const getExtensionWindows = async (id: number) => {
return await db('window_extension').where({extension_id: id});
};
Expand All @@ -72,6 +78,7 @@ export const ExtensionDB = {
createExtension,
updateExtension,
deleteExtension,
deleteWindowReleted,
insertExtensionWindows,
deleteExtensionWindows,
getExtensionWindows,
Expand Down
14 changes: 8 additions & 6 deletions packages/main/src/fingerprint/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,23 +110,25 @@ const getAvailablePort = async () => {
throw new Error('Failed to find a free port after multiple attempts');
};

const waitForChromeReady = async (chromePort: number, maxAttempts = 30) => {
const timeout = 500; // 每次尝试等待 500ms
const waitForChromeReady = async (chromePort: number, id: number, maxAttempts = 30) => {
let attempts = 0;

while (attempts < maxAttempts) {
try {
// 尝试连接 CDP
const response = await fetch(`http://127.0.0.1:${chromePort}/json/version`);
if (response.ok) {
const response = await api.get(`http://${HOST}:${chromePort}/json/version`, {
timeout: 1000,
});
if (response.status === 200) {
return true;
}
} catch (error) {
logger.error('连接失败', error);
// 连接失败,继续等待
}

attempts++;
await sleep(timeout);
await sleep(0.5);
}

throw new Error('Chrome instance failed to start within the timeout period');
Expand Down Expand Up @@ -292,7 +294,7 @@ export async function openFingerprintWindow(id: number, headless = false) {
await closeFingerprintWindow(id, false);
});

await waitForChromeReady(chromePort);
await waitForChromeReady(chromePort, id, 30);

try {
const browserURL = `http://${HOST}:${chromePort}`;
Expand Down
6 changes: 3 additions & 3 deletions packages/main/src/services/common-service.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {app, BrowserWindow, ipcMain, dialog, shell} from 'electron';
import {createLogger} from '../../../shared/utils/logger';
import {SERVICE_LOGGER_LABEL} from '../constants';
import {CONFIG_FILE_PATH, LOGS_PATH, SERVICE_LOGGER_LABEL} from '../constants';
import {join} from 'path';
import {copyFileSync, writeFileSync, readFileSync, readdir, existsSync, mkdirSync} from 'fs';
import type {SettingOptions} from '../../../shared/types/common';
Expand Down Expand Up @@ -45,7 +45,7 @@ export const initCommonService = () => {
// if (import.meta.env.DEV) {
// return [];
// }
const logDir = join(app.getPath('appData'), 'logs', module);
const logDir = join(LOGS_PATH, module);
if (!existsSync(logDir)) {
mkdirSync(logDir, {recursive: true});
}
Expand Down Expand Up @@ -90,7 +90,7 @@ export const initCommonService = () => {
if (values.localChromePath === '/Applications/Google Chrome.app') {
values.localChromePath = values.localChromePath + '/Contents/MacOS/Google Chrome';
}
const configFilePath = join(process.resourcesPath, 'chrome-power-config.json');
const configFilePath = CONFIG_FILE_PATH;

try {
writeFileSync(configFilePath, JSON.stringify(values), 'utf8');
Expand Down
3 changes: 1 addition & 2 deletions packages/main/src/services/extension-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import extract from 'extract-zip';
import {join} from 'path';
import {getSettings} from '../utils/get-settings';
import {db} from '../db';
import {readdir, rename} from 'fs/promises';

export const initExtensionService = () => {
ipcMain.handle('extension-create', async (_, extension: DB.Extension) => {
Expand Down Expand Up @@ -101,8 +102,6 @@ export const initExtensionService = () => {
mkdirSync(versionDir);

// 将临时目录中的文件移动到版本目录
const {rename} = require('fs/promises');
const {readdir} = require('fs/promises');
const files = await readdir(tempExtractDir);
for (const file of files) {
await rename(join(tempExtractDir, file), join(versionDir, file));
Expand Down
5 changes: 4 additions & 1 deletion packages/main/src/services/window-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import {randomASCII, randomFloat, randomInt} from '../../../shared/utils';
import path from 'path';
import puppeteer from 'puppeteer';
import {presetCookie} from '../puppeteer/helpers';

import {ExtensionDB} from '../db/extension';
const logger = createLogger(SERVICE_LOGGER_LABEL);
export const initWindowService = () => {
logger.info('init window service...');
Expand Down Expand Up @@ -50,12 +50,15 @@ export const initWindowService = () => {
});

ipcMain.handle('window-delete', async (_, id: number) => {
await ExtensionDB.deleteWindowReleted(id);
return await WindowDB.remove(id);
});
ipcMain.handle('window-batchClear', async (_, ids: number[]) => {
await ExtensionDB.deleteWindowReleted(ids);
return await WindowDB.batchClear(ids);
});
ipcMain.handle('window-batchDelete', async (_, ids: number[]) => {
await ExtensionDB.deleteWindowReleted(ids);
return await WindowDB.batchRemove(ids);
});

Expand Down
5 changes: 2 additions & 3 deletions packages/main/src/utils/get-settings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@ import {join} from 'path';
import type {SettingOptions} from '../../../shared/types/common';
import {getChromePath} from '../fingerprint/device';
import {app} from 'electron';

import {CONFIG_FILE_PATH} from '../constants';
export const getSettings = (): SettingOptions => {
const configFilePath = join(process.resourcesPath, 'chrome-power-config.json');
const configFilePath = CONFIG_FILE_PATH;
const isMac = process.platform === 'darwin';
const defaultCachePath = isMac
? `${app.getPath('documents')}/ChromePowerCache`
: join(app.getPath('appData'), 'ChromePowerCache');

let settings = {
profileCachePath: defaultCachePath,
useLocalChrome: true,
Expand Down
5 changes: 0 additions & 5 deletions packages/renderer/src/pages/extensions/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,6 @@ const Extensions = () => {
setLoading(true);
try {
const data = await ExtensionBridge.getAll();
console.log(data);
setExtensions(data);
} catch (error) {
messageApi.error('获取扩展列表失败');
Expand All @@ -169,7 +168,6 @@ const Extensions = () => {
};

const handleUploadExtension = async (extension: DB.Extension) => {
console.log(extension);
if (!extension.name || !extension.path) {
if (!extension.name) {
messageApi.error('请填写扩展名称');
Expand Down Expand Up @@ -279,19 +277,16 @@ const Extensions = () => {
showUploadList: false,
fileList,
onChange: ({fileList: newFileList}) => {
console.log(newFileList);
setFileList(newFileList);
},
accept: '.zip',
customRequest: async ({file, onSuccess, onError}) => {
try {
console.log(file);
setUploading(true);
const result = await ExtensionBridge.uploadPackage(
(file as File).path,
selectedExtension?.id,
);
console.log(result);
if (result.success) {
form.setFieldsValue({
id: result.extensionId,
Expand Down
2 changes: 1 addition & 1 deletion packages/shared/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ export function createLogger(label: string) {
// // 开发环境: 所有日志都输出到控制台
// transport = new winston.transports.Console({level: 'info'});
// } else {
const logsPath = join(app.getPath('appData'), 'logs');
const logsPath = join(app.getPath('userData'), 'logs');
if (!existsSync(logsPath)) {
mkdirSync(logsPath, {recursive: true});
}
Expand Down

0 comments on commit f314e1c

Please sign in to comment.