about summary refs log tree commit diff
path: root/assets/src/network/transfer/request.ts
blob: 920cd9a7931f5317fabdd2879d38ef50ae9dc13e (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
import { on, send } from "../channel/connection";
import type { RequestIceCandidateMessage } from "../channel/messages/messages";
import {
    createTransfer,
    onIncomingIceCandidate,
    Transfer,
    TransferType,
    unregisterIceOnComplete,
} from "./transfer";

export async function answer(
    offer: RTCSessionDescriptionInit
): Promise<Transfer> {
    const transfer = createTransfer(TransferType.ANSWER, onChannel);

    const offerDescription = new RTCSessionDescription(offer);
    transfer.pc.setRemoteDescription(offerDescription);

    const answer = await transfer.pc.createAnswer();
    transfer.pc.setLocalDescription(answer);

    transfer.pc.onicecandidate = event => {
        const candidate = event.candidate;
        if (event.candidate !== null) {
            send("ice_candidate", { candidate });
        }
    };

    const unregisterIce = on(
        "ice_candidate",
        (message: RequestIceCandidateMessage) =>
            onIncomingIceCandidate(transfer, message)
    );

    unregisterIceOnComplete(transfer, unregisterIce);

    send("accept_share", {
        sdp: answer.sdp,
        type: answer.type,
    });

    return transfer;
}

function onChannel(channel: RTCDataChannel) {
    channel.onmessage = event => {
        console.log(event.data)
    }
}