feat: transformation en application Radyobòkaz Player (WIP sécurisé)

Fork de la librairie headless svelte-podcast transformé en lecteur :
radio Funkwhale mizik.o-k-i.net (~2000 titres), page démo RSS Syntax.fm,
file de lecture, préférences et progression persistées.

État avant refonte playbook OKI (bugs connus : volume inerte,
bouton démo RSS cassé en navigation client, cibles tactiles mobiles).
This commit is contained in:
sucupira
2026-07-21 17:54:36 -04:00
parent b1165a817e
commit 72f4d2e160
82 changed files with 1226 additions and 2330 deletions
+79
View File
@@ -0,0 +1,79 @@
/**
* Minimal client for the Funkwhale API of mizik.o-k-i.net,
* restricted to the public radio "Radyobòkaz" (id 7).
*/
import type { PlayableTrack } from './playable';
export const FUNKWHALE_BASE = 'https://mizik.o-k-i.net';
export const RADIO_ID = 7;
export const RADIO_PAGE_SIZE = 50; // max allowed by the API
/** A track from the radio, ready to be played. */
export interface RadioTrack extends PlayableTrack {
id: number;
}
interface ApiImage {
urls: {
original: string | null;
medium_square_crop: string | null;
};
}
interface ApiTrack {
id: number;
title: string;
listen_url: string;
artist: { name: string };
album: { title: string; cover: ApiImage | null } | null;
uploads: { duration: number | null }[];
}
interface ApiPage {
count: number;
next: string | null;
results: ApiTrack[];
}
function to_radio_track(track: ApiTrack): RadioTrack {
const cover = track.album?.cover?.urls;
return {
id: track.id,
title: track.title,
artist: track.artist.name,
album: track.album?.title ?? null,
cover: cover?.medium_square_crop ?? cover?.original ?? null,
stream_url: `${FUNKWHALE_BASE}${track.listen_url}`,
duration: track.uploads[0]?.duration ?? null,
};
}
/**
* Fetches one page of the radio's track list.
* @param page - 1-based page number
*/
export async function fetch_radio_page(
page: number,
): Promise<{ count: number; tracks: RadioTrack[] }> {
const url = `${FUNKWHALE_BASE}/api/v1/radios/radios/${RADIO_ID}/tracks/?page=${page}&page_size=${RADIO_PAGE_SIZE}`;
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Funkwhale API error: ${response.status}`);
}
const data: ApiPage = await response.json();
return { count: data.count, tracks: data.results.map(to_radio_track) };
}
/**
* Shuffles an array in place (FisherYates) and returns it.
*/
export function shuffle<T>(array: T[]): T[] {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temporary = array[i] as T;
array[i] = array[j] as T;
array[j] = temporary;
}
return array;
}
+93
View File
@@ -0,0 +1,93 @@
import { get, writable } from 'svelte/store';
import {
fetch_radio_page,
RADIO_PAGE_SIZE,
type RadioTrack,
} from './funkwhale';
import { radio_player } from './radio-store';
/**
* State of the browsable library (all tracks of the radio).
*/
export interface LibraryState {
tracks: RadioTrack[];
/** Total number of tracks on the radio (known after the first page). */
total: number | null;
loaded_pages: number;
total_pages: number | null;
is_loading: boolean;
is_done: boolean;
error: string | null;
}
const initial_state: LibraryState = {
tracks: [],
total: null,
loaded_pages: 0,
total_pages: null,
is_loading: false,
is_done: false,
error: null,
};
export const library = writable<LibraryState>(initial_state);
/**
* Loads every page of the radio's track list, one after another.
* Idempotent: does nothing if already loading or fully loaded.
*/
export async function load_library(): Promise<void> {
const state = get(library);
if (state.is_loading || state.is_done) return;
library.set({ ...state, is_loading: true, error: null });
try {
// First page: tells us how many tracks / pages exist.
const first = await fetch_radio_page(1);
const total_pages = Math.ceil(first.count / RADIO_PAGE_SIZE);
library.set({
tracks: first.tracks,
total: first.count,
loaded_pages: 1,
total_pages,
is_loading: true,
is_done: total_pages <= 1,
error: null,
});
// Load remaining pages in small parallel batches.
const CONCURRENCY = 4;
for (let start = 2; start <= total_pages; start += CONCURRENCY) {
// Pause while playback is loading a track: streaming and
// playback-related requests have priority over the library.
while (get(radio_player).is_loading) {
await new Promise((resolve) => setTimeout(resolve, 300));
}
const pages = await Promise.all(
Array.from(
{ length: Math.min(CONCURRENCY, total_pages - start + 1) },
(_, i) => fetch_radio_page(start + i),
),
);
library.update((prev) => ({
...prev,
tracks: [...prev.tracks, ...pages.flatMap((p) => p.tracks)],
loaded_pages: Math.min(start + CONCURRENCY - 1, total_pages),
}));
}
library.update((prev) => ({
...prev,
is_loading: false,
is_done: true,
}));
} catch (error) {
library.update((prev) => ({
...prev,
is_loading: false,
error: error instanceof Error ? error.message : String(error),
}));
}
}
+16
View File
@@ -0,0 +1,16 @@
/**
* A track that can be queued in the player, regardless of its source
* (Funkwhale radio, podcast episode…).
*/
export interface PlayableTrack {
id: string | number;
title: string;
artist: string;
album: string | null;
/** URL of the artwork, if any. */
cover: string | null;
/** Absolute URL of the audio stream. */
stream_url: string;
/** Duration in seconds, if known. */
duration: number | null;
}
+159
View File
@@ -0,0 +1,159 @@
<script lang="ts">
import BackwardIcon from '@inqling/svelte-icons/heroicon-24-solid/backward.svelte';
import ForwardIcon from '@inqling/svelte-icons/heroicon-24-solid/forward.svelte';
import MusicalNoteIcon from '@inqling/svelte-icons/heroicon-24-solid/musical-note.svelte';
import PauseIcon from '@inqling/svelte-icons/heroicon-24-solid/pause.svelte';
import PlayIcon from '@inqling/svelte-icons/heroicon-24-solid/play.svelte';
import SpeakerWaveIcon from '@inqling/svelte-icons/heroicon-24-solid/speaker-wave.svelte';
import SpeakerXMarkIcon from '@inqling/svelte-icons/heroicon-24-solid/speaker-x-mark.svelte';
import { AudioPlayer, user_preferences } from '$lib/index';
import { radio_player } from './radio-store';
let is_muted = false;
$: current = $radio_player.current;
</script>
<AudioPlayer let:PlayerProgress let:play let:mute let:attributes>
<div class="rounded-2xl bg-slate-900 p-4 text-slate-200 shadow-xl">
<div class="flex flex-col gap-4 sm:flex-row sm:items-center">
<!-- Cover -->
<div
class="h-24 w-24 shrink-0 overflow-hidden rounded-xl bg-slate-700"
>
{#if current?.cover}
<img
src={current.cover}
alt="Pochette de {current.album ?? current.title}"
class="h-full w-full object-cover"
/>
{:else}
<div
class="grid h-full w-full place-content-center text-slate-500"
>
<MusicalNoteIcon class="h-10 w-10" />
</div>
{/if}
</div>
<!-- Track info -->
<div class="min-w-0 flex-1">
{#if current}
<p class="truncate text-lg font-semibold text-white">
{current.title}
</p>
<p class="truncate text-sm text-slate-400">
{current.artist}
{#if current.album}· {current.album}{/if}
</p>
{#if $radio_player.mode === 'radio'}
<p
class="mt-1 text-xs uppercase tracking-wider text-orange-400"
>
Mode radio aléatoire
</p>
{/if}
{:else}
<p class="text-lg font-semibold text-slate-400">
Aucun titre en cours
</p>
<p class="text-sm text-slate-500">
Lance la radio ou choisis un titre dans la liste.
</p>
{/if}
</div>
<!-- Controls -->
<div class="flex items-center gap-2">
<button
type="button"
on:click={() => radio_player.previous()}
disabled={!current}
class="rounded-full p-2 hover:bg-slate-700 disabled:opacity-30"
aria-label="Titre précédent"
>
<BackwardIcon class="h-6 w-6" />
</button>
<button
type="button"
on:click={() => play('toggle')}
disabled={!attributes.is_loaded}
class="rounded-full bg-orange-500 p-3 text-white hover:bg-orange-400 disabled:opacity-30"
aria-label={attributes.is_paused ? 'Lecture' : 'Pause'}
>
{#if attributes.is_paused}
<PlayIcon class="h-7 w-7" />
{:else}
<PauseIcon class="h-7 w-7" />
{/if}
</button>
<button
type="button"
on:click={() => radio_player.next()}
disabled={!current || $radio_player.is_loading}
class="rounded-full p-2 hover:bg-slate-700 disabled:opacity-30"
aria-label="Titre suivant"
>
<ForwardIcon class="h-6 w-6" />
</button>
<button
type="button"
on:click={() => {
mute('toggle');
is_muted = !is_muted;
}}
class="rounded-full p-2 hover:bg-slate-700"
aria-label="Activer / couper le son"
>
{#if is_muted || $user_preferences.volume === 0}
<SpeakerXMarkIcon class="h-5 w-5" />
{:else}
<SpeakerWaveIcon class="h-5 w-5" />
{/if}
</button>
<input
type="range"
min="0"
max="1"
step="0.05"
value={$user_preferences.volume}
on:input={(e) =>
user_preferences.set_volume(e.currentTarget.valueAsNumber)}
class="h-1 w-20 accent-orange-500"
aria-label="Volume"
/>
</div>
</div>
<!-- Progress -->
<div
class="mt-4 flex items-center gap-3 text-xs tabular-nums text-slate-400"
>
<span>{attributes.timestamp_current}</span>
<div class="flex-1">
<PlayerProgress />
</div>
<span>{attributes.timestamp_end}</span>
</div>
</div>
</AudioPlayer>
<style lang="postcss">
/* Theme the svelte-podcast progress bar */
:global(:root) {
--progress-bg: rgb(51, 65, 85);
--progress-fg: rgb(249, 115, 22);
--progress-border: rgb(51, 65, 85);
--progress-active-bg: rgb(71, 85, 105);
--progress-active-fg: rgb(251, 146, 60);
--progress-active-border: rgb(249, 115, 22);
--progress-radius: 4px;
--progress-thumb-width: 3px;
--progress-height: 10px;
}
</style>
+197
View File
@@ -0,0 +1,197 @@
import { BROWSER } from 'esm-env';
import { get, writable } from 'svelte/store';
import { audio } from '$lib/actions';
import { audio_element } from '$lib/_internal_/audio-element';
import { fetch_radio_page, RADIO_PAGE_SIZE, shuffle } from './funkwhale';
import type { PlayableTrack } from './playable';
export type PlayMode = 'radio' | 'list';
/**
* State of the playback queue.
*/
export interface RadioPlayerState {
/** 'radio' = endless shuffle, 'list' = play tracks from the library. */
mode: PlayMode;
queue: PlayableTrack[];
index: number;
current: PlayableTrack | null;
is_loading: boolean;
}
const initial_state: RadioPlayerState = {
mode: 'list',
queue: [],
index: -1,
current: null,
is_loading: false,
};
const state = writable<RadioPlayerState>(initial_state);
/**
* Loads a track into the audio element and starts playback.
* If the track was previously played to its end, restarts from 0
* (svelte-podcast restores the saved position otherwise).
*/
function load_and_play(track: PlayableTrack): void {
audio.src.load(track.stream_url, {
title: track.title,
artist: track.artist,
album: track.album,
artwork: track.cover,
});
const element = get(audio_element);
if (element) {
element.addEventListener(
'loadedmetadata',
() => {
if (
Number.isFinite(element.duration) &&
element.currentTime > element.duration - 5
) {
element.currentTime = 0;
}
},
{ once: true },
);
}
audio.play(true);
}
function play_at(index: number): void {
const current_state = get(state);
const track = current_state.queue[index];
if (!track) return;
state.set({ ...current_state, index, current: track });
load_and_play(track);
}
/** Fetches a random page of the radio, shuffled. */
async function fetch_random_queue(): Promise<PlayableTrack[]> {
// Page 1 is cheap and tells us the total number of pages.
const { count } = await fetch_radio_page(1);
const total_pages = Math.max(1, Math.ceil(count / RADIO_PAGE_SIZE));
const page = 1 + Math.floor(Math.random() * total_pages);
const { tracks } = await fetch_radio_page(page);
return shuffle(tracks);
}
export const radio_player = {
subscribe: state.subscribe,
/**
* Starts radio mode: an endless shuffled queue of random tracks.
*/
async start_radio(): Promise<void> {
const current_state = get(state);
if (current_state.is_loading) return;
state.set({ ...current_state, mode: 'radio', is_loading: true });
try {
const queue = await fetch_random_queue();
const first_track = queue[0];
if (!first_track) throw new Error('La radio ne contient aucun titre');
state.set({
mode: 'radio',
queue,
index: 0,
current: first_track,
is_loading: false,
});
load_and_play(first_track);
} catch (error) {
console.error(error);
state.set({ ...get(state), is_loading: false });
}
},
/**
* Plays a list of tracks (e.g. from the library) starting at index.
*/
play_tracks(tracks: PlayableTrack[], index: number): void {
const track = tracks[index];
if (!track) return;
state.set({
mode: 'list',
queue: tracks,
index,
current: track,
is_loading: false,
});
load_and_play(track);
},
/**
* Skips to the next track. In radio mode, fetches a new random
* page when the queue is exhausted. In list mode, stops at the end.
*/
async next(): Promise<void> {
const current_state = get(state);
if (current_state.is_loading) return;
if (current_state.index + 1 < current_state.queue.length) {
play_at(current_state.index + 1);
} else if (current_state.mode === 'radio') {
state.set({ ...current_state, is_loading: true });
try {
const queue = await fetch_random_queue();
const first_track = queue[0];
if (!first_track) {
state.set({ ...get(state), is_loading: false });
return;
}
state.set({
mode: 'radio',
queue,
index: 0,
current: first_track,
is_loading: false,
});
load_and_play(first_track);
} catch (error) {
console.error(error);
state.set({ ...get(state), is_loading: false });
}
}
},
/**
* Goes back to the previous track, or restarts the current one
* if it has been playing for more than 5 seconds.
*/
previous(): void {
const current_state = get(state);
const element = get(audio_element);
if (element && element.currentTime > 5) {
audio.seek_to(0);
return;
}
if (current_state.index > 0) {
play_at(current_state.index - 1);
} else {
audio.seek_to(0);
}
},
};
// Automatically play the next track when the current one ends.
if (BROWSER) {
let attached: HTMLAudioElement | null = null;
const handle_ended = () => {
void radio_player.next();
};
audio_element.subscribe((element) => {
if (attached) attached.removeEventListener('ended', handle_ended);
attached = element;
if (element) element.addEventListener('ended', handle_ended);
});
}
+140
View File
@@ -0,0 +1,140 @@
<script lang="ts">
import MagnifyingGlassIcon from '@inqling/svelte-icons/heroicon-24-solid/magnifying-glass.svelte';
import MusicalNoteIcon from '@inqling/svelte-icons/heroicon-24-solid/musical-note.svelte';
import PlayIcon from '@inqling/svelte-icons/heroicon-24-solid/play.svelte';
import { format_seconds } from '$lib/index';
import { onMount } from 'svelte';
import type { RadioTrack } from './funkwhale';
import { library, load_library } from './library-store';
import { radio_player } from './radio-store';
/** Maximum number of rows rendered at once. */
const MAX_ROWS = 200;
let search = '';
onMount(() => {
void load_library();
});
function matches(track: RadioTrack, query: string): boolean {
const haystack = `${track.title} ${track.artist} ${
track.album ?? ''
}`.toLowerCase();
return query
.toLowerCase()
.split(/\s+/)
.filter(Boolean)
.every((word) => haystack.includes(word));
}
$: filtered = search.trim()
? $library.tracks.filter((track) => matches(track, search))
: $library.tracks;
$: visible = filtered.slice(0, MAX_ROWS);
function play_track(track: RadioTrack) {
const index = filtered.indexOf(track);
radio_player.play_tracks(filtered, index);
}
</script>
<section>
<div class="mb-4 flex flex-wrap items-center gap-4">
<h2 class="text-xl font-bold text-slate-900">Titres de la radio</h2>
<div class="min-w-60 relative flex-1">
<div
class="pointer-events-none absolute inset-y-0 left-3 flex items-center text-slate-400"
>
<MagnifyingGlassIcon class="h-5 w-5" />
</div>
<input
type="search"
bind:value={search}
placeholder="Rechercher un titre, un artiste, un album…"
class="w-full rounded-lg border-slate-300 pl-10 text-sm focus:border-orange-500 focus:ring-orange-500"
/>
</div>
<p class="text-sm tabular-nums text-slate-500">
{#if $library.is_done}
{$library.total} titres
{:else if $library.total}
{$library.tracks.length} / {$library.total} titres chargés…
{:else}
Chargement…
{/if}
</p>
</div>
{#if $library.error}
<p class="rounded-lg bg-red-50 p-4 text-sm text-red-700">
Erreur de chargement : {$library.error}
</p>
{:else}
<ul
class="divide-y divide-slate-200 rounded-xl border border-slate-200 bg-white"
>
{#each visible as track (track.id)}
{@const is_current = $radio_player.current?.id === track.id}
<li>
<button
type="button"
on:click={() => play_track(track)}
class="flex w-full items-center gap-3 px-3 py-2 text-left hover:bg-orange-50"
class:bg-orange-100={is_current}
>
<span
class="grid h-8 w-8 shrink-0 place-content-center rounded-full text-slate-400"
class:bg-orange-500={is_current}
class:text-white={is_current}
>
{#if is_current}
<MusicalNoteIcon class="h-4 w-4" />
{:else}
<PlayIcon class="h-4 w-4" />
{/if}
</span>
<span class="min-w-0 flex-1">
<span
class="block truncate text-sm font-medium text-slate-900"
>
{track.title}
</span>
<span class="block truncate text-xs text-slate-500">
{track.artist}
{#if track.album}· {track.album}{/if}
</span>
</span>
{#if track.duration}
<span class="shrink-0 text-xs tabular-nums text-slate-400">
{format_seconds.to_timestamp(track.duration)}
</span>
{/if}
</button>
</li>
{:else}
<li class="px-4 py-8 text-center text-sm text-slate-500">
{#if $library.is_loading}
Chargement des titres…
{:else if search.trim()}
Aucun titre ne correspond à « {search} ».
{:else}
Aucun titre.
{/if}
</li>
{/each}
</ul>
{#if filtered.length > visible.length}
<p class="mt-2 text-center text-sm text-slate-500">
… et {filtered.length - visible.length} autres titres. Précise ta recherche
pour les trouver.
</p>
{/if}
{/if}
</section>