183 lines
12 KiB
JavaScript
183 lines
12 KiB
JavaScript
import {randomKey,hmac,base64url} from './webcrypto.mjs';
|
|
import { MusicError } from '../../core/controller.mjs';
|
|
// Shared trusted-GM/optional-companion transport. Never construct with MA credentials on a player client.
|
|
export class MAReadClient {
|
|
#base; #token; #target; #fetch; #providers; #catalog = new Map(); #catalogKey; #campaign; #expectedName; #expectedProvider; #writes = Promise.resolve(); #synthetic; #uncertain = false; #authorizedMedia = new Set(); #targetVolume;
|
|
constructor({ baseUrl, token, target, approvedProviders = [], catalogKey = randomKey(), campaign = 'default', expectedName, expectedProvider, syntheticSequences = {}, fetchImpl = fetch }) {
|
|
const url = new URL(baseUrl);
|
|
if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password ||
|
|
url.search || url.hash || url.pathname !== '/' || typeof token !== 'string' || !token ||
|
|
/[\r\n]/.test(token) || typeof target !== 'string' || !target ||
|
|
!Array.isArray(approvedProviders) || approvedProviders.some(p => typeof p !== 'string' || !p)) throw new MusicError('denied');
|
|
this.#base = url.origin; this.#token = token; this.#target = target; this.#fetch = fetchImpl;
|
|
if (!(catalogKey instanceof Uint8Array) || catalogKey.length !== 32 || !campaign) throw new MusicError('denied');
|
|
this.#providers = [...new Set(approvedProviders)];
|
|
this.#catalogKey = Uint8Array.from(catalogKey); this.#campaign = campaign;
|
|
if(!syntheticSequences || typeof syntheticSequences!=='object' || Object.values(syntheticSequences).some(v=>!Array.isArray(v)||!v.length||v.length>5000||v.some(uri=>typeof uri!=='string'||!uri.startsWith('builtin://track/http://'))))throw new MusicError('denied');
|
|
this.#synthetic = structuredClone(syntheticSequences);
|
|
for(const uri of Object.values(this.#synthetic).flat())this.#authorizedMedia.add(uri);
|
|
this.#expectedName = expectedName; this.#expectedProvider = expectedProvider;
|
|
}
|
|
async #read(command, args, messageId = 'adaptive-music-read') {
|
|
try {
|
|
const response = await this.#fetch(`${this.#base}/api`, { method: 'POST', redirect: 'error',
|
|
signal: AbortSignal.timeout(5000), headers: { Authorization: `Bearer ${this.#token}`, 'Content-Type': 'application/json' },
|
|
body: JSON.stringify({ message_id: messageId, command, args }) });
|
|
if (!response.ok) throw new MusicError(response.status === 403 ? 'denied' : 'unavailable');
|
|
const reader = response.body?.getReader();
|
|
if (!reader) return null;
|
|
const chunks = []; let size = 0;
|
|
try {
|
|
while (true) {
|
|
const { value, done } = await reader.read(); if (done) break;
|
|
size += value.byteLength;
|
|
if (size > 1048576) { await reader.cancel(); throw new MusicError('unavailable'); }
|
|
chunks.push(value);
|
|
}
|
|
} finally { reader.releaseLock(); }
|
|
const bytes=new Uint8Array(size);let offset=0;for(const chunk of chunks){bytes.set(chunk,offset);offset+=chunk.length;}
|
|
const body = new TextDecoder().decode(bytes);
|
|
return body ? JSON.parse(body) : null;
|
|
} catch (error) {
|
|
throw new MusicError(error instanceof MusicError ? error.code : 'unavailable');
|
|
}
|
|
}
|
|
async getOwnedQueue(target) {
|
|
if (target !== this.#target) throw new MusicError('denied');
|
|
const queue = await this.#read('player_queues/get', { queue_id: this.#target });
|
|
if (queue?.queue_id !== this.#target || queue.active !== true) throw new MusicError('denied');
|
|
return { state: queue.state, items: queue.items };
|
|
}
|
|
async verifyTarget({allowUnavailable=false}={}) {
|
|
if(!allowUnavailable && this.#expectedName && this.#expectedProvider){
|
|
await this.getOwnedQueue(this.#target);
|
|
const active=await this.#read('player_queues/get_active_queue',{player_id:this.#target});
|
|
if(active?.queue_id!==this.#target)throw new MusicError('denied');
|
|
}
|
|
const player = await this.#read('players/get', { player_id: this.#target });
|
|
if (player?.player_id !== this.#target || !allowUnavailable&&player.available !== true || player.enabled !== true ||
|
|
(this.#expectedName && player.name !== this.#expectedName) ||
|
|
(this.#expectedProvider && player.provider !== this.#expectedProvider) ||
|
|
!player.provider?.startsWith('sendspin') || player.active_group || player.synced_to ||
|
|
['group_members','group_childs','static_group_members'].some(k => !Array.isArray(player[k]) || player[k].some(id => id !== this.#target))) throw new MusicError('denied');
|
|
if(!allowUnavailable&&(!this.#expectedName || !this.#expectedProvider))await this.getOwnedQueue(this.#target);
|
|
this.#targetVolume=Number.isFinite(player.volume_level)&&typeof player.volume_muted==='boolean'?{volume:Math.min(100,Math.max(0,player.volume_level)),muted:player.volume_muted}:null;
|
|
return { dedicated: true, available: player.available===true, standalone: true };
|
|
}
|
|
targetVolumeState(){if(!this.#targetVolume)throw new MusicError('unsupported');return {...this.#targetVolume};}
|
|
async catalog() {
|
|
if (!this.#providers.length) throw new MusicError('denied');
|
|
const next = new Map(); const choices = [];
|
|
// Bounded all-or-nothing pagination; a full final page fails rather than truncating silently.
|
|
for (const [kind, type] of [['playlists','playlist'],['radios','radio']]) {
|
|
let complete = false;
|
|
for (let offset = 0; offset < 5000; offset += 100) {
|
|
const page = await this.#read(`music/${kind}/library_items`, {
|
|
provider: this.#providers, limit: 100, offset, order_by: 'name', summary: false });
|
|
if (!Array.isArray(page) || page.length > 100) throw new MusicError('unavailable');
|
|
for (const item of page) {
|
|
const mapping = Array.isArray(item?.provider_mappings) && [...item.provider_mappings].sort((a,b) => String(a?.provider_instance).localeCompare(String(b?.provider_instance))).find(m => m && this.#providers.includes(m.provider_instance) && m.available === true);
|
|
if (!mapping || item.media_type !== type || item.is_playable !== true ||
|
|
typeof item.name !== 'string' || typeof mapping.item_id !== 'string') continue;
|
|
// Keyed campaign-scoped identity survives restart with the same private key.
|
|
const key = JSON.stringify([type, mapping.provider_instance, mapping.item_id]);
|
|
if (next.has(key)) continue;
|
|
const id = base64url(await hmac(this.#catalogKey,JSON.stringify([this.#campaign,key])));
|
|
next.set(key, { id, type, provider: mapping.provider_instance, itemId: mapping.item_id, dynamic: item.is_dynamic === true });
|
|
choices.push({ provider: 'ma', id, kind: type, name: item.name.replace(/[\x00-\x1f\x7f]/g,'').slice(0,160) });
|
|
}
|
|
if (page.length < 100) { complete = true; break; }
|
|
}
|
|
if (!complete) throw new MusicError('unavailable');
|
|
}
|
|
this.#catalog = next;
|
|
return choices;
|
|
}
|
|
resolveCatalog(ref) {
|
|
if (ref?.provider !== 'ma') throw new MusicError('denied');
|
|
const entry = [...this.#catalog.values()].find(e => e.id === ref.id);
|
|
if (!entry) throw new MusicError('expired-media');
|
|
if(entry.dynamic)throw new MusicError('unsupported');
|
|
const uri=`${entry.provider}://${entry.type}/${entry.itemId}`;this.#authorizedMedia.add(uri);return uri;
|
|
}
|
|
resolveMedia(ref) {
|
|
if (ref?.provider === 'ma' && Object.hasOwn(this.#synthetic,ref.id)) return [...this.#synthetic[ref.id]];
|
|
return [this.resolveCatalog(ref)];
|
|
}
|
|
async prepareMedia(ref) {
|
|
const media=this.resolveMedia(ref);
|
|
if(Object.hasOwn(this.#synthetic,ref.id)) {
|
|
await this.inspectSynthetic(media);
|
|
return media;
|
|
}
|
|
const entry=[...this.#catalog.values()].find(e=>e.id===ref.id);
|
|
if(entry.type==='radio')return media;
|
|
const playlist=await this.#read('music/playlists/get',{item_id:entry.itemId,provider_instance_id_or_domain:entry.provider,allow_update_metadata:false});
|
|
if(playlist?.is_dynamic!==false)throw new MusicError('unsupported');
|
|
const tracks=await this.#read('music/playlists/playlist_tracks',{item_id:entry.itemId,provider_instance_id_or_domain:entry.provider,allow_dynamic_tracks:false});
|
|
if(!Array.isArray(tracks) || !tracks.length || tracks.length>5000)throw new MusicError('unavailable');
|
|
return tracks.map(track=>this.mediaURI({media_item:track}));
|
|
}
|
|
async inspectSynthetic(selected) {
|
|
const approved=Object.values(this.#synthetic).flat();
|
|
const uris=selected??approved;
|
|
if(!Array.isArray(uris) || uris.some(uri=>!approved.includes(uri)))throw new MusicError('denied');
|
|
if(!this.#providers.includes('builtin') || !uris.length)throw new MusicError('denied');
|
|
const result=[];
|
|
for(const uri of uris){
|
|
if(typeof uri!=='string' || !uri.startsWith('builtin://track/http://'))throw new MusicError('denied');
|
|
const track=await this.#read('music/tracks/get',{item_id:uri.slice('builtin://track/'.length),provider_instance_id_or_domain:'builtin',allow_update_metadata:false});
|
|
if(!(track?.duration>=60))throw new MusicError('unavailable');
|
|
result.push({duration:track.duration});
|
|
}
|
|
return result;
|
|
}
|
|
async queueState({allowUnavailable=false}={}) {
|
|
const queue = await this.#read('player_queues/get', {queue_id:this.#target});
|
|
if (queue?.queue_id !== this.#target || !allowUnavailable&&(queue.active !== true || queue.available !== true)) throw new MusicError('denied');
|
|
return queue;
|
|
}
|
|
async queueItems(offset = 0) {
|
|
if (!Number.isSafeInteger(offset) || offset < 0 || offset >= 5000) throw new MusicError('denied');
|
|
const items = await this.#read('player_queues/items', {queue_id:this.#target,limit:100,offset});
|
|
if (!Array.isArray(items) || items.length > 100) throw new MusicError('unavailable');
|
|
return items;
|
|
}
|
|
mediaURI(item) {
|
|
const media = item?.media_item;
|
|
const mapping = Array.isArray(media?.provider_mappings) && media.provider_mappings.find(m => m && this.#providers.includes(m.provider_instance) && m.available === true);
|
|
if (!mapping || !['track','radio'].includes(media.media_type) || typeof mapping.item_id !== 'string') throw new MusicError('unsupported');
|
|
const uri=`${mapping.provider_instance}://${media.media_type}/${mapping.item_id}`;this.#authorizedMedia.add(uri);return uri;
|
|
}
|
|
// Server-only fixed command surface, never a browser route. Target is not an argument.
|
|
async mutate(action, args, ctx) {
|
|
const fields = {stop:[],pause:[],resume:[],clear:[],seek:['position'],shuffle:['shuffle_enabled'],repeat:['repeat_mode'],
|
|
play_index:['index','seek_position'],play_media:['media','option','shuffle']};
|
|
if (!Object.hasOwn(fields,action) || !args || Object.keys(args).some(k => !fields[action].includes(k)) ||
|
|
!this.#expectedName || !this.#expectedProvider || !ctx?.check) throw new MusicError('denied');
|
|
if (action === 'seek' && (!Number.isSafeInteger(args.position) || args.position < 0)) throw new MusicError('denied');
|
|
if (action === 'shuffle' && typeof args.shuffle_enabled !== 'boolean') throw new MusicError('denied');
|
|
if (action === 'repeat' && !['off','one','all'].includes(args.repeat_mode)) throw new MusicError('denied');
|
|
if (action === 'play_index' && (!Number.isSafeInteger(args.index) || args.index < 0 || !Number.isSafeInteger(args.seek_position) || args.seek_position < 0)) throw new MusicError('denied');
|
|
if (action === 'play_media') {
|
|
if (!['replace','add'].includes(args.option) || typeof args.shuffle !== 'boolean' || !Array.isArray(args.media) || !args.media.length || args.media.length > 5000 ||
|
|
args.media.some(uri => typeof uri !== 'string' || !this.#authorizedMedia.has(uri) || !this.#providers.some(p => uri.startsWith(`${p}://track/`) || uri.startsWith(`${p}://playlist/`) || uri.startsWith(`${p}://radio/`)))) throw new MusicError('denied');
|
|
}
|
|
const captured = structuredClone(args);
|
|
const operation = this.#writes.catch(() => {}).then(async () => {
|
|
ctx.check();
|
|
if(this.#uncertain)throw new MusicError('uncertain');
|
|
const queue = await this.queueState();
|
|
if (queue.is_dynamic !== false || queue.autoplay_enabled !== false || queue.dont_stop_the_music_enabled !== false || queue.overlay_enabled !== false || queue.playback_speed !== 1) throw new MusicError('unsupported');
|
|
await this.verifyTarget();
|
|
ctx.check(); // Recheck authority after all reads, immediately before dispatch.
|
|
try{await this.#read(`player_queues/${action}`, {...captured,queue_id:this.#target},`adaptive-music-write-${crypto.randomUUID()}`);}
|
|
catch{this.#uncertain=true;throw new MusicError('uncertain');}
|
|
ctx.check();
|
|
});
|
|
this.#writes = operation;
|
|
return operation;
|
|
}
|
|
|
|
}
|