mirror of
https://github.com/Kuingsmile/PicList.git
synced 2025-03-13 00:18:13 -04:00
✨ Feature(custom): refactor upload and delete api
This commit is contained in:
parent
922f04f672
commit
475b85eb1f
@ -14,6 +14,8 @@ import fs from 'fs-extra'
|
|||||||
import { marked } from 'marked'
|
import { marked } from 'marked'
|
||||||
import { markdownContent } from './apiDoc'
|
import { markdownContent } from './apiDoc'
|
||||||
|
|
||||||
|
const DEFAULT_PORT = 36677
|
||||||
|
const DEFAULT_HOST = '0.0.0.0'
|
||||||
const appPath = app.getPath('userData')
|
const appPath = app.getPath('userData')
|
||||||
const serverTempDir = path.join(appPath, 'serverTemp')
|
const serverTempDir = path.join(appPath, 'serverTemp')
|
||||||
|
|
||||||
@ -44,117 +46,117 @@ class Server {
|
|||||||
private config: IServerConfig
|
private config: IServerConfig
|
||||||
|
|
||||||
constructor () {
|
constructor () {
|
||||||
let config = picgo.getConfig<IServerConfig>('settings.server')
|
this.config = this.getConfigWithDefaults()
|
||||||
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
|
|
||||||
})
|
|
||||||
}
|
|
||||||
this.httpServer = http.createServer(this.handleRequest)
|
this.httpServer = http.createServer(this.handleRequest)
|
||||||
}
|
}
|
||||||
|
|
||||||
private checkIfConfigIsValid (config: IObj | undefined) {
|
getConfigWithDefaults () {
|
||||||
|
let config = picgo.getConfig<IServerConfig>('settings.server')
|
||||||
|
if (!this.isValidConfig(config)) {
|
||||||
|
config = { port: DEFAULT_PORT, host: DEFAULT_HOST, enable: true }
|
||||||
|
picgo.saveConfig({ 'settings.server': config })
|
||||||
|
}
|
||||||
|
config.host = config.host === '127.0.0.1' ? '0.0.0.0' : config.host
|
||||||
|
return config
|
||||||
|
}
|
||||||
|
|
||||||
|
private isValidConfig (config: IObj | undefined) {
|
||||||
return config && config.port && config.host && (config.enable !== undefined)
|
return config && config.port && config.host && (config.enable !== undefined)
|
||||||
}
|
}
|
||||||
|
|
||||||
private handleRequest = (request: http.IncomingMessage, response: http.ServerResponse) => {
|
private handleRequest = (request: http.IncomingMessage, response: http.ServerResponse) => {
|
||||||
if (request.method === 'OPTIONS') {
|
switch (request.method) {
|
||||||
handleResponse({
|
case 'OPTIONS':
|
||||||
response
|
handleResponse({ response })
|
||||||
})
|
break
|
||||||
return
|
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') {
|
private handlePostRequest = (request: http.IncomingMessage, response: http.ServerResponse) => {
|
||||||
const [url, query] = request.url!.split('?')
|
const [url, query] = request.url!.split('?')
|
||||||
if (!routers.getHandler(url!)) {
|
if (!routers.getHandler(url!)) {
|
||||||
logger.warn(`[PicList Server] don't support [${url}] url`)
|
logger.warn(`[PicList Server] don't support [${url}] url`)
|
||||||
handleResponse({
|
handleResponse({
|
||||||
response,
|
response,
|
||||||
statusCode: 404,
|
statusCode: 404,
|
||||||
body: {
|
body: {
|
||||||
success: false
|
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
|
// @ts-ignore
|
||||||
uploadMulter.any()(request, response, (err: any) => {
|
const list = request.files.map(file => file.path)
|
||||||
if (err) {
|
logger.info('[PicList Server] get a formData request')
|
||||||
logger.info('[PicList Server]', err)
|
const handler = routers.getHandler(url)?.handler
|
||||||
return handleResponse({
|
if (handler) {
|
||||||
response,
|
handler({
|
||||||
body: {
|
list,
|
||||||
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,
|
|
||||||
response,
|
response,
|
||||||
urlparams: query ? new URLSearchParams(query) : undefined
|
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
|
// port as string is a bug
|
||||||
private listen = (port: number | string) => {
|
private listen = (port: number | string) => {
|
||||||
logger.info(`[PicList Server] is listening at ${port} of ${this.config.host}`)
|
logger.info(`[PicList Server] is listening at ${port} of ${this.config.host}`)
|
||||||
@ -173,12 +175,13 @@ class Server {
|
|||||||
// to solve the auto number problem
|
// to solve the auto number problem
|
||||||
this.listen((port as number) + 1)
|
this.listen((port as number) + 1)
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
logger.error('[PicList Server]', err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
startup () {
|
startup () {
|
||||||
console.log('startup', this.config.enable)
|
|
||||||
if (this.config.enable) {
|
if (this.config.enable) {
|
||||||
this.listen(this.config.port)
|
this.listen(this.config.port)
|
||||||
}
|
}
|
||||||
@ -192,11 +195,8 @@ class Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
restart () {
|
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.shutdown()
|
||||||
|
this.config = this.getConfigWithDefaults()
|
||||||
this.startup()
|
this.startup()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -32,7 +32,6 @@ router.post('/upload', async ({
|
|||||||
urlparams?: URLSearchParams
|
urlparams?: URLSearchParams
|
||||||
}): Promise<void> => {
|
}): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
const picbed = urlparams?.get('picbed')
|
|
||||||
const passedKey = urlparams?.get('key')
|
const passedKey = urlparams?.get('key')
|
||||||
const serverKey = picgo.getConfig('settings.serverKey') || ''
|
const serverKey = picgo.getConfig('settings.serverKey') || ''
|
||||||
if (serverKey && passedKey !== serverKey) {
|
if (serverKey && passedKey !== serverKey) {
|
||||||
@ -40,11 +39,12 @@ router.post('/upload', async ({
|
|||||||
response,
|
response,
|
||||||
body: {
|
body: {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'server key is not correct'
|
message: 'server key is uncorrect'
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
const picbed = urlparams?.get('picbed')
|
||||||
let currentPicBedType = ''
|
let currentPicBedType = ''
|
||||||
let currentPicBedConfig = {} as IStringKeyMap
|
let currentPicBedConfig = {} as IStringKeyMap
|
||||||
let currentPicBedConfigId = ''
|
let currentPicBedConfigId = ''
|
||||||
@ -176,36 +176,21 @@ router.post('/delete', async ({
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
// 区分是否是加密的数据,如果不是直接传入list,如果是,解密后再传入
|
|
||||||
const treatList = list.map(item => {
|
const treatList = list.map(item => {
|
||||||
if (item.isEncrypted) {
|
if (!item.isEncrypted) return item
|
||||||
const aesHelper = new AESHelper()
|
const aesHelper = new AESHelper()
|
||||||
const data = aesHelper.decrypt(item.EncryptedData)
|
return JSON.parse(aesHelper.decrypt(item.EncryptedData))
|
||||||
return JSON.parse(data)
|
|
||||||
} else {
|
|
||||||
return item
|
|
||||||
}
|
|
||||||
})
|
})
|
||||||
const result = await deleteChoosedFiles(treatList)
|
const result = await deleteChoosedFiles(treatList)
|
||||||
const successCount = result.filter(item => item).length
|
const successCount = result.filter(item => item).length
|
||||||
const failCount = result.filter(item => !item).length
|
const failCount = result.length - successCount
|
||||||
if (successCount) {
|
handleResponse({
|
||||||
handleResponse({
|
response,
|
||||||
response,
|
body: {
|
||||||
body: {
|
success: !!successCount,
|
||||||
success: true,
|
message: successCount ? `delete success: ${successCount}, fail: ${failCount}` : deleteErrorMessage
|
||||||
message: `delete success: ${successCount}, fail: ${failCount}`
|
}
|
||||||
}
|
})
|
||||||
})
|
|
||||||
} else {
|
|
||||||
handleResponse({
|
|
||||||
response,
|
|
||||||
body: {
|
|
||||||
success: false,
|
|
||||||
message: deleteErrorMessage
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
logger.error(err)
|
logger.error(err)
|
||||||
handleResponse({
|
handleResponse({
|
||||||
|
Loading…
Reference in New Issue
Block a user