diff --git a/.env.example b/.env.example
new file mode 100644
index 0000000..8c8dfed
--- /dev/null
+++ b/.env.example
@@ -0,0 +1,4 @@
+SPOTIFY_CLIENT_ID=your_client_id_here
+SPOTIFY_CLIENT_SECRET=your_client_secret_here
+SPOTIFY_ACCESS_TOKEN=BQA...
+SPOTIFY_REFRESH_TOKEN=AQA...
\ No newline at end of file
diff --git a/astro.config.mjs b/astro.config.mjs
index d0b3fd6..2a57602 100644
--- a/astro.config.mjs
+++ b/astro.config.mjs
@@ -26,6 +26,7 @@ export default defineConfig({
integrations: [preact(), mdx(), icon({
include: {
mdi: ["clock", "tag", "arrow-right", "link", "email", "rss", "download", "web", "arrow-left"],
+ "simple-icons": ["spotify", "gitea", "bluesky", "react", "typescript", "astro", "go", "postgresql", "redis", "docker", "github", "linkedin"],
},
}),
],
diff --git a/docker-compose.yml b/docker-compose.yml
index 438bdf1..f85fef5 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -5,4 +5,8 @@ services:
- "${APP_PORT}:4321"
environment:
NODE_ENV: production
+ SPOTIFY_CLIENT_ID: ${SPOTIFY_CLIENT_ID}
+ SPOTIFY_CLIENT_SECRET: ${SPOTIFY_CLIENT_SECRET}
+ SPOTIFY_REFRESH_TOKEN: ${SPOTIFY_REFRESH_TOKEN}
+ SPOTIFY_ACCESS_TOKEN: ${SPOTIFY_ACCESS_TOKEN}
restart: unless-stopped
diff --git a/package.json b/package.json
index 8085b59..94aecd9 100644
--- a/package.json
+++ b/package.json
@@ -25,7 +25,7 @@
},
"devDependencies": {
"@iconify-json/mdi": "^1.2.3",
- "@iconify-json/simple-icons": "^1.2.36",
+ "@iconify-json/simple-icons": "^1.2.37",
"daisyui": "^5.0.43"
},
"pnpm": {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 0fe05c0..7d5848d 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -52,8 +52,8 @@ importers:
specifier: ^1.2.3
version: 1.2.3
'@iconify-json/simple-icons':
- specifier: ^1.2.36
- version: 1.2.36
+ specifier: ^1.2.37
+ version: 1.2.37
daisyui:
specifier: ^5.0.43
version: 5.0.43
@@ -111,16 +111,16 @@ packages:
resolution: {integrity: sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==}
engines: {node: '>=6.9.0'}
- '@babel/compat-data@7.27.3':
- resolution: {integrity: sha512-V42wFfx1ymFte+ecf6iXghnnP8kWTO+ZLXIyZq+1LAXHHvTZdVxicn4yiVYdYMGaCO3tmqub11AorKkv+iodqw==}
+ '@babel/compat-data@7.27.5':
+ resolution: {integrity: sha512-KiRAp/VoJaWkkte84TvUd9qjdbZAdiqyvMxrGl1N6vzFogKmaLgoM3L1kgtLicp2HP5fBJS8JrZKLVIZGVJAVg==}
engines: {node: '>=6.9.0'}
'@babel/core@7.27.4':
resolution: {integrity: sha512-bXYxrXFubeYdvB0NhD/NBB3Qi6aZeV20GOWVI47t2dkecCEoneR4NPVcb7abpXDEvejgrUfFtG6vG/zxAKmg+g==}
engines: {node: '>=6.9.0'}
- '@babel/generator@7.27.3':
- resolution: {integrity: sha512-xnlJYj5zepml8NXtjkG0WquFUv8RskFqyFcVgTBp5k+NaA/8uw/K+OSVf8AMGw5e9HKP2ETd5xpK5MLZQD6b4Q==}
+ '@babel/generator@7.27.5':
+ resolution: {integrity: sha512-ZGhA37l0e/g2s1Cnzdix0O3aLYm66eF8aufiVteOgnwxgnRP8GoyMj7VWsgWnQbVKXyge7hqrFh2K2TQM6t1Hw==}
engines: {node: '>=6.9.0'}
'@babel/helper-annotate-as-pure@7.27.3':
@@ -161,8 +161,8 @@ packages:
resolution: {integrity: sha512-Y+bO6U+I7ZKaM5G5rDUZiYfUvQPUibYmAFe7EnKdnKBbVXDZxvp+MWOH5gYciY0EPk4EScsuFMQBbEfpdRKSCQ==}
engines: {node: '>=6.9.0'}
- '@babel/parser@7.27.4':
- resolution: {integrity: sha512-BRmLHGwpUqLFR2jzx9orBuX/ABDkj2jLKOXrHDTN2aOKL+jFDDKaRNo9nyYsIl9h/UE/7lMKdDjKQQyxKKDZ7g==}
+ '@babel/parser@7.27.5':
+ resolution: {integrity: sha512-OsQd175SxWkGlzbny8J3K8TnnDD0N3lrIUtB92xwyRpzaenGZhxDvxN/JgU00U3CDZNj9tPuDJ5H0WS4Nt3vKg==}
engines: {node: '>=6.0.0'}
hasBin: true
@@ -355,8 +355,8 @@ packages:
'@iconify-json/mdi@1.2.3':
resolution: {integrity: sha512-O3cLwbDOK7NNDf2ihaQOH5F9JglnulNDFV7WprU2dSoZu3h3cWH//h74uQAB87brHmvFVxIOkuBX2sZSzYhScg==}
- '@iconify-json/simple-icons@1.2.36':
- resolution: {integrity: sha512-ZMpVdoW/7hhbt2aHVSvudjH8eSVNNjKkAAjwAQHgiuPUiIfbvNakVin+H9uhUz4N9TbDT/nanzV/4Slb+6dDXw==}
+ '@iconify-json/simple-icons@1.2.37':
+ resolution: {integrity: sha512-jZwTBznpYVDYKWyAuRpepPpCiHScVrX6f8WRX8ReX6pdii99LYVHwJywKcH2excWQrWmBomC9nkxGlEKzXZ/wQ==}
'@iconify/tools@4.1.2':
resolution: {integrity: sha512-q6NzLQYEN9zkDfcyBqD3vItHcZw97w/s++3H3TBxUORr57EfHxj6tOW6fyufDjMq+Vl56WXWaPx1csBPYlI5CA==}
@@ -1251,8 +1251,8 @@ packages:
ee-first@1.1.1:
resolution: {integrity: sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==}
- electron-to-chromium@1.5.161:
- resolution: {integrity: sha512-hwtetwfKNZo/UlwHIVBlKZVdy7o8bIZxxKs0Mv/ROPiQQQmDgdm5a+KvKtBsxM8ZjFzTaCeLoodZ8jiBE3o9rA==}
+ electron-to-chromium@1.5.162:
+ resolution: {integrity: sha512-hQA+Zb5QQwoSaXJWEAGEw1zhk//O7qDzib05Z4qTqZfNju/FAkrm5ZInp0JbTp4Z18A6bilopdZWEYrFSsfllA==}
emoji-regex@10.4.0:
resolution: {integrity: sha512-EC+0oUMY1Rqm4O6LLrgjtYDvcVYTy7chDnM4Q7030tP4Kwj3u/pR6gP9ygnp2CJMK5Gq+9Q2oqmrFJAz01DXjw==}
@@ -2620,8 +2620,8 @@ packages:
typescript: ^4.9.4 || ^5.0.2
zod: ^3
- zod@3.25.42:
- resolution: {integrity: sha512-PcALTLskaucbeHc41tU/xfjfhcz8z0GdhhDcSgrCTmSazUuqnYqiXO63M0QUBVwpBlsLsNVn5qHSC5Dw3KZvaQ==}
+ zod@3.25.49:
+ resolution: {integrity: sha512-JMMPMy9ZBk3XFEdbM3iL1brx4NUSejd6xr3ELrrGEfGb355gjhiAWtG3K5o+AViV/3ZfkIrCzXsZn6SbLwTR8Q==}
zwitch@2.0.4:
resolution: {integrity: sha512-bXE4cR/kVZhKZX/RjPEflHaKVhUVl85noU3v6b8apfQEc1x4A+zBxjZ4lN8LqGd6WZ3dl98pY4o717VFmoPp+A==}
@@ -2747,17 +2747,17 @@ snapshots:
js-tokens: 4.0.0
picocolors: 1.1.1
- '@babel/compat-data@7.27.3': {}
+ '@babel/compat-data@7.27.5': {}
'@babel/core@7.27.4':
dependencies:
'@ampproject/remapping': 2.3.0
'@babel/code-frame': 7.27.1
- '@babel/generator': 7.27.3
+ '@babel/generator': 7.27.5
'@babel/helper-compilation-targets': 7.27.2
'@babel/helper-module-transforms': 7.27.3(@babel/core@7.27.4)
'@babel/helpers': 7.27.4
- '@babel/parser': 7.27.4
+ '@babel/parser': 7.27.5
'@babel/template': 7.27.2
'@babel/traverse': 7.27.4
'@babel/types': 7.27.3
@@ -2769,9 +2769,9 @@ snapshots:
transitivePeerDependencies:
- supports-color
- '@babel/generator@7.27.3':
+ '@babel/generator@7.27.5':
dependencies:
- '@babel/parser': 7.27.4
+ '@babel/parser': 7.27.5
'@babel/types': 7.27.3
'@jridgewell/gen-mapping': 0.3.8
'@jridgewell/trace-mapping': 0.3.25
@@ -2783,7 +2783,7 @@ snapshots:
'@babel/helper-compilation-targets@7.27.2':
dependencies:
- '@babel/compat-data': 7.27.3
+ '@babel/compat-data': 7.27.5
'@babel/helper-validator-option': 7.27.1
browserslist: 4.25.0
lru-cache: 5.1.1
@@ -2818,7 +2818,7 @@ snapshots:
'@babel/template': 7.27.2
'@babel/types': 7.27.3
- '@babel/parser@7.27.4':
+ '@babel/parser@7.27.5':
dependencies:
'@babel/types': 7.27.3
@@ -2848,14 +2848,14 @@ snapshots:
'@babel/template@7.27.2':
dependencies:
'@babel/code-frame': 7.27.1
- '@babel/parser': 7.27.4
+ '@babel/parser': 7.27.5
'@babel/types': 7.27.3
'@babel/traverse@7.27.4':
dependencies:
'@babel/code-frame': 7.27.1
- '@babel/generator': 7.27.3
- '@babel/parser': 7.27.4
+ '@babel/generator': 7.27.5
+ '@babel/parser': 7.27.5
'@babel/template': 7.27.2
'@babel/types': 7.27.3
debug: 4.4.1
@@ -2960,7 +2960,7 @@ snapshots:
dependencies:
'@iconify/types': 2.0.0
- '@iconify-json/simple-icons@1.2.36':
+ '@iconify-json/simple-icons@1.2.37':
dependencies:
'@iconify/types': 2.0.0
@@ -3587,9 +3587,9 @@ snapshots:
xxhash-wasm: 1.1.0
yargs-parser: 21.1.1
yocto-spinner: 0.2.3
- zod: 3.25.42
- zod-to-json-schema: 3.24.5(zod@3.25.42)
- zod-to-ts: 1.2.0(typescript@5.8.3)(zod@3.25.42)
+ zod: 3.25.49
+ zod-to-json-schema: 3.24.5(zod@3.25.49)
+ zod-to-ts: 1.2.0(typescript@5.8.3)(zod@3.25.49)
optionalDependencies:
sharp: 0.33.5
transitivePeerDependencies:
@@ -3671,7 +3671,7 @@ snapshots:
browserslist@4.25.0:
dependencies:
caniuse-lite: 1.0.30001720
- electron-to-chromium: 1.5.161
+ electron-to-chromium: 1.5.162
node-releases: 2.0.19
update-browserslist-db: 1.1.3(browserslist@4.25.0)
@@ -3882,7 +3882,7 @@ snapshots:
ee-first@1.1.1: {}
- electron-to-chromium@1.5.161: {}
+ electron-to-chromium@1.5.162: {}
emoji-regex@10.4.0: {}
@@ -4425,7 +4425,7 @@ snapshots:
magicast@0.3.5:
dependencies:
- '@babel/parser': 7.27.4
+ '@babel/parser': 7.27.5
'@babel/types': 7.27.3
source-map-js: 1.2.1
@@ -5666,15 +5666,15 @@ snapshots:
yoctocolors@2.1.1: {}
- zod-to-json-schema@3.24.5(zod@3.25.42):
+ zod-to-json-schema@3.24.5(zod@3.25.49):
dependencies:
- zod: 3.25.42
+ zod: 3.25.49
- zod-to-ts@1.2.0(typescript@5.8.3)(zod@3.25.42):
+ zod-to-ts@1.2.0(typescript@5.8.3)(zod@3.25.49):
dependencies:
typescript: 5.8.3
- zod: 3.25.42
+ zod: 3.25.49
- zod@3.25.42: {}
+ zod@3.25.49: {}
zwitch@2.0.4: {}
diff --git a/src/components/SocialLinks.astro b/src/components/SocialLinks.astro
index a1e3d3c..cc2137f 100644
--- a/src/components/SocialLinks.astro
+++ b/src/components/SocialLinks.astro
@@ -1,5 +1,6 @@
---
import { Icon } from 'astro-icon/components';
+import SpotifyIcon from './SpotifyIcon';
---
@@ -38,4 +39,6 @@ import { Icon } from 'astro-icon/components';
>
+
+
diff --git a/src/components/SpotifyIcon.tsx b/src/components/SpotifyIcon.tsx
new file mode 100644
index 0000000..2a6a9fa
--- /dev/null
+++ b/src/components/SpotifyIcon.tsx
@@ -0,0 +1,157 @@
+import { useSignal } from "@preact/signals";
+import { useEffect } from "preact/hooks";
+
+interface SpotifyTrack {
+ name: string;
+ artists: { name: string }[];
+ is_playing: boolean;
+ external_urls?: {
+ spotify: string;
+ };
+}
+
+interface SpotifyResponse {
+ is_playing: boolean;
+ item: SpotifyTrack;
+}
+
+interface SpotifyIconProps {
+ profileUrl?: string;
+}
+
+// Spotify SVG icon component
+const SpotifySVG = ({ className }: { className?: string }) => (
+
+);
+
+export default function SpotifyIcon({ profileUrl = "https://open.spotify.com" }: SpotifyIconProps) {
+ const currentTrack = useSignal(null);
+ const isPlaying = useSignal(false);
+
+ useEffect(() => {
+ // Set up Server-Sent Events connection
+ const eventSource = new EventSource('/api/spotify/stream');
+
+ eventSource.onopen = () => {
+ console.log('Spotify SSE connected');
+ };
+
+ eventSource.onmessage = (event) => {
+ try {
+ const data: SpotifyResponse = JSON.parse(event.data);
+
+ if (data.is_playing && data.item) {
+ currentTrack.value = data.item;
+ isPlaying.value = data.is_playing;
+ } else {
+ currentTrack.value = null;
+ isPlaying.value = false;
+ }
+ } catch (err) {
+ console.error('Error parsing SSE data:', err);
+ // Fail silently
+ }
+ };
+
+ eventSource.onerror = (event) => {
+ console.error('Spotify SSE error:', event);
+
+ // Fallback to polling if SSE fails
+ if (eventSource.readyState === EventSource.CLOSED) {
+ console.log('SSE connection closed, falling back to polling');
+ startPolling();
+ }
+ };
+
+ // Cleanup on unmount
+ return () => {
+ eventSource.close();
+ };
+ }, []);
+
+ // Fallback polling function if SSE fails
+ const startPolling = () => {
+ const fetchCurrentTrack = async () => {
+ try {
+ const response = await fetch('/api/spotify/current', {
+ credentials: 'include'
+ });
+
+ if (!response.ok) {
+ throw new Error('Failed to fetch Spotify data');
+ }
+
+ const data: SpotifyResponse = await response.json();
+
+ if (data.is_playing && data.item) {
+ currentTrack.value = data.item;
+ isPlaying.value = data.is_playing;
+ } else {
+ currentTrack.value = null;
+ isPlaying.value = false;
+ }
+ } catch (err) {
+ // Fail silently
+ }
+ };
+
+ // Fetch immediately
+ fetchCurrentTrack();
+
+ // Then fetch every 10 seconds (fallback polling)
+ const interval = setInterval(fetchCurrentTrack, 10000);
+
+ return () => clearInterval(interval);
+ };
+
+ const getTooltipText = () => {
+ if (currentTrack.value && isPlaying.value) {
+ const artists = currentTrack.value.artists.map(artist => artist.name).join(', ');
+ return `♪ ${currentTrack.value.name} by ${artists} (click to open in Spotify)`;
+ }
+ return "Spotify";
+ };
+
+ const getSpotifyUrl = () => {
+ // If we have a current track with external URL, use that
+ if (currentTrack.value && isPlaying.value && currentTrack.value.external_urls?.spotify) {
+ return currentTrack.value.external_urls.spotify;
+ }
+ // Otherwise, use the provided profile URL or fallback to general Spotify
+ return profileUrl;
+ };
+
+ return (
+
+ );
+}
\ No newline at end of file
diff --git a/src/pages/api/spotify/current.ts b/src/pages/api/spotify/current.ts
new file mode 100644
index 0000000..98f2067
--- /dev/null
+++ b/src/pages/api/spotify/current.ts
@@ -0,0 +1,117 @@
+import type { APIRoute } from 'astro';
+
+// 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',
+ 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();
+}
+
+export const GET: APIRoute = async ({ request }) => {
+ try {
+ const clientId = import.meta.env.SPOTIFY_CLIENT_ID;
+ const clientSecret = import.meta.env.SPOTIFY_CLIENT_SECRET;
+ let accessToken = import.meta.env.SPOTIFY_ACCESS_TOKEN;
+ const refreshToken = import.meta.env.SPOTIFY_REFRESH_TOKEN;
+
+ if (!clientId || !clientSecret || !refreshToken) {
+ throw new Error('Missing Spotify credentials. Make sure SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, and SPOTIFY_REFRESH_TOKEN are set.');
+ }
+
+ // 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',
+ },
+ });
+
+ // If token is expired (401), refresh it
+ if (spotifyResponse.status === 401) {
+ console.log('Access token expired, refreshing...');
+
+ try {
+ const tokenData = await refreshSpotifyToken(refreshToken, clientId, clientSecret);
+ accessToken = tokenData.access_token;
+
+ // Note: In a real app, you'd want to save this new token somewhere
+ // For now, it will work until the next restart
+ console.log('Token refreshed successfully');
+
+ // 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',
+ },
+ });
+ } catch (refreshError) {
+ console.error('Failed to refresh token:', refreshError);
+ throw new Error('Token refresh failed');
+ }
+ }
+
+ if (spotifyResponse.status === 204) {
+ // Nothing is currently playing
+ return new Response(JSON.stringify({
+ is_playing: false,
+ item: null
+ }), {
+ status: 200,
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+ }
+
+ if (!spotifyResponse.ok) {
+ throw new Error(`Spotify API returned ${spotifyResponse.status}`);
+ }
+
+ const data = await spotifyResponse.json();
+
+ return new Response(JSON.stringify({
+ 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
+ }), {
+ status: 200,
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+
+ } catch (error) {
+ console.error('Spotify API Error:', error);
+
+ // Return a fallback response
+ return new Response(JSON.stringify({
+ is_playing: false,
+ item: null,
+ error: 'Unable to fetch Spotify data'
+ }), {
+ status: 200, // Return 200 to avoid client-side errors
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ });
+ }
+};
\ No newline at end of file
diff --git a/src/pages/api/spotify/stream.ts b/src/pages/api/spotify/stream.ts
new file mode 100644
index 0000000..0c3c097
--- /dev/null
+++ b/src/pages/api/spotify/stream.ts
@@ -0,0 +1,190 @@
+import type { APIRoute } from 'astro';
+
+// 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',
+ 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() {
+ try {
+ const clientId = import.meta.env.SPOTIFY_CLIENT_ID;
+ const clientSecret = import.meta.env.SPOTIFY_CLIENT_SECRET;
+ let accessToken = import.meta.env.SPOTIFY_ACCESS_TOKEN;
+ const refreshToken = import.meta.env.SPOTIFY_REFRESH_TOKEN;
+
+ if (!clientId || !clientSecret || !refreshToken) {
+ return null;
+ }
+
+ // 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',
+ },
+ });
+
+ // If token is expired (401), refresh it
+ if (spotifyResponse.status === 401) {
+ try {
+ const tokenData = await refreshSpotifyToken(refreshToken, clientId, clientSecret);
+ accessToken = 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',
+ },
+ });
+ } 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 }) => {
+ // Set up Server-Sent Events
+ const encoder = new TextEncoder();
+ let controller: ReadableStreamDefaultController;
+ 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;
+ }
+ }
+ });
+
+ // 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();
+
+ // 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',
+ },
+ });
+};
\ No newline at end of file