Skip to content

Commit

Permalink
✨ Feature(custom): refactor upload and delete api
Browse files Browse the repository at this point in the history
  • Loading branch information
Kuingsmile committed Mar 20, 2024
1 parent 922f04f commit 475b85e
Show file tree
Hide file tree
Showing 2 changed files with 109 additions and 124 deletions.
192 changes: 96 additions & 96 deletions src/main/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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')

Expand Down Expand Up @@ -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<IServerConfig>('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}`)
Expand All @@ -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)
}
Expand All @@ -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()
}
}
Expand Down
41 changes: 13 additions & 28 deletions src/main/server/routerManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,19 @@ router.post('/upload', async ({
urlparams?: URLSearchParams
}): Promise<void> => {
try {
const picbed = urlparams?.get('picbed')
const passedKey = urlparams?.get('key')
const serverKey = picgo.getConfig('settings.serverKey') || ''
if (serverKey && passedKey !== serverKey) {
handleResponse({
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 = ''
Expand Down Expand Up @@ -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({
Expand Down

0 comments on commit 475b85e

Please sign in to comment.