新增赋能中心一楼设备使用教程

This commit is contained in:
2026-11-22 22:48:45 +08:00
parent 2fae181fae
commit 1bb8f73f1e
4 changed files with 185 additions and 5 deletions
+102 -3
View File
@@ -11,17 +11,41 @@ from pathlib import PurePosixPath
from datetime import datetime
from pathlib import Path
from fastapi import Depends, HTTPException, Request
from fastapi.responses import FileResponse
from fastapi import Depends, Form, HTTPException, Request, UploadFile
from fastapi.responses import FileResponse, StreamingResponse
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_tutorials, center_items, center_loans, center_checks, activities, users
from .duty import BEIJING
from .security import now_ms, PHONE_PATTERN
class RangeResponse(StreamingResponse):
def __init__(self, path: Path, range_header: str | None, media_type: str):
size = path.stat().st_size
match = re.fullmatch(r'bytes=(\d+)-(\d*)', range_header or '')
start, end = (int(match[1]), int(match[2]) if match[2] else size - 1) if match else (0, size - 1)
if (range_header and not match) or start >= size or start > end:
super().__init__(b'', status_code=416, headers={'Content-Range': f'bytes */{size}'})
return
end = min(end, size - 1)
def chunks():
with path.open('rb') as source:
source.seek(start)
remaining = end - start + 1
while remaining:
chunk = source.read(min(1024 * 1024, remaining))
if not chunk: break
remaining -= len(chunk)
yield chunk
super().__init__(chunks(), status_code=206 if match else 200, media_type=media_type, headers={
'Content-Length': str(end - start + 1), 'Accept-Ranges': 'bytes',
'Content-Range': f'bytes {start}-{end}/{size}',
})
def required_text(value: str, message: str) -> str:
value = value.strip()
if not value:
@@ -92,6 +116,8 @@ class MaterialIn(BaseModel):
MAX_PHOTOS_PER_UPLOAD = 50
MAX_PHOTO_BYTES = 8 * 1024 * 1024
MAX_TUTORIAL_BYTES = 500 * 1024 * 1024
TUTORIAL_TYPES = {'.mp4': 'video/mp4', '.m4v': 'video/x-m4v', '.mov': 'video/quicktime', '.webm': 'video/webm'}
MAX_ZIP_BYTES = 100 * 1024 * 1024
MAX_ZIP_EXPANDED_BYTES = 500 * 1024 * 1024
MAX_ZIP_ENTRY_BYTES = 50 * 1024 * 1024
@@ -320,6 +346,79 @@ def install(app, get_db, current_user, photo_root, visible_clause):
path=photo_root()/(row['id']+'.zip')
if not path.is_file():raise HTTPException(404,'材料包文件不存在')
return FileResponse(path,media_type='application/zip',filename='center-materials-'+row['id']+'.zip')
@app.get('/api/center/tutorials')
async def tutorials(q: str = '', db=Depends(get_db), viewer=Depends(current_user)):
keyword = q.strip()[:100]
query = select(center_tutorials, users.c.display_name).join(users, users.c.id == center_tutorials.c.owner_id)
if keyword:
query = query.where(or_(center_tutorials.c.classroom.like('%' + keyword + '%'), center_tutorials.c.device_name.like('%' + keyword + '%')))
rows = (await db.execute(query.order_by(center_tutorials.c.created_at.desc()).limit(200))).mappings().all()
return {'items': [dict(row, can_delete=row['owner_id'] == viewer['id']) for row in rows]}
@app.post('/api/center/tutorials')
async def create_tutorial(classroom: str = Form(), device_name: str = Form(), video: UploadFile = Form(), db=Depends(get_db), viewer=Depends(current_user)):
classroom = classroom.strip()
device_name = device_name.strip()
if not classroom or not device_name: raise HTTPException(422, '教室号和设备名不能为空')
if len(classroom) > 40 or len(device_name) > 100: raise HTTPException(422, '教室号最多40字,设备名最多100字')
filename = (video.filename or '').strip()[:180]
extension = Path(filename).suffix.lower()
if extension not in TUTORIAL_TYPES: raise HTTPException(422, '仅支持MP4、WebM、MOV、M4V视频')
folder = photo_root() / 'tutorials'
folder.mkdir(parents=True, exist_ok=True)
video_key = uuid.uuid4().hex
path = folder / (video_key + extension)
size = 0
try:
with path.open('wb') as output:
while chunk := await video.read(1024 * 1024):
size += len(chunk)
if size > MAX_TUTORIAL_BYTES: raise HTTPException(413, '教程视频最大500MB')
await asyncio.to_thread(output.write, chunk)
if not size: raise HTTPException(422, '视频文件不能为空')
await db.execute(insert(center_tutorials).values(
id=uuid.uuid4().hex, classroom=classroom, device_name=device_name,
video_key=video_key, original_name=filename, media_type=TUTORIAL_TYPES[extension],
size_bytes=size, owner_id=viewer['id'], created_at=now_ms(),
))
await db.commit()
except Exception:
await db.rollback()
path.unlink(missing_ok=True)
raise
finally:
await video.close()
return {'ok': True}
@app.post('/api/center/tutorials/{tutorial_id}/playback')
async def tutorial_playback(tutorial_id: str, db=Depends(get_db), viewer=Depends(current_user)):
await tutorial_file(tutorial_id, db)
return {'url': f'/api/center/tutorials/{tutorial_id}/video'}
async def tutorial_file(tutorial_id: str, db):
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, '教程不存在')
extension = next((ext for ext, mime in TUTORIAL_TYPES.items() if mime == row['media_type']), '.mp4')
path = photo_root() / 'tutorials' / (row['video_key'] + extension)
if not path.is_file(): raise HTTPException(404, '教程视频文件不存在')
return path, row
@app.get('/api/center/tutorials/{tutorial_id}/video')
async def tutorial_video(tutorial_id: str, request: Request, db=Depends(get_db), viewer=Depends(current_user)):
path, row = await tutorial_file(tutorial_id, db)
return RangeResponse(path, request.headers.get('Range'), row['media_type'])
@app.delete('/api/center/tutorials/{tutorial_id}')
async def delete_tutorial(tutorial_id: str, db=Depends(get_db), viewer=Depends(current_user)):
path, row = await tutorial_file(tutorial_id, db)
if row['owner_id'] != viewer['id']: raise HTTPException(403, '只能删除自己上传的教程')
await db.execute(delete(center_tutorials).where(center_tutorials.c.id == tutorial_id))
await db.commit()
path.unlink(missing_ok=True)
return {'ok': True}
@app.post('/api/center/photos')
async def upload_photo(request: Request, db=Depends(get_db), viewer=Depends(current_user)):
raw = bytearray()
+9 -1
View File
@@ -143,6 +143,14 @@ center_activity_materials = Table('center_activity_materials', metadata,
Column('activity_id', String(36), ForeignKey('activities.id', ondelete='CASCADE'), primary_key=True),
Column('material_id', String(32), ForeignKey('center_materials.id'), primary_key=True),
Column('created_at', Integer, nullable=False))
center_tutorials = Table('center_tutorials', metadata,
Column('id', String(32), primary_key=True),
Column('classroom', String(40), nullable=False), Column('device_name', String(100), nullable=False),
Column('video_key', String(40), nullable=False, unique=True),
Column('original_name', String(180), nullable=False), Column('media_type', String(40), nullable=False),
Column('size_bytes', Integer, nullable=False), Column('owner_id', String(36), ForeignKey('users.id'), nullable=False),
Column('created_at', Integer, nullable=False))
Index('ix_center_tutorial_created', center_tutorials.c.created_at)
center_items = Table('center_items', metadata,
Column('id', String(32), primary_key=True), Column('name', String(100), nullable=False, unique=True),
Column('quantity', Integer, nullable=False), Column('created_at', Integer, nullable=False))
@@ -180,5 +188,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_tutorials, center_items, center_loans, center_checks, center_duty_leaves, timetables,
)