summaryrefslogtreecommitdiff
path: root/client-web/source/download_stream.ts
blob: d2cf1c562871342d50988670aea496503e6d81d7 (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
80
81
/*
    This file is part of keks-meet (https://codeberg.org/metamuffin/keks-meet)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2023 metamuffin <metamuffin@disroot.org>
*/
/// <reference lib="dom" />
import { log } from "./logger.ts"
import { send_sw_message, SW_ENABLED } from "./sw/client.ts"

function FallbackStreamDownload(size: number, filename?: string, progress?: (position: number) => void) {
    log({ scope: "*", warn: true }, "downloading to memory because serviceworker is not available")
    let position = 0
    let 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()
        },
        abort() { buffer = new Uint8Array(); /* have fun gc */ },
        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, filename, cancel, progress }: {
    size: number,
    filename: string,
    cancel: () => void,
    progress: (position: number) => void
}) {
    if (!SW_ENABLED) return FallbackStreamDownload(size, filename, progress)
    let position = 0

    // the sw will handle this download
    const path = `/download/${encodeURIComponent(filename ?? "file")}`

    const { port1, port2 } = new MessageChannel()
    send_sw_message({ download: { path, size } }, [port2])

    const a = document.createElement("a")
    a.href = path
    a.download = filename ?? "file"
    a.target = "_blank"
    // TODO this delay is part of a race condition btw
    setTimeout(() => {
        a.click()
    }, 100)

    port1.onmessage = ev => {
        if (ev.data.abort) {
            cancel()
            port1.close()
        }
    }

    return {
        close() {
            port1.postMessage("end")
        },
        abort() {
            port1.postMessage("abort")
        },
        write(chunk: ArrayBuffer) {
            const arr = new Uint8Array(chunk);
            port1.postMessage(arr)
            position += arr.length
            if (progress) progress(position)
        }
    }
}