Adaptive Music v0.8.0 release candidate
Validate and generate manual release / package (push) Waiting to run

This commit is contained in:
Jason committed 2026-12-05 09:40:14 -05:00
1 parent 8c07a468a4
commit 95b0427aa1
48 files changed
+3631 -313

No files matched your search

+1 -1
View File
@@ -166,7 +166,7 @@ export class MAReadClient {
}
// 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'],
const fields = {stop:[],pause:[],resume:[],next:[],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');
+22 -4
View File
@@ -4,14 +4,28 @@ export async function probeWebSockets(baseUrl,{createSocket=url=>new WebSocket(u
const base=new URL(baseUrl);
if(base.username||base.password||base.search||base.hash||base.pathname!=='/'||!['https:','http:'].includes(base.protocol))throw {code:'address-invalid'};
if(globalThis.location?.protocol==='https:'&&base.protocol!=='https:')throw {code:'mixed-content'};
// Permissions are advisory. Browser support and names vary, and "prompt"
// does not establish that this particular destination needs permission.
const permissions={};
for(const name of ['local-network','local-network-access','local-network-devices','loopback-network']){
try{
const state=(await globalThis.navigator?.permissions?.query({name}))?.state;
if(['granted','prompt','denied'].includes(state))permissions[name]=state;
}catch{}
}
const results=[];
// Sequential, bounded and deliberately unauthenticated. No player or queue commands.
for(const path of ['/ws','/sendspin']){
const url=new URL(path,base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
results.push(await new Promise(resolve=>{
let socket,timer,done=false,csp=false;
const finish=code=>{if(done)return;done=true;clearTimeout(timer);events?.removeEventListener('securitypolicyviolation',policy);if(socket){socket.onopen=socket.onerror=socket.onclose=null;socket.close();}resolve({path,code});};
const policy=event=>{if(event.disposition==='enforce'&&['connect-src','default-src'].includes(event.effectiveDirective)&&event.blockedURI===url.href){csp=true;finish('csp-blocked');}};
const finish=code=>{if(done)return;done=true;clearTimeout(timer);events?.removeEventListener('securitypolicyviolation',policy);if(socket){socket.onopen=socket.onerror=socket.onclose=null;socket.close();}resolve({path,code,...(Object.keys(permissions).length&&{permissions})});};
const policy=event=>{
if(event.disposition!=='enforce'||!['connect-src','default-src'].includes(event.effectiveDirective))return;
if(event.blockedURI===url.href||event.blockedURI===url.origin||event.blockedURI===url.origin+'/'){
csp=true;finish('csp-blocked');
}
};
events?.addEventListener('securitypolicyviolation',policy);
timer=setTimeout(()=>finish(csp?'csp-blocked':'upgrade-timeout'),timeoutMs);
try{socket=createSocket(url.href);socket.onopen=()=>finish('upgrade-ok');socket.onerror=()=>setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),25);socket.onclose=()=>setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),25);}catch{setTimeout(()=>finish(csp?'csp-blocked':'upgrade-failed'),50);}
@@ -19,9 +33,13 @@ export async function probeWebSockets(baseUrl,{createSocket=url=>new WebSocket(u
}
return results;
}
export const diagnosticMessage=result=>({
export const diagnosticMessage=result=>{
const hint=result.code!=='upgrade-ok'&&Object.entries(result.permissions??{}).some(([permission,state])=>permission!=='loopback-network'&&state==='denied')
? ' This Foundry site also reports denied local network access. If the proxy is on your private network, review Foundry’s site permission in the browser.' : '';
return ({
'upgrade-ok':'WebSocket upgrade succeeded from this page. Authentication, receiver pairing and audio are still untested.',
'csp-blocked':'This page’s enforced Content Security Policy blocked the connection. Ask the Foundry host administrator to allow the exact trusted MA WSS origin in connect-src; retain existing policy restrictions.',
'upgrade-timeout':'No WebSocket upgrade within 5 seconds. Check the private route and compare from the MA page. Browser APIs cannot identify DNS, TLS or firewall causes.',
'upgrade-failed':'The browser did not expose a successful upgrade. Compare the same check from the MA origin. Check the exact Origin at the reverse proxy and page policy. HTTP status and TLS errors are hidden by browsers; 101 from another client does not prove this path works.'
}[result.code]??'Diagnostic unavailable.');
}[result.code]??'Diagnostic unavailable.')+hint;
};
+13 -7
View File
@@ -21,6 +21,7 @@ export class MAPlaybackProvider {
title: typeof item?.name === 'string' ? item.name.replace(/[\x00-\x1f\x7f]/g, '').slice(0, 180) : '',
duration: Number.isFinite(item?.duration) ? Math.max(0, Math.floor(item.duration)) : 0,
position,
repeat: queue.repeat_mode,
};
}
#check(ctx) {
@@ -41,7 +42,7 @@ export class MAPlaybackProvider {
async #capture(ctx) {
this.#check(ctx);await this.#client.verifyTarget();
const before=await this.#client.queueState();
if (before.shuffle_enabled || before.is_dynamic || before.autoplay_enabled || before.dont_stop_the_music_enabled || before.overlay_enabled || before.playback_speed !== 1 || before.ended) throw new MusicError('unsupported');
if (before.shuffle_enabled || before.is_dynamic || before.autoplay_enabled || before.dont_stop_the_music_enabled || before.overlay_enabled || before.playback_speed !== 1) throw new MusicError('unsupported');
const items=[];
for(let offset=0;offset<5000;offset+=100){this.#check(ctx);const page=await this.#client.queueItems(offset);items.push(...page);if(page.length<100)break;if(offset===4900)throw new MusicError('unsupported');}
const after=await this.#client.queueState();
@@ -50,12 +51,12 @@ export class MAPlaybackProvider {
if (before.items!==items.length || stable(before)!==stable(after) || identity(items)!==identity(again)) throw new MusicError('stale');
if (!['idle','playing','paused'].includes(after.state) || !['off','one','all'].includes(after.repeat_mode) ||
(items.length && (!Number.isSafeInteger(after.current_index) || after.current_index<0 || after.current_index>=items.length))) throw new MusicError('unsupported');
const elapsed=after.state==='playing' ? after.elapsed_time+Math.max(0,Date.now()/1000-after.elapsed_time_last_updated) : after.elapsed_time;
const elapsed=after.ended ? 0 : after.state==='playing' ? after.elapsed_time+Math.max(0,Date.now()/1000-after.elapsed_time_last_updated) : after.elapsed_time;
const position=Math.floor(elapsed ?? 0);
if (!Number.isSafeInteger(position) || position<0 || (position>0 && !(items[after.current_index]?.duration>position))) throw new MusicError('unsupported');
this.#check(ctx);
const value={version:1,campaign:this.#campaign,session:this.#session,fence:this.#fence,generation:ctx.generation,expires:Date.now()+43200000,
state:after.state,repeat:after.repeat_mode,shuffle:false,index:after.current_index,position,
state:after.ended?'idle':after.state,ended:after.ended===true,repeat:after.repeat_mode,shuffle:false,index:after.current_index,position,
items:items.map(item=>({uri:this.#client.mediaURI(item),duration:item.duration ?? 0}))};
if(this.#paused){if(value.state!=='idle'||JSON.stringify(value.items)!==JSON.stringify(this.#paused.items))throw new MusicError('stale');return {...value,state:'paused',index:this.#paused.index,position:this.#paused.position};}
return value;
@@ -72,16 +73,18 @@ export class MAPlaybackProvider {
async stopOwned(ctx) { return this.#once(ctx,`stop:${this.#epoch}`,()=>{this.#paused=undefined;return this.#client.mutate('stop',{},this.#context(ctx));}); }
async control(action,value,ctx) {
this.#check(ctx);
const args={pause:{},resume:{},stop:{},seek:{position:value},shuffle:{shuffle_enabled:value},repeat:{repeat_mode:value}};
const args={pause:{},resume:{},stop:{},next:{},seek:{position:value},shuffle:{shuffle_enabled:value},repeat:{repeat_mode:value}};
if(!Object.hasOwn(args,action))throw new MusicError('denied');
return this.#once(ctx,`control:${action}:${JSON.stringify(value)}`,async()=>{
if(action==='pause'&&this.#client.supportsNativePause?.()===false){
const captured=await this.#capture(ctx);if(!captured.items.length)return;
const captured=await this.#capture(ctx);if(!captured.items.length||captured.ended)return;
await this.#client.mutate('stop',{},this.#context(ctx));this.#paused=captured;
}else if(action==='resume'&&this.#paused){
const captured=await this.#capture(ctx);await this.#client.mutate('play_index',{index:captured.index,seek_position:captured.position},this.#context(ctx));this.#paused=undefined;
}else if(action==='seek'&&this.#paused){
const captured=await this.#capture(ctx);if(!Number.isSafeInteger(value)||value<0||!(captured.items[captured.index]?.duration>value))throw new MusicError('unsupported');this.#paused={...captured,position:value};
}else if(action==='next'&&this.#paused){
throw new MusicError('unsupported');
}else{if(action==='stop')this.#paused=undefined;await this.#client.mutate(action,args[action],this.#context(ctx));}
this.#epoch++;
});
@@ -103,8 +106,11 @@ export class MAPlaybackProvider {
const rebuilt=[];for(let offset=0;offset<value.items.length;offset+=100)rebuilt.push(...await this.#client.queueItems(offset));
if(JSON.stringify(rebuilt.map(i=>this.#client.mediaURI(i)))!==JSON.stringify(value.items.map(i=>i.uri)))throw new MusicError('unsupported');
if(value.state==='paused'&&this.#client.supportsNativePause?.()===false)this.#paused=structuredClone(value);
else{await write('play_index',{index:value.index,seek_position:value.position});if(value.state==='paused')await write('pause',{});}
if(value.state==='idle')await write('stop',{});
else if(!value.ended){
await write('play_index',{index:value.index,seek_position:value.position});
if(value.state==='paused')await write('pause',{});
if(value.state==='idle')await write('stop',{});
}
}
});
}
+1 -1
View File
@@ -1,5 +1,5 @@
import {MusicError} from '../../core/controller.mjs';
const commands=new Set(['sendspin/pair_web_player','providers','players/get','player_queues/get','player_queues/get_active_queue','player_queues/items','music/playlists/library_items','music/radios/library_items','music/playlists/get','music/playlists/playlist_tracks','music/tracks/get',...['play_media','play_index','pause','resume','stop','seek','shuffle','repeat','clear'].map(a=>'player_queues/'+a)]);
const commands=new Set(['sendspin/pair_web_player','providers','players/get','player_queues/get','player_queues/get_active_queue','player_queues/items','music/playlists/library_items','music/radios/library_items','music/playlists/get','music/playlists/playlist_tracks','music/tracks/get',...['play_media','play_index','pause','resume','stop','next','seek','shuffle','repeat','clear'].map(a=>'player_queues/'+a)]);
// GM-local adapter for MA's public /ws API. No HTTP CORS dependency or server proxy.
export class GMMAWebSocket{
#base;#token;#socket;#connect;#pending=new Map();#factory;#closed=false;#authenticated=false;#onDisconnect;
+2 -1
View File
@@ -24,7 +24,7 @@ export class NativeProvider {
return { id: p.id, soundId: sound.id };
}
async snapshot(ctx) {
const playlists = [...this.owned].map(id => {
const playlists = [...this.owned].filter(id=>!this.sceneConflict(id)).map(id => {
const p = this.playlist(id, ctx);
return { id, mode: p.mode, sounds: [...p.sounds].map(s => ({
id: s.id, playing: s.playing, pausedTime: s.playing ? (s.sound?.currentTime ?? 0) : s.pausedTime,
@@ -35,6 +35,7 @@ export class NativeProvider {
}
async stopOwned(ctx) {
for (const id of this.owned) {
if(this.sceneConflict(id))continue;
const p = this.playlist(id, ctx);
const updates = [...p.sounds].filter(s => s.playing).map(s => ({ _id: s.id, playing: false, pausedTime: null }));
if (updates.length) { ctx.check(); await p.updateEmbeddedDocuments('PlaylistSound', updates); }