Removed spotify... its hard to maintain and also fuck spotify
Some checks failed
Docker Deploy / build-and-push (push) Has been cancelled

This commit is contained in:
2025-06-27 15:44:43 -06:00
parent 6c2f4e1b81
commit 9dbdd265ba
10 changed files with 16 additions and 611 deletions

View File

@ -1,48 +0,0 @@
import type { APIRoute } from "astro";
import {
getSpotifyCredentials,
isSpotifyConfigured,
} from "../../../utils/spotify";
export const GET: APIRoute = async () => {
try {
const isConfigured = isSpotifyConfigured();
if (!isConfigured) {
const credentials = getSpotifyCredentials();
console.log(
"Spotify integration disabled - missing environment variables:",
{
hasClientId: !!credentials?.clientId,
hasClientSecret: !!credentials?.clientSecret,
hasRefreshToken: !!credentials?.refreshToken,
},
);
}
return new Response(
JSON.stringify({
configured: isConfigured,
}),
{
status: 200,
headers: {
"Content-Type": "application/json",
},
},
);
} catch (error) {
console.error("Error checking Spotify configuration:", error);
return new Response(
JSON.stringify({
configured: false,
}),
{
status: 200,
headers: {
"Content-Type": "application/json",
},
},
);
}
};

View File

@ -1,268 +0,0 @@
import type { APIRoute } from "astro";
import { getSpotifyCredentials } from "../../../utils/spotify";
// Refresh the access token
async function refreshSpotifyToken(
refreshToken: string,
clientId: string,
clientSecret: string,
) {
const response = await fetch("https://accounts.spotify.com/api/token", {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Basic ${btoa(`${clientId}:${clientSecret}`)}`,
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: refreshToken,
}),
});
if (!response.ok) {
throw new Error("Failed to refresh token");
}
return await response.json();
}
// Function to fetch current track from Spotify
async function fetchCurrentTrack(
clientId: string,
clientSecret: string,
refreshToken: string,
accessToken?: string,
) {
try {
let currentAccessToken = accessToken;
// Try to fetch current track with existing token
let spotifyResponse = await fetch(
"https://api.spotify.com/v1/me/player/currently-playing",
{
headers: {
Authorization: `Bearer ${currentAccessToken}`,
"Content-Type": "application/json",
},
},
);
// If token is expired (401), refresh it
if (spotifyResponse.status === 401) {
try {
const tokenData = await refreshSpotifyToken(
refreshToken,
clientId,
clientSecret,
);
currentAccessToken = tokenData.access_token;
// Retry the request with new token
spotifyResponse = await fetch(
"https://api.spotify.com/v1/me/player/currently-playing",
{
headers: {
Authorization: `Bearer ${currentAccessToken}`,
"Content-Type": "application/json",
},
},
);
} catch (refreshError) {
console.error("Failed to refresh token:", refreshError);
return null;
}
}
if (spotifyResponse.status === 204) {
// Nothing is currently playing
return {
is_playing: false,
item: null,
};
}
if (!spotifyResponse.ok) {
return null;
}
const data = await spotifyResponse.json();
return {
is_playing: data.is_playing,
item: data.item
? {
name: data.item.name,
artists: data.item.artists,
is_playing: data.is_playing,
external_urls: data.item.external_urls,
}
: null,
};
} catch (error) {
console.error("Spotify API Error:", error);
return null;
}
}
export const GET: APIRoute = async ({ request }) => {
try {
// Get Spotify credentials
const credentials = getSpotifyCredentials();
if (!credentials) {
console.log(
"Spotify SSE stream disabled - missing environment variables",
);
return new Response(JSON.stringify({ error: "Spotify not configured" }), {
status: 503,
headers: {
"Content-Type": "application/json",
},
});
}
const { clientId, clientSecret, refreshToken, accessToken } = credentials;
// Set up Server-Sent Events
const encoder = new TextEncoder();
let controller: ReadableStreamDefaultController<Uint8Array>;
let isClosed = false;
let pollInterval: NodeJS.Timeout | null = null;
const stream = new ReadableStream({
start(ctrl) {
controller = ctrl;
// Send initial data immediately to establish connection
const message = `data: ${JSON.stringify({ type: "connected", timestamp: Date.now() })}\n\n`;
controller.enqueue(encoder.encode(message));
},
cancel() {
// Client disconnected
console.log("SSE stream cancelled by client");
isClosed = true;
cleanup();
},
});
// Function to send SSE message
const sendMessage = (data: any) => {
if (isClosed) {
return; // Don't try to send if stream is closed
}
try {
const message = `data: ${JSON.stringify(data)}\n\n`;
controller.enqueue(encoder.encode(message));
} catch (error) {
if (
error instanceof TypeError &&
error.message.includes("Controller is already closed")
) {
console.log("SSE controller is closed, stopping polling");
isClosed = true;
if (pollInterval) {
clearInterval(pollInterval);
pollInterval = null;
}
} else {
console.error("Error sending SSE message:", error);
}
}
};
// Start polling and sending updates
let lastTrackData: any = null;
const poll = async () => {
if (isClosed) {
if (pollInterval) {
clearInterval(pollInterval);
pollInterval = null;
}
return;
}
try {
const currentTrack = await fetchCurrentTrack(
clientId,
clientSecret,
refreshToken,
accessToken,
);
// Only send if data has changed and stream is still open
if (
!isClosed &&
JSON.stringify(currentTrack) !== JSON.stringify(lastTrackData)
) {
lastTrackData = currentTrack;
sendMessage({
type: "track",
data: currentTrack || { is_playing: false, item: null },
timestamp: Date.now(),
});
}
} catch (error) {
if (!isClosed) {
console.error("Polling error:", error);
}
}
};
// Send initial data immediately
poll();
// Poll every 3 seconds
pollInterval = setInterval(poll, 3000);
// Send keepalive every 30 seconds to prevent connection timeout
const keepaliveInterval = setInterval(() => {
if (!isClosed) {
sendMessage({ type: "keepalive", timestamp: Date.now() });
}
}, 30000);
// Clean up keepalive interval too
const cleanup = () => {
if (pollInterval) {
clearInterval(pollInterval);
pollInterval = null;
}
if (keepaliveInterval) {
clearInterval(keepaliveInterval);
}
};
// Clean up when client disconnects (abort signal)
request.signal.addEventListener("abort", () => {
console.log("SSE request aborted");
isClosed = true;
cleanup();
});
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache, no-store, must-revalidate",
Connection: "keep-alive",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Cache-Control",
"X-Accel-Buffering": "no",
"CF-Cache-Status": "BYPASS",
"Transfer-Encoding": "chunked",
Vary: "Accept-Encoding",
},
});
} catch (error) {
console.error("Error setting up Spotify SSE stream:", error);
return new Response(
JSON.stringify({ error: "Failed to initialize stream" }),
{
status: 500,
headers: {
"Content-Type": "application/json",
},
},
);
}
};