main.js 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. // Modules to control application life and create native browser window
  2. const {app, BrowserWindow, dialog, ipcMain, screen, session} = require('electron');
  3. app.commandLine.appendSwitch("--disable-http-cache");
  4. const {Builder, By, Key, until, Select, StaleElementReferenceException} = require("selenium-webdriver");
  5. const chrome = require('selenium-webdriver/chrome');
  6. const {ServiceBuilder} = require('selenium-webdriver/chrome');
  7. const {rootCertificates} = require('tls');
  8. const {exit} = require('process');
  9. const path = require('path');
  10. const fs = require('fs');
  11. const {exec, spawn} = require('child_process');
  12. const iconPath = path.join(__dirname, 'favicon.ico');
  13. const task_server = require(path.join(__dirname, 'server.js'));
  14. const util = require('util');
  15. let config = fs.readFileSync(path.join(task_server.getDir(), `config.json`), 'utf8');
  16. config = JSON.parse(config);
  17. if (config.debug) {
  18. let logPath = 'info.log'
  19. let logFile = fs.createWriteStream(logPath, {flags: 'a'})
  20. console.log = function () {
  21. logFile.write(util.format.apply(null, arguments) + '\n')
  22. process.stdout.write(util.format.apply(null, arguments) + '\n')
  23. }
  24. console.error = function () {
  25. logFile.write(util.format.apply(null, arguments) + '\n')
  26. process.stderr.write(util.format.apply(null, arguments) + '\n')
  27. }
  28. }
  29. let allWindowSockets = [];
  30. let allWindowScoketNames = [];
  31. task_server.start(config.webserver_port); //start local server
  32. let server_address = `${config.webserver_address}:${config.webserver_port}`;
  33. const websocket_port = 8084; //目前只支持8084端口,写死,因为扩展里面写死了
  34. console.log("server_address: " + server_address);
  35. let driverPath = "";
  36. let chromeBinaryPath = "";
  37. let execute_path = "";
  38. console.log(process.arch);
  39. exec(`wmic os get Caption`, function (error, stdout, stderr) {
  40. if (error) {
  41. console.error(`执行的错误: ${error}`);
  42. return;
  43. }
  44. if (stdout.includes('Windows 7')) {
  45. console.log('Windows 7');
  46. let sys_arch = config.sys_arch;
  47. if (sys_arch === 'x64') {
  48. dialog.showMessageBoxSync({
  49. type: 'error',
  50. title: 'Error',
  51. message: 'Windows 7系统请下载使用x32版本的软件,不论Win 7系统为x64还是x32版本。\nFor Windows 7, please download and use the x32 version of the software, regardless of whether the Win 7 system is x64 or x32 version.',
  52. });
  53. }
  54. } else {
  55. console.log('Not Windows 7');
  56. }
  57. });
  58. if (process.platform === 'win32' && process.arch === 'ia32') {
  59. driverPath = path.join(__dirname, "chrome_win32/chromedriver_win32.exe");
  60. chromeBinaryPath = path.join(__dirname, "chrome_win32/chrome.exe");
  61. execute_path = path.join(__dirname, "chrome_win32/execute.bat");
  62. } else if (process.platform === 'win32' && process.arch === 'x64') {
  63. driverPath = path.join(__dirname, "chrome_win64/chromedriver_win64.exe");
  64. chromeBinaryPath = path.join(__dirname, "chrome_win64/chrome.exe");
  65. execute_path = path.join(__dirname, "chrome_win64/execute.bat");
  66. } else if (process.platform === 'darwin') {
  67. driverPath = path.join(__dirname, "chromedriver_mac64");
  68. chromeBinaryPath = path.join(__dirname, "chrome_mac64.app/Contents/MacOS/Google Chrome");
  69. execute_path = path.join(__dirname, "");
  70. } else if (process.platform === 'linux') {
  71. driverPath = path.join(__dirname, "chrome_linux64/chromedriver_linux64");
  72. chromeBinaryPath = path.join(__dirname, "chrome_linux64/chrome");
  73. execute_path = path.join(__dirname, "chrome_linux64/execute.sh");
  74. }
  75. console.log(driverPath, chromeBinaryPath, execute_path);
  76. let language = "en";
  77. let driver = null;
  78. let mainWindow = null;
  79. let flowchart_window = null;
  80. let current_handle = null;
  81. let old_handles = [];
  82. let handle_pairs = {};
  83. let socket_window = null;
  84. let socket_start = null;
  85. let socket_flowchart = null;
  86. let invoke_window = null;
  87. // var ffi = require('ffi-napi');
  88. // var libm = ffi.Library('libm', {
  89. // 'ceil': [ 'double', [ 'double' ] ]
  90. // });
  91. // libm.ceil(1.5); // 2
  92. // const {user32FindWindowEx,
  93. // winspoolGetDefaultPrinter,} = require('win32-api/fun');
  94. // async function testt(){
  95. // // 获取当前电脑当前用户默认打印机名
  96. // const printerName = await winspoolGetDefaultPrinter()
  97. // console.log(printerName);
  98. // }
  99. // testt();
  100. function createWindow() {
  101. // Create the browser window.
  102. mainWindow = new BrowserWindow({
  103. width: 600,
  104. height: 800,
  105. webPreferences: {
  106. preload: path.join(__dirname, 'src/js/preload.js')
  107. },
  108. icon: iconPath,
  109. // frame: false, //取消window自带的关闭最小化等
  110. resizable: false //禁止改变主窗口尺寸
  111. })
  112. // and load the index.html of the app.
  113. // mainWindow.loadFile('src/index.html');
  114. mainWindow.loadURL(server_address + '/index.html?user_data_folder=' + config.user_data_folder + "&copyright=" + config.copyright, {extraHeaders: 'pragma: no-cache\n'});
  115. // 隐藏菜单栏
  116. const {Menu} = require('electron');
  117. Menu.setApplicationMenu(null);
  118. mainWindow.on('close', function (e) {
  119. if (process.platform !== 'darwin') {
  120. app.quit();
  121. }
  122. });
  123. // mainWindow.webContents.openDevTools();
  124. // Open the DevTools.
  125. // mainWindow.webContents.openDevTools()
  126. }
  127. async function findElementRecursive(driver, by, value, frames) {
  128. for (const frame of frames) {
  129. try {
  130. // Try to switch to the frame
  131. try {
  132. await driver.switchTo().frame(frame);
  133. } catch (error) {
  134. if (error.name.indexOf('StaleElement') >= 0) {
  135. // If the frame is stale, switch to the parent frame and then retry switching to the frame
  136. await driver.switchTo().parentFrame();
  137. await driver.switchTo().frame(frame);
  138. } else {
  139. // If it is another exception rethrow it
  140. throw error;
  141. }
  142. }
  143. let element;
  144. try {
  145. // Attempt to find the element in this frame
  146. element = await driver.findElement(by(value));
  147. return element;
  148. } catch (error) {
  149. if (error.name.indexOf('NoSuchElement') >= 0) {
  150. // The element was not found in this frame, recurse into nested iframes
  151. const nestedFrames = await driver.findElements(By.tagName("iframe"));
  152. if (nestedFrames.length > 0) {
  153. element = await findElementRecursive(driver, by, value, nestedFrames);
  154. if (element) {
  155. return element;
  156. }
  157. }
  158. } else {
  159. // If it is another exception, log it
  160. console.error(`Exception while processing frame: ${error}`);
  161. }
  162. }
  163. } catch (error) {
  164. console.error(`Exception while processing frame: ${error}`);
  165. }
  166. }
  167. throw new Error(`Element ${value} not found in any frame or iframe`);
  168. }
  169. async function findElement(driver, by, value, iframe = false) {
  170. // Switch back to the main document
  171. await driver.switchTo().defaultContent();
  172. if (iframe) {
  173. const frames = await driver.findElements(By.tagName("iframe"));
  174. if (frames.length === 0) {
  175. throw new Error(`No iframes found in the current page while searching for ${value}`);
  176. }
  177. const element = await findElementRecursive(driver, by, value, frames);
  178. return element;
  179. } else {
  180. // Find element in the main document as normal
  181. let element = await driver.findElement(by(value));
  182. return element;
  183. }
  184. }
  185. async function findElementAcrossAllWindows(msg, notifyBrowser = true, scrollIntoView = true) {
  186. let handles = await driver.getAllWindowHandles();
  187. // console.log("handles", handles);
  188. let content_handle = current_handle;
  189. let id = -1;
  190. try {
  191. id = msg.message.id;
  192. } catch {
  193. id = msg.id;
  194. }
  195. if (id == -1) { //如果是-1,从当前窗口开始搜索
  196. content_handle = current_handle;
  197. } else {
  198. content_handle = handle_pairs[id];
  199. }
  200. // console.log(msg.message.id, content_handle);
  201. let order = [...handles.filter(handle => handle != current_handle && handle != content_handle), current_handle, content_handle]; //搜索顺序
  202. let len = order.length;
  203. let element = null;
  204. let iframe = false;
  205. try {
  206. iframe = msg.message.iframe;
  207. } catch {
  208. iframe = msg.iframe;
  209. }
  210. // if (iframe) {
  211. // notify_browser("在IFrame中执行操作可能需要较长时间,请耐心等待。", "Executing operations in IFrame may take a long time, please wait patiently.", "info");
  212. // }
  213. let xpath = "";
  214. try {
  215. xpath = msg.message.xpath;
  216. } catch {
  217. //如果msg.pathList存在,说明是循环中的元素
  218. if (msg.pathList != undefined && msg.pathList != null && msg.pathList != "") {
  219. xpath = msg.pathList[0].trim();
  220. } else {
  221. xpath = msg.xpath;
  222. }
  223. }
  224. if (xpath.indexOf("Field(") >= 0 || xpath.indexOf("eval(") >= 0) {
  225. //两秒后通知浏览器
  226. await new Promise(resolve => setTimeout(resolve, 2000));
  227. notify_browser("检测到XPath中包含Field(\"\")或eval(\"\"),试运行时无法正常定位到包含此两项表达式的元素,请在任务正式运行阶段测试是否有效。", "Field(\"\") or eval(\"\") is detected in xpath, and the element containing these two expressions cannot be located normally during trial operation. Please test whether it is valid in the formal call stage.", "warning");
  228. return null;
  229. }
  230. let notify = false;
  231. while (true) {
  232. // console.log("handles");
  233. try {
  234. let h = order[len - 1];
  235. console.log("current_handle", current_handle);
  236. if (h != null && handles.includes(h)) {
  237. await driver.switchTo().window(h);
  238. current_handle = h;
  239. console.log("switch to handle: ", h);
  240. }
  241. element = await findElement(driver, By.xpath, xpath, iframe);
  242. break;
  243. } catch (error) {
  244. console.log("len", len);
  245. len = len - 1;
  246. if (!notify) {
  247. notify = true;
  248. // notify_browser("正在尝试在其他窗口中查找元素,请耐心等待。", "Trying to find elements in other windows, please wait patiently.", "info");
  249. }
  250. if (len == 0) {
  251. break;
  252. }
  253. }
  254. }
  255. if (element == null && notifyBrowser) {
  256. notify_browser("无法找到元素,请检查XPath是否正确:" + xpath, "Cannot find the element, please check if the XPath is correct: " + xpath, "warning");
  257. }
  258. if (element != null && scrollIntoView) {
  259. // 浏览器切换到元素位置稍微靠上的位置
  260. try {
  261. // let script = `arguments[0].scrollIntoView(true);`;
  262. let script = `arguments[0].scrollIntoView({block: "center", inline: "center"});`;
  263. await driver.executeScript(script, element);
  264. } catch (e) {
  265. console.log("Cannot scrollIntoView");
  266. }
  267. }
  268. return element;
  269. }
  270. async function beginInvoke(msg, ws) {
  271. if (msg.type == 1) {
  272. if (msg.message.id != -1) {
  273. let url = "";
  274. if (language == "zh") {
  275. url = server_address + `/taskGrid/FlowChart_CN.html?id=${msg.message.id}&wsport=${websocket_port}&backEndAddressServiceWrapper=` + server_address;
  276. } else if (language == "en") {
  277. url = server_address + `/taskGrid/FlowChart.html?id=${msg.message.id}&wsport=${websocket_port}&backEndAddressServiceWrapper=` + server_address;
  278. }
  279. console.log(url);
  280. flowchart_window.loadURL(url, {extraHeaders: 'pragma: no-cache\n'});
  281. }
  282. mainWindow.hide();
  283. // Prints the currently focused window bounds.
  284. // This method has to be called on macOS before changing the window's bounds, otherwise it will throw an error.
  285. // It will prompt an accessibility permission request dialog, if needed.
  286. if (process.platform != "linux" && process.platform != "darwin") {
  287. // 非用户信息模式下,设置窗口位置
  288. if (config.user_data_folder == null || config.user_data_folder == undefined || config.user_data_folder == "") {
  289. const {windowManager} = require("node-window-manager");
  290. const window = windowManager.getActiveWindow();
  291. console.log(window);
  292. windowManager.requestAccessibility();
  293. // Sets the active window's bounds.
  294. let size = screen.getPrimaryDisplay().workAreaSize
  295. let width = parseInt(size.width)
  296. let height = parseInt(size.height * 0.6)
  297. window.setBounds({x: 0, y: size.height * 0.4, height: height, width: width});
  298. }
  299. }
  300. flowchart_window.show();
  301. // flowchart_window.openDevTools();
  302. } else if (msg.type == 2) {
  303. // 键盘输入事件
  304. // const robot = require("@jitsi/robotjs");
  305. let keyInfo = msg.message.keyboardStr;
  306. let enter = false;
  307. if (/<enter>/i.test(keyInfo)) {
  308. keyInfo = keyInfo.replace(/<enter>/gi, '');
  309. enter = true;
  310. }
  311. let element = await findElementAcrossAllWindows(msg, notifyBrowser = true, scrollIntoView = false);
  312. await element.sendKeys(Key.HOME, Key.chord(Key.SHIFT, Key.END), keyInfo);
  313. if (enter) {
  314. await element.sendKeys(Key.ENTER);
  315. }
  316. } else if (msg.type == 3) {
  317. try {
  318. if (msg.from == 0) {
  319. socket_flowchart.send(msg.message.pipe); //直接把消息转接
  320. let message = JSON.parse(msg.message.pipe);
  321. let type = message.type;
  322. console.log("FROM Browser: ", message);
  323. if (type.indexOf("Click") >= 0 || type.indexOf("Move") >= 0) {
  324. let element = await findElementAcrossAllWindows(message, notifyBrowser = true, scrollIntoView = false);
  325. if (type.indexOf("Click") >= 0) {
  326. await click_element(element, type);
  327. } else if (type.indexOf("Move") >= 0) {
  328. await driver.actions().move({origin: element}).perform();
  329. }
  330. }
  331. } else {
  332. send_message_to_browser(msg.message.pipe);
  333. console.log("FROM Flowchart: ", JSON.parse(msg.message.pipe));
  334. }
  335. } catch (e) {
  336. console.log(e);
  337. }
  338. } else if (msg.type == 4) { //标记元素和试运行功能
  339. let node = JSON.parse(msg.message.node);
  340. let type = msg.message.type;
  341. if (type == 0) { //标记元素
  342. let option = node.option;
  343. let parameters = node.parameters;
  344. //下面是让浏览器自动滚动到元素位置
  345. if (option == 2 || option == 4 || option == 6 || option == 7) {
  346. let xpath = parameters.xpath;
  347. let parent_node = JSON.parse(msg.message.parentNode);
  348. if (parameters.useLoop && option != 4 && option != 6) {
  349. let parent_xpath = parent_node.parameters.xpath;
  350. if (parent_node.parameters.loopType == 2) {
  351. parent_xpath = parent_node.parameters.pathList.split("\n")[0].trim();
  352. }
  353. xpath = parent_xpath + xpath;
  354. }
  355. if (xpath.includes("point(")) {
  356. xpath = "//body";
  357. }
  358. let elementInfo = {"iframe": parameters.iframe, "xpath": xpath, "id": -1};
  359. //用于跳转到元素位置
  360. let element = await findElementAcrossAllWindows(elementInfo);
  361. } else if (option == 3) {
  362. let params = parameters.params; //所有的提取数据参数
  363. let param = params[0];
  364. let xpath = param.relativeXPath;
  365. if (param.relative) {
  366. let parent_node = JSON.parse(msg.message.parentNode);
  367. let parent_xpath = parent_node.parameters.xpath;
  368. if (parent_node.parameters.loopType == 2) {
  369. parent_xpath = parent_node.parameters.pathList.split("\n")[0].trim();
  370. }
  371. xpath = parent_xpath + xpath;
  372. }
  373. let elementInfo = {"iframe": param.iframe, "xpath": xpath, "id": -1};
  374. let element = await findElementAcrossAllWindows(elementInfo);
  375. } else if (option == 11) {
  376. let params = parameters.params; //所有的提取数据参数
  377. let i = parameters.index;
  378. let param = params[i];
  379. let xpath = param.relativeXPath;
  380. if (param.relative) {
  381. let parent_node = JSON.parse(msg.message.parentNode);
  382. let parent_xpath = parent_node.parameters.xpath;
  383. if (parent_node.parameters.loopType == 2) {
  384. parent_xpath = parent_node.parameters.pathList.split("\n")[0].trim();
  385. }
  386. xpath = parent_xpath + xpath;
  387. }
  388. let elementInfo = {"iframe": param.iframe, "xpath": xpath, "id": -1};
  389. let element = await findElementAcrossAllWindows(elementInfo);
  390. } else if (option == 8) {
  391. let loopType = parameters.loopType;
  392. if (loopType <= 2) {
  393. let xpath = "";
  394. if (loopType <= 1) {
  395. xpath = parameters.xpath;
  396. } else if (loopType == 2) {
  397. xpath = parameters.pathList.split("\n")[0].trim();
  398. }
  399. let elementInfo = {"iframe": parameters.iframe, "xpath": xpath, "id": -1};
  400. let element = await findElementAcrossAllWindows(elementInfo);
  401. } else if (loopType == 5) { //JavaScript命令返回值
  402. let code = parameters.code;
  403. let waitTime = parameters.waitTime;
  404. let element = await driver.findElement(By.tagName("body"));
  405. let outcome = await execute_js(code, element, waitTime);
  406. if (!outcome || outcome == -1) {
  407. notify_browser("目前页面中,设置的循环“" + node.title + "”的JavaScript条件不成立", "The condition of the loop " + node.title + " is not met, skip this loop.", "warning");
  408. } else {
  409. notify_browser("目前页面中,设置的循环“" + node.title + "”的JavaScript条件成立", "The condition of the loop " + node.title + " is met, continue this loop.", "success");
  410. }
  411. }
  412. } else if (option == 10) { //条件分支
  413. let condition = parameters.class; //条件类型
  414. let result = -1;
  415. let additionalInfo = "";
  416. if (condition == 5 || condition == 7) { //JavaScript命令返回值
  417. let code = parameters.code;
  418. let waitTime = parameters.waitTime;
  419. let element = await driver.findElement(By.tagName("body"));
  420. if (condition == 7) {
  421. let parent_node = JSON.parse(msg.message.parentNode);
  422. let parent_xpath = parent_node.parameters.xpath;
  423. if (parent_node.parameters.loopType == 2) {
  424. parent_xpath = parent_node.parameters.pathList.split("\n")[0].trim();
  425. }
  426. let elementInfo = {"iframe": parent_node.parameters.iframe, "xpath": parent_xpath, "id": -1};
  427. element = await findElementAcrossAllWindows(elementInfo);
  428. }
  429. let outcome = await execute_js(code, element, waitTime);
  430. if (!outcome) {
  431. msg.message.result = 0; //条件不成立传入扩展
  432. } else if (outcome == -1) {
  433. msg.message.result = -1; //JS执行出错
  434. } else {
  435. msg.message.result = 1; //条件成立传入扩展
  436. }
  437. }
  438. }
  439. send_message_to_browser(JSON.stringify({"type": "trial", "message": msg}));
  440. } else { //试运行
  441. try {
  442. let flowchart_url = flowchart_window.webContents.getURL();
  443. } catch {
  444. flowchart_window = null;
  445. }
  446. if (flowchart_window == null) {
  447. notify_flowchart("试运行功能只能在任务设计阶段,Chrome浏览器打开时使用!", "The trial run function can only be used when designing tasks and opening in Chrome browser!", "error");
  448. } else {
  449. notify_browser("正在试运行操作:" + node.title, "Trying to run the operation: " + node.title, "info");
  450. let option = node.option;
  451. let parameters = node.parameters;
  452. let beforeJS = "";
  453. let beforeJSWaitTime = 0;
  454. let afterJS = "";
  455. let afterJSWaitTime = 0;
  456. try {
  457. beforeJS = parameters.beforeJS;
  458. beforeJSWaitTime = parameters.beforeJSWaitTime;
  459. afterJS = parameters.afterJS;
  460. afterJSWaitTime = parameters.afterJSWaitTime;
  461. } catch (e) {
  462. console.log(e);
  463. }
  464. if (option == 1) {
  465. let url = parameters.links.split("\n")[0].trim();
  466. if (parameters.useLoop) {
  467. let parent_node = JSON.parse(msg.message.parentNode);
  468. url = parent_node["parameters"]["textList"].split("\n")[0];
  469. }
  470. try {
  471. await driver.get(url);
  472. } catch (e) {
  473. try {
  474. await driver.switchTo().window(current_handle);
  475. await driver.get(url);
  476. } catch (e) {
  477. let all_handles = await driver.getAllWindowHandles();
  478. let handle = all_handles[all_handles.length - 1];
  479. await driver.switchTo().window(handle);
  480. await driver.get(url);
  481. }
  482. }
  483. } else if (option == 2 || option == 7) { //点击事件
  484. let xpath = parameters.xpath;
  485. let point = parameters.xpath;
  486. if (xpath.includes("point(")) {
  487. xpath = "//body"
  488. }
  489. let elementInfo = {"iframe": parameters.iframe, "xpath": xpath, "id": -1};
  490. if (parameters.useLoop && !parameters.xpath.includes("point(")) {
  491. let parent_node = JSON.parse(msg.message.parentNode);
  492. let parent_xpath = parent_node.parameters.xpath;
  493. if (parent_node.parameters.loopType == 2) {
  494. parent_xpath = parent_node.parameters.pathList.split("\n")[0].trim();
  495. }
  496. elementInfo.xpath = parent_xpath + elementInfo.xpath;
  497. }
  498. let element = await findElementAcrossAllWindows(elementInfo, notifyBrowser = false); //通过此函数找到元素并切换到对应的窗口
  499. await execute_js(parameters.beforeJS, element, parameters.beforeJSWaitTime);
  500. if (option == 2) {
  501. if (parameters.xpath.includes("point(")) {
  502. await click_element(element, point);
  503. } else {
  504. await click_element(element);
  505. }
  506. let alertHandleType = parameters.alertHandleType;
  507. if (alertHandleType == 1) {
  508. try {
  509. await driver.switchTo().alert().accept();
  510. } catch (e) {
  511. console.log("No alert");
  512. }
  513. } else if (alertHandleType == 2) {
  514. try {
  515. await driver.switchTo().alert().dismiss();
  516. } catch (e) {
  517. console.log("No alert");
  518. }
  519. }
  520. } else if (option == 7) {
  521. await driver.actions().move({origin: element}).perform();
  522. }
  523. await execute_js(parameters.afterJS, element, parameters.afterJSWaitTime);
  524. send_message_to_browser(JSON.stringify({"type": "cancelSelection"}));
  525. } else if (option == 3) { //提取数据
  526. notify_browser("提示:提取数据操作只能试运行设置的JavaScript语句,且只针对第一个匹配的元素。", "Hint: can only test JavaScript statement set in the data extraction operation, and only for the first matching element.", "info");
  527. let params = parameters.params; //所有的提取数据参数
  528. let not_found_xpaths = [];
  529. for (let i = 0; i < params.length; i++) {
  530. let param = params[i];
  531. let xpath = param.relativeXPath;
  532. if (param.relative) {
  533. let parent_node = JSON.parse(msg.message.parentNode);
  534. let parent_xpath = parent_node.parameters.xpath;
  535. if (parent_node.parameters.loopType == 2) {
  536. parent_xpath = parent_node.parameters.pathList.split("\n")[0].trim();
  537. }
  538. xpath = parent_xpath + xpath;
  539. }
  540. let elementInfo = {"iframe": param.iframe, "xpath": xpath, "id": -1};
  541. let element = await findElementAcrossAllWindows(elementInfo, notifyBrowser = false);
  542. if (element != null) {
  543. await execute_js(param.beforeJS, element, param.beforeJSWaitTime);
  544. await execute_js(param.afterJS, element, param.afterJSWaitTime);
  545. } else {
  546. not_found_xpaths.push(xpath);
  547. }
  548. }
  549. if (not_found_xpaths.length > 0) {
  550. notify_browser("无法找到以下元素,请检查XPath是否正确:" + not_found_xpaths.join("\n"), "Cannot find the element, please check if the XPath is correct: " + not_found_xpaths.join("\n"), "warning");
  551. }
  552. } else if (option == 4) { //键盘输入事件
  553. let elementInfo = {"iframe": parameters.iframe, "xpath": parameters.xpath, "id": -1};
  554. let value = node.parameters.value;
  555. if (node.parameters.useLoop) {
  556. let parent_node = JSON.parse(msg.message.parentNode);
  557. value = parent_node["parameters"]["textList"].split("\n")[0];
  558. let index = node.parameters.index;
  559. if (index > 0) {
  560. value = value.split("~")[index - 1];
  561. }
  562. }
  563. let keyInfo = value
  564. let enter = false;
  565. if (/<enter>/i.test(keyInfo)) {
  566. keyInfo = keyInfo.replace(/<enter>/gi, '');
  567. enter = true;
  568. }
  569. if (keyInfo.indexOf("Field(") >= 0 || keyInfo.indexOf("eval(") >= 0) {
  570. //两秒后通知浏览器
  571. await new Promise(resolve => setTimeout(resolve, 2000));
  572. notify_browser("检测到文字中包含Field(\"\")或eval(\"\"),试运行时无法输入两项表达式的替换值,请在任务正式运行阶段测试是否有效。", "Field(\"\") or eval(\"\") is detected in the text, and the replacement value of the two expressions cannot be entered during trial operation. Please test whether it is valid in the formal call stage.", "warning");
  573. }
  574. let element = await findElementAcrossAllWindows(elementInfo, notifyBrowser = false);
  575. await execute_js(beforeJS, element, beforeJSWaitTime);
  576. await element.sendKeys(Key.HOME, Key.chord(Key.SHIFT, Key.END), keyInfo);
  577. if (enter) {
  578. await element.sendKeys(Key.ENTER);
  579. }
  580. await execute_js(afterJS, element, afterJSWaitTime);
  581. } else if (option == 5) { //自定义操作的JS代码
  582. let code = parameters.code;
  583. let codeMode = parameters.codeMode;
  584. let waitTime = parameters.waitTime;
  585. let element = await driver.findElement(By.tagName("body"));
  586. if (codeMode == 0) {
  587. await execute_js(code, element, waitTime);
  588. } else if (codeMode == 8) {
  589. //刷新页面
  590. try {
  591. await driver.navigate().refresh();
  592. } catch (e) {
  593. try {
  594. await driver.switchTo().window(current_handle);
  595. await driver.navigate().refresh();
  596. } catch (e) {
  597. let all_handles = await driver.getAllWindowHandles();
  598. let handle = all_handles[all_handles.length - 1];
  599. await driver.switchTo().window(handle);
  600. await driver.navigate().refresh();
  601. }
  602. }
  603. }
  604. } else if (option == 6) { //切换下拉选项
  605. let optionMode = parseInt(parameters.optionMode);
  606. let optionValue = parameters.optionValue;
  607. if (node.parameters.useLoop) {
  608. let parent_node = JSON.parse(msg.message.parentNode);
  609. optionValue = parent_node["parameters"]["textList"].split("\n")[0];
  610. let index = node.parameters.index;
  611. if (index > 0) {
  612. optionValue = optionValue.split("~")[index - 1];
  613. }
  614. }
  615. let elementInfo = {"iframe": parameters.iframe, "xpath": parameters.xpath, "id": -1};
  616. let element = await findElementAcrossAllWindows(elementInfo, notifyBrowser = false);
  617. execute_js(beforeJS, element, beforeJSWaitTime);
  618. let dropdown = new Select(element);
  619. // Interacting with dropdown element based on optionMode
  620. switch (optionMode) {
  621. case 0: //切换到下一个选项
  622. let script = `var options = arguments[0].options;
  623. for (var i = 0; i < options.length; i++) {
  624. if (options[i].selected) {
  625. options[i].selected = false;
  626. if (i == options.length - 1) {
  627. options[0].selected = true;
  628. } else {
  629. options[i + 1].selected = true;
  630. }
  631. break;
  632. }
  633. }`;
  634. await driver.executeScript(script, element);
  635. break;
  636. case 1:
  637. await dropdown.selectByIndex(parseInt(optionValue));
  638. break;
  639. case 2:
  640. await dropdown.selectByValue(optionValue);
  641. break;
  642. case 3:
  643. await dropdown.selectByVisibleText(optionValue);
  644. break;
  645. default:
  646. throw new Error('Invalid option mode');
  647. }
  648. execute_js(afterJS, element, afterJSWaitTime);
  649. } else if (option == 11) { //单个提取数据参数
  650. notify_browser("提示:提取数据操作只能试运行设置的JavaScript语句,且只针对第一个匹配的元素。", "Hint: can only test JavaScript statement set in the data extraction operation, and only for the first matching element.", "info");
  651. let params = parameters.params; //所有的提取数据参数
  652. let i = parameters.index;
  653. let param = params[i];
  654. let xpath = param.relativeXPath;
  655. if (param.relative) {
  656. let parent_node = JSON.parse(msg.message.parentNode);
  657. let parent_xpath = parent_node.parameters.xpath;
  658. if (parent_node.parameters.loopType == 2) {
  659. parent_xpath = parent_node.parameters.pathList.split("\n")[0].trim();
  660. }
  661. xpath = parent_xpath + xpath;
  662. }
  663. let elementInfo = {"iframe": param.iframe, "xpath": xpath, "id": -1};
  664. let element = await findElementAcrossAllWindows(elementInfo, notifyBrowser = false);
  665. if (element != null) {
  666. await execute_js(param.beforeJS, element, param.beforeJSWaitTime);
  667. await execute_js(param.afterJS, element, param.afterJSWaitTime);
  668. }
  669. }
  670. }
  671. }
  672. } else if (msg.type == 5) {
  673. let child = require('child_process').execFile;
  674. // 参数顺序: 1. task id 2. server address 3. saved_file_name 4. "remote" or "local" 5. user_data_folder
  675. // var parameters = [msg.message.id, server_address];
  676. let parameters = [];
  677. console.log(msg.message)
  678. if (msg.message.user_data_folder == null || msg.message.user_data_folder == undefined || msg.message.user_data_folder == "") {
  679. parameters = ["--ids", "[" + msg.message.id + "]", "--server_address", server_address, "--user_data", 0];
  680. } else {
  681. let user_data_folder_path = path.join(task_server.getDir(), msg.message.user_data_folder);
  682. parameters = ["--ids", "[" + msg.message.id + "]", "--server_address", server_address, "--user_data", 1];
  683. config.user_data_folder = msg.message.user_data_folder;
  684. config.absolute_user_data_folder = user_data_folder_path;
  685. fs.writeFileSync(path.join(task_server.getDir(), "config.json"), JSON.stringify(config));
  686. }
  687. if (msg.message.mysql_config_path != "-1") {
  688. config.mysql_config_path = msg.message.mysql_config_path;
  689. }
  690. fs.writeFileSync(path.join(task_server.getDir(), "config.json"), JSON.stringify(config));
  691. // child('Chrome/easyspider_executestage.exe', parameters, function(err,stdout, stderr) {
  692. // console.log(stdout);
  693. // });
  694. let spawn = require("child_process").spawn;
  695. if (process.platform != "darwin" && msg.message.execute_type == 1 && msg.message.id != -1) {
  696. let child_process = spawn(execute_path, parameters);
  697. child_process.stdout.on('data', function (data) {
  698. console.log(data.toString());
  699. });
  700. }
  701. ws.send(JSON.stringify({
  702. "config_folder": task_server.getDir() + "/",
  703. "easyspider_location": task_server.getEasySpiderLocation()
  704. }));
  705. } else if (msg.type == 6) {
  706. try {
  707. flowchart_window.openDevTools();
  708. } catch {
  709. console.log("open devtools error");
  710. }
  711. try {
  712. invoke_window.openDevTools();
  713. } catch {
  714. console.log("open devtools error");
  715. }
  716. } else if (msg.type == 7) {
  717. // 获得当前页面Cookies
  718. try {
  719. let cookies = await driver.manage().getCookies();
  720. console.log("Cookies: ", cookies);
  721. let cookiesText = cookies.map(cookie => `${cookie.name}=${cookie.value}`).join('\n');
  722. socket_flowchart.send(JSON.stringify({"type": "GetCookies", "message": cookiesText}));
  723. } catch {
  724. console.log("Cannot get Cookies");
  725. }
  726. }
  727. }
  728. async function click_element(element, type = "click") {
  729. try {
  730. if (type == "loopClickEvery") {
  731. await driver.actions().keyDown(Key.CONTROL).click(element).keyUp(Key.CONTROL).perform();
  732. } else if (type.includes("point(")) {
  733. //point(10, 20)表示点击坐标为(10, 20)的位置
  734. let point = type.substring(6, type.length - 1).split(",");
  735. let x = parseInt(point[0]);
  736. let y = parseInt(point[1]);
  737. // let actions = driver.actions();
  738. // await actions.move({origin: element}).perform();
  739. // await actions.move({x: x, y: y}).perform();
  740. // await actions.click().perform();
  741. let script = `document.elementFromPoint(${x}, ${y}).click();`;
  742. await driver.executeScript(script);
  743. } else {
  744. await element.click();
  745. }
  746. } catch (e) {
  747. console.log(e);
  748. await driver.executeScript("arguments[0].click();", element);
  749. }
  750. }
  751. async function execute_js(js, element, wait_time = 3) {
  752. let outcome = 0;
  753. if (js.length != 0) {
  754. try {
  755. outcome = await driver.executeScript(js, element);
  756. if (wait_time == 0) {
  757. wait_time = 30000;
  758. }
  759. // await new Promise(resolve => setTimeout(resolve, wait_time));
  760. } catch (e) {
  761. // await new Promise(resolve => setTimeout(resolve, 2000));
  762. notify_browser("执行JavaScript出错,请检查JavaScript语句是否正确:" + js + "\n错误信息:" + e, "Error executing JavaScript, please check if the JavaScript statement is correct: " + js + "\nError message: " + e, "error");
  763. outcome = -1;
  764. }
  765. if (js.indexOf("Field(") >= 0 || js.indexOf("eval(") >= 0) {
  766. //两秒后通知浏览器
  767. await new Promise(resolve => setTimeout(resolve, 2000));
  768. notify_browser("检测到JavaScript中包含Field(\"\")或eval(\"\"),试运行时无法执行两项表达式,请在任务正式运行阶段测试是否有效。", "Field(\"\") or eval(\"\") is detected in JavaScript, and the two expressions cannot be executed during trial operation. Please test whether it is valid in the formal call stage.", "warning");
  769. }
  770. }
  771. return outcome;
  772. }
  773. function notify_flowchart(msg_zh, msg_en, level = "info") {
  774. socket_flowchart.send(JSON.stringify({"type": "notify", "level": level, "msg_zh": msg_zh, "msg_en": msg_en}));
  775. }
  776. function notify_browser(msg_zh, msg_en, level = "info") {
  777. send_message_to_browser(JSON.stringify({"type": "notify", "level": level, "msg_zh": msg_zh, "msg_en": msg_en}));
  778. }
  779. function send_message_to_browser(message) {
  780. socket_window.send(message);
  781. for (let i in allWindowSockets) {
  782. try {
  783. allWindowSockets[i].send(message);
  784. } catch {
  785. console.log("Cannot send to socket with id: ", allWindowScoketNames[i]);
  786. }
  787. }
  788. }
  789. const WebSocket = require('ws');
  790. const {all} = require("express/lib/application");
  791. let wss = new WebSocket.Server({port: websocket_port});
  792. wss.on('connection', function (ws) {
  793. ws.on('message', async function (message, isBinary) {
  794. let msg = JSON.parse(message.toString());
  795. // console.log("\n\nGET A MESSAGE: ", msg);
  796. // console.log(msg, msg.type, msg.message);
  797. if (msg.type == 0) {
  798. if (msg.message.id == 0) {
  799. socket_window = ws;
  800. // socket_window.on('close', function (event) {
  801. // socket_window = null;
  802. // console.log("socket_window closed");
  803. // });
  804. // console.log("set socket_window at time: ", new Date());
  805. } else if (msg.message.id == 1) {
  806. socket_start = ws;
  807. console.log("set socket_start at time: ", new Date());
  808. } else if (msg.message.id == 2) {
  809. socket_flowchart = ws;
  810. // socket_flowchart.on('close', function (event) {
  811. // socket_flowchart = null;
  812. // console.log("socket_flowchart closed");
  813. // });
  814. console.log("set socket_flowchart at time: ", new Date());
  815. } else { //其他的ID是用来标识不同的浏览器标签页的
  816. // await new Promise(resolve => setTimeout(resolve, 200));
  817. let handles = await driver.getAllWindowHandles();
  818. if (arrayDifference(handles, old_handles).length > 0) {
  819. old_handles = handles;
  820. current_handle = handles[handles.length - 1];
  821. await driver.switchTo().window(current_handle);
  822. console.log("New tab opened, change current_handle to: ", current_handle);
  823. // 调整浏览器窗口大小,不然扩展会白屏
  824. let size = await driver.manage().window().getRect();
  825. let width = size.width;
  826. let height = size.height;
  827. await driver.manage().window().setRect({width: width, height: height + 10});
  828. // height = height - 1;
  829. await driver.manage().window().setRect({width: width, height: height});
  830. }
  831. await new Promise(resolve => setTimeout(resolve, 2000));
  832. handle_pairs[msg.message.id] = current_handle;
  833. console.log("Set handle_pair for id: ", msg.message.id, " to ", current_handle, ", title is: ", msg.message.title);
  834. socket_flowchart.send(JSON.stringify({"type": "title", "data": {"title": msg.message.title}}));
  835. allWindowSockets.push(ws);
  836. allWindowScoketNames.push(msg.message.id);
  837. console.log("set socket for id: ", msg.message.id, " at time: ", new Date());
  838. ws.on('close', async function (event) {
  839. let index = allWindowSockets.indexOf(ws);
  840. if (index > -1) {
  841. allWindowSockets.splice(index, 1);
  842. allWindowScoketNames.splice(index, 1);
  843. }
  844. let handles = await driver.getAllWindowHandles();
  845. if (handles.length < old_handles.length) {
  846. old_handles = handles;
  847. current_handle = handles[handles.length - 1];
  848. await driver.switchTo().window(current_handle);
  849. console.log("Current tab closed, change current_handle to: ", current_handle);
  850. }
  851. console.log("socket for id: ", msg.message.id, " closed at time: ", new Date());
  852. });
  853. // console.log("handle_pairs: ", handle_pairs);
  854. }
  855. } else if (msg.type == 10) {
  856. let leave_handle = handle_pairs[msg.message.id];
  857. if (leave_handle != null && leave_handle != undefined && leave_handle != "") {
  858. await driver.switchTo().window(leave_handle);
  859. console.log("Switch to handle: ", leave_handle);
  860. current_handle = leave_handle;
  861. }
  862. } else {
  863. await beginInvoke(msg, ws);
  864. }
  865. });
  866. });
  867. console.log(process.platform);
  868. async function runBrowser(lang = "en", user_data_folder = '', mobile = false) {
  869. const serviceBuilder = new ServiceBuilder(driverPath);
  870. let options = new chrome.Options();
  871. options.addArguments('--disable-blink-features=AutomationControlled');
  872. options.addArguments('--disable-infobars');
  873. // 添加实验性选项以排除'enable-automation'开关
  874. options.set('excludeSwitches', ['enable-automation']);
  875. options.excludeSwitches("enable-automation")
  876. // 添加实验性选项来禁用自动化扩展
  877. options.set('useAutomationExtension', false);
  878. // options.addArguments('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36');
  879. options.set
  880. language = lang;
  881. if (lang == "en") {
  882. options.addExtensions(path.join(__dirname, "EasySpider_en.crx"));
  883. } else if (lang == "zh") {
  884. options.addExtensions(path.join(__dirname, "EasySpider_zh.crx"));
  885. }
  886. options.addExtensions(path.join(__dirname, "XPathHelper.crx"));
  887. options.setChromeBinaryPath(chromeBinaryPath);
  888. if (user_data_folder != "") {
  889. let dir = path.join(task_server.getDir(), user_data_folder);
  890. console.log(dir);
  891. options.addArguments("--user-data-dir=" + dir);
  892. config.user_data_folder = user_data_folder;
  893. fs.writeFileSync(path.join(task_server.getDir(), "config.json"), JSON.stringify(config));
  894. } else {
  895. config.user_data_folder = "";
  896. }
  897. if (mobile) {
  898. const mobileEmulation = {
  899. deviceName: 'iPhone XR'
  900. };
  901. options.addArguments(`--user-agent="Mozilla/5.0 (iPhone; CPU iPhone OS 13_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1"`);
  902. options.setMobileEmulation(mobileEmulation);
  903. }
  904. driver = new Builder()
  905. .forBrowser('chrome')
  906. .setChromeOptions(options)
  907. .setChromeService(serviceBuilder)
  908. .build();
  909. await driver.manage().setTimeouts({implicit: 3, pageLoad: 10000, script: 10000});
  910. await driver.executeScript("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})");
  911. // await driver.executeScript("localStorage.clear();"); //重置参数数量
  912. const cdpConnection = await driver.createCDPConnection("page");
  913. let stealth_path = path.join(__dirname, "stealth.min.js");
  914. let stealth = fs.readFileSync(stealth_path, 'utf8');
  915. await cdpConnection.execute('Page.addScriptToEvaluateOnNewDocument', {
  916. source: stealth,
  917. });
  918. try {
  919. if (mobile) {
  920. await driver.get(server_address + "/taskGrid/taskList.html?wsport=" + websocket_port + "&backEndAddressServiceWrapper=" + server_address + "&mobile=1&lang=" + lang);
  921. } else {
  922. await driver.get(server_address + "/taskGrid/taskList.html?wsport=" + websocket_port + "&backEndAddressServiceWrapper=" + server_address + "&lang=" + lang);
  923. }
  924. old_handles = await driver.getAllWindowHandles();
  925. current_handle = old_handles[old_handles.length - 1];
  926. } finally {
  927. // await driver.quit(); // 退出浏览器
  928. }
  929. }
  930. function handleOpenBrowser(event, lang = "en", user_data_folder = "", mobile = false) {
  931. const webContents = event.sender;
  932. const win = BrowserWindow.fromWebContents(webContents);
  933. runBrowser(lang, user_data_folder, mobile);
  934. let size = screen.getPrimaryDisplay().workAreaSize;
  935. let width = parseInt(size.width);
  936. let height = parseInt(size.height * 0.5);
  937. flowchart_window = new BrowserWindow({
  938. x: 0,
  939. y: 0,
  940. width: width,
  941. height: height,
  942. icon: iconPath,
  943. maximizable: true,
  944. resizable: true,
  945. });
  946. let url = "";
  947. let id = -1;
  948. if (lang == "en") {
  949. url = server_address + `/taskGrid/FlowChart.html?id=${id}&wsport=${websocket_port}&backEndAddressServiceWrapper=` + server_address + "&mobile=" + mobile.toString();
  950. } else if (lang == "zh") {
  951. url = server_address + `/taskGrid/FlowChart_CN.html?id=${id}&wsport=${websocket_port}&backEndAddressServiceWrapper=` + server_address + "&mobile=" + mobile.toString();
  952. }
  953. // and load the index.html of the app.
  954. flowchart_window.loadURL(url, {extraHeaders: 'pragma: no-cache\n'});
  955. if (process.platform != "darwin") {
  956. flowchart_window.hide();
  957. }
  958. flowchart_window.on('close', function (event) {
  959. mainWindow.show();
  960. driver.quit();
  961. });
  962. }
  963. function handleOpenInvoke(event, lang = "en") {
  964. invoke_window = new BrowserWindow({icon: iconPath});
  965. let url = "";
  966. language = lang;
  967. if (lang == "en") {
  968. url = server_address + `/taskGrid/taskList.html?type=1&wsport=${websocket_port}&backEndAddressServiceWrapper=` + server_address;
  969. } else if (lang == "zh") {
  970. url = server_address + `/taskGrid/taskList.html?type=1&wsport=${websocket_port}&backEndAddressServiceWrapper=` + server_address + "&lang=zh";
  971. }
  972. // and load the index.html of the app.
  973. invoke_window.loadURL(url, {extraHeaders: 'pragma: no-cache\n'});
  974. invoke_window.maximize();
  975. mainWindow.hide();
  976. invoke_window.on('close', function (event) {
  977. mainWindow.show();
  978. });
  979. }
  980. // This method will be called when Electron has finished
  981. // initialization and is ready to create browser windows.
  982. // Some APIs can only be used after this event occurs.
  983. app.whenReady().then(() => {
  984. session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
  985. details.requestHeaders['Accept-Language'] = 'zh'
  986. callback({cancel: false, requestHeaders: details.requestHeaders})
  987. })
  988. ipcMain.on('start-design', handleOpenBrowser);
  989. ipcMain.on('start-invoke', handleOpenInvoke);
  990. ipcMain.on('accept-agreement', function (event, arg) {
  991. config.copyright = 1;
  992. fs.writeFileSync(path.join(task_server.getDir(), "config.json"), JSON.stringify(config));
  993. });
  994. createWindow();
  995. app.on('activate', function () {
  996. // On MacOS it's common to re-create a window in the app when the
  997. // dock icon is clicked and there are no other windows open.
  998. if (BrowserWindow.getAllWindows().length === 0) {
  999. createWindow();
  1000. }
  1001. })
  1002. })
  1003. // Quit when all windows are closed, except on macOS. There, it's common
  1004. // for applications and their menu bar to stay active until the user quits
  1005. // explicitly with Cmd + Q.
  1006. app.on('window-all-closed', function () {
  1007. if (process.platform !== 'darwin') {
  1008. app.quit();
  1009. }
  1010. })
  1011. // In this file you can include the rest of your app's specific main process
  1012. // code. You can also put them in separate files and require them here.
  1013. function arrayDifference(arr1, arr2) {
  1014. return arr1.filter(item => !arr2.includes(item));
  1015. }