From 021313260675525f2ee205b6c4a1f4af05f7af5e Mon Sep 17 00:00:00 2001 From: Eduard Prigoana Date: Thu, 12 Feb 2026 09:43:39 +0000 Subject: [PATCH] improve qobuz functionality --- js/music-api.js | 6 + js/player.js | 50 +++++--- js/qobuz-api.js | 216 ++++++++++++++++++++++++++------ js/tracker.js | 9 +- qobuz-api/get-artist/route.ts | 13 +- qobuz-api/get-releases/route.ts | 2 +- 6 files changed, 234 insertions(+), 62 deletions(-) diff --git a/js/music-api.js b/js/music-api.js index 87917d2..59445f0 100644 --- a/js/music-api.js +++ b/js/music-api.js @@ -173,4 +173,10 @@ export class MusicAPI { get settings() { return this._settings; } + + // Extract stream URL from manifest (Tidal only) + extractStreamUrlFromManifest(manifest) { + // This is only available for Tidal + return this.tidalAPI.extractStreamUrlFromManifest(manifest); + } } diff --git a/js/player.js b/js/player.js index 44fa0f0..b246c7b 100644 --- a/js/player.js +++ b/js/player.js @@ -486,27 +486,43 @@ export class Player { } await this.audio.play(); } else { - // Get track data for ReplayGain (should be cached by API) - const trackData = await this.api.getTrack(track.id, this.quality); + const isQobuz = String(track.id).startsWith('q:'); - if (trackData && trackData.info) { - this.currentRgValues = { - trackReplayGain: trackData.info.trackReplayGain, - trackPeakAmplitude: trackData.info.trackPeakAmplitude, - albumReplayGain: trackData.info.albumReplayGain, - albumPeakAmplitude: trackData.info.albumPeakAmplitude, - }; - } else { + if (isQobuz) { + // Qobuz: skip getTrack call, directly fetch stream URL this.currentRgValues = null; - } - this.applyReplayGain(); + this.applyReplayGain(); - if (this.preloadCache.has(track.id)) { - streamUrl = this.preloadCache.get(track.id); - } else if (trackData.originalTrackUrl) { - streamUrl = trackData.originalTrackUrl; + if (this.preloadCache.has(track.id)) { + streamUrl = this.preloadCache.get(track.id); + } else { + streamUrl = await this.api.getStreamUrl(track.id, this.quality); + } } else { - streamUrl = this.api.extractStreamUrlFromManifest(trackData.info.manifest); + // Tidal: Get track data for ReplayGain (should be cached by API) + const trackData = await this.api.getTrack(track.id, this.quality); + + if (trackData && trackData.info) { + this.currentRgValues = { + trackReplayGain: trackData.info.trackReplayGain, + trackPeakAmplitude: trackData.info.trackPeakAmplitude, + albumReplayGain: trackData.info.albumReplayGain, + albumPeakAmplitude: trackData.info.albumPeakAmplitude, + }; + } else { + this.currentRgValues = null; + } + this.applyReplayGain(); + + if (this.preloadCache.has(track.id)) { + streamUrl = this.preloadCache.get(track.id); + } else if (trackData.originalTrackUrl) { + streamUrl = trackData.originalTrackUrl; + } else if (trackData.info?.manifest) { + streamUrl = this.api.extractStreamUrlFromManifest(trackData.info.manifest); + } else { + streamUrl = await this.api.getStreamUrl(track.id, this.quality); + } } // Handle playback diff --git a/js/qobuz-api.js b/js/qobuz-api.js index 3efa0a0..767ccb7 100644 --- a/js/qobuz-api.js +++ b/js/qobuz-api.js @@ -30,7 +30,11 @@ export class QobuzAPI { // Search tracks async searchTracks(query, options = {}) { try { - const data = await this.fetchWithRetry(`/get-music?q=${encodeURIComponent(query)}`); + const offset = options.offset || 0; + const limit = options.limit || 10; + const data = await this.fetchWithRetry( + `/get-music?q=${encodeURIComponent(query)}&offset=${offset}&limit=${limit}` + ); if (!data.success || !data.data) { return { items: [], limit: 0, offset: 0, totalNumberOfItems: 0 }; @@ -55,7 +59,11 @@ export class QobuzAPI { // Search albums async searchAlbums(query, options = {}) { try { - const data = await this.fetchWithRetry(`/get-music?q=${encodeURIComponent(query)}`); + const offset = options.offset || 0; + const limit = options.limit || 10; + const data = await this.fetchWithRetry( + `/get-music?q=${encodeURIComponent(query)}&offset=${offset}&limit=${limit}` + ); if (!data.success || !data.data) { return { items: [], limit: 0, offset: 0, totalNumberOfItems: 0 }; @@ -80,7 +88,11 @@ export class QobuzAPI { // Search artists async searchArtists(query, options = {}) { try { - const data = await this.fetchWithRetry(`/get-music?q=${encodeURIComponent(query)}`); + const offset = options.offset || 0; + const limit = options.limit || 10; + const data = await this.fetchWithRetry( + `/get-music?q=${encodeURIComponent(query)}&offset=${offset}&limit=${limit}` + ); if (!data.success || !data.data) { return { items: [], limit: 0, offset: 0, totalNumberOfItems: 0 }; @@ -104,25 +116,10 @@ export class QobuzAPI { // Get track details async getTrack(id) { - try { - // For Qobuz, we'll need to search or get from album - // Since the API might not have a direct track endpoint - const data = await this.fetchWithRetry(`/get-music?q=${encodeURIComponent(id)}`); - - if (!data.success || !data.data) { - throw new Error('Track not found'); - } - - const track = data.data.tracks?.items?.find((t) => t.id === id || t.isrc === id); - if (!track) { - throw new Error('Track not found'); - } - - return this.transformTrack(track); - } catch (error) { - console.error('Qobuz getTrack failed:', error); - throw error; - } + // Qobuz doesn't have a direct track endpoint + // Track metadata comes from search/album endpoints + // For playback, use getStreamUrl directly + throw new Error('Qobuz getTrack not implemented - use getStreamUrl for playback'); } // Get album details @@ -135,7 +132,7 @@ export class QobuzAPI { } const album = this.transformAlbum(data.data); - const tracks = (data.data.tracks || []).map((track) => this.transformTrack(track, data.data)); + const tracks = (data.data.tracks?.items || []).map((track) => this.transformTrack(track, data.data)); return { album, tracks }; } catch (error) { @@ -147,16 +144,42 @@ export class QobuzAPI { // Get artist details async getArtist(id) { try { - const data = await this.fetchWithRetry(`/get-artist?artist_id=${encodeURIComponent(id)}`); + const artistData = await this.fetchWithRetry(`/get-artist?artist_id=${encodeURIComponent(id)}`); - if (!data.success || !data.data) { + if (!artistData.success || !artistData.data) { throw new Error('Artist not found'); } - const artist = this.transformArtist(data.data); - const albums = (data.data.albums || []).map((album) => this.transformAlbum(album)); + // Qobuz get-artist returns { artist: {...} } nested structure + const artistInfo = artistData.data.artist || artistData.data; + if (!artistInfo) { + throw new Error('Artist info not found in response'); + } + const artist = this.transformArtist(artistInfo); - return { ...artist, albums, eps: [], tracks: [] }; + // Get albums from the releases section + let albums = []; + let eps = []; + if (Array.isArray(artistData.data.releases)) { + // Find album releases + const albumReleases = artistData.data.releases.find((r) => r.type === 'album'); + if (albumReleases?.items) { + albums = albumReleases.items.map((album) => this.transformAlbum(album)); + } + // Find EP/single releases + const epReleases = artistData.data.releases.find((r) => r.type === 'epSingle'); + if (epReleases?.items) { + eps = epReleases.items.map((album) => this.transformAlbum(album)); + } + } + + // Get top tracks + let tracks = []; + if (Array.isArray(artistData.data.top_tracks)) { + tracks = artistData.data.top_tracks.map((track) => this.transformTrack(track)); + } + + return { ...artist, albums, eps, tracks }; } catch (error) { console.error('Qobuz getArtist failed:', error); throw error; @@ -165,12 +188,16 @@ export class QobuzAPI { // Transform Qobuz track to Tidal-like format transformTrack(track, albumData = null) { + // Qobuz uses 'performer' for the main artist, not 'artist' + const mainArtist = track.performer || track.artist; + const artistsList = track.artists || (mainArtist ? [mainArtist] : []); + return { id: `q:${track.id}`, title: track.title, duration: track.duration, - artist: track.artist ? this.transformArtist(track.artist) : null, - artists: track.artists ? track.artists.map((a) => this.transformArtist(a)) : [], + artist: mainArtist ? this.transformArtist(mainArtist) : null, + artists: artistsList.map((a) => this.transformArtist(a)), album: albumData ? this.transformAlbum(albumData) : track.album ? this.transformAlbum(track.album) : null, audioQuality: this.mapQuality(track.streaming_quality), explicit: track.parental_warning || false, @@ -184,11 +211,17 @@ export class QobuzAPI { // Transform Qobuz album to Tidal-like format transformAlbum(album) { + // Qobuz albums have artist (single) or artists (array) + const mainArtist = album.artist || album.artists?.[0]; return { id: `q:${album.id}`, title: album.title, - artist: album.artist ? this.transformArtist(album.artist) : null, - artists: album.artists ? album.artists.map((a) => this.transformArtist(a)) : [], + artist: mainArtist ? this.transformArtist(mainArtist) : null, + artists: album.artists + ? album.artists.map((a) => this.transformArtist(a)) + : mainArtist + ? [this.transformArtist(mainArtist)] + : [], numberOfTracks: album.tracks_count || 0, releaseDate: album.release_date_original || album.release_date, cover: album.image?.large || album.image?.medium || album.image?.small, @@ -201,10 +234,30 @@ export class QobuzAPI { // Transform Qobuz artist to Tidal-like format transformArtist(artist) { + if (!artist) { + return { + id: 'q:unknown', + name: 'Unknown Artist', + picture: null, + provider: 'qobuz', + originalId: null, + }; + } + // Handle different name structures: string or { display: string } + const name = typeof artist.name === 'string' ? artist.name : artist.name?.display || 'Unknown Artist'; + // Handle different image structures: image object or picture string or images.portrait + const picture = + artist.image?.large || + artist.image?.medium || + artist.image?.small || + artist.picture || + (artist.images?.portrait + ? `https://static.qobuz.com/images/artists/covers/large/${artist.images.portrait.hash}.${artist.images.portrait.format}` + : null); return { id: `q:${artist.id}`, - name: artist.name, - picture: artist.image?.large || artist.image?.medium || artist.image?.small, + name: name, + picture: picture, provider: 'qobuz', originalId: artist.id, }; @@ -234,11 +287,37 @@ export class QobuzAPI { return coverId; } + // Get artist picture URL + getArtistPictureUrl(pictureUrl, size = '320') { + if (!pictureUrl) { + return `https://picsum.photos/seed/${Math.random()}/${size}`; + } + + // Qobuz picture URLs are usually full URLs + if (typeof pictureUrl === 'string' && pictureUrl.startsWith('http')) { + return pictureUrl; + } + + return pictureUrl; + } + // Get stream URL for a track - async getStreamUrl(trackId) { + async getStreamUrl(trackId, quality = '27') { try { const cleanId = trackId.replace(/^q:/, ''); - const data = await this.fetchWithRetry(`/download-music?track_id=${encodeURIComponent(cleanId)}`); + // Map Tidal quality format to Qobuz quality values + // Qobuz: 27=MP3 320kbps, 7=FLAC lossless, 6=HiRes 96/24, 5=HiRes 192/24 + const qualityMap = { + LOW: '27', + HIGH: '27', + LOSSLESS: '7', + HI_RES: '6', + HI_RES_LOSSLESS: '5', + }; + const qobuzQuality = qualityMap[quality] || quality || '27'; + const data = await this.fetchWithRetry( + `/download-music?track_id=${encodeURIComponent(cleanId)}&quality=${qobuzQuality}` + ); if (!data.success || !data.data?.url) { throw new Error('Stream URL not available'); @@ -250,6 +329,71 @@ export class QobuzAPI { throw error; } } + + // Unified search - search all types at once + async search(query, options = {}) { + const offset = options.offset || 0; + const limit = options.limit || 10; + + try { + const data = await this.fetchWithRetry( + `/get-music?q=${encodeURIComponent(query)}&offset=${offset}&limit=${limit}` + ); + + if (!data.success || !data.data) { + return { + tracks: { items: [], limit: 0, offset: 0, totalNumberOfItems: 0 }, + albums: { items: [], limit: 0, offset: 0, totalNumberOfItems: 0 }, + artists: { items: [], limit: 0, offset: 0, totalNumberOfItems: 0 }, + }; + } + + const tracks = (data.data.tracks?.items || []).map((track) => this.transformTrack(track)); + const albums = (data.data.albums?.items || []).map((album) => this.transformAlbum(album)); + const artists = (data.data.artists?.items || []).map((artist) => this.transformArtist(artist)); + + return { + tracks: { + items: tracks, + limit: data.data.tracks?.limit || tracks.length, + offset: data.data.tracks?.offset || 0, + totalNumberOfItems: data.data.tracks?.total || tracks.length, + }, + albums: { + items: albums, + limit: data.data.albums?.limit || albums.length, + offset: data.data.albums?.offset || 0, + totalNumberOfItems: data.data.albums?.total || albums.length, + }, + artists: { + items: artists, + limit: data.data.artists?.limit || artists.length, + offset: data.data.artists?.offset || 0, + totalNumberOfItems: data.data.artists?.total || artists.length, + }, + }; + } catch (error) { + if (error.name === 'AbortError') throw error; + console.error('Qobuz search failed:', error); + return { + tracks: { items: [], limit: 0, offset: 0, totalNumberOfItems: 0 }, + albums: { items: [], limit: 0, offset: 0, totalNumberOfItems: 0 }, + artists: { items: [], limit: 0, offset: 0, totalNumberOfItems: 0 }, + }; + } + } + + // Get next page helper + getNextPage(currentOffset, limit, total) { + const nextOffset = currentOffset + limit; + return nextOffset < total ? nextOffset : null; + } + + // Get previous page helper + getPreviousPage(currentOffset, limit) { + const prevOffset = currentOffset - limit; + return prevOffset >= 0 ? prevOffset : null; + } } export const qobuzAPI = new QobuzAPI(); diff --git a/js/tracker.js b/js/tracker.js index 24a9f79..950bd6e 100644 --- a/js/tracker.js +++ b/js/tracker.js @@ -444,7 +444,7 @@ export async function renderTrackerArtistPage(sheetId, container) { Object.values(era.data).forEach((songs) => { if (songs && songs.length) { songs.forEach((song, index) => { - if (song.name.toLowerCase().includes(query)) { + if (song.name?.toLowerCase().includes(query)) { matches.push({ song, era, index }); } }); @@ -734,6 +734,8 @@ export async function renderUnreleasedPage(container) { const sheetId = getSheetId(artist.url); if (!sheetId) return; + if (!artist.name) return; + const artistCard = document.createElement('div'); artistCard.className = 'card'; artistCard.style.cursor = 'pointer'; @@ -953,12 +955,15 @@ export async function initTracker(player) { // Helper function to find a tracker artist by name (for use in normal artist pages) export function findTrackerArtistByName(artistName) { // First try exact match - let match = artistsData.find((a) => a.name.toLowerCase() === artistName.toLowerCase()); + if (!artistName) return null; + + let match = artistsData.find((a) => a.name?.toLowerCase() === artistName.toLowerCase()); if (match) return match; // Try fuzzy match (remove special chars and spaces) const normalized = artistName.toLowerCase().replace(/[^a-z0-9]/g, ''); match = artistsData.find((a) => { + if (!a.name) return false; const aNormalized = a.name.toLowerCase().replace(/[^a-z0-9]/g, ''); return aNormalized === normalized || aNormalized.includes(normalized) || normalized.includes(aNormalized); }); diff --git a/qobuz-api/get-artist/route.ts b/qobuz-api/get-artist/route.ts index c0db1d8..e3c1f02 100644 --- a/qobuz-api/get-artist/route.ts +++ b/qobuz-api/get-artist/route.ts @@ -1,19 +1,20 @@ +import { NextRequest, NextResponse } from 'next/server'; import { getArtist } from '@/lib/qobuz-dl-server'; import z from 'zod'; -const artistReleasesParamsSchema = z.object({ +const artistParamsSchema = z.object({ artist_id: z.string().min(1, 'ID is required'), }); -export async function GET(request: Request) { +export async function GET(request: NextRequest) { const country = request.headers.get('Token-Country'); const params = Object.fromEntries(new URL(request.url).searchParams.entries()); try { - const { artist_id } = artistReleasesParamsSchema.parse(params); - const artist = await getArtist(artist_id, country ? { country } : {}); - return new Response(JSON.stringify({ success: true, data: { artist } }), { status: 200 }); + const { artist_id } = artistParamsSchema.parse(params); + const data = await getArtist(artist_id, country ? { country } : {}); + return new NextResponse(JSON.stringify({ success: true, data }), { status: 200 }); } catch (error: any) { - return new Response( + return new NextResponse( JSON.stringify({ success: false, error: error?.errors || error.message || 'An error occurred parsing the request.', diff --git a/qobuz-api/get-releases/route.ts b/qobuz-api/get-releases/route.ts index f6394ee..c237c58 100644 --- a/qobuz-api/get-releases/route.ts +++ b/qobuz-api/get-releases/route.ts @@ -6,7 +6,7 @@ const releasesParamsSchema = z.object({ artist_id: z.string().min(1, 'ID is required'), release_type: z.enum(['album', 'live', 'compilation', 'epSingle', 'download']).default('album'), track_size: z.number().positive().default(1000), - offset: z.preprocess((a) => parseInt(a as string), z.number().positive().default(0)), + offset: z.preprocess((a) => parseInt(a as string), z.number().nonnegative().default(0)), limit: z.preprocess((a) => parseInt(a as string), z.number().positive().default(10)), });