File size: 6,315 Bytes
f9907a0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
"""云端相机 - FastAPI 后端

接口一览:
  POST   /api/login               登录 / 注册(首次输入即注册)
  POST   /api/upload              上传照片(multipart: username, pin, file)
  GET    /api/photos              相册列表(header X-Pin 鉴权)
  GET    /api/photo/{u}/{id}      查看图片(?t=签名令牌&thumb=1 取缩略图)
  DELETE /api/photo/{u}/{id}      删除照片(header X-Pin 鉴权)
  GET    /                        前端页面(同域托管 static/index.html)
"""
import io
import time
import uuid
from pathlib import Path

from fastapi import FastAPI, File, Form, Header, HTTPException, UploadFile
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from PIL import Image, UnidentifiedImageError

import storage

# 模块加载即确保存储目录存在(被外部应用挂载时不触发 startup 事件)
storage.ensure_dirs()

STATIC_DIR = Path(__file__).parent

app = FastAPI(title="云端相机")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

MAX_UPLOAD_MB = 20
THUMB_MAX = 480


def _check_credentials(username: str, pin: str) -> None:
    if not storage.valid_username(username):
        raise HTTPException(status_code=400, detail="用户名不合法(1-24位,中文/字母/数字/下划线/短横线)")
    if not storage.valid_pin(pin):
        raise HTTPException(status_code=400, detail="PIN 需为 4-20 位")
    if not storage.verify_user(username, pin):
        raise HTTPException(status_code=403, detail="用户名或 PIN 不正确")


@app.on_event("startup")
def _startup() -> None:
    storage.ensure_dirs()


@app.get("/")
def index():
    return FileResponse(str(STATIC_DIR / "index.html"))


@app.post("/api/login")
def login(payload: dict):
    username = str(payload.get("username", "")).strip()
    pin = str(payload.get("pin", ""))
    if not storage.valid_username(username):
        raise HTTPException(status_code=400, detail="用户名不合法(1-24位,中文/字母/数字/下划线/短横线)")
    if not storage.valid_pin(pin):
        raise HTTPException(status_code=400, detail="PIN 需为 4-20 位")
    is_new = False
    if not storage.user_exists(username):
        storage.create_user(username, pin)
        is_new = True
    elif not storage.verify_user(username, pin):
        raise HTTPException(status_code=403, detail="用户名或 PIN 不正确")
    return {"ok": True, "is_new": is_new}


@app.post("/api/upload")
async def upload(
    file: UploadFile = File(...),
    username: str = Form(...),
    pin: str = Form(...),
):
    _check_credentials(username, pin)

    raw = await file.read()
    if not raw:
        raise HTTPException(status_code=400, detail="文件为空")
    if len(raw) > MAX_UPLOAD_MB * 1024 * 1024:
        raise HTTPException(status_code=413, detail=f"图片超过 {MAX_UPLOAD_MB}MB 限制")

    try:
        img = Image.open(io.BytesIO(raw))
        img.load()
    except UnidentifiedImageError:
        raise HTTPException(status_code=400, detail="不是有效的图片文件")
    except Exception:
        raise HTTPException(status_code=400, detail="图片解析失败")

    # 统一转 JPEG(含 EXIF 方向修正)
    img = ImageOps_exif_transpose(img)
    if img.mode not in ("RGB", "L"):
        img = img.convert("RGB")

    photo_id = f"{int(time.time() * 1000):x}{uuid.uuid4().hex[:6]}"
    user_dir = storage._user_dir(username)
    user_dir.mkdir(parents=True, exist_ok=True)

    full_path = user_dir / f"{photo_id}.jpg"
    img.save(full_path, "JPEG", quality=90)

    thumb_path = user_dir / f"{photo_id}_thumb.jpg"
    thumb = img.copy()
    thumb.thumbnail((THUMB_MAX, THUMB_MAX))
    thumb.save(thumb_path, "JPEG", quality=75)

    photo = {
        "id": photo_id,
        "name": file.filename or f"{photo_id}.jpg",
        "size": len(raw),
        "uploaded_at": time.strftime("%Y-%m-%d %H:%M:%S"),
        "width": img.width,
        "height": img.height,
    }
    storage.add_photo(username, photo)

    return {"ok": True, "photo": photo}


@app.get("/api/photos")
def photos(username: str, x_pin: str = Header(default="")):
    _check_credentials(username, x_pin)
    photos_list = storage.list_photos(username)
    for p in photos_list:
        pid = p["id"]
        p["thumb_url"] = f"/api/photo/{username}/{pid}?t={storage.make_token(username, pid)}&thumb=1"
        p["url"] = f"/api/photo/{username}/{pid}?t={storage.make_token(username, pid)}"
    return {"ok": True, "photos": photos_list}


@app.get("/api/photo/{username}/{photo_id}")
def photo(
    username: str,
    photo_id: str,
    t: str,
    thumb: int = 0,
):
    if not storage.verify_token(username, photo_id, t):
        raise HTTPException(status_code=403, detail="链接无效或已过期,请回到相册刷新")
    suffix = "_thumb" if thumb else ""
    path = storage._user_dir(username) / f"{photo_id}{suffix}.jpg"
    if not path.exists():
        raise HTTPException(status_code=404, detail="照片不存在")
    return FileResponse(str(path), media_type="image/jpeg")


@app.delete("/api/photo/{username}/{photo_id}")
def delete_photo(
    username: str,
    photo_id: str,
    x_pin: str = Header(default=""),
):
    _check_credentials(username, x_pin)
    if not storage.remove_photo(username, photo_id):
        raise HTTPException(status_code=404, detail="照片不存在")
    for suffix in ("", "_thumb"):
        p = storage._user_dir(username) / f"{photo_id}{suffix}.jpg"
        if p.exists():
            p.unlink()
    return {"ok": True}


def ImageOps_exif_transpose(img: Image.Image) -> Image.Image:
    """按 EXIF 方向信息旋转图片。"""
    try:
        exif = img.getexif()
        orientation = exif.get(0x0112, 1)
        ops = {
            2: (Image.Transpose.FLIP_LEFT_RIGHT,),
            3: (Image.Transpose.ROTATE_180,),
            4: (Image.Transpose.FLIP_TOP_BOTTOM,),
            5: (Image.Transpose.TRANSPOSE,),
            6: (Image.Transpose.ROTATE_270,),
            7: (Image.Transpose.TRANSVERSE,),
            8: (Image.Transpose.ROTATE_90,),
        }
        for op in ops.get(orientation, ()):
            img = img.transpose(op)
    except Exception:
        pass
    return img