element-call/src/App.jsx

538 lines
13 KiB
React
Raw Normal View History

2021-07-16 21:38:44 +00:00
/*
Copyright 2021 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2021-07-19 19:55:30 +00:00
import React, { useCallback, useEffect, useRef, useState } from "react";
2021-07-16 21:22:03 +00:00
import "./App.css";
2021-07-19 19:55:30 +00:00
import {
BrowserRouter as Router,
Switch,
Route,
useHistory,
useParams,
Link,
Redirect,
} from "react-router-dom";
2021-07-22 06:28:01 +00:00
import { ConferenceCall } from "./ConferenceCall";
2021-07-16 21:22:03 +00:00
export default function App() {
const { protocol, host } = window.location;
// Assume homeserver is hosted on same domain (proxied in development by vite)
const homeserverUrl = `${protocol}//${host}`;
const { loading, authenticated, error, client, login, register } =
useClient(homeserverUrl);
return (
2021-07-19 19:55:30 +00:00
<Router>
2021-07-16 21:22:03 +00:00
<div className="App">
{error && <p>{error.message}</p>}
{loading ? (
<p>Loading...</p>
) : (
2021-07-19 19:55:30 +00:00
<Switch>
<Route exact path="/">
{authenticated ? (
<JoinOrCreateRoom client={client} />
) : (
<>
<Register onRegister={register} />
<Login onLogin={login} />
</>
)}
</Route>
<Route path="/room/:roomId">
{!authenticated ? <Redirect to="/" /> : <Room client={client} />}
</Route>
</Switch>
2021-07-16 21:22:03 +00:00
)}
</div>
2021-07-19 19:55:30 +00:00
</Router>
2021-07-16 21:22:03 +00:00
);
}
2021-07-19 19:55:30 +00:00
function waitForSync(client) {
return new Promise((resolve, reject) => {
const onSync = (state) => {
if (state === "PREPARED") {
resolve();
client.removeListener("sync", onSync);
}
};
client.on("sync", onSync);
});
}
2021-07-16 21:22:03 +00:00
function useClient(homeserverUrl) {
2021-07-19 19:55:30 +00:00
const [{ loading, authenticated, client, error }, setState] = useState({
loading: true,
authenticated: false,
client: undefined,
error: undefined,
});
2021-07-16 21:22:03 +00:00
useEffect(() => {
async function restoreClient() {
try {
const authStore = localStorage.getItem("matrix-auth-store");
if (authStore) {
const { user_id, device_id, access_token } = JSON.parse(authStore);
2021-07-26 18:44:25 +00:00
const client = matrixcs.createClient({
2021-07-16 21:22:03 +00:00
baseUrl: homeserverUrl,
accessToken: access_token,
userId: user_id,
deviceId: device_id,
});
await client.startClient();
2021-07-19 19:55:30 +00:00
await waitForSync(client);
setState({
client,
loading: false,
authenticated: true,
error: undefined,
});
} else {
setState({
client: undefined,
loading: false,
authenticated: false,
error: undefined,
});
2021-07-16 21:22:03 +00:00
}
} catch (err) {
console.error(err);
localStorage.removeItem("matrix-auth-store");
2021-07-19 19:55:30 +00:00
setState({
client: undefined,
loading: false,
authenticated: false,
error: err,
});
2021-07-16 21:22:03 +00:00
}
}
restoreClient();
}, []);
const login = useCallback(async (username, password) => {
try {
2021-07-19 19:55:30 +00:00
setState((prevState) => ({
...prevState,
authenticated: false,
error: undefined,
}));
2021-07-16 21:22:03 +00:00
2021-07-26 18:44:25 +00:00
const registrationClient = matrixcs.createClient(homeserverUrl);
2021-07-16 21:22:03 +00:00
const { user_id, device_id, access_token } =
await registrationClient.loginWithPassword(username, password);
2021-07-26 18:44:25 +00:00
const client = matrixcs.createClient({
2021-07-16 21:22:03 +00:00
baseUrl: homeserverUrl,
accessToken: access_token,
userId: user_id,
deviceId: device_id,
});
await client.startClient();
localStorage.setItem(
"matrix-auth-store",
JSON.stringify({ user_id, device_id, access_token })
);
2021-07-19 19:55:30 +00:00
setState({
client,
loading: false,
authenticated: true,
error: undefined,
});
2021-07-16 21:22:03 +00:00
} catch (err) {
console.error(err);
localStorage.removeItem("matrix-auth-store");
2021-07-19 19:55:30 +00:00
setState({
client: undefined,
loading: false,
authenticated: false,
error: err,
});
2021-07-16 21:22:03 +00:00
}
}, []);
2021-07-19 19:55:30 +00:00
const register = useCallback(async (username, password) => {
try {
setState((prevState) => ({
...prevState,
authenticated: false,
error: undefined,
}));
2021-07-16 21:22:03 +00:00
2021-07-26 18:44:25 +00:00
const registrationClient = matrixcs.createClient(homeserverUrl);
2021-07-16 21:22:03 +00:00
2021-07-19 19:55:30 +00:00
const { user_id, device_id, access_token } =
await registrationClient.register(username, password, null, {
type: "m.login.dummy",
2021-07-16 21:22:03 +00:00
});
2021-07-26 18:44:25 +00:00
const client = matrixcs.createClient({
2021-07-19 19:55:30 +00:00
baseUrl: homeserverUrl,
accessToken: access_token,
userId: user_id,
deviceId: device_id,
});
2021-07-16 21:22:03 +00:00
2021-07-19 19:55:30 +00:00
await client.startClient();
2021-07-16 21:22:03 +00:00
2021-07-19 19:55:30 +00:00
localStorage.setItem(
"matrix-auth-store",
JSON.stringify({ user_id, device_id, access_token })
);
setState({
client,
loading: false,
authenticated: true,
error: undefined,
});
} catch (err) {
localStorage.removeItem("matrix-auth-store");
setState({
client: undefined,
loading: false,
authenticated: false,
error: err,
});
}
}, []);
return { loading, authenticated, client, error, login, register };
2021-07-16 21:22:03 +00:00
}
function Register({ onRegister }) {
const usernameRef = useRef();
const passwordRef = useRef();
const onSubmit = useCallback((e) => {
e.preventDefault();
onRegister(usernameRef.current.value, passwordRef.current.value);
});
return (
<form onSubmit={onSubmit}>
<input type="text" ref={usernameRef} placeholder="Username"></input>
<input type="password" ref={passwordRef} placeholder="Password"></input>
<button type="submit">Register</button>
</form>
);
}
function Login({ onLogin }) {
const usernameRef = useRef();
const passwordRef = useRef();
const onSubmit = useCallback((e) => {
e.preventDefault();
onLogin(usernameRef.current.value, passwordRef.current.value);
});
return (
<form onSubmit={onSubmit}>
<input type="text" ref={usernameRef} placeholder="Username"></input>
<input type="password" ref={passwordRef} placeholder="Password"></input>
<button type="submit">Login</button>
</form>
);
}
2021-07-19 19:55:30 +00:00
function JoinOrCreateRoom({ client }) {
const history = useHistory();
2021-07-16 21:22:03 +00:00
const roomNameRef = useRef();
const roomIdRef = useRef();
const [createRoomError, setCreateRoomError] = useState();
const [joinRoomError, setJoinRoomError] = useState();
2021-07-19 19:55:30 +00:00
const [rooms, setRooms] = useState([]);
useEffect(() => {
function updateRooms() {
setRooms(client.getRooms());
}
updateRooms();
client.on("Room", updateRooms);
return () => {
client.removeListener("Room", updateRooms);
};
}, []);
2021-07-16 21:22:03 +00:00
const onCreateRoom = useCallback(
(e) => {
e.preventDefault();
setCreateRoomError(undefined);
client
.createRoom({
visibility: "private",
2021-07-19 19:55:30 +00:00
preset: "public_chat",
2021-07-16 21:22:03 +00:00
name: roomNameRef.current.value,
})
.then(({ room_id }) => {
2021-07-26 19:20:11 +00:00
history.push(`/room/${room_id}`);
2021-07-16 21:22:03 +00:00
})
.catch(setCreateRoomError);
},
[client]
);
const onJoinRoom = useCallback(
(e) => {
e.preventDefault();
setJoinRoomError(undefined);
client
.joinRoom(roomIdRef.current.value)
.then(({ roomId }) => {
2021-07-26 19:20:11 +00:00
history.push(`/room/${roomId}`);
2021-07-16 21:22:03 +00:00
})
.catch(setJoinRoomError);
},
[client]
);
return (
<div>
<form onSubmit={onCreateRoom}>
2021-07-19 19:55:30 +00:00
<h3>Create New Room</h3>
2021-07-16 21:22:03 +00:00
<input
id="roomName"
name="roomName"
type="text"
required
autoComplete="off"
placeholder="Room Name"
ref={roomNameRef}
></input>
{createRoomError && <p>{createRoomError.message}</p>}
<button type="submit">Create Room</button>
</form>
<form onSubmit={onJoinRoom}>
2021-07-19 19:55:30 +00:00
<h3>Join Existing Room</h3>
2021-07-16 21:22:03 +00:00
<input
id="roomId"
name="roomId"
type="text"
required
autoComplete="off"
placeholder="Room ID"
ref={roomIdRef}
></input>
{joinRoomError && <p>{joinRoomError.message}</p>}
<button type="submit">Join Room</button>
</form>
2021-07-19 19:55:30 +00:00
<h3>Rooms:</h3>
<ul>
{rooms.map((room) => (
<li key={room.roomId}>
<Link to={`/room/${room.roomId}`}>{room.name}</Link>
</li>
))}
</ul>
2021-07-16 21:22:03 +00:00
</div>
);
}
2021-07-19 19:55:30 +00:00
function useVideoRoom(client, roomId, timeout = 5000) {
const [
{ loading, joined, room, conferenceCall, participants, error },
setState,
] = useState({
2021-07-19 19:55:30 +00:00
loading: true,
2021-07-22 06:28:01 +00:00
joined: false,
2021-07-19 19:55:30 +00:00
room: undefined,
2021-07-22 06:28:01 +00:00
participants: [],
2021-07-19 19:55:30 +00:00
error: undefined,
conferenceCall: null,
2021-07-19 19:55:30 +00:00
});
2021-07-16 21:22:03 +00:00
useEffect(() => {
const conferenceCall = new ConferenceCall(client, roomId);
2021-07-22 06:28:01 +00:00
setState((prevState) => ({
...prevState,
conferenceCall,
2021-07-22 06:28:01 +00:00
loading: true,
room: undefined,
error: undefined,
}));
2021-07-19 19:55:30 +00:00
2021-07-22 06:28:01 +00:00
client.joinRoom(roomId).catch((err) => {
setState((prevState) => ({ ...prevState, loading: false, error: err }));
});
2021-07-16 21:22:03 +00:00
let initialRoom = client.getRoom(roomId);
if (initialRoom) {
2021-07-22 06:28:01 +00:00
setState((prevState) => ({
...prevState,
loading: false,
room: initialRoom,
error: undefined,
}));
2021-07-16 21:22:03 +00:00
return;
}
let timeoutId;
function roomCallback(room) {
if (room && room.roomId === roomId) {
clearTimeout(timeoutId);
client.removeListener("Room", roomCallback);
2021-07-22 06:28:01 +00:00
setState((prevState) => ({
...prevState,
loading: false,
room,
error: undefined,
}));
2021-07-16 21:22:03 +00:00
}
}
client.on("Room", roomCallback);
timeoutId = setTimeout(() => {
2021-07-22 06:28:01 +00:00
setState((prevState) => ({
...prevState,
2021-07-19 19:55:30 +00:00
loading: false,
room: undefined,
error: new Error("Room could not be found."),
2021-07-22 06:28:01 +00:00
}));
2021-07-16 21:22:03 +00:00
client.removeListener("Room", roomCallback);
}, timeout);
return () => {
client.removeListener("Room", roomCallback);
clearTimeout(timeoutId);
};
}, [roomId]);
2021-07-19 19:55:30 +00:00
const joinCall = useCallback(() => {
2021-07-22 06:28:01 +00:00
const onParticipantsChanged = () => {
setState((prevState) => ({
...prevState,
participants: conferenceCall.participants,
}));
};
conferenceCall.on("participants_changed", onParticipantsChanged);
2021-07-16 21:22:03 +00:00
2021-07-22 06:28:01 +00:00
conferenceCall.join();
setState((prevState) => ({
...prevState,
joined: true,
}));
2021-07-22 06:28:01 +00:00
return () => {
conferenceCall.removeListener(
"participants_changed",
onParticipantsChanged
);
setState((prevState) => ({
...prevState,
joined: false,
participants: [],
}));
};
}, [client, conferenceCall, roomId]);
2021-07-22 06:28:01 +00:00
return { loading, joined, room, participants, error, joinCall };
2021-07-19 19:55:30 +00:00
}
2021-07-16 21:22:03 +00:00
2021-07-19 19:55:30 +00:00
function Room({ client }) {
const { roomId } = useParams();
2021-07-22 06:28:01 +00:00
const { loading, joined, room, participants, error, joinCall } = useVideoRoom(
client,
roomId
);
2021-07-16 21:22:03 +00:00
return (
<div>
2021-07-23 23:32:30 +00:00
<p>User ID:{client.getUserId()}</p>
<p>Room ID:{roomId}</p>
2021-07-19 19:55:30 +00:00
{loading && <p>Loading room...</p>}
2021-07-16 21:22:03 +00:00
{error && <p>{error.message}</p>}
2021-07-19 19:55:30 +00:00
{!loading && room && (
<>
<h3>Members:</h3>
<ul>
{room.getMembers().map((member) => (
<li key={member.userId}>{member.name}</li>
))}
</ul>
2021-07-22 06:28:01 +00:00
{joined ? (
participants.map((participant) => (
<Participant key={participant.userId} participant={participant} />
))
) : (
<button onClick={joinCall}>Join Call</button>
)}
2021-07-19 19:55:30 +00:00
</>
)}
2021-07-16 21:22:03 +00:00
</div>
);
}
2021-07-22 06:28:01 +00:00
function Participant({ participant }) {
const videoRef = useRef();
useEffect(() => {
if (participant.feed) {
if (participant.muted) {
videoRef.current.muted = true;
}
videoRef.current.srcObject = participant.feed.stream;
videoRef.current.play();
}
}, [participant.feed]);
2021-07-22 23:41:57 +00:00
return (
<li>
<h3>
User ID:{participant.userId} {participant.local && "(Local)"}
</h3>
{!participant.local && (
<>
<h3>Calls:</h3>
<ul>
{participant.calls.map((call) => (
<li key={call.callId}>
<p>Call ID: {call.callId}</p>
<p>Direction: {call.direction}</p>
<p>State: {call.state}</p>
<p>Hangup Reason: {call.hangupReason}</p>
</li>
))}
</ul>
</>
)}
2021-07-22 23:41:57 +00:00
<video ref={videoRef}></video>
</li>
2021-07-22 23:41:57 +00:00
);
2021-07-22 06:28:01 +00:00
}