Skip to content

Commit

Permalink
fix(proxy): Fixed the issue that the TCP connection was interrupted w…
Browse files Browse the repository at this point in the history
…hen setting a proxy

siyuan-note/siyuan#9708
  • Loading branch information
Zuoqiu-Yingyi committed Nov 21, 2023
1 parent 081530a commit cb68e91
Show file tree
Hide file tree
Showing 11 changed files with 114 additions and 58 deletions.
30 changes: 21 additions & 9 deletions app/electron/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -763,7 +763,7 @@ app.whenReady().then(() => {
event.sender.send("siyuan-event", "leave-full-screen");
});
});
ipcMain.on("siyuan-cmd", (event, data) => {
ipcMain.on("siyuan-cmd", async (event, data) => {
let cmd = data;
let webContentsId = event.sender.id;
if (typeof data !== "string") {
Expand Down Expand Up @@ -831,17 +831,29 @@ app.whenReady().then(() => {
}
break;
case "setProxy":
event.sender.session.closeAllConnections().then(() => {
try {
let proxy, log;
if (data.proxyURL.startsWith("://")) {
event.sender.session.setProxy({mode: "system"}).then(() => {
console.log("network proxy [system]");
});
return;
proxy = {mode: "system"};
log = "network proxy [system]";
} else {
proxy = {proxyRules: data.proxyURL};
log = `network proxy [${data.proxyURL}]`;
}
event.sender.session.setProxy({proxyRules: data.proxyURL}).then(() => {
console.log("network proxy [" + data.proxyURL + "]");
await event.sender.session.closeAllConnections();
await event.sender.session.setProxy(proxy);
console.log(log);
event.reply("siyuan-proxy-reply", {
state: "fulfilled",
proxy,
});
});
} catch (error) {
event.reply("siyuan-proxy-reply", {
state: "rejected",
proxy,
error,
});
}
break;
}
});
Expand Down
2 changes: 1 addition & 1 deletion app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
"clean-webpack-plugin": "^4.0.0",
"css-loader": "^6.7.1",
"dayjs": "^1.11.5",
"electron": "25.9.4",
"electron": "27.1.0",
"electron-builder": "^24.6.3",
"encoding": "^0.1.13",
"esbuild-loader": "^3.0.1",
Expand Down
14 changes: 7 additions & 7 deletions app/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions app/src/boot/onGetConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import {showMessage} from "../dialog/message";
import {replaceLocalPath} from "../editor/rename";
import {setTabPosition} from "../window/setHeader";
import {initBar} from "../layout/topBar";
import {setProxy} from "../config/util/about";
import {openChangelog} from "./openChangelog";
import {getIdFromSYProtocol, isSYProtocol} from "../util/pathName";
import {App} from "../index";
Expand Down Expand Up @@ -135,7 +134,6 @@ export const onGetConfig = (isStart: boolean, app: App) => {
}
});
initBar(app);
setProxy();
initStatus();
initWindow(app);
appearance.onSetappearance(window.siyuan.config.appearance);
Expand Down
25 changes: 22 additions & 3 deletions app/src/config/util/about.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,28 @@ import {Constants} from "../../constants";

export const setProxy = () => {
/// #if !BROWSER
ipcRenderer.send(Constants.SIYUAN_CMD, {
cmd: "setProxy",
proxyURL: `${window.siyuan.config.system.networkProxy.scheme}://${window.siyuan.config.system.networkProxy.host}:${window.siyuan.config.system.networkProxy.port}`
return new Promise((resolve, reject) => {
ipcRenderer.once(Constants.SIYUAN_PROXY_REPLY, (event, data: {
state: "fulfilled" | "rejected",
proxy: {mode: "system"} | {proxyRules: string},
error?: any,
}) => {
switch (data.state) {
case "fulfilled":
resolve(data.proxy);
break;
case "rejected":
reject(data.error);
break;
default:
reject(new Error(`Unknown state: ${data.state}`));
break;
}
});
ipcRenderer.send(Constants.SIYUAN_CMD, {
cmd: "setProxy",
proxyURL: `${window.siyuan.config.system.networkProxy.scheme}://${window.siyuan.config.system.networkProxy.host}:${window.siyuan.config.system.networkProxy.port}`
});
});
/// #endif
};
Expand Down
2 changes: 2 additions & 0 deletions app/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ export abstract class Constants {
public static readonly SIYUAN_GET: string = "siyuan-get";
public static readonly SIYUAN_EVENT: string = "siyuan-event";

public static readonly SIYUAN_PROXY_REPLY: string = "siyuan-proxy-reply";

public static readonly SIYUAN_CONFIG_TRAY: string = "siyuan-config-tray";
public static readonly SIYUAN_QUIT: string = "siyuan-quit";
public static readonly SIYUAN_HOTKEY: string = "siyuan-hotkey";
Expand Down
20 changes: 13 additions & 7 deletions app/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {Model} from "./layout/Model";
import {onGetConfig} from "./boot/onGetConfig";
import {initBlockPopover} from "./block/popover";
import {account} from "./config/account";
import {setProxy} from "./config/util/about";
import {addScript, addScriptSync} from "./protyle/util/addScript";
import {genUUID} from "./util/genID";
import {fetchGet, fetchPost} from "./util/fetch";
Expand Down Expand Up @@ -33,11 +34,6 @@ export class App {
public appId: string;

constructor() {
/// #if BROWSER
registerServiceWorker(`${Constants.SERVICE_WORKER_PATH}?v=${Constants.SIYUAN_VERSION}`);
/// #endif
addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");
addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");
addBaseURL();

this.appId = Constants.SIYUAN_APPID;
Expand Down Expand Up @@ -161,6 +157,18 @@ export class App {
data: response.data.conf.uiLayout.bottom
};
}

await setProxy();

/// #if BROWSER
await registerServiceWorker(`${Constants.SERVICE_WORKER_PATH}?v=${Constants.SIYUAN_VERSION}`);
/// #endif
addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");
addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");

setNoteBook();
initBlockPopover(this);

await loadPlugins(this);
getLocalStorage(() => {
fetchGet(`/appearance/langs/${window.siyuan.config.appearance.lang}.json?v=${Constants.SIYUAN_VERSION}`, (lauguages) => {
Expand All @@ -177,8 +185,6 @@ export class App {
});
});
});
setNoteBook();
initBlockPopover(this);
}
}

Expand Down
15 changes: 10 additions & 5 deletions app/src/mobile/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,12 +32,8 @@ class App {
public appId: string;

constructor() {
if (!window.webkit?.messageHandlers && !window.JSAndroid) {
registerServiceWorker(`${Constants.SERVICE_WORKER_PATH}?v=${Constants.SIYUAN_VERSION}`);
}
addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");
addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");
addBaseURL();

this.appId = Constants.SIYUAN_APPID;
window.siyuan = {
zIndex: 10,
Expand All @@ -60,6 +56,7 @@ class App {
}
})
};

// 不能使用 touchstart,否则会被 event.stopImmediatePropagation() 阻塞
window.addEventListener("click", (event: MouseEvent & { target: HTMLElement }) => {
if (!window.siyuan.menus.menu.element.contains(event.target) && !hasClosestByAttribute(event.target, "data-menu", "true")) {
Expand All @@ -80,9 +77,17 @@ class App {
window.addEventListener("pagehide", () => {
saveScroll(window.siyuan.mobile.editor.protyle);
}, false);

fetchPost("/api/system/getConf", {}, async (confResponse) => {
confResponse.data.conf.keymap = Constants.SIYUAN_KEYMAP;
window.siyuan.config = confResponse.data.conf;

if (!window.webkit?.messageHandlers && !window.JSAndroid) {
await registerServiceWorker(`${Constants.SERVICE_WORKER_PATH}?v=${Constants.SIYUAN_VERSION}`);
}
addScriptSync(`${Constants.PROTYLE_CDN}/js/lute/lute.min.js?v=${Constants.SIYUAN_VERSION}`, "protyleLuteScript");
addScript(`${Constants.PROTYLE_CDN}/js/protyle-html.js?v=${Constants.SIYUAN_VERSION}`, "protyleWcHtmlScript");

await loadPlugins(this);
getLocalStorage(() => {
fetchGet(`/appearance/langs/${window.siyuan.config.appearance.lang}.json?v=${Constants.SIYUAN_VERSION}`, (lauguages) => {
Expand Down
29 changes: 19 additions & 10 deletions app/src/plugin/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,29 @@ const runCode = (code: string, sourceURL: string) => {
return window.eval("(function anonymous(require, module, exports){".concat(code, "\n})\n//# sourceURL=").concat(sourceURL, "\n"));
};

export const getStyleElement = (id: string) => {
let style = document.getElementById(id);
if (!style) {
style = document.createElement("style");
style.id = id;
document.head.append(style);
}
return style;
}

export const loadPlugins = async (app: App) => {
const pluginsStyle = getStyleElement("pluginsStyle");
const response = await fetchSyncPost("/api/petal/loadPetals", {frontend: getFrontend()});
let css = "";
const css: string[] = [];
// 为加快启动速度,不进行 await
response.data.forEach((item: IPluginData) => {
loadPluginJS(app, item);
css += item.css || "" + "\n";
response.data.forEach((plugin: IPluginData) => {
loadPluginJS(app, plugin);
css.push(
`/* ${plugin.name} */`,
(plugin.css || ""),
);
});
const pluginsStyle = document.getElementById("pluginsStyle");
if (pluginsStyle) {
pluginsStyle.innerHTML = css;
} else {
document.head.insertAdjacentHTML("beforeend", `<style id="pluginsStyle">${css}</style>`);
}
pluginsStyle.innerHTML = css.join("\n");
};

const loadPluginJS = async (app: App, item: IPluginData) => {
Expand Down
29 changes: 15 additions & 14 deletions app/src/util/serviceWorker.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
// https://github.com/siyuan-note/siyuan/pull/8012
export const registerServiceWorker = (scriptURL: string, scope = "/", workerType: WorkerType = "module") => {
if (!("serviceWorker" in navigator) || typeof (navigator.serviceWorker) === "undefined" ||
!("caches" in window) || !("fetch" in window)) {
return;
export const registerServiceWorker = async (scriptURL: string, scope = "/", workerType: WorkerType = "module") => {
if (("serviceWorker" in window.navigator) && ("caches" in window) && ("fetch" in window)) {
try {
// REF https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
const registration = await window.navigator.serviceWorker.register(scriptURL, {
scope,
type: workerType,
});
await registration.update();
return true;
} catch (error) {
console.debug(`Registration failed with ${error}`);
return false;
}
}
// REF https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerRegistration
window.navigator.serviceWorker
.register(scriptURL, {
scope,
type: workerType,
}).then(registration => {
registration.update();
}).catch(e => {
console.debug(`Registration failed with ${e}`);
});
return false;
};
4 changes: 4 additions & 0 deletions scripts/win-build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ pnpm run build

cd ..

## ----------------------------------------------------------------

echo 'Cleaning Builds'

Remove-Item './app/build' -Recurse
Expand Down Expand Up @@ -39,6 +41,8 @@ go build --tags fts5 -v -o "../app/kernel/SiYuan-Kernel.exe" -ldflags "-s -w -H=

cd ..

## ----------------------------------------------------------------

echo 'Building Electron'

cd app
Expand Down

0 comments on commit cb68e91

Please sign in to comment.