server.js 16 KB

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