import {validateIceServers} from '../audio/peer-audio.mjs'; import {probeWebSockets,diagnosticMessage} from '../providers/ma/diagnostics.mjs'; const messages={ '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.', '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-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.', 'sendspin-auth-failed':'The receiver socket opened, but Sendspin authentication failed. Verify the authenticated /sendspin route, separate from /ws.', 'sendspin-sync-failed':'Sendspin did not complete pairing and clock synchronization. Retry the remembered receiver; transport HTTP 101 alone does not prove a working audio receiver.', 'insecure-context':'Open Foundry over trusted HTTPS to use secure browser audio APIs.', 'mixed-content':'HTTPS Foundry requires a trusted HTTPS MA address. Browser security cannot permit an HTTP/ws downgrade.', 'reconcile-required':'This dedicated receiver has an existing queue. Playback was left untouched. Resume the remembered receiver after reviewing its queue in MA, or use a new dedicated receiver.', 'catalog-empty':'No available music providers were returned. Check the dedicated MA account’s music-provider access.', 'unsupported':'This queue or browser feature is unsupported. Use a standalone receiver with a static queue, shuffle and autoplay off, and a browser with Web Locks, Web Audio and WebRTC.', 'private-storage-unavailable':'This browser denied private receiver storage. Allow site storage for Foundry, then retry. No MA token is stored there.', 'private-storage-corrupt':'The remembered receiver could not be decrypted. Use Forget remembered receiver below to create a replacement. Existing MA queues are left untouched.', 'identity-mismatch':'The remembered receiver identity does not match this connection. Forget that receiver to create a new campaign receiver.', 'dedicated-target-required':'The receiver did not match the identity and name created for this campaign. No unrelated player was selected.', 'receiver-queue-unavailable':'MA did not make this receiver’s queue available after connection. Retry connecting the remembered receiver.', 'denied':'The dedicated receiver, account permission or active GM check failed. Keep one active GM and verify that this account can control its campaign receiver.', 'stale':'GM authority or the connection changed during setup. Keep one active GM, then retry.', 'uncertain':'MA did not confirm a queue write. Automation stopped to avoid duplicate playback. Review this dedicated queue before reconnecting.', '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; }