Skip to content

Commit

Permalink
增加 api 界面,开放调试链接
Browse files Browse the repository at this point in the history
  • Loading branch information
niuniuland committed Mar 21, 2024
1 parent 5888eda commit 20a5607
Show file tree
Hide file tree
Showing 16 changed files with 168 additions and 18 deletions.
7 changes: 7 additions & 0 deletions .electron-builder.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ module.exports = async function () {
from: 'migrations',
to: 'app/migrations',
},
{
from: 'assets',
to: 'app/assets',
},
],
extraMetadata: {
version: getVersion(),
Expand All @@ -43,6 +47,9 @@ module.exports = async function () {
createDesktopShortcut: true,
createStartMenuShortcut: true,
shortcutName: 'chrome-power',
win: {
icon: "buildResources/icon.ico",
}
},

win: {
Expand Down
Binary file added buildResources/icon.ico
Binary file not shown.
16 changes: 11 additions & 5 deletions packages/main/src/fingerprint/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ const logger = createLogger(WINDOW_LOGGER_LABEL);

const HOST = '127.0.0.1';

const settings = getSettings();

// const HomePath = app.getPath('userData');
// console.log(HomePath);

Expand Down Expand Up @@ -85,10 +83,13 @@ async function connectBrowser(port: number, ipInfo: IP, windowId: number) {
} catch (error) {
logger.error(error);
}
return data;
}
}

