Files
worklog/server/center.py
T

458 lines
26 KiB
Python

"""赋能中心一楼:照片、物品、每日清点与借还。"""
import asyncio
import io
import json
import re
import time
import uuid
import warnings
import zipfile
from pathlib import PurePosixPath
from datetime import datetime
from pathlib import Path
from typing import Literal
from fastapi import Depends, HTTPException, Query, Request
from fastapi.responses import FileResponse
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 .duty import BEIJING
class ItemIn(BaseModel):
name: str = Field(min_length=1, max_length=100)
quantity: int = Field(ge=0, le=100000)
@field_validator('name')
@classmethod
def clean_name(cls, value):
if not value.strip(): raise ValueError('物品名称不能为空')
return value.strip()
class LoanBaseIn(BaseModel):
quantity: int = Field(ge=1, le=100000)
reason: str = Field(min_length=1, max_length=500)
contact: str = Field(min_length=1, max_length=200)
@field_validator('reason', 'contact')
@classmethod
def required_text(cls, value):
if not value.strip(): raise ValueError('申请理由和联系方式不能为空')
return value.strip()
class LoanIn(LoanBaseIn):
item_name: str = Field(min_length=1, max_length=100)
@field_validator('item_name')
@classmethod
def clean_item_name(cls, value):
if not value.strip(): raise ValueError('借出物品不能为空')
return value.strip()
class PublicLoanIn(BaseModel):
name: str = Field(min_length=1, max_length=64)
phone: str = Field(min_length=11, max_length=11)
college: str = Field(min_length=1, max_length=100)
activity_name: str = Field(min_length=1, max_length=160)
note: str = Field(min_length=1, max_length=500)
@field_validator('name', 'college', 'activity_name', 'note')
@classmethod
def required_public_text(cls, value):
value = value.strip()
if not value:
raise ValueError('姓名、学院、活动名称和物品备注不能为空')
return value
@field_validator('phone')
@classmethod
def valid_phone(cls, value):
value = value.strip()
if not re.fullmatch(r'1[3-9]\d{9}', value):
raise ValueError('请填写正确的 11 位手机号')
return value
class CheckIn(BaseModel):
quantities: dict[str, int]
note: str = Field(default='', max_length=1000)
class MaterialIn(BaseModel):
material_id: str | None = Field(default=None, min_length=32, max_length=32)
photo_ids: list[str] = Field(default_factory=list)
MAX_PHOTOS_PER_UPLOAD = 50
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
DAILY_PHOTO_LIMIT = 1000
UPLOAD_ORPHAN_TTL_MS = 24 * 60 * 60 * 1000
def now_ms(): return int(time.time() * 1000)
async def cleanup_orphan_uploads(db, root: Path, before_ms: int) -> tuple[int, int]:
"""Remove unlinked uploads after a grace period, preserving every referenced photo/package."""
materials = (await db.execute(select(center_materials))).mappings().all()
linked_ids = set((await db.execute(select(center_activity_materials.c.material_id))).scalars())
meta_materials = await db.execute(select(center_activity_meta.c.material_id))
linked_ids.update(row[0] for row in meta_materials.all() if row[0])
stale_materials = [row for row in materials if row['created_at'] < before_ms and row['id'] not in linked_ids]
stale_ids = {row['id'] for row in stale_materials}
if stale_ids:
await db.execute(delete(center_materials).where(center_materials.c.id.in_(stale_ids)))
# A photo is retained while any activity or any remaining material references it.
photo_refs = set()
for raw in (await db.execute(select(center_activity_meta.c.photo_ids))).scalars():
try:
photo_refs.update(json.loads(raw))
except (TypeError, ValueError):
continue
for raw in (await db.execute(select(center_materials.c.photo_ids))).scalars():
try:
photo_refs.update(json.loads(raw))
except (TypeError, ValueError):
continue
photo_rows = (await db.execute(select(center_photos).where(center_photos.c.created_at < before_ms))).mappings().all()
stale_photos = [row['id'] for row in photo_rows if row['id'] not in photo_refs]
if stale_photos:
await db.execute(delete(center_photos).where(center_photos.c.id.in_(stale_photos)))
known_materials = set((await db.execute(select(center_materials.c.id))).scalars())
known_photos = set((await db.execute(select(center_photos.c.id))).scalars())
await db.commit()
root.mkdir(parents=True, exist_ok=True)
for material_id in stale_ids:
(root / f'{material_id}.zip').unlink(missing_ok=True)
for photo_id in stale_photos:
if re.fullmatch(r'[0-9a-f]{32}', photo_id):
(root / f'{photo_id}.jpg').unlink(missing_ok=True)
# Also remove old files left behind if an earlier cleanup deleted database rows but
# could not unlink the files (for example, a temporary filesystem error).
for path in root.iterdir():
match = re.fullmatch(r'([0-9a-f]{32})\.(zip|jpg)', path.name)
if not match or match.group(1) in (known_materials if match.group(2) == 'zip' else known_photos):
continue
try:
if path.stat().st_mtime * 1000 < before_ms:
path.unlink(missing_ok=True)
except OSError:
continue
return len(stale_ids), len(stale_photos)
async def orphan_upload_cleanup_loop(session_factory, root_provider):
while True:
try:
async with session_factory() as db:
materials, photos = await cleanup_orphan_uploads(db, root_provider(), now_ms() - UPLOAD_ORPHAN_TTL_MS)
if materials or photos:
print(f'[uploads] 清理未关联文件包 {materials} 个、照片 {photos} 张', flush=True)
except asyncio.CancelledError:
raise
except Exception as exc:
print(f'[uploads] 清理未关联文件失败: {exc}', flush=True)
await asyncio.sleep(6 * 60 * 60)
def validate_photo_batch(ids, existing=()):
"""限制本次新增照片,历史照片不占本次额度。"""
if len(set(ids) - set(existing)) > MAX_PHOTOS_PER_UPLOAD:
raise HTTPException(422, f'每次最多上传{MAX_PHOTOS_PER_UPLOAD}张照片(含ZIP内照片)')
async def validate_photos(db, ids, owner_id, existing=(), allow_empty=False):
if (not ids and not allow_empty) or len(set(ids)) != len(ids):
raise HTTPException(422, '请至少上传照片或ZIP附件,照片不能重复')
rows = (await db.execute(select(center_photos).where(center_photos.c.id.in_(ids)))).mappings().all()
if len(rows) != len(ids) or any(r['owner_id'] != owner_id and r['id'] not in existing for r in rows):
raise HTTPException(403, '照片不存在或不属于当前账号')
async def save_meta(db, activity_id, kind, photo_ids, owner_id, material_id=None):
if kind != 'center':
return
await validate_photos(db, photo_ids, owner_id, allow_empty=bool(material_id))
await db.execute(insert(center_activity_meta).values(activity_id=activity_id, photo_ids=json.dumps(photo_ids),material_id=material_id))
if material_id: await link_material(db, activity_id, material_id)
async def link_material(db, activity_id, material_id):
await db.execute(sqlite_insert(center_activity_materials).values(
activity_id=activity_id, material_id=material_id, created_at=now_ms()
).on_conflict_do_nothing(index_elements=['activity_id', 'material_id']))
async def activity_materials(db, activity_ids):
"""同时读取原材料和成员补充材料,兼容尚未迁移的旧关联。"""
grouped = {}
if not activity_ids: return grouped
linked = select(center_activity_materials.c.activity_id, center_activity_materials.c.material_id, center_activity_materials.c.created_at).where(center_activity_materials.c.activity_id.in_(activity_ids))
original = select(center_activity_meta.c.activity_id, center_activity_meta.c.material_id, center_materials.c.created_at).join(center_materials, center_materials.c.id == center_activity_meta.c.material_id).where(center_activity_meta.c.activity_id.in_(activity_ids))
links = linked.union_all(original).subquery()
rows = (await db.execute(select(links.c.activity_id, links.c.material_id, links.c.created_at, center_materials.c.photo_ids, users.c.id.label('uploader_id'), users.c.display_name.label('uploader_name')).select_from(links).join(center_materials, center_materials.c.id == links.c.material_id).join(users, users.c.id == center_materials.c.owner_id).order_by(links.c.created_at, links.c.material_id))).mappings()
seen = set()
for row in rows:
key = (row['activity_id'], row['material_id'])
if key in seen: continue
seen.add(key)
grouped.setdefault(row['activity_id'], []).append({
'id': row['material_id'], 'uploader_id': row['uploader_id'], 'uploader_name': row['uploader_name'],
'created_at': row['created_at'], 'photo_ids': json.loads(row['photo_ids']),
'download_url': '/api/center/materials/' + row['material_id'],
})
return grouped
async def material_photos(db, material_id, owner_id):
row = (await db.execute(select(center_materials).where(center_materials.c.id==material_id))).mappings().first()
if not row or row['owner_id']!=owner_id:raise HTTPException(403,'材料包不存在或不属于当前账号')
return json.loads(row['photo_ids'])
def convert_photo(raw):
from PIL import Image, ImageOps
with warnings.catch_warnings():
warnings.simplefilter('error', Image.DecompressionBombError)
with Image.open(io.BytesIO(raw)) as image:
if image.format not in ('JPEG', 'MPO', 'PNG', 'WEBP'):
raise ValueError('仅支持JPG、PNG、WebP照片')
image = ImageOps.exif_transpose(image).convert('RGB')
output = io.BytesIO(); image.save(output, 'JPEG', quality=90)
return output.getvalue()
def convert_package(raw):
photos=[];names=set();file_count=0
allowed={'.jpg','.jpeg','.png','.webp','.pdf','.doc','.docx','.xls','.xlsx','.ppt','.pptx','.txt','.csv','.md'}
with zipfile.ZipFile(io.BytesIO(raw)) as archive:
entries=archive.infolist()
if sum(e.file_size for e in entries)>MAX_ZIP_EXPANDED_BYTES:raise ValueError(f'ZIP展开后不超过{MAX_ZIP_EXPANDED_BYTES // 1024 // 1024}MB')
for entry in entries:
name=entry.filename.replace('\\','/');path=PurePosixPath(name)
if path.is_absolute() or '..' in path.parts or ':' in name or '\x00' in name or ((entry.external_attr>>16)&0o170000)==0o120000:raise ValueError('ZIP包含不安全路径或链接')
if entry.flag_bits&1:raise ValueError('不支持加密ZIP')
if name in names:raise ValueError('ZIP中存在重复文件名')
names.add(name)
if entry.is_dir():continue
if name.startswith('__MACOSX/') or path.name=='.DS_Store':continue
if path.suffix.lower() not in allowed:raise ValueError('ZIP只支持图片、PDF、Office文档和文本材料')
file_count += 1
if entry.file_size>MAX_ZIP_ENTRY_BYTES:raise ValueError(f'包内单个文档不超过{MAX_ZIP_ENTRY_BYTES // 1024 // 1024}MB')
if path.suffix.lower() in {'.jpg','.jpeg','.png','.webp'}:
if len(photos) >= MAX_PHOTOS_PER_UPLOAD:raise ValueError(f'每次最多上传{MAX_PHOTOS_PER_UPLOAD}张照片(含ZIP内照片)')
if entry.file_size>MAX_PHOTO_BYTES:raise ValueError(f'包内单张照片不超过{MAX_PHOTO_BYTES // 1024 // 1024}MB')
photos.append(convert_photo(archive.read(entry)))
if not file_count:raise ValueError('ZIP附件不能为空')
return photos
def install(app, get_db, current_user, photo_root, visible_clause):
from .hall_log import snapshot as hall_log_snapshot
@app.get('/api/center/hall-log')
async def hall_log(refresh: bool = False, viewer=Depends(current_user)):
"""赋能中心展厅使用登记(实时读取金山文档在线表格)。"""
return await hall_log_snapshot(force=refresh)
@app.post('/api/center/materials')
async def upload_material(request:Request,db=Depends(get_db),viewer=Depends(current_user)):
raw=bytearray()
async for chunk in request.stream():
raw.extend(chunk)
if len(raw)>MAX_ZIP_BYTES:raise HTTPException(413,f'ZIP材料包最大{MAX_ZIP_BYTES // 1024 // 1024}MB')
try:photos=await asyncio.to_thread(convert_package,bytes(raw))
except Exception as exc:raise HTTPException(422,str(exc) if isinstance(exc,ValueError) else 'ZIP材料包无效或损坏') from exc
key=uuid.uuid4().hex;folder=photo_root();folder.mkdir(parents=True,exist_ok=True);paths=[];ids=[]
try:
package=folder/(key+'.zip');paths.append(package);await asyncio.to_thread(package.write_bytes,bytes(raw))
for photo in photos:
photo_id=uuid.uuid4().hex;path=folder/(photo_id+'.jpg');paths.append(path);ids.append(photo_id)
await asyncio.to_thread(path.write_bytes,photo)
await db.execute(insert(center_photos).values(id=photo_id,owner_id=viewer['id'],created_at=now_ms()))
await db.execute(insert(center_materials).values(id=key,owner_id=viewer['id'],photo_ids=json.dumps(ids),created_at=now_ms()))
await db.commit()
except Exception:
await db.rollback()
for path in paths:path.unlink(missing_ok=True)
raise
return {'id':key,'photo_ids':ids}
@app.get('/api/center/materials/{material_id}')
async def material(material_id:str,db=Depends(get_db),viewer=Depends(current_user)):
row=(await db.execute(select(center_materials).where(center_materials.c.id==material_id))).mappings().first()
if not row:raise HTTPException(404,'材料包不存在')
if row['owner_id']!=viewer['id']:
contributed = select(center_activity_materials.c.activity_id).where(center_activity_materials.c.material_id == material_id)
allowed=(await db.execute(select(activities.c.id).join(center_activity_meta).where(visible_clause(viewer['id']),or_(center_activity_meta.c.material_id==material_id, activities.c.id.in_(contributed))))).first()
if not allowed:raise HTTPException(403,'无权下载此材料包')
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.post('/api/center/photos')
async def upload_photo(request: Request, db=Depends(get_db), viewer=Depends(current_user)):
raw = bytearray()
async for chunk in request.stream():
raw.extend(chunk)
if len(raw) > MAX_PHOTO_BYTES: raise HTTPException(413, f'每张照片最大{MAX_PHOTO_BYTES // 1024 // 1024}MB')
count = (await db.execute(select(func.count()).select_from(center_photos).where(center_photos.c.owner_id == viewer['id'], center_photos.c.created_at > now_ms() - 86400000))).scalar()
if count >= DAILY_PHOTO_LIMIT: raise HTTPException(429, f'今日照片上传已达{DAILY_PHOTO_LIMIT}张')
try: data = await asyncio.to_thread(convert_photo, bytes(raw))
except DecompressionBombError as exc: raise HTTPException(422, '图片数据过大,无法安全处理') from exc
except Exception as exc: raise HTTPException(422, '照片无效,仅支持JPG、PNG、WebP') from exc
key = uuid.uuid4().hex
folder = photo_root(); folder.mkdir(parents=True, exist_ok=True)
path = folder / (key + '.jpg')
await asyncio.to_thread(path.write_bytes, data)
try:
await db.execute(insert(center_photos).values(id=key, owner_id=viewer['id'], created_at=now_ms()))
await db.commit()
except Exception:
path.unlink(missing_ok=True); raise
return {'id': key}
@app.get('/api/center/photos/{photo_id}')
async def photo(photo_id: str, db=Depends(get_db), viewer=Depends(current_user)):
if not re.fullmatch(r'[0-9a-f]{32}', photo_id): raise HTTPException(404, '照片不存在')
row = (await db.execute(select(center_photos).where(center_photos.c.id == photo_id))).mappings().first()
if not row: raise HTTPException(404, '照片不存在')
if row['owner_id'] != viewer['id']:
contributed = select(center_activity_materials.c.activity_id).join(center_materials).where(center_materials.c.photo_ids.like('%"' + photo_id + '"%'))
allowed = (await db.execute(select(activities.c.id).join(center_activity_meta).where(visible_clause(viewer['id']), or_(center_activity_meta.c.photo_ids.like('%"' + photo_id + '"%'), activities.c.id.in_(contributed))))).first()
if not allowed: raise HTTPException(403, '无权查看此照片')
path = photo_root() / (row['id'] + '.jpg')
if not path.is_file(): raise HTTPException(404, '照片文件不存在')
return FileResponse(path, media_type='image/jpeg')
@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()
borrowed = dict((await db.execute(select(center_loans.c.item_id, func.sum(center_loans.c.quantity)).where(center_loans.c.status=='approved', center_loans.c.returned_at.is_(None)).group_by(center_loans.c.item_id))).all())
day = datetime.now(BEIJING).date().isoformat()
check = (await db.execute(select(center_checks).where(center_checks.c.day == day))).mappings().first()
return {'items': [{**r, 'borrowed': borrowed.get(r['id'], 0), 'available': r['quantity']-borrowed.get(r['id'],0)} for r in rows], 'day': day, 'checked_today': bool(check), 'check': dict(check) if check else None}
@app.post('/api/center/items')
async def add_item(payload: ItemIn, db=Depends(get_db), viewer=Depends(current_user)):
key=uuid.uuid4().hex
await db.execute(insert(center_items).values(id=key, **payload.model_dump(), created_at=now_ms())); await db.commit()
return {'id': key}
@app.post('/api/center/public-loans')
async def record_public_loan(payload: PublicLoanIn, db=Depends(get_db)):
"""登录页免账号登记;公开记录不进入活动、账号或库存统计。"""
created = now_ms()
recent = (await db.execute(select(func.count()).select_from(center_loans).where(
center_loans.c.guest_phone == payload.phone,
center_loans.c.created_at > created - 60_000,
))).scalar()
if recent:
raise HTTPException(429, '同一手机号 1 分钟内只能登记一次')
key = uuid.uuid4().hex
await db.execute(insert(center_loans).values(
id=key, item_id=None, item_name='免登录物品借出', user_id=None,
quantity=1, reason=payload.note, contact=payload.phone,
guest_name=payload.name, guest_phone=payload.phone,
guest_college=payload.college, guest_activity_name=payload.activity_name,
status='recorded', created_at=created,
))
await db.commit()
return {'id': key, 'status': 'recorded', 'created_at': created,
'message': '借出登记已提交,请按现场要求归还物品。'}
@app.post('/api/center/loans')
async def record_loan(payload: LoanIn, db=Depends(get_db), viewer=Depends(current_user)):
"""仅记录借出,不扣减库存,也不要求物品已加入库存清单。"""
key=uuid.uuid4().hex
await db.execute(insert(center_loans).values(
id=key,item_id=None,user_id=viewer['id'],**payload.model_dump(),
status='recorded',created_at=now_ms()
))
await db.commit(); return {'id':key,'status':'recorded'}
@app.post('/api/center/items/{item_id}/loans')
async def record_linked_loan_compat(item_id: str, payload: LoanBaseIn, db=Depends(get_db), viewer=Depends(current_user)):
"""兼容旧调用:仍关联库存名称,但只登记,不再占用库存。"""
item=(await db.execute(select(center_items).where(center_items.c.id==item_id))).mappings().first()
if not item: raise HTTPException(404,'物品不存在')
key=uuid.uuid4().hex
await db.execute(insert(center_loans).values(
id=key,item_id=item_id,item_name=None,user_id=viewer['id'],**payload.model_dump(),
status='recorded',created_at=now_ms()
))
await db.commit(); return {'id':key,'status':'recorded'}
@app.get('/api/center/loans')
async def loans(status: str='all', db=Depends(get_db), viewer=Depends(current_user)):
stmt=select(
center_loans.c.id, center_loans.c.item_id,
func.coalesce(center_loans.c.item_name,center_items.c.name).label('item_name'),
center_loans.c.user_id, center_loans.c.quantity, center_loans.c.reason,
center_loans.c.contact, center_loans.c.created_at, center_loans.c.returned_at,
center_loans.c.status, center_loans.c.reviewer_id, center_loans.c.reviewed_at,
center_loans.c.review_note, users.c.display_name,
center_loans.c.guest_name, center_loans.c.guest_phone,
center_loans.c.guest_college, center_loans.c.guest_activity_name,
).select_from(center_loans).outerjoin(center_items,center_items.c.id==center_loans.c.item_id).outerjoin(users,users.c.id==center_loans.c.user_id)
if status=='recorded':stmt=stmt.where(center_loans.c.status=='recorded')
elif status in ('approved','borrowed'):stmt=stmt.where(center_loans.c.status=='approved')
elif status=='returned':stmt=stmt.where(center_loans.c.status==status)
elif status!='all':raise HTTPException(422,'无效借用状态')
rows=(await db.execute(stmt.order_by(center_loans.c.created_at.desc()).limit(200))).mappings().all()
return {'items':[{**r,
'display_name': r['display_name'] or r['guest_name'],
'contact': r['contact'] if r['user_id']==viewer['id'] or r['user_id'] is None else None,
} for r in rows]}
@app.post('/api/center/loans/{loan_id}/return')
async def return_item(loan_id: str, db=Depends(get_db), viewer=Depends(current_user)):
row=(await db.execute(select(center_loans).where(center_loans.c.id==loan_id))).mappings().first()
if not row:raise HTTPException(404,'借用记录不存在')
if row['user_id']!=viewer['id']:raise HTTPException(403,'仅借用人可以登记归还')
if row['status']=='returned':return {'ok':True}
if row['status']!='approved':raise HTTPException(409,'仅历史库存借出记录可归还')
await db.execute(update(center_loans).where(center_loans.c.id==loan_id,center_loans.c.returned_at.is_(None)).values(returned_at=now_ms(),status='returned'))
await db.commit(); return {'ok':True}
@app.post('/api/center/checks')
async def stocktake(payload: CheckIn, db=Depends(get_db), viewer=Depends(current_user)):
await db.execute(text('BEGIN IMMEDIATE'))
day=datetime.now(BEIJING).date().isoformat()
existing=(await db.execute(select(center_checks).where(center_checks.c.day==day))).mappings().first()
if existing and existing['user_id'] != viewer['id']:
raise HTTPException(409,'今天的清点已由其他成员提交,只有提交人可以修正')
rows=(await db.execute(select(center_items))).mappings().all()
if not rows or set(payload.quantities)!={r['id'] for r in rows}:raise HTTPException(422,'请逐项清点全部物品,物品列表如有变化请刷新')
used=dict((await db.execute(select(center_loans.c.item_id,func.sum(center_loans.c.quantity)).where(center_loans.c.status=='approved',center_loans.c.returned_at.is_(None)).group_by(center_loans.c.item_id))).all())
details=[]
for row in rows:
count=payload.quantities[row['id']]
if type(count) is not int or not 0<=count<=100000:raise HTTPException(422,'实点在库数量必须为非负整数')
expected=row['quantity']-used.get(row['id'],0)
if count!=expected and not payload.note.strip():raise HTTPException(422,'清点有差异,请填写说明')
details.append({'id':row['id'],'name':row['name'],'expected':expected,'actual':count,'borrowed':used.get(row['id'],0)})
await db.execute(update(center_items).where(center_items.c.id==row['id']).values(quantity=count+used.get(row['id'],0)))
check_values = {'details':json.dumps(details,ensure_ascii=False),'note':payload.note.strip()}
if existing:
await db.execute(update(center_checks).where(center_checks.c.day==day,center_checks.c.user_id==viewer['id']).values(**check_values))
else:
await db.execute(insert(center_checks).values(day=day,user_id=viewer['id'],**check_values,created_at=now_ms()))
await db.commit();return {'ok':True,'day':day}
@app.get('/api/center/checks')
async def checks(db=Depends(get_db), viewer=Depends(current_user)):
rows=(await db.execute(select(center_checks,users.c.display_name).join(users).order_by(center_checks.c.day.desc()).limit(100))).mappings().all()
return {'items':[{**r,'details':json.loads(r['details'])} for r in rows]}