🔨 Refactor: most config handle by picgo-core

for config syncing with picgo-core && picgo-plugins
This commit is contained in:
Molunerfinn
2019-12-26 20:15:41 +08:00
parent fec4360043
commit 3418560c63
30 changed files with 294 additions and 232 deletions

View File

@@ -1,14 +1,7 @@
import path from 'path'
import db from '#/datastore'
import { App } from 'electron'
// eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
import picgo from './picgo'
const getPicBeds = (app: App) => {
const PicGo = requireFunc('picgo')
const STORE_PATH = app.getPath('userData')
const CONFIG_PATH = path.join(STORE_PATH, '/data.json')
const picgo = new PicGo(CONFIG_PATH)
const getPicBeds = () => {
const picBedTypes = picgo.helper.uploader.getIdList()
const picBedFromDB = db.get('picBed.list') || []
const picBeds = picBedTypes.map((item: string) => {

View File

@@ -7,7 +7,7 @@ import {
ipcMain
} from 'electron'
import db from '#/datastore'
import Uploader from './uploader'
import uploader from './uploader'
import pasteTemplate from '#/utils/pasteTemplate'
const WEBCONTENTS = Symbol('WEBCONTENTS')
@@ -52,7 +52,7 @@ class GuiApi implements IGuiApi {
}
async upload (input: IUploadOption) {
const imgs = await new Uploader(input, this[WEBCONTENTS]).upload()
const imgs = await uploader.setWebContents(this[WEBCONTENTS]).upload(input)
if (imgs !== false) {
const pasteStyle = db.get('settings.pasteStyle') || 'markdown'
let pasteText = ''

19
src/main/utils/picgo.ts Normal file
View File

@@ -0,0 +1,19 @@
import PicGoCore from '~/universal/types/picgo'
import {
app
} from 'electron'
import path from 'path'
// eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
const PicGo = requireFunc('picgo') as typeof PicGoCore
const STORE_PATH = app.getPath('userData')
const CONFIG_PATH = path.join(STORE_PATH, '/data.json')
const picgo = new PicGo(CONFIG_PATH)
picgo.setConfig({
debug: true,
PICGO_ENV: 'GUI'
})
export default picgo as PicGoCore

View File

@@ -1,14 +1,24 @@
import path from 'path'
import GuiApi from './guiApi'
import { dialog, shell, IpcMain, IpcMainEvent, App } from 'electron'
import db from '#/datastore'
import {
dialog,
shell,
IpcMain,
IpcMainEvent,
App,
ipcMain,
app
} from 'electron'
import PicGoCore from '~/universal/types/picgo'
import { IPicGoHelperType } from '#/types/enum'
import shortKeyHandler from './shortKeyHandler'
import picgo from '~/main/utils/picgo'
// eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
const PicGo = requireFunc('picgo') as typeof PicGoCore
const PluginHandler = requireFunc('picgo/dist/lib/PluginHandler').default
// const PluginHandler = requireFunc('picgo/dist/lib/PluginHandler').default
const STORE_PATH = app.getPath('userData')
// const CONFIG_PATH = path.join(STORE_PATH, '/data.json')
type PicGoNotice = {
title: string,
@@ -48,9 +58,8 @@ const handleConfigWithFunction = (config: any[]) => {
return config
}
const handleGetPluginList = (ipcMain: IpcMain, STORE_PATH: string, CONFIG_PATH: string) => {
const handleGetPluginList = () => {
ipcMain.on('getPluginList', (event: IpcMainEvent) => {
const picgo = new PicGo(CONFIG_PATH)
const pluginList = picgo.pluginLoader.getList()
const list = []
for (let i in pluginList) {
@@ -102,48 +111,49 @@ const handleGetPluginList = (ipcMain: IpcMain, STORE_PATH: string, CONFIG_PATH:
})
}
const handlePluginInstall = (ipcMain: IpcMain, CONFIG_PATH: string) => {
const handlePluginInstall = () => {
ipcMain.on('installPlugin', async (event: IpcMainEvent, msg: string) => {
const picgo = new PicGo(CONFIG_PATH)
const pluginHandler = new PluginHandler(picgo)
picgo.on('installSuccess', (notice: PicGoNotice) => {
picgo.once('installSuccess', (notice: PicGoNotice) => {
event.sender.send('installSuccess', notice.body[0].replace(/picgo-plugin-/, ''))
shortKeyHandler.registerPluginShortKey(notice.body[0])
picgo.removeAllListeners('installFailed')
})
picgo.on('failed', () => {
picgo.once('installFailed', () => {
handleNPMError()
picgo.removeAllListeners('installSuccess')
})
await pluginHandler.uninstall([msg])
pluginHandler.install([msg])
await picgo.pluginHandler.install([msg])
picgo.cmd.program.removeAllListeners()
})
}
const handlePluginUninstall = (ipcMain: IpcMain, CONFIG_PATH: string) => {
const handlePluginUninstall = () => {
ipcMain.on('uninstallPlugin', async (event: IpcMainEvent, msg: string) => {
const picgo = new PicGo(CONFIG_PATH)
const pluginHandler = new PluginHandler(picgo)
picgo.on('uninstallSuccess', (notice: PicGoNotice) => {
picgo.once('uninstallSuccess', (notice: PicGoNotice) => {
event.sender.send('uninstallSuccess', notice.body[0].replace(/picgo-plugin-/, ''))
shortKeyHandler.unregisterPluginShortKey(notice.body[0])
picgo.removeAllListeners('uninstallFailed')
})
picgo.on('failed', () => {
picgo.once('uninstallFailed', () => {
handleNPMError()
picgo.removeAllListeners('uninstallSuccess')
})
await pluginHandler.uninstall([msg])
await picgo.pluginHandler.uninstall([msg])
picgo.cmd.program.removeAllListeners()
})
}
const handlePluginUpdate = (ipcMain: IpcMain, CONFIG_PATH: string) => {
const handlePluginUpdate = () => {
ipcMain.on('updatePlugin', async (event: IpcMainEvent, msg: string) => {
const picgo = new PicGo(CONFIG_PATH)
const pluginHandler = new PluginHandler(picgo)
picgo.on('updateSuccess', notice => {
picgo.once('updateSuccess', (notice: { body: string[], title: string }) => {
event.sender.send('updateSuccess', notice.body[0].replace(/picgo-plugin-/, ''))
picgo.removeAllListeners('updateFailed')
})
picgo.on('failed', () => {
picgo.once('updateFailed', () => {
handleNPMError()
picgo.removeAllListeners('updateSuccess')
})
await pluginHandler.update([msg])
await picgo.pluginHandler.update([msg])
picgo.cmd.program.removeAllListeners()
})
}
@@ -160,9 +170,8 @@ const handleNPMError = () => {
})
}
const handleGetPicBedConfig = (ipcMain: IpcMain, CONFIG_PATH: string) => {
const handleGetPicBedConfig = () => {
ipcMain.on('getPicBedConfig', (event: IpcMainEvent, type: string) => {
const picgo = new PicGo(CONFIG_PATH)
const name = picgo.helper.uploader.get(type).name || type
if (picgo.helper.uploader.get(type).config) {
const config = handleConfigWithFunction(picgo.helper.uploader.get(type).config(picgo))
@@ -174,9 +183,8 @@ const handleGetPicBedConfig = (ipcMain: IpcMain, CONFIG_PATH: string) => {
})
}
const handlePluginActions = (ipcMain: IpcMain, CONFIG_PATH: string) => {
const handlePluginActions = () => {
ipcMain.on('pluginActions', (event: IpcMainEvent, name: string, label: string) => {
const picgo = new PicGo(CONFIG_PATH)
const plugin = picgo.pluginLoader.getPlugin(`picgo-plugin-${name}`)
const guiApi = new GuiApi(event.sender)
if (plugin.guiMenu && plugin.guiMenu(picgo).length > 0) {
@@ -190,9 +198,8 @@ const handlePluginActions = (ipcMain: IpcMain, CONFIG_PATH: string) => {
})
}
const handleRemoveFiles = (ipcMain: IpcMain, CONFIG_PATH: string) => {
const handleRemoveFiles = () => {
ipcMain.on('removeFiles', (event: IpcMainEvent, files: ImgInfo[]) => {
const picgo = new PicGo(CONFIG_PATH)
const guiApi = new GuiApi(event.sender)
setTimeout(() => {
picgo.emit('remove', files, guiApi)
@@ -200,26 +207,19 @@ const handleRemoveFiles = (ipcMain: IpcMain, CONFIG_PATH: string) => {
})
}
// const handlePluginShortKeyRegister = (plugin) => {
// if (plugin.shortKeys && plugin.shortKeys.length > 0) {
// let shortKeyConfig = db.get('settings.shortKey')
// plugin.shortKeys.forEach(item => {
// if (!shortKeyConfig[item.name]) {
// shortKeyConfig[item.name] = item
// }
// })
// }
// }
export default (app: App, ipcMain: IpcMain) => {
const STORE_PATH = app.getPath('userData')
const CONFIG_PATH = path.join(STORE_PATH, '/data.json')
handleGetPluginList(ipcMain, STORE_PATH, CONFIG_PATH)
handlePluginInstall(ipcMain, CONFIG_PATH)
handlePluginUninstall(ipcMain, CONFIG_PATH)
handlePluginUpdate(ipcMain, CONFIG_PATH)
handleGetPicBedConfig(ipcMain, CONFIG_PATH)
handlePluginActions(ipcMain, CONFIG_PATH)
handleRemoveFiles(ipcMain, CONFIG_PATH)
// handlePluginShortKeyRegister({})
const handlePicGoSaveData = () => {
ipcMain.on('picgoSaveData', (event: IpcMainEvent, data: IObj) => {
picgo.saveConfig(data)
})
}
export default () => {
handleGetPluginList()
handlePluginInstall()
handlePluginUninstall()
handlePluginUpdate()
handleGetPicBedConfig()
handlePluginActions()
handleRemoveFiles()
handlePicGoSaveData()
}

View File

@@ -10,12 +10,7 @@ import logger from './logger'
import GuiApi from './guiApi'
import db from '#/datastore'
import shortKeyService from './shortKeyService'
// eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
const PicGo = requireFunc('picgo') as typeof PicGoCore
const STORE_PATH = app.getPath('userData')
const CONFIG_PATH = path.join(STORE_PATH, '/data.json')
import picgo from './picgo'
class ShortKeyHandler {
private isInModifiedMode: boolean = false
@@ -40,7 +35,6 @@ class ShortKeyHandler {
})
}
private initPluginsShortKey () {
const picgo = new PicGo(CONFIG_PATH)
const pluginList = picgo.pluginLoader.getList()
for (let item of pluginList) {
const plugin = picgo.pluginLoader.getPlugin(item)
@@ -75,12 +69,14 @@ class ShortKeyHandler {
logger.warn(`${command} do not provide a key to bind`)
}
if (writeFlag) {
db.set(`settings.shortKey.${command}`, {
enable: true,
name: config.name,
label: config.label,
key: config.key
} as IShortKeyConfig)
picgo.saveConfig({
[`settings.shortKey.${command}`]: {
enable: true,
name: config.name,
label: config.label,
key: config.key
}
})
}
}
// enable or disable shortKey
@@ -88,13 +84,17 @@ class ShortKeyHandler {
const command = `${from}:${item.name}`
if (item.enable === false) {
globalShortcut.unregister(item.key)
db.set(`settings.shortKey.${command}.enable`, false)
picgo.saveConfig({
[`settings.shortKey.${command}.enable`]: false
})
return true
} else {
if (globalShortcut.isRegistered(item.key)) {
return false
} else {
db.set(`settings.shortKey.${command}.enable`, true)
picgo.saveConfig({
[`settings.shortKey.${command}.enable`]: true
})
globalShortcut.register(item.key, () => {
this.handler(command)
})
@@ -107,7 +107,9 @@ class ShortKeyHandler {
const command = `${from}:${item.name}`
if (globalShortcut.isRegistered(item.key)) return false
globalShortcut.unregister(oldKey)
db.set(`settings.shortKey.${command}.key`, item.key)
picgo.saveConfig({
[`settings.shortKey.${command}.key`]: item.key
})
globalShortcut.register(item.key, () => {
this.handler(`${from}:${item.name}`)
})
@@ -122,7 +124,6 @@ class ShortKeyHandler {
} else if (command.includes('picgo-plugin-')) {
const handler = shortKeyService.getShortKeyHandler(command)
if (handler) {
const picgo = new PicGo(CONFIG_PATH)
// make sure settingWindow is created
bus.once('createSettingWindowDone', (cmd: string, settingWindowId: number) => {
if (cmd === command) {
@@ -138,7 +139,6 @@ class ShortKeyHandler {
}
}
registerPluginShortKey (pluginName: string) {
const picgo = new PicGo(CONFIG_PATH)
const plugin = picgo.pluginLoader.getPlugin(pluginName)
if (plugin && plugin.commands) {
if (typeof plugin.commands !== 'function') {
@@ -170,7 +170,7 @@ class ShortKeyHandler {
keyList.forEach(item => {
globalShortcut.unregister(item.key)
shortKeyService.unregisterCommand(item.command)
db.unset('settings.shortKey', item.command)
picgo.unsetConfig('settings.shortKey', item.command)
})
}
}

View File

@@ -3,13 +3,8 @@ import db from '#/datastore'
import axios from 'axios'
import pkg from 'root/package.json'
const version = pkg.version
let release = 'https://api.github.com/repos/Molunerfinn/PicGo/releases/latest'
let release = 'https://cdn.jsdelivr.net/gh/Molunerfinn/PicGo/package.json'
const downloadUrl = 'https://github.com/Molunerfinn/PicGo/releases/latest'
const isDevelopment = process.env.NODE_ENV !== 'production'
if (isDevelopment) {
release = `${release}?access_token=${process.env.GITHUB_TOKEN}`
}
const checkVersion = async () => {
let showTip = db.get('settings.showUpdateTip')
@@ -25,7 +20,7 @@ const checkVersion = async () => {
console.log(err)
}
if (res.status === 200) {
const latest = res.data.name
const latest = res.data.version
const result = compareVersion2Update(version, latest)
if (result) {
dialog.showMessageBox({

View File

@@ -5,37 +5,15 @@ import {
ipcMain,
WebContents
} from 'electron'
import path from 'path'
import dayjs from 'dayjs'
import PicGoCore from '~/universal/types/picgo'
import picgo from '~/main/utils/picgo'
import db from '#/datastore'
// eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
const PicGo = requireFunc('picgo') as typeof PicGoCore
const STORE_PATH = app.getPath('userData')
const CONFIG_PATH = path.join(STORE_PATH, '/data.json')
const renameURL = process.env.NODE_ENV === 'development'
? `${(process.env.WEBPACK_DEV_SERVER_URL as string)}#rename-page`
: `picgo://./index.html#rename-page`
// type BrowserWindowOptions = {
// height: number,
// width: number,
// show: boolean,
// fullscreenable: boolean,
// resizable: boolean,
// vibrancy: string | any,
// webPreferences: {
// nodeIntegration: boolean,
// nodeIntegrationInWorker: boolean,
// backgroundThrottling: boolean
// },
// backgroundColor?: string
// autoHideMenuBar?: boolean
// transparent?: boolean
// }
const createRenameWindow = (win: BrowserWindow) => {
const createRenameWindow = (currentWindow: BrowserWindow) => {
let options: IBrowserWindowOptions = {
height: 175,
width: 300,
@@ -60,9 +38,9 @@ const createRenameWindow = (win: BrowserWindow) => {
const window = new BrowserWindow(options)
window.loadURL(renameURL)
// check if this window is visible
if (win.isVisible()) {
if (currentWindow && currentWindow.isVisible()) {
// bounds: { x: 821, y: 75, width: 800, height: 450 }
const bounds = win.getBounds()
const bounds = currentWindow.getBounds()
const positionX = bounds.x + bounds.width / 2 - 150
let positionY
// if is the settingWindow
@@ -98,27 +76,34 @@ const waitForRename = (window: BrowserWindow, id: number): Promise<string|null>
}
class Uploader {
private picgo: PicGoCore
private webContents: WebContents
private img: undefined | string[]
constructor (img: IUploadOption, webContents: WebContents, picgo: PicGoCore | undefined = undefined) {
this.img = img
this.webContents = webContents
this.picgo = picgo || new PicGo(CONFIG_PATH)
private webContents: WebContents | null = null
private currentWindow: BrowserWindow | null = null
constructor () {
this.init()
}
upload (): Promise<ImgInfo[]|false> {
const win = BrowserWindow.fromWebContents(this.webContents)
const picgo = this.picgo
picgo.config.debug = true
// for picgo-core
picgo.config.PICGO_ENV = 'GUI'
let input = this.img
init () {
picgo.on('notification', message => {
const notification = new Notification(message)
notification.show()
})
picgo.on('uploadProgress', progress => {
this.webContents!.send('uploadProgress', progress)
})
picgo.on('beforeTransform', ctx => {
if (db.get('settings.uploadNotification')) {
const notification = new Notification({
title: '上传进度',
body: '正在上传'
})
notification.show()
}
})
picgo.helper.beforeUploadPlugins.register('renameFn', {
handle: async ctx => {
const rename = picgo.getConfig('settings.rename')
const autoRename = picgo.getConfig('settings.autoRename')
const rename = db.get('settings.rename')
const autoRename = db.get('settings.autoRename')
await Promise.all(ctx.output.map(async (item, index) => {
let name: undefined | string | null
let fileName: string | undefined
@@ -128,7 +113,7 @@ class Uploader {
fileName = item.fileName
}
if (rename) {
const window = createRenameWindow(win)
const window = createRenameWindow(this.currentWindow!)
await waitForShow(window.webContents)
window.webContents.send('rename', fileName, window.webContents.id)
name = await waitForRename(window, window.webContents.id)
@@ -137,46 +122,40 @@ class Uploader {
}))
}
})
}
picgo.on('beforeTransform', ctx => {
if (ctx.getConfig('settings.uploadNotification')) {
const notification = new Notification({
title: '上传进度',
body: '正在上传'
})
notification.show()
}
})
setWebContents (webContents: WebContents) {
this.webContents = webContents
return this
}
picgo.upload(input)
upload (img?: IUploadOption): Promise<ImgInfo[]|false> {
this.currentWindow = BrowserWindow.fromWebContents(this.webContents!)
picgo.on('notification', message => {
const notification = new Notification(message)
notification.show()
})
picgo.on('uploadProgress', progress => {
this.webContents.send('uploadProgress', progress)
})
picgo.upload(img)
return new Promise((resolve) => {
picgo.on('finished', ctx => {
picgo.once('finished', ctx => {
if (ctx.output.every((item: ImgInfo) => item.imgUrl)) {
resolve(ctx.output)
} else {
resolve(false)
}
picgo.removeAllListeners('failed')
})
picgo.on('failed', ctx => {
const notification = new Notification({
title: '上传失败',
body: '请检查配置和上传的文件是否符合要求'
})
notification.show()
picgo.once('failed', ctx => {
setTimeout(() => {
const notification = new Notification({
title: '上传失败',
body: '请检查配置和上传的文件是否符合要求'
})
notification.show()
}, 500)
picgo.removeAllListeners('finished')
resolve(false)
})
})
}
}
export default Uploader
export default new Uploader()