项目文件夹

文件
yf bfc07e2546 feat: add photo album at /album with AI image captioning
Merged into file-hub to share the same environment (platform resource
quota limits to one web_function). Routes: /api/photos/upload,
/api/photos, /api/photos/:id/url, /api/photos/:id/ai-caption.
2026-08-07 15:45:19 +08:00

495 行
15 KiB
HTML

<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>在线相册 · AI 识图</title>
<style>
:root {
color-scheme: light dark;
--ink: #1a1a2e;
--paper: #f5f5f5;
--card: #ffffff;
--accent: #6c5ce7;
--accent-hover: #5b4bd6;
--line: #e0e0e0;
--muted: #999;
--danger: #e5484d;
--ok: #00b894;
--shadow: 0 4px 20px rgba(0,0,0,0.08);
}
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
min-height: 100svh;
background: var(--paper);
color: var(--ink);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
}
header {
background: var(--card);
border-bottom: 1px solid var(--line);
padding: 16px 24px;
display: flex;
align-items: center;
justify-content: space-between;
position: sticky;
top: 0;
z-index: 10;
box-shadow: var(--shadow);
}
header h1 { font-size: 1.25rem; font-weight: 700; }
header .stats { font-size: 0.8rem; color: var(--muted); }
.container { max-width: 1200px; margin: 0 auto; padding: 24px 16px; }
/* upload zone */
.upload-zone {
border: 2px dashed var(--line);
border-radius: 16px;
padding: 40px 20px;
text-align: center;
cursor: pointer;
transition: all 0.2s;
background: var(--card);
margin-bottom: 24px;
}
.upload-zone:hover, .upload-zone.dragover {
border-color: var(--accent);
background: rgba(108, 92, 231, 0.04);
transform: scale(1.01);
}
.upload-zone .icon { font-size: 3rem; }
.upload-zone p { color: var(--muted); font-size: 0.9rem; margin-top: 8px; }
.upload-progress { margin-top: 12px; }
.upload-item {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 12px;
border-radius: 8px;
background: rgba(108, 92, 231, 0.08);
font-size: 0.85rem;
margin-top: 6px;
}
.upload-item .spinner { animation: spin 0.8s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
/* gallery */
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
gap: 16px;
}
.photo-card {
background: var(--card);
border-radius: 12px;
overflow: hidden;
box-shadow: var(--shadow);
transition: transform 0.15s;
position: relative;
}
.photo-card:hover { transform: translateY(-4px); }
.photo-thumb {
width: 100%;
aspect-ratio: 1;
object-fit: cover;
background: var(--paper);
cursor: pointer;
}
.photo-info { padding: 10px 14px; }
.photo-name {
font-size: 0.85rem;
font-weight: 600;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.photo-meta { font-size: 0.72rem; color: var(--muted); margin-top: 2px; }
.photo-actions {
display: flex;
gap: 4px;
padding: 0 14px 12px;
flex-wrap: wrap;
}
.btn {
border: none;
border-radius: 6px;
padding: 5px 10px;
font-size: 0.72rem;
cursor: pointer;
font-weight: 600;
transition: background 0.15s;
}
.btn-accent { background: rgba(108, 92, 231, 0.12); color: var(--accent); }
.btn-accent:hover { background: rgba(108, 92, 231, 0.22); }
.btn-danger { background: transparent; color: var(--danger); }
.btn-danger:hover { background: rgba(229,72,77,0.1); }
.ai-badge {
position: absolute;
top: 8px;
right: 8px;
background: rgba(108, 92, 231, 0.9);
color: #fff;
font-size: 0.65rem;
padding: 3px 8px;
border-radius: 999px;
display: none;
}
.ai-badge.show { display: block; }
.loading-overlay {
position: absolute;
inset: 0;
background: rgba(0,0,0,0.5);
display: none;
align-items: center;
justify-content: center;
color: #fff;
font-size: 0.8rem;
}
.loading-overlay.show { display: flex; }
/* lightbox */
.lightbox {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.9);
display: none;
align-items: center;
justify-content: center;
z-index: 100;
padding: 20px;
}
.lightbox.show { display: flex; }
.lightbox img {
max-width: 90vw;
max-height: 80vh;
border-radius: 8px;
}
.lightbox-info {
position: absolute;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background: rgba(255,255,255,0.95);
border-radius: 12px;
padding: 14px 20px;
max-width: 90vw;
font-size: 0.85rem;
text-align: center;
}
.lightbox-info .caption { color: var(--ink); line-height: 1.5; }
.lightbox-info .caption-label { font-weight: 700; color: var(--accent); margin-bottom: 4px; }
.lightbox-close {
position: absolute;
top: 20px;
right: 20px;
background: rgba(255,255,255,0.2);
color: #fff;
border: none;
border-radius: 50%;
width: 40px;
height: 40px;
font-size: 1.2rem;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
}
.lightbox-close:hover { background: rgba(255,255,255,0.35); }
/* share modal */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.4);
display: flex;
align-items: center;
justify-content: center;
z-index: 200;
}
.modal {
background: var(--card);
border-radius: 12px;
padding: 24px;
max-width: 480px;
width: 90%;
}
.modal h3 { margin-bottom: 12px; }
.modal .share-link { display: flex; gap: 8px; margin-top: 12px; }
.modal input {
flex: 1;
border: 1px solid var(--line);
border-radius: 6px;
padding: 8px 12px;
font-size: 0.85rem;
}
.modal .close { margin-top: 16px; width: 100%; }
.empty {
text-align: center;
padding: 60px 20px;
color: var(--muted);
}
.empty .icon { font-size: 4rem; }
.empty p { margin-top: 12px; font-size: 0.9rem; }
</style>
</head>
<body>
<header>
<h1>🖼️ 在线相册</h1>
<span class="stats" id="headerStats">加载中...</span>
</header>
<div class="container">
<div class="upload-zone" id="uploadZone" onclick="document.getElementById('fileInput').click()">
<div class="icon">📸</div>
<p>点击或拖拽图片到此处上传</p>
<input type="file" id="fileInput" accept="image/*" style="display:none" multiple>
</div>
<div class="upload-progress" id="uploadProgress"></div>
<div class="gallery" id="gallery"></div>
</div>
<!-- lightbox -->
<div class="lightbox" id="lightbox">
<button class="lightbox-close" onclick="closeLightbox()"></button>
<img id="lightboxImg" src="" alt="" />
<div class="lightbox-info" id="lightboxInfo" style="display:none">
<div class="caption-label">🤖 AI 识图</div>
<div class="caption" id="lightboxCaption"></div>
</div>
</div>
<script>
const API = "/api";
const fileInput = document.getElementById("fileInput");
const uploadZone = document.getElementById("uploadZone");
const uploadProgress = document.getElementById("uploadProgress");
const gallery = document.getElementById("gallery");
const lightbox = document.getElementById("lightbox");
const photoUrls = {};
// ── health ──
async function loadHealth() {
try {
const res = await fetch(`${API}/health`);
const data = await res.json();
const b = data.bindings || {};
const parts = [];
if (b.database) parts.push("DB ✓");
if (b.object_storage) parts.push("存储 ✓");
if (b.model_router) parts.push("AI ✓");
document.getElementById("headerStats").textContent = parts.length ? parts.join(" · ") : "未就绪";
} catch (e) {
document.getElementById("headerStats").textContent = "连接失败";
}
}
function esc(s) { return String(s ?? "").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"); }
function formatSize(bytes) {
if (bytes === 0) return "0 B";
const k = 1024;
const sizes = ["B", "KB", "MB", "GB"];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
}
// ── gallery ──
async function loadPhotos() {
try {
const res = await fetch(`${API}/photos`);
const data = await res.json();
if (!data.ok) throw new Error(data.error);
if (data.photos.length === 0) {
gallery.innerHTML = '<div class="empty"><div class="icon">🖼️</div><p>还没有照片,上传第一张吧!</p></div>';
return;
}
gallery.innerHTML = data.photos.map(p => `
<div class="photo-card" id="card-${p.id}">
<img class="photo-thumb" data-id="${p.id}" src="" alt="${esc(p.filename)}" onclick="openLightbox(${p.id})" />
<span class="ai-badge ${p.ai_caption ? "show" : ""}">AI ✓</span>
<div class="loading-overlay" id="loading-${p.id}"><span class="spinner">⏳</span> 加载中...</div>
<div class="photo-info">
<div class="photo-name" title="${esc(p.filename)}">${esc(p.filename)}</div>
<div class="photo-meta">${formatSize(p.size)} · ${new Date(p.created_at).toLocaleDateString("zh-CN")}</div>
</div>
<div class="photo-actions">
<button class="btn btn-accent" onclick="openLightbox(${p.id})">查看</button>
<button class="btn btn-accent" onclick="aiCaption(${p.id})">AI识图</button>
<button class="btn btn-accent" onclick="sharePhoto('${p.share_token}')">分享</button>
<button class="btn btn-danger" onclick="deletePhoto(${p.id}, '${esc(p.filename)}')">删除</button>
</div>
</div>
`).join("");
data.photos.forEach(p => loadThumb(p.id));
} catch (e) {
gallery.innerHTML = `<div class="empty"><p>加载失败: ${esc(e.message)}</p></div>`;
}
}
async function loadThumb(id) {
try {
const res = await fetch(`${API}/photos/${id}/url`);
const data = await res.json();
if (!data.ok) return;
photoUrls[id] = data.url;
const img = document.querySelector(`.photo-thumb[data-id="${id}"]`);
if (img) img.src = data.url;
} catch (_) {}
}
// ── upload ──
fileInput.addEventListener("change", (e) => {
for (const file of e.target.files) uploadPhoto(file);
fileInput.value = "";
});
uploadZone.addEventListener("dragover", (e) => { e.preventDefault(); uploadZone.classList.add("dragover"); });
uploadZone.addEventListener("dragleave", () => uploadZone.classList.remove("dragover"));
uploadZone.addEventListener("drop", (e) => {
e.preventDefault();
uploadZone.classList.remove("dragover");
for (const file of e.dataTransfer.files) {
if (file.type.startsWith("image/")) uploadPhoto(file);
}
});
async function uploadPhoto(file) {
if (!file.type.startsWith("image/")) {
const item = document.createElement("div");
item.className = "upload-item";
item.innerHTML = `❌ ${esc(file.name)} 不是图片`;
item.style.color = "var(--danger)";
uploadProgress.appendChild(item);
setTimeout(() => item.remove(), 5000);
return;
}
const item = document.createElement("div");
item.className = "upload-item";
item.innerHTML = `<span class="spinner">⏳</span> 上传中: ${esc(file.name)}...`;
uploadProgress.appendChild(item);
try {
const r1 = await fetch(`${API}/photos/upload`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ filename: file.name, content_type: file.type, size: file.size }),
});
const d1 = await r1.json();
if (!d1.ok) throw new Error(d1.error);
await fetch(d1.upload_url, { method: "PUT", headers: { "content-type": file.type }, body: file });
const r2 = await fetch(`${API}/photos`, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ object_key: d1.object_key, filename: file.name, content_type: file.type, size: file.size }),
});
const d2 = await r2.json();
if (!d2.ok) throw new Error(d2.error);
item.innerHTML = `✅ ${esc(file.name)} 上传成功`;
item.style.color = "var(--ok)";
loadPhotos();
} catch (e) {
item.innerHTML = `❌ ${esc(file.name)}: ${esc(e.message)}`;
item.style.color = "var(--danger)";
}
setTimeout(() => item.remove(), 5000);
}
// ── actions ──
async function openLightbox(id) {
const img = document.getElementById("lightboxImg");
const info = document.getElementById("lightboxInfo");
const caption = document.getElementById("lightboxCaption");
img.src = "";
info.style.display = "none";
lightbox.classList.add("show");
try {
const res = await fetch(`${API}/photos/${id}/url`);
const data = await res.json();
if (!data.ok) throw new Error(data.error);
img.src = data.url;
const card = document.getElementById(`card-${id}`);
const badge = card?.querySelector(".ai-badge.show");
const captionText = badge ? badge.parentElement.querySelector(".photo-name")?.textContent : null;
// fetch caption from gallery data
const photosRes = await fetch(`${API}/photos`);
const photosData = await photosRes.json();
const photo = photosData.photos?.find(p => p.id === id);
if (photo && photo.ai_caption) {
caption.textContent = photo.ai_caption;
info.style.display = "block";
}
} catch (e) {
caption.textContent = "加载失败: " + e.message;
info.style.display = "block";
}
}
function closeLightbox() {
lightbox.classList.remove("show");
}
lightbox.addEventListener("click", (e) => { if (e.target === lightbox) closeLightbox(); });
document.addEventListener("keydown", (e) => { if (e.key === "Escape") closeLightbox(); });
function sharePhoto(token) {
const url = `${location.origin}/s/${token}`;
const overlay = document.createElement("div");
overlay.className = "modal-overlay";
overlay.innerHTML = `
<div class="modal">
<h3>🔗 分享链接</h3>
<p style="font-size:0.85rem;color:var(--muted)">任何人可通过此链接查看/下载照片(1小时内有效)</p>
<div class="share-link">
<input type="text" value="${url}" id="shareInput" readonly>
<button class="btn btn-accent" onclick="copyShare()">复制</button>
</div>
<button class="btn btn-accent close" onclick="this.closest('.modal-overlay').remove()">关闭</button>
</div>`;
document.body.appendChild(overlay);
overlay.addEventListener("click", (e) => { if (e.target === overlay) overlay.remove(); });
}
function copyShare() {
const input = document.getElementById("shareInput");
input.select();
navigator.clipboard.writeText(input.value).then(() => alert("链接已复制")).catch(() => { document.execCommand("copy"); alert("链接已复制"); });
}
async function aiCaption(id) {
const loading = document.getElementById(`loading-${id}`);
if (loading) loading.classList.add("show");
try {
const res = await fetch(`${API}/photos/${id}/ai-caption`, { method: "POST" });
const data = await res.json();
if (!data.ok) throw new Error(data.error);
const card = document.getElementById(`card-${id}`);
if (card) {
const badge = card.querySelector(".ai-badge");
badge.classList.add("show");
}
loadPhotos();
} catch (e) {
alert("AI 识图失败: " + e.message);
}
if (loading) loading.classList.remove("show");
}
async function deletePhoto(id, name) {
if (!confirm(`确定删除 "${name}" 吗?`)) return;
try {
const res = await fetch(`${API}/photos/${id}`, { method: "DELETE" });
const data = await res.json();
if (!data.ok) throw new Error(data.error);
loadPhotos();
} catch (e) {
alert("删除失败: " + e.message);
}
}
loadHealth();
loadPhotos();
</script>
</body>
</html>