sfu.js 29.9 KB
Newer Older
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Copyright (c) 2020 by Juliusz Chroboczek.

// This is not open source software.  Copy it, and I'll break into your
// house and tell your three year-old that Santa doesn't exist.

'use strict';

let myid;

let group;

let socket;

let up = {}, down = {};

let iceServers = [];

18 19
let permissions = {};

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
function toHex(array) {
    let a = new Uint8Array(array);
    function hex(x) {
        let h = x.toString(16);
        if(h.length < 2)
            h = '0' + h;
        return h;
    }
    return a.reduce((x, y) => x + hex(y), '');
}

function randomid() {
    let a = new Uint8Array(16);
    crypto.getRandomValues(a);
    return toHex(a);
}

function Connection(id, pc) {
    this.id = id;
39
    this.kind = null;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
40 41 42
    this.label = null;
    this.pc = pc;
    this.stream = null;
43
    this.labels = {};
44
    this.labelsByMid = {};
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
45
    this.iceCandidates = [];
46 47 48 49 50 51 52
    this.timers = [];
    this.audioStats = {};
    this.videoStats = {};
}

Connection.prototype.setInterval = function(f, t) {
    this.timers.push(setInterval(f, t));
Antonin Décimo's avatar
Antonin Décimo committed
53
};
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
54

55
Connection.prototype.close = function(sendit) {
56 57 58
    while(this.timers.length > 0)
        clearInterval(this.timers.pop());

59 60 61 62 63 64 65 66
    if(this.stream) {
        this.stream.getTracks().forEach(t => {
            try {
                t.stop();
            } catch(e) {
            }
        });
    }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
67
    this.pc.close();
68 69 70 71 72 73 74

    if(sendit) {
        send({
            type: 'close',
            id: this.id,
        });
    }
Antonin Décimo's avatar
Antonin Décimo committed
75
};
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100

function setUserPass(username, password) {
    window.sessionStorage.setItem(
        'userpass',
        JSON.stringify({username: username, password: password}),
    );
}

function getUserPass() {
    let userpass = window.sessionStorage.getItem('userpass');
    if(!userpass)
        return null;
    return JSON.parse(userpass);
}

function getUsername() {
    let userpass = getUserPass();
    if(!userpass)
        return null;
    return userpass.username;
}

function setConnected(connected) {
    let statspan = document.getElementById('statspan');
    let userform = document.getElementById('userform');
101
    let disconnectbutton = document.getElementById('disconnectbutton');
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
102
    if(connected) {
103
        clearError();
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
104 105 106
        statspan.textContent = 'Connected';
        statspan.classList.remove('disconnected');
        statspan.classList.add('connected');
107
        userform.classList.add('invisible');
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
108
        userform.classList.remove('userform');
109
        disconnectbutton.classList.remove('invisible');
110
        displayUsername();
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
111 112 113 114 115 116 117 118 119 120
    } else {
        let userpass = getUserPass();
        document.getElementById('username').value =
            userpass ? userpass.username : '';
        document.getElementById('password').value =
            userpass ? userpass.password : '';
        statspan.textContent = 'Disconnected';
        statspan.classList.remove('connected');
        statspan.classList.add('disconnected');
        userform.classList.add('userform');
121 122
        userform.classList.remove('invisible');
        disconnectbutton.classList.add('invisible');
123
        permissions={};
124
        clearUsername(false);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
125 126 127
    }
}

128
document.getElementById('presentbutton').onclick = function(e) {
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
129
    e.preventDefault();
130
    addLocalMedia();
Antonin Décimo's avatar
Antonin Décimo committed
131
};
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
132

133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
document.getElementById('unpresentbutton').onclick = function(e) {
    e.preventDefault();
    delUpMediaKind('local');
};

function changePresentation() {
    let found = false;
    for(let id in up) {
        if(up[id].kind === 'local')
            found = true;
    }
    delUpMediaKind('local');
    if(found)
        addLocalMedia();
}

