jormungandr-bite/src/server/web/url-preview.ts

26 lines
612 B
TypeScript
Raw Normal View History

2018-04-12 15:06:18 -06:00
import * as Koa from 'koa';
2016-12-28 15:49:51 -07:00
import summaly from 'summaly';
2018-04-12 15:06:18 -06:00
module.exports = async (ctx: Koa.Context) => {
2018-05-17 21:08:05 -06:00
try {
const summary = await summaly(ctx.query.url);
summary.icon = wrap(summary.icon);
summary.thumbnail = wrap(summary.thumbnail);
2018-04-13 10:45:44 -06:00
2018-05-17 21:08:05 -06:00
// Cache 7days
ctx.set('Cache-Control', 'max-age=604800, immutable');
2018-04-13 10:45:44 -06:00
2018-05-17 21:08:05 -06:00
ctx.body = summary;
} catch (e) {
ctx.status = 500;
}
2016-12-28 15:49:51 -07:00
};
function wrap(url: string): string {
2017-01-13 18:51:48 -07:00
return url != null
? url.startsWith('https://') || url.startsWith('data:')
2018-05-05 11:08:27 -06:00
? url
2018-05-09 05:14:34 -06:00
: `https://images.weserv.nl/?url=${encodeURIComponent(url.replace(/^http:\/\//, ''))}`
2017-01-13 18:51:48 -07:00
: null;
2016-12-28 15:49:51 -07:00
}