FoundKey/packages/backend/src/server/web/url-preview.ts

66 lines
1.5 KiB
TypeScript
Raw Normal View History

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