init项目

This commit is contained in:
2024-08-07 21:48:41 +08:00
parent 2c3a02d33b
commit 1581a5aaf5
18 changed files with 938 additions and 0 deletions

View File

@@ -0,0 +1,170 @@
const { app: electronApp } = require('electron');
const { autoUpdater } = require("electron-updater");
const is = require('ee-core/utils/is');
const Log = require('ee-core/log');
const Conf = require('ee-core/config');
const CoreWindow = require('ee-core/electron/window');
const Electron = require('ee-core/electron');
/**
* 自动升级插件
* @class
*/
class AutoUpdaterAddon {
constructor() {
}
/**
* 创建
*/
create () {
Log.info('[addon:autoUpdater] load');
const cfg = Conf.getValue('addons.autoUpdater');
if ((is.windows() && cfg.windows)
|| (is.macOS() && cfg.macOS)
|| (is.linux() && cfg.linux))
{
// continue
} else {
return
}
// 是否检查更新
if (cfg.force) {
this.checkUpdate();
}
const status = {
error: -1,
available: 1,
noAvailable: 2,
downloading: 3,
downloaded: 4,
}
const version = electronApp.getVersion();
Log.info('[addon:autoUpdater] current version: ', version);
// 设置下载服务器地址
let server = cfg.options.url;
let lastChar = server.substring(server.length - 1);
server = lastChar === '/' ? server : server + "/";
//Log.info('[addon:autoUpdater] server: ', server);
cfg.options.url = server;
// 是否后台自动下载
autoUpdater.autoDownload = cfg.force ? true : false;
try {
autoUpdater.setFeedURL(cfg.options);
} catch (error) {
Log.error('[addon:autoUpdater] setFeedURL error : ', error);
}
autoUpdater.on('checking-for-update', () => {
//sendStatusToWindow('正在检查更新...');
})
autoUpdater.on('update-available', (info) => {
info.status = status.available;
info.desc = '有可用更新';
this.sendStatusToWindow(info);
})
autoUpdater.on('update-not-available', (info) => {
info.status = status.noAvailable;
info.desc = '没有可用更新';
this.sendStatusToWindow(info);
})
autoUpdater.on('error', (err) => {
let info = {
status: status.error,
desc: err
}
this.sendStatusToWindow(info);
})
autoUpdater.on('download-progress', (progressObj) => {
let percentNumber = parseInt(progressObj.percent);
let totalSize = this.bytesChange(progressObj.total);
let transferredSize = this.bytesChange(progressObj.transferred);
let text = '已下载 ' + percentNumber + '%';
text = text + ' (' + transferredSize + "/" + totalSize + ')';
let info = {
status: status.downloading,
desc: text,
percentNumber: percentNumber,
totalSize: totalSize,
transferredSize: transferredSize
}
Log.info('[addon:autoUpdater] progress: ', text);
this.sendStatusToWindow(info);
})
autoUpdater.on('update-downloaded', (info) => {
info.status = status.downloaded;
info.desc = '下载完成';
this.sendStatusToWindow(info);
// 托盘插件默认会阻止窗口关闭,这里设置允许关闭窗口
Electron.extra.closeWindow = true;
autoUpdater.quitAndInstall();
// const mainWindow = CoreWindow.getMainWindow();
// if (mainWindow) {
// mainWindow.destroy()
// }
// electronApp.appQuit()
});
}
/**
* 检查更新
*/
checkUpdate () {
autoUpdater.checkForUpdates();
}
/**
* 下载更新
*/
download () {
autoUpdater.downloadUpdate();
}
/**
* 向前端发消息
*/
sendStatusToWindow(content = {}) {
const textJson = JSON.stringify(content);
const channel = 'app.updater';
const win = CoreWindow.getMainWindow();
win.webContents.send(channel, textJson);
}
/**
* 单位转换
*/
bytesChange (limit) {
let size = "";
if(limit < 0.1 * 1024){
size = limit.toFixed(2) + "B";
}else if(limit < 0.1 * 1024 * 1024){
size = (limit/1024).toFixed(2) + "KB";
}else if(limit < 0.1 * 1024 * 1024 * 1024){
size = (limit/(1024 * 1024)).toFixed(2) + "MB";
}else{
size = (limit/(1024 * 1024 * 1024)).toFixed(2) + "GB";
}
let sizeStr = size + "";
let index = sizeStr.indexOf(".");
let dou = sizeStr.substring(index + 1 , index + 3);
if(dou == "00"){
return sizeStr.substring(0, index) + sizeStr.substring(index + 3, index + 5);
}
return size;
}
}
AutoUpdaterAddon.toString = () => '[class AutoUpdaterAddon]';
module.exports = AutoUpdaterAddon;

View File

