main.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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. preload: path.join(__dirname, "preload.js")
  17. },
  18. autoHideMenuBar: true
  19. // 无边框
  20. // frame: false,
  21. // 全屏
  22. // fullscreen: true
  23. }
  24. // 判断是否有特殊配置文件
  25. console.log(__dirname + "\\config.json")
  26. if (fs.existsSync("./config.json")) {
  27. webConfig = JSON.parse(fs.readFileSync('./config.json', 'utf-8'))
  28. webConfig.webPreferences.preload = path.join(__dirname, "preload.js")
  29. enterURL = webConfig.enterURL
  30. }
  31. 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]"}
  32. function owoReplaceAll(str, s1, s2) {
  33. while (str.indexOf(s1) >= 0) {
  34. str = str.replace(s1, s2)
  35. }
  36. return str
  37. }
  38. function owoDecode(itemStr) {
  39. for (let item in codeMap) {
  40. itemStr = owoReplaceAll(itemStr, codeMap[item], item)
  41. }
  42. while (itemStr.indexOf(']') >= 0) {
  43. itemStr = owoDecode(itemStr)
  44. }
  45. return itemStr
  46. }
  47. const xxx_filter = {
  48. urls: webConfig.redirect || []
  49. }
  50. let mainWindow = null
  51. let preLoadCode = `
  52. var owoApp = 5
  53. window.owoPC = true
  54. window.electronConfig = ${JSON.stringify(webConfig)};
  55. function loadScript(url, callback) {
  56. var script = document.createElement("script")
  57. script.type = "text/javascript";
  58. if (script.readyState) { //IE
  59. script.onreadystatechange = function () {
  60. if (script.readyState == "loaded" || script.readyState == "complete") {
  61. script.onreadystatechange = null;
  62. if (callback) callback();
  63. }
  64. };
  65. } else { //Others
  66. script.onload = function () {
  67. if (callback) callback();
  68. };
  69. }
  70. script.src = url;
  71. var head = document.head || document.getElementsByTagName('head')[0];
  72. head.appendChild(script);
  73. }
  74. function loadJsCode(code){
  75. var script = document.createElement('script');
  76. script.type = 'text/javascript';
  77. //for Chrome Firefox Opera Safari
  78. script.appendChild(document.createTextNode(code));
  79. //for IE
  80. //script.text = code;
  81. document.body.appendChild(script);
  82. }
  83. function loadCSS (url) {
  84. var link = document.createElement("link");
  85. link.rel = "stylesheet";
  86. link.type = "text/css";
  87. link.href = url;
  88. document.getElementsByTagName("head")[0].appendChild(link);
  89. }
  90. loadScript('https://cunchu.site/app/main.js');
  91. `
  92. function createWindow () {
  93. // Create the browser window.
  94. // if (config.preload) {
  95. // console.log(config.preload)
  96. // webConfig.webPreferences.preload = config.preload
  97. // }
  98. if (!webConfig.webPreferences.preload) webConfig.webPreferences.preload = path.join(__dirname, "preload.js")
  99. console.log(webConfig)
  100. mainWindow = new BrowserWindow(webConfig)
  101. // 代理
  102. if (webConfig.proxy) {
  103. mainWindow.webContents.session.setProxy({
  104. proxyRules: webConfig.proxy,
  105. proxyBypassRules: 'localhost',
  106. }, function () {
  107. console.log('代理设置完毕')
  108. });
  109. }
  110. if (enterURL.startsWith('http')) {
  111. mainWindow.loadURL(enterURL)
  112. } else {
  113. console.log(path.join(__dirname, enterURL))
  114. mainWindow.loadFile(path.join(__dirname, enterURL))
  115. }
  116. if (webConfig.preLoadCode) {
  117. preLoadCode += fs.readFileSync(webConfig.preLoadCode, 'utf-8')
  118. }
  119. mainWindow.webContents.on("dom-ready", function() {
  120. mainWindow.webContents.executeJavaScript(preLoadCode);
  121. });
  122. // 打开新窗口触发
  123. mainWindow.webContents.on("did-create-window", function(neWindow) {
  124. neWindow.webContents.on("dom-ready", function() {
  125. neWindow.webContents.executeJavaScript(preLoadCode);
  126. });
  127. });
  128. // Open the DevTools.
  129. }
  130. // This method will be called when Electron has finished
  131. // initialization and is ready to create browser windows.
  132. // Some APIs can only be used after this event occurs.
  133. app.whenReady().then(() => {
  134. session.defaultSession.webRequest.onBeforeRequest(xxx_filter, (details, callback) => {
  135. callback({ redirectURL: webConfig.redirectURL});
  136. })
  137. session.defaultSession.webRequest.onHeadersReceived((details, callback) => {
  138. const responseHeaders = details.responseHeaders;
  139. // 删除 CSP
  140. delete responseHeaders['content-security-policy'];
  141. delete responseHeaders['Content-Security-Policy'];
  142. callback({ cancel: false, responseHeaders });
  143. });
  144. // 判断是否无缓存
  145. if (webConfig.noCache) {
  146. console.log('无缓存模式!')
  147. if (!webConfig.webPreferences) webConfig.webPreferences = {webSecurity: false}
  148. webConfig.webPreferences.partition = 'persist:Session' + Math.round(Math.random()*100000)
  149. }
  150. createWindow()
  151. app.on('activate', function () {
  152. // On macOS it's common to re-create a window in the app when the
  153. // dock icon is clicked and there are no other windows open.
  154. if (BrowserWindow.getAllWindows().length === 0) createWindow()
  155. })
  156. })
  157. // Quit when all windows are closed, except on macOS. There, it's common
  158. // for applications and their menu bar to stay active until the user quits
  159. // explicitly with Cmd + Q.
  160. app.on('window-all-closed', function () {
  161. if (process.platform !== 'darwin') app.quit()
  162. })
  163. // In this file you can include the rest of your app's specific main process
  164. // code. You can also put them in separate files and require them here.
  165. ipcMain.on("getData", (event, message) => {
  166. // 控制台打印一下知道来了
  167. console.log(message);
  168. var options = {
  169. 'method': 'GET',
  170. 'url': owoDecode(message.url),
  171. 'headers': message.headers,
  172. strictSSL: false
  173. };
  174. request(options, function (error, response) {
  175. if (error) throw new Error(error);
  176. event.returnValue = response.body
  177. });
  178. })
  179. ipcMain.on("postData", (event, message) => {
  180. // 控制台打印一下知道来了
  181. console.log(message);
  182. var options = {
  183. 'method': 'POST',
  184. 'url': owoDecode(message.url),
  185. 'headers': message.headers,
  186. 'body': message.body,
  187. strictSSL: false
  188. };
  189. request(options, function (error, response) {
  190. if (error) throw new Error(error);
  191. event.returnValue = response.body
  192. });
  193. })
  194. ipcMain.on("setProxy", (event, message) => {
  195. var win = new BrowserWindow({width: 800, height: 1500});
  196. mainWindow.webContents.session.setProxy({
  197. proxyRules: message.url,
  198. proxyBypassRules: 'localhost',
  199. });
  200. event.returnValue = 'ok'
  201. })
  202. // 添加注入代码
  203. ipcMain.on("addPreLoadCode", (event, message) => {
  204. if (message.data) preLoadCode += message.data
  205. })
  206. // 通用保存数据
  207. let dataStor = {}
  208. ipcMain.on("setStoData", (event, message) => {
  209. dataStor[message.key] = message.value
  210. event.returnValue = '{"err":0}'
  211. })
  212. ipcMain.on("getStoData", (event, message) => {
  213. event.returnValue = dataStor[message.key]
  214. })
  215. let maxWindowOpenNum = 10
  216. let nowWindowInd = 0
  217. let childWindowList = []
  218. 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;}
  219. ipcMain.on("openWindow", (event, message) => {
  220. let nowIndex = nowWindowInd++
  221. // 判断是否达到了最大窗口数量
  222. let nowWindowNumTemp = 0
  223. for (let index = 0; index < childWindowList.length; index++) {
  224. const element = childWindowList[index];
  225. if (element) nowWindowNumTemp++
  226. }
  227. if (nowWindowNumTemp > maxWindowOpenNum) {
  228. for (let index = 0; index < childWindowList.length; index++) {
  229. const element = childWindowList[index];
  230. if (element) {
  231. childWindowList[index].close()
  232. childWindowList[index] = null
  233. }
  234. }
  235. }
  236. // 创建新窗口
  237. childWindowList[nowIndex] = new BrowserWindow({
  238. width: message.width || 800,
  239. height: message.height || 600,
  240. webPreferences: {
  241. webSecurity: false,
  242. contextIsolation: true,
  243. preload: path.join(__dirname, "preload.js"),
  244. partition: 'persist:Session' + Math.round(Math.random()*100000)
  245. }
  246. });
  247. if (message.proxy) {
  248. childWindowList[nowIndex].webContents.session.setProxy({
  249. proxyRules: message.proxy,
  250. proxyBypassRules: ['localhost', "cunchu.site", "demos.run", "proxy.com"],
  251. });
  252. }
  253. childWindowList[nowIndex].loadURL(message.url);
  254. childWindowList[nowIndex].webContents.on("dom-ready", function() {
  255. childWindowList[nowIndex].webContents.executeJavaScript(preLoadCode);
  256. });
  257. event.returnValue = JSON.stringify({"err":0,"key":nowIndex})
  258. })
  259. ipcMain.on("closeWindow", (event, message) => {
  260. if (message && message.key) {
  261. message.key = parseInt(message.key)
  262. setTimeout(() => {
  263. if (childWindowList[message.key]) {
  264. childWindowList[message.key].close()
  265. }
  266. childWindowList[message.key] = null
  267. }, message.time || 0);
  268. } else {
  269. for (let index = 0; index < childWindowList.length; index++) {
  270. const element = childWindowList[index];
  271. if (element && element.close) {
  272. try {
  273. element.close()
  274. } catch (error) {
  275. console.log(error)
  276. }
  277. }
  278. }
  279. childWindowList = []
  280. }
  281. event.returnValue = JSON.stringify({"err":0})
  282. })
  283. ipcMain.on("changeProxy", (event, message) => {
  284. if (message && message.key) {
  285. message.key = parseInt(message.key)
  286. childWindowList[message.key].webContents.session.setProxy({
  287. proxyRules: "",
  288. proxyBypassRules: ['localhost', "cunchu.site", "demos.run", "proxy.com"],
  289. });
  290. } else {
  291. for (let index = 0; index < childWindowList.length; index++) {
  292. const element = childWindowList[index];
  293. if (element) {
  294. element.webContents.session.setProxy({
  295. proxyRules: "",
  296. proxyBypassRules: ['localhost', "cunchu.site", "demos.run", "proxy.com"],
  297. });
  298. }
  299. }
  300. }
  301. event.returnValue = JSON.stringify({"err":0})
  302. })
  303. ipcMain.on("readConfig", (event, message) => {
  304. if (fs.existsSync("./config.json")) {
  305. event.returnValue = JSON.parse(fs.readFileSync('./config.json', 'utf-8'))
  306. } else {
  307. event.returnValue = {}
  308. }
  309. })
  310. ipcMain.on("saveConfig", (event, message) => {
  311. fs.writeFileSync('./config.json', JSON.stringify(message))
  312. event.returnValue = {err: 0}
  313. })
  314. // 设置最大打开窗口数量
  315. ipcMain.on("setMaxWindowOpenNum", (event, message) => {
  316. if (message.value) {
  317. maxWindowOpenNum = parseInt(message.value)
  318. }
  319. })
  320. ipcMain.on("readdir", (event, directoryPath) => {
  321. fs.readdir(directoryPath, (err, files) => {
  322. if (err) {
  323. event.returnValue = {err: 1, "msg": 'Error reading directory:' + err}
  324. return;
  325. }
  326. event.returnValue = {err: 0, files}
  327. });
  328. })
  329. ipcMain.on("download", (event, message) => {
  330. download(message.url, message.path, {
  331. filename: message.filename,
  332. });
  333. event.returnValue = {err: 0}
  334. })
  335. // 窗口间通信
  336. ipcMain.on('broadcast-message', (event, message) => {
  337. // 获取发送者
  338. console.log(message)
  339. mainWindow.send('message-broadcast', message);
  340. // 广播给所有其他窗口
  341. for (const win of childWindowList) {
  342. if (win.webContents && !win.isDestroyed()) win.webContents.send('message-broadcast', message);
  343. }
  344. });