init
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
[libsignal_protocol.js]
|
||||
indent_size = unset
|
||||
indent_style = unset
|
||||
insert_final_newline = unset
|
||||
+1
File diff suppressed because one or more lines are too long
@@ -0,0 +1,52 @@
|
||||
var MovimAvatar = {
|
||||
file : function(files, formname, width = 384, height = 384) {
|
||||
var f = files[0];
|
||||
if (!f.type.match(/image.*/)) {
|
||||
console.log("Not a picture !");
|
||||
MovimAvatar.clear(formname);
|
||||
} else {
|
||||
var reader = new FileReader();
|
||||
reader.readAsDataURL(f);
|
||||
|
||||
reader.onload = function (ev) {
|
||||
MovimUtils.getOrientation(f, function(orientation) {
|
||||
MovimAvatar.preview(ev.target.result, orientation, formname, width, height);
|
||||
});
|
||||
};
|
||||
};
|
||||
},
|
||||
clear : function(formname) {
|
||||
document.querySelector('form[name=' + formname + '] img').src = '';
|
||||
document.querySelector('form[name=' + formname + '] input[name="photobin"]').value = '';
|
||||
},
|
||||
preview : function(src, orientation, formname, setWidth, setHeight) {
|
||||
var image = new Image();
|
||||
image.src = src;
|
||||
|
||||
image.onload = function() {
|
||||
var canvas = document.createElement('canvas');
|
||||
width = canvas.width = setWidth;
|
||||
height = canvas.height = setHeight;
|
||||
ctx = canvas.getContext("2d");
|
||||
|
||||
MovimUtils.applyOrientation(ctx, orientation, width, height)
|
||||
MovimUtils.drawImageProp(ctx, image);
|
||||
|
||||
var base64 = canvas.toDataURL('image/jpeg', 0.80);
|
||||
|
||||
var preview = document.querySelector('form[name=' + formname + '] img');
|
||||
|
||||
var list = document.querySelector('form[name=' + formname + '] ul');
|
||||
if (list) list.classList.add('hide');
|
||||
|
||||
var input = document.querySelector('form[name=' + formname + '] input[name="photobin"]');
|
||||
|
||||
if (preview.className == 'error') preview.className = '';
|
||||
|
||||
preview.src = base64;
|
||||
|
||||
var bin = base64.split(",");
|
||||
input.value = bin[1];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Register a service worker for the Progressive Web App
|
||||
*/
|
||||
if ('serviceWorker' in navigator) {
|
||||
navigator.serviceWorker
|
||||
.register(SW_URI)
|
||||
.then(e => navigator.serviceWorker.ready)
|
||||
.then((r) => {
|
||||
console.log('Service Worker Registered');
|
||||
});
|
||||
|
||||
let refreshing = false;
|
||||
navigator.serviceWorker.addEventListener('controllerchange', () => {
|
||||
if (refreshing) return;
|
||||
refreshing = true;
|
||||
window.location.reload();
|
||||
});
|
||||
|
||||
const channel = new BroadcastChannel('messages');
|
||||
channel.addEventListener('message', event => {
|
||||
Notif.snackbarClear();
|
||||
window.focus();
|
||||
|
||||
switch (event.data.type) {
|
||||
case 'call':
|
||||
break;
|
||||
case 'call_reject':
|
||||
VisioUtils.cancelLobby(event.data.data.fullJid, event.data.data.callId);
|
||||
break;
|
||||
case 'space_chat':
|
||||
MovimUtils.reload(event.data.data.server, event.data.data.node, event.data.data.room);
|
||||
break;
|
||||
case 'chat':
|
||||
Search.chat(event.data.data.jid, event.data.data.muc);
|
||||
break;
|
||||
default:
|
||||
if (event.data.data.url) {
|
||||
MovimUtils.reload(event.data.data.url);
|
||||
}
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
MovimEvents.registerWindow('loaded', 'movimbase', () => {
|
||||
const pwaButton = document.querySelector('#pwa');
|
||||
|
||||
if (pwaButton) {
|
||||
window.addEventListener('beforeinstallprompt', (e) => {
|
||||
e.preventDefault();
|
||||
deferredPrompt = e;
|
||||
pwaButton.style.display = 'initial';
|
||||
|
||||
pwaButton.addEventListener('click', () => {
|
||||
deferredPrompt.prompt();
|
||||
|
||||
deferredPrompt.userChoice.then((choiceResult) => {
|
||||
if (choiceResult.outcome === 'accepted') {
|
||||
console.log('Movim App installed');
|
||||
}
|
||||
|
||||
deferredPrompt = null;
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
const KEY_ALGO = {
|
||||
'name': 'AES-GCM',
|
||||
'length': 128
|
||||
};
|
||||
const NUM_PREKEYS = 50;
|
||||
const SIGNED_PREKEY_ID = 1;
|
||||
const AESGCM_REGEX = /^aesgcm:\/\/([^#]+\/([^\/]+\.([a-z0-9]+)))#([a-z0-9]+)/i;
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,94 @@
|
||||
/**
|
||||
* Movim Events
|
||||
*/
|
||||
|
||||
var MovimEvents = {
|
||||
eventsBody: {},
|
||||
eventsWindow: {},
|
||||
isFocused: false,
|
||||
isTouch: false,
|
||||
|
||||
/**
|
||||
* @brief Register an event on the body
|
||||
* @param string event
|
||||
* @param string key
|
||||
* @param function action
|
||||
*/
|
||||
registerBody: function (event, key, action) {
|
||||
if (MovimEvents.eventsBody[event] == undefined) {
|
||||
MovimEvents.eventsBody[event] = {};
|
||||
}
|
||||
|
||||
MovimEvents.eventsBody[event][key] = action;
|
||||
},
|
||||
|
||||
/**
|
||||
* @brief Register an event on the window
|
||||
* @param string event
|
||||
* @param string key
|
||||
* @param function action
|
||||
*/
|
||||
registerWindow: function (event, key, action) {
|
||||
if (MovimEvents.eventsWindow[event] == undefined) {
|
||||
MovimEvents.eventsWindow[event] = {};
|
||||
}
|
||||
|
||||
MovimEvents.eventsWindow[event][key] = action;
|
||||
},
|
||||
|
||||
triggerBody: function (event, e) {
|
||||
if (MovimEvents.eventsBody[event] != undefined) {
|
||||
for (const value of Object.values(MovimEvents.eventsBody[event])) {
|
||||
value(e);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
triggerWindow: function (event, e) {
|
||||
if (MovimEvents.eventsWindow[event] != undefined) {
|
||||
for (const value of Object.values(MovimEvents.eventsWindow[event])) {
|
||||
value(e);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
focusEvent: function (e) {
|
||||
if (MovimEvents.isFocused) return;
|
||||
|
||||
MovimEvents.isFocused = true;
|
||||
MovimEvents.triggerWindow('focus', e);
|
||||
}
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', (e) => {
|
||||
// Window
|
||||
window.addEventListener('load', (e) => MovimEvents.triggerWindow('loaded', e), false);
|
||||
window.addEventListener('keydown', (e) => MovimEvents.triggerWindow('keydown', e), false);
|
||||
window.addEventListener('paste', (e) => MovimEvents.triggerWindow('paste', e), false);
|
||||
window.addEventListener('resize', (e) => MovimEvents.triggerWindow('resize', e), false);
|
||||
window.addEventListener('online', (e) => MovimEvents.triggerWindow('online', e), false);
|
||||
window.addEventListener('offline', (e) => MovimEvents.triggerWindow('offline', e), false);
|
||||
window.addEventListener('popstate', (e) => MovimEvents.triggerWindow('popstate', e), false);
|
||||
window.addEventListener('touchstart', (e) => MovimEvents.triggerWindow('touchstart', e), false);
|
||||
window.addEventListener('touchstart', function () { MovimEvents.isTouch = true; }, { once: true });
|
||||
|
||||
/**
|
||||
* The focus event doesn't seems to be triggered all the time ¯\_(ツ)_/¯
|
||||
*/
|
||||
window.addEventListener('blur', (e) => {
|
||||
MovimEvents.isFocused = false;
|
||||
MovimEvents.triggerWindow('blur', e);
|
||||
}, false);
|
||||
window.addEventListener('focusin', (e) => MovimEvents.focusEvent(e), false);
|
||||
window.addEventListener('mouseover', (e) => MovimEvents.focusEvent(e), false);
|
||||
|
||||
// Body
|
||||
document.body.addEventListener('click', (e) => MovimEvents.triggerBody('click', e), false);
|
||||
document.body.addEventListener('keydown', (e) => MovimEvents.triggerBody('keydown', e), false);
|
||||
document.body.addEventListener('touchstart', (e) => MovimEvents.triggerBody('touchstart', e), false);
|
||||
document.body.addEventListener('touchend', (e) => MovimEvents.triggerBody('touchend', e), false);
|
||||
document.body.addEventListener('touchmove', (e) => MovimEvents.triggerBody('touchmove', e), false);
|
||||
document.body.addEventListener('dragover', (e) => MovimEvents.triggerBody('dragover', e), false);
|
||||
document.body.addEventListener('drop', (e) => MovimEvents.triggerBody('drop', e), false);
|
||||
document.body.addEventListener('dragleave', (e) => MovimEvents.triggerBody('dragleave', e), false);
|
||||
}, false);
|
||||
@@ -0,0 +1,75 @@
|
||||
var MovimFavicon = {
|
||||
originalUrl: null,
|
||||
originalIcon: null,
|
||||
sizes: '128x128',
|
||||
|
||||
counter: function (counterTab1, counterTab2) {
|
||||
let counter = counterTab1 + counterTab2;
|
||||
|
||||
link = document.querySelector('link[sizes="' + MovimFavicon.sizes + '"]');
|
||||
|
||||
canvas = document.createElement("canvas");
|
||||
ctx = canvas.getContext('2d');
|
||||
|
||||
canvas.width = 32;
|
||||
canvas.height = 32;
|
||||
|
||||
ctx.drawImage(MovimFavicon.originalIcon, 0, 0, 32, 32);
|
||||
|
||||
if (counter > 0) {
|
||||
large = counter > 9;
|
||||
if (counter > 99) {
|
||||
counter = '+';
|
||||
large = false;
|
||||
}
|
||||
|
||||
ctx.textAlign = 'center';
|
||||
ctx.font = 'bold 18px Roboto';
|
||||
|
||||
radius = 5;
|
||||
x = large ? 4 : 12;
|
||||
y = 12;
|
||||
w = large ? 28 : 20;
|
||||
h = 20;
|
||||
|
||||
var r = x + w;
|
||||
var b = y + h;
|
||||
|
||||
ctx.beginPath();
|
||||
ctx.fillStyle = getComputedStyle(document.body).getPropertyValue(counterTab2 > 0
|
||||
? '--p-red'
|
||||
: '--movim-accent'
|
||||
);
|
||||
ctx.moveTo(x + radius, y);
|
||||
ctx.lineTo(r - radius, y);
|
||||
ctx.quadraticCurveTo(r, y, r, y + radius);
|
||||
ctx.lineTo(r, y + h - radius);
|
||||
ctx.quadraticCurveTo(r, b, r - radius, b);
|
||||
ctx.lineTo(x + radius, b);
|
||||
ctx.quadraticCurveTo(x, b, x, b - radius);
|
||||
ctx.lineTo(x, y + radius);
|
||||
ctx.quadraticCurveTo(x, y, x + radius, y);
|
||||
ctx.fill();
|
||||
|
||||
ctx.fillStyle = "#fff";
|
||||
counterTextX = large ? 18 : 22;
|
||||
ctx.fillText(counter, counterTextX, 28, w);
|
||||
}
|
||||
|
||||
MovimFavicon.set(canvas.toDataURL());
|
||||
},
|
||||
|
||||
set: function (url) {
|
||||
link = document.querySelector('link[sizes="' + MovimFavicon.sizes + '"]');
|
||||
link.href = url;
|
||||
},
|
||||
|
||||
init: function () {
|
||||
link = document.querySelector('link[sizes="' + MovimFavicon.sizes + '"]');
|
||||
MovimFavicon.originalUrl = link.href;
|
||||
MovimFavicon.originalIcon = new Image();
|
||||
MovimFavicon.originalIcon.src = MovimFavicon.originalUrl;
|
||||
}
|
||||
}
|
||||
|
||||
MovimFavicon.init();
|
||||
@@ -0,0 +1,61 @@
|
||||
class MovimJingleSessionAudioWorklet extends AudioWorkletProcessor {
|
||||
static BUFFER_SIZE = 128 * 128;
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this.isMuteStep = 0;
|
||||
this.remoteMaxLevel = 0;
|
||||
this.buffer = new Float32Array(MovimJingleSessionAudioWorklet.BUFFER_SIZE);
|
||||
this.offset = 0;
|
||||
}
|
||||
|
||||
process(inputList, _outputList, _parameters) {
|
||||
const input = inputList[0][0];
|
||||
|
||||
if (input != undefined) {
|
||||
for (let i = 0; i < input.length; i++) {
|
||||
this.buffer[i + this.offset] = input[i];
|
||||
}
|
||||
|
||||
this.offset += input.length;
|
||||
|
||||
if (this.offset >= this.buffer.length - 1) {
|
||||
this.flush();
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
flush() {
|
||||
this.offset = 0;
|
||||
|
||||
var instant = 0.0;
|
||||
var sum = 0.0;
|
||||
|
||||
for (var i = 0; i < this.buffer.length; ++i) {
|
||||
sum += this.buffer[i] * this.buffer[i];
|
||||
}
|
||||
|
||||
instant = Math.sqrt(sum / this.buffer.length);
|
||||
this.remoteMaxLevel = Math.max(this.remoteMaxLevel, instant);
|
||||
|
||||
var base = (instant / this.remoteMaxLevel);
|
||||
var level = (base > 0.05) ? base ** .3 : 0;
|
||||
|
||||
// Fallback in case we don't have the proper signalisation
|
||||
if (level == 0) {
|
||||
this.isMuteStep++;
|
||||
} else {
|
||||
this.isMuteStep = 0;
|
||||
}
|
||||
|
||||
this.port.postMessage({
|
||||
"isMuteStep": this.isMuteStep,
|
||||
"level": level.toFixed(2),
|
||||
"published": Date.now()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
registerProcessor('jinglesession-audioworklet', MovimJingleSessionAudioWorklet);
|
||||
@@ -0,0 +1,935 @@
|
||||
var MovimJingleSession = function (jid, fullJid, id, name, avatarUrl) {
|
||||
this.id = id ?? crypto.randomUUID();
|
||||
this.jid = jid;
|
||||
this.fullJid = fullJid;
|
||||
this.tracksTypes = {};
|
||||
this.tracksScreen = {};
|
||||
this.name = name;
|
||||
this.avatarUrl = avatarUrl;
|
||||
this.audioLevel = 0;
|
||||
this.lastPostMessage = 0;
|
||||
|
||||
this.audioSharingSender = null;
|
||||
this.screenSharingSender = null;
|
||||
|
||||
this.pc = new RTCPeerConnection({
|
||||
iceServers: MovimVisio.services,
|
||||
bundlePolicy: 'max-bundle',
|
||||
iceCandidatePoolSize: 10
|
||||
});
|
||||
|
||||
this.screenSharingPc = null; // RTCPc specific for the SFU
|
||||
|
||||
this.adaptToNetworkCondition = setInterval(() => {
|
||||
VisioUtils.adaptToNetworkCondition(this.pc);
|
||||
}, 5000);
|
||||
|
||||
this.participant = document.createElement('div');
|
||||
this.participant.dataset.jid = this.jid;
|
||||
this.participant.classList.add('participant');
|
||||
|
||||
document.querySelector('#participants').appendChild(this.participant);
|
||||
|
||||
this.participant.classList.add('audio_off');
|
||||
this.participant.classList.add('screen_off');
|
||||
this.participant.classList.add('video_off');
|
||||
|
||||
this.remoteScreenVideo = document.createElement('video');
|
||||
this.remoteScreenVideo.classList.add('screen');
|
||||
this.remoteScreenVideo.autoplay = true;
|
||||
this.remoteScreenVideo.disablePictureInPicture = true;
|
||||
this.remoteScreenVideo.poster = BASE_URI + 'theme/img/empty.png';
|
||||
this.participant.appendChild(this.remoteScreenVideo);
|
||||
|
||||
this.remoteVideo = document.createElement('video');
|
||||
this.remoteVideo.autoplay = true;
|
||||
this.remoteVideo.disablePictureInPicture = true;
|
||||
this.remoteVideo.poster = BASE_URI + 'theme/img/empty.png';
|
||||
this.remoteVideo.muted = true;
|
||||
this.participant.appendChild(this.remoteVideo);
|
||||
|
||||
this.remoteAudio = document.createElement('audio');
|
||||
this.remoteAudio.autoplay = true;
|
||||
this.participant.appendChild(this.remoteAudio);
|
||||
|
||||
this.remoteScreenAudio = document.createElement('audio');
|
||||
this.remoteScreenAudio.classList.add('screen');
|
||||
this.remoteScreenAudio.autoplay = true;
|
||||
this.participant.appendChild(this.remoteScreenAudio);
|
||||
|
||||
this.callStatus = document.createElement('div')
|
||||
this.callStatus.classList.add('status');
|
||||
this.participant.appendChild(this.callStatus);
|
||||
|
||||
this.audioOffStatus = document.createElement('span');
|
||||
this.audioOffStatus.classList.add('audio_off');
|
||||
this.callStatus.appendChild(this.audioOffStatus);
|
||||
|
||||
this.videoOffStatus = document.createElement('span');
|
||||
this.videoOffStatus.classList.add('video_off');
|
||||
this.callStatus.appendChild(this.videoOffStatus);
|
||||
|
||||
this.screenStatus = document.createElement('span');
|
||||
this.screenStatus.classList.add('screen');
|
||||
this.callStatus.appendChild(this.screenStatus);
|
||||
|
||||
// Pin button
|
||||
this.pin = document.createElement('span');
|
||||
this.pin.classList.add('pin');
|
||||
this.participant.appendChild(this.pin);
|
||||
|
||||
this.pin.addEventListener('click', e => {
|
||||
VisioUtils.toggleMode(true);
|
||||
|
||||
if (MovimJingles.pinned == this.jid) {
|
||||
MovimJingles.pinned = null;
|
||||
Visio_ajaxHttpUnpin();
|
||||
} else {
|
||||
MovimJingles.pinned = this.jid;
|
||||
|
||||
if (this.name) {
|
||||
Visio_ajaxHttpPin(this.name);
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingles.checkActiveSpeaker();
|
||||
})
|
||||
|
||||
this.screenQualityInterval = setInterval(() => {
|
||||
this.callStatus.classList.remove('screen_hd', 'screen_fhd');
|
||||
if (!this.participant.classList.contains('screen_off')) {
|
||||
if (this.remoteScreenVideo.videoWidth >= 1920) {
|
||||
this.callStatus.classList.add('screen_fhd');
|
||||
} else if (this.remoteScreenVideo.videoWidth >= 1280) {
|
||||
this.callStatus.classList.add('screen_hd');
|
||||
}
|
||||
}
|
||||
}, 3000);
|
||||
|
||||
if (this.name) {
|
||||
this.callStatus.dataset.name = this.name;
|
||||
}
|
||||
|
||||
if (this.avatarUrl) {
|
||||
let background = document.createElement('img');
|
||||
background.classList.add('avatar');
|
||||
background.src = this.avatarUrl;
|
||||
this.participant.prepend(background);
|
||||
}
|
||||
|
||||
this.pc.ontrack = event => {
|
||||
var srcObject = null;
|
||||
|
||||
if (event.streams && event.streams[0]) {
|
||||
srcObject = event.streams[0];
|
||||
} else {
|
||||
srcObject = new MediaStream();
|
||||
srcObject.addTrack(event.track);
|
||||
}
|
||||
|
||||
if (event.track.kind == 'audio') {
|
||||
if (this.tracksScreen[event.transceiver.mid]) {
|
||||
this.remoteScreenAudio.srcObject = srcObject;
|
||||
this.tracksTypes['mid' + event.transceiver.mid] = 'audio_screen';
|
||||
} else {
|
||||
this.remoteAudio.srcObject = srcObject;
|
||||
this.participant.classList.remove('audio_off');
|
||||
this.handleRemoteAudio();
|
||||
this.tracksTypes['mid' + event.transceiver.mid] = 'audio';
|
||||
}
|
||||
} else if (event.track.kind === 'video') {
|
||||
if (this.tracksScreen[event.transceiver.mid]) {
|
||||
this.remoteScreenVideo.srcObject = srcObject;
|
||||
this.tracksTypes['mid' + event.transceiver.mid] = 'video_screen';
|
||||
this.remoteScreenVideo.oncanplay = event => {
|
||||
this.participant.classList.remove('screen_off');
|
||||
}
|
||||
} else {
|
||||
this.remoteVideo.srcObject = srcObject;
|
||||
this.tracksTypes['mid' + event.transceiver.mid] = 'video';
|
||||
this.participant.classList.remove('video_off');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.pc.onnegotiationneeded = event => {
|
||||
if (this.pc.localDescription) {
|
||||
this.oldLocalDescription = this.pc.localDescription.sdp;
|
||||
|
||||
this.pc.getTransceivers().forEach(transceiver => {
|
||||
if (transceiver.sender.track && transceiver.sender.track.kind === 'video') {
|
||||
VisioUtils.setVideoCodecPreferences(transceiver);
|
||||
}
|
||||
});
|
||||
|
||||
this.pc.createOffer()
|
||||
.then(offer => {
|
||||
offer.sdp = this.maybeInjectScreenCategory(offer.sdp);
|
||||
return this.pc.setLocalDescription(offer)
|
||||
}).then(() => this.updateContent())
|
||||
.catch(err => MovimUtils.logError(err));
|
||||
}
|
||||
};
|
||||
|
||||
this.pc.onicecandidate = event => {
|
||||
let candidate = event.candidate;
|
||||
if (candidate && candidate.candidate && candidate.candidate.length > 0) {
|
||||
Visio_ajaxCandidate(this.fullJid, this.id, event.candidate);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Add all the existing tracks
|
||||
*/
|
||||
|
||||
if (MovimVisio.sfu == null) {
|
||||
MovimVisio.localStream.getTracks().forEach(track => {
|
||||
this.pc.addTrack(track, MovimVisio.localStream);
|
||||
});
|
||||
|
||||
if (MovimVisio.screenSharing.srcObject) {
|
||||
this.enableScreenSharing();
|
||||
}
|
||||
}
|
||||
|
||||
Notif.userJoinedCall();
|
||||
MovimJingles.checkActiveSpeaker();
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.handleRemoteAudio = async function () {
|
||||
this.remoteAudioContext = new AudioContext();
|
||||
|
||||
try {
|
||||
var remoteMicrophone = this.remoteAudioContext.createMediaStreamSource(
|
||||
this.remoteAudio.srcObject
|
||||
);
|
||||
|
||||
await this.remoteAudioContext.audioWorklet.addModule(BASE_URI + 'scripts/movim_jingle_session_audio_worklet.js');
|
||||
const audioWorkletNode = new AudioWorkletNode(this.remoteAudioContext, 'jinglesession-audioworklet');
|
||||
remoteMicrophone.connect(audioWorkletNode);
|
||||
|
||||
audioWorkletNode.port.onmessage = (e) => {
|
||||
this.processRemoteAudioMessage(e.data);
|
||||
};
|
||||
|
||||
} catch (error) {
|
||||
MovimUtils.logError(error);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* In some clients, such as Dino, the buffer is stopped when the microphone is muted
|
||||
* we detect that there and send a clear message properly
|
||||
*/
|
||||
MovimJingleSession.prototype.clearRemoteAudioMessage = function () {
|
||||
const second = 1000;
|
||||
const secondAgo = Date.now() - second;
|
||||
|
||||
if (this.lastPostMessage < secondAgo) {
|
||||
this.processRemoteAudioMessage({
|
||||
"isMuteStep": 5,
|
||||
"level": 0,
|
||||
"published": Date.now()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.processRemoteAudioMessage = function (message) {
|
||||
if (message.isMuteStep >= 5) {
|
||||
this.participant.classList.add('audio_off');
|
||||
} else {
|
||||
this.participant.classList.remove('audio_off');
|
||||
}
|
||||
|
||||
this.lastPostMessage = message.published;
|
||||
this.audioLevel = message.level;
|
||||
this.participant.style.setProperty('--level', message.level);
|
||||
|
||||
if (message.level > 0) {
|
||||
clearTimeout(this.clearRemoteAudioMessageId);
|
||||
this.clearRemoteAudioMessageId = setTimeout(this.clearRemoteAudioMessage.bind(this), 2000);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* movim-rs: the signaling messages can arrive faster than the asynchronous
|
||||
* WebRTC calls complete (a content-add right after a session-accept, candidates
|
||||
* before the remote description), run them one after the other.
|
||||
*/
|
||||
MovimJingleSession.prototype.enqueue = function (task) {
|
||||
this.queue = (this.queue || Promise.resolve())
|
||||
.then(() => this.pc ? task() : null)
|
||||
.catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onCandidate = function (candidate, mid, mlineindex) {
|
||||
this.enqueue(() => this._onCandidate(candidate, mid, mlineindex));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onContentAdd = function (sdp, mids) {
|
||||
this.enqueue(() => this._onContentAdd(sdp, mids));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onContentModify = function (sdp, mid) {
|
||||
this.enqueue(() => this._onContentModify(sdp, mid));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onContentRemove = function (sdp, mids) {
|
||||
this.enqueue(() => this._onContentRemove(sdp, mids));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onAcceptSDP = function (sdp) {
|
||||
this.enqueue(() => this._onAcceptSDP(sdp));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onInitiateSDP = function (sdp) {
|
||||
this.enqueue(() => this._onInitiateSDP(sdp));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.terminate = function (reason, muji) {
|
||||
if (MovimVisio.sfu == null) {
|
||||
Visio_ajaxTerminate(this.fullJid, this.id, reason, muji);
|
||||
}
|
||||
this.close();
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.close = function () {
|
||||
clearInterval(this.adaptToNetworkCondition);
|
||||
clearInterval(this.screenQualityInterval);
|
||||
|
||||
Notif.userLeftCall();
|
||||
|
||||
if (this.pc) {
|
||||
this.pc.close();
|
||||
this.pc = null;
|
||||
}
|
||||
|
||||
if (this.remoteAudioContext) {
|
||||
this.remoteAudioContext.close();
|
||||
this.remoteAudioContext = null;
|
||||
}
|
||||
|
||||
let participant = document.querySelector('.participant[data-jid="' + this.jid + '"]');
|
||||
if (participant) participant.remove();
|
||||
|
||||
let remoteVideoStream = this.remoteVideo.srcObject;
|
||||
if (remoteVideoStream) {
|
||||
remoteVideoStream.getTracks().forEach(track => track.stop());
|
||||
remoteVideoStream = null;
|
||||
}
|
||||
|
||||
let remoteAudioStream = this.remoteAudio.srcObject;
|
||||
if (remoteAudioStream) {
|
||||
remoteAudioStream.getTracks().forEach(track => track.stop());
|
||||
remoteAudioStream = null;
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype._onCandidate = function (candidate, mid, mlineindex) {
|
||||
const iceCandidate = new RTCIceCandidate({
|
||||
// filter the a=candidate lines
|
||||
'candidate': candidate.split(/\n/).filter(line => {
|
||||
return line.startsWith('a=candidate');
|
||||
}).join('').substring(2),
|
||||
'sdpMid': mid,
|
||||
'sdpMLineIndex': mlineindex
|
||||
});
|
||||
|
||||
// When we share our own screen have some candidates from the SFU for our PC
|
||||
if (this.jid == MovimVisio.sfu && MovimVisio.screenshareSFUPc) {
|
||||
MovimVisio.screenshareSFUPc.addIceCandidate(iceCandidate).catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
|
||||
if (this.screenSharingPc) {
|
||||
// In this case we send the candidate to both pcs, and let it sort it out ¯\_(ツ)_/¯
|
||||
this.screenSharingPc.addIceCandidate(iceCandidate).catch(error => MovimUtils.logError(error));
|
||||
} else if (this.pc && this.pc.remoteDescription) {
|
||||
return this.pc.addIceCandidate(iceCandidate).catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype._onContentAdd = function (sdp, mids) {
|
||||
remoteDescription = this.pc.remoteDescription.sdp;
|
||||
remoteDescription += sdp.match('m=[^]*');
|
||||
remoteDescription = remoteDescription.replace(/^a=group.*/m, sdp.match(/a=group.*/)[0]);
|
||||
|
||||
this.maybeDetectTracksScreen(sdp);
|
||||
|
||||
return this.pc.setRemoteDescription({ 'sdp': remoteDescription + "\n", 'type': 'offer' })
|
||||
.then(() => {
|
||||
return this.pc.createAnswer()
|
||||
.then(answer => this.pc.setLocalDescription(answer))
|
||||
.then(() => Visio_ajaxContentAccept(this.fullJid, this.id, this.pc.localDescription.sdp))
|
||||
.catch(MovimUtils.logError);
|
||||
})
|
||||
.catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype._onContentModify = function (sdp, mid) {
|
||||
// TODO, implement mid
|
||||
this.maybeDetectTracksScreen(sdp);
|
||||
|
||||
return this.pc.setRemoteDescription({ 'sdp': sdp + "\n", 'type': 'offer' })
|
||||
.then(() => {
|
||||
return this.pc.createAnswer()
|
||||
.then(answer => this.pc.setLocalDescription(answer))
|
||||
.then(() => Visio_ajaxContentAccept(this.fullJid, this.id, this.pc.localDescription.sdp))
|
||||
.catch(MovimUtils.logError);
|
||||
})
|
||||
.catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype._onContentRemove = function (sdp, mids) {
|
||||
remoteDescription = this.pc.remoteDescription.sdp;
|
||||
mids.forEach(mid => delete this.tracksScreen[mid]);
|
||||
|
||||
let parts = remoteDescription.split('m=');
|
||||
let filtered = [];
|
||||
|
||||
parts.forEach(part => {
|
||||
let mid = part.match(/a=mid:(.*)/);
|
||||
if (!mid || !mids.includes(mid[1])) {
|
||||
filtered.push(part)
|
||||
}
|
||||
});
|
||||
|
||||
remoteDescription = filtered.join('m=');
|
||||
return this.pc.setRemoteDescription({ 'sdp': sdp + "\n", 'type': 'offer' })
|
||||
.then(() => {
|
||||
return this.pc.createAnswer()
|
||||
.then(answer => this.pc.setLocalDescription(answer))
|
||||
.then(() => Visio_ajaxContentAccept(this.fullJid, this.id, this.pc.localDescription.sdp))
|
||||
.catch(MovimUtils.logError);
|
||||
})
|
||||
.catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.sessionInitiate = function (fullJid, id, mujiRoom) {
|
||||
this.id = id;
|
||||
this.fullJid = fullJid;
|
||||
|
||||
this.pc.getTransceivers().forEach(transceiver => {
|
||||
if (transceiver.sender.track.kind === 'video') {
|
||||
VisioUtils.setVideoCodecPreferences(transceiver)
|
||||
}
|
||||
});
|
||||
|
||||
this.pc.createOffer()
|
||||
.then(offer => this.pc.setLocalDescription(offer))
|
||||
.then(() => Visio_ajaxSessionInitiate(this.fullJid, this.pc.localDescription, id, mujiRoom));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.updateContent = function () {
|
||||
let oldMedias = this.oldLocalDescription.match(MovimVisio.bundleRegex)[2].split(' ');
|
||||
let newMedias = this.pc.localDescription.sdp.match(MovimVisio.bundleRegex)[2].split(' ');
|
||||
|
||||
let createdMedias = newMedias.filter((e) => !oldMedias.includes(e));
|
||||
let destroyedMedias = oldMedias.filter((e) => !newMedias.includes(e));
|
||||
|
||||
let changed = false;
|
||||
let localDescription = this.maybeInjectScreenCategory(this.pc.localDescription.sdp);
|
||||
|
||||
if (createdMedias.length > 0) {
|
||||
changed = true;
|
||||
console.log('CONTENT ADD ?' + this.fullJid + ' ' + this.jid);
|
||||
Visio_ajaxContentAdd(this.fullJid, localDescription, this.id, createdMedias);
|
||||
}
|
||||
|
||||
if (destroyedMedias.length > 0) {
|
||||
changed = true;
|
||||
Visio_ajaxContentRemove(this.fullJid, this.oldLocalDescription, this.id, destroyedMedias);
|
||||
}
|
||||
|
||||
// Nothing added, nothing removed, lets update everything...
|
||||
if (changed == false) {
|
||||
Visio_ajaxContentModify(this.fullJid, localDescription, this.id);
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype._onAcceptSDP = function (sdp) {
|
||||
this.maybeDetectTracksScreen(sdp);
|
||||
|
||||
return this.pc.setRemoteDescription({ 'sdp': sdp + "\n", 'type': 'answer' })
|
||||
.catch(error => {
|
||||
let visio = document.querySelector('#visio');
|
||||
Visio_ajaxGoodbye(visio.dataset.jid, this.id, 'incompatible-parameters');
|
||||
|
||||
MovimUtils.logError(error);
|
||||
});
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype._onInitiateSDP = function (sdp) {
|
||||
this.maybeDetectTracksScreen(sdp);
|
||||
|
||||
return this.pc.setRemoteDescription({ 'sdp': sdp + "\n", 'type': 'offer' })
|
||||
.then(() => {
|
||||
return this.pc.createAnswer()
|
||||
.then(answer => this.pc.setLocalDescription(answer))
|
||||
.then(() => {
|
||||
if (MovimVisio.sfu != null) {
|
||||
Visio_ajaxContentAccept(
|
||||
this.fullJid,
|
||||
this.id,
|
||||
this.maybeInjectScreenCategory(this.pc.localDescription.sdp),
|
||||
this.jid
|
||||
);
|
||||
} else {
|
||||
Visio_ajaxSessionAccept(
|
||||
this.fullJid,
|
||||
this.id,
|
||||
this.maybeInjectScreenCategory(this.pc.localDescription.sdp)
|
||||
);
|
||||
}
|
||||
})
|
||||
.catch(MovimUtils.logError);
|
||||
}).catch(error => MovimUtils.logError(error));
|
||||
}
|
||||
|
||||
/**
|
||||
* With the SFU we can't have the screen as a new content, so we have to build a completely
|
||||
* new RTPPc
|
||||
*/
|
||||
MovimJingleSession.prototype.onSFUScreenSharingPropose = function (sdp) {
|
||||
this.maybeDetectTracksScreen(sdp);
|
||||
|
||||
this.screenSharingPc = new RTCPeerConnection({
|
||||
iceServers: MovimVisio.services,
|
||||
bundlePolicy: 'max-bundle',
|
||||
iceCandidatePoolSize: 10
|
||||
});
|
||||
|
||||
this.screenSharingPc.ontrack = event => {
|
||||
var srcObject = null;
|
||||
|
||||
if (event.streams && event.streams[0]) {
|
||||
srcObject = event.streams[0];
|
||||
} else {
|
||||
srcObject = new MediaStream();
|
||||
srcObject.addTrack(event.track);
|
||||
}
|
||||
|
||||
if (event.track.kind == 'audio') {
|
||||
if (this.tracksScreen[event.transceiver.mid]) {
|
||||
this.remoteScreenAudio.srcObject = srcObject;
|
||||
this.tracksTypes['sfu_screen_mid' + event.transceiver.mid] = 'audio_screen';
|
||||
}
|
||||
} else if (event.track.kind === 'video') {
|
||||
if (this.tracksScreen[event.transceiver.mid]) {
|
||||
this.remoteScreenVideo.srcObject = srcObject;
|
||||
this.tracksTypes['sfu_screen_mid' + event.transceiver.mid] = 'video_screen';
|
||||
this.remoteScreenVideo.oncanplay = event => {
|
||||
this.participant.classList.remove('screen_off');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.screenSharingPc.onicecandidate = event => {
|
||||
let candidate = event.candidate;
|
||||
if (candidate && candidate.candidate && candidate.candidate.length > 0) {
|
||||
Visio_ajaxCandidate(this.fullJid, this.id, event.candidate);
|
||||
}
|
||||
};
|
||||
|
||||
this.screenSharingPc.setRemoteDescription({ 'sdp': sdp + "\n", 'type': 'offer' })
|
||||
.then(this.screenSharingPc.createAnswer()
|
||||
.then(answer => this.screenSharingPc.setLocalDescription(answer))
|
||||
.then(() => {
|
||||
Visio_ajaxContentAccept(
|
||||
this.fullJid,
|
||||
this.id,
|
||||
this.maybeInjectScreenCategory(this.screenSharingPc.localDescription.sdp),
|
||||
this.jid
|
||||
)
|
||||
})
|
||||
.catch(MovimUtils.logError));
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onSFUScreenSharingTerminate = function () {
|
||||
if (this.screenSharingPc) {
|
||||
this.screenSharingPc.close();
|
||||
this.screenSharingPc = null;
|
||||
}
|
||||
|
||||
this.participant.classList.add('screen_off');
|
||||
|
||||
Object.keys(MovimJingles.sessions[this.jid].tracksTypes).forEach(
|
||||
key => {
|
||||
if (key.startsWith('sfu_screen_mid')) {
|
||||
delete MovimJingles.sessions[this.jid].tracksTypes[key]
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.enableScreenSharing = function () {
|
||||
MovimVisio.screenSharing.srcObject.getTracks().forEach(track => {
|
||||
if (track.kind == 'video') {
|
||||
if (this.screenSharingSender) {
|
||||
this.screenSharingSender.replaceTrack(track).then(() => {
|
||||
this.unmute(track);
|
||||
});
|
||||
} else {
|
||||
this.screenSharingSender = this.pc.addTrack(track);
|
||||
}
|
||||
} else {
|
||||
if (this.audioSharingSender) {
|
||||
this.audioSharingSender.replaceTrack(track).then(() => {
|
||||
this.unmute(track);
|
||||
});
|
||||
} else {
|
||||
this.audioSharingSender = this.pc.addTrack(track);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.disableScreenSharing = function () {
|
||||
if (this.pc && MovimVisio.screenSharing.srcObject) {
|
||||
MovimVisio.screenSharing.srcObject.getTracks().forEach(track => this.mute(track));
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.resolveTransceiver = function (track) {
|
||||
const transceiver = this.pc.getTransceivers().find(transceiver => transceiver.sender.track && transceiver.sender.track.id == track.id);
|
||||
return transceiver ?? null;
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.mute = function (track) {
|
||||
const transceiver = this.resolveTransceiver(track);
|
||||
if (transceiver) {
|
||||
Visio_ajaxMute(this.fullJid, this.id, 'mid' + transceiver.mid);
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.unmute = function (track) {
|
||||
const transceiver = this.resolveTransceiver(track);
|
||||
if (transceiver) {
|
||||
Visio_ajaxUnmute(this.fullJid, this.id, 'mid' + transceiver.mid);
|
||||
} else if (track.kind == 'video') {
|
||||
this.pc.addTrack(track);
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onMute = function (name) {
|
||||
if (this.tracksTypes[name]) {
|
||||
if (this.tracksTypes[name] == 'audio') {
|
||||
this.participant.classList.add('audio_off');
|
||||
}
|
||||
|
||||
if (this.tracksTypes[name] == 'video') {
|
||||
this.participant.classList.add('video_off');
|
||||
}
|
||||
|
||||
if (this.tracksTypes[name] == 'video_screen') {
|
||||
this.participant.classList.add('screen_off');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.onUnmute = function (name) {
|
||||
if (this.tracksTypes[name]) {
|
||||
if (this.tracksTypes[name] == 'audio') {
|
||||
this.participant.classList.remove('audio_off');
|
||||
}
|
||||
|
||||
if (this.tracksTypes[name] == 'video') {
|
||||
this.participant.classList.remove('video_off');
|
||||
}
|
||||
|
||||
if (this.tracksTypes[name] == 'video_screen') {
|
||||
this.participant.classList.remove('screen_off');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MovimJingleSession.prototype.insertDtmf = function (s) {
|
||||
var rtc = this.pc.getSenders().find(rtc => rtc.track && rtc.track.kind == 'audio');
|
||||
|
||||
if (!rtc || !rtc.dtmf.canInsertDTMF) return;
|
||||
|
||||
rtc.dtmf.insertDTMF(s);
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect RFC4796 content attribute
|
||||
*/
|
||||
MovimJingleSession.prototype.maybeDetectTracksScreen = function (sdp) {
|
||||
sdp.split('m=').forEach(media => {
|
||||
let content = media.match(/a=content:(.*)/);
|
||||
if (content && content.includes('slides')) {
|
||||
let mid = media.match(/a=mid:(.*)/);
|
||||
this.tracksScreen[mid[1]] = true;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Inject RFC4796 content attribute to respect XEP-0507: Jingle Content Category
|
||||
*/
|
||||
MovimJingleSession.prototype.maybeInjectScreenCategory = function (sdp) {
|
||||
if (this.audioSharingSender?.track || this.screenSharingSender?.track) {
|
||||
let ids = [];
|
||||
if (this.audioSharingSender) ids.push(this.audioSharingSender.track.id);
|
||||
if (this.screenSharingSender) ids.push(this.screenSharingSender.track.id);
|
||||
|
||||
sdp = sdp.split('m=').map(media => {
|
||||
let mid = media.match(MovimVisio.midRegex);
|
||||
if (mid != null) {
|
||||
const transceiver = this.pc.getTransceivers().find(transceiver => transceiver.mid == mid[1]);
|
||||
if (transceiver) {
|
||||
if (ids.includes(transceiver.sender.track.id)) {
|
||||
return media + 'a=content:slides' + "\n";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return media;
|
||||
}).join('m=');
|
||||
}
|
||||
|
||||
return sdp;
|
||||
}
|
||||
|
||||
var MovimJingles = {
|
||||
sessions: {},
|
||||
pinned: null,
|
||||
|
||||
startCalls: function (mujiRoom) {
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
MovimJingles.onProceed(jid, MovimJingles.sessions[jid].fullJid, MovimJingles.sessions[jid].id, mujiRoom);
|
||||
}
|
||||
},
|
||||
|
||||
initSession: function (jid, fullJid, id, name, avatarUrl) {
|
||||
if (Object.keys(MovimJingles.sessions).includes(jid)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!MovimVisio.localStream) {
|
||||
throw Error('localStream is not ready');
|
||||
};
|
||||
|
||||
MovimJingles.sessions[jid] = new MovimJingleSession(jid, fullJid, id, name, avatarUrl);
|
||||
return MovimJingles.sessions[jid].id;
|
||||
},
|
||||
|
||||
checkActiveSpeaker: function () {
|
||||
let maxLevel = 0;
|
||||
let maxJid = null;
|
||||
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
if (maxLevel < MovimJingles.sessions[jid].audioLevel) {
|
||||
maxLevel = MovimJingles.sessions[jid].audioLevel;
|
||||
maxJid = jid;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].participant.classList.remove('active', 'pinned');
|
||||
}
|
||||
|
||||
// Pinned has priority
|
||||
if (MovimJingles.pinned && MovimJingles.sessions[MovimJingles.pinned]) {
|
||||
MovimJingles.sessions[MovimJingles.pinned].participant.classList.add('active', 'pinned');
|
||||
return;
|
||||
}
|
||||
|
||||
if (maxJid != null) {
|
||||
MovimJingles.sessions[maxJid].participant.classList.add('active');
|
||||
} else if (Object.values(MovimJingles.sessions).length > 0) {
|
||||
Object.values(MovimJingles.sessions)[MovimVisio.sfu != null ? 1 : 0]?.participant.classList.add('active');
|
||||
}
|
||||
},
|
||||
|
||||
onManageTrack: function (stream, enable) {
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
MovimJingles.sessions[jid].onManageTrack(stream, enable);
|
||||
}
|
||||
},
|
||||
|
||||
enableScreenSharing: function () {
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
MovimJingles.sessions[jid].enableScreenSharing();
|
||||
}
|
||||
},
|
||||
|
||||
disableScreenSharing: function () {
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
MovimJingles.sessions[jid].disableScreenSharing();
|
||||
}
|
||||
},
|
||||
|
||||
enableAudio: function (enable = true) {
|
||||
MovimVisio.localStream.getTracks().filter(track => track.kind == 'audio').forEach(track => {
|
||||
track.enabled = enable;
|
||||
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
if (enable) {
|
||||
MovimJingles.sessions[jid].unmute(track);
|
||||
} else {
|
||||
MovimJingles.sessions[jid].mute(track);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
enableVideo: function (enable = true) {
|
||||
MovimVisio.mujiPublish();
|
||||
|
||||
MovimVisio.localStream.getTracks().filter(track => track.kind == 'video').forEach(track => {
|
||||
track.enabled = enable;
|
||||
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
if (enable) {
|
||||
MovimJingles.sessions[jid].unmute(track);
|
||||
} else {
|
||||
MovimJingles.sessions[jid].mute(track);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
insertDtmf: function (s) {
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
MovimJingles.sessions[jid].insertDtmf(s);
|
||||
}
|
||||
},
|
||||
|
||||
onCandidate: function (jid, candidate, mid, mlineindex, sid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Candidate from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
if (sid && sid === MovimVisio.screenshareSid) {
|
||||
MovimVisio.onScreenshareCandidate(candidate, mid, mlineindex);
|
||||
return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onCandidate(candidate, mid, mlineindex);
|
||||
},
|
||||
|
||||
onInitiateSDP: function (jid, sdp, sid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Initiate SDP from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
// Put the real sid
|
||||
MovimJingles.sessions[jid].id = sid;
|
||||
MovimJingles.sessions[jid].onInitiateSDP(sdp);
|
||||
},
|
||||
|
||||
onAcceptSDP: function (jid, sdp, sid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Accept SDP from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
if (sid && sid === MovimVisio.screenshareSid) {
|
||||
MovimVisio.onScreenshareAcceptSDP(sdp);
|
||||
return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onAcceptSDP(sdp);
|
||||
},
|
||||
|
||||
onProceed: function (jid, fullJid, id, mujiRoom) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Proceed from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].sessionInitiate(fullJid, id, mujiRoom);
|
||||
},
|
||||
|
||||
onMute: function (jid, name) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Mute from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onMute(name);
|
||||
},
|
||||
|
||||
onUnmute: function (jid, name) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Unmute from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onUnmute(name);
|
||||
},
|
||||
|
||||
onContentAdd: function (jid, sdp, mid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Content add from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onContentAdd(sdp, mid);
|
||||
},
|
||||
|
||||
onContentModify: function (jid, sdp, mid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Content modify from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onContentModify(sdp, mid);
|
||||
},
|
||||
|
||||
onContentRemove: function (jid, sdp, mid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('Content remove from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onContentRemove(sdp, mid);
|
||||
},
|
||||
|
||||
onSFUScreenSharingPropose: function (jid, sdp) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('SFU screen sharing propose from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onSFUScreenSharingPropose(sdp);
|
||||
},
|
||||
|
||||
onSFUScreenSharingTerminate: function (jid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) {
|
||||
console.log('SFU screen sharing terminate from a non initiated session ' + jid); return;
|
||||
}
|
||||
|
||||
MovimJingles.sessions[jid].onSFUScreenSharingTerminate();
|
||||
},
|
||||
|
||||
terminate: function (jid, reason) {
|
||||
if (MovimJingles.sessions[jid] == undefined) return;
|
||||
|
||||
let visio = document.querySelector('#visio');
|
||||
MovimJingles.sessions[jid].terminate(reason, (visio.dataset.muji == 'true'));
|
||||
delete MovimJingles.sessions[jid];
|
||||
},
|
||||
|
||||
onTerminate: function (jid) {
|
||||
if (MovimJingles.sessions[jid] == undefined) return;
|
||||
|
||||
MovimJingles.sessions[jid].close();
|
||||
delete MovimJingles.sessions[jid];
|
||||
|
||||
let visio = document.querySelector('#visio');
|
||||
|
||||
// No sessions left
|
||||
if (Object.keys(MovimJingles.sessions).length == 0) {
|
||||
if (visio.dataset.muji == 'false') {
|
||||
Visio_ajaxClear();
|
||||
} else {
|
||||
let state = document.querySelector('p.state');
|
||||
if (state) {
|
||||
state.innerText = MovimVisio.states.no_participants_left;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
terminateAll: function (reason) {
|
||||
for (const jid of Object.keys(MovimJingles.sessions)) {
|
||||
MovimJingles.terminate(jid, reason);
|
||||
}
|
||||
|
||||
MovimJingles.pinned = null;
|
||||
Visio_ajaxClear();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Short functions
|
||||
*/
|
||||
function MWSa(widget, func, params) {
|
||||
return MovimRPC.fetch(widget, func, params, false);
|
||||
}
|
||||
|
||||
function MWSad(widget, func, params) {
|
||||
return MovimRPC.fetch(widget, func, params, true);
|
||||
}
|
||||
|
||||
var MovimRPC = {
|
||||
fetchWithTimeout: async function (resource, options = {}) {
|
||||
const { timeout = 5000 } = options;
|
||||
|
||||
const controller = new AbortController();
|
||||
|
||||
const id = setTimeout(() => controller.abort(), timeout);
|
||||
const response = await fetch(resource, {
|
||||
...options,
|
||||
signal: controller.signal
|
||||
});
|
||||
clearTimeout(id);
|
||||
|
||||
return response;
|
||||
},
|
||||
|
||||
fetch: function (widget, func, params, daemon) {
|
||||
var body = {
|
||||
'c': MovimUtils.urlParts().page,
|
||||
'w': widget,
|
||||
'f': func
|
||||
};
|
||||
|
||||
if (params) body.p = params;
|
||||
|
||||
var url = BASE_URI;
|
||||
let request = MovimRPC.fetchWithTimeout(url += daemon ? 'ajaxd' : 'ajax', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify(
|
||||
{ 'func': 'message', 'b': body }
|
||||
)
|
||||
});
|
||||
|
||||
if (!daemon) {
|
||||
request.then(response => {
|
||||
if (response.ok) {
|
||||
return response.json();
|
||||
} else if (response.status == 403) {
|
||||
MovimUtils.disconnect();
|
||||
}
|
||||
}).then(data => {
|
||||
for (funcall of data) {
|
||||
MovimRPC.handle(funcall);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return request;
|
||||
},
|
||||
|
||||
handle: function (funcall) {
|
||||
if (funcall.func != null && (typeof window[funcall.func] == 'function')) {
|
||||
try {
|
||||
window[funcall.func].apply(null, funcall.p);
|
||||
} catch (err) {
|
||||
console.log("Error caught: "
|
||||
+ err.toString()
|
||||
+ " - "
|
||||
+ funcall.func
|
||||
+ ":"
|
||||
+ JSON.stringify(funcall.p)
|
||||
);
|
||||
}
|
||||
} else if (funcall.func != null) {
|
||||
var funcs = funcall.func.split('.');
|
||||
var called = funcs[0];
|
||||
if (typeof window[called] == 'object'
|
||||
&& typeof window[funcs[0]][funcs[1]] != 'undefined') {
|
||||
window[funcs[0]][funcs[1]].apply(null, funcall.p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
/**
|
||||
* Movim Javascript Template functions
|
||||
|
||||
* Look at the comments for help.
|
||||
*/
|
||||
|
||||
var MovimTpl = {
|
||||
startX: 0,
|
||||
startY: 0,
|
||||
translateX: 0,
|
||||
menuDragged: false,
|
||||
currentPage: '',
|
||||
currentAnchor: '',
|
||||
popAnchorKey: null,
|
||||
popAnchorAction: null,
|
||||
|
||||
loadingPage: function () {
|
||||
document.body.classList.add('loading');
|
||||
document.body.classList.remove('finished');
|
||||
},
|
||||
finishedPage: function () {
|
||||
document.body.classList.add('finished');
|
||||
|
||||
setTimeout(e => {
|
||||
document.body.classList.remove('loading', 'finished');
|
||||
}, 1000);
|
||||
},
|
||||
|
||||
append: function (selector, html) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
target.insertAdjacentHTML('beforeend', html);
|
||||
}
|
||||
},
|
||||
appendAfter: function (selector, html) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
target.insertAdjacentHTML('afterend', html);
|
||||
}
|
||||
},
|
||||
pushAnchorState: function (key, action) {
|
||||
if (MovimTpl.popAnchorAction && key != MovimTpl.popAnchorKey) {
|
||||
MovimTpl.popAnchorAction();
|
||||
}
|
||||
|
||||
window.history.pushState(null, null, '#' + key);
|
||||
MovimTpl.popAnchorKey = key;
|
||||
MovimTpl.popAnchorAction = action;
|
||||
},
|
||||
clearAnchorState: function () {
|
||||
if (MovimTpl.popAnchorAction) {
|
||||
MovimTpl.popAnchorAction();
|
||||
}
|
||||
|
||||
MovimTpl.popAnchorKey = null;
|
||||
MovimTpl.popAnchorAction = null;
|
||||
window.history.replaceState(null, null, ' ');
|
||||
},
|
||||
fill: function (selector, html) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
target.innerHTML = html;
|
||||
}
|
||||
},
|
||||
showPanel: function () {
|
||||
MovimUtils.addClass('main', 'enabled');
|
||||
MovimUtils.addClass('ul#bottomnavigation', 'hidden');
|
||||
},
|
||||
hidePanel: function () {
|
||||
MovimUtils.removeClass('main', 'enabled');
|
||||
MovimUtils.removeClass('ul#bottomnavigation', 'hidden');
|
||||
},
|
||||
prepend: function (selector, html) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
target.insertAdjacentHTML('afterbegin', html);
|
||||
}
|
||||
},
|
||||
prependBefore: function (selector, html) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
target.insertAdjacentHTML('beforebegin', html);
|
||||
}
|
||||
},
|
||||
remove: function (selector) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
target.remove();
|
||||
}
|
||||
},
|
||||
replace: function (selector, html) {
|
||||
target = document.querySelector(selector);
|
||||
if (target) {
|
||||
var div = document.createElement('div');
|
||||
div.innerHTML = html;
|
||||
var element = div.firstChild;
|
||||
replacedNode = target.parentNode.replaceChild(element, target);
|
||||
}
|
||||
},
|
||||
showContextMenu: function () {
|
||||
var contextMenu = document.querySelector('ul.context_menu');
|
||||
contextMenu.classList.add('shown');
|
||||
},
|
||||
hideContextMenu: function (e) {
|
||||
var contextMenu = document.querySelector('ul.context_menu');
|
||||
if (contextMenu == null) return;
|
||||
|
||||
if (!document.querySelector('.show_context_menu')?.contains(e.target)) {
|
||||
contextMenu.classList.remove('shown');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
MovimEvents.registerBody('click', 'movimtpl', (e) => MovimTpl.hideContextMenu(e));
|
||||
|
||||
MovimEvents.registerWindow('loaded', 'movimtpl', () => {
|
||||
MovimTpl.currentPage = window.location.pathname;
|
||||
});
|
||||
|
||||
MovimEvents.registerWindow('popstate', 'movimtpl', (e) => {
|
||||
if (Dialog.filled()) {
|
||||
Dialog.clear();
|
||||
return;
|
||||
}
|
||||
|
||||
if (MovimTpl.popAnchorKey || e.target.location.hash != '') {
|
||||
MovimTpl.clearAnchorState();
|
||||
return;
|
||||
}
|
||||
|
||||
if (e.target.location.pathname == MovimTpl.currentPage) return;
|
||||
|
||||
MovimUtils.reload(e.target.location.href, true);
|
||||
|
||||
MovimTpl.currentPage = e.target.location.pathname;
|
||||
MovimTpl.currentAnchor = window.location.hash.substring(1);
|
||||
});
|
||||
@@ -0,0 +1,484 @@
|
||||
/**
|
||||
* Movim Utils
|
||||
*
|
||||
* This file include some useful functions used quite everywhere in Movim
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Set object in localStorage
|
||||
* @param key string
|
||||
* @param value the object
|
||||
*/
|
||||
Storage.prototype.setObject = function (key, value) {
|
||||
this.setItem(key, JSON.stringify(value));
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Get object in localStorage
|
||||
* @param key
|
||||
*/
|
||||
Storage.prototype.getObject = function (key) {
|
||||
return JSON.parse(this.getItem(key));
|
||||
};
|
||||
|
||||
var MovimUtils = {
|
||||
cleanupId: function (string) {
|
||||
return 'id-' + string.replace(/([^a-z0-9]+)/gi, '-').toLowerCase();
|
||||
},
|
||||
hash(string) {
|
||||
let hash = 0;
|
||||
|
||||
if (string.length === 0) return hash;
|
||||
|
||||
for (let i = 0; i < string.length; i++) {
|
||||
const char = string.charCodeAt(i);
|
||||
hash = ((hash << 5) - hash) + char;
|
||||
hash = hash & hash;
|
||||
}
|
||||
|
||||
return hash;
|
||||
},
|
||||
isMobile: function () {
|
||||
return window.matchMedia('(max-width: 1024px)').matches;
|
||||
},
|
||||
disconnect: function () {
|
||||
window.location.replace(ERROR_URI);
|
||||
},
|
||||
|
||||
clearAllActivesRooms: function () {
|
||||
document.querySelectorAll('ul.list.rooms li:not(.subheader)')
|
||||
.forEach(item => item.classList.remove('active'));
|
||||
},
|
||||
setActiveRoom: function (jid) {
|
||||
if (typeof Chats != 'undefined') Chats.clearAllActives();
|
||||
MovimUtils.clearAllActivesRooms();
|
||||
MovimUtils.addClass('ul.list.rooms li[data-jid="' + jid + '"]', 'active');
|
||||
},
|
||||
|
||||
formSetDirty: function (formname) {
|
||||
var form = document.forms[formname];
|
||||
|
||||
if (!form) {
|
||||
return false;
|
||||
}
|
||||
|
||||
form.dataset.dirty = true;
|
||||
},
|
||||
|
||||
formToJson: function (formname) {
|
||||
var form = document.forms[formname];
|
||||
|
||||
if (!form) {
|
||||
return;
|
||||
}
|
||||
|
||||
var json = {};
|
||||
|
||||
json['isDirty'] = Boolean(form.dataset.dirty);
|
||||
|
||||
for (var i = 0; i < form.elements.length; i++) {
|
||||
json_att = {};
|
||||
|
||||
for (var j = 0; j < form.elements[i].attributes.length; j++) {
|
||||
if (form.elements[i].attributes[j].name != 'value') {
|
||||
json_att[form.elements[i].attributes[j].name] = form.elements[i].attributes[j].value;
|
||||
}
|
||||
}
|
||||
|
||||
if (form.elements[i].name.length != 0) {
|
||||
if (form.elements[i].type == 'checkbox') {
|
||||
json[form.elements[i].name] = {
|
||||
'value': form.elements[i].checked,
|
||||
'attributes': json_att
|
||||
};
|
||||
} else if (form.elements[i].type == 'radio' && form.elements[i].checked) {
|
||||
json[form.elements[i].name] = {
|
||||
'value': form.elements[i].value,
|
||||
'attributes': json_att
|
||||
};
|
||||
} else if (form.elements[i].type != 'radio') {
|
||||
json[form.elements[i].name] = {
|
||||
'value': form.elements[i].value,
|
||||
'attributes': json_att
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return json;
|
||||
},
|
||||
cleanTime: function (seconds) {
|
||||
var currentMinute = parseInt(seconds / 60) % 60,
|
||||
currentSecondsLong = seconds % 60,
|
||||
currentSeconds = currentSecondsLong.toFixed(),
|
||||
currentTime = (currentMinute < 10 ? "0" + currentMinute : currentMinute)
|
||||
+ ":" + (currentSeconds < 10 ? "0" + currentSeconds : currentSeconds);
|
||||
|
||||
return currentTime;
|
||||
},
|
||||
setTitle: function (title) {
|
||||
document.title = title;
|
||||
},
|
||||
pushState: function (url) {
|
||||
window.history.pushState(null, '', url);
|
||||
},
|
||||
pushSoftState: function (url) {
|
||||
if (window.location != url) {
|
||||
window.history.pushState({ soft: true }, '', url);
|
||||
MovimTpl.currentPage = window.location.pathname;
|
||||
}
|
||||
},
|
||||
redirect: function (url) {
|
||||
window.location.href = url;
|
||||
},
|
||||
openInNew: function (url) {
|
||||
window.open(url, '_blank');
|
||||
},
|
||||
reload: function (uri, noHistory) {
|
||||
requestUri = new URL(uri.replace(/^\/\//, 'https://'));
|
||||
requestUri.searchParams.append('soft', 'true');
|
||||
|
||||
MovimTpl.loadingPage();
|
||||
|
||||
MovimRPC.fetchWithTimeout(requestUri.toString(), {
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
}).then(reponse => {
|
||||
reponse.text().then(value => {
|
||||
let page = JSON.parse(value);
|
||||
|
||||
const oldWidgetCss = Array.from(
|
||||
document.head.querySelectorAll('link[rel=stylesheet].widget')
|
||||
);
|
||||
|
||||
const cssPromises = page.widgetsCSS.map(url => new Promise((resolve) => {
|
||||
const css = document.createElement('link');
|
||||
css.setAttribute('rel', 'stylesheet');
|
||||
css.href = url;
|
||||
css.classList.add('widget');
|
||||
css.onload = resolve;
|
||||
css.onerror = resolve;
|
||||
document.head.appendChild(css);
|
||||
}));
|
||||
|
||||
Promise.all(cssPromises).then(() => {
|
||||
MovimTpl.finishedPage();
|
||||
|
||||
if (noHistory !== true) {
|
||||
MovimUtils.pushSoftState(uri);
|
||||
}
|
||||
|
||||
if (typeof MovimWebsocket !== 'undefined') {
|
||||
MovimWebsocket.clear();
|
||||
}
|
||||
|
||||
oldWidgetCss.forEach(e => e.remove());
|
||||
document.head.querySelectorAll('script[type=\'text/javascript\'].widget').forEach(e => e.remove());
|
||||
document.head.querySelectorAll('script[type=\'text/javascript\'].inline').forEach(e => e.remove());
|
||||
document.querySelectorAll('#endcommon ~ *').forEach(e => e.remove());
|
||||
|
||||
document.body.insertAdjacentHTML('beforeend', page.content);
|
||||
document.title = page.title;
|
||||
|
||||
const promises = page.widgetsScripts.map(script => new Promise((resolve) => {
|
||||
const js = document.createElement('script');
|
||||
js.src = script;
|
||||
js.setAttribute('type', 'text/javascript');
|
||||
js.onload = resolve;
|
||||
js.onerror = resolve;
|
||||
js.classList.add('widget');
|
||||
document.head.appendChild(js);
|
||||
}));
|
||||
|
||||
const inlineJs = document.createElement('script');
|
||||
inlineJs.classList.add('inline');
|
||||
inlineJs.innerHTML = page.inlineScripts;
|
||||
document.head.appendChild(inlineJs);
|
||||
|
||||
Promise.all(promises).then(() => {
|
||||
MovimEvents.triggerWindow('loaded', null);
|
||||
});
|
||||
});
|
||||
});
|
||||
}).catch(error => {
|
||||
document.body.classList.add('finished');
|
||||
});
|
||||
},
|
||||
reloadThis: function () {
|
||||
window.location.reload();
|
||||
},
|
||||
addClass: function (element, classname) {
|
||||
let el = document.querySelector(element);
|
||||
if (el) el.classList.add(classname);
|
||||
},
|
||||
removeClass: function (element, classname) {
|
||||
let el = document.querySelector(element);
|
||||
if (el) el.classList.remove(classname);
|
||||
},
|
||||
setDataItem: function (element, key, value) {
|
||||
let el = document.querySelector(element);
|
||||
if (el) {
|
||||
if (value) {
|
||||
el.dataset[key] = value;
|
||||
} else {
|
||||
delete el.dataset[key];
|
||||
}
|
||||
}
|
||||
},
|
||||
decodeHTMLEntities(text) {
|
||||
var textarea = document.createElement('textarea');
|
||||
textarea.innerHTML = text;
|
||||
return textarea.value;
|
||||
},
|
||||
copyToClipboard: function (text) {
|
||||
navigator.clipboard.writeText(text).catch(err => MovimUtils.logError(err));
|
||||
},
|
||||
htmlEscape: function (string) {
|
||||
return string
|
||||
.replaceAll("&", "&")
|
||||
.replaceAll("<", "<")
|
||||
.replaceAll(">", ">")
|
||||
.replaceAll('"', """)
|
||||
.replaceAll("'", "'");
|
||||
},
|
||||
enhanceArticlesContent: function () {
|
||||
document.querySelectorAll('article section > div video')
|
||||
.forEach(item => item.setAttribute('controls', 'controls'));
|
||||
|
||||
document.querySelectorAll('article section > div a:not(.innertag)')
|
||||
.forEach(link => link.setAttribute('target', '_blank'));
|
||||
|
||||
document.querySelectorAll('article section > div img')
|
||||
.forEach(img => {
|
||||
if (img.parentNode.localName != 'a') {
|
||||
var div = document.createElement('div');
|
||||
if (!img.parentNode.classList.contains('previewable')) {
|
||||
img.parentNode.insertBefore(div, img);
|
||||
div.classList.add('previewable');
|
||||
img.classList.add('active');
|
||||
img.addEventListener('click', () => Preview_ajaxHttpShow(img.src))
|
||||
|
||||
div.appendChild(img);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
urlParts: function () {
|
||||
var str = window.location.pathname.split('/');
|
||||
var page = str[1];
|
||||
|
||||
str.shift();
|
||||
str.shift();
|
||||
|
||||
str = str.map(param => decodeURIComponent(param));
|
||||
|
||||
return { 'page': page, 'params': str, 'hash': window.location.hash.substring(1) };
|
||||
},
|
||||
humanFileSize: function (bytes, si) {
|
||||
var thresh = si ? 1000 : 1024;
|
||||
if (Math.abs(bytes) < thresh) {
|
||||
return bytes + ' B';
|
||||
}
|
||||
var units = si
|
||||
? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
|
||||
: ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
|
||||
var u = -1;
|
||||
do {
|
||||
bytes /= thresh;
|
||||
++u;
|
||||
} while (Math.abs(bytes) >= thresh && u < units.length - 1);
|
||||
return bytes.toFixed(1) + ' ' + units[u];
|
||||
},
|
||||
getOrientation: function (file, callback) {
|
||||
var testImageURL =
|
||||
'data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAA' +
|
||||
'AAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBA' +
|
||||
'QEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE' +
|
||||
'BAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/x' +
|
||||
'ABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAA' +
|
||||
'AAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQ' +
|
||||
'voP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXw' +
|
||||
'H/9k='
|
||||
|
||||
var img = document.createElement('img');
|
||||
img.onload = function () {
|
||||
// Check if the browser supports automatic image orientation:
|
||||
let orientation = img.width === 2 && img.height === 3;
|
||||
|
||||
if (orientation) {
|
||||
return callback(-1);
|
||||
} else {
|
||||
var reader = new FileReader();
|
||||
|
||||
reader.onload = function (e) {
|
||||
var view = new DataView(e.target.result);
|
||||
if (view.getUint16(0, false) != 0xFFD8) return callback(-2);
|
||||
var length = view.byteLength, offset = 2;
|
||||
|
||||
while (offset < length) {
|
||||
var marker = view.getUint16(offset, false);
|
||||
offset += 2;
|
||||
if (marker == 0xFFE1) {
|
||||
if (view.getUint32(offset += 2, false) != 0x45786966) return callback(-1);
|
||||
|
||||
var little = view.getUint16(offset += 6, false) == 0x4949;
|
||||
offset += view.getUint32(offset + 4, little);
|
||||
|
||||
var tags = view.getUint16(offset, little);
|
||||
offset += 2;
|
||||
|
||||
for (var i = 0; i < tags; i++)
|
||||
if (view.getUint16(offset + (i * 12), little) == 0x0112)
|
||||
|
||||
return callback(view.getUint16(offset + (i * 12) + 8, little));
|
||||
}
|
||||
else if ((marker & 0xFF00) != 0xFF00) break;
|
||||
else offset += view.getUint16(offset, false);
|
||||
}
|
||||
|
||||
return callback(-1);
|
||||
};
|
||||
|
||||
reader.readAsArrayBuffer(file);
|
||||
}
|
||||
}
|
||||
img.src = testImageURL
|
||||
},
|
||||
applyOrientation: function (ctx, orientation, width, height) {
|
||||
switch (orientation) {
|
||||
case 2: ctx.transform(-1, 0, 0, 1, width, 0); break;
|
||||
case 3: ctx.transform(-1, 0, 0, -1, width, height); break;
|
||||
case 4: ctx.transform(1, 0, 0, -1, 0, height); break;
|
||||
case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
|
||||
case 6: ctx.transform(0, 1, -1, 0, height, 0); break;
|
||||
case 7: ctx.transform(0, -1, -1, 0, height, width); break;
|
||||
case 8: ctx.transform(0, -1, 1, 0, 0, width); break;
|
||||
default: ctx.transform(1, 0, 0, 1, 0, 0);
|
||||
}
|
||||
},
|
||||
drawImageProp: function (ctx, img, x, y, w, h, offsetX, offsetY) {
|
||||
if (arguments.length === 2) {
|
||||
x = y = 0;
|
||||
w = ctx.canvas.width;
|
||||
h = ctx.canvas.height;
|
||||
}
|
||||
|
||||
// default offset is center
|
||||
offsetX = typeof offsetX === "number" ? offsetX : 0.5;
|
||||
offsetY = typeof offsetY === "number" ? offsetY : 0.5;
|
||||
|
||||
// keep bounds [0.0, 1.0]
|
||||
if (offsetX < 0) offsetX = 0;
|
||||
if (offsetY < 0) offsetY = 0;
|
||||
if (offsetX > 1) offsetX = 1;
|
||||
if (offsetY > 1) offsetY = 1;
|
||||
|
||||
var iw = img.width,
|
||||
ih = img.height,
|
||||
r = Math.min(w / iw, h / ih),
|
||||
nw = iw * r, // new prop. width
|
||||
nh = ih * r, // new prop. height
|
||||
cx, cy, cw, ch, ar = 1;
|
||||
|
||||
// decide which gap to fill
|
||||
if (nw < w) ar = w / nw;
|
||||
if (Math.abs(ar - 1) < 1e-14 && nh < h) ar = h / nh; // updated
|
||||
nw *= ar;
|
||||
nh *= ar;
|
||||
|
||||
// calc source rectangle
|
||||
cw = iw / (nw / w);
|
||||
ch = ih / (nh / h);
|
||||
|
||||
cx = (iw - cw) * offsetX;
|
||||
cy = (ih - ch) * offsetY;
|
||||
|
||||
// make sure source rectangle is valid
|
||||
if (cx < 0) cx = 0;
|
||||
if (cy < 0) cy = 0;
|
||||
if (cw > iw) cw = iw;
|
||||
if (ch > ih) ch = ih;
|
||||
|
||||
// fill image in dest. rectangle
|
||||
ctx.drawImage(img, cx, cy, cw, ch, x, y, w, h);
|
||||
},
|
||||
imageToHex: function (img) {
|
||||
const context = document.createElement("canvas").getContext("2d");
|
||||
context.drawImage(img, 0, 0, 1, 1);
|
||||
const i = context.getImageData(0, 0, 1, 1).data;
|
||||
return "#" + ((1 << 24) + (i[0] << 16) + (i[1] << 8) + i[2]).toString(16).slice(1);
|
||||
},
|
||||
getEventLocation: function (e) {
|
||||
if (e.touches && e.touches.length == 1) {
|
||||
return { x: e.touches[0].clientX, y: e.touches[0].clientY }
|
||||
}
|
||||
else if (e.clientX && e.clientY) {
|
||||
return { x: e.clientX, y: e.clientY }
|
||||
}
|
||||
},
|
||||
base64ToBinary: function (base64) {
|
||||
return new Uint8Array(atob(base64).split('').map(x => x.charCodeAt(0)));
|
||||
},
|
||||
arrayBufferToBase64: function (ab) {
|
||||
return btoa((new Uint8Array(ab)).reduce((data, byte) => data + String.fromCharCode(byte), ''));
|
||||
},
|
||||
base64ToArrayBuffer: function (base64) {
|
||||
var binary_string = window.atob(base64);
|
||||
var len = binary_string.length;
|
||||
var bytes = new Uint8Array(len);
|
||||
for (var i = 0; i < len; i++) {
|
||||
bytes[i] = binary_string.charCodeAt(i);
|
||||
}
|
||||
return bytes.buffer;
|
||||
},
|
||||
stringToArrayBuffer: function (string) {
|
||||
const bytes = new TextEncoder("utf-8").encode(string);
|
||||
return bytes.buffer;
|
||||
},
|
||||
arrayBufferToString: function (ab) {
|
||||
return new TextDecoder().decode(ab);
|
||||
},
|
||||
hexToArrayBuffer: function (hex) {
|
||||
const typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(h => parseInt(h, 16)));
|
||||
return typedArray.buffer;
|
||||
},
|
||||
appendArrayBuffer: function (buffer1, buffer2) {
|
||||
const tmp = new Uint8Array(buffer1.byteLength + buffer2.byteLength);
|
||||
tmp.set(new Uint8Array(buffer1), 0);
|
||||
tmp.set(new Uint8Array(buffer2), buffer1.byteLength);
|
||||
return tmp.buffer;
|
||||
},
|
||||
range: function (start, end) {
|
||||
return Array.from({ length: end - start + 1 }, (_, i) => i)
|
||||
},
|
||||
linkify: function (inputText) {
|
||||
const replacePattern1 = /(^|[ ])(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])($|[ ])/gim;
|
||||
const replacePattern2 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
|
||||
|
||||
let replacedText = inputText.replace(replacePattern1, '<a href="$2" target="_blank" rel="noopener noreferrer">$2</a>');
|
||||
replacedText = replacedText.replace(replacePattern2, '<a href="mailto:$1">$1</a>');
|
||||
|
||||
return replacedText;
|
||||
},
|
||||
logError: function (error) {
|
||||
console.log(error.name + ': ' + error.message);
|
||||
console.error(error);
|
||||
},
|
||||
};
|
||||
|
||||
/*
|
||||
* Set the li onclick event to the link and stop propagation, for accessinility purposes
|
||||
*/
|
||||
function listIconClick(event) {
|
||||
event.stopPropagation();
|
||||
let li = event.target.closest('li');
|
||||
if (li && li.onclick) {
|
||||
li.click();
|
||||
return;
|
||||
}
|
||||
|
||||
let span = event.target.closest('span.icon');
|
||||
if (span) span.click();
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
var MovimVisio = {
|
||||
id: null,
|
||||
|
||||
calling: false,
|
||||
|
||||
pc: null,
|
||||
|
||||
screenshareSid: null,
|
||||
screenshareSFUPc: null,
|
||||
|
||||
states: null,
|
||||
services: [],
|
||||
|
||||
localStream: null,
|
||||
localVideo: null,
|
||||
localAudio: null,
|
||||
screenSharing: null,
|
||||
|
||||
observer: null,
|
||||
|
||||
activeSpeakerIntervalId: null,
|
||||
|
||||
bundleRegex: 'a=group:(\\S+) (.+)',
|
||||
midRegex: 'a=mid:(.+)',
|
||||
|
||||
mouseMovement: null,
|
||||
mouseMovementTimeout: 5000,
|
||||
|
||||
startedAtTimer: null,
|
||||
|
||||
sfu: null,
|
||||
|
||||
load: function () {
|
||||
MovimVisio.localVideo = document.getElementById('local_video');
|
||||
|
||||
// Disable the video toggle by default
|
||||
MovimVisio.localVideo.classList.add('video_off');
|
||||
|
||||
MovimVisio.localVideo.addEventListener('loadeddata', () => {
|
||||
MovimVisio.localVideo.play()
|
||||
});
|
||||
|
||||
MovimVisio.screenSharing = document.getElementById('screen_sharing_video');
|
||||
MovimVisio.localAudio = document.getElementById('local_audio');
|
||||
},
|
||||
|
||||
init: function (fullJid, jid, id, withVideo, isMuji, sfuConference, contactName, contactAvatarUrl) {
|
||||
MovimVisio.id = id;
|
||||
|
||||
// Set a lock for the current browser (in case there's several others opened)
|
||||
localStorage.setItem('callId', id);
|
||||
localStorage.setItem('callJid', jid);
|
||||
|
||||
let visio = document.querySelector('#visio');
|
||||
delete visio.dataset.type;
|
||||
visio.dataset.jid = jid;
|
||||
visio.dataset.muji = isMuji ? 'true' : 'false';
|
||||
|
||||
if (typeof sfuConference == 'string') {
|
||||
visio.dataset.muji = 'true'; // To use the Muji layout... without using Muji
|
||||
visio.dataset.sfu = 'true';
|
||||
visio.dataset.jid = sfuConference;
|
||||
|
||||
Visio_ajaxHttpPrepareInfo(sfuConference, true);
|
||||
MovimVisio.activeSpeakerIntervalId = setInterval(MovimJingles.checkActiveSpeaker, 1000);
|
||||
} else {
|
||||
Visio_ajaxHttpPrepareInfo(jid, isMuji);
|
||||
}
|
||||
|
||||
if (isMuji == true) {
|
||||
MovimVisio.mujiPublish(true);
|
||||
MovimVisio.activeSpeakerIntervalId = setInterval(MovimJingles.checkActiveSpeaker, 1000);
|
||||
} else {
|
||||
MovimJingles.initSession(jid, fullJid, id, contactName, contactAvatarUrl);
|
||||
|
||||
if (MovimVisio.id) {
|
||||
// Called
|
||||
Visio_ajaxProceed(fullJid, MovimVisio.id);
|
||||
} else {
|
||||
// Calling
|
||||
MovimVisio.id = crypto.randomUUID();
|
||||
localStorage.setItem('callId', MovimVisio.id);
|
||||
Visio_ajaxPropose(fullJid, MovimVisio.id, withVideo, (typeof sfuConference == 'string'));
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof sfuConference == 'string') {
|
||||
MovimVisio.sfu = jid;
|
||||
|
||||
let sfuParticipant = visio.querySelector('div.participant[data-jid="' + jid + '"]');
|
||||
if (sfuParticipant) {
|
||||
// Ugly but works for now
|
||||
sfuParticipant.remove();
|
||||
}
|
||||
|
||||
Visio_ajaxUpgradeCurrentCallToSFU(jid, sfuConference);
|
||||
}
|
||||
|
||||
visio.classList.add('movements');
|
||||
|
||||
Notif.setCallStatus(MovimVisio.states.in_call);
|
||||
|
||||
visio.addEventListener('mousemove', e => {
|
||||
clearTimeout(MovimVisio.mouseMovement);
|
||||
visio.classList.add('movements');
|
||||
|
||||
MovimVisio.mouseMovement = setTimeout(() => {
|
||||
visio.classList.remove('movements');
|
||||
}, MovimVisio.mouseMovementTimeout);
|
||||
})
|
||||
|
||||
if (typeof navigator.mediaDevices.getDisplayMedia == 'undefined') {
|
||||
document.querySelector('#screen_sharing').classList.add('hide');
|
||||
}
|
||||
|
||||
if (MovimVisio.startedAtTimer) {
|
||||
clearInterval(MovimVisio.startedAtTimer);
|
||||
}
|
||||
|
||||
setInterval(VisioUtils.updateStartedAtCounters, 1000);
|
||||
|
||||
Dialog_ajaxClear();
|
||||
Notif.snackbarClear();
|
||||
},
|
||||
|
||||
startScreenshareSFU: function () {
|
||||
if (!MovimVisio.screenSharing.srcObject) return;
|
||||
|
||||
const pc = new RTCPeerConnection({
|
||||
iceServers: MovimVisio.services,
|
||||
bundlePolicy: 'max-bundle',
|
||||
iceCandidatePoolSize: 10
|
||||
});
|
||||
|
||||
MovimVisio.screenshareSid = crypto.randomUUID();
|
||||
MovimVisio.screenshareSFUPc = pc;
|
||||
|
||||
MovimVisio.screenSharing.srcObject.getTracks().forEach(track => {
|
||||
pc.addTrack(track, MovimVisio.screenSharing.srcObject);
|
||||
});
|
||||
|
||||
pc.onicecandidate = event => {
|
||||
if (event.candidate && event.candidate.candidate) {
|
||||
Visio_ajaxCandidate(MovimVisio.sfu, MovimVisio.screenshareSid, event.candidate);
|
||||
}
|
||||
};
|
||||
|
||||
pc.createOffer()
|
||||
.then(offer => pc.setLocalDescription(offer))
|
||||
.then(() => Visio_ajaxSessionInitiate(MovimVisio.sfu, pc.localDescription, MovimVisio.screenshareSid, null))
|
||||
.catch(err => MovimUtils.logError(err));
|
||||
},
|
||||
|
||||
stopScreenshareSFU: function () {
|
||||
if (!MovimVisio.screenshareSFUPc) return;
|
||||
|
||||
Visio_ajaxTerminate(MovimVisio.sfu, MovimVisio.screenshareSid, 'success', false);
|
||||
|
||||
MovimVisio.screenshareSFUPc.close();
|
||||
MovimVisio.screenshareSFUPc = null;
|
||||
MovimVisio.screenshareSid = null;
|
||||
},
|
||||
|
||||
onScreenshareAcceptSDP: function (sdp) {
|
||||
if (!MovimVisio.screenshareSFUPc) return;
|
||||
|
||||
MovimVisio.screenshareSFUPc
|
||||
.setRemoteDescription({ 'sdp': sdp + "\n", 'type': 'answer' })
|
||||
.catch(err => MovimUtils.logError(err));
|
||||
},
|
||||
|
||||
onScreenshareCandidate: function (candidate, mid, mlineindex) {
|
||||
if (!MovimVisio.screenshareSFUPc) return;
|
||||
|
||||
MovimVisio.screenshareSFUPc.addIceCandidate(new RTCIceCandidate({
|
||||
'candidate': candidate.split(/\n/).filter(line => line.startsWith('a=candidate')).join('').substring(2),
|
||||
'sdpMid': mid,
|
||||
'sdpMLineIndex': mlineindex
|
||||
})).catch(error => MovimUtils.logError(error));
|
||||
},
|
||||
|
||||
mujiPublish: function (init) {
|
||||
let pc = new RTCPeerConnection({ 'iceServers': MovimVisio.services });
|
||||
|
||||
/**
|
||||
* Ugly heuristic because it is not possible to match the SDP mids with the tranceiver sender track ids...
|
||||
*/
|
||||
let id = 0;
|
||||
|
||||
MovimVisio.localStream.getTracks().forEach(track => {
|
||||
pc.addTrack(track, MovimVisio.localStream);
|
||||
id++;
|
||||
});
|
||||
|
||||
let screenIds = [];
|
||||
|
||||
if (MovimVisio.screenSharing.srcObject) {
|
||||
MovimVisio.screenSharing.srcObject.getTracks().forEach(track => {
|
||||
pc.addTrack(track);
|
||||
screenIds.push(id);
|
||||
id++;
|
||||
});
|
||||
}
|
||||
|
||||
pc.createOffer().then(function (offer) {
|
||||
if (MovimVisio.screenSharing.srcObject) {
|
||||
// XEP-0507: Jingle Content Category
|
||||
newMedias = offer.sdp.split('m=').map(media => {
|
||||
let mid = media.match(MovimVisio.midRegex);
|
||||
if (mid != null) {
|
||||
if (screenIds.includes(parseInt(mid[1]))) {
|
||||
return media + 'a=content:slides' + "\n";
|
||||
}
|
||||
}
|
||||
|
||||
return media;
|
||||
});
|
||||
|
||||
localDescription = newMedias.join('m=');
|
||||
offer.sdp = localDescription;
|
||||
}
|
||||
|
||||
Visio_ajaxMujiPublish(MovimVisio.id, offer, init);
|
||||
pc.close();
|
||||
});
|
||||
},
|
||||
|
||||
setStates: function (states) {
|
||||
MovimVisio.states = states;
|
||||
},
|
||||
|
||||
setServices: function (services) {
|
||||
MovimVisio.services = services;
|
||||
},
|
||||
|
||||
getUserMedia: function (withVideo) {
|
||||
MovimVisio.load();
|
||||
|
||||
let lobby = document.querySelector('#visio_lobby');
|
||||
|
||||
if (lobby) {
|
||||
VisioUtils.disableLobbyCallButton();
|
||||
}
|
||||
|
||||
MovimTpl.loadingPage();
|
||||
|
||||
return navigator.mediaDevices.getUserMedia(VisioUtils.getConstraints(withVideo)).then(stream => {
|
||||
MovimTpl.finishedPage();
|
||||
|
||||
MovimVisio.localStream = stream;
|
||||
|
||||
if (lobby) {
|
||||
lobby.classList.add('configure');
|
||||
} else if (MovimVisio.localAudio.srcObject == null) {
|
||||
Visio_ajaxClear();
|
||||
return;
|
||||
}
|
||||
|
||||
stream.getTracks().forEach(track => {
|
||||
if (lobby) {
|
||||
VisioUtils.enableLobbyCallButton();
|
||||
}
|
||||
|
||||
if (track.kind == 'audio' && MovimVisio.localAudio && MovimVisio.localAudio.srcObject == null /* In case we're just adding the video */) {
|
||||
MovimVisio.localAudio.srcObject = stream;
|
||||
} else if (withVideo && track.kind === 'video') {
|
||||
MovimVisio.localVideo.srcObject = stream;
|
||||
|
||||
// Toggle the video on
|
||||
MovimVisio.localVideo.classList.remove('video_off');
|
||||
document.querySelector('#toggle_video i').innerText = 'videocam';
|
||||
|
||||
if (lobby) {
|
||||
let cameraPreview = lobby.querySelector('video#camera_preview');
|
||||
cameraPreview.addEventListener('loadeddata', () => cameraPreview.play());
|
||||
cameraPreview.srcObject = stream;
|
||||
cameraPreview.disablePictureInPicture = true;
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
VisioUtils.handleAudio();
|
||||
|
||||
if (lobby) {
|
||||
navigator.mediaDevices.enumerateDevices().then(devices => MovimVisio.gotDevices(withVideo, devices));
|
||||
}
|
||||
}, (e) => {
|
||||
MovimTpl.finishedPage();
|
||||
});
|
||||
},
|
||||
|
||||
gotDevices: function (withVideo, devicesInfo) {
|
||||
microphoneFound = false;
|
||||
cameraFound = false;
|
||||
|
||||
let microphoneSelect = document.querySelector('select[name=default_microphone]');
|
||||
microphoneSelect.onchange = (e) => {
|
||||
localStorage.defaultMicrophone = e.target.value;
|
||||
MovimVisio.getUserMedia(withVideo);
|
||||
};
|
||||
microphoneSelect.innerText = '';
|
||||
|
||||
VisioUtils.handleAudio();
|
||||
|
||||
let cameraSelect = document.querySelector('select[name=default_camera]');
|
||||
|
||||
if (cameraSelect) {
|
||||
cameraSelect.addEventListener('change', e => {
|
||||
localStorage.defaultCamera = e.target.value;
|
||||
|
||||
let cameraPreview = document.querySelector('video#camera_preview');
|
||||
|
||||
if (cameraPreview.srcObject) {
|
||||
cameraPreview.srcObject.getTracks().forEach(track => track.stop());
|
||||
}
|
||||
|
||||
cameraPreview.srcObject = null;
|
||||
|
||||
MovimVisio.getUserMedia(withVideo);
|
||||
});
|
||||
cameraSelect.innerText = '';
|
||||
}
|
||||
|
||||
for (const deviceInfo of devicesInfo) {
|
||||
if (deviceInfo.kind === 'audioinput') {
|
||||
const option = document.createElement('option');
|
||||
option.value = deviceInfo.deviceId;
|
||||
option.text = deviceInfo.label || `Microphone ${microphoneSelect.length + 1}`;
|
||||
|
||||
if (deviceInfo.deviceId == localStorage.defaultMicrophone) {
|
||||
option.selected = true;
|
||||
microphoneFound = true;
|
||||
}
|
||||
|
||||
microphoneSelect.appendChild(option);
|
||||
}
|
||||
|
||||
if (withVideo && deviceInfo.kind === 'videoinput') {
|
||||
const option = document.createElement('option');
|
||||
option.value = deviceInfo.deviceId;
|
||||
option.text = deviceInfo.label || `Camera ${microphoneSelect.length + 1}`;
|
||||
|
||||
if (deviceInfo.deviceId == localStorage.defaultCamera) {
|
||||
option.selected = true;
|
||||
cameraFound = true;
|
||||
}
|
||||
|
||||
// Sometimes we can have two devices with the same id
|
||||
if (!cameraSelect.querySelector('option[value="' + deviceInfo.deviceId + '"]')) {
|
||||
cameraSelect.appendChild(option);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (microphoneFound == false) {
|
||||
localStorage.defaultMicrophone = microphoneSelect.value;
|
||||
}
|
||||
|
||||
if (withVideo && cameraFound == false) {
|
||||
localStorage.defaultCamera = cameraSelect.value;
|
||||
}
|
||||
},
|
||||
|
||||
clear: function () {
|
||||
MovimTpl.finishedPage();
|
||||
|
||||
MovimVisio.id = null;
|
||||
MovimVisio.sfu = null;
|
||||
|
||||
Notif.setCallStatus(null);
|
||||
|
||||
clearInterval(MovimVisio.activeSpeakerIntervalId);
|
||||
|
||||
let visio = document.querySelector('#visio');
|
||||
//delete visio.dataset.type;
|
||||
delete visio.dataset.jid;
|
||||
delete visio.dataset.muji;
|
||||
delete visio.dataset.sfu;
|
||||
|
||||
if (document.fullscreenElement) {
|
||||
document.exitFullscreen();
|
||||
}
|
||||
|
||||
VisioUtils.stopAudio();
|
||||
|
||||
if (MovimVisio.localAudio) {
|
||||
let stream = MovimVisio.localAudio.srcObject;
|
||||
|
||||
if (stream) {
|
||||
stream.getTracks().forEach(track => track.stop());
|
||||
stream = null;
|
||||
}
|
||||
|
||||
MovimVisio.localAudio.srcObject = null;
|
||||
}
|
||||
|
||||
if (MovimVisio.localVideo) {
|
||||
let stream = MovimVisio.localVideo.srcObject;
|
||||
|
||||
if (stream) {
|
||||
stream.getTracks().forEach(track => track.stop());
|
||||
stream = null;
|
||||
}
|
||||
|
||||
MovimVisio.localVideo.srcObject = null;
|
||||
}
|
||||
|
||||
if (MovimVisio.localStream) {
|
||||
MovimVisio.localStream.getTracks().forEach(function (track) {
|
||||
track.stop();
|
||||
});
|
||||
MovimVisio.localStream = null;
|
||||
}
|
||||
|
||||
VisioUtils.disableScreenSharing();
|
||||
|
||||
MovimVisio.localAudio = null;
|
||||
MovimVisio.localVideo = null;
|
||||
MovimVisio.screenSharing = null;
|
||||
},
|
||||
|
||||
moveToChat: function (jid) {
|
||||
if (MovimVisio.observer != null) {
|
||||
MovimVisio.observer.disconnect();
|
||||
}
|
||||
|
||||
// SFU case
|
||||
if (MovimVisio.sfu != null) {
|
||||
let visio = document.querySelector('#visio');
|
||||
jid = visio.dataset.jid;
|
||||
}
|
||||
|
||||
var parts = MovimUtils.urlParts();
|
||||
|
||||
if ((parts.page == 'chat' && parts.params[0] == jid)
|
||||
|| (parts.page == 'space' && parts.params[2] == jid)) {
|
||||
const visio = document.getElementById('visio');
|
||||
const body = document.body;
|
||||
|
||||
document.querySelector('#chat_widget header').after(visio);
|
||||
Chat.scrollRestore();
|
||||
|
||||
const callback = (mutationList, observer) => {
|
||||
if (!document.getElementById('visio')) {
|
||||
document.getElementById('endcommon').before(visio);
|
||||
}
|
||||
};
|
||||
|
||||
MovimVisio.observer = new MutationObserver(callback);
|
||||
MovimVisio.observer.observe(body, { childList: true, subtree: true });
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
callStop: function (id, jid) {
|
||||
localStorage.removeItem('callId');
|
||||
localStorage.removeItem('callJid');
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof Visio_ajaxHttpGetStates == 'function') {
|
||||
Visio_ajaxHttpGetStates();
|
||||
}
|
||||
|
||||
if (typeof MovimWebsocket != 'undefined') {
|
||||
MovimWebsocket.attach(() => {
|
||||
if (MovimVisio.services.length == 0 && typeof Visio_ajaxResolveServices == 'function') {
|
||||
Visio_ajaxResolveServices();
|
||||
Visio_ajaxCheckStatus(localStorage.getItem('callId'), localStorage.getItem('callJid'));
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* Movim Websocket
|
||||
*
|
||||
* This file define the websocket behaviour and handle its connection
|
||||
*/
|
||||
|
||||
WebSocket.prototype.unregister = function () {
|
||||
this.send(JSON.stringify({ 'func': 'unregister' }));
|
||||
};
|
||||
|
||||
WebSocket.prototype.register = function (host) {
|
||||
this.send(JSON.stringify({ 'func': 'register', 'host': host }));
|
||||
};
|
||||
|
||||
/**
|
||||
* Short functions
|
||||
*/
|
||||
function MWSs(widget, func, params) {
|
||||
MovimWebsocket.send(widget, func, params);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Definition of the MovimWebsocket object
|
||||
* @param string error
|
||||
*/
|
||||
|
||||
var MovimWebsocket = {
|
||||
connection: null,
|
||||
initiated: [], // Launched when the socket is connecting or reconnecting
|
||||
attached: [], // Launched when the socket is connected to the daemon
|
||||
started: [], // Launched when the linker is started
|
||||
registered: [], // Launched when the linker is connected to XMPP
|
||||
reconnectTimeout: null,
|
||||
attempts: 1,
|
||||
pong: false,
|
||||
closed: false,
|
||||
statusBar: null,
|
||||
|
||||
launchAttached: function () {
|
||||
// We hide the Websocket error
|
||||
MovimWebsocket.statusBar.classList.add('hide');
|
||||
|
||||
for (var i = 0; i < MovimWebsocket.attached.length; i++) {
|
||||
MovimWebsocket.attached[i]();
|
||||
}
|
||||
},
|
||||
|
||||
launchRegistered: function () {
|
||||
for (var i = 0; i < MovimWebsocket.registered.length; i++) {
|
||||
MovimWebsocket.registered[i]();
|
||||
}
|
||||
},
|
||||
|
||||
launchStarted: function () {
|
||||
for (var i = 0; i < MovimWebsocket.started.length; i++) {
|
||||
MovimWebsocket.started[i]();
|
||||
}
|
||||
},
|
||||
|
||||
launchInitiated: function () {
|
||||
for (var i = 0; i < MovimWebsocket.initiated.length; i++) {
|
||||
MovimWebsocket.initiated[i]();
|
||||
}
|
||||
},
|
||||
|
||||
resolvePushEndpoint: async function () {
|
||||
if (!('serviceWorker' in navigator)) return null;
|
||||
|
||||
const registration = await navigator.serviceWorker.getRegistration(SW_URI);
|
||||
if (!registration || !registration.pushManager) return null;
|
||||
|
||||
const pushSubscription = await registration.pushManager.getSubscription();
|
||||
if (!pushSubscription) return null;
|
||||
|
||||
return pushSubscription.endpoint;
|
||||
},
|
||||
|
||||
init: async function () {
|
||||
var uri = 'ws:' + BASE_URI + 'ws/';
|
||||
|
||||
if (window.location.protocol === "https:") {
|
||||
var uri = 'wss:' + BASE_URI + 'ws/';
|
||||
}
|
||||
|
||||
if (this.connection !== null) {
|
||||
this.connection.onclose = null;
|
||||
this.connection.close();
|
||||
}
|
||||
|
||||
const pushEndpoint = await this.resolvePushEndpoint();
|
||||
|
||||
if (pushEndpoint) {
|
||||
uri += '?push=' + encodeURIComponent(pushEndpoint);
|
||||
}
|
||||
|
||||
this.connection = new WebSocket(uri);
|
||||
|
||||
this.connection.onopen = function (e) {
|
||||
console.log("Connection established!");
|
||||
|
||||
MovimWebsocket.attempts = 1;
|
||||
clearTimeout(MovimWebsocket.reconnectTimeout);
|
||||
|
||||
MovimWebsocket.launchAttached();
|
||||
};
|
||||
|
||||
this.connection.onmessage = function (e) {
|
||||
var obj = JSON.parse(e.data);
|
||||
|
||||
if (obj != null) {
|
||||
if (obj.func == 'registered') {
|
||||
MovimWebsocket.launchRegistered();
|
||||
}
|
||||
|
||||
if (obj.func == 'started') {
|
||||
// If the linker was started but we're not on the login page
|
||||
if (!['login', 'account', 'register', 'tag', 'about', 'community'].includes(MovimUtils.urlParts().page)) {
|
||||
MovimUtils.disconnect();
|
||||
} else {
|
||||
MovimWebsocket.launchStarted();
|
||||
}
|
||||
}
|
||||
|
||||
if (obj.func == 'disconnected') {
|
||||
MovimUtils.disconnect();
|
||||
}
|
||||
|
||||
if (obj.func == 'pong') {
|
||||
MovimWebsocket.pong = true;
|
||||
}
|
||||
|
||||
MovimRPC.handle(obj);
|
||||
}
|
||||
};
|
||||
|
||||
this.connection.onclose = function (e) {
|
||||
console.log("Connection closed by the server or session closed");
|
||||
|
||||
if (e.code == 1008) {
|
||||
// The server closed the connection and asked to keep it this way
|
||||
this.closed = true;
|
||||
MovimWebsocket.statusBar.classList.remove('hide', 'connect');
|
||||
MovimWebsocket.connection.close();
|
||||
} else if (e.code == 1006) {
|
||||
MovimWebsocket.reconnect();
|
||||
} else if (e.code == 1000) {
|
||||
MovimUtils.disconnect();
|
||||
}
|
||||
};
|
||||
|
||||
this.connection.onerror = function (e) {
|
||||
console.log("Connection error!");
|
||||
|
||||
// We show the Websocket error
|
||||
MovimWebsocket.statusBar.classList.remove('hide', 'connect');
|
||||
MovimWebsocket.reconnect();
|
||||
|
||||
// We prevent the onclose launch
|
||||
this.onclose = null;
|
||||
};
|
||||
},
|
||||
|
||||
send: function (widget, func, params) {
|
||||
if (this.connection && this.connection.readyState == 1) {
|
||||
var body = {
|
||||
'w': widget,
|
||||
'f': func
|
||||
};
|
||||
|
||||
if (params) body.p = params;
|
||||
this.connection.send(JSON.stringify(
|
||||
{ 'func': 'message', 'b': body }
|
||||
));
|
||||
}
|
||||
},
|
||||
|
||||
attach: function (func) {
|
||||
if (typeof (func) === "function") {
|
||||
this.attached.push(func);
|
||||
}
|
||||
},
|
||||
|
||||
register: function (func) {
|
||||
if (typeof (func) === "function") {
|
||||
this.registered.push(func);
|
||||
}
|
||||
},
|
||||
|
||||
start: function (func) {
|
||||
if (typeof (func) === "function") {
|
||||
this.started.push(func);
|
||||
}
|
||||
},
|
||||
|
||||
initiate: function (func) {
|
||||
if (typeof (func) === "function") {
|
||||
this.initiated.push(func);
|
||||
}
|
||||
},
|
||||
|
||||
clearAttached: function () {
|
||||
this.attached = [];
|
||||
},
|
||||
|
||||
clearInitiated: function () {
|
||||
this.initiated = [];
|
||||
},
|
||||
|
||||
clear: function () {
|
||||
this.clearAttached();
|
||||
this.clearInitiated();
|
||||
},
|
||||
|
||||
unregister: function () {
|
||||
this.connection.unregister();
|
||||
},
|
||||
|
||||
reconnect: function () {
|
||||
var interval = MovimWebsocket.generateInterval();
|
||||
console.log("Try to reconnect");
|
||||
|
||||
MovimWebsocket.reconnectTimeout = setTimeout(function () {
|
||||
// We've tried to reconnect so increment the attempts by 1
|
||||
MovimWebsocket.attempts++;
|
||||
|
||||
// Show the reconnect state
|
||||
MovimWebsocket.statusBar.classList.remove('hide');
|
||||
MovimWebsocket.statusBar.classList.add('connect');
|
||||
|
||||
// Connection has closed so try to reconnect every x seconds.
|
||||
MovimWebsocket.init();
|
||||
}, interval);
|
||||
},
|
||||
|
||||
generateInterval: function () {
|
||||
var maxInterval = (Math.pow(2, MovimWebsocket.attempts) - 1) * 1000;
|
||||
|
||||
if (maxInterval > 10 * 1000) {
|
||||
maxInterval = 10 * 1000; // If the generated interval is more than 30 seconds, truncate it down to 30 seconds.
|
||||
}
|
||||
|
||||
// generate the interval to a random number between 0 and the maxInterval determined from above
|
||||
return Math.random() * maxInterval;
|
||||
}
|
||||
}
|
||||
|
||||
MovimEvents.registerWindow('offline', 'movimwebsocket', () => {
|
||||
console.log('offline');
|
||||
MovimWebsocket.connection.onerror();
|
||||
});
|
||||
|
||||
MovimEvents.registerWindow('online', 'movimwebsocket', () => {
|
||||
MovimWebsocket.statusBar.classList.remove('hide');
|
||||
MovimWebsocket.statusBar.classList.add('connect');
|
||||
|
||||
MovimWebsocket.launchInitiated();
|
||||
MovimWebsocket.init();
|
||||
});
|
||||
|
||||
window.onbeforeunload = function () {
|
||||
if (MovimWebsocket.connection !== null) {
|
||||
MovimWebsocket.connection.onclose = function () { }; // disable onclose handler first
|
||||
MovimWebsocket.connection.close()
|
||||
}
|
||||
};
|
||||
|
||||
// If the Websocket was closed after some inactivity, we try to reconnect
|
||||
MovimEvents.registerWindow('focus', 'movimwebsocket', () => {
|
||||
if (MovimWebsocket.connection !== null
|
||||
&& MovimWebsocket.connection.readyState > 1) {
|
||||
|
||||
// Show the reconnect state
|
||||
MovimWebsocket.statusBar.classList.remove('hide');
|
||||
MovimWebsocket.statusBar.classList.add('connect');
|
||||
|
||||
MovimWebsocket.init();
|
||||
}
|
||||
});
|
||||
|
||||
MovimEvents.registerWindow('loaded', 'movimwebsocket', () => {
|
||||
MovimWebsocket.statusBar = document.getElementById('status_websocket');
|
||||
MovimWebsocket.launchInitiated();
|
||||
MovimWebsocket.init();
|
||||
});
|
||||
@@ -0,0 +1,288 @@
|
||||
/**
|
||||
* Encodes an RGBA image to a ThumbHash. RGB should not be premultiplied by A.
|
||||
*
|
||||
* @param w The width of the input image. Must be ≤100px.
|
||||
* @param h The height of the input image. Must be ≤100px.
|
||||
* @param rgba The pixels in the input image, row-by-row. Must have w*h*4 elements.
|
||||
* @returns The ThumbHash as a Uint8Array.
|
||||
*/
|
||||
function rgbaToThumbHash(w, h, rgba) {
|
||||
// Encoding an image larger than 100x100 is slow with no benefit
|
||||
if (w > 100 || h > 100) throw new Error(`${w}x${h} doesn't fit in 100x100`)
|
||||
let { PI, round, max, cos, abs } = Math
|
||||
|
||||
// Determine the average color
|
||||
let avg_r = 0, avg_g = 0, avg_b = 0, avg_a = 0
|
||||
for (let i = 0, j = 0; i < w * h; i++, j += 4) {
|
||||
let alpha = rgba[j + 3] / 255
|
||||
avg_r += alpha / 255 * rgba[j]
|
||||
avg_g += alpha / 255 * rgba[j + 1]
|
||||
avg_b += alpha / 255 * rgba[j + 2]
|
||||
avg_a += alpha
|
||||
}
|
||||
if (avg_a) {
|
||||
avg_r /= avg_a
|
||||
avg_g /= avg_a
|
||||
avg_b /= avg_a
|
||||
}
|
||||
|
||||
let hasAlpha = avg_a < w * h
|
||||
let l_limit = hasAlpha ? 5 : 7 // Use fewer luminance bits if there's alpha
|
||||
let lx = max(1, round(l_limit * w / max(w, h)))
|
||||
let ly = max(1, round(l_limit * h / max(w, h)))
|
||||
let l = [] // luminance
|
||||
let p = [] // yellow - blue
|
||||
let q = [] // red - green
|
||||
let a = [] // alpha
|
||||
|
||||
// Convert the image from RGBA to LPQA (composite atop the average color)
|
||||
for (let i = 0, j = 0; i < w * h; i++, j += 4) {
|
||||
let alpha = rgba[j + 3] / 255
|
||||
let r = avg_r * (1 - alpha) + alpha / 255 * rgba[j]
|
||||
let g = avg_g * (1 - alpha) + alpha / 255 * rgba[j + 1]
|
||||
let b = avg_b * (1 - alpha) + alpha / 255 * rgba[j + 2]
|
||||
l[i] = (r + g + b) / 3
|
||||
p[i] = (r + g) / 2 - b
|
||||
q[i] = r - g
|
||||
a[i] = alpha
|
||||
}
|
||||
|
||||
// Encode using the DCT into DC (constant) and normalized AC (varying) terms
|
||||
let encodeChannel = (channel, nx, ny) => {
|
||||
let dc = 0, ac = [], scale = 0, fx = []
|
||||
for (let cy = 0; cy < ny; cy++) {
|
||||
for (let cx = 0; cx * ny < nx * (ny - cy); cx++) {
|
||||
let f = 0
|
||||
for (let x = 0; x < w; x++)
|
||||
fx[x] = cos(PI / w * cx * (x + 0.5))
|
||||
for (let y = 0; y < h; y++)
|
||||
for (let x = 0, fy = cos(PI / h * cy * (y + 0.5)); x < w; x++)
|
||||
f += channel[x + y * w] * fx[x] * fy
|
||||
f /= w * h
|
||||
if (cx || cy) {
|
||||
ac.push(f)
|
||||
scale = max(scale, abs(f))
|
||||
} else {
|
||||
dc = f
|
||||
}
|
||||
}
|
||||
}
|
||||
if (scale)
|
||||
for (let i = 0; i < ac.length; i++)
|
||||
ac[i] = 0.5 + 0.5 / scale * ac[i]
|
||||
return [dc, ac, scale]
|
||||
}
|
||||
let [l_dc, l_ac, l_scale] = encodeChannel(l, max(3, lx), max(3, ly))
|
||||
let [p_dc, p_ac, p_scale] = encodeChannel(p, 3, 3)
|
||||
let [q_dc, q_ac, q_scale] = encodeChannel(q, 3, 3)
|
||||
let [a_dc, a_ac, a_scale] = hasAlpha ? encodeChannel(a, 5, 5) : []
|
||||
|
||||
// Write the constants
|
||||
let isLandscape = w > h
|
||||
let header24 = round(63 * l_dc) | (round(31.5 + 31.5 * p_dc) << 6) | (round(31.5 + 31.5 * q_dc) << 12) | (round(31 * l_scale) << 18) | (hasAlpha << 23)
|
||||
let header16 = (isLandscape ? ly : lx) | (round(63 * p_scale) << 3) | (round(63 * q_scale) << 9) | (isLandscape << 15)
|
||||
let hash = [header24 & 255, (header24 >> 8) & 255, header24 >> 16, header16 & 255, header16 >> 8]
|
||||
let ac_start = hasAlpha ? 6 : 5
|
||||
let ac_index = 0
|
||||
if (hasAlpha) hash.push(round(15 * a_dc) | (round(15 * a_scale) << 4))
|
||||
|
||||
// Write the varying factors
|
||||
for (let ac of hasAlpha ? [l_ac, p_ac, q_ac, a_ac] : [l_ac, p_ac, q_ac])
|
||||
for (let f of ac)
|
||||
hash[ac_start + (ac_index >> 1)] |= round(15 * f) << ((ac_index++ & 1) << 2)
|
||||
return new Uint8Array(hash)
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a ThumbHash to an RGBA image. RGB is not be premultiplied by A.
|
||||
*
|
||||
* @param hash The bytes of the ThumbHash.
|
||||
* @returns The width, height, and pixels of the rendered placeholder image.
|
||||
*/
|
||||
function thumbHashToRGBA(hash) {
|
||||
let { PI, min, max, cos, round } = Math
|
||||
|
||||
// Read the constants
|
||||
let header24 = hash[0] | (hash[1] << 8) | (hash[2] << 16)
|
||||
let header16 = hash[3] | (hash[4] << 8)
|
||||
let l_dc = (header24 & 63) / 63
|
||||
let p_dc = ((header24 >> 6) & 63) / 31.5 - 1
|
||||
let q_dc = ((header24 >> 12) & 63) / 31.5 - 1
|
||||
let l_scale = ((header24 >> 18) & 31) / 31
|
||||
let hasAlpha = header24 >> 23
|
||||
let p_scale = ((header16 >> 3) & 63) / 63
|
||||
let q_scale = ((header16 >> 9) & 63) / 63
|
||||
let isLandscape = header16 >> 15
|
||||
let lx = max(3, isLandscape ? hasAlpha ? 5 : 7 : header16 & 7)
|
||||
let ly = max(3, isLandscape ? header16 & 7 : hasAlpha ? 5 : 7)
|
||||
let a_dc = hasAlpha ? (hash[5] & 15) / 15 : 1
|
||||
let a_scale = (hash[5] >> 4) / 15
|
||||
|
||||
// Read the varying factors (boost saturation by 1.25x to compensate for quantization)
|
||||
let ac_start = hasAlpha ? 6 : 5
|
||||
let ac_index = 0
|
||||
let decodeChannel = (nx, ny, scale) => {
|
||||
let ac = []
|
||||
for (let cy = 0; cy < ny; cy++)
|
||||
for (let cx = cy ? 0 : 1; cx * ny < nx * (ny - cy); cx++)
|
||||
ac.push((((hash[ac_start + (ac_index >> 1)] >> ((ac_index++ & 1) << 2)) & 15) / 7.5 - 1) * scale)
|
||||
return ac
|
||||
}
|
||||
let l_ac = decodeChannel(lx, ly, l_scale)
|
||||
let p_ac = decodeChannel(3, 3, p_scale * 1.25)
|
||||
let q_ac = decodeChannel(3, 3, q_scale * 1.25)
|
||||
let a_ac = hasAlpha && decodeChannel(5, 5, a_scale)
|
||||
|
||||
// Decode using the DCT into RGB
|
||||
let ratio = thumbHashToApproximateAspectRatio(hash)
|
||||
let w = round(ratio > 1 ? 32 : 32 * ratio)
|
||||
let h = round(ratio > 1 ? 32 / ratio : 32)
|
||||
let rgba = new Uint8Array(w * h * 4), fx = [], fy = []
|
||||
for (let y = 0, i = 0; y < h; y++) {
|
||||
for (let x = 0; x < w; x++, i += 4) {
|
||||
let l = l_dc, p = p_dc, q = q_dc, a = a_dc
|
||||
|
||||
// Precompute the coefficients
|
||||
for (let cx = 0, n = max(lx, hasAlpha ? 5 : 3); cx < n; cx++)
|
||||
fx[cx] = cos(PI / w * (x + 0.5) * cx)
|
||||
for (let cy = 0, n = max(ly, hasAlpha ? 5 : 3); cy < n; cy++)
|
||||
fy[cy] = cos(PI / h * (y + 0.5) * cy)
|
||||
|
||||
// Decode L
|
||||
for (let cy = 0, j = 0; cy < ly; cy++)
|
||||
for (let cx = cy ? 0 : 1, fy2 = fy[cy] * 2; cx * ly < lx * (ly - cy); cx++, j++)
|
||||
l += l_ac[j] * fx[cx] * fy2
|
||||
|
||||
// Decode P and Q
|
||||
for (let cy = 0, j = 0; cy < 3; cy++) {
|
||||
for (let cx = cy ? 0 : 1, fy2 = fy[cy] * 2; cx < 3 - cy; cx++, j++) {
|
||||
let f = fx[cx] * fy2
|
||||
p += p_ac[j] * f
|
||||
q += q_ac[j] * f
|
||||
}
|
||||
}
|
||||
|
||||
// Decode A
|
||||
if (hasAlpha)
|
||||
for (let cy = 0, j = 0; cy < 5; cy++)
|
||||
for (let cx = cy ? 0 : 1, fy2 = fy[cy] * 2; cx < 5 - cy; cx++, j++)
|
||||
a += a_ac[j] * fx[cx] * fy2
|
||||
|
||||
// Convert to RGB
|
||||
let b = l - 2 / 3 * p
|
||||
let r = (3 * l - b + q) / 2
|
||||
let g = r - q
|
||||
rgba[i] = max(0, 255 * min(1, r))
|
||||
rgba[i + 1] = max(0, 255 * min(1, g))
|
||||
rgba[i + 2] = max(0, 255 * min(1, b))
|
||||
rgba[i + 3] = max(0, 255 * min(1, a))
|
||||
}
|
||||
}
|
||||
return { w, h, rgba }
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the average color from a ThumbHash. RGB is not be premultiplied by A.
|
||||
*
|
||||
* @param hash The bytes of the ThumbHash.
|
||||
* @returns The RGBA values for the average color. Each value ranges from 0 to 1.
|
||||
*/
|
||||
function thumbHashToAverageRGBA(hash) {
|
||||
let { min, max } = Math
|
||||
let header = hash[0] | (hash[1] << 8) | (hash[2] << 16)
|
||||
let l = (header & 63) / 63
|
||||
let p = ((header >> 6) & 63) / 31.5 - 1
|
||||
let q = ((header >> 12) & 63) / 31.5 - 1
|
||||
let hasAlpha = header >> 23
|
||||
let a = hasAlpha ? (hash[5] & 15) / 15 : 1
|
||||
let b = l - 2 / 3 * p
|
||||
let r = (3 * l - b + q) / 2
|
||||
let g = r - q
|
||||
return {
|
||||
r: max(0, min(1, r)),
|
||||
g: max(0, min(1, g)),
|
||||
b: max(0, min(1, b)),
|
||||
a
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts the approximate aspect ratio of the original image.
|
||||
*
|
||||
* @param hash The bytes of the ThumbHash.
|
||||
* @returns The approximate aspect ratio (i.e. width / height).
|
||||
*/
|
||||
function thumbHashToApproximateAspectRatio(hash) {
|
||||
let header = hash[3]
|
||||
let hasAlpha = hash[2] & 0x80
|
||||
let isLandscape = hash[4] & 0x80
|
||||
let lx = isLandscape ? hasAlpha ? 5 : 7 : header & 7
|
||||
let ly = isLandscape ? header & 7 : hasAlpha ? 5 : 7
|
||||
return lx / ly
|
||||
}
|
||||
|
||||
/**
|
||||
* Encodes an RGBA image to a PNG data URL. RGB should not be premultiplied by
|
||||
* A. This is optimized for speed and simplicity and does not optimize for size
|
||||
* at all. This doesn't do any compression (all values are stored uncompressed).
|
||||
*
|
||||
* @param w The width of the input image. Must be ≤100px.
|
||||
* @param h The height of the input image. Must be ≤100px.
|
||||
* @param rgba The pixels in the input image, row-by-row. Must have w*h*4 elements.
|
||||
* @returns A data URL containing a PNG for the input image.
|
||||
*/
|
||||
function rgbaToDataURL(w, h, rgba) {
|
||||
let row = w * 4 + 1
|
||||
let idat = 6 + h * (5 + row)
|
||||
let bytes = [
|
||||
137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82, 0, 0,
|
||||
w >> 8, w & 255, 0, 0, h >> 8, h & 255, 8, 6, 0, 0, 0, 0, 0, 0, 0,
|
||||
idat >>> 24, (idat >> 16) & 255, (idat >> 8) & 255, idat & 255,
|
||||
73, 68, 65, 84, 120, 1
|
||||
]
|
||||
let table = [
|
||||
0, 498536548, 997073096, 651767980, 1994146192, 1802195444, 1303535960,
|
||||
1342533948, -306674912, -267414716, -690576408, -882789492, -1687895376,
|
||||
-2032938284, -1609899400, -1111625188
|
||||
]
|
||||
let a = 1, b = 0
|
||||
for (let y = 0, i = 0, end = row - 1; y < h; y++, end += row - 1) {
|
||||
bytes.push(y + 1 < h ? 0 : 1, row & 255, row >> 8, ~row & 255, (row >> 8) ^ 255, 0)
|
||||
for (b = (b + a) % 65521; i < end; i++) {
|
||||
let u = rgba[i] & 255
|
||||
bytes.push(u)
|
||||
a = (a + u) % 65521
|
||||
b = (b + a) % 65521
|
||||
}
|
||||
}
|
||||
bytes.push(
|
||||
b >> 8, b & 255, a >> 8, a & 255, 0, 0, 0, 0,
|
||||
0, 0, 0, 0, 73, 69, 78, 68, 174, 66, 96, 130
|
||||
)
|
||||
for (let [start, end] of [[12, 29], [37, 41 + idat]]) {
|
||||
let c = ~0
|
||||
for (let i = start; i < end; i++) {
|
||||
c ^= bytes[i]
|
||||
c = (c >>> 4) ^ table[c & 15]
|
||||
c = (c >>> 4) ^ table[c & 15]
|
||||
}
|
||||
c = ~c
|
||||
bytes[end++] = c >>> 24
|
||||
bytes[end++] = (c >> 16) & 255
|
||||
bytes[end++] = (c >> 8) & 255
|
||||
bytes[end++] = c & 255
|
||||
}
|
||||
return 'data:image/png;base64,' + btoa(String.fromCharCode(...bytes))
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes a ThumbHash to a PNG data URL. This is a convenience function that
|
||||
* just calls "thumbHashToRGBA" followed by "rgbaToDataURL".
|
||||
*
|
||||
* @param hash The bytes of the ThumbHash.
|
||||
* @returns A data URL containing a PNG for the rendered ThumbHash.
|
||||
*/
|
||||
function thumbHashToDataURL(hash) {
|
||||
let image = thumbHashToRGBA(hash)
|
||||
return rgbaToDataURL(image.w, image.h, image.rgba)
|
||||
}
|
||||
Reference in New Issue
Block a user