|
| 1 | +import type { NotLoggedInError } from "../deps/scrapbox.ts"; |
| 2 | +import { cookie } from "./auth.ts"; |
| 3 | +import { UnexpectedResponseError } from "./error.ts"; |
| 4 | +import { tryToErrorLike } from "../is.ts"; |
| 5 | +import { BaseOptions, Result, setDefaults } from "./util.ts"; |
| 6 | + |
| 7 | +export interface GetGyazoTokenOptions extends BaseOptions { |
| 8 | + /** Gyazo Teamsのチーム名 |
| 9 | + * |
| 10 | + * Gyazo Teamsでuploadしたいときに使う |
| 11 | + */ |
| 12 | + gyazoTeamsName?: string; |
| 13 | +} |
| 14 | + |
| 15 | +/** Gyazo OAuth uploadで使うaccess tokenを取得する |
| 16 | + * |
| 17 | + * @param init connect.sidなど |
| 18 | + * @return access token |
| 19 | + */ |
| 20 | +export const getGyazoToken = async ( |
| 21 | + init?: GetGyazoTokenOptions, |
| 22 | +): Promise< |
| 23 | + Result< |
| 24 | + string | undefined, |
| 25 | + NotLoggedInError |
| 26 | + > |
| 27 | +> => { |
| 28 | + const { sid, hostName, gyazoTeamsName } = setDefaults(init ?? {}); |
| 29 | + const path = `https://${hostName}/api/login/gyazo/oauth-upload/token${ |
| 30 | + gyazoTeamsName ? `?gyazoTeamsName=${gyazoTeamsName}` : "" |
| 31 | + }`; |
| 32 | + |
| 33 | + const res = await fetch( |
| 34 | + path, |
| 35 | + sid ? { headers: { Cookie: cookie(sid) } } : undefined, |
| 36 | + ); |
| 37 | + |
| 38 | + if (!res.ok) { |
| 39 | + const text = await res.text(); |
| 40 | + const value = tryToErrorLike(text); |
| 41 | + if (!value) { |
| 42 | + throw new UnexpectedResponseError({ |
| 43 | + path: new URL(path), |
| 44 | + ...res, |
| 45 | + body: await res.text(), |
| 46 | + }); |
| 47 | + } |
| 48 | + return { ok: false, value: value as NotLoggedInError }; |
| 49 | + } |
| 50 | + |
| 51 | + const { token } = (await res.json()) as { token?: string }; |
| 52 | + return { ok: true, value: token }; |
| 53 | +}; |
0 commit comments