electronApi.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. import pjson from '/package.json'
  2. const axios = require('axios');
  3. const https = require('https');
  4. const path = require("path");
  5. const fs = require("fs");
  6. const os = require("os");
  7. const regedit = require('regedit');
  8. const child_process = require("child_process");
  9. const { app, dialog, shell, Menu, net, ipcMain } = require("electron");
  10. var exeMap = {};
  11. var procMap = {};
  12. if (process.env.NODE_ENV == 'development') {
  13. getAllExe(path.join(__dirname, "../../bin"));
  14. } else {
  15. getAllExe(path.join(__dirname, "../../../app.asar.unpacked/bin"));
  16. }
  17. function getAllExe(dir) {
  18. fs.readdir(dir, function (err, files) {
  19. if (err) return;
  20. files.forEach(function (file) {
  21. if (process.platform != "win32" || file.endsWith(".exe")) {
  22. exeMap[file] = path.join(dir, file); // JSON.stringify(path.join(dir, file));
  23. }
  24. getAllExe(path.join(dir, file));
  25. });
  26. });
  27. }
  28. function statistics(token) {
  29. let key1 = 'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment';
  30. let key2 = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion';
  31. let key3 = 'HKLM\\SOFTWARE\\Microsoft\\Cryptography';
  32. let mac = '';
  33. let os_platform = '';
  34. let os_arch = '';
  35. if (process.env.NODE_ENV == 'development') {
  36. } else {
  37. const vbsDirectory = path.join(path.dirname(app.getPath('exe')), './resources/app.asar.unpacked/bin/vbs');
  38. regedit.setExternalVBSLocation(vbsDirectory);
  39. }
  40. try{
  41. regedit.list([key1, key2, key3], function (err, result) {
  42. os_arch = result[key1]['values']['PROCESSOR_ARCHITECTURE']['value'] || '';
  43. os_platform = result[key2]['values']['ProductName']['value'] || '';
  44. if(os_arch == 'x86'){ //
  45. regedit.arch.list32([key1, key2, key3], function (err, result) {
  46. mac = result[key3]['values']['MachineGuid']['value'] + '_' + result[key2]['values']['ProductId']['value'] || '';
  47. userlog(mac, os_platform, os_arch, token)
  48. })
  49. }else{
  50. regedit.arch.list64([key1, key2, key3], function (err, result) {
  51. mac = result[key3]['values']['MachineGuid']['value'] + '_' + result[key2]['values']['ProductId']['value'] || '';
  52. userlog(mac, os_platform, os_arch, token)
  53. })
  54. }
  55. })
  56. }catch(e){
  57. //TODO handle the exception
  58. }
  59. }
  60. function userlog(mac, os_platform, os_arch, token){
  61. let params = {
  62. type: 3,
  63. soft_mid: pjson.softInfo.softMid,
  64. soft_name: pjson.softInfo.softName + pjson.version,
  65. mac: mac,
  66. os_platform: os_platform,
  67. os_arch: os_arch,
  68. os_json: ''
  69. }
  70. // 使用日志
  71. let target = 'https://www.xingyousoft.com';
  72. const agent = new https.Agent({
  73. rejectUnauthorized: false
  74. });
  75. axios.post(target + '/api/index/user_log', params, {httpsAgent: agent, headers: {'x-token': token}})
  76. .then(res=>{
  77. // console.log('user_log user_log user_log res ===========>',res);
  78. }).catch(err => {
  79. // console.log('user_log user_log user_log err ===========>',err);
  80. })
  81. }
  82. let api = {
  83. getStatistics(token){
  84. statistics(token);
  85. },
  86. getAppPath(){
  87. return new Promise((resolve, reject) => {
  88. resolve(app.getPath('exe'))
  89. });
  90. },
  91. getLoginItem(){
  92. const exeName = path.basename(process.execPath)
  93. let obj = {
  94. path: process.execPath,
  95. args: [
  96. '--processStart', `"${exeName}"`,
  97. '--process-start-args', `"--hidden"`
  98. ]
  99. };
  100. return new Promise((resolve, reject) => {
  101. resolve(app.getLoginItemSettings(obj))
  102. });
  103. },
  104. isWin32() {
  105. return process.platform == "win32";
  106. },
  107. getVersion() {
  108. return 10000;
  109. },
  110. getExeMap() {
  111. return exeMap;
  112. },
  113. getArgs() {
  114. return process.argv;
  115. },
  116. openExternal(url) {
  117. shell.openExternal(url);
  118. },
  119. // 隐藏主窗口,并创建托盘,绑定关闭事件
  120. setTray(appTray, app, mainWindow) {
  121. // 用一个 Tray 来表示一个图标,这个图标处于正在运行的系统的通知区
  122. // 通常被添加到一个 context menu 上.
  123. // 系统托盘右键菜单
  124. const trayMenuTemplate = [
  125. {
  126. label: '帮助中心',
  127. click: () => {
  128. mainWindow.webContents.send('help', true);
  129. }
  130. },
  131. {
  132. label: '软件设置',
  133. click: () => {
  134. mainWindow.show();
  135. mainWindow.webContents.send('setting', true);
  136. }
  137. },
  138. {
  139. // 系统托盘图标目录
  140. label: '退出软件',
  141. click: () => {
  142. app.quit();
  143. }
  144. }
  145. ];
  146. // 图标的上下文菜单
  147. const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
  148. // 设置托盘悬浮提示
  149. appTray.setToolTip(pjson.softInfo.softName);
  150. // 设置托盘菜单
  151. appTray.setContextMenu(contextMenu);
  152. // 单击托盘小图标显示应用
  153. appTray.on('click', () => {
  154. // 显示主程序
  155. mainWindow.setSkipTaskbar(false)
  156. mainWindow.show();
  157. });
  158. return appTray;
  159. },
  160. //#region 文件相关
  161. /**
  162. * 选择保存文件路径,返回文件路径
  163. * @param {string} [title] 默认文件名称
  164. * @param {string} [ext] 限定文件后缀
  165. * @returns {Promise<string>}
  166. */
  167. pickSaveFile(title, ext) {
  168. var win = this;
  169. return new Promise(function (resolve, reject) {
  170. var pms = dialog.showSaveDialog(
  171. win,
  172. {
  173. defaultPath: title + "-副本",
  174. nameFieldLabel: title,
  175. filters: [
  176. {
  177. name: "*",
  178. extensions: ext
  179. ? ext.split(",").filter(function (x) {
  180. return x;
  181. })
  182. : [],
  183. },
  184. ],
  185. },
  186. function (filePath) {
  187. resolve(filePath);
  188. }
  189. );
  190. if (pms && pms.then)
  191. pms.then(function (x) {
  192. resolve(x.filePath);
  193. });
  194. });
  195. },
  196. /**
  197. * https://www.electronjs.org/docs/api/dialog#dialogshowopendialogbrowserwindow-options
  198. * 选取文件,返回文件路径
  199. * @param {string} [ext] 文件后缀
  200. * @param {boolean} [multi]
  201. * @returns {Promise<string>}
  202. */
  203. pickFile(ext, multi) {
  204. var win = this;
  205. var properties = ["openFile"];
  206. multi && properties.push("multiSelections");
  207. return new Promise(function (resolve, reject) {
  208. var pms = dialog.showOpenDialog(
  209. win,
  210. {
  211. properties: properties,
  212. filters: [
  213. {
  214. name: "*",
  215. extensions: ext
  216. ? ext.split(",").filter(function (x) {
  217. return x;
  218. })
  219. : [],
  220. },
  221. ],
  222. },
  223. resolve
  224. );
  225. if (pms && pms.then)
  226. pms.then(function (data) {
  227. resolve(multi ? data.filePaths : data.filePaths && data.filePaths[0]);
  228. });
  229. });
  230. },
  231. pickDir(defaultPath) {
  232. var win = this;
  233. return new Promise(function (resolve, reject) {
  234. var pms = dialog.showOpenDialog(
  235. win,
  236. {
  237. defaultPath,
  238. properties: ["openDirectory"],
  239. },
  240. function (filePaths) {
  241. resolve(filePaths && filePaths[0]);
  242. }
  243. );
  244. if (pms && pms.then)
  245. pms.then(function (data) {
  246. resolve(data.filePaths && data.filePaths[0]);
  247. });
  248. });
  249. },
  250. /**
  251. * 文件修改时间,文件不存在返回0
  252. * @param {string} path 文件路径
  253. * @returns {number}
  254. */
  255. getFileModifyAt(path) {
  256. return new Promise(function (resolve, reject) {
  257. fs.stat(path, (err, data) => (err ? resolve(0) : resolve(data.mtimeMs)));
  258. });
  259. },
  260. /**
  261. * 读取
  262. * @param {string} path 文件路径
  263. * @param {string} [encode] 编码
  264. * @returns
  265. */
  266. readFile(path, encode) {
  267. return new Promise(function (resolve, reject) {
  268. fs.readFile(path, encode || "utf8", (err, data) => (err ? reject(err) : resolve(data)));
  269. });
  270. },
  271. /**
  272. * 写入
  273. * @param {string} path
  274. * @param {string} data
  275. * @returns
  276. */
  277. writeFile(path, data) {
  278. return new Promise(function (resolve, reject) {
  279. fs.writeFile(path, data, (err) => (err ? reject(err) : resolve()));
  280. });
  281. },
  282. readdir(path) {
  283. return new Promise(function (resolve, reject) {
  284. fs.readdir(path, function (err, files) {
  285. err ? reject(err) : resolve(files);
  286. });
  287. });
  288. },
  289. unlink(path) {
  290. return new Promise(function (resolve, reject) {
  291. fs.unlink(path, function (err, files) {
  292. err ? reject(err) : resolve(files);
  293. });
  294. });
  295. },
  296. showItemInfolder(filepath) {
  297. if (process.platform == "win32") filepath = filepath.replace(/\//g, "\\");
  298. return shell.showItemInFolder(filepath);
  299. },
  300. stat(path) {
  301. return new Promise(function (resolve, reject) {
  302. fs.stat(path, function (err, stat) {
  303. err ? reject(err) : resolve(stat);
  304. });
  305. });
  306. },
  307. mkdirs(dir) {
  308. var dirs = dir.split(/[\/\\]/);
  309. let pms = Promise.resolve();
  310. let s = "";
  311. for (var i = 0; i < dirs.length; i++) {
  312. let tmp = (s = s + (s ? "/" + dirs[i] : dirs[i]));
  313. pms = pms.then(
  314. () =>
  315. new Promise((resolve, reject) =>
  316. fs.exists(tmp, (ok) =>
  317. ok ? resolve() : fs.mkdir(tmp, (err) => (err ? reject(err) : resolve()))
  318. )
  319. )
  320. );
  321. }
  322. return pms;
  323. },
  324. //#endregion
  325. //#region 进程相关
  326. procCreate(cmds, opts) {
  327. opts = Object.assign({}, opts);
  328. var cmd = cmds[0];
  329. if (process.platform == "win32" && !cmd.endsWith(".exe")) cmd += ".exe";
  330. if (exeMap[cmd]) {
  331. cmd = exeMap[cmd];
  332. }
  333. var proc = child_process.spawn(cmd, cmds.slice(1), opts);
  334. if (opts.spawnMode) {
  335. var name = path.basename(process.argv0).slice(0, -4);
  336. if (!opts.stdout) opts.stdout = path.join(app.getPath("temp"), name + "-out" + Math.random());
  337. if (!opts.stderr) opts.stderr = path.join(app.getPath("temp"), name + "-err" + Math.random());
  338. var ws = fs.createWriteStream(opts.stdout);
  339. if (opts.stdout == opts.stderr) {
  340. proc.stdout.pipe(ws, { end: false });
  341. proc.stderr.pipe(ws, { end: false });
  342. } else {
  343. proc.stdout.pipe(ws);
  344. proc.stderr.pipe(fs.createWriteStream(opts.stderr));
  345. }
  346. var ret = {};
  347. ret.pid = proc.pid;
  348. ret.stdout = opts.stdout;
  349. ret.stderr = opts.stderr;
  350. procMap[proc.pid] = proc;
  351. proc.data = ret;
  352. proc._pms = new Promise(function (resolve, reject) {
  353. proc.on("exit", function (code) {
  354. ws.end();
  355. ret.stoped = true;
  356. code ? reject(code) : resolve(code);
  357. });
  358. });
  359. return ret;
  360. }
  361. return new Promise(function (resolve, reject) {
  362. var stdout = [];
  363. proc.stdout.on("data", function (buf) {
  364. stdout.push(buf);
  365. });
  366. var stderr = [];
  367. proc.stderr.on("data", function (buf) {
  368. stderr.push(buf);
  369. });
  370. proc.on("exit", function (code) {
  371. stdout = Buffer.concat(stdout);
  372. stderr = Buffer.concat(stderr);
  373. if (process.platform == "win32") {
  374. stdout = iconv.decode(stdout, "gbk").replace(/\r\n/g, "\n");
  375. stderr = iconv.decode(stderr, "gbk").replace(/\r\n/g, "\n");
  376. } else {
  377. stdout += "";
  378. stderr += "";
  379. }
  380. code ? reject({ code, stdout, stderr }) : resolve({ stdout, stderr });
  381. });
  382. });
  383. },
  384. procGet(pid) {
  385. var proc = procMap[pid];
  386. if (!proc) return null;
  387. ["connected", "exitCode", "killed", "signalCode", "spawnargs", "spawnfile"].forEach((k) => {
  388. proc.data[k] = proc[k];
  389. });
  390. return proc.data;
  391. },
  392. procWait(pid) {
  393. var proc = procMap[pid];
  394. if (!proc) return Promise.reject("not found proc:" + pid);
  395. return proc._pms;
  396. },
  397. procWrite(pid, base64) {
  398. var proc = procMap[pid];
  399. if (proc) {
  400. proc.stdin.write(Buffer.from(base64, "base64"));
  401. return true;
  402. }
  403. return false;
  404. },
  405. procKill(pid, code) {
  406. var proc = procMap[pid];
  407. if (proc) {
  408. code == null ? proc.kill() : proc.kill(code);
  409. delete procMap[pid];
  410. return true;
  411. }
  412. return false;
  413. },
  414. procList() {
  415. var list = [];
  416. for (var k in procMap) {
  417. list.push(api.procGet(k));
  418. }
  419. return list;
  420. },
  421. exec(cmds, opts) {
  422. // console.log('=======exec', cmds, opts);
  423. if (typeof cmds == "string") cmds = cmds.split(" ");
  424. var cmd = cmds[0];
  425. if (process.platform == "win32" && !cmd.endsWith(".exe")) cmd += ".exe";
  426. if (exeMap[cmd]) {
  427. cmds[0] = JSON.stringify(exeMap[cmd]);
  428. }
  429. return new Promise(function (resolve, reject) {
  430. child_process.exec(
  431. cmds.join(" "),
  432. Object.assign({ encoding: "buffer" }, opts),
  433. function (err, stdout, stderr) {
  434. if (process.platform == "win32") {
  435. stdout = iconv.decode(stdout, "gbk").replace(/\r\n/g, "\n");
  436. stderr = iconv.decode(stderr, "gbk").replace(/\r\n/g, "\n");
  437. } else {
  438. stdout += "";
  439. stderr += "";
  440. }
  441. err ? reject({ err, stdout, stderr }) : resolve({ stdout, stderr });
  442. }
  443. );
  444. });
  445. },
  446. //#endregion
  447. eval(code) {
  448. var c = {};
  449. var win = this;
  450. Object.keys(console).forEach((k) => {
  451. c[k] = function () {
  452. console[k].apply(console, arguments);
  453. try {
  454. var args = Array.from(arguments);
  455. args.unshift(k);
  456. win.webContents.send("console", args);
  457. } catch (error) { }
  458. };
  459. });
  460. return new Function("require", "console", code).call(this, require, c);
  461. },
  462. };
  463. export default api;