about summary refs log tree commit diff
path: root/assets/src/network/transfer/transfer.ts
blob: 434c4fc205b580748f80e396945ef4a1df1a4ab0 (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
import { Writable, writable } from "svelte/store";
import { toast, ToastType } from "../../state/toast";

export enum TransferState {
    CONNECTING,
    TRANSFERRING,
    DONE,
    FAILED,
}

export type Transfer = {
    pc: RTCPeerConnection;
    channel: RTCDataChannel;
    state: Writable<TransferState>;
};

const servers = {
    iceServers: [
        {
            urls: [
                "stun:stun1.l.google.com:19302",
                "stun:stun2.l.google.com:19302",
            ],
        },
    ],
    iceCandidatePoolSize: 10,
};

export function createTransfer(
    onChannel: (channel: RTCDataChannel, completeTransfer: () => void) => void
): Transfer {
    const pc = new RTCPeerConnection(servers);
    const channel = pc.createDataChannel("channel", {
        negotiated: true,
        id: 0,
    });

    const state = writable(TransferState.CONNECTING);

    const transfer = {
        pc,
        channel,
        state,
    };

    channel.onopen = () => {
        state.set(TransferState.TRANSFERRING);
        onChannel(channel, () => onTransferComplete(transfer));
    };

    pc.addEventListener("iceconnectionstatechange", (e: any) => {
        if (pc.iceConnectionState === "failed") {
            toast({
                type: ToastType.ERROR,
                title: "An error occurred!",
                // FIXME: Implement said fix!
                message: "ICE negotiation failed. A fix is in progress.",
            });
            transfer.state.set(TransferState.FAILED);
        }
    });

    return transfer;
}

export function addRemoteIceCandidate(
    transfer: Transfer,
    candidate: RTCIceCandidateInit
) {
    transfer.pc.addIceCandidate(candidate);
}

function onTransferComplete(transfer: Transfer) {
    transfer.state.set(TransferState.DONE);
    transfer.pc.close();
}