🐛 修复 #264

 支持 db.postAttachment 和 db.getAttachment
♻️ 重构版本更新机制
This commit is contained in:
muwoo 2023-10-18 11:02:14 +08:00
parent a7a85a7c62
commit bde5377282
12 changed files with 195 additions and 120 deletions

View File

@ -22,11 +22,11 @@
<template #renderItem="{ item }">
<a-list-item>
<template #actions>
<a v-if="!item.plugin.isdownload && !item.plugin.isloading" key="list-loadmore-edit"
<a v-if="!item.plugin?.isdownload && !item.plugin?.isloading" key="list-loadmore-edit"
@click="() => downloadPlugin(item.plugin)">
<CloudDownloadOutlined style="font-size: 18px;"/>
</a>
<a v-if="item.plugin.isloading" key="list-loadmore-edit">
<a v-if="item.plugin?.isloading" key="list-loadmore-edit">
<LoadingOutlined style="font-size: 18px;"/>
</a>
<a key="list-loadmore-edit" @click="() => showKeys(item)">
@ -36,11 +36,11 @@
<a-list-item-meta :description="`${item.keys.length} 份文档`">
<template #title>
<div>
<span>{{ item.plugin.pluginName }}</span>
<span>{{ item.plugin?.pluginName }}</span>
</div>
</template>
<template #avatar>
<a-avatar shape="square" :src="item.plugin.logo"/>
<a-avatar shape="square" :src="item.plugin?.logo"/>
</template>
</a-list-item-meta>
</a-list-item>

View File