function setVisibility(id, visible) {
    let elt = document.getElementById(id);
    if(visible)
        elt.classList.remove('invisible');
    else
        elt.classList.add('invisible');
}

function setButtonsVisibility() {
    let local = findUpMedia('local');
    let share = findUpMedia('screenshare')
    // don't allow multiple presentations
    setVisibility('presentbutton', permissions.present && !local);
    setVisibility('unpresentbutton', local);
    // allow multiple shared documents
    setVisibility('sharebutton', permissions.present);
    setVisibility('unsharebutton', share);

    setVisibility('mediaoptions', permissions.present);
}

170 171
document.getElementById('audioselect').onchange = function(e) {
    e.preventDefault();
172
    changePresentation();
Antonin Décimo's avatar
Antonin Décimo committed
173
};
174 175 176

document.getElementById('videoselect').onchange = function(e) {
    e.preventDefault();
177
    changePresentation();
Antonin Décimo's avatar
Antonin Décimo committed
178
};
179

180
document.getElementById('sharebutton').onclick = function(e) {
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
181
    e.preventDefault();
182
    addShareMedia();
Antonin Décimo's avatar
Antonin Décimo committed
183
};
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
184

185 186 187 188 189
document.getElementById('unsharebutton').onclick = function(e) {
    e.preventDefault();
    delUpMediaKind('screenshare');
}

190
document.getElementById('requestselect').onchange = function(e) {
191
    e.preventDefault();
192
    sendRequest(this.value);
Antonin Décimo's avatar
Antonin Décimo committed
193
};
194

195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
async function updateStats(conn, sender) {
    let stats;
    if(!sender.track)
        return;

    if(sender.track.kind === 'audio')
        stats = conn.audioStats;
    else if(sender.track.kind === 'video')
        stats = conn.videoStats;
    else
        return;

    let report;
    try {
        report = await sender.getStats();
    } catch(e) {
        delete(stats.rate);
        delete(stats.timestamp);
        delete(stats.bytesSent);
Antonin Décimo's avatar
Antonin Décimo committed
214
        return;
215 216 217 218 219 220 221 222
    }

    for(let r of report.values()) {
        if(r.type !== 'outbound-rtp')
            continue;

        if(stats.timestamp) {
            stats.rate =
223
                ((r.bytesSent - stats.bytesSent) * 1000 /
224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
                 (r.timestamp - stats.timestamp)) * 8;
        } else {
            delete(stats.rate);
        }
        stats.timestamp = r.timestamp;
        stats.bytesSent = r.bytesSent;
        return;
    }
}

function displayStats(id) {
    let conn = up[id];
    if(!conn.audioStats.rate && !conn.videoStats.rate) {
        setLabel(id);
        return;
    }

    let a = conn.audioStats.rate;
    let v = conn.videoStats.rate;

    let text = '';
    if(a)
        text = text + Math.round(a / 1000) + 'kbps';
    if(a && v)
        text = text + ' + ';
    if(v)
        text = text + Math.round(v / 1000) + 'kbps';
    if(text)
        setLabel(id, text);
    else
        setLabel(id);
}

257 258 259 260 261 262 263 264
function mapMediaOption(value) {
    console.assert(typeof(value) === 'string');
    switch(value) {
    case 'default':
        return true;
    case 'off':
        return false;
    default:
265
        return {deviceId: value};
266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321
    }
}

function addSelectOption(select, label, value) {
    if(!value)
        value = label;
    for(let i = 0; i < select.children.length; i++) {
        if(select.children[i].value === value) {
            return;
        }
    }

    let option = document.createElement('option');
    option.value = value;
    option.textContent = label;
    select.appendChild(option);
}

// media names might not be available before we call getDisplayMedia.  So
// we call this lazily.
let mediaChoicesDone = false;

