iceshrimp/src/server/web/url-preview.ts

58 lines
1.5 KiB
TypeScript
Raw Normal View History

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