import { Body, Controller, Delete, ForbiddenException, Get, NotFoundException, Param, Patch, Post, Put, Query, Req, Res, UseGuards, BadRequestException, UnauthorizedException, Injectable, } from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import type { Request, Response } from 'express'; import { randomUUID } from 'node:crypto'; import { JwtAuthGuard } from '../modules/auth/jwt-auth.guard'; import { MusicService, textValue } from './music.service'; import { DiscoveryService } from './discovery.service'; import { StorageService } from './storage.service'; import { DownloadsService } from './downloads.service'; import { Store } from './store'; import { now, Track } from './models'; import { parseRange } from './audio-vault'; import type { ExecutionContext } from '@nestjs/common'; import { HfLibraryService } from './hf-library.service'; @Injectable() export class OptionalAuthGuard extends JwtAuthGuard { handleRequest( err: any, user: any, _info?: any, context?: ExecutionContext, _status?: any, ) { if ( !user && context?.switchToHttp().getRequest()?.headers?.authorization ) throw new UnauthorizedException('Your session has expired'); return user || null; } } @Controller() export class PublicController { constructor( private readonly music: MusicService, private readonly discovery: DiscoveryService, private readonly downloads: DownloadsService, ) {} @Get('health') health() { return { status: 'ok', application: 'Stillwave', version: '1.0.0' }; } @Get('tracks') @UseGuards(JwtAuthGuard) tracks( @Req() req: any, @Query('q') q = '', @Query('offset') offset = '0', ) { return this.music .tracks(req.user?.userId) .filter( (t) => !q || `${t.title} ${t.artist_name} ${t.album_title}` .toLowerCase() .includes(q.slice(0, 120).toLowerCase()), ) .sort((a, b) => a.id.localeCompare(b.id)) .slice( Math.max(0, Number(offset) || 0), Math.max(0, Number(offset) || 0) + 500, ) .map((t) => this.music.present(t, req.user?.userId)); } @Get('home') @UseGuards(JwtAuthGuard) home(@Req() req: any) { return this.discovery.home(req.user?.userId); } @Get('search') @UseGuards(JwtAuthGuard) search( @Req() req: any, @Query('q') q = '', ) { return this.downloads.search(q, req.user?.userId); } } @Controller() @UseGuards(JwtAuthGuard) export class MusicController { constructor( private readonly music: MusicService, private readonly discovery: DiscoveryService, private readonly storage: StorageService, private readonly downloads: DownloadsService, private readonly store: Store, private readonly jwt: JwtService, private readonly library: HfLibraryService, ) {} @Post('library/sync') syncLibrary() { this.music.enableMetadataBackfill(); return this.library.sync(); } @Post('library/refresh') refreshLibrary() { return this.library.sync(true); } @Get('library/status') libraryStatus() { return this.library.status(); } @Get('library/activity') libraryActivity(@Req() req: any) { return this.music.activity(req.user.userId); } @Get('tracks/on-repeat') onRepeat(@Req() req: any) { return this.discovery .onRepeat(req.user.userId) .map((t) => this.music.present(t, req.user.userId)); } @Get('tracks/:id') async track(@Req() req: any, @Param('id') id: string) { let track = this.music.track(id, req.user.userId); try { track = track.remote ? await this.library.hydrate(track) : await this.music.metadata(track); } catch { track = { ...track, metadata_error: 'Metadata could not be read. Please retry.', }; } return { ...this.music.present(track, req.user.userId), lyrics: track.lyrics || [], }; } @Patch('tracks/:id') update( @Req() req: any, @Param('id') id: string, @Body() body: any, ) { return this.music.updateTrack(req.user.userId, id, body); } @Delete('tracks/:id') remove(@Req() req: any, @Param('id') id: string) { return this.music.removeTrack(req.user.userId, id); } @Get('tracks/:id/stream') stream(@Req() req: any, @Param('id') id: string) { const track = this.music.track(id, req.user.userId); if (!track.asset && !track.remote) throw new BadRequestException( 'This song needs to be prepared before playing', ); const ticket = this.jwt.sign( { type: 'stream', sub: req.user.userId, sid: req.user.sessionId, track: id, }, { expiresIn: '2h' }, ); return { signedUrl: `/api/v1/tracks/${id}/audio?ticket=${ticket}`, expiresAt: new Date(Date.now() + 7200000).toISOString(), }; } @Get('tracks/:id/artwork') artwork( @Req() req: any, @Param('id') id: string, @Res() res: Response, ) { const t = this.music.track(id, req.user.userId); const image = this.store.get('artwork', id); if (!image && !t.artwork) throw new NotFoundException(); res.setHeader('Cache-Control', 'private, max-age=3600'); res .type(image?.mime || t.artwork_mime || 'image/jpeg') .send(Buffer.from(image?.data || t.artwork!, 'base64')); } @Post('tracks/:id/play') play( @Req() req: any, @Param('id') id: string, @Body() body: any, ) { return this.discovery.log(req.user.userId, id, body); } @Post('tracks/:id/feedback') feedback( @Req() req: any, @Param('id') id: string, @Body() body: any, ) { return this.discovery.feedback(req.user.userId, id, body.value); } @Post('tracks/download-demand') download(@Req() req: any, @Body() body: any) { return this.downloads.request(req.user.userId, textValue(body.track_id)); } @Get('tracks/download-status/:id') downloadStatus( @Req() req: any, @Param('id') id: string, ) { this.music.track(id, req.user.userId); return this.store.get('downloads', id) || { status: 'not_requested' }; } @Get('me/recommendations/home') home(@Req() req: any) { return this.discovery.home(req.user.userId); } @Get('me/recommendations/next') next( @Req() req: any, @Query('seed') seed?: string, @Query('adventure') adventure = '0.3', @Query('exclude') exclude = '', ) { return this.discovery.next( req.user.userId, seed, Math.min(1, Math.max(0, Number(adventure) || 0)), exclude.split(','), ); } @Get('me/library/tracks') liked(@Req() req: any) { const likes = new Set( this.store.list('likes', req.user.userId).map((l) => l.track_id), ); return this.music .tracks(req.user.userId) .filter((t) => likes.has(t.id)) .map((t) => this.music.present(t, req.user.userId)); } @Post('me/library/tracks/:id') like( @Req() req: any, @Param('id') id: string, ) { return this.discovery.feedback(req.user.userId, id, 'like'); } @Delete('me/library/tracks/:id') unlike( @Req() req: any, @Param('id') id: string, ) { return this.discovery.feedback(req.user.userId, id, 'clear'); } @Get('uploads') uploads(@Req() req: any) { return this.store.list('uploads', req.user.userId, 500).map((u) => { const track = u.track_id ? this.store.get('tracks', u.track_id) : undefined; return { ...u, backup_status: track ? this.music.backupStatus(track) : undefined, }; }); } @Post('uploads') createUpload(@Req() req: any, @Body() body: any) { return this.music.createUpload(req.user.userId, body); } @Get('uploads/usage') usage(@Req() req: any) { return this.music.usage(req.user.userId); } @Put('uploads/speed') speed(@Body() body: Buffer) { if (!Buffer.isBuffer(body) || body.length > 1024 * 1024) throw new BadRequestException('Invalid speed sample'); return { received: body.length }; } @Get('uploads/:id') upload(@Req() req: any, @Param('id') id: string) { return this.music.upload(req.user.userId, id); } @Put('uploads/:id/chunk') chunk( @Req() req: any, @Param('id') id: string, @Query('offset') offset: string, @Body() body: Buffer, ) { return this.music.chunk(req.user.userId, id, Number(offset), body); } @Post('uploads/:id/complete') complete( @Req() req: any, @Param('id') id: string, ) { return this.music.complete(req.user.userId, id); } @Delete('uploads/:id') cancel(@Req() req: any, @Param('id') id: string) { return this.music.cancel(req.user.userId, id); } @Get('playlists') playlists(@Req() req: any) { return this.store.list('playlists', req.user.userId); } @Post('playlists') createPlaylist(@Req() req: any, @Body() body: any) { const title = textValue(body.title); if (!title) throw new BadRequestException('Name your playlist'); const ids = Array.isArray(body.track_ids) ? body.track_ids.slice(0, 1000) : []; ids.forEach((id) => this.music.track(id, req.user.userId)); return this.store.put( 'playlists', { id: randomUUID(), owner_id: req.user.userId, title, description: textValue(body.description), track_ids: [...new Set(ids)], created_at: now(), }, req.user.userId, ); } private ownedPlaylist(id: string, userId: string) { const p = this.store.get('playlists', id); if (!p || p.owner_id !== userId) throw new NotFoundException('Playlist not found'); return p; } @Get('playlists/:id') playlist(@Req() req: any, @Param('id') id: string) { const p = this.ownedPlaylist(id, req.user.userId); return { ...p, tracks: p.track_ids .map((trackId: string) => { try { return this.music.present( this.music.track(trackId, req.user.userId), req.user.userId, ); } catch { return null; } }) .filter(Boolean), }; } @Patch('playlists/:id') editPlaylist( @Req() req: any, @Param('id') id: string, @Body() body: any, ) { const p = this.ownedPlaylist(id, req.user.userId); if (body.title) p.title = textValue(body.title); return this.store.put('playlists', p, req.user.userId); } @Delete('playlists/:id') deletePlaylist( @Req() req: any, @Param('id') id: string, ) { this.ownedPlaylist(id, req.user.userId); this.store.remove('playlists', id); return { success: true }; } @Post('playlists/:id/tracks') addTracks( @Req() req: any, @Param('id') id: string, @Body() body: any, ) { const p = this.ownedPlaylist(id, req.user.userId); if (!Array.isArray(body.track_ids) || body.track_ids.length > 500) throw new BadRequestException('Invalid track list'); body.track_ids.forEach((trackId: string) => this.music.track(trackId, req.user.userId), ); p.track_ids = [...new Set([...p.track_ids, ...body.track_ids])].slice( 0, 2000, ); return this.store.put('playlists', p, req.user.userId); } @Delete('playlists/:id/tracks/:track') removeFromPlaylist( @Req() req: any, @Param('id') id: string, @Param('track') track: string, ) { const p = this.ownedPlaylist(id, req.user.userId); p.track_ids = p.track_ids.filter((t: string) => t !== track); return this.store.put('playlists', p, req.user.userId); } @Get('me/settings') settings(@Req() req: any) { return ( this.store.get('preferences', req.user.userId) || { autoplay: true, adventure: 0.3, theme: 'light', } ); } @Patch('me/settings') updateSettings(@Req() req: any, @Body() body: any) { const prev = this.store.get('preferences', req.user.userId) || { autoplay: true, adventure: 0.3, theme: 'light', }; return this.store.put( 'preferences', { id: req.user.userId, autoplay: typeof body.autoplay === 'boolean' ? body.autoplay : prev.autoplay, adventure: typeof body.adventure === 'number' ? Math.min(1, Math.max(0, body.adventure)) : prev.adventure, theme: ['light', 'dark'].includes(body.theme) ? body.theme : prev.theme, }, req.user.userId, ); } @Get('me/export') export(@Req() req: any) { return { exported_at: now(), tracks: this.music .tracks(req.user.userId) .filter((t) => t.owner_id === req.user.userId) .map((t) => this.music.present(t, req.user.userId)), playlists: this.store.list('playlists', req.user.userId), likes: this.store.list('likes', req.user.userId), history: this.store.list('events', req.user.userId), }; } @Get('me/history') history(@Req() req: any) { return this.store.list('events', req.user.userId, 100); } @Delete('me/history') clearHistory(@Req() req: any) { this.store .list('events', req.user.userId) .forEach((e) => this.store.remove('events', e.id)); this.store.remove('playback', req.user.userId); return { success: true }; } private admin(req: any) { if (req.user.role !== 'admin') throw new ForbiddenException('Administrator access required'); } @Get('admin/storage') storageStatus(@Req() req: any) { this.admin(req); return this.storage.status(); } @Post('admin/storage/accounts') addAccount( @Req() req: any, @Body() body: any, ) { this.admin(req); return this.storage.save(body); } @Patch('admin/storage/accounts/:id') editAccount( @Req() req: any, @Param('id') id: string, @Body() body: any, ) { this.admin(req); return this.storage.save(body, id); } @Post('admin/storage/accounts/:id/test') testAccount( @Req() req: any, @Param('id') id: string, ) { this.admin(req); return this.storage.test(id); } @Post('admin/storage/jobs/:id/retry') retryStorage( @Req() req: any, @Param('id') id: string, ) { this.admin(req); return this.storage.retry(id); } } @Controller('tracks') export class AudioController { constructor( private readonly jwt: JwtService, private readonly store: Store, private readonly music: MusicService, private readonly storage: StorageService, ) {} @Get(':id/audio') async audio( @Param('id') id: string, @Query('ticket') ticket: string, @Req() req: Request, @Res() res: Response, ) { let payload: any; try { payload = this.jwt.verify(ticket); const session = this.store.get('sessions', payload.sid); if ( payload.type !== 'stream' || payload.track !== id || !session || session.user_id !== payload.sub || session.expires < Date.now() ) throw new Error(); } catch { throw new UnauthorizedException( 'Playback link expired. Please reload the song.', ); } const track = this.music.track(id, payload.sub); const source = track.asset || track.remote; if (!source) throw new NotFoundException('Audio is not ready'); const range = parseRange(req.headers.range, source.size); if (!range) { res.status(416).setHeader('Content-Range', `bytes */${source.size}`); res.end(); return; } const stream = this.storage.read(track, range.start, range.end); try { const first = await stream.next(); res.status(range.partial ? 206 : 200); res.setHeader('Content-Type', source.mime); res.setHeader('Accept-Ranges', 'bytes'); res.setHeader('Content-Length', range.end - range.start + 1); res.setHeader('Cache-Control', 'private, no-store'); res.setHeader('X-Content-Type-Options', 'nosniff'); if (range.partial) res.setHeader( 'Content-Range', `bytes ${range.start}-${range.end}/${source.size}`, ); if (req.method === 'HEAD') { res.end(); return; } const write = async (chunk: Buffer) => { if (res.destroyed) return; if (!res.write(chunk)) await new Promise((resolve) => { const done = () => { res.off('drain', done); res.off('close', done); resolve(); }; res.once('drain', done); res.once('close', done); }); }; if (!first.done) await write(first.value); for await (const chunk of stream) { if (res.destroyed) break; await write(chunk); } if (!res.destroyed) res.end(); } catch (error) { if (res.headersSent) res.destroy(); else throw error; } finally { await stream.return(undefined); } } }