mtfosbot/route/index.js

109 lines
2.7 KiB
JavaScript
Raw Normal View History

2018-06-25 10:07:10 +00:00
const Router = require('koa-router')
const r = new Router()
2018-07-13 08:07:49 +00:00
const gm = require('gm')
const config = require('@config/index')
const fs = require('fs')
const path = require('path')
const getImageToRes = async (c, n) => {
let filepath = path.resolve(config.image_root, c.state.file)
console.log(filepath)
try {
fs.accessSync(filepath)
} catch (err) {
c.throw(404, 'image not found')
}
let buf = null
let imgSize = await getImageSize(filepath)
if (imgSize === null) c.throw(500)
if (c.state.ori === true) {
// max 1024x1024
if (imgSize.width > 1024 || imgSize.height > 1024) {
buf = await resizeImage(filepath, 1024)
if (buf === null) c.throw(500)
}
} else {
// max 240x240
if (imgSize.width > 240 || imgSize.height > 240) {
buf = await resizeImage(filepath, 240)
if (buf === null) c.throw(500)
}
}
if (buf === null) {
let format = await getImageFormat(filepath)
if (format === null) c.throw(500)
if (format !== 'JPEG') {
buf = await convertToJPEG(filepath)
if (buf === null) c.throw(500)
} else {
buf = fs.readFileSync(filepath)
}
}
c.type = 'image/jpeg'
c.body = buf
}
const convertToJPEG = async (file = null) => {
let buf = await new Promise((resolve) => {
gm(file).toBuffer('JPEG', (err, buf) => {
resolve(err ? null : buf)
})
})
return buf
}
const getImageFormat = async (file = null) => {
let format = await new Promise((resolve) => {
gm(file).format((err, format) => {
resolve(err ? null : format)
})
})
return format
}
const getImageSize = async (file = null) => {
let size = await new Promise((resolve) => {
gm(file).size((err, val) => {
resolve(err ? null : val)
})
})
return size
}
const resizeImage = async (file = null, size = 1024) => {
let buf = await new Promise((resolve) => {
gm(file).resize(size, size).toBuffer('JPEG', (err, buf) => {
resolve(err ? null : buf)
})
})
return buf
}
r.get('/image/origin/:name', async (c, n) => {
c.state.ori = true
let name = c.params.name || ''
if (typeof name !== 'string' || name.trim().length === 0) c.throw('image name not valid', 400)
c.state.file = name
return n()
}, getImageToRes)
r.get('/image/thumbnail/:name', async (c, n) => {
c.state.ori = false
let name = c.params.name || ''
if (typeof name !== 'string' || name.trim().length === 0) c.throw('image name not valid', 400)
c.state.file = name
return n()
}, getImageToRes)
2018-06-25 10:07:10 +00:00
2018-08-11 15:28:00 +00:00
r.use('/web', require('./web').routes())
r.use('/api', require('./api').routes())
2018-06-25 10:07:10 +00:00
r.use('/line', require('./line').routes())
2018-07-03 14:14:14 +00:00
r.use('/google', require('./google').routes())
2018-08-12 15:31:09 +00:00
r.use('/twitch', require('./twitch').routes())
2018-06-25 10:07:10 +00:00
module.exports = r