main.js 12 KB

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