From 42415af3477861abc87806fa36f45a1b929194c8 Mon Sep 17 00:00:00 2001 From: gaoshuaixing Date: Mon, 21 Feb 2022 19:11:37 +0800 Subject: [PATCH] chromeExtension --- app/controller/example.js | 2 +- electron/controller/example.js | 25 +++- electron/lib/api.js | 117 ------------------ electron/lib/autoLaunch.js | 28 ----- electron/lib/autoUpdater.js | 67 ----------- electron/lib/awaken.js | 57 --------- electron/lib/chromeExtension.js | 83 ------------- electron/lib/constant.js | 10 -- electron/lib/crashReport.js | 13 -- electron/lib/eLogger.js | 39 ------ electron/lib/helper.js | 52 -------- electron/lib/ipcMain.js | 56 --------- electron/lib/lanucher.js | 69 ----------- electron/lib/security.js | 22 ---- electron/lib/shortcut.js | 54 --------- electron/lib/storage.js | 125 -------------------- electron/lib/tray.js | 63 ---------- electron/library/chromeExtension.js | 2 +- frontend/src/views/base/extension/Index.vue | 9 +- package.json | 3 +- 20 files changed, 30 insertions(+), 866 deletions(-) delete mode 100644 electron/lib/api.js delete mode 100644 electron/lib/autoLaunch.js delete mode 100644 electron/lib/autoUpdater.js delete mode 100644 electron/lib/awaken.js delete mode 100644 electron/lib/chromeExtension.js delete mode 100644 electron/lib/constant.js delete mode 100644 electron/lib/crashReport.js delete mode 100644 electron/lib/eLogger.js delete mode 100644 electron/lib/helper.js delete mode 100644 electron/lib/ipcMain.js delete mode 100644 electron/lib/lanucher.js delete mode 100644 electron/lib/security.js delete mode 100644 electron/lib/shortcut.js delete mode 100644 electron/lib/storage.js delete mode 100644 electron/lib/tray.js diff --git a/app/controller/example.js b/app/controller/example.js index 42216d2..2af9e08 100644 --- a/app/controller/example.js +++ b/app/controller/example.js @@ -60,7 +60,7 @@ class ExampleController extends BaseController { const self = this; const { ctx, service } = this; const data = {}; - let tmpDir = service.storage.getStorageDir(); + let tmpDir = Utils.getLogDir(); const file = ctx.request.files[0]; this.app.logger.info('file:', file); diff --git a/electron/controller/example.js b/electron/controller/example.js index d575ee1..4f92957 100644 --- a/electron/controller/example.js +++ b/electron/controller/example.js @@ -3,9 +3,11 @@ const _ = require('lodash'); const path = require('path'); const is = require('electron-is'); +const unzip = require("unzip-crx-3"); const Controller = require('ee-core').Controller; const electronApp = require('electron').app; const {dialog, webContents, shell, BrowserWindow, BrowserView, Notification, powerMonitor, screen, nativeTheme} = require('electron'); +const chromeExtension = require('../library/chromeExtension'); let myTimer = null; let browserViewObj = null; @@ -19,7 +21,7 @@ class ExampleController extends Controller { /** * 所有方法接收两个参数 - * args 前端传的参数 + * @param args 前端 或 egg,传的参数(单个参数,或参数数组) * @param event - IpcMainEvent 文档:https://www.electronjs.org/docs/latest/api/structures/ipc-main-event */ @@ -203,6 +205,27 @@ class ExampleController extends Controller { winObj.loadURL(content); return winObj.id + } + + /** + * 加载扩展程序 + */ + async loadExtension (args) { + const crxFile = args[0]; + if (_.isEmpty(crxFile)) { + return false; + } + const extensionId = path.basename(crxFile, '.crx'); + const chromeExtensionDir = chromeExtension.getDirectory(); + const extensionDir = path.join(chromeExtensionDir, extensionId); + + console.log("[api] [example] [loadExtension] extension id:", extensionId); + unzip(crxFile, extensionDir).then(() => { + console.log("[api] [example] [loadExtension] unzip success!"); + chromeExtension.load(extensionId); + }); + + return true; } } diff --git a/electron/lib/api.js b/electron/lib/api.js deleted file mode 100644 index 28595b8..0000000 --- a/electron/lib/api.js +++ /dev/null @@ -1,117 +0,0 @@ -'use strict'; - -const fs = require('fs'); -const http = require('http'); -const path = require('path'); -const _ = require('lodash'); -const storage = require('./storage'); -const socketIo = require('socket.io'); -const eLogger = require('./eLogger').get(); - -const apis = {}; - -/** - * 安装模块 - */ -exports.setup = async function () { - console.log('[electron-lib-api] [setup]'); - setApi(); - - // use api server - let port = await storage.setIpcDynamicPort(); - eLogger.info('[api] [setup] dynamic ipc port:', port); - const listen = 'localhost'; - port = port ? port : 7069; - - const server = http.createServer(function(req, res) { - eLogger.info('[api] [setup] command received', { method: req.method, url: req.url }); - if ((req.method === 'POST' && req.url === '/send')) { - let body = ''; - req.setEncoding('utf8'); - req - .on('data', function(data) { - body += data; - }) - .on('end', function() { - let message; - try { - message = JSON.parse(body); - } catch (e) { - res.statusCode = 400; - return res.end('request body parse failure.'); - } - if (!apis[message.cmd]) { - eLogger.info('[api] [setup] invalid command called:', message.cmd); - res.statusCode = 404; - return res.end('NG'); - } - - eLogger.info('[api] [setup] command received message:', message); - const data = apis[message.cmd](...message.params); - res.statusCode = 200; - const result = { - err: null, - data: data, - }; - res.end(JSON.stringify(result)); - }); - } else { - res.statusCode = 404; - res.end('NOT FOUND'); - } - }); - - // socket io - const io = socketIo(server); - io.on('connection', (socket) => { - socket.on('ipc', (message, callback) => { - eLogger.info('[api] [setup] socket id:' + socket.id + ' message cmd: ' + message.cmd); - const data = apis[message.cmd](...message.params); - if (data && typeof data.then === 'function') { // 判断是否是异步 - data.then((data) => { - const result = { - err: null, - data: data, - }; - callback(result) - }); - } else { - const result = { - err: null, - data: data, - }; - callback(result); - } - }); - }); - - server.listen(port, listen, function() { - eLogger.info('[api] [setup] server is listening on', `${listen}:${port}`); - }); - - return true; -}; - -function setApi() { - const apiDir = path.normalize(__dirname + '/../apis'); - fs.readdirSync(apiDir).forEach(function(filename) { - if (path.extname(filename) === '.js' && filename !== 'index.js') { - const name = path.basename(filename, '.js'); - const fileObj = require(`../apis/${filename}`); - _.map(fileObj, function(fn, method) { - let methodName = getApiName(name, method); - apis[methodName] = fn; - }); - } - }); -}; - -/** - * get api method name - * ex.) jsname='user' method='get' => 'user.get' - * @param {String} jsname - * @param {String} method - */ -function getApiName (jsname, method) { - return jsname + '.' + method; -} diff --git a/electron/lib/autoLaunch.js b/electron/lib/autoLaunch.js deleted file mode 100644 index 36fba34..0000000 --- a/electron/lib/autoLaunch.js +++ /dev/null @@ -1,28 +0,0 @@ -const { app } = require('electron'); -const { LOGIN_SETTING_OPTIONS } = require('./constant').AutoLaunch; - -class AutoLaunch { - enable () { - const enabled = app.getLoginItemSettings(LOGIN_SETTING_OPTIONS).openAtLogin; - if (enabled) { - return true; - } - app.setLoginItemSettings({ - ...LOGIN_SETTING_OPTIONS, - openAtLogin: true - }) - return true; - } - - disable () { - app.setLoginItemSettings({ openAtLogin: false }) - return true; - } - - isEnabled () { - const enabled = app.getLoginItemSettings(LOGIN_SETTING_OPTIONS).openAtLogin; - return enabled; - } -} - -module.exports = AutoLaunch; \ No newline at end of file diff --git a/electron/lib/autoUpdater.js b/electron/lib/autoUpdater.js deleted file mode 100644 index 848300b..0000000 --- a/electron/lib/autoUpdater.js +++ /dev/null @@ -1,67 +0,0 @@ -'use strict'; - -const updater = require("electron-updater"); -const autoUpdater = updater.autoUpdater; -const config = require('../config'); -const {app} = require('electron'); -const eLogger = require('./eLogger').get(); -const helper = require('./helper'); - -/** - * 安装模块 - */ -exports.setup = function () { - console.log('[electron-lib-autoUpater] [setup]'); - const version = app.getVersion(); - eLogger.info('[autoUpdater] [setup] current version: ', version); - const platformObj = helper.getPlatform(); - - const updateConfig = config.get('autoUpdate'); - let server = updateConfig.options.url; - server = `${server}${platformObj.platform}/`; - eLogger.info('[autoUpdater] [setup] server: ', server); - updateConfig.options.url = server; - - try { - autoUpdater.setFeedURL(updateConfig.options); - } catch (error) { - eLogger.error('[autoUpdater] [setup] setFeedURL error : ', error); - } - - autoUpdater.on('checking-for-update', () => { - sendStatusToWindow('Checking for update...'); - }) - autoUpdater.on('update-available', (info) => { - sendStatusToWindow('Update available.'); - }) - autoUpdater.on('update-not-available', (info) => { - sendStatusToWindow('Update not available.'); - }) - autoUpdater.on('error', (err) => { - sendStatusToWindow('Error in auto-updater. ' + err); - }) - autoUpdater.on('download-progress', (progressObj) => { - let log_message = "Download speed: " + progressObj.bytesPerSecond; - log_message = log_message + ' - Downloaded ' + progressObj.percent + '%'; - log_message = log_message + ' (' + progressObj.transferred + "/" + progressObj.total + ')'; - sendStatusToWindow(log_message); - }) - autoUpdater.on('update-downloaded', (info) => { - sendStatusToWindow('Update downloaded'); - // quit and update - helper.appQuit(); - autoUpdater.quitAndInstall(); - }); - -}; - -exports.checkUpdate = function () { - autoUpdater.checkForUpdatesAndNotify(); -} - -function sendStatusToWindow(text) { - eLogger.info(text); - MAIN_WINDOW.webContents.send('message', text); -} - -exports = module.exports; \ No newline at end of file diff --git a/electron/lib/awaken.js b/electron/lib/awaken.js deleted file mode 100644 index 52b16ee..0000000 --- a/electron/lib/awaken.js +++ /dev/null @@ -1,57 +0,0 @@ -'use strict'; - -const { app } = require('electron'); -const config = require('../config'); -const eLogger = require('./eLogger').get(); - -/** - * 唤起Electron应用 - */ -exports.setup = function () { - console.log('[electron-lib-awaken] [setup]'); - const protocolInfo = config.get('awakeProtocol'); - const PROTOCOL = protocolInfo.protocol; - - // 唤醒的协议详情,开发者可根据所带参数,开发额外功能 - let awakeUrlInfo = {} - - app.setAsDefaultProtocolClient(PROTOCOL); - - handleArgv(process.argv); - - app.on('second-instance', (event, argv) => { - if (process.platform === 'win32') { - handleArgv(argv) - } - }) - - // 仅用于macOS - app.on('open-url', (event, urlStr) => { - handleUrl(urlStr) - }) - - // 参数处理 - function handleArgv(argv) { - const offset = app.isPackaged ? 1 : 2; - const url = argv.find((arg, i) => i >= offset && arg.startsWith(PROTOCOL)); - handleUrl(url) - } - - // url解析 - function handleUrl(awakeUrlStr) { - eLogger.info('[awaken] [handleUrl] url:', awakeUrlStr); - if (!awakeUrlStr || awakeUrlStr.length === 0) { - return - } - const {hostname, pathname, search} = new URL(awakeUrlStr); - awakeUrlInfo = { - urlStr: awakeUrlStr, - urlHost: hostname, - urlPath: pathname, - urlParams: search && search.slice(1) - } - eLogger.info('[awaken] [handleUrl] awakeUrlInfo:', awakeUrlInfo); - } -} - -exports = module.exports; \ No newline at end of file diff --git a/electron/lib/chromeExtension.js b/electron/lib/chromeExtension.js deleted file mode 100644 index b4b0e45..0000000 --- a/electron/lib/chromeExtension.js +++ /dev/null @@ -1,83 +0,0 @@ -'use strict'; - -const { app, session } = require('electron'); -const _ = require('lodash'); -const fs = require('fs'); -const path = require('path') -const eLogger = require('./eLogger').get(); - -/** - * 安装模块 - */ -exports.setup = async function () { - console.log('[electron-lib-chromeExtension] [setup]'); - const extensionIds = this.getAllIds(); - - for (let i = 0; i < extensionIds.length; i++) { - await this.load(extensionIds[i]); - } -} - -/** - * 获取扩展id列表(crx解压后的目录名,即是该扩展的id) - */ -exports.getAllIds = function () { - const extendsionDir = this.getDirectory(); - const ids = getDirs(extendsionDir); - - return ids; -} - -/** - * 扩展所在目录 - */ -exports.getDirectory = function () { - let extensionDirPath = ''; - let variablePath = 'build'; // 打包前路径 - if (app.isPackaged) { - variablePath = '..'; // 打包后路径 - } - extensionDirPath = path.join(app.getAppPath(), variablePath, "extraResources", "chromeExtension"); - - return extensionDirPath; -} - -/** - * 加载扩展 - */ -exports.load = async function (extensionId = '') { - if (_.isEmpty(extensionId)) { - return false - } - - try { - const extensionPath = path.join(this.getDirectory(), extensionId); - console.log('[chromeExtension] [load] extensionPath:', extensionPath); - await session.defaultSession.loadExtension(extensionPath, { allowFileAccess: true }); - } catch (e) { - eLogger.error('[chromeExtension] [load] load extension error extensionId:%s, errorInfo:%s', extensionId, e.toString()); - return false - } - - return true -} - -/* - * 获取目录下所有文件夹 - */ -function getDirs(dir) { - if (!dir) { - return []; - } - - const components = []; - const files = fs.readdirSync(dir); - files.forEach(function(item, index) { - const stat = fs.lstatSync(dir + '/' + item); - if (stat.isDirectory() === true) { - components.push(item); - } - }); - - return components; -}; \ No newline at end of file diff --git a/electron/lib/constant.js b/electron/lib/constant.js deleted file mode 100644 index 0d9fdab..0000000 --- a/electron/lib/constant.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - AutoLaunch: { - LOGIN_SETTING_OPTIONS: { - // For Windows - args: [ - '--opened-at-login=1' - ] - } - }, -}; \ No newline at end of file diff --git a/electron/lib/crashReport.js b/electron/lib/crashReport.js deleted file mode 100644 index a286857..0000000 --- a/electron/lib/crashReport.js +++ /dev/null @@ -1,13 +0,0 @@ -'use strict'; - -const { crashReporter } = require('electron'); -const config = require('../config'); - -/** - * 安装模块 - */ -exports.setup = function () { - console.log('[electron-lib-crashReport] [setup]'); - const options = config.get('crashReport'); - crashReporter.start(options); -} \ No newline at end of file diff --git a/electron/lib/eLogger.js b/electron/lib/eLogger.js deleted file mode 100644 index 431619c..0000000 --- a/electron/lib/eLogger.js +++ /dev/null @@ -1,39 +0,0 @@ -const eLog = require('electron-log'); -const config = require('../config'); - -class Log { - constructor () { - if (typeof Log.instance === 'object') { - return Log.instance; - } - - let logConfig = config.get('log'); - for (let transport in logConfig) { - const configInfo = logConfig[transport]; - if (transport === 'file') { - eLog.transports.file.level = configInfo.level; - eLog.transports.file.file = configInfo.fileName; - eLog.transports.file.fileName = configInfo.fileName; - eLog.transports.file.format = configInfo.format; - eLog.transports.file.maxSize = configInfo.maxSize; - } - } - Log.instance = eLog; - - return Log.instance; - } -} - -/** - * 安装模块 - */ -exports.setup = function () { - console.log('[electron-lib-eLogger] [setup]'); - return new Log(); -} - -exports.get = function () { - return new Log(); -} - -exports = module.exports; \ No newline at end of file diff --git a/electron/lib/helper.js b/electron/lib/helper.js deleted file mode 100644 index 1c26158..0000000 --- a/electron/lib/helper.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -const is = require('electron-is'); -const { app } = require('electron'); - -/** - * application quit - * - * @return {undefined} - */ -exports.appQuit = function () { - MAIN_WINDOW.destroy(); - app.quit(); -} - -/** - * get Platform - * - * @return {Object} - */ -exports.getPlatform = function () { - let platform = null; - let arch = null; - if (is.windows()) { - platform = 'windows'; - } else if (is.macOS()) { - platform = 'macOS'; - } else if (is.linux()) { - platform = 'linux'; - } else { - platform = 'other'; - } - - if (is.x86()) { - arch = '32'; - } else if (is.x64()) { - arch = '64'; - } else if (process.arch == 'arm') { - arch = 'arm32'; - } else if (process.arch == 'arm64') { - arch = 'arm64'; - } else { - arch = 'other'; - } - - const platfromObj = { - platform: platform, - arch: arch - }; - - return platfromObj; -} \ No newline at end of file diff --git a/electron/lib/ipcMain.js b/electron/lib/ipcMain.js deleted file mode 100644 index 7ee60b7..0000000 --- a/electron/lib/ipcMain.js +++ /dev/null @@ -1,56 +0,0 @@ -const { ipcMain: ipc } = require('electron') -const path = require('path') -const fs = require('fs') -const _ = require('lodash'); - -/** - * 发送响应信息给渲染进程 - * @param event - * @param channel - * @param data - * @private - */ -const _echo = (event, channel, data) => { - console.log('[ipc] [answerRenderer] result: ', {channel, data}) - event.reply(`${channel}`, data) -} - -/** - * 执行主进程函数,并响应渲染进程 - * @param channel - * @param callback - */ -const answerRenderer = (channel, callback) => { - ipc.on(channel, async (event, param) => { - const result = await callback(event, channel, param) - _echo(event, channel, result) - }) -} - -/** - * get api method name - * ex.) jsname='user' method='get' => 'user.get' - * @param {String} jsname - * @param {String} method - */ -const getApiName = (jsname, method) => { - return jsname + '.' + method; -} - -/** - * 加载所有的主程序 - */ -exports.setup = () => { - console.log('[electron-lib-ipc] [setup]'); - const ipcDir = path.normalize(__dirname + '/../ipc'); - fs.readdirSync(ipcDir).forEach(function (filename) { - if (path.extname(filename) === '.js' && filename !== 'index.js') { - const name = path.basename(filename, '.js'); - const fileObj = require(`../ipc/${filename}`); - _.map(fileObj, function(fn, method) { - let methodName = getApiName(name, method); - answerRenderer(methodName, fn); - }); - } - }) -} diff --git a/electron/lib/lanucher.js b/electron/lib/lanucher.js deleted file mode 100644 index 513f5d8..0000000 --- a/electron/lib/lanucher.js +++ /dev/null @@ -1,69 +0,0 @@ -'use strict'; - -const path = require('path'); -const startCluster = require('egg-cluster').startCluster; -const {app} = require('electron'); - -exports = module.exports; - -/** - * egg server start - * - * @param {Object} argv - * @return {Promise} - */ -exports.start = function (argv) { - const { env } = process; - - let baseDir = app.getAppPath(); - argv.baseDir = baseDir; - argv.framework = path.join(baseDir, 'node_modules/egg'); - - const appName = app.getName(); - argv.title = argv.title || `egg-server-${appName}`; - - // normalize env - env.HOME = baseDir; - env.NODE_ENV = 'production'; - - // it makes env big but more robust - env.PATH = env.Path = [ - // for nodeinstall - path.join(baseDir, 'node_modules/.bin'), - // support `.node/bin`, due to npm5 will remove `node_modules/.bin` - path.join(baseDir, '.node/bin'), - // adjust env for win - env.PATH || env.Path, - ].filter(x => !!x).join(path.delimiter); - - // for alinode - env.ENABLE_NODE_LOG = 'YES'; - env.NODE_LOG_DIR = env.NODE_LOG_DIR || path.join(baseDir, 'logs/alinode'); - - // cli argv -> process.env.EGG_SERVER_ENV -> `undefined` then egg will use `prod` - if (argv.env) { - // if undefined, should not pass key due to `spwan`, https://github.com/nodejs/node/blob/master/lib/child_process.js#L470 - env.EGG_SERVER_ENV = argv.env; - } - - // remove unused properties from stringify, alias had been remove by `removeAlias` - const ignoreKeys = [ '_', '$0', 'env', 'daemon', 'stdout', 'stderr', 'timeout', 'ignore-stderr', 'node' ]; - const clusterOptions = stringify(argv, ignoreKeys); - const options = JSON.parse(clusterOptions); - // console.log('[lanucher] options:', options) - return new Promise((resolve, reject) => { - startCluster(options, function(){ - resolve('success'); - }); - }); -}; - -function stringify(obj, ignore) { - const result = {}; - Object.keys(obj).forEach(key => { - if (!ignore.includes(key)) { - result[key] = obj[key]; - } - }); - return JSON.stringify(result); -} \ No newline at end of file diff --git a/electron/lib/security.js b/electron/lib/security.js deleted file mode 100644 index fb118ec..0000000 --- a/electron/lib/security.js +++ /dev/null @@ -1,22 +0,0 @@ -'use strict'; - -const helper = require('./helper'); -const eLogger = require('./eLogger').get(); - -/** - * 安装模块 - */ -exports.setup = function () { - console.log('[electron-lib-security] [setup]'); - const runWithDebug = process.argv.find(function(e){ - let isHasDebug = e.includes("--inspect") || e.includes("--inspect-brk") || e.includes("--remote-debugging-port"); - return isHasDebug; - }) - - if (runWithDebug) { - eLogger.info('[security] [setup] runWithDebug:', runWithDebug); - helper.appQuit(); - } -} - -exports = module.exports; \ No newline at end of file diff --git a/electron/lib/shortcut.js b/electron/lib/shortcut.js deleted file mode 100644 index b263e2c..0000000 --- a/electron/lib/shortcut.js +++ /dev/null @@ -1,54 +0,0 @@ -'use strict'; - -const { globalShortcut } = require('electron'); -const storage = require('./storage'); - -/** - * 安装模块 - */ -exports.setup = function () { - // default - console.log('[electron-lib-shortcut] [setup]'); - storage.iniPreferences(); -} - -/** - * 快捷键注册 - * @param {Object} shortcutObj - shortcut object - * @param {Boolean} force - force register - * @param {Function} fn - callback - * @return {Boolean} - */ -exports.register = function (shortcutObj, force = true, fn) { - if (!shortcutObj['id'] || !shortcutObj['name'] || !shortcutObj['cmd']) { - return false; - } - const isRegistered = this.isRegistered(shortcutObj['cmd']); - if (isRegistered && !force) { - return false; - } - storage.setShortcuts(shortcutObj); - globalShortcut.register(shortcutObj['cmd'], fn) - - return true; -} - -/** - * 快捷键是否注册成功 - * @param {String} cmd - shortcut string - * @return {Boolean} - */ -exports.isRegistered = function (cmd) { - return globalShortcut.isRegistered(cmd) -} - -/** - * 注销全局快捷键 - * @param {String} cmd - shortcut string - * @return {Boolean} - */ -exports.unregister = function (cmd) { - globalShortcut.unregister(cmd) -} - -exports = module.exports; \ No newline at end of file diff --git a/electron/lib/storage.js b/electron/lib/storage.js deleted file mode 100644 index 8756399..0000000 --- a/electron/lib/storage.js +++ /dev/null @@ -1,125 +0,0 @@ -'use strict'; - -const path = require('path'); -const lowdb = require('lowdb'); -const FileSync = require('lowdb/adapters/FileSync'); -const fs = require('fs'); -const getPort = require('get-port'); -const utils = require('../../app/utils/utils'); -const storageKey = require('../../app/const/storageKey'); -const os = require('os'); -const pkg = require('../../package.json'); -const storageDb = 'db.json'; -const _ = require('lodash'); - -/** - * 安装模块 - */ -exports.setup = function () { - console.log('[electron-lib-storage] [setup]'); - const storageDir = this.getStorageDir(); - if (!fs.existsSync(storageDir)) { - utils.mkdir(storageDir); - utils.chmodPath(storageDir, '777'); - } - const file = storageDir + storageDb; - const adapter = new FileSync(file); - const db = lowdb(adapter); - const eggConfigKey = storageKey.EGG_CONFIG; - if (!db.has(eggConfigKey).value()) { - db.set(eggConfigKey, {}).write(); - } - - return true; -}; - -exports.instance = function (file = null) { - if (!file) { - const storageDir = this.getStorageDir(); - file = path.normalize(storageDir + storageDb); - } - const isExist = fs.existsSync(file); - if (!isExist) { - return null; - } - - const adapter = new FileSync(file); - const db = lowdb(adapter); - - return db; -}; - -exports.getEggConfig = function () { - const key = storageKey.EGG_CONFIG; - const res = this.instance() - .get(key) - .value(); - - return res; -}; - -exports.setDynamicPort = async function () { - // const eggConfig = config.get('egg'); - // console.log('setDynamicPort eggConfig:', eggConfig); - // const dynamicPort = await getPort({port: eggConfig.port}) - const dynamicPort = await getPort(); - const key = storageKey.EGG_CONFIG + '.port'; - const res = this.instance() - .set(key, dynamicPort) - .write(); - - return res; -}; - -exports.setIpcDynamicPort = async function () { - const key = storageKey.ELECTRON_IPC + '.port'; - const dynamicPort = await getPort(); - this.instance() - .set(key, dynamicPort) - .write(); - - return dynamicPort; -}; - -exports.getStorageDir = function () { - const userHomeDir = os.userInfo().homedir; - const storageDir = path.normalize(userHomeDir + '/' + pkg.name + '/'); - - return storageDir; -} - -exports.iniPreferences = function () { - const key = storageKey.PREFERENCES; - if (!this.instance().has(key).value()) { - this.instance().set(key, {}).write(); - } - const res = this.instance() - .get(key) - .value(); - - return res; -}; - -exports.setShortcuts = function (data) { - const key = storageKey.PREFERENCES + '.shortcuts'; - if (!this.instance().has(key).value()) { - this.instance().set(key, []).write(); - } - const item = this.instance().get(key).find({id: data.id}).value(); - if (_.isEmpty(item)) { - this.instance() - .get(key) - .push(data) - .write(); - } else { - this.instance() - .get(key) - .find({id: data.id}) - .assign(data) - .write(); - } - - return true; -}; - -exports = module.exports; \ No newline at end of file diff --git a/electron/lib/tray.js b/electron/lib/tray.js deleted file mode 100644 index e4882ff..0000000 --- a/electron/lib/tray.js +++ /dev/null @@ -1,63 +0,0 @@ -'use strict'; - -const {app, Tray, Menu} = require('electron'); -const path = require('path'); -const helper = require('./helper'); -const config = require('../config'); - -/** - * 安装模块 - */ -exports.setup = function () { - console.log('[electron-lib-tray] [setup]'); - const cfg = config.get('tray'); - - // 托盘图标 - let iconPath = path.join(app.getAppPath(), cfg.icon); - - // 托盘菜单功能列表 - let trayMenuTemplate = [ - { - label: '显示', - click: function () { - MAIN_WINDOW.show(); - } - }, - { - label: '退出', - click: function () { - helper.appQuit(); - } - } - ] - - // 点击关闭,最小化到托盘 - MAIN_WINDOW.on('close', (event) => { - if (!CAN_QUIT) { - MAIN_WINDOW.hide(); - MAIN_WINDOW.setSkipTaskbar(true); - event.preventDefault(); - } - }); - MAIN_WINDOW.show(); - - APP_TRAY = new Tray(iconPath); - APP_TRAY.setToolTip(cfg.title); // 托盘标题 - const contextMenu = Menu.buildFromTemplate(trayMenuTemplate); - APP_TRAY.setContextMenu(contextMenu); - - // 监听 显示/隐藏 - APP_TRAY.on('click', function(){ - if (MAIN_WINDOW.isVisible()) { - MAIN_WINDOW.hide(); - MAIN_WINDOW.setSkipTaskbar(false); - } else { - MAIN_WINDOW.show(); - MAIN_WINDOW.setSkipTaskbar(true); - } - }); - - return APP_TRAY; -} - -exports = module.exports; \ No newline at end of file diff --git a/electron/library/chromeExtension.js b/electron/library/chromeExtension.js index 57d9e18..3350499 100644 --- a/electron/library/chromeExtension.js +++ b/electron/library/chromeExtension.js @@ -13,7 +13,7 @@ module.exports = { /** * 安装 */ - async install (eeApp) { + async install () { console.log('[preload] load chrome extension module'); const extensionIds = this.getAllIds(); for (let i = 0; i < extensionIds.length; i++) { diff --git a/frontend/src/views/base/extension/Index.vue b/frontend/src/views/base/extension/Index.vue index b7a514e..192e479 100644 --- a/frontend/src/views/base/extension/Index.vue +++ b/frontend/src/views/base/extension/Index.vue @@ -16,7 +16,7 @@

- Click or drag file to this area to upload + 上传

@@ -37,7 +37,7 @@ export default { data() { return { - action_url: process.env.VUE_APP_API_BASE_URL + '/api/v1/example/uploadExtension', + action_url: process.env.VUE_APP_API_BASE_URL + '/api/example/uploadExtension', }; }, mounted () { @@ -54,11 +54,6 @@ export default { if (status === 'done') { const uploadRes = info.file.response; console.log('uploadRes:', uploadRes) - // if (uploadRes.code !== 'success') { - // this.$message.error(`file upload failed ${uploadRes.code} .`); - // return false; - // } - // this.$message.success(`${info.file.name} file uploaded successfully.`); } else if (status === 'error') { this.$message.error(`${info.file.name} file upload failed.`); } diff --git a/package.json b/package.json index c1d64ca..dbb1a2d 100755 --- a/package.json +++ b/package.json @@ -106,6 +106,7 @@ "egg-scripts": "^2.15.2", "egg-view-ejs": "^2.0.1", "electron-is": "^3.0.0", - "lodash": "^4.17.21" + "lodash": "^4.17.21", + "unzip-crx-3": "^0.2.0" } }