server.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. return function(m,n){
  24. var a = m[p];
  25. var b = n[p];
  26. return b - a; //降序
  27. }
  28. }
  29. function getDir(){
  30. if(__dirname.indexOf("app") >= 0 && __dirname.indexOf("sources") >= 0){
  31. if(process.platform == "darwin"){
  32. return app.getPath("userData");
  33. } else {
  34. return path.join(__dirname,"../../..");
  35. }
  36. } else {
  37. return __dirname;
  38. }
  39. }
  40. function getEasySpiderLocation(){
  41. if(__dirname.indexOf("app") >= 0 && __dirname.indexOf("sources") >= 0){
  42. if(process.platform == "darwin"){
  43. return path.join(__dirname,"../../../");
  44. } else {
  45. return path.join(__dirname,"../../../");
  46. }
  47. } else {
  48. return __dirname;
  49. }
  50. }
  51. if(!fs.existsSync(path.join(getDir(), "tasks"))){
  52. fs.mkdirSync(path.join(getDir(), "tasks"));
  53. }
  54. if(!fs.existsSync(path.join(getDir(), "execution_instances"))){
  55. fs.mkdirSync(path.join(getDir(), "execution_instances"));
  56. }
  57. if(!fs.existsSync(path.join(getDir(), "config.json"))){
  58. fs.writeFileSync(path.join(getDir(), "config.json"), JSON.stringify({"webserver_address":"http://localhost","webserver_port":8074,"user_data_folder":"./user_data","absolute_user_data_folder":""}));
  59. }
  60. exports.getDir = getDir;
  61. exports.getEasySpiderLocation = getEasySpiderLocation;
  62. FileMimes = JSON.parse(fs.readFileSync(path.join(__dirname,'mime.json')).toString());
  63. const fileServer = express();
  64. const upload = multer({ dest: 'Data/' });
  65. fileServer.use(cors());
  66. fileServer.post('/excelUpload', upload.single('file'), (req, res) => {
  67. let workbook = XLSX.readFile(req.file.path);
  68. let sheet_name_list = workbook.SheetNames;
  69. let data = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
  70. let result = data.reduce((acc, obj) => {
  71. Object.keys(obj).forEach(key => {
  72. if(!acc[key]) {
  73. acc[key] = [];
  74. }
  75. acc[key].push(obj[key]);
  76. });
  77. return acc;
  78. }, {});
  79. // console.log(data);
  80. // delete file after reading
  81. fs.unlink(req.file.path, (err) => {
  82. if (err) {
  83. console.error(err);
  84. return;
  85. }
  86. // file removed
  87. });
  88. res.send(JSON.stringify(result));
  89. });
  90. fileServer.listen(8075, () => {
  91. console.log('Server listening on http://localhost:8075');
  92. });
  93. exports.start = function(port = 8074) {
  94. http.createServer(function(req, res) {
  95. let body = "";
  96. res.setHeader("Access-Control-Allow-Origin", "*"); // 设置可访问的源
  97. // 解析参数
  98. const pathName = url.parse(req.url).pathname;
  99. if(pathName == "/excelUpload" && req.method.toLowerCase() === 'post'){
  100. // // parse a file upload
  101. // let form = new formidable.IncomingForm();
  102. // // Set the max file size
  103. // form.maxFileSize = 200 * 1024 * 1024; // 200MB
  104. // form.parse(req, function (err, fields, files) {
  105. // console.log("excelUpload")
  106. // console.log(err, fields, files);
  107. // let oldpath = files.file.path;
  108. // let workbook = XLSX.readFile(oldpath);
  109. // let sheet_name_list = workbook.SheetNames;
  110. // let data = XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]);
  111. // console.log(data);
  112. // res.end('File uploaded and read successfully.');
  113. // });
  114. } else if(pathName.indexOf(".") < 0) { //如果没有后缀名, 则为后台请求
  115. res.writeHead(200, { 'Content-Type': 'application/json' });
  116. }
  117. // else if(pathName.indexOf("index.html") >= 0) {
  118. // fs.readFile(path.join(__dirname,"src", pathName), async (err, data) => {
  119. // if (err) {
  120. // res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' })
  121. // res.end(err.message)
  122. // return;
  123. // }
  124. // if (!err) {
  125. // // 3. 针对不同的文件返回不同的内容头
  126. // let extname = path.extname(pathName);
  127. // let mime = FileMimes[extname]
  128. // res.writeHead(200, { 'Content-Type': mime + ';charset="utf-8"' })
  129. // res.end(data);
  130. // return;
  131. // }
  132. // })
  133. // }
  134. else { //如果有后缀名, 则为前端请求
  135. // console.log(path.join(__dirname,"src/taskGrid", pathName));
  136. fs.readFile(path.join(__dirname,"src", pathName), async (err, data) => {
  137. if (err) {
  138. res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' })
  139. res.end(err.message)
  140. return;
  141. }
  142. if (!err) {
  143. // 3. 针对不同的文件返回不同的内容头
  144. let extname = path.extname(pathName);
  145. let mime = FileMimes[extname]
  146. res.writeHead(200, { 'Content-Type': mime + ';charset="utf-8"' })
  147. res.end(data);
  148. return;
  149. }
  150. })
  151. }
  152. req.on('data', function(chunk) {
  153. body += chunk;
  154. });
  155. req.on('end', function() {
  156. // 设置响应头部信息及编码
  157. if (pathName == "/queryTasks") { //查询所有服务信息,只包括id和服务名称
  158. output = [];
  159. travel(path.join(getDir(), "tasks"),function(pathname){
  160. const data = fs.readFileSync(pathname, 'utf8');
  161. let stat = fs.statSync(pathname, 'utf8');
  162. // parse JSON string to JSON object
  163. const task = JSON.parse(data);
  164. let item = {
  165. "id": task.id,
  166. "name": task.name,
  167. "url": task.url,
  168. "mtime": stat.mtime,
  169. }
  170. if(item.id!= -2) {
  171. output.push(item);
  172. }
  173. });
  174. output.sort(compare("mtime"));
  175. res.write(JSON.stringify(output));
  176. res.end();
  177. } else if(pathName == "/queryOSVersion") {
  178. res.write(JSON.stringify({"version":process.platform, "bit":process.arch}));
  179. res.end();
  180. } else if (pathName == "/queryExecutionInstances") { //查询所有服务信息,只包括id和服务名称
  181. output = [];
  182. travel(path.join(getDir(), "execution_instances"),function(pathname){
  183. const data = fs.readFileSync(pathname, 'utf8');
  184. // parse JSON string to JSON object
  185. const task = JSON.parse(data);
  186. let item = {
  187. "id": task.id,
  188. "name": task.name,
  189. "url": task.url,
  190. }
  191. if(item.id!= -2) {
  192. output.push(item);
  193. }
  194. });
  195. res.write(JSON.stringify(output));
  196. res.end();
  197. } else if (pathName == "/queryTask") {
  198. var params = url.parse(req.url, true).query;
  199. try {
  200. var tid = parseInt(params.id);
  201. const data = fs.readFileSync(path.join(getDir(), `tasks/${tid}.json`), 'utf8');
  202. // parse JSON string to JSON object
  203. res.write(data);
  204. res.end();
  205. } catch (error) {
  206. res.write(JSON.stringify({ "error": "Cannot find task based on specified task ID." }));
  207. res.end();
  208. }
  209. } else if (pathName == "/queryExecutionInstance") {
  210. var params = url.parse(req.url, true).query;
  211. try {
  212. var tid = parseInt(params.id);
  213. const data = fs.readFileSync(path.join(getDir(), `execution_instances/${tid}.json`), 'utf8');
  214. // parse JSON string to JSON object
  215. res.write(data);
  216. res.end();
  217. } catch (error) {
  218. res.write(JSON.stringify({ "error": "Cannot find execution instance based on specified execution ID." }));
  219. res.end();
  220. }
  221. } else if(pathName == "/"){
  222. res.write("Hello World!", 'utf8');
  223. res.end();
  224. } else if(pathName == "/deleteTask"){
  225. var params = url.parse(req.url, true).query;
  226. try {
  227. let tid = parseInt(params.id);
  228. let data = fs.readFileSync(path.join(getDir(), `tasks/${tid}.json`), 'utf8');
  229. data = JSON.parse(data);
  230. data.id = -2;
  231. data = JSON.stringify(data);
  232. // write JSON string to a file
  233. fs.writeFile(path.join(getDir(), `tasks/${tid}.json`), data, (err) => {
  234. if (err) {
  235. throw err;
  236. }
  237. });
  238. res.write(JSON.stringify({ "success": "Task has been deleted successfully." }));
  239. res.end();
  240. } catch (error) {
  241. res.write(JSON.stringify({ "error": "Cannot find task based on specified task ID." }));
  242. res.end();
  243. }
  244. } else if(pathName == "/manageTask"){
  245. body = querystring.parse(body);
  246. data = JSON.parse(body.paras);
  247. let id = data["id"];
  248. if (data["id"] == -1) {
  249. file_names = [];
  250. fs.readdirSync(path.join(getDir(), "tasks")).forEach((file)=>{
  251. try{
  252. if(file.split(".")[1] == "json"){
  253. file_names.push(parseInt(file.split(".")[0]));
  254. }
  255. } catch (error) {
  256. }
  257. })
  258. if(file_names.length == 0){
  259. id = 0;
  260. } else {
  261. id = Math.max(...file_names) + 1;
  262. }
  263. data["id"] = id;
  264. // write JSON string to a fil
  265. }
  266. data = JSON.stringify(data);
  267. // write JSON string to a file
  268. fs.writeFile(path.join(getDir(), `tasks/${id}.json`), data, (err) => {});
  269. res.write(id.toString(), 'utf8');
  270. res.end();
  271. } else if(pathName == "/invokeTask"){
  272. body = querystring.parse(body);
  273. let data = JSON.parse(body.paras);
  274. let id = body.id;
  275. let task = fs.readFileSync(path.join(getDir(), `tasks/${id}.json`), 'utf8');
  276. task = JSON.parse(task);
  277. try{
  278. task["links"] = data["urlList_0"];
  279. }catch(error){
  280. console.log(error);
  281. }
  282. for (const [key, value] of Object.entries(data)) {
  283. for (let i = 0; i < task["inputParameters"].length; i++) {
  284. if (key === task["inputParameters"][i]["name"]) { // 能调用
  285. const nodeId = parseInt(task["inputParameters"][i]["nodeId"]);
  286. const node = task["graph"][nodeId];
  287. if (node["option"] === 1) {
  288. node["parameters"]["links"] = value;
  289. } else if (node["option"] === 4) {
  290. node["parameters"]["value"] = value;
  291. } else if (node["option"] === 8 && node["parameters"]["loopType"] === 0) {
  292. node["parameters"]["exitCount"] = parseInt(value);
  293. } else if (node["option"] === 8) {
  294. node["parameters"]["textList"] = value;
  295. }
  296. break;
  297. }
  298. }
  299. }
  300. let file_names = [];
  301. fs.readdirSync(path.join(getDir(), "execution_instances")).forEach((file)=>{
  302. try{
  303. if(file.split(".")[1] == "json"){
  304. file_names.push(parseInt(file.split(".")[0]));
  305. }
  306. console.log(file);
  307. } catch (error) {
  308. }
  309. })
  310. let eid = 0;
  311. if (file_names.length != 0) {
  312. eid = Math.max(...file_names) + 1;
  313. }
  314. task["id"] = eid;
  315. task = JSON.stringify(task);
  316. fs.writeFile(path.join(getDir(), `execution_instances/${eid}.json`), task, (err) => {});
  317. res.write(eid.toString(), 'utf8');
  318. res.end();
  319. } else if(pathName == "/getConfig"){
  320. let config = fs.readFileSync(path.join(getDir(), `config.json`), 'utf8');
  321. config = JSON.parse(config);
  322. res.write(JSON.stringify(config));
  323. res.end();
  324. } else if(pathName == "/setUserDataFolder"){
  325. let config = fs.readFileSync(path.join(getDir(), `config.json`), 'utf8');
  326. config = JSON.parse(config);
  327. body = querystring.parse(body);
  328. config["user_data_folder"] = body["user_data_folder"];
  329. config = JSON.stringify(config);
  330. fs.writeFile(path.join(getDir(), `config.json`), config, (err) => {});
  331. res.write(JSON.stringify({ "success": "User data folder has been set successfully." }));
  332. res.end();
  333. }
  334. });
  335. }).listen(port);
  336. console.log("Server has started.");
  337. }