2022-02-23 23:36:38 +00:00
|
|
|
import { useState, useEffect, useCallback } from "react";
|
2022-01-06 19:13:42 +00:00
|
|
|
|
2022-01-06 00:51:24 +00:00
|
|
|
async function fetchGroupCall(
|
|
|
|
client,
|
|
|
|
roomIdOrAlias,
|
|
|
|
viaServers = undefined,
|
|
|
|
timeout = 5000
|
|
|
|
) {
|
|
|
|
const { roomId } = await client.joinRoom(roomIdOrAlias, { viaServers });
|
|
|
|
|
|
|
|
return new Promise((resolve, reject) => {
|
|
|
|
let timeoutId;
|
|
|
|
|
|
|
|
function onGroupCallIncoming(groupCall) {
|
|
|
|
if (groupCall && groupCall.room.roomId === roomId) {
|
|
|
|
clearTimeout(timeoutId);
|
|
|
|
client.removeListener("GroupCall.incoming", onGroupCallIncoming);
|
|
|
|
resolve(groupCall);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const groupCall = client.getGroupCallForRoom(roomId);
|
|
|
|
|
|
|
|
if (groupCall) {
|
|
|
|
resolve(groupCall);
|
|
|
|
}
|
|
|
|
|
|
|
|
client.on("GroupCall.incoming", onGroupCallIncoming);
|
|
|
|
|
|
|
|
if (timeout) {
|
|
|
|
timeoutId = setTimeout(() => {
|
|
|
|
client.removeListener("GroupCall.incoming", onGroupCallIncoming);
|
|
|
|
reject(new Error("Fetching group call timed out."));
|
|
|
|
}, timeout);
|
|
|
|
}
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
export function useLoadGroupCall(client, roomId, viaServers) {
|
|
|
|
const [state, setState] = useState({
|
|
|
|
loading: true,
|
|
|
|
error: undefined,
|
|
|
|
groupCall: undefined,
|
2022-02-23 23:36:38 +00:00
|
|
|
reloadId: 0,
|
2022-01-06 00:51:24 +00:00
|
|
|
});
|
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
setState({ loading: true });
|
|
|
|
fetchGroupCall(client, roomId, viaServers, 30000)
|
2022-02-23 23:36:38 +00:00
|
|
|
.then((groupCall) =>
|
|
|
|
setState((prevState) => ({ ...prevState, loading: false, groupCall }))
|
|
|
|
)
|
|
|
|
.catch((error) =>
|
|
|
|
setState((prevState) => ({ ...prevState, loading: false, error }))
|
|
|
|
);
|
|
|
|
}, [client, roomId, state.reloadId]);
|
|
|
|
|
|
|
|
const reload = useCallback(() => {
|
|
|
|
setState((prevState) => ({ ...prevState, reloadId: prevState.reloadId++ }));
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
return { ...state, reload };
|
2022-01-06 00:51:24 +00:00
|
|
|
}
|