Fixed spotify
All checks were successful
Docker Deploy / build-and-push (push) Successful in 3m26s

This commit is contained in:
2025-06-19 23:34:44 -06:00
parent 7161584dcd
commit 41614a49a8
8 changed files with 413 additions and 282 deletions

View File

@ -1,40 +1,48 @@
import type { APIRoute } from 'astro';
import type { APIRoute } from "astro";
import {
getSpotifyCredentials,
isSpotifyConfigured,
} from "../../../utils/spotify";
export const GET: APIRoute = async () => {
try {
// Only check environment variables at runtime, not build time
const clientId = process.env.SPOTIFY_CLIENT_ID;
const clientSecret = process.env.SPOTIFY_CLIENT_SECRET;
const refreshToken = process.env.SPOTIFY_REFRESH_TOKEN;
const isConfigured = isSpotifyConfigured();
const isConfigured = !!(clientId && clientSecret && refreshToken);
if (!isConfigured) {
console.log('Spotify integration disabled - missing environment variables:', {
hasClientId: !!clientId,
hasClientSecret: !!clientSecret,
hasRefreshToken: !!refreshToken
});
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',
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',
console.error("Error checking Spotify configuration:", error);
return new Response(
JSON.stringify({
configured: false,
}),
{
status: 200,
headers: {
"Content-Type": "application/json",
},
},
});
);
}
};
};

View File

@ -1,62 +1,74 @@
import type { APIRoute } from 'astro';
import type { APIRoute } from "astro";
import { getSpotifyCredentials } from "../../../utils/spotify";
// Helper function to 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',
// 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}`)}`,
"Content-Type": "application/x-www-form-urlencoded",
Authorization: `Basic ${btoa(`${clientId}:${clientSecret}`)}`,
},
body: new URLSearchParams({
grant_type: 'refresh_token',
grant_type: "refresh_token",
refresh_token: refreshToken,
}),
});
if (!response.ok) {
throw new Error('Failed to refresh token');
throw new Error("Failed to refresh token");
}
return await response.json();
}
// Function to fetch current track from Spotify
async function fetchCurrentTrack() {
async function fetchCurrentTrack(
clientId: string,
clientSecret: string,
refreshToken: string,
accessToken?: string,
) {
try {
// Use runtime env vars instead of build-time
const clientId = process.env.SPOTIFY_CLIENT_ID;
const clientSecret = process.env.SPOTIFY_CLIENT_SECRET;
let accessToken = process.env.SPOTIFY_ACCESS_TOKEN;
const refreshToken = process.env.SPOTIFY_REFRESH_TOKEN;
if (!clientId || !clientSecret || !refreshToken) {
return null;
}
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 ${accessToken}`,
'Content-Type': 'application/json',
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);
accessToken = tokenData.access_token;
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 ${accessToken}`,
'Content-Type': 'application/json',
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);
console.error("Failed to refresh token:", refreshError);
return null;
}
}
@ -65,7 +77,7 @@ async function fetchCurrentTrack() {
// Nothing is currently playing
return {
is_playing: false,
item: null
item: null,
};
}
@ -74,118 +86,160 @@ async function fetchCurrentTrack() {
}
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
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);
console.error("Spotify API Error:", error);
return null;
}
}
export const GET: APIRoute = async ({ request }) => {
// 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;
},
cancel() {
// Client disconnected
console.log('SSE stream cancelled by client');
isClosed = true;
if (pollInterval) {
clearInterval(pollInterval);
pollInterval = null;
}
}
});
try {
// Get Spotify credentials
const credentials = getSpotifyCredentials();
// Function to send SSE message
const sendMessage = (data: any) => {
if (isClosed) {
return; // Don't try to send if stream is closed
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",
},
});
}
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');
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;
},
cancel() {
// Client disconnected
console.log("SSE stream cancelled by client");
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) {
// 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(currentTrack || { is_playing: false, item: null });
}
} catch (error) {
if (!isClosed) {
console.error("Polling error:", error);
}
}
};
// Send initial data
poll();
// Poll every 3 seconds
pollInterval = setInterval(poll, 3000);
// Clean up when client disconnects (abort signal)
request.signal.addEventListener("abort", () => {
console.log("SSE request aborted");
isClosed = true;
if (pollInterval) {
clearInterval(pollInterval);
pollInterval = null;
}
return;
}
});
try {
const currentTrack = await fetchCurrentTrack();
// Only send if data has changed and stream is still open
if (!isClosed && JSON.stringify(currentTrack) !== JSON.stringify(lastTrackData)) {
lastTrackData = currentTrack;
sendMessage(currentTrack || { is_playing: false, item: null });
}
} catch (error) {
if (!isClosed) {
console.error('Polling error:', error);
}
}
};
// Send initial data
poll();
// Poll every 3 seconds
pollInterval = setInterval(poll, 3000);
// Clean up when client disconnects (abort signal)
request.signal.addEventListener('abort', () => {
console.log('SSE request aborted');
isClosed = true;
if (pollInterval) {
clearInterval(pollInterval);
pollInterval = null;
}
});
return new Response(stream, {
headers: {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Cache-Control',
},
});
};
return new Response(stream, {
headers: {
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Cache-Control",
},
});
} 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",
},
},
);
}
};