🔨 Refactor: rebuild multi-config communication way

This commit is contained in:
PiEgg 2023-01-02 14:13:27 +08:00
parent 5969daedac
commit cbafe66a75
10 changed files with 173 additions and 81 deletions

View File

@ -29,14 +29,14 @@ import {
OPEN_WINDOW, OPEN_WINDOW,
GET_LANGUAGE_LIST, GET_LANGUAGE_LIST,
SET_CURRENT_LANGUAGE, SET_CURRENT_LANGUAGE,
GET_CURRENT_LANGUAGE, GET_CURRENT_LANGUAGE
RPC_ACTIONS
} from '#/events/constants' } from '#/events/constants'
import { GalleryDB } from 'apis/core/datastore' import { GalleryDB } from 'apis/core/datastore'
import { IObject, IFilter } from '@picgo/store/dist/types' import { IObject, IFilter } from '@picgo/store/dist/types'
import pasteTemplate from '../utils/pasteTemplate' import pasteTemplate from '../utils/pasteTemplate'
import { i18nManager, T } from '~/main/i18n' import { i18nManager, T } from '~/main/i18n'
import { rpcServer } from './rpc'
// eslint-disable-next-line // eslint-disable-next-line
const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require const requireFunc = typeof __webpack_require__ === 'function' ? __non_webpack_require__ : require
@ -397,7 +397,7 @@ const handleI18n = () => {
} }
const handleRPCActions = () => { const handleRPCActions = () => {
ipcMain.on(RPC_ACTIONS, (event: IpcMainEvent, action: IRPCActions, ...args: any[], callbackId: string) => {}) rpcServer.start()
} }
export default { export default {

View File

@ -0,0 +1,83 @@
import { ipcMain, IpcMainEvent } from 'electron'
import { IRPCActionType } from '~/universal/types/enum'
import { RPC_ACTIONS } from '#/events/constants'
import {
deleteUploaderConfig,
getUploaderConfigList,
selectUploaderConfig,
updateUploaderConfig
} from '~/universal/utils/handleUploaderConfig'
class RPCServer {
start () {
ipcMain.on(RPC_ACTIONS, (event: IpcMainEvent, action: IRPCActionType, args: any[], callbackId: string) => {
try {
switch (action) {
case IRPCActionType.GET_PICBED_CONFIG_LIST: {
const configList = this.getPicBedConfigList(args as IGetUploaderConfigListArgs)
this.sendBack(event, action, configList, callbackId)
break
}
case IRPCActionType.DELETE_PICBED_CONFIG: {
const res = this.deleteUploaderConfig(args as IDeleteUploaderConfigArgs)
this.sendBack(event, action, res, callbackId)
break
}
case IRPCActionType.SELECT_UPLOADER: {
this.selectUploaderConfig(args as ISelectUploaderConfigArgs)
this.sendBack(event, action, true, callbackId)
break
}
case IRPCActionType.UPDATE_UPLOADER_CONFIG: {
this.updateUploaderConfig(args as IUpdateUploaderConfigArgs)
this.sendBack(event, action, true, callbackId)
break
}
default: {
this.sendBack(event, action, null, callbackId)
break
}
}
} catch (e) {
this.sendBack(event, action, null, callbackId)
}
})
}
/**
* if sendback data is null, then it means that the action is not supported or error occurs
*/
private sendBack (event: IpcMainEvent, action: IRPCActionType, data: any, callbackId: string) {
event.sender.send(RPC_ACTIONS, data, action, callbackId)
}
private getPicBedConfigList (args: IGetUploaderConfigListArgs) {
const [type] = args
const config = getUploaderConfigList(type)
return config
}
private deleteUploaderConfig (args: IDeleteUploaderConfigArgs) {
const [type, id] = args
const config = deleteUploaderConfig(type, id)
return config
}
private selectUploaderConfig (args: ISelectUploaderConfigArgs) {
const [type, id] = args
const config = selectUploaderConfig(type, id)
return config
}
private updateUploaderConfig (args: IUpdateUploaderConfigArgs) {
const [type, id, config] = args
const res = updateUploaderConfig(type, id, config)
return res
}
}
const rpcServer = new RPCServer()
export {
rpcServer
}

View File

@ -45,8 +45,8 @@
<script lang="ts"> <script lang="ts">
import { Component, Vue } from 'vue-property-decorator' import { Component, Vue } from 'vue-property-decorator'
import dayjs from 'dayjs' import dayjs from 'dayjs'
import { completeUploaderMetaConfig } from '../utils/uploader'
import mixin from '@/utils/ConfirmButtonMixin' import mixin from '@/utils/ConfirmButtonMixin'
import { IRPCActionType } from '~/universal/types/enum'
@Component({ @Component({
name: 'UploaderConfigPage', name: 'UploaderConfigPage',
@ -58,9 +58,7 @@ export default class extends Vue {
defaultConfigId = ''; defaultConfigId = '';
async selectItem (id: string) { async selectItem (id: string) {
await this.saveConfig(`uploader.${this.type}.defaultId`, id) await this.triggerRPC<void>(IRPCActionType.SELECT_UPLOADER, this.type, id)
const activeConfig = this.curConfigList.find(i => i._id === id)
await this.saveConfig(`picBed.${this.type}`, activeConfig)
this.defaultConfigId = id this.defaultConfigId = id
} }
@ -70,39 +68,9 @@ export default class extends Vue {
} }
async getCurrentConfigList () { async getCurrentConfigList () {
const curUploaderConfig = await this.getConfig<IStringKeyMap>(`uploader.${this.type}`) ?? {} const configList = await this.triggerRPC<IUploaderConfigItem>(IRPCActionType.GET_PICBED_CONFIG_LIST, this.type)
let curConfigList = curUploaderConfig?.configList this.curConfigList = configList?.configList ?? []
this.defaultConfigId = curUploaderConfig?.defaultId this.defaultConfigId = configList?.defaultId ?? ''
if (!curConfigList) {
curConfigList = await this.fixUploaderConfig()
}
this.curConfigList = curConfigList
}
async fixUploaderConfig (): Promise<IStringKeyMap[]> {
const curUploaderConfig = await this.getConfig<IStringKeyMap>(`picBed.${this.type}`) ?? {}
if (!curUploaderConfig._id) {
Object.assign(
curUploaderConfig,
completeUploaderMetaConfig(curUploaderConfig)
)
}
const curUploaderConfigList = [curUploaderConfig]
await this.saveConfig(`uploader.${this.type}`, {
configList: curUploaderConfigList,
defaultId: curUploaderConfig._id
})
// fix exist config
await this.saveConfig(`picBed.${this.type}`, curUploaderConfig)
this.defaultConfigId = curUploaderConfig._id
return curUploaderConfigList
} }
openEditPage (configId: string) { openEditPage (configId: string) {
@ -123,15 +91,10 @@ export default class extends Vue {
} }
async deleteConfig (id: string) { async deleteConfig (id: string) {
if (this.curConfigList.length <= 1) return const res = await this.triggerRPC<IUploaderConfigItem | undefined>(IRPCActionType.DELETE_PICBED_CONFIG, this.type, id)
const updatedConfigList = this.curConfigList.filter(i => i._id !== id) if (!res) return
this.curConfigList = res.configList
if (id === this.defaultConfigId) { this.defaultConfigId = res.defaultId
await this.selectItem(updatedConfigList[0]._id)
}
await this.saveConfig(`uploader.${this.type}.configList`, updatedConfigList)
this.curConfigList = updatedConfigList
} }
addNewConfig () { addNewConfig () {

View File

@ -31,8 +31,7 @@ import {
ipcRenderer, ipcRenderer,
IpcRendererEvent IpcRendererEvent
} from 'electron' } from 'electron'
import { completeUploaderMetaConfig } from '@/utils/uploader' import { IRPCActionType } from '~/universal/types/enum'
import { trimValues } from '@/utils/common'
@Component({ @Component({
name: 'OtherPicBed', name: 'OtherPicBed',
@ -55,22 +54,7 @@ export default class extends Vue {
// @ts-ignore // @ts-ignore
const result = await this.$refs.configForm.validate() const result = await this.$refs.configForm.validate()
if (result !== false) { if (result !== false) {
const configListConfigPath = `uploader.${this.type}.configList` await this.triggerRPC<void>(IRPCActionType.UPDATE_UPLOADER_CONFIG, this.type, result?._id, result)
const configList = await this.getConfig<IStringKeyMap[]>(configListConfigPath)
// Finds the specified item from the config array and modifies it
const existItem = configList?.find(item => item._id === result._id)
// edit
if (existItem) {
Object.assign(existItem, trimValues(result), {
_updatedAt: Date.now()
})
} else { // add new
configList?.push(trimValues(completeUploaderMetaConfig(result)))
}
await this.saveConfig(configListConfigPath, configList)
existItem && await this.shouldUpdateDefaultConfig(existItem)
const successNotification = new Notification(this.$T('SETTINGS_RESULT'), { const successNotification = new Notification(this.$T('SETTINGS_RESULT'), {
body: this.$T('TIPS_SET_SUCCEED') body: this.$T('TIPS_SET_SUCCEED')
}) })

View File

@ -37,11 +37,12 @@ export default class extends Vue {
/** /**
* trigger RPC action * trigger RPC action
* TODO: create an isolate rpc handler
*/ */
triggerRPC<T> (action: IRPCActionType, ...args: any[]): Promise<T | undefined> { triggerRPC<T> (action: IRPCActionType, ...args: any[]): Promise<T | null> {
return new Promise((resolve) => { return new Promise((resolve) => {
const callbackId = uuid() const callbackId = uuid()
const callback = (event: IpcRendererEvent, data: T | undefined, returnActionType: IRPCActionType, returnCallbackId: string) => { const callback = (event: IpcRendererEvent, data: T | null, returnActionType: IRPCActionType, returnCallbackId: string) => {
if (returnCallbackId === callbackId && returnActionType === action) { if (returnCallbackId === callbackId && returnActionType === action) {
resolve(data) resolve(data)
ipcRenderer.removeListener(RPC_ACTIONS, callback) ipcRenderer.removeListener(RPC_ACTIONS, callback)

View File

@ -52,4 +52,8 @@ export enum IRemoteNoticeTriggerCount {
*/ */
export enum IRPCActionType { export enum IRPCActionType {
GET_PICBED_CONFIG_LIST = 'GET_PICBED_CONFIG_LIST', GET_PICBED_CONFIG_LIST = 'GET_PICBED_CONFIG_LIST',
DELETE_PICBED_CONFIG = 'DELETE_PICBED_CONFIG',
CHANGE_CURRENT_UPLOADER = 'CHANGE_CURRENT_UPLOADER',
SELECT_UPLOADER = 'SELECT_UPLOADER',
UPDATE_UPLOADER_CONFIG = 'UPDATE_UPLOADER_CONFIG',
} }

View File

@ -24,6 +24,7 @@ declare module 'vue/types/vue' {
saveConfig(data: IObj | string, value?: any): void saveConfig(data: IObj | string, value?: any): void
getConfig<T>(key?: string): Promise<T | undefined> getConfig<T>(key?: string): Promise<T | undefined>
setDefaultPicBed(picBed: string): void setDefaultPicBed(picBed: string): void
triggerRPC<T> (action: import('~/universal/types/enum').IRPCActionType, ...args: any[]): Promise<T | null>
defaultPicBed: string defaultPicBed: string
forceUpdate(): void forceUpdate(): void
sendToMain(channel: string, ...args: any[]): void sendToMain(channel: string, ...args: any[]): void

4
src/universal/types/rpc.d.ts vendored Normal file
View File

@ -0,0 +1,4 @@
type IGetUploaderConfigListArgs = [type: string]
type IDeleteUploaderConfigArgs = [type: string, id: string]
type ISelectUploaderConfigArgs = [type: string, id: string]
type IUpdateUploaderConfigArgs = [type: string, id: string, config: IStringKeyMap]

View File

@ -414,8 +414,12 @@ interface IUploaderListItemMetaInfo {
} }
interface IUploaderConfig { interface IUploaderConfig {
[picBedType: string]: { [picBedType: string]: IUploaderConfigItem
configList: (IStringKeyMap & IUploaderListItemMetaInfo)[]
defaultId: string
}
} }
interface IUploaderConfigItem {
configList: IUploaderConfigListItem[]
defaultId: string
}
type IUploaderConfigListItem = IStringKeyMap & IUploaderListItemMetaInfo

View File

@ -14,7 +14,7 @@ export const handleConfigWithFunction = (config: IPicGoPluginOriginConfig[]): IP
return config as IPicGoPluginConfig[] return config as IPicGoPluginConfig[]
} }
export const completeUploaderMetaConfig = (originData: IStringKeyMap): IStringKeyMap => { export const completeUploaderMetaConfig = (originData: IStringKeyMap): IUploaderConfigListItem => {
return Object.assign({ return Object.assign({
_configName: 'Default' _configName: 'Default'
}, trimValues(originData), { }, trimValues(originData), {
@ -46,8 +46,8 @@ export const getPicBedConfig = (type: string) => {
} }
} }
export const changeCurrentUploader = (type: string, config: IStringKeyMap, id?: string) => { export const changeCurrentUploader = (type: string, config?: IStringKeyMap, id?: string) => {
if (!type || !config) { if (!type) {
return return
} }
if (id) { if (id) {
@ -55,16 +55,37 @@ export const changeCurrentUploader = (type: string, config: IStringKeyMap, id?:
[`uploader.${type}.defaultId`]: id [`uploader.${type}.defaultId`]: id
}) })
} }
if (config) {
picgo.saveConfig({
[`picBed.${type}`]: config
})
}
picgo.saveConfig({ picgo.saveConfig({
'picBed.current': type, 'picBed.current': type,
'picBed.uploader': type, 'picBed.uploader': type
[`picBed.${type}`]: config
}) })
} }
export const getUploaderConfigList = (type: string) => { export const selectUploaderConfig = (type: string, id: string) => {
const { configList } = getUploaderConfigList(type)
const config = configList.find((item: IStringKeyMap) => item._id === id)
if (config) {
picgo.saveConfig({
[`uploader.${type}.defaultId`]: id,
[`picBed.${type}`]: config
})
}
}
export const getUploaderConfigList = (type: string): IUploaderConfigItem => {
if (!type) {
return {
configList: [],
defaultId: ''
}
}
const currentUploaderConfig = picgo.getConfig<IStringKeyMap>(`uploader.${type}`) ?? {} const currentUploaderConfig = picgo.getConfig<IStringKeyMap>(`uploader.${type}`) ?? {}
let configList = currentUploaderConfig.configList || [] let configList = currentUploaderConfig.configList
let defaultId = currentUploaderConfig.defaultId || '' let defaultId = currentUploaderConfig.defaultId || ''
if (!configList) { if (!configList) {
const res = upgradeUploaderConfig(type) const res = upgradeUploaderConfig(type)
@ -80,18 +101,24 @@ export const getUploaderConfigList = (type: string) => {
/** /**
* delete uploader config by type & id * delete uploader config by type & id
*/ */
export const deleteUploaderConfig = (type: string, id: string) => { export const deleteUploaderConfig = (type: string, id: string): IUploaderConfigItem | void => {
const { configList, defaultId } = getUploaderConfigList(type) const { configList, defaultId } = getUploaderConfigList(type)
if (configList.length <= 1) { if (configList.length <= 1) {
return return
} }
let newDefaultId = defaultId
const updatedConfigList = configList.filter((item: IStringKeyMap) => item._id !== id) const updatedConfigList = configList.filter((item: IStringKeyMap) => item._id !== id)
if (id === defaultId) { if (id === defaultId) {
newDefaultId = updatedConfigList[0]._id
changeCurrentUploader(type, updatedConfigList[0], updatedConfigList[0]._id) changeCurrentUploader(type, updatedConfigList[0], updatedConfigList[0]._id)
} }
picgo.saveConfig({ picgo.saveConfig({
[`uploader.${type}.configList`]: updatedConfigList [`uploader.${type}.configList`]: updatedConfigList
}) })
return {
configList: updatedConfigList,
defaultId: newDefaultId
}
} }
/** /**
@ -119,3 +146,24 @@ export const upgradeUploaderConfig = (type: string): {
defaultId: uploaderConfig._id defaultId: uploaderConfig._id
} }
} }
export const updateUploaderConfig = (type: string, id: string, config: IStringKeyMap) => {
const { configList, defaultId } = getUploaderConfigList(type)
const existConfig = configList.find((item: IStringKeyMap) => item._id === id)
let updatedConfig: IUploaderConfigListItem
let updatedDefaultId = defaultId
if (existConfig) {
updatedConfig = Object.assign(existConfig, trimValues(config), {
_updatedAt: Date.now()
})
} else {
updatedConfig = completeUploaderMetaConfig(config)
updatedDefaultId = updatedConfig._id
configList.push(updatedConfig)
}
picgo.saveConfig({
[`uploader.${type}.configList`]: configList,
[`uploader.${type}.defaultId`]: updatedDefaultId,
[`picBed.${type}`]: updatedConfig
})
}