@ -1,6 +1,6 @@
{
"name": "rubick",
"version": "4.0.4",
"version": "4.0.5",
"author": "muwoo <2424880409@qq.com>",
"private": true,
"scripts": {
@ -69,7 +69,7 @@
"less-loader": "^5.0.0",
"prettier": "^2.8.4",
"typescript": "~4.1.5",
"vue-cli-plugin-electron-builder": "~2.1.1",
"vue-cli-plugin-electron-builder": "3.0.0-alpha.4",
"worker-plugin": "^5.0.1"
},
"resolutions": {

View File

@ -85,6 +85,10 @@ window.rubick = {
remove: (doc) => ipcSendSync('dbRemove', { doc }),
bulkDocs: (docs) => ipcSendSync('dbBulkDocs', { docs }),
allDocs: (key) => ipcSendSync('dbAllDocs', { key }),
postAttachment: (docId, attachment, type) =>
ipcSendSync('dbPostAttachment', { docId, attachment, type }),
getAttachment: (docId) => ipcSendSync('dbGetAttachment', { docId }),
getAttachmentType: (docId) => ipcSendSync('dbGetAttachmentType', { docId }),
},
dbStorage: {
setItem: (key, value) => {

View File

@ -204,4 +204,38 @@ export default class DB {
this.pouchDB = syncDb.pouchDB;
await webdavClient.createReadStream(this.pouchDB);
}
public async postAttachment(
name: string,
docId: string,
attachment: Buffer | Uint8Array,
type: string
) {
const buffer = Buffer.from(attachment);
if (buffer.byteLength > this.docAttachmentMaxByteLength)
return this.errorInfo(
'exception',
'attachment data up to ' +
this.docAttachmentMaxByteLength / 1024 / 1024 +
'M'
);
try {
const result = await this.pouchDB.put({
_id: this.getDocId(name, docId),
_attachments: { 0: { data: buffer, content_type: type } },
});
result.id = this.replaceDocId(name, result.id);
return result;
} catch (e) {
return this.errorInfo(e.name, e.message);
}
}
async getAttachment(name: string, docId: string, len = '0') {
try {
return await this.pouchDB.getAttachment(this.getDocId(name, docId), len);
} catch (e) {
return null;
}
}
}

View File

@ -11,8 +11,8 @@ type WebDavOptions = {
};
type DBInstance = {
loadIt: (stream: unknown) => void;
dump: (stream: unknown) => void;
loadIt: (stream: unknown, options?: any) => void;
dump: (stream: unknown, options?: any) => void;
};
export default class WebDav {
@ -54,7 +54,12 @@ export default class WebDav {
}).show();
}
const ws = new MemoryStream();
dbInstance.dump(ws);
dbInstance.dump(ws, {
filter: (doc) => {
// attachment 文档导出有问题,
return !doc._attachments;
},
});
ws.pipe(
this.client.createWriteStream(this.cloudPath, {}, () => {
new Notification({

View File

@ -157,13 +157,17 @@ class AdapterHandler {
*/
private async execCommand(cmd: string, modules: string[]): Promise<string> {
return new Promise((resolve: any, reject: any) => {
const args: string[] = [cmd]
.concat(
cmd !== 'uninstall' ? modules.map((m) => `${m}@latest`) : modules
)
let args: string[] = [cmd].concat(
cmd !== 'uninstall' && cmd !== 'link'
? modules.map((m) => `${m}@latest`)
: modules
);
if (cmd !== 'link') {
args = args
.concat('--color=always')
.concat('--save')
.concat(`--registry=${this.registry}`);
}
const npm = spawn('npm', args, {
cwd: this.baseDir,

View File

@ -73,23 +73,31 @@ export default () => {
const init = (plugin, window: BrowserWindow) => {
if (view === null || view === undefined) {
if (viewInstance.getView(plugin.name) && !commonConst.dev()) {
view = viewInstance.getView(plugin.name).view;
window.setBrowserView(view);
view.inited = true;
viewReadyFn(window, plugin);
} else {
createView(plugin, window);
viewInstance.addView(plugin.name, view);
}
// if (viewInstance.getView(plugin.name) && !commonConst.dev()) {
// view = viewInstance.getView(plugin.name).view;
// window.setBrowserView(view);
// view.inited = true;
// viewReadyFn(window, plugin);
// } else {
// createView(plugin, window);
// viewInstance.addView(plugin.name, view);
// }
// eslint-disable-next-line @typescript-eslint/no-var-requires
require('@electron/remote/main').enable(view.webContents);
}
};
const createView = (plugin, window: BrowserWindow) => {
const { tplPath, indexPath, development, name, main, pluginSetting, ext } =
plugin;
const {
tplPath,
indexPath,
development,
name,
main = 'index.html',
pluginSetting,
ext,
} = plugin;
let pluginIndexPath = tplPath || indexPath;
let preloadPath;
let darkMode;
@ -160,7 +168,7 @@ export default () => {
window.removeBrowserView(view);
window.setSize(800, 60);
executeHooks('PluginOut', null);
window.webContents.executeJavaScript(`window.initRubick()`);
window.webContents?.executeJavaScript(`window.initRubick()`);
view = undefined;
};
@ -174,7 +182,7 @@ export default () => {
} catch(e) {}
}
`;
view.webContents.executeJavaScript(evalJs);
view.webContents?.executeJavaScript(evalJs);
};
return {

View File

@ -14,13 +14,18 @@ import { screenCapture } from '@/core';
import plist from 'plist';
import ks from 'node-key-sender';
import { DECODE_KEY } from '@/common/constans/main';
import {
DECODE_KEY,
PLUGIN_INSTALL_DIR as baseDir,
} from '@/common/constans/main';
import getCopyFiles from '@/common/utils/getCopyFiles';
import common from '@/common/utils/commonConst';
import mainInstance from '../index';
import { runner, detach } from '../browsers';
import DBInstance from './db';
import getWinPosition from './getWinPosition';
import path from 'path';
const runnerInstance = runner();
const detachInstance = detach();
@ -77,8 +82,29 @@ class API extends DBInstance {
}
public openPlugin({ data: plugin }, window) {
if (plugin.platform && !plugin.platform.includes(process.platform)) {
return new Notification({
title: `插件不支持当前 ${process.platform} 系统`,
body: `插件仅支持 ${plugin.platform.join(',')}`,
icon: plugin.logo,
}).show();
}
window.setSize(window.getSize()[0], 60);
this.removePlugin(null, window);
// 模板文件
if (!plugin.main) {
plugin.tplPath = common.dev()
? 'http://localhost:8083/#/'
: `file://${__static}/tpl/index.html`;
}
if (!plugin.indexPath) {
const pluginPath = path.resolve(baseDir, 'node_modules', plugin.name);
plugin.indexPath = `file://${path.join(
pluginPath,
'./',
plugin.main || ''
)}`;
}
runnerInstance.init(plugin, window);
this.currentPlugin = plugin;
window.webContents.executeJavaScript(

View File

@ -54,4 +54,20 @@ export default class DBInstance {
public dbImport({ data }) {
return dbInstance.importDb(data.target);
}
public dbPostAttachment({ data }) {
const { docId, attachment, type } = data;
return dbInstance.postAttachment(this.DBKEY, docId, attachment, type);
}
public dbGetAttachment({ data }) {
return dbInstance.getAttachment(this.DBKEY, data.docId);
}
public async dbGetAttachmentType({ data }) {
const res: any = await this.dbGet(data.docId);
if (!res || !res._attachments) return null;
const result = res._attachments[0];
return result ? result.content_type : null;
}
}

View File

@ -0,0 +1,27 @@
// for referer policy, we can't use it in renderer
import axios from 'axios';
const RELEASE_URL = 'https://api.github.com/repos/rubickCenter/rubick/releases';
export const getLatestVersion = async (isCheckBetaUpdate = false) => {
let res = '';
try {
res = await axios
.get(RELEASE_URL, {
headers: {
Referer: 'https://github.com',
},
})
.then((r) => {
const list = r.data;
if (isCheckBetaUpdate) {
const betaList = list.filter((item) => item.name.includes('beta'));
return betaList[0].name;
}
const normalList = list.filter((item) => !item.name.includes('beta'));
return normalList[0].name;
});
} catch (err) {
console.log(err);
}
return res;
};

View File

@ -1,96 +1,45 @@
import { dialog } from 'electron';
import { autoUpdater } from 'electron-updater';
import { dialog, shell } from 'electron';
import pkg from '../../../package.json';
import { main } from '../browsers';
import { lt } from 'semver';
import { getLatestVersion } from './getLatestVersion';
const version = pkg.version;
const downloadUrl = 'https://github.com/rubickCenter/rubick/releases/latest';
class VersionHandler {
private lastestVersion: string;
private currentVersion: string;
private releaseNotes: string;
private isUpdate: boolean;
constructor() {
this.lastestVersion = '';
this.currentVersion = pkg.version;
this.releaseNotes = '';
this.isUpdate = false;
autoUpdater.autoDownload = false;
autoUpdater.autoInstallOnAppQuit = false;
}
checkForMacAndWindows() {
let sendUpdateMsg = false;
autoUpdater.removeAllListeners();
// update-available 会触发多次,限制只通知一次
autoUpdater.checkForUpdates();
autoUpdater.on('download-progress', ({ percent }) => {
console.log('下载进度', percent);
// if (percent < 50) {
// }
this.isUpdate = true;
});
autoUpdater.on('update-available', (info) => {
if (sendUpdateMsg) return;
const { version, releaseName = 'normal', releaseNotes } = info;
this.lastestVersion = version;
sendUpdateMsg = true;
autoUpdater.on('update-downloaded', () => {
console.log('下载完成');
this.isUpdate = false;
if (releaseName === 'major') {
autoUpdater.quitAndInstall(true, true);
}
const mainWindow = main().getWindow();
const checkVersion = async () => {
const res: string = await getLatestVersion();
if (res !== '') {
const latest = res;
const result = compareVersion2Update(version, latest);
if (result) {
dialog
.showMessageBox(mainWindow, {
title: '版本更新',
message: `发现新版本${this.lastestVersion},是否更新\n\n${releaseNotes}`,
.showMessageBox({
type: 'info',
buttons: ['稍后提示', '立即更新'],
title: 'Rubick 更新提示',
buttons: ['Yes', 'No'],
message: `发现新版本 v${latest},是否更新?`,
})
.then(({ response }) => {
console.log(response);
if (response === 1) {
this.update();
.then((res) => {
if (res.response === 0) {
// if selected yes
shell.openExternal(downloadUrl);
}
});
});
// 自动下载安装包
if (!this.isUpdate) {
autoUpdater.downloadUpdate();
console.log('download');
}
});
autoUpdater.on('update-not-available', (info) => {
if (sendUpdateMsg) return;
sendUpdateMsg = true;
});
autoUpdater.on('error', () => {
this.isUpdate = false;
});
} else {
return false;
}
};
checkUpdate(): void {
this.checkForMacAndWindows();
// if true -> update else return false
const compareVersion2Update = (current: string, latest: string) => {
try {
if (latest.includes('beta')) {
return false;
}
update() {
let sendUpdateMsg = false;
this.checkUpdate();
autoUpdater.on('update-downloaded', () => {
if (sendUpdateMsg) return;
sendUpdateMsg = true;
this.isUpdate = false;
autoUpdater.quitAndInstall(true, true);
// App.quit();
});
return lt(current, latest);
} catch (e) {
return false;
}
}
};
export default new VersionHandler();
export default checkVersion;

View File

@ -22,6 +22,7 @@ import {
import '../common/utils/localPlugin';
import registerySystemPlugin from './common/registerySystemPlugin';
import checkVersion from './common/versionHandler';
class App {
public windowCreator: { init: () => void; getWindow: () => BrowserWindow };
@ -62,6 +63,7 @@ class App {
}
onReady() {
const readyFunction = async () => {
checkVersion();
await localConfig.init();
const config = await localConfig.getConfig();
if (!config.perf.common.guide) {