2019-02-04 19:01:36 +01:00
|
|
|
import * as fs from 'fs';
|
|
|
|
import * as Koa from 'koa';
|
|
|
|
import { serverLogger } from '..';
|
2019-05-15 14:27:20 +02:00
|
|
|
import { IImage, convertToPng, convertToJpeg } from '../../services/drive/image-processor';
|
2019-03-20 20:50:44 +01:00
|
|
|
import { createTemp } from '../../misc/create-temp';
|
2020-04-11 12:49:25 +02:00
|
|
|
import { downloadUrl } from '../../misc/download-url';
|
2020-01-12 08:40:58 +01:00
|
|
|
import { detectType } from '../../misc/get-file-info';
|
2019-02-04 19:01:36 +01:00
|
|
|
|
2019-11-24 09:09:32 +01:00
|
|
|
export async function proxyMedia(ctx: Koa.Context) {
|
2019-02-04 19:01:36 +01:00
|
|
|
const url = 'url' in ctx.query ? ctx.query.url : 'https://' + ctx.params.url;
|
|
|
|
|
|
|
|
// Create temp file
|
2019-03-20 20:50:44 +01:00
|
|
|
const [path, cleanup] = await createTemp();
|
2019-02-04 19:01:36 +01:00
|
|
|
|
|
|
|
try {
|
2019-03-20 20:50:44 +01:00
|
|
|
await downloadUrl(url, path);
|
2019-02-04 19:01:36 +01:00
|
|
|
|
2020-01-12 08:40:58 +01:00
|
|
|
const { mime, ext } = await detectType(path);
|
2019-02-04 19:01:36 +01:00
|
|
|
|
2020-01-12 08:40:58 +01:00
|
|
|
if (!mime.startsWith('image/')) throw 403;
|
2019-06-14 05:14:23 +02:00
|
|
|
|
2019-02-04 19:01:36 +01:00
|
|
|
let image: IImage;
|
|
|
|
|
2020-01-12 08:40:58 +01:00
|
|
|
if ('static' in ctx.query && ['image/png', 'image/gif', 'image/apng', 'image/vnd.mozilla.apng'].includes(mime)) {
|
2019-05-15 14:27:20 +02:00
|
|
|
image = await convertToPng(path, 498, 280);
|
2020-01-12 08:40:58 +01:00
|
|
|
} else if ('preview' in ctx.query && ['image/jpeg', 'image/png', 'image/gif', 'image/apng', 'image/vnd.mozilla.apng'].includes(mime)) {
|
2019-05-15 14:27:20 +02:00
|
|
|
image = await convertToJpeg(path, 200, 200);
|
2019-02-04 19:01:36 +01:00
|
|
|
} else {
|
|
|
|
image = {
|
|
|
|
data: fs.readFileSync(path),
|
|
|
|
ext,
|
2020-01-12 08:40:58 +01:00
|
|
|
type: mime,
|
2019-02-04 19:01:36 +01:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2019-07-12 15:21:47 +02:00
|
|
|
ctx.set('Content-Type', image.type);
|
2019-02-04 19:01:36 +01:00
|
|
|
ctx.set('Cache-Control', 'max-age=31536000, immutable');
|
|
|
|
ctx.body = image.data;
|
|
|
|
} catch (e) {
|
|
|
|
serverLogger.error(e);
|
2019-02-05 16:20:00 +01:00
|
|
|
|
|
|
|
if (typeof e == 'number' && e >= 400 && e < 500) {
|
|
|
|
ctx.status = e;
|
|
|
|
} else {
|
|
|
|
ctx.status = 500;
|
|
|
|
}
|
2019-02-04 19:01:36 +01:00
|
|
|
} finally {
|
|
|
|
cleanup();
|
|
|
|
}
|
|
|
|
}
|