···11-import {
22- SPOTIFY_CLIENT_ID,
33- SPOTIFY_CLIENT_SECRET,
44- SPOTIFY_REDIRECT_URI,
55-} from "astro:env/server";
66-import fs from "fs/promises";
77-88-const throws = (val: unknown) => {
99- throw val;
1010-};
1111-1212-/** via: https://www.totaltypescript.com/concepts/the-prettify-helper */
1313-type Prettify<T> = {
1414- [K in keyof T]: T[K];
1515-} & {};
1616-1717-type AuthToken = {
1818- access_token: string;
1919- token_type: "Bearer";
2020- scope: string;
2121- expires_in: number;
2222- refresh_token: string;
2323-};
2424-2525-type RefreshToken = Prettify<
2626- Omit<AuthToken, "refresh_token"> & { refresh_token?: string }
2727->;
2828-2929-const isRefreshToken = (obj: unknown): obj is RefreshToken =>
3030- // validate is object
3131- typeof obj === "object" &&
3232- obj !== null &&
3333- // validate properties
3434- "access_token" in obj &&
3535- typeof obj.access_token === "string" &&
3636- "token_type" in obj &&
3737- obj.token_type === "Bearer" &&
3838- "scope" in obj &&
3939- typeof obj.scope === "string" &&
4040- "expires_in" in obj &&
4141- typeof obj.expires_in === "number" &&
4242- // either refresh token exists as string or not at all
4343- (("refresh_token" in obj && typeof obj.refresh_token === "string") ||
4444- !("refresh_token" in obj));
4545-4646-// auth token is just refresh with a non optional refresh_token
4747-const isAuthToken = (obj: unknown): obj is AuthToken =>
4848- isRefreshToken(obj) && "refresh_token" in obj;
4949-5050-export async function getAccessCode(userAuthCode?: string) {
5151- const refreshToken = await fs
5252- .readFile("./.refreshToken", { encoding: "utf-8" })
5353- .catch((_) => undefined)
5454- .then((x) => (x === "" || x === "REFRESH_TOKEN" ? undefined : x));
5555- if (!(userAuthCode || refreshToken))
5656- throw new Error(
5757- "No auth code or refresh token.\nGenerate an auth code at `/src/pages/_callback`\nA refresh token will be generated from this auth token.",
5858- );
5959-6060- // prefer auth codes over refresh tokens
6161- // since the auth code may have updated scopes.
6262-6363- const accessFrom:
6464- | {
6565- userAuthCode: string;
6666- }
6767- | {
6868- refreshToken: string;
6969- } = userAuthCode
7070- ? { userAuthCode }
7171- : refreshToken
7272- ? { refreshToken }
7373- : (undefined as never);
7474-7575- const req = fetch("https://accounts.spotify.com/api/token", {
7676- method: "POST",
7777- headers: {
7878- "Content-Type": "application/x-www-form-urlencoded",
7979- Authorization: `Basic ${Buffer.from(SPOTIFY_CLIENT_ID + ":" + SPOTIFY_CLIENT_SECRET).toString("base64")}`,
8080- },
8181- body: new URLSearchParams({
8282- grant_type:
8383- "userAuthCode" in accessFrom ? "authorization_code" : "refresh_token",
8484- ...("userAuthCode" in accessFrom
8585- ? {
8686- code: accessFrom.userAuthCode,
8787- redirect_uri: SPOTIFY_REDIRECT_URI,
8888- }
8989- : {
9090- refresh_token: accessFrom.refreshToken,
9191- }),
9292- }).toString(),
9393- });
9494-9595- return (
9696- req
9797- // if res isn't 200 handle it in the catch
9898- .then((res) => (res.ok ? res : throws(res)))
9999- // request is 200-299
100100- // json can throw SyntaxError in this case
101101- .then((res) => res.json())
102102- .then((res) =>
103103- "userAuthCode" in accessFrom
104104- ? isAuthToken(res)
105105- ? { code: res.access_token, refresh: res.refresh_token }
106106- : throws({ err: "INVALID_RESPONSE", res })
107107- : isRefreshToken(res)
108108- ? {
109109- code: res.access_token,
110110- refresh: res.refresh_token ?? accessFrom.refreshToken,
111111- }
112112- : throws({ err: "INVALID_RESPONSE", res }),
113113- )
114114- // res is now an access token and refresh token
115115- .then((res) => {
116116- fs.writeFile("./.refreshToken", res.refresh, { encoding: "utf-8" });
117117- return res.code;
118118- })
119119- .catch((err) => {
120120- // SyntaxError
121121- // Response
122122- // {err: string, res: Response}
123123- if (err instanceof Response) console.error("Request failed:", err);
124124- else if (err instanceof SyntaxError)
125125- console.error("Response JSON failed", err);
126126- else if (err.err === "INVALID_RESPONSE")
127127- console.error("Response malformed:", err);
128128- else {
129129- console.error("Unhandled exception.");
130130- throw err;
131131- }
132132- })
133133- );
134134-}
135135-136136-export async function getSpotifyApi(url: string) {
137137- const accessToken = await getAccessCode();
138138- if (!accessToken)
139139- return new Error(
140140- "Failed to get access code. try using src/pages/_callback",
141141- );
142142- const res = await fetch("https://api.spotify.com/v1" + url, {
143143- headers: {
144144- Authorization: `Bearer ${accessToken}`,
145145- },
146146- })
147147- .then((res) => (!res.ok ? throws(res) : res))
148148- .catch((err) => {
149149- if (err instanceof Response) {
150150- if (err.status === 401)
151151- return new Error("Bad token. Try using /_callback");
152152- if (err.status === 403)
153153- return new Error("Bad OAuth. Cry about it (???)");
154154- if (err.status === 429) return new Error("Rate limited. Cry about it");
155155- console.error(err);
156156- return new Error("Unexpected status code");
157157- }
158158- if (err instanceof Error) return err;
159159- console.log("Unexpected exception.");
160160- throw err;
161161- });
162162-163163- return res;
164164-}
165165-166166-export async function nowPlayingSongID() {
167167- const res = await getSpotifyApi("/me/player/currently-playing");
168168- if (res instanceof Error) return res;
169169-170170- const output = await Promise.resolve(res)
171171- // send "not modified to catch"
172172- .then((res) => (res.status === 204 ? throws(res) : res))
173173- .then((res) => res.json() as Promise<Record<string, unknown>>)
174174- // res code is 204
175175- .catch((res) => undefined);
176176-177177- if (!output) return undefined;
178178-179179- // https://developer.spotify.com/documentation/web-api/reference/get-the-users-currently-playing-track
180180- return (output as { item: { id: string } | null }).item?.id ?? null;
181181-}
182182-183183-export async function getTrack(id: string) {
184184- const res = await getSpotifyApi("/tracks/" + id);
185185- if (res instanceof Error) return res;
186186-187187- const output = await Promise.resolve(res)
188188- // send "not modified to catch"
189189- .then((res) => (res.status === 204 ? throws(res) : res))
190190- .then((res) => res.json() as Promise<Record<string, unknown>>)
191191- // res code is 204
192192- .catch((res) => undefined);
193193-194194- if (!output) return undefined;
195195-196196- return output as {
197197- external_urls: {
198198- spotify: string;
199199- };
200200- album: {
201201- images: {
202202- url: string;
203203- width: number;
204204- height: number;
205205- }[];
206206- };
207207- name: string;
208208- artists: {
209209- id: string;
210210- name: string;
211211- }[];
212212- };
213213-}
+115
src/components/playing/spotify/access.ts
···11+import fs from "fs/promises";
22+import {
33+ SPOTIFY_CLIENT_ID,
44+ SPOTIFY_CLIENT_SECRET,
55+ SPOTIFY_REDIRECT_URI,
66+} from "astro:env/server";
77+import { SpotifyError, throws } from "./errors";
88+import { isAuthToken, isRefreshToken } from "./types";
99+1010+/**
1111+ * Get an access code which can be used to authenticate requests on behalf of the user.
1212+ * @param userAuthCode Authentication code for the user (via callback). Uses the stored refresh token if not provided
1313+ * @returns `string`: access code to authorize requests
1414+ * @returns `undefined`: failed to authenticate user.
1515+ * @throws `SpotifyError<NO_AUTH>` when no refresh token is stored and no auth code is provided
1616+ */
1717+export default async function getAccessCode(userAuthCode?: string) {
1818+ const refreshToken = await fs
1919+ .readFile("./.refreshToken", { encoding: "utf-8" })
2020+ .catch((_) => undefined)
2121+ .then((x) => (x === "" || x === "REFRESH_TOKEN" ? undefined : x));
2222+ if (!(userAuthCode || refreshToken))
2323+ throw new SpotifyError(
2424+ "NO_AUTH",
2525+ null,
2626+ `No auth code or refresh token.
2727+Generate an auth code at \`/src/pages/_callback\`
2828+A refresh token will be generated from this auth token.`,
2929+ );
3030+3131+ // prefer auth codes over refresh tokens
3232+ // since the auth code may have updated scopes.
3333+3434+ const accessFrom:
3535+ | {
3636+ userAuthCode: string;
3737+ }
3838+ | {
3939+ refreshToken: string;
4040+ } = userAuthCode
4141+ ? { userAuthCode }
4242+ : refreshToken
4343+ ? { refreshToken }
4444+ : (undefined as never);
4545+4646+ const req = fetch("https://accounts.spotify.com/api/token", {
4747+ method: "POST",
4848+ headers: {
4949+ "Content-Type": "application/x-www-form-urlencoded",
5050+ Authorization: `Basic ${Buffer.from(SPOTIFY_CLIENT_ID + ":" + SPOTIFY_CLIENT_SECRET).toString("base64")}`,
5151+ },
5252+ body: new URLSearchParams({
5353+ grant_type:
5454+ "userAuthCode" in accessFrom ? "authorization_code" : "refresh_token",
5555+ ...("userAuthCode" in accessFrom
5656+ ? {
5757+ code: accessFrom.userAuthCode,
5858+ redirect_uri: SPOTIFY_REDIRECT_URI,
5959+ }
6060+ : {
6161+ refresh_token: accessFrom.refreshToken,
6262+ }),
6363+ }).toString(),
6464+ });
6565+6666+ return (
6767+ req
6868+ // if res isn't 200 handle it in the catch
6969+ .then((res) => (res.ok ? res : throws(res)))
7070+ // request is 200-299
7171+ // json can throw SyntaxError in this case
7272+ .then((res) => res.json())
7373+ .then((res) => {
7474+ if ("userAuthCode" in accessFrom) {
7575+ if (isAuthToken(res)) {
7676+ return {
7777+ code: res.access_token,
7878+ refresh: res.refresh_token,
7979+ };
8080+ }
8181+ } else {
8282+ if (isRefreshToken(res)) {
8383+ return {
8484+ code: res.access_token,
8585+ refresh: res.refresh_token ?? accessFrom.refreshToken,
8686+ };
8787+ }
8888+ }
8989+ throw new SpotifyError(
9090+ "INVALID_AUTH_RES",
9191+ res,
9292+ "Could not parse access token response",
9393+ );
9494+ })
9595+ // res is now an access token and refresh token
9696+ .then((res) => {
9797+ fs.writeFile("./.refreshToken", res.refresh, { encoding: "utf-8" });
9898+ return res.code;
9999+ })
100100+ .catch((err) => {
101101+ // SyntaxError
102102+ // Response
103103+ // SpotifyError<"INVALID_AUTH_RES">
104104+ if (err instanceof Response) console.error("Request failed:", err);
105105+ else if (err instanceof SyntaxError)
106106+ console.error("Response JSON failed", err);
107107+ else if (err instanceof SpotifyError && err.code === "INVALID_AUTH_RES")
108108+ console.error("Response malformed:", err);
109109+ else {
110110+ console.error("Unhandled exception.");
111111+ throw err;
112112+ }
113113+ })
114114+ );
115115+}
+155
src/components/playing/spotify/api.ts
···11+import getAccessCode from "./access";
22+import { SpotifyError, throws } from "./errors";
33+import { isNowPlaying, type nowPlaying } from "./types";
44+55+/**
66+ * Wrapper for authorizing a spotify API with default headers etc
77+ * @param url API endpoint to call. Pass a leading slash
88+ * @returns `Response`
99+ * @throws `SpotifyError<NO_AUTH>` when auth fails
1010+ * @throws `Response` on non 200-299 status codes
1111+ */
1212+export async function getSpotifyApi(url: string) {
1313+ // get the access code
1414+ const accessToken = await getAccessCode();
1515+ // check its valid
1616+ if (!accessToken)
1717+ throw new SpotifyError(
1818+ "NO_AUTH",
1919+ null,
2020+ "Failed to get access code. try using src/pages/_callback",
2121+ );
2222+2323+ // fetch the api and throw on non 2** code
2424+ return fetch(`https://api.spotify.com/v1${url}`, {
2525+ headers: {
2626+ Authorization: `Bearer ${accessToken}`,
2727+ },
2828+ }).then((res) => (res.ok ? res : throws(res)));
2929+}
3030+/**
3131+ * Get the current playing track
3232+ * @returns `nowPlaying`
3333+ * @throws `SpotifyError` of NO_AUTH | UNHANDLED_API_ERR | INVALID_AUTH_RES | RATE_LIMITED | NO_CONTENT | MALFORMED_SPOTIFY_RES
3434+ */
3535+export async function spotifyNowPlaying() {
3636+ type success = nowPlaying["item"];
3737+ let res: (v: success) => void, rej: (v: unknown) => void;
3838+ const output = new Promise<success>((_res, _rej) => {
3939+ (res = _res), (rej = _rej);
4040+ });
4141+ const nowPlaying = getSpotifyApi("/me/player/currently-playing");
4242+4343+ // auth failed
4444+ nowPlaying.catch((err) => {
4545+ if (err instanceof SpotifyError && err.code === "NO_AUTH") {
4646+ console.error("Authentication failed:", err.human);
4747+ rej(err);
4848+ }
4949+ });
5050+5151+ /**
5252+ * request failed.
5353+ * https://developer.spotify.com/documentation/web-api/concepts/api-calls
5454+ * 400 Bad Request - The request could not be understood by the server due to malformed syntax. The message body will contain more information; see Response Schema.
5555+ * 401 Unauthorized - The request requires user authentication or, if the request included authorization credentials, authorization has been refused for those credentials.
5656+ * 403 Forbidden - The server understood the request, but is refusing to fulfill it.
5757+ * 404 Not Found - The requested resource could not be found. This error can be due to a temporary or permanent condition.
5858+ * 429 Too Many Requests - Rate limiting has been applied.
5959+ * 500 Internal Server Error. You should never receive this error because our clever coders catch them all ... but if you are unlucky enough to get one, please report it to us through a comment at the bottom of this page.
6060+ * 502 Bad Gateway - The server was acting as a gateway or proxy and received an invalid response from the upstream server.
6161+ * 503 Service Unavailable - The server is currently unable to handle the request due to a temporary condition which will be alleviated after some delay. You can choose to resend the request again.
6262+ */
6363+ nowPlaying.catch((res) => {
6464+ switch (res.status) {
6565+ // handle req error
6666+ case 400: {
6767+ rej(new SpotifyError("UNHANDLED_API_ERR", res, "400: Bad request"));
6868+ break;
6969+ }
7070+ case 401: {
7171+ rej(new SpotifyError("INVALID_AUTH_RES", res, "401: Unauthorized"));
7272+ break;
7373+ }
7474+ case 403: {
7575+ rej(new SpotifyError("UNHANDLED_API_ERR", res, "403: Forbidden"));
7676+ break;
7777+ }
7878+ case 404: {
7979+ rej(new SpotifyError("UNHANDLED_API_ERR", res, "404: Not found"));
8080+ break;
8181+ }
8282+ case 429: {
8383+ rej(new SpotifyError("RATE_LIMITED", res, "429: Rate Limited"));
8484+ break;
8585+ }
8686+ case 500: {
8787+ rej(new SpotifyError("UNHANDLED_API_ERR", res, "500: Internal Error"));
8888+ break;
8989+ }
9090+ case 502: {
9191+ rej(new SpotifyError("UNHANDLED_API_ERR", res, "502: Bad Gateway"));
9292+ break;
9393+ }
9494+ case 503: {
9595+ rej(
9696+ new SpotifyError(
9797+ "UNHANDLED_API_ERR",
9898+ res,
9999+ "503: Service Unavaliable",
100100+ ),
101101+ );
102102+ break;
103103+ }
104104+ }
105105+ });
106106+107107+ /**
108108+ * request succeeded
109109+ * https://developer.spotify.com/documentation/web-api/concepts/api-calls
110110+ * 200 OK - The request has succeeded. The client can read the result of the request in the body and the headers of the response.
111111+ * 201 Created - The request has been fulfilled and resulted in a new resource being created.
112112+ * 202 Accepted - The request has been accepted for processing, but the processing has not been completed.
113113+ * 204 No Content - The request has succeeded but returns no message body.
114114+ */
115115+ nowPlaying
116116+ .then((res) => {
117117+ if (res instanceof Error) return;
118118+ switch (res.status) {
119119+ // handle 200 codes
120120+ case 200: {
121121+ return res;
122122+ }
123123+ case 201: {
124124+ rej(new SpotifyError("UNHANDLED_API_ERR", res, "201: Created"));
125125+ return;
126126+ }
127127+ case 202: {
128128+ rej(new SpotifyError("UNHANDLED_API_ERR", res, "202: Accepted"));
129129+ return;
130130+ }
131131+ case 204: {
132132+ rej(new SpotifyError("NO_CONTENT", res, "204: No Content"));
133133+ return;
134134+ }
135135+ }
136136+ })
137137+ .then(async (resp) => {
138138+ // quit early if it rejected last time
139139+ if (!resp) return;
140140+ try {
141141+ const json = await resp.json();
142142+143143+144144+ // verify structure
145145+ if (!isNowPlaying(json)) {
146146+ rej(new SpotifyError("MALFORMED_SPOTIFY_RES", json, "Response missing required fields."));
147147+ return;
148148+ }
149149+150150+ res(json.item)
151151+ } catch (e) {}
152152+ });
153153+154154+ return output;
155155+}