Spaces:
Sleeping
Sleeping
Download backend/src/core/api.controller.ts from kishankrish19/Chat: direct link, hf CLI and curl.
- Browser
- Download file 16.9 kB
-
https://huggingface.co/spaces/kishankrish19/Chat/resolve/main/backend/src/core/api.controller.ts
- Command line
-
hf download hf://spaces/kishankrish19/Chat/backend/src/core/api.controller.ts
-
curl -L -o api.controller.ts https://huggingface.co/spaces/kishankrish19/Chat/resolve/main/backend/src/core/api.controller.ts
16.9 kB
| 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'; | |
| () | |
| export class OptionalAuthGuard extends JwtAuthGuard { | |
| handleRequest( | |
| err: any, | |
| user: any, | |
| _info?: any, | |
| context?: ExecutionContext, | |
| _status?: any, | |
| ) { | |
| if ( | |
| !user && | |
| context?.switchToHttp().getRequest<Request>()?.headers?.authorization | |
| ) | |
| throw new UnauthorizedException('Your session has expired'); | |
| return user || null; | |
| } | |
| } | |
| () | |
| export class PublicController { | |
| constructor( | |
| private readonly music: MusicService, | |
| private readonly discovery: DiscoveryService, | |
| private readonly downloads: DownloadsService, | |
| ) {} | |
| ('health') health() { | |
| return { status: 'ok', application: 'Stillwave', version: '1.0.0' }; | |
| } | |
| ('tracks') (JwtAuthGuard) tracks( | |
| () req: any, | |
| ('q') q = '', | |
| ('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)); | |
| } | |
| ('home') (JwtAuthGuard) home(() req: any) { | |
| return this.discovery.home(req.user?.userId); | |
| } | |
| ('search') (JwtAuthGuard) search( | |
| () req: any, | |
| ('q') q = '', | |
| ) { | |
| return this.downloads.search(q, req.user?.userId); | |
| } | |
| } | |
| () | |
| (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, | |
| ) {} | |
| ('library/sync') syncLibrary() { | |
| this.music.enableMetadataBackfill(); | |
| return this.library.sync(); | |
| } | |
| ('library/refresh') refreshLibrary() { | |
| return this.library.sync(true); | |
| } | |
| ('library/status') libraryStatus() { | |
| return this.library.status(); | |
| } | |
| ('library/activity') libraryActivity(() req: any) { | |
| return this.music.activity(req.user.userId); | |
| } | |
| ('tracks/on-repeat') onRepeat(() req: any) { | |
| return this.discovery | |
| .onRepeat(req.user.userId) | |
| .map((t) => this.music.present(t, req.user.userId)); | |
| } | |
| ('tracks/:id') async track(() req: any, ('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 || [], | |
| }; | |
| } | |
| ('tracks/:id') update( | |
| () req: any, | |
| ('id') id: string, | |
| () body: any, | |
| ) { | |
| return this.music.updateTrack(req.user.userId, id, body); | |
| } | |
| ('tracks/:id') remove(() req: any, ('id') id: string) { | |
| return this.music.removeTrack(req.user.userId, id); | |
| } | |
| ('tracks/:id/stream') stream(() req: any, ('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(), | |
| }; | |
| } | |
| ('tracks/:id/artwork') artwork( | |
| () req: any, | |
| ('id') id: string, | |
| () 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')); | |
| } | |
| ('tracks/:id/play') play( | |
| () req: any, | |
| ('id') id: string, | |
| () body: any, | |
| ) { | |
| return this.discovery.log(req.user.userId, id, body); | |
| } | |
| ('tracks/:id/feedback') feedback( | |
| () req: any, | |
| ('id') id: string, | |
| () body: any, | |
| ) { | |
| return this.discovery.feedback(req.user.userId, id, body.value); | |
| } | |
| ('tracks/download-demand') download(() req: any, () body: any) { | |
| return this.downloads.request(req.user.userId, textValue(body.track_id)); | |
| } | |
| ('tracks/download-status/:id') downloadStatus( | |
| () req: any, | |
| ('id') id: string, | |
| ) { | |
| this.music.track(id, req.user.userId); | |
| return this.store.get('downloads', id) || { status: 'not_requested' }; | |
| } | |
| ('me/recommendations/home') home(() req: any) { | |
| return this.discovery.home(req.user.userId); | |
| } | |
| ('me/recommendations/next') next( | |
| () req: any, | |
| ('seed') seed?: string, | |
| ('adventure') adventure = '0.3', | |
| ('exclude') exclude = '', | |
| ) { | |
| return this.discovery.next( | |
| req.user.userId, | |
| seed, | |
| Math.min(1, Math.max(0, Number(adventure) || 0)), | |
| exclude.split(','), | |
| ); | |
| } | |
| ('me/library/tracks') liked(() 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)); | |
| } | |
| ('me/library/tracks/:id') like( | |
| () req: any, | |
| ('id') id: string, | |
| ) { | |
| return this.discovery.feedback(req.user.userId, id, 'like'); | |
| } | |
| ('me/library/tracks/:id') unlike( | |
| () req: any, | |
| ('id') id: string, | |
| ) { | |
| return this.discovery.feedback(req.user.userId, id, 'clear'); | |
| } | |
| ('uploads') uploads(() req: any) { | |
| return this.store.list('uploads', req.user.userId, 500).map((u) => { | |
| const track = u.track_id | |
| ? this.store.get<Track>('tracks', u.track_id) | |
| : undefined; | |
| return { | |
| ...u, | |
| backup_status: track ? this.music.backupStatus(track) : undefined, | |
| }; | |
| }); | |
| } | |
| ('uploads') createUpload(() req: any, () body: any) { | |
| return this.music.createUpload(req.user.userId, body); | |
| } | |
| ('uploads/usage') usage(() req: any) { | |
| return this.music.usage(req.user.userId); | |
| } | |
| ('uploads/speed') speed(() body: Buffer) { | |
| if (!Buffer.isBuffer(body) || body.length > 1024 * 1024) | |
| throw new BadRequestException('Invalid speed sample'); | |
| return { received: body.length }; | |
| } | |
| ('uploads/:id') upload(() req: any, ('id') id: string) { | |
| return this.music.upload(req.user.userId, id); | |
| } | |
| ('uploads/:id/chunk') chunk( | |
| () req: any, | |
| ('id') id: string, | |
| ('offset') offset: string, | |
| () body: Buffer, | |
| ) { | |
| return this.music.chunk(req.user.userId, id, Number(offset), body); | |
| } | |
| ('uploads/:id/complete') complete( | |
| () req: any, | |
| ('id') id: string, | |
| ) { | |
| return this.music.complete(req.user.userId, id); | |
| } | |
| ('uploads/:id') cancel(() req: any, ('id') id: string) { | |
| return this.music.cancel(req.user.userId, id); | |
| } | |
| ('playlists') playlists(() req: any) { | |
| return this.store.list('playlists', req.user.userId); | |
| } | |
| ('playlists') createPlaylist(() req: any, () 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; | |
| } | |
| ('playlists/:id') playlist(() req: any, ('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), | |
| }; | |
| } | |
| ('playlists/:id') editPlaylist( | |
| () req: any, | |
| ('id') id: string, | |
| () 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); | |
| } | |
| ('playlists/:id') deletePlaylist( | |
| () req: any, | |
| ('id') id: string, | |
| ) { | |
| this.ownedPlaylist(id, req.user.userId); | |
| this.store.remove('playlists', id); | |
| return { success: true }; | |
| } | |
| ('playlists/:id/tracks') addTracks( | |
| () req: any, | |
| ('id') id: string, | |
| () 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); | |
| } | |
| ('playlists/:id/tracks/:track') removeFromPlaylist( | |
| () req: any, | |
| ('id') id: string, | |
| ('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); | |
| } | |
| ('me/settings') settings(() req: any) { | |
| return ( | |
| this.store.get('preferences', req.user.userId) || { | |
| autoplay: true, | |
| adventure: 0.3, | |
| theme: 'light', | |
| } | |
| ); | |
| } | |
| ('me/settings') updateSettings(() req: any, () 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, | |
| ); | |
| } | |
| ('me/export') export(() 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), | |
| }; | |
| } | |
| ('me/history') history(() req: any) { | |
| return this.store.list('events', req.user.userId, 100); | |
| } | |
| ('me/history') clearHistory(() 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'); | |
| } | |
| ('admin/storage') storageStatus(() req: any) { | |
| this.admin(req); | |
| return this.storage.status(); | |
| } | |
| ('admin/storage/accounts') addAccount( | |
| () req: any, | |
| () body: any, | |
| ) { | |
| this.admin(req); | |
| return this.storage.save(body); | |
| } | |
| ('admin/storage/accounts/:id') editAccount( | |
| () req: any, | |
| ('id') id: string, | |
| () body: any, | |
| ) { | |
| this.admin(req); | |
| return this.storage.save(body, id); | |
| } | |
| ('admin/storage/accounts/:id/test') testAccount( | |
| () req: any, | |
| ('id') id: string, | |
| ) { | |
| this.admin(req); | |
| return this.storage.test(id); | |
| } | |
| ('admin/storage/jobs/:id/retry') retryStorage( | |
| () req: any, | |
| ('id') id: string, | |
| ) { | |
| this.admin(req); | |
| return this.storage.retry(id); | |
| } | |
| } | |
| ('tracks') | |
| export class AudioController { | |
| constructor( | |
| private readonly jwt: JwtService, | |
| private readonly store: Store, | |
| private readonly music: MusicService, | |
| private readonly storage: StorageService, | |
| ) {} | |
| (':id/audio') async audio( | |
| ('id') id: string, | |
| ('ticket') ticket: string, | |
| () req: Request, | |
| () 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<void>((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); | |
| } | |
| } | |
| } | |