1
Fork 0
galene/static/galene.js

2691 lines
72 KiB
JavaScript
Raw Normal View History

2020-04-24 19:38:21 +02:00
// Copyright (c) 2020 by Juliusz Chroboczek.
2020-12-19 17:26:16 +01:00
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
2020-04-24 19:38:21 +02:00
'use strict';
2020-08-24 22:31:22 +02:00
/** @type {string} */
2020-04-24 19:38:21 +02:00
let group;
2020-08-24 22:31:22 +02:00
/** @type {ServerConnection} */
let serverConnection;
2020-04-24 19:38:21 +02:00
2020-09-12 16:34:52 +02:00
/**
* @typedef {Object} userpass
* @property {string} username
* @property {string} password
*/
/* Some browsers disable session storage when cookies are disabled,
we fall back to a global variable. */
2020-09-12 16:34:52 +02:00
/**
* @type {userpass}
*/
let fallbackUserPass = null;
2020-09-12 16:34:52 +02:00
/**
* @param {string} username
* @param {string} password
*/
function storeUserPass(username, password) {
let userpass = {username: username, password: password};
try {
window.sessionStorage.setItem('userpass', JSON.stringify(userpass));
fallbackUserPass = null;
} catch(e) {
console.warn("Couldn't store password:", e);
2020-09-12 16:34:52 +02:00
fallbackUserPass = userpass;
}
2020-04-24 19:38:21 +02:00
}
2020-09-12 16:34:52 +02:00
/**
* Returns null if the user hasn't logged in yet.
*
2020-09-12 16:34:52 +02:00
* @returns {userpass}
*/
2020-04-24 19:38:21 +02:00
function getUserPass() {
/** @type{userpass} */
let userpass;
try {
let json = window.sessionStorage.getItem('userpass');
userpass = JSON.parse(json);
} catch(e) {
console.warn("Couldn't retrieve password:", e);
userpass = fallbackUserPass;
}
return userpass || null;
2020-04-24 19:38:21 +02:00
}
/**
* @typedef {Object} settings
* @property {boolean} [localMute]
* @property {string} [video]
* @property {string} [audio]
* @property {string} [send]
* @property {string} [request]
* @property {boolean} [activityDetection]
* @property {Array.<number>} [resolution]
2021-01-23 01:15:53 +01:00
* @property {boolean} [mirrorView]
2020-09-18 19:14:10 +02:00
* @property {boolean} [blackboardMode]
* @property {string} [filter]
*/
/** @type{settings} */
let fallbackSettings = null;
/**
* @param {settings} settings
*/
function storeSettings(settings) {
try {
window.sessionStorage.setItem('settings', JSON.stringify(settings));
fallbackSettings = null;
} catch(e) {
console.warn("Couldn't store password:", e);
fallbackSettings = settings;
}
}
/**
* This always returns a dictionary.
*
* @returns {settings}
*/
function getSettings() {
/** @type {settings} */
let settings;
try {
let json = window.sessionStorage.getItem('settings');
settings = JSON.parse(json);
} catch(e) {
console.warn("Couldn't retrieve password:", e);
settings = fallbackSettings;
}
return settings || {};
}
/**
* @param {settings} settings
*/
function updateSettings(settings) {
let s = getSettings();
for(let key in settings)
s[key] = settings[key];
storeSettings(s);
}
2020-09-23 21:01:29 +02:00
/**
* @param {string} key
* @param {any} value
*/
function updateSetting(key, value) {
let s = {};
s[key] = value;
updateSettings(s);
}
/**
* @param {string} key
*/
function delSetting(key) {
let s = getSettings();
if(!(key in s))
return;
delete(s[key]);
2020-12-26 17:28:44 +01:00
storeSettings(s);
2020-09-23 21:01:29 +02:00
}
/**
* @param {string} id
*/
function getSelectElement(id) {
let elt = document.getElementById(id);
if(!elt || !(elt instanceof HTMLSelectElement))
throw new Error(`Couldn't find ${id}`);
return elt;
}
/**
* @param {string} id
*/
function getInputElement(id) {
let elt = document.getElementById(id);
if(!elt || !(elt instanceof HTMLInputElement))
throw new Error(`Couldn't find ${id}`);
return elt;
}
/**
* @param {string} id
*/
function getButtonElement(id) {
let elt = document.getElementById(id);
if(!elt || !(elt instanceof HTMLButtonElement))
throw new Error(`Couldn't find ${id}`);
return elt;
}
function reflectSettings() {
let settings = getSettings();
let store = false;
setLocalMute(settings.localMute);
let videoselect = getSelectElement('videoselect');
if(!settings.hasOwnProperty('video') ||
!selectOptionAvailable(videoselect, settings.video)) {
settings.video = selectOptionDefault(videoselect);
store = true;
}
videoselect.value = settings.video;
let audioselect = getSelectElement('audioselect');
if(!settings.hasOwnProperty('audio') ||
!selectOptionAvailable(audioselect, settings.audio)) {
settings.audio = selectOptionDefault(audioselect);
store = true;
}
audioselect.value = settings.audio;
if(settings.hasOwnProperty('filter')) {
getSelectElement('filterselect').value = settings.filter;
} else {
let s = getSelectElement('filterselect').value;
if(s) {
settings.filter = s;
store = true;
}
}
if(settings.hasOwnProperty('request')) {
getSelectElement('requestselect').value = settings.request;
} else {
settings.request = getSelectElement('requestselect').value;
store = true;
}
if(settings.hasOwnProperty('send')) {
getSelectElement('sendselect').value = settings.send;
} else {
settings.send = getSelectElement('sendselect').value;
store = true;
}
if(settings.hasOwnProperty('blackboardMode')) {
getInputElement('blackboardbox').checked = settings.blackboardMode;
} else {
settings.blackboardMode = getInputElement('blackboardbox').checked;
store = true;
}
2021-01-23 01:15:53 +01:00
if(settings.hasOwnProperty('mirrorView')) {
getInputElement('mirrorbox').checked = settings.mirrorView;
} else {
settings.mirrorView = getInputElement('mirrorbox').checked;
store = true;
}
if(settings.hasOwnProperty('activityDetection')) {
getInputElement('activitybox').checked = settings.activityDetection;
} else {
settings.activityDetection = getInputElement('activitybox').checked;
store = true;
}
2020-09-18 19:14:10 +02:00
if(store)
storeSettings(settings);
}
function showVideo() {
2020-09-09 20:26:19 +02:00
let width = window.innerWidth;
let video_container = document.getElementById('video-container');
video_container.classList.remove('no-video');
2020-09-09 20:26:19 +02:00
if (width <= 768)
document.getElementById('collapse-video').style.display = "block";
}
2020-09-12 16:34:52 +02:00
/**
* @param {boolean} [force]
*/
function hideVideo(force) {
let mediadiv = document.getElementById('peers');
2020-09-12 16:34:52 +02:00
if(mediadiv.childElementCount > 0 && !force)
return;
let video_container = document.getElementById('video-container');
video_container.classList.add('no-video');
let left = document.getElementById("left");
if (left.style.display !== "none") {
// hide all video buttons used to switch video on mobile layout
closeVideoControls();
}
2020-09-09 20:26:19 +02:00
}
function closeVideoControls() {
// hide all video buttons used to switch video on mobile layout
document.getElementById('switch-video').style.display = "";
2020-09-09 20:26:19 +02:00
document.getElementById('collapse-video').style.display = "";
}
2020-12-12 23:36:08 +01:00
function fillLogin() {
let userpass = getUserPass();
getInputElement('username').value =
userpass ? userpass.username : '';
getInputElement('password').value =
userpass ? userpass.password : '';
}
2020-09-05 12:59:28 +02:00
/**
* @param{boolean} connected
*/
2020-04-24 19:38:21 +02:00
function setConnected(connected) {
2020-11-24 17:36:52 +01:00
let userbox = document.getElementById('profile');
2020-09-02 15:35:55 +02:00
let connectionbox = document.getElementById('login-container');
2020-04-24 19:38:21 +02:00
if(connected) {
resetUsers();
clearChat();
2020-09-02 15:35:55 +02:00
userbox.classList.remove('invisible');
connectionbox.classList.add('invisible');
2020-04-25 18:09:31 +02:00
displayUsername();
2020-04-24 19:38:21 +02:00
} else {
2020-09-05 12:59:28 +02:00
resetUsers();
2020-12-12 23:36:08 +01:00
fillLogin();
2020-09-02 15:35:55 +02:00
userbox.classList.add('invisible');
connectionbox.classList.remove('invisible');
displayError('Disconnected', 'error');
2020-09-09 20:26:19 +02:00
hideVideo();
closeVideoControls();
}
}
/** @this {ServerConnection} */
function gotConnected() {
setConnected(true);
let up = getUserPass();
this.join(group, up.username, up.password);
}
2020-09-12 16:34:52 +02:00
/**
* @this {ServerConnection}
2020-09-12 16:34:52 +02:00
* @param {number} code
* @param {string} reason
*/
function gotClose(code, reason) {
setConnected(false);
if(code != 1000) {
console.warn('Socket close', code, reason);
}
}
/**
* @this {ServerConnection}
* @param {Stream} c
*/
function gotDownStream(c) {
c.onclose = function(replace) {
if(!replace)
delMedia(c.localId);
};
c.onerror = function(e) {
console.error(e);
displayError(e);
2020-12-26 17:28:44 +01:00
};
c.ondowntrack = function(track, transceiver, label, stream) {
setMedia(c, false);
2020-12-26 17:28:44 +01:00
};
c.onstatus = function(status) {
setMediaStatus(c);
2020-12-26 17:28:44 +01:00
};
2020-09-11 23:20:46 +02:00
c.onstats = gotDownStats;
if(getSettings().activityDetection)
2020-09-11 23:20:46 +02:00
c.setStatsInterval(activityDetectionInterval);
2020-12-25 20:29:46 +01:00
setMedia(c, false);
2020-04-24 19:38:21 +02:00
}
2020-09-09 20:26:19 +02:00
// Store current browser viewport height in css variable
function setViewportHeight() {
2020-09-12 16:34:52 +02:00
document.documentElement.style.setProperty(
'--vh', `${window.innerHeight/100}px`,
);
// Ajust video component size
resizePeers();
}
2020-09-09 20:26:19 +02:00
setViewportHeight();
// On resize and orientation change, we update viewport height
addEventListener('resize', setViewportHeight);
addEventListener('orientationchange', setViewportHeight);
getButtonElement('presentbutton').onclick = async function(e) {
2020-04-24 19:38:21 +02:00
e.preventDefault();
let button = this;
if(!(button instanceof HTMLButtonElement))
throw new Error('Unexpected type for this.');
// there's a potential race condition here: the user might click the
// button a second time before the stream is set up and the button hidden.
button.disabled = true;
try {
let id = findUpMedia('local');
if(!id)
await addLocalMedia();
} finally {
button.disabled = false;
}
2020-05-10 21:18:07 +02:00
};
2020-04-24 19:38:21 +02:00
getButtonElement('unpresentbutton').onclick = function(e) {
e.preventDefault();
closeUpMediaKind('local');
2020-09-03 20:54:27 +02:00
resizePeers();
};
function changePresentation() {
let c = findUpMedia('local');
if(c)
addLocalMedia(c.localId);
}
/**
* @param {string} id
* @param {boolean} visible
*/
function setVisibility(id, visible) {
let elt = document.getElementById(id);
if(visible)
elt.classList.remove('invisible');
else
elt.classList.add('invisible');
}
function setButtonsVisibility() {
let permissions = serverConnection.permissions;
let local = !!findUpMedia('local');
let share = !!findUpMedia('screenshare');
2020-11-24 22:41:43 +01:00
let video = !!findUpMedia('video');
2021-02-01 01:08:39 +01:00
let canFile =
/** @ts-ignore */
!!HTMLVideoElement.prototype.captureStream ||
/** @ts-ignore */
!!HTMLVideoElement.prototype.mozCaptureStream;
// don't allow multiple presentations
setVisibility('presentbutton', permissions.present && !local);
setVisibility('unpresentbutton', local);
setVisibility('mutebutton', permissions.present);
// allow multiple shared documents
setVisibility('sharebutton', permissions.present &&
('getDisplayMedia' in navigator.mediaDevices));
setVisibility('unsharebutton', share);
2020-11-24 22:41:43 +01:00
setVisibility('stopvideobutton', video);
setVisibility('mediaoptions', permissions.present);
setVisibility('sendform', permissions.present);
setVisibility('fileform', canFile && permissions.present);
}
2020-09-12 16:34:52 +02:00
/**
* @param {boolean} mute
2020-11-30 14:22:36 +01:00
* @param {boolean} [reflect]
2020-09-12 16:34:52 +02:00
*/
2020-11-30 14:22:36 +01:00
function setLocalMute(mute, reflect) {
muteLocalTracks(mute);
2020-06-09 18:05:16 +02:00
let button = document.getElementById('mutebutton');
2020-11-09 15:57:30 +01:00
let icon = button.querySelector("span .fas");
if(mute){
2020-09-11 10:39:32 +02:00
icon.classList.add('fa-microphone-slash');
icon.classList.remove('fa-microphone');
2020-06-09 18:05:16 +02:00
button.classList.add('muted');
2020-09-11 10:39:32 +02:00
} else {
icon.classList.remove('fa-microphone-slash');
icon.classList.add('fa-microphone');
2020-06-09 18:05:16 +02:00
button.classList.remove('muted');
2020-09-11 10:39:32 +02:00
}
2020-11-30 14:22:36 +01:00
if(reflect)
updateSettings({localMute: mute});
2020-06-09 18:05:16 +02:00
}
getSelectElement('videoselect').onchange = function(e) {
e.preventDefault();
if(!(this instanceof HTMLSelectElement))
throw new Error('Unexpected type for this');
updateSettings({video: this.value});
changePresentation();
2020-05-10 21:18:07 +02:00
};
getSelectElement('audioselect').onchange = function(e) {
e.preventDefault();
if(!(this instanceof HTMLSelectElement))
throw new Error('Unexpected type for this');
updateSettings({audio: this.value});
changePresentation();
2020-05-10 21:18:07 +02:00
};
2021-01-23 01:15:53 +01:00
getInputElement('mirrorbox').onchange = function(e) {
e.preventDefault();
if(!(this instanceof HTMLInputElement))
throw new Error('Unexpected type for this');
updateSettings({mirrorView: this.checked});
changePresentation();
};
getInputElement('blackboardbox').onchange = function(e) {
2020-09-18 19:14:10 +02:00
e.preventDefault();
if(!(this instanceof HTMLInputElement))
throw new Error('Unexpected type for this');
2020-09-18 19:14:10 +02:00
updateSettings({blackboardMode: this.checked});
changePresentation();
2020-12-26 17:28:44 +01:00
};
2020-09-18 19:14:10 +02:00
2020-06-09 18:05:16 +02:00
document.getElementById('mutebutton').onclick = function(e) {
e.preventDefault();
let localMute = getSettings().localMute;
localMute = !localMute;
2020-11-30 14:22:36 +01:00
setLocalMute(localMute, true);
2020-12-26 17:28:44 +01:00
};
2020-06-09 18:05:16 +02:00
document.getElementById('sharebutton').onclick = function(e) {
2020-04-24 19:38:21 +02:00
e.preventDefault();
addShareMedia();
2020-05-10 21:18:07 +02:00
};
2020-04-24 19:38:21 +02:00
document.getElementById('unsharebutton').onclick = function(e) {
e.preventDefault();
closeUpMediaKind('screenshare');
2020-10-31 01:15:03 +01:00
resizePeers();
2020-12-26 17:28:44 +01:00
};
2020-11-24 22:41:43 +01:00
document.getElementById('stopvideobutton').onclick = function(e) {
e.preventDefault();
closeUpMediaKind('video');
2020-11-24 22:41:43 +01:00
resizePeers();
2020-12-26 17:28:44 +01:00
};
2020-11-24 22:41:43 +01:00
getSelectElement('filterselect').onchange = async function(e) {
if(!(this instanceof HTMLSelectElement))
throw new Error('Unexpected type for this');
updateSettings({filter: this.value});
changePresentation();
};
/** @returns {number} */
function getMaxVideoThroughput() {
let v = getSettings().send;
switch(v) {
case 'lowest':
return 150000;
case 'low':
return 300000;
case 'normal':
return 700000;
case 'unlimited':
return null;
default:
console.error('Unknown video quality', v);
return 700000;
}
}
getSelectElement('sendselect').onchange = async function(e) {
if(!(this instanceof HTMLSelectElement))
throw new Error('Unexpected type for this');
updateSettings({send: this.value});
let t = getMaxVideoThroughput();
for(let id in serverConnection.up) {
let c = serverConnection.up[id];
await setMaxVideoThroughput(c, t);
}
2020-12-26 17:28:44 +01:00
};
getSelectElement('requestselect').onchange = function(e) {
2020-05-09 19:39:34 +02:00
e.preventDefault();
if(!(this instanceof HTMLSelectElement))
throw new Error('Unexpected type for this');
updateSettings({request: this.value});
serverConnection.request(this.value);
2020-05-10 21:18:07 +02:00
};
2020-05-09 19:39:34 +02:00
const activityDetectionInterval = 200;
2020-09-11 23:20:46 +02:00
const activityDetectionPeriod = 700;
const activityDetectionThreshold = 0.2;
getInputElement('activitybox').onchange = function(e) {
if(!(this instanceof HTMLInputElement))
throw new Error('Unexpected type for this');
updateSettings({activityDetection: this.checked});
2020-09-11 23:20:46 +02:00
for(let id in serverConnection.down) {
let c = serverConnection.down[id];
if(this.checked)
2020-09-11 23:20:46 +02:00
c.setStatsInterval(activityDetectionInterval);
else {
c.setStatsInterval(0);
setActive(c, false);
2020-09-11 23:20:46 +02:00
}
}
2020-12-26 17:28:44 +01:00
};
2020-09-11 23:20:46 +02:00
2020-11-24 19:22:38 +01:00
getInputElement('fileinput').onchange = function(e) {
2020-11-28 02:08:52 +01:00
if(!(this instanceof HTMLInputElement))
throw new Error('Unexpected type for this');
let input = this;
2020-11-24 19:22:38 +01:00
let files = input.files;
for(let i = 0; i < files.length; i++) {
addFileMedia(files[i]).catch(e => {
console.error(e);
displayError(e);
});
}
2020-11-24 22:41:43 +01:00
input.value = '';
closeNav();
2020-12-26 17:28:44 +01:00
};
2020-11-24 19:22:38 +01:00
/**
* @this {Stream}
* @param {Object<string,any>} stats
*/
2020-09-11 23:20:46 +02:00
function gotUpStats(stats) {
let c = this;
2020-04-26 19:21:01 +02:00
let text = '';
c.pc.getSenders().forEach(s => {
let tid = s.track && s.track.id;
let stats = tid && c.stats[tid];
2020-09-11 23:20:46 +02:00
let rate = stats && stats['outbound-rtp'] && stats['outbound-rtp'].rate;
if(typeof rate === 'number') {
if(text)
text = text + ' + ';
2020-09-11 23:20:46 +02:00
text = text + Math.round(rate / 1000) + 'kbps';
}
});
setLabel(c, text);
2020-04-26 19:21:01 +02:00
}
2020-09-11 23:20:46 +02:00
/**
* @param {Stream} c
* @param {boolean} value
*/
function setActive(c, value) {
let peer = document.getElementById('peer-' + c.localId);
2020-09-11 23:20:46 +02:00
if(value)
peer.classList.add('peer-active');
else
peer.classList.remove('peer-active');
}
/**
* @this {Stream}
* @param {Object<string,any>} stats
*/
2020-09-11 23:20:46 +02:00
function gotDownStats(stats) {
if(!getInputElement('activitybox').checked)
2020-09-11 23:20:46 +02:00
return;
let c = this;
let maxEnergy = 0;
c.pc.getReceivers().forEach(r => {
let tid = r.track && r.track.id;
let s = tid && stats[tid];
let energy = s && s['track'] && s['track'].audioEnergy;
if(typeof energy === 'number')
maxEnergy = Math.max(maxEnergy, energy);
});
// totalAudioEnergy is defined as the integral of the square of the
// volume, so square the threshold.
if(maxEnergy > activityDetectionThreshold * activityDetectionThreshold) {
c.userdata.lastVoiceActivity = Date.now();
setActive(c, true);
} else {
let last = c.userdata.lastVoiceActivity;
if(!last || Date.now() - last > activityDetectionPeriod)
setActive(c, false);
}
}
2020-09-12 16:34:52 +02:00
/**
* @param {HTMLSelectElement} select
* @param {string} label
* @param {string} [value]
2020-09-12 16:34:52 +02:00
*/
function addSelectOption(select, label, value) {
if(!value)
value = label;
for(let i = 0; i < select.children.length; i++) {
let child = select.children[i];
if(!(child instanceof HTMLOptionElement)) {
console.warn('Unexpected select child');
continue;
}
if(child.value === value) {
if(child.label !== label) {
child.label = label;
}
return;
}
}
let option = document.createElement('option');
option.value = value;
option.textContent = label;
select.appendChild(option);
}
/**
* @param {HTMLSelectElement} select
* @param {string} value
*/
function selectOptionAvailable(select, value) {
let children = select.children;
for(let i = 0; i < children.length; i++) {
let child = select.children[i];
if(!(child instanceof HTMLOptionElement)) {
console.warn('Unexpected select child');
continue;
}
if(child.value === value)
return true;
}
return false;
}
/**
* @param {HTMLSelectElement} select
* @returns {string}
*/
function selectOptionDefault(select) {
/* First non-empty option. */
for(let i = 0; i < select.children.length; i++) {
let child = select.children[i];
if(!(child instanceof HTMLOptionElement)) {
console.warn('Unexpected select child');
continue;
}
if(child.value)
return child.value;
}
/* The empty option is always available. */
return '';
}
/* media names might not be available before we call getDisplayMedia. So
we call this twice, the second time to update the menu with user-readable
labels. */
2020-08-24 22:37:48 +02:00
/** @type {boolean} */
let mediaChoicesDone = false;
/**
* @param{boolean} done
*/
async function setMediaChoices(done) {
if(mediaChoicesDone)
return;
let devices = [];
try {
devices = await navigator.mediaDevices.enumerateDevices();
} catch(e) {
console.error(e);
return;
}
let cn = 1, mn = 1;
devices.forEach(d => {
let label = d.label;
if(d.kind === 'videoinput') {
if(!label)
label = `Camera ${cn}`;
addSelectOption(getSelectElement('videoselect'),
label, d.deviceId);
cn++;
} else if(d.kind === 'audioinput') {
if(!label)
label = `Microphone ${mn}`;
addSelectOption(getSelectElement('audioselect'),
label, d.deviceId);
mn++;
}
});
mediaChoicesDone = done;
}
/**
* @param {string} [localId]
*/
function newUpStream(localId) {
let c = serverConnection.newUpStream(localId);
c.onstatus = function(status) {
setMediaStatus(c);
2020-12-26 17:28:44 +01:00
};
c.onerror = function(e) {
console.error(e);
displayError(e);
2020-12-26 17:28:44 +01:00
};
c.onnegotiationcompleted = function() {
2020-12-26 17:28:44 +01:00
setMaxVideoThroughput(c, getMaxVideoThroughput());
};
return c;
}
/**
* @param {Stream} c
* @param {number} [bps]
*/
async function setMaxVideoThroughput(c, bps) {
let senders = c.pc.getSenders();
for(let i = 0; i < senders.length; i++) {
let s = senders[i];
if(!s.track || s.track.kind !== 'video')
continue;
let p = s.getParameters();
if(!p.encodings)
p.encodings = [{}];
p.encodings.forEach(e => {
if(bps > 0)
e.maxBitrate = bps;
else
delete e.maxBitrate;
});
try {
await s.setParameters(p);
} catch(e) {
console.error(e);
}
}
}
/**
* @typedef {Object} filterDefinition
* @property {string} [description]
* @property {string} [contextType]
* @property {Object} [contextAttributes]
2021-01-13 18:10:16 +01:00
* @property {(this: Filter, ctx: RenderingContext) => void} [init]
* @property {(this: Filter) => void} [cleanup]
* @property {(this: Filter, src: CanvasImageSource, width: number, height: number, ctx: RenderingContext) => boolean} f
*/
/**
* @param {MediaStream} stream
* @param {filterDefinition} definition
* @constructor
*/
function Filter(stream, definition) {
/** @ts-ignore */
if(!HTMLCanvasElement.prototype.captureStream) {
throw new Error('Filters are not supported on this platform');
}
/** @type {MediaStream} */
this.inputStream = stream;
/** @type {filterDefinition} */
this.definition = definition;
/** @type {number} */
this.frameRate = 30;
/** @type {HTMLVideoElement} */
this.video = document.createElement('video');
/** @type {HTMLCanvasElement} */
this.canvas = document.createElement('canvas');
/** @type {any} */
this.context = this.canvas.getContext(
definition.contextType || '2d',
definition.contextAttributes || null);
/** @type {MediaStream} */
this.captureStream = null;
/** @type {MediaStream} */
this.outputStream = null;
/** @type {number} */
this.timer = null;
/** @type {number} */
this.count = 0;
/** @type {boolean} */
this.fixedFramerate = false;
2021-01-13 18:10:16 +01:00
/** @type {Object} */
this.userdata = {}
/** @ts-ignore */
this.captureStream = this.canvas.captureStream(0);
/** @ts-ignore */
if(!this.captureStream.getTracks()[0].requestFrame) {
console.warn('captureFrame not supported, using fixed framerate');
/** @ts-ignore */
this.captureStream = this.canvas.captureStream(this.frameRate);
this.fixedFramerate = true;
}
this.outputStream = new MediaStream();
this.outputStream.addTrack(this.captureStream.getTracks()[0]);
this.inputStream.getTracks().forEach(t => {
t.onended = e => this.stop();
if(t.kind != 'video')
this.outputStream.addTrack(t);
});
this.video.srcObject = stream;
this.video.muted = true;
this.video.play();
2021-01-13 18:10:16 +01:00
if(this.definition.init)
this.definition.init.call(this, this.context);
this.timer = setInterval(() => this.draw(), 1000 / this.frameRate);
}
Filter.prototype.draw = function() {
// check framerate evecry 30 frames
if((this.count % 30) === 0) {
let frameRate = 0;
this.inputStream.getTracks().forEach(t => {
if(t.kind === 'video') {
let r = t.getSettings().frameRate;
if(r)
frameRate = r;
}
});
if(frameRate && frameRate != this.frameRate) {
clearInterval(this.timer);
this.timer = setInterval(() => this.draw(), 1000 / this.frameRate);
}
}
2021-01-13 17:07:40 +01:00
let ok = false;
try {
ok = this.definition.f.call(this, this.video,
this.video.videoWidth,
this.video.videoHeight,
this.context);
2021-01-13 17:07:40 +01:00
} catch(e) {
console.error(e);
}
if(ok && !this.fixedFramerate) {
/** @ts-ignore */
this.captureStream.getTracks()[0].requestFrame();
}
2021-01-13 17:07:40 +01:00
this.count++;
};
Filter.prototype.stop = function() {
if(!this.timer)
return;
this.captureStream.getTracks()[0].stop();
clearInterval(this.timer);
this.timer = null;
2021-01-13 18:10:16 +01:00
if(this.definition.cleanup)
this.definition.cleanup.call(this);
};
/**
* @param {Stream} c
* @param {Filter} f
*/
function setFilter(c, f) {
if(!f) {
let filter = c.userdata.filter;
2021-01-13 17:07:40 +01:00
if(!filter)
return null;
if(!(filter instanceof Filter))
throw new Error('userdata.filter is not a filter');
if(c.userdata.filter) {
c.stream = c.userdata.filter.inputStream;
c.userdata.filter.stop();
c.userdata.filter = null;
}
return
}
if(c.userdata.filter)
setFilter(c, null);
if(f.inputStream != c.stream)
throw new Error('Setting filter for wrong stream');
c.stream = f.outputStream;
c.userdata.filter = f;
}
/**
* @type {Object.<string,filterDefinition>}
*/
let filters = {
'mirror-h': {
description: "Horizontal mirror",
f: function(src, width, height, ctx) {
if(!(ctx instanceof CanvasRenderingContext2D))
throw new Error('bad context type');
2021-01-13 17:07:40 +01:00
if(ctx.canvas.width !== width || ctx.canvas.height !== height) {
ctx.canvas.width = width;
ctx.canvas.height = height;
}
ctx.scale(-1, 1);
ctx.drawImage(src, -width, 0);
2021-01-13 14:36:29 +01:00
ctx.resetTransform();
return true;
},
},
'mirror-v': {
description: "Vertical mirror",
f: function(src, width, height, ctx) {
if(!(ctx instanceof CanvasRenderingContext2D))
throw new Error('bad context type');
2021-01-13 17:07:40 +01:00
if(ctx.canvas.width !== width || ctx.canvas.height !== height) {
ctx.canvas.width = width;
ctx.canvas.height = height;
}
ctx.scale(1, -1);
ctx.drawImage(src, 0, -height);
2021-01-13 14:36:29 +01:00
ctx.resetTransform();
return true;
},
},
};
function addFilters() {
for(let name in filters) {
let f = filters[name];
let d = f.description || name;
addSelectOption(getSelectElement('filterselect'), d, name);
}
}
function isSafari() {
let ua = navigator.userAgent.toLowerCase();
return ua.indexOf('safari') >= 0 && ua.indexOf('chrome') < 0;
}
/**
* @param {string} [localId]
*/
async function addLocalMedia(localId) {
let settings = getSettings();
let audio = settings.audio ? {deviceId: settings.audio} : false;
let video = settings.video ? {deviceId: settings.video} : false;
let filter = null;
if(settings.filter) {
filter = filters[settings.filter];
if(!filter) {
displayWarning(`Unknown filter ${settings.filter}`);
}
}
2020-09-18 19:14:10 +02:00
if(video) {
let resolution = settings.resolution;
if(resolution) {
video.width = { ideal: resolution[0] };
video.height = { ideal: resolution[1] };
} else if(settings.blackboardMode) {
2020-09-18 19:14:10 +02:00
video.width = { min: 640, ideal: 1920 };
video.height = { min: 400, ideal: 1080 };
}
}
let old = serverConnection.findByLocalId(localId);
if(old && old.onclose) {
// make sure that the camera is released before we try to reopen it
old.onclose.call(old, true);
}
let constraints = {audio: audio, video: video};
/** @type {MediaStream} */
let stream = null;
try {
stream = await navigator.mediaDevices.getUserMedia(constraints);
} catch(e) {
displayError(e);
return;
2020-04-24 19:38:21 +02:00
}
setMediaChoices(true);
let c = newUpStream(localId);
c.kind = 'local';
c.stream = stream;
if(filter) {
try {
let f = new Filter(stream, filter);
setFilter(c, f);
c.onclose = replace => {
stopStream(stream);
setFilter(c, null);
if(!replace)
delMedia(c.localId);
}
} catch(e) {
displayWarning(e);
c.onclose = replace => {
stopStream(c.stream);
if(!replace)
delMedia(c.localId);
}
}
} else {
c.onclose = replace => {
stopStream(c.stream);
if(!replace)
delMedia(c.localId);
}
}
let mute = getSettings().localMute;
c.stream.getTracks().forEach(t => {
2020-12-26 17:28:44 +01:00
c.labels[t.id] = t.kind;
2020-09-18 19:14:10 +02:00
if(t.kind == 'audio') {
if(mute)
t.enabled = false;
} else if(t.kind == 'video') {
if(settings.blackboardMode) {
/** @ts-ignore */
t.contentHint = 'detail';
2020-09-18 19:14:10 +02:00
}
}
c.pc.addTrack(t, stream);
});
2020-09-11 23:20:46 +02:00
c.onstats = gotUpStats;
c.setStatsInterval(2000);
2021-01-23 01:15:53 +01:00
await setMedia(c, true, settings.mirrorView);
setButtonsVisibility();
2020-04-24 19:38:21 +02:00
}
let safariScreenshareDone = false;
async function addShareMedia() {
/** @type {MediaStream} */
let stream = null;
try {
if(!('getDisplayMedia' in navigator.mediaDevices))
throw new Error('Your browser does not support screen sharing');
/** @ts-ignore */
stream = await navigator.mediaDevices.getDisplayMedia({video: true});
} catch(e) {
console.error(e);
displayError(e);
2020-04-24 19:38:21 +02:00
return;
}
if(!safariScreenshareDone) {
if(isSafari())
displayWarning('Screen sharing under Safari is experimental. ' +
'Please use a different browser if possible.');
safariScreenshareDone = true;
}
let c = newUpStream();
c.kind = 'screenshare';
c.stream = stream;
c.onclose = replace => {
stopStream(stream);
if(!replace)
delMedia(c.localId);
}
stream.getTracks().forEach(t => {
c.pc.addTrack(t, stream);
t.onended = e => c.close();
c.labels[t.id] = 'screenshare';
});
2020-09-11 23:20:46 +02:00
c.onstats = gotUpStats;
c.setStatsInterval(2000);
await setMedia(c, true);
2020-12-26 17:28:44 +01:00
setButtonsVisibility();
}
2020-11-24 19:22:38 +01:00
/**
* @param {File} file
*/
async function addFileMedia(file) {
let url = URL.createObjectURL(file);
let video = document.createElement('video');
video.src = url;
video.controls = true;
2021-02-01 01:08:39 +01:00
let stream;
/** @ts-ignore */
if(video.captureStream)
/** @ts-ignore */
stream = video.captureStream();
2020-11-24 19:22:38 +01:00
/** @ts-ignore */
2021-02-01 01:08:39 +01:00
else if(video.mozCaptureStream)
/** @ts-ignore */
stream = video.mozCaptureStream();
else {
displayError("This browser doesn't support file playback");
return;
}
2020-11-24 19:22:38 +01:00
let c = newUpStream();
c.kind = 'video';
c.stream = stream;
c.onclose = function(replace) {
stopStream(c.stream);
let media = /** @type{HTMLVideoElement} */
(document.getElementById('media-' + this.localId));
if(media && media.src) {
URL.revokeObjectURL(media.src);
media.src = null;
}
if(!replace)
delMedia(c.localId);
};
2020-11-24 19:22:38 +01:00
stream.onaddtrack = function(e) {
let t = e.track;
2020-11-29 21:48:14 +01:00
if(t.kind === 'audio') {
let presenting = !!findUpMedia('local');
let muted = getSettings().localMute;
if(presenting && !muted) {
2020-11-30 14:22:36 +01:00
setLocalMute(true, true);
2020-11-29 21:48:14 +01:00
displayWarning('You have been muted');
}
}
2020-11-24 19:22:38 +01:00
c.pc.addTrack(t, stream);
c.labels[t.id] = t.kind;
c.onstats = gotUpStats;
c.setStatsInterval(2000);
};
stream.onremovetrack = function(e) {
let t = e.track;
delete(c.labels[t.id]);
/** @type {RTCRtpSender} */
let sender;
c.pc.getSenders().forEach(s => {
if(s.track === t)
sender = s;
});
if(sender) {
2020-12-26 17:28:44 +01:00
c.pc.removeTrack(sender);
} else {
console.warn('Removing unknown track');
}
if(Object.keys(c.labels).length === 0) {
stream.onaddtrack = null;
stream.onremovetrack = null;
c.close();
}
};
await setMedia(c, true, false, video);
c.userdata.play = true;
2020-12-26 17:28:44 +01:00
setButtonsVisibility();
2020-11-24 19:22:38 +01:00
}
/**
* @param {MediaStream} s
*/
function stopStream(s) {
s.getTracks().forEach(t => {
try {
t.stop();
} catch(e) {
console.warn(e);
}
});
}
/**
* closeUpMediaKind closes all up connections that correspond to a given
* kind of media. If kind is null, it closes all up connections.
*
* @param {string} kind
*/
function closeUpMediaKind(kind) {
for(let id in serverConnection.up) {
let c = serverConnection.up[id];
if(kind && c.kind != kind)
continue
c.close();
2020-04-24 19:38:21 +02:00
}
}
/**
* @param {string} kind
* @returns {Stream}
*/
function findUpMedia(kind) {
for(let id in serverConnection.up) {
let c = serverConnection.up[id]
if(c.kind === kind)
return c;
}
return null;
2020-04-24 19:38:21 +02:00
}
/**
* @param {boolean} mute
*/
2020-06-09 18:05:16 +02:00
function muteLocalTracks(mute) {
if(!serverConnection)
return;
for(let id in serverConnection.up) {
let c = serverConnection.up[id];
2020-06-09 18:05:16 +02:00
if(c.kind === 'local') {
let stream = c.stream;
stream.getTracks().forEach(t => {
if(t.kind === 'audio') {
t.enabled = !mute;
}
});
}
}
}
/**
* setMedia adds a new media element corresponding to stream c.
*
* @param {Stream} c
* @param {boolean} isUp
* - indicates whether the stream goes in the up direction
2020-12-03 18:38:36 +01:00
* @param {boolean} [mirror]
* - whether to mirror the video
2020-11-24 19:22:38 +01:00
* @param {HTMLVideoElement} [video]
* - the video element to add. If null, a new element with custom
* controls will be created.
*/
async function setMedia(c, isUp, mirror, video) {
2020-04-24 19:38:21 +02:00
let peersdiv = document.getElementById('peers');
let div = document.getElementById('peer-' + c.localId);
2020-04-24 19:38:21 +02:00
if(!div) {
div = document.createElement('div');
div.id = 'peer-' + c.localId;
2020-04-24 19:38:21 +02:00
div.classList.add('peer');
peersdiv.appendChild(div);
}
let media = /** @type {HTMLVideoElement} */
(document.getElementById('media-' + c.localId));
if(media) {
if(video) {
throw new Error("Duplicate video");
}
} else {
2020-11-24 19:22:38 +01:00
if(video) {
media = video;
} else {
media = document.createElement('video');
if(isUp)
media.muted = true;
}
2020-04-24 19:38:21 +02:00
media.classList.add('media');
media.autoplay = true;
/** @ts-ignore */
2020-04-24 19:38:21 +02:00
media.playsinline = true;
media.id = 'media-' + c.localId;
2020-04-24 19:38:21 +02:00
div.appendChild(media);
if(!video)
addCustomControls(media, div, c);
2020-04-24 19:38:21 +02:00
}
if(mirror)
media.classList.add('mirror');
else
media.classList.remove('mirror');
if(!video && media.srcObject !== c.stream)
media.srcObject = c.stream;
let label = document.getElementById('label-' + c.localId);
2020-04-24 19:38:21 +02:00
if(!label) {
label = document.createElement('div');
label.id = 'label-' + c.localId;
2020-04-24 19:38:21 +02:00
label.classList.add('label');
2020-05-10 21:18:07 +02:00
div.appendChild(label);
2020-04-24 19:38:21 +02:00
}
setLabel(c);
setMediaStatus(c);
2020-05-01 01:22:17 +02:00
showVideo();
2020-05-01 01:22:17 +02:00
resizePeers();
if(!isUp && isSafari() && !findUpMedia('local')) {
// Safari doesn't allow autoplay unless the user has granted media access
try {
let stream = await navigator.mediaDevices.getUserMedia({audio: true});
stream.getTracks().forEach(t => t.stop());
} catch(e) {
}
}
}
/**
* @param {Element} elt
*/
function cloneHTMLElement(elt) {
if(!(elt instanceof HTMLElement))
throw new Error('Unexpected element type');
return /** @type{HTMLElement} */(elt.cloneNode(true));
}
/**
* @param {HTMLVideoElement} media
* @param {HTMLElement} container
* @param {Stream} c
*/
function addCustomControls(media, container, c) {
media.controls = false;
let controls = document.getElementById('controls-' + c.localId);
if(controls) {
console.warn('Attempted to add duplicate controls');
return;
}
let template =
document.getElementById('videocontrols-template').firstElementChild;
controls = cloneHTMLElement(template);
controls.id = 'controls-' + c.localId;
let volume = getVideoButton(controls, 'volume');
if(c.kind === 'local') {
volume.remove();
} else {
setVolumeButton(media.muted,
getVideoButton(controls, "volume-mute"),
getVideoButton(controls, "volume-slider"));
}
container.appendChild(controls);
registerControlHandlers(media, container);
}
/**
* @param {HTMLElement} container
* @param {string} name
*/
function getVideoButton(container, name) {
return /** @type {HTMLElement} */(container.getElementsByClassName(name)[0]);
}
/**
* @param {boolean} muted
* @param {HTMLElement} button
* @param {HTMLElement} slider
*/
function setVolumeButton(muted, button, slider) {
if(!muted) {
button.classList.remove("fa-volume-mute");
button.classList.add("fa-volume-up");
} else {
button.classList.remove("fa-volume-up");
button.classList.add("fa-volume-mute");
}
if(!(slider instanceof HTMLInputElement))
throw new Error("Couldn't find volume slider");
slider.disabled = muted;
2020-04-24 19:38:21 +02:00
}
/**
* @param {HTMLVideoElement} media
* @param {HTMLElement} container
*/
function registerControlHandlers(media, container) {
let play = getVideoButton(container, 'video-play');
if(play) {
play.onclick = function(event) {
event.preventDefault();
media.play();
};
}
let volume = getVideoButton(container, 'volume');
if (volume) {
volume.onclick = function(event) {
let target = /** @type{HTMLElement} */(event.target);
if(!target.classList.contains('volume-mute'))
// if click on volume slider, do nothing
return;
event.preventDefault();
media.muted = !media.muted;
setVolumeButton(media.muted, target,
getVideoButton(volume, "volume-slider"));
};
volume.oninput = function() {
let slider = /** @type{HTMLInputElement} */
(getVideoButton(volume, "volume-slider"));
media.volume = parseInt(slider.value, 10)/100;
};
}
2020-11-08 17:07:17 +01:00
let pip = getVideoButton(container, 'pip');
if(pip) {
/** @ts-ignore */
if(HTMLVideoElement.prototype.requestPictureInPicture) {
pip.onclick = function(e) {
e.preventDefault();
/** @ts-ignore */
if(media.requestPictureInPicture) {
/** @ts-ignore */
media.requestPictureInPicture();
} else {
displayWarning('Picture in Picture not supported.');
}
};
} else {
pip.style.display = 'none';
}
2020-11-09 00:35:52 +01:00
}
2020-11-08 17:07:17 +01:00
let fs = getVideoButton(container, 'fullscreen');
if(fs) {
2020-12-05 14:13:30 +01:00
if(HTMLVideoElement.prototype.requestFullscreen ||
/** @ts-ignore */
HTMLVideoElement.prototype.webkitRequestFullscreen) {
fs.onclick = function(e) {
e.preventDefault();
if(media.requestFullscreen) {
media.requestFullscreen();
2020-12-05 14:13:30 +01:00
/** @ts-ignore */
} else if(media.webkitRequestFullscreen) {
/** @ts-ignore */
media.webkitRequestFullscreen();
} else {
displayWarning('Full screen not supported!');
}
};
} else {
fs.style.display = 'none';
}
}
2020-04-24 19:38:21 +02:00
}
2020-09-12 16:34:52 +02:00
/**
* @param {string} localId
2020-09-12 16:34:52 +02:00
*/
function delMedia(localId) {
2020-04-24 19:38:21 +02:00
let mediadiv = document.getElementById('peers');
let peer = document.getElementById('peer-' + localId);
2020-08-19 14:39:40 +02:00
if(!peer)
throw new Error('Removing unknown media');
let media = /** @type{HTMLVideoElement} */
(document.getElementById('media-' + localId));
2020-04-24 19:38:21 +02:00
media.srcObject = null;
mediadiv.removeChild(peer);
2020-05-01 01:22:17 +02:00
setButtonsVisibility();
2020-05-01 01:22:17 +02:00
resizePeers();
hideVideo();
2020-04-24 19:38:21 +02:00
}
/**
* @param {Stream} c
*/
function setMediaStatus(c) {
2020-06-12 21:28:35 +02:00
let state = c && c.pc && c.pc.iceConnectionState;
let good = state === 'connected' || state === 'completed';
let media = document.getElementById('media-' + c.localId);
if(!media) {
console.warn('Setting status of unknown media.');
return;
}
if(good) {
media.classList.remove('media-failed');
if(c.userdata.play) {
if(media instanceof HTMLMediaElement)
media.play().catch(e => {
console.error(e);
displayError(e);
});
delete(c.userdata.play);
}
} else {
media.classList.add('media-failed');
}
}
/**
* @param {Stream} c
* @param {string} [fallback]
*/
function setLabel(c, fallback) {
let label = document.getElementById('label-' + c.localId);
2020-04-24 19:38:21 +02:00
if(!label)
return;
let l = c.username;
2020-04-25 14:45:48 +02:00
if(l) {
label.textContent = l;
label.classList.remove('label-fallback');
} else if(fallback) {
label.textContent = fallback;
label.classList.add('label-fallback');
} else {
label.textContent = '';
label.classList.remove('label-fallback');
}
2020-04-24 19:38:21 +02:00
}
2020-05-01 01:22:17 +02:00
function resizePeers() {
// Window resize can call this method too early
if (!serverConnection)
return;
let count =
Object.keys(serverConnection.up).length +
Object.keys(serverConnection.down).length;
let peers = document.getElementById('peers');
2020-05-01 01:22:17 +02:00
let columns = Math.ceil(Math.sqrt(count));
2020-09-03 20:54:27 +02:00
if (!count)
// No video, nothing to resize.
return;
let container = document.getElementById("video-container");
// Peers div has total padding of 40px, we remove 40 on offsetHeight
// Grid has row-gap of 5px
let rows = Math.ceil(count / columns);
let margins = (rows - 1) * 5 + 40;
if (count <= 2 && container.offsetHeight > container.offsetWidth) {
peers.style['grid-template-columns'] = "repeat(1, 1fr)";
rows = count;
} else {
peers.style['grid-template-columns'] = `repeat(${columns}, 1fr)`;
}
if (count === 1)
return;
let max_video_height = (peers.offsetHeight - margins) / rows;
let media_list = peers.querySelectorAll(".media");
for(let i = 0; i < media_list.length; i++) {
let media = media_list[i];
if(!(media instanceof HTMLMediaElement)) {
console.warn('Unexpected media');
continue;
}
media.style['max-height'] = max_video_height + "px";
2020-09-09 20:26:19 +02:00
}
2020-05-01 01:22:17 +02:00
}
/** @type{Object<string,string>} */
2020-04-24 19:38:21 +02:00
let users = {};
/**
* Lexicographic order, with case differences secondary.
* @param{string} a
* @param{string} b
*/
function stringCompare(a, b) {
2020-12-26 17:28:44 +01:00
let la = a.toLowerCase();
let lb = b.toLowerCase();
if(la < lb)
return -1;
else if(la > lb)
return +1;
else if(a < b)
return -1;
else if(a > b)
return +1;
return 0
}
/**
* @param {string} id
* @param {string} name
*/
2020-04-24 19:38:21 +02:00
function addUser(id, name) {
if(!name)
name = null;
if(id in users)
throw new Error('Duplicate user id');
users[id] = name;
let div = document.getElementById('users');
let user = document.createElement('div');
user.id = 'user-' + id;
2020-09-11 10:39:32 +02:00
user.classList.add("user-p");
2020-04-24 19:38:21 +02:00
user.textContent = name ? name : '(anon)';
2020-09-12 15:23:38 +02:00
if(name) {
let us = div.children;
for(let i = 0; i < us.length; i++) {
let child = us[i];
let childname = users[child.id.slice('user-'.length)] || null;
if(!childname || stringCompare(childname, name) > 0) {
2020-09-12 15:23:38 +02:00
div.insertBefore(user, child);
return;
}
}
}
2020-04-24 19:38:21 +02:00
div.appendChild(user);
}
/**
* @param {string} id
* @param {string} name
*/
2020-04-24 19:38:21 +02:00
function delUser(id, name) {
if(!name)
name = null;
if(!(id in users))
2020-04-24 19:38:21 +02:00
throw new Error('Unknown user id');
if(users[id] !== name)
throw new Error('Inconsistent user name');
delete(users[id]);
let div = document.getElementById('users');
let user = document.getElementById('user-' + id);
div.removeChild(user);
}
function resetUsers() {
for(let id in users)
delUser(id, users[id]);
}
/**
* @param {string} id
* @param {string} kind
* @param {string} name
*/
2020-08-12 13:51:31 +02:00
function gotUser(id, kind, name) {
switch(kind) {
case 'add':
2020-04-24 19:38:21 +02:00
addUser(id, name);
2020-08-12 13:51:31 +02:00
break;
case 'delete':
delUser(id, name);
break;
default:
console.warn('Unknown user kind', kind);
break;
}
2020-04-24 19:38:21 +02:00
}
2020-04-25 18:09:31 +02:00
function displayUsername() {
let userpass = getUserPass();
let text = '';
if(userpass && userpass.username)
2020-11-24 17:36:52 +01:00
document.getElementById('userspan').textContent = userpass.username;
if(serverConnection.permissions.op && serverConnection.permissions.present)
2020-11-24 17:36:52 +01:00
text = '(op, presenter)';
else if(serverConnection.permissions.op)
2020-11-24 17:36:52 +01:00
text = 'operator';
else if(serverConnection.permissions.present)
2020-11-24 17:36:52 +01:00
text = 'presenter';
document.getElementById('permspan').textContent = text;
2020-04-25 18:09:31 +02:00
}
let presentRequested = null;
/**
* @this {ServerConnection}
* @param {string} group
* @param {Object<string,boolean>} perms
*/
async function gotJoined(kind, group, perms, message) {
let present = presentRequested;
presentRequested = null;
switch(kind) {
case 'fail':
displayError('The server said: ' + message);
this.close();
return;
case 'redirect':
this.close();
document.location = message;
return;
case 'leave':
this.close();
return;
case 'join':
case 'change':
displayUsername();
setButtonsVisibility();
if(kind === 'change')
return;
break;
default:
displayError('Unknown join message');
this.close();
return;
}
let input = /** @type{HTMLTextAreaElement} */
(document.getElementById('input'));
input.placeholder = 'Type /help for help';
setTimeout(() => {input.placeholder = '';}, 8000);
this.request(getSettings().request);
if(serverConnection.permissions.present && !findUpMedia('local')) {
if(present) {
if(present === 'mike')
updateSettings({video: ''});
else if(present === 'both')
delSetting('video');
reflectSettings();
let button = getButtonElement('presentbutton');
button.disabled = true;
try {
await addLocalMedia();
} finally {
button.disabled = false;
}
} else {
displayMessage(
"Press Ready to enable your camera or microphone"
);
}
}
2020-04-25 02:25:51 +02:00
}
/**
* @param {string} id
* @param {string} dest
* @param {string} username
* @param {number} time
* @param {boolean} privileged
* @param {string} kind
* @param {unknown} message
*/
function gotUserMessage(id, dest, username, time, privileged, kind, message) {
switch(kind) {
case 'error':
case 'warning':
case 'info':
let from = id ? (username || 'Anonymous') : 'The Server';
if(privileged)
displayError(`${from} said: ${message}`, kind);
else
console.error(`Got unprivileged message of kind ${kind}`);
break;
case 'mute':
if(privileged) {
setLocalMute(true, true);
let by = username ? ' by ' + username : '';
displayWarning(`You have been muted${by}`);
} else {
console.error(`Got unprivileged message of kind ${kind}`);
}
break;
2021-01-03 17:47:56 +01:00
case 'clearchat':
if(privileged) {
clearChat();
} else {
console.error(`Got unprivileged message of kind ${kind}`);
}
2021-01-04 13:15:50 +01:00
break;
default:
console.warn(`Got unknown user message ${kind}`);
break;
}
};
2020-11-09 00:11:55 +01:00
const urlRegexp = /https?:\/\/[-a-zA-Z0-9@:%/._\\+~#&()=?]+[-a-zA-Z0-9@:%/_\\+~#&()=]/g;
2020-04-24 19:38:21 +02:00
2020-09-12 16:34:52 +02:00
/**
* @param {string} line
* @returns {Array.<Text|HTMLElement>}
2020-09-12 16:34:52 +02:00
*/
2020-04-24 19:38:21 +02:00
function formatLine(line) {
let r = new RegExp(urlRegexp);
let result = [];
let pos = 0;
while(true) {
let m = r.exec(line);
if(!m)
break;
result.push(document.createTextNode(line.slice(pos, m.index)));
let a = document.createElement('a');
a.href = m[0];
a.textContent = m[0];
a.target = '_blank';
a.rel = 'noreferrer noopener';
result.push(a);
pos = m.index + m[0].length;
}
result.push(document.createTextNode(line.slice(pos)));
return result;
}
2020-09-12 16:34:52 +02:00
/**
* @param {string[]} lines
2020-09-12 16:34:52 +02:00
* @returns {HTMLElement}
*/
2020-04-24 19:38:21 +02:00
function formatLines(lines) {
let elts = [];
if(lines.length > 0)
elts = formatLine(lines[0]);
for(let i = 1; i < lines.length; i++) {
elts.push(document.createElement('br'));
elts = elts.concat(formatLine(lines[i]));
}
let elt = document.createElement('p');
elts.forEach(e => elt.appendChild(e));
return elt;
}
2020-09-30 00:33:23 +02:00
/**
* @param {number} time
* @returns {string}
*/
function formatTime(time) {
let delta = Date.now() - time;
let date = new Date(time);
let m = date.getMinutes();
if(delta > -30000)
return date.getHours() + ':' + ((m < 10) ? '0' : '') + m;
2020-09-30 00:33:23 +02:00
return date.toLocaleString();
}
2020-08-24 22:37:48 +02:00
/**
* @typedef {Object} lastMessage
* @property {string} [nick]
* @property {string} [peerId]
2020-10-01 16:52:01 +02:00
* @property {string} [dest]
* @property {number} [time]
2020-08-24 22:37:48 +02:00
*/
/** @type {lastMessage} */
2020-04-24 19:38:21 +02:00
let lastMessage = {};
/**
* @param {string} peerId
* @param {string} nick
2020-09-30 00:33:23 +02:00
* @param {number} time
* @param {string} kind
* @param {unknown} message
*/
2020-12-14 10:35:12 +01:00
function addToChatbox(peerId, dest, nick, time, privileged, kind, message) {
2020-09-02 15:35:55 +02:00
let userpass = getUserPass();
2020-08-27 21:17:46 +02:00
let row = document.createElement('div');
row.classList.add('message-row');
2020-04-24 19:38:21 +02:00
let container = document.createElement('div');
container.classList.add('message');
2020-08-27 21:17:46 +02:00
row.appendChild(container);
let footer = document.createElement('p');
footer.classList.add('message-footer');
2020-09-23 21:01:29 +02:00
if(!peerId)
container.classList.add('message-system');
2020-10-01 16:52:01 +02:00
if(userpass.username === nick)
2020-09-23 21:01:29 +02:00
container.classList.add('message-sender');
2020-10-01 16:52:01 +02:00
if(dest)
container.classList.add('message-private');
2020-08-12 12:17:56 +02:00
if(kind !== 'me') {
let p = formatLines(message.toString().split('\n'));
let doHeader = true;
if(!peerId && !dest && !nick) {
doHeader = false;
} else if(lastMessage.nick !== (nick || null) ||
lastMessage.peerId !== peerId ||
lastMessage.dest !== (dest || null) ||
!time || !lastMessage.time) {
doHeader = true;
} else {
let delta = time - lastMessage.time;
doHeader = delta < 0 || delta > 60000;
}
if(doHeader) {
2020-09-30 00:33:23 +02:00
let header = document.createElement('p');
if(peerId || nick || dest) {
let user = document.createElement('span');
user.textContent = dest ?
`${nick||'(anon)'} \u2192 ${users[dest]||'(anon)'}` :
(nick || '(anon)');
user.classList.add('message-user');
header.appendChild(user);
}
2020-09-30 00:33:23 +02:00
header.classList.add('message-header');
container.appendChild(header);
if(time) {
let tm = document.createElement('span');
tm.textContent = formatTime(time);
tm.classList.add('message-time');
header.appendChild(tm);
}
2020-04-24 19:38:21 +02:00
}
2020-04-24 19:38:21 +02:00
p.classList.add('message-content');
container.appendChild(p);
2020-10-08 15:18:22 +02:00
lastMessage.nick = (nick || null);
2020-04-24 19:38:21 +02:00
lastMessage.peerId = peerId;
2020-10-01 16:52:01 +02:00
lastMessage.dest = (dest || null);
lastMessage.time = (time || null);
2020-04-24 19:38:21 +02:00
} else {
let asterisk = document.createElement('span');
asterisk.textContent = '*';
asterisk.classList.add('message-me-asterisk');
let user = document.createElement('span');
2020-10-08 15:18:22 +02:00
user.textContent = nick || '(anon)';
2020-04-24 19:38:21 +02:00
user.classList.add('message-me-user');
let content = document.createElement('span');
formatLine(message.toString()).forEach(elt => {
2020-04-24 19:38:21 +02:00
content.appendChild(elt);
});
content.classList.add('message-me-content');
container.appendChild(asterisk);
container.appendChild(user);
container.appendChild(content);
container.classList.add('message-me');
2020-10-01 16:52:01 +02:00
lastMessage = {};
2020-04-24 19:38:21 +02:00
}
container.appendChild(footer);
2020-04-24 19:38:21 +02:00
let box = document.getElementById('box');
2020-08-27 21:17:46 +02:00
box.appendChild(row);
2020-04-24 19:38:21 +02:00
if(box.scrollHeight > box.clientHeight) {
box.scrollTop = box.scrollHeight - box.clientHeight;
}
return message;
}
2021-01-11 19:28:57 +01:00
/**
* @param {string} message
*/
function localMessage(message) {
return addToChatbox(null, null, null, Date.now(), false, null, message);
}
function clearChat() {
2020-04-25 21:16:49 +02:00
lastMessage = {};
document.getElementById('box').textContent = '';
}
/**
* A command known to the command-line parser.
*
* @typedef {Object} command
* @property {string} [parameters]
* - A user-readable list of parameters.
* @property {string} [description]
* - A user-readable description, null if undocumented.
* @property {() => string} [predicate]
* - Returns null if the command is available.
* @property {(c: string, r: string) => void} f
*/
/**
* The set of commands known to the command-line parser.
*
* @type {Object.<string,command>}
*/
2020-12-26 17:28:44 +01:00
let commands = {};
function operatorPredicate() {
if(serverConnection && serverConnection.permissions &&
serverConnection.permissions.op)
return null;
return 'You are not an operator';
}
function recordingPredicate() {
if(serverConnection && serverConnection.permissions &&
serverConnection.permissions.record)
return null;
return 'You are not allowed to record';
}
commands.help = {
description: 'display this help',
f: (c, r) => {
/** @type {string[]} */
let cs = [];
for(let cmd in commands) {
let c = commands[cmd];
if(!c.description)
continue;
if(c.predicate && c.predicate())
continue;
cs.push(`/${cmd}${c.parameters?' ' + c.parameters:''}: ${c.description}`);
}
cs.sort();
let s = '';
for(let i = 0; i < cs.length; i++)
s = s + cs[i] + '\n';
2021-01-11 19:28:57 +01:00
localMessage(s);
}
};
commands.me = {
f: (c, r) => {
// handled as a special case
throw new Error("this shouldn't happen");
}
};
commands.set = {
f: (c, r) => {
if(!r) {
let settings = getSettings();
let s = "";
for(let key in settings)
s = s + `${key}: ${JSON.stringify(settings[key])}\n`;
2021-01-11 19:28:57 +01:00
localMessage(s);
return;
}
let p = parseCommand(r);
let value;
if(p[1]) {
2020-12-26 17:28:44 +01:00
value = JSON.parse(p[1]);
} else {
value = true;
}
updateSetting(p[0], value);
reflectSettings();
}
};
commands.unset = {
f: (c, r) => {
delSetting(r.trim());
return;
}
};
commands.leave = {
description: "leave group",
f: (c, r) => {
if(!serverConnection)
throw new Error('Not connected');
serverConnection.close();
}
};
commands.clear = {
predicate: operatorPredicate,
description: 'clear the chat history',
f: (c, r) => {
serverConnection.groupAction('clearchat');
}
};
commands.lock = {
predicate: operatorPredicate,
description: 'lock this group',
parameters: '[message]',
f: (c, r) => {
serverConnection.groupAction('lock', r);
}
};
commands.unlock = {
predicate: operatorPredicate,
description: 'unlock this group, revert the effect of /lock',
f: (c, r) => {
serverConnection.groupAction('unlock');
}
};
commands.record = {
predicate: recordingPredicate,
description: 'start recording',
f: (c, r) => {
serverConnection.groupAction('record');
}
};
commands.unrecord = {
predicate: recordingPredicate,
description: 'stop recording',
f: (c, r) => {
serverConnection.groupAction('unrecord');
}
};
2020-12-02 19:47:32 +01:00
commands.subgroups = {
predicate: operatorPredicate,
description: 'list subgroups',
f: (c, r) => {
serverConnection.groupAction('subgroups');
2020-12-02 19:47:32 +01:00
}
};
2020-12-05 21:02:28 +01:00
commands.renegotiate = {
description: 'renegotiate media streams',
f: (c, r) => {
for(let id in serverConnection.up)
serverConnection.up[id].restartIce();
for(let id in serverConnection.down)
serverConnection.down[id].restartIce();
}
};
/**
* parseCommand splits a string into two space-separated parts. The first
* part may be quoted and may include backslash escapes.
*
* @param {string} line
* @returns {string[]}
*/
function parseCommand(line) {
let i = 0;
while(i < line.length && line[i] === ' ')
i++;
let start = ' ';
if(i < line.length && line[i] === '"' || line[i] === "'") {
start = line[i];
i++;
}
let first = "";
while(i < line.length) {
if(line[i] === start) {
if(start !== ' ')
i++;
break;
}
if(line[i] === '\\' && i < line.length - 1)
i++;
first = first + line[i];
i++;
}
while(i < line.length && line[i] === ' ')
i++;
return [first, line.slice(i)];
}
/**
* @param {string} user
*/
function findUserId(user) {
if(user in users)
return user;
for(let id in users) {
if(users[id] === user)
return id;
}
return null;
}
commands.msg = {
parameters: 'user message',
description: 'send a private message',
f: (c, r) => {
let p = parseCommand(r);
if(!p[0])
throw new Error('/msg requires parameters');
let id = findUserId(p[0]);
if(!id)
throw new Error(`Unknown user ${p[0]}`);
serverConnection.chat('', id, p[1]);
addToChatbox(serverConnection.id, id, serverConnection.username,
Date.now(), false, '', p[1]);
}
};
/**
@param {string} c
@param {string} r
*/
function userCommand(c, r) {
let p = parseCommand(r);
if(!p[0])
throw new Error(`/${c} requires parameters`);
let id = findUserId(p[0]);
if(!id)
throw new Error(`Unknown user ${p[0]}`);
serverConnection.userAction(c, id, p[1]);
}
2020-11-30 14:22:36 +01:00
function userMessage(c, r) {
let p = parseCommand(r);
if(!p[0])
throw new Error(`/${c} requires parameters`);
let id = findUserId(p[0]);
if(!id)
throw new Error(`Unknown user ${p[0]}`);
serverConnection.userMessage(c, id, p[1]);
2020-11-30 14:22:36 +01:00
}
commands.kick = {
parameters: 'user [message]',
description: 'kick out a user',
predicate: operatorPredicate,
f: userCommand,
};
commands.op = {
parameters: 'user',
description: 'give operator status',
predicate: operatorPredicate,
f: userCommand,
};
commands.unop = {
parameters: 'user',
description: 'revoke operator status',
predicate: operatorPredicate,
f: userCommand,
};
commands.present = {
parameters: 'user',
description: 'give user the right to present',
predicate: operatorPredicate,
f: userCommand,
};
commands.unpresent = {
parameters: 'user',
description: 'revoke the right to present',
predicate: operatorPredicate,
f: userCommand,
};
2020-11-30 14:22:36 +01:00
commands.mute = {
parameters: 'user',
description: 'mute a remote user',
predicate: operatorPredicate,
f: userMessage,
};
2021-01-11 16:30:19 +01:00
commands.muteall = {
description: 'mute all remote users',
predicate: operatorPredicate,
f: (c, r) => {
serverConnection.userMessage('mute', null, null, true);
}
}
2020-11-30 15:48:23 +01:00
commands.warn = {
parameters: 'user message',
description: 'send a warning to a user',
predicate: operatorPredicate,
f: (c, r) => {
userMessage('warning', r);
},
};
commands.wall = {
parameters: 'message',
description: 'send a warning to all users',
predicate: operatorPredicate,
f: (c, r) => {
if(!r)
throw new Error('empty message');
serverConnection.userMessage('warning', '', r);
2020-11-30 15:48:23 +01:00
},
};
2021-01-11 18:45:20 +01:00
/**
* Test loopback through a TURN relay.
*
* @returns {Promise<number>}
*/
2021-01-11 18:18:55 +01:00
async function relayTest() {
2021-01-11 18:45:20 +01:00
if(!serverConnection)
throw new Error('not connected');
2021-01-11 18:18:55 +01:00
let conf = Object.assign({}, serverConnection.rtcConfiguration);
conf.iceTransportPolicy = 'relay';
let pc1 = new RTCPeerConnection(conf);
let pc2 = new RTCPeerConnection(conf);
pc1.onicecandidate = e => {e.candidate && pc2.addIceCandidate(e.candidate);};
pc2.onicecandidate = e => {e.candidate && pc1.addIceCandidate(e.candidate);};
try {
2021-01-11 18:45:20 +01:00
return await new Promise(async (resolve, reject) => {
2021-01-11 18:18:55 +01:00
let d1 = pc1.createDataChannel('loopbackTest');
d1.onopen = e => {
2021-01-11 18:45:20 +01:00
d1.send(Date.now().toString());
2021-01-11 18:18:55 +01:00
};
let offer = await pc1.createOffer();
await pc1.setLocalDescription(offer);
await pc2.setRemoteDescription(pc1.localDescription);
2021-01-11 18:18:55 +01:00
let answer = await pc2.createAnswer();
await pc2.setLocalDescription(answer);
await pc1.setRemoteDescription(pc2.localDescription);
2021-01-11 18:18:55 +01:00
pc2.ondatachannel = e => {
let d2 = e.channel;
d2.onmessage = e => {
2021-01-11 18:45:20 +01:00
let t = parseInt(e.data);
if(isNaN(t))
reject(new Error('corrupt data'));
2021-01-11 18:18:55 +01:00
else
2021-01-11 18:45:20 +01:00
resolve(Date.now() - t);
2021-01-11 18:18:55 +01:00
}
}
2021-01-11 18:45:20 +01:00
setTimeout(() => reject(new Error('timeout')), 5000);
2021-01-11 18:18:55 +01:00
})
} finally {
pc1.close();
pc2.close();
}
}
commands['relay-test'] = {
f: async (c, r) => {
2021-01-11 19:28:57 +01:00
localMessage('Relay test in progress...');
2021-01-11 18:18:55 +01:00
try {
2021-01-11 18:45:20 +01:00
let s = Date.now();
let rtt = await relayTest();
let e = Date.now();
2021-01-11 19:28:57 +01:00
localMessage(`Relay test successful in ${e-s}ms, RTT ${rtt}ms`);
2021-01-11 18:18:55 +01:00
} catch(e) {
2021-01-11 19:28:57 +01:00
localMessage(`Relay test failed: ${e}`);
2021-01-11 18:18:55 +01:00
}
}
}
2020-04-24 19:38:21 +02:00
function handleInput() {
let input = /** @type {HTMLTextAreaElement} */
(document.getElementById('input'));
2020-04-24 19:38:21 +02:00
let data = input.value;
input.value = '';
let message, me;
if(data === '')
return;
if(data[0] === '/') {
if(data.length > 1 && data[1] === '/') {
message = data.slice(1);
2020-04-24 19:38:21 +02:00
me = false;
} else {
let cmd, rest;
let space = data.indexOf(' ');
2020-04-24 19:38:21 +02:00
if(space < 0) {
cmd = data.slice(1);
2020-04-24 19:38:21 +02:00
rest = '';
} else {
cmd = data.slice(1, space);
rest = data.slice(space + 1);
2020-04-24 19:38:21 +02:00
}
if(cmd === 'me') {
2020-04-24 19:38:21 +02:00
message = rest;
me = true;
} else {
let c = commands[cmd];
if(!c) {
displayError(`Uknown command /${cmd}, type /help for help`);
2020-09-23 21:01:29 +02:00
return;
}
if(c.predicate) {
let s = c.predicate();
if(s) {
displayError(s);
2020-09-23 21:01:29 +02:00
return;
}
2020-04-25 17:36:35 +02:00
}
try {
c.f(cmd, rest);
} catch(e) {
displayError(e);
2020-10-01 16:52:01 +02:00
}
2020-04-25 17:36:35 +02:00
return;
2020-05-10 21:18:12 +02:00
}
2020-04-24 19:38:21 +02:00
}
} else {
message = data;
me = false;
}
if(!serverConnection || !serverConnection.socket) {
displayError("Not connected.");
return;
}
try {
serverConnection.chat(me ? 'me' : '', '', message);
} catch(e) {
console.error(e);
displayError(e);
}
2020-04-24 19:38:21 +02:00
}
document.getElementById('inputform').onsubmit = function(e) {
e.preventDefault();
handleInput();
};
document.getElementById('input').onkeypress = function(e) {
if(e.key === 'Enter' && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
e.preventDefault();
handleInput();
}
2020-05-10 21:18:07 +02:00
};
2020-04-24 19:38:21 +02:00
function chatResizer(e) {
e.preventDefault();
let full_width = document.getElementById("mainrow").offsetWidth;
let left = document.getElementById("left");
let right = document.getElementById("right");
2020-04-24 19:38:21 +02:00
let start_x = e.clientX;
2020-09-11 22:46:23 +02:00
let start_width = left.offsetWidth;
2020-04-24 19:38:21 +02:00
function start_drag(e) {
let left_width = (start_width + e.clientX - start_x) * 100 / full_width;
// set min chat width to 300px
let min_left_width = 300 * 100 / full_width;
if (left_width < min_left_width) {
return;
}
2020-09-12 16:34:52 +02:00
left.style.flex = left_width.toString();
right.style.flex = (100 - left_width).toString();
2020-04-24 19:38:21 +02:00
}
function stop_drag(e) {
document.documentElement.removeEventListener(
'mousemove', start_drag, false,
);
document.documentElement.removeEventListener(
'mouseup', stop_drag, false,
);
}
document.documentElement.addEventListener(
'mousemove', start_drag, false,
);
document.documentElement.addEventListener(
'mouseup', stop_drag, false,
);
}
document.getElementById('resizer').addEventListener('mousedown', chatResizer, false);
/**
2020-09-28 20:58:07 +02:00
* @param {unknown} message
* @param {string} [level]
*/
function displayError(message, level) {
if(!level)
2020-09-28 20:58:07 +02:00
level = "error";
var background = 'linear-gradient(to right, #e20a0a, #df2d2d)';
var position = 'center';
var gravity = 'top';
switch(level) {
2020-09-28 20:58:07 +02:00
case "info":
background = 'linear-gradient(to right, #529518, #96c93d)';
position = 'right';
gravity = 'bottom';
break;
2020-09-28 20:58:07 +02:00
case "warning":
background = "linear-gradient(to right, #bdc511, #c2cf01)";
break;
2020-04-24 19:38:21 +02:00
}
/** @ts-ignore */
Toastify({
text: message,
duration: 4000,
close: true,
position: position,
gravity: gravity,
backgroundColor: background,
className: level,
}).showToast();
2020-04-24 19:38:21 +02:00
}
/**
2020-09-28 20:58:07 +02:00
* @param {unknown} message
*/
2020-04-24 19:38:21 +02:00
function displayWarning(message) {
2020-09-28 20:58:07 +02:00
return displayError(message, "warning");
}
/**
2020-09-28 20:58:07 +02:00
* @param {unknown} message
*/
function displayMessage(message) {
2020-09-28 20:58:07 +02:00
return displayError(message, "info");
2020-04-24 19:38:21 +02:00
}
2020-11-24 16:29:19 +01:00
let connecting = false;
document.getElementById('userform').onsubmit = async function(e) {
2020-04-24 19:38:21 +02:00
e.preventDefault();
2020-11-24 16:29:19 +01:00
if(connecting)
return;
connecting = true;
try {
let username = getInputElement('username').value.trim();
let password = getInputElement('password').value;
storeUserPass(username, password);
serverConnect();
} finally {
connecting = false;
}
if(getInputElement('presentboth').checked)
presentRequested = 'both';
else if(getInputElement('presentmike').checked)
presentRequested = 'mike';
else
presentRequested = null;
2020-11-30 21:28:45 +01:00
getInputElement('presentoff').checked = true;
2020-05-10 21:18:07 +02:00
};
2020-04-24 19:38:21 +02:00
document.getElementById('disconnectbutton').onclick = function(e) {
serverConnection.close();
2020-11-24 17:36:52 +01:00
closeNav();
2020-05-10 21:18:07 +02:00
};
2020-04-24 19:38:21 +02:00
2020-08-27 21:17:46 +02:00
function openNav() {
document.getElementById("sidebarnav").style.width = "250px";
}
function closeNav() {
document.getElementById("sidebarnav").style.width = "0";
}
document.getElementById('sidebarCollapse').onclick = function(e) {
document.getElementById("left-sidebar").classList.toggle("active");
document.getElementById("mainrow").classList.toggle("full-width-active");
};
document.getElementById('openside').onclick = function(e) {
e.preventDefault();
let sidewidth = document.getElementById("sidebarnav").style.width;
if (sidewidth !== "0px" && sidewidth !== "") {
closeNav();
return;
} else {
openNav();
}
};
document.getElementById('clodeside').onclick = function(e) {
e.preventDefault();
closeNav();
};
2020-09-09 20:26:19 +02:00
document.getElementById('collapse-video').onclick = function(e) {
e.preventDefault();
if(!(this instanceof HTMLElement))
throw new Error('Unexpected type for this');
2020-09-09 20:26:19 +02:00
let width = window.innerWidth;
let left = document.getElementById("left");
if (left.style.display === "" || left.style.display === "none") {
//left chat is hidden, we show the chat and hide collapse button
left.style.display = "block";
this.style.display = "";
}
if (width <= 768) {
// fixed div for small screen
2020-09-09 20:26:19 +02:00
this.style.display = "";
hideVideo(true);
document.getElementById('switch-video').style.display = "block";
}
};
document.getElementById('switch-video').onclick = function(e) {
e.preventDefault();
if(!(this instanceof HTMLElement))
throw new Error('Unexpected type for this');
showVideo();
this.style.display = "";
2020-09-09 20:26:19 +02:00
document.getElementById('collapse-video').style.display = "block";
};
document.getElementById('close-chat').onclick = function(e) {
e.preventDefault();
let left = document.getElementById("left");
left.style.display = "none";
document.getElementById('collapse-video').style.display = "block";
};
async function serverConnect() {
2020-11-24 16:29:19 +01:00
if(serverConnection && serverConnection.socket)
serverConnection.close();
serverConnection = new ServerConnection();
serverConnection.onconnected = gotConnected;
serverConnection.onclose = gotClose;
serverConnection.ondownstream = gotDownStream;
serverConnection.onuser = gotUser;
serverConnection.onjoined = gotJoined;
serverConnection.onchat = addToChatbox;
serverConnection.onusermessage = gotUserMessage;
let url = `ws${location.protocol === 'https:' ? 's' : ''}://${location.host}/ws`;
try {
await serverConnection.connect(url);
} catch(e) {
console.error(e);
displayError(e.message ? e.message : "Couldn't connect to " + url);
}
}
2020-04-24 19:38:21 +02:00
function start() {
group = decodeURIComponent(location.pathname.replace(/^\/[a-z]*\//, ''));
2020-04-25 17:43:56 +02:00
let title = group.charAt(0).toUpperCase() + group.slice(1);
if(group !== '') {
document.title = title;
2020-05-10 21:18:07 +02:00
document.getElementById('title').textContent = title;
2020-04-25 17:43:56 +02:00
}
2020-04-24 19:38:21 +02:00
addFilters();
setMediaChoices(false).then(e => reflectSettings());
2020-06-09 18:05:16 +02:00
2020-12-12 23:36:08 +01:00
fillLogin();
document.getElementById("login-container").classList.remove('invisible');
2020-04-24 19:38:21 +02:00
}
start();