| 123456789101112131415161718192021222324252627282930313233343536373839404142 |
- "use strict";const{app:u,BrowserWindow:q,ipcMain:c,shell:D,session:C,Menu:E,Tray:$,nativeImage:S,webContents:p}=require("electron"),{join:g}=require("path");require("fs");let e=null,d=null,v=!1;const k=process.env.VITE_DEV_SERVER_URL;function I(){return k?g(__dirname,"../public/icons/icon-256.png"):g(__dirname,"../dist/icons/icon-256.png")}function R(){return k?g(__dirname,"../public/icons/tray-icon.png"):g(__dirname,"../dist/icons/tray-icon.png")}function z(){const i=R();return S.createFromPath(i)}function A(){const i=z();d=new $(i);const t=E.buildFromTemplate([{label:"显示主窗口",click:()=>{e&&(e.show(),e.focus())}},{label:"最小化到托盘",click:()=>{e==null||e.hide()}},{type:"separator"},{label:"退出",click:()=>{v=!0,u.quit()}}]);d.setToolTip("多平台媒体管理系统"),d.setContextMenu(t),d.on("click",()=>{e&&(e.isVisible()||e.show(),e.focus())}),d.on("double-click",()=>{e&&(e.show(),e.focus())})}function P(){E.setApplicationMenu(null);const i=I();e=new q({width:1400,height:900,minWidth:1200,minHeight:700,icon:i,webPreferences:{preload:g(__dirname,"preload.js"),nodeIntegration:!1,contextIsolation:!0,webviewTag:!0},frame:!1,transparent:!1,backgroundColor:"#f0f2f5",show:!1}),e.once("ready-to-show",()=>{e==null||e.show(),V()}),k?(e.loadURL(k),e.webContents.openDevTools()):e.loadFile(g(__dirname,"../dist/index.html")),e.webContents.setWindowOpenHandler(({url:t})=>(D.openExternal(t),{action:"deny"})),e.on("close",t=>{v||(t.preventDefault(),e==null||e.hide(),d&&u.isPackaged)}),e.on("closed",()=>{e=null})}const H=u.requestSingleInstanceLock();H?(u.on("second-instance",()=>{e&&(e.show(),e.isMinimized()&&e.restore(),e.focus())}),u.whenReady().then(()=>{A(),P(),U(),u.on("activate",()=>{q.getAllWindows().length===0?P():e&&e.show()})})):u.quit();function U(){u.on("web-contents-created",(i,t)=>{t.getType()==="webview"&&(t.setUserAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"),t.on("will-navigate",(r,n)=>{T(n)||(console.log("[WebView] 阻止导航到自定义协议:",n),r.preventDefault())}),t.setWindowOpenHandler(({url:r})=>T(r)?(console.log("[WebView] 拦截新窗口,在当前页面打开:",r),t.loadURL(r),{action:"deny"}):(console.log("[WebView] 阻止打开自定义协议窗口:",r),{action:"deny"})),t.session.setPermissionRequestHandler((r,n,s)=>{s(!0)}),t.session.webRequest.onBeforeSendHeaders((r,n)=>{delete r.requestHeaders["X-DevTools-Emulate-Network-Conditions-Client-Id"],!r.requestHeaders.Origin&&r.requestHeaders.origin,n({requestHeaders:r.requestHeaders})}))})}function T(i){if(!i)return!1;const t=i.toLowerCase();return t.startsWith("http://")||t.startsWith("https://")||t.startsWith("about:")||t.startsWith("data:")}u.on("window-all-closed",()=>{});u.on("before-quit",()=>{v=!0});u.on("quit",()=>{d&&(d.destroy(),d=null)});c.handle("get-app-version",()=>u.getVersion());c.handle("get-platform",()=>process.platform);c.on("window-minimize",()=>{e==null||e.minimize()});c.on("window-maximize",()=>{e!=null&&e.isMaximized()?e.unmaximize():e==null||e.maximize()});c.on("window-close",()=>{e==null||e.hide()});c.on("app-quit",()=>{v=!0,u.quit()});c.handle("window-is-maximized",()=>(e==null?void 0:e.isMaximized())||!1);function V(){e==null||e.on("maximize",()=>{e==null||e.webContents.send("window-maximized",!0)}),e==null||e.on("unmaximize",()=>{e==null||e.webContents.send("window-maximized",!1)})}c.handle("get-webview-cookies",async(i,t,r)=>{try{return await C.fromPartition(t).cookies.get({url:r})}catch(n){return console.error("获取 cookies 失败:",n),[]}});c.handle("clear-webview-cookies",async(i,t)=>{try{return await C.fromPartition(t).clearStorageData({storages:["cookies"]}),!0}catch(r){return console.error("清除 cookies 失败:",r),!1}});c.handle("set-webview-cookies",async(i,t,r)=>{try{console.log(`[Main] 设置 webview cookies, partition=${t}, count=${r.length}`);const n=C.fromPartition(t);let s=0;for(const o of r)try{const l={url:o.url,name:o.name,value:o.value,domain:o.domain,path:o.path||"/"};o.expirationDate&&(l.expirationDate=o.expirationDate),o.httpOnly!==void 0&&(l.httpOnly=o.httpOnly),o.secure!==void 0&&(l.secure=o.secure),o.sameSite&&(l.sameSite=o.sameSite),await n.cookies.set(l),s++,(o.name==="BDUSS"||o.name==="STOKEN"||o.name==="sessionid")&&console.log(`[Main] 成功设置关键 Cookie: ${o.name}, domain: ${o.domain}`)}catch(l){console.error(`[Main] 设置 cookie 失败 (${o.name}):`,l)}console.log(`[Main] 成功设置 ${s}/${r.length} 个 cookies`);try{const o=await n.cookies.get({domain:".baidu.com"});console.log(`[Main] 验证:当前 session 中有 ${o.length} 个百度 Cookie`);const l=o.slice(0,5).map(m=>m.name).join(", ");console.log(`[Main] 关键 Cookie 名称: ${l}`)}catch(o){console.error("[Main] 验证 Cookie 失败:",o)}return!0}catch(n){return console.error("[Main] 设置 cookies 失败:",n),!1}});c.handle("capture-webview-page",async(i,t)=>{try{const r=p.fromId(t);if(!r)return console.error("找不到 webContents:",t),null;const n=await r.capturePage();return!n||n.isEmpty()?(console.warn("截图为空"),null):n.toJPEG(80).toString("base64")}catch(r){return console.error("截图失败:",r),null}});c.handle("webview-send-mouse-click",async(i,t,r,n)=>{try{const s=p.fromId(t);return s?(s.sendInputEvent({type:"mouseMove",x:Math.round(r),y:Math.round(n)}),await new Promise(o=>setTimeout(o,50)),s.sendInputEvent({type:"mouseDown",x:Math.round(r),y:Math.round(n),button:"left",clickCount:1}),await new Promise(o=>setTimeout(o,50)),s.sendInputEvent({type:"mouseUp",x:Math.round(r),y:Math.round(n),button:"left",clickCount:1}),console.log(`[webview-send-mouse-click] Clicked at (${r}, ${n})`),!0):(console.error("找不到 webContents:",t),!1)}catch(s){return console.error("发送点击事件失败:",s),!1}});c.handle("webview-send-text-input",async(i,t,r)=>{try{const n=p.fromId(t);if(!n)return console.error("找不到 webContents:",t),!1;for(const s of r)n.sendInputEvent({type:"char",keyCode:s}),await new Promise(o=>setTimeout(o,30));return console.log(`[webview-send-text-input] Typed: ${r}`),!0}catch(n){return console.error("发送输入事件失败:",n),!1}});c.handle("webview-get-element-position",async(i,t,r)=>{try{const n=p.fromId(t);return n?await n.executeJavaScript(`
- (function() {
- const el = document.querySelector('${r.replace(/'/g,"\\'")}');
- if (!el) return null;
- const rect = el.getBoundingClientRect();
- return {
- x: rect.left + rect.width / 2,
- y: rect.top + rect.height / 2,
- width: rect.width,
- height: rect.height
- };
- })()
- `):(console.error("找不到 webContents:",t),null)}catch(n){return console.error("获取元素位置失败:",n),null}});c.handle("webview-click-by-text",async(i,t,r)=>{try{const n=p.fromId(t);if(!n)return console.error("找不到 webContents:",t),!1;const s=await n.executeJavaScript(`
- (function() {
- const searchText = '${r.replace(/'/g,"\\'")}';
-
- // 查找可点击元素
- const clickables = document.querySelectorAll('a, button, [role="button"], [onclick], input[type="submit"], input[type="button"]');
- for (const el of clickables) {
- if (el.textContent?.includes(searchText) || el.getAttribute('aria-label')?.includes(searchText) || el.getAttribute('title')?.includes(searchText)) {
- const rect = el.getBoundingClientRect();
- if (rect.width > 0 && rect.height > 0) {
- return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
- }
- }
- }
-
- // 查找所有包含文本的元素
- const allElements = document.querySelectorAll('*');
- for (const el of allElements) {
- const text = el.innerText?.trim();
- if (text && text.length < 100 && text.includes(searchText)) {
- const rect = el.getBoundingClientRect();
- if (rect.width > 0 && rect.height > 0 && rect.width < 500) {
- return { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 };
- }
- }
- }
-
- return null;
- })()
- `);return s?(n.sendInputEvent({type:"mouseMove",x:Math.round(s.x),y:Math.round(s.y)}),await new Promise(o=>setTimeout(o,50)),n.sendInputEvent({type:"mouseDown",x:Math.round(s.x),y:Math.round(s.y),button:"left",clickCount:1}),await new Promise(o=>setTimeout(o,50)),n.sendInputEvent({type:"mouseUp",x:Math.round(s.x),y:Math.round(s.y),button:"left",clickCount:1}),console.log(`[webview-click-by-text] Clicked "${r}" at (${s.x}, ${s.y})`),!0):(console.warn(`[webview-click-by-text] 未找到包含 "${r}" 的元素`),!1)}catch(n){return console.error("通过文本点击失败:",n),!1}});const y=new Map;c.handle("enable-network-intercept",async(i,t,r)=>{var n;try{const s=p.fromId(t);if(!s)return console.error("[CDP] 找不到 webContents:",t),!1;if(y.has(t))try{s.debugger.detach()}catch{}y.set(t,{patterns:r,pendingRequests:new Map});try{s.debugger.attach("1.3")}catch(o){if(!((n=o.message)!=null&&n.includes("Already attached")))throw o}return await s.debugger.sendCommand("Network.enable"),s.debugger.on("message",async(o,l,m)=>{const w=y.get(t);if(w){if(l==="Network.responseReceived"){const{requestId:f,response:a}=m;if(!f||!(a!=null&&a.url))return;a.url.includes("baijiahao.baidu.com")&&(a.url.includes("/pcui/")||a.url.includes("/article"))&&console.log(`[CDP DEBUG] 百家号 API: ${a.url}`);for(const h of w.patterns)if(a.url.includes(h.match)){w.pendingRequests.set(f,{url:a.url,timestamp:Date.now()}),console.log(`[CDP] 匹配到 API: ${h.key} - ${a.url}`);break}}if(l==="Network.loadingFinished"){const{requestId:f}=m;if(!f)return;const a=w.pendingRequests.get(f);if(!a)return;w.pendingRequests.delete(f);try{const h=await s.debugger.sendCommand("Network.getResponseBody",{requestId:f});let x=h.body;h.base64Encoded&&(x=Buffer.from(x,"base64").toString("utf8"));const M=JSON.parse(x);let b="";for(const _ of w.patterns)if(a.url.includes(_.match)){b=_.key;break}b&&(console.log(`[CDP] 获取到响应: ${b}`,JSON.stringify(M).substring(0,200)),e==null||e.webContents.send("network-intercept-data",{webContentsId:t,key:b,url:a.url,data:M}))}catch(h){console.warn("[CDP] 获取响应体失败:",h)}}}}),console.log(`[CDP] 已启用网络拦截,webContentsId: ${t}, patterns:`,r.map(o=>o.key)),!0}catch(s){return console.error("[CDP] 启用网络拦截失败:",s),!1}});c.handle("disable-network-intercept",async(i,t)=>{try{const r=p.fromId(t);if(r)try{r.debugger.detach()}catch{}return y.delete(t),console.log(`[CDP] 已禁用网络拦截,webContentsId: ${t}`),!0}catch(r){return console.error("[CDP] 禁用网络拦截失败:",r),!1}});c.handle("update-network-patterns",async(i,t,r)=>{const n=y.get(t);return n?(n.patterns=r,console.log(`[CDP] 已更新 patterns,webContentsId: ${t}`),!0):!1});
|