🔨 Refactor(custom): refactor manage api to be more concise

This commit is contained in:
Kuingsmile
2025-08-29 10:17:26 +08:00
parent 3e98fd4325
commit 7df95c8328

View File

@@ -26,6 +26,36 @@ export class ManageApi extends EventEmitter implements IManageApiType {
logger: ManageLogger logger: ManageLogger
currentPicBedConfig: IPicBedMangeConfig currentPicBedConfig: IPicBedMangeConfig
private readonly ALL_CLIENTS = [
'tcyun',
'aliyun',
'qiniu',
'upyun',
'smms',
'github',
'imgur',
's3plist',
'webdavplist',
'local',
'sftp'
]
private readonly CLOUD_STORAGE_CLIENTS = ['tcyun', 'aliyun', 'qiniu', 's3plist']
private readonly BASIC_API_CLIENTS = ['tcyun', 'aliyun', 'qiniu', 'github', 'imgur', 's3plist']
private readonly FOLDER_SUPPORT_CLIENTS = [
'tcyun',
'aliyun',
'qiniu',
'upyun',
'github',
's3plist',
'webdavplist',
'local',
'sftp'
]
private readonly FILE_LIST_CLIENTS = ['tcyun', 'aliyun', 'qiniu', 'upyun', 'smms', 's3plist']
constructor(currentPicBed: string = '') { constructor(currentPicBed: string = '') {
super() super()
this.currentPicBed = currentPicBed || 'placeholder' this.currentPicBed = currentPicBed || 'placeholder'
@@ -48,83 +78,101 @@ export class ManageApi extends EventEmitter implements IManageApiType {
this.logger.error(formatError(err, param)) this.logger.error(formatError(err, param))
} }
private readonly clientFactories = {
aliyun: () =>
new API.AliyunApi(this.currentPicBedConfig.accessKeyId, this.currentPicBedConfig.accessKeySecret, this.logger),
github: () =>
new API.GithubApi(
this.currentPicBedConfig.token,
this.currentPicBedConfig.githubUsername,
this.currentPicBedConfig.proxy,
this.logger
),
imgur: () =>
new API.ImgurApi(
this.currentPicBedConfig.imgurUserName,
this.currentPicBedConfig.accessToken,
this.currentPicBedConfig.proxy,
this.logger
),
local: () => new API.LocalApi(this.logger),
qiniu: () => new API.QiniuApi(this.currentPicBedConfig.accessKey, this.currentPicBedConfig.secretKey, this.logger),
smms: () => new API.SmmsApi(this.currentPicBedConfig.token, this.logger),
s3plist: () =>
new API.S3plistApi(
this.currentPicBedConfig.accessKeyId,
this.currentPicBedConfig.secretAccessKey,
this.currentPicBedConfig.endpoint,
this.currentPicBedConfig.sslEnabled,
this.currentPicBedConfig.s3ForcePathStyle,
this.currentPicBedConfig.proxy,
this.logger,
this.currentPicBedConfig.dogeCloudSupport || false,
this.currentPicBedConfig.bucketName || ''
),
sftp: () =>
new API.SftpApi(
this.currentPicBedConfig.host,
this.currentPicBedConfig.port,
this.currentPicBedConfig.username,
this.currentPicBedConfig.password,
this.currentPicBedConfig.privateKey,
this.currentPicBedConfig.passphrase,
this.currentPicBedConfig.fileMode,
this.currentPicBedConfig.dirMode,
this.logger
),
tcyun: () => new API.TcyunApi(this.currentPicBedConfig.secretId, this.currentPicBedConfig.secretKey, this.logger),
upyun: () =>
new API.UpyunApi(
this.currentPicBedConfig.bucketName,
this.currentPicBedConfig.operator,
this.currentPicBedConfig.password,
this.logger,
this.currentPicBedConfig.antiLeechToken,
this.currentPicBedConfig.expireTime
),
webdavplist: () =>
new API.WebdavplistApi(
this.currentPicBedConfig.endpoint,
this.currentPicBedConfig.username,
this.currentPicBedConfig.password,
this.currentPicBedConfig.sslEnabled,
this.currentPicBedConfig.proxy,
this.currentPicBedConfig.authType,
this.logger
)
}
createClient() { createClient() {
const name = this.currentPicBedConfig.picBedName const factory = this.clientFactories[this.currentPicBedConfig.picBedName as keyof typeof this.clientFactories]
switch (name) { return factory ? factory() : ({} as any)
case 'aliyun': }
return new API.AliyunApi(
this.currentPicBedConfig.accessKeyId, private async executeWithClient<T>(
this.currentPicBedConfig.accessKeySecret, supportedProviders: string[],
this.logger method: string,
) operation: (client: any) => Promise<T>,
case 'github': defaultValue: T
return new API.GithubApi( ): Promise<T> {
this.currentPicBedConfig.token, if (!supportedProviders.includes(this.currentPicBedConfig.picBedName)) {
this.currentPicBedConfig.githubUsername, return defaultValue
this.currentPicBedConfig.proxy,
this.logger
)
case 'imgur':
return new API.ImgurApi(
this.currentPicBedConfig.imgurUserName,
this.currentPicBedConfig.accessToken,
this.currentPicBedConfig.proxy,
this.logger
)
case 'local':
return new API.LocalApi(this.logger)
case 'qiniu':
return new API.QiniuApi(this.currentPicBedConfig.accessKey, this.currentPicBedConfig.secretKey, this.logger)
case 'smms':
return new API.SmmsApi(this.currentPicBedConfig.token, this.logger)
case 's3plist':
return new API.S3plistApi(
this.currentPicBedConfig.accessKeyId,
this.currentPicBedConfig.secretAccessKey,
this.currentPicBedConfig.endpoint,
this.currentPicBedConfig.sslEnabled,
this.currentPicBedConfig.s3ForcePathStyle,
this.currentPicBedConfig.proxy,
this.logger,
this.currentPicBedConfig.dogeCloudSupport || false,
this.currentPicBedConfig.bucketName || ''
)
case 'sftp':
return new API.SftpApi(
this.currentPicBedConfig.host,
this.currentPicBedConfig.port,
this.currentPicBedConfig.username,
this.currentPicBedConfig.password,
this.currentPicBedConfig.privateKey,
this.currentPicBedConfig.passphrase,
this.currentPicBedConfig.fileMode,
this.currentPicBedConfig.dirMode,
this.logger
)
case 'tcyun':
return new API.TcyunApi(this.currentPicBedConfig.secretId, this.currentPicBedConfig.secretKey, this.logger)
case 'upyun':
return new API.UpyunApi(
this.currentPicBedConfig.bucketName,
this.currentPicBedConfig.operator,
this.currentPicBedConfig.password,
this.logger,
this.currentPicBedConfig.antiLeechToken,
this.currentPicBedConfig.expireTime
)
case 'webdavplist':
return new API.WebdavplistApi(
this.currentPicBedConfig.endpoint,
this.currentPicBedConfig.username,
this.currentPicBedConfig.password,
this.currentPicBedConfig.sslEnabled,
this.currentPicBedConfig.proxy,
this.currentPicBedConfig.authType,
this.logger
)
default:
return {} as any
} }
try {
const client = this.createClient() as any
return await operation(client)
} catch (error: any) {
this.errorMsg(error, this.getMsgParam(method))
return defaultValue
}
}
private sendDefaultResult(eventName: string, defaultResult: any) {
const window = windowManager.get(IWindowList.SETTING_WINDOW)!
window.webContents.send(eventName, defaultResult)
ipcMain.removeAllListeners(
eventName === refreshDownloadFileTransferList ? cancelDownloadLoadingFileList : 'cancelLoadingFileList'
)
} }
private getPicBedConfig(picBedName: string): IPicBedMangeConfig { private getPicBedConfig(picBedName: string): IPicBedMangeConfig {
@@ -190,46 +238,19 @@ export class ManageApi extends EventEmitter implements IManageApiType {
unset(this.getConfig(key), propName) unset(this.getConfig(key), propName)
} }
async getBucketList(param?: IStringKeyMap | undefined): Promise<any> { async getBucketList(_?: IStringKeyMap | undefined): Promise<any> {
let client const staticBuckets = {
const name = this.currentPicBedConfig.picBedName.replace('plist', '') upyun: [{ Name: this.currentPicBedConfig.bucketName, Location: 'upyun', CreationDate: new Date().toISOString() }],
switch (this.currentPicBedConfig.picBedName) { smms: [{ Name: 'smms', Location: 'smms', CreationDate: new Date().toISOString() }],
case 'tcyun': webdavplist: [{ Name: 'webdav', Location: 'webdav', CreationDate: new Date().toISOString() }],
case 'aliyun': local: [{ Name: 'local', Location: 'local', CreationDate: new Date().toISOString() }],
case 'qiniu': sftp: [{ Name: 'sftp', Location: 'sftp', CreationDate: new Date().toISOString() }]
case 'github':
case 'imgur':
case 's3plist':
try {
client = this.createClient()
return await client.getBucketList()
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('getBucketList'))
return []
}
case 'upyun':
return [
{
Name: this.currentPicBedConfig.bucketName,
Location: 'upyun',
CreationDate: new Date().toISOString()
}
]
case 'smms':
case 'webdavplist':
case 'local':
case 'sftp':
return [
{
Name: name,
Location: name,
CreationDate: new Date().toISOString()
}
]
default:
console.log(param)
return []
} }
const staticResult = staticBuckets[this.currentPicBedConfig.picBedName as keyof typeof staticBuckets]
if (staticResult) return staticResult
return this.executeWithClient(this.BASIC_API_CLIENTS, 'getBucketList', client => client.getBucketList(), [])
} }
async getBucketInfo(param?: IStringKeyMap | undefined): Promise<IStringKeyMap | IManageError> { async getBucketInfo(param?: IStringKeyMap | undefined): Promise<IStringKeyMap | IManageError> {
@@ -238,125 +259,66 @@ export class ManageApi extends EventEmitter implements IManageApiType {
} }
async getBucketDomain(param: IStringKeyMap): Promise<IStringKeyMap | IManageError> { async getBucketDomain(param: IStringKeyMap): Promise<IStringKeyMap | IManageError> {
let client const staticDomains = {
switch (this.currentPicBedConfig.picBedName) { upyun: [this.currentPicBedConfig.customUrl],
case 'tcyun': smms: ['https://smms.app'],
case 'aliyun': imgur: ['https://imgur.com']
case 'qiniu':
case 'github':
try {
client = this.createClient() as any
return await client.getBucketDomain(param)
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('getBucketDomain'))
return []
}
case 'upyun':
return [this.currentPicBedConfig.customUrl]
case 'smms':
return ['https://smms.app']
case 'imgur':
return ['https://imgur.com']
default:
return []
} }
const staticResult = staticDomains[this.currentPicBedConfig.picBedName as keyof typeof staticDomains]
if (staticResult) return staticResult
const supportedClients = ['tcyun', 'aliyun', 'qiniu', 'github']
return this.executeWithClient(supportedClients, 'getBucketDomain', client => client.getBucketDomain(param), [])
} }
async createBucket(param?: IStringKeyMap): Promise<boolean> { async createBucket(param?: IStringKeyMap): Promise<boolean> {
let client return this.executeWithClient(
switch (this.currentPicBedConfig.picBedName) { this.CLOUD_STORAGE_CLIENTS,
case 'tcyun': 'createBucket',
case 'aliyun': client => client.createBucket(param!),
case 'qiniu': false
case 's3plist': )
try {
client = this.createClient() as any
return await client.createBucket(param!)
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('createBucket'))
return false
}
default:
return false
}
} }
async deleteBucket(param?: IStringKeyMap): Promise<boolean> { async deleteBucket(_?: IStringKeyMap): Promise<boolean> {
console.log(param)
return false return false
} }
async getOperatorList(param?: IStringKeyMap): Promise<string[] | IManageError> { async getOperatorList(_?: IStringKeyMap): Promise<string[] | IManageError> {
console.log(param)
return [] return []
} }
async addOperator(param?: IStringKeyMap): Promise<boolean> { async addOperator(_?: IStringKeyMap): Promise<boolean> {
console.log(param)
return false return false
} }
async deleteOperator(param?: IStringKeyMap): Promise<boolean> { async deleteOperator(_?: IStringKeyMap): Promise<boolean> {
console.log(param)
return false return false
} }
async getBucketAclPolicy(param?: IStringKeyMap): Promise<IStringKeyMap | IManageError> { async getBucketAclPolicy(_?: IStringKeyMap): Promise<IStringKeyMap | IManageError> {
console.log(param)
return {} return {}
} }
async setBucketAclPolicy(param?: IStringKeyMap): Promise<boolean> { async setBucketAclPolicy(param?: IStringKeyMap): Promise<boolean> {
let client if (this.currentPicBedConfig.picBedName !== 'qiniu') return false
switch (this.currentPicBedConfig.picBedName) { return this.executeWithClient(['qiniu'], 'setBucketAclPolicy', client => client.setBucketAclPolicy(param!), false)
case 'qiniu':
try {
client = new API.QiniuApi(this.currentPicBedConfig.accessKey, this.currentPicBedConfig.secretKey, this.logger)
return await client.setBucketAclPolicy(param!)
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('setBucketAclPolicy'))
return false
}
default:
return false
}
} }
async getBucketListRecursively(param?: IStringKeyMap): Promise<IStringKeyMap | IManageError> { async getBucketListRecursively(param?: IStringKeyMap): Promise<IStringKeyMap | IManageError> {
let client const defaultResult = { fullList: [], success: false, finished: true }
let window
const defaultResult = { try {
fullList: [], return await this.executeWithClient(
success: false, this.ALL_CLIENTS,
finished: true 'getBucketListRecursively',
} client => client.getBucketListRecursively(param!),
switch (this.currentPicBedConfig.picBedName) { defaultResult
case 'tcyun': )
case 'aliyun': } catch (error: any) {
case 'qiniu': this.sendDefaultResult(refreshDownloadFileTransferList, defaultResult)
case 'upyun': return {}
case 'smms':
case 'github':
case 'imgur':
case 's3plist':
case 'webdavplist':
case 'local':
case 'sftp':
try {
client = this.createClient() as any
return await client.getBucketListRecursively(param!)
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('getBucketListRecursively'))
window = windowManager.get(IWindowList.SETTING_WINDOW)!
window.webContents.send(refreshDownloadFileTransferList, defaultResult)
ipcMain.removeAllListeners(cancelDownloadLoadingFileList)
return {}
}
default:
window = windowManager.get(IWindowList.SETTING_WINDOW)!
window.webContents.send(refreshDownloadFileTransferList, defaultResult)
ipcMain.removeAllListeners(cancelDownloadLoadingFileList)
return {}
} }
} }
@@ -366,40 +328,18 @@ export class ManageApi extends EventEmitter implements IManageApiType {
* @returns * @returns
*/ */
async getBucketListBackstage(param?: IStringKeyMap): Promise<IStringKeyMap | IManageError> { async getBucketListBackstage(param?: IStringKeyMap): Promise<IStringKeyMap | IManageError> {
let client const defaultResult = { fullList: [], success: false, finished: true }
let window
const defaultResult = { try {
fullList: [], return await this.executeWithClient(
success: false, this.ALL_CLIENTS,
finished: true 'getBucketListBackstage',
} client => client.getBucketListBackstage(param!),
switch (this.currentPicBedConfig.picBedName) { defaultResult
case 'tcyun': )
case 'aliyun': } catch (error: any) {
case 'qiniu': this.sendDefaultResult('refreshFileTransferList', defaultResult)
case 'upyun': return {}
case 'smms':
case 'github':
case 'imgur':
case 's3plist':
case 'webdavplist':
case 'local':
case 'sftp':
try {
client = this.createClient() as any
return await client.getBucketListBackstage(param!)
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('getBucketListBackstage'))
window = windowManager.get(IWindowList.SETTING_WINDOW)!
window.webContents.send('refreshFileTransferList', defaultResult)
ipcMain.removeAllListeners('cancelLoadingFileList')
return {}
}
default:
window = windowManager.get(IWindowList.SETTING_WINDOW)!
window.webContents.send('refreshFileTransferList', defaultResult)
ipcMain.removeAllListeners('cancelLoadingFileList')
return {}
} }
} }
@@ -413,206 +353,81 @@ export class ManageApi extends EventEmitter implements IManageApiType {
* fileSize: 文件大小 * fileSize: 文件大小
**/ **/
async getBucketFileList(param?: IStringKeyMap): Promise<IStringKeyMap | IManageError> { async getBucketFileList(param?: IStringKeyMap): Promise<IStringKeyMap | IManageError> {
const defaultResponse = { const defaultResponse = { fullList: [] as any, isTruncated: false, nextMarker: '', success: false }
fullList: [] as any, return this.executeWithClient(
isTruncated: false, this.FILE_LIST_CLIENTS,
nextMarker: '', 'getBucketFileList',
success: false client => client.getBucketFileList(param!),
} defaultResponse
let client )
switch (this.currentPicBedConfig.picBedName) {
case 'tcyun':
case 'aliyun':
case 'qiniu':
case 'upyun':
case 'smms':
case 's3plist':
try {
client = this.createClient()
return await client.getBucketFileList(param!)
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('getBucketFileList'))
return defaultResponse
}
default:
return defaultResponse
}
} }
async deleteBucketFile(param?: IStringKeyMap): Promise<boolean> { async deleteBucketFile(param?: IStringKeyMap): Promise<boolean> {
let client return this.executeWithClient(
switch (this.currentPicBedConfig.picBedName) { this.ALL_CLIENTS,
case 'tcyun': 'deleteBucketFile',
case 'aliyun': client => client.deleteBucketFile(param!),
case 'qiniu': false
case 'upyun': )
case 'smms':
case 'github':
case 'imgur':
case 's3plist':
case 'webdavplist':
case 'local':
case 'sftp':
try {
client = this.createClient() as any
const res = await client.deleteBucketFile(param!)
return res
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('deleteBucketFile'))
return false
}
default:
return false
}
} }
async deleteBucketFolder(param?: IStringKeyMap): Promise<boolean> { async deleteBucketFolder(param?: IStringKeyMap): Promise<boolean> {
let client return this.executeWithClient(
switch (this.currentPicBedConfig.picBedName) { this.FOLDER_SUPPORT_CLIENTS,
case 'tcyun': 'deleteBucketFolder',
case 'aliyun': client => client.deleteBucketFolder(param!),
case 'qiniu': false
case 'upyun': )
case 'github':
case 's3plist':
case 'webdavplist':
case 'local':
case 'sftp':
try {
client = this.createClient() as any
return await client.deleteBucketFolder(param!)
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('deleteBucketFolder'))
return false
}
default:
return false
}
} }
async renameBucketFile(param?: IStringKeyMap): Promise<boolean> { async renameBucketFile(param?: IStringKeyMap): Promise<boolean> {
let client const supportedClients = ['tcyun', 'aliyun', 'qiniu', 'upyun', 's3plist', 'webdavplist', 'local', 'sftp']
switch (this.currentPicBedConfig.picBedName) { return this.executeWithClient(
case 'tcyun': supportedClients,
case 'aliyun': 'renameBucketFile',
case 'qiniu': client => client.renameBucketFile(param!),
case 'upyun': false
case 's3plist': )
case 'webdavplist':
case 'local':
case 'sftp':
try {
client = this.createClient() as any
return await client.renameBucketFile(param!)
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('renameBucketFile'))
return false
}
default:
return false
}
} }
async downloadBucketFile(param?: IStringKeyMap): Promise<boolean> { async downloadBucketFile(param?: IStringKeyMap): Promise<boolean> {
let client return this.executeWithClient(
switch (this.currentPicBedConfig.picBedName) { this.ALL_CLIENTS,
case 'tcyun': 'downloadBucketFile',
case 'aliyun': client => client.downloadBucketFile(param!),
case 'qiniu': false
case 'upyun': )
case 'smms':
case 'github':
case 'imgur':
case 's3plist':
case 'webdavplist':
case 'local':
case 'sftp':
try {
client = this.createClient() as any
const res = await client.downloadBucketFile(param!)
return res
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('downloadBucketFile'))
return false
}
default:
return false
}
} }
async copyMoveBucketFile(param?: IStringKeyMap): Promise<boolean> { async copyMoveBucketFile(_?: IStringKeyMap): Promise<boolean> {
console.log(param)
return false return false
} }
async createBucketFolder(param?: IStringKeyMap): Promise<boolean> { async createBucketFolder(param?: IStringKeyMap): Promise<boolean> {
let client return this.executeWithClient(
switch (this.currentPicBedConfig.picBedName) { this.FOLDER_SUPPORT_CLIENTS,
case 'tcyun': 'createBucketFolder',
case 'aliyun': client => client.createBucketFolder(param!),
case 'qiniu': false
case 'upyun': )
case 'github':
case 's3plist':
case 'webdavplist':
case 'local':
case 'sftp':
try {
client = this.createClient() as any
return await client.createBucketFolder(param!)
} catch (error) {
this.errorMsg(error, this.getMsgParam('createBucketFolder'))
return false
}
default:
return false
}
} }
async uploadBucketFile(param?: IStringKeyMap): Promise<boolean> { async uploadBucketFile(param?: IStringKeyMap): Promise<boolean> {
let client return this.executeWithClient(
switch (this.currentPicBedConfig.picBedName) { this.ALL_CLIENTS,
case 'tcyun': 'uploadBucketFile',
case 'aliyun': client => client.uploadBucketFile(param!),
case 'qiniu': false
case 'upyun': )
case 'smms':
case 'github':
case 'imgur':
case 's3plist':
case 'webdavplist':
case 'local':
case 'sftp':
try {
client = this.createClient() as any
return await client.uploadBucketFile(param!)
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('uploadBucketFile'))
return false
}
default:
return false
}
} }
async getPreSignedUrl(param?: IStringKeyMap): Promise<string> { async getPreSignedUrl(param?: IStringKeyMap): Promise<string> {
let client const supportedClients = ['tcyun', 'aliyun', 'qiniu', 'github', 's3plist', 'webdavplist']
switch (this.currentPicBedConfig.picBedName) { return this.executeWithClient(
case 'tcyun': supportedClients,
case 'aliyun': 'getPreSignedUrl',
case 'qiniu': client => client.getPreSignedUrl(param!),
case 'github': 'error'
case 's3plist': )
case 'webdavplist':
try {
client = this.createClient() as any
return await client.getPreSignedUrl(param!)
} catch (error: any) {
this.errorMsg(error, this.getMsgParam('getPreSignedUrl'))
return 'error'
}
default:
return 'error'
}
} }
} }