aboutsummaryrefslogtreecommitdiff
path: root/client-web/source/sw/download_stream.ts
blob: 2a8049dd70c16744a04044530185bf0e57e04e2c (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
import { SW } from "./init.ts"

// export function StreamDownload(size: number, filename?: string, progress?: (position: number) => void) {
//     let position = 0
//     const buffer = new Uint8Array(size)
//     return {
//         close() {
//             const a = document.createElement("a")
//             a.href = URL.createObjectURL(new Blob([buffer], { type: "text/plain" }))
//             a.download = filename ?? "file"
//             a.click()
//         },
//         write(chunk: Blob) {
//             const reader = new FileReader();
//             reader.onload = function (event) {
//                 const arr = new Uint8Array(event.target!.result as ArrayBuffer);
//                 for (let i = 0; i < arr.length; i++, position++) {
//                     buffer[position] = arr[i]
//                 }
//                 if (progress) progress(position)
//             };
//             reader.readAsArrayBuffer(chunk);
//         }
//     }
// }

export function StreamDownload(size: number, filename?: string, progress?: (position: number) => void) {
    let position = 0

    const path = `/download/${encodeURIComponent(filename ?? "file")}`

    const { port1, port2 } = new MessageChannel()
    SW!.postMessage({ path, size }, [port2])

    const a = document.createElement("a")
    a.href = path
    a.download = filename ?? "file"
    a.target = "_blank"
    a.click()

    return {
        close() {
            port1.postMessage("end")
        },
        write(chunk: Blob) {
            const reader = new FileReader();
            reader.onload = function (event) {
                const arr = new Uint8Array(event.target!.result as ArrayBuffer);
                port1.postMessage(arr)
                position += arr.length
                if (progress) progress(position)
            };
            reader.readAsArrayBuffer(chunk);
        }
    }
}