async function setMediaChoices() {
    if(mediaChoicesDone)
        return;

    let devices = [];
    try {
        devices = await navigator.mediaDevices.enumerateDevices();
    } catch(e) {
        console.error(e);
        return;
    }

    let cn = 1, mn = 1;

    devices.forEach(d => {
        let label = d.label;
        if(d.kind === 'videoinput') {
            if(!label)
                label = `Camera ${cn}`;
            addSelectOption(document.getElementById('videoselect'),
                            label, d.deviceId);
            cn++;
        } else if(d.kind === 'audioinput') {
            if(!label)
                label = `Microphone ${mn}`;
            addSelectOption(document.getElementById('audioselect'),
                            label, d.deviceId);
            mn++;
        }
    });

    mediaChoicesDone = true;
}

322
async function addLocalMedia() {
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
323 324 325
    if(!getUserPass())
        return;

326 327 328 329 330 331 332 333 334 335 336 337 338
    let audio = mapMediaOption(document.getElementById('audioselect').value);
    let video = mapMediaOption(document.getElementById('videoselect').value);

    if(!audio && !video)
        return;

    let constraints = {audio: audio, video: video};
    let stream = null;
    try {
        stream = await navigator.mediaDevices.getUserMedia(constraints);
    } catch(e) {
        console.error(e);
        return;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
339
    }
340 341 342

    setMediaChoices();

343 344 345
    let id = await newUpStream();
    let c = up[id];
    c.kind = 'local';
346 347
    c.stream = stream;
    stream.getTracks().forEach(t => {
348
        c.labels[t.id] = t.kind
349 350 351 352 353 354
        let sender = c.pc.addTrack(t, stream);
        c.setInterval(() => {
            updateStats(c, sender);
        }, 2000);
    });
    c.setInterval(() => {
355
        displayStats(id);
356
    }, 2500);
357 358
    await setMedia(id);
    setButtonsVisibility()
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
359 360
}

361
async function addShareMedia(setup) {
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
362 363 364
    if(!getUserPass())
        return;

365 366 367 368 369
    let stream = null;
    try {
        stream = await navigator.mediaDevices.getDisplayMedia({});
    } catch(e) {
        console.error(e);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
370 371
        return;
    }
372 373 374 375 376 377 378 379 380 381 382

    let id = await newUpStream();
    let c = up[id];
    c.kind = 'screenshare';
    c.stream = stream;
    stream.getTracks().forEach(t => {
        let sender = c.pc.addTrack(t, stream);
        t.onended = e => {
            delUpMedia(id);
        };
        c.labels[t.id] = 'screenshare';
383
        c.setInterval(() => {
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
            updateStats(c, sender);
        }, 2000);
    });
    c.setInterval(() => {
        displayStats(id);
    }, 2500);
    await setMedia(id);
    setButtonsVisibility()
}

function delUpMedia(id) {
    let c = up[id];
    if(!c) {
        console.error("Deleting unknown up media");
        return;
    }
    c.close(true);
    delMedia(id);
    delete(up[id]);

    setButtonsVisibility()
}

function delUpMediaKind(kind) {
    for(let id in up) {
        let c = up[id];
        if(c.kind != kind)
            continue
        c.close(true);
        delMedia(id);
        delete(up[id]);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
415
    }
416 417 418 419 420 421 422 423 424 425

    setButtonsVisibility()
}

function findUpMedia(kind) {
    for(let id in up) {
        if(up[id].kind === kind)
            return true;
    }
    return false;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
}

function setMedia(id) {
    let mine = true;
    let c = up[id];
    if(!c) {
        c = down[id];
        mine = false;
    }
    if(!c)
        throw new Error('Unknown connection');

    let peersdiv = document.getElementById('peers');

    let div = document.getElementById('peer-' + id);
    if(!div) {
        div = document.createElement('div');
        div.id = 'peer-' + id;
        div.classList.add('peer');
        peersdiv.appendChild(div);
    }

    let media = document.getElementById('media-' + id);
    if(!media) {
        media = document.createElement('video');
        media.id = 'media-' + id;
        media.classList.add('media');
        media.autoplay = true;
        media.playsinline = true;
        media.controls = true;
        if(mine)
            media.muted = true;
        div.appendChild(media);
    }

    let label = document.getElementById('label-' + id);
    if(!label) {
        label = document.createElement('div');
        label.id = 'label-' + id;
        label.classList.add('label');
Antonin Décimo's avatar
Antonin Décimo committed
466
        div.appendChild(label);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
467 468 469 470
    }

    media.srcObject = c.stream;
    setLabel(id);
471 472

    resizePeers();
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
473 474 475 476 477 478 479 480 481
}

