|
| 1 | +import type { |
| 2 | + BadRequestError, |
| 3 | + InvalidURLError, |
| 4 | + SessionError, |
| 5 | +} from "../deps/scrapbox.ts"; |
| 6 | +import { cookie, getCSRFToken } from "./auth.ts"; |
| 7 | +import { UnexpectedResponseError } from "./error.ts"; |
| 8 | +import { tryToErrorLike } from "../is.ts"; |
| 9 | +import { ExtendedOptions, Result, setDefaults } from "./util.ts"; |
| 10 | + |
| 11 | +/** 指定したURLのweb pageのtitleをscrapboxのserver経由で取得する |
| 12 | + * |
| 13 | + * @param url 取得したいURL |
| 14 | + * @param init connect.sidなど |
| 15 | + * @return web pageのtilte |
| 16 | + */ |
| 17 | +export const getWebPageTitle = async ( |
| 18 | + url: string | URL, |
| 19 | + init?: ExtendedOptions, |
| 20 | +): Promise< |
| 21 | + Result< |
| 22 | + string, |
| 23 | + | SessionError |
| 24 | + | InvalidURLError |
| 25 | + | BadRequestError |
| 26 | + > |
| 27 | +> => { |
| 28 | + const { sid, hostName, fetch, csrf } = setDefaults(init ?? {}); |
| 29 | + const path = `https://${hostName}/api/embed-text/url?url=${ |
| 30 | + encodeURIComponent(url.toString()) |
| 31 | + }`; |
| 32 | + |
| 33 | + const res = await fetch( |
| 34 | + path, |
| 35 | + { |
| 36 | + method: "POST", |
| 37 | + headers: { |
| 38 | + "Content-Type": "application/json;charset=utf-8", |
| 39 | + "X-CSRF-TOKEN": csrf ?? await getCSRFToken(init), |
| 40 | + ...(sid ? { Cookie: cookie(sid) } : {}), |
| 41 | + }, |
| 42 | + body: JSON.stringify({ timeout: 3000 }), |
| 43 | + }, |
| 44 | + ); |
| 45 | + |
| 46 | + if (!res.ok) { |
| 47 | + if (res.status === 422) { |
| 48 | + return { |
| 49 | + ok: false, |
| 50 | + value: { |
| 51 | + name: "InvalidURLError", |
| 52 | + message: (await res.json()).message as string, |
| 53 | + }, |
| 54 | + }; |
| 55 | + } |
| 56 | + const text = await res.json(); |
| 57 | + const value = tryToErrorLike(text); |
| 58 | + if (!value) { |
| 59 | + throw new UnexpectedResponseError({ |
| 60 | + path: new URL(path), |
| 61 | + ...res, |
| 62 | + body: await res.text(), |
| 63 | + }); |
| 64 | + } |
| 65 | + return { |
| 66 | + ok: false, |
| 67 | + value: value as |
| 68 | + | SessionError |
| 69 | + | BadRequestError, |
| 70 | + }; |
| 71 | + } |
| 72 | + |
| 73 | + const { title } = (await res.json()) as { title: string }; |
| 74 | + return { ok: true, value: title }; |
| 75 | +}; |
0 commit comments