From 475b85eb1f11b972aa29abb07435525ef1e8348d Mon Sep 17 00:00:00 2001 From: Kuingsmile Date: Wed, 20 Mar 2024 13:31:36 +0800 Subject: [PATCH] :sparkles: Feature(custom): refactor upload and delete api --- src/main/server/index.ts | 192 +++++++++++++++---------------- src/main/server/routerManager.ts | 41 +++---- 2 files changed, 109 insertions(+), 124 deletions(-) diff --git a/src/main/server/index.ts b/src/main/server/index.ts index a45387e9..2eff0b98 100644 --- a/src/main/server/index.ts +++ b/src/main/server/index.ts @@ -14,6 +14,8 @@ import fs from 'fs-extra' import { marked } from 'marked' import { markdownContent } from './apiDoc' +const DEFAULT_PORT = 36677 +const DEFAULT_HOST = '0.0.0.0' const appPath = app.getPath('userData') const serverTempDir = path.join(appPath, 'serverTemp') @@ -44,117 +46,117 @@ class Server { private config: IServerConfig constructor () { + this.config = this.getConfigWithDefaults() + this.httpServer = http.createServer(this.handleRequest) + } + + getConfigWithDefaults () { let config = picgo.getConfig('settings.server') - const result = this.checkIfConfigIsValid(config) - if (result) { - this.config = config - if (this.config.host === '127.0.0.1') { - this.config.host = '0.0.0.0' - } - } else { - config = { - port: 36677, - host: '0.0.0.0', - enable: true - } - this.config = config - picgo.saveConfig({ - 'settings.server': config - }) + if (!this.isValidConfig(config)) { + config = { port: DEFAULT_PORT, host: DEFAULT_HOST, enable: true } + picgo.saveConfig({ 'settings.server': config }) } - this.httpServer = http.createServer(this.handleRequest) + config.host = config.host === '127.0.0.1' ? '0.0.0.0' : config.host + return config } - private checkIfConfigIsValid (config: IObj | undefined) { + private isValidConfig (config: IObj | undefined) { return config && config.port && config.host && (config.enable !== undefined) } private handleRequest = (request: http.IncomingMessage, response: http.ServerResponse) => { - if (request.method === 'OPTIONS') { - handleResponse({ - response - }) - return + switch (request.method) { + case 'OPTIONS': + handleResponse({ response }) + break + case 'POST': + this.handlePostRequest(request, response) + break + case 'GET': + this.handleGetRequest(request, response) + break + default: + logger.warn(`[PicList Server] don't support [${request.method}] method`) + response.statusCode = 405 + response.end() } + } - if (request.method === 'POST') { - const [url, query] = request.url!.split('?') - if (!routers.getHandler(url!)) { - logger.warn(`[PicList Server] don't support [${url}] url`) - handleResponse({ - response, - statusCode: 404, - body: { - success: false + private handlePostRequest = (request: http.IncomingMessage, response: http.ServerResponse) => { + const [url, query] = request.url!.split('?') + if (!routers.getHandler(url!)) { + logger.warn(`[PicList Server] don't support [${url}] url`) + handleResponse({ + response, + statusCode: 404, + body: { + success: false + } + }) + } else { + if (request.headers['content-type'] && request.headers['content-type'].startsWith('multipart/form-data')) { + // @ts-ignore + uploadMulter.any()(request, response, (err: any) => { + if (err) { + logger.info('[PicList Server]', err) + return handleResponse({ + response, + body: { + success: false, + message: 'Error processing formData' + } + }) } - }) - } else { - if (request.headers['content-type'] && request.headers['content-type'].startsWith('multipart/form-data')) { // @ts-ignore - uploadMulter.any()(request, response, (err: any) => { - if (err) { - logger.info('[PicList Server]', err) - return handleResponse({ - response, - body: { - success: false, - message: 'Error processing formData' - } - }) - } - // @ts-ignore - const list = request.files.map(file => file.path) - logger.info('[PicList Server] get a formData request') - const handler = routers.getHandler(url)?.handler - if (handler) { - handler({ - list, - response, - urlparams: query ? new URLSearchParams(query) : undefined - }) - } - }) - } else { - let body: string = '' - let postObj: IObj - request.on('data', chunk => { - body += chunk - }) - request.on('end', () => { - try { - postObj = (body === '') ? {} : JSON.parse(body) - } catch (err: any) { - logger.error('[PicList Server]', err) - return handleResponse({ - response, - body: { - success: false, - message: 'Not sending data in JSON format' - } - }) - } - logger.info('[PicList Server] get the request', body) - const handler = routers.getHandler(url!)?.handler - handler!({ - ...postObj, + const list = request.files.map(file => file.path) + logger.info('[PicList Server] get a formData request') + const handler = routers.getHandler(url)?.handler + if (handler) { + handler({ + list, response, urlparams: query ? new URLSearchParams(query) : undefined }) + } + }) + } else { + let body: string = '' + let postObj: IObj + request.on('data', chunk => { + body += chunk + }) + request.on('end', () => { + try { + postObj = (body === '') ? {} : JSON.parse(body) + } catch (err: any) { + logger.error('[PicList Server]', err) + return handleResponse({ + response, + body: { + success: false, + message: 'Not sending data in JSON format' + } + }) + } + logger.info('[PicList Server] get the request', body) + const handler = routers.getHandler(url!)?.handler + handler!({ + ...postObj, + response, + urlparams: query ? new URLSearchParams(query) : undefined }) - } + }) } - } else if (request.method === 'GET') { - response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }) - const htmlContent = marked(markdownContent) - response.write(htmlContent) - response.end() - } else { - logger.warn(`[PicList Server] don't support [${request.method}] method`) - response.statusCode = 404 - response.end() } } + private handleGetRequest = (_request: http.IncomingMessage, response: http.ServerResponse) => { + response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' }) + const htmlContent = marked(markdownContent) + response.write(htmlContent) + response.end() + } + // port as string is a bug private listen = (port: number | string) => { logger.info(`[PicList Server] is listening at ${port} of ${this.config.host}`) @@ -173,12 +175,13 @@ class Server { // to solve the auto number problem this.listen((port as number) + 1) } + } else { + logger.error('[PicList Server]', err) } }) } startup () { - console.log('startup', this.config.enable) if (this.config.enable) { this.listen(this.config.port) } @@ -192,11 +195,8 @@ class Server { } restart () { - this.config = picgo.getConfig('settings.server') - if (this.config.host === '127.0.0.1') { - this.config.host = '0.0.0.0' - } this.shutdown() + this.config = this.getConfigWithDefaults() this.startup() } } diff --git a/src/main/server/routerManager.ts b/src/main/server/routerManager.ts index bde62313..a843ae3f 100644 --- a/src/main/server/routerManager.ts +++ b/src/main/server/routerManager.ts @@ -32,7 +32,6 @@ router.post('/upload', async ({ urlparams?: URLSearchParams }): Promise => { try { - const picbed = urlparams?.get('picbed') const passedKey = urlparams?.get('key') const serverKey = picgo.getConfig('settings.serverKey') || '' if (serverKey && passedKey !== serverKey) { @@ -40,11 +39,12 @@ router.post('/upload', async ({ response, body: { success: false, - message: 'server key is not correct' + message: 'server key is uncorrect' } }) return } + const picbed = urlparams?.get('picbed') let currentPicBedType = '' let currentPicBedConfig = {} as IStringKeyMap let currentPicBedConfigId = '' @@ -176,36 +176,21 @@ router.post('/delete', async ({ return } try { - // 区分是否是加密的数据,如果不是直接传入list,如果是,解密后再传入 const treatList = list.map(item => { - if (item.isEncrypted) { - const aesHelper = new AESHelper() - const data = aesHelper.decrypt(item.EncryptedData) - return JSON.parse(data) - } else { - return item - } + if (!item.isEncrypted) return item + const aesHelper = new AESHelper() + return JSON.parse(aesHelper.decrypt(item.EncryptedData)) }) const result = await deleteChoosedFiles(treatList) const successCount = result.filter(item => item).length - const failCount = result.filter(item => !item).length - if (successCount) { - handleResponse({ - response, - body: { - success: true, - message: `delete success: ${successCount}, fail: ${failCount}` - } - }) - } else { - handleResponse({ - response, - body: { - success: false, - message: deleteErrorMessage - } - }) - } + const failCount = result.length - successCount + handleResponse({ + response, + body: { + success: !!successCount, + message: successCount ? `delete success: ${successCount}, fail: ${failCount}` : deleteErrorMessage + } + }) } catch (err: any) { logger.error(err) handleResponse({