function delMedia(id) {
    let mediadiv = document.getElementById('peers');
    let peer = document.getElementById('peer-' + id);
    let media = document.getElementById('media-' + id);

    media.srcObject = null;
    mediadiv.removeChild(peer);
482 483

    resizePeers();
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
484 485
}

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
486
function setLabel(id, fallback) {
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
487 488 489 490
    let label = document.getElementById('label-' + id);
    if(!label)
        return;
    let l = down[id] ? down[id].label : null;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
491 492 493 494 495 496 497 498 499 500
    if(l) {
        label.textContent = l;
        label.classList.remove('label-fallback');
    } else if(fallback) {
        label.textContent = fallback;
        label.classList.add('label-fallback');
    } else {
        label.textContent = '';
        label.classList.remove('label-fallback');
    }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
501 502
}

503 504 505 506 507 508 509
function resizePeers() {
    let count = Object.keys(up).length + Object.keys(down).length;
    let columns = Math.ceil(Math.sqrt(count));
    document.getElementById('peers').style['grid-template-columns'] =
        `repeat(${columns}, 1fr)`;
}

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
function serverConnect() {
    if(socket) {
        socket.close(1000, 'Reconnecting');
        socket = null;
        setConnected(false);
    }

    try {
        socket = new WebSocket(
            `ws${location.protocol === 'https:' ? 's' : ''}://${location.host}/ws`,
        );
    } catch(e) {
        console.error(e);
        setConnected(false);
        return Promise.reject(e);
    }

    return new Promise((resolve, reject) => {
        socket.onerror = function(e) {
            console.error(e);
            reject(e.error ? e.error : e);
        };
        socket.onopen = function(e) {
            resetUsers();
534
            resetChat();
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
535 536 537 538 539 540 541 542 543
            setConnected(true);
            let up = getUserPass();
            send({
                type: 'handshake',
                id: myid,
                group: group,
                username: up.username,
                password: up.password,
            });
544
            sendRequest(document.getElementById('requestselect').value);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
545 546 547 548
            resolve();
        };
        socket.onclose = function(e) {
            setConnected(false);
549 550
            delUpMediaKind('local');
            delUpMediaKind('screenshare');
551 552 553 554 555 556
            for(let id in down) {
                let c = down[id];
                delete(down[id]);
                c.close(false);
                delMedia(id);
            }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
557 558 559 560 561 562
            reject(new Error('websocket close ' + e.code + ' ' + e.reason));
        };
        socket.onmessage = function(e) {
            let m = JSON.parse(e.data);
            switch(m.type) {
            case 'offer':
563
                gotOffer(m.id, m.labels, m.offer);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
564 565 566 567 568 569 570
                break;
            case 'answer':
                gotAnswer(m.id, m.answer);
                break;
            case 'close':
                gotClose(m.id);
                break;
571 572 573
            case 'abort':
                gotAbort(m.id);
                break;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
574 575 576 577 578 579
            case 'ice':
                gotICE(m.id, m.candidate);
                break;
            case 'label':
                gotLabel(m.id, m.value);
                break;
580 581 582
            case 'permissions':
                gotPermissions(m.permissions);
                break;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
583 584 585 586 587 588
            case 'user':
                gotUser(m.id, m.username, m.del);
                break;
            case 'chat':
                addToChatbox(m.id, m.username, m.value, m.me);
                break;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
589 590 591
            case 'clearchat':
                resetChat();
                break;
592 593 594 595 596 597 598 599
            case 'ping':
                send({
                    type: 'pong',
                });
                break;
            case 'pong':
                /* nothing */
                break;
600
            case 'error':
601
                displayError('The server said: ' + m.value);
602
                break;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
603 604 605 606 607 608 609 610
            default:
                console.warn('Unexpected server message', m.type);
                return;
            }
        };
    });
}

