File size: 7,917 Bytes
2485dd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import Stack from '@mui/material/Stack';
import TextField from '@mui/material/TextField';
import {isValidRoomID, isValidPartialRoomID} from './generateNewRoomID';
import {useCallback, useEffect, useState} from 'react';
import Button from '@mui/material/Button';
import {useSocket} from './useSocket';
import FormGroup from '@mui/material/FormGroup';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import {RoomState} from './types/RoomState';
import setURLParam from './setURLParam';
import {getURLParams} from './URLParams';
import {
  JoinRoomConfig,
  Roles,
  ServerState,
  StreamingStatus,
} from './types/StreamingTypes';
import Alert from '@mui/material/Alert';

function capitalize(str: string): string {
  return str.charAt(0).toUpperCase() + str.slice(1);
}

type Props = {
  roomState: RoomState | null;
  serverState: ServerState | null;
  onJoinRoomOrUpdateRoles?: () => void;
  streamingStatus: StreamingStatus;
};

export default function RoomConfig({
  roomState,
  serverState,
  onJoinRoomOrUpdateRoles,
  streamingStatus,
}: Props) {
  const {socket, clientID} = useSocket();

  const urlParams = getURLParams();
  const roomIDParam = urlParams.roomID;
  const autoJoinRoom = urlParams.autoJoin;

  const [roomID, setRoomID] = useState<string>(
    (roomIDParam ?? '').toUpperCase(),
  );
  const [roomIDError, setRoomIDError] = useState<boolean>(false);
  const [roles, setRoles] = useState<{speaker: boolean; listener: boolean}>({
    speaker: true,
    listener: true,
  });
  const [lockServer, setLockServer] = useState<boolean>(false);
  const [lockServerName, setLockServerName] = useState<string>('');

  const [joinInProgress, setJoinInProgress] = useState<boolean>(false);
  const [didAttemptAutoJoin, setDidAttemptAutoJoin] = useState<boolean>(false);

  const isValidServerLock =
    lockServer === false ||
    (lockServerName != null && lockServerName.length > 0);
  const isValidRoles = Object.values(roles).filter(Boolean).length > 0;
  const isValidAllInputs =
    isValidRoomID(roomID) && isValidRoles && isValidServerLock;
  const roomIDFromServer = roomState?.room_id ?? null;

  const onJoinRoom = useCallback(
    (createNewRoom: boolean) => {
      if (socket == null) {
        console.error('Socket is null, cannot join room');
        return;
      }
      console.debug(`Attempting to join roomID ${roomID}...`);

      const lockServerValidated: string | null =
        lockServer && roles['speaker'] ? lockServerName : null;

      setJoinInProgress(true);

      const configObject: JoinRoomConfig = {
        roles: (Object.keys(roles) as Array<Roles>).filter(
          (role) => roles[role] === true,
        ),
        lockServerName: lockServerValidated,
      };

      socket.emit(
        'join_room',
        clientID,
        createNewRoom ? null : roomID,
        configObject,
        (result) => {
          console.log('join_room result:', result);
          if (createNewRoom) {
            setRoomID(result.roomID);
          }
          if (onJoinRoomOrUpdateRoles != null) {
            onJoinRoomOrUpdateRoles();
          }
          setURLParam('roomID', result.roomID);
          setJoinInProgress(false);
        },
      );
    },
    [
      clientID,
      lockServer,
      lockServerName,
      onJoinRoomOrUpdateRoles,
      roles,
      roomID,
      socket,
    ],
  );

  useEffect(() => {
    if (
      autoJoinRoom === true &&
      didAttemptAutoJoin === false &&
      socket != null
    ) {
      // We want to consider this an attempt whether or not we actually try to join, because
      // we only want auto-join to happen on initial load
      setDidAttemptAutoJoin(true);
      if (
        isValidAllInputs &&
        joinInProgress === false &&
        roomIDFromServer == null
      ) {
        console.debug('Attempting to auto-join room...');

        onJoinRoom(false);
      } else {
        console.debug('Unable to auto-join room', {
          isValidAllInputs,
          joinInProgress,
          roomIDFromServer,
        });
      }
    }
  }, [
    autoJoinRoom,
    didAttemptAutoJoin,
    isValidAllInputs,
    joinInProgress,
    onJoinRoom,
    roomIDFromServer,
    socket,
  ]);

  return (
    <Stack direction="column" spacing="12px">
      <Stack direction="row" spacing="12px" sx={{alignItems: 'center'}}>
        <TextField
          size="small"
          label="Room Code"
          variant="outlined"
          disabled={roomState?.room_id != null}
          value={roomID}
          error={roomIDError}
          onChange={(e) => {
            const id = e.target.value.toUpperCase();
            if (isValidPartialRoomID(id)) {
              setRoomIDError(false);
              setRoomID(id);
            } else {
              setRoomIDError(true);
            }
          }}
          sx={{width: '8em'}}
        />

        <div>
          <Button
            variant="contained"
            disabled={
              isValidAllInputs === false ||
              joinInProgress ||
              streamingStatus !== 'stopped'
            }
            onClick={() => onJoinRoom(false)}>
            {roomState?.room_id != null ? 'Update Roles' : 'Join Room'}
          </Button>
        </div>

        {roomState?.room_id == null && (
          <div>
            <Button
              variant="contained"
              disabled={
                roomState?.room_id != null ||
                joinInProgress ||
                streamingStatus !== 'stopped'
              }
              onClick={() => onJoinRoom(true)}>
              {'Create New Room'}
            </Button>
          </div>
        )}
      </Stack>

      <FormGroup>
        {Object.keys(roles).map((role) => {
          return (
            <FormControlLabel
              disabled={streamingStatus !== 'stopped'}
              key={role}
              control={
                <Checkbox
                  checked={roles[role]}
                  onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                    setRoles((prevRoles) => ({
                      ...prevRoles,
                      [role]: event.target.checked,
                    }));
                  }}
                />
              }
              label={capitalize(role)}
            />
          );
        })}

        {urlParams.enableServerLock && roles['speaker'] === true && (
          <>
            <FormControlLabel
              disabled={streamingStatus !== 'stopped'}
              control={
                <Checkbox
                  checked={lockServer}
                  onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                    setLockServer(event.target.checked);
                  }}
                />
              }
              label="Lock Server (prevent other users from streaming)"
            />
          </>
        )}
      </FormGroup>

      {urlParams.enableServerLock &&
        roles['speaker'] === true &&
        lockServer && (
          <TextField
            disabled={streamingStatus !== 'stopped'}
            label="Enter Your Name + Expected Lock End Time"
            variant="outlined"
            value={lockServerName}
            onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
              setLockServerName(event.target.value);
            }}
            helperText="Locking the server will prevent anyone else from using it until you close the page, in order to maximize server performance. Please only use this for live demos."
          />
        )}

      {serverState?.serverLock != null &&
        serverState.serverLock.clientID === clientID && (
          <Alert severity="success">{`The server is now locked for your use (${serverState?.serverLock?.name}). Close this window to release the lock so that others may use the server.`}</Alert>
        )}
    </Stack>
  );
}