aboutsummaryrefslogtreecommitdiff
path: root/client-web/source/resource/track.ts
blob: b2f73ab5f17d58280a73bda56d262e7b6b303947 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
/// <reference lib="dom" />

import { ProvideInfo } from "../../../common/packets.d.ts";
import { ebutton } from "../helper.ts";
import { TrackHandle } from "../track_handle.ts";
import { LocalUser } from "../user/local.ts";
import { User } from "../user/mod.ts";
import { Resource } from "./mod.ts";

export class TrackResource extends Resource {
    private _track?: TrackHandle
    constructor(user: User, info: ProvideInfo, track?: TrackHandle) {
        super(user, info)
        this.track = track
    }

    get track() { return this._track }
    set track(value: TrackHandle | undefined) {
        const handle_end = () => {
            this.track = undefined
            if (this.user instanceof LocalUser) this.destroy()
        }
        this._track?.removeEventListener("ended", handle_end)
        this._track = value
        this._track?.addEventListener("ended", handle_end)
        this.update_el()
    }

    destroy() {
        this.track?.end()
        super.destroy()
    }

    // TODO --- all the following code could be more generic and prettier in the UI ---

    create_preview(): HTMLElement {
        return ebutton(`Enable ${this.info.kind}`, {
            onclick: (e) => {
                (e as HTMLButtonElement).disabled = true;
                this.request()
            }
        })
    }
    create_element() {
        if (!this.track) { return this.create_preview() }
        const el = document.createElement("div")
        el.append(ebutton(`Enable ${this.info.kind}`, {
            onclick: (e) => {
                (e as HTMLButtonElement).disabled = true;
                this.request_stop()
            }
        }))

        const is_video = this.track.kind == "video"
        const media_el = is_video ? document.createElement("video") : document.createElement("audio")
        const stream = new MediaStream([this.track.track])
        media_el.srcObject = stream
        media_el.classList.add("media")
        media_el.autoplay = true
        media_el.controls = true
        if (this.track.local) media_el.muted = true
        el.append(media_el)

        if (this.track.local) {
            const end_button = document.createElement("button")
            end_button.textContent = "End"
            end_button.addEventListener("click", () => {
                this.track?.end()
            })
            el.append(end_button)
        }
        this.el.append(el)
        this.track.addEventListener("ended", () => {
            media_el.srcObject = null // TODO
            el.remove()
        })
        return el
    }
}