forked from ivLis-Studio/ivLyrics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCommunityVideoSelector.js
More file actions
1463 lines (1327 loc) · 50.5 KB
/
Copy pathCommunityVideoSelector.js
File metadata and controls
1463 lines (1327 loc) · 50.5 KB
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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* 커뮤니티 영상 선택기 컴포넌트
* 사용자들이 추천한 YouTube 영상 목록을 보여주고 투표할 수 있게 합니다.
*/
// 커스텀 확인 다이얼로그 컴포넌트
const ConfirmDialog = ({ isOpen, title, message, onConfirm, onCancel }) => {
const confirmButtonRef = react.useRef(null);
react.useEffect(() => {
if (!isOpen) return undefined;
const handleEscape = (event) => {
if (event.key === "Escape") {
event.preventDefault();
onCancel();
}
};
document.addEventListener("keydown", handleEscape);
requestAnimationFrame(() => {
confirmButtonRef.current?.focus?.();
});
return () => {
document.removeEventListener("keydown", handleEscape);
};
}, [isOpen, onCancel]);
if (!isOpen) return null;
return react.createElement(
"div",
{
className: "confirm-dialog-overlay",
onClick: onCancel,
},
react.createElement(
"div",
{
className: "confirm-dialog",
onClick: (e) => e.stopPropagation(),
role: "dialog",
"aria-modal": "true",
"aria-labelledby": "ivlyrics-community-confirm-title",
},
react.createElement(
"h3",
{
id: "ivlyrics-community-confirm-title",
className: "confirm-dialog-title",
},
title || I18n.t("communityVideo.delete")
),
react.createElement(
"p",
{
className: "confirm-dialog-message",
},
message
),
react.createElement(
"div",
{
className: "confirm-dialog-buttons",
},
react.createElement(
"button",
{
className: "confirm-dialog-btn cancel",
onClick: onCancel,
},
I18n.t("cancel")
),
react.createElement(
"button",
{
className: "confirm-dialog-btn confirm",
onClick: onConfirm,
ref: confirmButtonRef,
},
I18n.t("communityVideo.delete")
)
)
)
);
};
// 현재 음악 재생 시간에 맞춰 동기화된 YouTube 미리보기 컴포넌트
// startTime: 영상에서 첫 가사가 시작되는 시간 (초)
// VideoBackground와 동일한 로직: offset = captionStartTime - lyricsStartTime
// 헬퍼 모드 지원: CONFIG.visual["video-helper-enabled"]가 true면 로컬 비디오 사용
const getPreviewVideoSyncOffsetSeconds = (captionStartTime, lyricsStartTime, isAutoGenerated) => {
if (captionStartTime === null || captionStartTime === undefined) {
return 0;
}
const parsedCaptionStartTime = Number(captionStartTime);
if (!Number.isFinite(parsedCaptionStartTime)) {
return 0;
}
// System matches often use 0 as an unknown caption start. Treat that as song-start sync.
if (isAutoGenerated === true && Math.abs(parsedCaptionStartTime) < 0.001) {
return 0;
}
return parsedCaptionStartTime - lyricsStartTime;
};
const SyncedVideoPreview = ({ videoId, startTime, isAutoGenerated = false }) => {
const { useState, useEffect, useRef } = react;
const containerRef = useRef(null);
const playerRef = useRef(null);
const videoRef = useRef(null); // HTML5 video for helper mode
const syncIntervalRef = useRef(null);
const abortRef = useRef(null);
const [isReady, setIsReady] = useState(false);
const [useHelper, setUseHelper] = useState(false);
const [helperVideoUrl, setHelperVideoUrl] = useState(null);
// 헬퍼 모드 확인
useEffect(() => {
const helperEnabled = CONFIG?.visual?.["video-helper-enabled"] === true || CONFIG?.visual?.["video-helper-enabled"] === "true";
setUseHelper(helperEnabled);
const handleHelperChange = (e) => {
setUseHelper(e.detail?.enabled === true);
setHelperVideoUrl(null);
setIsReady(false);
};
window.addEventListener("ivLyrics:videoHelperChanged", handleHelperChange);
return () => window.removeEventListener("ivLyrics:videoHelperChanged", handleHelperChange);
}, []);
// 헬퍼 모드: 비디오 다운로드
useEffect(() => {
if (!useHelper || !videoId) return;
setIsReady(false);
setHelperVideoUrl(null);
// 1.5초 이내 응답 시 toast 숨기기 위한 변수
const requestStartTime = Date.now();
let preparingToastTimeout = setTimeout(() => {
Toast.progress(I18n.t("videoBackground.preparing"), 0);
}, 1500);
const requestVideo = async () => {
if (typeof VideoHelperService === "undefined") return;
const isAvailable = await VideoHelperService.isHelperAvailable();
if (!isAvailable) {
clearTimeout(preparingToastTimeout);
console.warn("[SyncedVideoPreview] Helper not available");
Toast.error(I18n.t("videoBackground.helperNotConnected"));
return;
}
abortRef.current = VideoHelperService.requestVideo(videoId, {
onProgress: (progress) => {
clearTimeout(preparingToastTimeout);
const percent = Math.round(progress.percent || 0);
if (progress.status === "downloading") {
Toast.progress(I18n.t("videoBackground.downloading", { percent }), percent);
} else if (progress.status === "checking") {
Toast.progress(I18n.t("videoBackground.checking"), 0);
}
},
onComplete: (url) => {
clearTimeout(preparingToastTimeout);
Toast.dismissProgress();
setHelperVideoUrl(url);
// 1.5초 이내로 완료되면 완료 toast도 숨김
const elapsed = Date.now() - requestStartTime;
if (elapsed > 1500) {
Toast.success(I18n.t("videoBackground.downloadComplete"));
}
},
onError: (message) => {
clearTimeout(preparingToastTimeout);
Toast.dismissProgress();
console.error("[SyncedVideoPreview] Helper error:", message);
Toast.error(I18n.t("videoBackground.helperError"));
},
});
};
requestVideo();
return () => {
clearTimeout(preparingToastTimeout);
Toast.dismissProgress(); // 컴포넌트 언마운트 시 progress toast 닫기
if (abortRef.current) {
abortRef.current();
abortRef.current = null;
}
};
}, [useHelper, videoId]);
// 헬퍼 모드: video 요소 설정
useEffect(() => {
if (!useHelper || !helperVideoUrl || !videoRef.current) return;
const video = videoRef.current;
video.src = helperVideoUrl;
video.muted = true;
const handleCanPlay = () => {
// 영상이 준비되면 즉시 현재 Spotify 위치로 동기화
const spotifyPositionSec = Spicetify.Player.getProgress() / 1000;
const lyricsStartTimeSec = (window.ivLyrics_firstLyricTime || 0) / 1000;
const captionStartTime = startTime;
const offset = getPreviewVideoSyncOffsetSeconds(captionStartTime, lyricsStartTimeSec, isAutoGenerated);
const videoTime = Math.max(0, spotifyPositionSec + offset);
if (videoTime >= 0 && video.duration > 0) {
video.currentTime = Math.min(videoTime, video.duration);
}
setIsReady(true);
if (Spicetify.Player.isPlaying()) {
video.play().catch(() => { });
}
};
video.addEventListener('canplay', handleCanPlay);
video.load();
return () => {
video.removeEventListener('canplay', handleCanPlay);
};
}, [useHelper, helperVideoUrl, startTime, isAutoGenerated]);
// 헬퍼 모드: 동기화
useEffect(() => {
if (!useHelper || !videoRef.current || !isReady) return;
const video = videoRef.current;
const syncToSpotify = () => {
const spotifyPositionSec = Spicetify.Player.getProgress() / 1000;
const lyricsStartTimeSec = (window.ivLyrics_firstLyricTime || 0) / 1000;
const captionStartTime = startTime;
const offset = getPreviewVideoSyncOffsetSeconds(captionStartTime, lyricsStartTimeSec, isAutoGenerated);
const videoTime = Math.max(0, spotifyPositionSec + offset);
if (Math.abs(video.currentTime - videoTime) > 0.5) {
video.currentTime = videoTime;
}
if (Spicetify.Player.isPlaying()) {
if (video.paused) video.play().catch(() => { });
} else {
if (!video.paused) video.pause();
}
};
syncIntervalRef.current = setInterval(syncToSpotify, 2000);
syncToSpotify();
const handlePlayPause = () => syncToSpotify();
Spicetify.Player.addEventListener("onplaypause", handlePlayPause);
return () => {
if (syncIntervalRef.current) clearInterval(syncIntervalRef.current);
Spicetify.Player.removeEventListener("onplaypause", handlePlayPause);
};
}, [useHelper, isReady, startTime, isAutoGenerated]);
// 일반 모드: YouTube IFrame
useEffect(() => {
if (useHelper) return;
if (!videoId || !containerRef.current) return;
let isMounted = true;
// Spotify 재생 위치에 맞춰 동기화
// VideoBackground와 동일한 로직 사용:
// offset = captionStartTime - lyricsStartTime
// targetVideoTime = spotifyTime + offset
const syncToSpotify = () => {
if (!playerRef.current) return;
try {
// player가 준비되었는지 확인
if (typeof playerRef.current.seekTo !== "function") return;
if (typeof playerRef.current.getPlayerState !== "function") return;
const spotifyPositionSec = Spicetify.Player.getProgress() / 1000; // ms -> 초
// 첫 가사 시작 시간 가져오기 (index.js에서 전역으로 노출됨)
const lyricsStartTimeSec =
(window.ivLyrics_firstLyricTime || 0) / 1000; // ms -> 초
// offset 계산: 영상의 첫 가사 시간 - Spotify의 첫 가사 시간
const captionStartTime = startTime;
const offset = getPreviewVideoSyncOffsetSeconds(captionStartTime, lyricsStartTimeSec, isAutoGenerated);
// 최종 영상 시간 계산
const videoTime = Math.max(0, spotifyPositionSec + offset);
playerRef.current.seekTo(videoTime, true);
// YT.PlayerState: -1 (unstarted), 0 (ended), 1 (playing), 2 (paused), 3 (buffering), 5 (cued)
const playerState = playerRef.current.getPlayerState();
if (Spicetify.Player.isPlaying()) {
if (playerState !== 1 && playerState !== 3) {
// not playing and not buffering
playerRef.current.playVideo();
}
} else {
if (playerState === 1) {
// playing
playerRef.current.pauseVideo();
}
}
} catch (e) {
console.error("[SyncedVideoPreview] Sync error:", e);
}
};
// YouTube IFrame API 로드 확인
const initPlayer = () => {
if (!window.YT || !window.YT.Player) {
setTimeout(initPlayer, 100);
return;
}
if (!isMounted || !containerRef.current) return;
// 고유 ID 생성
const playerId = `preview-player-${videoId}-${Date.now()}`;
const playerDiv = document.createElement("div");
playerDiv.id = playerId;
containerRef.current.innerHTML = "";
containerRef.current.appendChild(playerDiv);
playerRef.current = new window.YT.Player(playerId, {
videoId: videoId,
width: "100%",
height: 200,
playerVars: {
autoplay: 1,
controls: 0,
disablekb: 1,
fs: 0,
iv_load_policy: 3,
modestbranding: 1,
rel: 0,
showinfo: 0,
mute: 1,
playsinline: 1,
origin: window.location.origin,
},
events: {
onReady: (event) => {
if (!isMounted) return;
window.__ivLyricsDebugLog?.("[SyncedVideoPreview] Player ready");
setIsReady(true);
// 초기 동기화
setTimeout(() => {
if (isMounted) syncToSpotify();
}, 500);
},
onStateChange: (event) => {
if (!isMounted) return;
// 버퍼링이 끝나고 재생 준비되면 동기화
if (
event.data === window.YT.PlayerState.PLAYING ||
event.data === window.YT.PlayerState.CUED
) {
syncToSpotify();
}
},
onError: (event) => {
console.error("[SyncedVideoPreview] Player error:", event.data);
},
},
});
};
initPlayer();
// 주기적 동기화 (2초마다)
syncIntervalRef.current = setInterval(() => {
if (isMounted) syncToSpotify();
}, 2000);
// Spotify 재생/일시정지 이벤트 리스너
const handlePlayPause = () => {
if (!isMounted) return;
syncToSpotify();
};
Spicetify.Player.addEventListener("onplaypause", handlePlayPause);
return () => {
isMounted = false;
if (syncIntervalRef.current) {
clearInterval(syncIntervalRef.current);
syncIntervalRef.current = null;
}
Spicetify.Player.removeEventListener("onplaypause", handlePlayPause);
if (playerRef.current) {
try {
playerRef.current.destroy();
} catch (e) { }
playerRef.current = null;
}
};
}, [useHelper, videoId, startTime, isAutoGenerated]);
return react.createElement(
"div",
{
className: "community-video-embed synced-preview",
},
// 헬퍼 모드: video 태그
useHelper && react.createElement("video", {
ref: videoRef,
style: { width: "100%", height: "200px", background: "#000", objectFit: "contain" },
muted: true,
playsInline: true,
}),
// 일반 모드: YouTube 컨테이너
!useHelper && react.createElement("div", {
ref: containerRef,
style: { width: "100%", height: "200px", background: "#000" },
}),
!isReady &&
react.createElement(
"div",
{
className: "preview-loading",
},
I18n.t("communityVideo.loading")
)
);
};
// 시간 입력 시 iframe 리로드 방지를 위한 단순 미리보기 컴포넌트
// 헬퍼 모드 지원
const SimpleVideoPreview = ({ videoId, startTime }) => {
const { useState, useEffect, useRef } = react;
const containerRef = useRef(null);
const playerRef = useRef(null);
const videoRef = useRef(null);
const abortRef = useRef(null);
const [useHelper, setUseHelper] = useState(false);
const [helperVideoUrl, setHelperVideoUrl] = useState(null);
// 헬퍼 모드 확인
useEffect(() => {
const helperEnabled = CONFIG?.visual?.["video-helper-enabled"] === true || CONFIG?.visual?.["video-helper-enabled"] === "true";
setUseHelper(helperEnabled);
const handleHelperChange = (e) => {
setUseHelper(e.detail?.enabled === true);
setHelperVideoUrl(null);
};
window.addEventListener("ivLyrics:videoHelperChanged", handleHelperChange);
return () => window.removeEventListener("ivLyrics:videoHelperChanged", handleHelperChange);
}, []);
// 헬퍼 모드: 비디오 다운로드
useEffect(() => {
if (!useHelper || !videoId) return;
setHelperVideoUrl(null);
// 1.5초 이내 응답 시 toast 숨기기 위한 변수
const requestStartTime = Date.now();
let preparingToastTimeout = setTimeout(() => {
Toast.progress(I18n.t("videoBackground.preparing"), 0);
}, 1500);
const requestVideo = async () => {
if (typeof VideoHelperService === "undefined") return;
const isAvailable = await VideoHelperService.isHelperAvailable();
if (!isAvailable) {
clearTimeout(preparingToastTimeout);
Toast.error(I18n.t("videoBackground.helperNotConnected"));
return;
}
abortRef.current = VideoHelperService.requestVideo(videoId, {
onProgress: (progress) => {
clearTimeout(preparingToastTimeout);
const percent = Math.round(progress.percent || 0);
if (progress.status === "downloading") {
Toast.progress(I18n.t("videoBackground.downloading", { percent }), percent);
} else if (progress.status === "checking") {
Toast.progress(I18n.t("videoBackground.checking"), 0);
}
},
onComplete: (url) => {
clearTimeout(preparingToastTimeout);
Toast.dismissProgress();
setHelperVideoUrl(url);
// 1.5초 이내로 완료되면 완료 toast도 숨김
const elapsed = Date.now() - requestStartTime;
if (elapsed > 1500) {
Toast.success(I18n.t("videoBackground.downloadComplete"));
}
},
onError: () => {
clearTimeout(preparingToastTimeout);
Toast.dismissProgress();
Toast.error(I18n.t("videoBackground.helperError"));
},
});
};
requestVideo();
return () => {
clearTimeout(preparingToastTimeout);
Toast.dismissProgress(); // 컴포넌트 언마운트 시 progress toast 닫기
if (abortRef.current) {
abortRef.current();
abortRef.current = null;
}
};
}, [useHelper, videoId]);
// 헬퍼 모드: video 시간 설정
useEffect(() => {
if (!useHelper || !videoRef.current || !helperVideoUrl) return;
const video = videoRef.current;
video.currentTime = startTime;
video.play().catch(() => { });
}, [useHelper, helperVideoUrl, startTime]);
// 일반 모드: YouTube
useEffect(() => {
if (useHelper) return;
if (!videoId || !containerRef.current) return;
let isMounted = true;
const initPlayer = () => {
if (!window.YT || !window.YT.Player) {
setTimeout(initPlayer, 100);
return;
}
if (!isMounted) return;
// 고유 ID 생성
const playerId = `simple-preview-${videoId}-${Date.now()}`;
const playerDiv = document.createElement("div");
playerDiv.id = playerId;
containerRef.current.innerHTML = "";
containerRef.current.appendChild(playerDiv);
playerRef.current = new window.YT.Player(playerId, {
videoId: videoId,
width: "100%",
height: "180",
playerVars: {
autoplay: 1,
controls: 0,
disablekb: 1,
fs: 0,
iv_load_policy: 3,
modestbranding: 1,
rel: 0,
showinfo: 0,
mute: 0,
playsinline: 1,
start: Math.floor(startTime),
origin: window.location.origin,
},
events: {
onReady: (event) => {
if (isMounted && playerRef.current) {
playerRef.current.seekTo(startTime, true);
playerRef.current.playVideo();
}
},
},
});
};
initPlayer();
return () => {
isMounted = false;
if (playerRef.current) {
try {
playerRef.current.destroy();
} catch (e) { }
playerRef.current = null;
}
};
}, [useHelper, videoId]);
useEffect(() => {
if (useHelper) return;
if (playerRef.current && typeof playerRef.current.seekTo === "function") {
playerRef.current.seekTo(startTime, true);
playerRef.current.playVideo();
}
}, [useHelper, startTime]);
return react.createElement(
"div",
{
className: "community-video-embed submit-preview",
style: { position: "relative" },
},
// 헬퍼 모드: video 태그
useHelper && react.createElement("video", {
ref: videoRef,
src: helperVideoUrl,
style: { width: "100%", height: "180px", background: "#000", objectFit: "contain" },
muted: false,
playsInline: true,
autoPlay: true,
}),
// 일반 모드: YouTube 컨테이너
!useHelper && react.createElement("div", {
ref: containerRef,
style: { width: "100%", height: "180px", background: "#000" },
}),
react.createElement("div", {
style: {
position: "absolute",
top: 0,
left: 0,
right: 0,
bottom: 0,
cursor: "default",
},
})
);
};
const CommunityVideoSelector = ({
trackUri,
currentVideoId,
onVideoSelect,
defaultStartTime = 0,
onClose,
}) => {
const { useState, useEffect, useCallback, useRef } = react;
const getDefaultSubmitStartTime = () => {
const parsed = Number(defaultStartTime);
return Number.isFinite(parsed) && parsed >= 0 ? parsed : 0;
};
const [videos, setVideos] = useState([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
const [showSubmitForm, setShowSubmitForm] = useState(false);
const [submitUrl, setSubmitUrl] = useState("");
const [submitStartTime, setSubmitStartTime] = useState(() => getDefaultSubmitStartTime());
const [isSubmitting, setIsSubmitting] = useState(false);
const [votingId, setVotingId] = useState(null);
const [previewVideoId, setPreviewVideoId] = useState(null); // 목록에서 미리보기 중인 영상
const [previewStartTime, setPreviewStartTime] = useState(0);
const [submitVideoTitle, setSubmitVideoTitle] = useState("");
const [isLoadingTitle, setIsLoadingTitle] = useState(false);
const [editingVideo, setEditingVideo] = useState(null);
const [formPreviewVideoId, setFormPreviewVideoId] = useState(null); // 폼에서 미리보기 중인 영상
const [deletingId, setDeletingId] = useState(null); // 삭제 중인 영상 ID
const [deleteConfirmId, setDeleteConfirmId] = useState(null); // 삭제 확인 다이얼로그용
const [deleteConfirmTitle, setDeleteConfirmTitle] = useState(""); // 삭제할 영상 제목
const titleFetchTimeout = useRef(null);
// 현재 사용자 해시 ID
const currentUserHash = Utils.getCurrentUserHash();
const hasSpotifyTrackId = !!Utils.extractTrackId(trackUri);
const isLocalVideoMode = !hasSpotifyTrackId;
// 영상 목록 로드 (skipCache: 등록/삭제 후 캐시 우회)
const loadVideos = useCallback(
async (skipCache = false) => {
setIsLoading(true);
setError(null);
try {
if (isLocalVideoMode) {
const savedVideo = await Utils.getSelectedVideo(trackUri);
setVideos(savedVideo?.youtubeVideoId ? [{
id: "local",
youtubeVideoId: savedVideo.youtubeVideoId,
youtubeTitle: savedVideo.youtubeTitle,
startTime: savedVideo.captionStartTime ?? 0,
submitterId: currentUserHash,
isLocalOnly: true,
isAutoGenerated: false,
likes: 0,
dislikes: 0,
score: 0,
userVote: null,
}] : []);
setIsLoading(false);
return;
}
const data = await Utils.getCommunityVideos(trackUri, skipCache);
if (data && data.videos) {
setVideos(data.videos);
} else {
setVideos([]);
}
} catch (e) {
setError(I18n.t("communityVideo.loadError"));
}
setIsLoading(false);
},
[trackUri, isLocalVideoMode, currentUserHash]
);
useEffect(() => {
loadVideos();
}, [loadVideos]);
const resetSubmitForm = useCallback(() => {
setShowSubmitForm(false);
setSubmitUrl("");
setSubmitStartTime(getDefaultSubmitStartTime());
setSubmitVideoTitle("");
setFormPreviewVideoId(null);
setEditingVideo(null);
setIsLoadingTitle(false);
}, [defaultStartTime]);
const openSubmitForm = useCallback(async (video = null) => {
if (!isLocalVideoMode) {
try {
await Utils.requireDiscordAuth(
I18n.t("communityVideo.loginRequired"),
{ checkingMessage: I18n.t("settingsAdvanced.aboutTab.account.checking") }
);
} catch (e) {
Utils.promptDiscordLoginRequired(e?.message || I18n.t("communityVideo.loginRequired"));
return;
}
}
setEditingVideo(video);
setSubmitUrl("");
setSubmitStartTime(video?.startTime ?? getDefaultSubmitStartTime());
setSubmitVideoTitle(video?.youtubeTitle || "");
setFormPreviewVideoId(video?.youtubeVideoId || null);
setIsLoadingTitle(false);
setShowSubmitForm(true);
}, [defaultStartTime, isLocalVideoMode]);
// URL 변경 시 YouTube 제목 자동 가져오기
useEffect(() => {
if (titleFetchTimeout.current) {
clearTimeout(titleFetchTimeout.current);
}
if (editingVideo && !submitUrl) {
setSubmitVideoTitle(editingVideo.youtubeTitle || "");
setFormPreviewVideoId(editingVideo.youtubeVideoId || null);
setIsLoadingTitle(false);
return;
}
const videoId = editingVideo?.youtubeVideoId || Utils.extractYouTubeVideoId(submitUrl);
if (!videoId) {
setSubmitVideoTitle("");
setFormPreviewVideoId(null);
return;
}
// 디바운스: 500ms 후에 제목 가져오기
titleFetchTimeout.current = setTimeout(async () => {
setIsLoadingTitle(true);
try {
const title = await Utils.getYouTubeVideoTitle(videoId);
setSubmitVideoTitle(title || "");
setFormPreviewVideoId(videoId); // 폼 미리보기용 상태 사용
} catch (e) {
console.error("Failed to fetch YouTube title:", e);
setSubmitVideoTitle("");
}
setIsLoadingTitle(false);
}, 500);
return () => {
if (titleFetchTimeout.current) {
clearTimeout(titleFetchTimeout.current);
}
};
}, [editingVideo, submitUrl]);
// 투표 처리
const handleVote = async (videoEntryId, currentVote, newVote) => {
if (isLocalVideoMode) return;
setVotingId(videoEntryId);
// 같은 버튼을 다시 누르면 투표 취소
const voteType = currentVote === newVote ? 0 : newVote;
try {
const result = await Utils.voteCommunityVideo(videoEntryId, voteType, trackUri);
if (result) {
// 투표 결과로 목록 업데이트
setVideos((prev) =>
prev
.map((v) => {
if (v.id === videoEntryId) {
return {
...v,
likes: result.data.likes,
dislikes: result.data.dislikes,
score: result.data.score,
userVote: voteType === 0 ? null : voteType,
};
}
return v;
})
.sort((a, b) => b.score - a.score)
);
}
} catch (e) {
console.error("Vote failed:", e);
}
setVotingId(null);
};
// 영상 등록 처리
const handleSubmit = async () => {
const videoId = editingVideo?.youtubeVideoId || Utils.extractYouTubeVideoId(submitUrl);
if (!videoId) {
Toast.error(I18n.t("communityVideo.invalidUrl"));
return;
}
setIsSubmitting(true);
try {
let videoTitle = submitVideoTitle || editingVideo?.youtubeTitle || videoId;
if (!editingVideo) {
// YouTube 영상 유효성 검사 (실제로 존재하고 재생 가능한지 확인)
const validation = await Utils.validateYouTubeVideo(videoId);
if (!validation.valid) {
// 에러 유형에 따른 메시지
let errorMsg;
switch (validation.error) {
case "notFound":
errorMsg = I18n.t("communityVideo.videoNotFound");
break;
case "private":
errorMsg = I18n.t("communityVideo.videoPrivate");
break;
case "invalidFormat":
errorMsg = I18n.t("communityVideo.invalidUrl");
break;
default:
errorMsg = I18n.t("communityVideo.validationError");
}
Toast.error(errorMsg);
setIsSubmitting(false);
return;
}
// 유효성 검사에서 가져온 제목 사용
videoTitle = validation.title || videoTitle;
}
if (isLocalVideoMode) {
const localVideoInfo = {
youtubeVideoId: videoId,
youtubeTitle: videoTitle,
captionStartTime: parseFloat(submitStartTime) || 0,
communityEntryId: null,
isAutoGenerated: false,
isLocalOnly: true,
};
onVideoSelect?.(localVideoInfo);
Toast.success(I18n.t("communityVideo.localOnlyApplied") || "로컬 영상이 적용되었습니다.");
resetSubmitForm();
onClose?.();
setIsSubmitting(false);
return;
}
const result = await Utils.submitCommunityVideo(
trackUri,
videoId,
videoTitle,
parseFloat(submitStartTime) || 0
);
if (result) {
Toast.success(
result.data.action === "updated"
? I18n.t("communityVideo.updated")
: I18n.t("communityVideo.submitted")
);
resetSubmitForm();
// 캐시를 우회하여 새 데이터 가져오기
loadVideos(true);
}
} catch (e) {
Toast.error(e?.message || I18n.t("communityVideo.submitError"));
}
setIsSubmitting(false);
};
// 영상 적용 처리 (모달 닫지 않음)
const handleEdit = (video, e) => {
e.stopPropagation();
void openSubmitForm(video);
};
const handleApply = (video) => {
if (onVideoSelect) {
onVideoSelect({
youtubeVideoId: video.youtubeVideoId,
youtubeTitle: video.youtubeTitle,
captionStartTime: video.startTime,
communityEntryId: video.isLocalOnly ? null : video.id,
isAutoGenerated: !video.isLocalOnly && (video.submitterId === "system" || video.isAutoGenerated === true),
isLocalOnly: video.isLocalOnly === true,
});
}
Toast.success(I18n.t("communityVideo.applied"));
};
// 삭제 확인 다이얼로그 열기
const showDeleteConfirm = (video, e) => {
e.stopPropagation();
setDeleteConfirmId(video.id);
setDeleteConfirmTitle(video.youtubeTitle || video.youtubeVideoId);
};
// 삭제 확인 다이얼로그 닫기
const closeDeleteConfirm = () => {
setDeleteConfirmId(null);
setDeleteConfirmTitle("");
};
// 영상 삭제 실행 (본인만 가능)
const executeDelete = async () => {
const videoEntryId = deleteConfirmId;
if (!videoEntryId) return;
closeDeleteConfirm();
setDeletingId(videoEntryId);
try {
if (isLocalVideoMode) {
await Utils.removeSelectedVideo(trackUri);
if (previewVideoId) {
setPreviewVideoId(null);
}
setVideos([]);
onVideoSelect?.(null);
Toast.success(I18n.t("communityVideo.deleted"));
setDeletingId(null);
return;
}
const result = await Utils.deleteCommunityVideo(videoEntryId, trackUri);
if (result) {
const deletedVideo = previewVideoId
? videos.find((v) => v.id === videoEntryId)
: null;
Toast.success(I18n.t("communityVideo.deleted"));
// 목록에서 제거
setVideos((prev) => prev.filter((v) => v.id !== videoEntryId));
// 미리보기 중이던 영상이면 미리보기 닫기
if (deletedVideo && deletedVideo.youtubeVideoId === previewVideoId) {
setPreviewVideoId(null);
}
} else {
Toast.error(I18n.t("communityVideo.deleteError"));
}
} catch (e) {
console.error("Delete failed:", e);
Toast.error(I18n.t("communityVideo.deleteError"));
}
setDeletingId(null);
};
// 영상 미리보기 토글
const togglePreview = (video, e) => {
e.stopPropagation();
if (previewVideoId === video.youtubeVideoId) {
setPreviewVideoId(null);
} else {