Skip to content

Commit

Permalink
✨ Feature: add /delete route for build in http server
Browse files Browse the repository at this point in the history
  • Loading branch information
Kuingsmile committed Mar 28, 2023
1 parent a736190 commit 9e8ae93
Show file tree
Hide file tree
Showing 4 changed files with 136 additions and 14 deletions.
71 changes: 65 additions & 6 deletions src/main/apis/app/uploader/apis.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ import db, { GalleryDB } from '~/main/apis/core/datastore'
import { handleCopyUrl } from '~/main/utils/common'
import { handleUrlEncode } from '#/utils/common'
import { T } from '~/main/i18n/index'
import ALLApi from '@/apis/allApi'
import picgo from '@core/picgo'
import GuiApi from '../../gui'

const handleClipboardUploading = async (): Promise<false | ImgInfo[]> => {
const useBuiltinClipboard = !!db.get('settings.useBuiltinClipboard')
Expand All @@ -20,7 +23,7 @@ const handleClipboardUploading = async (): Promise<false | ImgInfo[]> => {
return await uploader.setWebContents(win!.webContents).upload()
}

export const uploadClipboardFiles = async (): Promise<string> => {
export const uploadClipboardFiles = async (): Promise<IStringKeyMap> => {
const img = await handleClipboardUploading()
console.log(img)
if (img !== false) {
Expand All @@ -43,21 +46,30 @@ export const uploadClipboardFiles = async (): Promise<string> => {
if (windowManager.has(IWindowList.SETTING_WINDOW)) {
windowManager.get(IWindowList.SETTING_WINDOW)!.webContents?.send('updateGallery')
}
return handleUrlEncode(img[0].imgUrl as string)
return {
url: handleUrlEncode(img[0].imgUrl as string),
fullResult: img[0]
}
} else {
const notification = new Notification({
title: T('UPLOAD_FAILED'),
body: T('TIPS_UPLOAD_NOT_PICTURES')
})
notification.show()
return ''
return {
url: '',
fullResult: {}
}
}
} else {
return ''
return {
url: '',
fullResult: {}
}
}
}

export const uploadChoosedFiles = async (webContents: WebContents, files: IFileWithPath[]): Promise<string[]> => {
export const uploadChoosedFiles = async (webContents: WebContents, files: IFileWithPath[]): Promise<IStringKeyMap[]> => {
const input = files.map(item => item.path)
const imgs = await uploader.setWebContents(webContents).upload(input)
const result = []
Expand All @@ -75,7 +87,10 @@ export const uploadChoosedFiles = async (webContents: WebContents, files: IFileW
notification.show()
}, i * 100)
await GalleryDB.getInstance().insert(imgs[i])
result.push(handleUrlEncode(imgs[i].imgUrl!))
result.push({
url: handleUrlEncode(imgs[i].imgUrl!),
fullResult: imgs[i]
})
}
handleCopyUrl(pasteText.join('\n'))
// trayWindow just be created in mac/windows, not in linux
Expand All @@ -88,3 +103,47 @@ export const uploadChoosedFiles = async (webContents: WebContents, files: IFileW
return []
}
}

export const deleteChoosedFiles = async (list: ImgInfo[]): Promise<boolean[]> => {
const result = []
const picBedsCanbeDeleted = ['smms', 'github', 'imgur', 'tcyun', 'aliyun', 'qiniu', 'upyun', 'aws-s3', 'webdavplist']
for (const item of list) {
if (item.id) {
try {
const dbStore = GalleryDB.getInstance()
const file = await dbStore.removeById(item.id)
if (await picgo.getConfig('settings.deleteCloudFile')) {
if (item.type !== undefined && picBedsCanbeDeleted.includes(item.type)) {
setTimeout(() => {
ALLApi.delete(item).then((value: boolean) => {
if (value) {
const notification = new Notification({
title: T('MANAGE_BUCKET_BATCH_DELETE_ERROR_MSG_MSG2'),
body: T('GALLERY_SYNC_DELETE_NOTICE_SUCCEED')
})
notification.show()
} else {
const notification = new Notification({
title: T('MANAGE_BUCKET_BATCH_DELETE_ERROR_MSG_MSG2'),
body: T('GALLERY_SYNC_DELETE_NOTICE_FAILED')
})
notification.show()
}
})
}, 0)
}
}
setTimeout(() => {
picgo.emit('remove', [file], GuiApi.getInstance())
}, 500)
result.push(true)
} catch (e) {
result.push(false)
}
}
}
if (windowManager.has(IWindowList.SETTING_WINDOW)) {
windowManager.get(IWindowList.SETTING_WINDOW)!.webContents?.send('updateGallery')
}
return result
}
6 changes: 4 additions & 2 deletions src/main/events/busEventList.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,13 +34,15 @@ function initEventCenter () {
}

async function busCallUploadClipboardFiles () {
const imgUrl = await uploadClipboardFiles()
const result = await uploadClipboardFiles()
const imgUrl = result.url
bus.emit(UPLOAD_WITH_CLIPBOARD_FILES_RESPONSE, imgUrl)
}

async function busCallUploadFiles (pathList: IFileWithPath[]) {
const win = windowManager.getAvailableWindow()
const urls = await uploadChoosedFiles(win.webContents, pathList)
const result = await uploadChoosedFiles(win.webContents, pathList)
const urls = result.map((item: any) => item.url)
bus.emit(UPLOAD_WITH_FILES_RESPONSE, urls)
}

Expand Down
72 changes: 67 additions & 5 deletions src/main/server/routerManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import {
} from './utils'
import logger from '@core/picgo/logger'
import windowManager from 'apis/app/window/windowManager'
import { uploadChoosedFiles, uploadClipboardFiles } from 'apis/app/uploader/apis'
import { uploadChoosedFiles, uploadClipboardFiles, deleteChoosedFiles } from 'apis/app/uploader/apis'
import path from 'path'
import { dbPathDir } from 'apis/core/datastore/dbChecker'
const STORE_PATH = dbPathDir()
const LOG_PATH = path.join(STORE_PATH, 'piclist.log')
// import AllAPI from '../../renderer/apis/allApi'

const errorMessage = `upload error. see ${LOG_PATH} for more detail.`
const deleteErrorMessage = `delete error. see ${LOG_PATH} for more detail.`

router.post('/upload', async ({
response,
Expand All @@ -23,14 +25,17 @@ router.post('/upload', async ({
if (list.length === 0) {
// upload with clipboard
logger.info('[PicList Server] upload clipboard file')
const res = await uploadClipboardFiles()
const result = await uploadClipboardFiles()
const res = result.url
const fullResult = result.fullResult
logger.info('[PicList Server] upload result:', res)
if (res) {
handleResponse({
response,
body: {
success: true,
result: [res]
result: [res],
fullResult: [fullResult]
}
})
} else {
Expand All @@ -51,14 +56,21 @@ router.post('/upload', async ({
}
})
const win = windowManager.getAvailableWindow()
const res = await uploadChoosedFiles(win.webContents, pathList)
const result = await uploadChoosedFiles(win.webContents, pathList)
const res = result.map(item => {
return item.url
})
const fullResult = result.map((item: any) => {
return item.fullResult
})
logger.info('[PicList Server] upload result', res.join(' ; '))
if (res.length) {
handleResponse({
response,
body: {
success: true,
result: res
result: res,
fullResult
}
})
} else {
Expand All @@ -83,6 +95,56 @@ router.post('/upload', async ({
}
})

router.post('/delete', async ({
response,
list = []
} : {
response: IHttpResponse,
list?: IStringKeyMap[]
}): Promise<void> => {
if (list.length === 0) {
handleResponse({
response,
body: {
success: false,
message: 'no file to delete'
}
})
return
}
try {
const result = await deleteChoosedFiles(list)
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
}
})
}
} catch (err: any) {
logger.error(err)
handleResponse({
response,
body: {
success: false,
message: deleteErrorMessage
}
})
}
})

router.post('/heartbeat', async ({
response
} : {
Expand Down
1 change: 0 additions & 1 deletion src/renderer/pages/Upload.vue
Original file line number Diff line number Diff line change
Expand Up @@ -532,7 +532,6 @@ async function handlePicBedNameClick (picBedName: string, picBedConfigName: stri
defaultConfigId: currentPicBedConfig.defaultId || ''
}
})
console.log(configList, picBedConfigName)
}
onBeforeUnmount(() => {
Expand Down

0 comments on commit 9e8ae93

Please sign in to comment.