新增赋能中心一楼设备使用教程
This commit is contained in:
@@ -1,6 +1,12 @@
|
|||||||
# 赋能中心一楼
|
# 赋能中心一楼
|
||||||
|
|
||||||
导航中的“赋能中心一楼”整合活动记录、独立值班、物品清点与借出登记。原有活动、账号和招生就业服务队值班功能保留。
|
导航中的“赋能中心一楼”整合活动记录、独立值班、物品清点与借出登记、展厅使用登记和设备使用教程。原有活动、账号和招生就业服务队值班功能保留。
|
||||||
|
|
||||||
|
## 设备使用教程
|
||||||
|
|
||||||
|
“设备使用教程”标签页提供视频上传、按教室号或设备名搜索、在线播放和本人删除。登录成员均可上传或观看,上传时需填写教室号和设备名,支持 MP4、WebM、MOV、M4V,单个文件不超过 500MB。
|
||||||
|
|
||||||
|
视频保存在业务数据库同目录的 `uploads/tutorials/`,不会出现在静态 `/uploads` 公开目录中;上传、列表、播放均需要登录,仅上传者可删除。浏览器通过登录请求取得视频,关闭播放弹层后释放临时视频资源。新增教程记录由启动时的表结构检查自动创建,不修改已有业务数据。部署备份继续保留整个 data 目录,包括教程视频。
|
||||||
|
|
||||||
## 赋能中心一楼值班
|
## 赋能中心一楼值班
|
||||||
|
|
||||||
|
|||||||
+102
-3
@@ -11,17 +11,41 @@ from pathlib import PurePosixPath
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
from fastapi import Depends, HTTPException, Request
|
from fastapi import Depends, Form, HTTPException, Request, UploadFile
|
||||||
from fastapi.responses import FileResponse
|
from fastapi.responses import FileResponse, StreamingResponse
|
||||||
from PIL.Image import DecompressionBombError
|
from PIL.Image import DecompressionBombError
|
||||||
from pydantic import BaseModel, Field, field_validator
|
from pydantic import BaseModel, Field, field_validator
|
||||||
from sqlalchemy import select, insert, update, delete, func, text, or_
|
from sqlalchemy import select, insert, update, delete, func, text, or_
|
||||||
from sqlalchemy.dialects.sqlite import insert as sqlite_insert
|
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 .duty import BEIJING
|
||||||
from .security import now_ms, PHONE_PATTERN
|
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:
|
def required_text(value: str, message: str) -> str:
|
||||||
value = value.strip()
|
value = value.strip()
|
||||||
if not value:
|
if not value:
|
||||||
@@ -92,6 +116,8 @@ class MaterialIn(BaseModel):
|
|||||||
|
|
||||||
MAX_PHOTOS_PER_UPLOAD = 50
|
MAX_PHOTOS_PER_UPLOAD = 50
|
||||||
MAX_PHOTO_BYTES = 8 * 1024 * 1024
|
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_BYTES = 100 * 1024 * 1024
|
||||||
MAX_ZIP_EXPANDED_BYTES = 500 * 1024 * 1024
|
MAX_ZIP_EXPANDED_BYTES = 500 * 1024 * 1024
|
||||||
MAX_ZIP_ENTRY_BYTES = 50 * 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')
|
path=photo_root()/(row['id']+'.zip')
|
||||||
if not path.is_file():raise HTTPException(404,'材料包文件不存在')
|
if not path.is_file():raise HTTPException(404,'材料包文件不存在')
|
||||||
return FileResponse(path,media_type='application/zip',filename='center-materials-'+row['id']+'.zip')
|
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')
|
@app.post('/api/center/photos')
|
||||||
async def upload_photo(request: Request, db=Depends(get_db), viewer=Depends(current_user)):
|
async def upload_photo(request: Request, db=Depends(get_db), viewer=Depends(current_user)):
|
||||||
raw = bytearray()
|
raw = bytearray()
|
||||||
|
|||||||
+9
-1
@@ -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('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('material_id', String(32), ForeignKey('center_materials.id'), primary_key=True),
|
||||||
Column('created_at', Integer, nullable=False))
|
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,
|
center_items = Table('center_items', metadata,
|
||||||
Column('id', String(32), primary_key=True), Column('name', String(100), nullable=False, unique=True),
|
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))
|
Column('quantity', Integer, nullable=False), Column('created_at', Integer, nullable=False))
|
||||||
@@ -180,5 +188,5 @@ timetables = Table('timetables', metadata,
|
|||||||
TABLES = (
|
TABLES = (
|
||||||
users, sessions, email_verifications, activities, participations, join_links,
|
users, sessions, email_verifications, activities, participations, join_links,
|
||||||
center_photos, center_materials, center_activity_materials, center_activity_meta,
|
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,
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
import tempfile
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
from sqlalchemy import select
|
||||||
|
from test_api import ApiTestCase, auth, register
|
||||||
|
from server.models import center_tutorials
|
||||||
|
|
||||||
|
|
||||||
|
class CenterTutorialTests(ApiTestCase):
|
||||||
|
def setUp(self):
|
||||||
|
super().setUp()
|
||||||
|
self.files = tempfile.TemporaryDirectory()
|
||||||
|
self.root = Path(self.files.name)
|
||||||
|
self.path_patch = patch.object(self.m, '_db_path', self.root / 'test.db')
|
||||||
|
self.path_patch.start()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.path_patch.stop()
|
||||||
|
self.files.cleanup()
|
||||||
|
super().tearDown()
|
||||||
|
|
||||||
|
async def upload(self, user, classroom='101', device='投影机', content=b'0123456789', name='guide.mp4'):
|
||||||
|
return await self.client.post('/api/center/tutorials', headers=auth(user['token']), data={
|
||||||
|
'classroom': classroom, 'device_name': device,
|
||||||
|
}, files={'video': (name, content, 'video/mp4')})
|
||||||
|
|
||||||
|
async def test_upload_search_stream_and_owner_delete(self):
|
||||||
|
owner = await register(self.client, 'tutorialowner')
|
||||||
|
other = await register(self.client, 'tutorialother')
|
||||||
|
self.assertEqual((await self.client.get('/api/center/tutorials')).status_code, 401)
|
||||||
|
response = await self.upload(owner)
|
||||||
|
self.assertEqual(response.status_code, 200, response.text)
|
||||||
|
self.assertEqual((await self.upload(owner, name='guide.exe')).status_code, 422)
|
||||||
|
self.assertEqual((await self.upload(owner, classroom=' ', device='')).status_code, 422)
|
||||||
|
items = (await self.client.get('/api/center/tutorials?q=投影', headers=auth(other['token']))).json()['items']
|
||||||
|
self.assertEqual(len(items), 1)
|
||||||
|
tutorial = items[0]
|
||||||
|
self.assertEqual(tutorial['classroom'], '101')
|
||||||
|
self.assertEqual(tutorial['device_name'], '投影机')
|
||||||
|
self.assertTrue(tutorial['can_delete'] is False)
|
||||||
|
self.assertEqual((await self.client.get('/api/center/tutorials?q=202', headers=auth(other['token']))).json()['items'], [])
|
||||||
|
self.assertEqual((await self.client.delete('/api/center/tutorials/' + tutorial['id'], headers=auth(other['token']))).status_code, 403)
|
||||||
|
self.assertEqual((await self.client.get('/api/center/tutorials/' + tutorial['id'] + '/video')).status_code, 401)
|
||||||
|
playback = await self.client.post('/api/center/tutorials/' + tutorial['id'] + '/playback', headers=auth(other['token']))
|
||||||
|
self.assertEqual(playback.status_code, 200, playback.text)
|
||||||
|
url = playback.json()['url']
|
||||||
|
self.assertNotIn(owner['token'], url)
|
||||||
|
video = await self.client.get(url, headers={**auth(other['token']), 'Range': 'bytes=2-5'})
|
||||||
|
self.assertEqual(video.status_code, 206)
|
||||||
|
self.assertEqual(video.content, b'2345')
|
||||||
|
self.assertEqual(video.headers['Content-Range'], 'bytes 2-5/10')
|
||||||
|
self.assertEqual((await self.client.get(url, headers={**auth(other['token']), 'Range': 'bytes=20-25'})).status_code, 416)
|
||||||
|
async with self.sessions() as db:
|
||||||
|
row = (await db.execute(select(center_tutorials))).mappings().one()
|
||||||
|
path = self.root / 'uploads' / 'tutorials' / (row['video_key'] + '.mp4')
|
||||||
|
self.assertEqual(path.read_bytes(), b'0123456789')
|
||||||
|
self.assertEqual((await self.client.delete('/api/center/tutorials/' + tutorial['id'], headers=auth(owner['token']))).status_code, 200)
|
||||||
|
self.assertFalse(path.exists())
|
||||||
|
self.assertEqual((await self.client.get('/api/center/tutorials/' + tutorial['id'] + '/video', headers=auth(owner['token']))).status_code, 404)
|
||||||
|
|
||||||
|
async def test_video_limit_removes_partial_file(self):
|
||||||
|
user = await register(self.client, 'tutoriallimit')
|
||||||
|
with patch.object(self.m.center, 'MAX_TUTORIAL_BYTES', 5):
|
||||||
|
response = await self.upload(user)
|
||||||
|
self.assertEqual(response.status_code, 413)
|
||||||
|
self.assertEqual(list((self.root / 'uploads' / 'tutorials').glob('*')), [])
|
||||||
Reference in New Issue
Block a user