This commit is contained in:
uimaxbai 2026-04-18 10:04:31 +01:00
parent d4f6c5911f
commit 6ddb411b94
5 changed files with 36 additions and 93 deletions

View file

@ -1,67 +0,0 @@
export async function onRequest(context) {
const { request } = context;
const url = new URL(request.url);
const targetUrl = url.searchParams.get('url');
if (!targetUrl) {
return new Response('Missing url parameter', { status: 400 });
}
try {
const cacheUrl = new URL(request.url);
try {
const tidalUrl = new URL(targetUrl);
cacheUrl.searchParams.set('cache_key', tidalUrl.pathname);
} catch (e) {}
const cacheKey = new Request(cacheUrl.toString(), request);
const cache = caches.default;
let response = await cache.match(cacheKey);
if (!response) {
console.log('Cache Miss. Fetching from Tidal...');
const headers = new Headers(request.headers);
headers.delete('host');
headers.delete('referer');
headers.set(
'User-Agent',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'
);
response = await fetch(targetUrl, {
method: request.method,
headers: headers,
redirect: 'follow',
cf: {
cacheTtl: 2592000,
cacheEverything: true,
},
});
if (request.method === 'GET' && response.ok) {
const cacheResponse = new Response(response.body, response);
cacheResponse.headers.set('Access-Control-Allow-Origin', '*');
cacheResponse.headers.set('Cache-Control', 'public, max-age=2592000');
cacheResponse.headers.delete('Set-Cookie');
context.waitUntil(cache.put(cacheKey, cacheResponse.clone()));
response = cacheResponse;
}
} else {
console.log('Cache Hit! Serving from Edge.');
}
const newResponse = new Response(response.body, response);
newResponse.headers.set('Access-Control-Allow-Origin', '*');
newResponse.headers.set('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');
newResponse.headers.set('Access-Control-Expose-Headers', '*');
newResponse.headers.delete('content-security-policy');
newResponse.headers.delete('x-frame-options');
return newResponse;
} catch (error) {
return new Response('Proxy Error: ' + error.message, { status: 500 });
}
}

View file

@ -1717,7 +1717,11 @@ class HiFiClient {
const artist_url = `https://openapi.tidal.com/v2/artists/${id}`; const artist_url = `https://openapi.tidal.com/v2/artists/${id}`;
const payload = await this.#fetchJson<any>( const payload = await this.#fetchJson<any>(
artist_url, artist_url,
{ countryCode: this.#countryCode, include: 'albums,albums.coverArt,tracks,tracks.albums,biography,profileArt', collapseBy: 'FINGERPRINT' }, {
countryCode: this.#countryCode,
include: 'albums,albums.coverArt,tracks,tracks.albums,biography,profileArt',
collapseBy: 'FINGERPRINT',
},
signal signal
); );
@ -1746,7 +1750,7 @@ class HiFiClient {
picture: getPic(data, 'profileArt') || data?.attributes?.selectedAlbumCoverFallback || null, picture: getPic(data, 'profileArt') || data?.attributes?.selectedAlbumCoverFallback || null,
}; };
let picture = artist_data.picture; const picture = artist_data.picture;
let cover: ArtistCover | null = null; let cover: ArtistCover | null = null;
if (picture) { if (picture) {
const slug = picture.replace(/-/g, '/'); const slug = picture.replace(/-/g, '/');
@ -1772,7 +1776,7 @@ class HiFiClient {
releaseDate: al.attributes?.releaseDate, releaseDate: al.attributes?.releaseDate,
type: al.attributes?.albumType, type: al.attributes?.albumType,
cover: getPic(al, 'coverArt'), cover: getPic(al, 'coverArt'),
artist: { id: artist_data.id, name: artist_data.name } artist: { id: artist_data.id, name: artist_data.name },
}); });
} }
} }
@ -1787,7 +1791,11 @@ class HiFiClient {
const aRef = tr.relationships.albums.data[0]; const aRef = tr.relationships.albums.data[0];
const aItem = includedMap.get(`albums:${aRef.id}`); const aItem = includedMap.get(`albums:${aRef.id}`);
if (aItem) { if (aItem) {
albumInfo = { id: Number(aItem.id), title: aItem.attributes?.title, cover: getPic(aItem, 'coverArt') }; albumInfo = {
id: Number(aItem.id),
title: aItem.attributes?.title,
cover: getPic(aItem, 'coverArt'),
};
} }
} }
tracks.push({ tracks.push({
@ -1795,13 +1803,19 @@ class HiFiClient {
title: tr.attributes?.title, title: tr.attributes?.title,
duration: tr.attributes?.duration ? 100 : undefined, duration: tr.attributes?.duration ? 100 : undefined,
album: albumInfo, album: albumInfo,
artist: { id: artist_data.id, name: artist_data.name } artist: { id: artist_data.id, name: artist_data.name },
}); });
} }
} }
} }
return HiFiClient.#jsonResponse({ version: HiFiClient.API_VERSION, artist: artist_data, cover, albums: { items: albums }, tracks }); return HiFiClient.#jsonResponse({
version: HiFiClient.API_VERSION,
artist: artist_data,
cover,
albums: { items: albums },
tracks,
});
} }
// fallback to original f logic // fallback to original f logic

