2018-04-13 00:06:18 +03:00
|
|
|
import * as Koa from 'koa';
|
2016-12-29 00:49:51 +02:00
|
|
|
import summaly from 'summaly';
|
2019-04-24 02:11:19 +03:00
|
|
|
import { fetchMeta } from '../../misc/fetch-meta';
|
2019-03-02 11:51:59 +02:00
|
|
|
import Logger from '../../services/logger';
|
2019-03-10 18:03:09 +02:00
|
|
|
import config from '../../config';
|
|
|
|
import { query } from '../../prelude/url';
|
2020-04-09 17:42:23 +03:00
|
|
|
import { getJson } from '../../misc/fetch';
|
2019-02-28 05:00:57 +02:00
|
|
|
|
|
|
|
const logger = new Logger('url-preview');
|
2016-12-29 00:49:51 +02:00
|
|
|
|
2019-11-24 10:09:32 +02:00
|
|
|
module.exports = async (ctx: Koa.Context) => {
|
2018-11-23 01:13:17 +02:00
|
|
|
const meta = await fetchMeta();
|
|
|
|
|
2019-03-01 07:40:29 +02:00
|
|
|
logger.info(meta.summalyProxy
|
2019-06-21 09:41:02 +03:00
|
|
|
? `(Proxy) Getting preview of ${ctx.query.url}@${ctx.query.lang} ...`
|
|
|
|
: `Getting preview of ${ctx.query.url}@${ctx.query.lang} ...`);
|
2019-02-28 05:00:57 +02:00
|
|
|
|
2018-05-18 06:08:05 +03:00
|
|
|
try {
|
2020-04-09 17:42:23 +03:00
|
|
|
const summary = meta.summalyProxy ? await getJson(`${meta.summalyProxy}?${query({
|
|
|
|
url: ctx.query.url,
|
|
|
|
lang: ctx.query.lang || 'ja-JP'
|
|
|
|
})}`) : await summaly(ctx.query.url, {
|
2019-06-21 09:41:02 +03:00
|
|
|
followRedirects: false,
|
|
|
|
lang: ctx.query.lang || 'ja-JP'
|
2018-05-18 06:21:53 +03:00
|
|
|
});
|
2018-08-25 19:56:21 +03:00
|
|
|
|
2019-02-28 05:00:57 +02:00
|
|
|
logger.succ(`Got preview of ${ctx.query.url}: ${summary.title}`);
|
|
|
|
|
2018-05-18 06:08:05 +03:00
|
|
|
summary.icon = wrap(summary.icon);
|
|
|
|
summary.thumbnail = wrap(summary.thumbnail);
|
2018-04-13 19:45:44 +03:00
|
|
|
|
2018-05-18 06:08:05 +03:00
|
|
|
// Cache 7days
|
|
|
|
ctx.set('Cache-Control', 'max-age=604800, immutable');
|
2018-04-13 19:45:44 +03:00
|
|
|
|
2018-05-18 06:08:05 +03:00
|
|
|
ctx.body = summary;
|
|
|
|
} catch (e) {
|
2019-06-13 16:35:37 +03:00
|
|
|
logger.warn(`Failed to get preview of ${ctx.query.url}: ${e}`);
|
2018-08-11 12:04:59 +03:00
|
|
|
ctx.status = 200;
|
|
|
|
ctx.set('Cache-Control', 'max-age=86400, immutable');
|
|
|
|
ctx.body = '{}';
|
2018-05-18 06:08:05 +03:00
|
|
|
}
|
2016-12-29 00:49:51 +02:00
|
|
|
};
|
|
|
|
|
2019-04-12 19:43:22 +03:00
|
|
|
function wrap(url?: string): string | null {
|
2017-01-14 03:51:48 +02:00
|
|
|
return url != null
|
2019-02-10 12:19:26 +02:00
|
|
|
? url.match(/^https?:\/\//)
|
2019-03-10 18:03:09 +02:00
|
|
|
? `${config.url}/proxy/preview.jpg?${query({
|
|
|
|
url,
|
|
|
|
preview: '1'
|
|
|
|
})}`
|
2019-02-10 12:19:26 +02:00
|
|
|
: url
|
2017-01-14 03:51:48 +02:00
|
|
|
: null;
|
2016-12-29 00:49:51 +02:00
|
|
|
}
|