Skip to content

Commit

Permalink
Improve URL preview (#2465)
Browse files Browse the repository at this point in the history
* Twitter, YouTube

* Twitch
  • Loading branch information
mei23 authored Jun 16, 2023
1 parent 662585e commit 64c80b4
Showing 1 changed file with 37 additions and 9 deletions.
46 changes: 37 additions & 9 deletions src/server/web/url-preview.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as Koa from 'koa';
import summaly from 'summaly';
import { Summary } from 'summaly';
import { fetchMeta } from '../../misc/fetch-meta';
import Logger from '../../services/logger';
import config from '../../config';
Expand All @@ -9,20 +9,44 @@ import { sanitizeUrl } from '../../misc/sanitize-url';

const logger = new Logger('url-preview');

//#region SummaryInstance
let summaryInstance: Summary | null = null;

function getSummaryInstance(): Summary {
if (summaryInstance) return summaryInstance;
summaryInstance = new Summary({
allowedPlugins: [
'twitter',
'youtube',
],
});
return summaryInstance;
}
//#endregion


module.exports = async (ctx: Koa.Context) => {
const meta = await fetchMeta();

const url = sanitizeUrl(ctx.query.url);
if (url == null) {
ctx.status = 400;
ctx.set('Cache-Control', 'max-age=3600');
return;
}

const lang = ctx.query.lang || 'ja-JP';

logger.info(meta.summalyProxy
? `(Proxy) Getting preview of ${ctx.query.url}@${ctx.query.lang} ...`
: `Getting preview of ${ctx.query.url}@${ctx.query.lang} ...`);
? `(Proxy) Getting preview of ${url}@${lang} ...`
: `Getting preview of ${url}@${lang} ...`);

try {
const summary = meta.summalyProxy ? await getJson(`${meta.summalyProxy}?${query({
url: ctx.query.url,
lang: ctx.query.lang || 'ja-JP'
})}`) : await summaly(ctx.query.url, {
followRedirects: false,
lang: ctx.query.lang || 'ja-JP'
url: url,
lang: lang
})}`) : await getSummaryInstance().summary(url, {
lang: lang
});

logger.succ(`Got preview of ${ctx.query.url}: ${summary.title}`);
Expand All @@ -33,14 +57,18 @@ module.exports = async (ctx: Koa.Context) => {
if (summary.player) summary.player.url = sanitizeUrl(summary.player.url);
summary.url = sanitizeUrl(summary.url);

if (summary.player?.url?.startsWith('https://player.twitch.tv/')) {
summary.player.url = summary.player.url.replace('parent=meta.tag', `parent=${config.url.replace(/^https?:[/][/]/, '')}`);
}

// Cache 7days
ctx.set('Cache-Control', 'max-age=604800, immutable');

ctx.body = summary;
} catch (e) {
logger.warn(`Failed to get preview of ${ctx.query.url}: ${e}`);
ctx.status = 200;
ctx.set('Cache-Control', 'max-age=86400, immutable');
ctx.set('Cache-Control', 'max-age=3600, immutable');
ctx.body = '{}';
}
};
Expand Down

0 comments on commit 64c80b4

Please sign in to comment.