新增赋能中心一楼设备教程:上传、搜索与在线播放
This commit is contained in:
+101
-1
@@ -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()
|
||||
|
||||
+11
-1
@@ -169,6 +169,16 @@ center_duty_leaves = Table('center_duty_leaves', metadata,
|
||||
UniqueConstraint('duty_date', 'slot', 'user_id', name='uq_center_duty_leave_member'))
|
||||
Index('ix_center_duty_leave_date_slot', center_duty_leaves.c.duty_date, center_duty_leaves.c.slot)
|
||||
|
||||
center_tutorials = Table('center_tutorials', metadata,
|
||||
Column('id', String(36), primary_key=True),
|
||||
Column('room', String(40), nullable=False), Column('equipment', String(100), nullable=False),
|
||||
# 视频保存在 uploads/tutorials/{id}.{ext},这里只记文件名
|
||||
Column('video_file', String(80), nullable=False), Column('video_bytes', Integer, nullable=False),
|
||||
Column('note', Text, nullable=False, default=''),
|
||||
Column('uploader_id', String(36), ForeignKey('users.id'), nullable=False),
|
||||
Column('created_at', Integer, nullable=False))
|
||||
Index('ix_center_tutorials_created', center_tutorials.c.created_at)
|
||||
|
||||
timetables = Table('timetables', metadata,
|
||||
Column('user_id', String(36), ForeignKey('users.id', ondelete='CASCADE'), primary_key=True),
|
||||
Column('week_type', String(4), primary_key=True),
|
||||
@@ -180,5 +190,5 @@ timetables = Table('timetables', metadata,
|
||||
TABLES = (
|
||||
users, sessions, email_verifications, activities, participations, join_links,
|
||||
center_photos, center_materials, center_activity_materials, center_activity_meta,
|
||||
center_items, center_loans, center_checks, center_duty_leaves, timetables,
|
||||
center_items, center_loans, center_checks, center_duty_leaves, center_tutorials, timetables,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
"""静态文件响应:容忍媒体元素发出的异常 Range 头(#416 / #400)。"""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from starlette.datastructures import Headers
|
||||
from starlette.responses import FileResponse
|
||||
from starlette.types import Receive, Scope, Send
|
||||
|
||||
|
||||
class RangeSafeFileResponse(FileResponse):
|
||||
"""不可满足或无法解析的 Range 头退化为整文件 200 响应。
|
||||
|
||||
浏览器视频元素偶尔会发出 ``Range: bytes=12345-`` 这类超出文件长度的请求,
|
||||
Starlette 会回 416,部分浏览器随即报错。这里只在可满足时走正常的 206 分段。
|
||||
"""
|
||||
|
||||
async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
|
||||
if scope["type"] != "http" or "range" not in Headers(scope=scope):
|
||||
await super().__call__(scope, receive, send)
|
||||
return
|
||||
if self.stat_result is None:
|
||||
self.stat_result = os.stat(self.path)
|
||||
self.set_stat_headers(self.stat_result)
|
||||
try:
|
||||
FileResponse._parse_range_header(Headers(scope=scope)["range"], self.stat_result.st_size)
|
||||
except Exception:
|
||||
scope = dict(scope)
|
||||
raw = list(scope["headers"])
|
||||
scope["headers"] = [(name, value) for name, value in raw if name.lower() not in (b"range", b"if-range")]
|
||||
await super().__call__(scope, receive, send)
|
||||
|
||||
|
||||
def range_safe_file(path: Path, media_type: str | None = None, filename: str | None = None,
|
||||
stat_result=None, content_disposition_type: str = "attachment") -> FileResponse:
|
||||
return RangeSafeFileResponse(path, media_type=media_type, filename=filename, stat_result=stat_result,
|
||||
content_disposition_type=content_disposition_type)
|
||||
Reference in New Issue
Block a user