Personal Site

Gut all files as theyre going to be mainly replace with the spotify API

vielle.dev 4abcb8a4 79e93e30

verified
+7 -472
-124
src/components/home/playing/spotify/access.ts
··· 1 - import fs from "fs/promises"; 2 - import { 3 - SPOTIFY_CLIENT_ID, 4 - SPOTIFY_CLIENT_SECRET, 5 - SPOTIFY_REDIRECT_URI, 6 - } from "astro:env/server"; 7 - import { SpotifyError } from "./errors"; 8 - import { throws } from "/utils"; 9 - import { isAuthToken, isRefreshToken } from "./types"; 10 - 11 - /** 12 - * Get an access code which can be used to authenticate requests on behalf of the user. 13 - * @param userAuthCode Authentication code for the user (via callback). Uses the stored refresh token if not provided 14 - * @returns `string`: access code to authorize requests 15 - * @returns `undefined`: failed to authenticate user. 16 - * @returns `SpotofyError<NETWORK_ERR>` when a network error occours and the fetch request fails. 17 - * @throws `SpotifyError<NO_AUTH>` when no refresh token is stored and no auth code is provided 18 - */ 19 - export default async function getAccessCode(userAuthCode?: string) { 20 - const refreshToken = await fs 21 - .readFile("./.refreshToken", { encoding: "utf-8" }) 22 - .catch((_) => undefined) 23 - .then((x) => (x === "" || x === "REFRESH_TOKEN" ? undefined : x)); 24 - if (!(userAuthCode || refreshToken)) 25 - throw new SpotifyError( 26 - "NO_AUTH", 27 - null, 28 - `No auth code or refresh token. 29 - Generate an auth code at \`/src/pages/_callback\` 30 - A refresh token will be generated from this auth token.`, 31 - ); 32 - 33 - // prefer auth codes over refresh tokens 34 - // since the auth code may have updated scopes. 35 - 36 - const accessFrom: 37 - | { 38 - userAuthCode: string; 39 - } 40 - | { 41 - refreshToken: string; 42 - } = userAuthCode 43 - ? { userAuthCode } 44 - : refreshToken 45 - ? { refreshToken } 46 - : (undefined as never); 47 - 48 - const req = fetch("https://accounts.spotify.com/api/token", { 49 - method: "POST", 50 - headers: { 51 - "Content-Type": "application/x-www-form-urlencoded", 52 - Authorization: `Basic ${Buffer.from(SPOTIFY_CLIENT_ID + ":" + SPOTIFY_CLIENT_SECRET).toString("base64")}`, 53 - }, 54 - body: new URLSearchParams({ 55 - grant_type: 56 - "userAuthCode" in accessFrom ? "authorization_code" : "refresh_token", 57 - ...("userAuthCode" in accessFrom 58 - ? { 59 - code: accessFrom.userAuthCode, 60 - redirect_uri: SPOTIFY_REDIRECT_URI, 61 - } 62 - : { 63 - refresh_token: accessFrom.refreshToken, 64 - }), 65 - }).toString(), 66 - }); 67 - 68 - return ( 69 - req 70 - // if res isn't 200 handle it in the catch 71 - .then((res) => (res.ok ? res : throws(res))) 72 - // request is 200-299 73 - // json can throw SyntaxError in this case 74 - .then((res) => res.json()) 75 - .then((res) => { 76 - if ("userAuthCode" in accessFrom) { 77 - if (isAuthToken(res)) { 78 - return { 79 - code: res.access_token, 80 - refresh: res.refresh_token, 81 - }; 82 - } 83 - } else { 84 - if (isRefreshToken(res)) { 85 - return { 86 - code: res.access_token, 87 - refresh: res.refresh_token ?? accessFrom.refreshToken, 88 - }; 89 - } 90 - } 91 - throw new SpotifyError( 92 - "INVALID_AUTH_RES", 93 - res, 94 - "Could not parse access token response", 95 - ); 96 - }) 97 - // res is now an access token and refresh token 98 - .then((res) => { 99 - fs.writeFile("./.refreshToken", res.refresh, { encoding: "utf-8" }); 100 - return res.code; 101 - }) 102 - .catch((err) => { 103 - // SyntaxError 104 - // Response 105 - // SpotifyError<"INVALID_AUTH_RES"> 106 - if (err instanceof Response) console.error("access.ts", "Request failed:", err); 107 - else if (err instanceof SyntaxError) 108 - console.error("access.ts", "Response JSON failed", err); 109 - else if (err instanceof SpotifyError && err.code === "INVALID_AUTH_RES") 110 - console.error("access.ts", "Response malformed:", err); 111 - else if (err instanceof TypeError) { 112 - console.error("access.ts", "A network error occurred.", err); 113 - return new SpotifyError( 114 - "NETWORK_ERR", 115 - err, 116 - "Network error occurred. Could not reach spotify servers or something else.", 117 - ); 118 - } else { 119 - console.error("access.ts", "Unhandled exception."); 120 - throw err; 121 - } 122 - }) 123 - ); 124 - }
···
-185
src/components/home/playing/spotify/api.ts
··· 1 - import getAccessCode from "./access"; 2 - import { SpotifyError } from "./errors"; 3 - import { isNowPlaying, type nowPlaying } from "./types"; 4 - import { isObj, throws } from "/utils"; 5 - 6 - /** 7 - * Wrapper for authorizing a spotify API with default headers etc 8 - * @param url API endpoint to call. Pass a leading slash 9 - * @returns `Response` 10 - * @throws `SpotifyError<NETWORK_ERR>` when a fetch request fails 11 - * @throws `SpotifyError<NO_AUTH>` when auth fails 12 - * @throws `Response` on non 200-299 status codes 13 - */ 14 - export async function getSpotifyApi(url: string) { 15 - // get the access code 16 - const accessToken = await getAccessCode(); 17 - // check its valid 18 - if (!accessToken) 19 - throw new SpotifyError( 20 - "NO_AUTH", 21 - null, 22 - "Failed to get access code. try using src/pages/_callback", 23 - ); 24 - 25 - if (accessToken instanceof SpotifyError) throw accessToken; 26 - 27 - // fetch the api and throw on non 2** code 28 - return fetch(`https://api.spotify.com/v1${url}`, { 29 - headers: { 30 - Authorization: `Bearer ${accessToken}`, 31 - }, 32 - }) 33 - .catch((err) => 34 - err instanceof TypeError 35 - ? throws( 36 - new SpotifyError("NETWORK_ERR", err, "Spotify API request failed"), 37 - ) 38 - : throws(err), 39 - ) 40 - .then((res) => (res.ok ? res : throws(res))); 41 - } 42 - /** 43 - * Get the current playing track 44 - * @returns `nowPlaying` 45 - * @throws `SpotifyError` of NO_AUTH | UNHANDLED_API_ERR | INVALID_AUTH_RES | RATE_LIMITED | NO_CONTENT | MALFORMED_SPOTIFY_RES | NETWORK_ERR 46 - */ 47 - export async function spotifyNowPlaying() { 48 - type success = nowPlaying; 49 - let res: (v: success) => void, rej: (v: unknown) => void; 50 - const output = new Promise<success>((_res, _rej) => { 51 - ((res = _res), (rej = _rej)); 52 - }); 53 - const nowPlaying = getSpotifyApi("/me/player/currently-playing"); 54 - 55 - // auth failed 56 - nowPlaying.catch((err) => { 57 - if (err instanceof SpotifyError && err.code === "NO_AUTH") { 58 - console.error("api.ts", "Authentication failed:", err.human); 59 - rej(err); 60 - } else if (err instanceof SpotifyError && err.code === "NETWORK_ERR") { 61 - console.error("api.ts", "Network request failed:", err.human); 62 - rej(err) 63 - } 64 - }); 65 - 66 - /** 67 - * request failed. 68 - * https://developer.spotify.com/documentation/web-api/concepts/api-calls 69 - * 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. 70 - * 401 Unauthorized - The request requires user authentication or, if the request included authorization credentials, authorization has been refused for those credentials. 71 - * 403 Forbidden - The server understood the request, but is refusing to fulfill it. 72 - * 404 Not Found - The requested resource could not be found. This error can be due to a temporary or permanent condition. 73 - * 429 Too Many Requests - Rate limiting has been applied. 74 - * 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. 75 - * 502 Bad Gateway - The server was acting as a gateway or proxy and received an invalid response from the upstream server. 76 - * 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. 77 - */ 78 - nowPlaying.catch((res) => { 79 - switch (res.status) { 80 - // handle req error 81 - case 400: { 82 - rej(new SpotifyError("UNHANDLED_API_ERR", res, "400: Bad request")); 83 - break; 84 - } 85 - case 401: { 86 - rej(new SpotifyError("INVALID_AUTH_RES", res, "401: Unauthorized")); 87 - break; 88 - } 89 - case 403: { 90 - rej(new SpotifyError("UNHANDLED_API_ERR", res, "403: Forbidden")); 91 - break; 92 - } 93 - case 404: { 94 - rej(new SpotifyError("UNHANDLED_API_ERR", res, "404: Not found")); 95 - break; 96 - } 97 - case 429: { 98 - rej(new SpotifyError("RATE_LIMITED", res, "429: Rate Limited")); 99 - break; 100 - } 101 - case 500: { 102 - rej(new SpotifyError("UNHANDLED_API_ERR", res, "500: Internal Error")); 103 - break; 104 - } 105 - case 502: { 106 - rej(new SpotifyError("UNHANDLED_API_ERR", res, "502: Bad Gateway")); 107 - break; 108 - } 109 - case 503: { 110 - rej( 111 - new SpotifyError( 112 - "UNHANDLED_API_ERR", 113 - res, 114 - "503: Service Unavaliable", 115 - ), 116 - ); 117 - break; 118 - } 119 - } 120 - }); 121 - 122 - /** 123 - * request succeeded 124 - * https://developer.spotify.com/documentation/web-api/concepts/api-calls 125 - * 200 OK - The request has succeeded. The client can read the result of the request in the body and the headers of the response. 126 - * 201 Created - The request has been fulfilled and resulted in a new resource being created. 127 - * 202 Accepted - The request has been accepted for processing, but the processing has not been completed. 128 - * 204 No Content - The request has succeeded but returns no message body. 129 - */ 130 - nowPlaying 131 - .then((res) => { 132 - if (res instanceof Error) return; 133 - switch (res.status) { 134 - // handle 200 codes 135 - case 200: { 136 - return res; 137 - } 138 - case 201: { 139 - rej(new SpotifyError("UNHANDLED_API_ERR", res, "201: Created")); 140 - return; 141 - } 142 - case 202: { 143 - rej(new SpotifyError("UNHANDLED_API_ERR", res, "202: Accepted")); 144 - return; 145 - } 146 - case 204: { 147 - rej(new SpotifyError("NO_CONTENT", res, "204: No Content")); 148 - return; 149 - } 150 - } 151 - }) 152 - .then(async (resp) => { 153 - // quit early if it rejected last time 154 - if (!resp) return; 155 - try { 156 - const json = await resp 157 - .json() 158 - .then((res) => 159 - isObj(res) && "item" in res && isObj(res.item) 160 - ? res.item 161 - : throws("Item field missing"), 162 - ); 163 - 164 - // verify structure 165 - if (!isNowPlaying(json)) { 166 - rej( 167 - new SpotifyError( 168 - "MALFORMED_SPOTIFY_RES", 169 - json, 170 - "Response missing required fields.", 171 - ), 172 - ); 173 - return; 174 - } 175 - 176 - res(json); 177 - } catch (e) { 178 - rej( 179 - new SpotifyError("MALFORMED_SPOTIFY_RES", e, "Could not parse JSON."), 180 - ); 181 - } 182 - }); 183 - 184 - return output; 185 - }
···
+3 -2
src/components/home/playing/spotify/client.ts
··· 1 - export * from "./types"; 2 - export * from "./errors";
··· 1 + /** 2 + * types & type guards for front end logic when received from now-playing-sse 3 + */
-52
src/components/home/playing/spotify/errors.ts
··· 1 - import { isObj } from "/utils"; 2 - 3 - export const spotErrs = [ 4 - "NO_AUTH", 5 - "INVALID_AUTH_RES", 6 - "UNHANDLED_API_ERR", 7 - "RATE_LIMITED", 8 - "NO_CONTENT", 9 - "MALFORMED_SPOTIFY_RES", 10 - "NETWORK_ERR" 11 - ] as const; 12 - 13 - export class SpotifyError { 14 - code: (typeof spotErrs)[number]; 15 - details: unknown; 16 - human: string; 17 - 18 - constructor(code: SpotifyError["code"], details: unknown, human: string); 19 - constructor(error: SpotifyErrorInit); 20 - constructor( 21 - code: SpotifyError["code"] | SpotifyErrorInit, 22 - details?: unknown, 23 - human?: string, 24 - ) { 25 - if (typeof code === "string") { 26 - this.code = code; 27 - this.details = details; 28 - this.human = human ?? code; 29 - return; 30 - } 31 - 32 - this.code = code.code; 33 - this.details = code.details; 34 - this.human = code.human ?? code.code; 35 - } 36 - } 37 - 38 - export interface SpotifyErrorInit { 39 - code: SpotifyError["code"]; 40 - details: unknown; 41 - human?: string; 42 - } 43 - 44 - export const isSpotifyError = ( 45 - err: unknown, 46 - ): err is SpotifyError | SpotifyErrorInit => 47 - isObj(err) && 48 - "code" in err && 49 - typeof err.code === "string" && 50 - spotErrs.reduce((acc, cur) => acc || cur === err.code, false) && 51 - "details" in err && 52 - ("human" in err ? typeof err.human === "string" : true);
···
+4 -5
src/components/home/playing/spotify/index.ts
··· 1 - import getAccessCode from "./access"; 2 - export { getAccessCode }; 3 - export * from "./errors"; 4 - export * from "./api"; 5 - export * from "./types";
··· 1 + /** 2 + * types and logic for getting now playing information 3 + */ 4 +
-104
src/components/home/playing/spotify/types.ts
··· 1 - import { isObj, type Prettify } from "/utils"; 2 - 3 - export type AuthToken = { 4 - access_token: string; 5 - token_type: "Bearer"; 6 - scope: string; 7 - expires_in: number; 8 - refresh_token: string; 9 - }; 10 - 11 - export type RefreshToken = Prettify< 12 - Omit<AuthToken, "refresh_token"> & { refresh_token?: string } 13 - >; 14 - 15 - export function isRefreshToken(obj: unknown): obj is RefreshToken { 16 - return ( 17 - // validate is object 18 - typeof obj === "object" && 19 - obj !== null && 20 - // validate properties 21 - "access_token" in obj && 22 - typeof obj.access_token === "string" && 23 - "token_type" in obj && 24 - obj.token_type === "Bearer" && 25 - "scope" in obj && 26 - typeof obj.scope === "string" && 27 - "expires_in" in obj && 28 - typeof obj.expires_in === "number" && 29 - // either refresh token exists as string or not at all 30 - (("refresh_token" in obj && typeof obj.refresh_token === "string") || 31 - !("refresh_token" in obj)) 32 - ); 33 - } 34 - 35 - // auth token is just refresh with a non optional refresh_token 36 - export function isAuthToken(obj: unknown): obj is AuthToken { 37 - return isRefreshToken(obj) && "refresh_token" in obj; 38 - } 39 - 40 - type externalUrls = { 41 - spotify: string; 42 - }; 43 - 44 - const isExternalUrl = (obj: unknown): obj is externalUrls => 45 - isObj(obj) && "spotify" in obj && typeof obj.spotify === "string"; 46 - 47 - export type nowPlaying = null | { 48 - type: "track"; 49 - name: string; 50 - id: string; 51 - 52 - external_urls: externalUrls; 53 - 54 - album: { 55 - external_urls: externalUrls; 56 - name: string; 57 - images: { 58 - url: string; 59 - }[]; 60 - }; 61 - artists: { 62 - external_urls: externalUrls; 63 - name: string; 64 - }[]; 65 - }; 66 - 67 - export function isNowPlaying(obj: unknown): obj is nowPlaying { 68 - return ( 69 - obj === null || 70 - (isObj(obj) && 71 - "type" in obj && 72 - obj.type === "track" && 73 - "name" in obj && 74 - typeof obj.name === "string" && 75 - "id" in obj && 76 - typeof obj.id === "string" && 77 - "external_urls" in obj && 78 - isExternalUrl(obj.external_urls) && 79 - "album" in obj && 80 - isObj(obj.album) && 81 - "external_urls" in obj.album && 82 - isExternalUrl(obj.album.external_urls) && 83 - "name" in obj.album && 84 - typeof obj.album.name === "string" && 85 - "images" in obj.album && 86 - Array.isArray(obj.album.images) && 87 - obj.album.images.reduce( 88 - (acc, curr) => 89 - acc && isObj(curr) && "url" in curr && typeof curr.url === "string", 90 - true, 91 - ) && 92 - "artists" in obj && 93 - Array.isArray(obj.artists) && 94 - obj.artists.reduce( 95 - (acc, curr) => 96 - acc && 97 - "external_urls" in curr && 98 - isExternalUrl(curr.external_urls) && 99 - "name" in curr && 100 - typeof curr.name === "string", 101 - true, 102 - )) 103 - ); 104 - }
···