Compare commits

..

10 Commits

Author SHA1 Message Date
5811c16c20 perf(search): 유튜브뮤직 검색과 ytsearch 폴백을 병렬 실행 (실험 브랜치)
측정으로 확인한 낭비: YoutubeMusic.getSearchUrl 적중률이 6/10(평균 548ms)이라,
빗나가는 40% 에서는 YTM 을 끝까지 기다린 뒤 다시 ytsearch(~0.5초)를 도는 순차 대기가
통째로 버려지고 있었다.

변경: resolveQuery 기본 경로에서 ytsearch 폴백 검색을 먼저 띄워두고 YTM 결과를 기다린다.
  - YTM 적중  -> 폴백 결과는 버리고 기존과 동일하게 동작(Lavalink 검색 1회가 헛돌 뿐)
  - YTM 빗나감 -> 이미 진행 중인 폴백 결과를 그대로 사용(추가 대기 0)
  - 버려지는 폴백 promise 는 catch 를 달아 unhandledRejection 방지
  - " Topic" 중복 부가 방지 조건 추가

실측 A/B(YTM 이 빗나가는 3곡, 검색+해석+리졸브 구간):
  기존 1500 / 1688 / 1391ms  ->  신규 1224 / 1180 / 1399ms
  재생은 3곡 모두 성공, 관찰 중 멈춤 0.
남은 병목: 음성접속 핸드셰이크(0.5~1.3초)는 디스코드 왕복이라 단축 여지가 거의 없다.
2026-09-18 20:02:16 +09:00
fed948ca02 Merge branch 'master' into experiment/potoken-direct 2026-09-18 19:54:46 +09:00
ef16b67839 experiment: 내부 API(VISIONOS) 리졸버 상세 검증 — 전 케이스 통과, 32분 연속재생 무결
운영 리졸버 + 내부API 0순위 조합을 테스트 포트(8780)에 올리고, 운영 Lavalink(.6)로
실제 재생을 검증했다. 프로덕션(8779/Lavalink/master)은 변경하지 않았다.

케이스별 결과(첫 소리 / 관찰 중 멈춤):
  짧은영상 7초     성공   888ms  (재생 후 정상 종료. 관찰창이 곡보다 길어 판정 오탐 1회 발생)
  짧은영상 18초    성공  1437ms  0/2
  일반곡(K-pop)    성공  2017ms  0/3
  해외곡           성공  4209ms  0/3
  스포티파이 URL   성공  2753ms  0/3
  플레이리스트120  성공  3147ms  0/3
  곡 전환          성공  2982ms  0/2 (Ditto -> HEYA, 6.0s)
  긴 곡(1시간)     성공  1430ms  0/3
  32분 연속재생    성공   888ms  0/383  <- position 5,180 -> 1,920,180ms 정확히 선형 증가
리졸버 경로 통계: 내부API 11회 / 폴백 0회 / 내부API 실패 0회

참고: SABR 직결은 55초에서 403으로 끊겼던 반면, 이 방식은 32분간 무결. 포맷도 itag 251 동일.
남은 과제(운영 적용 전): visitorData 를 봇이 2시간마다 갱신하는 값과 공유하도록 배선.
현재는 고정 파일(/tmp/vd.txt)을 읽는 프로토타입이라 만료 시 폴백으로 떨어진다.
연령제한곡은 샘플 확보 실패로 미검증(폴백 경로가 쿠키로 처리).
2026-09-17 23:33:11 +09:00
3c6dbc9631 experiment: 내부 API 리졸버 후보 구현 채움(직전 커밋에 빈 파일이 올라감) 2026-09-17 19:07:16 +09:00
e7283ae862 experiment: 더 빠른 경로 발견 — 유튜브 내부 API(VISIONOS) 직접 호출로 리졸브 0.3초
yt-dlp 호출 자체를 없애는 경로를 탐색해 실측했다.

[탐색 과정]
- 내부 player API 를 클라이언트별로 호출해 비교:
  ANDROID_VR/TVHTML5/WEB_EMBEDDED = LOGIN_REQUIRED·ERROR, WEB = SABR 전용(직접 URL 없음)
  IOS = 0.32s 로 직접 URL(itag 140) 획득했으나 뒷부분 range 요청이 403 → 이어받기 불가
- 정상 재생되는 yt-dlp URL 의 c= 파라미터가 VISIONOS 임을 확인하고 동일 클라이언트로 재현.
  visitorData 없이 호출하면 LOGIN_REQUIRED, 넣으면 status=OK.

[결과] VISIONOS + visitorData 직접 호출
- 추출 0.30~0.38s (현행 상주 리졸버 1.7~2.3s, 기존 subprocess 4.2~4.7s)
- itag 251 로 yt-dlp 결과와 동일 포맷, Lavalink loadType=track
- range 0 / 1MB / 2MB / 3MB 전부 206 → 이어받기 정상(SABR·IOS 와 다름)
- 실제 재생: 90초 끊김 0/17, 일반곡·곡전환 성공. 첫 소리 2.0~2.3s
- 리졸버에 0순위로 넣고 실패 시 상주 lib → subprocess 로 폴백(경로 통계 innertube 5 / lib 1 / 실패 0)

미해결/주의: visitorData 를 정적 파일에서 읽는 프로토타입이라, 운영 적용 시 봇이 2시간마다
생성하는 visitorData 를 공유받도록 배선해야 한다. 검색어(비 URL) 입력은 영상 ID 가 없어
기존 경로로 폴백한다. 연령제한곡은 미검증(폴백 경로가 쿠키로 처리).
프로덕션(리졸버 8779, Lavalink, master)은 변경하지 않았다.
2026-09-17 19:06:47 +09:00
5d5bf9b3f3 experiment: SABR 끊김은 업스트림 미완성으로 해결 불가 / 대안 '상주 리졸버' 검증 성공
[1] 재생 중 끊김(~55초) 해결 시도 — 전부 실패
  - poToken 정상 주입 + 프로덕션 동일 설정 : 55초 끊김 동일
  - 클라이언트 WEB 단독(SABR 경로 강제)    : 55초 끊김 동일(decode 오류)
  - 프록시(.4:3128) 제거                   : 55초 끊김 동일
  원인: 첫 청크 재생 후 '이어받기' 요청이 실패(정적 경로 403 / SABR 경로 decode).
  feat/sabr-support 는 열린 PR #229, 마지막 커밋 2026-07-27 로 미병합 진행 중 기능.
  => 우리 쪽 설정으로 고칠 수 없음. SABR 직결 보류 확정.

[2] 새 방식: yt-dlp 를 '상주 라이브러리'로 호출하는 리졸버(프로토타입 첨부)
  - zipapp(/usr/local/bin/yt-dlp) 을 sys.path 에 넣어 import, YoutubeDL 인스턴스 1회 생성
  - 매 요청 프로세스 기동(0.40s) 제거 + player_client=default 단독
  - 실패 시 기존 subprocess 경로로 자동 폴백(안전)
  리졸브 실측: 1.58~2.30s (기존 subprocess 3곡 평균 4.2~4.7s)
  재생 검증(프로덕션 Lavalink .6 + 이 리졸버):
    일반곡 2656ms / 해외곡 2968ms / 직접URL 1900ms / 곡전환 성공
    90초 장시간: 85초 진행, 끊김 0/17  ← SABR(55초 실패) 대비 안정
프로덕션(리졸버 8779, Lavalink, master)은 변경하지 않음. 테스트는 8780 포트로만 수행.
2026-09-17 15:29:21 +09:00
7f057d818c experiment: SABR 빌드 확대 검증 — 첫 재생은 빠르나 ~55초 뒤 403으로 끊김(적용 불가)
SelfTest 확장: 관찰시간(SELFTEST_WATCH_SEC), 곡전환(SELFTEST_SECOND_QUERY) 지원.
position 샘플링 주기를 Lavalink 보고 주기(5초)에 맞춰 멈춤 오탐 제거.

격리 Lavalink(.9:2334, SABR 빌드) + ytresolver OFF 결과:
  일반곡(K-pop)      성공  첫소리 1455ms  20초 관찰 끊김 0
  해외곡             성공  첫소리 1696ms  20초 관찰 끊김 0
  직접 URL           성공  첫소리  932ms  20초 관찰 끊김 0
  긴 곡(1시간)       성공  첫소리 3865ms  20초 관찰 끊김 0
  플레이리스트(120곡) 성공  첫소리 5656ms  20초 관찰 끊김 0
  곡 전환            성공  (Ditto → HEYA, 6.0s)
  라이브 스트림      실패  ※ 현행 방식(1.18.2+ytresolver)도 동일 실패 → 기존 한계
  장시간 90초        실패  50초 재생 후 정지, 2곡 재현
장시간 실패 원인: 재생 중 googlevideo 403
  (PersistentHttpStream.connect → "Not success status code: 403")
대조군(현행 방식) 동일 90초 테스트: 85초 진행, 끊김 0 → 현행이 안정적.

결론: SABR 빌드는 첫 재생이 약 3초 빠르지만 곡 길이(3~4분)를 못 버티므로 적용 불가.
프로덕션(Lavalink .6, 리졸버, master)은 변경하지 않았다.
2026-09-17 15:08:47 +09:00
4fbf8d9326 experiment: SABR 지원 빌드로 직결 재생 성공 — ytresolver 제거 가능성 확인
이전 결론(직결 불가)은 youtube-source 1.18.2 '릴리스' 기준이었다. upstream 에
feat/sabr-support 브랜치(커밋 02f536d "SABR stream support")가 있고, 스냅샷
저장소에 빌드가 배포돼 있어 격리 Lavalink(.9:2334)에 올려 재검증했다.