View file

@ -1507,11 +1507,6 @@ export class LosslessAPI {
}; };
} }
if (streamUrl && streamUrl.includes('tidal.com')) {
const encodedUrl = encodeURIComponent(streamUrl);
streamUrl = `/proxy-audio?url=${encodedUrl}`;
}
const result = { url: streamUrl, rgInfo: manifestRgInfo }; const result = { url: streamUrl, rgInfo: manifestRgInfo };
this.streamCache.set(cacheKey, result); this.streamCache.set(cacheKey, result);
@ -1559,11 +1554,6 @@ export class LosslessAPI {
throw new Error(`Could not resolve video stream URL for ID: ${id}`); throw new Error(`Could not resolve video stream URL for ID: ${id}`);
} }
if (streamUrl && streamUrl.includes('tidal.com')) {
const encodedUrl = encodeURIComponent(streamUrl);
streamUrl = `/proxy-audio?url=${encodedUrl}`;
}
if (!(lookup instanceof TidalResponse)) { if (!(lookup instanceof TidalResponse)) {
this.streamCache.set(cacheKey, streamUrl); this.streamCache.set(cacheKey, streamUrl);
} }

View file

@ -1049,8 +1049,8 @@ ul {
gap: 0.375rem; gap: 0.375rem;
padding: 0.4rem 0.6rem; padding: 0.4rem 0.6rem;
margin-bottom: 1rem; margin-bottom: 1rem;
background: rgba(245, 158, 11, 0.12); background: rgb(245, 158, 11, 0.12);
border: 1px solid rgba(245, 158, 11, 0.25); border: 1px solid rgb(245, 158, 11, 0.25);
border-radius: var(--radius-md); border-radius: var(--radius-md);
color: #f59e0b; color: #f59e0b;
font-size: 0.7rem; font-size: 0.7rem;

View file

@ -4,7 +4,13 @@ import { LosslessAPI } from './js/api.js';
// mock out modules to make LosslessAPI load in bun // mock out modules to make LosslessAPI load in bun
import { mock } from 'bun:test'; import { mock } from 'bun:test';
mock.module('./js/icons.ts', () => ({})); mock.module('./js/icons.ts', () => ({}));
mock.module('./js/settings.js', () => ({ devModeSettings: { isEnabled: () => false }, syncManager: {}, musicProviderSettings: {}, audioSettings: {}, apiSettings: {} })); mock.module('./js/settings.js', () => ({
devModeSettings: { isEnabled: () => false },
syncManager: {},
musicProviderSettings: {},
audioSettings: {},
apiSettings: {},
}));
globalThis.localStorage = { getItem: () => null, setItem: () => {}, removeItem: () => {} }; globalThis.localStorage = { getItem: () => null, setItem: () => {}, removeItem: () => {} };
globalThis.window = { matchMedia: () => ({ matches: false }) }; globalThis.window = { matchMedia: () => ({ matches: false }) };
@ -17,11 +23,11 @@ async function test() {
api.cache = { get: () => null, set: () => {} }; api.cache = { get: () => null, set: () => {} };
api.fetchWithRetry = async function (relativePath, options) { api.fetchWithRetry = async function (relativePath, options) {
console.log("fetchWithRetry called:", relativePath); console.log('fetchWithRetry called:', relativePath);
return HiFiClient.instance.query(relativePath); return HiFiClient.instance.query(relativePath);
}; };
const res = await api.search('coldplay'); const res = await api.search('coldplay');
console.log("Returned tracks:", res.tracks?.items?.length); console.log('Returned tracks:', res.tracks?.items?.length);
} }
test().catch(console.error); test().catch(console.error);