From 536e7d69eaf0e3a21a1ee2baaaef47ce93be2121 Mon Sep 17 00:00:00 2001 From: takker99 <37929109+takker99@users.noreply.github.com> Date: Fri, 8 Apr 2022 21:27:52 +0900 Subject: [PATCH] =?UTF-8?q?:sparkles:=20Gyazo=20OAuth=20upload=E3=81=AEacc?= =?UTF-8?q?ess=20token=E3=82=92=E5=8F=96=E5=BE=97=E3=81=A7=E3=81=8D?= =?UTF-8?q?=E3=82=8B=E3=82=88=E3=81=86=E3=81=AB=E3=81=AA=E3=81=A3=E3=81=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- rest/getGyazoToken.ts | 53 +++++++++++++++++++++++++++++++++++++++++++ rest/mod.ts | 1 + 2 files changed, 54 insertions(+) create mode 100644 rest/getGyazoToken.ts diff --git a/rest/getGyazoToken.ts b/rest/getGyazoToken.ts new file mode 100644 index 0000000..7489c2f --- /dev/null +++ b/rest/getGyazoToken.ts @@ -0,0 +1,53 @@ +import type { NotLoggedInError } from "../deps/scrapbox.ts"; +import { cookie } from "./auth.ts"; +import { UnexpectedResponseError } from "./error.ts"; +import { tryToErrorLike } from "../is.ts"; +import { BaseOptions, Result, setDefaults } from "./util.ts"; + +export interface GetGyazoTokenOptions extends BaseOptions { + /** Gyazo Teamsのチーム名 + * + * Gyazo Teamsでuploadしたいときに使う + */ + gyazoTeamsName?: string; +} + +/** Gyazo OAuth uploadで使うaccess tokenを取得する + * + * @param init connect.sidなど + * @return access token + */ +export const getGyazoToken = async ( + init?: GetGyazoTokenOptions, +): Promise< + Result< + string | undefined, + NotLoggedInError + > +> => { + const { sid, hostName, gyazoTeamsName } = setDefaults(init ?? {}); + const path = `https://${hostName}/api/login/gyazo/oauth-upload/token${ + gyazoTeamsName ? `?gyazoTeamsName=${gyazoTeamsName}` : "" + }`; + + const res = await fetch( + path, + sid ? { headers: { Cookie: cookie(sid) } } : undefined, + ); + + if (!res.ok) { + const text = await res.text(); + const value = tryToErrorLike(text); + if (!value) { + throw new UnexpectedResponseError({ + path: new URL(path), + ...res, + body: await res.text(), + }); + } + return { ok: false, value: value as NotLoggedInError }; + } + + const { token } = (await res.json()) as { token?: string }; + return { ok: true, value: token }; +}; diff --git a/rest/mod.ts b/rest/mod.ts index c78102f..88723d0 100644 --- a/rest/mod.ts +++ b/rest/mod.ts @@ -7,6 +7,7 @@ export * from "./link.ts"; export * from "./search.ts"; export * from "./getWebPageTitle.ts"; export * from "./getTweetInfo.ts"; +export * from "./getGyazoToken.ts"; export * from "./auth.ts"; export * from "./util.ts"; export * from "./error.ts";