123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483 |
- import pjson from '/package.json'
- const axios = require('axios');
- const https = require('https');
- const path = require("path");
- const fs = require("fs");
- const os = require("os");
- const regedit = require('regedit');
- const child_process = require("child_process");
- const { app, dialog, shell, Menu, net, ipcMain } = require("electron");
- var exeMap = {};
- var procMap = {};
- if (process.env.NODE_ENV == 'development') {
- getAllExe(path.join(__dirname, "../../bin"));
- } else {
- getAllExe(path.join(__dirname, "../../../app.asar.unpacked/bin"));
- }
- function getAllExe(dir) {
- fs.readdir(dir, function (err, files) {
- if (err) return;
- files.forEach(function (file) {
- if (process.platform != "win32" || file.endsWith(".exe")) {
- exeMap[file] = path.join(dir, file); // JSON.stringify(path.join(dir, file));
- }
- getAllExe(path.join(dir, file));
- });
- });
- }
- function statistics(token) {
- let key1 = 'HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment';
- let key2 = 'HKLM\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion';
- let key3 = 'HKLM\\SOFTWARE\\Microsoft\\Cryptography';
- let mac = '';
- let os_platform = '';
- let os_arch = '';
- if (process.env.NODE_ENV == 'development') {
- } else {
- const vbsDirectory = path.join(path.dirname(app.getPath('exe')), './resources/app.asar.unpacked/bin/vbs');
- regedit.setExternalVBSLocation(vbsDirectory);
- }
-
- try{
- regedit.list([key1, key2, key3], function (err, result) {
- os_arch = result[key1]['values']['PROCESSOR_ARCHITECTURE']['value'] || '';
- os_platform = result[key2]['values']['ProductName']['value'] || '';
-
- if(os_arch == 'x86'){ //
- regedit.arch.list32([key1, key2, key3], function (err, result) {
- mac = result[key3]['values']['MachineGuid']['value'] + '_' + result[key2]['values']['ProductId']['value'] || '';
- userlog(mac, os_platform, os_arch, token)
- })
- }else{
- regedit.arch.list64([key1, key2, key3], function (err, result) {
- mac = result[key3]['values']['MachineGuid']['value'] + '_' + result[key2]['values']['ProductId']['value'] || '';
- userlog(mac, os_platform, os_arch, token)
- })
- }
- })
- }catch(e){
- //TODO handle the exception
- }
- }
- function userlog(mac, os_platform, os_arch, token){
- let params = {
- type: 3,
- soft_mid: pjson.softInfo.softMid,
- soft_name: pjson.softInfo.softName + pjson.version,
- mac: mac,
- os_platform: os_platform,
- os_arch: os_arch,
- os_json: ''
- }
- // 使用日志
- let target = 'https://www.xingyousoft.com';
- const agent = new https.Agent({
- rejectUnauthorized: false
- });
- axios.post(target + '/api/index/user_log', params, {httpsAgent: agent, headers: {'x-token': token}})
- .then(res=>{
- // console.log('user_log user_log user_log res ===========>',res);
- }).catch(err => {
- // console.log('user_log user_log user_log err ===========>',err);
- })
- }
- let api = {
- getStatistics(token){
- statistics(token);
- },
- getAppPath(){
- return new Promise((resolve, reject) => {
- resolve(app.getPath('exe'))
- });
- },
- getLoginItem(){
- const exeName = path.basename(process.execPath)
- let obj = {
- path: process.execPath,
- args: [
- '--processStart', `"${exeName}"`,
- '--process-start-args', `"--hidden"`
- ]
- };
- return new Promise((resolve, reject) => {
- resolve(app.getLoginItemSettings(obj))
- });
- },
- isWin32() {
- return process.platform == "win32";
- },
- getVersion() {
- return 10000;
- },
- getExeMap() {
- return exeMap;
- },
- getArgs() {
- return process.argv;
- },
- openExternal(url) {
- shell.openExternal(url);
- },
- // 隐藏主窗口,并创建托盘,绑定关闭事件
- setTray(appTray, app, mainWindow) {
- // 用一个 Tray 来表示一个图标,这个图标处于正在运行的系统的通知区
- // 通常被添加到一个 context menu 上.
- // 系统托盘右键菜单
- const trayMenuTemplate = [
- {
- label: '帮助中心',
- click: () => {
- mainWindow.webContents.send('help', true);
- }
- },
- {
- label: '软件设置',
- click: () => {
-
- mainWindow.show();
- mainWindow.webContents.send('setting', true);
- }
- },
- {
- // 系统托盘图标目录
- label: '退出软件',
- click: () => {
- app.quit();
- }
- }
- ];
- // 图标的上下文菜单
- const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
- // 设置托盘悬浮提示
- appTray.setToolTip(pjson.softInfo.softName);
- // 设置托盘菜单
- appTray.setContextMenu(contextMenu);
- // 单击托盘小图标显示应用
- appTray.on('click', () => {
- // 显示主程序
- mainWindow.setSkipTaskbar(false)
- mainWindow.show();
- });
- return appTray;
- },
- //#region 文件相关
- /**
- * 选择保存文件路径,返回文件路径
- * @param {string} [title] 默认文件名称
- * @param {string} [ext] 限定文件后缀
- * @returns {Promise<string>}
- */
- pickSaveFile(title, ext) {
- var win = this;
- return new Promise(function (resolve, reject) {
- var pms = dialog.showSaveDialog(
- win,
- {
- defaultPath: title + "-副本",
- nameFieldLabel: title,
- filters: [
- {
- name: "*",
- extensions: ext
- ? ext.split(",").filter(function (x) {
- return x;
- })
- : [],
- },
- ],
- },
- function (filePath) {
- resolve(filePath);
- }
- );
- if (pms && pms.then)
- pms.then(function (x) {
- resolve(x.filePath);
- });
- });
- },
- /**
- * https://www.electronjs.org/docs/api/dialog#dialogshowopendialogbrowserwindow-options
- * 选取文件,返回文件路径
- * @param {string} [ext] 文件后缀
- * @param {boolean} [multi]
- * @returns {Promise<string>}
- */
- pickFile(ext, multi) {
- var win = this;
- var properties = ["openFile"];
- multi && properties.push("multiSelections");
- return new Promise(function (resolve, reject) {
- var pms = dialog.showOpenDialog(
- win,
- {
- properties: properties,
- filters: [
- {
- name: "*",
- extensions: ext
- ? ext.split(",").filter(function (x) {
- return x;
- })
- : [],
- },
- ],
- },
- resolve
- );
- if (pms && pms.then)
- pms.then(function (data) {
- resolve(multi ? data.filePaths : data.filePaths && data.filePaths[0]);
- });
- });
- },
- pickDir(defaultPath) {
- var win = this;
- return new Promise(function (resolve, reject) {
- var pms = dialog.showOpenDialog(
- win,
- {
- defaultPath,
- properties: ["openDirectory"],
- },
- function (filePaths) {
- resolve(filePaths && filePaths[0]);
- }
- );
- if (pms && pms.then)
- pms.then(function (data) {
- resolve(data.filePaths && data.filePaths[0]);
- });
- });
- },
- /**
- * 文件修改时间,文件不存在返回0
- * @param {string} path 文件路径
- * @returns {number}
- */
- getFileModifyAt(path) {
- return new Promise(function (resolve, reject) {
- fs.stat(path, (err, data) => (err ? resolve(0) : resolve(data.mtimeMs)));
- });
- },
- /**
- * 读取
- * @param {string} path 文件路径
- * @param {string} [encode] 编码
- * @returns
- */
- readFile(path, encode) {
- return new Promise(function (resolve, reject) {
- fs.readFile(path, encode || "utf8", (err, data) => (err ? reject(err) : resolve(data)));
- });
- },
- /**
- * 写入
- * @param {string} path
- * @param {string} data
- * @returns
- */
- writeFile(path, data) {
- return new Promise(function (resolve, reject) {
- fs.writeFile(path, data, (err) => (err ? reject(err) : resolve()));
- });
- },
- readdir(path) {
- return new Promise(function (resolve, reject) {
- fs.readdir(path, function (err, files) {
- err ? reject(err) : resolve(files);
- });
- });
- },
- unlink(path) {
- return new Promise(function (resolve, reject) {
- fs.unlink(path, function (err, files) {
- err ? reject(err) : resolve(files);
- });
- });
- },
- showItemInfolder(filepath) {
- if (process.platform == "win32") filepath = filepath.replace(/\//g, "\\");
- return shell.showItemInFolder(filepath);
- },
- stat(path) {
- return new Promise(function (resolve, reject) {
- fs.stat(path, function (err, stat) {
- err ? reject(err) : resolve(stat);
- });
- });
- },
- mkdirs(dir) {
- var dirs = dir.split(/[\/\\]/);
- let pms = Promise.resolve();
- let s = "";
- for (var i = 0; i < dirs.length; i++) {
- let tmp = (s = s + (s ? "/" + dirs[i] : dirs[i]));
- pms = pms.then(
- () =>
- new Promise((resolve, reject) =>
- fs.exists(tmp, (ok) =>
- ok ? resolve() : fs.mkdir(tmp, (err) => (err ? reject(err) : resolve()))
- )
- )
- );
- }
- return pms;
- },
- //#endregion
- //#region 进程相关
- procCreate(cmds, opts) {
- opts = Object.assign({}, opts);
- var cmd = cmds[0];
- if (process.platform == "win32" && !cmd.endsWith(".exe")) cmd += ".exe";
- if (exeMap[cmd]) {
- cmd = exeMap[cmd];
- }
- var proc = child_process.spawn(cmd, cmds.slice(1), opts);
- if (opts.spawnMode) {
- var name = path.basename(process.argv0).slice(0, -4);
- if (!opts.stdout) opts.stdout = path.join(app.getPath("temp"), name + "-out" + Math.random());
- if (!opts.stderr) opts.stderr = path.join(app.getPath("temp"), name + "-err" + Math.random());
- var ws = fs.createWriteStream(opts.stdout);
- if (opts.stdout == opts.stderr) {
- proc.stdout.pipe(ws, { end: false });
- proc.stderr.pipe(ws, { end: false });
- } else {
- proc.stdout.pipe(ws);
- proc.stderr.pipe(fs.createWriteStream(opts.stderr));
- }
- var ret = {};
- ret.pid = proc.pid;
- ret.stdout = opts.stdout;
- ret.stderr = opts.stderr;
- procMap[proc.pid] = proc;
- proc.data = ret;
- proc._pms = new Promise(function (resolve, reject) {
- proc.on("exit", function (code) {
- ws.end();
- ret.stoped = true;
- code ? reject(code) : resolve(code);
- });
- });
- return ret;
- }
- return new Promise(function (resolve, reject) {
- var stdout = [];
- proc.stdout.on("data", function (buf) {
- stdout.push(buf);
- });
- var stderr = [];
- proc.stderr.on("data", function (buf) {
- stderr.push(buf);
- });
- proc.on("exit", function (code) {
- stdout = Buffer.concat(stdout);
- stderr = Buffer.concat(stderr);
- if (process.platform == "win32") {
- stdout = iconv.decode(stdout, "gbk").replace(/\r\n/g, "\n");
- stderr = iconv.decode(stderr, "gbk").replace(/\r\n/g, "\n");
- } else {
- stdout += "";
- stderr += "";
- }
- code ? reject({ code, stdout, stderr }) : resolve({ stdout, stderr });
- });
- });
- },
- procGet(pid) {
- var proc = procMap[pid];
- if (!proc) return null;
- ["connected", "exitCode", "killed", "signalCode", "spawnargs", "spawnfile"].forEach((k) => {
- proc.data[k] = proc[k];
- });
- return proc.data;
- },
- procWait(pid) {
- var proc = procMap[pid];
- if (!proc) return Promise.reject("not found proc:" + pid);
- return proc._pms;
- },
- procWrite(pid, base64) {
- var proc = procMap[pid];
- if (proc) {
- proc.stdin.write(Buffer.from(base64, "base64"));
- return true;
- }
- return false;
- },
- procKill(pid, code) {
- var proc = procMap[pid];
- if (proc) {
- code == null ? proc.kill() : proc.kill(code);
- delete procMap[pid];
- return true;
- }
- return false;
- },
- procList() {
- var list = [];
- for (var k in procMap) {
- list.push(api.procGet(k));
- }
- return list;
- },
- exec(cmds, opts) {
- // console.log('=======exec', cmds, opts);
- if (typeof cmds == "string") cmds = cmds.split(" ");
- var cmd = cmds[0];
- if (process.platform == "win32" && !cmd.endsWith(".exe")) cmd += ".exe";
- if (exeMap[cmd]) {
- cmds[0] = JSON.stringify(exeMap[cmd]);
- }
- return new Promise(function (resolve, reject) {
- child_process.exec(
- cmds.join(" "),
- Object.assign({ encoding: "buffer" }, opts),
- function (err, stdout, stderr) {
- if (process.platform == "win32") {
- stdout = iconv.decode(stdout, "gbk").replace(/\r\n/g, "\n");
- stderr = iconv.decode(stderr, "gbk").replace(/\r\n/g, "\n");
- } else {
- stdout += "";
- stderr += "";
- }
- err ? reject({ err, stdout, stderr }) : resolve({ stdout, stderr });
- }
- );
- });
- },
- //#endregion
- eval(code) {
- var c = {};
- var win = this;
- Object.keys(console).forEach((k) => {
- c[k] = function () {
- console[k].apply(console, arguments);
- try {
- var args = Array.from(arguments);
- args.unshift(k);
- win.webContents.send("console", args);
- } catch (error) { }
- };
- });
- return new Function("require", "console", code).call(this, require, c);
- },
- };
- export default api;
|