Release v0.7.2 - Redesigned interface and persistent account settings
Validate and generate manual release / package (push) Canceled after 0s
Validate and generate manual release / package (push) Canceled after 0s
This commit is contained in:
1 parent
1d894f59fb
commit
398749210a
35 files changed
+2807
-256
No files matched your search
+11
-7
@@ -2,7 +2,7 @@ import {MusicError} from '../core/controller.mjs';
|
||||
import {MAReadClient} from '../providers/ma/client.mjs';
|
||||
import {MAPlaybackProvider} from '../providers/ma/provider.mjs';
|
||||
import {GMMAWebSocket} from '../providers/ma/websocket.mjs';
|
||||
import {randomKey} from '../providers/ma/webcrypto.mjs';
|
||||
import {hmac,randomKey} from '../providers/ma/webcrypto.mjs';
|
||||
export function gmAccessPolicy(baseUrl,pageUrl){
|
||||
let target,page;try{target=new URL(baseUrl);page=new URL(pageUrl);}catch{throw new MusicError('address-invalid');}
|
||||
if(target.username||target.password||target.search||target.hash||target.pathname!=='/'||!['http:','https:'].includes(target.protocol))throw new MusicError('denied');
|
||||
@@ -19,7 +19,7 @@ export class GMAudioHost{
|
||||
get session(){return this.#session;}
|
||||
get stream(){return this.#destination?.stream;}
|
||||
get connected(){return this.#live;}
|
||||
supports(ref){return ref?.provider==='ma'&&this.#live&&(this.#allowed.has(ref.id)||this.#catalogPlayback&&this.#catalog.some(c=>c.id===ref.id&&c.kind==='playlist')); }
|
||||
supports(ref){return ref?.provider==='ma'&&this.#live&&(this.#allowed.has(ref.id)||this.#catalogPlayback&&this.#catalog.some(c=>(c.id===ref.id||c.legacyId&&c.legacyId===ref.id)&&c.kind==='playlist')); }
|
||||
async prepare(profile){
|
||||
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
||||
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);this.#phase='API authentication';
|
||||
@@ -64,22 +64,24 @@ export class GMAudioHost{
|
||||
if(!this.#authority()||this.#live)throw new MusicError('denied');if(profile.webSocketAuthLogSafe!==true)throw new MusicError('auth-log-review-required');const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
|
||||
const key=Uint8Array.from(atob(profile.catalogKey),c=>c.charCodeAt(0));if(key.length!==32||!profile.targetName)throw new MusicError('denied');
|
||||
if(!preserveTransport){this.#apiTransport?.close();this.#apiTransport=new GMMAWebSocket({baseUrl:base.origin,token:profile.token,createSocket:this.createSocket});}
|
||||
this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:key,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch});
|
||||
// The same authorized token, world and MA origin can resolve new assignments on another GM device.
|
||||
const portable=profile.portableCatalog&&await hmac(new TextEncoder().encode(profile.token),'adaptive-music portable catalog\0'+JSON.stringify([base.origin,profile.namespace]));
|
||||
this.#client=new MAReadClient({baseUrl:base.origin,token:profile.token,target:profile.target,expectedName:profile.targetName,expectedProvider:profile.expectedProvider,approvedProviders:profile.approvedProviders,catalogKey:portable||key,legacyCatalogKey:portable?key:undefined,campaign:profile.namespace,syntheticSequences:profile.syntheticSequences??{},fetchImpl:this.#apiTransport.fetch});
|
||||
try{await this.#client.verifyTarget({allowUnavailable:reconnecting});this.#catalog=await this.#client.catalog();this.#status='catalog-ready';return this.catalog;}catch(error){await this.close();throw error;}
|
||||
}
|
||||
start(profile){if(this.#starting)return Promise.reject(new MusicError('denied'));this.#starting=true;return this.#start(profile).finally(()=>{this.#starting=false;});}
|
||||
start(profile,{audioContext}={}){if(this.#starting)return Promise.reject(new MusicError('denied'));this.#starting=true;return this.#start(profile,audioContext).finally(()=>{this.#starting=false;});}
|
||||
#connectionLost(epoch,stage){
|
||||
if(epoch!==this.#epoch||!this.#live)return;
|
||||
void this.close();
|
||||
this.#status='connection-lost';this.#phase=stage;
|
||||
this.onDisconnect();
|
||||
}
|
||||
async #start(profile){
|
||||
async #start(profile,audioContext){
|
||||
if(!this.#authority()||this.#live)throw new MusicError('denied');
|
||||
const base=gmAccessPolicy(profile.maUrl,this.pageUrl);
|
||||
if(!profile.targetName||typeof profile.target!=='string'||!profile.identityStorage?.['sendspin-identity-sk']||!Array.isArray(profile.approvedProviders)||!profile.catalogKey||!profile.namespace)throw new MusicError('profile-required');
|
||||
const epoch=this.#epoch,check=()=>{if(epoch!==this.#epoch||!this.#authority())throw new MusicError('stale');};
|
||||
this.#lastError=undefined;this.#attachedQueue=false;this.#context=this.createContext();const unlocked=this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();this.#frames=this.#samples=this.#energy=this.#lastAudio=this.#scheduled=this.#late=this.#ahead=0;
|
||||
this.#lastError=undefined;this.#attachedQueue=false;this.#context=audioContext??this.createContext();const unlocked=audioContext?null:this.#context.resume();this.#destination=this.#context.createMediaStreamDestination();this.#frames=this.#samples=this.#energy=this.#lastAudio=this.#scheduled=this.#late=this.#ahead=0;
|
||||
try{
|
||||
this.#sdk=await this.loadSDK();await unlocked;check();
|
||||
const storage=memoryStorage(profile.identityStorage),identity=this.#sdk.loadSendspinClientIdentity(storage);
|
||||
@@ -106,6 +108,7 @@ export class GMAudioHost{
|
||||
while(!this.#core.timeSyncInfo.synced&&Date.now()<deadline){check();await new Promise(resolve=>setTimeout(resolve,50));}
|
||||
if(!this.#core.timeSyncInfo.synced)throw new MusicError('sendspin-sync-failed');check();
|
||||
if(profile.autoProvision){this.#phase='dedicated receiver verification';Object.assign(profile,await this.inspect(profile,{transport:this.#apiTransport}));check();}
|
||||
this.#phase='catalog retrieval';
|
||||
await this.readCatalog(profile,{reconnecting:true,preserveTransport:true});check();
|
||||
this.#phase='dedicated queue verification';
|
||||
await this.#client.verifyTarget({checkRegistration:check});
|
||||
@@ -119,7 +122,7 @@ export class GMAudioHost{
|
||||
this.#session=crypto.randomUUID();this.#catalogPlayback=profile.allowCatalogPlayback===true;this.#live=true;this.#phase='ready';
|
||||
this.#provider=new MAPlaybackProvider({client:this.#client,campaign:profile.campaign,session:this.#session,fence:1,snapshotKey:randomKey(),authority:()=>{if(!this.#live||!this.#authority())throw new MusicError('stale');}});
|
||||
return {clientIdVerified:true,catalog:this.#catalog.length,codecs:['pcm'],remoteAudio:'webrtc',audioMeasured:false,distributedFencing:false,attachedExistingQueue:this.#attachedQueue};
|
||||
}catch(error){this.#lastError={code:error instanceof MusicError?error.code:'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};if(epoch===this.#epoch)await this.close();throw new MusicError(this.#lastError.code);}
|
||||
}catch(error){this.#lastError={code:error instanceof MusicError?error.code:'unavailable',stage:this.#phase,command:error.command,upstreamCode:error.upstreamCode,translationKey:error.translationKey};if(epoch===this.#epoch)await this.close();throw Object.assign(new MusicError(this.#lastError.code),this.#lastError);}
|
||||
}
|
||||
#authenticatedSocket(base,token,clientId){
|
||||
const url=new URL('/sendspin',base);url.protocol=base.protocol==='https:'?'wss:':'ws:';
|
||||
@@ -161,6 +164,7 @@ export class GMAudioHost{
|
||||
restore(snapshot,ctx){return this.#observe(()=>this.#ready().restore(snapshot,ctx));}
|
||||
stopOwned(ctx){return this.#ready().stopOwned(ctx);}
|
||||
control(action,value,ctx){return this.#observe(()=>this.#ready().control(action,value,ctx));}
|
||||
playbackStatus(){return this.#ready().playbackStatus();}
|
||||
setVolume(value){this.#ready();if(!Number.isFinite(value)||value<0||value>100)throw new MusicError('denied');this.#core.setVolume(Math.round(value));}
|
||||
async close(){this.#epoch++;this.#status='disconnected';this.#catalogPlayback=false;this.#live=false;this.#releaseLock?.();this.#releaseLock=null;this.#clear();this.#core?.disconnect('user_request');this.#socket?.close();this.#core=null;this.#socket=null;this.#provider=null;this.#apiTransport?.close();this.#apiTransport=null;this.#client=null;this.#catalog=[];this.#allowed.clear();for(const track of this.#destination?.stream.getTracks()??[])track.stop();this.#destination=null;this.#meter=null;const context=this.#context;this.#context=null;if(context&&context.state!=='closed')await context.close();}
|
||||
}
|
||||
+24
-2
@@ -25,13 +25,35 @@ export class MusicController {
|
||||
}
|
||||
update(state) {
|
||||
const input = structuredClone(state);
|
||||
const context = this.#nextContext();
|
||||
return this.#enqueue(() => this.transition(input, context));
|
||||
}
|
||||
control(action, value) {
|
||||
if (!['pause', 'resume', 'stop', 'seek'].includes(action) || !this.providers.ma?.control) {
|
||||
return Promise.reject(new MusicError('unsupported'));
|
||||
}
|
||||
const expected = this.generation;
|
||||
return this.#enqueue(() => {
|
||||
if (expected !== this.generation) throw new MusicError('stale');
|
||||
const context = this.#nextContext();
|
||||
context.check();
|
||||
return this.providers.ma.control(action, value, context);
|
||||
});
|
||||
}
|
||||
cancel() {
|
||||
this.generation++;
|
||||
this.abort?.abort();
|
||||
}
|
||||
#nextContext() {
|
||||
const generation = ++this.generation;
|
||||
this.abort?.abort(); this.abort = new AbortController();
|
||||
const context = { campaign: this.campaign, session: this.session, generation,
|
||||
return { campaign: this.campaign, session: this.session, generation,
|
||||
signal: this.abort.signal, check: () => {
|
||||
if (generation !== this.generation || !this.authority()) throw new MusicError('stale');
|
||||
} };
|
||||
const task = this.tail.catch(() => {}).then(() => this.transition(input, context));
|
||||
}
|
||||
#enqueue(operation) {
|
||||
const task = this.tail.catch(() => {}).then(operation);
|
||||
this.tail = task; return task;
|
||||
}
|
||||
async transition(state, ctx) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
import {base64url,hmac} from '../providers/ma/webcrypto.mjs';
|
||||
|
||||
const bytes=new TextEncoder();
|
||||
|
||||
async function key(token,scope){
|
||||
const material=await hmac(bytes.encode(token),'adaptive-music saved connection\0'+scope);
|
||||
return crypto.subtle.importKey('raw',material,'AES-GCM',false,['encrypt','decrypt']);
|
||||
}
|
||||
|
||||
function decode(value){
|
||||
if(typeof value!=='string'||!/^[A-Za-z0-9_-]+$/.test(value))throw new MusicError('saved-connection-unavailable');
|
||||
return Uint8Array.from(atob(value.replace(/-/g,'+').replace(/_/g,'/')),char=>char.charCodeAt(0));
|
||||
}
|
||||
|
||||
export async function sealAccountConnection({maUrl,targetName},token,scope){
|
||||
const iv=crypto.getRandomValues(new Uint8Array(12));
|
||||
const content=bytes.encode(JSON.stringify({maUrl,targetName}));
|
||||
if(content.length>2048)throw new MusicError('saved-connection-too-large');
|
||||
const cipher=await crypto.subtle.encrypt({name:'AES-GCM',iv,additionalData:bytes.encode(scope)},await key(token,scope),content);
|
||||
return {version:1,iv:base64url(iv),cipher:base64url(new Uint8Array(cipher))};
|
||||
}
|
||||
|
||||
export async function openAccountConnection(saved,token,scope){
|
||||
try{
|
||||
if(saved?.version!==1||saved.iv?.length!==16||!saved.cipher||saved.cipher.length>2800)throw Error();
|
||||
const content=await crypto.subtle.decrypt({name:'AES-GCM',iv:decode(saved.iv),additionalData:bytes.encode(scope)},await key(token,scope),decode(saved.cipher));
|
||||
const {maUrl,targetName}=JSON.parse(new TextDecoder().decode(content));
|
||||
if(typeof maUrl!=='string'||typeof targetName!=='string')throw Error();
|
||||
return {maUrl,targetName};
|
||||
}catch{throw new MusicError('saved-connection-unavailable');}
|
||||
}
|
||||
@@ -1,11 +1,18 @@
|
||||
import {gmAccessPolicy} from '../audio/gm-host.mjs';
|
||||
import {validateIceServers} from '../audio/peer-audio.mjs';
|
||||
import {probeWebSockets,diagnosticMessage} from '../providers/ma/diagnostics.mjs';
|
||||
const messages={
|
||||
'saved-connection-unavailable':'This token could not unlock the saved connection. Enter the server address and a valid token to save a new connection.',
|
||||
'saved-connection-write-failed':'Connected, but Foundry could not save the connection for this account.',
|
||||
'ice-config-invalid':'Enter a valid existing STUN/TURN URL. TURN also needs a username, credential and UTC expiry within one hour. No network setting was applied.',
|
||||
'token-required':'Enter a Music Assistant access token for this server.',
|
||||
'token-invalid':'Remove line breaks from the access token and try again.',
|
||||
'receiver-name-invalid':'Use at most 120 characters for the receiver name, without line breaks.',
|
||||
'automation-disabled':'Enable automation before applying a manual playlist override.',
|
||||
'address-invalid':'Enter the MA server origin, such as https://ma.example.test, without a path or query.',
|
||||
'ws-upgrade-failed':'The browser could not open the API WebSocket. Run Check browser connection below. If it works from MA’s page only, compare this browser’s local-network permission, private DNS and site restrictions.',
|
||||
'ws-auth-timeout':'The API socket opened, but authentication did not finish. Check that /ws reaches MA rather than a login portal.',
|
||||
'ws-auth-denied':'MA rejected the token. Enter a replacement and Authenticate again; the receiver is remembered.',
|
||||
'ws-auth-denied':'MA rejected the token. Enter a replacement and select Connect again; the receiver is remembered.',
|
||||
'ws-disconnected':'The API socket closed. Your private inputs remain in this tab. Retry after checking the private route.',
|
||||
'ws-command-timeout':'MA did not answer a command before its deadline. Catalog reads have a 10-second limit; stream startup has a 60-second limit. Unconfirmed queue writes stop automation for review.',
|
||||
'ws-command-failed':'MA rejected a command. The account needs music-provider access and permission to control and pair its dedicated web receiver.',
|
||||
@@ -27,64 +34,141 @@ const messages={
|
||||
'unavailable':'The operation failed. Your private inputs are retained. Run the browser connection check to separate transport failures from receiver and audio setup.'
|
||||
};
|
||||
export const connectionMessage=error=>error?.upstreamCode===2&&['player_queues/play_media','player_queues/play_index'].includes(error.command)?'MA could not find playable media for this playlist (MA error 2). Check its content/provider in MA or choose another playlist. Automation stopped; an unconfirmed queue write is never retried.':messages[error?.code]??messages.unavailable;
|
||||
export function mountConnectionWizard({game,container,connection,onCatalog=()=>{},onError=()=>{}}){
|
||||
const dom=container.ownerDocument,panel=dom.createElement('fieldset'),legend=dom.createElement('legend');legend.textContent='1. Music Assistant';panel.append(legend);
|
||||
const note=dom.createElement('p');note.textContent='Enter your server and access token. A dedicated campaign receiver is created and paired automatically. The token stays in this GM tab; its receiver identity is remembered privately in this browser.';panel.append(note);
|
||||
const status=dom.createElement('p');status.setAttribute('role','status');panel.append(status);
|
||||
const steps=Array.from({length:2},()=>{const step=dom.createElement('div');step.className='adaptive-music-step';panel.append(step);return step;});
|
||||
const go=index=>steps.forEach((step,i)=>{step.hidden=i!==index;});
|
||||
const field=(parent,label,type='text')=>{const l=dom.createElement('label');l.textContent=label;const input=dom.createElement('input');input.type=type;input.autocomplete='off';input.spellcheck=false;l.append(input);parent.append(l);return input;};
|
||||
const button=(parent,label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw {code:'denied'};await action();}catch(error){status.textContent=connectionMessage(error);onError(error);}finally{b.disabled=false;show();}});parent.append(b);return b;};
|
||||
const draft=connection.draftFields??{},address=field(steps[0],'Music Assistant server address','url');address.placeholder='https://ma.example.test';address.value=draft.maUrl??'';
|
||||
const token=field(steps[0],'Private GM access token','password');
|
||||
const advanced=dom.createElement('details'),summary=dom.createElement('summary');summary.textContent='Receiver options';advanced.append(summary);steps[0].append(advanced);
|
||||
const name=field(advanced,'Dedicated receiver name');name.value=draft.targetName??'Adaptive Music '+(game.world?.title??'campaign');
|
||||
const iceURL=field(advanced,'Existing ICE server URL (optional)');iceURL.placeholder='stun:stun.example.test:3478';
|
||||
const iceUsername=field(advanced,'TURN username (if required)'),iceCredential=field(advanced,'Short-lived TURN credential','password'),iceExpiry=field(advanced,'TURN credential expiry (UTC)','datetime-local');
|
||||
const networkNote=dom.createElement('p');networkNote.textContent='Direct connections use no external ICE service. For remote players, you may supply an existing STUN/TURN service. TURN credentials must expire within one hour; no service is installed.';advanced.append(networkNote);
|
||||
const logging=dom.createElement('p');logging.textContent='Keep MA raw-frame VERBOSE logging disabled: it can record authentication frames. No server logging settings are changed by this module.';advanced.append(logging);
|
||||
button(steps[0],'Authenticate',async()=>{
|
||||
if(!address.value.trim())throw {code:'address-invalid'};status.textContent='Authenticating with Music Assistant…';
|
||||
const network={};
|
||||
if(iceURL.value.trim()){
|
||||
const server={urls:iceURL.value.trim()};
|
||||
if(/^turns?:/.test(server.urls)){server.username=iceUsername.value.trim();server.credential=iceCredential.value;server.expires=Date.parse(iceExpiry.value+'Z');}
|
||||
try{validateIceServers([server]);}catch{throw {code:'ice-config-invalid'};}network.listenerNetwork={iceServers:[server]};
|
||||
}
|
||||
let result;try{result=await connection.test({maUrl:address.value.trim(),token:token.value,targetName:name.value.trim(),allowCatalogPlayback:true,webSocketAuthLogSafe:true,...network});}
|
||||
finally{if(connection.status.hasPrivateDraft){token.value='';}}
|
||||
token.value='';setTarget(result.target,result.targetName);go(1);connect.disabled=false;
|
||||
status.textContent='Authenticated. Connect this dedicated campaign receiver to pair it and load your playlists.';
|
||||
});
|
||||
const target=dom.createElement('select'),label=dom.createElement('label');label.textContent='Dedicated campaign receiver';label.append(target);steps[1].append(label);
|
||||
const setTarget=(id,name)=>{target.replaceChildren();const option=dom.createElement('option');option.value=id;option.textContent=name;target.append(option);target.value=id;};
|
||||
const connect=button(steps[1],'Connect audio',async()=>{
|
||||
status.textContent='Connecting and pairing the dedicated receiver…';
|
||||
const result=await connection.connect(target.value);await onCatalog();status.textContent=result?.attachedExistingQueue?'Campaign audio reconnected. The existing queue was preserved. Apply the automation setting below when ready to resume scene control.':'Campaign audio connected. Assign ambient and combat playlists below, then enable automation. Players connect automatically.';
|
||||
});
|
||||
button(steps[1],'Enable GM audio',()=>connection.resume());
|
||||
const volume=field(steps[1],'Campaign volume','range');volume.min='0';volume.max='100';volume.value=String(connection.status.volume??100);volume.addEventListener('change',()=>{try{connection.setVolume?.(Number(volume.value));}catch(error){status.textContent=connectionMessage(error);onError(error);}});
|
||||
button(steps[1],'Refresh playlists',async()=>{await connection.refresh();await onCatalog();status.textContent='Playlists refreshed.';});
|
||||
button(steps[1],'Back to authentication',()=>go(0));
|
||||
const diagnostics=dom.createElement('p');diagnostics.setAttribute('role','status');panel.append(diagnostics);
|
||||
const report=dom.createElement('div');report.setAttribute('aria-live','polite');panel.append(report);let transportResults=[];
|
||||
button(panel,'Check browser connection (no MA token)',async()=>{
|
||||
report.replaceChildren();status.textContent='Checking both WebSocket routes from this Foundry page…';
|
||||
try{transportResults=await probeWebSockets(address.value.trim());}catch(error){throw error?.code?error:{code:'address-invalid'};}
|
||||
for(const result of transportResults){const line=dom.createElement('p');line.textContent=result.path+': '+diagnosticMessage(result);report.append(line);}
|
||||
status.textContent='Browser checks complete. No MA token was sent. An open socket still needs authentication, pairing and clock synchronization.';
|
||||
});
|
||||
button(panel,'Copy connection diagnostics',async()=>{
|
||||
const d=connection.status;const text=JSON.stringify({state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2);
|
||||
await navigator.clipboard.writeText(text);status.textContent='Diagnostics copied. The report excludes the address, token, receiver identity and catalog titles.';
|
||||
});
|
||||
button(panel,'Disconnect Music Assistant',async()=>{await connection.disconnect();token.value='';iceCredential.value='';target.replaceChildren();go(0);status.textContent='Disconnected. The token was forgotten; this browser remembers its campaign receiver.';await onCatalog();});
|
||||
const recovery=dom.createElement('details'),recoveryTitle=dom.createElement('summary');recoveryTitle.textContent='Connection recovery';recovery.append(recoveryTitle);panel.append(recovery);
|
||||
button(recovery,'Reconnect remembered receiver',async()=>{await connection.reconnect();await onCatalog();status.textContent='Receiver reconnected using retained private inputs. The queue was preserved and automation is paused. Review it, then Apply automation setting when ready.';});
|
||||
button(recovery,'Forget remembered receiver',async()=>{await (connection.forgetReceiver?.()??connection.disconnect());token.value='';iceCredential.value='';target.replaceChildren();go(0);status.textContent='Local receiver identity forgotten. Reauthenticate to provision a new receiver. Existing MA queues were left untouched.';await onCatalog();});
|
||||
const show=()=>{const d=connection.status;volume.disabled=d.state!=='connected';if(d.hasPrivateDraft)token.placeholder='Retained in this tab; leave blank to retry';connect.disabled=d.state==='connected'||d.state==='connecting';diagnostics.textContent=`${d.state}. ${d.stage??''} Playlists: ${d.catalog??0}. GM audio: ${d.audioContext??'closed'}. Decoded frames: ${d.decodedFrames??0}. Connected listeners: ${d.peers??0}.`;};
|
||||
const d=connection.status;if(d.selectedTarget){setTarget(d.selectedTarget,d.selectedName);go(1);}else go(0);show();container.append(panel);
|
||||
// Refresh while the actual ApplicationV2 window is mounted; no secret-bearing events.
|
||||
if(globalThis.document===dom&&typeof panel.isConnected==='boolean'){const timer=setInterval(()=>{if(!panel.isConnected){clearInterval(timer);return;}show();},1000);}
|
||||
return panel;
|
||||
|
||||
function failureStage(error) {
|
||||
if (['ws-upgrade-failed', 'ws-disconnected', 'mixed-content', 'insecure-context'].includes(error?.code)) return 'Connection failed';
|
||||
if (['ws-auth-denied', 'ws-auth-timeout'].includes(error?.code) || error?.stage === 'API authentication') return 'Authentication failed';
|
||||
if (['receiver pairing','dedicated receiver verification','dedicated queue verification','Noise handshake'].includes(error?.stage) || error?.code === 'sendspin-sync-failed') return 'Receiver setup failed';
|
||||
if (error?.stage === 'Sendspin authentication' || error?.code === 'sendspin-auth-failed') return 'Receiver connection failed';
|
||||
if (error?.stage === 'catalog retrieval' || error?.code === 'catalog-empty') return 'Playlist catalog unavailable';
|
||||
return 'Setup failed';
|
||||
}
|
||||
|
||||
function iceConfiguration(fields) {
|
||||
const {url, username, credential, expires} = fields;
|
||||
if (!url && !username && !credential && !expires) return undefined;
|
||||
const scheme = url.match(/^(stun|stuns|turn|turns):/i)?.[1].toLowerCase();
|
||||
const target = scheme && URL.canParse(`https://${url.slice(scheme.length + 1)}`) && new URL(`https://${url.slice(scheme.length + 1)}`);
|
||||
const turn = scheme?.startsWith('turn');
|
||||
if (!target || !target.hostname || target.username || target.password || target.pathname !== '/' || target.hash ||
|
||||
/[\s/]/.test(url) || (target.search && !(turn && /^\?transport=(udp|tcp)$/.test(target.search))) ||
|
||||
(!turn && (username || credential || expires))) throw {code:'ice-config-invalid'};
|
||||
const server = {urls:url, ...(turn ? {username, credential, expires:Date.parse(expires + 'Z')} : {})};
|
||||
try{validateIceServers([server]);}
|
||||
catch{throw {code:'ice-config-invalid'};}
|
||||
return {iceServers:[server]};
|
||||
}
|
||||
|
||||
export function mountConnectionWizard({game,container,connection,onCatalog=()=>{},onError=()=>{},next,advancedContent}) {
|
||||
const dom=container.ownerDocument;
|
||||
const make=(tag,text,parent=container)=>{
|
||||
const node=dom.createElement(tag);
|
||||
if(text)node.textContent=text;
|
||||
parent.append(node);
|
||||
return node;
|
||||
};
|
||||
const input=(parent,label,type='text')=>{
|
||||
const wrapper=make('label',label,parent),field=make('input',null,wrapper);
|
||||
field.type=type;field.autocomplete='off';field.spellcheck=false;
|
||||
return field;
|
||||
};
|
||||
const initial=connection.draftFields??{};
|
||||
make('h2','Connect Music Assistant');
|
||||
make('p','Enter your Music Assistant address and access token. Adaptive Music creates or reconnects your campaign receiver and loads your playlists.');
|
||||
if(initial.savedConnection)make('p','This Foundry account has a saved connection. Enter its access token to unlock the address, or enter a different address to replace it.');
|
||||
const fields=make('div');fields.className='adaptive-fields';
|
||||
const address=input(fields,'Music Assistant server address','url');address.placeholder='https://ma.example.test';address.value=initial.maUrl??'';
|
||||
const token=input(fields,'Private GM access token','password');
|
||||
const retainError=make('p');retainError.setAttribute('role','alert');retainError.hidden=true;
|
||||
const actions=make('div');actions.className='adaptive-actions';
|
||||
const state=make('p');state.className='adaptive-state';
|
||||
const status=make('p');status.setAttribute('role','status');
|
||||
const advanced=make('details');make('summary','Advanced',advanced);
|
||||
const advancedFields=make('div',null,advanced);advancedFields.className='adaptive-fields';
|
||||
const name=input(advancedFields,'Dedicated receiver name');name.value=initial.targetName??'';name.placeholder='Adaptive Music '+(game.world?.title??'campaign');
|
||||
const iceURL=input(advancedFields,'ICE server URL');iceURL.placeholder='stun:stun.example.test:3478';
|
||||
const iceUsername=input(advancedFields,'TURN username'),iceCredential=input(advancedFields,'TURN credential','password');
|
||||
const iceExpiry=input(advancedFields,'TURN credential expiry (UTC)','datetime-local');
|
||||
const diagnosticsActions=make('div');diagnosticsActions.className='adaptive-actions';
|
||||
const report=make('div');report.setAttribute('aria-live','polite');
|
||||
let transportResults=[],busy=false;
|
||||
const run=async(action,label)=>{
|
||||
if(busy||!game.user.isGM)return;
|
||||
busy=true;retainError.hidden=true;render();
|
||||
try{await action();}
|
||||
catch(error){
|
||||
busy=false;render();error.field?.focus?.();
|
||||
retainError.textContent=`${typeof label==='function'?label(error):label}. ${connectionMessage(error)}`;retainError.hidden=false;onError(error);
|
||||
}finally{busy=false;render();}
|
||||
};
|
||||
const button=(parent,label,action)=>{
|
||||
const b=make('button',label,parent);b.type='button';b.addEventListener('click',action);return b;
|
||||
};
|
||||
const pageUrl=()=>dom.location?.href??globalThis.location?.href??'https://foundry.invalid';
|
||||
function validatedAddress(){
|
||||
try{return gmAccessPolicy(address.value.trim(),pageUrl()).origin;}
|
||||
catch(error){if(error.code==='denied')throw {code:'address-invalid'};throw error;}
|
||||
}
|
||||
function retainedToken(){
|
||||
const draft=connection.draftFields??{};
|
||||
try{return draft.retainedToken===true&&new URL(draft.maUrl).origin===validatedAddress();}
|
||||
catch{return false;}
|
||||
}
|
||||
const connect=button(actions,'Connect',()=>run(async()=>{
|
||||
let maUrl;
|
||||
const useSaved=!address.value.trim()&&connection.draftFields?.savedConnection;
|
||||
if(!useSaved)try{maUrl=validatedAddress();}catch(error){throw {code:error.code,field:address};}
|
||||
if(!token.value.trim()&&(useSaved||!retainedToken()))throw {code:'token-required',field:token};
|
||||
if(/[\r\n]/.test(token.value))throw {code:'token-invalid',field:token};
|
||||
const targetName=name.value.trim();
|
||||
if(targetName.length>120||/[\x00-\x1f\x7f]/.test(name.value)){advanced.open=true;throw {code:'receiver-name-invalid',field:name};}
|
||||
let listenerNetwork;
|
||||
try{listenerNetwork=iceConfiguration({url:iceURL.value.trim(),username:iceUsername.value.trim(),credential:iceCredential.value,expires:iceExpiry.value});}
|
||||
catch{advanced.open=true;throw {code:'ice-config-invalid',field:iceURL};}
|
||||
status.textContent='Contacting Music Assistant…';
|
||||
let result;
|
||||
try{result=await connection.open({maUrl,token:token.value.trim(),...(targetName&&{targetName}),...(listenerNetwork&&{listenerNetwork})});}
|
||||
finally{if(connection.status.hasPrivateDraft){token.value='';iceCredential.value='';}}
|
||||
address.value=connection.draftFields?.maUrl??address.value;
|
||||
await onCatalog();
|
||||
status.textContent=result?.attachedExistingQueue?'Connected. The existing queue is preserved. Enable automation from Playback when you’re ready.':'Campaign audio connected. Choose playlists for your scene.';
|
||||
},error=>['address-invalid','token-invalid','token-required','receiver-name-invalid','ice-config-invalid'].includes(error.code)?'Check your settings':failureStage(error)));
|
||||
connect.className='adaptive-primary';
|
||||
const nextButton=button(actions,'Choose scene music',()=>next?.());
|
||||
const disconnect=button(actions,'Disconnect',()=>run(async()=>{
|
||||
await connection.disconnect();token.value='';iceCredential.value='';status.textContent='Disconnected. The receiver is remembered for next time.';await onCatalog();
|
||||
},'Disconnect failed'));
|
||||
button(diagnosticsActions,'Check browser connection',()=>run(async()=>{
|
||||
report.replaceChildren();transportResults=await probeWebSockets(validatedAddress());
|
||||
for(const result of transportResults)make('p',`${result.path} — ${diagnosticMessage(result)}`,report);
|
||||
status.textContent='Browser checks complete.';
|
||||
},'Browser connection check failed'));
|
||||
button(diagnosticsActions,'Copy connection diagnostics',()=>run(async()=>{
|
||||
const d=connection.status;
|
||||
await navigator.clipboard.writeText(JSON.stringify({state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,outputRMS:d.outputRMS,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2));
|
||||
status.textContent='Connection diagnostics copied.';
|
||||
},'Could not copy diagnostics'));
|
||||
const advancedActions=make('div',null,advanced);advancedActions.className='adaptive-actions';
|
||||
const refresh=button(advancedActions,'Refresh playlists',()=>run(async()=>{await connection.refresh();await onCatalog();status.textContent='Playlists refreshed.';},'Catalog refresh failed'));
|
||||
const forget=button(advancedActions,'Forget saved connection',()=>run(async()=>{
|
||||
await connection.forgetReceiver();address.value='';token.value='';iceCredential.value='';name.value='';status.textContent='Saved connection removed from this account.';await onCatalog();
|
||||
},'Could not forget the connection'));
|
||||
if(advancedContent)advanced.append(advancedContent);
|
||||
function render(){
|
||||
const d=connection.status,connected=d.state==='connected';
|
||||
const label=connected?'Connected':busy?'Working':d.state==='connection-lost'?'Connection lost':'Disconnected';
|
||||
const summary=connected?`${label} · ${d.catalog??0} catalog choices`:
|
||||
busy&&d.stage&&d.stage!=='idle'?`${label} · ${d.stage}`:label;
|
||||
if(state.textContent!==summary)state.textContent=summary;
|
||||
state.dataset.connected=String(connected);
|
||||
connect.hidden=connected;connect.disabled=busy;connect.textContent=busy?'Connecting…':'Connect';
|
||||
disconnect.hidden=!connected;disconnect.disabled=busy;
|
||||
nextButton.hidden=!connected||!next;nextButton.disabled=busy;refresh.hidden=!connected;
|
||||
forget.disabled=busy||(!d.hasPrivateDraft&&!connection.draftFields?.savedConnection);
|
||||
for(const field of [address,token,name,iceURL,iceUsername,iceCredential,iceExpiry])field.disabled=connected||busy;
|
||||
token.placeholder=retainedToken()?'Retained for this address':'Paste your access token';
|
||||
}
|
||||
address.addEventListener('input',render);
|
||||
render();
|
||||
return render;
|
||||
}
|
||||
+82
-13
@@ -4,26 +4,39 @@ import {connectionDraft} from './connection-draft.mjs';
|
||||
import {startNativeRuntime,primaryGM} from './runtime.mjs';
|
||||
import {startConfigurationInterfaces,mountPlaylistConfiguration} from './configuration.mjs';
|
||||
import {GatewayClient} from '../providers/ma/remote.mjs';
|
||||
import {GMAudioHost} from '../audio/gm-host.mjs';
|
||||
import {GMAudioHost,gmAccessPolicy} from '../audio/gm-host.mjs';
|
||||
import {AutoListeners} from '../audio/auto-listeners.mjs';
|
||||
import {PeerAudio} from '../audio/peer-audio.mjs';
|
||||
import {ListenerAudio} from './listener-audio.mjs';
|
||||
import {createSetupClass,createListenerClass} from './setup.mjs';
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
import {openAccountConnection,sealAccountConnection} from './account-connection.mjs';
|
||||
const id='adaptive-music';
|
||||
const receiverVault=new ReceiverVault();
|
||||
const receiverScope=profile=>({campaign:game.world.id,userId:game.user.id,maUrl:profile.maUrl});
|
||||
const accountScope=()=>JSON.stringify([location.origin,game.world.id,game.user.id]);
|
||||
const savedConnection=()=>game.settings.get(id,'savedConnection');
|
||||
let runtime,interfaces,gateway,audio,renewTimer,gmHost,peers,remoteAudio;let authorityHooks=[];let bootstrap,privateProfile,privateDraft,inviteTimer,latestInvite,listenerStopped=false,listenerState='Waiting for GM audio.',inviteTail=Promise.resolve();const sentInvites=new Map();let connectionGeneration=0,connectionTesting=false;let listenerContext,listenerSource;
|
||||
let automationRunning=false,previousController;
|
||||
const gmAuthority=()=>game.ready&&game.user.isGM&&primaryGM(game.users)===game.user.id&&[...game.users].filter(u=>u.active&&u.isGM).length===1&&game.socket?.connected===true;
|
||||
const owned=()=>game.settings.get(id,'ownedPlaylistIds').split(',').map(s=>s.trim()).filter(Boolean);
|
||||
const choices=async()=>[...[...game.playlists].filter(p=>owned().includes(p.id)).map(p=>({provider:'native',id:p.id,name:p.name})),...(gmHost?.catalog.length?gmHost.catalog.filter(c=>c.kind==='playlist'||c.kind==='sequence'):gateway?.catalog??[])];
|
||||
const onError=error=>{if(error?.code==='uncertain')stop();ui.notifications.warn('Adaptive Music: '+connectionMessage(error));};
|
||||
function start(){
|
||||
if(!game.user.isGM||runtime)return;
|
||||
runtime=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,onError});
|
||||
runtime.refresh().catch(onError);
|
||||
function ensureRuntime(){
|
||||
runtime??=startNativeRuntime({game,Hooks,campaign:game.world.id,session:gmHost?.connected?gmHost.session:globalThis.crypto.randomUUID(),ownedPlaylistIds:owned(),maProvider:gmHost?.connected?gmHost:gateway,
|
||||
isEnabled:()=>automationRunning,authority:gmAuthority,previousController,onError});
|
||||
return runtime;
|
||||
}
|
||||
function stop(){runtime?.dispose();runtime=null;}
|
||||
function setOverrides(value){if(!runtime)throw Error('Automation is disabled');return runtime.setOverrides(value);}
|
||||
function start(){
|
||||
if(!gmAuthority()||automationRunning)return;
|
||||
automationRunning=true;
|
||||
return ensureRuntime().refresh().catch(onError);
|
||||
}
|
||||
function stop(){
|
||||
automationRunning=false;
|
||||
if(runtime){runtime.dispose();previousController=runtime.controller;runtime=null;}
|
||||
}
|
||||
function setOverrides(value){if(!automationRunning)throw new MusicError('automation-disabled');return runtime.setOverrides(value);}
|
||||
function ensureRemoteAudio(){if(!remoteAudio){remoteAudio=document.createElement('audio');remoteAudio.autoplay=true;document.body.append(remoteAudio);}return remoteAudio;}
|
||||
function attachListenerSource(stream){listenerSource?.disconnect();if(listenerContext){listenerSource=listenerContext.createMediaStreamSource(stream);listenerSource.connect(listenerContext.destination);remoteAudio.muted=true;}}
|
||||
function resumeListener(){if(game.user.isGM)return gmHost.resumeAudio();listenerStopped=false;const element=ensureRemoteAudio();let resumed=Promise.resolve();if(globalThis.AudioContext){listenerContext??=new AudioContext();resumed=listenerContext.resume();if(element.srcObject)attachListenerSource(element.srcObject);}const play=element.play();play.catch(()=>{});if(!peers.diagnostics().peers.length)bootstrap?.start().catch(onError);return resumed.then(()=>{listenerState=element.srcObject?'Campaign audio enabled.':'Audio enabled. Waiting for GM audio.';});}
|
||||
@@ -38,8 +51,28 @@ function sendInvites(){
|
||||
});return inviteTail;
|
||||
}
|
||||
const connection={
|
||||
get draftFields(){return privateDraft?{maUrl:privateDraft.maUrl,targetName:privateDraft.targetName,webSocketAuthLogSafe:privateDraft.webSocketAuthLogSafe,allowCatalogPlayback:privateDraft.allowCatalogPlayback}:{};},
|
||||
get status(){return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),hasPrivateDraft:!!privateDraft,selectedTarget:privateProfile?.target,selectedName:privateProfile?.targetName,listenerDiagnostics:peers?.diagnostics(),peers:peers?.diagnostics().peers.filter(p=>p.connection==='connected').length??0};},
|
||||
get draftFields(){return {maUrl:privateDraft?.maUrl,targetName:privateDraft?.targetName,retainedToken:!!privateDraft?.token,savedConnection:savedConnection()?.version===1};},
|
||||
get status(){const listeners=peers?.diagnostics();return {...(gmHost?.status??{state:'disconnected',catalog:0,audioContext:'closed'}),hasPrivateDraft:!!privateDraft,selectedName:privateProfile?.targetName,listenerDiagnostics:listeners,peers:listeners?.peers.filter(p=>p.connection==='connected').length??0,automationRunning};},
|
||||
async open(profile){
|
||||
if(!gmAuthority()||connectionTesting||gmHost.connected||gateway.connected)throw new MusicError('denied');
|
||||
// Claim browser audio activation before authentication performs asynchronous work.
|
||||
const audioContext=gmHost.createContext();
|
||||
const generation=connectionGeneration;
|
||||
try{
|
||||
void audioContext.resume().catch(()=>{});
|
||||
if(!profile.maUrl){
|
||||
const remembered=await openAccountConnection(savedConnection(),profile.token,accountScope());
|
||||
gmAccessPolicy(remembered.maUrl,location.href);
|
||||
profile={...profile,maUrl:remembered.maUrl,targetName:profile.targetName??remembered.targetName};
|
||||
}
|
||||
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||
const {target}=await connection.test(profile);
|
||||
return await connection.connect(target,{audioContext});
|
||||
}catch(error){
|
||||
if(audioContext.state!=='closed')await audioContext.close();
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
async test(profile){
|
||||
if(connectionTesting||gmHost.connected||gmHost.status.state==='connecting'||gateway.connected)throw {code:'denied'};
|
||||
connectionTesting=true;stop();const generation=++connectionGeneration;privateProfile=null;
|
||||
@@ -48,16 +81,51 @@ const connection={
|
||||
await gmHost.close();check();
|
||||
const candidate=connectionDraft(privateDraft,profile,game.world.id);privateDraft=candidate;
|
||||
if(!candidate.identityStorage?.['sendspin-identity-sk'])Object.assign(candidate,await receiverVault.load(receiverScope(candidate))??{});check();
|
||||
candidate.targetName??='Adaptive Music '+game.world.title;candidate.allowCatalogPlayback=true;
|
||||
candidate.targetName??='Adaptive Music '+game.world.title;candidate.allowCatalogPlayback=true;candidate.portableCatalog=true;
|
||||
const result=await gmHost.prepare(candidate);check();
|
||||
await receiverVault.save(receiverScope(result),result);check();
|
||||
privateProfile=result;privateDraft=result;return {target:result.target,targetName:result.targetName};
|
||||
}finally{connectionTesting=false;}
|
||||
}catch(error){error.stage??='API authentication';throw error;}
|
||||
finally{connectionTesting=false;}
|
||||
},
|
||||
async connect(target,{resumeAutomation=true,audioContext}={}){
|
||||
if(!privateProfile||target!==privateProfile.target||gateway.connected)throw new MusicError('denied');
|
||||
stop();const profile=privateProfile,generation=connectionGeneration;
|
||||
let result;
|
||||
try{result=await gmHost.start(profile,{audioContext});}
|
||||
finally{if(generation===connectionGeneration)await receiverVault.save(receiverScope(profile),profile);}
|
||||
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||
try{
|
||||
const saved=await sealAccountConnection(profile,profile.token,accountScope());
|
||||
if(generation===connectionGeneration)await game.settings.set(id,'savedConnection',saved);
|
||||
}catch{onError(new MusicError('saved-connection-write-failed'));}
|
||||
if(generation!==connectionGeneration||!gmAuthority())throw new MusicError('stale');
|
||||
peers.setSource(gmHost.stream);sentInvites.clear();await sendInvites();
|
||||
if(resumeAutomation&&game.settings.get(id,'enabled')&&!result.attachedExistingQueue)start();
|
||||
return result;
|
||||
},
|
||||
async connect(target,{resumeAutomation=true}={}){if(!privateProfile||target!==privateProfile.target||gateway.connected)throw {code:'denied'};stop();const pending=gmHost.start(privateProfile);let result;try{result=await pending;}finally{if(privateProfile)await receiverVault.save(receiverScope(privateProfile),privateProfile);}peers.setSource(gmHost.stream);sentInvites.clear();await sendInvites();if(resumeAutomation&&game.settings.get(id,'enabled')&&!result.attachedExistingQueue)start();return result;},
|
||||
async reconnect(){if(!privateProfile||!gmAuthority())throw {code:'denied'};const generation=++connectionGeneration;stop();peers?.reset();sentInvites.clear();await gmHost.close();if(generation!==connectionGeneration)throw {code:'stale'};return connection.connect(privateProfile.target,{resumeAutomation:false});},
|
||||
refresh:()=>gmHost.refreshCatalog(),resume:()=>gmHost.resumeAudio(),setVolume:value=>gmHost.setVolume(value),
|
||||
async forgetReceiver(){if(privateDraft){const scope=receiverScope(privateDraft);await connection.disconnect();await receiverVault.forget(scope);}},
|
||||
async playback(){
|
||||
if(!gmAuthority())throw new MusicError('denied');
|
||||
const current=runtime?.controller.current?.playlist;
|
||||
if(current?.provider==='native'){
|
||||
const sound=[...game.playlists.get(current.id)?.sounds??[]].find(sound=>sound.playing);
|
||||
return {source:'Foundry',state:sound?'playing':'idle',title:sound?.name??''};
|
||||
}
|
||||
if(gmHost.connected)return {source:'Music Assistant',...await gmHost.playbackStatus()};
|
||||
return {state:'idle',title:''};
|
||||
},
|
||||
control(action,value){
|
||||
if(!gmAuthority()||!gmHost.connected||runtime?.controller.current?.playlist?.provider==='native')throw new MusicError('denied');
|
||||
return ensureRuntime().controller.control(action,value);
|
||||
},
|
||||
async forgetReceiver(){
|
||||
const scope=privateDraft&&receiverScope(privateDraft);
|
||||
await connection.disconnect();
|
||||
await game.settings.set(id,'savedConnection',{});
|
||||
if(scope)await receiverVault.forget(scope);
|
||||
},
|
||||
async disconnect(){connectionGeneration++;stop();peers?.reset();sentInvites.clear();privateProfile=null;privateDraft=null;await gmHost.close();}
|
||||
};
|
||||
function listenWebRTC(invite){
|
||||
@@ -66,6 +134,7 @@ function listenWebRTC(invite){
|
||||
}
|
||||
function stopWebRTC(){listenerStopped=true;listenerState='Audio stopped.';listenerSource?.disconnect();listenerSource=null;listenerContext?.suspend();peers?.reset();remoteAudio?.pause();if(remoteAudio)remoteAudio.srcObject=null;}
|
||||
Hooks.once('init',()=>{
|
||||
game.settings.register(id,'savedConnection',{scope:'user',config:false,type:Object,default:{}});
|
||||
game.settings.register(id,'advancedDevelopment',{name:'Show advanced development controls',hint:'Optional companion and manual test capabilities. Not needed for normal music setup.',scope:'client',config:true,type:Boolean,default:false});
|
||||
game.settings.register(id,'enabled',{name:'Enable music automation',hint:'Configure through Adaptive Music setup. Defaults off.',scope:'world',config:false,type:Boolean,default:false});
|
||||
game.settings.register(id,'ownedPlaylistIds',{scope:'world',config:false,type:String,default:'',requiresReload:true});
|
||||
|
||||
@@ -18,8 +18,9 @@ export function musicSelect(dom,choices,current,{nativeOnly=false,empty='Use wor
|
||||
const add=(value,text)=>{const option=dom.createElement('option');option.value=value;option.textContent=text;select.append(option);};
|
||||
add('',empty);
|
||||
for(const c of choices.filter(c=>!nativeOnly||c.provider==='native'))add(referenceKey(c),`${c.provider==='ma'?'Music Assistant':'Foundry'}: ${c.name}`);
|
||||
if(current&&!choices.some(c=>referenceKey(c)===referenceKey(current)))add(referenceKey(current),'Saved selection (catalog unavailable)');
|
||||
select.value=referenceKey(current);return select;
|
||||
const replacement=current?.provider==='ma'&&choices.find(c=>c.provider==='ma'&&c.legacyId===current.id);
|
||||
if(current&&!replacement&&!choices.some(c=>referenceKey(c)===referenceKey(current)))add(referenceKey(current),'Saved selection (catalog unavailable)');
|
||||
select.value=referenceKey(replacement||current);return select;
|
||||
}
|
||||
export function mountMusicAssignments({document,game,container,choices,defaults=false,onError=()=>{}}){
|
||||
if(!game.user?.isGM)return null;
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
import {connectionMessage} from './connection-wizard.mjs';
|
||||
import {referenceKey,selection} from '../core/scene-music.mjs';
|
||||
|
||||
const clock=value=>`${Math.floor(value/60)}:${String(value%60).padStart(2,'0')}`;
|
||||
const states={playing:'Playing',paused:'Paused',idle:'Stopped'};
|
||||
|
||||
export function mountPlaybackPanel({game,container,connection,getChoices,start,stop,setOverrides,onError}) {
|
||||
const dom=container.ownerDocument;
|
||||
const make=(tag,text,parent=container)=>{const node=dom.createElement(tag);if(text)node.textContent=text;parent.append(node);return node;};
|
||||
make('h2','Playback');
|
||||
const now=make('section');now.className='adaptive-now';
|
||||
const state=make('p','Stopped',now);state.className='adaptive-state';
|
||||
const track=make('h3','Nothing playing',now);
|
||||
const timing=make('p',null,now);
|
||||
const controls=make('div');controls.className='adaptive-actions';
|
||||
const output=make('div');output.className='adaptive-fields';
|
||||
const volumeLabel=make('label','Campaign volume',output),volume=make('input',null,volumeLabel);
|
||||
volume.type='range';volume.min='0';volume.max='100';volume.value='100';
|
||||
const seekLabel=make('label','Playback position',output),seek=make('input',null,seekLabel);
|
||||
seek.type='range';seek.min='0';seek.max='0';seek.step='1';seek.value='0';
|
||||
const summary=make('div');summary.className='adaptive-playback-summary';
|
||||
const automationText=make('p',null,summary),listeners=make('p',null,summary);
|
||||
const status=make('p');status.setAttribute('role','status');
|
||||
const failure=make('p');failure.setAttribute('role','alert');failure.hidden=true;
|
||||
let trackStatus,refreshing=false,busy=false,volumeEditing=false,seekEditing=false,oldChoices='';
|
||||
|
||||
const button=(parent,label,action)=>{
|
||||
const b=make('button',label,parent);b.type='button';b.addEventListener('click',()=>run(action));return b;
|
||||
};
|
||||
const toggle=button(controls,'Pause',()=>connection.control(trackStatus.state==='playing'?'pause':'resume'));
|
||||
toggle.className='adaptive-primary';
|
||||
const stopTrack=button(controls,'Stop playback',()=>connection.control('stop'));
|
||||
const unlock=button(controls,'Enable GM audio',()=>connection.resume());
|
||||
const automation=button(summary,'Enable automation',async()=>{
|
||||
const enable=!isRunning();
|
||||
if(!enable)stop();
|
||||
await game.settings.set('adaptive-music','enabled',enable);
|
||||
if(enable)await start();
|
||||
status.textContent=enable?'Scene automation enabled.':'Scene automation disabled.';
|
||||
});
|
||||
|
||||
const manual=make('details');make('summary','Manual playlist override',manual);
|
||||
const label=make('label','Override playlist',manual),select=make('select',null,label);
|
||||
const manualActions=make('div',null,manual);manualActions.className='adaptive-actions';
|
||||
button(manualActions,'Apply override',()=>setOverrides([{id:'gm-manual',playlist:selection(select.value,getChoices())}]));
|
||||
button(manualActions,'Clear override',()=>setOverrides([]));
|
||||
function isRunning(){return connection?.status.automationRunning??game.settings.get('adaptive-music','enabled');}
|
||||
|
||||
volume.addEventListener('input',()=>{volumeEditing=true;volume.setAttribute('aria-valuetext',`${volume.value}%`);});
|
||||
volume.addEventListener('change',()=>run(()=>connection.setVolume(Number(volume.value))).finally(()=>{volumeEditing=false;}));
|
||||
seek.addEventListener('input',()=>{seekEditing=true;seek.setAttribute('aria-valuetext',clock(Number(seek.value)));});
|
||||
seek.addEventListener('change',()=>run(()=>connection.control('seek',Number(seek.value))).finally(()=>{seekEditing=false;}));
|
||||
|
||||
async function run(action){
|
||||
if(busy||!game.user.isGM)return;
|
||||
busy=true;failure.hidden=true;render();
|
||||
try{await action();}
|
||||
catch(error){failure.textContent=`Playback action failed. ${connectionMessage(error)}`;failure.hidden=false;onError(error);}
|
||||
finally{busy=false;await refresh();}
|
||||
}
|
||||
function render(){
|
||||
const d=connection?.status??{},connected=d.state==='connected',playing=trackStatus?.state==='playing',paused=trackStatus?.state==='paused';
|
||||
const canControl=connected&&trackStatus?.source==='Music Assistant'&&d.lastError?.code!=='uncertain';
|
||||
state.textContent=states[trackStatus?.state]??(trackStatus?'Playback status unavailable':'Stopped');
|
||||
track.textContent=trackStatus?.title||'Nothing playing';
|
||||
timing.textContent=trackStatus?.duration?`${clock(trackStatus.position)} / ${clock(trackStatus.duration)}`:'';
|
||||
if(!volumeEditing){volume.value=String(d.volume??100);volume.setAttribute('aria-valuetext',`${volume.value}%`);}
|
||||
if(!seekEditing){
|
||||
seek.max=String(Math.max(0,(trackStatus?.duration??0)-1));seek.value=String(Math.min(Number(seek.max),trackStatus?.position??0));
|
||||
seek.setAttribute('aria-valuetext',clock(Number(seek.value)));
|
||||
}
|
||||
toggle.textContent=paused?'Resume':'Pause';toggle.disabled=busy||!canControl||!(playing||paused);
|
||||
stopTrack.disabled=busy||!canControl||!(playing||paused);
|
||||
volume.disabled=busy||!connected;seek.disabled=busy||!canControl||!(playing||paused)||Number(seek.max)<=0;
|
||||
unlock.hidden=!connected||d.audioContext==='running';unlock.disabled=busy;
|
||||
const enabled=isRunning();
|
||||
automationText.textContent=enabled?'Automation active':game.settings.get('adaptive-music','enabled')?'Automation paused':'Automation off';
|
||||
automation.textContent=enabled?'Disable automation':'Enable automation';automation.disabled=busy;
|
||||
const count=d.peers??0;listeners.textContent=`${count} connected ${count===1?'listener':'listeners'}`;
|
||||
if(d.lastError?.code==='uncertain'){
|
||||
failure.textContent=`Queue needs review. ${connectionMessage(d.lastError)}`;failure.hidden=false;
|
||||
}
|
||||
const choices=getChoices();const display=JSON.stringify(choices.map(choice=>[referenceKey(choice),choice.name]));
|
||||
if(display!==oldChoices){
|
||||
const previous=select.value;select.replaceChildren();
|
||||
const empty=make('option','Silence',select);empty.value='';
|
||||
for(const choice of choices){const option=make('option',choice.name,select);option.value=referenceKey(choice);}
|
||||
if(choices.some(choice=>referenceKey(choice)===previous))select.value=previous;
|
||||
oldChoices=display;
|
||||
}
|
||||
}
|
||||
async function refresh(){
|
||||
render();if(refreshing||busy)return;
|
||||
refreshing=true;
|
||||
try{trackStatus=await connection?.playback?.();}
|
||||
catch{trackStatus={state:'unavailable'};}
|
||||
finally{refreshing=false;render();}
|
||||
}
|
||||
render();
|
||||
return refresh;
|
||||
}
|
||||
+10
-4
@@ -5,15 +5,21 @@ export const primaryGM = users => [...users].filter(u => u.active && u.isGM)
|
||||
.sort((a,b) => a.id.localeCompare(b.id))[0]?.id;
|
||||
// Explicit development bootstrap. No hooks or document mutations occur on import.
|
||||
// All music configuration uses module-owned flags; no actor/system schema access.
|
||||
export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider, onError = () => {} }) {
|
||||
export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlaylistIds, maProvider,
|
||||
isEnabled = () => true, authority = () => game.ready && primaryGM(game.users) === game.user.id,
|
||||
previousController, onError = () => {} }) {
|
||||
const flag = d => d?.getFlag('adaptive-music', 'music');
|
||||
const provider = new NativeProvider({ playlists: game.playlists, ownedPlaylistIds, campaign, session,
|
||||
sceneConflict: id => [...game.scenes].some(s => s.active && (s.playlist?.id ?? s.playlist) === id) });
|
||||
const controller = new MusicController({ campaign, session, providers: { native: provider,...(maProvider?{ma:maProvider}:{}) },
|
||||
authority: () => game.ready && primaryGM(game.users) === game.user.id });
|
||||
authority });
|
||||
if (previousController) {
|
||||
controller.generation = previousController.generation;
|
||||
controller.tail = previousController.tail;
|
||||
}
|
||||
let overrides = [];
|
||||
const refresh = () => {
|
||||
if (!game.ready || primaryGM(game.users) !== game.user.id) return Promise.resolve();
|
||||
if (!isEnabled() || !authority()) return Promise.resolve();
|
||||
const scene = [...game.scenes].find(s => s.active);
|
||||
const defaults=game.settings.get('adaptive-music','musicDefaults')??{};
|
||||
const choose=(ref,fallback)=>ref?.provider==='ma'&&!maProvider?.supports(ref)?fallback??null:ref;
|
||||
@@ -30,6 +36,6 @@ export function startNativeRuntime({ game, Hooks, campaign, session, ownedPlayli
|
||||
const subscriptions = events.map(event => [event, Hooks.on(event, () => refresh().catch(onError))]);
|
||||
return { controller, refresh,
|
||||
setOverrides: value => { overrides = structuredClone(value); return refresh(); },
|
||||
dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.generation++; controller.abort?.abort(); }
|
||||
dispose: () => { for (const [event,id] of subscriptions) Hooks.off(event,id); controller.cancel(); }
|
||||
};
|
||||
}
|
||||
+116
-41
@@ -1,54 +1,129 @@
|
||||
import {mountConnectionWizard} from './connection-wizard.mjs';
|
||||
import {mountConnectionWizard,connectionMessage} from './connection-wizard.mjs';
|
||||
import {MusicError} from '../core/controller.mjs';
|
||||
import {selection} from '../core/scene-music.mjs';
|
||||
import {mountMusicAssignments,mountBossEditor,musicSelect} from './music-editor.mjs';
|
||||
import {mountMusicAssignments,mountBossEditor} from './music-editor.mjs';
|
||||
import {mountPlaybackPanel} from './playback-panel.mjs';
|
||||
|
||||
const namespace='adaptive-music';
|
||||
const tabs=[['connection','Connection'],['scene','Scene Music'],['playback','Playback']];
|
||||
|
||||
export function createSetupClass({game,gateway,audio,getChoices,start,stop,setOverrides,onError,canConnect=()=>true,connection,Base=globalThis.foundry.applications.api.ApplicationV2}){
|
||||
return class AdaptiveMusicSetup extends Base {
|
||||
static DEFAULT_OPTIONS={id:'adaptive-music-setup',window:{title:'Adaptive Music setup'},position:{width:640,height:'auto'}};
|
||||
static DEFAULT_OPTIONS={id:'adaptive-music-setup',window:{title:'Adaptive Music',resizable:true},position:{width:760,height:620}};
|
||||
#tab='connection';
|
||||
#scene;
|
||||
#timer;
|
||||
|
||||
async _renderHTML(){
|
||||
if(!game.user.isGM)throw new MusicError('denied');
|
||||
const dom=globalThis.document,root=dom.createElement('div');root.className='adaptive-music-setup';
|
||||
const text=value=>{const p=dom.createElement('p');p.textContent=value;root.append(p);return p;};
|
||||
const status=text('Automation is opt-in. Configure dedicated music playlists and assignments before enabling it.');status.setAttribute('role','status');
|
||||
const button=(label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw new MusicError('denied');await action();}catch(e){status.textContent='Could not apply this change. Check ownership, active GM authority and connection diagnostics.';onError(e);}finally{b.disabled=false;}});root.append(b);return b;};
|
||||
const assignmentRoot=dom.createElement('div');
|
||||
if(connection)mountConnectionWizard({game,container:root,connection,onCatalog:()=>renderAssignments(),onError});
|
||||
const owned=new Set(game.settings.get('adaptive-music','ownedPlaylistIds').split(',').filter(Boolean));
|
||||
const boxes=[];const ownedPanel=dom.createElement('fieldset');const legend=dom.createElement('legend');legend.textContent='2. Foundry music and fallback';ownedPanel.append(legend);
|
||||
for(const playlist of game.playlists){const label=dom.createElement('label'),input=dom.createElement('input');input.type='checkbox';input.checked=owned.has(playlist.id);label.textContent=playlist.name+' ';label.append(input);ownedPanel.append(label);boxes.push({id:playlist.id,input});}root.append(ownedPanel);
|
||||
text('Opt in only dedicated music playlists. Do not select AmbientSound, effects or shared playlists. Saving ownership disables automation and requires a reload.');
|
||||
button('Save native ownership',async()=>{stop();await game.settings.set('adaptive-music','enabled',false);await game.settings.set('adaptive-music','ownedPlaylistIds',boxes.filter(b=>b.input.checked).map(b=>b.id).join(','));status.textContent='Ownership saved. Reload this world before enabling automation.';});
|
||||
const advanced=game.settings.get('adaptive-music','advancedDevelopment')===true;
|
||||
if(advanced){
|
||||
const dev=dom.createElement('details'),title=dom.createElement('summary');title.textContent='Advanced development: optional companion';dev.append(title);root.append(dev);
|
||||
const label=dom.createElement('label');label.textContent='Companion controller code';const code=dom.createElement('input');code.type='password';code.autocomplete='off';label.append(code);dev.append(label);
|
||||
const connect=button('Connect optional companion',async()=>{if(!canConnect())throw new MusicError('denied');const value=code.value;code.value='';await gateway.connect(value);await renderAssignments();});dev.append(connect);
|
||||
const disconnect=button('Disconnect optional companion',()=>gateway.disconnect());dev.append(disconnect);
|
||||
const listen=dom.createElement('input');listen.type='password';listen.setAttribute('aria-label','Companion test capability');dev.append(listen);
|
||||
const enable=button('Enable synthetic test audio',()=>{const value=JSON.parse(listen.value);listen.value='';return audio.start(gateway.audioRequest(value));});dev.append(enable);
|
||||
const disable=button('Stop test audio',()=>audio.stop());dev.append(disable);
|
||||
}
|
||||
const renderAssignments=async()=>{
|
||||
assignmentRoot.replaceChildren();const choices=await getChoices();
|
||||
const defaults=dom.createElement('details'),defaultsTitle=dom.createElement('summary');defaultsTitle.textContent='World music defaults';defaults.append(defaultsTitle);mountMusicAssignments({game,container:defaults,choices,defaults:true,onError});assignmentRoot.append(defaults);
|
||||
const sceneLabel=dom.createElement('label');sceneLabel.textContent='Scene ';const scenes=dom.createElement('select');
|
||||
for(const scene of game.scenes){const option=dom.createElement('option');option.value=scene.id;option.textContent=scene.name;scenes.append(option);}sceneLabel.append(scenes);assignmentRoot.append(sceneLabel);
|
||||
const scenePanel=dom.createElement('div');assignmentRoot.append(scenePanel);
|
||||
const showScene=()=>{scenePanel.replaceChildren();const scene=game.scenes.get(scenes.value);if(scene)mountMusicAssignments({document:scene,game,container:scenePanel,choices,onError});};
|
||||
const active=[...game.scenes].find(s=>s.active);if(active)scenes.value=active.id;scenes.addEventListener('change',showScene);showScene();
|
||||
const more=dom.createElement('details'),moreTitle=dom.createElement('summary');moreTitle.textContent='Boss music and manual controls';more.append(moreTitle);assignmentRoot.append(more);
|
||||
const bossLabel=dom.createElement('label');bossLabel.textContent='Boss combatant ';const bosses=dom.createElement('select'),documents=new Map();
|
||||
for(const combat of game.combats)for(const combatant of combat.combatants){const option=dom.createElement('option');option.value=combat.id+':'+combatant.id;option.textContent=combatant.name??combatant.id;documents.set(option.value,combatant);bosses.append(option);}bossLabel.append(bosses);more.append(bossLabel);
|
||||
const bossPanel=dom.createElement('div');more.append(bossPanel);const showBoss=()=>{bossPanel.replaceChildren();const document=documents.get(bosses.value);if(document)mountBossEditor({document,game,container:bossPanel,choices,onError});};bosses.addEventListener('change',showBoss);showBoss();
|
||||
const manual=musicSelect(dom,choices,null,{empty:'Silence'});manual.setAttribute('aria-label','Manual music override');more.append(manual);
|
||||
for(const [label,action]of [['Apply manual override',()=>setOverrides([{id:'gm-manual',playlist:selection(manual.value,choices)}])],['Clear manual override',()=>setOverrides([])]]){const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',()=>Promise.resolve().then(action).catch(onError));more.append(b);}
|
||||
const make=(tag,text,parent=root)=>{const node=dom.createElement(tag);if(text)node.textContent=text;parent.append(node);return node;};
|
||||
const nav=make('div');nav.className='adaptive-tabs';nav.setAttribute('role','tablist');nav.setAttribute('aria-label','Adaptive Music setup');
|
||||
const panels=new Map();
|
||||
let refreshPlayback=()=>{};
|
||||
const switchTab=(id,focus=false)=>{
|
||||
this.#tab=id;
|
||||
for(const [key,{tab,panel}] of panels){
|
||||
const selected=key===id;tab.setAttribute('aria-selected',String(selected));tab.tabIndex=selected?0:-1;panel.hidden=!selected;
|
||||
}
|
||||
if(focus)panels.get(id).tab.focus?.();
|
||||
if(id==='playback')void refreshPlayback();
|
||||
};
|
||||
await renderAssignments();root.append(assignmentRoot);
|
||||
const enabledLabel=dom.createElement('label');enabledLabel.textContent='Enable music automation ';const enabled=dom.createElement('input');enabled.type='checkbox';enabled.checked=game.settings.get('adaptive-music','enabled');enabledLabel.append(enabled);root.append(enabledLabel);
|
||||
button('Apply automation setting',async()=>{await game.settings.set('adaptive-music','enabled',enabled.checked);if(enabled.checked)start();else stop();status.textContent=enabled.checked?'Automation enabled. MA assignments require authorized content; otherwise the configured native fallback is selected.':'Automation disabled; current playback is retained.';});
|
||||
for(const [index,[id,label]] of tabs.entries()){
|
||||
const tab=make('button',label,nav);tab.type='button';tab.id=`adaptive-tab-${id}`;tab.setAttribute('role','tab');
|
||||
const panel=make('section');panel.className='adaptive-panel';panel.id=`adaptive-panel-${id}`;panel.setAttribute('role','tabpanel');
|
||||
tab.setAttribute('aria-controls',panel.id);panel.setAttribute('aria-labelledby',tab.id);
|
||||
tab.addEventListener('click',()=>switchTab(id));
|
||||
tab.addEventListener('keydown',event=>{
|
||||
const positions={ArrowRight:(index+1)%tabs.length,ArrowLeft:(index+tabs.length-1)%tabs.length,Home:0,End:tabs.length-1};
|
||||
if(!Object.hasOwn(positions,event.key))return;
|
||||
event.preventDefault();switchTab(tabs[positions[event.key]][0],true);
|
||||
});
|
||||
panels.set(id,{tab,panel});
|
||||
}
|
||||
const connectionPanel=panels.get('connection').panel,scenePanel=panels.get('scene').panel,playbackPanel=panels.get('playback').panel;
|
||||
const button=(parent,label,action,status,className)=>{
|
||||
const b=make('button',label,parent);b.type='button';if(className)b.className=className;
|
||||
b.addEventListener('click',async()=>{
|
||||
if(!game.user.isGM||b.disabled)return;
|
||||
b.disabled=true;
|
||||
try{await action();}catch(error){if(status)status.textContent=connectionMessage(error);onError(error);}finally{b.disabled=false;}
|
||||
});return b;
|
||||
};
|
||||
const addOption=(select,value,label)=>{const option=make('option',label,select);option.value=value;return option;};
|
||||
|
||||
make('h2','Assign scene music',scenePanel);
|
||||
const sceneLabel=make('label','Scene',scenePanel),scenes=make('select',null,sceneLabel);
|
||||
for(const scene of game.scenes)addOption(scenes,scene.id,scene.name);
|
||||
const selected=game.scenes.get(this.#scene)??[...game.scenes].find(scene=>scene.active);
|
||||
if(selected)scenes.value=selected.id;
|
||||
const assignments=make('div',null,scenePanel);
|
||||
const sceneActions=make('div',null,scenePanel);sceneActions.className='adaptive-actions';
|
||||
button(sceneActions,'Go to Playback',()=>switchTab('playback',true));
|
||||
const defaults=make('details',null,scenePanel);make('summary','World defaults and boss combatants',defaults);
|
||||
const defaultBody=make('div',null,defaults),bossLabel=make('label','Boss combatant',defaults);
|
||||
const bosses=make('select',null,bossLabel),bossBody=make('div',null,defaults),documents=new Map();
|
||||
for(const combat of game.combats??[])for(const combatant of combat.combatants){
|
||||
const key=`${combat.id}:${combatant.id}`;documents.set(key,combatant);addOption(bosses,key,combatant.name??combatant.id);
|
||||
}
|
||||
if(!documents.size){bossLabel.hidden=true;make('p','Create a combatant to assign a boss override.',defaults);}
|
||||
const ownedDetails=make('details',null,scenePanel);make('summary','Foundry fallback playlists',ownedDetails);
|
||||
make('p','Select dedicated music playlists for fallback playback. After saving ownership, reload the world before enabling automation.',ownedDetails);
|
||||
const owned=new Set(game.settings.get(namespace,'ownedPlaylistIds').split(',').filter(Boolean)),boxes=[];
|
||||
const ownedChoices=make('div',null,ownedDetails);ownedChoices.className='adaptive-checklist';
|
||||
for(const playlist of game.playlists){
|
||||
const label=make('label',null,ownedChoices),check=make('input',null,label);check.type='checkbox';check.checked=owned.has(playlist.id);
|
||||
make('span',playlist.name,label);boxes.push({id:playlist.id,check});
|
||||
}
|
||||
const ownershipStatus=make('p',null,ownedDetails);ownershipStatus.setAttribute('role','status');
|
||||
button(ownedDetails,'Save fallback ownership',async()=>{
|
||||
stop();await game.settings.set(namespace,'enabled',false);
|
||||
await game.settings.set(namespace,'ownedPlaylistIds',boxes.filter(box=>box.check.checked).map(box=>box.id).join(','));
|
||||
ownershipStatus.textContent='Ownership saved. Reload this world before enabling automation.';
|
||||
},ownershipStatus);
|
||||
|
||||
let choices=[];
|
||||
const showScene=()=>{
|
||||
this.#scene=scenes.value;assignments.replaceChildren();const scene=game.scenes.get(scenes.value);
|
||||
if(scene)mountMusicAssignments({document:scene,game,container:assignments,choices,onError});
|
||||
else make('p','Create a scene to assign its playlists.',assignments);
|
||||
};
|
||||
const showBoss=()=>{
|
||||
bossBody.replaceChildren();const document=documents.get(bosses.value);
|
||||
if(document)mountBossEditor({document,game,container:bossBody,choices,onError});
|
||||
};
|
||||
const refreshAssignments=async()=>{
|
||||
choices=await getChoices();showScene();showBoss();defaultBody.replaceChildren();
|
||||
mountMusicAssignments({game,container:defaultBody,choices,defaults:true,onError});
|
||||
};
|
||||
scenes.addEventListener('change',showScene);bosses.addEventListener('change',showBoss);
|
||||
await refreshAssignments();
|
||||
|
||||
let development;
|
||||
if(game.settings.get(namespace,'advancedDevelopment')===true){
|
||||
development=dom.createElement('section');make('h3','Optional companion',development);
|
||||
const label=make('label','Companion controller code',development),code=make('input',null,label);code.type='password';code.autocomplete='off';
|
||||
const status=make('p',null,development);status.setAttribute('role','status');
|
||||
button(development,'Connect optional companion',async()=>{if(!canConnect())throw new MusicError('denied');const value=code.value;code.value='';await gateway.connect(value);await refreshAssignments();},status);
|
||||
button(development,'Disconnect optional companion',async()=>{await gateway.disconnect();await refreshAssignments();},status);
|
||||
const capabilityLabel=make('label','Companion test capability',development),capability=make('input',null,capabilityLabel);capability.type='password';
|
||||
button(development,'Enable synthetic test audio',async()=>{const value=JSON.parse(capability.value);capability.value='';await audio.start(gateway.audioRequest(value));},status);
|
||||
button(development,'Stop test audio',()=>audio.stop(),status);
|
||||
}
|
||||
const refreshConnection=connection?mountConnectionWizard({game,container:connectionPanel,connection,onCatalog:refreshAssignments,onError,next:()=>switchTab('scene',true),advancedContent:development}):()=>{};
|
||||
refreshPlayback=mountPlaybackPanel({game,container:playbackPanel,connection,getChoices:()=>choices,start,stop,setOverrides,onError});
|
||||
switchTab(this.#tab);
|
||||
clearInterval(this.#timer);
|
||||
if(globalThis.document===dom&&typeof root.isConnected==='boolean'){
|
||||
this.#timer=setInterval(()=>{
|
||||
if(!root.isConnected)return;
|
||||
if(this.#tab==='connection')refreshConnection();
|
||||
if(this.#tab==='playback')void refreshPlayback();
|
||||
},1500);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
_replaceHTML(result,content){content.replaceChildren(result);}
|
||||
_onClose(...args){clearInterval(this.#timer);super._onClose?.(...args);}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@ 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; #authorizedMedia = new Set(); #targetVolume; #nativePause;
|
||||
constructor({ baseUrl, token, target, approvedProviders = [], catalogKey = randomKey(), campaign = 'default', expectedName, expectedProvider, syntheticSequences = {}, fetchImpl = fetch }) {
|
||||
#base; #token; #target; #fetch; #providers; #catalog = new Map(); #catalogKey; #legacyCatalogKey; #campaign; #expectedName; #expectedProvider; #writes = Promise.resolve(); #synthetic; #uncertain; #authorizedMedia = new Set(); #targetVolume; #nativePause;
|
||||
constructor({ baseUrl, token, target, approvedProviders = [], catalogKey = randomKey(), legacyCatalogKey, 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 ||
|
||||
@@ -13,6 +13,7 @@ export class MAReadClient {
|
||||
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 (legacyCatalogKey) this.#legacyCatalogKey = Uint8Array.from(legacyCatalogKey);
|
||||
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);
|
||||
@@ -96,8 +97,9 @@ export class MAReadClient {
|
||||
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) });
|
||||
const legacyId = this.#legacyCatalogKey && base64url(await hmac(this.#legacyCatalogKey,JSON.stringify([this.#campaign,key])));
|
||||
next.set(key, { id, legacyId, type, provider: mapping.provider_instance, itemId: mapping.item_id, dynamic: item.is_dynamic === true });
|
||||
choices.push({ provider: 'ma', id, ...(legacyId && {legacyId}), kind: type, name: item.name.replace(/[\x00-\x1f\x7f]/g,'').slice(0,160) });
|
||||
}
|
||||
if (page.length < 100) { complete = true; break; }
|
||||
}
|
||||
@@ -108,7 +110,7 @@ export class MAReadClient {
|
||||
}
|
||||
resolveCatalog(ref) {
|
||||
if (ref?.provider !== 'ma') throw new MusicError('denied');
|
||||
const entry = [...this.#catalog.values()].find(e => e.id === ref.id);
|
||||
const entry = [...this.#catalog.values()].find(e => e.id === ref.id || e.legacyId && e.legacyId === 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;
|
||||
@@ -123,7 +125,7 @@ export class MAReadClient {
|
||||
await this.inspectSynthetic(media);
|
||||
return media;
|
||||
}
|
||||
const entry=[...this.#catalog.values()].find(e=>e.id===ref.id);
|
||||
const entry=[...this.#catalog.values()].find(e=>e.id===ref.id || e.legacyId && e.legacyId===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');
|
||||
|
||||
@@ -8,6 +8,21 @@ export class MAPlaybackProvider {
|
||||
this.#client=client; this.#campaign=campaign; this.#session=session; this.#fence=fence; this.#authority=authority; this.#key=Uint8Array.from(snapshotKey);
|
||||
}
|
||||
capabilities() { return {seek:true,exactOrderRestore:false,exactUnshuffledRestore:true,concurrentLayers:false,volume:false}; }
|
||||
async playbackStatus() {
|
||||
this.#authority(this.#fence);
|
||||
const queue = await this.#client.queueState();
|
||||
this.#authority(this.#fence);
|
||||
const item = queue.current_item;
|
||||
const paused = this.#paused && queue.state === 'idle' && queue.current_index === this.#paused.index;
|
||||
const elapsed = paused ? this.#paused.position : queue.elapsed_time;
|
||||
const position = Number.isFinite(elapsed) ? Math.max(0, Math.floor(elapsed)) : 0;
|
||||
return {
|
||||
state: paused ? 'paused' : queue.state,
|
||||
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,
|
||||
};
|
||||
}
|
||||
#check(ctx) {
|
||||
if (ctx?.campaign !== this.#campaign || ctx?.session !== this.#session || !Number.isSafeInteger(ctx.generation) || ctx.generation < this.#generation || ctx.generation < 1) throw new MusicError('stale');
|
||||
ctx.check(); this.#authority(this.#fence); this.#generation=ctx.generation;
|
||||
|
||||
Reference in new issue
Block a user