Files
Aurora-SpotiRip/endpoints/spotify-session_GET.ts
T

49 lines
1.8 KiB
TypeScript
Raw Normal View History

2026-09-25 23:20:57 -05:00
import superjson from "superjson";
import { appendSetCookies, ensureSpotifyAccessToken } from "../helpers/spotifyServer";
import type { OutputType } from "./spotify-session_GET.schema";
import { isDownloadAllowed } from "../helpers/downloadJobs";
type SpotifyProfile = {
id: string;
display_name?: string;
email?: string;
product?: string;
images?: Array<{ url?: string }>;
};
export async function handle(request: Request) {
try {
const session = await ensureSpotifyAccessToken(request);
const headers = new Headers({ "Content-Type": "application/json", "Cache-Control": "no-store" });
appendSetCookies(headers, session.setCookies);
if (!session.accessToken) {
return new Response(superjson.stringify({ connected: false } satisfies OutputType), { headers });
}
const response = await fetch("https://api.spotify.com/v1/me", {
headers: { Authorization: `Bearer ${session.accessToken}` },
});
if (!response.ok) {
return new Response(superjson.stringify({ connected: false } satisfies OutputType), { headers });
}
const profile = (await response.json()) as SpotifyProfile;
const output: OutputType = {
connected: true,
accessToken: session.accessToken,
canDownload: isDownloadAllowed(profile.id),
profile: {
id: profile.id,
displayName: profile.display_name || profile.id,
email: profile.email,
imageUrl: profile.images?.find((image) => image.url)?.url,
product: profile.product,
},
};
return new Response(superjson.stringify(output), { headers });
} catch (error) {
const message = error instanceof Error ? error.message : "Unable to read Spotify session.";
return new Response(superjson.stringify({ error: message }), { status: 500 });
}
}