fork/replay-manager-for-slippi

git clone https://git.julia.blue/fork/replay-manager-for-slippi

Nicolethost dns lookup2ca916a

main
21.0 KiB703 linesraw
1import {
2  BrowserUpdated,
3  Close,
4  ContentCopy,
5  FolderOpen,
6  Router,
7} from '@mui/icons-material';
8import {
9  Alert,
10  Button,
11  CircularProgress,
12  Dialog,
13  DialogActions,
14  DialogContent,
15  DialogContentText,
16  DialogTitle,
17  Divider,
18  IconButton,
19  InputBase,
20  List,
21  ListItem,
22  ListItemButton,
23  ListItemText,
24  MenuItem,
25  Snackbar,
26  Stack,
27  TextField,
28  Tooltip,
29  Typography,
30} from '@mui/material';
31import { useCallback, useEffect, useMemo, useState } from 'react';
32import {
33  CopySettings,
34  Output,
35  WebSocketServerStatus,
36  CopyHostOrClient,
37  CopyHostFormat,
38  GuideState,
39} from '../common/types';
40import ErrorDialog from './ErrorDialog';
41import LabeledCheckbox from './LabeledCheckbox';
42import { setWindowEventListener, WindowEvent } from './setWindowEventListener';
43
44function ClientsDialog({
45  disabled,
46  setHosting,
47}: {
48  disabled: boolean;
49  setHosting: (hosting: boolean) => void;
50}) {
51  const [open, setOpen] = useState(false);
52  const [status, setStatus] = useState(WebSocketServerStatus.STOPPED);
53  const [clients, setClients] = useState<CopyHostOrClient[]>([]);
54  const [v4Address, setV4Address] = useState('');
55  const [v6Address, setV6Address] = useState('');
56  const [port, setPort] = useState(0);
57  const [hostname, setHostname] = useState('');
58
59  const [v4Copied, setV4Copied] = useState(false);
60  const [v6Copied, setV6Copied] = useState(false);
61
62  const v4AddressAndPort = useMemo(
63    () => `${v4Address}:${port}`,
64    [v4Address, port],
65  );
66  const v6AddressAndPort = useMemo(
67    () => `[${v6Address}]:${port}`,
68    [v6Address, port],
69  );
70
71  useEffect(() => {
72    (async () => {
73      setClients(await window.electron.getCopyClients());
74    })();
75  }, []);
76
77  useEffect(() => {
78    window.electron.onHostServerStatus((event, newStatus) => {
79      setStatus(newStatus);
80      setHosting(newStatus !== WebSocketServerStatus.STOPPED);
81    });
82  }, [setHosting]);
83  useEffect(() => {
84    window.electron.onCopyClients((event, newClients) => {
85      setClients(newClients);
86    });
87  }, []);
88
89  const [stopOpen, setStopOpen] = useState(false);
90
91  return (
92    <>
93      <Button
94        disabled={disabled}
95        endIcon={<BrowserUpdated />}
96        onClick={async () => {
97          setHostname(await window.electron.startHostServer());
98          const startBroadcastingHostRet =
99            await window.electron.startBroadcastingHost();
100          setV4Address(startBroadcastingHostRet.v4Address);
101          setV6Address(startBroadcastingHostRet.v6Address);
102          setPort(startBroadcastingHostRet.port);
103          setOpen(true);
104        }}
105      >
106        {status === WebSocketServerStatus.STOPPED
107          ? 'Host on LAN'
108          : `Add Clients (${clients.length})`}
109      </Button>
110      <Dialog
111        open={open}
112        onClose={async () => {
113          if (clients.length === 0) {
114            await window.electron.stopHostServer();
115          }
116          await window.electron.stopBroadcastingHost();
117          setOpen(false);
118        }}
119        fullWidth
120      >
121        <DialogTitle>Hosting on LAN as {hostname}</DialogTitle>
122        <DialogContent>
123          <Stack alignItems="center" direction="row" gap="8px">
124            <TextField
125              disabled={!v6Address}
126              fullWidth
127              label="Websocket Address (IPv6)"
128              size="small"
129              value={v6AddressAndPort}
130              variant="standard"
131            />
132            <Button
133              disabled={v6Copied || !v6Address}
134              endIcon={v6Copied ? undefined : <ContentCopy />}
135              onClick={async () => {
136                await window.electron.copyToClipboard(v6AddressAndPort);
137                setV6Copied(true);
138                setTimeout(() => setV6Copied(false), 5000);
139              }}
140              variant="contained"
141            >
142              {v6Copied ? 'Copied!' : 'Copy'}
143            </Button>
144          </Stack>
145          <Stack alignItems="center" direction="row" gap="8px">
146            <TextField
147              disabled={!v4Address}
148              fullWidth
149              label="Websocket Address (IPv4)"
150              size="small"
151              value={v4AddressAndPort}
152              variant="standard"
153            />
154            <Button
155              disabled={v4Copied || !v4Address}
156              endIcon={v4Copied ? undefined : <ContentCopy />}
157              onClick={async () => {
158                await window.electron.copyToClipboard(v4AddressAndPort);
159                setV4Copied(true);
160                setTimeout(() => setV4Copied(false), 5000);
161              }}
162              variant="contained"
163            >
164              {v4Copied ? 'Copied!' : 'Copy'}
165            </Button>
166          </Stack>
167          <List>
168            {clients.map(({ address, name }) => (
169              <ListItem
170                key={address}
171                disablePadding
172                style={{ marginRight: '-16px', width: 'calc(100% + 16px)' }}
173                secondaryAction={
174                  <Tooltip arrow title="Disconnect">
175                    <IconButton
176                      edge="end"
177                      onClick={async () => {
178                        await window.electron.kickCopyClient(address);
179                      }}
180                    >
181                      <Close />
182                    </IconButton>
183                  </Tooltip>
184                }
185              >
186                <ListItemText>
187                  {address} - {name}
188                </ListItemText>
189              </ListItem>
190            ))}
191          </List>
192        </DialogContent>
193        <DialogActions>
194          <Button
195            color="error"
196            variant="contained"
197            onClick={() => {
198              setStopOpen(true);
199            }}
200          >
201            Stop Hosting
202          </Button>
203        </DialogActions>
204      </Dialog>
205      <Dialog
206        open={stopOpen}
207        onClose={() => {
208          setStopOpen(false);
209        }}
210      >
211        <DialogTitle>Stop hosting on LAN?</DialogTitle>
212        <DialogActions>
213          <Button
214            variant="contained"
215            onClick={() => {
216              setStopOpen(false);
217            }}
218          >
219            Cancel
220          </Button>
221          <Button
222            color="error"
223            variant="contained"
224            onClick={async () => {
225              await window.electron.stopBroadcastingHost();
226              await window.electron.stopHostServer();
227              setStopOpen(false);
228              setOpen(false);
229            }}
230          >
231            Stop
232          </Button>
233        </DialogActions>
234      </Dialog>
235    </>
236  );
237}
238
239function HostsDialog({ host }: { host: CopyHostOrClient }) {
240  const [open, setOpen] = useState(false);
241  const [copyHosts, setCopyHosts] = useState<string[]>([]);
242  const [selfName, setSelfName] = useState('');
243  useEffect(() => {
244    window.electron.onCopyHosts((event, newCopyHosts) => {
245      setCopyHosts(newCopyHosts);
246    });
247  }, []);
248
249  const [connecting, setConnecting] = useState(false);
250  const [manualAddress, setManualAddress] = useState('');
251  const [error, setError] = useState('');
252
253  return (
254    <>
255      <Button
256        onClick={async () => {
257          setCopyHosts([]);
258          setError('');
259          setSelfName(await window.electron.startListeningForHosts());
260          setOpen(true);
261        }}
262        endIcon={<Router />}
263      >
264        {host.address ? 'Connected' : 'Search LAN'}
265      </Button>
266      <Dialog
267        open={open}
268        onClose={async () => {
269          await window.electron.stopListeningForHosts();
270          setOpen(false);
271        }}
272        fullWidth
273      >
274        <DialogTitle>Searching LAN for host Replay Reporter...</DialogTitle>
275        <DialogContent>
276          <form
277            style={{
278              alignItems: 'center',
279              display: 'flex',
280              marginTop: '8px',
281              marginBottom: '8px',
282              gap: '8px',
283            }}
284            onSubmit={async (event) => {
285              event.preventDefault();
286              event.stopPropagation();
287
288              setConnecting(true);
289              try {
290                await window.electron.connectToHost(manualAddress);
291                await window.electron.stopListeningForHosts();
292                setOpen(false);
293              } catch (e: unknown) {
294                if (e instanceof Error) {
295                  setError(e.message);
296                }
297              } finally {
298                setConnecting(false);
299              }
300            }}
301          >
302            <TextField
303              autoFocus
304              label="IP address and port"
305              placeholder="192.168.0.106:54673"
306              size="small"
307              variant="outlined"
308              value={manualAddress}
309              onChange={(event) => {
310                setManualAddress(event.target.value);
311              }}
312            />
313            <Button
314              disabled={connecting}
315              endIcon={connecting && <CircularProgress size="24px" />}
316              type="submit"
317              variant="contained"
318            >
319              Connect
320            </Button>
321          </form>
322          {error && <Alert severity="error">{error}</Alert>}
323          <DialogContentText>Searching as {selfName}</DialogContentText>
324          <List>
325            {host.address && (
326              <ListItem
327                disablePadding
328                style={{ marginRight: '-16px', width: 'calc(100% + 16px)' }}
329                secondaryAction={
330                  <Tooltip arrow title="Disconnect">
331                    <IconButton
332                      edge="end"
333                      onClick={async () => {
334                        await window.electron.disconnectFromHost();
335                      }}
336                    >
337                      <Close />
338                    </IconButton>
339                  </Tooltip>
340                }
341              >
342                <ListItemText>
343                  {host.address} - {host.name}
344                </ListItemText>
345              </ListItem>
346            )}
347            {copyHosts.map((copyHost) => (
348              <ListItem
349                key={copyHost}
350                disablePadding
351                style={{ margin: '0 -16px', width: 'calc(100% + 32px)' }}
352              >
353                <ListItemButton
354                  onClick={async () => {
355                    setConnecting(true);
356                    try {
357                      await window.electron.connectToHost(copyHost);
358                      await window.electron.stopListeningForHosts();
359                      setOpen(false);
360                    } catch (e: unknown) {
361                      if (e instanceof Error) {
362                        setError(e.message);
363                      }
364                    } finally {
365                      setConnecting(false);
366                    }
367                  }}
368                >
369                  <ListItemText>{copyHost}</ListItemText>
370                </ListItemButton>
371              </ListItem>
372            ))}
373            <ListItem disableGutters>
374              <CircularProgress size="24px" />
375            </ListItem>
376          </List>
377        </DialogContent>
378      </Dialog>
379    </>
380  );
381}
382
383export default function CopyControls({
384  dir,
385  setDir,
386  useLAN,
387  host,
388  hostFormat,
389  error,
390  setError,
391  errorDialogOpen,
392  setErrorDialogOpen,
393  hasSelectedReplays,
394  isCopying,
395  onCopy,
396  success,
397  copySettings,
398  setCopySettings,
399  elevateSettings,
400  vlerkMode,
401  undoSubdir,
402  hideCopyButton,
403  setConfirmedCopySettings,
404  guideState,
405  setGuideBackdropOpen,
406}: {
407  dir: string;
408  setDir: (dir: string) => void;
409  useLAN: boolean;
410  host: CopyHostOrClient;
411  hostFormat: CopyHostFormat;
412  error: string;
413  setError: (error: string) => void;
414  errorDialogOpen: boolean;
415  setErrorDialogOpen: (errorDialogOpen: boolean) => void;
416  hasSelectedReplays: boolean;
417  isCopying: boolean;
418  onCopy: () => Promise<void>;
419  success: string;
420  copySettings: CopySettings;
421  setCopySettings: (newCopySettings: CopySettings) => void;
422  elevateSettings: boolean;
423  vlerkMode: boolean;
424  undoSubdir: string;
425  hideCopyButton: boolean;
426  setConfirmedCopySettings: (confirmedCopySettings: boolean) => void;
427  guideState: GuideState;
428  setGuideBackdropOpen: (backdropOpen: boolean) => void;
429}) {
430  const [hosting, setHosting] = useState(false);
431  const [copySettingsOpen, setCopySettingsOpen] = useState(elevateSettings);
432  const [copyToastOpen, setCopyToastOpen] = useState(false);
433
434  useEffect(() => {
435    if (elevateSettings) {
436      setCopySettingsOpen(true);
437    }
438  }, [elevateSettings]);
439
440  const chooseDir = async () => {
441    const newDir = await window.electron.chooseCopyDir();
442    if (newDir) {
443      setDir(newDir);
444    }
445  };
446
447  const ctrlS = useCallback(async () => {
448    if (
449      vlerkMode &&
450      !isCopying &&
451      (dir || host.address) &&
452      hasSelectedReplays
453    ) {
454      try {
455        await onCopy();
456        setCopyToastOpen(true);
457      } catch (e: any) {
458        const message = e instanceof Error ? e.message : e;
459        setError(message);
460        setErrorDialogOpen(true);
461      }
462    }
463  }, [
464    dir,
465    hasSelectedReplays,
466    host.address,
467    isCopying,
468    onCopy,
469    setError,
470    setErrorDialogOpen,
471    vlerkMode,
472  ]);
473
474  useEffect(() => {
475    setWindowEventListener(WindowEvent.CTRLS, ctrlS);
476  }, [ctrlS]);
477
478  return (
479    <>
480      <Divider />
481      <Stack paddingLeft="42px">
482        <Stack direction="row">
483          <InputBase
484            disabled
485            size="small"
486            value={
487              host.address
488                ? `${host.address} - ${host.name}`
489                : dir || 'Set copy folder...'
490            }
491            style={{ flexGrow: 1 }}
492          />
493          {useLAN && (
494            <>
495              {!host.address && (
496                <ClientsDialog
497                  disabled={!dir}
498                  setHosting={async (newHosting: boolean) => {
499                    if (newHosting) {
500                      setCopySettings({
501                        ...copySettings,
502                        output: Output.ZIP,
503                      });
504                    } else {
505                      setCopySettings(await window.electron.getCopySettings());
506                    }
507                    setHosting(newHosting);
508                  }}
509                />
510              )}
511              {!hosting && <HostsDialog host={host} />}
512            </>
513          )}
514          <Tooltip arrow title="Set copy folder">
515            <IconButton onClick={chooseDir}>
516              <FolderOpen />
517            </IconButton>
518          </Tooltip>
519        </Stack>
520        <Stack
521          alignItems="center"
522          direction="row"
523          justifyContent="right"
524          spacing="8px"
525        >
526          <ErrorDialog
527            messages={[error]}
528            onClose={() => {
529              setError('');
530              setErrorDialogOpen(false);
531            }}
532            open={errorDialogOpen}
533          />
534          <Button
535            variant="text"
536            onClick={() => {
537              setCopySettingsOpen(true);
538            }}
539            sx={
540              elevateSettings
541                ? {
542                    backgroundColor: 'white',
543                    zIndex: (theme) => theme.zIndex.modal + 1,
544                  }
545                : undefined
546            }
547          >
548            Copy Settings
549          </Button>
550          <Dialog
551            open={copySettingsOpen}
552            onClose={() => {
553              setCopySettingsOpen(false);
554              setConfirmedCopySettings(true);
555              setGuideBackdropOpen(guideState !== GuideState.NONE);
556            }}
557          >
558            <DialogTitle>Copy Settings</DialogTitle>
559            <DialogContent>
560              <Tooltip
561                arrow
562                placement="right"
563                title="A file containing set metadata will be included in the copy folder/zip"
564              >
565                <div>
566                  <LabeledCheckbox
567                    checked={copySettings.writeContext}
568                    disabled={
569                      hostFormat.copySettings !== undefined ||
570                      copySettings.output === Output.FILES
571                    }
572                    label="Write context.json"
573                    set={async (checked: boolean) => {
574                      const newCopySettings = { ...copySettings };
575                      newCopySettings.writeContext = checked;
576                      await window.electron.setCopySettings(newCopySettings);
577                      setCopySettings(newCopySettings);
578                    }}
579                  />
580                </div>
581              </Tooltip>
582              <Tooltip
583                arrow
584                placement="right"
585                title="Player tags will appear in the in-game HUD (like Slippi Broadcast/Online) depending on playback settings"
586              >
587                <div>
588                  <LabeledCheckbox
589                    checked={copySettings.writeDisplayNames}
590                    disabled={hostFormat.copySettings !== undefined}
591                    label="Overwrite Display Names"
592                    set={async (checked: boolean) => {
593                      const newCopySettings = { ...copySettings };
594                      newCopySettings.writeDisplayNames = checked;
595                      await window.electron.setCopySettings(newCopySettings);
596                      setCopySettings(newCopySettings);
597                    }}
598                  />
599                </div>
600              </Tooltip>
601              <Tooltip
602                arrow
603                placement="right"
604                title="New file names will indicate game start time, player tags, and characters"
605              >
606                <div>
607                  <LabeledCheckbox
608                    checked={copySettings.writeFileNames}
609                    disabled={hostFormat.copySettings !== undefined}
610                    label="Overwrite File Names"
611                    set={async (checked: boolean) => {
612                      const newCopySettings = { ...copySettings };
613                      newCopySettings.writeFileNames = checked;
614                      await window.electron.setCopySettings(newCopySettings);
615                      setCopySettings(newCopySettings);
616                    }}
617                  />
618                </div>
619              </Tooltip>
620              <Tooltip
621                arrow
622                placement="right"
623                title="Game start times will be shifted to have the set end exactly now. Useful if your Wii clocks aren't accurate"
624              >
625                <div>
626                  <LabeledCheckbox
627                    checked={
628                      copySettings.writeStartTimes && undoSubdir.length === 0
629                    }
630                    disabled={
631                      hostFormat.copySettings !== undefined ||
632                      undoSubdir.length > 0
633                    }
634                    label="Overwrite Start Times"
635                    set={async (checked: boolean) => {
636                      const newCopySettings = { ...copySettings };
637                      newCopySettings.writeStartTimes = checked;
638                      await window.electron.setCopySettings(newCopySettings);
639                      setCopySettings(newCopySettings);
640                    }}
641                  />
642                </div>
643              </Tooltip>
644              <TextField
645                disabled={hostFormat.copySettings !== undefined || hosting}
646                label="Output"
647                onChange={async (event) => {
648                  const newCopySettings = { ...copySettings };
649                  newCopySettings.output = parseInt(event.target.value, 10);
650                  await window.electron.setCopySettings(newCopySettings);
651                  setCopySettings(newCopySettings);
652                }}
653                select
654                size="small"
655                style={{ marginTop: '8px' }}
656                value={copySettings.output}
657              >
658                <MenuItem value={Output.FILES}>Separate Files</MenuItem>
659                <MenuItem value={Output.FOLDER}>Make Subfolder</MenuItem>
660                <MenuItem value={Output.ZIP}>Make ZIP folder</MenuItem>
661              </TextField>
662            </DialogContent>
663          </Dialog>
664          {(vlerkMode || !hideCopyButton) && (
665            <>
666              {success && <Typography variant="caption">{success}</Typography>}
667              <Button
668                disabled={
669                  isCopying || (!dir && !host.address) || !hasSelectedReplays
670                }
671                onClick={async () => {
672                  try {
673                    await onCopy();
674                  } catch (e: any) {
675                    const message = e instanceof Error ? e.message : e;
676                    setError(message);
677                    setErrorDialogOpen(true);
678                  }
679                }}
680                variant="contained"
681              >
682                {isCopying ? 'Copying...' : 'Copy'}
683              </Button>
684            </>
685          )}
686        </Stack>
687      </Stack>
688      {vlerkMode && (
689        <Snackbar
690          open={copyToastOpen}
691          autoHideDuration={5000}
692          onClose={(ev, reason) => {
693            if (reason === 'clickaway') {
694              return;
695            }
696            setCopyToastOpen(false);
697          }}
698          message="Copied!"
699        />
700      )}
701    </>
702  );
703}