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=no, viewport-fit=cover">
|
| 6 |
+
<meta name="apple-mobile-web-app-capable" content="yes">
|
| 7 |
+
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
|
| 8 |
+
<meta name="theme-color" content="#0f1115">
|
| 9 |
+
<title>云端相机</title>
|
| 10 |
+
<style>
|
| 11 |
+
/* 云端相机 - 深色移动端主题 */
|
| 12 |
+
* { margin: 0; padding: 0; box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
|
| 13 |
+
|
| 14 |
+
:root {
|
| 15 |
+
--bg: #0f1115;
|
| 16 |
+
--card: #1a1d24;
|
| 17 |
+
--card2: #232833;
|
| 18 |
+
--line: #2c3240;
|
| 19 |
+
--text: #f2f4f8;
|
| 20 |
+
--dim: #9aa3b2;
|
| 21 |
+
--accent: #3b82f6;
|
| 22 |
+
--accent2: #2563eb;
|
| 23 |
+
--danger: #ef4444;
|
| 24 |
+
--ok: #22c55e;
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
html, body { height: 100%; }
|
| 28 |
+
body {
|
| 29 |
+
background: var(--bg);
|
| 30 |
+
color: var(--text);
|
| 31 |
+
font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", sans-serif;
|
| 32 |
+
overflow: hidden;
|
| 33 |
+
user-select: none;
|
| 34 |
+
-webkit-user-select: none;
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
.hidden { display: none !important; }
|
| 38 |
+
|
| 39 |
+
/* ---------- 通用按钮 ---------- */
|
| 40 |
+
button {
|
| 41 |
+
font-family: inherit;
|
| 42 |
+
border: none;
|
| 43 |
+
border-radius: 14px;
|
| 44 |
+
padding: 14px 18px;
|
| 45 |
+
font-size: 16px;
|
| 46 |
+
color: var(--text);
|
| 47 |
+
background: var(--card2);
|
| 48 |
+
cursor: pointer;
|
| 49 |
+
transition: transform .08s, opacity .15s, background .15s;
|
| 50 |
+
}
|
| 51 |
+
button:active { transform: scale(.97); }
|
| 52 |
+
button.primary { background: var(--accent); font-weight: 600; }
|
| 53 |
+
button.primary:active { background: var(--accent2); }
|
| 54 |
+
button.ghost { background: rgba(255,255,255,.12); }
|
| 55 |
+
button.danger { background: rgba(239,68,68,.15); color: #fca5a5; }
|
| 56 |
+
button.small { padding: 8px 14px; font-size: 14px; border-radius: 10px; }
|
| 57 |
+
button.round { width: 56px; height: 56px; border-radius: 50%; font-size: 22px; background: rgba(255,255,255,.12); }
|
| 58 |
+
button[disabled] { opacity: .5; pointer-events: none; }
|
| 59 |
+
|
| 60 |
+
/* ---------- 页面容器 ---------- */
|
| 61 |
+
.page {
|
| 62 |
+
position: fixed;
|
| 63 |
+
inset: 0;
|
| 64 |
+
display: flex;
|
| 65 |
+
flex-direction: column;
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
/* ---------- 登录页 ---------- */
|
| 69 |
+
#page-login { align-items: center; justify-content: center; padding: 24px; background: radial-gradient(1200px 500px at 50% -10%, #1b2b4a 0%, var(--bg) 60%); }
|
| 70 |
+
.login-box { width: 100%; max-width: 400px; }
|
| 71 |
+
.logo { font-size: 56px; text-align: center; margin-bottom: 8px; }
|
| 72 |
+
.login-box h1 { text-align: center; font-size: 26px; letter-spacing: 1px; }
|
| 73 |
+
.subtitle { text-align: center; color: var(--dim); margin: 8px 0 32px; font-size: 14px; }
|
| 74 |
+
.field { margin-bottom: 16px; }
|
| 75 |
+
.field label { display: block; color: var(--dim); font-size: 13px; margin-bottom: 6px; }
|
| 76 |
+
.field input {
|
| 77 |
+
width: 100%;
|
| 78 |
+
padding: 14px 16px;
|
| 79 |
+
font-size: 16px;
|
| 80 |
+
color: var(--text);
|
| 81 |
+
background: var(--card);
|
| 82 |
+
border: 1px solid var(--line);
|
| 83 |
+
border-radius: 14px;
|
| 84 |
+
outline: none;
|
| 85 |
+
}
|
| 86 |
+
.field input:focus { border-color: var(--accent); }
|
| 87 |
+
#btn-login { width: 100%; margin-top: 8px; }
|
| 88 |
+
.hint { text-align: center; color: var(--dim); font-size: 12px; margin-top: 14px; line-height: 1.6; }
|
| 89 |
+
|
| 90 |
+
/* ---------- 相机页 ---------- */
|
| 91 |
+
#tab-camera { position: relative; }
|
| 92 |
+
#cam-stage { position: absolute; inset: 0; background: #000; overflow: hidden; }
|
| 93 |
+
#cam-video { width: 100%; height: 100%; object-fit: cover; }
|
| 94 |
+
#cam-canvas { display: none; }
|
| 95 |
+
#cam-fallback {
|
| 96 |
+
position: absolute; inset: 0;
|
| 97 |
+
display: flex; flex-direction: column;
|
| 98 |
+
align-items: center; justify-content: center;
|
| 99 |
+
color: var(--dim); gap: 12px;
|
| 100 |
+
}
|
| 101 |
+
.fb-icon { font-size: 48px; }
|
| 102 |
+
#cam-controls {
|
| 103 |
+
position: absolute; left: 0; right: 0; bottom: calc(env(safe-area-inset-bottom, 0px) + 18px);
|
| 104 |
+
display: flex; align-items: center; justify-content: space-evenly;
|
| 105 |
+
padding: 0 30px;
|
| 106 |
+
}
|
| 107 |
+
.shutter {
|
| 108 |
+
width: 78px; height: 78px; border-radius: 50%;
|
| 109 |
+
background: #fff;
|
| 110 |
+
border: 6px solid rgba(255,255,255,.35);
|
| 111 |
+
background-clip: padding-box;
|
| 112 |
+
font-size: 30px;
|
| 113 |
+
}
|
| 114 |
+
.shutter:active { transform: scale(.92); }
|
| 115 |
+
|
| 116 |
+
/* 拍照预览 */
|
| 117 |
+
#shot-preview {
|
| 118 |
+
position: absolute; inset: 0;
|
| 119 |
+
background: #000;
|
| 120 |
+
display: flex; flex-direction: column;
|
| 121 |
+
align-items: center; justify-content: center;
|
| 122 |
+
padding: 20px;
|
| 123 |
+
}
|
| 124 |
+
#shot-preview img { max-width: 100%; max-height: 62vh; border-radius: 12px; box-shadow: 0 8px 40px rgba(0,0,0,.6); }
|
| 125 |
+
.shot-actions { display: flex; gap: 12px; margin-top: 20px; width: 100%; max-width: 420px; }
|
| 126 |
+
.shot-actions button { flex: 1; }
|
| 127 |
+
|
| 128 |
+
/* 上传进度 */
|
| 129 |
+
#upload-progress {
|
| 130 |
+
position: absolute; left: 24px; right: 24px; top: calc(env(safe-area-inset-top, 0px) + 20px);
|
| 131 |
+
background: var(--card);
|
| 132 |
+
border-radius: 12px;
|
| 133 |
+
padding: 14px;
|
| 134 |
+
text-align: center;
|
| 135 |
+
z-index: 5;
|
| 136 |
+
box-shadow: 0 8px 30px rgba(0,0,0,.5);
|
| 137 |
+
}
|
| 138 |
+
#upload-bar {
|
| 139 |
+
height: 6px; width: 0%;
|
| 140 |
+
background: var(--accent);
|
| 141 |
+
border-radius: 3px;
|
| 142 |
+
margin-bottom: 8px;
|
| 143 |
+
transition: width .2s;
|
| 144 |
+
}
|
| 145 |
+
#upload-text { font-size: 13px; color: var(--dim); }
|
| 146 |
+
|
| 147 |
+
/* ---------- 相册页 ---------- */
|
| 148 |
+
#tab-album { padding-top: calc(env(safe-area-inset-top, 0px) + 12px); padding-bottom: 90px; overflow-y: auto; }
|
| 149 |
+
.tab-head {
|
| 150 |
+
display: flex; align-items: center; justify-content: space-between;
|
| 151 |
+
padding: 8px 16px 14px;
|
| 152 |
+
position: sticky; top: 0;
|
| 153 |
+
background: var(--bg);
|
| 154 |
+
z-index: 2;
|
| 155 |
+
}
|
| 156 |
+
.tab-head h2 { font-size: 18px; }
|
| 157 |
+
#album-grid {
|
| 158 |
+
display: grid;
|
| 159 |
+
grid-template-columns: repeat(3, 1fr);
|
| 160 |
+
gap: 3px;
|
| 161 |
+
padding: 0 3px;
|
| 162 |
+
}
|
| 163 |
+
#album-grid img {
|
| 164 |
+
width: 100%;
|
| 165 |
+
aspect-ratio: 1;
|
| 166 |
+
object-fit: cover;
|
| 167 |
+
border-radius: 2px;
|
| 168 |
+
background: var(--card);
|
| 169 |
+
}
|
| 170 |
+
#album-empty { text-align: center; padding: 80px 20px; color: var(--dim); }
|
| 171 |
+
.empty-icon { font-size: 56px; margin-bottom: 14px; }
|
| 172 |
+
#album-more { text-align: center; color: var(--dim); font-size: 13px; padding: 18px; }
|
| 173 |
+
|
| 174 |
+
/* ---------- 设置页 ---------- */
|
| 175 |
+
#tab-settings { padding: calc(env(safe-area-inset-top, 0px) + 12px) 16px 90px; overflow-y: auto; }
|
| 176 |
+
.card {
|
| 177 |
+
background: var(--card);
|
| 178 |
+
border-radius: 16px;
|
| 179 |
+
margin-bottom: 20px;
|
| 180 |
+
overflow: hidden;
|
| 181 |
+
}
|
| 182 |
+
.card-row {
|
| 183 |
+
display: flex; align-items: center; justify-content: space-between;
|
| 184 |
+
padding: 16px;
|
| 185 |
+
border-bottom: 1px solid var(--line);
|
| 186 |
+
font-size: 15px;
|
| 187 |
+
color: var(--dim);
|
| 188 |
+
}
|
| 189 |
+
.card-row b { color: var(--text); }
|
| 190 |
+
.switch-row { cursor: pointer; position: relative; padding-right: 64px; }
|
| 191 |
+
.switch-row input { display: none; }
|
| 192 |
+
.switch {
|
| 193 |
+
position: absolute; right: 16px; top: 50%; transform: translateY(-50%);
|
| 194 |
+
width: 46px; height: 26px;
|
| 195 |
+
background: var(--card2);
|
| 196 |
+
border-radius: 13px;
|
| 197 |
+
transition: background .2s;
|
| 198 |
+
}
|
| 199 |
+
.switch::after {
|
| 200 |
+
content: "";
|
| 201 |
+
position: absolute; top: 3px; left: 3px;
|
| 202 |
+
width: 20px; height: 20px;
|
| 203 |
+
background: #fff;
|
| 204 |
+
border-radius: 50%;
|
| 205 |
+
transition: transform .2s;
|
| 206 |
+
}
|
| 207 |
+
.switch-row input:checked + .switch { background: var(--accent); }
|
| 208 |
+
.switch-row input:checked + .switch::after { transform: translateX(20px); }
|
| 209 |
+
#btn-logout { width: 100%; margin-bottom: 24px; }
|
| 210 |
+
.about { color: var(--dim); font-size: 12px; text-align: center; line-height: 2; }
|
| 211 |
+
|
| 212 |
+
/* ---------- 底部导航 ---------- */
|
| 213 |
+
#tabbar {
|
| 214 |
+
position: absolute; left: 0; right: 0; bottom: 0;
|
| 215 |
+
display: flex;
|
| 216 |
+
background: rgba(18,20,26,.96);
|
| 217 |
+
border-top: 1px solid var(--line);
|
| 218 |
+
padding-bottom: env(safe-area-inset-bottom, 0px);
|
| 219 |
+
z-index: 10;
|
| 220 |
+
}
|
| 221 |
+
.tab-btn {
|
| 222 |
+
flex: 1;
|
| 223 |
+
display: flex; flex-direction: column; align-items: center;
|
| 224 |
+
gap: 3px;
|
| 225 |
+
background: transparent;
|
| 226 |
+
border-radius: 0;
|
| 227 |
+
padding: 9px 0 8px;
|
| 228 |
+
font-size: 11px;
|
| 229 |
+
color: var(--dim);
|
| 230 |
+
}
|
| 231 |
+
.tab-btn.active { color: var(--accent); }
|
| 232 |
+
.tb-icon { font-size: 20px; }
|
| 233 |
+
|
| 234 |
+
/* ---------- 大图查看器 ---------- */
|
| 235 |
+
#viewer {
|
| 236 |
+
position: fixed; inset: 0;
|
| 237 |
+
background: rgba(0,0,0,.95);
|
| 238 |
+
z-index: 50;
|
| 239 |
+
display: flex; flex-direction: column;
|
| 240 |
+
align-items: center; justify-content: center;
|
| 241 |
+
padding: 20px;
|
| 242 |
+
}
|
| 243 |
+
#viewer-img { max-width: 100%; max-height: 66vh; border-radius: 10px; }
|
| 244 |
+
#viewer-info { color: var(--dim); font-size: 13px; margin: 16px 0; text-align: center; line-height: 1.8; }
|
| 245 |
+
.viewer-actions { display: flex; gap: 12px; }
|
| 246 |
+
#btn-viewer-close {
|
| 247 |
+
position: absolute; top: calc(env(safe-area-inset-top, 0px) + 16px); right: 16px;
|
| 248 |
+
width: 40px; height: 40px; border-radius: 50%;
|
| 249 |
+
font-size: 16px;
|
| 250 |
+
background: rgba(255,255,255,.15);
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
/* ---------- Toast ---------- */
|
| 254 |
+
#toast {
|
| 255 |
+
position: fixed; left: 50%; bottom: 110px;
|
| 256 |
+
transform: translateX(-50%);
|
| 257 |
+
background: rgba(20,22,28,.95);
|
| 258 |
+
color: var(--text);
|
| 259 |
+
padding: 12px 22px;
|
| 260 |
+
border-radius: 12px;
|
| 261 |
+
font-size: 14px;
|
| 262 |
+
z-index: 100;
|
| 263 |
+
max-width: 84vw;
|
| 264 |
+
text-align: center;
|
| 265 |
+
box-shadow: 0 8px 30px rgba(0,0,0,.5);
|
| 266 |
+
animation: toast-in .2s;
|
| 267 |
+
}
|
| 268 |
+
#toast.ok { border: 1px solid rgba(34,197,94,.5); }
|
| 269 |
+
#toast.err { border: 1px solid rgba(239,68,68,.5); }
|
| 270 |
+
@keyframes toast-in { from { opacity: 0; transform: translate(-50%, 8px); } to { opacity: 1; transform: translate(-50%, 0); } }
|
| 271 |
+
|
| 272 |
+
</style>
|
| 273 |
+
</head>
|
| 274 |
+
<body>
|
| 275 |
+
|
| 276 |
+
<!-- ============ 登录页 ============ -->
|
| 277 |
+
<div id="page-login" class="page">
|
| 278 |
+
<div class="login-box">
|
| 279 |
+
<div class="logo">📷</div>
|
| 280 |
+
<h1>云端相机</h1>
|
| 281 |
+
<p class="subtitle">拍照即传云端,走到哪看到哪</p>
|
| 282 |
+
<div class="field">
|
| 283 |
+
<label for="login-username">用户名</label>
|
| 284 |
+
<input id="login-username" type="text" placeholder="给自己起个名字" maxlength="24" autocomplete="username">
|
| 285 |
+
</div>
|
| 286 |
+
<div class="field">
|
| 287 |
+
<label for="login-pin">PIN 码</label>
|
| 288 |
+
<input id="login-pin" type="password" placeholder="4-20 位,保护你的相册" maxlength="20" autocomplete="current-password">
|
| 289 |
+
</div>
|
| 290 |
+
<button id="btn-login" class="primary">进入云端相册</button>
|
| 291 |
+
<p class="hint">首次使用输入用户名和 PIN 会自动创建你的专属相册</p>
|
| 292 |
+
</div>
|
| 293 |
+
</div>
|
| 294 |
+
|
| 295 |
+
<!-- ============ 主界面 ============ -->
|
| 296 |
+
<div id="page-app" class="page hidden">
|
| 297 |
+
|
| 298 |
+
<!-- 相机页 -->
|
| 299 |
+
<section id="tab-camera" class="tab active">
|
| 300 |
+
<div id="cam-stage">
|
| 301 |
+
<video id="cam-video" autoplay playsinline muted></video>
|
| 302 |
+
<canvas id="cam-canvas" class="hidden"></canvas>
|
| 303 |
+
<div id="cam-fallback" class="hidden">
|
| 304 |
+
<div class="fb-icon">🚫</div>
|
| 305 |
+
<p>无法启动实时预览(请确认已授权摄像头)</p>
|
| 306 |
+
</div>
|
| 307 |
+
<!-- 拍照预览 -->
|
| 308 |
+
<div id="shot-preview" class="hidden">
|
| 309 |
+
<img id="shot-img" alt="预览">
|
| 310 |
+
<div class="shot-actions">
|
| 311 |
+
<button id="btn-retake" class="ghost">↻ 重拍</button>
|
| 312 |
+
<button id="btn-save-local">💾 存本地</button>
|
| 313 |
+
<button id="btn-upload-cloud" class="primary">☁️ 传云端</button>
|
| 314 |
+
</div>
|
| 315 |
+
<p class="hint" id="shot-hint">上传后可在云端相册随时查看</p>
|
| 316 |
+
</div>
|
| 317 |
+
<!-- 取景控制 -->
|
| 318 |
+
<div id="cam-controls">
|
| 319 |
+
<button id="btn-switch" class="round" title="切换前后摄像头">🔄</button>
|
| 320 |
+
<button id="btn-shutter" class="shutter" title="拍照">📷</button>
|
| 321 |
+
<button id="btn-album-pick" class="round" title="从手机相册选照片">🖼</button>
|
| 322 |
+
</div>
|
| 323 |
+
</div>
|
| 324 |
+
<div id="upload-progress" class="hidden"><div id="upload-bar"></div><span id="upload-text">上传中</span></div>
|
| 325 |
+
</section>
|
| 326 |
+
|
| 327 |
+
<!-- 相册页 -->
|
| 328 |
+
<section id="tab-album" class="tab">
|
| 329 |
+
<div class="tab-head">
|
| 330 |
+
<h2>云端相册</h2>
|
| 331 |
+
<button id="btn-refresh" class="small">↻ 刷新</button>
|
| 332 |
+
</div>
|
| 333 |
+
<div id="album-grid"></div>
|
| 334 |
+
<div id="album-empty" class="hidden">
|
| 335 |
+
<div class="empty-icon">🖼</div>
|
| 336 |
+
<p>相册还是空的</p>
|
| 337 |
+
<p class="hint">切到「相机」页拍第一张照片吧</p>
|
| 338 |
+
</div>
|
| 339 |
+
<div id="album-more" class="hidden">上拉加载更多</div>
|
| 340 |
+
</section>
|
| 341 |
+
|
| 342 |
+
<!-- 设置页 -->
|
| 343 |
+
<section id="tab-settings" class="tab">
|
| 344 |
+
<div class="tab-head"><h2>设置</h2></div>
|
| 345 |
+
<div class="card">
|
| 346 |
+
<div class="card-row">
|
| 347 |
+
<span>当前用户</span>
|
| 348 |
+
<b id="set-username">-</b>
|
| 349 |
+
</div>
|
| 350 |
+
<label class="card-row switch-row">
|
| 351 |
+
<span>上传后自动存一份到本地</span>
|
| 352 |
+
<input type="checkbox" id="set-autosave">
|
| 353 |
+
<span class="switch"></span>
|
| 354 |
+
</label>
|
| 355 |
+
</div>
|
| 356 |
+
<button id="btn-logout" class="danger">退出登录</button>
|
| 357 |
+
<div class="about">
|
| 358 |
+
<p>照片存储于你的 Hugging Face 云空间,受 PIN 保护</p>
|
| 359 |
+
<p>云端相机 v1.0</p>
|
| 360 |
+
</div>
|
| 361 |
+
</section>
|
| 362 |
+
|
| 363 |
+
<!-- 底部导航 -->
|
| 364 |
+
<nav id="tabbar">
|
| 365 |
+
<button class="tab-btn active" data-tab="camera"><span class="tb-icon">📷</span>相机</button>
|
| 366 |
+
<button class="tab-btn" data-tab="album"><span class="tb-icon">🖼</span>相册</button>
|
| 367 |
+
<button class="tab-btn" data-tab="settings"><span class="tb-icon">⚙️</span>设置</button>
|
| 368 |
+
</nav>
|
| 369 |
+
</div>
|
| 370 |
+
|
| 371 |
+
<!-- ============ 大图查看器 ============ -->
|
| 372 |
+
<div id="viewer" class="hidden">
|
| 373 |
+
<img id="viewer-img" alt="查看">
|
| 374 |
+
<div id="viewer-info"></div>
|
| 375 |
+
<div class="viewer-actions">
|
| 376 |
+
<button id="btn-viewer-download">💾 下载</button>
|
| 377 |
+
<button id="btn-viewer-delete" class="danger">🗑 删除</button>
|
| 378 |
+
</div>
|
| 379 |
+
<button id="btn-viewer-close" class="close">✕</button>
|
| 380 |
+
</div>
|
| 381 |
+
|
| 382 |
+
<!-- 隐藏的图片选择器(系统相机 / 相册) -->
|
| 383 |
+
<input type="file" id="file-input" accept="image/*" class="hidden">
|
| 384 |
+
|
| 385 |
+
<div id="toast" class="hidden"></div>
|
| 386 |
+
|
| 387 |
+
<script>
|
| 388 |
+
/* 云端相机 - 前端逻辑 */
|
| 389 |
+
(function () {
|
| 390 |
+
"use strict";
|
| 391 |
+
|
| 392 |
+
// ---------- 状态 ----------
|
| 393 |
+
var user = null; // { username, pin }
|
| 394 |
+
var allPhotos = []; // 云端相册全部照片元数据
|
| 395 |
+
var renderedCount = 0; // 已渲染张数
|
| 396 |
+
var PAGE = 30;
|
| 397 |
+
var currentPhoto = null; // 查看器中的照片
|
| 398 |
+
var shotBlob = null; // 拍照/选择后的图片 blob
|
| 399 |
+
var stream = null; // 摄像头流
|
| 400 |
+
var uploading = false;
|
| 401 |
+
|
| 402 |
+
var LS_USER = "cc_user";
|
| 403 |
+
var LS_AUTOSAVE = "cc_autosave";
|
| 404 |
+
|
| 405 |
+
// ---------- DOM ----------
|
| 406 |
+
var $ = function (id) { return document.getElementById(id); };
|
| 407 |
+
var els = {
|
| 408 |
+
pageLogin: $("page-login"),
|
| 409 |
+
pageApp: $("page-app"),
|
| 410 |
+
loginUsername: $("login-username"),
|
| 411 |
+
loginPin: $("login-pin"),
|
| 412 |
+
btnLogin: $("btn-login"),
|
| 413 |
+
camVideo: $("cam-video"),
|
| 414 |
+
camCanvas: $("cam-canvas"),
|
| 415 |
+
camFallback: $("cam-fallback"),
|
| 416 |
+
camControls: $("cam-controls"),
|
| 417 |
+
btnSwitch: $("btn-switch"),
|
| 418 |
+
btnShutter: $("btn-shutter"),
|
| 419 |
+
btnAlbumPick: $("btn-album-pick"),
|
| 420 |
+
shotPreview: $("shot-preview"),
|
| 421 |
+
shotImg: $("shot-img"),
|
| 422 |
+
btnRetake: $("btn-retake"),
|
| 423 |
+
btnSaveLocal: $("btn-save-local"),
|
| 424 |
+
btnUploadCloud: $("btn-upload-cloud"),
|
| 425 |
+
shotHint: $("shot-hint"),
|
| 426 |
+
uploadProgress: $("upload-progress"),
|
| 427 |
+
uploadBar: $("upload-bar"),
|
| 428 |
+
uploadText: $("upload-text"),
|
| 429 |
+
albumGrid: $("album-grid"),
|
| 430 |
+
albumEmpty: $("album-empty"),
|
| 431 |
+
albumMore: $("album-more"),
|
| 432 |
+
btnRefresh: $("btn-refresh"),
|
| 433 |
+
setUsername: $("set-username"),
|
| 434 |
+
setAutosave: $("set-autosave"),
|
| 435 |
+
btnLogout: $("btn-logout"),
|
| 436 |
+
viewer: $("viewer"),
|
| 437 |
+
viewerImg: $("viewer-img"),
|
| 438 |
+
viewerInfo: $("viewer-info"),
|
| 439 |
+
btnViewerDownload: $("btn-viewer-download"),
|
| 440 |
+
btnViewerDelete: $("btn-viewer-delete"),
|
| 441 |
+
btnViewerClose: $("btn-viewer-close"),
|
| 442 |
+
fileInput: $("file-input"),
|
| 443 |
+
toast: $("toast"),
|
| 444 |
+
};
|
| 445 |
+
|
| 446 |
+
// ---------- 工具 ----------
|
| 447 |
+
function toast(msg, type) {
|
| 448 |
+
els.toast.textContent = msg;
|
| 449 |
+
els.toast.className = type || "";
|
| 450 |
+
clearTimeout(toast._t);
|
| 451 |
+
toast._t = setTimeout(function () { els.toast.className = "hidden"; }, 2400);
|
| 452 |
+
}
|
| 453 |
+
|
| 454 |
+
function fmtSize(bytes) {
|
| 455 |
+
if (bytes < 1024) return bytes + " B";
|
| 456 |
+
if (bytes < 1048576) return (bytes / 1024).toFixed(1) + " KB";
|
| 457 |
+
return (bytes / 1048576).toFixed(1) + " MB";
|
| 458 |
+
}
|
| 459 |
+
|
| 460 |
+
function apiHeaders() {
|
| 461 |
+
return user ? { "X-Pin": user.pin } : {};
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
function saveUser() {
|
| 465 |
+
try { localStorage.setItem(LS_USER, JSON.stringify(user)); } catch (e) {}
|
| 466 |
+
}
|
| 467 |
+
|
| 468 |
+
// ---------- 页面 / Tab ----------
|
| 469 |
+
function showLogin() {
|
| 470 |
+
els.pageLogin.classList.remove("hidden");
|
| 471 |
+
els.pageApp.classList.add("hidden");
|
| 472 |
+
}
|
| 473 |
+
|
| 474 |
+
function showApp() {
|
| 475 |
+
els.pageLogin.classList.add("hidden");
|
| 476 |
+
els.pageApp.classList.remove("hidden");
|
| 477 |
+
els.setUsername.textContent = user.username;
|
| 478 |
+
try { els.setAutosave.checked = localStorage.getItem(LS_AUTOSAVE) === "1"; } catch (e) {}
|
| 479 |
+
switchTab("album");
|
| 480 |
+
loadPhotos();
|
| 481 |
+
}
|
| 482 |
+
|
| 483 |
+
function switchTab(tab) {
|
| 484 |
+
document.querySelectorAll(".tab").forEach(function (t) { t.classList.remove("active"); });
|
| 485 |
+
document.querySelectorAll(".tab-btn").forEach(function (b) { b.classList.remove("active"); });
|
| 486 |
+
$("tab-" + tab).classList.add("active");
|
| 487 |
+
document.querySelector('.tab-btn[data-tab="' + tab + '"]').classList.add("active");
|
| 488 |
+
if (tab === "camera") startCamera();
|
| 489 |
+
if (tab === "album") loadPhotos();
|
| 490 |
+
}
|
| 491 |
+
|
| 492 |
+
// ---------- 登录 ----------
|
| 493 |
+
els.btnLogin.addEventListener("click", doLogin);
|
| 494 |
+
els.loginPin.addEventListener("keydown", function (e) { if (e.key === "Enter") doLogin(); });
|
| 495 |
+
els.loginUsername.addEventListener("keydown", function (e) { if (e.key === "Enter") els.loginPin.focus(); });
|
| 496 |
+
|
| 497 |
+
function doLogin() {
|
| 498 |
+
var username = els.loginUsername.value.trim();
|
| 499 |
+
var pin = els.loginPin.value;
|
| 500 |
+
if (!username) { toast("请输入用户名", "err"); return; }
|
| 501 |
+
if (pin.length < 4) { toast("PIN 至少 4 位", "err"); return; }
|
| 502 |
+
els.btnLogin.disabled = true;
|
| 503 |
+
els.btnLogin.textContent = "登录中...";
|
| 504 |
+
fetch("/api/login", {
|
| 505 |
+
method: "POST",
|
| 506 |
+
headers: { "Content-Type": "application/json" },
|
| 507 |
+
body: JSON.stringify({ username: username, pin: pin }),
|
| 508 |
+
}).then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); })
|
| 509 |
+
.then(function (res) {
|
| 510 |
+
if (!res.ok) throw new Error(res.d.detail || "登录失败");
|
| 511 |
+
user = { username: username, pin: pin };
|
| 512 |
+
saveUser();
|
| 513 |
+
toast(res.d.is_new ? "相册创建成功,欢迎!" : "欢迎回来," + username, "ok");
|
| 514 |
+
showApp();
|
| 515 |
+
})
|
| 516 |
+
.catch(function (err) { toast(err.message, "err"); })
|
| 517 |
+
.finally(function () {
|
| 518 |
+
els.btnLogin.disabled = false;
|
| 519 |
+
els.btnLogin.textContent = "进入云端相册";
|
| 520 |
+
});
|
| 521 |
+
}
|
| 522 |
+
|
| 523 |
+
// ---------- 相机 ----------
|
| 524 |
+
var facing = "environment";
|
| 525 |
+
|
| 526 |
+
function startCamera() {
|
| 527 |
+
if (!els.shotPreview.classList.contains("hidden")) return; // 预览中不重启
|
| 528 |
+
if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
|
| 529 |
+
els.camFallback.classList.remove("hidden");
|
| 530 |
+
els.camControls.classList.add("hidden");
|
| 531 |
+
return;
|
| 532 |
+
}
|
| 533 |
+
stopStream();
|
| 534 |
+
els.camVideo.classList.remove("hidden");
|
| 535 |
+
els.camFallback.classList.add("hidden");
|
| 536 |
+
els.camControls.classList.remove("hidden");
|
| 537 |
+
var opts = { audio: false, video: { facingMode: { ideal: facing }, width: { ideal: 1920 }, height: { ideal: 1080 } } };
|
| 538 |
+
navigator.mediaDevices.getUserMedia(opts)
|
| 539 |
+
.then(function (s) {
|
| 540 |
+
stream = s;
|
| 541 |
+
els.camVideo.srcObject = s;
|
| 542 |
+
})
|
| 543 |
+
.catch(function () {
|
| 544 |
+
// 尝试不带 facingMode
|
| 545 |
+
navigator.mediaDevices.getUserMedia({ audio: false, video: true })
|
| 546 |
+
.then(function (s) {
|
| 547 |
+
stream = s;
|
| 548 |
+
els.camVideo.srcObject = s;
|
| 549 |
+
})
|
| 550 |
+
.catch(function () {
|
| 551 |
+
els.camVideo.classList.add("hidden");
|
| 552 |
+
els.camFallback.classList.remove("hidden");
|
| 553 |
+
els.camControls.classList.add("hidden");
|
| 554 |
+
});
|
| 555 |
+
});
|
| 556 |
+
}
|
| 557 |
+
|
| 558 |
+
function stopStream() {
|
| 559 |
+
if (stream) { stream.getTracks().forEach(function (t) { t.stop(); }); stream = null; }
|
| 560 |
+
if (els.camVideo.srcObject) { els.camVideo.srcObject = null; }
|
| 561 |
+
}
|
| 562 |
+
|
| 563 |
+
els.btnSwitch.addEventListener("click", function () {
|
| 564 |
+
facing = facing === "environment" ? "user" : "environment";
|
| 565 |
+
startCamera();
|
| 566 |
+
});
|
| 567 |
+
|
| 568 |
+
// 快门:截取当前帧
|
| 569 |
+
els.btnShutter.addEventListener("click", function () {
|
| 570 |
+
if (els.camVideo.readyState < 2) { toast("相机还没准备好", "err"); return; }
|
| 571 |
+
var v = els.camVideo;
|
| 572 |
+
var canvas = els.camCanvas;
|
| 573 |
+
canvas.width = v.videoWidth;
|
| 574 |
+
canvas.height = v.videoHeight;
|
| 575 |
+
canvas.getContext("2d").drawImage(v, 0, 0);
|
| 576 |
+
canvas.toBlob(function (blob) {
|
| 577 |
+
if (!blob) { toast("拍照失败,请重试", "err"); return; }
|
| 578 |
+
showShotPreview(blob);
|
| 579 |
+
}, "image/jpeg", 0.92);
|
| 580 |
+
});
|
| 581 |
+
|
| 582 |
+
// 从系统相机 / 相册选图
|
| 583 |
+
els.btnAlbumPick.addEventListener("click", function () { els.fileInput.removeAttribute("capture"); els.fileInput.click(); });
|
| 584 |
+
els.fileInput.addEventListener("change", function () {
|
| 585 |
+
var f = els.fileInput.files && els.fileInput.files[0];
|
| 586 |
+
els.fileInput.value = "";
|
| 587 |
+
if (!f) return;
|
| 588 |
+
if (f.size > 20 * 1024 * 1024) { toast("图片超过 20MB", "err"); return; }
|
| 589 |
+
showShotPreview(f);
|
| 590 |
+
});
|
| 591 |
+
|
| 592 |
+
function showShotPreview(src) {
|
| 593 |
+
stopStream();
|
| 594 |
+
els.camVideo.classList.add("hidden");
|
| 595 |
+
els.camControls.classList.add("hidden");
|
| 596 |
+
els.camFallback.classList.add("hidden");
|
| 597 |
+
els.shotPreview.classList.remove("hidden");
|
| 598 |
+
if (src instanceof Blob) {
|
| 599 |
+
shotBlob = src;
|
| 600 |
+
els.shotImg.src = URL.createObjectURL(src);
|
| 601 |
+
} else {
|
| 602 |
+
shotBlob = src;
|
| 603 |
+
els.shotImg.src = URL.createObjectURL(src);
|
| 604 |
+
}
|
| 605 |
+
}
|
| 606 |
+
|
| 607 |
+
els.btnRetake.addEventListener("click", function () {
|
| 608 |
+
els.shotPreview.classList.add("hidden");
|
| 609 |
+
els.shotImg.src = "";
|
| 610 |
+
shotBlob = null;
|
| 611 |
+
startCamera();
|
| 612 |
+
});
|
| 613 |
+
|
| 614 |
+
// 保存到本地(下载)
|
| 615 |
+
function saveBlobToLocal(blob, name) {
|
| 616 |
+
var url = URL.createObjectURL(blob);
|
| 617 |
+
var a = document.createElement("a");
|
| 618 |
+
a.href = url;
|
| 619 |
+
a.download = name || ("photo_" + Date.now() + ".jpg");
|
| 620 |
+
document.body.appendChild(a);
|
| 621 |
+
a.click();
|
| 622 |
+
document.body.removeChild(a);
|
| 623 |
+
setTimeout(function () { URL.revokeObjectURL(url); }, 5000);
|
| 624 |
+
toast("已保存到本地(如未自动保存,请在浏览器下载记录中查看)", "ok");
|
| 625 |
+
}
|
| 626 |
+
|
| 627 |
+
els.btnSaveLocal.addEventListener("click", function () {
|
| 628 |
+
if (!shotBlob) return;
|
| 629 |
+
var name = user ? ("cc_" + user.username + "_" + Date.now() + ".jpg") : "photo.jpg";
|
| 630 |
+
saveBlobToLocal(shotBlob, name);
|
| 631 |
+
});
|
| 632 |
+
|
| 633 |
+
// 上传云端(XHR 带进度)
|
| 634 |
+
els.btnUploadCloud.addEventListener("click", uploadShot);
|
| 635 |
+
function uploadShot() {
|
| 636 |
+
if (!shotBlob || uploading) return;
|
| 637 |
+
if (shotBlob instanceof File && !shotBlob.type) { /* ignore */ }
|
| 638 |
+
uploading = true;
|
| 639 |
+
var fd = new FormData();
|
| 640 |
+
fd.append("username", user.username);
|
| 641 |
+
fd.append("pin", user.pin);
|
| 642 |
+
var fname = shotBlob instanceof File ? shotBlob.name : ("camera_" + Date.now() + ".jpg");
|
| 643 |
+
fd.append("file", shotBlob, fname);
|
| 644 |
+
|
| 645 |
+
els.uploadProgress.classList.remove("hidden");
|
| 646 |
+
els.uploadBar.style.width = "0%";
|
| 647 |
+
els.uploadText.textContent = "上传中 0%";
|
| 648 |
+
|
| 649 |
+
var xhr = new XMLHttpRequest();
|
| 650 |
+
xhr.open("POST", "/api/upload");
|
| 651 |
+
xhr.upload.onprogress = function (e) {
|
| 652 |
+
if (e.lengthComputable) {
|
| 653 |
+
var pct = Math.round(e.loaded / e.total * 100);
|
| 654 |
+
els.uploadBar.style.width = pct + "%";
|
| 655 |
+
els.uploadText.textContent = "上传中 " + pct + "%";
|
| 656 |
+
}
|
| 657 |
+
};
|
| 658 |
+
xhr.onload = function () {
|
| 659 |
+
els.uploadProgress.classList.add("hidden");
|
| 660 |
+
uploading = false;
|
| 661 |
+
var res;
|
| 662 |
+
try { res = JSON.parse(xhr.responseText); } catch (e) { res = null; }
|
| 663 |
+
if (xhr.status === 200 && res && res.ok) {
|
| 664 |
+
if (localStorage.getItem(LS_AUTOSAVE) === "1") {
|
| 665 |
+
try { saveBlobToLocal(shotBlob, "cc_" + user.username + "_" + Date.now() + ".jpg"); } catch (e) {}
|
| 666 |
+
}
|
| 667 |
+
toast("已上传到云端相册", "ok");
|
| 668 |
+
els.btnRetake.click();
|
| 669 |
+
loadPhotos();
|
| 670 |
+
} else {
|
| 671 |
+
toast((res && res.detail) || "上传失败,请重试", "err");
|
| 672 |
+
}
|
| 673 |
+
};
|
| 674 |
+
xhr.onerror = function () {
|
| 675 |
+
els.uploadProgress.classList.add("hidden");
|
| 676 |
+
uploading = false;
|
| 677 |
+
toast("网络错误,上传失败", "err");
|
| 678 |
+
};
|
| 679 |
+
xhr.send(fd);
|
| 680 |
+
}
|
| 681 |
+
|
| 682 |
+
// ---------- 相册 ----------
|
| 683 |
+
function loadPhotos() {
|
| 684 |
+
if (!user) return;
|
| 685 |
+
fetch("/api/photos?username=" + encodeURIComponent(user.username), { headers: apiHeaders() })
|
| 686 |
+
.then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); })
|
| 687 |
+
.then(function (res) {
|
| 688 |
+
if (!res.ok) throw new Error(res.d.detail || "加载失败");
|
| 689 |
+
allPhotos = res.d.photos || [];
|
| 690 |
+
renderedCount = 0;
|
| 691 |
+
els.albumGrid.innerHTML = "";
|
| 692 |
+
els.albumEmpty.classList.toggle("hidden", allPhotos.length > 0);
|
| 693 |
+
els.albumMore.classList.add("hidden");
|
| 694 |
+
renderMore();
|
| 695 |
+
})
|
| 696 |
+
.catch(function (err) {
|
| 697 |
+
if (err.message.indexOf("PIN") >= 0 || err.message.indexOf("用户名") >= 0) {
|
| 698 |
+
toast("登录状态失效,请重新登录", "err");
|
| 699 |
+
logout();
|
| 700 |
+
} else {
|
| 701 |
+
toast(err.message, "err");
|
| 702 |
+
}
|
| 703 |
+
});
|
| 704 |
+
}
|
| 705 |
+
|
| 706 |
+
function renderMore() {
|
| 707 |
+
var chunk = allPhotos.slice(renderedCount, renderedCount + PAGE);
|
| 708 |
+
chunk.forEach(function (p) {
|
| 709 |
+
var img = document.createElement("img");
|
| 710 |
+
img.loading = "lazy";
|
| 711 |
+
img.src = p.thumb_url;
|
| 712 |
+
img.alt = p.name || "";
|
| 713 |
+
img.dataset.id = p.id;
|
| 714 |
+
img.addEventListener("click", function () { openViewer(p); });
|
| 715 |
+
els.albumGrid.appendChild(img);
|
| 716 |
+
});
|
| 717 |
+
renderedCount += chunk.length;
|
| 718 |
+
els.albumMore.classList.toggle("hidden", renderedCount >= allPhotos.length);
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
// 滚动加载
|
| 722 |
+
$("tab-album").addEventListener("scroll", function () {
|
| 723 |
+
var el = this;
|
| 724 |
+
if (el.scrollTop + el.clientHeight >= el.scrollHeight - 120) renderMore();
|
| 725 |
+
});
|
| 726 |
+
|
| 727 |
+
els.btnRefresh.addEventListener("click", function () {
|
| 728 |
+
els.btnRefresh.textContent = "刷新中...";
|
| 729 |
+
loadPhotos();
|
| 730 |
+
setTimeout(function () { els.btnRefresh.textContent = "↻ 刷新"; }, 600);
|
| 731 |
+
});
|
| 732 |
+
|
| 733 |
+
// ---------- 大图查看器 ----------
|
| 734 |
+
function openViewer(p) {
|
| 735 |
+
currentPhoto = p;
|
| 736 |
+
els.viewerImg.src = p.url;
|
| 737 |
+
els.viewerInfo.textContent = p.name + " · " + fmtSize(p.size) + " · " + p.uploaded_at +
|
| 738 |
+
(p.width ? " · " + p.width + "×" + p.height : "");
|
| 739 |
+
els.viewer.classList.remove("hidden");
|
| 740 |
+
}
|
| 741 |
+
|
| 742 |
+
els.btnViewerClose.addEventListener("click", function () {
|
| 743 |
+
els.viewer.classList.add("hidden");
|
| 744 |
+
els.viewerImg.src = "";
|
| 745 |
+
currentPhoto = null;
|
| 746 |
+
});
|
| 747 |
+
|
| 748 |
+
els.btnViewerDownload.addEventListener("click", function () {
|
| 749 |
+
if (!currentPhoto) return;
|
| 750 |
+
fetch(currentPhoto.url)
|
| 751 |
+
.then(function (r) { if (!r.ok) throw new Error(); return r.blob(); })
|
| 752 |
+
.then(function (blob) { saveBlobToLocal(blob, currentPhoto.name || (currentPhoto.id + ".jpg")); })
|
| 753 |
+
.catch(function () { toast("下载失败,请重试", "err"); });
|
| 754 |
+
});
|
| 755 |
+
|
| 756 |
+
els.btnViewerDelete.addEventListener("click", function () {
|
| 757 |
+
if (!currentPhoto) return;
|
| 758 |
+
if (!window.confirm("确定删除这张照片吗?云端和本地副本都会被删掉(本地已下载的不受影响)。")) return;
|
| 759 |
+
fetch("/api/photo/" + encodeURIComponent(user.username) + "/" + currentPhoto.id, {
|
| 760 |
+
method: "DELETE",
|
| 761 |
+
headers: apiHeaders(),
|
| 762 |
+
}).then(function (r) { return r.json().then(function (d) { return { ok: r.ok, d: d }; }); })
|
| 763 |
+
.then(function (res) {
|
| 764 |
+
if (!res.ok) throw new Error(res.d.detail || "删除失败");
|
| 765 |
+
els.viewer.classList.add("hidden");
|
| 766 |
+
els.viewerImg.src = "";
|
| 767 |
+
currentPhoto = null;
|
| 768 |
+
toast("已删除", "ok");
|
| 769 |
+
loadPhotos();
|
| 770 |
+
})
|
| 771 |
+
.catch(function (err) { toast(err.message, "err"); });
|
| 772 |
+
});
|
| 773 |
+
|
| 774 |
+
// ---------- 设置 ----------
|
| 775 |
+
els.setAutosave.addEventListener("change", function () {
|
| 776 |
+
try { localStorage.setItem(LS_AUTOSAVE, els.setAutosave.checked ? "1" : "0"); } catch (e) {}
|
| 777 |
+
});
|
| 778 |
+
|
| 779 |
+
els.btnLogout.addEventListener("click", function () {
|
| 780 |
+
if (!window.confirm("退出登录?本机记住的账号信息将被清除。")) return;
|
| 781 |
+
logout();
|
| 782 |
+
});
|
| 783 |
+
|
| 784 |
+
function logout() {
|
| 785 |
+
try { localStorage.removeItem(LS_USER); } catch (e) {}
|
| 786 |
+
user = null;
|
| 787 |
+
allPhotos = [];
|
| 788 |
+
stopStream();
|
| 789 |
+
els.shotPreview.classList.add("hidden");
|
| 790 |
+
els.shotImg.src = "";
|
| 791 |
+
showLogin();
|
| 792 |
+
}
|
| 793 |
+
|
| 794 |
+
// ---------- 启动 ----------
|
| 795 |
+
(function init() {
|
| 796 |
+
// 读取记住的登录
|
| 797 |
+
try {
|
| 798 |
+
var saved = JSON.parse(localStorage.getItem(LS_USER) || "null");
|
| 799 |
+
if (saved && saved.username && saved.pin) {
|
| 800 |
+
user = saved;
|
| 801 |
+
showApp();
|
| 802 |
+
return;
|
| 803 |
+
}
|
| 804 |
+
} catch (e) {}
|
| 805 |
+
showLogin();
|
| 806 |
+
})();
|
| 807 |
+
|
| 808 |
+
// 页面隐藏时释放摄像头(省电)
|
| 809 |
+
document.addEventListener("visibilitychange", function () {
|
| 810 |
+
if (document.hidden && els.shotPreview.classList.contains("hidden")) stopStream();
|
| 811 |
+
});
|
| 812 |
+
})();
|
| 813 |
+
|
| 814 |
+
</script>
|
| 815 |
+
</body>
|
| 816 |
+
</html>
|
main.py
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 FastAPI, File, Form, Header, HTTPException, UploadFile
|
| 17 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 18 |
+
from fastapi.responses import FileResponse
|
| 19 |
+
from PIL import Image, UnidentifiedImageError
|
| 20 |
+
|
| 21 |
+
import storage
|
| 22 |
+
|
| 23 |
+
STATIC_DIR = Path(__file__).parent
|
| 24 |
+
|
| 25 |
+
app = FastAPI(title="云端相机")
|
| 26 |
+
|
| 27 |
+
app.add_middleware(
|
| 28 |
+
CORSMiddleware,
|
| 29 |
+
allow_origins=["*"],
|
| 30 |
+
allow_methods=["*"],
|
| 31 |
+
allow_headers=["*"],
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
MAX_UPLOAD_MB = 20
|
| 35 |
+
THUMB_MAX = 480
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _check_credentials(username: str, pin: str) -> None:
|
| 39 |
+
if not storage.valid_username(username):
|
| 40 |
+
raise HTTPException(status_code=400, detail="用户名不合法(1-24位,中文/字母/数字/下划线/短横线)")
|
| 41 |
+
if not storage.valid_pin(pin):
|
| 42 |
+
raise HTTPException(status_code=400, detail="PIN 需为 4-20 位")
|
| 43 |
+
if not storage.verify_user(username, pin):
|
| 44 |
+
raise HTTPException(status_code=403, detail="用户名或 PIN 不正确")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
@app.on_event("startup")
|
| 48 |
+
def _startup() -> None:
|
| 49 |
+
storage.ensure_dirs()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@app.get("/")
|
| 53 |
+
def index():
|
| 54 |
+
return FileResponse(str(STATIC_DIR / "index.html"))
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@app.post("/api/login")
|
| 58 |
+
def login(payload: dict):
|
| 59 |
+
username = str(payload.get("username", "")).strip()
|
| 60 |
+
pin = str(payload.get("pin", ""))
|
| 61 |
+
if not storage.valid_username(username):
|
| 62 |
+
raise HTTPException(status_code=400, detail="用户名不合法(1-24位,中文/字母/数字/下划线/短横线)")
|
| 63 |
+
if not storage.valid_pin(pin):
|
| 64 |
+
raise HTTPException(status_code=400, detail="PIN 需为 4-20 位")
|
| 65 |
+
is_new = False
|
| 66 |
+
if not storage.user_exists(username):
|
| 67 |
+
storage.create_user(username, pin)
|
| 68 |
+
is_new = True
|
| 69 |
+
elif not storage.verify_user(username, pin):
|
| 70 |
+
raise HTTPException(status_code=403, detail="用户名或 PIN 不正确")
|
| 71 |
+
return {"ok": True, "is_new": is_new}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@app.post("/api/upload")
|
| 75 |
+
async def upload(
|
| 76 |
+
file: UploadFile = File(...),
|
| 77 |
+
username: str = Form(...),
|
| 78 |
+
pin: str = Form(...),
|
| 79 |
+
):
|
| 80 |
+
_check_credentials(username, pin)
|
| 81 |
+
|
| 82 |
+
raw = await file.read()
|
| 83 |
+
if not raw:
|
| 84 |
+
raise HTTPException(status_code=400, detail="文件为空")
|
| 85 |
+
if len(raw) > MAX_UPLOAD_MB * 1024 * 1024:
|
| 86 |
+
raise HTTPException(status_code=413, detail=f"图片超过 {MAX_UPLOAD_MB}MB 限制")
|
| 87 |
+
|
| 88 |
+
try:
|
| 89 |
+
img = Image.open(io.BytesIO(raw))
|
| 90 |
+
img.load()
|
| 91 |
+
except UnidentifiedImageError:
|
| 92 |
+
raise HTTPException(status_code=400, detail="不是有效的图片文件")
|
| 93 |
+
except Exception:
|
| 94 |
+
raise HTTPException(status_code=400, detail="图片解析失败")
|
| 95 |
+
|
| 96 |
+
# 统一转 JPEG(含 EXIF 方向修正)
|
| 97 |
+
img = ImageOps_exif_transpose(img)
|
| 98 |
+
if img.mode not in ("RGB", "L"):
|
| 99 |
+
img = img.convert("RGB")
|
| 100 |
+
|
| 101 |
+
photo_id = f"{int(time.time() * 1000):x}{uuid.uuid4().hex[:6]}"
|
| 102 |
+
user_dir = storage._user_dir(username)
|
| 103 |
+
user_dir.mkdir(parents=True, exist_ok=True)
|
| 104 |
+
|
| 105 |
+
full_path = user_dir / f"{photo_id}.jpg"
|
| 106 |
+
img.save(full_path, "JPEG", quality=90)
|
| 107 |
+
|
| 108 |
+
thumb_path = user_dir / f"{photo_id}_thumb.jpg"
|
| 109 |
+
thumb = img.copy()
|
| 110 |
+
thumb.thumbnail((THUMB_MAX, THUMB_MAX))
|
| 111 |
+
thumb.save(thumb_path, "JPEG", quality=75)
|
| 112 |
+
|
| 113 |
+
photo = {
|
| 114 |
+
"id": photo_id,
|
| 115 |
+
"name": file.filename or f"{photo_id}.jpg",
|
| 116 |
+
"size": len(raw),
|
| 117 |
+
"uploaded_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
| 118 |
+
"width": img.width,
|
| 119 |
+
"height": img.height,
|
| 120 |
+
}
|
| 121 |
+
storage.add_photo(username, photo)
|
| 122 |
+
|
| 123 |
+
return {"ok": True, "photo": photo}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
@app.get("/api/photos")
|
| 127 |
+
def photos(username: str, x_pin: str = Header(default="")):
|
| 128 |
+
_check_credentials(username, x_pin)
|
| 129 |
+
photos_list = storage.list_photos(username)
|
| 130 |
+
for p in photos_list:
|
| 131 |
+
pid = p["id"]
|
| 132 |
+
p["thumb_url"] = f"/api/photo/{username}/{pid}?t={storage.make_token(username, pid)}&thumb=1"
|
| 133 |
+
p["url"] = f"/api/photo/{username}/{pid}?t={storage.make_token(username, pid)}"
|
| 134 |
+
return {"ok": True, "photos": photos_list}
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
@app.get("/api/photo/{username}/{photo_id}")
|
| 138 |
+
def photo(
|
| 139 |
+
username: str,
|
| 140 |
+
photo_id: str,
|
| 141 |
+
t: str,
|
| 142 |
+
thumb: int = 0,
|
| 143 |
+
):
|
| 144 |
+
if not storage.verify_token(username, photo_id, t):
|
| 145 |
+
raise HTTPException(status_code=403, detail="链接无效或已过期,请回到相册刷新")
|
| 146 |
+
suffix = "_thumb" if thumb else ""
|
| 147 |
+
path = storage._user_dir(username) / f"{photo_id}{suffix}.jpg"
|
| 148 |
+
if not path.exists():
|
| 149 |
+
raise HTTPException(status_code=404, detail="照片不存在")
|
| 150 |
+
return FileResponse(str(path), media_type="image/jpeg")
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
@app.delete("/api/photo/{username}/{photo_id}")
|
| 154 |
+
def delete_photo(
|
| 155 |
+
username: str,
|
| 156 |
+
photo_id: str,
|
| 157 |
+
x_pin: str = Header(default=""),
|
| 158 |
+
):
|
| 159 |
+
_check_credentials(username, x_pin)
|
| 160 |
+
if not storage.remove_photo(username, photo_id):
|
| 161 |
+
raise HTTPException(status_code=404, detail="照片不存在")
|
| 162 |
+
for suffix in ("", "_thumb"):
|
| 163 |
+
p = storage._user_dir(username) / f"{photo_id}{suffix}.jpg"
|
| 164 |
+
if p.exists():
|
| 165 |
+
p.unlink()
|
| 166 |
+
return {"ok": True}
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def ImageOps_exif_transpose(img: Image.Image) -> Image.Image:
|
| 170 |
+
"""按 EXIF 方向信息旋转图片。"""
|
| 171 |
+
try:
|
| 172 |
+
exif = img.getexif()
|
| 173 |
+
orientation = exif.get(0x0112, 1)
|
| 174 |
+
ops = {
|
| 175 |
+
2: (Image.Transpose.FLIP_LEFT_RIGHT,),
|
| 176 |
+
3: (Image.Transpose.ROTATE_180,),
|
| 177 |
+
4: (Image.Transpose.FLIP_TOP_BOTTOM,),
|
| 178 |
+
5: (Image.Transpose.TRANSPOSE,),
|
| 179 |
+
6: (Image.Transpose.ROTATE_270,),
|
| 180 |
+
7: (Image.Transpose.TRANSVERSE,),
|
| 181 |
+
8: (Image.Transpose.ROTATE_90,),
|
| 182 |
+
}
|
| 183 |
+
for op in ops.get(orientation, ()):
|
| 184 |
+
img = img.transpose(op)
|
| 185 |
+
except Exception:
|
| 186 |
+
pass
|
| 187 |
+
return img
|
storage.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""云端相机 - 存储与用户管理
|
| 2 |
+
|
| 3 |
+
目录结构(默认根目录 /data,Hugging Face Space 持久化磁盘):
|
| 4 |
+
/data/
|
| 5 |
+
.secret # 签名密钥(首次启动自动生成,持久保存)
|
| 6 |
+
.users/<name>.json # 用户 PIN 哈希
|
| 7 |
+
<name>/index.json # 相册索引(照片元数据列表)
|
| 8 |
+
<name>/<id>.jpg # 原图
|
| 9 |
+
<name>/<id>_thumb.jpg# 缩略图
|
| 10 |
+
"""
|
| 11 |
+
import hashlib
|
| 12 |
+
import hmac
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import re
|
| 16 |
+
import time
|
| 17 |
+
import uuid
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
DATA_DIR = Path(os.environ.get("DATA_DIR", "/data"))
|
| 21 |
+
USERS_DIR = DATA_DIR / ".users"
|
| 22 |
+
|
| 23 |
+
USERNAME_RE = re.compile(r"^[\w\u4e00-\u9fff-]{1,24}$")
|
| 24 |
+
PIN_RE = re.compile(r"^.{4,20}$")
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def ensure_dirs() -> None:
|
| 28 |
+
USERS_DIR.mkdir(parents=True, exist_ok=True)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _user_file(username: str) -> Path:
|
| 32 |
+
return USERS_DIR / f"{username}.json"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _user_dir(username: str) -> Path:
|
| 36 |
+
return DATA_DIR / username
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _index_file(username: str) -> Path:
|
| 40 |
+
return _user_dir(username) / "index.json"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def valid_username(username: str) -> bool:
|
| 44 |
+
return bool(username) and bool(USERNAME_RE.match(username))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def valid_pin(pin: str) -> bool:
|
| 48 |
+
return bool(pin) and bool(PIN_RE.match(pin))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _hash_pin(pin: str, salt: str) -> str:
|
| 52 |
+
return hashlib.sha256(f"{salt}:{pin}".encode("utf-8")).hexdigest()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def user_exists(username: str) -> bool:
|
| 56 |
+
return _user_file(username).exists()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def create_user(username: str, pin: str) -> None:
|
| 60 |
+
salt = uuid.uuid4().hex
|
| 61 |
+
_user_file(username).write_text(
|
| 62 |
+
json.dumps({"salt": salt, "pin_hash": _hash_pin(pin, salt)}),
|
| 63 |
+
encoding="utf-8",
|
| 64 |
+
)
|
| 65 |
+
_user_dir(username).mkdir(parents=True, exist_ok=True)
|
| 66 |
+
_index_file(username).write_text(json.dumps({"photos": []}), encoding="utf-8")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def verify_user(username: str, pin: str) -> bool:
|
| 70 |
+
f = _user_file(username)
|
| 71 |
+
if not f.exists():
|
| 72 |
+
return False
|
| 73 |
+
try:
|
| 74 |
+
data = json.loads(f.read_text(encoding="utf-8"))
|
| 75 |
+
except Exception:
|
| 76 |
+
return False
|
| 77 |
+
return _hash_pin(pin, data.get("salt", "")) == data.get("pin_hash", "")
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def list_photos(username: str) -> list:
|
| 81 |
+
f = _index_file(username)
|
| 82 |
+
if not f.exists():
|
| 83 |
+
return []
|
| 84 |
+
try:
|
| 85 |
+
return json.loads(f.read_text(encoding="utf-8")).get("photos", [])
|
| 86 |
+
except Exception:
|
| 87 |
+
return []
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def add_photo(username: str, photo: dict) -> None:
|
| 91 |
+
f = _index_file(username)
|
| 92 |
+
data = {"photos": []}
|
| 93 |
+
if f.exists():
|
| 94 |
+
try:
|
| 95 |
+
data = json.loads(f.read_text(encoding="utf-8"))
|
| 96 |
+
except Exception:
|
| 97 |
+
data = {"photos": []}
|
| 98 |
+
data.setdefault("photos", []).insert(0, photo)
|
| 99 |
+
f.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def remove_photo(username: str, photo_id: str) -> bool:
|
| 103 |
+
f = _index_file(username)
|
| 104 |
+
if not f.exists():
|
| 105 |
+
return False
|
| 106 |
+
try:
|
| 107 |
+
data = json.loads(f.read_text(encoding="utf-8"))
|
| 108 |
+
except Exception:
|
| 109 |
+
return False
|
| 110 |
+
before = len(data.get("photos", []))
|
| 111 |
+
data["photos"] = [p for p in data.get("photos", []) if p["id"] != photo_id]
|
| 112 |
+
f.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
|
| 113 |
+
return len(data["photos"]) < before
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# ---------- 图片访问签名 ----------
|
| 117 |
+
|
| 118 |
+
def get_secret() -> bytes:
|
| 119 |
+
"""签名密钥:优先环境变量 SIGN_SECRET,否则用持久化的随机密钥。"""
|
| 120 |
+
env = os.environ.get("SIGN_SECRET")
|
| 121 |
+
if env:
|
| 122 |
+
return env.encode("utf-8")
|
| 123 |
+
f = DATA_DIR / ".secret"
|
| 124 |
+
if f.exists():
|
| 125 |
+
return f.read_text(encoding="utf-8").strip().encode("utf-8")
|
| 126 |
+
s = uuid.uuid4().hex
|
| 127 |
+
f.write_text(s, encoding="utf-8")
|
| 128 |
+
return s.encode("utf-8")
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def make_token(username: str, photo_id: str, ttl: int = 86400) -> str:
|
| 132 |
+
"""为图片生成带过期时间的访问令牌。"""
|
| 133 |
+
expires = int(time.time()) + ttl
|
| 134 |
+
msg = f"{username}/{photo_id}/{expires}".encode("utf-8")
|
| 135 |
+
sig = hmac.new(get_secret(), msg, hashlib.sha256).hexdigest()
|
| 136 |
+
return f"{expires}.{sig}"
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def verify_token(username: str, photo_id: str, token: str) -> bool:
|
| 140 |
+
try:
|
| 141 |
+
expires_str, sig = token.split(".", 1)
|
| 142 |
+
expires = int(expires_str)
|
| 143 |
+
except Exception:
|
| 144 |
+
return False
|
| 145 |
+
if time.time() > expires:
|
| 146 |
+
return False
|
| 147 |
+
msg = f"{username}/{photo_id}/{expires}".encode("utf-8")
|
| 148 |
+
expect = hmac.new(get_secret(), msg, hashlib.sha256).hexdigest()
|
| 149 |
+
return hmac.compare_digest(expect, sig)
|