main.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. // Modules to control application life and create native browser window
  2. const {app, ipcMain, BrowserWindow, session} = require('electron')
  3. const path = require('path')
  4. const fs = require('fs')
  5. const request = require('request');
  6. const download = require('download');
  7. // 读取配置文件
  8. let enterURL = 'https://demos.run/debuger/index.html'
  9. let webConfig = {
  10. width: 376,
  11. height: 667,
  12. webPreferences: {
  13. webSecurity: false,
  14. contextIsolation: true,
  15. nodeIntegration: false,
  16. allowRunningInsecureContent: true, // 允许不安全内容
  17. preload: path.join(__dirname, "preload.js")
  18. },
  19. autoHideMenuBar: true
  20. // 无边框
  21. // frame: false,
  22. // 全屏
  23. // fullscreen: true
  24. }
  25. // 判断是否有特殊配置文件
  26. console.log(__dirname + "\\config.json")
  27. if (fs.existsSync("./config.json")) {
  28. let configStr = fs.readFileSync('./config.json', 'utf-8')
  29. // 特殊符号表示运行目录
  30. configStr = configStr.replaceAll('<dir>', __dirname.replaceAll('\\', '/').replace('/resources/app.asar', ''))
  31. webConfig = JSON.parse(configStr)
  32. enterURL = webConfig.enterURL
  33. }
  34. console.log(webConfig)
  35. const codeMap = {"fc":"[re]","ep":"[Af]","rj":"[M_]","sp":"[sW]","ws":"[Pj]","mb":"[^~]","ww":"[Dp]","wh":"[ZH]","ph":"[b+]","hk":"[3b]","mc":"[%)]","fm":"[$4]","nm":"[T!]","ei":"[J3]","pd":"[(A]","ef":"[%t]","xf":"[n_]","na":"[W6]","mr":"[dn]","km":"[b*]","aw":"[#*]","sj":"[~6]","ry":"[t#]","sd":"[$R]","eh":"[!!]","wp":"[TE]","fy":"[s6]","ex":"[EE]","ce":"[PS]","xr":"[~z]","cj":"[xh]","am":"[(G]","kw":"[Nr]","hj":"[p@]","ia":"[jO]","mp":"[75]","py":"[6C]","hc":"[46]","sk":"[(8]","hp":"[SB]","my":"[pq]","wk":"[Xd]","bk":"[Q^]","ak":"[)J]","cw":"[ai]","ym":"[Te]","yh":"[Cd]","xb":"[R5]","yy":"[#H]","nt":"[4)]","bc":"[#J]","fe":"[2+]","ni":"[f@]","bb":"[!k]","jc":"[$Q]","an":"[m$]","ee":"[RH]","nn":"[n$]","jr":"[5F]","pp":"[JQ]","fx":"[86]","2":"[)h]","3":"[iL]","4":"[r2]","5":"[Ys]","6":"[7p]","7":"[!5]","8":"[@A]","A":"[_W]","B":"[Kt]","C":"[m#]","D":"[A!]","E":"[M!]","F":"[xG]","G":"[k@]","H":"[_!]","J":"[rP]","K":"[z#]","M":"[r$]","N":"[rN]","P":"[t$]","Q":"[3(]","R":"[fF]","S":"[H)]","T":"[J@]","W":"[83]","X":"[t5]","Y":"[T_]","Z":"[CT]","a":"[Jt]","b":"[Ks]","c":"[yn]","d":"[2r]","e":"[#2]","f":"[yM]","h":"[)m]","i":"[mx]","j":"[YV]","k":"[$j]","m":"[Xy]","n":"[Bk]","p":"[5$]","r":"[EH]","s":"[Pw]","t":"[j(]","w":"[p7]","x":"[a+]","y":"[B2]","z":"[4n]","~":"[~C]","!":"[iw]","@":"[SK]","#":"[Pf]","$":"[de]","%":"[3t]","^":"[H_]","&":"[WA]","*":"[!A]","(":"[z*]",")":"[)n]","_":"[&k]","+":"[*F]"}
  36. function owoReplaceAll(str, s1, s2) {
  37. while (str.indexOf(s1) >= 0) {
  38. str = str.replace(s1, s2)
  39. }
  40. return str
  41. }
  42. function owoDecode(itemStr) {
  43. for (let item in codeMap) {
  44. itemStr = owoReplaceAll(itemStr, codeMap[item], item)
  45. }
  46. while (itemStr.indexOf(']') >= 0) {
  47. itemStr = owoDecode(itemStr)
  48. }
  49. return itemStr
  50. }
  51. const xxx_filter = {
  52. urls: webConfig.redirect || []
  53. }
  54. let mainWindow = null
  55. let preLoadCode = `
  56. var owoApp = 5
  57. window.owoPC = true
  58. window.electronConfig = ${JSON.stringify(webConfig)};
  59. function loadScript(url, callback) {
  60. var script = document.createElement("script")
  61. script.type = "text/javascript";
  62. if (script.readyState) { //IE
  63. script.onreadystatechange = function () {
  64. if (script.readyState == "loaded" || script.readyState == "complete") {
  65. script.onreadystatechange = null;
  66. if (callback) callback();
  67. }
  68. };
  69. } else { //Others
  70. script.onload = function () {
  71. if (callback) callback();
  72. };
  73. }
  74. script.src = url;
  75. var head = document.head || document.getElementsByTagName('head')[0];
  76. head.appendChild(script);
  77. }
  78. function loadJsCode(code){
  79. var script = document.createElement('script');
  80. script.type = 'text/javascript';
  81. //for Chrome Firefox Opera Safari
  82. script.appendChild(document.createTextNode(code));
  83. //for IE
  84. //script.text = code;
  85. document.body.appendChild(script);
  86. }
  87. function loadCSS (url) {
  88. var link = document.createElement("link");
  89. link.rel = "stylesheet";
  90. link.type = "text/css";
  91. link.href = url;
  92. document.getElementsByTagName("head")[0].appendChild(link);
  93. }
  94. loadScript('https://cunchu.site/app/main.js');
  95. `
  96. function createWindow () {
  97. // console.log(webConfig)
  98. mainWindow = new BrowserWindow(webConfig)
  99. // 代理
  100. if (webConfig.proxy) {
  101. mainWindow.webContents.session.setProxy({
  102. proxyRules: webConfig.proxy,
  103. proxyBypassRules: 'localhost',
  104. }, function () {
  105. console.log('代理设置完毕')
  106. });
  107. }
  108. // 拦截到新窗口打开请求
  109. mainWindow.webContents.setWindowOpenHandler(({ url }) => {
  110. console.log('拦截到新窗口打开请求:', url);
  111. mainWindow.loadURL(url); // 当前窗口跳转
  112. return { action: 'deny' }; // 阻止 Electron 弹出窗口
  113. });
  114. if (enterURL.startsWith('http')) {
  115. mainWindow.loadURL(enterURL)
  116. } else {
  117. console.log(path.join(__dirname, enterURL))
  118. mainWindow.loadFile(enterURL)
  119. }
  120. if (webConfig.preLoadCode) {
  121. preLoadCode += fs.readFileSync(webConfig.preLoadCode, 'utf-8')
  122. }
  123. mainWindow.webContents.on("dom-ready", function() {
  124. mainWindow.webContents.executeJavaScript(preLoadCode);
  125. });
  126. // 打开新窗口触发
  127. mainWindow.webContents.on("did-create-window", function(neWindow) {
  128. neWindow.webContents.on("dom-ready", function() {
  129. neWindow.webContents.executeJavaScript(preLoadCode);
  130. });
  131. });
  132. }
  133. function setupCSPRemoval(ses) {
  134. ses.webRequest.onHeadersReceived((details, callback) => {
  135. const responseHeaders = details.responseHeaders || {};
  136. const cspHeaders = [
  137. 'content-security-policy',
  138. 'Content-Security-Policy',
  139. 'content-security-policy-report-only',
  140. 'x-content-security-policy',
  141. 'x-webkit-csp'
  142. ];
  143. cspHeaders.forEach(header => {
  144. if (responseHeaders[header]) {
  145. console.log('Removing', header, 'from', details.url);
  146. delete responseHeaders[header];
  147. }
  148. });
  149. callback({ cancel: false, responseHeaders });
  150. });
  151. }
  152. // This method will be called when Electron has finished
  153. // initialization and is ready to create browser windows.
  154. // Some APIs can only be used after this event occurs.
  155. app.whenReady().then(() => {
  156. // 判断是否无缓存
  157. if (webConfig.noCache) {
  158. console.log('无缓存模式!')
  159. webConfig.webPreferences.partition = 'persist:Session' + Math.round(Math.random()*100000)
  160. } else {
  161. webConfig.webPreferences.partition = 'persist:owoApp'
  162. }
  163. // 去掉安全措施
  164. const partitionSession = session.fromPartition(webConfig.webPreferences.partition);
  165. setupCSPRemoval(partitionSession);
  166. createWindow()
  167. app.on('activate', function () {
  168. // On macOS it's common to re-create a window in the app when the
  169. // dock icon is clicked and there are no other windows open.
  170. if (BrowserWindow.getAllWindows().length === 0) createWindow()
  171. })
  172. })
  173. // Quit when all windows are closed, except on macOS. There, it's common
  174. // for applications and their menu bar to stay active until the user quits
  175. // explicitly with Cmd + Q.
  176. app.on('window-all-closed', function () {
  177. if (process.platform !== 'darwin') app.quit()
  178. })
  179. // In this file you can include the rest of your app's specific main process
  180. // code. You can also put them in separate files and require them here.
  181. ipcMain.on("getData", (event, message) => {
  182. // 控制台打印一下知道来了
  183. console.log(message);
  184. var options = {
  185. 'method': 'GET',
  186. 'url': owoDecode(message.url),
  187. 'headers': message.headers,
  188. strictSSL: false
  189. };
  190. request(options, function (error, response) {
  191. if (error) throw new Error(error);
  192. event.returnValue = response.body
  193. });
  194. })
  195. ipcMain.on("postData", (event, message) => {
  196. // 控制台打印一下知道来了
  197. console.log(message);
  198. var options = {
  199. 'method': 'POST',
  200. 'url': owoDecode(message.url),
  201. 'headers': message.headers,
  202. 'body': message.body,
  203. strictSSL: false
  204. };
  205. request(options, function (error, response) {
  206. if (error) throw new Error(error);
  207. event.returnValue = response.body
  208. });
  209. })
  210. ipcMain.on("setProxy", (event, message) => {
  211. var win = new BrowserWindow({width: 800, height: 1500});
  212. mainWindow.webContents.session.setProxy({
  213. proxyRules: message.url,
  214. proxyBypassRules: 'localhost',
  215. });
  216. event.returnValue = 'ok'
  217. })
  218. // 添加注入代码
  219. ipcMain.on("addPreLoadCode", (event, message) => {
  220. if (message.data) preLoadCode += message.data
  221. })
  222. // 通用保存数据
  223. let dataStor = {}
  224. ipcMain.on("setStoData", (event, message) => {
  225. dataStor[message.key] = message.value
  226. event.returnValue = '{"err":0}'
  227. })
  228. ipcMain.on("getStoData", (event, message) => {
  229. event.returnValue = dataStor[message.key]
  230. })
  231. let maxWindowOpenNum = 10
  232. let nowWindowInd = 0
  233. let childWindowList = []
  234. function randomString(n){const str = 'abcdefghijklmnopqrstuvwxyz9876543210';let tmp = '',i = 0,l = str.length;for (i = 0; i < n; i++) {tmp += str.charAt(Math.floor(Math.random() * l));}return tmp;}
  235. ipcMain.handle("openWindow", async (event, message) => {
  236. console.log(message)
  237. let nowIndex = nowWindowInd++
  238. // 判断是否达到了最大窗口数量
  239. let nowWindowNumTemp = 0
  240. for (let index = 0; index < childWindowList.length; index++) {
  241. const element = childWindowList[index];
  242. if (element) nowWindowNumTemp++
  243. }
  244. if (nowWindowNumTemp > maxWindowOpenNum) {
  245. for (let index = 0; index < childWindowList.length; index++) {
  246. const element = childWindowList[index];
  247. if (element) {
  248. childWindowList[index].close()
  249. childWindowList[index] = null
  250. }
  251. }
  252. }
  253. // 获取对应 session
  254. let partitionName = 'persist:owoAppChild'
  255. if (message.noCache) {
  256. partitionName = 'persist:Session' + Math.round(Math.random()*100000)
  257. }
  258. const customSession = session.fromPartition(partitionName);
  259. if (message.proxy) {
  260. // 设置代理(等待设置完成)
  261. await customSession.setProxy({
  262. proxyRules: message.proxy,
  263. proxyBypassRules: ['localhost', "cunchu.site", "demos.run", "proxy.com"],
  264. });
  265. }
  266. let childWindowPreferences = webConfig.webPreferences
  267. if (message.webPreferences) childWindowPreferences = message.webPreferences
  268. childWindowPreferences.partition = partitionName
  269. // 创建新窗口
  270. childWindowList[nowIndex] = new BrowserWindow({
  271. width: message.width || 800,
  272. height: message.height || 600,
  273. webPreferences: childWindowPreferences
  274. });
  275. // 判断是否静音
  276. if (message.muted) {
  277. // 设置静音
  278. childWindowList[nowIndex].webContents.setAudioMuted(true);
  279. }
  280. childWindowList[nowIndex].webContents.on("dom-ready", function() {
  281. console.log("dom-ready")
  282. childWindowList[nowIndex].webContents.executeJavaScript(preLoadCode);
  283. });
  284. childWindowList[nowIndex].on('closed', () => {
  285. childWindowList[nowIndex] = null;
  286. });
  287. // 拦截到新窗口打开请求
  288. childWindowList[nowIndex].webContents.setWindowOpenHandler(({ url }) => {
  289. console.log('拦截到新窗口打开请求:', url);
  290. childWindowList[nowIndex].loadURL(url); // 当前窗口跳转
  291. return { action: 'deny' }; // 阻止 Electron 弹出窗口
  292. });
  293. childWindowList[nowIndex].loadURL(message.url, {
  294. userAgent: message.userAgent ? message.userAgent : "Mozilla/5.0 (iPhone; CPU iPhone OS 16_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Mobile/15E148 Safari/604.1"
  295. });
  296. event.returnValue = JSON.stringify({"err":0,"key":nowIndex})
  297. })
  298. ipcMain.on("closeWindow", (event, message) => {
  299. if (message && message.key) {
  300. message.key = parseInt(message.key)
  301. setTimeout(() => {
  302. if (childWindowList[message.key]) {
  303. childWindowList[message.key].close()
  304. }
  305. setTimeout(() => {
  306. childWindowList[message.key] = null
  307. }, 0);
  308. }, message.time || 0);
  309. }
  310. event.returnValue = JSON.stringify({"err":0})
  311. })
  312. ipcMain.on("closeAllWindow", (event, message) => {
  313. for (let index = 0; index < childWindowList.length; index++) {
  314. const element = childWindowList[index];
  315. if (element && element.close) {
  316. try {
  317. element.close()
  318. } catch (error) {
  319. console.log(error)
  320. }
  321. }
  322. }
  323. setTimeout(() => {
  324. childWindowList = []
  325. }, 0);
  326. event.returnValue = JSON.stringify({"err":0})
  327. })
  328. ipcMain.on("changeProxy", (event, message) => {
  329. if (message && message.key) {
  330. message.key = parseInt(message.key)
  331. childWindowList[message.key].webContents.session.setProxy({
  332. proxyRules: "",
  333. proxyBypassRules: ['localhost', "cunchu.site", "demos.run", "proxy.com"],
  334. });
  335. } else {
  336. for (let index = 0; index < childWindowList.length; index++) {
  337. const element = childWindowList[index];
  338. if (element) {
  339. element.webContents.session.setProxy({
  340. proxyRules: "",
  341. proxyBypassRules: ['localhost', "cunchu.site", "demos.run", "proxy.com"],
  342. });
  343. }
  344. }
  345. }
  346. event.returnValue = JSON.stringify({"err":0})
  347. })
  348. ipcMain.on("readConfig", (event, message) => {
  349. if (fs.existsSync("./config.json")) {
  350. event.returnValue = JSON.parse(fs.readFileSync('./config.json', 'utf-8'))
  351. } else {
  352. event.returnValue = {}
  353. }
  354. })
  355. ipcMain.on("saveConfig", (event, message) => {
  356. fs.writeFileSync('./config.json', JSON.stringify(message))
  357. event.returnValue = {err: 0}
  358. })
  359. // 设置最大打开窗口数量
  360. ipcMain.on("setMaxWindowOpenNum", (event, message) => {
  361. if (message.value) {
  362. maxWindowOpenNum = parseInt(message.value)
  363. }
  364. })
  365. ipcMain.on("readdir", (event, directoryPath) => {
  366. fs.readdir(directoryPath, (err, files) => {
  367. if (err) {
  368. event.returnValue = {err: 1, "msg": 'Error reading directory:' + err}
  369. return;
  370. }
  371. event.returnValue = {err: 0, files}
  372. });
  373. })
  374. ipcMain.on("download", (event, message) => {
  375. download(message.url, message.path, {
  376. filename: message.filename,
  377. });
  378. event.returnValue = {err: 0}
  379. })
  380. // 窗口间通信
  381. ipcMain.on('broadcast-message', (event, message) => {
  382. // 获取发送者
  383. console.log(message)
  384. mainWindow.send('message-broadcast', message);
  385. // 广播给所有其他窗口
  386. for (const win of childWindowList) {
  387. if (win && !win.isDestroyed()) win.webContents.send('message-broadcast', message);
  388. }
  389. });