-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsw.js
85 lines (77 loc) · 2.59 KB
/
sw.js
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
self.addEventListener('install', e => {
self.skipWaiting()
})
self.addEventListener('activate', evt => {
return self.clients.claim()
})
self.addEventListener('fetch', evt => {
const { request } = evt
const { url, method, headers } = request
if (!url.includes(self.registration.scope + 'webtorrent/')) return null
console.log("url", url)
// keep the worker alive
if (url == `${self.registration.scope}webtorrent/ping`) {
evt.respondWith(new Response("pong", { status: 200 }))
return
}
function getConsumer(clients) {
return new Promise(resolve => {
// Use race condition for whoever controls the response stream
for (const client of clients) {
const mc = new MessageChannel()
const { port1, port2 } = mc
port1.onmessage = evt => {
resolve([evt.data, mc])
}
client.postMessage({
url,
method,
headers: [...headers],
scope: self.registration.scope
}, [port2])
}
})
}
evt.respondWith(
clients.matchAll({ type: 'window', includeUncontrolled: true })
.then(getConsumer)
.then(([data, mc]) => {
let tm = null
const body = data.body === 'stream'
? new ReadableStream({
pull(controller) {
return new Promise(resolve => {
mc.port1.onmessage = evt => {
if (evt.data) {
controller.enqueue(evt.data) // evt.data is Uint8Array
} else {
clearTimeout(tm)
controller.close() // evt.data is null, means the stream ended
mc.port1.onmessage = null
}
resolve()
}
// 'media player' does NOT signal a close on the stream and we cannot close it because it's locked to the reader,
// so we just empty it after 5s of inactivity,
// the browser will request another port anyways
clearTimeout(tm)
tm = setTimeout(() => {
controller.close()
mc.port1.postMessage(false) // send timeout
mc.port1.onmessage = null
resolve()
}, 5000)
mc.port1.postMessage(true) // send a pull request
})
},
cancel() {
// This event is never executed
mc.port1.postMessage(false) // send a cancel request
}
})
: data.body
return new Response(body, data)
})
.catch(console.error)
)
})