-
Notifications
You must be signed in to change notification settings - Fork 1
/
Gameroom.tsx
939 lines (875 loc) · 33.6 KB
/
Gameroom.tsx
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
import React, { useCallback,useEffect, useState, useRef, useMemo, useLayoutEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import BaseContainer from "components/ui/BaseContainer";
import PropTypes from "prop-types";
import "styles/views/Gameroom.scss";
import "styles/views/Header.scss";
import "styles/twemoji-amazing.css";
import Header from "./Header"
import { FFmpeg } from "@ffmpeg/ffmpeg";
import { Roundstatus, RoundstatusProps } from "components/views/GameroomRoundStatus";
import { PlayerList } from "components/views/GameroomPlayerList";
import { ValidateAnswerForm } from "components/views/GameroomAnswerForm";
// Stomp related imports
import SockJS from "sockjs-client";
import { over } from "stompjs";
import { showToast} from "../../helpers/toastService";
import type {
Timestamped,
PlayerAudio,
PlayerAndRoomID,
AnswerGuess,
StompResponse,
Base64audio,
} from "stomp_types";
import { v4 as uuidv4 } from "uuid";
import { getDomain } from "helpers/getDomain";
import { throttle } from "lodash";
const DEFAULT_VOLUME = 0.5;
const THROTTLE_TIME = 1000;
const RESPONSE_TIME = 5000;
const TOAST_TIME_LONG = 6000;
const INDEX_NOT_FOUND = -1;
type SharedAudioURL = { [userId: string]: string };
const Gameroom = () => {
const navigate = useNavigate();
const { currentRoomID } = useParams();
const stompClientRef = useRef(null);
const user = {
token: sessionStorage.getItem("token"),
id: sessionStorage.getItem("id"),
username: sessionStorage.getItem("username")
};
// console.log(user)
const ffmpegRef = useRef(null);
const [isFFmpegLoaded, setIsFFmpegLoaded] = useState(false);
const [isStartedPressed, setIsStartedPressed] = useState(false);
const [showReadyPopup, setShowReadyPopup] = useState(false);
const readyStatus = useRef(false);
const [gameOver, setGameOver] = useState(false);
const isMicReady = useRef(false);
const gameOverRef = useRef(false);
const [currentSpeakerID, setCurrentSpeakerID] = useState(null);
const [playerLists, setPlayerLists] = useState([]);
const roundFinished = useRef(false);
const [endTime, setEndTime] = useState(null);
const currentRoomNameValid = useRef("");
const gameTheme = useRef("Loading....");
const leaderboardInfoRecieved = useRef(false);
const [leaderboardInfo, setLeaderboardInfo] = useState([]);
const requestLists = useRef([]);
const [gameInfo, setGameInfo] = useState(null);
const gameInfoRef = useRef(null);
// const [roomInfo, setRoomInfo] = useState({
// roomID: currentRoomID,
// theme: "Advanced",
// });
const prevStatus = useRef("start");
const [currentStatus, setCurrentStatus] = useState<
"speak" | "guess" | "reveal"
>("speak");
const [sharedAudioList, setSharedAudioList] = useState<SharedAudioURL[]>([]);
const [currentSpeakerAudioURL, setCurrentSpeakerAudioURL] = useState<
string | null
>(null);
const myRecordingReversedRef = useRef<Base64audio | null>(null);
const roundStatusComponentRef = useRef(null);
// this ref is used to track the current speaker id in callback functions
const currentSpeakerIdRef = useRef<number>();
if (gameInfo && gameInfo.currentSpeaker) {
currentSpeakerIdRef.current = gameInfo.currentSpeaker.userID;
}
const [globalVolume, setGlobalVolume] = useState(DEFAULT_VOLUME);
const globalVolumeBeforeMute = useRef(0);
gameInfoRef.current = gameInfo;
// useMemo to initialize and load FFmpeg wasm module
// load FFmpeg wasm module
// const ffmpegObj = useMemo( () => {
// const ffmpeg = new FFmpeg();
// const loadFFmpeg = async (ffmpeg) => {
// await ffmpeg.load();
// }
// try {
// loadFFmpeg(ffmpeg);
// console.error("FFmpegObj.loaded",ffmpegObj);
// console.error("FFmpegObj",ffmpegObj);
// } catch (error) {
// console.error("Failed to load FFmpeg module, please use Chrome browser.", error);
// alert("Failed to load FFmpeg module");
// }
// }, []);
// console.error("FFmpegObj.loaded",ffmpegObj);
// console.error("FFmpegObj",ffmpegObj);
//("GameInfo", gameInfo);
useLayoutEffect(() => {
ffmpegRef.current = new FFmpeg();
const loadFFmpeg = async (ffmpeg) => {
await ffmpeg.load();
}
try {
loadFFmpeg(ffmpegRef.current).then(() => {
console.log("FFmpegObj.loaded",ffmpegRef.current);
setIsFFmpegLoaded(true);
});
} catch (error) {
console.error("Failed to load FFmpeg module, please use Chrome browser.", error);
alert("Failed to load FFmpeg module");
}
return () => {
ffmpegRef.current?.loaded && ffmpegRef.current.terminate();
};
}, []);
//("GameInfo", gameInfo);
useEffect(() => {
//currentRoomNameValid.current = currentRoomName;
const isChrome = (window as any).chrome;
// console.error("ISCHROME",isChrome);
if (!isChrome) {
alert("Please use Chrome browser to play the game.");
// ffmpegRef.current?.loaded && ffmpegRef.current.terminate();
navigate("/lobby");
return;
}
// refuse non-chrome browser
// define subscription instances
let playerInfoSuber;
let gameInfoSuber;
let sharedAudioSuber;
let responseSuber;
const connectWebSocket = () => {
const baseurl = getDomain();
let Sock = new SockJS(`${baseurl}/ws`);
//let Sock = new SockJS('https://sopra-fs23-group-01-server.oa.r.appspot.com/ws');
stompClientRef.current = over(Sock);
stompClientRef.current.connect({}, onConnected, onError);
};
//console.log(sessionStorage.getItem("id"));
const timestamp = new Date().getTime(); // Get current timestamp
const onConnected = () => {
// subscribe to the topic
playerInfoSuber = stompClientRef.current.subscribe(
`/plays/info/${currentRoomID}`,
onPlayerInfoReceived
);
gameInfoSuber = stompClientRef.current.subscribe(
`/games/info/${currentRoomID}`,
onGameInfoReceived
);
sharedAudioSuber = stompClientRef.current.subscribe(
`/plays/audio/${currentRoomID}`,
onShareAudioReceived
);
responseSuber = stompClientRef.current.subscribe(
// `/response/${currentRoomID}`,
`/user/${user.id}/response/${currentRoomID}`,
onResponseReceived
);
throttledEnterRoom();
//connect or reconnect
};
const onError = (err) => {
console.error("WebSocket Error: ", err);
// alert("WebSocket connection error. Check console for details.");
// ffmpegObj.loaded && ffmpegObj.terminate();
// navigate("/lobby");
};
const onResponseReceived = (payload) => {
const msg = JSON.parse(payload.body);
console.log("=====response received=====")
// console.log(mssg)
console.log("[onResponseReceived] receiptId",msg.receiptId)
console.log("[onResponseReceived] reqList:",requestLists.current)
const index = requestLists.current.findIndex(item => item.receiptId === msg.receiptId);
if (index !== INDEX_NOT_FOUND) {
// Check if the message indicates an invalid or expired token
if (msg.auth === false) {
showToast("Invalid or expired token, please login again!", "error");
sessionStorage.clear(); // Clear session storage
// ffmpegRef.current?.loaded && ffmpegRef.current.terminate();
navigate("/login"); // Navigate to the login page
return; // Exit the function to avoid further processing
}
const messageType = requestLists.current[index].type;
const success = msg.success;
let toastMessage;
if (messageType === "ready") {
toastMessage = success ? "You are ready for the game now!" : msg.message;
} else if (messageType === "start") {
toastMessage = success ? "Game now successfully started!" : msg.message;
if(!success){
setIsStartedPressed(false);
}
} else if (messageType === "unready") {
toastMessage = success ? "You canceled ready successfully." : msg.message;
} else if (messageType === "submit") {
toastMessage = success ? "You have submitted the correct answer!" : msg.message;
} else if (messageType === "enter") {
toastMessage = success ? "You have entered the room successfully!" : msg.message;
if (!success){
// ffmpegRef.current?.loaded && ffmpegRef.current.terminate();
navigate("/lobby");
}
} else if (messageType === "upload") {
toastMessage = success ? "You have uploaded the audio successfully!" : msg.message;
}
if (success) {
showToast(toastMessage, "success");
} else {
showToast(toastMessage, "error");
}
}
/// 1. filter the response by the receiptId
/// 2. if the response is success, do nothing
/// 3. if the response is failure, show the error message
/// 4. if the response is not received, do something to handle the timeout
/// 5. if the response is unauthorized, navigate to login page and clear session
};
const onPlayerInfoReceived = (payload) => {
const payloadData = JSON.parse(payload.body);
setPlayerLists(payloadData.message);
const myInfo = payloadData.message.find(item => item.user.id === user.id);
if (!myInfo) {
console.error("My info not found in the player list");
return;
}
readyStatus.current = myInfo.ready;
if (!showReadyPopup && !gameOver){
if (myInfo && myInfo.roundFinished !== null){
roundFinished.current = myInfo.roundFinished;
}
}
if (gameOverRef.current === true && leaderboardInfoRecieved.current === false){
setLeaderboardInfo(payloadData.message);
leaderboardInfoRecieved.current = true;
}
};
const onGameInfoReceived = (payload) => {
const payloadData = JSON.parse(payload.body);
if (JSON.stringify(gameInfoRef.current) === JSON.stringify(payloadData.message)) {
console.log("Same game info received, ignore");
return;
}
if (currentRoomNameValid.current !== payloadData.message.roomName){
currentRoomNameValid.current = payloadData.message.roomName
}
if (gameTheme.current !== payloadData.message.theme){
gameTheme.current = payloadData.message.theme
}
if (payloadData.message.gameStatus === "ready") {
setShowReadyPopup(true);
} else if (payloadData.message.gameStatus === "over") {
setShowReadyPopup(false);
gameOverRef.current = true;
setGameOver(true);
} else {
setShowReadyPopup(false);
}
// if currentSpeaker is not null
if (payloadData.message.currentSpeaker) {
setCurrentSpeakerID(payloadData.message.currentSpeaker.userID);
}
// console.log("=============================");
// console.log("prevStatus.current", prevStatus.current);
// console.log("payloadData.message.roundStatus", payloadData.message.roundStatus);
if (
prevStatus.current === "reveal" &&
payloadData.message.roundStatus === "speak"
) {
//if(payloadData.message.roundStatus === "speak"){
//empty all the audio
console.log("=====clear audio====");
setCurrentSpeakerAudioURL(null);
setSharedAudioList([]);
roundStatusComponentRef.current?.clearAudio();
myRecordingReversedRef.current = null;
}
prevStatus.current = payloadData.message.roundStatus;
//"speak" | "guess" | "reveal" only allowed
setEndTime(payloadData.message.roundDue);
setCurrentStatus(payloadData.message.roundStatus);
setGameInfo(payloadData.message);
};
const onShareAudioReceived = (payload) => {
const payloadDataStamped = JSON.parse(
payload.body
) as Timestamped<PlayerAudio>;
const playerAudio = payloadDataStamped.message as PlayerAudio;
const userId = playerAudio.userID;
const audioData = playerAudio.audioData;
// create URL from base64 audio data
const blob = new Blob(
[
new Uint8Array(
atob(audioData.split(",")[1])
.split("")
.map((c) => c.charCodeAt(0))
),
],
{ type: "audio/webm" }
);
const audioURL = URL.createObjectURL(blob);
// inside the callback function, we cannot directly read a state
// since the state is always the initial state when the callback is created
// so we use a ref to store the current speaker id
if (
!!currentSpeakerIdRef.current &&
userId === currentSpeakerIdRef.current
) {
// if the audio is from the current speaker
setCurrentSpeakerAudioURL(audioURL);
} else {
// if it is shared audio
setSharedAudioList((prevState) => {
return { ...prevState, [userId]: audioURL };
});
}
};
connectWebSocket();
// Cleanup on component unmount
return () => {
if (playerInfoSuber) {
playerInfoSuber.unsubscribe();
}
if (gameInfoSuber) {
gameInfoSuber.unsubscribe();
}
if (sharedAudioSuber) {
sharedAudioSuber.unsubscribe();
}
if (responseSuber) {
responseSuber.unsubscribe();
}
if (stompClientRef.current) {
stompClientRef.current.disconnect(() => {
console.log("Disconnected");
});
}
};
}, []);
//#region -----------------WebSocket Send Functions-----------------
// when volume changes, apply the change to all audio players
useEffect(() => {
if(roundStatusComponentRef.current){
roundStatusComponentRef.current.setVolumeTo(globalVolume);
}
}, [globalVolume]);
//throttle
const enterRoom = useCallback(() => {
console.log("entered once - throttle")
const payload: Timestamped<PlayerAndRoomID> = {
timestamp: new Date().getTime(),
message: {
userID: user.id,
roomID: currentRoomID,
},
};
const receiptId = uuidv4();
stompClientRef.current?.send(
`/app/message/users/enterroom/${currentRoomID}`,
{ receiptId: receiptId,
token: sessionStorage.getItem("token") },
JSON.stringify(payload)
);
requestLists.current.push({ type: "enter",receiptId: receiptId });
console.log(requestLists.current)
const timeoutId = setTimeout(() => {
const index = requestLists.current.findIndex(request => request.receiptId === receiptId);
if (index !== INDEX_NOT_FOUND) {
requestLists.current.splice(index, 1);
}
console.log(requestLists.current)
}, RESPONSE_TIME);
return () => clearTimeout(timeoutId);
},[user.id, currentRoomID]);
const throttledEnterRoom = useCallback(throttle(enterRoom, THROTTLE_TIME), [enterRoom, THROTTLE_TIME]);
//ready
const getReady = useCallback(() => {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(function (stream) {
console.log("Microphone is already accessible.");
console.log("ready once - throttle")
const payload: Timestamped<PlayerAndRoomID> = {
// need to make sure the timestamp is UTC format
// and invariant to the time zone settings
timestamp: new Date().getTime(),
message: {
userID: user.id,
roomID: currentRoomID,
},
};
// get a random receipt uuid
const receiptId = uuidv4();
stompClientRef.current?.send(
`/app/message/users/ready/${currentRoomID}`,
{ receiptId: receiptId,
token: sessionStorage.getItem("token") },
JSON.stringify(payload)
);
requestLists.current.push({ type: "ready",receiptId: receiptId });
console.log(requestLists.current)
const timeoutId = setTimeout(() => {
const index = requestLists.current.findIndex(request => request.receiptId === receiptId);
if (index !== INDEX_NOT_FOUND) {
requestLists.current.splice(index, 1);
}
console.log(requestLists.current)
}, RESPONSE_TIME);
return () => clearTimeout(timeoutId);
})
.catch(function (err) {
console.log("Microphone access is not granted.");
showToast("Microphone access is required to start the game; Please verify your settings.", "error", TOAST_TIME_LONG);
});
},[user.id,currentRoomID]);
const throttledGetReady = useCallback(throttle(getReady, THROTTLE_TIME), [getReady, THROTTLE_TIME]);
//unready
const cancelReady = useCallback(() => {
console.log("unready once - throttle")
const payload: Timestamped<PlayerAndRoomID> = {
// need to make sure the timestamp is UTC format
// and invariant to the time zone settings
timestamp: new Date().getTime(),
message: {
userID: user.id,
roomID: currentRoomID,
},
};
const receiptId = uuidv4();
stompClientRef.current?.send(
`/app/message/users/unready/${currentRoomID}`,
{ receiptId: receiptId,
token: sessionStorage.getItem("token") },
JSON.stringify(payload)
);
requestLists.current.push({ type: "unready",receiptId: receiptId });
console.log(requestLists.current)
const timeoutId = setTimeout(() => {
const index = requestLists.current.findIndex(request => request.receiptId === receiptId);
if (index !== INDEX_NOT_FOUND) {
requestLists.current.splice(index, 1);
}
console.log(requestLists.current)
}, RESPONSE_TIME);
return () => clearTimeout(timeoutId);
},[user.id,currentRoomID]);
const throttledCancelReady = useCallback(throttle(cancelReady, THROTTLE_TIME),[cancelReady, THROTTLE_TIME]);
//start game
const startGame = useCallback(() => {
navigator.mediaDevices.getUserMedia({ audio: true })
.then(function (stream) {
console.log("Microphone is already accessible.");
console.log("start button used once")
const payload: Timestamped<PlayerAndRoomID> = {
// and invariant to the time zone settings
timestamp: new Date().getTime(),
message: {
userID: user.id,
roomID: currentRoomID,
},
};
const receiptId = uuidv4();
stompClientRef.current?.send(
`/app/message/games/start/${currentRoomID}`,
{ receiptId: receiptId,
token: sessionStorage.getItem("token") },
JSON.stringify(payload)
);
requestLists.current.push({ type: "start",receiptId: receiptId });
console.log(requestLists.current)
const timeoutId = setTimeout(() => {
const index = requestLists.current.findIndex(request => request.receiptId === receiptId);
if (index !== INDEX_NOT_FOUND) {
requestLists.current.splice(index, 1);
}
console.log(requestLists.current)
}, RESPONSE_TIME);
return () => clearTimeout(timeoutId);
})
.catch(function (err) {
console.log("Microphone access is not granted.");
showToast("Microphone access is required to start the game; Please verify your settings.", "error", TOAST_TIME_LONG);
});
},[user.id,currentRoomID]);
const throttledStartGame = useCallback(throttle(startGame, THROTTLE_TIME),[startGame, THROTTLE_TIME]);
//exit room
const exitRoom = useCallback(() => {
console.warn("isStartedPressed",isStartedPressed)
console.log("exit button used once")
const payload: Timestamped<PlayerAndRoomID> = {
// TODO: need to make sure the timestamp is UTC format
// and invariant to the time zone settings
timestamp: new Date().getTime(),
message: {
userID: user.id,
roomID: currentRoomID,
},
};
const receiptId = uuidv4();
stompClientRef.current?.send(
`/app/message/users/exitroom/${currentRoomID}`,
{ receiptId: receiptId,
token: sessionStorage.getItem("token") },
JSON.stringify(payload)
);
// ffmpegRef.current?.loaded && ffmpegRef.current.terminate();
sessionStorage.setItem("allowRedirect", "false");
// console.warn("ffmpegObj.loaded",ffmpegRef.current?.loaded)
navigate("/lobby")
},[user.id,currentRoomID]);
const throttledExitRoom = useCallback(throttle(exitRoom, THROTTLE_TIME),[exitRoom, THROTTLE_TIME]);
//validate Answer
const submitAnswer = useCallback((validateAnswer: string) => {
console.log("submit once - throttle")
const answer = validateAnswer.toLowerCase().replace(/\s/g, "");
const payload: Timestamped<AnswerGuess> = {
timestamp: new Date().getTime(),
message: {
userID: user.id,
roomID: currentRoomID,
guess: answer,
roundNum: gameInfo.currentRoundNum,
currentSpeakerID: gameInfo.currentSpeaker.userID,
},
};
const receiptId = uuidv4();
stompClientRef.current?.send(
`/app/message/games/validate/${currentRoomID}`,
{ receiptId: receiptId,
token: sessionStorage.getItem("token") },
JSON.stringify(payload)
);
requestLists.current.push({ type: "submit",receiptId: receiptId });
console.log(requestLists.current)
const timeoutId = setTimeout(() => {
const index = requestLists.current.findIndex(request => request.receiptId === receiptId);
if (index !== INDEX_NOT_FOUND) {
requestLists.current.splice(index, 1);
}
console.log(requestLists.current)
}, RESPONSE_TIME);
return () => clearTimeout(timeoutId);
},[user.id,gameInfo,currentRoomID]);
const throttledSubmitAnswer = useCallback(throttle(submitAnswer, THROTTLE_TIME),[submitAnswer, THROTTLE_TIME]);
//upload audio
const uploadAudio = useCallback(() => {
console.log("audio upload once - throttle")
console.log("[uploadAudio], myRecordingReversedRef.current", myRecordingReversedRef.current);
if (!myRecordingReversedRef.current) {
console.error("No audio to upload");
return;
}
// covert the audio blob to base64 string
const reader = new FileReader();
reader.onload = () => {
const base64data = reader.result as Base64audio;
const payload: Timestamped<PlayerAudio> = {
timestamp: new Date().getTime(),
message: {
userID: user.id,
roomID: currentRoomID,
audioData:base64data,
},
};
const receiptId = uuidv4();
stompClientRef.current.send(
`/app/message/games/audio/upload/${currentRoomID}`,
{ receiptId: receiptId,
token: sessionStorage.getItem("token") },
JSON.stringify(payload)
);
requestLists.current.push({ type: "upload",receiptId: receiptId });
console.log(requestLists.current)
const timeoutId = setTimeout(() => {
const index = requestLists.current.findIndex(request => request.receiptId === receiptId);
if (index !== INDEX_NOT_FOUND) {
requestLists.current.splice(index, 1);
}
console.log(requestLists.current)
}, RESPONSE_TIME);
return () => clearTimeout(timeoutId);
};
reader.readAsDataURL(myRecordingReversedRef.current);
},[user.id]);
const throttledUploadAudio = useCallback(throttle(uploadAudio, THROTTLE_TIME),[uploadAudio, THROTTLE_TIME]);
//#dendregion -----------------WebSocket Send Functions-----------------
const handleAudioReversed = useCallback((audio: Blob) => {
if (audio) {
myRecordingReversedRef.current = audio;
console.log("[GameRoom]Get reversed audio from AudioRecorder Success");
console.log("Reversed Audio: ", myRecordingReversedRef.current);
}
}, []);
console.log("[GameRoom]playerLists",playerLists);
console.log(playerLists);
const LeaderBoard = ({ playerStatus }) => {
console.log("[LeaderBoard]",playerStatus)
const sortedPlayerStatus = playerStatus.slice().sort((a, b) => b.score.total - a.score.total);
const LEADER_BOARD_GAP = 6;
return (
<>
{playerStatus !== null && (
<div className="leaderboarddiv">
<div className="leaderboard">
{sortedPlayerStatus.map((playerInfo, index) => (
<div className="single-score-container" key={index}>
<span className={`ranking-badge ranking-${index}`}>{index + 1}</span>
<span className={"ldgrid-item-1"}>
<span className="avatar">
<i className={`twa twa-${playerInfo.user.avatar}`} style={{ fontSize: "2.8rem" }} />
</span>
<span className="title">{playerInfo.user.name}</span>
</span>
<span className={"ldgrid-item-2"}>
<span className="score-container">{playerInfo.score.total}</span>
<span className="title">Total</span>
</span>
<span className={"ldgrid-item-3"}>
<span className="score-container">{playerInfo.score.guess}</span>
<span className="title">Guess</span>
</span>
<span className={"ldgrid-item-4"}>
<span className="score-container">{playerInfo.score.read}</span>
<span className="title">Read</span>
</span>
{playerInfo.score.details.map((detail, detailIndex) => {
const getBackgroundColor = (score) => {
if (score > 0) return "#d4edda";
if (score < 0) return "#f8d7da";
return "#fff3cd";
};
return (
<React.Fragment key={detailIndex}>
<span
className={"ldgrid-item"}
style={{ gridColumn: `${detailIndex + LEADER_BOARD_GAP}`}}
>
<span
style={{backgroundColor: getBackgroundColor(detail.score)}}
className={"score-container"}>{detail.score}</span>
<span className="title">{detail.word}</span>
</span>
</React.Fragment>
);
})}
</div>
))}
</div>
</div>
)}
</>
);
};
LeaderBoard.propTypes = {
playerStatus: PropTypes.arrayOf(
PropTypes.shape({
user: PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
avatar: PropTypes.string.isRequired,
}).isRequired,
score: PropTypes.shape({
total: PropTypes.number.isRequired,
guess: PropTypes.number.isRequired,
read: PropTypes.number.isRequired,
details: PropTypes.arrayOf(
PropTypes.shape({
word: PropTypes.string.isRequired,
role: PropTypes.number.isRequired,
score: PropTypes.number.isRequired,
})
).isRequired,
}).isRequired,
ready: PropTypes.bool.isRequired,
ifGuess: PropTypes.bool.isRequired,
})
).isRequired,
};
// if (playerLists === null || playerLists.length === 0) {
// return <div>Loading...</div>;
// }
return (
<BaseContainer className="gameroom basecontainer">
{/* <Header left="28vw" /> */}
<PlayerList
currentPlayerId={user.id}
playerStatus={playerLists}
sharedAudioList={sharedAudioList}
gameTheme={gameTheme.current}
currentRoomName={currentRoomNameValid.current}
showReadyPopup={showReadyPopup}
gameOver={gameOver}
globalVolume={globalVolume}
/>
<div className="gameroom right-area">
<Header
onChange={
e => {
const volume = parseFloat(e.target.value);
setGlobalVolume(volume);
console.log("[volume] set to", volume);
}
}
onClickMute={
() => {
if (globalVolume === 0) {
setGlobalVolume(globalVolumeBeforeMute.current);
} else {
globalVolumeBeforeMute.current = globalVolume;
setGlobalVolume(0);
}
}
}
volume={globalVolume}
/>
{!gameOver && showReadyPopup && isFFmpegLoaded && (
<div className="gameroom readypopupbg">
<div className="gameroom readypopupcontainer">
<span className="gameroom popuptitle"> {"Room#" + currentRoomNameValid.current}</span>
<span className="gameroom popuptheme">{gameTheme.current}</span>
<span className="gameroom popuptext">
{" "}
Ready to start the game?
</span>
<div className="gameroom buttonset">
{gameInfo.roomOwner.id === user.id &&(
<>
<div
className="gameroom readybutton"
onClick={() => {
setIsStartedPressed(true);
throttledStartGame();
}}
//onKeyDown={() => getReady()}
>
Start
</div>
<div
className="gameroom leavebutton"
onClick={() => {
// disable the quit button if the game is started
if (!isStartedPressed) {
throttledExitRoom();
}
}}
>
Quit
</div>
</>
)}
{gameInfo.roomOwner.id !== user.id &&(
<>
{(readyStatus.current === true)&&(
<div
className="gameroom cancelbutton"
onClick={() => throttledCancelReady()}
onKeyDown={() => throttledCancelReady()}
>
Cancel
</div>
)}
{(readyStatus.current === false)&&(
<div
className="gameroom readybutton"
onClick={() => throttledGetReady()}
onKeyDown={() => throttledGetReady()}
>
Confirm
</div>
)}
<div className="gameroom leavebutton"
onClick={() =>
{
if (readyStatus.current === false){
throttledExitRoom();
} else {
showToast("Please cancel ready before leaving the room.", "error");
}
}
}
onKeyDown={() =>
{
if (readyStatus.current === false){
throttledExitRoom();
} else {
showToast("Please cancel ready before leaving the room.", "error");
}
}
}
>
leave
</div>
</>
)}
</div>
</div>
</div>
)}
{gameOver && (
<LeaderBoard playerStatus={leaderboardInfo}></LeaderBoard>
)}
{!gameOver && !showReadyPopup && (
<Roundstatus
gameInfo = {gameInfo}
currentSpeakerAudioURL={currentSpeakerAudioURL}
endTime = {endTime}
ffmpegObj = {ffmpegRef.current}
meId = {user.id}
globalVolume = {globalVolume}
handleAudioReversed = {handleAudioReversed}
ref={roundStatusComponentRef}
/>
)}
<div className="gameroom inputarea">
{ gameInfo !== null &&
!gameOver &&
!showReadyPopup &&
gameInfo.currentSpeaker.userID !== user.id &&
currentStatus === "guess" && (
<div style={{ display: "flex", flexDirection: "row" }}>
<ValidateAnswerForm
submitAnswer={throttledSubmitAnswer}
roundFinished={roundFinished.current}
/>
</div>
)}
<div style={{display:"flex",flexDirection:"row"}}>
{showReadyPopup === true &&(
// {showReadyPopup === true && user.id !== gameInfo.roomOwner.id &&(
<></>
)}
{gameOver === true &&(
<div className="gameroom leavebutton" onClick={
() => {
//console.log("leave room after over");
exitRoom();
// navigate("/lobby");
}
}>leave</div>
)}
{currentSpeakerID === user.id &&
currentStatus === "speak" && (
<button className="gameroom readybutton"
disabled={roundFinished.current}
onClick={
() => {
//console.log("upload audio");
throttledUploadAudio();
}
}>upload</button>
)}
{currentSpeakerID !== user.id &&
currentStatus === "guess" && (
<div style={{marginTop:"1rem"}} className="gameroom readybutton" onClick={
() => {
//console.log("upload audio");
throttledUploadAudio();
}
}>Share Audio</div>
)}
</div>
</div>
</div>
</BaseContainer>
);
};
export default Gameroom;