Files

1206 lines
24 KiB
JavaScript

// media-controller.js
window.Kronick =
window.Kronick || {};
/*
* Convert internal, insecure or outdated media URLs
* into URLs that browsers can access from the HTTPS
* Kronick Chat page.
*/
Kronick.normalizePublicMediaUrl =
function normalizePublicMediaUrl(rawUrl) {
if (
typeof rawUrl !== 'string'
|| !rawUrl.trim()
) {
return '';
}
let normalized =
rawUrl.trim();
/*
* Remove HTML-escaped ampersands that may have
* come through an API response.
*/
normalized = normalized.replace(
/&/g,
'&'
);
/*
* Convert internal or insecure Kronick service
* addresses to their public HTTPS equivalents.
*/
normalized = normalized.replace(
/^http:\/\/tube\.kronickrusaders\.ca:3000(?=\/|$)/i,
'https://tube.kronickrusaders.ca'
);
normalized = normalized.replace(
/^https:\/\/tube\.kronickrusaders\.ca:3000(?=\/|$)/i,
'https://tube.kronickrusaders.ca'
);
normalized = normalized.replace(
/^http:\/\/tube\.kronickrusaders\.ca(?=\/|$)/i,
'https://tube.kronickrusaders.ca'
);
normalized = normalized.replace(
/^http:\/\/music\.kronickrusaders\.ca(?=\/|$)/i,
'https://music.kronickrusaders.ca'
);
normalized = normalized.replace(
/^http:\/\/discord\.kronickrusaders\.ca(?=\/|$)/i,
'https://discord.kronickrusaders.ca'
);
/*
* Convert protocol-relative URLs to HTTPS.
*/
if (normalized.startsWith('//')) {
normalized =
`https:${normalized}`;
}
/*
* Resolve relative media paths against the music
* service rather than the parent Discord app.
*/
try {
normalized =
new URL(
normalized,
'https://music.kronickrusaders.ca'
).href;
} catch (err) {
console.warn(
'Invalid media URL:',
{
rawUrl,
error:
err.message
}
);
return '';
}
return normalized;
};
/*
* Return a readable explanation for an HTMLMediaElement
* error code.
*/
Kronick.getMediaErrorMessage =
function getMediaErrorMessage(mediaError) {
const errorMessages = {
1:
'Playback was aborted.',
2:
'A network error prevented '
+ 'the media from loading.',
3:
'The media downloaded, but '
+ 'the browser could not decode it.',
4:
'The URL did not provide a '
+ 'supported media format.'
};
return (
errorMessages[
mediaError?.code
]
|| mediaError?.message
|| 'Unknown media playback error.'
);
};
/*
* Remove the previous media source and event handlers.
*/
Kronick.resetMediaElement =
function resetMediaElement(mediaElement) {
if (!mediaElement) {
return;
}
mediaElement.pause();
mediaElement.onerror = null;
mediaElement.onloadstart = null;
mediaElement.onloadedmetadata = null;
mediaElement.oncanplay = null;
mediaElement.onplaying = null;
mediaElement.onwaiting = null;
mediaElement.onstalled = null;
mediaElement.onabort = null;
mediaElement.onemptied = null;
mediaElement.removeAttribute(
'src'
);
if (
mediaElement.tagName
=== 'VIDEO'
) {
mediaElement.removeAttribute(
'poster'
);
}
mediaElement.load();
};
/*
* Publish a media selection to the LiveKit room.
*/
Kronick.sendMediaToRoom =
function sendMediaToRoom(data) {
const room =
Kronick.state.room;
if (!room?.localParticipant) {
alert(
'Join a room first.'
);
return;
}
if (
!data
|| typeof data !== 'object'
|| typeof data.url !== 'string'
|| !data.url.trim()
) {
console.warn(
'Media share has no valid URL:',
data
);
return;
}
const normalizedUrl =
Kronick.normalizePublicMediaUrl(
data.url
);
const normalizedThumbnail =
data.thumbnail
? Kronick
.normalizePublicMediaUrl(
data.thumbnail
)
: '';
if (!normalizedUrl) {
console.warn(
'Media URL could not be normalized:',
data.url
);
return;
}
const message = {
type:
'media',
mediaType:
data.mediaType
|| 'video',
url:
normalizedUrl,
title:
data.title
|| '',
thumbnail:
normalizedThumbnail
};
console.log(
'SENDING MEDIA TO LIVEKIT ROOM:',
message
);
const payload =
new TextEncoder().encode(
JSON.stringify(message)
);
room.localParticipant
.publishData(
payload,
{
reliable: true,
topic:
Kronick.config
.DATA_TOPIC_MEDIA
}
)
.catch(err => {
console.error(
'Could not publish media message:',
err
);
});
/*
* Display it immediately for the sender.
* LiveKit does not normally echo the sender's
* data packet back to the same participant.
*/
Kronick.handleRoomMedia(
message
);
};
/*
* Handle a media message received from LiveKit or
* generated locally.
*/
Kronick.handleRoomMedia =
function handleRoomMedia(message) {
if (
!message
|| typeof message !== 'object'
) {
return;
}
if (message.type === 'media-stop') {
Kronick.closeSharedMedia(
false
);
return;
}
const normalizedUrl =
Kronick.normalizePublicMediaUrl(
message.url
);
if (!normalizedUrl) {
console.warn(
'Received media message '
+ 'without a usable URL:',
message
);
return;
}
const mediaType =
String(
message.mediaType
|| 'video'
).toLowerCase();
const normalizedThumbnail =
message.thumbnail
? Kronick
.normalizePublicMediaUrl(
message.thumbnail
)
: '';
console.log(
'HANDLING ROOM MEDIA:',
{
...message,
url:
normalizedUrl,
thumbnail:
normalizedThumbnail
}
);
/*
* A room GIF is shown in the temporary overlay,
* rather than the audio/video player.
*/
if (mediaType === 'gif') {
Kronick.showSharedGif(
normalizedUrl
);
return;
}
Kronick.playSharedMedia({
url:
normalizedUrl,
mediaType,
title:
message.title
|| 'Shared Media',
thumbnail:
normalizedThumbnail
});
};
/*
* Display and play shared audio or video.
*/
Kronick.playSharedMedia =
function playSharedMedia({
url,
mediaType = 'video',
title = '',
thumbnail = ''
}) {
const wrap =
document.getElementById(
'sharedMediaWrap'
);
const titleEl =
document.getElementById(
'sharedMediaTitle'
);
const video =
document.getElementById(
'sharedMediaVideo'
);
const audio =
document.getElementById(
'sharedMediaAudio'
);
const thumb =
document.getElementById(
'sharedMediaThumb'
);
const error =
document.getElementById(
'sharedMediaError'
);
if (
!wrap
|| !titleEl
|| !video
|| !audio
|| !thumb
|| !error
) {
console.error(
'Shared media HTML elements '
+ 'could not be found.'
);
return;
}
const normalizedUrl =
Kronick.normalizePublicMediaUrl(
url
);
const normalizedThumbnail =
thumbnail
? Kronick
.normalizePublicMediaUrl(
thumbnail
)
: '';
if (!normalizedUrl) {
error.textContent =
'The shared media URL is invalid.';
error.style.display =
'block';
console.error(
'Cannot play invalid media URL:',
url
);
return;
}
/*
* Stop and clear any previous playback.
*/
Kronick.resetMediaElement(
video
);
Kronick.resetMediaElement(
audio
);
thumb.removeAttribute(
'src'
);
video.style.display =
'none';
audio.style.display =
'none';
thumb.style.display =
'none';
error.style.display =
'none';
error.textContent =
'';
titleEl.textContent =
title || 'Shared Media';
wrap.style.display =
'flex';
Kronick.bringToolWindowToFront(
wrap
);
requestAnimationFrame(() => {
Kronick.keepWindowInViewport(
wrap
);
});
const normalizedMediaType =
String(mediaType)
.toLowerCase();
/*
* Audio playback.
*/
if (
normalizedMediaType === 'audio'
|| normalizedMediaType === 'music'
) {
wrap.classList.add(
'audio-mode'
);
if (normalizedThumbnail) {
thumb.src =
normalizedThumbnail;
thumb.style.display =
'block';
thumb.onerror = () => {
console.warn(
'Shared audio thumbnail '
+ 'failed to load:',
normalizedThumbnail
);
thumb.style.display =
'none';
thumb.removeAttribute(
'src'
);
};
}
console.log(
'LOADING SHARED AUDIO:',
{
originalUrl:
url,
normalizedUrl,
thumbnail:
normalizedThumbnail,
mediaType:
normalizedMediaType,
pageOrigin:
window.location.origin,
browserSupport: {
mp3:
audio.canPlayType(
'audio/mpeg'
),
m4a:
audio.canPlayType(
'audio/mp4'
),
aac:
audio.canPlayType(
'audio/aac'
),
webmOpus:
audio.canPlayType(
'audio/webm; '
+ 'codecs="opus"'
),
oggOpus:
audio.canPlayType(
'audio/ogg; '
+ 'codecs="opus"'
)
}
}
);
audio.onerror = () => {
const mediaError =
audio.error;
const detail =
Kronick
.getMediaErrorMessage(
mediaError
);
console.error(
'SHARED AUDIO ERROR:',
{
code:
mediaError?.code,
detail,
originalUrl:
url,
normalizedUrl,
currentSrc:
audio.currentSrc,
networkState:
audio.networkState,
readyState:
audio.readyState
}
);
error.textContent =
`Audio playback failed: `
+ detail;
error.style.display =
'block';
};
audio.onloadstart = () => {
console.log(
'SHARED AUDIO LOAD STARTED:',
normalizedUrl
);
};
audio.onloadedmetadata = () => {
console.log(
'SHARED AUDIO METADATA LOADED:',
{
currentSrc:
audio.currentSrc,
duration:
audio.duration,
readyState:
audio.readyState,
networkState:
audio.networkState
}
);
};
audio.oncanplay = () => {
console.log(
'SHARED AUDIO CAN PLAY:',
audio.currentSrc
);
};
audio.onplaying = () => {
console.log(
'SHARED AUDIO PLAYING:',
audio.currentSrc
);
error.style.display =
'none';
error.textContent =
'';
};
audio.onwaiting = () => {
console.debug(
'Shared audio is buffering:',
audio.currentSrc
);
};
audio.onstalled = () => {
console.warn(
'Shared audio request stalled:',
audio.currentSrc
);
};
audio.preload =
'metadata';
audio.controls =
true;
audio.src =
normalizedUrl;
audio.volume =
0.5;
audio.style.display =
'block';
audio.load();
audio.play()
.catch(playError => {
console.error(
'SHARED AUDIO PLAY REJECTED:',
{
name:
playError.name,
message:
playError.message,
src:
audio.currentSrc
}
);
if (
playError.name
=== 'NotAllowedError'
) {
error.textContent =
'Press Play to start '
+ 'the audio.';
error.style.display =
'block';
} else if (
playError.name
=== 'NotSupportedError'
) {
error.textContent =
'The audio endpoint did '
+ 'not return a supported '
+ 'audio stream.';
error.style.display =
'block';
}
});
return;
}
/*
* Video playback.
*/
wrap.classList.remove(
'audio-mode'
);
if (normalizedThumbnail) {
video.poster =
normalizedThumbnail;
}
console.log(
'LOADING SHARED VIDEO:',
{
originalUrl:
url,
normalizedUrl,
thumbnail:
normalizedThumbnail,
mediaType:
normalizedMediaType,
pageOrigin:
window.location.origin,
browserSupport: {
mp4H264:
video.canPlayType(
'video/mp4; '
+ 'codecs="avc1.42E01E"'
),
mp4:
video.canPlayType(
'video/mp4'
),
webmVp8:
video.canPlayType(
'video/webm; '
+ 'codecs="vp8, vorbis"'
),
webmVp9:
video.canPlayType(
'video/webm; '
+ 'codecs="vp9, opus"'
),
ogg:
video.canPlayType(
'video/ogg'
)
}
}
);
video.onerror = () => {
const mediaError =
video.error;
const detail =
Kronick
.getMediaErrorMessage(
mediaError
);
console.error(
'SHARED VIDEO ERROR:',
{
code:
mediaError?.code,
detail,
originalUrl:
url,
normalizedUrl,
currentSrc:
video.currentSrc,
networkState:
video.networkState,
readyState:
video.readyState,
videoWidth:
video.videoWidth,
videoHeight:
video.videoHeight
}
);
error.textContent =
`Video playback failed: `
+ detail;
error.style.display =
'block';
};
video.onloadstart = () => {
console.log(
'SHARED VIDEO LOAD STARTED:',
normalizedUrl
);
};
video.onloadedmetadata = () => {
console.log(
'SHARED VIDEO METADATA LOADED:',
{
currentSrc:
video.currentSrc,
duration:
video.duration,
videoWidth:
video.videoWidth,
videoHeight:
video.videoHeight,
readyState:
video.readyState,
networkState:
video.networkState
}
);
};
video.oncanplay = () => {
console.log(
'SHARED VIDEO CAN PLAY:',
video.currentSrc
);
};
video.onplaying = () => {
console.log(
'SHARED VIDEO PLAYING:',
video.currentSrc
);
error.style.display =
'none';
error.textContent =
'';
};
video.onwaiting = () => {
console.debug(
'Shared video is buffering:',
video.currentSrc
);
};
video.onstalled = () => {
console.warn(
'Shared video request stalled:',
video.currentSrc
);
};
video.preload =
'metadata';
video.controls =
true;
video.playsInline =
true;
video.src =
normalizedUrl;
video.volume =
0.5;
video.style.display =
'block';
video.load();
video.play()
.catch(playError => {
console.error(
'SHARED VIDEO PLAY REJECTED:',
{
name:
playError.name,
message:
playError.message,
src:
video.currentSrc
}
);
if (
playError.name
=== 'NotAllowedError'
) {
error.textContent =
'Press Play to start '
+ 'the video.';
error.style.display =
'block';
} else if (
playError.name
=== 'NotSupportedError'
) {
error.textContent =
'The video endpoint did '
+ 'not return a supported '
+ 'video stream.';
error.style.display =
'block';
}
});
};
/*
* Close the shared media player.
*
* sendStop=false is used when another participant's
* stop message is being handled, preventing a loop.
*/
Kronick.closeSharedMedia =
function closeSharedMedia(
sendStop = false
) {
const wrap =
document.getElementById(
'sharedMediaWrap'
);
const video =
document.getElementById(
'sharedMediaVideo'
);
const audio =
document.getElementById(
'sharedMediaAudio'
);
const thumb =
document.getElementById(
'sharedMediaThumb'
);
const error =
document.getElementById(
'sharedMediaError'
);
if (
!wrap
|| !video
|| !audio
|| !thumb
|| !error
) {
return;
}
Kronick.resetMediaElement(
video
);
Kronick.resetMediaElement(
audio
);
thumb.onerror = null;
thumb.removeAttribute(
'src'
);
video.style.display =
'none';
audio.style.display =
'none';
thumb.style.display =
'none';
error.style.display =
'none';
error.textContent =
'';
wrap.style.display =
'none';
wrap.classList.remove(
'audio-mode'
);
const room =
Kronick.state.room;
if (
sendStop
&& room?.localParticipant
) {
const payload =
new TextEncoder().encode(
JSON.stringify({
type:
'media-stop'
})
);
room.localParticipant
.publishData(
payload,
{
reliable:
true,
topic:
Kronick.config
.DATA_TOPIC_MEDIA
}
)
.catch(err => {
console.warn(
'Could not publish '
+ 'media stop message:',
err
);
});
}
};
/*
* Explicit room-wide stop.
*
* Normal window close is local-only. Call this function only
* from a deliberate "Stop for everyone" control.
*/
Kronick.stopSharedMediaForRoom =
function stopSharedMediaForRoom() {
Kronick.closeSharedMedia(
true
);
};
/*
* Display a temporary room-wide GIF overlay.
*/
Kronick.showSharedGif =
function showSharedGif(url) {
const gif =
document.getElementById(
'sharedGif'
);
if (!gif) {
return;
}
const normalizedUrl =
Kronick.normalizePublicMediaUrl(
url
);
if (!normalizedUrl) {
console.warn(
'Cannot display invalid GIF URL:',
url
);
return;
}
/*
* Clear a previous GIF before assigning the
* new source, allowing the same GIF to restart.
*/
gif.removeAttribute(
'src'
);
gif.style.display =
'none';
gif.onload = () => {
gif.style.display =
'block';
};
gif.onerror = () => {
console.error(
'Shared GIF failed to load:',
normalizedUrl
);
gif.style.display =
'none';
gif.removeAttribute(
'src'
);
};
gif.src =
normalizedUrl;
clearTimeout(
Kronick.state
.sharedGifTimeout
);
Kronick.state.sharedGifTimeout =
setTimeout(
() => {
gif.style.display =
'none';
gif.removeAttribute(
'src'
);
gif.onload = null;
gif.onerror = null;
},
8000
);
};