-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathwebcast.ts
89 lines (74 loc) · 1.69 KB
/
webcast.ts
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
80
81
82
83
84
85
86
87
88
89
export const version = "1.0.1"
export class Socket {
socket: WebSocket
constructor({
mediaRecorder,
url: rawUrl,
info,
onError,
onOpen,
}: {
mediaRecorder: MediaRecorder
url: string
info: Record<string, unknown>
onError?: (_: Event) => void
onOpen?: (_: Event) => void
}) {
const parser = document.createElement("a")
parser.href = rawUrl
const user = parser.username
const password = parser.password
parser.username = parser.password = ""
const url = parser.href
this.socket = new WebSocket(url, "webcast")
if (onError) this.socket.onerror = onError
const hello = {
mime: mediaRecorder.mimeType,
...(user ? { user } : {}),
...(password ? { password } : {}),
...info,
}
this.socket.onopen = function onopen(event: Event) {
if (onOpen) onOpen(event)
this.send(
JSON.stringify({
type: "hello",
data: hello,
})
)
}
mediaRecorder.ondataavailable = async (e: BlobEvent) => {
const data = await e.data.arrayBuffer()
if (this.isConnected()) {
this.socket.send(data)
}
}
mediaRecorder.onstop = (e: Event) => {
if (this.isConnected()) {
this.socket.close()
}
}
}
isConnected() {
return this.socket.readyState === WebSocket.OPEN
}
sendMetadata(data: Record<string, unknown>) {
this.socket.send(
JSON.stringify({
type: "metadata",
data,
})
)
}
}
declare global {
interface Window {
Webcast: { Socket: typeof Socket; version: string }
}
}
if (typeof window !== "undefined") {
window.Webcast = {
version: "1.0.0",
Socket,
}
}