admin-dance-library.html 20.8 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
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<title>跳舞直播间片库管理</title>
<link rel="stylesheet" href="style.css" />
<style>
  .admin-wrap { padding: 18px 24px; max-width: 1400px; }
  .admin-toolbar { display: flex; gap: 10px; align-items: center; margin-bottom: 14px; flex-wrap: wrap; }
  .admin-toolbar input[type="search"] { flex: 1; min-width: 220px; }
  table.admin-table { width: 100%; border-collapse: collapse; font-size: 13px; background: #fff; }
  table.admin-table th, table.admin-table td { border-bottom: 1px solid var(--border); padding: 8px 10px; text-align: left; vertical-align: top; }
  table.admin-table th { cursor: pointer; user-select: none; color: var(--muted); font-weight: 600; white-space: nowrap; }
  table.admin-table th:hover { color: var(--text); }
  table.admin-table td.name { max-width: 220px; }
  table.admin-table td.prompt { max-width: 360px; color: var(--muted); }
  table.admin-table td input, table.admin-table td textarea { width: 100%; font-size: 12px; }
  table.admin-table td textarea { min-height: 50px; }
  .row-actions { display: flex; gap: 6px; white-space: nowrap; }
  .row-actions button { padding: 3px 8px; font-size: 12px; }
  .video-link { font-size: 12px; word-break: break-all; }
  .add-card { margin-bottom: 16px; }
  .row-4 { display: grid; grid-template-columns: 1fr 1fr 1.6fr 100px; gap: 14px; }
  .sort-arrow { font-size: 10px; }
  .count-hint { color: var(--muted); font-size: 12px; margin-bottom: 10px; }
  td.preview video { display: block; width: 180px; max-height: 200px; background: #000; border-radius: 4px; }
  td.ref-thumb { max-width: 180px; }
  td.ref-thumb img { display: block; width: 90px; height: 90px; object-fit: cover; border-radius: 4px; margin-bottom: 4px; background: #f0f0f0; }
  /* width must stay >=180px: Chrome collapses <video controls> into a bare
     kebab menu (no play button) below ~150px, so a narrower box can't be played */
  td.ref-thumb video { display: block; width: 180px; height: auto; max-height: 240px; object-fit: contain; background: #000; border-radius: 4px; margin-bottom: 4px; }
  td.ref-thumb .ref-name { display: block; font-size: 12px; color: var(--muted); }
  .qc-badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 12px; white-space: nowrap; }
  .qc-pending { background: #f0f0f0; color: var(--muted); }
  .qc-correct { background: #eef7ee; color: #2e7d32; }
  .qc-incorrect { background: #fbeaea; color: #c0392b; }
  tr.qc-incorrect-row { background: #fff6f6; }
  td.qcnote { max-width: 220px; color: var(--muted); }
  .pub-badge { display: inline-block; padding: 2px 8px; border-radius: 4px; font-size: 12px; white-space: nowrap; }
  .pub-on { background: #eef7ee; color: #2e7d32; }
  .pub-off { background: #f0f0f0; color: var(--muted); }
</style>
</head>
<body>
<header class="topbar">
  <h1>跳舞直播间片库管理</h1>
  <div class="spacer"></div>
  <a href="admin.html">视频库</a>
  <a href="admin-characters.html">人物库</a>
  <a href="admin-garments.html">衣服库</a>
  <a href="admin-dance-refs.html">参考跳舞视频库</a>
  <a href="admin-batch-gen.html">批量生成</a>
  <a href="admin-dressgenlist.html">人衣图生成</a>
  <a href="admin-dance-qc.html">质检</a>
  <a href="dance.html" target="_blank">跳舞直播间 ↗</a>
</header>

<main class="admin-wrap">
  <div class="card add-card">
    <div class="field"><label>新增片段(手动指定视频地址)</label></div>
    <div class="row-4">
      <input type="text" id="newPrompt" placeholder="名称(中文)" />
      <input type="text" id="newPromptEn" placeholder="名称(英文,可选)" />
      <input type="text" id="newVideoUrl" placeholder="视频文件地址(可访问的 mp4 URL)" />
      <input type="number" id="newDuration" placeholder="时长(秒)" />
    </div>
    <div class="field" style="margin-top:8px;">
      <textarea id="newFullPrompt" placeholder="完整 prompt(可选,留空则用名称)" style="min-height:60px;"></textarea>
    </div>
    <button id="addBtn" style="margin-top:8px;">新增</button>
    <div id="addError" class="error-box" hidden></div>
  </div>

  <div class="admin-toolbar">
    <input type="search" id="searchInput" placeholder="搜索名称 / prompt / id..." />
    <select id="characterFilter" data-all-label="全部人物"><option value="">全部人物</option></select>
    <select id="garmentFilter" data-all-label="全部衣服"><option value="">全部衣服</option></select>
    <select id="danceRefFilter" data-all-label="全部舞曲"><option value="">全部舞曲</option></select>
    <select id="qcFilter">
      <option value="">全部检查状态</option>
      <option value="pending">待检查</option>
      <option value="correct">正确</option>
      <option value="incorrect">有问题</option>
    </select>
    <select id="publishFilter">
      <option value="">全部上架状态</option>
      <option value="published">已上架</option>
      <option value="unpublished">未上架</option>
    </select>
    <select id="sourceFilter">
      <option value="">全部来源</option>
      <option value="h3console">h3console</option>
      <option value="manual">manual</option>
    </select>
  </div>
  <div class="count-hint" id="countHint"></div>

  <div style="overflow-x:auto;">
    <table class="admin-table">
      <thead>
        <tr>
          <th data-sort="prompt">名称(中)</th>
          <th data-sort="promptEn">名称(英)</th>
          <th data-sort="fullPrompt">Prompt</th>
          <th>视频地址</th>
          <th>预览</th>
          <th>人物</th>
          <th>衣服</th>
          <th>舞曲</th>
          <th>检查状态</th>
          <th>上架状态</th>
          <th>问题说明</th>
          <th data-sort="duration">时长</th>
          <th data-sort="likes">点赞</th>
          <th data-sort="source">来源</th>
          <th data-sort="createdAt">创建时间</th>
          <th data-sort="lastPlayedAt">上次播放</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody id="tbody"></tbody>
    </table>
  </div>
</main>

<script>
// Redirect to login whenever any /api/admin/* call comes back 401 (T6 auth
// gate) — a single interceptor instead of touching every fetch call site.
const _fetch = window.fetch;
window.fetch = async (...args) => {
  const res = await _fetch(...args);
  if (res.status === 401 && String(args[0]).startsWith("/api/admin/") && !String(args[0]).includes("/login")) {
    location.href = "/admin-login.html?next=" + encodeURIComponent(location.pathname);
  }
  return res;
};

let library = [];
let characters = [];
let garments = [];
let danceRefs = [];
let editingId = null;
let sortKey = "createdAt";
let sortDir = -1;

// This page only ever shows/creates channel:"dance" clips — 跳舞直播间
// (dance.html) has its own排播池, independent from 视频直播间(live.html,
// admin.html), same split architecture.md 2.1 describes.
function inChannel(c) {
  return c.channel === "dance";
}

function escapeHtml(s) {
  const div = document.createElement("div");
  div.textContent = s || "";
  return div.innerHTML;
}

async function loadLibrary() {
  const [libRes, charRes, garmentRes, danceRefRes] = await Promise.all([
    fetch("/api/library?sort=newest"),
    fetch("/api/admin/characters"),
    fetch("/api/admin/garments"),
    fetch("/api/admin/dance-refs"),
  ]);
  library = await libRes.json();
  characters = await charRes.json();
  garments = await garmentRes.json();
  danceRefs = await danceRefRes.json();
  refreshFilterOptions();
  render();
}

function nameOf(list, id) {
  if (!id) return null;
  const item = list.find((x) => x.id === id);
  return item ? item.name : id;
}

// 人物/衣服/舞曲 cells: thumbnail (or preview clip) + name, so QC can eyeball
// 原衣服图片+原舞蹈视频+原人物照片 against the generated dance clip in one row.
function characterCell(c) {
  const item = characters.find((x) => x.id === c.characterId);
  if (!item) return "-";
  const img = item.imageUrl ? `<img src="${escapeHtml(item.imageUrl)}" loading="lazy" />` : "";
  return `${img}<span class="ref-name">${escapeHtml(item.name)}</span>`;
}

function garmentCell(c) {
  const item = garments.find((x) => x.id === c.garmentId);
  if (!item) return "-";
  const src = item.thumbnailUrl || item.imageUrl;
  const img = src ? `<img src="${escapeHtml(src)}" loading="lazy" />` : "";
  return `${img}<span class="ref-name">${escapeHtml(item.name)}</span>`;
}

function danceRefCell(c) {
  const item = danceRefs.find((x) => x.id === c.refDanceVideoId);
  if (!item) return "-";
  const video = item.videoUrl ? `<video controls preload="metadata" data-src="${escapeHtml(item.videoUrl)}"></video>` : "";
  return `${video}<span class="ref-name">${escapeHtml(item.name)}</span>`;
}

// Keeps a <select>'s options in sync with whatever (id -> name) pairs
// actually appear in the current channel's rows, without clobbering the
// user's current selection — only used for the three traceability filters.
function populateFilter(selectEl, pairs) {
  const current = selectEl.value;
  const seen = new Map();
  for (const [id, name] of pairs) if (id && !seen.has(id)) seen.set(id, name || id);
  const options = [...seen.entries()].sort((a, b) => a[1].localeCompare(b[1]));
  selectEl.innerHTML = `<option value="">${selectEl.dataset.allLabel}</option>` + options.map(([id, name]) => `<option value="${id}">${escapeHtml(name)}</option>`).join("");
  if (seen.has(current)) selectEl.value = current;
}

function refreshFilterOptions() {
  const rows = library.filter(inChannel);
  populateFilter(
    document.getElementById("characterFilter"),
    rows.map((c) => [c.characterId, nameOf(characters, c.characterId)])
  );
  populateFilter(
    document.getElementById("garmentFilter"),
    rows.map((c) => [c.garmentId, nameOf(garments, c.garmentId)])
  );
  populateFilter(
    document.getElementById("danceRefFilter"),
    rows.map((c) => [c.refDanceVideoId, nameOf(danceRefs, c.refDanceVideoId)])
  );
}

function filteredSorted() {
  const q = document.getElementById("searchInput").value.trim().toLowerCase();
  const source = document.getElementById("sourceFilter").value;
  const characterId = document.getElementById("characterFilter").value;
  const garmentId = document.getElementById("garmentFilter").value;
  const refDanceVideoId = document.getElementById("danceRefFilter").value;
  const qcStatus = document.getElementById("qcFilter").value;
  const publishStatus = document.getElementById("publishFilter").value;
  let rows = library.filter(inChannel);
  if (q) rows = rows.filter((c) => c.prompt.toLowerCase().includes(q) || (c.promptEn || "").toLowerCase().includes(q) || (c.fullPrompt || "").toLowerCase().includes(q) || c.id.toLowerCase().includes(q));
  if (source) rows = rows.filter((c) => c.source === source);
  if (characterId) rows = rows.filter((c) => c.characterId === characterId);
  if (garmentId) rows = rows.filter((c) => c.garmentId === garmentId);
  if (refDanceVideoId) rows = rows.filter((c) => c.refDanceVideoId === refDanceVideoId);
  if (qcStatus) rows = rows.filter((c) => (c.qcStatus || "pending") === qcStatus);
  if (publishStatus) rows = rows.filter((c) => !!c.published === (publishStatus === "published"));
  rows.sort((a, b) => {
    const av = a[sortKey] ?? 0;
    const bv = b[sortKey] ?? 0;
    if (typeof av === "string") return av.localeCompare(bv) * sortDir;
    return (av - bv) * sortDir;
  });
  return rows;
}

function videoHref(c) {
  return `/lib/video/${c.id}`;
}

const QC_LABEL = { pending: "待检查", correct: "正确", incorrect: "有问题" };
function qcBadge(c) {
  const status = c.qcStatus || "pending";
  return `<span class="qc-badge qc-${status}">${QC_LABEL[status]}</span>`;
}

function pubBadge(c) {
  return c.published ? `<span class="pub-badge pub-on">已上架</span>` : `<span class="pub-badge pub-off">未上架</span>`;
}

const previewObserver = new IntersectionObserver(
  (entries) => {
    for (const e of entries) {
      if (!e.isIntersecting) continue;
      e.target.src = e.target.dataset.src;
      previewObserver.unobserve(e.target);
    }
  },
  { rootMargin: "200px" }
);

function render() {
  const rows = filteredSorted();
  document.getElementById("countHint").textContent = `本直播间共 ${library.filter(inChannel).length} 条,当前筛选 ${rows.length} 条`;
  document.querySelectorAll("th[data-sort]").forEach((th) => {
    th.innerHTML = th.textContent.replace(/ ?[▲▼]$/, "") + (th.dataset.sort === sortKey ? ` <span class="sort-arrow">${sortDir === 1 ? "▲" : "▼"}</span>` : "");
  });

  const tbody = document.getElementById("tbody");
  tbody.innerHTML = rows
    .map((c) => {
      const rowClass = (c.qcStatus || "pending") === "incorrect" ? " class=\"qc-incorrect-row\"" : "";
      if (c.id === editingId) {
        return `
        <tr data-id="${c.id}"${rowClass}>
          <td class="name"><input data-field="prompt" value="${escapeHtml(c.prompt)}" /></td>
          <td class="name"><input data-field="promptEn" value="${escapeHtml(c.promptEn || "")}" /></td>
          <td class="prompt"><textarea data-field="fullPrompt">${escapeHtml(c.fullPrompt || "")}</textarea></td>
          <td><input data-field="videoUrl" value="${escapeHtml(c.videoUrl || "")}" placeholder="留空=保持原有播放源" /></td>
          <td class="preview"><video controls preload="metadata" data-src="${videoHref(c)}"></video></td>
          <td class="ref-thumb">${characterCell(c)}</td>
          <td class="ref-thumb">${garmentCell(c)}</td>
          <td class="ref-thumb">${danceRefCell(c)}</td>
          <td>
            <select data-field="qcStatus">
              <option value="pending" ${(c.qcStatus || "pending") === "pending" ? "selected" : ""}>待检查</option>
              <option value="correct" ${c.qcStatus === "correct" ? "selected" : ""}>正确</option>
              <option value="incorrect" ${c.qcStatus === "incorrect" ? "selected" : ""}>有问题</option>
            </select>
          </td>
          <td>
            <select data-field="published">
              <option value="true" ${c.published ? "selected" : ""}>已上架</option>
              <option value="false" ${!c.published ? "selected" : ""}>未上架</option>
            </select>
          </td>
          <td class="qcnote"><textarea data-field="qcNote">${escapeHtml(c.qcNote || "")}</textarea></td>
          <td>${c.duration ?? "-"}s</td>
          <td>${c.likes || 0}</td>
          <td>${c.source}</td>
          <td>${new Date(c.createdAt).toLocaleDateString()}</td>
          <td>${c.lastPlayedAt ? new Date(c.lastPlayedAt).toLocaleString() : "从未"}</td>
          <td class="row-actions">
            <button data-save="${c.id}">保存</button>
            <button class="secondary" data-cancel="1">取消</button>
          </td>
        </tr>`;
      }
      return `
        <tr data-id="${c.id}"${rowClass}>
          <td class="name">${escapeHtml(c.prompt)}</td>
          <td class="name">${escapeHtml(c.promptEn || "")}</td>
          <td class="prompt" title="${escapeHtml(c.fullPrompt || "")}">${escapeHtml((c.fullPrompt || "").slice(0, 80))}${(c.fullPrompt || "").length > 80 ? "…" : ""}</td>
          <td><a class="video-link" href="${videoHref(c)}" target="_blank">${videoHref(c)}</a></td>
          <td class="preview"><video controls preload="metadata" data-src="${videoHref(c)}"></video></td>
          <td class="ref-thumb">${characterCell(c)}</td>
          <td class="ref-thumb">${garmentCell(c)}</td>
          <td class="ref-thumb">${danceRefCell(c)}</td>
          <td>${qcBadge(c)}</td>
          <td>${pubBadge(c)}</td>
          <td class="qcnote" title="${escapeHtml(c.qcNote || "")}">${escapeHtml(c.qcNote || "")}</td>
          <td>${c.duration ?? "-"}s</td>
          <td>${c.likes || 0}</td>
          <td>${c.source}</td>
          <td>${new Date(c.createdAt).toLocaleDateString()}</td>
          <td>${c.lastPlayedAt ? new Date(c.lastPlayedAt).toLocaleString() : "从未"}</td>
          <td class="row-actions">
            <button class="secondary" data-edit="${c.id}">编辑</button>
            <button data-qc-check="${c.id}">AI检查</button>
            <button data-publish-toggle="${c.id}" data-next="${!c.published}">${c.published ? "下架" : "上架"}</button>
            <button class="danger" data-del="${c.id}">删除</button>
          </td>
        </tr>`;
    })
    .join("");

  // Loading preload="metadata" for every row at once would hammer the
  // /lib/video proxy (each clip is a fresh H3 Console fetch); only pull a
  // row's first frame once it's actually scrolled into view.
  tbody.querySelectorAll("td.preview video[data-src], td.ref-thumb video[data-src]").forEach((v) => previewObserver.observe(v));

  tbody.querySelectorAll("[data-edit]").forEach((b) => b.addEventListener("click", () => { editingId = b.dataset.edit; render(); }));
  tbody.querySelectorAll("[data-cancel]").forEach((b) => b.addEventListener("click", () => { editingId = null; render(); }));
  tbody.querySelectorAll("[data-save]").forEach((b) =>
    b.addEventListener("click", async () => {
      const tr = b.closest("tr");
      const body = {};
      tr.querySelectorAll("[data-field]").forEach((el) => (body[el.dataset.field] = el.value));
      const res = await fetch(`/api/admin/library/${b.dataset.save}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(body),
      });
      if (res.ok) {
        editingId = null;
        await loadLibrary();
      }
    })
  );
  tbody.querySelectorAll("[data-del]").forEach((b) =>
    b.addEventListener("click", async () => {
      if (!confirm("确认删除这条片段?(如果来自 H3 Console 会同步从那边删除)")) return;
      const res = await fetch(`/api/admin/library/${b.dataset.del}`, { method: "DELETE" });
      if (res.ok) await loadLibrary();
    })
  );
  tbody.querySelectorAll("[data-publish-toggle]").forEach((b) =>
    b.addEventListener("click", async () => {
      b.disabled = true;
      const res = await fetch(`/api/admin/library/${b.dataset.publishToggle}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ published: b.dataset.next === "true" }),
      });
      if (res.ok) await loadLibrary();
      else b.disabled = false;
    })
  );
  tbody.querySelectorAll("[data-qc-check]").forEach((b) =>
    b.addEventListener("click", async () => {
      const id = b.dataset.qcCheck;
      b.disabled = true;
      b.textContent = "检查中…";
      try {
        const res = await fetch(`/api/admin/library/${id}/qc-check`, { method: "POST" });
        const data = await res.json().catch(() => ({}));
        if (!res.ok) {
          alert(data.error || "检查失败");
          return;
        }
        await loadLibrary();
      } finally {
        b.disabled = false;
        b.textContent = "AI检查";
      }
    })
  );
}

document.querySelectorAll("th[data-sort]").forEach((th) => {
  th.addEventListener("click", () => {
    if (sortKey === th.dataset.sort) sortDir *= -1;
    else {
      sortKey = th.dataset.sort;
      sortDir = -1;
    }
    render();
  });
});

document.getElementById("searchInput").addEventListener("input", render);
document.getElementById("sourceFilter").addEventListener("change", render);
document.getElementById("characterFilter").addEventListener("change", render);
document.getElementById("garmentFilter").addEventListener("change", render);
document.getElementById("danceRefFilter").addEventListener("change", render);
document.getElementById("qcFilter").addEventListener("change", render);
document.getElementById("publishFilter").addEventListener("change", render);

document.getElementById("addBtn").addEventListener("click", async () => {
  const errorBox = document.getElementById("addError");
  errorBox.hidden = true;
  const prompt = document.getElementById("newPrompt").value.trim();
  const promptEn = document.getElementById("newPromptEn").value.trim();
  const videoUrl = document.getElementById("newVideoUrl").value.trim();
  const fullPrompt = document.getElementById("newFullPrompt").value.trim();
  const duration = Number(document.getElementById("newDuration").value) || null;
  if (!prompt || !videoUrl) {
    errorBox.hidden = false;
    errorBox.textContent = "名称和视频地址必填";
    return;
  }
  const res = await fetch("/api/admin/library", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ prompt, promptEn, videoUrl, fullPrompt, duration, channel: "dance" }),
  });
  if (res.ok) {
    document.getElementById("newPrompt").value = "";
    document.getElementById("newPromptEn").value = "";
    document.getElementById("newVideoUrl").value = "";
    document.getElementById("newFullPrompt").value = "";
    document.getElementById("newDuration").value = "";
    await loadLibrary();
  } else {
    errorBox.hidden = false;
    errorBox.textContent = (await res.json()).error || "新增失败";
  }
});

loadLibrary();
</script>
</body>
</html>