Skip to content

Commit

Permalink
✨ Feature(server): add http server for uploading images by a http req…
Browse files Browse the repository at this point in the history
…uest

port 37766
  • Loading branch information
Molunerfinn committed Dec 31, 2019
1 parent 3fd9572 commit c56d4ef
Show file tree
Hide file tree
Showing 13 changed files with 558 additions and 54 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"keycode": "^2.2.0",
"lodash-id": "^0.14.0",
"lowdb": "^1.0.0",
"picgo": "^1.4.3",
"picgo": "^1.4.4",
"vue": "^2.6.10",
"vue-gallery": "^2.0.1",
"vue-lazyload": "^1.2.6",
Expand Down
55 changes: 46 additions & 9 deletions src/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ import {
} from '~/main/migrate/shortKeyUpdateHelper'
import shortKeyHandler from '~/main/utils/shortKeyHandler'
import logger from '~/main/utils/logger'
import {
UPLOAD_WITH_FILES,
UPLOAD_WITH_FILES_RESPONSE,
UPLOAD_WITH_CLIPBOARD_FILES,
UPLOAD_WITH_CLIPBOARD_FILES_RESPONSE
} from '~/main/utils/busApi/constants'
import server from '~/main/server/index'

const isDevelopment = process.env.NODE_ENV !== 'production'
protocol.registerSchemesAsPrivileged([{ scheme: 'picgo', privileges: { secure: true, standard: true } }])
Expand Down Expand Up @@ -246,8 +253,8 @@ const createWindow = () => {
return window
}

