mirror of
https://github.com/Kuingsmile/PicList.git
synced 2026-05-06 20:42:57 +08:00
🐛 Fix(custom): fix delete api
This commit is contained in:
@@ -1,236 +1,236 @@
|
|||||||
import db, { GalleryDB } from '@core/datastore'
|
import db, { GalleryDB } from '@core/datastore'
|
||||||
import picgo from '@core/picgo'
|
import picgo from '@core/picgo'
|
||||||
import uploader from 'apis/app/uploader'
|
import uploader from 'apis/app/uploader'
|
||||||
import windowManager from 'apis/app/window/windowManager'
|
import windowManager from 'apis/app/window/windowManager'
|
||||||
import { Notification, WebContents } from 'electron'
|
import { Notification, WebContents } from 'electron'
|
||||||
import fs from 'fs-extra'
|
import fs from 'fs-extra'
|
||||||
import { cloneDeep } from 'lodash-es'
|
import { cloneDeep } from 'lodash-es'
|
||||||
import type { IPicGo } from 'piclist'
|
import type { IPicGo } from 'piclist'
|
||||||
|
|
||||||
import type { IFileWithPath, ImgInfo, IStringKeyMap, IUploadOption } from '#/types/types'
|
import type { IFileWithPath, ImgInfo, IStringKeyMap, IUploadOption } from '#/types/types'
|
||||||
import { T as $t } from '~/i18n/index'
|
import { T as $t } from '~/i18n/index'
|
||||||
import { handleCopyUrl, handleUrlEncodeWithSetting } from '~/utils/common'
|
import { handleCopyUrl, handleUrlEncodeWithSetting } from '~/utils/common'
|
||||||
import { configPaths } from '~/utils/configPaths'
|
import { configPaths } from '~/utils/configPaths'
|
||||||
import { IPasteStyle, IWindowList } from '~/utils/enum'
|
import { IPasteStyle, IWindowList } from '~/utils/enum'
|
||||||
import { changeCurrentUploader } from '~/utils/handleUploaderConfig'
|
import { changeCurrentUploader } from '~/utils/handleUploaderConfig'
|
||||||
import pasteTemplate from '~/utils/pasteTemplate'
|
import pasteTemplate from '~/utils/pasteTemplate'
|
||||||
|
|
||||||
const handleClipboardUploading = async (): Promise<false | ImgInfo[]> => {
|
const handleClipboardUploading = async (): Promise<false | ImgInfo[]> => {
|
||||||
const useBuiltinClipboard =
|
const useBuiltinClipboard =
|
||||||
db.get(configPaths.settings.useBuiltinClipboard) === undefined
|
db.get(configPaths.settings.useBuiltinClipboard) === undefined
|
||||||
? true
|
? true
|
||||||
: !!db.get(configPaths.settings.useBuiltinClipboard)
|
: !!db.get(configPaths.settings.useBuiltinClipboard)
|
||||||
const win = windowManager.getAvailableWindow()
|
const win = windowManager.getAvailableWindow()
|
||||||
if (useBuiltinClipboard) {
|
if (useBuiltinClipboard) {
|
||||||
return await uploader.setWebContents(win!.webContents).uploadWithBuildInClipboard()
|
return await uploader.setWebContents(win!.webContents).uploadWithBuildInClipboard()
|
||||||
}
|
}
|
||||||
return await uploader.setWebContents(win!.webContents).upload()
|
return await uploader.setWebContents(win!.webContents).upload()
|
||||||
}
|
}
|
||||||
|
|
||||||
const handleClipboardUploadingReturnCtx = async (img?: IUploadOption, skipProcess = false): Promise<false | IPicGo> => {
|
const handleClipboardUploadingReturnCtx = async (img?: IUploadOption, skipProcess = false): Promise<false | IPicGo> => {
|
||||||
const useBuiltinClipboard =
|
const useBuiltinClipboard =
|
||||||
db.get(configPaths.settings.useBuiltinClipboard) === undefined
|
db.get(configPaths.settings.useBuiltinClipboard) === undefined
|
||||||
? true
|
? true
|
||||||
: !!db.get(configPaths.settings.useBuiltinClipboard)
|
: !!db.get(configPaths.settings.useBuiltinClipboard)
|
||||||
const win = windowManager.getAvailableWindow()
|
const win = windowManager.getAvailableWindow()
|
||||||
if (useBuiltinClipboard) {
|
if (useBuiltinClipboard) {
|
||||||
return await uploader.setWebContents(win!.webContents).uploadWithBuildInClipboardReturnCtx(img, skipProcess)
|
return await uploader.setWebContents(win!.webContents).uploadWithBuildInClipboardReturnCtx(img, skipProcess)
|
||||||
}
|
}
|
||||||
return await uploader.setWebContents(win!.webContents).uploadReturnCtx(img, skipProcess)
|
return await uploader.setWebContents(win!.webContents).uploadReturnCtx(img, skipProcess)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const uploadClipboardFiles = async (): Promise<IStringKeyMap> => {
|
export const uploadClipboardFiles = async (): Promise<IStringKeyMap> => {
|
||||||
const { needRestore, ctx } = await handleSecondaryUpload(undefined, undefined, 'clipboard')
|
const { needRestore, ctx } = await handleSecondaryUpload(undefined, undefined, 'clipboard')
|
||||||
let img: ImgInfo[] | false = false
|
let img: ImgInfo[] | false = false
|
||||||
if (needRestore) {
|
if (needRestore) {
|
||||||
const res = await handleClipboardUploadingReturnCtx(ctx ? ctx.processedInput : undefined, true)
|
const res = await handleClipboardUploadingReturnCtx(ctx ? ctx.processedInput : undefined, true)
|
||||||
img = res ? res.output : false
|
img = res ? res.output : false
|
||||||
} else {
|
} else {
|
||||||
img = await handleClipboardUploading()
|
img = await handleClipboardUploading()
|
||||||
}
|
}
|
||||||
if (img !== false) {
|
if (img !== false) {
|
||||||
if (img.length > 0) {
|
if (img.length > 0) {
|
||||||
const trayWindow = windowManager.get(IWindowList.TRAY_WINDOW)
|
const trayWindow = windowManager.get(IWindowList.TRAY_WINDOW)
|
||||||
const pasteStyle = db.get(configPaths.settings.pasteStyle) || IPasteStyle.MARKDOWN
|
const pasteStyle = db.get(configPaths.settings.pasteStyle) || IPasteStyle.MARKDOWN
|
||||||
const [pastedText, shortUrl] = await pasteTemplate(pasteStyle, img[0], db.get(configPaths.settings.customLink))
|
const [pastedText, shortUrl] = await pasteTemplate(pasteStyle, img[0], db.get(configPaths.settings.customLink))
|
||||||
img[0].shortUrl = shortUrl
|
img[0].shortUrl = shortUrl
|
||||||
handleCopyUrl(pastedText)
|
handleCopyUrl(pastedText)
|
||||||
const isShowResultNotification =
|
const isShowResultNotification =
|
||||||
db.get(configPaths.settings.uploadResultNotification) === undefined
|
db.get(configPaths.settings.uploadResultNotification) === undefined
|
||||||
? true
|
? true
|
||||||
: !!db.get(configPaths.settings.uploadResultNotification)
|
: !!db.get(configPaths.settings.uploadResultNotification)
|
||||||
if (isShowResultNotification) {
|
if (isShowResultNotification) {
|
||||||
const notification = new Notification({
|
const notification = new Notification({
|
||||||
title: $t('UPLOAD_SUCCEED'),
|
title: $t('UPLOAD_SUCCEED'),
|
||||||
body: shortUrl || img[0].imgUrl!
|
body: shortUrl || img[0].imgUrl!
|
||||||
// icon: img[0].imgUrl
|
// icon: img[0].imgUrl
|
||||||
})
|
})
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
notification.show()
|
notification.show()
|
||||||
}, 100)
|
}, 100)
|
||||||
}
|
}
|
||||||
await GalleryDB.getInstance().insert(img[0])
|
const inserted = await GalleryDB.getInstance().insert(img[0])
|
||||||
// trayWindow just be created in mac/windows, not in linux
|
// trayWindow just be created in mac/windows, not in linux
|
||||||
trayWindow?.webContents?.send('clipboardFiles', [])
|
trayWindow?.webContents?.send('clipboardFiles', [])
|
||||||
trayWindow?.webContents?.send('uploadFiles', img)
|
trayWindow?.webContents?.send('uploadFiles', img)
|
||||||
if (windowManager.has(IWindowList.SETTING_WINDOW)) {
|
if (windowManager.has(IWindowList.SETTING_WINDOW)) {
|
||||||
windowManager.get(IWindowList.SETTING_WINDOW)!.webContents?.send('updateGallery')
|
windowManager.get(IWindowList.SETTING_WINDOW)!.webContents?.send('updateGallery')
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
url: handleUrlEncodeWithSetting(img[0].imgUrl as string),
|
url: handleUrlEncodeWithSetting(inserted.imgUrl as string),
|
||||||
fullResult: img[0]
|
fullResult: inserted
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const notification = new Notification({
|
const notification = new Notification({
|
||||||
title: $t('UPLOAD_FAILED'),
|
title: $t('UPLOAD_FAILED'),
|
||||||
body: $t('TIPS_UPLOAD_NOT_PICTURES')
|
body: $t('TIPS_UPLOAD_NOT_PICTURES')
|
||||||
})
|
})
|
||||||
notification.show()
|
notification.show()
|
||||||
return {
|
return {
|
||||||
url: '',
|
url: '',
|
||||||
fullResult: {}
|
fullResult: {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
return {
|
return {
|
||||||
url: '',
|
url: '',
|
||||||
fullResult: {}
|
fullResult: {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const uploadChoosedFiles = async (
|
export const uploadChoosedFiles = async (
|
||||||
webContents: WebContents,
|
webContents: WebContents,
|
||||||
files: IFileWithPath[]
|
files: IFileWithPath[]
|
||||||
): Promise<IStringKeyMap[]> => {
|
): Promise<IStringKeyMap[]> => {
|
||||||
const input = files.map(item => item.path)
|
const input = files.map(item => item.path)
|
||||||
const rawInput = cloneDeep(input)
|
const rawInput = cloneDeep(input)
|
||||||
const { needRestore, ctx } = await handleSecondaryUpload(webContents, input)
|
const { needRestore, ctx } = await handleSecondaryUpload(webContents, input)
|
||||||
let imgs: ImgInfo[] | false = false
|
let imgs: ImgInfo[] | false = false
|
||||||
if (needRestore) {
|
if (needRestore) {
|
||||||
const res = await uploader.setWebContents(webContents).uploadReturnCtx(ctx ? ctx.processedInput : input, true)
|
const res = await uploader.setWebContents(webContents).uploadReturnCtx(ctx ? ctx.processedInput : input, true)
|
||||||
imgs = res ? res.output : false
|
imgs = res ? res.output : false
|
||||||
} else {
|
} else {
|
||||||
imgs = await uploader.setWebContents(webContents).upload(input)
|
imgs = await uploader.setWebContents(webContents).upload(input)
|
||||||
}
|
}
|
||||||
const result = []
|
const result = []
|
||||||
if (imgs !== false) {
|
if (imgs !== false) {
|
||||||
const pasteStyle = db.get(configPaths.settings.pasteStyle) || IPasteStyle.MARKDOWN
|
const pasteStyle = db.get(configPaths.settings.pasteStyle) || IPasteStyle.MARKDOWN
|
||||||
const deleteLocalFile = db.get(configPaths.settings.deleteLocalFile) || false
|
const deleteLocalFile = db.get(configPaths.settings.deleteLocalFile) || false
|
||||||
const pasteText: string[] = []
|
const pasteText: string[] = []
|
||||||
for (let i = 0; i < imgs.length; i++) {
|
for (let i = 0; i < imgs.length; i++) {
|
||||||
if (deleteLocalFile) {
|
if (deleteLocalFile) {
|
||||||
fs.remove(rawInput[i])
|
fs.remove(rawInput[i])
|
||||||
.then(() => {
|
.then(() => {
|
||||||
picgo.log.info(`delete local file: ${rawInput[i]}`)
|
picgo.log.info(`delete local file: ${rawInput[i]}`)
|
||||||
})
|
})
|
||||||
.catch((err: Error) => {
|
.catch((err: Error) => {
|
||||||
picgo.log.error(err)
|
picgo.log.error(err)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
const [pasteTextItem, shortUrl] = await pasteTemplate(
|
const [pasteTextItem, shortUrl] = await pasteTemplate(
|
||||||
pasteStyle,
|
pasteStyle,
|
||||||
imgs[i],
|
imgs[i],
|
||||||
db.get(configPaths.settings.customLink)
|
db.get(configPaths.settings.customLink)
|
||||||
)
|
)
|
||||||
imgs[i].shortUrl = shortUrl
|
imgs[i].shortUrl = shortUrl
|
||||||
pasteText.push(pasteTextItem)
|
pasteText.push(pasteTextItem)
|
||||||
const isShowResultNotification =
|
const isShowResultNotification =
|
||||||
db.get(configPaths.settings.uploadResultNotification) === undefined
|
db.get(configPaths.settings.uploadResultNotification) === undefined
|
||||||
? true
|
? true
|
||||||
: !!db.get(configPaths.settings.uploadResultNotification)
|
: !!db.get(configPaths.settings.uploadResultNotification)
|
||||||
if (isShowResultNotification) {
|
if (isShowResultNotification) {
|
||||||
const notification = new Notification({
|
const notification = new Notification({
|
||||||
title: $t('UPLOAD_SUCCEED'),
|
title: $t('UPLOAD_SUCCEED'),
|
||||||
body: shortUrl || imgs[i].imgUrl!
|
body: shortUrl || imgs[i].imgUrl!
|
||||||
// icon: files[i].path
|
// icon: files[i].path
|
||||||
})
|
})
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
notification.show()
|
notification.show()
|
||||||
}, i * 100)
|
}, i * 100)
|
||||||
}
|
}
|
||||||
await GalleryDB.getInstance().insert(imgs[i])
|
const inserted = await GalleryDB.getInstance().insert(imgs[i])
|
||||||
result.push({
|
result.push({
|
||||||
url: handleUrlEncodeWithSetting(imgs[i].imgUrl!),
|
url: handleUrlEncodeWithSetting(inserted.imgUrl!),
|
||||||
fullResult: imgs[i]
|
fullResult: inserted
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
handleCopyUrl(pasteText.join('\n'))
|
handleCopyUrl(pasteText.join('\n'))
|
||||||
// trayWindow just be created in mac/windows, not in linux
|
// trayWindow just be created in mac/windows, not in linux
|
||||||
windowManager.get(IWindowList.TRAY_WINDOW)?.webContents?.send('uploadFiles', imgs)
|
windowManager.get(IWindowList.TRAY_WINDOW)?.webContents?.send('uploadFiles', imgs)
|
||||||
if (windowManager.has(IWindowList.SETTING_WINDOW)) {
|
if (windowManager.has(IWindowList.SETTING_WINDOW)) {
|
||||||
windowManager.get(IWindowList.SETTING_WINDOW)!.webContents?.send('updateGallery')
|
windowManager.get(IWindowList.SETTING_WINDOW)!.webContents?.send('updateGallery')
|
||||||
}
|
}
|
||||||
return result
|
return result
|
||||||
} else {
|
} else {
|
||||||
return []
|
return []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const handleSecondaryUpload = async (
|
export const handleSecondaryUpload = async (
|
||||||
webContents?: WebContents,
|
webContents?: WebContents,
|
||||||
input?: string[],
|
input?: string[],
|
||||||
uploadType: 'clipboard' | 'file' | 'tray' = 'file'
|
uploadType: 'clipboard' | 'file' | 'tray' = 'file'
|
||||||
): Promise<{ needRestore: boolean; ctx: IPicGo | false }> => {
|
): Promise<{ needRestore: boolean; ctx: IPicGo | false }> => {
|
||||||
const enableSecondUploader = db.get(configPaths.settings.enableSecondUploader) || false
|
const enableSecondUploader = db.get(configPaths.settings.enableSecondUploader) || false
|
||||||
let currentPicBedType = ''
|
let currentPicBedType = ''
|
||||||
let currentPicBedConfig = {} as IStringKeyMap
|
let currentPicBedConfig = {} as IStringKeyMap
|
||||||
let currentPicBedConfigId = ''
|
let currentPicBedConfigId = ''
|
||||||
let needRestore = false
|
let needRestore = false
|
||||||
let ctx: IPicGo | false = false
|
let ctx: IPicGo | false = false
|
||||||
if (enableSecondUploader) {
|
if (enableSecondUploader) {
|
||||||
const secondUploader = db.get(configPaths.picBed.secondUploader)
|
const secondUploader = db.get(configPaths.picBed.secondUploader)
|
||||||
const secondUploaderConfig = db.get(configPaths.picBed.secondUploaderConfig)
|
const secondUploaderConfig = db.get(configPaths.picBed.secondUploaderConfig)
|
||||||
const secondUploaderId = db.get(configPaths.picBed.secondUploaderId)
|
const secondUploaderId = db.get(configPaths.picBed.secondUploaderId)
|
||||||
const currentPicBed = db.get('picBed') || ({} as IStringKeyMap)
|
const currentPicBed = db.get('picBed') || ({} as IStringKeyMap)
|
||||||
currentPicBedType = currentPicBed.uploader || currentPicBed.current || 'smms'
|
currentPicBedType = currentPicBed.uploader || currentPicBed.current || 'smms'
|
||||||
currentPicBedConfig = currentPicBed[currentPicBedType] || ({} as IStringKeyMap)
|
currentPicBedConfig = currentPicBed[currentPicBedType] || ({} as IStringKeyMap)
|
||||||
currentPicBedConfigId = currentPicBedConfig._id
|
currentPicBedConfigId = currentPicBedConfig._id
|
||||||
if (
|
if (
|
||||||
secondUploader === currentPicBedType &&
|
secondUploader === currentPicBedType &&
|
||||||
secondUploaderConfig._configName === currentPicBedConfig._configName &&
|
secondUploaderConfig._configName === currentPicBedConfig._configName &&
|
||||||
secondUploaderId === currentPicBedConfigId
|
secondUploaderId === currentPicBedConfigId
|
||||||
) {
|
) {
|
||||||
picgo.log.info('second uploader is the same as current uploader')
|
picgo.log.info('second uploader is the same as current uploader')
|
||||||
} else {
|
} else {
|
||||||
needRestore = true
|
needRestore = true
|
||||||
let secondImgs: ImgInfo[] | false = false
|
let secondImgs: ImgInfo[] | false = false
|
||||||
changeCurrentUploader(secondUploader, secondUploaderConfig, secondUploaderId)
|
changeCurrentUploader(secondUploader, secondUploaderConfig, secondUploaderId)
|
||||||
if (uploadType === 'clipboard') {
|
if (uploadType === 'clipboard') {
|
||||||
ctx = await handleClipboardUploadingReturnCtx(undefined)
|
ctx = await handleClipboardUploadingReturnCtx(undefined)
|
||||||
} else {
|
} else {
|
||||||
ctx = await uploader.setWebContents(webContents!).uploadReturnCtx(input)
|
ctx = await uploader.setWebContents(webContents!).uploadReturnCtx(input)
|
||||||
}
|
}
|
||||||
secondImgs = ctx ? ctx.output : false
|
secondImgs = ctx ? ctx.output : false
|
||||||
if (secondImgs !== false) {
|
if (secondImgs !== false) {
|
||||||
const trayWindow = windowManager.get(IWindowList.TRAY_WINDOW)
|
const trayWindow = windowManager.get(IWindowList.TRAY_WINDOW)
|
||||||
if (uploadType === 'clipboard') {
|
if (uploadType === 'clipboard') {
|
||||||
if (secondImgs.length > 0) {
|
if (secondImgs.length > 0) {
|
||||||
await GalleryDB.getInstance().insert(secondImgs[0])
|
await GalleryDB.getInstance().insert(secondImgs[0])
|
||||||
trayWindow?.webContents?.send('clipboardFiles', [])
|
trayWindow?.webContents?.send('clipboardFiles', [])
|
||||||
trayWindow?.webContents?.send('uploadFiles', secondImgs)
|
trayWindow?.webContents?.send('uploadFiles', secondImgs)
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
for (const secondImgsItem of secondImgs) {
|
for (const secondImgsItem of secondImgs) {
|
||||||
await GalleryDB.getInstance().insert(secondImgsItem)
|
await GalleryDB.getInstance().insert(secondImgsItem)
|
||||||
}
|
}
|
||||||
if (uploadType === 'tray') {
|
if (uploadType === 'tray') {
|
||||||
trayWindow?.webContents?.send('dragFiles', secondImgs)
|
trayWindow?.webContents?.send('dragFiles', secondImgs)
|
||||||
} else {
|
} else {
|
||||||
trayWindow?.webContents?.send('uploadFiles', secondImgs)
|
trayWindow?.webContents?.send('uploadFiles', secondImgs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (windowManager.has(IWindowList.SETTING_WINDOW) && uploadType !== 'tray') {
|
if (windowManager.has(IWindowList.SETTING_WINDOW) && uploadType !== 'tray') {
|
||||||
windowManager.get(IWindowList.SETTING_WINDOW)!.webContents?.send('updateGallery')
|
windowManager.get(IWindowList.SETTING_WINDOW)!.webContents?.send('updateGallery')
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (needRestore) {
|
if (needRestore) {
|
||||||
changeCurrentUploader(currentPicBedType, currentPicBedConfig, currentPicBedConfigId)
|
changeCurrentUploader(currentPicBedType, currentPicBedConfig, currentPicBedConfigId)
|
||||||
}
|
}
|
||||||
return {
|
return {
|
||||||
needRestore,
|
needRestore,
|
||||||
ctx
|
ctx
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,234 +1,234 @@
|
|||||||
import http from 'node:http'
|
import http from 'node:http'
|
||||||
import path from 'node:path'
|
import path from 'node:path'
|
||||||
|
|
||||||
import { dbPathDir } from '@core/datastore/dbChecker'
|
import { dbPathDir } from '@core/datastore/dbChecker'
|
||||||
import picgo from '@core/picgo'
|
import picgo from '@core/picgo'
|
||||||
import logger from '@core/picgo/logger'
|
import logger from '@core/picgo/logger'
|
||||||
import { uploadChoosedFiles, uploadClipboardFiles } from 'apis/app/uploader/apis'
|
import { uploadChoosedFiles, uploadClipboardFiles } from 'apis/app/uploader/apis'
|
||||||
import windowManager from 'apis/app/window/windowManager'
|
import windowManager from 'apis/app/window/windowManager'
|
||||||
import { app } from 'electron'
|
import { app } from 'electron'
|
||||||
import fs from 'fs-extra'
|
import fs from 'fs-extra'
|
||||||
import { marked } from 'marked'
|
import { marked } from 'marked'
|
||||||
|
|
||||||
import type { IHttpResponse, IStringKeyMap } from '#/types/types'
|
import type { IHttpResponse, IStringKeyMap } from '#/types/types'
|
||||||
import { markdownContent } from '~/server/apiDoc'
|
import { markdownContent } from '~/server/apiDoc'
|
||||||
import router from '~/server/router'
|
import router from '~/server/router'
|
||||||
import { deleteChoosedFiles, handleResponse } from '~/server/utils'
|
import { deleteChoosedFiles, handleResponse } from '~/server/utils'
|
||||||
import { AESHelper } from '~/utils/aesHelper'
|
import { AESHelper } from '~/utils/aesHelper'
|
||||||
import { configPaths } from '~/utils/configPaths'
|
import { configPaths } from '~/utils/configPaths'
|
||||||
import { changeCurrentUploader } from '~/utils/handleUploaderConfig'
|
import { changeCurrentUploader } from '~/utils/handleUploaderConfig'
|
||||||
|
|
||||||
const appPath = app.getPath('userData')
|
const appPath = app.getPath('userData')
|
||||||
const serverTempDir = path.join(appPath, 'serverTemp')
|
const serverTempDir = path.join(appPath, 'serverTemp')
|
||||||
|
|
||||||
const STORE_PATH = dbPathDir()
|
const STORE_PATH = dbPathDir()
|
||||||
const LOG_PATH = path.join(STORE_PATH, 'piclist.log')
|
const LOG_PATH = path.join(STORE_PATH, 'piclist.log')
|
||||||
|
|
||||||
const errorMessage = `upload error. see ${LOG_PATH} for more detail.`
|
const errorMessage = `upload error. see ${LOG_PATH} for more detail.`
|
||||||
const deleteErrorMessage = `delete error. see ${LOG_PATH} for more detail.`
|
const deleteErrorMessage = `delete error. see ${LOG_PATH} for more detail.`
|
||||||
|
|
||||||
async function responseForGet ({ response }: { response: http.ServerResponse }) {
|
async function responseForGet ({ response }: { response: http.ServerResponse }) {
|
||||||
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
|
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' })
|
||||||
const htmlContent = marked(markdownContent)
|
const htmlContent = marked(markdownContent)
|
||||||
response.write(htmlContent)
|
response.write(htmlContent)
|
||||||
response.end()
|
response.end()
|
||||||
}
|
}
|
||||||
|
|
||||||
router.get('/', responseForGet)
|
router.get('/', responseForGet)
|
||||||
router.get('/upload', responseForGet)
|
router.get('/upload', responseForGet)
|
||||||
|
|
||||||
router.post(
|
router.post(
|
||||||
'/upload',
|
'/upload',
|
||||||
async ({
|
async ({
|
||||||
response,
|
response,
|
||||||
list = [],
|
list = [],
|
||||||
urlparams
|
urlparams
|
||||||
}: {
|
}: {
|
||||||
response: IHttpResponse
|
response: IHttpResponse
|
||||||
list?: string[]
|
list?: string[]
|
||||||
urlparams?: URLSearchParams
|
urlparams?: URLSearchParams
|
||||||
}): Promise<void> => {
|
}): Promise<void> => {
|
||||||
try {
|
try {
|
||||||
const picbed = urlparams?.get('picbed')
|
const picbed = urlparams?.get('picbed')
|
||||||
const passedKey = urlparams?.get('key')
|
const passedKey = urlparams?.get('key')
|
||||||
const serverKey = picgo.getConfig<string>(configPaths.settings.serverKey) || ''
|
const serverKey = picgo.getConfig<string>(configPaths.settings.serverKey) || ''
|
||||||
const useShortUrl = picgo.getConfig<boolean>(configPaths.settings.useShortUrl)
|
const useShortUrl = picgo.getConfig<boolean>(configPaths.settings.useShortUrl)
|
||||||
if (serverKey && passedKey !== serverKey) {
|
if (serverKey && passedKey !== serverKey) {
|
||||||
handleResponse({
|
handleResponse({
|
||||||
response,
|
response,
|
||||||
body: {
|
body: {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'server key is uncorrect'
|
message: 'server key is uncorrect'
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
let currentPicBedType = ''
|
let currentPicBedType = ''
|
||||||
let currentPicBedConfig = {} as IStringKeyMap
|
let currentPicBedConfig = {} as IStringKeyMap
|
||||||
let currentPicBedConfigId = ''
|
let currentPicBedConfigId = ''
|
||||||
let needRestore = false
|
let needRestore = false
|
||||||
if (picbed) {
|
if (picbed) {
|
||||||
const currentPicBed = picgo.getConfig<IStringKeyMap>('picBed') || ({} as IStringKeyMap)
|
const currentPicBed = picgo.getConfig<IStringKeyMap>('picBed') || ({} as IStringKeyMap)
|
||||||
currentPicBedType = currentPicBed.uploader || currentPicBed.current || 'smms'
|
currentPicBedType = currentPicBed.uploader || currentPicBed.current || 'smms'
|
||||||
currentPicBedConfig = currentPicBed[currentPicBedType] || ({} as IStringKeyMap)
|
currentPicBedConfig = currentPicBed[currentPicBedType] || ({} as IStringKeyMap)
|
||||||
currentPicBedConfigId = currentPicBedConfig._id
|
currentPicBedConfigId = currentPicBedConfig._id
|
||||||
const configName = urlparams?.get('configName') || currentPicBed[picbed]?._configName
|
const configName = urlparams?.get('configName') || currentPicBed[picbed]?._configName
|
||||||
if (picbed === currentPicBedType && configName === currentPicBedConfig._configName) {
|
if (picbed === currentPicBedType && configName === currentPicBedConfig._configName) {
|
||||||
// do nothing
|
// do nothing
|
||||||
} else {
|
} else {
|
||||||
needRestore = true
|
needRestore = true
|
||||||
const picBeds = picgo.getConfig<IStringKeyMap>('uploader')
|
const picBeds = picgo.getConfig<IStringKeyMap>('uploader')
|
||||||
const currentPicBedList = picBeds?.[picbed]?.configList
|
const currentPicBedList = picBeds?.[picbed]?.configList
|
||||||
if (currentPicBedList) {
|
if (currentPicBedList) {
|
||||||
const currentConfig = currentPicBedList?.find((item: any) => item._configName === configName)
|
const currentConfig = currentPicBedList?.find((item: any) => item._configName === configName)
|
||||||
if (currentConfig) {
|
if (currentConfig) {
|
||||||
changeCurrentUploader(picbed, currentConfig, currentConfig._id)
|
changeCurrentUploader(picbed, currentConfig, currentConfig._id)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (list.length === 0) {
|
if (list.length === 0) {
|
||||||
// upload with clipboard
|
// upload with clipboard
|
||||||
logger.info('[PicList Server] upload clipboard file')
|
logger.info('[PicList Server] upload clipboard file')
|
||||||
const result = await uploadClipboardFiles()
|
const result = await uploadClipboardFiles()
|
||||||
const res = useShortUrl ? result.fullResult.shortUrl || result.url : result.url
|
const res = useShortUrl ? result.fullResult.shortUrl || result.url : result.url
|
||||||
const fullResult = result.fullResult
|
const fullResult = result.fullResult
|
||||||
fullResult.imgUrl = useShortUrl ? fullResult.shortUrl || fullResult.imgUrl : fullResult.imgUrl
|
fullResult.imgUrl = useShortUrl ? fullResult.shortUrl || fullResult.imgUrl : fullResult.imgUrl
|
||||||
logger.info('[PicList Server] upload result:', res)
|
logger.info('[PicList Server] upload result:', res)
|
||||||
if (res) {
|
if (res) {
|
||||||
const treatedFullResult = {
|
const treatedFullResult = {
|
||||||
isEncrypted: 1,
|
isEncrypted: 1,
|
||||||
EncryptedData: new AESHelper().encrypt(JSON.stringify(fullResult)),
|
EncryptedData: new AESHelper().encrypt(JSON.stringify(fullResult)),
|
||||||
...fullResult
|
...fullResult
|
||||||
}
|
}
|
||||||
delete treatedFullResult.config
|
delete treatedFullResult.config
|
||||||
handleResponse({
|
handleResponse({
|
||||||
response,
|
response,
|
||||||
body: {
|
body: {
|
||||||
success: true,
|
success: true,
|
||||||
result: [res],
|
result: [res],
|
||||||
fullResult: [treatedFullResult]
|
fullResult: [treatedFullResult]
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
handleResponse({
|
handleResponse({
|
||||||
response,
|
response,
|
||||||
body: {
|
body: {
|
||||||
success: false,
|
success: false,
|
||||||
message: errorMessage
|
message: errorMessage
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
logger.info('[PicList Server] upload files in list')
|
logger.info('[PicList Server] upload files in list')
|
||||||
// upload with files
|
// upload with files
|
||||||
const pathList = list.map(item => {
|
const pathList = list.map(item => {
|
||||||
return {
|
return {
|
||||||
path: item
|
path: item
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
const win = windowManager.getAvailableWindow()
|
const win = windowManager.getAvailableWindow()
|
||||||
const result = await uploadChoosedFiles(win.webContents, pathList)
|
const result = await uploadChoosedFiles(win.webContents, pathList)
|
||||||
const res = result.map(item => {
|
const res = result.map(item => {
|
||||||
return useShortUrl ? item.fullResult.shortUrl || item.url : item.url
|
return useShortUrl ? item.fullResult.shortUrl || item.url : item.url
|
||||||
})
|
})
|
||||||
const fullResult = result.map((item: any) => {
|
const fullResult = result.map((item: any) => {
|
||||||
const treatedItem = {
|
const treatedItem = {
|
||||||
isEncrypted: 1,
|
isEncrypted: 1,
|
||||||
EncryptedData: new AESHelper().encrypt(JSON.stringify(item.fullResult)),
|
EncryptedData: new AESHelper().encrypt(JSON.stringify(item.fullResult)),
|
||||||
...item.fullResult
|
...item.fullResult
|
||||||
}
|
}
|
||||||
delete treatedItem.config
|
delete treatedItem.config
|
||||||
treatedItem.imgUrl = useShortUrl ? treatedItem.shortUrl || treatedItem.imgUrl : treatedItem.imgUrl
|
treatedItem.imgUrl = useShortUrl ? treatedItem.shortUrl || treatedItem.imgUrl : treatedItem.imgUrl
|
||||||
return treatedItem
|
return treatedItem
|
||||||
})
|
})
|
||||||
logger.info('[PicList Server] upload result', res.join(' ; '))
|
logger.info('[PicList Server] upload result', res.join(' ; '))
|
||||||
if (res.length) {
|
if (res.length) {
|
||||||
handleResponse({
|
handleResponse({
|
||||||
response,
|
response,
|
||||||
body: {
|
body: {
|
||||||
success: true,
|
success: true,
|
||||||
result: res,
|
result: res,
|
||||||
fullResult
|
fullResult
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} else {
|
} else {
|
||||||
handleResponse({
|
handleResponse({
|
||||||
response,
|
response,
|
||||||
body: {
|
body: {
|
||||||
success: false,
|
success: false,
|
||||||
message: errorMessage
|
message: errorMessage
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fs.emptyDirSync(serverTempDir)
|
fs.emptyDirSync(serverTempDir)
|
||||||
if (needRestore) {
|
if (needRestore) {
|
||||||
changeCurrentUploader(currentPicBedType, currentPicBedConfig, currentPicBedConfigId)
|
changeCurrentUploader(currentPicBedType, currentPicBedConfig, currentPicBedConfigId)
|
||||||
}
|
}
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
logger.error(err)
|
logger.error(err)
|
||||||
handleResponse({
|
handleResponse({
|
||||||
response,
|
response,
|
||||||
body: {
|
body: {
|
||||||
success: false,
|
success: false,
|
||||||
message: errorMessage
|
message: errorMessage
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
router.post(
|
router.post(
|
||||||
'/delete',
|
'/delete',
|
||||||
async ({ response, list = [] }: { response: IHttpResponse; list?: IStringKeyMap[] }): Promise<void> => {
|
async ({ response, list = [] }: { response: IHttpResponse; list?: IStringKeyMap[] }): Promise<void> => {
|
||||||
if (list.length === 0) {
|
if (list.length === 0) {
|
||||||
handleResponse({
|
handleResponse({
|
||||||
response,
|
response,
|
||||||
body: {
|
body: {
|
||||||
success: false,
|
success: false,
|
||||||
message: 'no file to delete'
|
message: 'no file to delete'
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
try {
|
try {
|
||||||
const aesHelper = new AESHelper()
|
const aesHelper = new AESHelper()
|
||||||
const treatList = list.map(item => {
|
const treatList = list.map(item => {
|
||||||
if (!item.isEncrypted) return item
|
if (!item.isEncrypted) return item
|
||||||
return JSON.parse(aesHelper.decrypt(item.EncryptedData))
|
return JSON.parse(aesHelper.decrypt(item.EncryptedData))
|
||||||
})
|
})
|
||||||
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.length - successCount
|
const failCount = result.length - successCount
|
||||||
handleResponse({
|
handleResponse({
|
||||||
response,
|
response,
|
||||||
body: {
|
body: {
|
||||||
success: !!successCount,
|
success: !!successCount,
|
||||||
message: successCount ? `delete success: ${successCount}, fail: ${failCount}` : deleteErrorMessage
|
message: successCount ? `delete success: ${successCount}, fail: ${failCount}` : deleteErrorMessage
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} catch (err: any) {
|
} catch (err: any) {
|
||||||
logger.error(err)
|
logger.error(err)
|
||||||
handleResponse({
|
handleResponse({
|
||||||
response,
|
response,
|
||||||
body: {
|
body: {
|
||||||
success: false,
|
success: false,
|
||||||
message: deleteErrorMessage
|
message: deleteErrorMessage
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
router.any('/heartbeat', async ({ response }: { response: IHttpResponse }) => {
|
router.any('/heartbeat', async ({ response }: { response: IHttpResponse }) => {
|
||||||
handleResponse({
|
handleResponse({
|
||||||
response,
|
response,
|
||||||
body: {
|
body: {
|
||||||
success: true,
|
success: true,
|
||||||
result: 'alive'
|
result: 'alive'
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
export default router
|
export default router
|
||||||
|
|||||||
Reference in New Issue
Block a user