2019-02-05 03:01:36 +09:00
|
|
|
import * as fs from 'fs';
|
|
|
|
import * as Koa from 'koa';
|
|
|
|
import { serverLogger } from '..';
|
2019-03-11 01:03:09 +09:00
|
|
|
import { IImage, ConvertToPng, ConvertToJpeg } from '../../services/drive/image-processor';
|
2019-03-21 04:50:44 +09:00
|
|
|
import { createTemp } from '../../misc/create-temp';
|
|
|
|
import { downloadUrl } from '../../misc/donwload-url';
|
|
|
|
import { detectMine } from '../../misc/detect-mine';
|
2019-02-05 03:01:36 +09:00
|
|
|
|
|
|
|
export async function proxyMedia(ctx: Koa.BaseContext) {
|
|
|
|
const url = 'url' in ctx.query ? ctx.query.url : 'https://' + ctx.params.url;
|
|
|
|
|
|
|
|
// Create temp file
|
2019-03-21 04:50:44 +09:00
|
|
|
const [path, cleanup] = await createTemp();
|
2019-02-05 03:01:36 +09:00
|
|
|
|
|
|
|
try {
|
2019-03-21 04:50:44 +09:00
|
|
|
await downloadUrl(url, path);
|
2019-02-05 03:01:36 +09:00
|
|
|
|
|
|
|
const [type, ext] = await detectMine(path);
|
|
|
|
|
|
|
|
let image: IImage;
|
|
|
|
|
|
|
|
if ('static' in ctx.query && ['image/png', 'image/gif'].includes(type)) {
|
|
|
|
image = await ConvertToPng(path, 498, 280);
|
2019-03-11 01:03:09 +09:00
|
|
|
} else if ('preview' in ctx.query && ['image/jpeg', 'image/png', 'image/gif'].includes(type)) {
|
|
|
|
image = await ConvertToJpeg(path, 200, 200);
|
2019-02-05 03:01:36 +09:00
|
|
|
} else {
|
|
|
|
image = {
|
|
|
|
data: fs.readFileSync(path),
|
|
|
|
ext,
|
|
|
|
type,
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
ctx.set('Content-Type', type);
|
|
|
|
ctx.set('Cache-Control', 'max-age=31536000, immutable');
|
|
|
|
ctx.body = image.data;
|
|
|
|
} catch (e) {
|
|
|
|
serverLogger.error(e);
|
2019-02-06 00:20:00 +09:00
|
|
|
|
|
|
|
if (typeof e == 'number' && e >= 400 && e < 500) {
|
|
|
|
ctx.status = e;
|
|
|
|
} else {
|
|
|
|
ctx.status = 500;
|
|
|
|
}
|
2019-02-05 03:01:36 +09:00
|
|
|
} finally {
|
|
|
|
cleanup();
|
|
|
|
}
|
|
|
|
}
|