fix(training-video): 修复苹果企业微信无法播放培训视频

This commit is contained in:
runny committed 2026-07-21 14:11:01 +08:00
1 parent e457a66465
commit 9838b77441
13 files changed
+182 -21

No files matched your search

+81 -3
View File
@@ -6,7 +6,9 @@ backend/app/api/agents.py
逻辑:按当前用户 RBAC 返回可访问 Agent;列表统一 serialize_agent_for_user_list(结构化列为准)。
"""
import os
from flask import Blueprint, jsonify, send_from_directory
import mimetypes
import re
from flask import Blueprint, Response, jsonify, request, send_from_directory, stream_with_context
from app import db
from app.core.auth.jwt import get_current_user
@@ -115,8 +117,84 @@ def list_public_agents():
visible_agent_ids = {agent.id for agent in agents}
return jsonify([_serialize_agent_row(agent, visible_agent_ids=visible_agent_ids) for agent in sort_agent_rows(agents)])
# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口
def _parse_byte_range(range_header: str, file_size: int) -> tuple[int, int] | None:
"""
解析浏览器单段字节范围请求。
用途:iOS Safari/企业微信播放 MP4 时依赖 Range 请求,本函数将请求转换为闭区间。
参数约束:仅接受单个 bytes 范围;无效或越界范围返回 None。
"""
match = re.fullmatch(r'bytes=(\d*)-(\d*)', range_header.strip())
if not match or file_size <= 0:
return None
start_text, end_text = match.groups()
if not start_text and not end_text:
return None
if start_text:
start = int(start_text)
end = int(end_text) if end_text else file_size - 1
else:
suffix_length = int(end_text)
if suffix_length <= 0:
return None
start = max(file_size - suffix_length, 0)
end = file_size - 1
if start >= file_size or end < start:
return None
return start, min(end, file_size - 1)
def _stream_minio_guide_file(filename: str) -> Response:
"""
以同源流式响应返回 MinIO 指南文件。
用途:消除生产 HTTPS 页面加载 HTTP MinIO 地址的混合内容问题,并支持 iOS 所需的 206 响应。
参数约束:filename 为系统生成的 MinIO 对象名;响应流结束后必须释放连接。
"""
stat = minio_service.stat_file(filename)
file_size = int(stat.size)
content_type = stat.content_type or mimetypes.guess_type(filename)[0] or 'application/octet-stream'
requested_range = request.headers.get('Range', '').strip()
byte_range = _parse_byte_range(requested_range, file_size) if requested_range else None
if requested_range and byte_range is None:
return Response(status=416, headers={'Content-Range': f'bytes */{file_size}'})
start, end = byte_range or (0, file_size - 1)
content_length = end - start + 1
source = minio_service.open_file_stream(filename, offset=start, length=content_length)
def generate():
try:
while True:
chunk = source.read(64 * 1024)
if not chunk:
break
yield chunk
finally:
source.close()
source.release_conn()
headers = {
'Accept-Ranges': 'bytes',
'Content-Length': str(content_length),
'Cache-Control': 'private, max-age=3600',
}
status = 206 if byte_range else 200
if byte_range:
headers['Content-Range'] = f'bytes {start}-{end}/{file_size}'
return Response(stream_with_context(generate()), status=status, headers=headers, content_type=content_type)
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
def serve_guide_file(filename):
return send_from_directory(os.path.join(os.getcwd(), 'data', 'agent-guides'), filename)
"""
返回本地或 MinIO 中的指南文件。
用途:为 PDF、图片和培训视频提供统一同源地址;本地文件沿用 Flask 条件响应,MinIO 文件支持 Range。
参数约束:filename 仅用于系统指南存储目录或 MinIO 指南桶,不接受任意外部路径。
"""
local_directory = os.path.join(os.getcwd(), 'data', 'agent-guides')
if os.path.isfile(os.path.join(local_directory, filename)):
return send_from_directory(local_directory, filename, conditional=True)
return _stream_minio_guide_file(filename)
+28 -9
View File
@@ -77,16 +77,35 @@ class MinioService:
def get_public_url(self, object_name: str) -> str:
"""
Returns the public URL for the given object name.
"""
if os.path.exists(os.path.join('data/agent-guides', object_name)):
# It's a local fallback file
# the backend needs a static route to serve this, we'll assume /api/agents/guides/files/<object_name>
# but since we want it public without auth:
return f"/api/agents/guides/files/{object_name}"
返回同源的指南文件代理地址。
base_url = cfg.MINIO_PUBLIC_BASE_URL.rstrip('/')
return f"{base_url}/{self.bucket_name}/{object_name}"
用途:避免 HTTPS 页面直接加载 HTTP MinIO 对象时被移动端浏览器拦截。
参数约束:object_name 必须是系统生成的对象名;返回地址由指南文件接口提供 Range 响应。
"""
return f"/api/agents/guides/files/{object_name}"
def open_file_stream(self, object_name: str, *, offset: int = 0, length: int | None = None):
"""
按指定字节范围打开 MinIO 指南对象流。
用途:供同源指南文件接口透传视频数据,满足 iOS 媒体播放器的 Range/206 请求。
参数约束:offset 从 0 开始,length 为本次最多读取字节数;调用方必须关闭返回流。
"""
return self.client.get_object(
self.bucket_name,
object_name,
offset=offset,
length=length,
)
def stat_file(self, object_name: str):
"""
获取 MinIO 指南对象元数据。
用途:在返回视频前确定文件大小和 MIME 类型,以生成 iOS 可识别的媒体响应头。
参数约束:object_name 必须是系统保存的对象名;对象不存在时由 MinIO 异常上抛。
"""
return self.client.stat_object(self.bucket_name, object_name)
def get_file_bytes(self, object_name: str) -> bytes:
"""
@@ -0,0 +1,51 @@
"""
用途:验证 Agent 指南视频同源代理的字节范围响应。
依赖:Flask 请求上下文、agents API 的 Range 解析与 MinIO 流式响应函数。
逻辑:使用内存对象模拟 MinIO,断言 iOS 媒体请求得到 206、Content-Range 和正确数据。
"""
from io import BytesIO
from types import SimpleNamespace
from flask import Flask
from app.api import agents as agents_api
class _FakeObjectStream(BytesIO):
"""模拟 MinIO 响应流,并提供连接释放接口。"""
def release_conn(self) -> None:
"""模拟 MinIO SDK 的连接释放操作。"""
def test_parse_byte_range_supports_ios_media_requests():
"""验证普通、开放结尾和后缀三种媒体字节范围均可正确解析。"""
assert agents_api._parse_byte_range('bytes=0-3', 10) == (0, 3)
assert agents_api._parse_byte_range('bytes=4-', 10) == (4, 9)
assert agents_api._parse_byte_range('bytes=-3', 10) == (7, 9)
assert agents_api._parse_byte_range('bytes=10-', 10) is None
def test_stream_minio_guide_file_returns_partial_content(monkeypatch):
"""验证视频代理响应 iOS Range 请求时返回 206 和完整范围响应头。"""
payload = b'0123456789'
monkeypatch.setattr(
agents_api.minio_service,
'stat_file',
lambda _filename: SimpleNamespace(size=len(payload), content_type='video/mp4'),
)
monkeypatch.setattr(
agents_api.minio_service,
'open_file_stream',
lambda _filename, offset, length: _FakeObjectStream(payload[offset:offset + length]),
)
app = Flask(__name__)
with app.test_request_context(headers={'Range': 'bytes=2-5'}):
response = agents_api._stream_minio_guide_file('training.mp4')
assert response.status_code == 206
assert response.headers['Accept-Ranges'] == 'bytes'
assert response.headers['Content-Range'] == 'bytes 2-5/10'
assert response.headers['Content-Length'] == '4'
assert response.content_type == 'video/mp4'
assert b''.join(response.response) == b'2345'
+1
View File
@@ -31,6 +31,7 @@
| 培训聊天常见问题分角色配置 | 已实现 | Agent 管理表单支持分别维护普通员工与 HR 管理员进入“员工培训”聊天页时看到的常见问题;聊天欢迎区会按 `training_hr_manage` 权限自动切换对应问题集 |
| 培训 HR 统计问答兜底 | 已实现 | “员工培训”聊天页中,HR 管理员提问参训人数、通过率、未完成名单、本月成绩统计及考试明细等固定统计问题时,优先走后端本地统计兜底;明细列表会把培训阶段映射为中文(观看视频/知识点复盘/逐题考试/结束),并统一把考试时间、完成时间格式化为年月日,避免当前 Dify 工作流 SQL 改写异常导致问答失败 |
| 管理端培训模式配置 | 已实现 | Agent 管理表单支持显式开启培训工作区;平台应用说明页支持上传并标记“员工培训视频 / 员工培训试题 PDF”,并可直接把试题 PDF 解析导入题库表单;扫描件 PDF 在 OCR 依赖齐备时也可回退识别 |
| 培训视频 iOS 兼容播放 | 已实现 | 培训视频统一通过 HTTPS 站点同源接口访问 MinIO 文件,支持 Range/206 分段响应与 iOS 企业微信内联播放,避免生产 HTTPS 页面直连 HTTP MinIO 导致视频被拦截 |
| 首页培训推荐入口 | 前端已实现 | 当 Agent 开启培训模式后,工作台首页会在应用列表上方展示培训强入口卡片 |
| 培训记录后端落库 | 已实现 | 已新增培训记录模型、迁移与用户/管理端 API,考试进度、结果、统计与导出均可走后端数据源 |
| 培训主链推荐架构 | 已文档化 | 推荐采用“受控考试主链 + Dify 辅助问答/ChatBI”的混合方案;培训 Agent 对接 Dify 时会额外透传后台账号 `role`,便于区分学员/HR 问答分支,见 [docs/新人入职培训Agent_推荐落地方案.md](新人入职培训Agent_推荐落地方案.md) |
@@ -86,6 +86,13 @@ const handleVideoEnded = () => {
workspace.markVideoCompleted();
};
const reportVideoDebugEvent = (event: Event) => {
const video = event.target as HTMLVideoElement;
// #region debug-point A-E:ios-video-runtime
fetch('http://192.168.65.184:7777/event', { method: 'POST', body: JSON.stringify({ sessionId: 'ios-training-video', runId: 'pre-fix', hypothesisId: 'A-E', location: 'TrainingWorkspacePanel.vue:video', msg: '[DEBUG] iOS training video runtime event', data: { event: event.type, src: video.currentSrc || workspace.videoUrl, userAgent: navigator.userAgent, networkState: video.networkState, readyState: video.readyState, mediaErrorCode: video.error?.code ?? null, mediaErrorMessage: video.error?.message ?? null, duration: Number.isFinite(video.duration) ? video.duration : null, currentTime: video.currentTime }, ts: Date.now() }) }).catch(() => {});
// #endregion
};
const setWorkspaceExpanded = (expanded: boolean, manual = false) => {
workspaceExpanded.value = expanded;
emit('update:expanded', expanded);
@@ -841,8 +848,17 @@ const handleStageCardClick = (stageKey: string) => {
<div class="aspect-video bg-black">
<video
controls
autoplay
playsinline
webkit-playsinline="true"
preload="metadata"
class="h-full w-full"
@loadstart="reportVideoDebugEvent"
@loadedmetadata="reportVideoDebugEvent"
@canplay="reportVideoDebugEvent"
@play="reportVideoDebugEvent"
@error="reportVideoDebugEvent"
@stalled="reportVideoDebugEvent"
@abort="reportVideoDebugEvent"
@timeupdate="handleVideoTimeUpdate"
@seeking="handleVideoSeeking"
@ended="handleVideoEnded"
+1 -1
View File
@@ -908,7 +908,7 @@
"usageTrendEmpty": "No trend data yet",
"usageInsights": "Operational alerts",
"usageLowAgents": "Low-usage apps",
"usageLowAgentsHint": "Enabled apps with ≤ {max} chats in the selected range (including zero), sorted ascending, up to {limit}.",
"usageLowAgentsHint": "Apps with ≤ {max} chats in the selected range, sorted ascending, showing up to {limit}.",
"usageLowAgentsHintAria": "Show low-usage app selection rule",
"usageLowAgentsEmpty": "No low-usage apps in this range",
"usageSpikeDays": "Spike days",
-1
View File
@@ -65,7 +65,6 @@
"retryLogin": "Please close this dialog and sign in again."
},
"wecomLogin": "Login with WeCom",
"wecomComingSoon": "WeCom login is under development. Please stay tuned.",
"wecomConnecting": "Connecting to WeCom...",
"wecomStartFailed": "Failed to start WeCom login",
"wecomInvalidState": "Invalid WeCom login state",
+1 -1
View File
@@ -892,7 +892,7 @@
"usageTrendEmpty": "ยังไม่มีข้อมูลแนวโน้ม",
"usageInsights": "การแจ้งเตือนการดำเนินงาน",
"usageLowAgents": "แอปที่ใช้น้อย",
"usageLowAgentsHint": "แอปที่เปิดใช้และมีแชท ≤ {max} ครั้งในช่วงที่เลือก (รวมศูนย์ครั้ง) เรียงจากน้อยไปมาก แสดงสูงสุด {limit} รายการ",
"usageLowAgentsHint": "แอปที่มีแชท ≤ {max} ครั้งในช่วงที่เลือก เรียงจากน้อยไปมาก แสดงสูงสุด {limit} รายการ",
"usageLowAgentsHintAria": "ดูเกณฑ์การคัดเลือกแอปที่ใช้น้อย",
"usageLowAgentsEmpty": "ไม่มีแอปที่ใช้น้อยในช่วงนี้",
"usageSpikeDays": "วันที่มีการใช้งานพุ่งสูง",
-1
View File
@@ -55,7 +55,6 @@
"retryLogin": "กรุณาปิดหน้าต่างนี้แล้วเข้าสู่ระบบใหม่"
},
"wecomLogin": "เข้าสู่ระบบด้วย WeCom",
"wecomComingSoon": "ฟีเจอร์เข้าสู่ระบบด้วย WeCom กำลังพัฒนา กรุณารอติดตาม",
"wecomConnecting": "กำลังเชื่อมต่อ WeCom...",
"wecomStartFailed": "เริ่มต้นการเข้าสู่ระบบด้วย WeCom ไม่สำเร็จ",
"wecomInvalidState": "สถานะการเข้าสู่ระบบ WeCom ไม่ถูกต้อง",
+1 -1
View File
@@ -888,7 +888,7 @@
"usageTrendEmpty": "暂无趋势数据",
"usageInsights": "运营提醒",
"usageLowAgents": "低使用应用",
"usageLowAgentsHint": "启用应用中,统计范围内对话次数 ≤ {max}(含零使用),按对话量升序最多展示 {limit} 个。",
"usageLowAgentsHint": "统计范围内对话次数 ≤ {max} 的应用,按对话量升序最多展示 {limit} 个。",
"usageLowAgentsHintAria": "查看低使用应用选取规则",
"usageLowAgentsEmpty": "当前范围内暂无低使用应用",
"usageSpikeDays": "异常高峰日期",
-1
View File
@@ -65,7 +65,6 @@
"retryLogin": "请关闭此窗口后重新登录。"
},
"wecomLogin": "企业微信登录",
"wecomComingSoon": "企业微信登录功能正在开发中,敬请期待",
"wecomConnecting": "正在连接企业微信...",
"wecomStartFailed": "启动企业微信登录失败",
"wecomInvalidState": "企业微信登录状态无效",
+1 -1
View File
@@ -892,7 +892,7 @@
"usageTrendEmpty": "暫無趨勢資料",
"usageInsights": "營運提醒",
"usageLowAgents": "低使用應用",
"usageLowAgentsHint": "啟用應用中,統計範圍內對話次數 ≤ {max}(含零使用),按對話量升序最多展示 {limit} 個。",
"usageLowAgentsHint": "統計範圍內對話次數 ≤ {max} 的應用,按對話量升序最多展示 {limit} 個。",
"usageLowAgentsHintAria": "查看低使用應用選取規則",
"usageLowAgentsEmpty": "目前範圍內暫無低使用應用",
"usageSpikeDays": "異常高峰日期",
-1
View File
@@ -55,7 +55,6 @@
"retryLogin": "請關閉此窗口後重新登入。"
},
"wecomLogin": "企業微信登錄",
"wecomComingSoon": "企業微信登錄功能正在開發中,敬請期待",
"wecomConnecting": "正在連接企業微信...",
"wecomStartFailed": "啟動企業微信登錄失敗",
"wecomInvalidState": "企業微信登入狀態無效",