新增赋能中心一楼设备教程:上传、搜索与在线播放

This commit is contained in:
2026-11-23 11:13:58 +08:00
parent ad6ab63c8e
commit 533c401175
7 changed files with 446 additions and 8 deletions
+101 -1
View File
@@ -1,5 +1,6 @@
"""赋能中心一楼:照片、物品、每日清点、借还登记、展厅登记和值班入口。"""
import asyncio
import hashlib
import io
import json
import os
@@ -17,9 +18,10 @@ from PIL.Image import DecompressionBombError
from pydantic import BaseModel, Field, field_validator
from sqlalchemy import select, insert, update, delete, func, text, or_
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
from .models import center_photos, center_materials, center_activity_materials, center_activity_meta, center_items, center_loans, center_checks, activities, users
from .models import center_photos, center_materials, center_activity_materials, center_activity_meta, center_items, center_loans, center_checks, center_tutorials, activities, users
from .duty import BEIJING
from .security import now_ms, PHONE_PATTERN
from .spa_static import range_safe_file
def required_text(value: str, message: str) -> str:
@@ -95,6 +97,22 @@ MAX_PHOTO_BYTES = 8 * 1024 * 1024
MAX_ZIP_BYTES = 100 * 1024 * 1024
MAX_ZIP_EXPANDED_BYTES = 500 * 1024 * 1024
MAX_ZIP_ENTRY_BYTES = 50 * 1024 * 1024
# 设备教程视频:单段上传上限与格式白名单
MAX_TUTORIAL_BYTES = 1024 * 1024 * 1024
TUTORIAL_VIDEO_TYPES = {
'video/mp4': 'mp4', 'video/webm': 'webm', 'video/quicktime': 'mov',
'application/mp4': 'mp4', 'application/octet-stream': None,
}
TUTORIAL_PLAYLESS_TYPES = {'video/mp4', 'video/webm', 'video/quicktime', 'application/mp4'}
def detect_video_ext(head: bytes) -> str | None:
"""按文件头判断视频格式,避免仅凭浏览器声明的类型落盘错误后缀。"""
if len(head) >= 12 and head[4:8] == b'ftyp':
return 'mov' if head[8:12] in (b'qt ',) else 'mp4'
if head[:4] == b'\x1aE\xdf\xa3':
return 'webm'
return None
DAILY_PHOTO_LIMIT = 1000
UPLOAD_ORPHAN_TTL_MS = 24 * 60 * 60 * 1000
@@ -355,6 +373,88 @@ def install(app, get_db, current_user, photo_root, visible_clause):
if not path.is_file(): raise HTTPException(404, '照片文件不存在')
return FileResponse(path, media_type='image/jpeg')
# ---------------------------------------------------------------- 设备使用教程
@app.get('/api/center/tutorials')
async def list_tutorials(q: str = '', offset: int = 0, limit: int = 60, db=Depends(get_db), viewer=Depends(current_user)):
keyword = q.strip()
if keyword and len(keyword) > 100: raise HTTPException(422, '搜索关键词最多100字')
offset, limit = max(0, offset), min(100, max(1, limit))
stmt = select(center_tutorials.c.id, center_tutorials.c.room, center_tutorials.c.equipment,
center_tutorials.c.note, center_tutorials.c.created_at, center_tutorials.c.uploader_id,
center_tutorials.c.video_file, center_tutorials.c.video_bytes,
users.c.display_name.label('uploader_name')).select_from(center_tutorials).outerjoin(users, users.c.id == center_tutorials.c.uploader_id)
for word in keyword.split():
like = '%' + word + '%'
stmt = stmt.where(or_(center_tutorials.c.room.like(like), center_tutorials.c.equipment.like(like), center_tutorials.c.note.like(like)))
rows = (await db.execute(stmt.order_by(center_tutorials.c.created_at.desc(), center_tutorials.c.id)
.offset(offset).limit(limit + 1))).mappings().all()
items = []
for r in rows[:limit]:
item = dict(r)
item['uploader'] = item.pop('uploader_name') or '未命名成员'
items.append(item)
return {'items': items, 'has_more': len(rows) > limit}
@app.post('/api/center/tutorials')
async def upload_tutorial(request: Request, room: str = '', equipment: str = '', note: str = '',
db=Depends(get_db), viewer=Depends(current_user)):
room, equipment, note = room.strip(), equipment.strip(), note.strip()
if not room or len(room) > 40: raise HTTPException(422, '请填写教室号(40字以内)')
if not equipment or len(equipment) > 100: raise HTTPException(422, '请填写器材名(100字以内)')
if len(note) > 2000: raise HTTPException(422, '备注最多2000字')
content_type = (request.headers.get('content-type') or '').split(';')[0].strip().lower()
if content_type not in TUTORIAL_VIDEO_TYPES: raise HTTPException(422, '教程视频仅支持 MP4、MOV 或 WebM')
received = 0
head = b''
path = None
photo_root().mkdir(parents=True, exist_ok=True)
staging_name = photo_root() / ('tutorial-' + uuid.uuid4().hex + '.part')
staging = os.fdopen(os.open(staging_name, os.O_WRONLY | os.O_CREAT | os.O_TRUNC), 'wb', buffering=1024 * 1024)
try:
async for chunk in request.stream():
if not head: head = chunk[:16]
received += len(chunk)
if received > MAX_TUTORIAL_BYTES: raise HTTPException(413, f'教程视频最大{MAX_TUTORIAL_BYTES // 1024 // 1024 // 1024}GB')
await asyncio.to_thread(staging.write, chunk)
staging.flush(); await asyncio.to_thread(os.fsync, staging.fileno())
staging.close()
if received <= 12: raise HTTPException(422, '教程视频为空,请重新选择')
ext = detect_video_ext(head)
if not ext: raise HTTPException(422, '无法识别视频格式,请上传 MP4、MOV 或 WebM')
key = uuid.uuid4().hex
path = photo_root() / (key + '.' + ext)
os.replace(staging_name, path)
try:
await db.execute(insert(center_tutorials).values(
id=key, room=room, equipment=equipment, video_file=key + '.' + ext, video_bytes=received,
note=note, uploader_id=viewer['id'], created_at=now_ms()))
await db.commit()
except Exception:
await db.rollback()
path.unlink(missing_ok=True)
raise
except BaseException:
staging.close()
staging_name.unlink(missing_ok=True)
raise
return {'id': key}
@app.api_route('/api/center/tutorials/{tutorial_id}', methods=['GET', 'HEAD'])
async def tutorial_video(tutorial_id: str, preview: str = '0', db=Depends(get_db), viewer=Depends(current_user)):
if not re.fullmatch(r'[0-9a-f]{32}', tutorial_id): raise HTTPException(404, '教程不存在')
row = (await db.execute(select(center_tutorials).where(center_tutorials.c.id == tutorial_id))).mappings().first()
if not row: raise HTTPException(404, '教程不存在')
path = photo_root() / row['video_file']
if not path.is_file(): raise HTTPException(404, '教程视频文件不存在')
ext = row['video_file'].rpartition('.')[2]
media_type = {'mp4': 'video/mp4', 'mov': 'video/quicktime', 'webm': 'video/webm'}.get(ext, 'application/octet-stream')
if preview == '1':
if viewer['id'] != row['uploader_id']:
raise HTTPException(403, '只有上传者可以下载原始视频')
filename = f'{row["room"]}-{row["equipment"]}.{ext}'
return range_safe_file(path, media_type=media_type, filename=filename)
return range_safe_file(path, media_type=media_type, stat_result=path.stat(), content_disposition_type='inline')
@app.get('/api/center/items')
async def items(q: str = '', db=Depends(get_db), viewer=Depends(current_user)):
rows = (await db.execute(select(center_items).where(center_items.c.name.like('%'+q.strip()+'%')).order_by(center_items.c.name))).mappings().all()