Files
media-parser/templates/components/api_docs.html
T

1218 lines
59 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
{# 统一 API 接入文档与在线调试抽屉 (Stripe / OpenAPI Style Documentation & Drawer) #}
<div class="api-docs-container">
<!-- 纯净文档画布卡片 (Seamless Canvas) -->
<div class="api-docs-canvas">
<!-- 接口核心 Hero 头部 -->
<div class="api-endpoint-hero">
<div class="api-hero-main-row">
<div class="api-hero-endpoint">
<span class="api-hero-method">GET</span>
<code class="api-hero-path" id="api-hero-full-path">/api/v1/parse</code>
</div>
<div class="api-hero-actions">
<button type="button" class="btn btn-primary" onclick="openPlaygroundDrawer()" style="display:inline-flex;align-items:center;gap:6px;box-shadow:var(--shadow-sm)">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
<span>在线接口调试</span>
</button>
</div>
</div>
</div>
<!-- 正文阅读流与固定目录布局 (Layout: Article + Sticky TOC) -->
<div class="api-doc-layout">
<article class="api-doc-article">
<!-- 1. 鉴权机制 -->
<section id="sec-auth" class="api-doc-section">
<h2 class="doc-section-title">1. 接口鉴权机制</h2>
<p class="doc-p">
解析接口调用必须携带有效的 API Key 凭证。为了避免访问日志或浏览器记录泄露密钥,<strong>强烈推荐使用标准 HTTP Header 鉴权方式</strong>。
</p>
<div class="doc-flat-table-wrap">
<table class="doc-flat-table">
<thead>
<tr>
<th style="width:220px">鉴权模式</th>
<th style="width:140px">传递位置</th>
<th>语法示例与说明</th>
</tr>
</thead>
<tbody>
<tr>
<td><strong>请求头鉴权 (Bearer)</strong> <span class="param-rec">推荐</span></td>
<td>HTTP Header</td>
<td><code>Authorization: Bearer &lt;API_KEY&gt;</code></td>
</tr>
<tr>
<td><strong>URL 参数鉴权 (Key)</strong> <span class="param-opt">可选</span></td>
<td>URL Query</td>
<td><code>?key=&lt;API_KEY&gt;</code></td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- 2. 请求参数规范 -->
<section id="sec-params" class="api-doc-section">
<h2 class="doc-section-title">2. 请求参数规范</h2>
<p class="doc-p">接口采用 HTTP GET 方法请求,参数如下:</p>
<div class="doc-flat-table-wrap">
<table class="doc-flat-table">
<thead>
<tr>
<th style="width:150px">参数名</th>
<th style="width:90px">位置</th>
<th style="width:90px">类型</th>
<th style="width:80px">必选</th>
<th>说明与约束</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>url</code></td>
<td>Query</td>
<td>String</td>
<td><span class="param-req">必选</span></td>
<td>目标分享链接或包含分享文本的字符串(系统将自动提取文本中包含的 http/https 链接,长度限 2000 字符内)。</td>
</tr>
<tr>
<td><code>Authorization</code></td>
<td>Header</td>
<td>String</td>
<td><span class="param-rec">推荐</span></td>
<td>标准 Bearer 授权凭据。格式:<code>Bearer mp_xxxxxxxxxxxx</code></td>
</tr>
<tr>
<td><code>key</code></td>
<td>Query</td>
<td>String</td>
<td><span class="param-opt">可选</span></td>
<td>当未携带 Authorization Header 时的兼容授权参数。</td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- 3. 返回数据字典 -->
<section id="sec-schema" class="api-doc-section">
<h2 class="doc-section-title">3. 返回 JSON 数据字典</h2>
<p class="doc-p">所有接口返回标准的 JSON 结构,包含全局状态标识与媒体详情数据:</p>
<div class="doc-subtitle">3.1 基础返回格式</div>
<div class="doc-flat-table-wrap">
<table class="doc-flat-table">
<thead>
<tr>
<th style="width:140px">字段名</th>
<th style="width:130px">类型</th>
<th>业务含义</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>succ</code></td>
<td>Boolean</td>
<td>请求是否成功:<code>true</code> 成功;<code>false</code> 失败。</td>
</tr>
<tr>
<td><code>code</code></td>
<td>Integer / String</td>
<td>状态码。成功时固定为 <code>200</code>,失败时为对应错误标识。</td>
</tr>
<tr>
<td><code>message</code></td>
<td>String</td>
<td>提示信息或异常错误原因。</td>
</tr>
<tr>
<td><code>data</code></td>
<td>Object</td>
<td>解析成功返回的媒体实体数据对象。</td>
</tr>
</tbody>
</table>
</div>
<div class="doc-subtitle">3.2 媒体数据主体 (data 字段)</div>
<div class="doc-flat-table-wrap">
<table class="doc-flat-table">
<thead>
<tr>
<th style="width:150px">字段名</th>
<th style="width:130px">类型</th>
<th>说明与数据含义</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>platform</code></td>
<td>String</td>
<td>自动识别出的平台名称(如:<code>抖音</code>、<code>哔哩哔哩</code>、<code>快手</code>、<code>小红书</code> 等)。</td>
</tr>
<tr>
<td><code>video_id</code></td>
<td>String</td>
<td>源平台作品的全局唯一 ID。</td>
</tr>
<tr>
<td><code>title</code></td>
<td>String</td>
<td>作品标题或文案摘要。</td>
</tr>
<tr>
<td><code>desc</code></td>
<td>String</td>
<td>作品完整文本描述。</td>
</tr>
<tr>
<td><code>cover_url</code></td>
<td>String</td>
<td>作品高清主封面图 HTTPS 直链。</td>
</tr>
<tr>
<td><code>video_url</code></td>
<td>String</td>
<td>无水印视频 MP4 直链(纯图集作品时为空字符串)。</td>
</tr>
<tr>
<td><code>video_list</code></td>
<td>Array</td>
<td>可选。包含多清晰度(1080P/720P)或备用播放源直链数组。</td>
</tr>
<tr>
<td><code>image_list</code></td>
<td>Array</td>
<td>高清图集直链数组(支持 LivePhoto 动态图片)。</td>
</tr>
<tr>
<td><code>audio_url</code></td>
<td>String</td>
<td>提取出的背景音乐或纯音频直链(MP3 / M4A)。</td>
</tr>
<tr>
<td><code>author</code></td>
<td>Object</td>
<td>创作者信息对象:<code>{ "name": "作者名", "avatar": "头像URL", "uid": "ID" }</code></td>
</tr>
</tbody>
</table>
</div>
</section>
<!-- 4. 多语言代码集成 -->
<section id="sec-snippets" class="api-doc-section">
<h2 class="doc-section-title">4. 多语言对接代码示例</h2>
<p class="doc-p">一键复制并直接集成至您的客户端或服务端项目中:</p>
<div class="doc-code-card">
<div class="doc-code-header">
<div class="doc-code-header-left">
<div class="terminal-dots">
<span class="dot red"></span>
<span class="dot yellow"></span>
<span class="dot green"></span>
</div>
<div class="doc-code-tabs">
<button type="button" class="doc-code-tab active" data-lang="curl" onclick="switchSnippetTab('curl')">cURL</button>
<button type="button" class="doc-code-tab" data-lang="python" onclick="switchSnippetTab('python')">Python</button>
<button type="button" class="doc-code-tab" data-lang="js" onclick="switchSnippetTab('js')">Node.js</button>
<button type="button" class="doc-code-tab" data-lang="go" onclick="switchSnippetTab('go')">Go</button>
<button type="button" class="doc-code-tab" data-lang="php" onclick="switchSnippetTab('php')">PHP</button>
<button type="button" class="doc-code-tab" data-lang="java" onclick="switchSnippetTab('java')">Java</button>
</div>
</div>
<button type="button" class="doc-code-copy-btn" onclick="copyActiveCodeSnippet()" title="复制代码">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
<span id="copy-snippet-btn-text">复制代码</span>
</button>
</div>
<pre id="snippet-code-display" class="doc-code-pre custom-scroll"></pre>
</div>
</section>
<!-- 5. 错误码与排障指南 -->
<section id="sec-errors" class="api-doc-section">
<h2 class="doc-section-title">5. 标准错误码与排错指南</h2>
<p class="doc-p">当请求处理发生异常时,接口返回 <code>{"succ": false, "code": "...", "message": "..."}</code>:</p>
<div class="doc-flat-table-wrap">
<table class="doc-flat-table">
<thead>
<tr>
<th style="width:80px">HTTP</th>
<th style="width:190px">错误标识 (Code)</th>
<th>原因分析与排查指引</th>
</tr>
</thead>
<tbody>
<tr>
<td><span class="badge" style="background:#fef2f2;color:#b91c1c;border-color:#fecaca">400</span></td>
<td><code>INVALID_TEXT</code></td>
<td>请求 URL 参数为空,或文案长度超过了 2000 个字符限制。</td>
</tr>
<tr>
<td><span class="badge" style="background:#fef2f2;color:#b91c1c;border-color:#fecaca">400</span></td>
<td><code>URL_NOT_FOUND</code></td>
<td>文本中未提取到合法的 http/https 链接,请检查分享文本是否完整。</td>
</tr>
<tr>
<td><span class="badge" style="background:#fef2f2;color:#b91c1c;border-color:#fecaca">400</span></td>
<td><code>PLATFORM_NOT_SUPPORTED</code></td>
<td>目标平台域名不在支持列表中,或属于仅好友可见的私密作品。</td>
</tr>
<tr>
<td><span class="badge" style="background:#fef2f2;color:#b91c1c;border-color:#fecaca">400</span></td>
<td><code>MEDIA_NOT_FOUND</code></td>
<td>源视频已被创作者删除、设为私密,或触发了平台风控验证。</td>
</tr>
<tr>
<td><span class="badge" style="background:#fef2f2;color:#b91c1c;border-color:#fecaca">400</span></td>
<td><code>COOKIE_REQUIRED</code></td>
<td>目标平台需要服务端 Cookie。请在管理后台「系统设置 - Cookie管理」中配置有效凭据。</td>
</tr>
<tr>
<td><span class="badge" style="background:#fff7ed;color:#c2410c;border-color:#fed7aa">401</span></td>
<td><code>INVALID_KEY</code></td>
<td>未提供 API Key,或 Key 已被禁用、删除。</td>
</tr>
<tr>
<td><span class="badge" style="background:#fff7ed;color:#c2410c;border-color:#fed7aa">401</span></td>
<td><code>EXPIRED_USER</code></td>
<td>账号使用期限已到期,请联系管理员续期。</td>
</tr>
<tr>
<td><span class="badge" style="background:#fff7ed;color:#c2410c;border-color:#fed7aa">402</span></td>
<td><code>INSUFFICIENT_CREDITS</code></td>
<td>账号可用点数已耗尽(剩余 0 点),请充值或调整额度。</td>
</tr>
<tr>
<td><span class="badge" style="background:#fefce8;color:#a16207;border-color:#fef08a">429</span></td>
<td><code>RATE_LIMITED</code></td>
<td>超出并发 QPS 阈值,请在客户端增加重试与指数退避。</td>
</tr>
<tr>
<td><span class="badge" style="background:#f1f5f9;color:#475569;border-color:#cbd5e1">503</span></td>
<td><code>API_DISABLED</code></td>
<td>系统全局 API 服务被超级管理员临时维护关闭。</td>
</tr>
</tbody>
</table>
</div>
</section>
</article>
<!-- 右侧粘性固定目录 (本页目录) -->
<aside class="api-doc-toc-wrap">
<div class="api-doc-toc">
<div class="toc-title">本页目录</div>
<nav class="toc-list">
<a href="#sec-auth" class="toc-item active" onclick="smoothScrollToDocs('sec-auth');return false;">接口鉴权机制</a>
<a href="#sec-params" class="toc-item" onclick="smoothScrollToDocs('sec-params');return false;">请求参数规范</a>
<a href="#sec-schema" class="toc-item" onclick="smoothScrollToDocs('sec-schema');return false;">返回数据字典</a>
<a href="#sec-snippets" class="toc-item" onclick="smoothScrollToDocs('sec-snippets');return false;">多语言对接代码</a>
<a href="#sec-errors" class="toc-item" onclick="smoothScrollToDocs('sec-errors');return false;">错误码与排障</a>
</nav>
</div>
</aside>
</div>
</div>
</div>
<!-- ==========================================================================
Slide-over 侧滑调试抽屉 (Drawer)
========================================================================== -->
<div id="api-drawer-backdrop" class="api-drawer-backdrop" onclick="closePlaygroundDrawer()"></div>
<div id="api-drawer" class="api-drawer" role="dialog" aria-modal="true" aria-labelledby="drawer-title">
<div class="api-drawer-header">
<div class="row" style="gap:8px;align-items:center">
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" style="color:var(--brand)"><polygon points="5 3 19 12 5 21 5 3"/></svg>
<h3 class="api-drawer-title" id="drawer-title">在线接口调试</h3>
</div>
<button type="button" class="api-drawer-close" onclick="closePlaygroundDrawer()" aria-label="关闭抽屉">&times;</button>
</div>
<div class="api-drawer-body">
<form id="api-playground-form" onsubmit="executePlaygroundRequest(event)">
<!-- 待解析链接输入 -->
<div style="margin-bottom:14px">
<div class="pg-section-label">
<span>待解析链接 / 分享文案 <span style="color:#ef4444">*</span></span>
</div>
<textarea id="pg-target-url" class="pg-input" rows="4"
placeholder="粘贴目标作品分享链接或文案 (例如 https://v.douyin.com/...)"
required autocomplete="off" oninput="syncCodeSnippets()"></textarea>
</div>
<!-- 密钥凭证 -->
<div style="margin-bottom:14px">
<div class="pg-section-label">
<span>API Key 凭据</span>
<a href="{{ url_for('admin.keys') if g.user and g.user['role'] == 'admin' else url_for('portal.keys') }}" class="muted" style="font-size:11.5px;text-decoration:underline">前往密钥管理 ↗</a>
</div>
<div class="pg-key-input-wrap">
{% set available_keys = my_keys or (keys if g.user and g.user['role'] != 'admin' else []) %}
{% set first_key = available_keys[0] if available_keys and available_keys|length > 0 else None %}
{% set has_initial_key = (not new_api_key and first_key) %}
<div class="pg-key-input-box" id="pg-key-input-box" onclick="focusApiKeyInput(event)">
<div id="pg-selected-key-chip" class="pg-selected-key-chip" style="{% if not has_initial_key %}display:none{% endif %}" data-val="{{ first_key['key_prefix'] ~ '...' if first_key else '' }}">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="color:var(--brand);flex-shrink:0"><circle cx="7.5" cy="15.5" r="5.5"/><path d="m21 2-9.6 9.6"/><path d="m15.5 7.5 3 3L22 7l-3-3"/></svg>
<span id="pg-key-chip-name" class="key-chip-name">{{ first_key['name'] if first_key else '密钥' }}</span>
<span id="pg-key-chip-prefix" class="key-chip-prefix">({{ first_key['key_prefix'] ~ '...' if first_key else '' }})</span>
<button type="button" class="key-chip-remove" onclick="clearSelectedKey(event)" title="移除此 Key" aria-label="移除">&times;</button>
</div>
<input type="text" id="pg-api-key" class="pg-input-field"
placeholder="请输入或选择 API Key"
value="{% if not has_initial_key %}{{ new_api_key or '' }}{% endif %}"
style="{% if has_initial_key %}display:none{% endif %}"
autocomplete="off"
oninput="handleManualKeyInput()"
onkeydown="handleKeyInputKeydown(event)">
</div>
<!-- Custom Dropdown Component for Playground Key Selection -->
<div class="pg-key-dropdown-wrap" id="pg-key-dropdown-wrap">
<button type="button" class="pg-key-dropdown-trigger" id="pg-key-dropdown-btn" onclick="togglePgKeyDropdown(event)" title="选择已有 Key 或前往创建">
<span id="pg-key-dropdown-label">{{ first_key['name'] if has_initial_key else '选择 Key' }}</span>
<svg class="pg-key-dropdown-chevron" width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round">
<polyline points="6 9 12 15 18 9"></polyline>
</svg>
</button>
<div class="pg-key-dropdown-menu" id="pg-key-dropdown-menu">
<button type="button" class="pg-key-menu-item {% if not has_initial_key and not new_api_key %}active{% endif %}" data-val="" onclick="handlePgKeyItemSelect('', '手动输入')">
<span class="pg-key-item-title">未选择 Key</span>
<svg class="pg-key-item-check" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>
</button>
{% if available_keys and available_keys|length > 0 %}
{% for k in available_keys %}
{% set is_selected = (new_api_key and k['key_prefix'] in new_api_key) or (not new_api_key and loop.first) %}
<button type="button" class="pg-key-menu-item {% if is_selected %}active{% endif %}" data-val="{{ k['key_prefix'] }}..." data-name="{{ k['name'] or '密钥' }}" onclick="handlePgKeyItemSelect('{{ k['key_prefix'] }}...', '{{ k['name'] or '密钥' }}')">
<span class="pg-key-item-title">{{ k['name'] or '密钥' }}</span>
<svg class="pg-key-item-check" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5"><polyline points="20 6 9 17 4 12"/></svg>
</button>
{% endfor %}
<div class="pg-key-menu-divider"></div>
<button type="button" class="pg-key-menu-item action-create" onclick="handlePgKeyActionCreate()">
<span>+ 创建新 Key / 管理密钥 ↗</span>
</button>
{% else %}
<div class="pg-key-menu-divider"></div>
<button type="button" class="pg-key-menu-item action-create" onclick="handlePgKeyActionCreate()">
<span>+ 暂无 Key,点击前往创建 ↗</span>
</button>
{% endif %}
</div>
</div>
</div>
</div>
<!-- 传参模式与操作按钮 -->
<div class="row between" style="align-items:center;flex-wrap:wrap;gap:10px;margin-bottom:8px">
<div class="pg-mode-toggle">
<label id="lbl-auth-header" class="active">
<input type="radio" name="pg-auth-type" value="header" checked onchange="updateAuthToggleUI('header')">
<span>Header 模式</span>
</label>
<label id="lbl-auth-query">
<input type="radio" name="pg-auth-type" value="query" onchange="updateAuthToggleUI('query')">
<span>Query 模式</span>
</label>
</div>
<div class="row" style="gap:6px">
<button type="button" class="btn btn-secondary btn-sm" onclick="resetPlayground()" title="清空并重置">重置</button>
<button type="submit" id="pg-submit-btn" class="btn btn-primary btn-sm" style="min-width:115px;display:inline-flex;align-items:center;justify-content:center;gap:5px">
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polygon points="5 3 19 12 5 21 5 3"/></svg>
<span id="pg-btn-text">发送测试</span>
</button>
</div>
</div>
</form>
<!-- 调试响应结果容器 -->
<div id="pg-result-container" class="pg-result-wrapper" style="display:none">
<div class="pg-result-header" style="margin-bottom:10px">
<div class="row" style="gap:8px;align-items:center">
<span id="pg-res-status" class="status-pill online">--</span>
<span id="pg-res-time" class="muted" style="font-size:11.5px">-- ms</span>
</div>
</div>
<!-- 智能情境错误排错引导 (In-context Error Alert) -->
<div id="pg-context-alert" class="pg-context-alert warning" style="display:none">
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="12" y1="8" x2="12" y2="12"/><line x1="12" y1="16" x2="12.01" y2="16"/></svg>
<div id="pg-context-alert-text"></div>
</div>
<!-- 黑色终端响应代码卡片 -->
<div class="doc-code-card" style="margin-top:0">
<div class="doc-code-header">
<div class="doc-code-header-left">
<div class="terminal-dots">
<span class="dot red"></span>
<span class="dot yellow"></span>
<span class="dot green"></span>
</div>
<span style="font-size:11.5px;color:#94a3b8;font-family:ui-monospace,monospace">Response JSON</span>
</div>
<button type="button" id="pg-copy-btn" class="doc-code-copy-btn" onclick="copyPlaygroundJson()">
<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/></svg>
<span id="pg-copy-btn-text">复制 JSON</span>
</button>
</div>
<pre id="pg-res-json" class="doc-code-pre custom-scroll" style="max-height:360px;font-size:12.5px;line-height:1.6"></pre>
</div>
</div>
</div>
</div>
<!-- 交互脚本与智能排障字典 -->
<script>
(function() {
let currentLang = 'curl';
// 智能排障建议字典 (In-context Error Help)
const ERROR_TIPS = {
'COOKIE_REQUIRED': '💡 排查建议:该平台(如小红书、拼多多、微信)需要有效登录凭证。请在「系统设置 - Cookie管理」中配置有效 Cookie。',
'INSUFFICIENT_CREDITS': '💡 排查建议:当前账号可用点数已耗尽(剩余 0 点)。请联系系统管理员充值点数或修改额度。',
'EXPIRED_USER': '💡 排查建议:您的账号使用期限已到期。请联系系统超级管理员进行账号延期。',
'ACCOUNT_EXPIRED': '💡 排查建议:您的账号尚未开通或已到期。请联系系统超级管理员进行账号延期。',
'INVALID_KEY': '💡 排查建议:API Key 无效、已被删除或填入了脱敏前缀。出于安全,数据库仅加密存储,请填入创建时保存的完整 32 位 Key。',
'INVALID_API_KEY': '💡 排查建议:API Key 无效或填入了脱敏前缀(含 ...)。出于安全考虑,数据库仅加密存储哈希,无法还原完整明文,请直接粘贴创建密钥时保存的完整 32 位 API Key。',
'API_KEY_REQUIRED': '💡 排查建议:未提供 API Key,请在输入框填入有效的 32 位 API Key。',
'API_KEY_DISABLED': '💡 排查建议:该 API Key 或当前账号已被停用。',
'RATE_LIMITED': '💡 排查建议:超出并发 QPS 阈值。请在客户端降低请求并发度,并添加指数退避重试逻辑。',
'PLATFORM_NOT_SUPPORTED': '💡 排查建议:目标链接所属平台尚未受支持,或属于仅好友可见的私密分享作品。',
'MEDIA_NOT_FOUND': '💡 排查建议:源视频已被删除、作者隐藏,或源平台触发了滑块风控验证。',
'URL_NOT_FOUND': '💡 排查建议:未能在输入文本中检测到合法 http/https 链接,请检查文本是否粘贴完整。',
'INVALID_TEXT': '💡 排查建议:待解析链接内容为空,或文案长度超过了 2000 个字符限制。',
'API_DISABLED': '💡 排查建议:系统全局 API 目前处于维护关闭状态,请稍后再试或联系管理员。'
};
window.openPlaygroundDrawer = function() {
const drawer = document.getElementById('api-drawer');
const backdrop = document.getElementById('api-drawer-backdrop');
if (drawer && backdrop) {
drawer.classList.add('open');
backdrop.classList.add('open');
document.body.style.overflow = 'hidden';
const input = document.getElementById('pg-target-url');
if (input) setTimeout(() => input.focus(), 150);
}
};
window.closePlaygroundDrawer = function() {
const drawer = document.getElementById('api-drawer');
const backdrop = document.getElementById('api-drawer-backdrop');
if (drawer && backdrop) {
drawer.classList.remove('open');
backdrop.classList.remove('open');
document.body.style.overflow = '';
}
};
// ESC 键关闭抽屉
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
closePlaygroundDrawer();
}
});
window.smoothScrollToDocs = function(elementId) {
const el = document.getElementById(elementId);
if (el) {
const topbar = document.querySelector('.main-topbar');
const topbarHeight = topbar ? topbar.offsetHeight : 64;
const y = el.getBoundingClientRect().top + window.pageYOffset - topbarHeight - 20;
window.scrollTo({ top: y, behavior: 'smooth' });
}
};
function initDocScrollSpy() {
const sectionIds = ['sec-auth', 'sec-params', 'sec-schema', 'sec-snippets', 'sec-errors'];
const links = document.querySelectorAll('.toc-item');
if (!links.length) return;
function updateSpy() {
const scrollY = window.pageYOffset || document.documentElement.scrollTop;
const topbar = document.querySelector('.main-topbar');
const topbarHeight = topbar ? topbar.offsetHeight : 64;
const triggerOffset = topbarHeight + 60;
let activeId = sectionIds[0];
for (let i = 0; i < sectionIds.length; i++) {
const sec = document.getElementById(sectionIds[i]);
if (sec) {
const top = sec.getBoundingClientRect().top + scrollY - triggerOffset;
if (scrollY >= top) {
activeId = sectionIds[i];
}
}
}
links.forEach(link => {
const href = link.getAttribute('href') || '';
if (href === '#' + activeId) {
link.classList.add('active');
} else {
link.classList.remove('active');
}
});
}
window.addEventListener('scroll', updateSpy, { passive: true });
window.addEventListener('resize', updateSpy, { passive: true });
setTimeout(updateSpy, 100);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initDocScrollSpy);
} else {
initDocScrollSpy();
}
window.copyText = function(text, successMsg) {
navigator.clipboard.writeText(text).then(() => {
if (typeof showToast === 'function') {
showToast(successMsg || '已复制到剪贴板', 'success');
}
});
};
window.updateAuthToggleUI = function(mode) {
const lblHeader = document.getElementById('lbl-auth-header');
const lblQuery = document.getElementById('lbl-auth-query');
if (mode === 'header') {
if (lblHeader) lblHeader.classList.add('active');
if (lblQuery) lblQuery.classList.remove('active');
} else {
if (lblHeader) lblHeader.classList.remove('active');
if (lblQuery) lblQuery.classList.add('active');
}
syncCodeSnippets();
};
window.fillPlaygroundUrl = function(url) {
const input = document.getElementById('pg-target-url');
if (input) {
input.value = url;
syncCodeSnippets();
input.focus();
}
};
function getBaseUrl() {
return (window.location.origin || '').replace(/\/$/, '') + '/';
}
window.goToKeyManagement = function() {
closePlaygroundDrawer();
window.location.href = "{{ url_for('admin.keys') if g.user and g.user['role'] == 'admin' else url_for('portal.keys') }}";
};
window.focusApiKeyInput = function(e) {
if (e && e.target && (e.target.classList.contains('key-chip-remove') || e.target.closest('.key-chip-remove'))) return;
const input = document.getElementById('pg-api-key');
if (input && input.style.display !== 'none') input.focus();
};
window.togglePgKeyDropdown = function(e) {
if (e) {
e.preventDefault();
e.stopPropagation();
}
const wrap = document.getElementById('pg-key-dropdown-wrap');
if (wrap) {
wrap.classList.toggle('open');
}
};
window.closePgKeyDropdown = function() {
const wrap = document.getElementById('pg-key-dropdown-wrap');
if (wrap) {
wrap.classList.remove('open');
}
};
window.handlePgKeyItemSelect = function(val, name) {
closePgKeyDropdown();
if (!val) {
clearSelectedKey();
return;
}
applySelectedKey(val, name);
};
window.handlePgKeyActionCreate = function() {
closePgKeyDropdown();
goToKeyManagement();
};
window.applySelectedKey = function(prefixVal, name) {
const chip = document.getElementById('pg-selected-key-chip');
const chipName = document.getElementById('pg-key-chip-name');
const chipPrefix = document.getElementById('pg-key-chip-prefix');
const input = document.getElementById('pg-api-key');
const label = document.getElementById('pg-key-dropdown-label');
if (chipName) chipName.textContent = name || '密钥';
if (chipPrefix) chipPrefix.textContent = '(' + prefixVal + ')';
if (chip) {
chip.dataset.val = prefixVal;
chip.style.display = 'inline-flex';
}
if (input) {
input.value = prefixVal;
input.style.display = 'none';
}
if (label) {
label.textContent = name || '密钥';
}
document.querySelectorAll('#pg-key-dropdown-menu .pg-key-menu-item').forEach(item => {
if (item.dataset.val === prefixVal) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
syncCodeSnippets();
};
window.clearSelectedKey = function(e) {
if (e) e.stopPropagation();
const chip = document.getElementById('pg-selected-key-chip');
const input = document.getElementById('pg-api-key');
const label = document.getElementById('pg-key-dropdown-label');
if (chip) {
chip.style.display = 'none';
chip.dataset.val = '';
}
if (input) {
input.style.display = 'block';
input.value = '';
input.placeholder = '请输入或选择 API Key';
input.focus();
}
if (label) {
label.textContent = '选择 Key';
}
document.querySelectorAll('#pg-key-dropdown-menu .pg-key-menu-item').forEach(item => {
if (!item.dataset.val) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
syncCodeSnippets();
};
window.handleManualKeyInput = function() {
const chip = document.getElementById('pg-selected-key-chip');
const label = document.getElementById('pg-key-dropdown-label');
if (chip && chip.style.display !== 'none') {
chip.style.display = 'none';
chip.dataset.val = '';
}
if (label) {
label.textContent = '选择 Key';
}
document.querySelectorAll('#pg-key-dropdown-menu .pg-key-menu-item').forEach(item => {
if (!item.dataset.val) {
item.classList.add('active');
} else {
item.classList.remove('active');
}
});
syncCodeSnippets();
};
window.handleKeyInputKeydown = function(e) {
const chip = document.getElementById('pg-selected-key-chip');
if ((e.key === 'Backspace' || e.key === 'Delete') && chip && chip.style.display !== 'none') {
e.preventDefault();
clearSelectedKey();
}
};
window.selectApiKey = function(keyVal) {
let matched = false;
document.querySelectorAll('#pg-key-dropdown-menu .pg-key-menu-item[data-val]').forEach(item => {
if (item.dataset.val === keyVal || item.dataset.val === (keyVal + '...')) {
applySelectedKey(item.dataset.val, item.dataset.name || '密钥');
matched = true;
}
});
if (!matched) {
const input = document.getElementById('pg-api-key');
if (input) {
input.value = keyVal;
syncCodeSnippets();
}
}
};
document.addEventListener('click', function(e) {
const wrap = document.getElementById('pg-key-dropdown-wrap');
if (wrap && wrap.classList.contains('open') && !wrap.contains(e.target)) {
wrap.classList.remove('open');
}
});
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
const wrap = document.getElementById('pg-key-dropdown-wrap');
if (wrap) wrap.classList.remove('open');
}
});
window.resetPlayground = function() {
const urlInput = document.getElementById('pg-target-url');
if (urlInput) urlInput.value = '';
clearSelectedKey();
const resBox = document.getElementById('pg-result-container');
if (resBox) resBox.style.display = 'none';
};
function getPlaygroundValues() {
const urlInput = document.getElementById('pg-target-url');
const keyInput = document.getElementById('pg-api-key');
const chip = document.getElementById('pg-selected-key-chip');
const authRadio = document.querySelector('input[name="pg-auth-type"]:checked');
const rawUrl = (urlInput ? urlInput.value : '').trim() || 'https://v.douyin.com/xxx/';
const rawKey = (chip && chip.style.display !== 'none' ? (chip.dataset.val || (keyInput ? keyInput.value : '')) : (keyInput ? keyInput.value : '')).trim() || 'mp_xxxxxxxxxxxxxxxx';
const authType = authRadio ? authRadio.value : 'header';
return { rawUrl, rawKey, authType, baseUrl: getBaseUrl() };
}
window.switchSnippetTab = function(lang) {
currentLang = lang;
document.querySelectorAll('.doc-code-tabs .doc-code-tab').forEach(tab => {
if (tab.dataset.lang === lang) {
tab.classList.add('active');
} else {
tab.classList.remove('active');
}
});
syncCodeSnippets();
};
window.syncCodeSnippets = function() {
const { rawUrl, rawKey, authType, baseUrl } = getPlaygroundValues();
const endpoint = baseUrl + 'api/v1/parse';
const display = document.getElementById('snippet-code-display');
if (!display) return;
let code = '';
if (currentLang === 'curl') {
if (authType === 'header') {
code = `curl -X GET '${endpoint}?url=${encodeURIComponent(rawUrl)}' \\\n -H 'Authorization: Bearer ${rawKey}'`;
} else {
code = `curl -X GET '${endpoint}?key=${encodeURIComponent(rawKey)}&url=${encodeURIComponent(rawUrl)}'`;
}
} else if (currentLang === 'python') {
if (authType === 'header') {
code = `import requests
url = "${endpoint}"
headers = {
"Authorization": "Bearer ${rawKey}"
}
params = {
"url": "${rawUrl}"
}
response = requests.get(url, headers=headers, params=params, timeout=15)
data = response.json()
if data.get("succ"):
print("解析成功:", data["data"]["title"])
print("视频直链:", data["data"].get("video_url"))
else:
print(f"解析失败 [{data.get('code')}]: {data.get('message')}")`;
} else {
code = `import requests
url = "${endpoint}"
params = {
"key": "${rawKey}",
"url": "${rawUrl}"
}
response = requests.get(url, params=params, timeout=15)
data = response.json()
print(data)`;
}
} else if (currentLang === 'js') {
if (authType === 'header') {
code = `// Node.js (Fetch API) / 现代浏览器
const targetUrl = encodeURIComponent("${rawUrl}");
const apiUrl = "${endpoint}?url=" + targetUrl;
async function parseMedia() {
try {
const res = await fetch(apiUrl, {
method: "GET",
headers: {
"Authorization": "Bearer ${rawKey}"
}
});
const result = await res.json();
if (result.succ) {
console.log("解析成功:", result.data.title);
console.log("视频地址:", result.data.video_url);
} else {
console.error("解析失败:", result.message);
}
} catch (err) {
console.error("请求异常:", err);
}
}
parseMedia();`;
} else {
code = `// Query 参数写法
const params = new URLSearchParams({
key: "${rawKey}",
url: "${rawUrl}"
});
fetch(\`${endpoint}?\${params.toString()}\`)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));`;
}
} else if (currentLang === 'go') {
code = `package main
import (
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
func main() {
baseURL := "${endpoint}"
targetURL := "${rawUrl}"
apiKey := "${rawKey}"
params := url.Values{}
params.Add("url", targetURL)
req, err := http.NewRequest("GET", baseURL+"?"+params.Encode(), nil)
if err != nil {
panic(err)
}
req.Header.Set("Authorization", "Bearer "+apiKey)
client := &http.Client{Timeout: 15 * time.Second}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
defer resp.Body.Close()
body, _ := io.ReadAll(resp.Body)
fmt.Println(string(body))
}`;
} else if (currentLang === 'php') {
code = `<?php
$apiUrl = "${endpoint}";
$apiKey = "${rawKey}";
$targetUrl = "${rawUrl}";
$ch = curl_init();
$query = http_build_query(['url' => $targetUrl]);
curl_setopt($ch, CURLOPT_URL, $apiUrl . '?' . $query);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
if (!empty($data['succ'])) {
echo "标题: " . $data['data']['title'] . PHP_EOL;
echo "视频直链: " . $data['data']['video_url'] . PHP_EOL;
} else {
echo "错误: " . ($data['message'] ?? '未知错误') . PHP_EOL;
}`;
} else if (currentLang === 'java') {
code = `import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
public class MediaParserDemo {
public static void main(String[] args) throws Exception {
String baseUrl = "${endpoint}";
String targetUrl = "${rawUrl}";
String apiKey = "${rawKey}";
String fullUrl = baseUrl + "?url=" + URLEncoder.encode(targetUrl, StandardCharsets.UTF_8);
HttpClient client = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(10))
.build();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(fullUrl))
.header("Authorization", "Bearer " + apiKey)
.GET()
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println("Status: " + response.statusCode());
System.out.println("Body: " + response.body());
}
}`;
}
window._activeSnippetRawCode = code;
display.innerHTML = highlightSyntax(code, currentLang);
};
function highlightSyntax(raw, lang) {
if (!raw) return '';
let s = raw
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
if (lang === 'curl') {
s = s.replace(/\b(curl)\b/g, '<span class="hl-cmd">$1</span>')
.replace(/(-X|-H)\b/g, '<span class="hl-kw">$1</span>')
.replace(/(GET|POST|Bearer)/g, '<span class="hl-type">$1</span>')
.replace(/('([^'\\]|\\.)*'|"([^"\\]|\\.)*")/g, '<span class="hl-str">$1</span>');
} else {
// Strings
s = s.replace(/(&quot;[\s\S]*?&quot;|&#39;[\s\S]*?&#39;|`[\s\S]*?`|"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/g, '<span class="hl-str">$1</span>');
// Comments
s = s.replace(/(^|[^:])(\/\/[^\n]*|#[^\n]*)/gm, '$1<span class="hl-cmt">$2</span>');
// Keywords
const kwRegex = /\b(import|from|const|let|var|function|async|await|if|else|return|public|class|static|void|package|defer|panic|try|catch|new|throws|print|echo|def|as|export|default|switch|case|break|throws)\b/g;
s = s.replace(kwRegex, '<span class="hl-kw">$1</span>');
// Builtin Types / standard libraries
const typeRegex = /\b(String|HttpClient|HttpRequest|HttpResponse|URI|URLEncoder|Duration|StandardCharsets|Exception|URLSearchParams|JSON|response|requests|time|http|url|io|fmt|json|int|bool|error|true|false|null|nil|Array)\b/g;
s = s.replace(typeRegex, '<span class="hl-type">$1</span>');
}
return s;
}
window.copyActiveCodeSnippet = function() {
const rawCode = window._activeSnippetRawCode || document.getElementById('snippet-code-display')?.textContent || '';
const btnText = document.getElementById('copy-snippet-btn-text');
if (!rawCode) return;
navigator.clipboard.writeText(rawCode).then(() => {
if (typeof showToast === 'function') {
showToast('已复制 ' + currentLang.toUpperCase() + ' 示例代码', 'success');
}
if (btnText) {
const old = btnText.textContent;
btnText.textContent = '已复制!';
setTimeout(() => { btnText.textContent = old; }, 1800);
}
});
};
function highlightJson(json) {
if (typeof json !== 'string') {
json = JSON.stringify(json, null, 2);
}
return json
.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
let cls = 'hl-num';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'hl-type';
} else {
cls = 'hl-str';
}
} else if (/true|false/.test(match)) {
cls = 'hl-kw';
} else if (/null/.test(match)) {
cls = 'hl-cmt';
}
return '<span class="' + cls + '">' + match + '</span>';
});
}
window.copyPlaygroundJson = function() {
const rawJson = window._lastPlaygroundRawJson || document.getElementById('pg-res-json')?.textContent || '';
if (!rawJson) return;
navigator.clipboard.writeText(rawJson).then(() => {
if (typeof showToast === 'function') {
showToast('已复制响应 JSON', 'success');
}
});
};
window.executePlaygroundRequest = async function(e) {
if (e) e.preventDefault();
const { rawUrl, rawKey, authType } = getPlaygroundValues();
if (!rawUrl) {
if (typeof showToast === 'function') showToast('请提供待解析链接', 'warning');
return;
}
const btn = document.getElementById('pg-submit-btn');
const btnText = document.getElementById('pg-btn-text');
const resBox = document.getElementById('pg-result-container');
const resStatus = document.getElementById('pg-res-status');
const resTime = document.getElementById('pg-res-time');
const resPlatform = document.getElementById('pg-res-platform');
const resJson = document.getElementById('pg-res-json');
const alertBox = document.getElementById('pg-context-alert');
const alertText = document.getElementById('pg-context-alert-text');
if (btn) btn.disabled = true;
if (btnText) btnText.textContent = '请求中...';
let targetRequestUrl = '/api/v1/parse?url=' + encodeURIComponent(rawUrl);
const headers = {};
if (rawKey) {
if (authType === 'header') {
headers['Authorization'] = 'Bearer ' + rawKey;
} else {
targetRequestUrl += '&key=' + encodeURIComponent(rawKey);
}
}
const startTime = performance.now();
try {
const resp = await fetch(targetRequestUrl, {
method: 'GET',
headers: headers
});
const elapsed = Math.round(performance.now() - startTime);
const status = resp.status;
const data = await resp.json().catch(() => null);
window._lastPlaygroundRawJson = JSON.stringify(data, null, 2);
if (resBox) resBox.style.display = 'block';
if (resTime) resTime.textContent = elapsed + ' ms';
if (resStatus) {
resStatus.className = 'status-pill ' + (status === 200 && data && data.succ ? 'online' : 'danger');
resStatus.innerHTML = '<span class="status-dot"></span>HTTP ' + status;
}
if (resJson) {
resJson.innerHTML = highlightJson(data || {});
}
// 智能情境错误提示检查 (In-context Error Alert)
if (alertBox && alertText) {
const errorCode = (data && (data.error_code || data.code)) ? String(data.error_code || data.code) : '';
if (errorCode && ERROR_TIPS[errorCode]) {
alertText.textContent = ERROR_TIPS[errorCode];
alertBox.style.display = 'flex';
} else if (!data || !data.succ) {
alertText.textContent = '💡 提示:' + ((data && (data.retdesc || data.message)) ? (data.retdesc || data.message) : '接口请求未能成功完成');
alertBox.style.display = 'flex';
} else {
alertBox.style.display = 'none';
}
}
if (data && data.succ) {
if (resPlatform && data.data) {
resPlatform.textContent = data.data.platform || '已解析';
resPlatform.style.display = 'inline-block';
}
if (typeof showToast === 'function') {
showToast('解析成功!耗时 ' + elapsed + 'ms', 'success');
}
} else {
if (resPlatform) resPlatform.style.display = 'none';
if (typeof showToast === 'function') {
showToast('请求失败: ' + (data && (data.retdesc || data.message) ? (data.retdesc || data.message) : 'HTTP ' + status), 'error');
}
}
} catch (err) {
const elapsed = Math.round(performance.now() - startTime);
if (resBox) resBox.style.display = 'block';
if (resStatus) {
resStatus.className = 'status-pill danger';
resStatus.innerHTML = '<span class="status-dot"></span>网络请求失败';
}
if (resTime) resTime.textContent = elapsed + ' ms';
if (resJson) resJson.textContent = 'Client Network Error: ' + (err.message || err);
if (alertBox) alertBox.style.display = 'none';
if (typeof showToast === 'function') showToast('请求发生网络异常', 'error');
} finally {
if (btn) btn.disabled = false;
if (btnText) btnText.textContent = '发送测试';
}
};
// 监听 Ctrl+Enter / Cmd+Enter 快速提交
document.addEventListener('keydown', function(e) {
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
const targetInput = document.getElementById('pg-target-url');
if (targetInput && document.activeElement === targetInput) {
e.preventDefault();
executePlaygroundRequest();
}
}
});
// 目录滚动联动 (ScrollSpy)
const sections = document.querySelectorAll('.api-doc-section');
const tocLinks = document.querySelectorAll('.toc-link');
window.addEventListener('scroll', () => {
let current = '';
sections.forEach(section => {
const sectionTop = section.offsetTop - 120;
if (window.pageYOffset >= sectionTop) {
current = section.getAttribute('id');
}
});
tocLinks.forEach(link => {
link.classList.remove('active');
if (link.getAttribute('href') === '#' + current) {
link.classList.add('active');
}
});
});
// 初始化代码示例
document.addEventListener('DOMContentLoaded', () => {
syncCodeSnippets();
});
setTimeout(syncCodeSnippets, 50);
})();
</script>