const createMiniWidow = () => {
if (miniWindow) {
const createMiniWindow = () => {
if (miniWindow || process.platform === 'darwin') {
return false
}
let obj: IBrowserWindowOptions = {
Expand Down Expand Up @@ -322,7 +329,7 @@ const createSettingWindow = () => {
}
})
createMenu()
createMiniWidow()
createMiniWindow()
return settingWindow
}

Expand Down Expand Up @@ -368,9 +375,9 @@ const showWindow = (bounds: IBounds) => {
window!.focus()
}

const uploadClipboardFiles = async () => {
const uploadClipboardFiles = async (): Promise<string> => {
let win
if (miniWindow!.isVisible()) {
if (miniWindow && miniWindow!.isVisible()) {
win = miniWindow
} else {
win = settingWindow || window || createSettingWindow()
Expand All @@ -392,19 +399,24 @@ const uploadClipboardFiles = async () => {
if (settingWindow) {
settingWindow.webContents.send('updateGallery')
}
return img[0].imgUrl as string
} else {
const notification = new Notification({
title: '上传不成功',
body: '你剪贴板最新的一条记录不是图片哦'
})
notification.show()
return ''
}
} else {
return ''
}
}

const uploadChoosedFiles = async (webContents: WebContents, files: IFileWithPath[]) => {
const uploadChoosedFiles = async (webContents: WebContents, files: IFileWithPath[]): Promise<string[]> => {
const input = files.map(item => item.path)
const imgs = await uploader.setWebContents(webContents).upload(input)
const result = []
if (imgs !== false) {
const pasteStyle = db.get('settings.pasteStyle') || 'markdown'
let pasteText = ''
Expand All @@ -419,12 +431,16 @@ const uploadChoosedFiles = async (webContents: WebContents, files: IFileWithPath
notification.show()
}, i * 100)
db.insert('uploaded', imgs[i])
result.push(imgs[i].imgUrl!)
}
clipboard.writeText(pasteText)
window!.webContents.send('uploadFiles', imgs)
if (settingWindow) {
settingWindow.webContents.send('updateGallery')
}
return result
} else {
return []
}
}

Expand Down Expand Up @@ -522,7 +538,7 @@ ipcMain.on('openSettingWindow', () => {

ipcMain.on('openMiniWindow', () => {
if (!miniWindow) {
createMiniWidow()
createMiniWindow()
}
miniWindow!.show()
miniWindow!.focus()
Expand Down Expand Up @@ -611,7 +627,7 @@ app.on('ready', async () => {
updateShortKeyFromVersion212(db, db.get('settings.shortKey'))
shortKeyHandler.init()
})

server.startup()
if (process.env.NODE_ENV !== 'development') {
let files = getUploadFiles()
if (files === null) {
Expand Down Expand Up @@ -654,6 +670,7 @@ app.on('activate', () => {
app.on('will-quit', () => {
globalShortcut.unregisterAll()
bus.removeAllListeners()
server.shutdown()
})

app.setLoginItemSettings({
Expand All @@ -664,7 +681,9 @@ function initEventCenter () {
const eventList: any = {
'picgo:upload': uploadClipboardFiles,
'createSettingWindow': shortKeyRequestSettingWindow,
hideMiniWindow
hideMiniWindow,
[UPLOAD_WITH_CLIPBOARD_FILES]: busCallUploadClipboardFiles,
[UPLOAD_WITH_FILES]: busCallUploadFiles
}
for (let i in eventList) {
bus.on(i, eventList[i])
Expand All @@ -682,17 +701,35 @@ function hideMiniWindow () {
}
}

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

async function busCallUploadFiles (pathList: IFileWithPath[]) {
let win
if (miniWindow && miniWindow.isVisible()) {
win = miniWindow
} else {
win = settingWindow || window || createSettingWindow()
}
const urls = await uploadChoosedFiles(win.webContents, pathList)
bus.emit(UPLOAD_WITH_FILES_RESPONSE, urls)
}

// Exit cleanly on request from parent process in development mode.
if (isDevelopment) {
if (process.platform === 'win32') {
process.on('message', data => {
if (data === 'graceful-exit') {
app.quit()
server.shutdown()
}
})
} else {
process.on('SIGTERM', () => {
app.quit()
server.shutdown()
})
}
}
Expand Down
72 changes: 72 additions & 0 deletions src/main/server/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import http from 'http'
import routers from './routerManager'
import {
handleResponse
} from './utils'

class Server {
private httpServer: http.Server
private port: number = 36677
constructor () {
this.httpServer = http.createServer(this.handleRequest)
}
private handleRequest = (request: http.IncomingMessage, response: http.ServerResponse) => {
if (request.method === 'POST') {
if (!routers.getHandler(request.url!)) {
handleResponse({
response,
statusCode: 404,
header: {},
body: {
success: false
}
})
} else {
let body: string = ''
let postObj: IObj
request.on('data', chunk => {
body += chunk
})
request.on('end', () => {
try {
postObj = JSON.parse(body)
} catch (err) {
return handleResponse({
response,
body: {
success: false,
message: 'Not sending data in JSON format'
}
})
}
const handler = routers.getHandler(request.url!)
handler!({
...postObj,
response
})
})
}
} else {
response.statusCode = 404
response.end()
}
}
private listen = (port: number) => {
console.log(`server listen at ${port}`)
this.httpServer.listen(port).on('error', (err: ErrnoException) => {
if (err.errno === 'EADDRINUSE') {
console.log(`----- Port ${port} is busy, trying with port ${port + 1} -----`)
this.port += 1
this.listen(this.port)
}
})
}
startup () {
this.listen(this.port)
}
shutdown () {
this.httpServer.close()
}
}

export default new Server()
20 changes: 20 additions & 0 deletions src/main/server/router.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
class Router {
private router = new Map<string, routeHandler>()

get (url: string, callback: routeHandler): void {
this.router.set(url, callback)
}
post (url: string, callback: routeHandler): void {
this.router.set(url, callback)
}

getHandler (url: string) {
if (this.router.has(url)) {
return this.router.get(url)
} else {
return null
}
}
}

export default new Router()
69 changes: 69 additions & 0 deletions src/main/server/routerManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import router from './router'
import {
uploadWithClipboardFiles,
uploadWithFiles
} from '~/main/utils/busApi/index'
import {
handleResponse
} from './utils'
import logger from '../utils/logger'

router.get('/upload', async ({
response,
list = []
} : {
response: IHttpResponse,
list?: string[]
}): Promise<void> => {
try {
if (list.length === 0) {
// upload with clipboard
const res = await uploadWithClipboardFiles()
if (res.success) {
handleResponse({
response,
body: {
success: true,
result: [res.result]
}
})
} else {
handleResponse({
response
})
}
} else {
// upload with files
const pathList = list.map(item => {
return {
path: item
}
})
const res = await uploadWithFiles(pathList)
if (res.success) {
handleResponse({
response,
body: {
success: true,
result: res.result
}
})
} else {
handleResponse({
response
})
}
}
} catch (err) {
logger.error(err)
handleResponse({
response,
body: {
success: false,
message: err
}
})
}
})

export default router
19 changes: 19 additions & 0 deletions src/main/server/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export const handleResponse = ({
response,
statusCode = 200,
header = {
'Content-Type': 'application/json'
},
body = {
success: false
}
} : {
response: IHttpResponse,
statusCode?: number,
header?: IObj,
body?: any
}) => {
response.writeHead(statusCode, header)
response.write(JSON.stringify(body))
response.end()
}
6 changes: 6 additions & 0 deletions src/main/utils/busApi/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const GET_SETTING_WINDOW = 'GET_SETTING_WINDOW'
export const GET_MINI_WINDOW = 'GET_SETTING_WINDOW'
export const UPLOAD_WITH_FILES = 'UPLOAD_WITH_FILES'
export const UPLOAD_WITH_FILES_RESPONSE = 'UPLOAD_WITH_FILES_RESPONSE'
export const UPLOAD_WITH_CLIPBOARD_FILES = 'UPLOAD_WITH_CLIPBOARD_FILES'
export const UPLOAD_WITH_CLIPBOARD_FILES_RESPONSE = 'UPLOAD_WITH_CLIPBOARD_FILES_RESPONSE'
Loading

0 comments on commit c56d4ef

Please sign in to comment.