const state = { view: "home", query: "", tag: "", type: "", artistId: "", offset: 0, limit: 48, total: 0, xPreviewId: "", xPreviewUsername: "", xPreviewAuthor: "", xhsPreviewId: "", }; const els = { search: document.querySelector("#searchInput"), type: document.querySelector("#typeFilter"), status: document.querySelector("#statusLine"), grid: document.querySelector("#artworkGrid"), tags: document.querySelector("#tagList"), artists: document.querySelector("#artistList"), followed: document.querySelector("#followedList"), xFollowed: document.querySelector("#xFollowedList"), title: document.querySelector("#viewTitle"), subtitle: document.querySelector("#viewSubtitle"), pageInfo: document.querySelector("#pageInfo"), dialog: document.querySelector("#detailDialog"), detail: document.querySelector("#detailContent"), pixivCookieFile: document.querySelector("#pixivCookieFile"), pixivSessionStatus: document.querySelector("#pixivSessionStatus"), refreshSessionButton: document.querySelector("#refreshSessionButton"), xCookieFile: document.querySelector("#xCookieFile"), xUsername: document.querySelector("#xUsernameInput"), xMediaType: document.querySelector("#xMediaType"), xMaxItems: document.querySelector("#xMaxItems"), xMediaGrid: document.querySelector("#xMediaGrid"), xMediaSummary: document.querySelector("#xMediaSummary"), xSelectAll: document.querySelector("#xSelectAll"), xFollowUsername: document.querySelector("#xFollowUsername"), xFollowName: document.querySelector("#xFollowName"), xLocalGrid: document.querySelector("#xLocalGrid"), xLocalSummary: document.querySelector("#xLocalSummary"), xLocalSelectAll: document.querySelector("#xLocalSelectAll"), xhsNavButton: document.querySelector("#xiaohongshuNavButton"), xhsTarget: document.querySelector("#xhsTargetInput"), xhsLimit: document.querySelector("#xhsLimitInput"), xhsGrid: document.querySelector("#xhsGrid"), xhsSummary: document.querySelector("#xhsSummary"), xhsSelectAll: document.querySelector("#xhsSelectAll"), originFollowSyncDialog: document.querySelector("#originFollowSyncDialog"), originFollowSyncResult: document.querySelector("#originFollowSyncResult"), }; function setStatus(text) { els.status.textContent = text; } function isPlaceholderPixivName(name, artistId) { const value = String(name || "").trim(); if (!value) { return true; } const idText = String(artistId || "").trim(); return Boolean(idText) && value.toLowerCase() === `artist_${idText}`.toLowerCase(); } function pixivArtistStoredName(item) { const artistId = item?.artist_id ?? item?.artistId ?? item?.creator_id ?? ""; const name = String(item?.name || item?.artist_name || item?.creator_name || "").trim(); return isPlaceholderPixivName(name, artistId) ? "" : name; } function pixivArtistDisplayName(item) { const artistId = item?.artist_id ?? item?.artistId ?? item?.creator_id ?? ""; const name = pixivArtistStoredName(item); if (name) { return name; } const account = String(item?.account || item?.artist_account || item?.creator_handle || "").trim().replace(/^@/, ""); if (account) { return `@${account}`; } return artistId ? `Pixiv ID ${artistId}` : "Pixiv 作者"; } window.addEventListener("unhandledrejection", (event) => { setStatus(event.reason?.message || "操作失败,请查看后端日志。"); }); async function api(path, options = {}) { const response = await fetch(path, { headers: { "Content-Type": "application/json" }, ...options, }); const payload = await response.json(); if (!response.ok || payload.error) { throw new Error(payload.error || `HTTP ${response.status}`); } return payload; } async function loadSessionStatus() { if (!els.pixivSessionStatus) { return null; } try { const payload = await api("/api/session/status"); const pixiv = payload.pixiv || {}; const cookieText = pixiv.has_cookie ? `已共享桌面端 Pixiv 会话${pixiv.saved_at ? `(${pixiv.saved_at})` : ""}` : "未检测到桌面端 Pixiv 会话,请先在 EXE 登录或导入 Cookie。"; els.pixivSessionStatus.textContent = cookieText; return payload; } catch (error) { els.pixivSessionStatus.textContent = `会话状态读取失败:${error.message || error}`; return null; } } function artworkUrl(item, pageIndex = 0, kind = "thumbnail") { return `/media/${kind}/${item.artwork_id}/${pageIndex}`; } function renderArtworkGrid(payload) { state.total = payload.total || 0; els.grid.innerHTML = ""; if (!payload.items.length) { els.grid.innerHTML = `
还没有作品。可以先下载作品,或点击“扫描旧目录”导入已有文件。
`; } else { els.grid.append(...payload.items.map(renderArtworkCard)); } const currentPage = Math.floor(state.offset / state.limit) + 1; const totalPages = Math.max(1, Math.ceil(state.total / state.limit)); els.pageInfo.textContent = `${currentPage} / ${totalPages}`; } function renderArtworkCard(item) { const card = document.createElement("article"); card.className = "artwork-card"; const thumb = item.thumbnail_path ? `${escapeHtml(item.title || String(item.artwork_id))}` : `
${item.type === "novel" ? "小说" : "暂无缩略图"}
`; card.innerHTML = `
${escapeHtml(item.title || String(item.artwork_id))}
${escapeHtml(item.artist_name || "未知作者")} · ${escapeHtml(item.type || "")}
${item.artist_id ? `` : ""} ${item.artist_id ? `` : ""}
`; const artworkSub = card.querySelector(".artwork-sub"); if (artworkSub) { artworkSub.textContent = `${pixivArtistDisplayName(item)} · ${item.type || ""}`; } const artworkFollow = card.querySelector("[data-follow]"); if (artworkFollow) { artworkFollow.dataset.name = pixivArtistStoredName(item); } return card; } async function loadArtworks() { const params = new URLSearchParams({ limit: state.limit, offset: state.offset, ensure_thumbnails: "true", }); if (state.query) params.set("q", state.query); if (state.tag) params.set("tag", state.tag); if (state.type) params.set("type", state.type); if (state.artistId) params.set("artist_id", state.artistId); setStatus("正在加载图库..."); const payload = await api(`/api/artworks?${params}`); renderArtworkGrid(payload); setStatus(`已加载 ${payload.items.length} / ${payload.total} 个作品`); } async function loadFavorites() { setStatus("正在加载收藏..."); const params = new URLSearchParams({ limit: state.limit, offset: state.offset }); const payload = await api(`/api/favorites?${params}`); renderArtworkGrid(payload); setStatus(`收藏 ${payload.total} 个作品`); } async function loadTags() { const tags = await api("/api/tags?limit=80"); els.tags.innerHTML = ""; if (!tags.length) { els.tags.innerHTML = `暂无标签`; return; } for (const tag of tags) { const button = document.createElement("button"); button.className = `tag-chip ${state.tag === tag.name ? "active" : ""}`; button.textContent = `${tag.name} ${tag.artwork_count}`; button.dataset.tag = tag.name; els.tags.append(button); } } async function loadArtists() { setStatus("正在加载作者..."); const artists = await api("/api/artists?limit=200"); els.artists.innerHTML = ""; if (!artists.length) { els.artists.innerHTML = `
暂无作者数据。
`; } else { els.artists.append(...artists.map(renderArtistRow)); } setStatus(`已加载 ${artists.length} 位作者`); } async function loadFollowed() { const followed = await api("/api/followed-artists"); els.followed.innerHTML = ""; if (!followed.length) { els.followed.innerHTML = `
还没有关注作者。
`; } else { els.followed.append(...followed.map(renderArtistRow)); } } async function loadXFollowed() { const followed = await api("/api/x/follows"); els.xFollowed.innerHTML = ""; if (!followed.length) { els.xFollowed.innerHTML = `
还没有 X 关注作者。
`; } else { els.xFollowed.append(...followed.map(renderXFollowRow)); } } function renderArtistRow(artist) { const row = document.createElement("div"); row.className = "artist-row"; const isFollowed = Number(artist.enabled ?? artist.is_followed ?? 0); row.innerHTML = `
${escapeHtml(artist.name || `artist_${artist.artist_id}`)} ID ${artist.artist_id} · ${artist.artwork_count || 0} 个作品${artist.last_synced_at ? ` · 上次同步 ${artist.last_synced_at}` : ""}
`; const artistTitle = row.querySelector("strong"); if (artistTitle) { artistTitle.textContent = pixivArtistDisplayName(artist); } const artistFollow = row.querySelector("[data-follow]"); if (artistFollow) { artistFollow.dataset.name = pixivArtistStoredName(artist); } return row; } function renderXFollowRow(artist) { const row = document.createElement("div"); row.className = "artist-row"; const handle = artist.username || artist.creator_handle || ""; const isFollowed = Number(artist.enabled ?? 1); const latest = artist.latest_published_at ? ` · 最新 ${artist.latest_published_at}` : ""; const checked = artist.last_checked_at ? ` · 检查 ${artist.last_checked_at}` : ""; const error = artist.last_error ? ` · ${escapeHtml(artist.last_error)}` : ""; row.innerHTML = `
${escapeHtml(artist.creator_name || handle || "x_author")} @${escapeHtml(handle)}${latest}${checked}${error}
`; return row; } async function openArtwork(artworkId) { const payload = await api(`/api/artworks/${artworkId}`); const artwork = payload.artwork; const files = payload.files || []; const tags = payload.tags || []; const firstFile = files[0]; const image = firstFile ? `${escapeHtml(artwork.title)}` : `
没有本地文件
`; els.detail.innerHTML = `
${image}

${escapeHtml(artwork.title || String(artwork.artwork_id))}

${escapeHtml(artwork.artist_name || "未知作者")} · ${escapeHtml(artwork.type)}

${artwork.artist_id ? `` : ""}
${tags.map((tag) => ``).join("")}

${escapeHtml(stripHtml(artwork.caption || ""))}

页数 ${files.length || artwork.page_count || 0} · 收藏 ${artwork.bookmark_count || 0} · 浏览 ${artwork.view_count || 0}

`; const detailArtist = els.detail.querySelector(".detail-info p"); if (detailArtist) { detailArtist.textContent = `${pixivArtistDisplayName(artwork)} · ${artwork.type}`; } const detailFollow = els.detail.querySelector("[data-follow]"); if (detailFollow) { detailFollow.dataset.name = pixivArtistStoredName(artwork); } els.dialog.showModal(); } async function showArtist(artistId) { setActiveView("gallery"); state.artistId = String(artistId); state.tag = ""; state.offset = 0; const detail = await api(`/api/artists/${artistId}?limit=1`); els.title.textContent = detail.artist.name || `作者 ${artistId}`; els.subtitle.textContent = `作者 ID ${artistId} · ${detail.artist.artwork_count || 0} 个本地作品`; await loadArtworks(); els.title.textContent = pixivArtistDisplayName(detail.artist); } async function toggleFavorite(artworkId, currentOn) { await api("/api/favorites", { method: "POST", body: JSON.stringify({ artwork_id: Number(artworkId), favorite: !Number(currentOn) }), }); await reloadCurrent(); } async function followArtist(artistId, name = "") { await setPixivFollow(artistId, name, true); } async function setPixivFollow(artistId, name = "", followed = true) { await api("/api/followed-artists", { method: "POST", body: JSON.stringify({ artist_id: String(artistId).trim(), name, followed }), }); setStatus(followed ? `已关注作者 ${artistId}` : `已取消关注作者 ${artistId}`); await Promise.all([loadFollowed(), reloadCurrent()]); } async function followXAuthor(username, name = "") { await setXFollow(username, name, true); } async function setXFollow(username, name = "", followed = true) { const handle = username.trim().replace(/^@/, ""); if (!handle) { return; } await api("/api/x/follows", { method: "POST", body: JSON.stringify({ username: handle, name, followed }), }); setStatus(followed ? `已关注 X 作者 @${handle}` : `已取消关注 X 作者 @${handle}`); await loadXFollowed(); } async function scanLegacy() { setStatus("正在扫描旧下载目录..."); const result = await api("/api/import/legacy", { method: "POST", body: JSON.stringify({ root: "Sakura_Downloads" }) }); setStatus(`扫描完成:导入 ${result.imported_files} 个文件,${result.imported_artworks} 个作品`); await Promise.all([loadTags(), reloadCurrent()]); } async function syncFollowed() { setStatus("正在同步关注作者..."); try { const result = await api("/api/sync/followed", { method: "POST", body: JSON.stringify({ download: true, max_new: 20 }), }); const downloaded = result.artists.reduce((sum, item) => sum + (item.downloaded || 0), 0); setStatus(`同步完成:下载 ${downloaded} 个新作品`); await Promise.all([loadFollowed(), loadTags(), reloadCurrent()]); } catch (error) { setStatus(error.message || "同步关注作者失败"); } } async function syncXFollowed() { setStatus("正在同步 X 关注..."); const result = await api("/api/x/follows/sync", { method: "POST", body: JSON.stringify({ download: true, max_new: 20 }), }); const total = (result.authors || []).reduce((sum, item) => sum + (item.new_posts || 0), 0); setStatus(`X 同步完成:发现 ${total} 个新动态`); await loadXFollowed(); } function openOriginFollowSyncDialog() { els.originFollowSyncResult.textContent = "请选择要同步的平台。"; els.originFollowSyncDialog.showModal(); } async function syncOriginFollows(platform) { const label = platform === "pixiv" ? "Pixiv" : "X"; const button = platform === "pixiv" ? document.querySelector("#syncOriginPixivButton") : document.querySelector("#syncOriginXButton"); if (button?.disabled) { return; } if (button) { button.disabled = true; } setStatus(`正在同步 ${label} 原站关注...`); els.originFollowSyncResult.textContent = `正在同步 ${label} 原站关注,请稍候...`; try { if (platform === "pixiv") { const session = await loadSessionStatus(); if (session && !session.pixiv?.has_cookie) { throw new Error("未检测到桌面端 Pixiv 会话,请先在 EXE 登录或导入 Cookie。"); } } const result = await api("/api/origin-follows/sync", { method: "POST", body: JSON.stringify({ platform }), }); const lines = [ `${label} 原站关注同步完成`, `同步页数:${result.pages || 0}`, `新增:${result.created || 0} 位`, `更新:${result.updated || 0} 位`, `跳过:${result.skipped || 0} 位`, `失败:${result.failed || 0} 位`, ]; if (Array.isArray(result.progress) && result.progress.length) { lines.push("", "进度:"); for (const item of result.progress.slice(-20)) { lines.push(item.message || `正在同步第 ${item.page || "?"} 页`); } } if (Array.isArray(result.errors) && result.errors.length) { lines.push("", "失败原因:"); for (const item of result.errors.slice(0, 10)) { lines.push(`${item.id || "-"}:${item.reason || ""}`); } } els.originFollowSyncResult.textContent = lines.join("\n"); setStatus(`${label} 原站关注同步完成:新增 ${result.created || 0},更新 ${result.updated || 0},跳过 ${result.skipped || 0},失败 ${result.failed || 0}`); if (platform === "pixiv") { await loadFollowed(); } else { await loadXFollowed(); } } catch (error) { const message = error.message || `${label} 原站关注同步失败`; els.originFollowSyncResult.textContent = message; setStatus(message); } finally { if (button) { button.disabled = false; } } } async function followCurrentX() { const username = els.xUsername.value.trim(); if (!username) { setStatus("请先输入 X 作者名。"); return; } const handle = username.replace(/^@/, ""); const creatorName = state.xPreviewUsername === handle ? state.xPreviewAuthor : ""; await followXAuthor(username, creatorName || handle); } async function buildThumbnails() { setStatus("正在生成缩略图..."); const result = await api("/api/thumbnails/build?limit=500"); setStatus(`缩略图完成:处理 ${result.items.length} 个文件`); await reloadCurrent(); } async function loadPluginPages() { const payload = await api("/api/plugins/pages"); const pages = payload.items || []; const hasXhs = pages.some((item) => item.view === "xiaohongshu"); els.xhsNavButton.classList.toggle("hidden", !hasXhs); } async function importCookieFile(platform, fileInput) { const file = fileInput.files?.[0]; if (!file) { setStatus("请先选择 cookies.txt 或 json 文件。"); return; } setStatus(`正在导入 ${platform} Cookie...`); const text = await file.text(); const result = await api("/api/cookies/import", { method: "POST", body: JSON.stringify({ platform, text }), }); setStatus(`Cookie 导入完成:${result.summary || `${result.count || 0} 个 Cookie`}`); } async function previewXMedia(event) { event.preventDefault(); const username = els.xUsername.value.trim(); if (!username) { setStatus("请输入 X 作者名称。"); return; } els.xMediaGrid.innerHTML = `
正在解析 X 媒体页,首次启动 Playwright 可能需要一些时间。
`; els.xMediaSummary.textContent = "解析中..."; const submitButton = event.submitter || document.querySelector("#xMediaForm button[type='submit']"); if (submitButton) { submitButton.disabled = true; } setStatus(`正在解析 X 作者 @${username.replace(/^@/, "")}...`); try { const payload = await api("/api/x/media/preview", { method: "POST", body: JSON.stringify({ username, media_type: els.xMediaType.value, max_items: Number(els.xMaxItems.value || 120), }), }); state.xPreviewId = payload.preview_id; renderXMedia(payload); setStatus(`X 解析完成:${payload.count} 个媒体项`); } catch (error) { state.xPreviewId = ""; els.xMediaSummary.textContent = "解析失败"; els.xMediaGrid.innerHTML = `
${escapeHtml(error.message || "X 解析失败")}
`; setStatus(error.message || "X 解析失败"); } finally { if (submitButton) { submitButton.disabled = false; } } } function renderXMedia(payload) { els.xMediaGrid.innerHTML = ""; els.xMediaSummary.textContent = `${payload.username} · ${payload.count} 个媒体项`; if (!payload.items.length) { els.xMediaGrid.innerHTML = `
没有解析到媒体。可能需要先导入 X Cookie,或该作者媒体页为空。
`; return; } els.xMediaGrid.append(...payload.items.map(renderXMediaCard)); els.xSelectAll.checked = true; } function renderXMediaCard(item) { const card = document.createElement("article"); card.className = "x-media-card"; const preview = item.thumbnail || item.files?.[0]?.url || ""; const media = item.kind === "video" ? `
VIDEO
` : `${escapeHtml(item.title || item.id)}`; card.innerHTML = `
${media}
${escapeHtml(item.title || item.id)}
@${escapeHtml(item.author_id || "")} · ${item.file_count || 1} 个文件
`; return card; } async function downloadXSelected() { if (!state.xPreviewId) { setStatus("请先解析 X 作者媒体。"); return; } const selected = [...document.querySelectorAll("[data-x-id]:checked")].map((item) => item.dataset.xId); if (!selected.length) { setStatus("没有选中的媒体。"); return; } setStatus(`正在下载 ${selected.length} 个 X 媒体项...`); const result = await api("/api/x/media/download", { method: "POST", body: JSON.stringify({ preview_id: state.xPreviewId, selected_ids: selected }), }); setStatus(`X 下载完成:保存 ${result.downloaded_files} 个文件,失败 ${result.failed_items} 项`); await loadXLocalMedia(); } async function loadXLocalMedia() { const payload = await api("/api/x/local-media?limit=160"); els.xLocalGrid.innerHTML = ""; els.xLocalSummary.textContent = `本地 ${payload.total || 0} 个文件`; if (!payload.items.length) { els.xLocalGrid.innerHTML = `
还没有本地 X 图片或视频。
`; return; } els.xLocalGrid.append(...payload.items.map(renderXLocalCard)); } function renderXLocalCard(item) { const card = document.createElement("article"); card.className = "x-media-card"; const media = item.kind === "video" ? `` : `${escapeHtml(item.name)}`; card.innerHTML = `
${media}
${escapeHtml(item.name)}
${escapeHtml(item.relative_path)} · ${formatBytes(item.size)}
`; return card; } async function deleteXLocalSelected() { const selected = [...document.querySelectorAll("[data-x-local-id]:checked")].map((item) => item.dataset.xLocalId); if (!selected.length) { setStatus("没有选中的本地 X 文件。"); return; } setStatus(`正在删除 ${selected.length} 个本地 X 文件...`); const result = await api("/api/x/local-media/delete", { method: "POST", body: JSON.stringify({ ids: selected }), }); setStatus(`删除完成:${result.deleted.length} 个,失败 ${result.failed.length} 个`); els.xLocalSelectAll.checked = false; await loadXLocalMedia(); } async function previewXhs(event) { event.preventDefault(); const target = els.xhsTarget.value.trim(); if (!target) { setStatus("请输入小红书关键词或笔记链接。"); return; } els.xhsGrid.innerHTML = `
正在解析小红书内容...
`; els.xhsSummary.textContent = "解析中..."; const payload = await api("/api/xiaohongshu/preview", { method: "POST", body: JSON.stringify({ target, limit: Number(els.xhsLimit.value || 20) }), }); state.xhsPreviewId = payload.preview_id; renderXhs(payload); setStatus(`小红书解析完成:${payload.count} 个项目`); } function renderXhs(payload) { els.xhsGrid.innerHTML = ""; els.xhsSummary.textContent = `${payload.count} 个项目`; if (!payload.items.length) { els.xhsGrid.innerHTML = `
没有解析到内容,可能需要先登录或换一个关键词。
`; return; } els.xhsGrid.append(...payload.items.map(renderXhsCard)); els.xhsSelectAll.checked = true; } function renderXhsCard(item) { const card = document.createElement("article"); card.className = "x-media-card"; const preview = item.thumbnail || item.metadata?.cover_url || ""; const media = preview ? `${escapeHtml(item.title || item.id)}` : `
暂无预览
`; card.innerHTML = `
${media}
${escapeHtml(item.title || item.id)}
${escapeHtml(item.author || "")} · ${item.file_count || 0} 个文件
`; return card; } async function downloadXhsSelected() { if (!state.xhsPreviewId) { setStatus("请先解析小红书内容。"); return; } const selected = [...document.querySelectorAll("[data-xhs-id]:checked")].map((item) => item.dataset.xhsId); if (!selected.length) { setStatus("没有选中的小红书项目。"); return; } setStatus(`正在下载 ${selected.length} 个小红书项目...`); const result = await api("/api/xiaohongshu/download", { method: "POST", body: JSON.stringify({ preview_id: state.xhsPreviewId, selected_ids: selected }), }); setStatus(`小红书下载完成:保存 ${result.downloaded_files} 个文件,失败 ${result.failed_items} 项`); } function setActiveView(view) { state.view = view; document.querySelectorAll(".nav-button").forEach((button) => { button.classList.toggle("active", button.dataset.view === view); }); document.querySelectorAll(".view").forEach((section) => section.classList.remove("active")); if (view === "home") { document.querySelector("#homeView").classList.add("active"); } else if (view === "artists") { document.querySelector("#artistsView").classList.add("active"); } else if (view === "sync") { document.querySelector("#syncView").classList.add("active"); } else if (view === "xMedia") { document.querySelector("#xMediaView").classList.add("active"); } else if (view === "xiaohongshu") { document.querySelector("#xiaohongshuView").classList.add("active"); } else { document.querySelector("#galleryView").classList.add("active"); } } async function reloadCurrent() { if (state.view === "home") { setStatus("首页已就绪。选择一个入口开始整理或同步内容。"); } else if (state.view === "favorites") { els.title.textContent = "本地收藏"; els.subtitle.textContent = "你标记收藏的作品"; await loadFavorites(); } else if (state.view === "artists") { await loadArtists(); } else if (state.view === "sync") { await Promise.all([loadFollowed(), loadXFollowed()]); } else if (state.view === "xMedia") { await loadXLocalMedia(); setStatus("X 作者媒体页已就绪。"); } else if (state.view === "xiaohongshu") { setStatus("小红书插件页已就绪。"); } else { if (!state.artistId) { els.title.textContent = state.tag ? `标签:${state.tag}` : "全部作品"; els.subtitle.textContent = state.query ? `搜索:${state.query}` : "本地已入库作品"; } await loadArtworks(); } } function clearFilters() { state.query = ""; state.tag = ""; state.type = ""; state.artistId = ""; state.offset = 0; els.search.value = ""; els.type.value = ""; } function escapeHtml(value) { return String(value ?? "").replace(/[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'", })[char]); } function stripHtml(value) { const tmp = document.createElement("div"); tmp.innerHTML = value; return tmp.textContent || tmp.innerText || ""; } function formatBytes(value) { const size = Number(value || 0); if (size < 1024) return `${size} B`; if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`; return `${(size / 1024 / 1024).toFixed(1)} MB`; } document.querySelectorAll(".nav-button").forEach((button) => { button.addEventListener("click", async () => { setActiveView(button.dataset.view); state.offset = 0; if (state.view !== "gallery") { state.artistId = ""; } await reloadCurrent(); }); }); els.search.addEventListener("input", debounce(async () => { state.query = els.search.value.trim(); state.offset = 0; setActiveView("gallery"); await reloadCurrent(); }, 280)); els.type.addEventListener("change", async () => { state.type = els.type.value; state.offset = 0; setActiveView("gallery"); await reloadCurrent(); }); document.addEventListener("click", async (event) => { const target = event.target.closest("button"); if (!target) return; if (target.dataset.viewAction) { setActiveView(target.dataset.viewAction); state.offset = 0; await reloadCurrent(); return; } if (target.dataset.open) await openArtwork(target.dataset.open); if (target.dataset.fav) await toggleFavorite(target.dataset.fav, target.dataset.on); if (target.dataset.artist) await showArtist(target.dataset.artist); if (target.dataset.tag) { state.tag = target.dataset.tag; state.artistId = ""; state.offset = 0; setActiveView("gallery"); await loadTags(); await reloadCurrent(); } if (target.dataset.follow) { const nextFollowed = target.dataset.followed === "1" ? false : true; await setPixivFollow(target.dataset.follow, target.dataset.name || "", nextFollowed); } if (target.dataset.followX) { const nextFollowed = target.dataset.followedX === "1" ? false : true; await setXFollow(target.dataset.followX, target.dataset.name || "", nextFollowed); } if (target.dataset.openX) { els.xUsername.value = `@${target.dataset.openX}`; setActiveView("xMedia"); setStatus(`已填入 @${target.dataset.openX},可以直接解析最新媒体。`); } }); document.querySelector("#clearFiltersButton").addEventListener("click", async () => { clearFilters(); await loadTags(); await reloadCurrent(); }); document.querySelector("#prevPageButton").addEventListener("click", async () => { state.offset = Math.max(0, state.offset - state.limit); await reloadCurrent(); }); document.querySelector("#nextPageButton").addEventListener("click", async () => { if (state.offset + state.limit < state.total) { state.offset += state.limit; await reloadCurrent(); } }); document.querySelector("#scanButton").addEventListener("click", scanLegacy); document.querySelector("#homeScanButton")?.addEventListener("click", scanLegacy); document.querySelector("#originFollowSyncButton").addEventListener("click", openOriginFollowSyncDialog); document.querySelector("#closeOriginFollowSyncDialogButton").addEventListener("click", () => els.originFollowSyncDialog.close()); document.querySelector("#syncOriginPixivButton").addEventListener("click", () => syncOriginFollows("pixiv")); document.querySelector("#syncOriginXButton").addEventListener("click", () => syncOriginFollows("x")); document.querySelector("#syncButton").addEventListener("click", syncFollowed); document.querySelector("#syncXButton").addEventListener("click", syncXFollowed); document.querySelector("#buildThumbsButton").addEventListener("click", buildThumbnails); document.querySelector("#homeThumbButton")?.addEventListener("click", buildThumbnails); document.querySelector("#closeDialogButton").addEventListener("click", () => els.dialog.close()); document.querySelector("#importPixivCookieButton")?.addEventListener("click", () => importCookieFile("pixiv", els.pixivCookieFile)); els.refreshSessionButton?.addEventListener("click", loadSessionStatus); document.querySelector("#importXCookieButton").addEventListener("click", () => importCookieFile("x", els.xCookieFile)); document.querySelector("#xMediaForm").addEventListener("submit", previewXMedia); document.querySelector("#followCurrentXButton").addEventListener("click", followCurrentX); document.querySelector("#downloadXSelectedButton").addEventListener("click", downloadXSelected); document.querySelector("#refreshXLocalButton").addEventListener("click", loadXLocalMedia); document.querySelector("#deleteXLocalButton").addEventListener("click", deleteXLocalSelected); document.querySelector("#xhsForm").addEventListener("submit", previewXhs); document.querySelector("#downloadXhsSelectedButton").addEventListener("click", downloadXhsSelected); els.xSelectAll.addEventListener("change", () => { document.querySelectorAll("[data-x-id]").forEach((item) => { item.checked = els.xSelectAll.checked; }); }); els.xLocalSelectAll.addEventListener("change", () => { document.querySelectorAll("[data-x-local-id]").forEach((item) => { item.checked = els.xLocalSelectAll.checked; }); }); els.xhsSelectAll.addEventListener("change", () => { document.querySelectorAll("[data-xhs-id]").forEach((item) => { item.checked = els.xhsSelectAll.checked; }); }); document.querySelector("#followForm").addEventListener("submit", async (event) => { event.preventDefault(); const id = document.querySelector("#followArtistId").value.trim(); const name = document.querySelector("#followArtistName").value.trim(); if (!id) return; await followArtist(id, name); event.target.reset(); }); document.querySelector("#xFollowForm").addEventListener("submit", async (event) => { event.preventDefault(); const username = els.xFollowUsername.value.trim(); const name = els.xFollowName.value.trim(); if (!username) return; await followXAuthor(username, name); event.target.reset(); }); function debounce(fn, delay) { let timer = 0; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; } async function boot() { try { await Promise.all([loadPluginPages(), loadSessionStatus(), loadTags(), loadArtworks(), loadFollowed(), loadXFollowed()]); } catch (error) { setStatus(error.message); } } boot();