Web player missing features #3

Merged
NotS1mp merged 2 commits from web-player-missing-features into master 2026-09-23 17:07:09 +00:00
11 changed files with 200 additions and 23 deletions
Showing only changes of commit a7929c0ac9 - Show all commits
+4
View File
@@ -381,6 +381,10 @@ services:
environment: environment:
NODE_ENV: production NODE_ENV: production
PORT: 3000 PORT: 3000
# adapter-node rejects request bodies over 512K by default; audio
# uploads are posted to /upload. Keep in line with the edge's
# client_max_body_size.
BODY_SIZE_LIMIT: 1G
ORIGIN: ${PUBLIC_WEB_URL} ORIGIN: ${PUBLIC_WEB_URL}
ZITADEL_ISSUER: ${PUBLIC_AUTH_URL} ZITADEL_ISSUER: ${PUBLIC_AUTH_URL}
ZITADEL_CLIENT_ID: ${WEB_CLIENT_ID} ZITADEL_CLIENT_ID: ${WEB_CLIENT_ID}
+6 -9
View File
@@ -1,15 +1,16 @@
import type { Handle } from '@sveltejs/kit'; import type { Handle } from '@sveltejs/kit';
import { import {
clearSessionCookie,
decodeSession, decodeSession,
encodeSession, encodeSession,
readSessionCookie,
refreshSession, refreshSession,
sessionCookieOptions, writeSessionCookie
SESSION_COOKIE
} from '$lib/server/auth'; } from '$lib/server/auth';
import { authConfig } from '$lib/server/config'; import { authConfig } from '$lib/server/config';
export const handle: Handle = async ({ event, resolve }) => { export const handle: Handle = async ({ event, resolve }) => {
let session = await decodeSession(event.cookies.get(SESSION_COOKIE)); let session = await decodeSession(readSessionCookie(event.cookies));
if ( if (
session && session &&
@@ -17,13 +18,9 @@ export const handle: Handle = async ({ event, resolve }) => {
) { ) {
session = await refreshSession(session); session = await refreshSession(session);
if (session) { if (session) {
event.cookies.set( writeSessionCookie(event.cookies, await encodeSession(session), event.url);
SESSION_COOKIE,
await encodeSession(session),
sessionCookieOptions(event.url)
);
} else { } else {
event.cookies.delete(SESSION_COOKIE, { path: '/' }); clearSessionCookie(event.cookies);
} }
} }
+2
View File
@@ -714,7 +714,9 @@ export interface components {
pictureIntentId: string; pictureIntentId: string;
audioIntentId: string; audioIntentId: string;
tags: components["schemas"]["Genre"][];
}; };
Genre: "Pop" | "Rock" | "HipHop" | "RnB" | "Jazz" | "Blues" | "Classical" | "Electronic" | "House" | "Techno" | "Trance" | "Dubstep" | "DrumAndBass" | "Metal" | "Punk" | "Reggae" | "Reggaeton" | "Country" | "Folk" | "Indie" | "KPop" | "Latin" | "Soul" | "Funk" | "Ambient" | "Lofi";
CreateUserRequest: { CreateUserRequest: {
id: number | string; id: number | string;
@@ -3,20 +3,21 @@
interface Props { interface Props {
selected?: boolean; selected?: boolean;
disabled?: boolean;
count?: number; count?: number;
href?: string; href?: string;
onclick?: () => void; onclick?: () => void;
children: Snippet; children: Snippet;
} }
let { selected = false, count, href, onclick, children }: Props = $props(); let { selected = false, disabled = false, count, href, onclick, children }: Props = $props();
const classes = $derived( const classes = $derived(
href href
? 'rounded-full border border-line-strong px-3.5 py-2 text-xs text-fg-2 transition-colors hover:bg-hover hover:text-fg' ? 'rounded-full border border-line-strong px-3.5 py-2 text-xs text-fg-2 transition-colors hover:bg-hover hover:text-fg'
: `flex items-center gap-2 rounded-full px-3.5 py-2 text-xs font-medium transition ${ : `flex items-center gap-2 rounded-full px-3.5 py-2 text-xs font-medium transition ${
selected ? 'bg-cta-strong text-ink' : 'bg-btn text-fg-2 hover:bg-btn-hover hover:text-fg' selected ? 'bg-cta-strong text-ink' : 'bg-btn text-fg-2 hover:bg-btn-hover hover:text-fg'
}` } ${disabled ? 'cursor-not-allowed opacity-40' : ''}`
); );
</script> </script>
@@ -30,5 +31,5 @@
{#if href} {#if href}
<a {href} class={classes}>{@render content()}</a> <a {href} class={classes}>{@render content()}</a>
{:else} {:else}
<button type="button" {onclick} class={classes}>{@render content()}</button> <button type="button" {onclick} {disabled} class={classes}>{@render content()}</button>
{/if} {/if}
+56
View File
@@ -0,0 +1,56 @@
export const TRACK_GENRES = [
{ value: 'Pop', label: 'Pop' },
{ value: 'Rock', label: 'Rock' },
{ value: 'HipHop', label: 'Hip-hop' },
{ value: 'RnB', label: 'R&B' },
{ value: 'Jazz', label: 'Jazz' },
{ value: 'Blues', label: 'Blues' },
{ value: 'Classical', label: 'Clásica' },
{ value: 'Electronic', label: 'Electrónica' },
{ value: 'House', label: 'House' },
{ value: 'Techno', label: 'Techno' },
{ value: 'Trance', label: 'Trance' },
{ value: 'Dubstep', label: 'Dubstep' },
{ value: 'DrumAndBass', label: 'Drum and bass' },
{ value: 'Metal', label: 'Metal' },
{ value: 'Punk', label: 'Punk' },
{ value: 'Reggae', label: 'Reggae' },
{ value: 'Reggaeton', label: 'Reggaetón' },
{ value: 'Country', label: 'Country' },
{ value: 'Folk', label: 'Folk' },
{ value: 'Indie', label: 'Indie' },
{ value: 'KPop', label: 'K-pop' },
{ value: 'Latin', label: 'Latina' },
{ value: 'Soul', label: 'Soul' },
{ value: 'Funk', label: 'Funk' },
{ value: 'Ambient', label: 'Ambient' },
{ value: 'Lofi', label: 'Lo-fi' }
] as const;
export type TrackGenre = (typeof TRACK_GENRES)[number]['value'];
const GENRE_VALUES: ReadonlySet<string> = new Set(TRACK_GENRES.map((genre) => genre.value));
const INTENSE: ReadonlySet<TrackGenre> = new Set(['Metal', 'Punk', 'Dubstep', 'DrumAndBass']);
const MELLOW: ReadonlySet<TrackGenre> = new Set(['Classical', 'Ambient', 'Lofi']);
export function isTrackGenre(value: string): value is TrackGenre {
return GENRE_VALUES.has(value);
}
export function areCompatible(a: TrackGenre, b: TrackGenre): boolean {
return !((INTENSE.has(a) && MELLOW.has(b)) || (INTENSE.has(b) && MELLOW.has(a)));
}
export function genreLabel(value: TrackGenre): string {
return TRACK_GENRES.find((genre) => genre.value === value)?.label ?? value;
}
export function findConflict(tags: readonly TrackGenre[]): [TrackGenre, TrackGenre] | undefined {
for (let i = 0; i < tags.length; i++) {
for (let j = i + 1; j < tags.length; j++) {
if (!areCompatible(tags[i], tags[j])) return [tags[i], tags[j]];
}
}
return undefined;
}
+20 -2
View File
@@ -52,9 +52,27 @@ export function unwrapOrError<T>(
return result.data; return result.data;
} }
export function apiErrorDetail(error: unknown): string | undefined {
if (typeof error !== 'object' || error === null) return undefined;
const { errors, detail, title } = error as {
errors?: Record<string, unknown>;
detail?: unknown;
title?: unknown;
};
if (errors && typeof errors === 'object') {
const messages = Object.values(errors)
.flat()
.filter((entry): entry is string => typeof entry === 'string');
if (messages.length > 0) return messages.join(' ');
}
if (typeof detail === 'string' && detail !== '') return detail;
if (typeof title === 'string' && title !== '') return title;
return undefined;
}
export function unwrapOrFail( export function unwrapOrFail(
result: { error?: unknown }, result: { error?: unknown },
message: string message: string
): ActionFailure<{ message: string }> | undefined { ): ActionFailure<{ message: string; detail?: string }> | undefined {
return result.error ? fail(502, { message }) : undefined; return result.error ? fail(502, { message, detail: apiErrorDetail(result.error) }) : undefined;
} }
+39
View File
@@ -1,3 +1,4 @@
import type { Cookies } from '@sveltejs/kit';
import * as client from 'openid-client'; import * as client from 'openid-client';
import { EncryptJWT, jwtDecrypt } from 'jose'; import { EncryptJWT, jwtDecrypt } from 'jose';
import { dev } from '$app/environment'; import { dev } from '$app/environment';
@@ -53,6 +54,44 @@ export function sessionCookieOptions(url: URL) {
}; };
} }
const SESSION_CHUNK_SIZE = 3600;
function sessionChunkName(index: number): string {
return index === 0 ? SESSION_COOKIE : `${SESSION_COOKIE}.${index}`;
}
export function readSessionCookie(cookies: Cookies): string | undefined {
const parts: string[] = [];
for (let index = 0; ; index++) {
const part = cookies.get(sessionChunkName(index));
if (part === undefined) break;
parts.push(part);
}
return parts.length > 0 ? parts.join('') : undefined;
}
export function clearSessionCookie(cookies: Cookies, keep = 0): void {
for (const { name } of cookies.getAll()) {
const match =
name === SESSION_COOKIE
? 0
: name.startsWith(`${SESSION_COOKIE}.`)
? Number(name.slice(SESSION_COOKIE.length + 1))
: -1;
if (Number.isInteger(match) && match >= keep) cookies.delete(name, { path: '/' });
}
}
export function writeSessionCookie(cookies: Cookies, token: string, url: URL): void {
const options = sessionCookieOptions(url);
const count = Math.ceil(token.length / SESSION_CHUNK_SIZE);
for (let index = 0; index < count; index++) {
const chunk = token.slice(index * SESSION_CHUNK_SIZE, (index + 1) * SESSION_CHUNK_SIZE);
cookies.set(sessionChunkName(index), chunk, options);
}
clearSessionCookie(cookies, count);
}
export async function encodeSession(session: Session): Promise<string> { export async function encodeSession(session: Session): Promise<string> {
const now = Math.floor(Date.now() / 1000); const now = Math.floor(Date.now() / 1000);
return new EncryptJWT({ ...session }) return new EncryptJWT({ ...session })
@@ -7,6 +7,7 @@ import {
unwrapOrFail unwrapOrFail
} from '$lib/server/api'; } from '$lib/server/api';
import { putPresigned, extOf, contentTypeOf, AUDIO_TYPES, IMAGE_TYPES } from '$lib/server/upload'; import { putPresigned, extOf, contentTypeOf, AUDIO_TYPES, IMAGE_TYPES } from '$lib/server/upload';
import { findConflict, genreLabel, isTrackGenre, type TrackGenre } from '$lib/data/trackGenres';
const MAX_TITLE = 100; const MAX_TITLE = 100;
@@ -23,6 +24,7 @@ export const actions: Actions = {
const title = String(form.get('title') ?? '').trim(); const title = String(form.get('title') ?? '').trim();
const audio = form.get('audio'); const audio = form.get('audio');
const cover = form.get('cover'); const cover = form.get('cover');
const rawTags = form.getAll('tags').map(String);
if (title === '' || title.length > MAX_TITLE) { if (title === '' || title.length > MAX_TITLE) {
return fail(400, { message: 'El título es obligatorio (máx. 100 caracteres).' }); return fail(400, { message: 'El título es obligatorio (máx. 100 caracteres).' });
@@ -34,6 +36,20 @@ export const actions: Actions = {
return fail(400, { message: 'Selecciona una portada.' }); return fail(400, { message: 'Selecciona una portada.' });
} }
if (rawTags.length === 0) {
return fail(400, { message: 'Elige al menos un género.' });
}
if (!rawTags.every(isTrackGenre)) {
return fail(400, { message: 'Alguno de los géneros no es válido.' });
}
const tags: TrackGenre[] = [...new Set(rawTags)];
const conflict = findConflict(tags);
if (conflict) {
return fail(400, {
message: `Los géneros ${genreLabel(conflict[0])} y ${genreLabel(conflict[1])} no se pueden combinar.`
});
}
const audioContentType = contentTypeOf(audio, AUDIO_TYPES); const audioContentType = contentTypeOf(audio, AUDIO_TYPES);
const pictureContentType = contentTypeOf(cover, IMAGE_TYPES); const pictureContentType = contentTypeOf(cover, IMAGE_TYPES);
const api = createApiClient({ fetch, accessToken }); const api = createApiClient({ fetch, accessToken });
@@ -73,7 +89,8 @@ export const actions: Actions = {
body: { body: {
title, title,
pictureIntentId: urls.pictureIntentId, pictureIntentId: urls.pictureIntentId,
audioIntentId: urls.audioIntentId audioIntentId: urls.audioIntentId,
tags
} }
}); });
@@ -13,6 +13,8 @@
import Input from '$lib/components/ui/primitives/Input.svelte'; import Input from '$lib/components/ui/primitives/Input.svelte';
import Checkbox from '$lib/components/ui/primitives/Checkbox.svelte'; import Checkbox from '$lib/components/ui/primitives/Checkbox.svelte';
import Button from '$lib/components/ui/primitives/Button.svelte'; import Button from '$lib/components/ui/primitives/Button.svelte';
import Chip from '$lib/components/ui/primitives/Chip.svelte';
import { TRACK_GENRES, areCompatible, type TrackGenre } from '$lib/data/trackGenres';
type Status = 'idle' | 'uploading' | 'done' | 'error'; type Status = 'idle' | 'uploading' | 'done' | 'error';
type StepState = 'idle' | 'active' | 'done'; type StepState = 'idle' | 'active' | 'done';
@@ -28,6 +30,8 @@
let status = $state<Status>('idle'); let status = $state<Status>('idle');
let acceptedTerms = $state(false); let acceptedTerms = $state(false);
let errorMsg = $state(''); let errorMsg = $state('');
let errorDetail = $state('');
let tags = $state<TrackGenre[]>([]);
let publishedTitle = $state(''); let publishedTitle = $state('');
let audioInput = $state<HTMLInputElement>(); let audioInput = $state<HTMLInputElement>();
@@ -40,7 +44,7 @@
const busy = $derived(status === 'uploading'); const busy = $derived(status === 'uploading');
const canPublish = $derived( const canPublish = $derived(
title.trim() !== '' && audioName !== '' && hasCover && acceptedTerms && !busy title.trim() !== '' && audioName !== '' && hasCover && tags.length > 0 && acceptedTerms && !busy
); );
const stepStates = $derived.by<StepState[]>(() => { const stepStates = $derived.by<StepState[]>(() => {
@@ -81,6 +85,14 @@
pickAudio(file); pickAudio(file);
} }
function toggleTag(tag: TrackGenre) {
tags = tags.includes(tag) ? tags.filter((current) => current !== tag) : [...tags, tag];
}
function tagBlocked(tag: TrackGenre) {
return !tags.includes(tag) && tags.some((current) => !areCompatible(current, tag));
}
function reset() { function reset() {
title = ''; title = '';
audioName = ''; audioName = '';
@@ -90,6 +102,8 @@
status = 'idle'; status = 'idle';
acceptedTerms = false; acceptedTerms = false;
errorMsg = ''; errorMsg = '';
errorDetail = '';
tags = [];
} }
</script> </script>
@@ -153,6 +167,7 @@
use:enhance={() => { use:enhance={() => {
status = 'uploading'; status = 'uploading';
errorMsg = ''; errorMsg = '';
errorDetail = '';
return async ({ result }) => { return async ({ result }) => {
if (result.type === 'success') { if (result.type === 'success') {
publishedTitle = title; publishedTitle = title;
@@ -160,6 +175,7 @@
} else if (result.type === 'failure') { } else if (result.type === 'failure') {
status = 'error'; status = 'error';
errorMsg = (result.data?.message as string) ?? 'No se pudo subir la canción.'; errorMsg = (result.data?.message as string) ?? 'No se pudo subir la canción.';
errorDetail = (result.data?.detail as string | undefined) ?? '';
} else { } else {
status = 'error'; status = 'error';
errorMsg = 'Error inesperado durante la subida.'; errorMsg = 'Error inesperado durante la subida.';
@@ -236,6 +252,26 @@
</Field> </Field>
</div> </div>
<Field label="Géneros">
<div class="flex flex-wrap gap-2">
{#each TRACK_GENRES as genre (genre.value)}
<Chip
selected={tags.includes(genre.value)}
disabled={tagBlocked(genre.value)}
onclick={() => toggleTag(genre.value)}
>
{genre.label}
</Chip>
{/each}
</div>
{#each tags as tag (tag)}
<input type="hidden" name="tags" value={tag} />
{/each}
{#snippet hint()}
<p>Elige al menos uno. Algunos géneros no se pueden combinar, como Metal con Ambient.</p>
{/snippet}
</Field>
<Checkbox bind:checked={acceptedTerms}> <Checkbox bind:checked={acceptedTerms}>
Acepto los Acepto los
<a <a
@@ -260,7 +296,10 @@
{/if} {/if}
{#if status === 'error'} {#if status === 'error'}
<Alert tone="danger">{errorMsg}</Alert> <Alert tone="danger">
{errorMsg}
{#if errorDetail}<span class="mt-1 block text-xs opacity-80">{errorDetail}</span>{/if}
</Alert>
{/if} {/if}
<div class="flex flex-col-reverse gap-3 sm:flex-row sm:items-center sm:justify-end sm:gap-4"> <div class="flex flex-col-reverse gap-3 sm:flex-row sm:items-center sm:justify-end sm:gap-4">
@@ -4,10 +4,9 @@ import type { RequestHandler } from './$types';
import { import {
getOidcConfig, getOidcConfig,
encodeSession, encodeSession,
sessionCookieOptions,
toSessionUser, toSessionUser,
writeSessionCookie,
type Session, type Session,
SESSION_COOKIE,
STATE_COOKIE, STATE_COOKIE,
VERIFIER_COOKIE, VERIFIER_COOKIE,
NONCE_COOKIE, NONCE_COOKIE,
@@ -55,7 +54,7 @@ export const GET: RequestHandler = async ({ url, cookies }) => {
expiresAt: Math.floor(Date.now() / 1000) + (tokens.expires_in ?? 3600) expiresAt: Math.floor(Date.now() / 1000) + (tokens.expires_in ?? 3600)
}; };
cookies.set(SESSION_COOKIE, await encodeSession(session), sessionCookieOptions(url)); writeSessionCookie(cookies, await encodeSession(session), url);
for (const name of [STATE_COOKIE, VERIFIER_COOKIE, NONCE_COOKIE, RETURN_COOKIE]) { for (const name of [STATE_COOKIE, VERIFIER_COOKIE, NONCE_COOKIE, RETURN_COOKIE]) {
cookies.delete(name, { path: '/' }); cookies.delete(name, { path: '/' });
+8 -3
View File
@@ -1,12 +1,17 @@
import { redirect } from '@sveltejs/kit'; import { redirect } from '@sveltejs/kit';
import * as client from 'openid-client'; import * as client from 'openid-client';
import type { RequestHandler } from './$types'; import type { RequestHandler } from './$types';
import { getOidcConfig, decodeSession, SESSION_COOKIE } from '$lib/server/auth'; import {
clearSessionCookie,
decodeSession,
getOidcConfig,
readSessionCookie
} from '$lib/server/auth';
import { authConfig } from '$lib/server/config'; import { authConfig } from '$lib/server/config';
const handleLogout: RequestHandler = async ({ cookies }) => { const handleLogout: RequestHandler = async ({ cookies }) => {
const session = await decodeSession(cookies.get(SESSION_COOKIE)); const session = await decodeSession(readSessionCookie(cookies));
cookies.delete(SESSION_COOKIE, { path: '/' }); clearSessionCookie(cookies);
const config = await getOidcConfig(); const config = await getOidcConfig();
const endSessionUrl = client.buildEndSessionUrl(config, { const endSessionUrl = client.buildEndSessionUrl(config, {