const Router = require('koa-router') const r = new Router() 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) r.use('/web', require('./web').routes()) r.use('/api', require('./api').routes()) r.use('/line', require('./line').routes()) r.use('/google', require('./google').routes()) r.use('/twitch', require('./twitch').routes()) module.exports = r