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