빌드 확인: 1.18.2 에 없던 dev/lavalink/youtube/sabr/* 클래스 14개 추가(SabrStream 등).
(참고: main 최신 스냅샷 f45bbb7 에는 SABR 미포함 — 감지 문자열만 존재)

실측(자가 테스트, 동일 3곡 + 1곡, 프로덕션 무영향):
  A) 현재 방식(.6 Lavalink 1.18.2 + ytresolver): 4437~4884ms, 성공
  B) SABR 빌드 + ytresolver OFF(직결)          : 1155~2816ms, 성공
→ 첫 소리까지 약 3초 단축. yt-dlp 단계 자체가 사라져 구조도 단순해진다.

미검증/주의: 연령제한곡·라이브·장시간 재생 안정성, 비공식 브랜치(미병합) 빌드 사용.
프로덕션 Lavalink(.6)·리졸버·master 는 변경하지 않았다.
2026-09-17 14:48:35 +09:00
7994e97631 experiment: 4번 추가 검증 — Lavalink 직결 전면 불가 확인 + 리졸버 고속화 후보 발견
POTOKEN_INJECT 플래그 추가(기본 true). 격리 테스트 Lavalink(.9:2334)를 별도로 띄워
클라이언트/OAuth/poToken 조합을 바꿔가며 직결 재생을 검증했다. 프로덕션 무영향.

[직결 재생 — 전부 실패]
- ANDROID_VR 우선 + OAuth + poToken : 실패
- ANDROID_VR 단독 + OAuth off       : 실패
- ANDROID_VR 단독 + OAuth/poToken off: 실패
Lavalink 측 실패 사유(클라이언트별):
  ANDROID_VR "This video requires login" / TVHTML5 "page needs to be reloaded"
  WEB "No supported audio streams available"(응답이 sabr=1 + serverAbrStreamingUrl 뿐)
  WEB_EMBEDDED "player configuration error" / MWEB 403
→ youtube-source 1.18.2(최신)는 SABR 미지원. 어떤 조합으로도 직결 불가 → ytresolver 필수.

[리졸버 고속화 — 유효한 개선 발견]
yt-dlp 클라이언트별 실측(동일 영상 5개, --get-url):
  현재 default,web_safari,tv : 5/5 성공, 평균 2.95s, itag 251
  default 단독               : 5/5 성공, 평균 2.00s, itag 251  ← 약 1.0s 단축
  android_vr 단독            : 1.6s로 가장 빠르나 오디오 전용 포맷 없음(항상 itag 18)
                               → Lavalink loadtracks 실패, 사용 불가
검증: default 단독 URL을 Lavalink가 loadType=track 로 정상 로드,
      실제 재생까지 성공(자가 테스트 position 증가 확인).
2026-09-17 14:40:42 +09:00
6762b8faba experiment: ytresolver 제거(poToken 직결) 검증 — 결론 '불가'
4번 안(yt-dlp 단계 제거) 독립 검증용 실험 브랜치. master 에는 병합하지 않는다.

- Config.ytresolverEnabled 플래그 추가(YTRESOLVER_ENABLED, 기본 true=기존 동작).
  false 면 resolvePlayable 이 Lavalink youtube-source(poToken) encoded 를 그대로 사용.
- SelfTest 추가: 사람이 음성채널에 없어도 봇이 스스로 입장→재생→position 증가를
  확인해 실제 오디오 흐름 여부를 판정(환경변수 미설정 시 비활성).

실측 결과(테스트봇, Redis off, 프로덕션 무영향):
- A) ytresolver ON : 재생 성공, 첫 소리까지 4779ms (오디오 리졸브 3166ms)
- B) ytresolver OFF: 첫 소리까지 1279~1391ms 로 빠르지만 재생 실패.
     Lavalink 예외 "All clients failed to load the item." 반복, position 0 고정.
     서로 다른 2곡에서 동일 재현 → 곡 특성 아닌 구조적 차단(SABR).
결론: poToken 주입만으로는 스트림 로드가 안 되므로 ytresolver 는 계속 필요.
2026-09-17 13:16:44 +09:00
14 changed files with 732 additions and 642 deletions

View File

@@ -0,0 +1,72 @@
"""
[실험 후보] 유튜브 내부 API(VISIONOS 클라이언트) 직접 호출로 오디오 URL을 얻는 리졸버 조각.
운영 리졸버(scripts/ytresolver.py)의 _do_resolve 맨 앞에 0순위로 끼워 넣어 쓴다.
yt-dlp 를 아예 거치지 않으므로 리졸브가 0.3초대로 떨어진다(상주 lib 1.7~2.3초).
동작 조건
- 대상이 유튜브 영상 URL 이어야 한다(영상 ID 필요). 검색어면 None 을 돌려 기존 경로로 폴백.
- visitorData 가 있어야 한다. 없으면 playabilityStatus=LOGIN_REQUIRED 로 실패한다.
운영 적용 시에는 봇이 2시간마다 생성하는 visitorData 를 공유받도록 배선해야 한다.
실측(2026-09-17)
추출 0.30~0.38s / itag 251(yt-dlp 와 동일 포맷) / Lavalink loadType=track
range 0·1MB·2MB·3MB 전부 206 (이어받기 정상) / 실제 재생 90초 끊김 0
"""
import json
import os
import re
import urllib.request
from urllib.parse import unquote
# 운영 적용 시에는 파일 대신 봇이 갱신하는 값을 받아오도록 교체할 것.
VISITOR_DATA_PATH = os.environ.get("YT_VISITOR_DATA_PATH", "/tmp/vd.txt")
_UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 15_7_3) AppleWebKit/605.1.15 "
"(KHTML, like Gecko) Version/26.0 Safari/605.1.15")
_VID_RE = re.compile(r"(?:v=|youtu\.be/|/shorts/|/embed/|/live/)([A-Za-z0-9_-]{11})")
def _visitor_data():
if not os.path.exists(VISITOR_DATA_PATH):
return ""
return unquote(open(VISITOR_DATA_PATH).read().strip())
def innertube_resolve(target):
"""유튜브 URL -> 최고 비트레이트 오디오 직링크. 불가하면 None(호출측이 폴백)."""
m = _VID_RE.search(target)
visitor = _visitor_data()
if not m or not visitor:
return None
ctx = {
"clientName": "VISIONOS", "clientVersion": "1.02",
"deviceMake": "Apple", "deviceModel": "RealityDevice17,1",
"osName": "visionOS", "osVersion": "26.5.23O471",
"hl": "ko", "gl": "KR", "visitorData": visitor,
}
body = {"videoId": m.group(1), "context": {"client": ctx},
"contentCheckOk": True, "racyCheckOk": True}
req = urllib.request.Request(
"https://www.youtube.com/youtubei/v1/player?prettyPrint=false",
data=json.dumps(body).encode(),
headers={
"Content-Type": "application/json",
"User-Agent": _UA,
"X-Goog-Visitor-Id": visitor,
"X-Youtube-Client-Name": "101",
"X-Youtube-Client-Version": "1.02",
},
)
data = json.loads(urllib.request.urlopen(req, timeout=15).read())
if data.get("playabilityStatus", {}).get("status") != "OK":
return None
formats = (data.get("streamingData") or {}).get("adaptiveFormats") or []
audio = [f for f in formats
if str(f.get("mimeType", "")).startswith("audio") and f.get("url")]
if not audio:
return None
audio.sort(key=lambda f: f.get("bitrate", 0), reverse=True)
return audio[0]["url"]

View File

@@ -0,0 +1,181 @@
#!/usr/bin/env python3
"""
ytresolver - yt-dlp 오디오 URL 리졸버 (HTTP 서비스)
봇(GuildPlayer.resolvePlayable)이 유튜브/스포티파이-미러 트랙을 재생하기 직전에 호출한다.
Lavalink의 youtube-plugin은 집 IP의 SABR 차단/성인인증(연령제한) 때문에 실재생이 막히므로,
여기서 yt-dlp로 "직접 오디오 URL"을 뽑아 봇에 돌려주고 봇은 그 URL을 Lavalink http 소스로 재생한다.
동작:
1) 먼저 익명(쿠키 없이)으로 시도 -> 일반 영상은 계정을 태우지 않는다(밴 리스크 최소화).
2) 실패하면 쿠키 + node(EJS 시그니처 해독) 로 재시도 -> 성인인증(연령제한) 영상 우회.
환경변수:
YTRESOLVER_COOKIE : Netscape 쿠키 파일 경로 (기본 /root/bot/db/ytcookie.txt)
YTRESOLVER_PORT : 리슨 포트 (기본 8779)
YTDLP : yt-dlp 실행 경로 (기본 /usr/local/bin/yt-dlp)
HTTP API:
GET /resolve?url=<유튜브 URL | ytsearch: | 검색어> -> {"url": "<직접 오디오 URL>"}
GET /health -> {"ok": true}
"""
import json, subprocess, time, threading, os, sys
sys.path.insert(0, os.environ.get("YTDLP", "/usr/local/bin/yt-dlp")) # zipapp 내부 모듈 임포트
import yt_dlp
_YDL_OPTS = {"format": "bestaudio/best", "noplaylist": True, "quiet": True,
"no_warnings": True, "nocheckcertificate": True, "socket_timeout": 15,
"extractor_args": {"youtube": {"player_client": ["default"]}}}
_ydl = yt_dlp.YoutubeDL(_YDL_OPTS) # 프로세스 상주(임포트/초기화 1회)
_ydl_lock = threading.Lock()
def lib_resolve(target):
print("[lib] enter " + target[:40], file=sys.stderr, flush=True)
# yt-dlp 를 라이브러리로 직접 호출: 매 요청 프로세스 기동(약 0.4s) 을 없앤다.
q = target if (target.startswith("http") or target.startswith("ytsearch")) else "ytsearch1:" + target
with _ydl_lock:
info = _ydl.extract_info(q, download=False)
print("[lib] got info keys=" + str(list(info.keys())[:6]), file=sys.stderr, flush=True)
if info.get("entries"):
info = info["entries"][0]
u = info.get("url")
if not u:
for f in (info.get("requested_formats") or []):
if f.get("url"): u = f["url"]; break
return u
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse, parse_qs
YTDLP = os.environ.get("YTDLP", "/usr/local/bin/yt-dlp")
COOKIE_FILE = os.environ.get("YTRESOLVER_COOKIE", "/root/bot/db/ytcookie.txt")
PORT = int(os.environ.get("YTRESOLVER_PORT", "8779"))
CACHE = {}
INFLIGHT = {} # target -> {"event": Event, "url": str|None} 진행 중 리졸브 합치기(coalescing)
LOCK = threading.Lock()
TTL = 1800 # 리졸브된 URL 캐시 30분(googlevideo URL 자체는 약 6시간 유효)
# 속도/안정성 공통 플래그
COMMON = ["-f", "bestaudio/best", "--no-playlist", "--no-warnings",
"--no-check-certificate", "--socket-timeout", "15"]
def run_ytdlp(target, use_cookies=False):
if use_cookies and os.path.exists(COOKIE_FILE):
# 성인인증(연령제한): web 클라이언트 + 쿠키 + node(EJS) 시그니처 해독 필요
cmd = [YTDLP, "--js-runtimes", "node", "--cookies", COOKIE_FILE,
*COMMON, "--extractor-args", "youtube:player_client=web"]
else:
# 익명: 계정 미사용. 일반 영상에서 잘 나오는 클라이언트 조합.
cmd = [YTDLP, *COMMON,
"--extractor-args", "youtube:player_client=default,web_safari,tv"]
cmd += ["--get-url", target]
return subprocess.run(cmd, capture_output=True, text=True, timeout=45)
def first_url(out):
lines = (out.stdout or "").strip().splitlines()
return lines[0] if lines else None
def _do_resolve(target):
# 1순위: 라이브러리 상주 호출(가장 빠름). 실패하면 기존 subprocess 경로로 폴백.
try:
u = lib_resolve(target)
if u and u.startswith("http"):
print("[result] OK(lib) " + u[:50], file=sys.stderr, flush=True)
with LOCK:
CACHE[target] = (u, time.time() + TTL)
return u
except Exception as e:
print("[lib-fail] " + str(e)[:150], file=sys.stderr, flush=True)
try:
out = run_ytdlp(target, use_cookies=False)
url = first_url(out)
if not (url and url.startswith("http")) and os.path.exists(COOKIE_FILE):
print(f"[retry-cookies] {(out.stderr or out.stdout or '')[:180]}", file=sys.stderr, flush=True)
out = run_ytdlp(target, use_cookies=True)
url = first_url(out)
except subprocess.TimeoutExpired:
print("[result] TIMEOUT", file=sys.stderr, flush=True)
return None
if not (url and url.startswith("http")):
print(f"[result] FAIL {(out.stderr or out.stdout or '')[:240]}", file=sys.stderr, flush=True)
return None
print(f"[result] OK {url[:60]}", file=sys.stderr, flush=True)
with LOCK:
CACHE[target] = (url, time.time() + TTL)
return url
def resolve(target):
now = time.time()
with LOCK:
hit = CACHE.get(target)
if hit and hit[1] > now:
return hit[0]
# 같은 target이 이미 리졸브 중이면, 새 yt-dlp를 띄우지 않고 그 결과를 기다린다.
# (봇이 음성 접속과 동시에 미리 리졸브를 걸어두면, 실제 재생 요청이 이 진행분에 합쳐져
# 음성 접속 시간과 리졸브 시간이 겹쳐 첫 재생 지연이 크게 줄어든다.)
entry = INFLIGHT.get(target)
owner = entry is None
if owner:
entry = {"event": threading.Event(), "url": None}
INFLIGHT[target] = entry
if not owner:
entry["event"].wait(50)
with LOCK:
hit = CACHE.get(target)
return hit[0] if hit and hit[1] > time.time() else entry.get("url")
# owner: 실제 리졸브 수행
url = None
try:
url = _do_resolve(target)
except Exception as e:
print(f"[result] ERR {str(e)[:120]}", file=sys.stderr, flush=True)
finally:
entry["url"] = url
with LOCK:
INFLIGHT.pop(target, None)
entry["event"].set()
return url
class H(BaseHTTPRequestHandler):
def log_message(self, *a):
pass
def do_GET(self):
p = urlparse(self.path)
q = parse_qs(p.query)
if p.path == "/health":
self._send(200, {"ok": True, "cookie": os.path.exists(COOKIE_FILE)})
return
if p.path != "/resolve":
self._send(404, {"error": "not found"})
return
target = (q.get("url") or q.get("q") or [None])[0]
print(f"[resolve] {target[:80] if target else None}", file=sys.stderr, flush=True)
if not target:
self._send(400, {"error": "missing url/q"})
return
if not (target.startswith("http") or target.startswith("ytsearch")):
target = "ytsearch1:" + target
url = resolve(target)
if url:
self._send(200, {"url": url})
else:
self._send(502, {"error": "resolve failed"})
def _send(self, code, obj):
b = json.dumps(obj).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
if __name__ == "__main__":
print(f"ytresolver listening on :{PORT} (cookie={COOKIE_FILE}, exists={os.path.exists(COOKIE_FILE)})",
file=sys.stderr, flush=True)
ThreadingHTTPServer(("0.0.0.0", PORT), H).serve_forever()

View File

@@ -261,6 +261,8 @@ export class GuildPlayer {
* youtube-source가 집 IP의 SABR 차단으로 실패하는 문제를 우회한다. 실패 시 원본 encoded로 폴백. */
private async resolvePlayable(track: QueueTrack): Promise<string> {
try {
// 실험: ytresolver 비활성화 시 Lavalink youtube-source(poToken)로 직접 재생 — yt-dlp 단계 생략.
if (!Config.ytresolverEnabled) return track.encoded;
const info: any = (track as any).info ?? {};
const src = info.sourceName;
if (src !== "youtube" && src !== "spotify" && src !== "youtubemusic") return track.encoded;

View File

@@ -43,6 +43,11 @@ export class LavalinkManager {
* BotGuard 생성의 메모리 스파이크를 봇 본체와 격리하기 위해 독립 ESM 스크립트를 자식 프로세스로 실행한다.
*/
private refreshPoToken(): void {
// [실험] poToken 주입을 끄고 비교하기 위한 플래그. 미설정 시 기존 동작(주입).
if (process.env.POTOKEN_INJECT?.trim()?.toLocaleLowerCase() === "false") {
Logger.warn(`[LavalinkManager] [실험] POTOKEN_INJECT=false — poToken 주입 생략`);
return;
}
const script = join(__dirname, "..", "..", "scripts", "potoken-refresh.mjs");
const child = spawn(process.execPath, [script], {
env: {
@@ -117,9 +122,9 @@ export class LavalinkManager {
// getSearchUrl이 null을 주고, 공식 오디오를 잘 잡는 `ytsearch:... Topic`로 폴백한다.
// ('-p' 플래그를 붙이면 스포티파이 우선 검색)
// 기본 경로는 YTM 검색과 ytsearch 폴백을 '동시에' 출발시킨다.
// YTM 적중률이 약 60%라, 빗나가는 40%에서는 YTM(~0.5초)을 끝까지 기다린 뒤 다시
// ytsearch(~0.5초)를 도는 순차 대기가 통째로 낭비된다. 미리 같이 돌려두면 빗나가도
// 추가 대기가 없다. (적중 시엔 폴백 결과를 버리므로 Lavalink 검색 1회가 헛돌지만 비용이 작다.)
// YTM 적중률이 약 60%라, 빗나가는 40%에서는 YTM(~0.5초)을 기다린 뒤 다시 ytsearch(~0.5초)를
// 도는 순차 대기가 통째로 낭비된다. 미리 같이 돌려두면 빗나가도 추가 대기가 없다.
// (적중 시에는 폴백 결과를 버리므로 Lavalink 검색 1회가 헛돌지만 비용이 작다.)
let searchText: string;
let pendingFallback: ReturnType<typeof node.rest.resolve> | null = null;
if (isUrl) searchText = text;
@@ -187,6 +192,7 @@ export class LavalinkManager {
*/
public prewarmTrack(track: Track) {
try {
if (!Config.ytresolverEnabled) return; // yt-dlp 미사용 실험 모드에서는 예열 자체가 불필요
const info: any = (track as any).info ?? {};
const src = info.sourceName;
if (src !== "youtube" && src !== "spotify" && src !== "youtubemusic") return;

View File

@@ -3,6 +3,7 @@ import { client, handler, Redis } from "../index";
import { Logger } from "../utils/Logger";
import { DB } from "../utils/Database";
import { channelRegister } from "../commands/channel";
import { runSelfTest } from "../utils/SelfTest";
export const clientReady = async () => {
if (!client.user) return;
@@ -20,6 +21,9 @@ export const clientReady = async () => {
Logger.info(`[Redis Pub] bot-guilds 설정 완료: [${guildIds.join(",")}]`);
}
// [실험 전용] 환경변수가 있을 때만 동작. 프로덕션에는 변수 미설정이라 아무 일도 안 한다.
runSelfTest();
if (!Config.dev) return;
try {
const body = Array.from(handler.commands.values().filter(cmd => cmd.visible).map(cmd => cmd.metaData));

View File

@@ -106,6 +106,11 @@ export const Config = {
// yt-dlp 오디오 리졸버(ytresolver) 주소. 리졸버는 봇/쿠키와 같은 .5 호스트에 co-located.
ytresolverUrl: (process.env.YTRESOLVER_URL?.trim() || "http://192.168.10.5:8779").replace(/\/+$/, ""),
// ytresolver(yt-dlp) 사용 여부. false 면 Lavalink youtube-source(poToken 주입)로 직접 재생한다.
// 첫 재생에서 yt-dlp 단계(콜드 3.6~4.2s)를 통째로 없애지만, 집 IP의 SABR/403 차단에
// 다시 걸릴 수 있어 실험용 플래그로 둔다. 미설정 시 기존 동작(true) 유지.
ytresolverEnabled: (process.env.YTRESOLVER_ENABLED?.trim()?.toLocaleLowerCase() ?? "true") !== "false",
proxyUrl: process.env.PROXY_URL?.trim() || "",
_redis: {

95
bot/src/utils/SelfTest.ts Normal file
View File

@@ -0,0 +1,95 @@
import { client, lavalinkManager } from "../index";
import { channelJoin } from "../commands/join";
import { channelRegister } from "../commands/channel";
import { Logger } from "./Logger";
/**
* [실험 전용] poToken 직결 재생 검증용 자가 테스트.
*
* SELFTEST_GUILD_ID / SELFTEST_VOICE_CHANNEL_ID 가 설정되면, 봇이 스스로 음성채널에 들어가
* 한 곡을 재생한 뒤 실제로 오디오가 흐르는지(position 이 증가하는지) 확인해 결과를 로그로 남긴다.
* 사람이 음성채널에 없어도 검증할 수 있게 하기 위한 것으로, 실험 브랜치에서만 사용한다.
*/
export async function runSelfTest() {
const guildId = process.env.SELFTEST_GUILD_ID?.trim();
const voiceChannelId = process.env.SELFTEST_VOICE_CHANNEL_ID?.trim();
const query = process.env.SELFTEST_QUERY?.trim() || "아이유 좋은 날";
if (!guildId || !voiceChannelId) return;
try {
Logger.info(`[SelfTest] 시작: guild=${guildId} voice=${voiceChannelId} query="${query}"`);
const guild = client.guilds.cache.get(guildId) ?? await client.guilds.fetch(guildId).catch(() => null);
if (!guild) return Logger.error(`[SelfTest] guild 를 찾을 수 없습니다: ${guildId}`);
// Lavalink 노드 연결을 기다린다(연결 전이면 channelJoin 이 실패한다).
for (let i = 0; i < 60 && !lavalinkManager.hasReadyNode(); i++) {
await new Promise((r) => setTimeout(r, 500));
}
if (!lavalinkManager.hasReadyNode()) return Logger.error(`[SelfTest] Lavalink 노드 연결 대기 실패`);
// 음악 텍스트 채널이 등록돼 있어야 재생 세션을 만들 수 있다.
const textChannelId = process.env.SELFTEST_TEXT_CHANNEL_ID?.trim();
if (textChannelId) {
const embed = await channelRegister(guild, textChannelId);
Logger.info(`[SelfTest] 음악채널 등록: ${embed.data.title ?? "-"}`);
}
const t0 = Date.now();
const { player } = await channelJoin(guild, voiceChannelId);
if (!player) return Logger.error(`[SelfTest] 음성채널 참가 실패`);
const tJoin = Date.now();
Logger.info(`[SelfTest] 음성접속 완료 ${tJoin - t0}ms`);
await lavalinkManager.search(guild.id, query, client.user?.id ?? "selftest", player);
const tPlay = Date.now();
Logger.info(`[SelfTest] 재생 요청까지 ${tPlay - t0}ms (검색+해석+리졸브 ${tPlay - tJoin}ms)`);
// 실제 오디오가 흐르는지 확인: position 이 시간에 따라 증가해야 한다.
// SELFTEST_WATCH_SEC 로 관찰 시간을 늘리면 장시간 재생 안정성(중간 끊김)을 검증할 수 있다.
const watchSec = Number(process.env.SELFTEST_WATCH_SEC?.trim() || "9");
// Lavalink 는 position 을 약 5초 주기로 보고하므로 그 주기에 맞춰 샘플링해야 오탐이 없다.
const stepMs = 5000;
const steps = Math.max(3, Math.round((watchSec * 1000) / stepMs));
const samples: number[] = [];
let stallCount = 0;
for (let i = 0; i < steps; i++) {
await new Promise((r) => setTimeout(r, stepMs));
const pos = player.position;
if (samples.length > 0 && pos <= samples[samples.length - 1]) stallCount++;
samples.push(pos);
if (i % 3 === 0 || i === steps - 1) {
Logger.log(`[SelfTest] t+${((i + 1) * stepMs / 1000).toFixed(0)}s position=${pos} isPlaying=${player.isPlaying} track="${player.nowTrack?.info?.title ?? "-"}"`);
}
}
const advanced = samples[samples.length - 1] > samples[0] && samples[samples.length - 1] > 0;
if (advanced) {
Logger.ready(`[SelfTest] 결과: 재생 성공 ✅ (${(watchSec).toFixed(0)}초 관찰, position ${samples[0]} → ${samples[samples.length - 1]}, 멈춤구간 ${stallCount}/${steps - 1}, 첫 소리까지 약 ${tPlay - t0}ms)`);
} else {
Logger.error(`[SelfTest] 결과: 재생 실패 ❌ (position 이 진행하지 않음: ${samples.slice(0, 6).join(", ")})`);
return;
}
// 곡 전환 검증: 두 번째 곡을 큐에 넣고 스킵해서 실제로 다음 곡이 재생되는지 본다.
const secondQuery = process.env.SELFTEST_SECOND_QUERY?.trim();
if (secondQuery) {
const firstTitle = player.nowTrack?.info?.title ?? "";
await lavalinkManager.search(guild.id, secondQuery, client.user?.id ?? "selftest", player);
await new Promise((r) => setTimeout(r, 1500));
const tSkip = Date.now();
player.skip();
let switched = false;
for (let i = 0; i < 10; i++) {
await new Promise((r) => setTimeout(r, 1500));
const cur = player.nowTrack?.info?.title ?? "";
if (cur && cur !== firstTitle && player.position > 0) { switched = true; break; }
}
if (switched) {
Logger.ready(`[SelfTest] 곡전환: 성공 ✅ ("${firstTitle.slice(0, 25)}" → "${(player.nowTrack?.info?.title ?? "").slice(0, 25)}", ${Date.now() - tSkip}ms)`);
} else {
Logger.error(`[SelfTest] 곡전환: 실패 ❌ (다음 곡이 재생되지 않음)`);
}
}
} catch (err) {
Logger.error(`[SelfTest] 예외: ${String(err)}`);
}
}

21
docker-compose.exp.yml Normal file
View File

@@ -0,0 +1,21 @@
services:
music-exp:
build: ./bot
container_name: music-exp
restart: "no"
network_mode: host
env_file:
- ./bot/.env
environment:
- REDIS=false
- LAVALINK_HOST=192.168.10.6
- LAVALINK_PORT=2333
- SELFTEST_GUILD_ID=1352269198297923648
- SELFTEST_VOICE_CHANNEL_ID=1352269198914621465
- SELFTEST_TEXT_CHANNEL_ID=1421342055774289980
- SELFTEST_QUERY=aespa Supernova
- SELFTEST_WATCH_SEC=15
- YTRESOLVER_ENABLED=true
- YTRESOLVER_URL=http://192.168.10.5:8779
volumes:
- ./testdb:/db

View File

@@ -1,8 +1,6 @@
"use client";
import { useState } from "react";
import { useSession } from "next-auth/react";
import { ListMusic, X } from "lucide-react";
import TopNav from "@/components/layout/TopNav";
import LeftSidebar from "@/components/layout/LeftSidebar";
import MainContent from "@/components/player/MainContent";
@@ -14,17 +12,11 @@ import type { DiscordServer } from "@/types/music";
export type ViewMode = "SERVER_LIST" | "SERVER_DETAIL" | "SEARCH_RESULT";
export default function MusicPlayerLayout() {
const { status } = useSession();
const [viewMode, setViewMode] = useState<ViewMode>("SERVER_LIST");
const [selectedServer, setSelectedServer] = useState<DiscordServer | null>(null);
const [searchQuery, setSearchQuery] = useState("");
// 모바일에서 대기열은 상시 컬럼이 아니라 오른쪽에서 밀려나오는 패널로 띄운다.
const [isQueueOpen, setIsQueueOpen] = useState(false);
const isAuthed = status === "authenticated";
// 서버를 고르기 전에는 재생/대기열이 의미가 없어, 화면을 차지하지 않게 숨긴다.
const showPlayback = isAuthed && !!selectedServer;
// 홈 버튼 클릭 시: 서버 목록(또는 상세)으로 복귀
const handleHome = () => {
if (selectedServer) {
setViewMode("SERVER_DETAIL");
@@ -35,38 +27,29 @@ export default function MusicPlayerLayout() {
}
};
// 검색 실행 시
const handleSearch = (query: string) => {
setSearchQuery(query);
setViewMode("SEARCH_RESULT");
};
// 서버 선택 시
const handleSelectServer = (server: DiscordServer) => {
setSelectedServer(server);
setViewMode("SERVER_DETAIL");
};
const handleBackToServers = () => {
setViewMode("SERVER_LIST");
setSelectedServer(null);
setSearchQuery("");
setIsQueueOpen(false);
};
return (
<div className="flex h-dvh flex-col overflow-hidden bg-neutral-950 font-sans text-white">
<TopNav
onSearch={handleSearch}
onHome={handleHome}
selectedServer={selectedServer}
<div className="flex flex-col h-screen bg-neutral-900 text-white overflow-hidden font-sans">
<TopNav
onSearch={handleSearch}
onHome={handleHome}
selectedServer={selectedServer} // 🌟 이 줄을 추가해서 선택된 서버 정보를 넘깁니다.
/>
<div className="relative flex flex-1 overflow-hidden">
{/* 좌측 사이드바: 보조 정보라 넓은 화면에서만 노출한다(모바일 공간 절약). */}
{showPlayback && (
<LeftSidebar selectedServer={selectedServer} onBackToServers={handleBackToServers} />
)}
<MainContent
<div className="flex flex-1 overflow-hidden">
<LeftSidebar />
<MainContent
viewMode={viewMode}
setViewMode={setViewMode}
selectedServer={selectedServer}
@@ -75,66 +58,10 @@ export default function MusicPlayerLayout() {
setSearchQuery={setSearchQuery}
onSelectServer={handleSelectServer}
/>
{showPlayback && (
<>
{/* 모바일에서 대기열이 열렸을 때 뒤쪽을 덮는 배경(탭하면 닫힘) */}
{isQueueOpen && (
<button
type="button"
aria-label="대기열 닫기"
onClick={() => setIsQueueOpen(false)}
className="absolute inset-0 z-30 bg-black/60 backdrop-blur-sm lg:hidden"
/>
)}
{/* 대기열: 데스크톱은 고정 컬럼, 모바일은 슬라이드 패널 (인스턴스는 하나만 유지) */}
<div
className={`absolute inset-y-0 right-0 z-40 w-[22rem] max-w-[88%] transform border-l border-neutral-800 bg-neutral-950 shadow-2xl transition-transform duration-300 ease-out
${isQueueOpen ? "translate-x-0" : "translate-x-full"}
lg:static lg:z-auto lg:w-80 lg:max-w-none lg:translate-x-0 lg:shadow-none`}
aria-hidden={!isQueueOpen && typeof window !== "undefined" && window.innerWidth < 1024}
>
<QueueSidebar
selectedServer={selectedServer}
onClose={() => setIsQueueOpen(false)}
/>
</div>
</>
)}
<QueueSidebar selectedServer={selectedServer} />
</div>
{showPlayback && (
<PlayerBar
selectedServer={selectedServer}
onToggleQueue={() => setIsQueueOpen((v) => !v)}
isQueueOpen={isQueueOpen}
/>
)}
{/* 모바일 전용 대기열 열기 버튼: 플레이어바에도 있지만, 재생 전에도 접근할 수 있게 둔다. */}
{showPlayback && !isQueueOpen && (
<button
type="button"
onClick={() => setIsQueueOpen(true)}
className="fixed bottom-24 right-4 z-30 flex h-14 w-14 items-center justify-center rounded-full bg-green-500 text-black shadow-xl transition hover:bg-green-400 active:scale-95 lg:hidden"
aria-label="대기열 열기"
>
<ListMusic size={24} />
</button>
)}
{/* 모바일 패널 닫기 버튼(패널 위에 떠 있음) */}
{showPlayback && isQueueOpen && (
<button
type="button"
onClick={() => setIsQueueOpen(false)}
className="fixed right-4 top-20 z-50 flex h-11 w-11 items-center justify-center rounded-full bg-neutral-800 text-white shadow-lg transition hover:bg-neutral-700 lg:hidden"
aria-label="대기열 닫기"
>
<X size={20} />
</button>
)}
<PlayerBar selectedServer={selectedServer} />
</div>
);
}
}

View File

@@ -1,61 +1,20 @@
"use client";
import { ChevronLeft, Info, Server } from "lucide-react";
import type { DiscordServer } from "@/types/music";
import { ListMusic } from "lucide-react";
interface LeftSidebarProps {
selectedServer: DiscordServer | null;
onBackToServers: () => void;
}
/**
* 좌측 보조 패널. 예전에는 안내 문구만 있는 죽은 공간이었어서,
* "지금 어느 서버를 조작 중인지"와 서버 전환 동선을 넣어 실제로 쓰이게 했다.
* 좁은 화면에서는 숨긴다(같은 정보가 본문/플레이어에 이미 있다).
*/
export default function LeftSidebar({ selectedServer, onBackToServers }: LeftSidebarProps) {
export default function LeftSidebar() {
return (
<aside className="hidden w-60 flex-shrink-0 flex-col gap-4 border-r border-neutral-800 bg-neutral-950 p-4 lg:flex">
<p className="px-1 text-xs font-semibold uppercase tracking-wider text-neutral-500">
조작 중인 서버
<aside className="w-60 bg-black p-6 flex flex-col gap-6">
<div className="flex items-center gap-2 text-neutral-400 font-medium">
<ListMusic size={20} />
<span>음악 봇 컨트롤</span>
</div>
<hr className="border-neutral-800" />
<p className="text-xs text-neutral-500 leading-relaxed">
상단 검색창에서 노래를 찾아 우측 대기열에 추가할 수 있습니다.
디스코드 음성 채널에 입장한 상태에서 사용해주세요.
</p>
<div className="flex items-center gap-3 rounded-xl border border-neutral-800 bg-neutral-900 p-3">
<span className="flex h-11 w-11 flex-shrink-0 items-center justify-center overflow-hidden rounded-full bg-neutral-800">
{selectedServer?.icon ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={`https://cdn.discordapp.com/icons/${selectedServer.id}/${selectedServer.icon}.png`}
alt=""
className="h-full w-full object-cover"
/>
) : (
<Server size={20} className="text-neutral-500" aria-hidden />
)}
</span>
<span className="min-w-0">
<span className="block truncate text-sm font-semibold">
{selectedServer?.name ?? "선택 안 됨"}
</span>
<span className="block text-xs text-neutral-500">음악 봇 연결됨</span>
</span>
</div>
<button
onClick={onBackToServers}
className="flex h-11 items-center gap-2 rounded-lg px-3 text-sm text-neutral-300 transition-colors hover:bg-neutral-900 hover:text-white"
>
<ChevronLeft size={18} aria-hidden />
다른 서버 선택
</button>
<div className="mt-auto rounded-xl border border-neutral-800 bg-neutral-900/60 p-3">
<p className="mb-1 flex items-center gap-1.5 text-xs font-semibold text-neutral-300">
<Info size={14} aria-hidden /> 사용 방법
</p>
<p className="text-xs leading-relaxed text-neutral-500">
디스코드 음성 채널에 먼저 들어간 뒤, 위 검색창에서 노래를 찾아 재생 버튼을 누르세요.
</p>
</div>
</aside>
);
}

View File

@@ -7,133 +7,77 @@ import type { DiscordServer } from "@/types/music";
interface TopNavProps {
onSearch: (query: string) => void;
onHome: () => void;
selectedServer: DiscordServer | null;
}
/** 프로필 이미지가 없을 수도 있어(이미지 URL 빈 값) 깨진 아이콘 대신 이니셜을 보여준다. */
function Avatar({
user,
size,
}: {
user: { name?: string | null; image?: string | null };
size: "sm" | "md";
}) {
const box = size === "sm" ? "h-7 w-7 text-xs" : "h-9 w-9 text-sm";
if (user.image) {
return (
// eslint-disable-next-line @next/next/no-img-element
<img src={user.image} alt="" className={`${box} rounded-full object-cover`} />
);
}
return (
<span
className={`${box} flex items-center justify-center rounded-full bg-neutral-700 font-semibold text-white`}
aria-hidden
>
{(user.name ?? "?").trim().charAt(0).toUpperCase()}
</span>
);
selectedServer: DiscordServer | null; // 🌟 추가: 선택된 서버 정보
}
export default function TopNav({ onSearch, onHome, selectedServer }: TopNavProps) {
const { data: session, status } = useSession();
const [term, setTerm] = useState("");
const isAuthed = status === "authenticated";
const canSearch = isAuthed && !!selectedServer;
const submitSearch = () => {
if (canSearch && term.trim()) onSearch(term.trim());
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter") submitSearch();
if (e.key === "Enter" && term.trim()) {
onSearch(term);
}
};
// 🌟 홈 버튼 클릭 시 검색어 초기화 로직 추가
const handleHomeClick = () => {
setTerm("");
onHome();
setTerm(""); // 검색창 비우기
onHome(); // 원래 홈 기능 실행
};
// 상황별로 검색창 안내를 다르게 준다(로그인 전인데 "서버를 고르라"고 하면 혼란스럽다).
const searchPlaceholder = !isAuthed
? "로그인하면 검색할 수 있어요"
: !selectedServer
? "먼저 서버를 선택해주세요"
: "노래 제목이나 유튜브·스포티파이 주소";
return (
<header className="z-20 flex-shrink-0 border-b border-neutral-800 bg-neutral-950">
<nav className="flex h-16 items-center gap-2 px-3 sm:gap-4 sm:px-6">
{/* 로고: 좁은 화면에서는 아이콘만 남겨 검색창 폭을 확보한다. */}
<div className="flex flex-shrink-0 items-center gap-2 text-lg font-bold">
<ListMusic className="text-green-500" aria-hidden />
<span className="hidden sm:inline">MusicBot</span>
</div>
<nav className="h-16 flex-shrink-0 bg-black border-b border-neutral-800 flex items-center justify-between px-6 z-20">
{/* 1. 왼쪽: 로고 */}
<div className="flex items-center gap-2 text-xl font-bold text-white w-52">
<ListMusic className="text-green-500" />
<span>MusicBot</span>
</div>
{isAuthed && (
<button
onClick={handleHomeClick}
className="flex h-11 w-11 flex-shrink-0 items-center justify-center rounded-full text-neutral-400 transition-colors hover:bg-neutral-800 hover:text-white"
aria-label="처음 화면으로"
>
<Home size={20} aria-hidden />
</button>
)}
{/* 2. 가운데: 검색창 & 홈 버튼 */}
<div className="flex-1 max-w-2xl px-4 flex items-center gap-4">
<button
onClick={handleHomeClick} // 🌟 수정된 핸들러 연결
className="p-2 hover:bg-neutral-800 rounded-full transition-colors cursor-pointer text-neutral-400 hover:text-white"
title="홈으로"
>
<Home size={22} />
</button>
{/* 검색: 남는 폭을 모두 차지하게 해서 모바일에서도 쓸 만하게 만든다. */}
<div className="relative min-w-0 flex-1">
<Search
className="pointer-events-none absolute left-3 top-1/2 -translate-y-1/2 text-neutral-500"
size={18}
aria-hidden
/>
<input
type="search"
<div className="relative w-full">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 text-neutral-400" size={18} />
<input
type="text"
value={term}
onChange={(e) => setTerm(e.target.value)}
onKeyDown={handleKeyDown}
disabled={!canSearch}
placeholder={searchPlaceholder}
aria-label="노래 검색"
className="h-11 w-full rounded-full border border-neutral-700 bg-neutral-900 pl-10 pr-4 text-sm text-white placeholder:text-neutral-500 focus:border-green-500 focus:outline-none focus:ring-2 focus:ring-green-500/40 disabled:cursor-not-allowed disabled:opacity-50"
disabled={!selectedServer} // 🌟 서버 미선택 시 입력창 비활성화 (선택 사항)
placeholder={selectedServer ? "노래 검색 후 엔터를 누르세요" : "서버를 먼저 선택해주세요"}
className={`w-full h-10 pl-10 pr-4 rounded-full bg-neutral-800 border border-neutral-700 text-sm text-white focus:outline-none focus:ring-2 focus:ring-white/30 transition-all ${!selectedServer ? 'opacity-50 cursor-not-allowed' : 'opacity-100'}`}
/>
</div>
</div>
{/* 계정 영역 */}
<div className="flex flex-shrink-0 items-center">
{status === "loading" ? (
<div className="h-11 w-11 animate-pulse rounded-full bg-neutral-800" aria-label="로그인 상태 확인 중" />
) : isAuthed && session?.user ? (
<div className="flex items-center gap-1 sm:gap-2">
<span className="hidden items-center gap-2 rounded-full border border-neutral-700 bg-neutral-900 py-1 pl-1 pr-3 md:flex">
<Avatar user={session.user} size="sm" />
<span className="max-w-[10rem] truncate text-sm font-medium">{session.user.name}</span>
</span>
<span className="md:hidden">
<Avatar user={session.user} size="md" />
</span>
<button
onClick={() => signOut()}
className="flex h-11 w-11 items-center justify-center rounded-full text-neutral-400 transition-colors hover:bg-neutral-800 hover:text-red-400"
aria-label="로그아웃"
title="로그아웃"
>
<LogOut size={18} aria-hidden />
</button>
{/* 3. 오른쪽: 유저 프로필 영역 (기존과 동일) */}
<div className="flex items-center justify-end w-auto min-w-[13rem]">
{status === "loading" ? (
<div className="text-sm text-neutral-400">로딩 중...</div>
) : status === "authenticated" && session?.user ? (
<div className="flex items-center gap-3">
<div className="flex items-center gap-2 bg-neutral-800/80 pr-4 pl-1 py-1 rounded-full border border-neutral-700 shadow-sm cursor-default">
<img src={session.user.image || ""} alt="Profile" className="w-7 h-7 rounded-full" />
<span className="text-sm font-medium text-white whitespace-nowrap">{session.user.name}</span>
</div>
) : (
<button
onClick={() => signIn("discord")}
className="flex h-11 items-center gap-2 rounded-full bg-[#5865F2] px-4 text-sm font-medium text-white shadow-md transition-colors hover:bg-[#4752C4] sm:px-5"
>
<LogIn size={16} aria-hidden />
<span className="hidden sm:inline">Discord 로그인</span>
<span className="sm:hidden">로그인</span>
<button onClick={() => signOut()} className="cursor-pointer text-neutral-400 hover:text-red-400 p-2 rounded-full hover:bg-neutral-800 transition-colors">
<LogOut size={18} />
</button>
)}
</div>
</nav>
</header>
</div>
) : (
<button onClick={() => signIn("discord")} className="cursor-pointer flex items-center gap-2 bg-[#5865F2] hover:bg-[#4752C4] text-white px-5 py-2 rounded-full font-medium transition-colors text-sm shadow-md">
<LogIn size={16} /> Discord 로그인
</button>
)}
</div>
</nav>
);
}
}

View File

@@ -1,7 +1,7 @@
"use client";
import { useEffect, useState } from "react";
import { signIn, useSession } from "next-auth/react";
import { Play, ChevronLeft, Server, Music, Loader2, SearchX, MonitorPlay, Disc, ListMusic, LogIn } from "lucide-react";
import { useSession } from "next-auth/react";
import { Play, ChevronLeft, Server, Music, Loader2, SearchX, MonitorPlay, Disc } from "lucide-react";
import { ViewMode } from "@/app/page";
// 🌟 [추가됨] 전역 토스트 훅 불러오기
import { useToast } from "@/components/ToastProvider";
@@ -157,108 +157,67 @@ export default function MainContent({
if (status === "unauthenticated") {
return (
<main className="flex flex-1 flex-col items-center justify-center gap-5 bg-neutral-900 px-6 text-center">
<span className="flex h-16 w-16 items-center justify-center rounded-2xl bg-neutral-800">
<ListMusic size={32} className="text-green-500" aria-hidden />
</span>
<div>
<h2 className="text-2xl font-bold">디스코드로 시작하기</h2>
<p className="mt-2 max-w-sm text-sm leading-relaxed text-neutral-400">
로그인하면 내가 속한 서버 중 음악 봇이 있는 서버가 보이고,
브라우저에서 바로 노래를 검색·재생할 수 있습니다.
</p>
</div>
{/* 안내만 하고 버튼이 없으면 사용자가 우상단을 찾아 헤매게 된다 — 여기서 바로 로그인시킨다. */}
<button
onClick={() => signIn("discord")}
className="flex h-12 items-center gap-2 rounded-full bg-[#5865F2] px-6 font-medium text-white shadow-lg transition hover:bg-[#4752C4] active:scale-95"
>
<LogIn size={18} aria-hidden />
Discord 로그인
</button>
<main className="flex-1 flex flex-col items-center justify-center bg-neutral-900">
<Server size={48} className="text-neutral-500 mb-4" />
<h2 className="text-2xl font-bold">로그인이 필요합니다</h2>
<p className="text-neutral-400">서비스를 이용하시려면 디스코드 로그인을 해주세요.</p>
</main>
);
}
if (status === "loading") {
return (
<main className="flex flex-1 items-center justify-center bg-neutral-900">
<Loader2 className="animate-spin text-neutral-600" size={32} aria-label="불러오는 중" />
</main>
);
}
if (status === "loading") return <main className="flex-1 bg-neutral-900" />;
const hasAnyResults = searchResults.spotify.length > 0 || searchResults.youtubeMusic.length > 0 || searchResults.youtubeVideo.length > 0;
// 카드 전체가 눌리는 버튼이다. 예전에는 hover 시에만 나타나는 작은 아이콘만 눌러야 해서
// 터치 기기(hover 없음)에서는 재생 방법을 찾기 어려웠다.
const renderTrackCard = (track: SearchTrack) => (
<button
key={track.videoId || track.id || track.url || track.title}
type="button"
onClick={() => handleMusicAction('player_play', track)}
aria-label={`${track.title} 재생목록에 추가`}
className="group w-full rounded-xl border border-transparent bg-neutral-800/40 p-3 text-left shadow-md transition-all hover:border-neutral-700 hover:bg-neutral-800 focus:outline-none focus:ring-2 focus:ring-green-500 active:scale-[0.98]"
>
<span className="relative mb-2 block aspect-square overflow-hidden rounded-md bg-neutral-700 shadow-lg">
{track.thumbnail && (
// eslint-disable-next-line @next/next/no-img-element
<img src={track.thumbnail} className="h-full w-full object-cover" alt="" />
)}
{/* 터치 기기에서는 항상 보이고, 마우스 환경에서는 hover 시 강조된다. */}
<span className="absolute bottom-2 right-2 flex h-11 w-11 items-center justify-center rounded-full bg-green-500 shadow-xl transition-all group-hover:bg-green-400 sm:h-10 sm:w-10 sm:opacity-90 sm:group-hover:opacity-100">
<Play fill="black" stroke="black" size={18} aria-hidden />
</span>
</span>
<span className="block truncate text-sm font-medium text-white">{track.title}</span>
<span className="block truncate text-xs text-neutral-400">{track.artist}</span>
</button>
<div key={track.videoId || track.id || track.url || track.title} className="bg-neutral-800/40 p-3 rounded-xl hover:bg-neutral-800 transition-all group border border-transparent hover:border-neutral-700 shadow-md w-full">
<div className="aspect-square bg-neutral-700 rounded-md mb-2 relative overflow-hidden shadow-lg">
{track.thumbnail && <img src={track.thumbnail} className="w-full h-full object-cover" alt={track.title} />}
<button
onClick={(e) => {
e.stopPropagation();
handleMusicAction('player_play', track);
}}
className="absolute right-2 bottom-2 cursor-pointer bg-green-500 hover:bg-green-400 rounded-full p-2 opacity-0 group-hover:opacity-100 transition-all translate-y-2 group-hover:translate-y-0 shadow-xl"
title="바로 재생"
>
<Play fill="black" stroke="black" size={16} />
</button>
</div>
<h3 className="font-medium text-white text-sm truncate">{track.title}</h3>
<p className="text-xs text-neutral-400 truncate">{track.artist}</p>
</div>
);
return (
<main className="flex flex-1 flex-col overflow-y-auto bg-gradient-to-b from-neutral-800/50 to-neutral-900 p-4 pb-28 sm:p-6 lg:p-8">
<main className="flex-1 flex flex-col bg-gradient-to-b from-neutral-800/50 to-neutral-900 overflow-y-auto p-8">
{/* 화면 1: 서버 목록 */}
{viewMode === "SERVER_LIST" && (
<>
<h2 className="mb-1 text-xl font-bold sm:text-2xl">어느 서버에서 들을까요?</h2>
<p className="mb-5 text-sm text-neutral-400">음악 봇이 들어가 있는 서버만 보입니다.</p>
<h2 className="text-2xl font-bold mb-6">접속 중인 서버 선택</h2>
{isFetching && servers.length === 0 ? (
<div className="flex flex-col items-center gap-3 py-20 text-neutral-400">
<Loader2 className="animate-spin text-green-500" size={36} aria-hidden />
<div className="flex flex-col items-center py-20">
<Loader2 className="animate-spin text-green-500 mb-4" size={40} />
<p>서버 목록을 불러오는 중...</p>
</div>
) : servers.length === 0 ? (
<div className="flex flex-col items-center gap-2 py-20 text-center text-neutral-500">
<Server size={40} className="opacity-50" aria-hidden />
<p className="text-sm">표시할 서버가 없습니다.</p>
<p className="max-w-sm text-xs text-neutral-600">
내가 속한 서버 중 음악 봇이 들어가 있는 곳이 없거나, 봇이 아직 준비 중일 수 있습니다.
</p>
</div>
) : (
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 md:grid-cols-4 xl:grid-cols-5">
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5 gap-4">
{servers.map((server) => (
<button
<div
key={server.id}
type="button"
onClick={() => onSelectServer(server)}
className="w-full rounded-xl border border-transparent bg-neutral-800/40 p-3 shadow-md transition-all hover:border-neutral-700 hover:bg-neutral-800 focus:outline-none focus:ring-2 focus:ring-green-500 active:scale-[0.98]"
className="bg-neutral-800/40 p-3 rounded-xl hover:bg-neutral-800 transition-all cursor-pointer group border border-transparent hover:border-neutral-700 shadow-md w-full"
>
<span className="mb-2 flex aspect-square items-center justify-center overflow-hidden rounded-full bg-neutral-700 shadow-lg">
<div className="aspect-square bg-neutral-700 rounded-full mb-2 overflow-hidden shadow-lg flex items-center justify-center">
{server.icon ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={`https://cdn.discordapp.com/icons/${server.id}/${server.icon}.png`}
className="h-full w-full object-cover"
alt=""
/>
<img src={`https://cdn.discordapp.com/icons/${server.id}/${server.icon}.png`} className="w-full h-full object-cover" alt="" />
) : (
<Server size={24} className="text-neutral-500" aria-hidden />
<Server size={24} className="text-neutral-500" />
)}
</span>
<span className="block truncate text-center text-sm font-medium">{server.name}</span>
</button>
</div>
<h3 className="font-medium text-center text-sm truncate">{server.name}</h3>
</div>
))}
</div>
)}
@@ -277,45 +236,29 @@ export default function MainContent({
서버 목록으로 돌아가기
</button>
<div className="mb-6 flex flex-col items-center gap-4 text-center sm:flex-row sm:items-end sm:gap-6 sm:text-left">
<span className="flex h-28 w-28 flex-shrink-0 items-center justify-center overflow-hidden rounded-2xl bg-neutral-800 shadow-2xl sm:h-40 sm:w-40">
<div className="flex items-end gap-6 mb-8">
<div className="w-48 h-48 bg-neutral-800 rounded-2xl shadow-2xl flex items-center justify-center overflow-hidden">
{selectedServer.icon ? (
// eslint-disable-next-line @next/next/no-img-element
<img
src={`https://cdn.discordapp.com/icons/${selectedServer.id}/${selectedServer.icon}.png`}
className="h-full w-full object-cover"
alt=""
/>
) : <Server size={56} className="text-neutral-500" aria-hidden />}
</span>
<div className="min-w-0">
<span className="text-xs font-bold uppercase tracking-wider text-neutral-400">서버 대시보드</span>
<h1 className="mt-1 break-words text-2xl font-black sm:text-4xl lg:text-5xl">{selectedServer.name}</h1>
<p className="mt-2 text-sm text-neutral-400">
위 검색창에서 노래를 찾아 바로 재생할 수 있습니다.
</p>
<img src={`https://cdn.discordapp.com/icons/${selectedServer.id}/${selectedServer.icon}.png`} className="w-full h-full object-cover" alt="" />
) : <Server size={64} className="text-neutral-500" />}
</div>
<div>
<span className="text-sm font-bold uppercase text-neutral-400 tracking-wider">서버 대시보드</span>
<h1 className="text-5xl font-black mt-2 mb-4">{selectedServer.name}</h1>
<p className="text-neutral-400">이 서버에서 음악 봇이 활발하게 작동 중입니다.</p>
</div>
</div>
{/* 무엇을 해야 하는지 알려주는 안내 — 서버만 고르면 다음 행동이 막막했던 문제 보완 */}
<div className="mb-6 rounded-xl border border-green-500/20 bg-green-500/10 p-4">
<p className="text-sm text-green-200">
먼저 디스코드에서 <strong>음성 채널에 입장</strong>한 뒤, 노래를 검색해 재생 버튼을 누르세요.
</p>
</div>
<div className="rounded-xl border border-neutral-800 bg-black/20 p-4 sm:p-6">
<h3 className="mb-4 flex items-center gap-2 text-base font-bold sm:text-lg">
<Music size={20} aria-hidden /> 상세 정보
</h3>
<div className="grid grid-cols-1 gap-3 text-sm sm:grid-cols-2 sm:gap-4">
<div className="rounded-lg border border-white/5 bg-neutral-800/50 p-4">
<p className="mb-1 text-neutral-500">서버 고유 ID</p>
<p className="break-all font-mono text-white">{selectedServer.id}</p>
<div className="bg-black/20 rounded-xl p-6 border border-neutral-800">
<h3 className="text-lg font-bold mb-4 flex items-center gap-2"><Music size={20} /> 상세 정보</h3>
<div className="grid grid-cols-2 gap-4 text-sm">
<div className="bg-neutral-800/50 p-4 rounded-lg border border-white/5">
<p className="text-neutral-500 mb-1">서버 고유 ID</p>
<p className="font-mono text-white">{selectedServer.id}</p>
</div>
<div className="rounded-lg border border-white/5 bg-neutral-800/50 p-4">
<p className="mb-1 text-neutral-500">나의 서버 권한</p>
<p className="font-bold text-green-400">{getPermissionLabel(selectedServer)}</p>
<div className="bg-neutral-800/50 p-4 rounded-lg border border-white/5">
<p className="text-neutral-500 mb-1">나의 서버 권한</p>
<p className="text-green-400 font-bold">{getPermissionLabel(selectedServer)}</p>
</div>
</div>
</div>
@@ -325,8 +268,8 @@ export default function MainContent({
{/* 화면 3: 검색 결과 목록 (3가지 카테고리로 분할) */}
{viewMode === "SEARCH_RESULT" && (
<div>
<h2 className="mb-1 break-words text-xl font-bold sm:text-2xl">&ldquo;{searchQuery}&rdquo; 검색 결과</h2>
<p className="mb-6 text-sm text-neutral-400">곡을 누르면 대기열에 추가됩니다.</p>
<h2 className="text-2xl font-bold mb-2">&ldquo;{searchQuery}&rdquo; 검색 결과</h2>
<p className="text-neutral-400 mb-8 text-sm">입력하신 검색어에 대한 플랫폼별 결과입니다.</p>
{isSearching ? (
<div className="flex flex-col items-center py-20">
@@ -347,7 +290,7 @@ export default function MainContent({
<h3 className="text-xl font-bold mb-4 flex items-center gap-2 text-green-400">
<Disc size={24} /> Spotify 결과
</h3>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 md:grid-cols-4 xl:grid-cols-5">
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5 gap-4">
{searchResults.spotify.map(renderTrackCard)}
</div>
</section>
@@ -359,7 +302,7 @@ export default function MainContent({
<h3 className="text-xl font-bold mb-4 flex items-center gap-2 text-red-500">
<Music size={24} /> YouTube Music
</h3>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 md:grid-cols-4 xl:grid-cols-5">
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5 gap-4">
{searchResults.youtubeMusic.map(renderTrackCard)}
</div>
</section>
@@ -371,7 +314,7 @@ export default function MainContent({
<h3 className="text-xl font-bold mb-4 flex items-center gap-2 text-white">
<MonitorPlay size={24} className="text-red-600" /> YouTube 영상
</h3>
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3 sm:gap-4 md:grid-cols-4 xl:grid-cols-5">
<div className="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 xl:grid-cols-5 gap-4">
{searchResults.youtubeVideo.map(renderTrackCard)}
</div>
</section>

View File

@@ -1,16 +1,14 @@
"use client";
import { useState, useEffect, useCallback, useRef } from "react";
import { SkipForward, SkipBack, Volume2, VolumeX, Pause, Play, ListMusic } from "lucide-react";
import { SkipForward, SkipBack, Volume2, VolumeX, Pause, Play } from "lucide-react";
import { useSession } from "next-auth/react";
import type { DiscordServer, Track } from "@/types/music";
interface PlayerBarProps {
selectedServer: DiscordServer | null;
onToggleQueue?: () => void;
isQueueOpen?: boolean;
}
export default function PlayerBar({ selectedServer, onToggleQueue, isQueueOpen }: PlayerBarProps) {
export default function PlayerBar({ selectedServer }: PlayerBarProps) {
const { data: session } = useSession();
// 재생 상태 관리
@@ -253,179 +251,136 @@ export default function PlayerBar({ selectedServer, onToggleQueue, isQueueOpen }
// 진행도 퍼센트 계산 (0 ~ 100)
const progressPercent = duration > 0 ? (position / duration) * 100 : 0;
const canControl = !!botPlayer && !!isPlaying && !!track;
return (
<footer className="z-50 flex-shrink-0 border-t border-neutral-800 bg-neutral-950">
{/* 모바일: 진행바를 맨 위에 가로로 꽉 채워 터치 영역을 넓게 확보한다. */}
<div className="flex items-center gap-2 px-3 pt-2 text-[11px] tabular-nums text-neutral-400 sm:hidden">
<span className="w-9 text-right">{formatTime(position)}</span>
<div className="group relative flex h-6 flex-1 items-center">
<input
type="range"
min={0}
max={duration || 100}
value={position}
disabled={!canControl}
aria-label="재생 위치"
onChange={(e) => {
isDragging.current = true;
setPosition(Number(e.target.value));
}}
onMouseUp={handleSeekEnd}
onTouchEnd={handleSeekEnd}
className="absolute z-20 h-6 w-full cursor-pointer opacity-0"
/>
<div className="pointer-events-none absolute z-10 h-1.5 w-full overflow-hidden rounded-full bg-neutral-700">
<div className="h-full bg-green-500" style={{ width: `${progressPercent}%` }} />
<footer className="h-24 flex-shrink-0 bg-black border-t border-neutral-800 px-6 flex items-center justify-between z-50">
{/* 1. 노래 정보 영역 */}
<div className="flex items-center gap-4 w-1/4">
{track ? (
<>
<div className="w-14 h-14 bg-neutral-800 rounded-md shadow-md overflow-hidden">
{track.info?.artworkUrl && <img src={track.info.artworkUrl} alt="cover" className="w-full h-full object-cover" />}
</div>
<div className="flex flex-col overflow-hidden">
<span className="text-sm font-bold text-white truncate cursor-pointer hover:underline">{track.info?.title}</span>
<span className="text-xs text-neutral-400 truncate cursor-pointer hover:underline">{track.info?.author?.replace(" - Topic", "")}</span>
</div>
</>
) : (
// 재생 중인 곡이 없을 때 빈 공간
<div className="flex items-center gap-4 text-neutral-600">
<div className="w-14 h-14 bg-neutral-900 rounded-md"></div>
<span className="text-sm">재생 중인 곡 없음</span>
</div>
</div>
<span className="w-9">{formatTime(duration)}</span>
)}
</div>
<div className="flex h-20 items-center justify-between gap-3 px-3 sm:h-24 sm:px-6">
{/* 1. 현재 곡 */}
<div className="flex min-w-0 flex-1 items-center gap-3 sm:w-1/4 sm:flex-none">
<span className="h-12 w-12 flex-shrink-0 overflow-hidden rounded-md bg-neutral-800 sm:h-14 sm:w-14">
{track?.info?.artworkUrl && (
// eslint-disable-next-line @next/next/no-img-element
<img src={track.info.artworkUrl} alt="" className="h-full w-full object-cover" />
)}
</span>
<span className="min-w-0 flex-1">
{track ? (
<>
<span className="block truncate text-sm font-semibold text-white">{track.info?.title}</span>
<span className="block truncate text-xs text-neutral-400">
{track.info?.author?.replace(" - Topic", "")}
</span>
</>
) : (
<>
<span className="block text-sm text-neutral-400">재생 중인 곡 없음</span>
<span className="hidden text-xs text-neutral-600 sm:block">검색해서 노래를 추가해보세요</span>
</>
)}
</span>
{/* 2. 중앙 컨트롤러 영역 */}
<div className="flex flex-col items-center gap-2 w-2/4 max-w-2xl">
<div className="flex items-center gap-6">
{/* 이전 곡 (비활성화 상태) */}
<button className="text-neutral-600 cursor-not-allowed">
<SkipBack size={20} />
</button>
{/* 재생/일시정지 버튼 */}
<button
onClick={handleTogglePause}
disabled={!botPlayer || !isPlaying || !track}
className={`w-8 h-8 rounded-full flex items-center justify-center transition-transform text-black
${track ? 'bg-white hover:scale-105' : 'bg-neutral-700 cursor-not-allowed'}`}
>
{!isPaused ? <Pause size={18} fill="black" /> : <Play size={18} fill="black" className="ml-0.5" />}
</button>
{/* 다음 곡 스킵 버튼 */}
<button
onClick={handleSkip}
disabled={!botPlayer || !isPlaying || !track}
className={`transition-colors ${isPlaying && track ? 'text-neutral-400 hover:text-white' : 'text-neutral-600 cursor-not-allowed'}`}
>
<SkipForward size={20} />
</button>
</div>
{/* 2. 컨트롤 (모바일에서는 버튼만, 진행바는 위쪽에 따로) */}
<div className="flex flex-shrink-0 flex-col items-center gap-1 sm:w-2/4 sm:max-w-2xl sm:flex-1">
<div className="flex items-center gap-1 sm:gap-4">
<button
disabled
title="이전 곡으로 돌아가는 기능은 아직 지원하지 않습니다"
aria-label="이전 곡 (지원 예정)"
className="hidden h-11 w-11 cursor-not-allowed items-center justify-center rounded-full text-neutral-700 sm:flex"
>
<SkipBack size={20} aria-hidden />
</button>
{/* 재생 바 (Range Input으로 구현하여 드래그/클릭 완벽 지원) */}
<div className="flex items-center gap-2 w-full text-xs text-neutral-400">
<span className="w-10 text-right">{formatTime(position)}</span>
<button
onClick={handleTogglePause}
disabled={!canControl}
aria-label={isPaused ? "재생" : "일시정지"}
className={`flex h-12 w-12 items-center justify-center rounded-full text-black transition
${canControl ? "bg-white hover:scale-105 active:scale-95" : "cursor-not-allowed bg-neutral-700 text-neutral-500"}`}
>
{!isPaused ? <Pause size={22} fill="currentColor" aria-hidden /> : <Play size={22} fill="currentColor" className="ml-0.5" aria-hidden />}
</button>
<button
onClick={handleSkip}
disabled={!canControl}
aria-label="다음 곡"
className={`flex h-11 w-11 items-center justify-center rounded-full transition-colors
${canControl ? "text-neutral-300 hover:bg-neutral-800 hover:text-white" : "cursor-not-allowed text-neutral-700"}`}
>
<SkipForward size={20} aria-hidden />
</button>
{/* 모바일 전용: 대기열 토글 */}
{onToggleQueue && (
<button
onClick={onToggleQueue}
aria-label={isQueueOpen ? "대기열 닫기" : "대기열 열기"}
className="flex h-11 w-11 items-center justify-center rounded-full text-neutral-300 transition-colors hover:bg-neutral-800 hover:text-white lg:hidden"
>
<ListMusic size={20} aria-hidden />
</button>
)}
</div>
{/* 데스크톱 진행바 */}
<div className="hidden w-full items-center gap-2 text-xs tabular-nums text-neutral-400 sm:flex">
<span className="w-10 text-right">{formatTime(position)}</span>
<div className="group relative flex h-4 flex-1 items-center">
<input
type="range"
min={0}
max={duration || 100}
value={position}
disabled={!canControl}
aria-label="재생 위치"
onChange={(e) => {
isDragging.current = true;
setPosition(Number(e.target.value));
}}
onMouseUp={handleSeekEnd}
onTouchEnd={handleSeekEnd}
className="absolute z-20 h-4 w-full cursor-pointer opacity-0"
/>
<div className="pointer-events-none absolute z-10 h-1 w-full overflow-hidden rounded-full bg-neutral-700">
<div
className="h-full bg-white transition-colors group-hover:bg-green-500"
style={{ width: `${progressPercent}%` }}
/>
</div>
<div
className="pointer-events-none absolute z-10 -ml-1.5 h-3 w-3 rounded-full bg-white opacity-0 shadow-md group-hover:opacity-100"
style={{ left: `${progressPercent}%` }}
/>
</div>
<span className="w-10">{formatTime(duration)}</span>
</div>
</div>
{/* 3. 볼륨 (좁은 화면에서는 숨긴다 — 기기 자체 볼륨으로 조절 가능) */}
<div className="hidden w-1/4 items-center justify-end gap-2 text-neutral-400 sm:flex">
<span aria-hidden>{volume === 0 ? <VolumeX size={20} /> : <Volume2 size={20} />}</span>
<div className="group relative flex h-8 w-24 items-center">
<div className="flex-1 flex items-center group relative h-4">
<input
type="range"
min={0}
max={100}
value={volume}
disabled={!canControl}
aria-label="볼륨"
aria-valuetext={`${volume}%`}
onChange={handleVolumeChange}
onMouseDown={() => { prevVolumeRef.current = volume; setIsVolumeDragging(true); }}
onTouchStart={() => { prevVolumeRef.current = volume; setIsVolumeDragging(true); }}
onMouseUp={handleVolumeEnd}
onTouchEnd={handleVolumeEnd}
className="absolute z-20 h-8 w-full cursor-pointer opacity-0"
max={duration || 100}
value={position}
disabled={!botPlayer || !isPlaying || !track}
onChange={(e) => {
isDragging.current = true;
setPosition(Number(e.target.value)); // 드래그 중 화면 즉시 업데이트
}}
onMouseUp={handleSeekEnd}
onTouchEnd={handleSeekEnd}
className="absolute w-full h-1 opacity-0 cursor-pointer z-20"
// ↑ 투명한 진짜 input을 덮어씌워서 클릭 이벤트를 완벽하게 받습니다.
/>
<div className="pointer-events-none absolute z-10 h-1 w-full overflow-hidden rounded-full bg-neutral-700">
{/* 시각적으로 보여주는 커스텀 바 */}
<div className="w-full h-1 bg-neutral-600 rounded-full overflow-hidden absolute z-10 pointer-events-none">
<div
className="h-full bg-white transition-colors group-hover:bg-green-500"
style={{ width: `${volume}%` }}
/>
className="h-full bg-white group-hover:bg-green-500 transition-colors pointer-events-none"
style={{ width: `${progressPercent}%` }}
></div>
</div>
{/* 동그란 핸들바 */}
<div
className="pointer-events-none absolute z-10 -ml-1.5 flex h-3 w-3 justify-center rounded-full bg-white opacity-0 shadow-md group-hover:opacity-100"
style={{ left: `${volume}%` }}
>
{isVolumeDragging && (
<span className="absolute bottom-4 whitespace-nowrap rounded border border-neutral-700 bg-neutral-800 px-2 py-1 text-[10px] font-bold text-white shadow-lg">
{volume}
</span>
)}
</div>
className="absolute w-3 h-3 bg-white rounded-full opacity-0 group-hover:opacity-100 shadow-md pointer-events-none z-10 -ml-1.5"
style={{ left: `${progressPercent}%` }}
></div>
</div>
<span className="w-10">{formatTime(duration)}</span>
</div>
</div>
{/* 3. 우측 볼륨 영역 */}
<div className="flex items-center justify-end gap-3 w-1/4 text-neutral-400">
{volume === 0 ? <VolumeX size={20} /> : <Volume2 size={20} />}
<div className="w-24 h-4 flex items-center group relative">
<input
type="range"
min={0}
max={100}
value={volume}
disabled={!botPlayer || !isPlaying || !track}
onChange={handleVolumeChange} // 눈에 보이는 볼륨만 즉시 변경
onMouseDown={() => { prevVolumeRef.current = volume; setIsVolumeDragging(true); }}
onTouchStart={() => { prevVolumeRef.current = volume; setIsVolumeDragging(true); }}
onMouseUp={handleVolumeEnd} // 🌟 마우스를 뗐을 때 봇으로 전송
onTouchEnd={handleVolumeEnd} // 🌟 스마트폰 터치를 뗐을 때 봇으로 전송
className="absolute w-full h-1 opacity-0 cursor-pointer z-20"
/>
{/* 커스텀 볼륨 바 디자인 */}
<div className="w-full h-1 bg-neutral-600 rounded-full overflow-hidden absolute z-10 pointer-events-none">
<div
className="h-full bg-white group-hover:bg-green-500 transition-colors pointer-events-none"
style={{ width: `${volume}%` }}
></div>
</div>
{/* 👇 [수정할 부분] 핸들바 안에 말풍선 툴팁 코드 추가 */}
<div
className="absolute w-3 h-3 bg-white rounded-full opacity-0 group-hover:opacity-100 shadow-md pointer-events-none z-10 -ml-1.5 flex justify-center"
style={{ left: `${volume}%` }}
>
{/* 드래그 중(isVolumeDragging === true)일 때만 나타나는 숫자 말풍선 */}
{isVolumeDragging && (
<div className="absolute bottom-4 bg-neutral-800 text-white text-[10px] font-bold py-1 px-2 rounded shadow-lg border border-neutral-700 whitespace-nowrap animate-in fade-in zoom-in duration-150">
{volume}
</div>
)}
</div>
</div>
</div>
</footer>
);
}

View File

@@ -1,17 +1,18 @@
"use client";
import { useState, useRef, useEffect, useCallback } from "react";
import { Trash2, GripVertical, Music, ChevronUp, ChevronDown } from "lucide-react";
import { Trash2, GripVertical, Music } from "lucide-react";
import { useSession } from "next-auth/react";
import { useToast } from "@/components/ToastProvider";
import type { DiscordServer, Track } from "@/types/music";
interface QueueSidebarProps {
selectedServer: DiscordServer | null;
onClose?: () => void;
}
export default function QueueSidebar({ selectedServer }: QueueSidebarProps) {
const { data: session, status } = useSession();
// 👇 [추가] 토스트 사용 준비 완료!
const { showToast } = useToast();
const [queue, setQueue] = useState<Track[]>([]);
@@ -79,68 +80,66 @@ export default function QueueSidebar({ selectedServer }: QueueSidebarProps) {
};
}, [selectedServer, status, fetchQueue]);
/** 바뀐 순서를 화면에 먼저 반영하고 서버에 보낸다(실패하면 되돌린다). */
const applyReorder = async (newQueue: Track[]) => {
if (!selectedServer) return;
const previous = queue;
// 🌟 [수정됨] 드래그 앤 드롭 정렬 함수
const handleSort = async () => {
const fromIndex = dragItem.current;
const toIndex = dragOverItem.current;
// 1. 마우스를 떼는 즉시 UI 애니메이션을 원래대로 되돌립니다.
setDraggingIndex(null);
setDragOverIndex(null);
dragItem.current = null;
dragOverItem.current = null;
// 드래그 위치가 없거나 서버가 없으면 종료
if (fromIndex === null || toIndex === null || !selectedServer) {
return;
}
// 2. 실제 노래가 삽입될 최종 인덱스 계산
let insertIndex = toIndex;
if (fromIndex < toIndex && toIndex !== queue.length) {
insertIndex = toIndex - 1;
}
// 🌟 [신규 추가] 결과적으로 순서가 바뀌지 않았다면 여기서 바로 함수를 종료합니다! (API 요청 안 함)
if (fromIndex === insertIndex) {
console.log("순서가 변경되지 않아서 통신을 건너뜁니다.");
return;
}
// --- 여기서부터는 진짜 순서가 바뀌었을 때만 실행됩니다 ---
const userId = session?.user?.id;
// 3. 화면 즉시 업데이트
const newQueue = [...queue];
const draggedItem = newQueue.splice(fromIndex, 1)[0];
newQueue.splice(insertIndex, 0, draggedItem);
setQueue(newQueue);
// 4. 서버(API)에 변경된 배열 전송
try {
const res = await fetch('/api/queue/set', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
serverId: selectedServer.id,
userId: session?.user?.id,
newQueue,
userId: userId,
newQueue: newQueue
})
});
const data = await res.json();
if (!res.ok || !data.success) {
showToast(data.message || data.error || "요청 처리 중 문제가 발생했습니다.", "error");
setQueue(previous);
fetchQueue();
fetchQueue(); // 실패 시 원래 큐로 복구
}
} catch (error) {
console.error("순서 동기화 실패:", error);
showToast("순서 변경을 서버에 적용하지 못했습니다.", "error");
setQueue(previous);
fetchQueue();
}
};
const handleSort = async () => {
const fromIndex = dragItem.current;
const toIndex = dragOverItem.current;
setDraggingIndex(null);
setDragOverIndex(null);
dragItem.current = null;
dragOverItem.current = null;
if (fromIndex === null || toIndex === null || !selectedServer) return;
let insertIndex = toIndex;
if (fromIndex < toIndex && toIndex !== queue.length) {
insertIndex = toIndex - 1;
}
if (fromIndex === insertIndex) return; // 순서가 그대로면 통신하지 않는다
const newQueue = [...queue];
const draggedItem = newQueue.splice(fromIndex, 1)[0];
newQueue.splice(insertIndex, 0, draggedItem);
await applyReorder(newQueue);
};
/** 터치 기기에서는 드래그앤드롭이 동작하지 않아, 한 칸씩 옮기는 버튼을 함께 제공한다. */
const moveItem = async (index: number, direction: -1 | 1) => {
const target = index + direction;
if (target < 0 || target >= queue.length) return;
const newQueue = [...queue];
[newQueue[index], newQueue[target]] = [newQueue[target], newQueue[index]];
await applyReorder(newQueue);
};
const handleDelete = async (indexToRemove: number) => {
if (!selectedServer) return;
@@ -172,36 +171,26 @@ export default function QueueSidebar({ selectedServer }: QueueSidebarProps) {
};
return (
<aside className="flex h-full flex-col bg-neutral-950 p-4 lg:border-l lg:border-neutral-800">
<div className="mb-3 flex items-center justify-between gap-2 pr-12 lg:pr-0">
<h2 className="text-base font-bold">다음 재생 목록</h2>
{queue.length > 0 && (
<span className="rounded-full bg-neutral-800 px-2 py-0.5 text-xs text-neutral-300">
{queue.length}곡
</span>
)}
</div>
<aside className="w-80 bg-black p-6 border-l border-neutral-800 flex flex-col">
<h2 className="text-lg font-bold mb-6">현재 재생 목록</h2>
{queue.length === 0 ? (
<div className="flex h-full flex-col items-center justify-center gap-2 px-4 text-center text-neutral-500">
<Music size={32} className="opacity-50" aria-hidden />
<p className="text-sm">대기 중인 노래가 없습니다.</p>
<p className="text-xs text-neutral-600">
검색해서 나온 곡의 재생 버튼을 누르면 여기에 쌓입니다.
</p>
<div className="flex flex-col items-center justify-center text-neutral-500 h-full gap-2">
<Music size={32} className="opacity-50" />
<p className="text-sm">대기열에 노래가 없습니다.</p>
</div>
) : (
<ul className="flex flex-col gap-1 overflow-y-auto pb-24 pr-1">
<div className="flex flex-col overflow-y-auto pr-2 pb-10">
{queue.map((item, index) => {
const isDropTarget = dragOverIndex === index && draggingIndex !== index;
const title = item.info?.title || "제목 없음";
return (
<li
key={(item.encoded as string) || `${index}-${title}`}
<div
key={(item.encoded as string) || `${index}-${item.info?.title || ''}`}
draggable
onDragStart={() => {
dragItem.current = index;
// 🌟 마우스 잔상(고스트)이 까맣게 캡처되는 것을 막기 위한 0초 딜레이 트릭
setTimeout(() => setDraggingIndex(index), 0);
}}
onDragEnter={() => {
@@ -210,81 +199,68 @@ export default function QueueSidebar({ selectedServer }: QueueSidebarProps) {
}}
onDragEnd={handleSort}
onDragOver={(e) => e.preventDefault()}
className={`relative flex items-center gap-2 rounded-lg border border-transparent bg-neutral-900/60 p-2 transition-colors hover:border-neutral-700
${draggingIndex === index ? "opacity-40" : "opacity-100"}
${isDropTarget ? "border-green-500/70" : ""}`}
className={`relative flex items-center gap-3 group bg-neutral-900/50 p-2 rounded-md transition-all duration-200 ease-in-out cursor-grab active:cursor-grabbing border border-transparent hover:border-neutral-700 my-1
${draggingIndex === index ? 'opacity-30 scale-95 shadow-inner' : 'opacity-100'}
${isDropTarget ? 'mt-10' : 'mt-1'}
`}
>
{/* 드래그 핸들: 마우스 환경에서만 의미가 있어 큰 화면에서만 노출 */}
<span className="hidden cursor-grab text-neutral-600 active:cursor-grabbing lg:block" aria-hidden>
{/* 초록색 드롭 인디케이터 선 */}
{isDropTarget && (
<div className="absolute -top-5 left-0 right-0 h-0.5 bg-green-500 rounded-full shadow-[0_0_8px_rgba(34,197,94,0.8)] z-10" />
)}
<div className="text-neutral-600 group-hover:text-neutral-400">
<GripVertical size={16} />
</span>
</div>
<span className="w-4 flex-shrink-0 text-center text-xs tabular-nums text-neutral-500">
{index + 1}
</span>
<span className="h-10 w-10 flex-shrink-0 overflow-hidden rounded bg-neutral-800">
<div className="w-10 h-10 bg-neutral-700 rounded flex-shrink-0 overflow-hidden shadow-md">
{item.info?.artworkUrl ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={item.info.artworkUrl} alt="" className="h-full w-full object-cover" />
<img src={item.info.artworkUrl} alt="" className="w-full h-full object-cover" />
) : null}
</span>
</div>
<span className="min-w-0 flex-1">
<span className="block truncate text-sm font-medium text-white">{title}</span>
<span className="block truncate text-xs text-neutral-400">
<div className="flex flex-col overflow-hidden flex-1 pointer-events-none">
<span className="text-sm font-medium text-white truncate group-hover:text-green-500 transition-colors">
{item.info?.title || "제목 없음"}
</span>
<span className="text-xs text-neutral-400 truncate">
{item.info?.author?.replace(" - Topic", "") || "알 수 없는 아티스트"}
</span>
</span>
</div>
{/* 조작 버튼: hover 로 숨기지 않는다(터치 기기에서는 hover 가 없어 아예 못 쓴다).
순서 이동 버튼은 드래그가 안 되는 좁은 화면에서만 띄워 제목 폭을 확보한다. */}
<span className="flex flex-shrink-0 items-center">
<button
onClick={() => moveItem(index, -1)}
disabled={index === 0}
className="flex h-9 w-8 items-center justify-center rounded text-neutral-500 transition-colors hover:bg-neutral-800 hover:text-white disabled:cursor-not-allowed disabled:opacity-30 lg:hidden"
aria-label={`${title} 위로 옮기기`}
>
<ChevronUp size={16} aria-hidden />
</button>
<button
onClick={() => moveItem(index, 1)}
disabled={index === queue.length - 1}
className="flex h-9 w-8 items-center justify-center rounded text-neutral-500 transition-colors hover:bg-neutral-800 hover:text-white disabled:cursor-not-allowed disabled:opacity-30 lg:hidden"
aria-label={`${title} 아래로 옮기기`}
>
<ChevronDown size={16} aria-hidden />
</button>
<button
onClick={() => handleDelete(index)}
className="flex h-9 w-9 items-center justify-center rounded text-neutral-500 transition-colors hover:bg-neutral-800 hover:text-red-400"
aria-label={`${title} 대기열에서 빼기`}
>
<Trash2 size={16} aria-hidden />
</button>
</span>
</li>
<button
onClick={(e) => {
e.stopPropagation();
handleDelete(index);
}}
className="opacity-0 group-hover:opacity-100 text-neutral-500 hover:text-red-500 transition-all p-1"
title="대기열에서 삭제"
>
<Trash2 size={16} />
</button>
</div>
);
})}
{/* 맨 아래로 드래그해 옮기기 위한 드롭존(마우스 전용) */}
{/* 🌟 [신규 추가] 맨 아래로 드래그하기 위한 전용 투명 드롭존 */}
{draggingIndex !== null && (
<li
<div
onDragEnter={() => {
dragOverItem.current = queue.length;
setDragOverIndex(queue.length);
}}
onDragOver={(e) => e.preventDefault()}
className="hidden h-10 items-center justify-center lg:flex"
className={`relative h-12 flex items-center justify-center transition-all ${dragOverIndex === queue.length ? 'mt-4' : 'mt-0'
}`}
>
{dragOverIndex === queue.length && (
<span className="h-0.5 w-full rounded-full bg-green-500" />
<div className="absolute top-1/2 left-0 right-0 h-0.5 bg-green-500 rounded-full shadow-[0_0_8px_rgba(34,197,94,0.8)] z-10" />
)}
</li>
</div>
)}
</ul>
</div>
)}
</aside>
);
}
}