server.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. const http = require("http");
  2. const querystring = require("querystring");
  3. const url = require("url");
  4. const fs = require("fs");
  5. const path = require("path");
  6. const { app, dialog } = require("electron");
  7. const XLSX = require("xlsx");
  8. const formidable = require("formidable");
  9. const express = require("express");
  10. const multer = require("multer");
  11. const cors = require("cors");
  12. function travel(dir, callback) {
  13. fs.readdirSync(dir).forEach((file) => {
  14. const pathname = path.join(dir, file);
  15. if (fs.statSync(pathname).isDirectory()) {
  16. travel(pathname, callback);
  17. } else {
  18. callback(pathname);
  19. }
  20. });
  21. }
  22. function compare(p) {
  23. //这是比较函数
  24. return function (m, n) {
  25. let a = m[p];
  26. let b = n[p];
  27. return b - a; //降序
  28. };
  29. }
  30. function getDir() {
  31. if (__dirname.indexOf("app") >= 0 && __dirname.indexOf("sources") >= 0) {
  32. if (process.platform == "darwin") {
  33. return app.getPath("userData");
  34. } else {
  35. return path.join(__dirname, "../../..");
  36. }
  37. } else {
  38. return __dirname;
  39. }
  40. }
  41. function getEasySpiderLocation() {
  42. if (__dirname.indexOf("app") >= 0 && __dirname.indexOf("sources") >= 0) {
  43. if (process.platform == "darwin") {
  44. return path.join(__dirname, "../../../");
  45. } else {
  46. return path.join(__dirname, "../../../");
  47. }
  48. } else {
  49. return __dirname;
  50. }
  51. }
  52. if (!fs.existsSync(path.join(getDir(), "tasks"))) {
  53. fs.mkdirSync(path.join(getDir(), "tasks"));
  54. }
  55. if (!fs.existsSync(path.join(getDir(), "execution_instances"))) {
  56. fs.mkdirSync(path.join(getDir(), "execution_instances"));
  57. }
  58. if (!fs.existsSync(path.join(getDir(), "config.json"))) {
  59. // Generate config.json
  60. fs.writeFileSync(
  61. path.join(getDir(), "config.json"),
  62. JSON.stringify({
  63. webserver_address: "http://localhost",
  64. webserver_port: 8074,
  65. user_data_folder: "./user_data",
  66. debug: false,
  67. copyright: 0,
  68. sys_arch: require("os").arch(),
  69. mysql_config_path: "./mysql_config.json",
  70. absolute_user_data_folder:
  71. "D:\\Document\\Projects\\EasySpider\\ElectronJS\\user_data",
  72. })
  73. );
  74. }
  75. exports.getDir = getDir;
  76. exports.getEasySpiderLocation = getEasySpiderLocation;
  77. FileMimes = JSON.parse(
  78. fs.readFileSync(path.join(__dirname, "mime.json")).toString()
  79. );
  80. const fileServer = express();
  81. const upload = multer({ dest: path.join(getDir(), "Data/") });
  82. fileServer.use(cors());
  83. fileServer.post("/excelUpload", upload.single("file"), (req, res) => {
  84. let workbook = XLSX.readFile(req.file.path);
  85. let sheet_name_list = workbook.SheetNames;
  86. let data = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
  87. let result = data.reduce((acc, obj) => {
  88. Object.keys(obj).forEach((key) => {
  89. if (!acc[key]) {
  90. acc[key] = [];
  91. }
  92. acc[key].push(obj[key]);
  93. });
  94. return acc;
  95. }, {});
  96. // console.log(data);
  97. // delete file after reading
  98. fs.unlink(req.file.path, (err) => {
  99. if (err) {
  100. console.error(err);
  101. return;
  102. }
  103. // file removed
  104. });
  105. res.send(JSON.stringify(result));
  106. });
  107. fileServer.listen(8075, () => {
  108. console.log("Server listening on http://localhost:8075");
  109. });
  110. exports.start = function (port = 8074) {
  111. http
  112. .createServer(function (req, res) {
  113. let body = "";
  114. res.setHeader("Access-Control-Allow-Origin", "*"); // 设置可访问的源
  115. // 解析参数
  116. const pathName = url.parse(req.url).pathname;
  117. const safeBase = path.join(__dirname, "src");
  118. const safeJoin = (base, target) => {
  119. const targetPath = "." + path.posix.normalize("/" + target);
  120. return path.join(base, targetPath);
  121. };
  122. if (pathName == "/excelUpload" && req.method.toLowerCase() === "post") {
  123. // // parse a file upload
  124. // let form = new formidable.IncomingForm();
  125. // // Set the max file size
  126. // form.maxFileSize = 200 * 1024 * 1024; // 200MB
  127. // form.parse(req, function (err, fields, files) {
  128. // console.log("excelUpload")
  129. // console.log(err, fields, files);
  130. // let oldpath = files.file.path;
  131. // let workbook = XLSX.readFile(oldpath);
  132. // let sheet_name_list = workbook.SheetNames;
  133. // let data = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
  134. // console.log(data);
  135. // res.end('File uploaded and read successfully.');
  136. // });
  137. } else if (pathName.indexOf(".") < 0) {
  138. //如果没有后缀名, 则为后台请求
  139. res.writeHead(200, { "Content-Type": "application/json" });
  140. }
  141. // else if(pathName.indexOf("index.html") >= 0) {
  142. // fs.readFile(path.join(__dirname,"src", pathName), async (err, data) => {
  143. // if (err) {
  144. // res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' })
  145. // res.end(err.message)
  146. // return;
  147. // }
  148. // if (!err) {
  149. // // 3. 针对不同的文件返回不同的内容头
  150. // let extname = path.extname(pathName);
  151. // let mime = FileMimes[extname]
  152. // res.writeHead(200, { 'Content-Type': mime + ';charset="utf-8"' })
  153. // res.end(data);
  154. // return;
  155. // }
  156. // })
  157. // }
  158. else {
  159. //如果有后缀名, 则为前端请求
  160. // console.log(path.join(__dirname,"src/taskGrid", pathName));
  161. const filePath = safeJoin(safeBase, pathName);
  162. if (!filePath.startsWith(safeBase)) {
  163. res.writeHead(400, { "Content-Type": 'text/html;charset="utf-8"' });
  164. res.end("Invalid path");
  165. return;
  166. }
  167. fs.readFile(
  168. filePath,
  169. async (err, data) => {
  170. if (err) {
  171. res.writeHead(404, {
  172. "Content-Type": 'text/html;charset="utf-8"',
  173. });
  174. res.end(err.message);
  175. return;
  176. }
  177. if (!err) {
  178. // 3. 针对不同的文件返回不同的内容头
  179. let extname = path.extname(pathName);
  180. let mime = FileMimes[extname];
  181. res.writeHead(200, { "Content-Type": mime + ';charset="utf-8"' });
  182. res.end(data);
  183. return;
  184. }
  185. }
  186. );
  187. }
  188. req.on("data", function (chunk) {
  189. body += chunk;
  190. });
  191. req.on("end", function () {
  192. // 设置响应头部信息及编码
  193. if (pathName == "/queryTasks") {
  194. //查询所有服务信息,只包括id和服务名称
  195. output = [];
  196. travel(path.join(getDir(), "tasks"), function (pathname) {
  197. const data = fs.readFileSync(pathname, "utf8");
  198. let stat = fs.statSync(pathname, "utf8");
  199. // parse JSON string to JSON object
  200. // console.log("\n\n\n\n\n", pathname, '\n\n\n\n\n\n');
  201. if (pathname.indexOf(".json") >= 0) {
  202. const task = JSON.parse(data);
  203. let item = {
  204. id: task.id,
  205. name: task.name,
  206. url: task.url,
  207. mtime: stat.mtime,
  208. links: task.links,
  209. desc: task.desc,
  210. };
  211. if (item.id != -2) {
  212. output.push(item);
  213. }
  214. }
  215. });
  216. output.sort(compare("mtime"));
  217. res.write(JSON.stringify(output));
  218. res.end();
  219. } else if (pathName == "/queryOSVersion") {
  220. res.write(
  221. JSON.stringify({ version: process.platform, bit: process.arch })
  222. );
  223. res.end();
  224. } else if (pathName == "/queryExecutionInstances") {
  225. //查询所有服务信息,只包括id和服务名称
  226. output = [];
  227. travel(
  228. path.join(getDir(), "execution_instances"),
  229. function (pathname) {
  230. const data = fs.readFileSync(pathname, "utf8");
  231. // parse JSON string to JSON object
  232. const task = JSON.parse(data);
  233. let item = {
  234. id: task.id,
  235. name: task.name,
  236. url: task.url,
  237. };
  238. if (item.id != -2) {
  239. output.push(item);
  240. }
  241. }
  242. );
  243. res.write(JSON.stringify(output));
  244. res.end();
  245. } else if (pathName == "/queryTask") {
  246. let params = url.parse(req.url, true).query;
  247. try {
  248. let tid = parseInt(params.id);
  249. const data = fs.readFileSync(
  250. path.join(getDir(), `tasks/${tid}.json`),
  251. "utf8"
  252. );
  253. // parse JSON string to JSON object
  254. res.write(data);
  255. res.end();
  256. } catch (error) {
  257. res.write(
  258. JSON.stringify({
  259. error: "Cannot find task based on specified task ID.",
  260. })
  261. );
  262. res.end();
  263. }
  264. } else if (pathName == "/queryExecutionInstance") {
  265. let params = url.parse(req.url, true).query;
  266. try {
  267. let tid = parseInt(params.id);
  268. const data = fs.readFileSync(
  269. path.join(getDir(), `execution_instances/${tid}.json`),
  270. "utf8"
  271. );
  272. // parse JSON string to JSON object
  273. res.write(data);
  274. res.end();
  275. } catch (error) {
  276. res.write(
  277. JSON.stringify({
  278. error:
  279. "Cannot find execution instance based on specified execution ID.",
  280. })
  281. );
  282. res.end();
  283. }
  284. } else if (pathName == "/") {
  285. res.write("Hello World!", "utf8");
  286. res.end();
  287. } else if (pathName == "/deleteTask") {
  288. let params = url.parse(req.url, true).query;
  289. try {
  290. let tid = parseInt(params.id);
  291. let data = fs.readFileSync(
  292. path.join(getDir(), `tasks/${tid}.json`),
  293. "utf8"
  294. );
  295. data = JSON.parse(data);
  296. data.id = -2;
  297. data = JSON.stringify(data);
  298. // write JSON string to a file
  299. fs.writeFile(
  300. path.join(getDir(), `tasks/${tid}.json`),
  301. data,
  302. (err) => {
  303. if (err) {
  304. throw err;
  305. }
  306. }
  307. );
  308. res.write(
  309. JSON.stringify({ success: "Task has been deleted successfully." })
  310. );
  311. res.end();
  312. } catch (error) {
  313. res.write(
  314. JSON.stringify({
  315. error: "Cannot find task based on specified task ID.",
  316. })
  317. );
  318. res.end();
  319. }
  320. } else if (pathName == "/manageTask") {
  321. body = querystring.parse(body);
  322. data = JSON.parse(body.params);
  323. let id = data["id"];
  324. if (data["id"] == -1) {
  325. file_names = [];
  326. fs.readdirSync(path.join(getDir(), "tasks")).forEach((file) => {
  327. try {
  328. if (file.split(".")[1] == "json") {
  329. file_names.push(parseInt(file.split(".")[0]));
  330. }
  331. } catch (error) {}
  332. });
  333. if (file_names.length == 0) {
  334. id = 0;
  335. } else {
  336. id = Math.max(...file_names) + 1;
  337. }
  338. data["id"] = id;
  339. // write JSON string to a fil
  340. }
  341. if (data["outputFormat"] == "mysql") {
  342. let mysql_config_path = path.join(getDir(), "mysql_config.json");
  343. // 检测文件是否存在
  344. fs.access(mysql_config_path, fs.F_OK, (err) => {
  345. if (err) {
  346. console.log("File does not exist. Creating...");
  347. // 文件不存在,创建文件
  348. const config = {
  349. host: "localhost",
  350. port: 3306,
  351. username: "your_username",
  352. password: "your_password",
  353. database: "your_database",
  354. };
  355. fs.writeFile(
  356. mysql_config_path,
  357. JSON.stringify(config, null, 4),
  358. (err) => {
  359. if (err) throw err;
  360. console.log("File is created successfully.");
  361. }
  362. );
  363. } else {
  364. console.log("File exists.");
  365. }
  366. });
  367. }
  368. data = JSON.stringify(data);
  369. // write JSON string to a file
  370. fs.writeFile(
  371. path.join(getDir(), `tasks/${id}.json`),
  372. data,
  373. (err) => {}
  374. );
  375. res.write(id.toString(), "utf8");
  376. res.end();
  377. } else if (pathName == "/invokeTask") {
  378. body = querystring.parse(body);
  379. let data = JSON.parse(body.params);
  380. let id = body.id;
  381. let task = fs.readFileSync(
  382. path.join(getDir(), `tasks/${id}.json`),
  383. "utf8"
  384. );
  385. task = JSON.parse(task);
  386. try {
  387. task["links"] = data["urlList_0"];
  388. if (task["links"] == undefined) {
  389. task["links"] = "about:blank";
  390. }
  391. } catch (error) {
  392. task["links"] = "about:blank";
  393. }
  394. for (const [key, value] of Object.entries(data)) {
  395. for (let i = 0; i < task["inputParameters"].length; i++) {
  396. if (key === task["inputParameters"][i]["name"]) {
  397. // 能调用
  398. const nodeId = parseInt(task["inputParameters"][i]["nodeId"]);
  399. const node = task["graph"][nodeId];
  400. if (node["option"] === 1) {
  401. node["parameters"]["links"] = value;
  402. } else if (node["option"] === 4) {
  403. node["parameters"]["value"] = value;
  404. } else if (
  405. node["option"] === 8 &&
  406. node["parameters"]["loopType"] === 0
  407. ) {
  408. node["parameters"]["exitCount"] = parseInt(value);
  409. } else if (node["option"] === 8) {
  410. node["parameters"]["textList"] = value;
  411. }
  412. break;
  413. }
  414. }
  415. }
  416. let file_names = [];
  417. fs.readdirSync(path.join(getDir(), "execution_instances")).forEach(
  418. (file) => {
  419. try {
  420. if (file.split(".")[1] == "json") {
  421. file_names.push(parseInt(file.split(".")[0]));
  422. }
  423. console.log(file);
  424. } catch (error) {}
  425. }
  426. );
  427. let eid = 0;
  428. if (file_names.length != 0) {
  429. eid = Math.max(...file_names) + 1;
  430. }
  431. if (body["EID"] != "" && body["EID"] != undefined) {
  432. //覆盖原有的执行实例
  433. eid = parseInt(body["EID"]);
  434. }
  435. task["id"] = eid;
  436. task = JSON.stringify(task);
  437. fs.writeFile(
  438. path.join(getDir(), `execution_instances/${eid}.json`),
  439. task,
  440. (err) => {}
  441. );
  442. res.write(eid.toString(), "utf8");
  443. res.end();
  444. } else if (pathName == "/getConfig") {
  445. let config_file = fs.readFileSync(
  446. path.join(getDir(), `config.json`),
  447. "utf8"
  448. );
  449. config_file = JSON.parse(config_file);
  450. res.write(JSON.stringify(config_file));
  451. res.end();
  452. } else if (pathName == "/setUserDataFolder") {
  453. let config = fs.readFileSync(
  454. path.join(getDir(), `config.json`),
  455. "utf8"
  456. );
  457. config = JSON.parse(config);
  458. body = querystring.parse(body);
  459. config["user_data_folder"] = body["user_data_folder"];
  460. config = JSON.stringify(config);
  461. fs.writeFile(path.join(getDir(), `config.json`), config, (err) => {});
  462. res.write(
  463. JSON.stringify({
  464. success: "User data folder has been set successfully.",
  465. })
  466. );
  467. res.end();
  468. }
  469. });
  470. })
  471. .listen(port);
  472. console.log("Server has started.");
  473. };