server.js 13 KB

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