-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhost.ts
98 lines (88 loc) · 2.27 KB
/
host.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
90
91
92
93
94
95
96
97
98
import { HOST } from './app'
import { html } from 'htm/preact'
import { useState, useEffect, useContext } from 'preact/hooks'
const Host = () => {
const [isSessionRunning, toggleSession] = useState(false)
const [err, setErr] = useState('')
const [id, setId] = useState('')
useEffect(() => {
chrome.storage.local.get(({ id, mode }) => {
setId(id)
if (mode === 'host' || mode === 'client') {
toggleSession(true)
}
})
}, [])
const finishHostSession = async (id: string) => {
chrome.storage.local.remove(['mode', 'id', 'host_last_send_link'])
try {
const res = await fetch(`${HOST}/api/v1/meeting`, {
method: 'DELETE',
body: JSON.stringify({ id }),
})
if (res.status === 204) {
} else {
setErr('Could not end session')
}
} catch (e) {
setErr(e.message)
}
}
const startHostSession = () => {
return fetch(`${HOST}/api/v1/meeting/create`, {
method: 'POST',
})
.then((res) => {
if (res.status === 200) {
return res.json()
} else {
return {
id: '',
ok: false,
}
}
})
.then(({ id }) => {
if (id) {
return {
id,
ok: true,
}
} else {
return { ok: false }
}
})
}
const handleButton = () => {
if (id && !isSessionRunning) {
chrome.storage.local.remove(['id', 'mode'])
location.reload()
}
if (!isSessionRunning && !id) {
startHostSession().then(({ id, ok }) => {
if (ok) {
toggleSession(true)
setId(id)
chrome.storage.local.set({ id })
chrome.storage.local.set({ mode: 'host' })
} else {
setErr('Error creating session')
chrome.storage.local.remove(['mode', 'id', 'host_last_send_link'])
}
})
} else if (isSessionRunning) {
toggleSession(false)
finishHostSession(id).then(() => location.reload())
}
}
return html`
${err === ''
? html`<h1>Host</h1>
<h2>ID: ${id}</h2>
<button onclick=${handleButton}>
${isSessionRunning ? 'Finish session' : 'Create session'}
</button>`
: err}
`
}
export default Host