const getDriverPath = () => {
const settings = getSettings();

if (settings.useLocalChrome) {
return settings.localChromePath;
} else {
Expand All @@ -101,14 +102,16 @@ export async function openFingerprintWindow(id: number) {
const proxyData = await ProxyDB.getById(windowData.proxy_id);
const proxyType = proxyData?.proxy_type?.toLowerCase();
const userDataPath = app.getPath('userData');
const settings = getSettings();

let cachePath;
if (settings.profileCachePath) {
cachePath = settings.profileCachePath;
} else {
cachePath = join(userDataPath, 'cache');
}
const win = BrowserWindow.getAllWindows()[0];
const windowDataDir = `${cachePath}\\${id}_${windowData.profile_id}`;
const windowDataDir = `${cachePath}\\${windowData.profile_id}`;
const driverPath = getDriverPath();

let ipInfo = {timeZone: '', ip: '', ll: [], country: ''};
Expand Down Expand Up @@ -213,13 +216,16 @@ export async function openFingerprintWindow(id: number) {
await sleep(1);

try {
connectBrowser(chromePort, ipInfo, windowData.id);
return connectBrowser(chromePort, ipInfo, windowData.id);
} catch (error) {
logger.error(error);
execSync(`taskkill /PID ${chromeInstance.pid} /F`);
closeFingerprintWindow(id, true);
return null;
}
} else {
win.webContents.send('window-opened', null);
logger.error('Driver path is empty');
return null;
}
}

Expand Down
10 changes: 10 additions & 0 deletions packages/main/src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,23 @@ import express from 'express';
import cors from 'cors';
import IPRouter from './routes/ip';
import WindowRouter from './routes/window';
import ProfilesRouter from './routes/profiles';

const app: Express = express();
let port: number = 49156; // 初始端口

app.use(cors());
app.use('/ip', IPRouter);
app.use('/window', WindowRouter);
app.use('/profiles', ProfilesRouter);

app.get('/status', async (req, res) => {

res.send({
status: 'ok',
port,
});
});

const server: Server = app
.listen(port, () => {
Expand Down
2 changes: 1 addition & 1 deletion packages/main/src/server/routes/ip.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const getIPInfo = async (ip: string, gateway: 'ip2location' | 'geoip') => {
}
if (gateway === 'ip2location') {
const ip2location = new IP2Location();
const filePath = path.join('assets', 'IP2LOCATION-LITE-DB11.BIN');
const filePath = path.join(import.meta.env.MODE === 'development' ? 'assets' : 'resources/app/assets', 'IP2LOCATION-LITE-DB11.BIN');
ip2location.open(filePath);
const ipInfo = ip2location.getAll(ip);
const {latitude, longitude, countryShort} = ipInfo;
Expand Down
23 changes: 23 additions & 0 deletions packages/main/src/server/routes/profiles.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import express from 'express';
import {WindowDB} from '/@/db/window';
import { openFingerprintWindow } from '/@/fingerprint';

const router = express.Router();

router.get('', async (req, res) => {
const windows = await WindowDB.all();
res.send(windows);
});

router.get('/browser', async (req, res) => {
const windowId = req.query.windowId as unknown as number;
const window = await WindowDB.getById(windowId);
const result = await openFingerprintWindow(windowId);

res.send({
window,
browser: result,
});
});

export default router;
11 changes: 11 additions & 0 deletions packages/main/src/services/commonService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {join} from 'path';
import {copyFileSync, writeFileSync, readFileSync, readdir} from 'fs';
import type {SettingOptions} from '../../../shared/types/common';
import {getSettings} from '../utils/get-settings';
import {getOrigin} from '../server';
import axios from 'axios';

const logger = createLogger(SERVICE_LOGGER_LABEL);

Expand Down Expand Up @@ -104,4 +106,13 @@ export const initCommonService = () => {
return path.filePaths[0];
},
);

ipcMain.handle('common-api', async () => {
const apiUrl = getOrigin();
const res = await axios.get(`${apiUrl}/status`);
return {
url: apiUrl,
...(res?.data || {}),
};
});
};
2 changes: 1 addition & 1 deletion packages/main/src/services/windowService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ export const initWindowService = () => {
};

export const randomFingerprint = () => {
const uaPath = path.join('assets', 'ua.txt');
const uaPath = path.join(import.meta.env.MODE === 'development' ? 'assets' : 'resources/app/assets', 'ua.txt');
const uaFile = readFileSync(uaPath, 'utf-8');
const uaList = uaFile.split('\n');
const randomIndex = Math.floor(Math.random() * uaList.length);
Expand Down
4 changes: 4 additions & 0 deletions packages/preload/src/bridges/common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,8 @@ export const CommonBridge = {
const result = await ipcRenderer.invoke('common-fetch-logs', logModule);
return result;
},
async getApi() {
const result = await ipcRenderer.invoke('common-api');
return result;
},
};
8 changes: 6 additions & 2 deletions packages/renderer/src/i18n.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ i18n
window_column_last_open: 'Last open',
window_column_created_at: 'Created at',
window_column_action: 'Action',
window_edit_form_profile_id: 'Profile ID',
window_edit_form_name: 'Name',
window_edit_form_remark: 'Remark',
window_edit_form_group: 'Group',
Expand Down Expand Up @@ -89,7 +90,7 @@ i18n
settings_cache_path: 'Cache path',
settings_choose_cache_path: 'Choose path',
settings_use_local_chrome: 'Use Chrome',
settings_chrome_path: 'Chrome Path',
settings_chrome_path: 'Chrome.exe Path',
setting_chromium_path: 'Chromium Path',

footer_ok: 'OK',
Expand All @@ -102,6 +103,7 @@ i18n
menu_settings: 'Settings',
menu_logs: 'Running Logs',
menu_sync: 'Sync',
menu_api: 'API',

header_language: 'Language',
header_settings: 'Settings',
Expand Down Expand Up @@ -142,6 +144,7 @@ i18n
window_column_last_open: '最后打开',
window_column_created_at: '创建时间',
window_column_action: '操作',
window_edit_form_profile_id: '缓存目录名',
window_edit_form_name: '名称',
window_edit_form_remark: '备注',
window_edit_form_group: '分组',
Expand Down Expand Up @@ -189,7 +192,7 @@ i18n
settings_cache_path: '缓存目录',
settings_choose_cache_path: '选择路径',
settings_use_local_chrome: '使用本地 Chrome',
settings_chrome_path: 'Chrome 路径',
settings_chrome_path: 'Chrome.exe 路径',
setting_chromium_path: 'Chromium 内核路径',

footer_ok: '确定',
Expand All @@ -202,6 +205,7 @@ i18n
menu_sync: '同步操作',
menu_logs: '运行日志',
menu_settings: '设置',
menu_api: 'API',

header_settings: '设置',
header_language: '语言',
Expand Down
5 changes: 3 additions & 2 deletions packages/renderer/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import type {ThemeConfig} from 'antd';
import {ConfigProvider, message} from 'antd';
import {HashRouter as Router} from 'react-router-dom';
import 'dayjs/locale/zh-cn';
import enUS from 'antd/locale/en_US';
// import enUS from 'antd/locale/en_US';
import zhCN from 'antd/locale/zh_CN';
import './i18n';

const rootContainer = document.getElementById('app');
Expand Down Expand Up @@ -42,7 +43,7 @@ const root = createRoot(rootContainer!);
root.render(
<React.StrictMode>
<ConfigProvider
locale={enUS}
locale={zhCN}
theme={customTheme}
>
<Router>
Expand Down
Empty file.
74 changes: 74 additions & 0 deletions packages/renderer/src/pages/api/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import {Card} from 'antd';
import React from 'react';
import './index.css';
import {CommonBridge} from '#preload';
import {useEffect, useState} from 'react';
import {Divider, Typography, Form} from 'antd';

const {Title, Paragraph, Text} = Typography;

const Api = () => {
const [apiInfo, setApiInfo] = useState({
url: '',
status: 'ok',
port: undefined,
});
const fetchApi = async () => {
const apiInfo = await CommonBridge.getApi();
setApiInfo(apiInfo);
console.log(apiInfo);
};

useEffect(() => {
fetchApi();
}, []);
return (
<>
<Card
className="content-card p-6 "
bordered={false}
>
<Title level={2}>API 详情</Title>

<Paragraph type="secondary">
API 作用于开发人员通过 <Text code>Puppeteer / Playwright / Selenium</Text>{' '}
等自动化工具连接浏览器实例,执行自动化脚本,非开发人员无需使用此功能。
</Paragraph>
<Divider />

<Form
name="validate_other"
size="large"
labelCol={{span: 4}}
wrapperCol={{span: 20}}
style={{maxWidth: 600}}
>
<Form.Item label="接口状态">
<Text type={apiInfo.status === 'ok' ? 'success' : 'warning'}>{apiInfo.status}</Text>
</Form.Item>
<Form.Item label="接口 URL">
<Text
type={apiInfo.status === 'ok' ? 'success' : 'warning'}
copyable
>
{apiInfo.url}
</Text>
</Form.Item>
</Form>
<Divider />

<Title level={3}>已支持接口</Title>

<Paragraph>* 获取所有窗口列表</Paragraph>
<Paragraph code copyable={{ text: `${apiInfo.url}/profiles` }}>
GET /profiles
</Paragraph>
<Paragraph>* 根据 ID 打开指定窗口(返回值中有调试链接)</Paragraph>
<Paragraph code copyable={{ text: `${apiInfo.url}/profiles/windowId=` }}>
GET /profiles/browser?windowId=xxx
</Paragraph>
</Card>
</>
);
};
export default Api;
2 changes: 0 additions & 2 deletions packages/renderer/src/pages/settings/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,11 @@ const Settings = () => {

const fetchSettings = async () => {
const settings = await CommonBridge.getSettings();
console.log(settings);
setFormValue(settings);
form.setFieldsValue(settings);
};

const handleSave = async (values: SettingOptions) => {
console.log(values);
await CommonBridge.saveSettings(values);
};

Expand Down
15 changes: 10 additions & 5 deletions packages/renderer/src/pages/windows/components/edit-form/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {useEffect, useState} from 'react';
import type {DB} from '../../../../../../shared/types/db';
import {GroupBridge, TagBridge, ProxyBridge} from '#preload';
import {TAG_COLORS} from '/@/constants';
import { useTranslation } from 'react-i18next';
import {useTranslation} from 'react-i18next';

const {TextArea} = Input;

Expand Down Expand Up @@ -144,9 +144,7 @@ const WindowEditForm = ({
name="remark"
label={t('window_edit_form_remark')}
>
<TextArea
rows={4}
/>
<TextArea rows={4} />
</Form.Item>

<Form.Item<FieldType>
Expand All @@ -158,9 +156,16 @@ const WindowEditForm = ({
allowClear
showSearch
filterOption={filterProxyOption}
fieldNames={{label: 'ip', value: 'id'}}
fieldNames={{label: 'proxy', value: 'id'}}
></Select>
</Form.Item>

<Form.Item<FieldType>
label={t('window_edit_form_profile_id')}
name="profile_id"
>
<Input />
</Form.Item>
</Form>
);
};
Expand Down
7 changes: 7 additions & 0 deletions packages/renderer/src/routes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {useMemo, type ReactElement} from 'react';
import {useTranslation} from 'react-i18next';
import Logs from '../pages/logs';
import Start from '../pages/start';
import Api from '../pages/api';

interface RouteOption {
path: string;
Expand Down Expand Up @@ -72,6 +73,12 @@ export const useRoutes = () => {
icon: <Icon icon="material-symbols:settings-outline" />,
component: Settings,
},
{
path: '/api',
name: t('menu_api'),
icon: <Icon icon="ant-design:api-outlined" />,
component: Api,
},
{
path: '/start',
component: () => <Start />,
Expand Down

0 comments on commit 20a5607

Please sign in to comment.