@@ -0,0 +1,67 @@
const { app: electronApp } = require('electron');
const Log = require('ee-core/log');
const Conf = require('ee-core/config');
/**
* 唤醒插件
* @class
*/
class AwakenAddon {
constructor() {
this.protocol = '';
}
/**
* 创建
*/
create () {
Log.info('[addon:awaken] load');
const cfg = Conf.getValue('addons.awaken');
this.protocol = cfg.protocol;
electronApp.setAsDefaultProtocolClient(this.protocol);
this.handleArgv(process.argv);
electronApp.on('second-instance', (event, argv) => {
if (process.platform === 'win32') {
this.handleArgv(argv)
}
})
// 仅用于macOS
electronApp.on('open-url', (event, urlStr) => {
this.handleUrl(urlStr)
})
}
/**
* 参数处理
*/
handleArgv(argv) {
const offset = electronApp.isPackaged ? 1 : 2;
const url = argv.find((arg, i) => i >= offset && arg.startsWith(this.protocol));
this.handleUrl(url)
}
/**
* url解析
*/
handleUrl(awakeUrlStr) {
if (!awakeUrlStr || awakeUrlStr.length === 0) {
return
}
const {hostname, pathname, search} = new URL(awakeUrlStr);
let awakeUrlInfo = {
urlStr: awakeUrlStr,
urlHost: hostname,
urlPath: pathname,
urlParams: search && search.slice(1)
}
Log.info('[addon:awaken] awakeUrlInfo:', awakeUrlInfo);
}
}
AwakenAddon.toString = () => '[class AwakenAddon]';
module.exports = AwakenAddon;

View File

@@ -0,0 +1,94 @@
const { app, session } = require('electron');
const _ = require('lodash');
const fs = require('fs');
const path = require('path');
const Log = require('ee-core/log');
/**
* 扩展插件 electron自身对该功能并不完全支持官方也不建议使用
* @class
*/
class ChromeExtensionAddon {
constructor() {
}
/**
* 创建
*/
async create () {
Log.info('[addon:chromeExtension] load');
const extensionIds = this.getAllIds();
for (let i = 0; i < extensionIds.length; i++) {
await this.load(extensionIds[i]);
}
}
/**
* 获取扩展id列表crx解压后的目录名即是该扩展的id
*/
getAllIds () {
const extendsionDir = this.getDirectory();
const ids = this.getDirs(extendsionDir);
return ids;
}
/**
* 扩展所在目录
*/
getDirectory () {
let extensionDirPath = '';
let variablePath = 'build'; // 打包前路径
if (app.isPackaged) {
variablePath = '..'; // 打包后路径
}
extensionDirPath = path.join(app.getAppPath(), variablePath, "extraResources", "chromeExtension");
return extensionDirPath;
}
/**
* 加载扩展
*/
async load (extensionId = '') {
if (_.isEmpty(extensionId)) {
return false
}
try {
const extensionPath = path.join(this.getDirectory(), extensionId);
Log.info('[addon:chromeExtension] extensionPath:', extensionPath);
await session.defaultSession.loadExtension(extensionPath, { allowFileAccess: true });
} catch (e) {
Log.info('[addon:chromeExtension] load extension error extensionId:%s, errorInfo:%s', extensionId, e.toString());
return false
}
return true
}
/**
* 获取目录下所有文件夹
*/
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;
};
}
ChromeExtensionAddon.toString = () => '[class ChromeExtensionAddon]';
module.exports = ChromeExtensionAddon;

View File

@@ -0,0 +1,33 @@
const Log = require('ee-core/log');
const EE = require('ee-core/ee');
/**
* 安全插件
* @class
*/
class SecurityAddon {
constructor() {
}
/**
* 创建
*/
create () {
Log.info('[addon:security] load');
const { CoreApp } = EE;
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) {
Log.error('[error] Remote debugging is not allowed, runWithDebug:', runWithDebug);
CoreApp.appQuit();
}
}
}
SecurityAddon.toString = () => '[class SecurityAddon]';
module.exports = SecurityAddon;

View File

@@ -0,0 +1,72 @@
const { Tray, Menu } = require('electron');
const path = require('path');
const Ps = require('ee-core/ps');
const Log = require('ee-core/log');
const Electron = require('ee-core/electron');
const CoreWindow = require('ee-core/electron/window');
const Conf = require('ee-core/config');
const EE = require('ee-core/ee');
/**
* 托盘插件
* @class
*/
class TrayAddon {
constructor() {
this.tray = null;
}
/**
* 创建托盘
*/
create () {
// 开发环境,代码热更新开启时,会导致托盘中有残影
if (Ps.isDev() && Ps.isHotReload()) return;
Log.info('[addon:tray] load');
const { CoreApp } = EE;
const cfg = Conf.getValue('addons.tray');
const mainWindow = CoreWindow.getMainWindow();
// 托盘图标
let iconPath = path.join(Ps.getHomeDir(), cfg.icon);
// 托盘菜单功能列表
let trayMenuTemplate = [
{
label: '显示',
click: function () {
mainWindow.show();
}
},
{
label: '退出',
click: function () {
CoreApp.appQuit();
}
}
]
// 点击关闭,最小化到托盘
mainWindow.on('close', (event) => {
if (Electron.extra.closeWindow == true) {
return;
}
mainWindow.hide();
event.preventDefault();
});
// 实例化托盘
this.tray = new Tray(iconPath);
this.tray.setToolTip(cfg.title);
const contextMenu = Menu.buildFromTemplate(trayMenuTemplate);
this.tray.setContextMenu(contextMenu);
this.tray.on('double-click', () => {
mainWindow.show()
})
}
}
TrayAddon.toString = () => '[class TrayAddon]';
module.exports = TrayAddon;