611 612 613 614
function sendRequest(value) {
    let request = [];
    switch(value) {
    case 'audio':
615
        request = {audio: true};
616 617
        break;
    case 'screenshare':
618
        request = {audio: true, screenshare: true};
619 620
        break;
    case 'everything':
621
        request = {audio: true, screenshare: true, video: true};
622 623 624 625 626 627
        break;
    default:
        console.error(`Uknown value ${value} in sendRequest`);
        break;
    }

628 629
    send({
        type: 'request',
630
        request: request,
631 632 633
    });
}

634
async function gotOffer(id, labels, offer) {
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
    let c = down[id];
    if(!c) {
        let pc = new RTCPeerConnection({
            iceServers: iceServers,
        });
        c = new Connection(id, pc);
        down[id] = c;

        c.pc.onicecandidate = function(e) {
            if(!e.candidate)
                return;
            send({type: 'ice',
                  id: id,
                  candidate: e.candidate,
                 });
Antonin Décimo's avatar
Antonin Décimo committed
650
        };
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
651 652

        c.pc.ontrack = function(e) {
653 654 655 656
            let label = e.transceiver && c.labelsByMid[e.transceiver.mid];
            if(label) {
                c.labels[e.track.id] = label;
            } else {
657
                console.warn("Couldn't find label for track");
658
            }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
659 660
            c.stream = e.streams[0];
            setMedia(id);
Antonin Décimo's avatar
Antonin Décimo committed
661
        };
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
662 663
    }

664
    c.labelsByMid = labels;
665

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
666 667 668 669
    await c.pc.setRemoteDescription(offer);
    await addIceCandidates(c);
    let answer = await c.pc.createAnswer();
    if(!answer)
Antonin Décimo's avatar
Antonin Décimo committed
670
        throw new Error("Didn't create answer");
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700
    await c.pc.setLocalDescription(answer);
    send({
        type: 'answer',
        id: id,
        answer: answer,
    });
}

function gotLabel(id, label) {
    let c = down[id];
    if(!c)
        throw new Error('Got label for unknown id');

    c.label = label;
    setLabel(id);
}

async function gotAnswer(id, answer) {
    let c = up[id];
    if(!c)
        throw new Error('unknown up stream');
    await c.pc.setRemoteDescription(answer);
    await addIceCandidates(c);
}

function gotClose(id) {
    let c = down[id];
    if(!c)
        throw new Error('unknown down stream');
    delete(down[id]);
701
    c.close(false);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
702 703 704
    delMedia(id);
}

705
function gotAbort(id) {
706
    delUpMedia(id);
707 708
}

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
709 710 711 712 713 714 715 716 717
async function gotICE(id, candidate) {
    let conn = up[id];
    if(!conn)
        conn = down[id];
    if(!conn)
        throw new Error('unknown stream');
    if(conn.pc.remoteDescription)
        await conn.pc.addIceCandidate(candidate).catch(console.warn);
    else
Antonin Décimo's avatar
Antonin Décimo committed
718
        conn.iceCandidates.push(candidate);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
719 720 721
}

async function addIceCandidates(conn) {
Antonin Décimo's avatar
Antonin Décimo committed
722
    let promises = [];
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
723 724 725 726 727 728 729 730 731 732
    conn.iceCandidates.forEach(c => {
        promises.push(conn.pc.addIceCandidate(c).catch(console.warn));
    });
    conn.iceCandidates = [];
    return await Promise.all(promises);
}

function send(m) {
    if(!m)
        throw(new Error('Sending null message'));
Antonin Décimo's avatar
Antonin Décimo committed
733
    return socket.send(JSON.stringify(m));
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754
}

let users = {};

function addUser(id, name) {
    if(!name)
        name = null;
    if(id in users)
        throw new Error('Duplicate user id');
    users[id] = name;

    let div = document.getElementById('users');
    let user = document.createElement('div');
    user.id = 'user-' + id;
    user.textContent = name ? name : '(anon)';
    div.appendChild(user);
}

