UNPKG

@fishjam-cloud/react-client

Version:
67 lines (66 loc) 3.16 kB
import { useCallback } from "react"; import { MissingSandboxApiUrlError } from "../utils/errors"; export const useSandbox = (props) => { const sandboxApiUrl = props?.sandboxApiUrl; const getSandboxPeerToken = useCallback(async (roomName, peerName, roomType = "conference") => { if (!sandboxApiUrl) throw new MissingSandboxApiUrlError(); const url = new URL(sandboxApiUrl); url.searchParams.set("roomName", roomName); url.searchParams.set("peerName", peerName); url.searchParams.set("roomType", roomType); const res = await fetch(url); if (!res.ok) { const message = `Failed to retrieve peer token for peer '${peerName}' in ${roomType} room '${roomName}'.`; throw new Error(message); } const data = await res.json(); return data.peerToken; }, [sandboxApiUrl]); const getSandboxViewerToken = useCallback(async (roomName) => { if (!sandboxApiUrl) throw new MissingSandboxApiUrlError(); const url = new URL(`${sandboxApiUrl}/${roomName}/livestream-viewer-token`); const res = await fetch(url); if (!res.ok) { let message = `Failed to retrieve viewer token for '${roomName}' livestream room.`; if (res.status === 404) { message = `A livestream room of name '${roomName}' does not exist.`; } throw new Error(message); } const data = await res.json(); return data.token; }, [sandboxApiUrl]); const getSandboxLivestream = useCallback(async (roomName, isPublic = false) => { if (!sandboxApiUrl) throw new MissingSandboxApiUrlError(); const url = new URL(`${sandboxApiUrl}/livestream`); url.searchParams.set("roomName", roomName); url.searchParams.set("public", isPublic.toString()); const res = await fetch(url); if (!res.ok) throw new Error(`Failed to retrieve streamer token for '${roomName}' livestream room.`); const data = await res.json(); return data; }, [sandboxApiUrl]); const fetchMoqAccess = useCallback(async (streamName, type) => { if (!sandboxApiUrl) throw new MissingSandboxApiUrlError(); const urlEncodedStreamName = encodeURIComponent(streamName); const res = await fetch(`${sandboxApiUrl}/moq/${urlEncodedStreamName}/${type}`); if (!res.ok) throw new Error(`Failed to retrieve MoQ ${type} connection for stream '${streamName}'.`); const data = await res.json(); return { connectionUrl: data.connection_url, token: data.token }; }, [sandboxApiUrl]); const getSandboxMoqPublisherAccess = useCallback(async (streamName) => fetchMoqAccess(streamName, "publisher"), [fetchMoqAccess]); const getSandboxMoqSubscriberAccess = useCallback(async (streamName) => fetchMoqAccess(streamName, "subscriber"), [fetchMoqAccess]); return { getSandboxPeerToken, getSandboxViewerToken, getSandboxLivestream, getSandboxMoqPublisherAccess, getSandboxMoqSubscriberAccess, }; };