From b75184ec8e3436200bacdcd832e3324702553d20 Mon Sep 17 00:00:00 2001 From: syuilo Date: Sun, 18 Sep 2022 03:27:08 +0900 Subject: なんかもうめっちゃ変えた MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../backend/src/server/web/UrlPreviewService.ts | 84 ++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 packages/backend/src/server/web/UrlPreviewService.ts (limited to 'packages/backend/src/server/web/UrlPreviewService.ts') diff --git a/packages/backend/src/server/web/UrlPreviewService.ts b/packages/backend/src/server/web/UrlPreviewService.ts new file mode 100644 index 0000000000..4e3b456144 --- /dev/null +++ b/packages/backend/src/server/web/UrlPreviewService.ts @@ -0,0 +1,84 @@ +import { Inject, Injectable } from '@nestjs/common'; +import summaly from 'summaly'; +import { DI } from '@/di-symbols.js'; +import { UsersRepository } from '@/models/index.js'; +import { Config } from '@/config.js'; +import { MetaService } from '@/core/MetaService.js'; +import { HttpRequestService } from '@/core/HttpRequestService.js'; +import Logger from '@/logger.js'; +import { query } from '@/misc/prelude/url.js'; +import type Koa from 'koa'; + +@Injectable() +export class UrlPreviewService { + #logger: Logger; + + constructor( + @Inject(DI.config) + private config: Config, + + @Inject(DI.usersRepository) + private usersRepository: UsersRepository, + + private metaService: MetaService, + private httpRequestService: HttpRequestService, + ) { + this.#logger = new Logger('url-preview'); + } + + #wrap(url?: string): string | null { + return url != null + ? url.match(/^https?:\/\//) + ? `${this.config.url}/proxy/preview.webp?${query({ + url, + preview: '1', + })}` + : url + : null; + } + + public async handle(ctx: Koa.Context) { + 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; + } + + const meta = await this.metaService.fetch(); + + this.#logger.info(meta.summalyProxy + ? `(Proxy) Getting preview of ${url}@${lang} ...` + : `Getting preview of ${url}@${lang} ...`); + + try { + const summary = meta.summalyProxy ? await this.httpRequestService.getJson(`${meta.summalyProxy}?${query({ + url: url, + lang: lang ?? 'ja-JP', + })}`) : await summaly.default(url, { + followRedirects: false, + lang: lang ?? 'ja-JP', + }); + + this.#logger.succ(`Got preview of ${url}: ${summary.title}`); + + summary.icon = this.#wrap(summary.icon); + summary.thumbnail = this.#wrap(summary.thumbnail); + + // Cache 7days + ctx.set('Cache-Control', 'max-age=604800, immutable'); + + ctx.body = summary; + } catch (err) { + this.#logger.warn(`Failed to get preview of ${url}: ${err}`); + ctx.status = 200; + ctx.set('Cache-Control', 'max-age=86400, immutable'); + ctx.body = '{}'; + } + } +} -- cgit v1.2.3-freya