WACATW commited on
Commit
fbc320e
·
verified ·
1 Parent(s): 80d61b6

Delete main.py

Browse files
Files changed (1) hide show
  1. main.py +0 -190
main.py DELETED
@@ -1,190 +0,0 @@
1
- """云端相机 - FastAPI 后端
2
-
3
- 接口一览:
4
- POST /api/login 登录 / 注册(首次输入即注册)
5
- POST /api/upload 上传照片(multipart: username, pin, file)
6
- GET /api/photos 相册列表(header X-Pin 鉴权)
7
- GET /api/photo/{u}/{id} 查看图片(?t=签名令牌&thumb=1 取缩略图)
8
- DELETE /api/photo/{u}/{id} 删除照片(header X-Pin 鉴权)
9
- GET / 前端页面(同域托管 static/index.html)
10
- """
11
- import io
12
- import time
13
- import uuid
14
- from pathlib import Path
15
-
16
- from fastapi import Depends, FastAPI, File, Form, Header, HTTPException, UploadFile
17
- from fastapi.middleware.cors import CORSMiddleware
18
- from fastapi.responses import FileResponse, JSONResponse
19
- from fastapi.staticfiles import StaticFiles
20
- from PIL import Image, UnidentifiedImageError
21
-
22
- from . import storage
23
-
24
- STATIC_DIR = Path(__file__).parent / "static"
25
-
26
- app = FastAPI(title="云端相机")
27
-
28
- app.add_middleware(
29
- CORSMiddleware,
30
- allow_origins=["*"],
31
- allow_methods=["*"],
32
- allow_headers=["*"],
33
- )
34
-
35
- app.mount("/static", StaticFiles(directory=str(STATIC_DIR)), name="static")
36
-
37
- MAX_UPLOAD_MB = 20
38
- THUMB_MAX = 480
39
-
40
-
41
- def _check_credentials(username: str, pin: str) -> None:
42
- if not storage.valid_username(username):
43
- raise HTTPException(status_code=400, detail="用户名不合法(1-24位,中文/字母/数字/下划线/短横线)")
44
- if not storage.valid_pin(pin):
45
- raise HTTPException(status_code=400, detail="PIN 需为 4-20 位")
46
- if not storage.verify_user(username, pin):
47
- raise HTTPException(status_code=403, detail="用户名或 PIN 不正确")
48
-
49
-
50
- @app.on_event("startup")
51
- def _startup() -> None:
52
- storage.ensure_dirs()
53
-
54
-
55
- @app.get("/")
56
- def index():
57
- return FileResponse(str(STATIC_DIR / "index.html"))
58
-
59
-
60
- @app.post("/api/login")
61
- def login(payload: dict):
62
- username = str(payload.get("username", "")).strip()
63
- pin = str(payload.get("pin", ""))
64
- if not storage.valid_username(username):
65
- raise HTTPException(status_code=400, detail="用户名不合法(1-24位,中文/字母/数字/下划线/短横线)")
66
- if not storage.valid_pin(pin):
67
- raise HTTPException(status_code=400, detail="PIN 需为 4-20 位")
68
- is_new = False
69
- if not storage.user_exists(username):
70
- storage.create_user(username, pin)
71
- is_new = True
72
- elif not storage.verify_user(username, pin):
73
- raise HTTPException(status_code=403, detail="用户名或 PIN 不正确")
74
- return {"ok": True, "is_new": is_new}
75
-
76
-
77
- @app.post("/api/upload")
78
- async def upload(
79
- file: UploadFile = File(...),
80
- username: str = Form(...),
81
- pin: str = Form(...),
82
- ):
83
- _check_credentials(username, pin)
84
-
85
- raw = await file.read()
86
- if not raw:
87
- raise HTTPException(status_code=400, detail="文件为空")
88
- if len(raw) > MAX_UPLOAD_MB * 1024 * 1024:
89
- raise HTTPException(status_code=413, detail=f"图片超过 {MAX_UPLOAD_MB}MB 限制")
90
-
91
- try:
92
- img = Image.open(io.BytesIO(raw))
93
- img.load()
94
- except UnidentifiedImageError:
95
- raise HTTPException(status_code=400, detail="不是有效的图片文件")
96
- except Exception:
97
- raise HTTPException(status_code=400, detail="图片解析失败")
98
-
99
- # 统一转 JPEG(含 EXIF 方向修正)
100
- img = ImageOps_exif_transpose(img)
101
- if img.mode not in ("RGB", "L"):
102
- img = img.convert("RGB")
103
-
104
- photo_id = f"{int(time.time() * 1000):x}{uuid.uuid4().hex[:6]}"
105
- user_dir = storage._user_dir(username)
106
- user_dir.mkdir(parents=True, exist_ok=True)
107
-
108
- full_path = user_dir / f"{photo_id}.jpg"
109
- img.save(full_path, "JPEG", quality=90)
110
-
111
- thumb_path = user_dir / f"{photo_id}_thumb.jpg"
112
- thumb = img.copy()
113
- thumb.thumbnail((THUMB_MAX, THUMB_MAX))
114
- thumb.save(thumb_path, "JPEG", quality=75)
115
-
116
- photo = {
117
- "id": photo_id,
118
- "name": file.filename or f"{photo_id}.jpg",
119
- "size": len(raw),
120
- "uploaded_at": time.strftime("%Y-%m-%d %H:%M:%S"),
121
- "width": img.width,
122
- "height": img.height,
123
- }
124
- storage.add_photo(username, photo)
125
-
126
- return {"ok": True, "photo": photo}
127
-
128
-
129
- @app.get("/api/photos")
130
- def photos(username: str, x_pin: str = Header(default="")):
131
- _check_credentials(username, x_pin)
132
- photos_list = storage.list_photos(username)
133
- for p in photos_list:
134
- pid = p["id"]
135
- p["thumb_url"] = f"/api/photo/{username}/{pid}?t={storage.make_token(username, pid)}&thumb=1"
136
- p["url"] = f"/api/photo/{username}/{pid}?t={storage.make_token(username, pid)}"
137
- return {"ok": True, "photos": photos_list}
138
-
139
-
140
- @app.get("/api/photo/{username}/{photo_id}")
141
- def photo(
142
- username: str,
143
- photo_id: str,
144
- t: str,
145
- thumb: int = 0,
146
- ):
147
- if not storage.verify_token(username, photo_id, t):
148
- raise HTTPException(status_code=403, detail="链接无效或已过期,请回到相册刷新")
149
- suffix = "_thumb" if thumb else ""
150
- path = storage._user_dir(username) / f"{photo_id}{suffix}.jpg"
151
- if not path.exists():
152
- raise HTTPException(status_code=404, detail="照片不存在")
153
- return FileResponse(str(path), media_type="image/jpeg")
154
-
155
-
156
- @app.delete("/api/photo/{username}/{photo_id}")
157
- def delete_photo(
158
- username: str,
159
- photo_id: str,
160
- x_pin: str = Header(default=""),
161
- ):
162
- _check_credentials(username, x_pin)
163
- if not storage.remove_photo(username, photo_id):
164
- raise HTTPException(status_code=404, detail="照片不存在")
165
- for suffix in ("", "_thumb"):
166
- p = storage._user_dir(username) / f"{photo_id}{suffix}.jpg"
167
- if p.exists():
168
- p.unlink()
169
- return {"ok": True}
170
-
171
-
172
- def ImageOps_exif_transpose(img: Image.Image) -> Image.Image:
173
- """按 EXIF 方向信息旋转图片。"""
174
- try:
175
- exif = img.getexif()
176
- orientation = exif.get(0x0112, 1)
177
- ops = {
178
- 2: (Image.Transpose.FLIP_LEFT_RIGHT,),
179
- 3: (Image.Transpose.ROTATE_180,),
180
- 4: (Image.Transpose.FLIP_TOP_BOTTOM,),
181
- 5: (Image.Transpose.TRANSPOSE,),
182
- 6: (Image.Transpose.ROTATE_270,),
183
- 7: (Image.Transpose.TRANSVERSE,),
184
- 8: (Image.Transpose.ROTATE_90,),
185
- }
186
- for op in ops.get(orientation, ()):
187
- img = img.transpose(op)
188
- except Exception:
189
- pass
190
- return img