function delUser(id, name) {
    if(!name)
        name = null;
Antonin Décimo's avatar
Antonin Décimo committed
755
    if(!(id in users))
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
        throw new Error('Unknown user id');
    if(users[id] !== name)
        throw new Error('Inconsistent user name');
    delete(users[id]);
    let div = document.getElementById('users');
    let user = document.getElementById('user-' + id);
    div.removeChild(user);
}

function resetUsers() {
    for(let id in users)
        delUser(id, users[id]);
}

function gotUser(id, name, del) {
    if(del)
        delUser(id, name);
    else
        addUser(id, name);
}

777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794
function displayUsername() {
    let userpass = getUserPass();
    let text = '';
    if(userpass && userpass.username)
        text = 'as ' + userpass.username;
    if(permissions.op && permissions.present)
        text = text + ' (op, presenter)';
    else if(permissions.op)
        text = text + ' (op)';
    else if(permissions.present)
        text = text + ' (presenter)';
    document.getElementById('userspan').textContent = text;
}

function clearUsername() {
    document.getElementById('userspan').textContent = '';
}

795 796
function gotPermissions(perm) {
    permissions = perm;
797
    displayUsername();
798
    setButtonsVisibility();
799 800
}

801
const urlRegexp = /https?:\/\/[-a-zA-Z0-9@:%/._\\+~#=?]+[-a-zA-Z0-9@:%/_\\+~#=]/g;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873

function formatLine(line) {
    let r = new RegExp(urlRegexp);
    let result = [];
    let pos = 0;
    while(true) {
        let m = r.exec(line);
        if(!m)
            break;
        result.push(document.createTextNode(line.slice(pos, m.index)));
        let a = document.createElement('a');
        a.href = m[0];
        a.textContent = m[0];
        a.target = '_blank';
        a.rel = 'noreferrer noopener';
        result.push(a);
        pos = m.index + m[0].length;
    }
    result.push(document.createTextNode(line.slice(pos)));
    return result;
}

function formatLines(lines) {
    let elts = [];
    if(lines.length > 0)
        elts = formatLine(lines[0]);
    for(let i = 1; i < lines.length; i++) {
        elts.push(document.createElement('br'));
        elts = elts.concat(formatLine(lines[i]));
    }
    let elt = document.createElement('p');
    elts.forEach(e => elt.appendChild(e));
    return elt;
}

let lastMessage = {};

function addToChatbox(peerId, nick, message, me){
    let container = document.createElement('div');
    container.classList.add('message');
    if(!me) {
        let p = formatLines(message.split('\n'));
        if (lastMessage.nick !== nick || lastMessage.peerId !== peerId) {
            let user = document.createElement('p');
            user.textContent = nick;
            user.classList.add('message-user');
            container.appendChild(user);
        }
        p.classList.add('message-content');
        container.appendChild(p);
        lastMessage.nick = nick;
        lastMessage.peerId = peerId;
    } else {
        let asterisk = document.createElement('span');
        asterisk.textContent = '*';
        asterisk.classList.add('message-me-asterisk');
        let user = document.createElement('span');
        user.textContent = nick;
        user.classList.add('message-me-user');
        let content = document.createElement('span');
        formatLine(message).forEach(elt => {
            content.appendChild(elt);
        });
        content.classList.add('message-me-content');
        container.appendChild(asterisk);
        container.appendChild(user);
        container.appendChild(content);
        container.classList.add('message-me');
        delete(lastMessage.nick);
        delete(lastMessage.peerId);
    }

874 875
    let box = document.getElementById('box');
    box.appendChild(container);
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
876 877 878 879 880 881 882
    if(box.scrollHeight > box.clientHeight) {
        box.scrollTop = box.scrollHeight - box.clientHeight;
    }

    return message;
}

883 884 885 886 887
function resetChat() {
    lastMessage = {};
    document.getElementById('box').textContent = '';
}

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
function handleInput() {
    let username = getUsername();
    let input = document.getElementById('input');
    let data = input.value;
    input.value = '';

    let message, me;

    if(data === '')
        return;

    if(data.charAt(0) === '/') {
        if(data.charAt(1) === '/') {
            message = data.substring(1);
            me = false;
        } else {
            let space, cmd, rest;
            space = data.indexOf(' ');
            if(space < 0) {
                cmd = data;
                rest = '';
            } else {
                cmd = data.slice(0, space);
                rest = data.slice(space + 1).trim();
            }

            switch(cmd) {
            case '/me':
                message = rest;
                me = true;
                break;
919 920 921
            case '/leave':
                socket.close();
                return;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
922 923 924 925 926 927 928 929 930
            case '/clear':
                if(!permissions.op) {
                    displayError("You're not an operator");
                    return;
                }
                send({
                    type: 'clearchat',
                });
                return;
931 932 933 934 935 936 937
            case '/lock':
            case '/unlock':
                if(!permissions.op) {
                    displayError("You're not an operator");
                    return;
                }
                send({
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
938 939 940 941 942 943 944 945 946 947 948
                    type: cmd.slice(1),
                });
                return;
            case '/record':
            case '/unrecord':
                if(!permissions.record) {
                    displayError("You're not allowed to record");
                    return;
                }
                send({
                    type: cmd.slice(1),
949 950
                });
                return;
951 952 953 954
            case '/op':
            case '/unop':
            case '/kick':
            case '/present':
955
            case '/unpresent': {
956 957
                if(!permissions.op) {
                    displayError("You're not an operator");
958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979
                    return;
                }
                let id;
                if(id in users) {
                    id = rest;
                } else {
                    for(let i in users) {
                        if(users[i] === rest) {
                            id = i;
                            break;
                        }
                    }
                }
                if(!id) {
                    displayError('Unknown user ' + rest);
                    return;
                }
                send({
                    type: cmd.slice(1),
                    id: id,
                });
                return;
980
            }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
981 982 983 984 985 986 987 988 989 990
            default:
                displayError('Uknown command ' + cmd);
                return;
            }
        }
    } else {
        message = data;
        me = false;
    }

991 992 993 994 995
    if(!username) {
        displayError("Sorry, you're anonymous, you cannot chat");
        return;
    }

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
996 997 998
    addToChatbox(myid, username, message, me);
    send({
        type: 'chat',
999
        id: myid,
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
        username: username,
        value: message,
        me: me,
    });
}

document.getElementById('inputform').onsubmit = function(e) {
    e.preventDefault();
    handleInput();
};

document.getElementById('input').onkeypress = function(e) {
    if(e.key === 'Enter' && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
        e.preventDefault();
        handleInput();
    }
Antonin Décimo's avatar
Antonin Décimo committed
1016
};
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060

function chatResizer(e) {
    e.preventDefault();
    let chat = document.getElementById('chat');
    let start_x = e.clientX;
    let start_width = parseFloat(
        document.defaultView.getComputedStyle(chat).width.replace('px', ''),
    );
    let inputbutton = document.getElementById('inputbutton');
    function start_drag(e) {
        let width = start_width + e.clientX - start_x;
        if(width < 40)
            inputbutton.style.display = 'none';
        else
            inputbutton.style.display = 'inline';
        chat.style.width = width + 'px';
    }
    function stop_drag(e) {
        document.documentElement.removeEventListener(
            'mousemove', start_drag, false,
        );
        document.documentElement.removeEventListener(
            'mouseup', stop_drag, false,
        );
    }

    document.documentElement.addEventListener(
        'mousemove', start_drag, false,
    );
    document.documentElement.addEventListener(
        'mouseup', stop_drag, false,
    );
}

document.getElementById('resizer').addEventListener('mousedown', chatResizer, false);

async function newUpStream() {
    let id = randomid();
    if(up[id])
        throw new Error('Eek!');
    let pc = new RTCPeerConnection({
        iceServers: iceServers,
    });
    if(!pc)
Antonin Décimo's avatar
Antonin Décimo committed
1061
        throw new Error("Couldn't create peer connection");
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
    up[id] = new Connection(id, pc);

    pc.onnegotiationneeded = e => negotiate(id);

    pc.onicecandidate = function(e) {
        if(!e.candidate)
            return;
        send({type: 'ice',
             id: id,
             candidate: e.candidate,
             });
Antonin Décimo's avatar
Antonin Décimo committed
1073
    };
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087

    pc.ontrack = console.error;

    return id;
}

async function negotiate(id) {
    let c = up[id];
    if(!c)
        throw new Error('unknown connection');
    let offer = await c.pc.createOffer({});
    if(!offer)
        throw(new Error("Didn't create offer"));
    await c.pc.setLocalDescription(offer);
1088 1089

    // mids are not known until this point
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104
    if(typeof(c.pc.getTransceivers) === 'function') {
        c.pc.getTransceivers().forEach(t => {
            if(t.sender && t.sender.track) {
                let label = c.labels[t.sender.track.id];
                if(label)
                    c.labelsByMid[t.mid] = label;
                else
                    console.warn("Couldn't find label for track");
            }
        });
    } else {
        console.warn('getTransceivers undefined');
        displayWarning('getTransceivers undefined, please upgrade your browser');
        // let the server deal with the mess
    }
1105

Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1106 1107 1108
    send({
        type: 'offer',
        id: id,
1109
        labels: c.labelsByMid,
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163
        offer: offer,
    });
}

let errorTimeout = null;

function setErrorTimeout(ms) {
    if(errorTimeout) {
        clearTimeout(errorTimeout);
        errorTimeout = null;
    }
    if(ms) {
        errorTimeout = setTimeout(clearError, ms);
    }
}

function displayError(message) {
    let errspan = document.getElementById('errspan');
    errspan.textContent = message;
    errspan.classList.remove('noerror');
    errspan.classList.add('error');
    setErrorTimeout(8000);
}

function displayWarning(message) {
    // don't overwrite real errors
    if(!errorTimeout)
        return displayError(message);
}

function clearError() {
    let errspan = document.getElementById('errspan');
    errspan.textContent = '';
    errspan.classList.remove('error');
    errspan.classList.add('noerror');
    setErrorTimeout(null);
}

async function getIceServers() {
    let r = await fetch('/ice-servers.json');
    if(!r.ok)
        throw new Error("Couldn't fetch ICE servers: " +
                        r.status + ' ' + r.statusText);
    let servers = await r.json();
    if(!(servers instanceof Array))
        throw new Error("couldn't parse ICE servers");
    iceServers = servers;
}

document.getElementById('userform').onsubmit = async function(e) {
    e.preventDefault();
    let username = document.getElementById('username').value.trim();
    let password = document.getElementById('password').value;
    setUserPass(username, password);
1164
    await serverConnect();
Antonin Décimo's avatar
Antonin Décimo committed
1165
};
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1166 1167 1168

document.getElementById('disconnectbutton').onclick = function(e) {
    socket.close();
Antonin Décimo's avatar
Antonin Décimo committed
1169
};
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1170 1171 1172

function start() {
    group = decodeURIComponent(location.pathname.replace(/^\/[a-z]*\//, ''));
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1173 1174 1175
    let title = group.charAt(0).toUpperCase() + group.slice(1);
    if(group !== '') {
        document.title = title;
Antonin Décimo's avatar
Antonin Décimo committed
1176
        document.getElementById('title').textContent = title;
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1177
    }
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1178 1179 1180 1181 1182 1183 1184 1185

    myid = randomid();

    getIceServers().catch(console.error).then(c => {
        document.getElementById('connectbutton').disabled = false;
    }).then(c => {
        let userpass = getUserPass();
        if(userpass)
1186
            return serverConnect();
Juliusz Chroboczek's avatar
Juliusz Chroboczek committed
1187 1188 1189 1190
    });
}

start();