Skip to content

Commit

Permalink
Merge pull request #193 from caorushizi/dev-webview
Browse files Browse the repository at this point in the history
feat(settings): ✨  新增无痕浏览模式
  • Loading branch information
caorushizi authored Jun 22, 2024
2 parents cb2deb5 + d1bc34e commit 63331e8
Show file tree
Hide file tree
Showing 10 changed files with 136 additions and 64 deletions.
4 changes: 4 additions & 0 deletions packages/main/src/controller/HomeController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,10 @@ export default class HomeController implements Controller {
if (key === "isMobile") {
this.webviewService.setUserAgent(val);
}
// privacy
if (key === "privacy") {
this.webviewService.setDefaultSession(val);
}

this.store.set(key, val);
}
Expand Down
1 change: 1 addition & 0 deletions packages/main/src/helper/variables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export const workspace = resolve(appData, appName);
export const defaultScheme = "mediago";
export const PERSIST_MEDIAGO = "persist:mediago";
export const PERSIST_WEBVIEW = "persist:webview";
export const PRIVACY_WEBVIEW = "webview";
export const db = resolve(workspace, "app.db");

// bin path
Expand Down
43 changes: 32 additions & 11 deletions packages/main/src/services/WebviewService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { TYPES } from "../types.ts";
import isDev from "electron-is-dev";
import {
PERSIST_WEBVIEW,
PRIVACY_WEBVIEW,
fetch,
mobileUA,
pcUA,
Expand All @@ -24,6 +25,7 @@ import { nativeTheme } from "electron/main";
export default class WebviewService {
private view: WebContentsView | null = null;
private blocker?: ElectronBlocker;
private defaultSession: string;

constructor(
@inject(TYPES.MainWindow)
Expand All @@ -45,14 +47,15 @@ export default class WebviewService {
this.sniffingHelper.start();
this.sniffingHelper.on("source", this.onSource);

const { useProxy, proxy } = this.store.store;
const { useProxy, proxy, privacy } = this.store.store;
this.setDefaultSession(privacy, true);
this.setProxy(useProxy, proxy);
}

async init(): Promise<void> {
this.view = new WebContentsView({
webPreferences: {
partition: PERSIST_WEBVIEW,
partition: this.defaultSession,
preload: resolve(__dirname, "./preload.js"),
},
});
Expand Down Expand Up @@ -221,12 +224,12 @@ export default class WebviewService {
}

private get session() {
return session.fromPartition(PERSIST_WEBVIEW);
return session.fromPartition(this.defaultSession);
}

private enableProxy(proxy: string) {
if (!proxy) {
this.logger.error("[proxy] 代理地址不能为空");
this.logger.error("[Proxy] 代理地址不能为空");
return;
}

Expand All @@ -236,12 +239,12 @@ export default class WebviewService {
}

this.session.setProxy({ proxyRules: proxy });
this.logger.info(`[proxy] 代理开启成功,代理地址为${proxy}`);
this.logger.info(`[Proxy] 代理开启(${proxy}`);
}

private disableProxy() {
this.session.setProxy({ proxyRules: "" });
this.logger.info("[proxy] 代理关闭成功");
this.logger.info("[Proxy] 代理关闭");
}

setProxy(useProxy: boolean, proxy: string): void {
Expand Down Expand Up @@ -269,23 +272,23 @@ export default class WebviewService {

private enableBlocking() {
if (!this.blocker) {
this.logger.error("开启 blocker 失败,未初始化");
this.logger.error("[AdBlocker] 开启失败(未初始化");
return;
}
this.blocker.enableBlockingInSession(this.session);
this.logger.info("开启 blocker 成功");
this.logger.info("[AdBlocker] 开启");
}

private disableBlocking() {
if (!this.blocker) {
this.logger.error("关闭 blocker 失败,未初始化");
this.logger.error("[AdBlocker] 关闭失败(未初始化");
return;
}
if (!this.blocker.isBlockingEnabled(this.session)) {
return;
}
this.blocker.disableBlockingInSession(this.session);
this.logger.info("关闭 blocker 成功");
this.logger.info("[AdBlocker] 关闭");
}

setUserAgent(isMobile?: boolean) {
Expand All @@ -295,7 +298,7 @@ export default class WebviewService {
} else {
this.view.webContents.setUserAgent(pcUA);
}
this.logger.info("设置 user-agent 成功", isMobile);
this.logger.info(`[UA] 设置为${isMobile ? "移动端" : " pc 端"}`);
}

captureView(): Promise<Electron.NativeImage> {
Expand All @@ -322,4 +325,22 @@ export default class WebviewService {
await this.session.clearCache();
await this.session.clearStorageData();
}

setDefaultSession(isPrivacy = false, init = false) {
this.logger.info(`[Session] ${isPrivacy ? "隐私" : "正常"}模式`);
if (isPrivacy) {
this.defaultSession = PRIVACY_WEBVIEW;
} else {
this.defaultSession = PERSIST_WEBVIEW;
}

if (this.view) {
this.destroyView();
this.init();
}

if (!init) {
this.window.webContents.send("change-privacy");
}
}
}
3 changes: 3 additions & 0 deletions packages/renderer/src/i18n/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,8 @@ Referer: http://www.example.com`,
canUseMouseWheelToAdjust: "Can use mouse wheel to adjust",
openBrowser: "Open Browser",
privacy: "Privacy Mode",
privacyTooltip:
"After turning on the switch, the browser will not save any data",
converter: "Converter",
addFile: "Add File",
},
Expand Down Expand Up @@ -265,6 +267,7 @@ Referer: http://www.example.com`,
canUseMouseWheelToAdjust: "可以使用鼠标滚轮调整",
openBrowser: "打开浏览器",
privacy: "隐私模式",
privacyTooltip: "打开开关后浏览器将不保存任何数据",
converter: "格式转换",
addFile: "添加文件",
},
Expand Down
61 changes: 33 additions & 28 deletions packages/renderer/src/layout/App/index.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import React, { FC, useState } from "react";
import { Link, Outlet, useLocation, useNavigate } from "react-router-dom";
import { Badge, Button, Layout, Menu, MenuProps, Flex } from "antd";
import { Badge, Button, Layout, Menu, MenuProps, Flex, Typography } from "antd";
import {
CheckCircleOutlined,
DownloadOutlined,
ExportOutlined,
EyeInvisibleOutlined,
ProfileOutlined,
QuestionCircleOutlined,
SettingOutlined,
Expand All @@ -21,8 +22,10 @@ import {
import { useAsyncEffect } from "ahooks";
import { useTranslation } from "react-i18next";
import { useStyles } from "./style";
import classNames from "classnames";

const { Footer, Sider, Content } = Layout;
const { Text } = Typography;

type MenuItem = Required<MenuProps>["items"][number];

Expand All @@ -45,7 +48,6 @@ const App: FC = () => {
const location = useLocation();
const navigate = useNavigate();
const dispatch = useDispatch();
const [showExport, setShowExport] = useState(false);
const count = useSelector(selectCount);
const appStore = useSelector(selectAppStore);
const { styles } = useStyles();
Expand Down Expand Up @@ -89,38 +91,33 @@ const App: FC = () => {
},
{
label: (
<Link to="/source" className={styles.linkItem}>
<Link
to="/source"
className={classNames([styles.linkItem, styles.extract])}
>
<ProfileOutlined />
<span>{t("materialExtraction")}</span>
{showExport && (
<Button
title={t("openInNewWindow")}
type="text"
style={{ marginLeft: "auto" }}
icon={<ExportOutlined />}
onClick={async (e) => {
e.stopPropagation();
e.preventDefault();
<Button
title={t("openInNewWindow")}
type="text"
className={styles.hoverButton}
icon={<ExportOutlined />}
onClick={async (e) => {
e.stopPropagation();
e.preventDefault();

dispatch(setAppStore({ openInNewWindow: true }));
if (location.pathname === "/source") {
navigate("/");
}
// FIXME: 有可能 webview 还没有完全隐藏
await ipcSetAppStore("openInNewWindow", true);
await showBrowserWindow();
}}
/>
)}
dispatch(setAppStore({ openInNewWindow: true }));
if (location.pathname === "/source") {
navigate("/");
}
// FIXME: 有可能 webview 还没有完全隐藏
await ipcSetAppStore("openInNewWindow", true);
await showBrowserWindow();
}}
/>
</Link>
),
key: "source",
onMouseEnter: () => {
setShowExport(true);
},
onMouseLeave: () => {
setShowExport(false);
},
},
{
label: (
Expand Down Expand Up @@ -169,6 +166,14 @@ const App: FC = () => {
<Outlet />
</Content>
<Footer className={styles.containerFooter}>
<Text>
{appStore.privacy && (
<>
<EyeInvisibleOutlined /> 隐私模式
</>
)}
</Text>

<Button
type={"link"}
onClick={openHelpUrl}
Expand Down
64 changes: 40 additions & 24 deletions packages/renderer/src/layout/App/style.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,42 @@
import { createStyles } from "antd-style";

export const useStyles = createStyles(({ css, token }) => ({
container: css`
height: 100vh;
width: 100vw;
overflow: hidden;
`,
containerSider: css`
border-right: ${token.colorBorderSecondary} solid 1px;
`,
containerInner: css`
height: 100%;
`,
linkItem: css`
display: flex;
flex-direction: row;
align-items: center;
`,
containerFooter: css`
padding: 5px;
background: ${token.colorBgContainer};
text-align: right;
border-top: ${token.colorBorderSecondary} solid 1px;
`,
}));
export const useStyles = createStyles(({ css, token, cx }) => {
const hoverButton = cx(css`
margin-left: auto;
display: none;
`);
return {
container: css`
height: 100vh;
width: 100vw;
overflow: hidden;
`,
containerSider: css`
border-right: ${token.colorBorderSecondary} solid 1px;
`,
containerInner: css`
height: 100%;
`,
linkItem: css`
display: flex;
flex-direction: row;
align-items: center;
`,
extract: css`
&:hover {
.${hoverButton} {
display: block;
}
}
`,
containerFooter: css`
padding: 5px 5px 5px 15px;
background: ${token.colorBgContainer};
text-align: right;
border-top: ${token.colorBorderSecondary} solid 1px;
justify-content: space-between;
display: flex;
`,
hoverButton,
};
});
5 changes: 4 additions & 1 deletion packages/renderer/src/pages/SettingPage/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,10 @@ const SettingPage: React.FC = () => {
)}
name="autoUpgrade"
/>
{/* <ProFormSwitch label={t("privacy")} name="privacy" /> */}
<ProFormSwitch
label={renderTooltipLabel(t("privacy"), t("privacyTooltip"))}
name="privacy"
/>
</ProFormGroup>
<ProFormGroup title={t("browserSetting")} direction={"vertical"}>
<ProFormText
Expand Down
7 changes: 7 additions & 0 deletions packages/renderer/src/pages/SourceExtract/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -213,13 +213,19 @@ const SourceExtract: React.FC<SourceExtractProps> = ({ page = false }) => {
setModalShow(true);
};

const onChangePrivacy = () => {
document.title = originTitle.current;
dispatch(setBrowserStore({ url: "", title: "", mode: PageMode.Default }));
};

useEffect(() => {
addIpcListener("webview-dom-ready", onDomReady);
addIpcListener("webview-fail-load", onFailLoad);
addIpcListener("webview-did-navigate", onDidNavigate);
addIpcListener("webview-did-navigate-in-page", onDidNavigateInPage);
addIpcListener("favorite-item-event", onFavoriteEvent);
addIpcListener("show-download-dialog", onShowDownloadDialog);
addIpcListener("change-privacy", onChangePrivacy);

return () => {
removeIpcListener("webview-dom-ready", onDomReady);
Expand All @@ -228,6 +234,7 @@ const SourceExtract: React.FC<SourceExtractProps> = ({ page = false }) => {
removeIpcListener("webview-did-navigate-in-page", onDidNavigateInPage);
removeIpcListener("favorite-item-event", onFavoriteEvent);
removeIpcListener("show-download-dialog", onShowDownloadDialog);
removeIpcListener("change-privacy", onChangePrivacy);
};
}, [store.status]);

Expand Down
8 changes: 8 additions & 0 deletions packages/renderer/src/renderer.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@ declare interface AppStore {
language?: AppLanguage;
// 是否显示终端
showTerminal?: boolean;
// 隐私模式
privacy?: boolean;
// 机器id
machineId?: string;
// 下载代理设置
downloadProxySwitch?: boolean;
// 自动更新
autoUpgrade?: boolean;
}

declare interface BrowserStore {
Expand Down
4 changes: 4 additions & 0 deletions packages/renderer/src/store/appSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ const initialState: AppStore = {
maxRunner: 2,
language: AppLanguage.System,
showTerminal: false,
privacy: false,
machineId: "",
downloadProxySwitch: false,
autoUpgrade: true,
};

export const appSlice = createSlice({
Expand Down

0 comments on commit 63331e8

Please sign in to comment.