dance.html
32.9 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>换装跳舞直播间</title>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Shrikhand&display=swap" />
<link rel="stylesheet" href="live.css" />
<link rel="stylesheet" href="dance.css" />
<style>
.like-btn { margin-top: 6px; font: bold 12px Tahoma, sans-serif; cursor: pointer; border: 3px solid #000; border-radius: 10px; background: #fff; color: var(--ink); padding: 4px 10px; box-shadow: var(--shadow-sm); }
.like-btn:active { transform: translate(2px, 2px); box-shadow: 1px 1px 0 #000; }
.wardrobe-card .meta { font-size: 11px; font-weight: bold; opacity: .6; margin-top: 3px; }
</style>
</head>
<body>
<div class="channel">
<header class="topbar">
<h1 class="logo" id="roomTitle">换装跳舞直播间</h1>
<div class="spacer"></div>
<div class="watching" id="watchingCount" hidden></div>
<button class="topbar-pill" id="muteBtn">🔇 静音</button>
<a class="topbar-pill" id="myWorksLink" href="my-works.html" hidden>📁 我的作品</a>
<button class="topbar-pill" id="topupBtn" hidden>💰 充值</button>
<button class="topbar-pill" id="authBtn">登录</button>
<a class="topbar-pill" href="dance-rooms.html">🏠 直播间列表</a>
<a class="topbar-pill" href="live.html">AI 短剧频道 →</a>
</header>
<div id="topupBanner" hidden></div>
<div class="body" id="body">
<aside class="left-col" id="leftCol">
<div class="wardrobe-tabs" id="wardrobeTabs">
<button data-tab="queue" class="active">待播放</button>
<button data-tab="garment">传衣服</button>
<button data-tab="character">传人</button>
</div>
<div class="clip-list" id="leftPanel"></div>
<div class="site-credit">🍋 <span>换装跳舞直播间</span></div>
</aside>
<div class="player-col">
<div class="player-wrap">
<div class="live-pill" id="liveDot"><span class="dot"></span>直播中</div>
<div class="now-playing-box" id="nowPlayingBox" hidden>
<span class="np-nick" id="nowPlayingNick"></span>
<span class="np-time" id="nowPlayingTime"></span>
<div><button class="like-btn" id="likeBtn" hidden>❤️ <span id="likeCount">0</span></button></div>
</div>
<video id="player" autoplay playsinline></video>
</div>
</div>
<aside class="right-col" id="rightCol">
<div class="section-title">选衣服</div>
<div class="clip-list" id="pickPanel"></div>
</aside>
<div class="mobile-subtabs" id="mobileSubtabs">
<button data-sub="wardrobe" class="active">待播放</button>
<button data-sub="queue">选衣服</button>
</div>
</div>
</div>
<!-- 点击进入蒙版(同 live.html):视频先静音自动播放,这次点击是浏览器要求的
"用户手势",借它把播放切到有声——绕开"未经手势不能自动有声播放"的限制。 -->
<div class="splash" id="splash">
<div class="splash-inner">
<div class="splash-logo">换装跳舞直播间</div>
<div class="splash-play">▶</div>
<div class="splash-sub">AI 生成的换装舞蹈直播<br />点击进入,开声音看直播</div>
<div class="splash-credit">🍋 换装跳舞直播间 出品</div>
</div>
</div>
<!-- 5.1 节:首次进入强制年龄确认,非模态(点背景不关),一次性 cookie 记忆 -->
<div class="nickname-modal" id="ageGateModal" hidden>
<div class="nickname-box age-box">
<div class="nickname-title">进入前确认</div>
<div class="age-disclaimer">
本频道播放 AI 生成的换装舞蹈内容,服饰类别可能包含泳装/舞台表演装等,全部角色与画面均由 AI 生成,不代表真实人物行为。<br /><br />
继续访问即表示您确认已年满 18 周岁。
</div>
<button id="ageConfirmBtn">我已满18岁,继续</button>
</div>
</div>
<div class="nickname-modal" id="nicknameModal" hidden>
<div class="nickname-box">
<div class="nickname-title">先起个昵称才能点赞</div>
<input type="text" id="nicknameInput" placeholder="你的昵称" maxlength="20" />
<button id="nicknameConfirmBtn">确定</button>
</div>
</div>
<!-- 登录完全可选,不阻塞免费模式一的任何现有流程(dev-plan-3.md T22) -->
<div class="nickname-modal" id="authModal" hidden>
<div class="nickname-box">
<div class="nickname-title" id="authTitle">登录</div>
<input type="email" id="authEmail" placeholder="邮箱" />
<input type="password" id="authPassword" placeholder="密码(至少8位)" />
<div class="auth-error" id="authError" hidden></div>
<button id="authSubmitBtn">登录</button>
<button class="auth-link-btn" id="authToggleBtn">没有账号?去注册</button>
<button class="auth-link-btn" id="authCloseBtn">取消</button>
</div>
</div>
<!-- T29: topup tier picker — reuses .nickname-modal/.nickname-box's shell -->
<div class="nickname-modal" id="topupModal" hidden>
<div class="nickname-box">
<div class="nickname-title">充值</div>
<div id="topupTierList"></div>
<button class="auth-link-btn" id="topupCloseBtn">取消</button>
</div>
</div>
<script>
// One live room per character (2026-09): this page is always scoped to one
// characterId from the URL — no characterId means there's no room to show.
const characterId = new URLSearchParams(location.search).get("characterId");
if (!characterId) location.href = "dance-rooms.html";
let wardrobe = [];
let lastState = null; // latest /api/dance/live/state response — the "待播放" left tab renders off this
let leftTab = "queue";
let mobileSub = "wardrobe";
let currentClipId = null;
let statePollTimer = null;
let advanceTimer = null;
let upNextCache = [];
const clientId = Math.random().toString(36).slice(2);
const player = document.getElementById("player");
const leftPanel = document.getElementById("leftPanel");
const pickPanel = document.getElementById("pickPanel");
const roomTitle = document.getElementById("roomTitle");
const nowPlayingBox = document.getElementById("nowPlayingBox");
const nowPlayingNick = document.getElementById("nowPlayingNick");
const nowPlayingTime = document.getElementById("nowPlayingTime");
const likeBtn = document.getElementById("likeBtn");
const likeCount = document.getElementById("likeCount");
const watchingCount = document.getElementById("watchingCount");
const muteBtn = document.getElementById("muteBtn");
const splash = document.getElementById("splash");
const leftCol = document.getElementById("leftCol");
const rightCol = document.getElementById("rightCol");
const mobileSubtabs = document.getElementById("mobileSubtabs");
const ageGateModal = document.getElementById("ageGateModal");
const ageConfirmBtn = document.getElementById("ageConfirmBtn");
const nicknameModal = document.getElementById("nicknameModal");
const nicknameInput = document.getElementById("nicknameInput");
const nicknameConfirmBtn = document.getElementById("nicknameConfirmBtn");
function escapeHtml(s) {
const div = document.createElement("div");
div.textContent = s || "";
return div.innerHTML;
}
function fmtClock(ts) {
return new Date(ts).toLocaleTimeString("zh-CN", { hour: "2-digit", minute: "2-digit" });
}
function getCookie(name) {
const m = document.cookie.match(new RegExp(`(?:^|; )${name}=([^;]*)`));
return m ? decodeURIComponent(m[1]) : null;
}
function setCookie(name, value, days) {
document.cookie = `${name}=${encodeURIComponent(value)}; max-age=${days * 86400}; path=/; samesite=lax`;
}
// ---- 5.1 年龄确认:非模态强制,一次性记忆,不能点背景关闭(没有绑定 backdrop click) ----
if (!getCookie("dance_age_confirmed")) ageGateModal.hidden = false;
ageConfirmBtn.addEventListener("click", () => {
setCookie("dance_age_confirmed", "1", 365);
ageGateModal.hidden = true;
});
// ---- viewer identity: same cookie pair as live.html, only needed to vote ----
function getIdentity() {
const uid = getCookie("viewer_uid");
const nickname = getCookie("viewer_nickname");
return uid && nickname ? { uid, nickname } : null;
}
function openNicknameModal(prefill) {
return new Promise((resolve) => {
nicknameModal.hidden = false;
nicknameInput.value = prefill || "";
nicknameInput.focus();
const onConfirm = () => {
const nickname = nicknameInput.value.trim().slice(0, 20);
if (!nickname) return;
nicknameModal.hidden = true;
nicknameConfirmBtn.removeEventListener("click", onConfirm);
nicknameInput.removeEventListener("keydown", onKeydown);
resolve(nickname);
};
const onKeydown = (e) => {
if (e.key === "Enter") onConfirm();
};
nicknameConfirmBtn.addEventListener("click", onConfirm);
nicknameInput.addEventListener("keydown", onKeydown);
});
}
function ensureIdentity() {
const existing = getIdentity();
if (existing) return Promise.resolve(existing);
return openNicknameModal("").then((nickname) => {
const uid = crypto.randomUUID ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(36).slice(2)}`;
setCookie("viewer_uid", uid, 365);
setCookie("viewer_nickname", nickname, 365);
return { uid, nickname };
});
}
// ---- account login (dev-plan-3.md T19-T22) — entirely optional. Free
// wardrobe picks/voting keep using the plain viewer_uid cookie above
// exactly as before; logging in just also ties that identity to an
// account server-side (T21) and, on login, re-syncs viewer_uid/
// viewer_nickname onto this browser so switching devices or clearing
// cookies doesn't silently start a fresh anonymous identity.
const authBtn = document.getElementById("authBtn");
const topupBtn = document.getElementById("topupBtn");
const myWorksLink = document.getElementById("myWorksLink");
const topupBanner = document.getElementById("topupBanner");
const authModal = document.getElementById("authModal");
const authTitle = document.getElementById("authTitle");
const authEmail = document.getElementById("authEmail");
const authPassword = document.getElementById("authPassword");
const authError = document.getElementById("authError");
const authSubmitBtn = document.getElementById("authSubmitBtn");
const authToggleBtn = document.getElementById("authToggleBtn");
const authCloseBtn = document.getElementById("authCloseBtn");
let authMode = "login";
let currentUser = null; // T28/T29 need to know login/emailVerified/creditBalance beyond just "is authBtn's dot lit"
function renderAuthButton(user) {
currentUser = user;
authBtn.textContent = user ? `${user.nickname || user.email.split("@")[0]} · 💰${user.creditBalance} · 退出` : "登录";
authBtn.dataset.loggedIn = user ? "1" : "";
topupBtn.hidden = !user;
myWorksLink.hidden = !user;
if (leftTab === "garment" || leftTab === "character") renderLeftPanel(); // price/balance-gated panels depend on login state
}
async function refreshAuthState() {
try {
const res = await fetch("/api/auth/me");
if (res.ok) {
renderAuthButton(await res.json());
return;
}
} catch {}
renderAuthButton(null);
}
function openAuthModal(mode) {
authMode = mode;
authTitle.textContent = mode === "login" ? "登录" : "注册";
authSubmitBtn.textContent = mode === "login" ? "登录" : "注册";
authToggleBtn.textContent = mode === "login" ? "没有账号?去注册" : "已有账号?去登录";
authError.hidden = true;
authEmail.value = "";
authPassword.value = "";
authModal.hidden = false;
authEmail.focus();
}
authBtn.addEventListener("click", async () => {
if (authBtn.dataset.loggedIn) {
await fetch("/api/auth/logout", { method: "POST" });
await refreshAuthState();
return;
}
openAuthModal("login");
});
authToggleBtn.addEventListener("click", () => openAuthModal(authMode === "login" ? "register" : "login"));
authCloseBtn.addEventListener("click", () => {
authModal.hidden = true;
});
async function submitAuth() {
const email = authEmail.value.trim();
const password = authPassword.value;
authError.hidden = true;
const res = await fetch(`/api/auth/${authMode}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ email, password }),
});
const body = await res.json().catch(() => ({}));
if (!res.ok) {
authError.textContent = body.error || "出错了,请重试";
authError.hidden = false;
return;
}
authModal.hidden = true;
await refreshAuthState();
}
authSubmitBtn.addEventListener("click", submitAuth);
authPassword.addEventListener("keydown", (e) => {
if (e.key === "Enter") submitAuth();
});
refreshAuthState();
// ---- T29: 积分余额 + 充值 (dev-plan-4.md) ----
let pricing = [];
async function loadPricing() {
try {
pricing = await fetch("/api/pricing").then((r) => r.json());
} catch {
pricing = [];
}
}
const topupModal = document.getElementById("topupModal");
const topupTierList = document.getElementById("topupTierList");
const topupCloseBtn = document.getElementById("topupCloseBtn");
function renderTopupTiers() {
const tiers = pricing.filter((p) => p.kind === "topup_tier");
topupTierList.innerHTML = tiers.length
? tiers
.map(
(t) => `
<div class="topup-tier">
<div><div class="credits">${t.credits} 积分</div>${t.priceCents != null ? `<div class="hint">$${(t.priceCents / 100).toFixed(2)}</div>` : ""}</div>
<button data-tier="${t.key}">购买</button>
</div>`
)
.join("")
: `<div class="empty-hint">暂无可购买档位</div>`;
topupTierList.querySelectorAll("[data-tier]").forEach((btn) =>
btn.addEventListener("click", async () => {
btn.disabled = true;
try {
const res = await fetch("/api/credits/checkout", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ tierKey: btn.dataset.tier }),
});
const data = await res.json();
if (!res.ok) {
alert(data.error || "创建支付会话失败");
return;
}
location.href = data.url; // Stripe's hosted page (real) or the mock completion URL — both redirect back here
} finally {
btn.disabled = false;
}
})
);
}
topupBtn.addEventListener("click", async () => {
if (!currentUser) {
openAuthModal("login");
return;
}
if (!pricing.length) await loadPricing();
renderTopupTiers();
topupModal.hidden = false;
});
topupCloseBtn.addEventListener("click", () => {
topupModal.hidden = true;
});
// A redirect back from Stripe (or the mock checkout) lands here with
// ?topup=success/cancelled — show a one-off banner, then scrub the query
// string so a page refresh doesn't keep re-showing it.
(function showTopupBanner() {
const topup = new URLSearchParams(location.search).get("topup");
if (!topup) return;
topupBanner.hidden = false;
topupBanner.className = topup === "success" ? "topup-banner success" : "topup-banner cancelled";
topupBanner.textContent = topup === "success" ? "充值成功!" : "已取消充值";
history.replaceState(null, "", location.pathname);
})();
loadPricing();
muteBtn.addEventListener("click", () => {
player.muted = !player.muted;
muteBtn.textContent = player.muted ? "🔇 静音" : "🔈 有声";
if (!player.muted) player.play().catch(() => {});
});
// Default to sound on (同 live.html). Chrome/Safari 在没有用户手势前不允许
// 有声自动播放,unmuted play() 被拒绝就退回静音自动播放,再靠下面的点击进入
// 蒙版拿到那次手势,切回有声。
function tryPlay() {
player.play().catch((err) => {
// Only fall back to muted autoplay for an actual autoplay-policy
// rejection. tryPlay() re-runs on every clip switch (every ~10s), and a
// switch mid-load commonly throws AbortError ("interrupted by a new
// load request") — treating that the same as a policy block used to
// silently flip sound back off even after the viewer had explicitly
// unmuted via the splash click or 🔈 button.
if (err && err.name !== "NotAllowedError") return;
player.muted = true;
muteBtn.textContent = "🔇 静音";
player.play().catch(() => {});
});
}
splash.addEventListener("click", () => {
splash.remove();
const desktop = matchMedia("(min-width: 769px)").matches;
player.muted = !desktop; // 手机进入后仍保持静音,同 live.html 的理由
player.play().catch((err) => {
// Same guard as tryPlay(): only a genuine autoplay-policy rejection
// should force muted — this click IS the user gesture, so a rejection
// here is almost always something else (e.g. the clip's src still
// mid-switch from a just-arrived pollState) and shouldn't silently
// override the sound-on choice this click just made.
if (!err || err.name === "NotAllowedError") player.muted = true;
muteBtn.textContent = player.muted ? "🔇 静音" : "🔈 有声";
});
muteBtn.textContent = player.muted ? "🔇 静音" : "🔈 有声";
});
// ---- 左侧栏:待播放 / 传衣服 / 传人 三个 tab ----
function garmentName(id) {
const g = wardrobe.find((x) => x.id === id);
return g ? g.name : id;
}
function garmentImage(id) {
const g = wardrobe.find((x) => x.id === id);
return g ? g.thumbnailUrl || g.imageUrl : null;
}
// "待播放" tab just renders lastState.upNext — same data pollState() already
// has, no separate fetch. Shows the garment's own thumbnail, not just its
// name, same wardrobe-card look as the picker on the right.
function renderQueueTab() {
const upcoming = (lastState && lastState.upNext) || [];
leftPanel.innerHTML = upcoming.length
? `<div class="wardrobe-grid">${upcoming
.map((c) => {
const img = garmentImage(c.garmentId);
return `
<div class="wardrobe-card">
${img ? `<img src="${escapeHtml(img)}" />` : ""}
<div class="name">${escapeHtml(c.prompt || garmentName(c.garmentId))}</div>
${c.requestedBy ? `<div class="meta">by ${escapeHtml(c.requestedBy)}</div>` : ""}
</div>`;
})
.join("")}</div>`
: `<div class="empty-hint">暂无排队,去右边选一件衣服吧</div>`;
}
function renderLeftPanel() {
document.querySelectorAll("#wardrobeTabs button").forEach((b) => b.classList.toggle("active", b.dataset.tab === leftTab));
if (leftTab === "garment") {
renderGarmentUploadPanel();
return;
}
if (leftTab === "character") {
renderCharacterUploadPanel();
return;
}
renderQueueTab();
}
// ---- T28: 模式二"传衣服"(付费,需登录+邮箱验证) ----
function renderGarmentUploadPanel() {
const spendGarment = pricing.find((p) => p.key === "spend_garment");
const priceLine = spendGarment ? `上传一张衣服照片,AI 换装生成跳舞视频,扣 ${spendGarment.credits} 积分` : "加载价格中…";
leftPanel.innerHTML = `
<div class="upload-panel">
<div class="hint">${priceLine}</div>
<input type="file" id="garmentFileInput" accept="image/jpeg,image/png,image/webp" />
<button id="garmentUploadBtn">上传并生成</button>
<div class="upload-error" id="garmentUploadError" hidden></div>
<div class="upload-status" id="garmentUploadStatus" hidden></div>
</div>`;
document.getElementById("garmentUploadBtn").addEventListener("click", submitGarmentUpload);
}
async function submitGarmentUpload() {
const fileInput = document.getElementById("garmentFileInput");
const errorBox = document.getElementById("garmentUploadError");
const statusBox = document.getElementById("garmentUploadStatus");
const btn = document.getElementById("garmentUploadBtn");
errorBox.hidden = true;
statusBox.hidden = true;
// 未登录/未验证先引导,而不是提交后静默失败(T28 验收标准)
if (!currentUser) {
openAuthModal("login");
return;
}
if (!currentUser.emailVerified) {
errorBox.hidden = false;
errorBox.textContent = "请先完成邮箱验证后再上传(查看邮箱中的验证链接)";
return;
}
const file = fileInput.files[0];
if (!file) {
errorBox.hidden = false;
errorBox.textContent = "请先选择一张图片";
return;
}
btn.disabled = true;
statusBox.hidden = false;
statusBox.textContent = "上传中…";
try {
const fd = new FormData();
fd.append("file", file);
fd.append("characterId", characterId);
const res = await fetch("/api/dance/upload-garment", { method: "POST", body: fd });
const data = await res.json().catch(() => ({}));
if (!res.ok) {
statusBox.hidden = true;
errorBox.hidden = false;
if (res.status === 402) {
errorBox.textContent = "积分不足,请先充值";
} else {
errorBox.textContent = data.error || "上传失败";
}
return;
}
const message = data.status === "ready" ? "生成完成,已加入播放队列!" : "生成中,完成后会自动加入播放队列";
// refreshAuthState() re-renders this whole panel (creditBalance changed
// -> renderAuthButton -> renderLeftPanel) — setting the message before
// that would just get wiped by the fresh render, so set it after and
// re-query, not on the (now-replaced) statusBox/fileInput above.
await refreshAuthState();
document.getElementById("garmentFileInput").value = "";
const freshStatusBox = document.getElementById("garmentUploadStatus");
freshStatusBox.hidden = false;
freshStatusBox.textContent = message;
pollState(); // surface the new queue entry immediately, same as pickGarment
} catch {
statusBox.hidden = true;
errorBox.hidden = false;
errorBox.textContent = "网络错误,请重试";
} finally {
btn.disabled = false;
}
}
// ---- T37: 模式三"传人"(付费,需登录+邮箱验证) ----
function renderCharacterUploadPanel() {
const spendCharacter = pricing.find((p) => p.key === "spend_character_per_segment");
const costPerSegment = spendCharacter ? Math.ceil(spendCharacter.credits / (spendCharacter.segmentsPerUnit || 1)) : null;
const priceLine = costPerSegment != null ? `上传一张人物照片,每购买 1 个 10 秒片段扣 ${costPerSegment} 积分——买得越多,这个新角色在直播间露出的时长越长` : "加载价格中…";
const garmentOptions = wardrobe.map((g) => `<option value="${g.id}">${escapeHtml(g.name)}</option>`).join("");
leftPanel.innerHTML = `
<div class="upload-panel">
<div class="hint">${priceLine}</div>
<input type="file" id="characterFileInput" accept="image/jpeg,image/png,image/webp" />
<label class="field-label" for="characterGarmentSelect">搭配衣服(不选则随机搭配)</label>
<select id="characterGarmentSelect">
<option value="">随机搭配</option>
${garmentOptions}
</select>
<label class="field-label" for="characterSegmentsInput">购买片段数(每个 10 秒)</label>
<input type="number" id="characterSegmentsInput" min="1" max="20" value="3" style="width:100%;margin-bottom:10px;" />
<button id="characterUploadBtn">上传并插队播放</button>
<div class="upload-error" id="characterUploadError" hidden></div>
<div class="upload-status" id="characterUploadStatus" hidden></div>
</div>`;
document.getElementById("characterUploadBtn").addEventListener("click", submitCharacterUpload);
}
async function submitCharacterUpload() {
const fileInput = document.getElementById("characterFileInput");
const garmentSelect = document.getElementById("characterGarmentSelect");
const segmentsInput = document.getElementById("characterSegmentsInput");
const errorBox = document.getElementById("characterUploadError");
const statusBox = document.getElementById("characterUploadStatus");
const btn = document.getElementById("characterUploadBtn");
errorBox.hidden = true;
statusBox.hidden = true;
statusBox.classList.remove("boosted");
// 未登录/未验证先引导,而不是提交后静默失败(同 T28 验收标准)
if (!currentUser) {
openAuthModal("login");
return;
}
if (!currentUser.emailVerified) {
errorBox.hidden = false;
errorBox.textContent = "请先完成邮箱验证后再上传(查看邮箱中的验证链接)";
return;
}
const file = fileInput.files[0];
if (!file) {
errorBox.hidden = false;
errorBox.textContent = "请先选择一张人物照片";
return;
}
btn.disabled = true;
statusBox.hidden = false;
statusBox.textContent = "上传中…";
try {
const fd = new FormData();
fd.append("file", file);
if (garmentSelect.value) fd.append("garmentId", garmentSelect.value);
fd.append("segments", segmentsInput.value || "3");
const res = await fetch("/api/dance/upload-character", { method: "POST", body: fd });
const data = await res.json().catch(() => ({}));
if (!res.ok) {
statusBox.hidden = true;
errorBox.hidden = false;
errorBox.textContent = res.status === 402 ? "积分不足,请先充值" : data.error || "上传失败";
return;
}
// This purchase just created a brand-new character, i.e. a brand-new
// room (getDanceRoomCharacterIds: "有视频就自动开间") — send the buyer
// straight there instead of leaving them in this room where their new
// character's clip will never actually appear.
location.href = `dance.html?characterId=${data.characterId}`;
return;
} catch {
statusBox.hidden = true;
errorBox.hidden = false;
errorBox.textContent = "网络错误,请重试";
} finally {
btn.disabled = false;
}
}
document.querySelectorAll("#wardrobeTabs button").forEach((b) =>
b.addEventListener("click", () => {
leftTab = b.dataset.tab;
renderLeftPanel();
})
);
// Wardrobe is scoped to this room and only ever lists garments THIS
// character already has a generated video for (server-side shuffled) — a
// pick here is always a cache hit, never a fresh generation.
async function loadWardrobe() {
const res = await fetch(`/api/dance/wardrobe?characterId=${characterId}`);
wardrobe = await res.json();
renderPickPanel();
}
async function pickGarment(garmentId, card) {
if (card.classList.contains("disabled")) return;
card.classList.add("disabled");
try {
const identity = getIdentity(); // 免费模式一不强制登录(架构文档 2.7 节)— 有 cookie 就带上昵称,没有也能提交
const res = await fetch("/api/dance/pick", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ characterId, garmentId, nickname: identity ? identity.nickname : undefined }),
});
const data = await res.json();
if (!res.ok) {
alert(data.error || "提交失败");
return;
}
pollState();
} finally {
card.classList.remove("disabled");
}
}
// ---- 右侧栏:选衣服(乱序待选列表)+ 生成中/失败(模式二/三上传偶尔会有) ----
function renderPickPanel() {
const queue = (lastState && lastState.queue) || [];
const generating = queue.filter((q) => q.status === "generating");
const failed = queue.filter((q) => q.status === "failed");
const pickHtml = wardrobe.length
? `<div class="wardrobe-grid">${wardrobe
.map(
(g) => `
<div class="wardrobe-card" data-garment="${g.id}">
<img src="${escapeHtml(g.thumbnailUrl || g.imageUrl)}" />
<div class="name">${escapeHtml(g.name)}</div>
</div>`
)
.join("")}</div>`
: `<div class="empty-hint">这个人物还没有可选的衣服</div>`;
const generatingHtml = generating
.map(
(q) => `
<div class="qrow">
<div class="clip-row gen">
<div class="prompt">👗 ${escapeHtml(garmentName(q.garmentId))}</div>
<div class="meta">${q.nickname ? `${escapeHtml(q.nickname)} · ` : ""}生成中…</div>
</div>
<button class="up-btn ${q.voted ? "voted" : ""}" data-vote="${q.id}">▲<span>${q.votes || 0}</span></button>
</div>`
)
.join("");
const failedHtml = failed
.map(
(q) => `
<div class="clip-row failed">
<div class="prompt">👗 ${escapeHtml(garmentName(q.garmentId))}</div>
<div class="meta">${q.nickname ? `${escapeHtml(q.nickname)} · ` : ""}❌ 生成失败</div>
</div>`
)
.join("");
pickPanel.innerHTML =
pickHtml +
(generatingHtml ? `<div class="section-head">生成中(可点赞)</div>${generatingHtml}` : "") +
(failedHtml ? `<div class="section-head">生成失败</div>${failedHtml}` : "");
pickPanel.querySelectorAll("[data-garment]").forEach((card) => card.addEventListener("click", () => pickGarment(card.dataset.garment, card)));
pickPanel.querySelectorAll("[data-vote]").forEach((btn) => btn.addEventListener("click", () => voteQueueItem(btn.dataset.vote, btn)));
}
async function voteQueueItem(id, btn) {
const identity = await ensureIdentity();
btn.disabled = true;
try {
const res = await fetch(`/api/dance/queue/vote/${id}`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ uid: identity.uid }),
});
if (!res.ok) return;
const data = await res.json();
btn.classList.toggle("voted", data.voted);
btn.querySelector("span").textContent = data.votes;
} finally {
btn.disabled = false;
}
}
// ---- 播放器:跟 live.html 一样,服务端 endAt 是权威时钟,轮询只是纠偏 ----
function setNowPlaying(nick, time, clip) {
nowPlayingBox.hidden = false;
nowPlayingNick.hidden = !nick;
nowPlayingNick.textContent = nick || "";
nowPlayingTime.hidden = !time;
nowPlayingTime.textContent = time || "";
likeBtn.hidden = !clip;
if (clip) {
likeCount.textContent = clip.likes || 0;
likeBtn.onclick = async () => {
const res = await fetch(`/api/like/${clip.id}`, { method: "POST" });
if (res.ok) likeCount.textContent = (await res.json()).likes;
};
}
}
// A clip whose /lib/video request errors out (e.g. a transient 401/502 from
// the upstream H3 console) would otherwise just sit there frozen until the
// server-clock advanceTimer eventually fires — skip ahead immediately
// instead of leaving the room looking dead.
player.addEventListener("error", () => {
if (player.currentSrc && currentClipId && player.currentSrc.endsWith(`/lib/video/${currentClipId}`) && upNextCache.length) {
switchToClip(upNextCache[0], 0, upNextCache[0].requestedBy);
}
});
function switchToClip(clip, offsetSec, requestedBy) {
currentClipId = clip.id;
player.src = `/lib/video/${clip.id}`;
if (offsetSec > 0) {
player.addEventListener(
"loadedmetadata",
() => {
player.currentTime = Math.min(offsetSec, player.duration || offsetSec);
},
{ once: true }
);
}
tryPlay();
setNowPlaying(requestedBy, fmtClock(Date.now()), clip);
}
async function pollState() {
try {
const identity = getIdentity();
const res = await fetch(`/api/dance/live/state?characterId=${characterId}&cid=${clientId}${identity ? `&uid=${encodeURIComponent(identity.uid)}` : ""}`);
if (res.status === 400) {
// this character has no room (never had a video, or was removed) —
// nothing to watch here.
location.href = "dance-rooms.html";
return;
}
const state = await res.json();
lastState = state;
watchingCount.hidden = false;
watchingCount.textContent = `👀 ${state.watching}`;
renderPickPanel();
if (leftTab === "queue") renderQueueTab();
upNextCache = state.upNext || [];
clearTimeout(advanceTimer);
if (state.current && state.current.clip) {
if (state.current.clip.id !== currentClipId) {
const offsetSec = Math.max(0, (state.now - state.current.startAt) / 1000);
switchToClip(state.current.clip, offsetSec, state.current.requestedBy);
}
if (upNextCache.length) {
const msUntilEnd = state.current.endAt - Date.now();
advanceTimer = setTimeout(() => switchToClip(upNextCache[0], 0, upNextCache[0].requestedBy), Math.max(0, msUntilEnd));
}
} else if (!currentClipId) {
setNowPlaying("还没有可播放的内容,去右边选一件衣服开播吧", null, null);
}
} catch {
// transient — next poll retries
}
}
async function loadRoomInfo() {
try {
const rooms = await fetch("/api/dance/rooms").then((r) => r.json());
const room = rooms.find((r) => r.id === characterId);
if (room) {
roomTitle.textContent = room.name;
document.title = `${room.name} · 换装跳舞直播间`;
}
} catch {
// cosmetic only — leave the generic title if this fails
}
}
function applyMobileSub() {
leftCol.classList.toggle("mobile-inactive", mobileSub !== "wardrobe");
rightCol.classList.toggle("mobile-inactive", mobileSub !== "queue");
mobileSubtabs.querySelectorAll("button").forEach((b) => b.classList.toggle("active", b.dataset.sub === mobileSub));
}
mobileSubtabs.querySelectorAll("button").forEach((b) =>
b.addEventListener("click", () => {
mobileSub = b.dataset.sub;
applyMobileSub();
})
);
applyMobileSub();
loadRoomInfo();
loadWardrobe();
pollState();
statePollTimer = setInterval(pollState, 4000);
</script>
</body>
</html>