// ==UserScript== // @name 小红书下载器 // @namespace http://tampermonkey.net/ // @version 3.6.0 // @description 新增下载质量/格式选择、纯视频笔记下载 // @match *://www.xiaohongshu.com/* // @match *://xiaohongshu.com/* // @match *://xhslink.com/* // @grant GM_download // @grant GM_addStyle // @grant GM_notification // @grant GM_xmlhttpRequest // @connect xiaohongshu.com // @connect *.xiaohongshu.com // @connect xhscdn.com // @connect *.xhscdn.com // @connect sns-webpic*.xhscdn.com // @run-at document-idle // @license MIT // ==/UserScript== (function () { 'use strict'; GM_addStyle(` .xhs-download-btn { position: fixed; top: 80px; right: 20px; z-index: 99999; background: linear-gradient(135deg, #ff2442, #ff6b6b); color: white; border: none; border-radius: 24px; padding: 12px 24px; font-size: 14px; font-weight: 600; cursor: pointer; box-shadow: 0 4px 15px rgba(255, 36, 66, 0.4); transition: all 0.3s ease; display: flex; align-items: center; gap: 8px; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; } .xhs-download-btn:hover { transform: translateY(-2px); box-shadow: 0 6px 20px rgba(255, 36, 66, 0.5); } .xhs-download-btn:active { transform: translateY(0); } .xhs-download-btn .icon { font-size: 18px; } .xhs-download-panel { position: fixed; top: 140px; right: 20px; z-index: 99998; background: white; border-radius: 16px; box-shadow: 0 8px 32px rgba(0,0,0,0.15); padding: 20px; width: 380px; max-height: 600px; overflow-y: auto; display: none; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; } .xhs-download-panel.show { display: block; } .xhs-panel-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; padding-bottom: 12px; border-bottom: 1px solid #f0f0f0; } .xhs-panel-title { font-size: 16px; font-weight: 600; color: #333; } .xhs-panel-close { background: none; border: none; font-size: 20px; cursor: pointer; color: #999; width: 28px; height: 28px; display: flex; align-items: center; justify-content: center; border-radius: 50%; transition: all 0.2s; padding: 0; } .xhs-panel-close:hover { background: #f5f5f5; color: #333; } .xhs-mode-switch { display: flex; gap: 8px; margin-bottom: 16px; background: #f5f5f5; border-radius: 10px; padding: 4px; } .xhs-mode-btn { flex: 1; background: transparent; border: none; border-radius: 8px; padding: 8px; font-size: 13px; cursor: pointer; color: #666; transition: all 0.2s; } .xhs-mode-btn.active { background: white; color: #ff2442; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.08); } .xhs-image-list { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; margin-bottom: 16px; } .xhs-image-item { position: relative; aspect-ratio: 1; border-radius: 8px; overflow: hidden; cursor: pointer; border: 2px solid transparent; transition: all 0.2s; } .xhs-image-item.selected { border-color: #ff2442; } .xhs-image-item img { width: 100%; height: 100%; object-fit: cover; } .xhs-image-item .check { position: absolute; top: 4px; right: 4px; width: 20px; height: 20px; background: #ff2442; border-radius: 50%; display: none; align-items: center; justify-content: center; color: white; font-size: 12px; } .xhs-image-item.selected .check { display: flex; } .xhs-select-all { display: flex; align-items: center; gap: 8px; margin-bottom: 12px; font-size: 14px; color: #666; cursor: pointer; } .xhs-download-all-btn { width: 100%; background: linear-gradient(135deg, #ff2442, #ff6b6b); color: white; border: none; border-radius: 12px; padding: 12px; font-size: 14px; font-weight: 600; cursor: pointer; transition: all 0.3s; } .xhs-download-all-btn:hover { opacity: 0.9; } .xhs-download-all-btn:disabled { opacity: 0.5; cursor: not-allowed; } .xhs-progress { margin-top: 12px; font-size: 13px; color: #666; text-align: center; } .xhs-single-download { position: absolute; bottom: 4px; left: 4px; background: rgba(0,0,0,0.6); color: white; border: none; border-radius: 4px; padding: 4px 8px; font-size: 11px; cursor: pointer; opacity: 0; transition: opacity 0.2s; } .xhs-image-item:hover .xhs-single-download { opacity: 1; } .xhs-note-list { display: flex; flex-direction: column; gap: 10px; margin-bottom: 16px; max-height: 380px; overflow-y: auto; } .xhs-note-item { display: flex; gap: 12px; padding: 10px; border-radius: 10px; cursor: pointer; transition: background 0.2s; border: 2px solid transparent; } .xhs-note-item:hover { background: #f9f9f9; } .xhs-note-item.selected { background: #fff5f6; border-color: #ff2442; } .xhs-note-cover { width: 80px; height: 80px; border-radius: 8px; overflow: hidden; flex-shrink: 0; position: relative; } .xhs-note-cover img { width: 100%; height: 100%; object-fit: cover; } .xhs-note-cover .img-count { position: absolute; bottom: 2px; right: 2px; background: rgba(0,0,0,0.6); color: white; font-size: 10px; padding: 1px 5px; border-radius: 4px; } .xhs-note-info { flex: 1; min-width: 0; display: flex; flex-direction: column; justify-content: center; } .xhs-note-title { font-size: 14px; color: #333; font-weight: 500; margin-bottom: 6px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .xhs-note-meta { font-size: 12px; color: #999; } .xhs-note-check { align-self: center; width: 22px; height: 22px; border-radius: 50%; border: 2px solid #ddd; display: flex; align-items: center; justify-content: center; flex-shrink: 0; transition: all 0.2s; } .xhs-note-item.selected .xhs-note-check { background: #ff2442; border-color: #ff2442; color: white; } .xhs-load-more { width: 100%; background: #f5f5f5; border: none; border-radius: 8px; padding: 10px; font-size: 13px; color: #666; cursor: pointer; margin-bottom: 8px; transition: all 0.2s; } .xhs-load-more:hover { background: #eee; } .xhs-load-more:disabled { opacity: 0.5; cursor: not-allowed; } .xhs-refresh-btn { width: 100%; background: #e8f4ff; border: none; border-radius: 8px; padding: 8px; font-size: 12px; color: #1890ff; cursor: pointer; margin-bottom: 12px; transition: all 0.2s; } .xhs-refresh-btn:hover { background: #d6eaff; } .xhs-batch-progress { margin-top: 12px; } .xhs-batch-progress-bar { height: 6px; background: #f0f0f0; border-radius: 3px; overflow: hidden; margin-bottom: 8px; } .xhs-batch-progress-fill { height: 100%; background: linear-gradient(90deg, #ff2442, #ff6b6b); border-radius: 3px; transition: width 0.3s; } .xhs-batch-progress-text { font-size: 12px; color: #666; text-align: center; } .xhs-folder-input { width: 100%; border: 1px solid #e0e0e0; border-radius: 8px; padding: 10px; font-size: 13px; margin-bottom: 12px; box-sizing: border-box; font-family: inherit; } .xhs-folder-input:focus { outline: none; border-color: #ff2442; } .xhs-debug-btn { background: #fff3cd; color: #664d03; border: 1px solid #ffecb5; border-radius: 6px; width: 28px; height: 28px; display: inline-flex; align-items: center; justify-content: center; cursor: pointer; font-size: 15px; line-height: 1; padding: 0; transition: all 0.2s; } .xhs-debug-btn:hover { background: #ffe69c; transform: scale(1.05); } .xhs-subtab-switch { display: flex; gap: 6px; margin-bottom: 14px; background: #f5f5f5; border-radius: 10px; padding: 4px; } .xhs-subtab-btn { flex: 1; background: transparent; border: none; border-radius: 8px; padding: 8px 10px; font-size: 13px; cursor: pointer; color: #666; transition: all 0.2s; } .xhs-subtab-btn.active { background: white; color: #ff2442; font-weight: 600; box-shadow: 0 2px 8px rgba(0,0,0,0.08); } .xhs-refresh-comments-btn { width: 100%; background: #fff5f6; border: 1px solid #ffd4db; color: #ff2442; border-radius: 8px; padding: 10px; font-size: 13px; cursor: pointer; margin-bottom: 12px; transition: all 0.2s; font-weight: 500; } .xhs-refresh-comments-btn:hover { background: #ffe8ec; } .xhs-refresh-comments-btn:disabled { opacity: 0.6; cursor: not-allowed; } .xhs-comment-meta { position: absolute; bottom: 4px; left: 4px; right: 4px; background: rgba(0,0,0,0.55); color: white; padding: 2px 6px; border-radius: 4px; font-size: 10px; line-height: 1.3; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .xhs-comment-meta .cmt-time { color: #ffd4db; margin-right: 4px; } .xhs-live-badge { position: absolute; top: 4px; left: 4px; background: linear-gradient(135deg, #7c3aed, #a855f7); color: white; font-size: 10px; font-weight: 600; padding: 2px 6px; border-radius: 4px; box-shadow: 0 1px 4px rgba(124,58,237,0.5); pointer-events: none; } .xhs-video-badge { position: absolute; top: 4px; left: 4px; background: linear-gradient(135deg, #f59e0b, #ef4444); color: white; font-size: 10px; font-weight: 600; padding: 2px 6px; border-radius: 4px; box-shadow: 0 1px 4px rgba(239,68,68,0.5); pointer-events: none; } .xhs-settings-row { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; padding: 10px; background: #fafafa; border-radius: 8px; margin-bottom: 12px; font-size: 12px; color: #666; } .xhs-settings-row label { display: inline-flex; align-items: center; gap: 4px; } .xhs-settings-row select, .xhs-settings-row input[type="range"] { font-size: 12px; padding: 2px 6px; border: 1px solid #e0e0e0; border-radius: 4px; background: white; } `); let state = { imageUrls: [], liveVideoUrls: [], noteVideoUrl: null, isVideoNote: false, selectedImages: new Set(), commentImages: [], selectedCommentImages: new Set(), noteSubTab: 'note', notesList: [], selectedNotes: new Set(), isDownloading: false, currentMode: 'note', isUserProfile: false, hasMoreNotes: true, loadingMore: false }; // ===== 下载设置(持久化到 localStorage)===== const SETTINGS_KEY = 'xhs_downloader_settings'; const DEFAULT_SETTINGS = { imgFormat: 'original', // original | jpg | png | webp imgQuality: 90, // 1-100,仅非原图时生效 liveMode: 'both' // both | image | video }; function loadSettings() { try { const s = JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}'); return Object.assign({}, DEFAULT_SETTINGS, s); } catch (e) { return Object.assign({}, DEFAULT_SETTINGS); } } function saveSettings(s) { try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(s)); } catch (e) {} } let settings = loadSettings(); function getPageWindow() { return typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; } function pageFetch(url, timeoutMs = 5000) { return new Promise((resolve) => { let done = false; const timer = setTimeout(() => { if (!done) { done = true; resolve(null); } }, timeoutMs); const pw = getPageWindow(); try { pw.fetch(url, { credentials: 'include', mode: 'cors', referrer: 'https://www.xiaohongshu.com/', referrerPolicy: 'strict-origin-when-cross-origin', cache: 'no-cache' }).then(res => { if (done) return; if (!res.ok) { clearTimeout(timer); done = true; resolve(null); return; } res.blob().then(blob => { if (done) return; clearTimeout(timer); done = true; resolve(blob && blob.size > 1000 ? blob : null); }).catch(() => { if (!done) { clearTimeout(timer); done = true; resolve(null); }}); }).catch(() => { if (!done) { clearTimeout(timer); done = true; resolve(null); }}); } catch (e) { if (!done) { clearTimeout(timer); done = true; resolve(null); } } }); } function normalizeUrl(url) { if (!url) return url; return url.replace(/^\/\//, 'https://'); } function getOriginalImageUrl(url) { if (!url) return url; url = normalizeUrl(url); url = url .replace(/\/wm_\d+\//g, '/') .replace(/\/watermark\//g, '/') .replace(/\/watermark_\d+[\w=]*\//g, '/') .replace(/\/format\//g, '/') .replace(/\/imageslim\//g, '/') .replace(/\/quality\/[^\/]+\//g, '/') .replace(/\/thumbnail\/[^\/]+\//g, '/') .replace(/\/imageMogr2\/[^\/]*\//g, '/') .replace(/\/stripmeta(\/|$)/g, '/'); const [base, qs, hash] = splitQueryHash(url); if (qs) { const params = new URLSearchParams(qs); const badKeys = [ 'imageView2', 'watermark', 'watermark_', 'wm', 'format', 'imageslim', 'quality', 'Q', 'q', 'px', 'thumbnail', 'stripmeta', 'imageMogr2', 'interlace', 'auto_orient', 'crop', 'resize', 'w', 'h', 'width', 'height', 'x-amz-process', 'x-oss-process' ]; for (const key of Array.from(params.keys())) { const lower = key.toLowerCase(); if (badKeys.some(b => lower === b.toLowerCase() || lower.startsWith(b.toLowerCase()))) { params.delete(key); } } const newQs = params.toString(); url = base + (newQs ? '?' + newQs : '') + (hash || ''); } return url; } function splitQueryHash(url) { let hash = null; const hashIdx = url.indexOf('#'); if (hashIdx >= 0) { hash = url.substring(hashIdx); url = url.substring(0, hashIdx); } const qIdx = url.indexOf('?'); if (qIdx < 0) return [url, '', hash]; return [url.substring(0, qIdx), url.substring(qIdx + 1), hash]; } function buildOriginalXhsUrl(picObjOrUri, defaultHost) { if (!picObjOrUri) return null; if (typeof picObjOrUri === 'string') { const s = picObjOrUri.trim(); if (!s) return null; if (s.startsWith('//')) return 'https:' + s; if (s.startsWith('http')) return s; const host = defaultHost || 'sns-img-hz.xhscdn.com'; return `https://${host}/${s.replace(/^\/+/, '')}`; } if (typeof picObjOrUri !== 'object') return null; const candidateKeys = [ 'urlReal', 'url_real', 'urlreal', 'urlDefaultMax', 'url_default_max', 'originUrl', 'originalUrl', 'origin_url', 'original_url', 'urlDefault', 'url_default', 'maxUrl', 'max_url', 'bigUrl', 'big_url', 'hdUrl', 'hd_url', 'largeUrl', 'large_url', 'rawUrl', 'raw_url', 'url', 'src', 'fullUrl', 'full_url', 'url_pre', 'urlPrev', 'url_prev', 'uri', 'traceId', 'fileId', 'file_key', 'imageKey', 'imgKey' ]; let best = null; let bestKeyOrder = Infinity; for (let i = 0; i < candidateKeys.length; i++) { const k = candidateKeys[i]; let v = picObjOrUri[k]; if (!v && typeof picObjOrUri.get === 'function') { try { v = picObjOrUri.get(k); } catch(e){} } if (!v) continue; if (typeof v === 'object') { for (const sub of ['urlReal', 'urlDefaultMax', 'originUrl', 'urlDefault', 'url', 'uri']) { if (typeof v[sub] === 'string' && v[sub]) { v = v[sub]; break; } } if (typeof v !== 'string') continue; } if (typeof v !== 'string' || !v.trim()) continue; if (i < bestKeyOrder) { best = v.trim(); bestKeyOrder = i; } if (i <= 3) break; } if (!best) { for (const key2 of Object.keys(picObjOrUri)) { const v = picObjOrUri[key2]; if (typeof v === 'string' && v && (v.startsWith('http') || /^[0-9a-f]{8}[- ]?/i.test(v))) { best = v; break; } } } if (!best) return null; if (best.startsWith('//')) return 'https:' + best; if (best.startsWith('http')) return best; const host = defaultHost || 'sns-img-hz.xhscdn.com'; return `https://${host}/${best.replace(/^\/+/, '')}`; } // 从笔记图对象中提取实况图(Live Photo)对应的短视频URL // 小红书实况图结构常见于: img.livePhoto.video.masterUrl / stream.h264[].masterUrl function extractLiveVideoUrl(imgObj) { if (!imgObj || typeof imgObj !== 'object') return null; const tried = new Set(); function pickUrl(obj) { if (!obj || typeof obj !== 'object') return null; const candidates = [ obj.masterUrl, obj.master_url, obj.url, obj.urlReal, obj.urlDefault, obj.uri, obj.fileId, obj.file_key ]; for (const c of candidates) { if (typeof c === 'string' && c) { let u = c.trim(); if (u.startsWith('//')) u = 'https:' + u; else if (!u.startsWith('http')) { const host = 'sns-video-hw.xhscdn.com'; u = `https://${host}/${u.replace(/^\/+/, '')}`; } return u; } } return null; } function digInto(streamObj) { if (!streamObj || typeof streamObj !== 'object') return null; // stream.h264 / stream.h265 等数组 for (const fmt of ['h264', 'h265', 'av1']) { const arr = streamObj[fmt]; if (Array.isArray(arr)) { for (const it of arr) { const u = pickUrl(it); if (u) return u; } } } // 直接字段 const direct = pickUrl(streamObj); if (direct) return direct; return null; } // 候选根节点 const roots = [ imgObj.livePhoto, imgObj.live_photo, imgObj.video, imgObj.media, imgObj.info?.livePhoto, imgObj.info?.video, imgObj.extra?.livePhoto, imgObj.extra?.video, ]; for (const root of roots) { if (!root || typeof root !== 'object') continue; if (tried.has(root)) continue; tried.add(root); // root.video 直接 if (root.video && typeof root.video === 'object') { const u = pickUrl(root.video); if (u) return u; if (root.video.stream) { const s = digInto(root.video.stream); if (s) return s; } } // root.stream if (root.stream) { const s = digInto(root.stream); if (s) return s; } // root 本身可能就是视频对象 const direct = pickUrl(root); if (direct) return direct; } // 兜底:扫描对象中所有含 video/masterUrl 的字符串字段 try { const json = JSON.stringify(imgObj); const re = /"(masterUrl|master_url|url)"\s*:\s*"((?:https?:)?\/\/[^"\\]*(?:xhscdn|sns-video)[^"\\]*)"/gi; let m; while ((m = re.exec(json)) !== null) { let u = m[2].replace(/\\\//g, '/'); if (u.startsWith('//')) u = 'https:' + u; if (u.includes('video') || u.includes('.mp4')) return u; } } catch (e) {} return null; } // 提取纯视频笔记的视频URL(区别于实况图:整笔记就是视频) function extractNoteVideoUrl(note) { if (!note || typeof note !== 'object') return null; const video = note.video || note.media || null; if (!video || typeof video !== 'object') return null; function pickUrl(obj) { if (!obj || typeof obj !== 'object') return null; const candidates = [obj.masterUrl, obj.master_url, obj.url, obj.uri]; for (const c of candidates) { if (typeof c === 'string' && c) { let u = c.trim(); if (u.startsWith('//')) u = 'https:' + u; else if (!u.startsWith('http')) u = 'https://sns-video-hw.xhscdn.com/' + u.replace(/^\/+/, ''); return u; } } return null; } // video.media.stream.h264[].masterUrl const media = video.media || video; if (media.stream && typeof media.stream === 'object') { for (const fmt of ['h264', 'h265', 'av1']) { const arr = media.stream[fmt]; if (Array.isArray(arr)) { for (const it of arr) { const u = pickUrl(it); if (u) return u; } } } } // 直接字段 return pickUrl(media) || pickUrl(video); } function getRealDomImageSrc(img) { if (!img) return null; const candidates = []; if (img.dataset) { const ds = img.dataset; if (ds.src) candidates.push(ds.src); if (ds.originalSrc) candidates.push(ds.originalSrc); if (ds.originSrc) candidates.push(ds.originSrc); if (ds.original) candidates.push(ds.original); if (ds.origin) candidates.push(ds.origin); if (ds.lazySrc) candidates.push(ds.lazySrc); if (ds.lazysrc) candidates.push(ds.lazysrc); if (ds.realSrc) candidates.push(ds.realSrc); if (ds.realsrc) candidates.push(ds.realsrc); if (ds.fullSrc) candidates.push(ds.fullSrc); if (ds.hdSrc) candidates.push(ds.hdSrc); if (ds.bigSrc) candidates.push(ds.bigSrc); if (ds.url) candidates.push(ds.url); if (ds.zoomSrc) candidates.push(ds.zoomSrc); if (ds.previewSrc) candidates.push(ds.previewSrc); if (ds.rawSrc) candidates.push(ds.rawSrc); } for (const attr of ['data-src', 'data-original', 'data-original-src', 'data-origin', 'data-origin-src', 'data-lazy-src', 'data-lazysrc', 'data-real-src', 'data-realsrc', 'data-full-src', 'data-hd-src', 'data-big-src', 'data-url', 'data-zoom-src', 'data-preview-src', 'data-preview', 'data-raw-src', 'data-big', 'data-hd']) { const v = img.getAttribute(attr); if (v) candidates.push(v); } if (img.srcset) candidates.push(...img.srcset.split(',').map(s => s.trim().split(/\s+/)[0]).filter(Boolean)); if (img.getAttribute('src')) candidates.push(img.getAttribute('src')); if (img.currentSrc) candidates.push(img.currentSrc); if (img.src) candidates.push(img.src); if (candidates.length === 0) { const parent = img.parentElement; if (parent && parent.tagName === 'A' && parent.href) candidates.push(parent.href); } for (const raw of candidates) { const cleaned = getOriginalImageUrl(raw); if (!cleaned) continue; if (!cleaned.includes('xhscdn') && !cleaned.includes('sns-webpic') && !cleaned.includes('http')) continue; const [base, qs] = splitQueryHash(cleaned); const hasThumb = qs && (/imageView/i.test(qs) || /\bw=/.test(qs) || /\bh=/.test(qs) || /thumbnail/i.test(qs)); if (cleaned.includes('xhscdn') || cleaned.includes('sns-webpic')) { if (!hasThumb) return cleaned; } } if (candidates.length === 0) return null; return getOriginalImageUrl(candidates[0]); } function getThumbUrl(url) { if (!url) return url; const base = getOriginalImageUrl(url); const [onlyBase, qs] = splitQueryHash(base); return onlyBase + (qs ? '?' + qs + '&' : '?') + 'imageView2/1/w/200/h/200/format/webp'; } function sanitizeFilename(name) { if (name === null || name === undefined) return ''; const s = String(name).replace(/[\\/:*?"<>|]/g, '_').substring(0, 80).trim(); return s; } function safeFilename(name, fallback) { const out = sanitizeFilename(name); if (out) return out; return (typeof fallback === 'string' && fallback) ? fallback : 'untitled'; } function escapeHtml(text) { const div = document.createElement('div'); div.textContent = text; return div.innerHTML; } function isProfilePage() { const path = window.location.pathname; if (path.includes('/explore/') || path.includes('/search_result/') || path.includes('/discovery/')) return false; if (path === '/' || path === '' || path === '/home') return false; return path.includes('/user/') || path.includes('/profile/'); } function debugLog(...args) { console.log('[XHS下载器]', ...args); } function describeValue(v) { if (v === null) return 'null'; if (v === undefined) return 'undefined'; const t = typeof v; if (t === 'string') { const s = v.length > 120 ? v.substring(0, 120) + '…' : v; return `str(len=${v.length}): "${s}"`; } if (t === 'number' || t === 'boolean') return `${t}: ${v}`; if (t === 'object') { if (Array.isArray(v)) return `array(len=${v.length})`; const keys = Object.keys(v); return `object(keys=${keys.length}): {${keys.slice(0, 20).join(', ') + (keys.length > 20 ? '…' : '')}}`; } return `${t}`; } function dumpAllFields(obj, label, depth = 0, visited = null) { if (!visited) visited = new WeakSet(); if (depth > 2) return; if (!obj || typeof obj !== 'object') { debugLog(`[dump ${label}] ${describeValue(obj)}`); return; } if (visited.has(obj)) return; visited.add(obj); const entries = Object.entries(obj); debugLog(`===== ${label} (${entries.length} fields) =====`); for (const [k, v] of entries) { if (v && typeof v === 'object' && !Array.isArray(v)) { const subKeys = Object.keys(v); debugLog(` ${k} = object(${subKeys.length}): ${describeValue(v)}`); if (depth < 1 && subKeys.length <= 40) { for (const sk of subKeys) { debugLog(` .${sk} = ${describeValue(v[sk])}`); } } } else if (Array.isArray(v)) { debugLog(` ${k} = ${describeValue(v)}`); if (depth < 1 && v.length > 0 && v.length <= 5) { v.forEach((it, i) => debugLog(` [${i}] ${describeValue(it)}`)); } else if (depth < 1 && v.length > 0) { debugLog(` [0] ${describeValue(v[0])}`); if (v.length > 1) debugLog(` [last] ${describeValue(v[v.length-1])}`); } } else { debugLog(` ${k} = ${describeValue(v)}`); } } } function debugDumpOrigins() { debugLog('╔══════════════════════════════════════════════════════════╗'); debugLog('║ 🔍 原图字段结构排查 (把以下日志完整截图发给我) ║'); debugLog('╚══════════════════════════════════════════════════════════╝'); const pw = getPageWindow(); const pageState = pw.__INITIAL_STATE__; if (pageState?.note?.noteDetailMap) { const noteMap = pageState.note.noteDetailMap; const currentId = pageState.note?.currentNoteId || pageState.note?.activeNoteId; debugLog('当前笔记ID:', currentId); let targetNote = null; if (currentId && noteMap[currentId]?.note) targetNote = noteMap[currentId].note; if (!targetNote) { for (const k in noteMap) { if (noteMap[k]?.note?.imageList?.length) { targetNote = noteMap[k].note; break; } } } pw.__xhs_noteImg = targetNote?.imageList?.[0] || null; pw.__xhs_noteAllKeys = targetNote ? Object.keys(targetNote) : null; if (targetNote?.imageList && targetNote.imageList.length > 0) { debugLog(`笔记图 imageList 长度: ${targetNote.imageList.length}`); dumpAllFields(targetNote.imageList[0], '笔记图 imageList[0] 完整字段'); // 实况图字段排查 let liveFound = 0; targetNote.imageList.forEach((img, i) => { const lv = extractLiveVideoUrl(img); if (lv) { liveFound++; debugLog(` ✅ imageList[${i}] 是实况图, 视频URL = ${lv.substring(0, 100)}`); } }); debugLog(`实况图检测结果: 共 ${liveFound}/${targetNote.imageList.length} 张实况图`); if (targetNote.imageList.length > 1) { debugLog(`笔记图 imageList[1] 样例:`); for (const k of Object.keys(targetNote.imageList[1]).sort()) { debugLog(` ${k} = ${describeValue(targetNote.imageList[1][k])}`); } } } else { debugLog('⚠️ STATE中没找到笔记图 imageList'); } } debugLog(''); debugLog('--- 评论区 pictures 结构检查 ---'); let cmtExamples = []; function scanForComments(obj, depth, visited) { if (cmtExamples.length >= 5 || depth > 7 || !obj || typeof obj !== 'object') return; if (visited.has(obj)) return; visited.add(obj); if (Array.isArray(obj)) { for (const it of obj) scanForComments(it, depth + 1, visited); return; } const keys = Object.keys(obj); for (const arrKey of ['pictures','pics','images','imageList']) { if (Array.isArray(obj[arrKey]) && obj[arrKey].length > 0 && obj[arrKey].some(x => { if (!x || typeof x !== 'object') return false; return Object.keys(x).some(k => /url|uri|src|trace|fileId/i.test(k)); })) { cmtExamples.push({ parentKeyList: keys, picturesElem: obj[arrKey][0], hasUser: !!(obj.user || obj.userInfo || obj.authorInfo || obj.nickUser), hasContent: !!(obj.content || obj.body || obj.text), arrName: arrKey, }); if (cmtExamples.length >= 5) return; } } for (const subKey of keys) { const sub = obj[subKey]; if (!sub || typeof sub !== 'object') continue; if (subKey === 'router' || subKey === 'route' || subKey.startsWith('__')) continue; scanForComments(sub, depth + 1, visited); } } scanForComments(pageState || pw, 0, new WeakSet()); pw.__xhs_cmtImgs = cmtExamples.map(e => e.picturesElem); debugLog(`找到 ${cmtExamples.length} 条带图评论示例`); if (cmtExamples.length === 0) { debugLog('⚠️ 没在STATE中找到带pictures字段的评论。请先滚动加载评论后再点一次此按钮。'); } cmtExamples.forEach((ex, i) => { debugLog(''); debugLog(`★★ 评论图示例 #${i+1} (数组名: ${ex.arrName}, 含评论user:${ex.hasUser} 含content:${ex.hasContent})`); dumpAllFields(ex.picturesElem, `评论图 pictures[0]`); }); debugLog(''); debugLog('--- 当前脚本提取出的URL对比 ---'); debugLog(`笔记图最终URL[0] = ${state.imageUrls?.[0] || '(无)'}`); debugLog(`评论图最终URL[0] = ${state.commentImages?.[0]?.url || '(无)'}`); if (state.commentImages && state.commentImages[0]) { debugLog(`评论图[0] 提取自: commenter=${state.commentImages[0].commenter}, time=${state.commentImages[0].commentTime}`); } debugLog(''); debugLog('★ 以下变量已挂载到页面window便于展开查看'); debugLog(' __xhs_noteImg = 笔记图 imageList[0] 原始对象'); debugLog(' __xhs_noteAllKeys = 笔记对象的所有字段名'); debugLog(' __xhs_cmtImgs = 评论图 pictures[0] 原始对象数组 (最多5个)'); debugLog(''); debugLog('▸ 请把以上控制台输出(或截图)发给我,我可以精确定位哪个字段才是评论图的原图。'); } function extractNoteImages(targetNoteId) { const urls = []; const liveVideos = []; let noteVideoUrl = null; let isVideoNote = false; const seen = new Set(); const pw = getPageWindow(); function addUrl(src, liveUrl) { if (!src) return false; const clean = getOriginalImageUrl(src); if (!clean || seen.has(clean)) return false; if (!clean.includes('xhscdn') && !clean.includes('sns-webpic')) return false; if (clean.includes('avatar') || clean.includes('/icon/') || clean.includes('emoji')) return false; seen.add(clean); urls.push(clean); liveVideos.push(liveUrl || null); return true; } try { const state = pw.__INITIAL_STATE__; if (state?.note?.noteDetailMap) { const noteMap = state.note.noteDetailMap; let targetNote = null; if (targetNoteId && noteMap[targetNoteId]?.note) { targetNote = noteMap[targetNoteId].note; } else { const currentId = state.note?.currentNoteId || state.note?.activeNoteId; if (currentId && noteMap[currentId]?.note) { targetNote = noteMap[currentId].note; } else if (targetNoteId) { for (const key in noteMap) { const n = noteMap[key]?.note; if (n?.noteId === targetNoteId) { targetNote = n; break; } } } } if (!targetNote) { const candidates = []; for (const key in noteMap) { const n = noteMap[key]?.note; if (n?.imageList && Array.isArray(n.imageList) && n.imageList.length > 0) { candidates.push(n); } } if (candidates.length === 1) { targetNote = candidates[0]; } else if (candidates.length > 1) { const domTitle = document.querySelector('#detail-title'); const domText = domTitle?.textContent?.trim(); if (domText) { for (const n of candidates) { if (n.title && domText.includes(n.title.substring(0, 5))) { targetNote = n; break; } } } if (!targetNote) targetNote = candidates[candidates.length - 1]; } } if (targetNote?.imageList && Array.isArray(targetNote.imageList)) { targetNote.imageList.forEach(img => { const url = buildOriginalXhsUrl(img); if (url) { const liveUrl = extractLiveVideoUrl(img); addUrl(url, liveUrl); } }); } // 检测是否为纯视频笔记 if (targetNote) { const nvUrl = extractNoteVideoUrl(targetNote); if (nvUrl) { noteVideoUrl = nvUrl; isVideoNote = true; debugLog('检测到纯视频笔记, 视频URL:', nvUrl.substring(0, 100)); } } } } catch (e) { debugLog('STATE提取失败:', e.message); } try { const nuxt = pw.__NUXT__; if (nuxt?.data?.[0]?.note?.imageList) { nuxt.data[0].note.imageList.forEach(img => { const url = buildOriginalXhsUrl(img); if (url) { const liveUrl = extractLiveVideoUrl(img); addUrl(url, liveUrl); } }); } } catch (e) {} if (urls.length > 0 || noteVideoUrl) { const liveCount = liveVideos.filter(Boolean).length; debugLog(`从STATE提取到 ${urls.length} 张图片 (含 ${liveCount} 张实况图)${isVideoNote ? ' [视频笔记]' : ''}`); return { urls, liveVideos, noteVideoUrl, isVideoNote }; } debugLog('STATE未找到,从DOM提取...'); const noteContainer = document.querySelector( '.note-detail-mask, .note-content, .note-slider, .swiper, .carousel, ' + '[class*="noteDetail"], [class*="note-detail"], .zoom-in-pic, ' + '.note-scroller, [class*="interactionContainer"]' ); const searchRoot = noteContainer || document; const imgs = searchRoot.querySelectorAll('img'); imgs.forEach(img => { const src = getRealDomImageSrc(img) || img.currentSrc || img.src; if (!src) return; const rect = img.getBoundingClientRect(); if (rect.width < 200 || rect.height < 200) return; const style = window.getComputedStyle(img); if (style.display === 'none' || style.visibility === 'hidden') return; addUrl(src, null); }); debugLog(`从DOM提取到 ${urls.length} 张图片`); return { urls, liveVideos, noteVideoUrl, isVideoNote }; } function extractCommentImages(noteId) { const result = []; const seen = new Set(); const pw = getPageWindow(); function addImage(src, commenter, commentTime, commentId) { if (!src) return; const clean = getOriginalImageUrl(src); if (!clean || seen.has(clean)) return; if (!clean.includes('xhscdn') && !clean.includes('sns-webpic')) return; if (clean.includes('avatar') || clean.includes('/icon/') || clean.includes('emoji')) return; seen.add(clean); result.push({ url: clean, commenter: sanitizeFilename(commenter) || 'anonymous', commentTime: formatNoteDate(commentTime) || '', commentId: commentId || ('c_' + result.length) }); } try { const state = pw.__INITIAL_STATE__; if (state) { let commentsMap = null; let commentsArr = null; const tryPaths = [ state?.comment?.commentDetailMap, state?.comments?.commentDetailMap, state?.note?.commentDetailMap, state?.feedsComments?.commentDetailMap, ]; for (const m of tryPaths) { if (m && typeof m === 'object' && Object.keys(m).length > 0) { commentsMap = m; break; } } if (!commentsMap) { const arrPaths = [ state?.comment?.comments, state?.comments?.list, state?.comments?.comments, state?.note?.comments, state?.feedsComments?.comments, state?.comment?.list, ]; for (const a of arrPaths) { if (Array.isArray(a) && a.length > 0) { commentsArr = a; break; } } } function processComment(c) { if (!c) return; const commentId = c.id || c.commentId || c.comment_id || ('c_' + Math.random().toString(36).substring(2, 10)); const user = c.user || c.userInfo || c.user_info || c.authorInfo || c.author_info || c.nickUser || {}; const commenter = user.nickname || user.nickName || user.name || user.userName || c.userName || c.user_name || 'anonymous'; const time = c.time || c.createTime || c.created_at || c.publishTime || c.lastUpdateTime || 0; let pics = []; if (Array.isArray(c.pictures)) pics = pics.concat(c.pictures); if (Array.isArray(c.pics)) pics = pics.concat(c.pics); if (Array.isArray(c.images)) pics = pics.concat(c.images); if (Array.isArray(c.imageList)) pics = pics.concat(c.imageList); if (c.picture && typeof c.picture === 'object') pics.push(c.picture); pics.forEach(pic => { if (!pic) return; let src = null; if (typeof pic === 'string') { src = buildOriginalXhsUrl(pic); } else { src = buildOriginalXhsUrl(pic); if (!src) { for (const key of Object.keys(pic)) { const v = pic[key]; if (v && typeof v === 'string' && (v.startsWith('http') || /^[0-9a-f]{8}[0-9a-f-]{0,32}$/i.test(v))) { src = buildOriginalXhsUrl(v); if (src) break; } } } } if (src) addImage(src, commenter, time, commentId); }); if (Array.isArray(c.subComments) || Array.isArray(c.sub_comments) || Array.isArray(c.replyComments)) { const subs = c.subComments || c.sub_comments || c.replyComments || []; subs.forEach(sc => processComment(sc)); } } if (commentsMap) { for (const key in commentsMap) { const entry = commentsMap[key]; const comment = entry.comment || entry; if (Array.isArray(comment)) { comment.forEach(c => processComment(c)); } else { processComment(comment); } } } if (commentsArr) { commentsArr.forEach(c => processComment(c)); } if (result.length === 0) { function findCommentsInObject(obj, depth, visited) { if (depth > 5 || result.length > 50) return; if (!obj || typeof obj !== 'object') return; if (visited.has(obj)) return; visited.add(obj); if (Array.isArray(obj)) { if (obj.length > 0 && obj.length < 300) { const looksLikeComment = obj.some(x => x && typeof x === 'object' && (x.pictures || x.pics || x.images || (x.user && (x.user.nickname || x.user.nickName))) ); if (looksLikeComment) { obj.forEach(c => processComment(c)); return; } } obj.forEach(x => findCommentsInObject(x, depth + 1, visited)); return; } for (const key of Object.keys(obj)) { if (key.startsWith('__')) continue; try { findCommentsInObject(obj[key], depth + 1, visited); } catch (e) {} } } findCommentsInObject(state, 0, new WeakSet()); } } } catch (e) { debugLog('STATE评论图片提取失败:', e.message); } if (result.length > 0) { debugLog(`从STATE提取到 ${result.length} 张评论图片`); return result; } debugLog('STATE未找到评论图片,从DOM提取...'); const commentRoot = document.querySelector( '.comment-container, .comment-section, .comments-wrapper, ' + '[class*="commentContainer"], [class*="commentSection"], [class*="commentsWrapper"], ' + '.note-scroller, [class*="interactionContainer"], [class*="note-detail"]' ) || document; const commentItems = commentRoot.querySelectorAll( '.comment-item, .comment, .parent-comment, .sub-comment, .reply-item, ' + '[class*="commentItem"], [class*="parentComment"], [class*="subComment"], [class*="replyItem"]' ); commentItems.forEach((item, idx) => { const commenterEl = item.querySelector('.nickname, .user-name, .username, .author, [class*="userName"], [class*="nick-name"]'); const commenter = commenterEl?.textContent?.trim() || ('commenter_' + (idx + 1)); const imgs = item.querySelectorAll('img'); imgs.forEach(img => { const src = getRealDomImageSrc(img) || img.currentSrc || img.src; if (!src) return; const rect = img.getBoundingClientRect(); if (rect.width < 50 || rect.height < 50) return; if (rect.width === rect.height && (rect.width === 32 || rect.width === 36 || rect.width === 40 || rect.width === 48)) return; const style = window.getComputedStyle(img); if (style.display === 'none' || style.visibility === 'hidden') return; if (img.closest('.avatar, [class*="Avatar"], [class*="avatar"]')) return; if (img.alt && (img.alt.includes('avatar') || img.alt.includes('头像'))) return; if (src.includes('avatar') || src.includes('emoji') || src.includes('/icon/')) return; addImage(src, commenter, 0, 'dom_c_' + idx); }); }); debugLog(`从DOM提取到 ${result.length} 张评论图片`); return result; } function extractNotesList() { const notes = []; const seen = new Set(); const pw = getPageWindow(); debugLog('开始提取笔记列表...'); function addNote(noteId, title, coverUrl, imgCount) { if (!noteId || noteId.length < 20 || seen.has(noteId)) return; if (!coverUrl) return; seen.add(noteId); notes.push({ id: noteId, title: (sanitizeFilename(title).substring(0, 60)) || '未命名笔记', cover: normalizeUrl(coverUrl), imageCount: imgCount || 1 }); } try { const state = pw.__INITIAL_STATE__; if (state) { const searchPaths = [ state?.user?.userPageData?.notes, state?.user?.userPostedNotes, state?.user?.noteBook?.notes, state?.note?.notes, state?.feed?.notes, state?.userFeed?.notes ]; for (const notesArr of searchPaths) { if (Array.isArray(notesArr) && notesArr.length > 0) { debugLog(`找到笔记数组,长度: ${notesArr.length}`); notesArr.forEach(n => { if (!n) return; const nid = n.noteId || n.id; let cover = ''; if (n.cover) { cover = typeof n.cover === 'string' ? n.cover : (n.cover.url || n.cover.urlDefault || n.cover.urlReal); } else if (n.imageList?.[0]) { const img = n.imageList[0]; cover = typeof img === 'string' ? img : (img.urlDefault || img.url || img.urlReal); } if (nid && cover) { addNote(nid, n.displayTitle || n.title || n.desc, cover, n.imageCount || (n.imageList?.length || 1)); } }); if (notes.length > 0) break; } } function findNotesInObject(obj, depth, visited) { if (depth > 5 || !obj || typeof obj !== 'object') return; if (visited.has(obj)) return; visited.add(obj); if (Array.isArray(obj)) { if (obj.length > 3 && obj.length < 100) { const looksLikeNotes = obj.some(x => x && typeof x === 'object' && (x.noteId || x.id) && (x.cover || x.imageList || x.imagesList) ); if (looksLikeNotes) { obj.forEach(n => { if (!n) return; const nid = n.noteId || n.id; let cover = ''; if (n.cover) { cover = typeof n.cover === 'string' ? n.cover : (n.cover.url || n.cover.urlDefault || n.cover.urlReal); } else if (n.imageList?.[0]) { const img = n.imageList[0]; cover = typeof img === 'string' ? img : (img.urlDefault || img.url || img.urlReal); } if (nid && cover) { addNote(nid, n.displayTitle || n.title || n.desc, cover, n.imageCount || n.imageList?.length); } }); } } if (notes.length === 0) { obj.forEach(x => findNotesInObject(x, depth + 1, visited)); } return; } const keys = Object.keys(obj); for (const key of keys) { if (key.startsWith('__')) continue; try { findNotesInObject(obj[key], depth + 1, visited); } catch (e) {} if (notes.length > 50) return; } } if (notes.length === 0) { debugLog('固定路径未找到,浅层搜索STATE...'); findNotesInObject(state, 0, new WeakSet()); } } } catch (e) { debugLog('STATE提取笔记失败:', e.message); } debugLog(`STATE提取到 ${notes.length} 个笔记,开始DOM提取...`); const noteIdRegex = /([a-f0-9]{24})/i; const allLinks = document.querySelectorAll('a[href]'); allLinks.forEach(a => { const href = a.getAttribute('href') || ''; if (!href.includes('/explore/') && !href.includes('/discovery/') && !href.includes('/item/')) return; const match = href.match(noteIdRegex); if (!match) return; const noteId = match[1]; if (seen.has(noteId)) return; let img = a.querySelector('img'); if (!img) { for (let p = a.parentElement; p && p !== document.body; p = p.parentElement) { img = p.querySelector('img'); if (img) break; } } if (!img?.src) return; const src = img.currentSrc || img.src; if (!src.includes('xhscdn') && !src.includes('sns-webpic')) return; if (src.includes('avatar') || src.includes('icon') || src.includes('logo')) return; const rect = img.getBoundingClientRect(); if (rect.width < 80 || rect.height < 80) return; let title = ''; let el = a; for (let i = 0; i < 8; i++) { el = el.parentElement; if (!el) break; const textEls = el.querySelectorAll('span, p, a, div'); for (const t of textEls) { const txt = t.textContent?.trim(); if (txt && txt.length > 2 && txt.length < 80 && !txt.match(/^\d+$/) && !txt.includes('赞') && !txt.includes('评论') && !txt.includes('收藏') && !txt.includes('http') && !txt.includes('www.') && !txt.includes('关注')) { title = txt; break; } } if (title) break; } addNote(noteId, title, src, 1); }); debugLog(`链接提取到 ${notes.length} 个笔记,扫描封面图...`); const coverImgs = document.querySelectorAll('img'); coverImgs.forEach(img => { const src = img.currentSrc || img.src; if (!src) return; if (!src.includes('xhscdn') && !src.includes('sns-webpic')) return; if (src.includes('avatar') || src.includes('icon') || src.includes('logo') || src.includes('/emoji/') || src.includes('/avatar/')) return; const rect = img.getBoundingClientRect(); if (rect.width < 100 || rect.height < 100) return; let card = null; let p = img.parentElement; for (let i = 0; i < 8; i++) { if (!p) break; const tag = p.tagName?.toLowerCase(); const cls = p.className || ''; if (tag === 'section' || tag === 'article' || (typeof cls === 'string' && (cls.includes('note') || cls.includes('card') || cls.includes('feed') || cls.includes('item')))) { card = p; break; } if (tag === 'a' && p.getAttribute('href')?.match(noteIdRegex)) { card = p; break; } p = p.parentElement; } if (!card) return; let noteId = null; const cardId = card.id || card.getAttribute('data-note-id') || card.getAttribute('data-id'); if (cardId) { const m = cardId.match(noteIdRegex); if (m) noteId = m[1]; } if (!noteId) { const cardLink = card.querySelector('a[href]'); if (cardLink) { const href = cardLink.getAttribute('href') || ''; const m = href.match(noteIdRegex); if (m && href.length > 10) noteId = m[1]; } } if (!noteId) { const attrs = Array.from(card.attributes); for (const attr of attrs) { if (attr.value && typeof attr.value === 'string' && attr.value.length >= 24) { const m = attr.value.match(noteIdRegex); if (m && m[1].length === 24) { noteId = m[1]; break; } } } } if (!noteId) { const reactKey = Object.keys(card).find(k => k.startsWith('__reactFiber') || k.startsWith('__reactProps')); if (reactKey) { try { const props = card[reactKey]; const propsStr = JSON.stringify(props); const m = propsStr.match(noteIdRegex); if (m) noteId = m[1]; } catch (e) {} } } if (!noteId) return; if (seen.has(noteId)) return; let title = ''; const textEls = card.querySelectorAll('span, p, div'); for (const t of textEls) { const txt = t.textContent?.trim(); if (txt && txt.length > 2 && txt.length < 80 && !txt.match(/^\d+$/) && !txt.includes('赞') && !txt.includes('评论') && !txt.includes('收藏') && !txt.includes('http')) { title = txt; break; } } addNote(noteId, title, src, 1); }); debugLog(`最终提取到 ${notes.length} 个笔记`); return notes; } async function loadMoreNotes() { if (state.loadingMore || !state.hasMoreNotes) return; state.loadingMore = true; const loadBtn = document.querySelector('.xhs-load-more'); if (loadBtn) { loadBtn.disabled = true; loadBtn.textContent = '加载中...'; } window.scrollTo(0, document.body.scrollHeight); await new Promise(r => setTimeout(r, 2000)); const newNotes = extractNotesList(); const existingIds = new Set(state.notesList.map(n => n.id)); newNotes.forEach(n => { if (!existingIds.has(n.id)) state.notesList.push(n); }); state.loadingMore = false; renderNotesPanel(); } function extractStateFromHtml(html) { try { const scriptRegex = /]*>([\s\S]*?)<\/script>/gi; let m; while ((m = scriptRegex.exec(html)) !== null) { const scriptContent = m[1]; if (!scriptContent.includes('INITIAL_STATE') && !scriptContent.includes('__INITIAL')) continue; const stateMarkers = [ 'window.__INITIAL_STATE__=', 'window.__INITIAL_STATE__ =', '__INITIAL_STATE__=', 'window.__INITIAL_SSR_STATE__=', 'window.__INITIAL_SSR_STATE__ =' ]; for (const marker of stateMarkers) { const startIdx = scriptContent.indexOf(marker); if (startIdx === -1) continue; let pos = startIdx + marker.length; while (pos < scriptContent.length && /\s/.test(scriptContent[pos])) pos++; if (scriptContent[pos] !== '{') continue; let depth = 0; let endPos = -1; let inString = false; let escape = false; let startPos = pos; for (let i = pos; i < scriptContent.length; i++) { const ch = scriptContent[i]; if (escape) { escape = false; continue; } if (ch === '\\') { escape = true; continue; } if (ch === '"') { inString = !inString; continue; } if (inString) continue; if (ch === '{') depth++; else if (ch === '}') { depth--; if (depth === 0) { endPos = i + 1; break; } } } if (endPos > startPos) { let jsonStr = scriptContent.substring(startPos, endPos); try { return JSON.parse(jsonStr.replace(/\bundefined\b/g, 'null')); } catch (e) { try { jsonStr = jsonStr.replace(/,\s*}/g, '}').replace(/,\s*]/g, ']'); return JSON.parse(jsonStr.replace(/\bundefined\b/g, 'null')); } catch (e2) { debugLog('SCRIPT中JSON解析失败:', e2.message?.substring(0, 100)); } } } } } const stateMarkers = [ 'window.__INITIAL_STATE__=', 'window.__INITIAL_STATE__ =', '__INITIAL_STATE__=', 'window.__INITIAL_SSR_STATE__=' ]; for (const marker of stateMarkers) { const startIdx = html.indexOf(marker); if (startIdx === -1) continue; let pos = startIdx + marker.length; while (pos < html.length && /\s/.test(html[pos])) pos++; if (html[pos] !== '{') continue; let depth = 0; let endPos = -1; let inString = false; let escape = false; let startPos = pos; for (let i = pos; i < html.length; i++) { const ch = html[i]; if (escape) { escape = false; continue; } if (ch === '\\') { escape = true; continue; } if (ch === '"') { inString = !inString; continue; } if (inString) continue; if (ch === '{') depth++; else if (ch === '}') { depth--; if (depth === 0) { endPos = i + 1; break; } } } if (endPos > startPos) { let jsonStr = html.substring(startPos, endPos); try { return JSON.parse(jsonStr.replace(/\bundefined\b/g, 'null')); } catch (e) { debugLog('HTML中JSON解析失败,尝试修复...', e.message?.substring(0, 80)); try { jsonStr = jsonStr.replace(/,\s*}/g, '}').replace(/,\s*]/g, ']'); return JSON.parse(jsonStr.replace(/\bundefined\b/g, 'null')); } catch (e2) { debugLog('修复后仍失败:', e2.message?.substring(0, 80)); } } } } } catch (e) { debugLog('提取STATE出错:', e); } return null; } function extractJsonArrayAt(html, marker) { const idx = html.indexOf(marker); if (idx === -1) return null; let pos = idx + marker.length; while (pos < html.length && /\s/.test(html[pos])) pos++; if (html[pos] !== '[') return null; let depth = 0; let endPos = -1; let inString = false; let escape = false; let startPos = pos; for (let i = pos; i < html.length; i++) { const ch = html[i]; if (escape) { escape = false; continue; } if (ch === '\\') { escape = true; continue; } if (ch === '"') { inString = !inString; continue; } if (inString) continue; if (ch === '[') depth++; else if (ch === ']') { depth--; if (depth === 0) { endPos = i + 1; break; } } } if (endPos > startPos) { return html.substring(startPos, endPos); } return null; } function extractImagesFromImageListJson(arrayJson, seen) { const images = []; const urlRealRegex = /"urlReal"\s*:\s*"((?:[^"\\]|\\.)*)"/g; const urlDefaultRegex = /"urlDefault"\s*:\s*"((?:[^"\\]|\\.)*)"/g; const urlRegex = /"url"\s*:\s*"((?:https?:)?\/\/[^"\\]*(?:xhscdn|sns-webpic)[^"\\]*)"/g; function extractUrls(regex, text) { let m; while ((m = regex.exec(text)) !== null) { let src = m[1].replace(/\\\//g, '/').replace(/\\"/g, '"').replace(/&/g, '&'); if (src.startsWith('//')) src = 'https:' + src; const clean = getOriginalImageUrl(src); if (clean && clean.includes('xhscdn') && !clean.includes('avatar') && !seen.has(clean)) { seen.add(clean); images.push(clean); } } } extractUrls(urlRealRegex, arrayJson); if (images.length === 0) extractUrls(urlDefaultRegex, arrayJson); if (images.length === 0) extractUrls(urlRegex, arrayJson); return images; } function fetchNoteText(url) { return new Promise((resolve) => { const pw = getPageWindow(); try { pw.fetch(url, { credentials: 'include', mode: 'cors', cache: 'no-cache', headers: { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' }, referrer: 'https://www.xiaohongshu.com/', referrerPolicy: 'strict-origin-when-cross-origin' }).then(res => { if (!res.ok) { debugLog('pageFetch HTTP状态:', res.status); resolve(null); return; } res.text().then(text => { if (text && text.length > 1000) { resolve(text); } else { debugLog('pageFetch返回内容太短:', text?.length); resolve(null); } }).catch(() => resolve(null)); }).catch(err => { debugLog('pageFetch异常:', err); resolve(null); }); } catch (e) { debugLog('pageFetch调用失败:', e); resolve(null); } setTimeout(() => resolve(null), 15000); }); } function parseNoteHtml(html, noteId) { let title = 'note_' + noteId; const images = []; const seen = new Set(); debugLog('HTML包含noteId:', html.includes(noteId), '包含INITIAL_STATE:', html.includes('INITIAL_STATE'), '包含imageList:', html.includes('imageList')); const titleMatch = html.match(/([^<]+)<\/title>/); if (titleMatch && titleMatch[1]) { title = sanitizeFilename(titleMatch[1].replace(/[-_|]\s*小红书\s*[-_|]?.*$/i, '').trim()) || title; } const state = extractStateFromHtml(html); debugLog('STATE解析结果:', state ? '成功' : '失败'); if (state) { const noteMap = state.note?.noteDetailMap; if (noteMap) { let targetNote = null; if (noteMap[noteId]?.note) { targetNote = noteMap[noteId].note; } else { for (const key in noteMap) { const n = noteMap[key]?.note; if (n?.noteId === noteId || key.includes(noteId)) { targetNote = n; break; } } } if (!targetNote) { for (const key in noteMap) { if (noteMap[key]?.note?.imageList && Array.isArray(noteMap[key].note.imageList)) { targetNote = noteMap[key].note; break; } } } if (targetNote) { debugLog('找到目标笔记, title:', targetNote.title || targetNote.displayTitle); if (targetNote.title || targetNote.displayTitle) { title = sanitizeFilename(targetNote.title || targetNote.displayTitle) || title; } if (Array.isArray(targetNote.imageList)) { debugLog('imageList长度:', targetNote.imageList.length); targetNote.imageList.forEach((img, idx) => { const src = img.urlReal || img.urlDefault || img.url || img.uri; debugLog(` 图片${idx}:`, src?.substring(0, 80)); if (src) { const fullSrc = src.startsWith('http') ? src : ('https://sns-img-bd.xhscdn.com/' + src.replace(/^\//, '')); const clean = getOriginalImageUrl(fullSrc); if (clean && clean.includes('xhscdn') && !seen.has(clean) && !clean.includes('avatar')) { seen.add(clean); images.push(clean); } } }); } } } } if (images.length === 0) { debugLog('STATE未找到,尝试正则提取imageList...'); const noteIdPos = html.indexOf(noteId); let searchArea = html; if (noteIdPos > 0) { searchArea = html.substring(Math.max(0, noteIdPos - 2000), Math.min(html.length, noteIdPos + 30000)); } const imgListMarkers = ['"imageList":', '"imageList" :', '"imagesList":', '"imagesList" :']; let markerPos = -1; let usedMarker = ''; for (const marker of imgListMarkers) { let pos = searchArea.indexOf(marker); if (pos === -1 && noteIdPos > 0) pos = html.indexOf(marker); if (pos > -1 && (markerPos === -1 || pos < markerPos)) { markerPos = pos; usedMarker = marker; } } if (markerPos > -1) { const textToSearch = noteIdPos > 0 ? searchArea : html; const arrStart = textToSearch.indexOf('[', markerPos); if (arrStart > 0) { debugLog('找到imageList数组位置:', usedMarker, '偏移:', arrStart); let depth = 0, endPos = -1, inStr = false, esc = false; for (let i = arrStart; i < textToSearch.length; i++) { const c = textToSearch[i]; if (esc) { esc = false; continue; } if (c === '\\') { esc = true; continue; } if (c === '"') { inStr = !inStr; continue; } if (inStr) continue; if (c === '[') depth++; else if (c === ']') { depth--; if (depth === 0) { endPos = i + 1; break; } } } if (endPos > arrStart) { const arrJson = textToSearch.substring(arrStart, endPos); const urlPatterns = [ /"urlReal"\s*:\s*"((?:[^"\\]|\\.)*)"/g, /"urlDefault"\s*:\s*"((?:[^"\\]|\\.)*)"/g, /"url"\s*:\s*"((?:https?:)?\/\/[^"\\]+)"/g, /"uri"\s*:\s*"([^"\\]+)"/g ]; for (const pat of urlPatterns) { let m; while ((m = pat.exec(arrJson)) !== null) { let u = m[1].replace(/\\\//g, '/'); if (!u.startsWith('http')) u = 'https://sns-img-bd.xhscdn.com/' + u.replace(/^\//, ''); const clean = getOriginalImageUrl(u); if (clean && clean.includes('xhscdn') && !clean.includes('avatar') && !seen.has(clean)) { seen.add(clean); images.push(clean); } } if (images.length > 0) break; } } } } } const result = { title: title || ('note_' + noteId), images: images.filter(u => u && u.includes('xhscdn') && !u.includes('avatar')) }; debugLog(`笔记${noteId}最终找到${result.images.length}张图片`); return result; } function waitFor(conditionFn, timeout = 10000, interval = 200) { return new Promise((resolve) => { const start = Date.now(); const check = () => { try { const result = conditionFn(); if (result) { resolve(result); return; } } catch (e) {} if (Date.now() - start > timeout) { resolve(null); return; } setTimeout(check, interval); }; check(); }); } function extractImagesFromCurrentNote() { const images = []; const seen = new Set(); const pw = getPageWindow(); let title = ''; try { const state = pw.__INITIAL_STATE__; if (state?.note?.noteDetailMap) { for (const key in state.note.noteDetailMap) { const note = state.note.noteDetailMap[key]?.note; if (note?.imageList && Array.isArray(note.imageList) && note.imageList.length > 0) { if (note.title || note.displayTitle) { title = sanitizeFilename(note.title || note.displayTitle) || title; } note.imageList.forEach(img => { const src = img.urlReal || img.urlDefault || img.url || img.uri; if (src) { const fullSrc = src.startsWith('http') ? src : ('https://sns-img-bd.xhscdn.com/' + src.replace(/^\//, '')); const clean = getOriginalImageUrl(fullSrc); if (clean && clean.includes('xhscdn') && !clean.includes('avatar') && !seen.has(clean)) { seen.add(clean); images.push(clean); } } }); if (images.length > 0) break; } } } } catch (e) { debugLog('从STATE提取失败:', e.message); } if (images.length === 0) { const detailContainer = document.querySelector('.note-detail-mask, [class*="noteDetail"], [class*="note-detail"], .note-container, .note-slider'); const root = detailContainer || document; const noteImgs = root.querySelectorAll('img'); noteImgs.forEach(img => { const src = img.currentSrc || img.src; if (src && src.includes('xhscdn') && !src.includes('avatar') && !src.includes('/icon/')) { const rect = img.getBoundingClientRect(); if (rect.width > 200 || rect.height > 200) { const clean = getOriginalImageUrl(src); if (!seen.has(clean)) { seen.add(clean); images.push(clean); } } } }); } if (!title) { const titleEl = document.querySelector('#detail-title, .note-content .title, [class*="title"]'); if (titleEl?.textContent) { title = sanitizeFilename(titleEl.textContent.trim()) || title; } } return { title: title || 'untitled', images: [...new Set(images)] }; } function pageFetchJson(url, options) { return new Promise((resolve) => { const pw = getPageWindow(); try { const opts = Object.assign({ credentials: 'include', mode: 'cors', cache: 'no-cache', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, referrer: location.href, referrerPolicy: 'strict-origin-when-cross-origin' }, options || {}); pw.fetch(url, opts).then(res => { if (!res.ok) { resolve(null); return; } res.json().then(data => resolve(data)).catch(() => resolve(null)); }).catch(() => resolve(null)); } catch (e) { resolve(null); } setTimeout(() => resolve(null), 12000); }); } async function fetchNoteImages(note) { const noteId = typeof note === 'string' ? note : note.id; const fallbackCover = typeof note === 'object' ? note.cover : null; return new Promise(async (resolve) => { let resolved = false; const done = (result) => { if (!resolved) { resolved = true; resolve(result); } }; const timeout = setTimeout(() => { debugLog('笔记超时'); safeClose(); done({ title: 'note_' + noteId, images: fallbackCover ? [getOriginalImageUrl(fallbackCover)] : [] }); }, 30000); const pw = getPageWindow(); function getCurrentNoteFromState() { try { const state = pw.__INITIAL_STATE__; const noteMap = state?.note?.noteDetailMap; if (!noteMap) return null; for (const key in noteMap) { const n = noteMap[key]?.note; if (!n) continue; if (n.noteId === noteId || key === noteId || (key.includes(noteId) && n.imageList?.length > 0)) { return n; } } } catch (e) {} return null; } function getImagesFromNoteData(noteData) { const imgs = []; const seen = new Set(); if (!noteData?.imageList || !Array.isArray(noteData.imageList)) return imgs; noteData.imageList.forEach(img => { const full = buildOriginalXhsUrl(img); if (!full) return; const clean = getOriginalImageUrl(full); if (clean && (clean.includes('xhscdn') || clean.includes('sns-webpic')) && !clean.includes('avatar') && !seen.has(clean)) { seen.add(clean); imgs.push(clean); } }); return imgs; } function safeClose() { try { document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', keyCode: 27, code: 'Escape', bubbles: true })); const closeBtn = document.querySelector('.close-circle, [class*="closeBtn"], [class*="close-button"]'); if (closeBtn) closeBtn.click(); const mask = document.querySelector('.note-detail-mask'); if (mask) mask.click(); } catch (e) {} } safeClose(); await new Promise(r => setTimeout(r, 800)); let linkEl = null; const links = document.querySelectorAll('a[href]'); for (const a of links) { if ((a.getAttribute('href') || '').indexOf(noteId) !== -1) { linkEl = a; break; } } if (!linkEl) { clearTimeout(timeout); done({ title: 'note_' + noteId, images: fallbackCover ? [getOriginalImageUrl(fallbackCover)] : [] }); return; } debugLog('点击打开笔记:', noteId); const origScroll = window.scrollY; linkEl.scrollIntoView({ block: 'center' }); await new Promise(r => setTimeout(r, 500 + Math.random() * 500)); const origTarget = linkEl.getAttribute('target'); linkEl.removeAttribute('target'); try { linkEl.click(); } catch (e) {} if (origTarget) linkEl.setAttribute('target', origTarget); let noteData = null; const waitStart = Date.now(); while (Date.now() - waitStart < 15000) { noteData = getCurrentNoteFromState(); if (noteData && noteData.imageList && noteData.imageList.length > 0) break; await new Promise(r => setTimeout(r, 400)); } let images = noteData ? getImagesFromNoteData(noteData) : []; let title = noteData ? (sanitizeFilename(noteData.title || noteData.displayTitle || '') || '') : ''; if (images.length === 0) { debugLog('STATE无数据,DOM提取...'); await new Promise(r => setTimeout(r, 1500)); const slider = document.querySelector('.note-slider, .swiper-wrapper, [class*="noteContent"]'); const root = slider || document; const domImgs = root.querySelectorAll('img'); const seen = new Set(); domImgs.forEach(img => { const src = img.currentSrc || img.src; if (src && src.includes('xhscdn') && !src.includes('avatar')) { const rect = img.getBoundingClientRect(); if (rect.width > 200 && rect.height > 200) { const clean = getOriginalImageUrl(src); if (!seen.has(clean)) { seen.add(clean); images.push(clean); } } } }); if (!title) { const t = document.querySelector('#detail-title, .title'); if (t?.textContent) title = sanitizeFilename(t.textContent.trim()) || title; } } if (images.length === 0 && fallbackCover) { images.push(getOriginalImageUrl(fallbackCover)); } debugLog(`笔记${noteId}获取到${images.length}张图片`); await new Promise(r => setTimeout(r, 300 + Math.random() * 300)); safeClose(); await new Promise(r => setTimeout(r, 600)); window.scrollTo(0, origScroll); clearTimeout(timeout); done({ title: title || 'note_' + noteId, images: [...new Set(images)] }); }); } function getNoteScopedRoot() { return document.querySelector( '.note-detail-mask, [class*="NoteDetail"], [class*="noteDetail"], ' + '.note-container, .note-scroller, [class*="noteContainer"], ' + '#noteContainer, .note-content, [class*="interactionContainer"]' ) || document; } function getCurrentNoteTitle() { const root = getNoteScopedRoot(); const trySelectors = [ '#detail-title', '[class*="noteDetail-title"]', '[class*="noteContentTitle"]', '[class*="contentTitle"]', '.note-content > #detail-title', '[class*="noteContent"] [class*="title"]', '.note-content .title', '.interaction-container .title', ]; for (const sel of trySelectors) { const el = root.querySelector(sel); if (!el) continue; const raw = el.textContent || ''; const txt = sanitizeFilename(raw); if (txt && txt.length >= 1 && txt.length < 200) { debugLog(`getCurrentNoteTitle命中优先选择器 [${sel}] = "${txt.substring(0, 40)}${txt.length > 40 ? '…' : ''}"`); return txt; } } const allTitles = root.querySelectorAll('[id*="title"], [class*="Title"], [class*="title"], h1, h2'); let best = ''; let bestScore = -1; let bestSelInfo = ''; for (const t of allTitles) { if (t.closest('.comment-item, .comment, .avatar, .sub-comment, .reply-item, [class*="commentItem"]')) continue; if (t.closest('.author-wrapper, .bottom-container, .authorInfo, .tab-bar, [class*="tabBar"]')) continue; const raw = t.textContent || ''; const txt = sanitizeFilename(raw); if (!txt || txt.length < 2 || txt.length > 200) continue; let score = 0; const idCls = ((t.id || '') + ' ' + (t.className || '')).toLowerCase(); if (/detail|notetitle|contenttitle|notedetail/.test(idCls)) score += 10; if (/head|title/.test(idCls)) score += 3; if (t.tagName === 'H1' || t.tagName === 'H2') score += 5; if (txt.length >= 4 && txt.length <= 60) score += 2; const rect = t.getBoundingClientRect(); if (rect.width > 200) score += 1; if (rect.top >= 0 && rect.top < 600) score += 2; if (score > bestScore) { bestScore = score; best = txt; bestSelInfo = `${t.tagName} id=${t.id || '-'} class=${(t.className || '').toString().substring(0, 40)}`; } } if (best) { debugLog(`getCurrentNoteTitle打分命中 [${bestSelInfo}] score=${bestScore} = "${best.substring(0, 40)}${best.length > 40 ? '…' : ''}" (scopedRoot有效=${root !== document})`); return best; } debugLog('getCurrentNoteTitle scoped搜索失败,退回到全局HTML <title> 及 meta og:title'); try { const ogTitle = document.querySelector('meta[property="og:title"]')?.content; if (ogTitle) { const t = sanitizeFilename(ogTitle.replace(/[-_|]\s*小红书\s*[-_|]?.*$/i, '').trim()); if (t) { debugLog(`getCurrentNoteTitle og:title = "${t.substring(0, 40)}"`); return t; } } } catch (e) {} try { const htmlTitle = sanitizeFilename((document.title || '').replace(/[-_|]\s*小红书\s*[-_|]?.*$/i, '').trim()); if (htmlTitle) { debugLog(`getCurrentNoteTitle HTML title = "${htmlTitle.substring(0, 40)}"`); return htmlTitle; } } catch (e) {} debugLog('getCurrentNoteTitle全部失败,返回空字符串'); return ''; } function formatNoteDate(timestamp) { if (!timestamp) return ''; let ts = Number(timestamp); if (!ts || isNaN(ts)) return ''; if (ts < 1e10) ts *= 1000; if (ts < 946684800000 || ts > 4102444800000) return ''; const d = new Date(ts); if (isNaN(d.getTime())) return ''; const y = d.getFullYear(); const m = String(d.getMonth() + 1).padStart(2, '0'); const day = String(d.getDate()).padStart(2, '0'); return `${y}${m}${day}`; } function extractTimeFromNote(noteObj) { if (!noteObj) return ''; const timeFields = ['time', 'createTime', 'lastUpdateTime', 'publishTime', 'publishedAt', 'date', 'createdAt', 'ctime', 'mtime']; for (const field of timeFields) { const val = noteObj[field]; if (val) { const formatted = formatNoteDate(val); if (formatted) return formatted; } } if (noteObj.trackInfo) { for (const field of timeFields) { const val = noteObj.trackInfo[field]; if (val) { const formatted = formatNoteDate(val); if (formatted) return formatted; } } } return ''; } function extractUserFromNote(noteObj) { if (!noteObj) return ''; const user = noteObj.user || noteObj.userInfo || noteObj.author || noteObj.authorInfo || noteObj.nickUser || noteObj.owner || {}; const name = user.nickname || user.nickName || user.name || user.userName || user.username || user.display_name || user.displayName || ''; return sanitizeFilename(name); } function extractTitleFromNote(noteObj) { if (!noteObj) return ''; const raw = noteObj.title || noteObj.displayTitle || noteObj.display_title || noteObj.showTitle || noteObj.name || ''; let t = sanitizeFilename(raw); if (!t && noteObj.desc) { const d = String(noteObj.desc).replace(/\s+/g, ' ').trim(); t = sanitizeFilename(d.substring(0, 30)); } return t; } function getCurrentNoteInfo() { const pw = getPageWindow(); const fallback = { noteId: '', title: '', publishDate: '', username: '', filePrefix: '', stateSource: false }; let noteDetailMap = null; try { noteDetailMap = pw.__INITIAL_STATE__?.note?.noteDetailMap; } catch (e) { noteDetailMap = null; } const noteMapSize = noteDetailMap ? Object.keys(noteDetailMap).length : 0; const urlNoteId = isNotePage() ? getCurrentNoteIdFromUrl() : ''; const domNoteId = getOpenNoteId(); const prefNoteId = urlNoteId || domNoteId || ''; const domTitle = getCurrentNoteTitle() || ''; debugLog(`getCurrentNoteInfo: prefNoteId=${prefNoteId ? prefNoteId.substring(0,10)+'…' : '(空)'} urlNoteId=${!!urlNoteId} domNoteId=${!!domNoteId} noteDetailMap.size=${noteMapSize} domTitle="${domTitle.substring(0,30)}${domTitle.length>30?'…':''}"`); function buildFromNote(key, note) { if (!note) return null; const nid = note.noteId || note.id || key || ''; if (prefNoteId && nid && prefNoteId !== nid && key !== prefNoteId) return null; let finalTitle = extractTitleFromNote(note) || domTitle; if (!finalTitle) finalTitle = 'note_' + ((nid || prefNoteId || '').substring(0, 8) || 'unknown'); const pub = extractTimeFromNote(note); let user = extractUserFromNote(note); if (!user) { const directUser = sanitizeFilename(note.userName || note.nickname || note.author || note.authorName || ''); if (directUser) user = directUser; } const prefix = pub ? `${pub}_${finalTitle}` : finalTitle; const info = { noteId: nid || prefNoteId, title: finalTitle, publishDate: pub, username: user, filePrefix: prefix, stateSource: true }; return info; } if (noteDetailMap && noteMapSize > 0) { try { debugLog(`getCurrentNoteInfo: 在noteDetailMap(${noteMapSize})中搜索匹配笔记`); if (prefNoteId && noteDetailMap[prefNoteId]?.note) { const info = buildFromNote(prefNoteId, noteDetailMap[prefNoteId].note); if (info) { debugLog(`getCurrentNoteInfo: 命中路径① prefNoteId,filePrefix="${info.filePrefix}" username="${info.username}"`); return info; } } const currentStateId = pw.__INITIAL_STATE__?.note?.currentNoteId || pw.__INITIAL_STATE__?.note?.activeNoteId; if (currentStateId && noteDetailMap[currentStateId]?.note) { const info = buildFromNote(currentStateId, noteDetailMap[currentStateId].note); if (info) { debugLog(`getCurrentNoteInfo: 命中路径② currentStateId=${currentStateId.substring(0,10)}…,filePrefix="${info.filePrefix}" username="${info.username}"`); return info; } } if (domTitle) { let bestMatch = null; let bestScore = 0; const keys = Object.keys(noteDetailMap); for (const key of keys) { const n = noteDetailMap[key]?.note; if (!n) continue; const t = extractTitleFromNote(n); if (!t) continue; let score = 0; if (t === domTitle) score = 100; else if (t && domTitle && (t.includes(domTitle.substring(0, Math.min(5, domTitle.length))) || domTitle.includes(t.substring(0, Math.min(5, t.length))))) score = 70; if (prefNoteId && ((n.noteId || n.id || key) === prefNoteId)) score += 30; if (score > bestScore) { bestScore = score; bestMatch = [key, n, t]; } } if (bestMatch && bestScore >= 70) { const info = buildFromNote(bestMatch[0], bestMatch[1]); if (info) { debugLog(`getCurrentNoteInfo: 命中路径③ DOM标题匹配 score=${bestScore} STATE标题="${bestMatch[2].substring(0,30)}" filePrefix="${info.filePrefix}"`); return info; } } else { debugLog(`getCurrentNoteInfo: DOM标题匹配得分=${bestScore} < 70,未命中` + (bestMatch ? ` (最佳候选标题="${bestMatch[2].substring(0,30)}")` : '')); } } const entries = Object.entries(noteDetailMap); if (entries.length === 1) { const [k, v] = entries[0]; const info = buildFromNote(k, v?.note); if (info) { debugLog(`getCurrentNoteInfo: 命中路径④ 唯一note entry,filePrefix="${info.filePrefix}"`); return info; } } debugLog('getCurrentNoteInfo: STATE路径全部落空,进入DOM兜底'); } catch (e) { debugLog('getCurrentNoteInfo STATE处理错误:', e.message, e.stack?.split('\n')[0] || ''); } } else { debugLog('getCurrentNoteInfo: noteDetailMap不存在或为空 → 直接进入DOM兜底'); } fallback.noteId = prefNoteId; fallback.title = domTitle || ('note_' + ((prefNoteId || '').substring(0, 8) || 'unknown')); fallback.publishDate = getNotePublishTime(prefNoteId); { let fbUser = ''; const authorSelectors = [ '.author-wrapper .user-name', '.author-wrapper .nickname', '.author-wrapper .username', '.authorInfo .user-name', '.authorInfo .nickname', '.bottom-container .user-name', '.bottom-container .nickname', ]; const root = getNoteScopedRoot(); for (const sel of authorSelectors) { const el = root.querySelector(sel); const txt = sanitizeFilename(el?.textContent?.trim()); if (txt && txt.length >= 1 && txt.length < 30) { fbUser = txt; break; } } if (!fbUser) { const globalHeader = document.querySelector('.profile-header .name, .info .name, .user-info .nickname, #userInfoCard .nickname'); const gt = sanitizeFilename(globalHeader?.textContent?.trim()); if (gt) fbUser = gt; } fallback.username = fbUser; } fallback.filePrefix = fallback.publishDate ? `${fallback.publishDate}_${fallback.title}` : fallback.title; if (!fallback.filePrefix) fallback.filePrefix = fallback.title; fallback.stateSource = false; debugLog(`getCurrentNoteInfo: 使用兜底(DOM)结果 title="${fallback.title}" date="${fallback.publishDate}" username="${fallback.username}" filePrefix="${fallback.filePrefix}"`); return fallback; } function getNotePublishTime(noteId) { const pw = getPageWindow(); try { const state = pw.__INITIAL_STATE__; const noteMap = state?.note?.noteDetailMap; if (noteMap) { let targetNote = null; if (noteId && noteMap[noteId]?.note) { targetNote = noteMap[noteId].note; } else { const currentId = state.note?.currentNoteId || state.note?.activeNoteId; if (currentId && noteMap[currentId]?.note) { targetNote = noteMap[currentId].note; } else if (noteId) { for (const key in noteMap) { const n = noteMap[key]?.note; if (n?.noteId === noteId) { targetNote = n; break; } } } else { const domTitle = getCurrentNoteTitle(); let best = null; for (const key in noteMap) { const n = noteMap[key]?.note; if (!n) continue; const t = sanitizeFilename(n.title) || ''; if (t && domTitle && (t === domTitle || t.includes(domTitle.substring(0, Math.min(5, domTitle.length))) || domTitle.includes(t.substring(0, Math.min(5, t.length))))) { best = n; if (t === domTitle) break; } if (!best && n.imageList?.length > 0) best = n; } targetNote = best; } } const t = extractTimeFromNote(targetNote); if (t) return t; } } catch (e) { debugLog('获取发布时间STATE失败:', e.message); } try { const root = getNoteScopedRoot(); const dateSelectors = [ '.date', '.publish-time', '.note-date', '.time', '[class*="date"]', '[class*="publishTime"]', '[class*="publish-time"]', '.bottom-container .date', '.author-wrapper .date', '.interaction-container .date' ]; for (const sel of dateSelectors) { const el = root.querySelector(sel); const text = el?.textContent?.trim(); if (!text) continue; const match = text.match(/(\d{4})[-\/\.年](\d{1,2})[-\/\.月](\d{1,2})/); if (match) return `${match[1]}${match[2].padStart(2, '0')}${match[3].padStart(2, '0')}`; const match2 = text.match(/(\d{1,2})[-\/\.月](\d{1,2})/); if (match2) { const year = new Date().getFullYear(); return `${year}${match2[1].padStart(2, '0')}${match2[2].padStart(2, '0')}`; } } } catch (e) {} return ''; } function getNoteFilePrefix(noteId) { let info = null; try { info = getCurrentNoteInfo(); } catch (e) { debugLog('getNoteFilePrefix getCurrentNoteInfo异常:', e.message); } let title = ''; let dateStr = ''; if (info) { title = info.title || ''; dateStr = info.publishDate || ''; if (info.filePrefix) { debugLog(`getNoteFilePrefix 命中info.filePrefix = "${info.filePrefix}"`); return info.filePrefix; } } if (!title) title = getCurrentNoteTitle(); if (!title) title = 'note_' + ((noteId || info?.noteId || '').substring(0, 8) || 'unknown'); if (!dateStr) dateStr = getNotePublishTime(noteId); const out = dateStr ? `${dateStr}_${title}` : title; debugLog(`getNoteFilePrefix fallback合成 = "${out}"`); return out; } function getCurrentUsername() { try { const info = getCurrentNoteInfo(); if (info && info.username) return info.username; } catch (e) { debugLog('getCurrentUsername info读取异常:', e.message); } const root = getNoteScopedRoot(); const scopedSelectors = [ '.author-wrapper .user-name', '.author-wrapper .nickname', '.author-wrapper .username', '.authorInfo .user-name', '.authorInfo .nickname', '.bottom-container .user-name', '.bottom-container .nickname', '[class*="authorWrapper"] [class*="userName"]', '[class*="authorWrapper"] [class*="nickName"]', '.note-container .nickname', ]; for (const sel of scopedSelectors) { const el = root.querySelector(sel); const txt = sanitizeFilename(el?.textContent?.trim()); if (txt && txt.length >= 1 && txt.length < 30) return txt; } const headerEl = document.querySelector('.user-name, .username, .nickname, .profile-header .name, .info .name'); const ht = sanitizeFilename(headerEl?.textContent?.trim()); if (ht) return ht; debugLog('getCurrentUsername 全部失败,兜底使用 xhs_images'); return 'xhs_images'; } function getImageExt(url) { const match = url.match(/\.(jpg|jpeg|png|webp|gif|avif|heic)/i); if (match) return match[1].toLowerCase(); if (url.includes('format=png')) return 'png'; if (url.includes('format=webp')) return 'webp'; return 'jpg'; } function getVideoExt(url) { const match = url.match(/\.(mp4|webm|mov|m4v)/i); if (match) return match[1].toLowerCase(); return 'mp4'; } // 根据 settings 给图片URL追加七牛云 imageMogr2 格式/质量参数 // 原图模式直接返回,不做处理 function applyImageFormat(url) { if (!url) return url; const fmt = settings.imgFormat; if (!fmt || fmt === 'original') return url; const quality = Math.max(1, Math.min(100, settings.imgQuality || 90)); const [base, qs, hash] = splitQueryHash(url); const proc = `imageMogr2/format/${fmt}/quality/${quality}`; const newQs = qs ? `${qs}&${proc}` : proc; return base + '?' + newQs + (hash || ''); } function sanitizePath(path) { return path.split('/').map(part => { const p = sanitizeFilename(part); return p ? p : 'untitled'; }).join('/'); } function saveBlob(blob, filename, allowVideo) { try { if (!blob || blob.size < 4000) return false; const isImg = !blob.type || blob.type === '' || /image\//i.test(blob.type); const isVid = /video\//i.test(blob.type); const typeOk = isImg || (allowVideo && isVid); if (!typeOk) { debugLog('saveBlob跳过: 类型不匹配:', blob.type, 'size=', blob.size); return false; } const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; a.style.display = 'none'; document.body.appendChild(a); a.click(); setTimeout(() => { document.body.removeChild(a); URL.revokeObjectURL(url); }, 200); return true; } catch (e) { debugLog('saveBlob失败:', e); return false; } } async function downloadImage(url, filename, isVideo) { if (!url) return false; const safeFilename = sanitizePath(filename); const flatFilename = safeFilename.replace(/\//g, '_'); const acceptHeader = isVideo ? 'video/mp4,video/webm,video/ogg,video/*,*/*;q=0.8' : 'image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8'; const typeRe = isVideo ? /^video\// : /^image\//; const kindLabel = isVideo ? '视频' : '图片'; debugLog(`下载${kindLabel}:`, url.substring(0, 80) + '...'); let finalBlob = null; try { debugLog(`策略1: 页面上下文fetch (带页面Cookie/Referer) [${kindLabel}]`); const blob = await pageFetch(url, 20000); if (blob && blob.size > 8000) { const typeOk = !blob.type || blob.type === '' || typeRe.test(blob.type); if (typeOk) { debugLog('pageFetch成功, size=', blob.size, 'type=', blob.type || '(无)'); finalBlob = blob; } else { debugLog('pageFetch类型不匹配:', blob.type); } } else { debugLog('pageFetch无结果, size=', blob?.size); } } catch (e) { debugLog('pageFetch异常:', e.message); } if (!finalBlob) { debugLog(`策略2: GM_xmlhttpRequest (blob) [${kindLabel}]`); finalBlob = await new Promise((resolve) => { let done = false; const finish = (b) => { if (!done) { done = true; resolve(b); } }; try { GM_xmlhttpRequest({ method: 'GET', url: url, responseType: 'blob', timeout: 20000, headers: { 'Referer': 'https://www.xiaohongshu.com/', 'Origin': 'https://www.xiaohongshu.com', 'Accept': acceptHeader }, anonymous: false, onload: (res) => { if (res.status >= 200 && res.status < 300 && res.response && res.response.size > 8000) { const tOk = !res.response.type || res.response.type === '' || typeRe.test(res.response.type); if (tOk) { debugLog('GM_xhr成功, size=', res.response.size, 'type=', res.response.type); finish(res.response); return; } debugLog('GM_xhr类型不匹配:', res.response.type, 'size=', res.response.size); } else { debugLog('GM_xhr失败, status=', res.status, 'size=', res.response?.size); } finish(null); }, onerror: () => { debugLog('GM_xhr onerror'); finish(null); }, ontimeout: () => { debugLog('GM_xhr ontimeout'); finish(null); } }); } catch (e) { debugLog('GM_xhr调用异常:', e.message); finish(null); } setTimeout(() => finish(null), 22000); }); } if (finalBlob && finalBlob.size > 8000) { debugLog('触发前端blob保存, size=', finalBlob.size, 'type=', finalBlob.type || '(无)'); if (saveBlob(finalBlob, flatFilename, !!isVideo)) return true; debugLog('blob保存失败 → 走GM_download兜底'); } debugLog(`策略3: GM_download 兜底 [${kindLabel}]`); return new Promise((resolve) => { let done = false; const finish = (ok) => { if (!done) { done = true; resolve(ok); } }; try { GM_download({ url: url, name: safeFilename, saveAs: false, onload: () => { debugLog('GM_download成功'); finish(true); }, onerror: (err) => { debugLog('GM_download失败:', err?.error || err); finish(false); }, ontimeout: () => { debugLog('GM_download超时'); finish(false); }, headers: { 'Referer': 'https://www.xiaohongshu.com/', 'Accept': acceptHeader } }); } catch (e) { debugLog('GM_download异常:', e.message); finish(false); } setTimeout(() => finish(false), 25000); }); } async function downloadSelectedImages() { if (state.isDownloading || state.selectedImages.size === 0 && !state.noteVideoUrl) return; state.isDownloading = true; const btn = document.querySelector('.xhs-download-all-btn:not(.xhs-comment-btn)'); const progress = document.querySelector('.xhs-progress'); if (btn) { btn.disabled = true; btn.textContent = '下载中...'; } await new Promise(r => setTimeout(r, 50)); const title = getNoteFilePrefix(); const indices = Array.from(state.selectedImages).sort((a, b) => a - b); let success = 0; let liveSuccess = 0; const liveTotal = indices.filter(i => state.liveVideoUrls[i]).length; const liveMode = settings.liveMode; const fmt = settings.imgFormat; for (let i = 0; i < indices.length; i++) { const idx = indices[i]; const url = state.imageUrls[idx]; if (!url) continue; if (progress) progress.textContent = `正在下载 ${i + 1}/${indices.length}`; const ext = (fmt && fmt !== 'original') ? fmt : getImageExt(url); const imgUrl = applyImageFormat(url); if (liveMode !== 'video') { if (await downloadImage(imgUrl, `${title}_${idx + 1}.${ext}`)) success++; } const liveUrl = state.liveVideoUrls[idx]; if (liveUrl && liveMode !== 'image') { const vExt = getVideoExt(liveUrl); const vName = `${title}_${idx + 1}_实况.${vExt}`; if (await downloadImage(liveUrl, vName, true)) liveSuccess++; } if (i < indices.length - 1) await new Promise(r => setTimeout(r, 300)); } // 纯视频笔记 let videoOk = false; if (state.noteVideoUrl) { if (progress) progress.textContent = '正在下载笔记视频...'; const vExt = getVideoExt(state.noteVideoUrl); videoOk = await downloadImage(state.noteVideoUrl, `${title}.${vExt}`, true); } const liveTxt = liveTotal > 0 ? ` (实况视频 ${liveSuccess}/${liveTotal})` : ''; const videoTxt = state.noteVideoUrl ? (videoOk ? ' [视频✓]' : ' [视频✗]') : ''; if (progress) progress.textContent = `完成!成功 ${success}/${indices.length}${liveTxt}${videoTxt}`; if (btn) { btn.disabled = false; btn.textContent = `下载选中笔记图 (${state.selectedImages.size})`; } state.isDownloading = false; GM_notification({ title: '下载完成', text: `成功 ${success} 张图片${liveTxt}${videoTxt}`, timeout: 3000 }); } async function downloadSelectedCommentImages() { if (state.isDownloading || state.selectedCommentImages.size === 0) return; state.isDownloading = true; const btn = document.querySelector('.xhs-download-all-btn.xhs-comment-btn'); const progress = document.querySelector('.xhs-progress'); if (btn) { btn.disabled = true; btn.textContent = '下载中...'; } await new Promise(r => setTimeout(r, 50)); const prefix = getNoteFilePrefix(); const indices = Array.from(state.selectedCommentImages).sort((a, b) => a - b); let success = 0; for (let k = 0; k < indices.length; k++) { const idx = indices[k]; const item = state.commentImages[idx]; if (!item) continue; if (progress) progress.textContent = `正在下载 ${k + 1}/${indices.length}`; const fmt = settings.imgFormat; const ext = (fmt && fmt !== 'original') ? fmt : getImageExt(item.url); const imgUrl = applyImageFormat(item.url); const timePrefix = item.commentTime ? item.commentTime + '_' : ''; const filename = `${prefix}_评论图/${timePrefix}${item.commenter}_${k + 1}.${ext}`; if (await downloadImage(imgUrl, filename)) success++; if (k < indices.length - 1) await new Promise(r => setTimeout(r, 350)); } if (progress) progress.textContent = `完成!成功 ${success}/${indices.length}`; if (btn) { btn.disabled = false; btn.textContent = `下载选中评论图 (${state.selectedCommentImages.size})`; } state.isDownloading = false; GM_notification({ title: '评论图片下载完成', text: `成功 ${success} 张图片`, timeout: 3000 }); } async function refreshCommentImages(scrollCount = 3) { const btn = document.getElementById('xhs-refresh-comments'); if (btn) { btn.disabled = true; btn.textContent = '扫描中...'; } for (let s = 0; s < scrollCount; s++) { const commentContainer = document.querySelector( '.comment-container, .comment-section, [class*="commentContainer"], [class*="commentSection"], .note-scroller' ); if (commentContainer) { commentContainer.scrollTo(0, commentContainer.scrollHeight); } else { window.scrollTo(0, document.body.scrollHeight); } await new Promise(r => setTimeout(r, 1000)); } state.commentImages = extractCommentImages(); state.selectedCommentImages = new Set(state.commentImages.map((_, i) => i)); state.noteSubTab = 'comment'; updatePanelCounters(); renderNoteSubTab(); rebuildCommentImagesView(); showBatchToast(`📸 扫描完成,共找到 ${state.commentImages.length} 张评论图`, 2000); } function updatePanelCounters() { const panel = document.querySelector('.xhs-download-panel'); if (!panel) return; const liveCount = state.liveVideoUrls.filter(Boolean).length; const title = panel.querySelector('.xhs-panel-title'); if (title) { let t = `笔记图片 ${state.imageUrls.length} 张`; if (liveCount > 0) t += ` (实况 ${liveCount})`; t += ` · 评论图片 ${state.commentImages.length} 张`; title.textContent = t; } const subtabBtns = panel.querySelectorAll('.xhs-subtab-btn'); subtabBtns.forEach(b => { if (b.dataset.tab === 'note') { let t = `🖼 笔记图 (${state.imageUrls.length})`; if (liveCount > 0) t += ` 实况${liveCount}`; b.textContent = t; } if (b.dataset.tab === 'comment') b.textContent = `💬 评论图 (${state.commentImages.length})`; }); } function rebuildCommentImagesView() { const panel = document.querySelector('.xhs-download-panel'); if (!panel) return; const view = panel.querySelector('.xhs-comment-images-view'); if (!view) return; const listHtml = state.commentImages.length > 0 ? state.commentImages.map((item, i) => ` <div class="xhs-image-item ${state.selectedCommentImages.has(i) ? 'selected' : ''}" data-comment-idx="${i}"> <img src="${getThumbUrl(item.url)}" loading="lazy"> <span class="check" style="display:${state.selectedCommentImages.has(i) ? 'flex' : 'none'};">✓</span> <div class="xhs-comment-meta"> ${item.commentTime ? `<span class="cmt-time">${item.commentTime}</span>` : ''} <span class="cmt-user">${escapeHtml(item.commenter.substring(0, 12))}</span> </div> <button class="xhs-single-download xhs-cmt-single" data-url="${escapeHtml(item.url)}" data-idx="${i}">下载</button> </div> `).join('') : `<div style="grid-column:1/-1;padding:30px;text-align:center;color:#999;font-size:13px;"> 暂无评论图片<br> <span style="font-size:12px;color:#bbb;">请先手动滚动加载评论,然后点击上方"重新扫描"按钮</span> </div>`; const allSelected = state.commentImages.length > 0 && state.selectedCommentImages.size === state.commentImages.length; view.innerHTML = ` <button id="xhs-refresh-comments" class="xhs-refresh-comments-btn">🔄 重新扫描评论图 (${state.commentImages.length}张)</button> <label class="xhs-select-all"> <input type="checkbox" ${allSelected ? 'checked' : ''} id="xhs-select-all-cmt-cb"><span>全选评论图${state.commentImages.length > 0 ? ' (' + state.commentImages.length + ')' : ''}</span> </label> <div class="xhs-image-list"> ${listHtml} </div> <button class="xhs-download-all-btn xhs-comment-btn" ${state.selectedCommentImages.size === 0 ? 'disabled' : ''}> 下载选中评论图 (${state.selectedCommentImages.size}) </button> `; const refreshBtn = view.querySelector('#xhs-refresh-comments'); if (refreshBtn) refreshBtn.onclick = () => refreshCommentImages(5); const selectCmtCb = view.querySelector('#xhs-select-all-cmt-cb'); const updateCmtBtn = () => { const btn = view.querySelector('.xhs-download-all-btn.xhs-comment-btn'); if (!btn) return; btn.textContent = `下载选中评论图 (${state.selectedCommentImages.size})`; btn.disabled = state.selectedCommentImages.size === 0 || state.isDownloading; }; if (selectCmtCb) { selectCmtCb.onchange = (e) => { view.querySelectorAll('.xhs-image-item[data-comment-idx]').forEach(item => { const idx = parseInt(item.dataset.commentIdx); if (e.target.checked) { item.classList.add('selected'); state.selectedCommentImages.add(idx); const chk = item.querySelector('.check'); if (chk) chk.style.display = 'flex'; } else { item.classList.remove('selected'); state.selectedCommentImages.delete(idx); const chk = item.querySelector('.check'); if (chk) chk.style.display = 'none'; } }); updateCmtBtn(); }; } view.querySelectorAll('.xhs-image-item[data-comment-idx]').forEach(item => { item.onclick = (e) => { if (e.target.classList.contains('xhs-single-download')) return; const idx = parseInt(item.dataset.commentIdx); if (!state.commentImages[idx]) return; const chk = item.querySelector('.check'); if (state.selectedCommentImages.has(idx)) { state.selectedCommentImages.delete(idx); item.classList.remove('selected'); if (chk) chk.style.display = 'none'; } else { state.selectedCommentImages.add(idx); item.classList.add('selected'); if (chk) chk.style.display = 'flex'; } if (selectCmtCb) selectCmtCb.checked = state.commentImages.length > 0 && state.selectedCommentImages.size === state.commentImages.length; updateCmtBtn(); }; }); view.querySelectorAll('.xhs-cmt-single').forEach(btn => { btn.onclick = async (e) => { e.stopPropagation(); const url = btn.dataset.url; const idx = parseInt(btn.dataset.idx); const item = state.commentImages[idx]; if (!item) return; const prefix = getNoteFilePrefix(); const fmt = settings.imgFormat; const ext = (fmt && fmt !== 'original') ? fmt : getImageExt(item.url); const imgUrl = applyImageFormat(item.url); const timePrefix = item.commentTime ? item.commentTime + '_' : ''; await downloadImage(imgUrl, `${prefix}_评论图/${timePrefix}${item.commenter}_${idx + 1}.${ext}`); }; }); const cmtDownloadBtn = view.querySelector('.xhs-download-all-btn.xhs-comment-btn'); if (cmtDownloadBtn) cmtDownloadBtn.onclick = downloadSelectedCommentImages; } function renderNoteSubTab() { const panel = document.querySelector('.xhs-download-panel'); if (!panel) return; const subtabBtns = panel.querySelectorAll('.xhs-subtab-btn'); subtabBtns.forEach(b => { if (b.dataset.tab === state.noteSubTab) b.classList.add('active'); else b.classList.remove('active'); }); const noteView = panel.querySelector('.xhs-note-images-view'); const commentView = panel.querySelector('.xhs-comment-images-view'); if (state.noteSubTab === 'note') { if (noteView) noteView.style.display = ''; if (commentView) commentView.style.display = 'none'; } else { if (noteView) noteView.style.display = 'none'; if (commentView) commentView.style.display = ''; } } const AUTO_KEY = 'xhs_auto_download_enabled'; const DOWNLOADED_KEY = 'xhs_downloaded_notes'; let autoObserver = null; let autoDownloading = false; let lastAutoNoteId = null; function isAutoDownloadEnabled() { return localStorage.getItem(AUTO_KEY) === '1'; } function setAutoDownload(enabled) { if (enabled) { localStorage.setItem(AUTO_KEY, '1'); startAutoObserver(); showAutoStatus(); showBatchToast('✅ 自动下载已开启\n手动打开笔记即可自动下载', 3000); } else { localStorage.removeItem(AUTO_KEY); stopAutoObserver(); hideAutoStatus(); showBatchToast('自动下载已关闭', 2000); } updateProfilePanel(); } function getDownloadedNotes() { try { return new Set(JSON.parse(localStorage.getItem(DOWNLOADED_KEY) || '[]')); } catch (e) { return new Set(); } } function markNoteDownloaded(noteId) { const set = getDownloadedNotes(); set.add(noteId); localStorage.setItem(DOWNLOADED_KEY, JSON.stringify([...set].slice(-500))); } function showAutoStatus() { let el = document.getElementById('xhs-auto-status'); if (el) return; el = document.createElement('div'); el.id = 'xhs-auto-status'; el.style.cssText = 'position:fixed;top:80px;left:50%;transform:translateX(-50%);background:linear-gradient(135deg,#ff2442,#ff6b6b);color:white;padding:8px 20px;border-radius:20px;z-index:100001;font-size:13px;font-family:-apple-system,sans-serif;box-shadow:0 4px 15px rgba(255,36,66,0.4);display:flex;align-items:center;gap:8px;'; el.innerHTML = `<span style="display:inline-block;width:8px;height:8px;background:#4ade80;border-radius:50%;animation:pulse 1s infinite;"></span>自动下载中 <button id="xhs-auto-stop" style="background:rgba(255,255,255,0.2);border:none;color:white;padding:2px 8px;border-radius:4px;cursor:pointer;font-size:11px;margin-left:8px;">关闭</button>`; document.body.appendChild(el); document.getElementById('xhs-auto-stop').onclick = () => setAutoDownload(false); if (!document.getElementById('xhs-auto-style')) { const style = document.createElement('style'); style.id = 'xhs-auto-style'; style.textContent = '@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.5}}'; document.head.appendChild(style); } } function hideAutoStatus() { const el = document.getElementById('xhs-auto-status'); if (el) el.remove(); } function isNotePanelVisible() { const masks = document.querySelectorAll( '.note-detail-mask, [class*="noteDetailMask"], [class*="NoteDetail"], ' + '[class*="note-detail"], [class*="note_detail"], .note-scroller, ' + '.interaction-container, [class*="interactionContainer"]' ); for (const mask of masks) { const style = window.getComputedStyle(mask); if (style.display !== 'none' && style.visibility !== 'hidden' && style.opacity !== '0') { const rect = mask.getBoundingClientRect(); if (rect.width > 200 && rect.height > 200) return true; } } const sliders = document.querySelectorAll( '.note-slider, .swiper-container, [class*="noteSlider"], [class*="note-slider"], ' + '.swiper-wrapper, .carousel, [class*="zoom-in"], [class*="noteContent"]' ); for (const s of sliders) { const style = window.getComputedStyle(s); if (style.display !== 'none' && style.visibility !== 'hidden') { const rect = s.getBoundingClientRect(); if (rect.width > 200 && rect.height > 200 && rect.top < window.innerHeight && rect.bottom > 0) return true; } } const closeBtn = document.querySelector('.close-circle, [class*="closeBtn"], [class*="close-button"]'); if (closeBtn) { const style = window.getComputedStyle(closeBtn); if (style.display !== 'none' && style.visibility !== 'hidden') { const rect = closeBtn.getBoundingClientRect(); if (rect.width > 10 && rect.height > 10 && rect.top >= 0 && rect.top < window.innerHeight) return true; } } return false; } function getOpenNoteId() { if (isNotePage()) return getCurrentNoteIdFromUrl(); if (!isNotePanelVisible()) return null; const pw = getPageWindow(); try { const state = pw.__INITIAL_STATE__; const noteMap = state?.note?.noteDetailMap; if (noteMap) { const currentNoteId = state.note?.currentNoteId || state.note?.activeNoteId; if (currentNoteId && noteMap[currentNoteId]?.note) { return currentNoteId; } const firstKey = Object.keys(noteMap)[0]; if (firstKey && noteMap[firstKey]?.note?.noteId && Object.keys(noteMap).length === 1) { return noteMap[firstKey].note.noteId; } const visibleNotes = []; for (const key in noteMap) { const n = noteMap[key]?.note; if (n?.noteId && n.imageList?.length > 0) { visibleNotes.push({ id: n.noteId, key: key, note: n }); } } if (visibleNotes.length === 1) { return visibleNotes[0].id; } if (visibleNotes.length > 1) { for (const vn of visibleNotes) { const noteData = vn.note; if (noteData.interactInfo || noteData.likedCount !== undefined || noteData.title || noteData.desc) { const domTitle = document.querySelector('#detail-title'); if (domTitle?.textContent?.trim()) { if (noteData.title && domTitle.textContent.trim().includes(noteData.title.substring(0, 5))) { return vn.id; } } } } return visibleNotes[visibleNotes.length - 1].id; } } } catch (e) { debugLog('getOpenNoteId STATE错误:', e.message); } try { const link = document.querySelector('link[rel="canonical"]'); if (link?.href) { const m = link.href.match(/\/explore\/([a-f0-9]{24})/); if (m) return m[1]; } } catch (e) {} return null; } let panelVisible = false; let lastSeenNoteId = null; function startAutoObserver() { if (autoObserver) autoObserver.disconnect(); let checkTimer = null; const check = () => { if (checkTimer) clearTimeout(checkTimer); checkTimer = setTimeout(() => { const currentlyVisible = isNotePanelVisible() || isNotePage(); const currentNoteId = getOpenNoteId(); if (panelVisible && !currentlyVisible) { debugLog('笔记面板已关闭,重置状态'); lastAutoNoteId = null; lastSeenNoteId = null; } if (currentNoteId && currentNoteId !== lastSeenNoteId) { debugLog('检测到笔记ID变化:', lastSeenNoteId, '->', currentNoteId); if (lastSeenNoteId !== null && !autoDownloading) { lastAutoNoteId = null; } lastSeenNoteId = currentNoteId; } if (!currentlyVisible) { lastSeenNoteId = null; } panelVisible = currentlyVisible; if (!autoDownloading && isAutoDownloadEnabled()) { autoCheckAndDownload(); } }, 500); }; autoObserver = new MutationObserver(check); autoObserver.observe(document.body, { childList: true, subtree: true }); panelVisible = isNotePanelVisible() || isNotePage(); lastSeenNoteId = getOpenNoteId(); setTimeout(() => { if (isAutoDownloadEnabled()) autoCheckAndDownload(); }, 1500); } function stopAutoObserver() { if (autoObserver) { autoObserver.disconnect(); autoObserver = null; } autoDownloading = false; lastAutoNoteId = null; lastSeenNoteId = null; } async function autoCheckAndDownload() { if (autoDownloading || !isAutoDownloadEnabled()) return; const noteId = getOpenNoteId(); if (!noteId) return; const downloaded = getDownloadedNotes(); if (downloaded.has(noteId)) { if (lastAutoNoteId !== noteId) { debugLog('笔记已下载过,跳过:', noteId); lastAutoNoteId = noteId; } return; } if (lastAutoNoteId === noteId) return; autoDownloading = true; debugLog('自动检测到笔记:', noteId); showBatchToast('📸 检测到新笔记,等待加载...', 0); let imageUrls = []; let liveVideoUrls = []; let noteVideoUrl = null; let isVideoNote = false; let folder = 'xhs_images'; let notePrefix = ''; for (let attempt = 0; attempt < 10; attempt++) { await new Promise(r => setTimeout(r, 800)); const noteImgs = extractNoteImages(noteId); imageUrls = noteImgs.urls; liveVideoUrls = noteImgs.liveVideos; noteVideoUrl = noteImgs.noteVideoUrl || null; isVideoNote = !!noteImgs.isVideoNote; const info = getCurrentNoteInfo(); if (info && info.username) folder = sanitizeFilename(info.username) || 'xhs_images'; else folder = sanitizeFilename(getCurrentUsername()) || 'xhs_images'; notePrefix = (info && info.filePrefix) ? info.filePrefix : getNoteFilePrefix(noteId); if (imageUrls.length > 0) { const liveCount = liveVideoUrls.filter(Boolean).length; debugLog(`第${attempt + 1}次尝试,找到 ${imageUrls.length} 张图片 (实况 ${liveCount} 张), folder=${folder}, prefix=${notePrefix}`); break; } if (attempt < 4) { debugLog(`第${attempt + 1}次尝试未找到图片,继续等待...`); showBatchToast(`📸 加载中... (${attempt + 1}/5)`, 0); } if (!isNotePanelVisible() && !isNotePage()) { debugLog('面板已关闭,取消等待'); showBatchToast('⚠️ 笔记面板已关闭', 1500); autoDownloading = false; lastAutoNoteId = null; return; } } lastAutoNoteId = noteId; debugLog(`最终找到 ${imageUrls.length} 张图片, folder=${folder}, prefix=${notePrefix}`); if (imageUrls.length === 0 && !noteVideoUrl) { showBatchToast('⚠️ 未找到图片,请刷新页面重试', 2000); autoDownloading = false; setTimeout(() => { if (!isNotePanelVisible() && !isNotePage()) lastAutoNoteId = null; }, 5000); return; } let success = 0; let liveSuccess = 0; const liveTotal = liveVideoUrls.filter(Boolean).length; const liveMode = settings.liveMode; const fmt = settings.imgFormat; for (let j = 0; j < imageUrls.length; j++) { showBatchToast(`⬇ 自动下载 ${j + 1}/${imageUrls.length}`, 0); const ext = (fmt && fmt !== 'original') ? fmt : getImageExt(imageUrls[j]); const imgUrl = applyImageFormat(imageUrls[j]); if (liveMode !== 'video') { if (await downloadImage(imgUrl, `${folder}/${notePrefix}_${j + 1}.${ext}`)) success++; } const liveUrl = liveVideoUrls[j]; if (liveUrl && liveMode !== 'image') { const vExt = getVideoExt(liveUrl); if (await downloadImage(liveUrl, `${folder}/${notePrefix}_${j + 1}_实况.${vExt}`, true)) { liveSuccess++; } } if (j < imageUrls.length - 1) await new Promise(r => setTimeout(r, 400)); } // 纯视频笔记下载视频文件 let videoOk = false; if (noteVideoUrl) { const vExt = getVideoExt(noteVideoUrl); showBatchToast(`⬇ 下载笔记视频...`, 0); videoOk = await downloadImage(noteVideoUrl, `${folder}/${notePrefix}.${vExt}`, true); } markNoteDownloaded(noteId); const liveTxt = liveTotal > 0 ? ` (实况视频 ${liveSuccess}/${liveTotal})` : ''; const videoTxt = noteVideoUrl ? (videoOk ? ' [视频✓]' : ' [视频✗]') : ''; showBatchToast(`✅ 下载完成 ${success}/${imageUrls.length} 张${liveTxt}${videoTxt}\n关闭面板后点击下一个`, 4000); GM_notification({ title: '笔记下载完成', text: `${notePrefix}: ${success} 张图片${liveTxt}${videoTxt}`, timeout: 3000 }); autoDownloading = false; } function showBatchToast(msg, duration = 2000) { const old = document.getElementById('xhs-batch-toast'); if (old) old.remove(); const t = document.createElement('div'); t.id = 'xhs-batch-toast'; t.style.cssText = 'position:fixed;top:130px;left:50%;transform:translateX(-50%);background:rgba(0,0,0,0.85);color:white;padding:12px 24px;border-radius:10px;z-index:100002;font-size:13px;font-family:-apple-system,sans-serif;box-shadow:0 4px 20px rgba(0,0,0,0.3);white-space:pre-line;text-align:center;'; t.textContent = msg; document.body.appendChild(t); if (duration > 0) setTimeout(() => { if (document.body.contains(t)) t.remove(); }, duration); return t; } function updateProfilePanel() { const panel = document.querySelector('.xhs-download-panel'); if (!panel || state.currentMode !== 'profile') return; const btn = panel.querySelector('.xhs-auto-btn'); if (btn) { if (isAutoDownloadEnabled()) { btn.textContent = '🔴 关闭自动下载'; btn.style.background = '#dc2626'; } else { btn.textContent = '🟢 开启自动下载'; btn.style.background = 'linear-gradient(135deg,#16a34a,#22c55e)'; } } } function isNotePage() { return /\/explore\/[a-f0-9]{24}/.test(window.location.pathname); } function getCurrentNoteIdFromUrl() { const m = window.location.pathname.match(/\/explore\/([a-f0-9]{24})/); return m ? m[1] : null; } function renderNotesPanel() { const listEl = document.querySelector('.xhs-note-list'); if (!listEl) return; listEl.innerHTML = state.notesList.map((note, i) => ` <div class="xhs-note-item ${state.selectedNotes.has(i) ? 'selected' : ''}" data-idx="${i}"> <div class="xhs-note-cover"> <img src="${getThumbUrl(note.cover).replace('/w/200/h/200', '/w/160/h/160')}" loading="lazy"> ${note.imageCount > 1 ? `<span class="img-count">${note.imageCount}图</span>` : ''} </div> <div class="xhs-note-info"> <div class="xhs-note-title">${escapeHtml(note.title)}</div> <div class="xhs-note-meta">${note.id}</div> </div> <div class="xhs-note-check">${state.selectedNotes.has(i) ? '✓' : ''}</div> </div> `).join(''); listEl.querySelectorAll('.xhs-note-item').forEach(item => { item.onclick = () => { const idx = parseInt(item.dataset.idx); if (state.selectedNotes.has(idx)) { state.selectedNotes.delete(idx); item.classList.remove('selected'); item.querySelector('.xhs-note-check').textContent = ''; } else { state.selectedNotes.add(idx); item.classList.add('selected'); item.querySelector('.xhs-note-check').textContent = '✓'; } const cb = document.querySelector('#xhs-select-all-notes'); if (cb) cb.checked = state.selectedNotes.size === state.notesList.length; const btn = document.querySelector('.xhs-download-all-btn'); if (btn) { btn.textContent = state.selectedNotes.size > 0 ? `开始引导下载 (${state.selectedNotes.size})` : '请选择笔记'; btn.disabled = state.selectedNotes.size === 0 || state.isDownloading; } }; }); const loadBtn = document.querySelector('.xhs-load-more'); if (loadBtn) { loadBtn.disabled = !state.hasMoreNotes || state.loadingMore; loadBtn.textContent = state.hasMoreNotes ? '加载更多笔记' : '已加载全部'; } } function createNotePanel() { const existing = document.querySelector('.xhs-download-panel'); if (existing) existing.remove(); const noteImgs = extractNoteImages(); state.imageUrls = noteImgs.urls; state.liveVideoUrls = noteImgs.liveVideos; state.noteVideoUrl = noteImgs.noteVideoUrl || null; state.isVideoNote = !!noteImgs.isVideoNote; state.commentImages = extractCommentImages(); if (state.imageUrls.length === 0 && !state.noteVideoUrl && state.commentImages.length === 0) { GM_notification({ title: '提示', text: '未找到图片或视频,请在笔记详情页使用', timeout: 3000 }); return; } state.selectedImages = new Set(state.imageUrls.map((_, i) => i)); state.selectedCommentImages = new Set(state.commentImages.map((_, i) => i)); state.currentMode = 'note'; state.noteSubTab = state.noteSubTab && state.commentImages.length > 0 ? state.noteSubTab : 'note'; const panel = document.createElement('div'); panel.className = 'xhs-download-panel show'; const commentListHtml = state.commentImages.length > 0 ? state.commentImages.map((item, i) => ` <div class="xhs-image-item ${state.selectedCommentImages.has(i) ? 'selected' : ''}" data-comment-idx="${i}"> <img src="${getThumbUrl(item.url)}" loading="lazy"> <span class="check">✓</span> <div class="xhs-comment-meta"> ${item.commentTime ? `<span class="cmt-time">${item.commentTime}</span>` : ''} <span class="cmt-user">${escapeHtml(item.commenter.substring(0, 12))}</span> </div> <button class="xhs-single-download xhs-cmt-single" data-url="${escapeHtml(item.url)}" data-idx="${i}">下载</button> </div> `).join('') : `<div style="grid-column:1/-1;padding:30px;text-align:center;color:#999;font-size:13px;"> 暂无评论图片<br> <span style="font-size:12px;color:#bbb;">请先手动滚动加载评论,然后点击下方"重新扫描"按钮</span> </div>`; const liveCount = state.liveVideoUrls.filter(Boolean).length; const liveBadge = liveCount > 0 ? ` (实况 ${liveCount})` : ''; panel.innerHTML = ` <div class="xhs-panel-header"> <span class="xhs-panel-title">笔记图片 ${state.imageUrls.length} 张${liveBadge} · 评论图片 ${state.commentImages.length} 张</span> <div style="display:flex;gap:4px;align-items:center;"> <button class="xhs-debug-btn" title="排查原图字段,输出原始STATE结构到控制台">🔍</button> <button class="xhs-panel-close">×</button> </div> </div> ${state.isUserProfile ? ` <div class="xhs-mode-switch"> <button class="xhs-mode-btn active" data-mode="note">当前笔记</button> <button class="xhs-mode-btn" data-mode="profile">自动下载</button> </div>` : ''} <div class="xhs-subtab-switch"> <button class="xhs-subtab-btn ${state.noteSubTab === 'note' ? 'active' : ''}" data-tab="note">🖼 笔记图 (${state.imageUrls.length})${liveCount > 0 ? ' 实况' + liveCount : ''}</button> <button class="xhs-subtab-btn ${state.noteSubTab === 'comment' ? 'active' : ''}" data-tab="comment">💬 评论图 (${state.commentImages.length})</button> </div> <div class="xhs-note-images-view" style="${state.noteSubTab === 'note' ? '' : 'display:none;'}"> <div class="xhs-settings-row"> <label>格式: <select id="xhs-img-format"> <option value="original" ${settings.imgFormat==='original'?'selected':''}>原图</option> <option value="jpg" ${settings.imgFormat==='jpg'?'selected':''}>JPG</option> <option value="png" ${settings.imgFormat==='png'?'selected':''}>PNG</option> <option value="webp" ${settings.imgFormat==='webp'?'selected':''}>WEBP</option> </select> </label> <label id="xhs-quality-wrap" style="${settings.imgFormat==='original'?'display:none;':''}">质量: <input type="range" id="xhs-img-quality" min="10" max="100" value="${settings.imgQuality}" style="width:80px;"> <span id="xhs-quality-val">${settings.imgQuality}</span> </label> <label>实况图: <select id="xhs-live-mode"> <option value="both" ${settings.liveMode==='both'?'selected':''}>图+视频</option> <option value="image" ${settings.liveMode==='image'?'selected':''}>仅图片</option> <option value="video" ${settings.liveMode==='video'?'selected':''}>仅视频</option> </select> </label> ${state.isVideoNote ? '<span style="color:#ef4444;font-weight:600;">🎬 视频笔记</span>' : ''} </div> <label class="xhs-select-all"> <input type="checkbox" ${state.selectedImages.size === state.imageUrls.length ? 'checked' : ''} id="xhs-select-all-cb"><span>全选笔记图${liveCount > 0 ? '(含实况视频)' : ''}</span> </label> <div class="xhs-image-list"> ${state.imageUrls.map((url, i) => ` <div class="xhs-image-item ${state.selectedImages.has(i) ? 'selected' : ''}" data-idx="${i}"> ${state.isVideoNote && i === 0 ? '<span class="xhs-video-badge">视频</span>' : (state.liveVideoUrls[i] ? '<span class="xhs-live-badge">实况</span>' : '')} <img src="${getThumbUrl(url)}" loading="lazy"> <span class="check" style="display:${state.selectedImages.has(i) ? 'flex' : 'none'};">✓</span> <button class="xhs-single-download" data-url="${escapeHtml(url)}" data-idx="${i}">下载</button> </div> `).join('')} </div> <button class="xhs-download-all-btn">${state.noteVideoUrl ? '下载图片+视频' : '下载选中笔记图'} (${state.selectedImages.size})</button> </div> <div class="xhs-comment-images-view" style="${state.noteSubTab === 'comment' ? '' : 'display:none;'}"> <button id="xhs-refresh-comments" class="xhs-refresh-comments-btn">🔄 重新扫描评论图 (${state.commentImages.length}张)</button> <label class="xhs-select-all"> <input type="checkbox" ${state.commentImages.length > 0 && state.selectedCommentImages.size === state.commentImages.length ? 'checked' : ''} id="xhs-select-all-cmt-cb"><span>全选评论图${state.commentImages.length > 0 ? ' (' + state.commentImages.length + ')' : ''}</span> </label> <div class="xhs-image-list"> ${commentListHtml} </div> <button class="xhs-download-all-btn xhs-comment-btn" ${state.selectedCommentImages.size === 0 ? 'disabled' : ''}> 下载选中评论图 (${state.selectedCommentImages.size}) </button> </div> <div class="xhs-progress"></div> `; document.body.appendChild(panel); panel.querySelector('.xhs-panel-close').onclick = () => panel.remove(); const debugBtn = panel.querySelector('.xhs-debug-btn'); if (debugBtn) { debugBtn.onclick = () => { debugDumpOrigins(); GM_notification({ title: '已输出原图字段排查信息', text: '请打开F12控制台,查看 [XHS下载器] 开头的日志,并把结果截图发给我', timeout: 4000 }); }; } panel.querySelectorAll('.xhs-mode-btn').forEach(b => { b.onclick = () => b.dataset.mode === 'profile' ? createProfilePanel() : createNotePanel(); }); panel.querySelectorAll('.xhs-subtab-btn').forEach(b => { b.onclick = () => { state.noteSubTab = b.dataset.tab; renderNoteSubTab(); }; }); // 下载设置控件 const fmtSel = panel.querySelector('#xhs-img-format'); const qWrap = panel.querySelector('#xhs-quality-wrap'); const qSel = panel.querySelector('#xhs-img-quality'); const qVal = panel.querySelector('#xhs-quality-val'); const liveSel = panel.querySelector('#xhs-live-mode'); if (fmtSel) { fmtSel.onchange = () => { settings.imgFormat = fmtSel.value; saveSettings(settings); if (qWrap) qWrap.style.display = fmtSel.value === 'original' ? 'none' : ''; }; } if (qSel) { qSel.oninput = () => { if (qVal) qVal.textContent = qSel.value; }; qSel.onchange = () => { settings.imgQuality = parseInt(qSel.value); saveSettings(settings); }; } if (liveSel) { liveSel.onchange = () => { settings.liveMode = liveSel.value; saveSettings(settings); }; } const selectCb = panel.querySelector('#xhs-select-all-cb'); const updateNoteBtn = () => { const btn = panel.querySelector('.xhs-download-all-btn:not(.xhs-comment-btn)'); if (!btn) return; if (state.selectedImages.size === state.imageUrls.length && state.imageUrls.length > 0) { btn.textContent = `下载选中笔记图 (${state.selectedImages.size})`; } else { btn.textContent = state.selectedImages.size > 0 ? `下载选中笔记图 (${state.selectedImages.size})` : `下载选中笔记图 (${state.selectedImages.size})`; } btn.disabled = state.selectedImages.size === 0 || state.isDownloading; }; if (selectCb) { selectCb.onchange = (e) => { const noteItems = panel.querySelectorAll('.xhs-image-item[data-idx]:not([data-comment-idx])'); noteItems.forEach(item => { const idx = parseInt(item.dataset.idx); if (e.target.checked) { item.classList.add('selected'); state.selectedImages.add(idx); item.querySelector('.check').style.display = 'flex'; } else { item.classList.remove('selected'); state.selectedImages.delete(idx); item.querySelector('.check').style.display = 'none'; } }); updateNoteBtn(); }; } panel.querySelectorAll('.xhs-image-item[data-idx]:not([data-comment-idx])').forEach(item => { item.onclick = (e) => { if (e.target.classList.contains('xhs-single-download')) return; const idx = parseInt(item.dataset.idx); if (state.selectedImages.has(idx)) { state.selectedImages.delete(idx); item.classList.remove('selected'); item.querySelector('.check').style.display = 'none'; } else { state.selectedImages.add(idx); item.classList.add('selected'); item.querySelector('.check').style.display = 'flex'; } selectCb.checked = state.imageUrls.length > 0 && state.selectedImages.size === state.imageUrls.length; updateNoteBtn(); }; }); panel.querySelectorAll('.xhs-image-item[data-idx]:not([data-comment-idx]) .xhs-single-download').forEach(btn => { btn.onclick = async (e) => { e.stopPropagation(); const url = btn.dataset.url; const idx = parseInt(btn.dataset.idx); const title = getNoteFilePrefix(); const fmt = settings.imgFormat; const ext = (fmt && fmt !== 'original') ? fmt : getImageExt(url); const imgUrl = applyImageFormat(url); if (settings.liveMode !== 'video') { await downloadImage(imgUrl, `${title}_${idx + 1}.${ext}`); } const liveUrl = state.liveVideoUrls[idx]; if (liveUrl && settings.liveMode !== 'image') { const vExt = getVideoExt(liveUrl); await downloadImage(liveUrl, `${title}_${idx + 1}_实况.${vExt}`, true); } }; }); const mainDownloadBtn = panel.querySelector('.xhs-download-all-btn:not(.xhs-comment-btn)'); if (mainDownloadBtn) mainDownloadBtn.onclick = downloadSelectedImages; const refreshBtn = panel.querySelector('#xhs-refresh-comments'); if (refreshBtn) refreshBtn.onclick = () => refreshCommentImages(5); const selectCmtCb = panel.querySelector('#xhs-select-all-cmt-cb'); const updateCmtBtn = () => { const btn = panel.querySelector('.xhs-download-all-btn.xhs-comment-btn'); if (!btn) return; btn.textContent = `下载选中评论图 (${state.selectedCommentImages.size})`; btn.disabled = state.selectedCommentImages.size === 0 || state.isDownloading; }; if (selectCmtCb) { selectCmtCb.onchange = (e) => { panel.querySelectorAll('.xhs-image-item[data-comment-idx]').forEach(item => { const idx = parseInt(item.dataset.commentIdx); if (e.target.checked) { item.classList.add('selected'); state.selectedCommentImages.add(idx); const chk = item.querySelector('.check'); if (chk) chk.style.display = 'flex'; } else { item.classList.remove('selected'); state.selectedCommentImages.delete(idx); const chk = item.querySelector('.check'); if (chk) chk.style.display = 'none'; } }); updateCmtBtn(); }; } panel.querySelectorAll('.xhs-image-item[data-comment-idx]').forEach(item => { item.onclick = (e) => { if (e.target.classList.contains('xhs-single-download')) return; const idx = parseInt(item.dataset.commentIdx); if (!state.commentImages[idx]) return; if (state.selectedCommentImages.has(idx)) { state.selectedCommentImages.delete(idx); item.classList.remove('selected'); const chk = item.querySelector('.check'); if (chk) chk.style.display = 'none'; } else { state.selectedCommentImages.add(idx); item.classList.add('selected'); const chk = item.querySelector('.check'); if (chk) chk.style.display = 'flex'; } selectCmtCb.checked = state.commentImages.length > 0 && state.selectedCommentImages.size === state.commentImages.length; updateCmtBtn(); }; }); panel.querySelectorAll('.xhs-cmt-single').forEach(btn => { btn.onclick = async (e) => { e.stopPropagation(); const url = btn.dataset.url; const idx = parseInt(btn.dataset.idx); const item = state.commentImages[idx]; if (!item) return; const prefix = getNoteFilePrefix(); const fmt = settings.imgFormat; const ext = (fmt && fmt !== 'original') ? fmt : getImageExt(item.url); const imgUrl = applyImageFormat(item.url); const timePrefix = item.commentTime ? item.commentTime + '_' : ''; await downloadImage(imgUrl, `${prefix}_评论图/${timePrefix}${item.commenter}_${idx + 1}.${ext}`); }; }); const cmtDownloadBtn = panel.querySelector('.xhs-download-all-btn.xhs-comment-btn'); if (cmtDownloadBtn) cmtDownloadBtn.onclick = downloadSelectedCommentImages; } function createProfilePanel() { const existing = document.querySelector('.xhs-download-panel'); if (existing) existing.remove(); state.currentMode = 'profile'; const panel = document.createElement('div'); panel.className = 'xhs-download-panel show'; const autoOn = isAutoDownloadEnabled(); panel.innerHTML = ` <div class="xhs-panel-header"> <span class="xhs-panel-title">自动下载设置</span> <button class="xhs-panel-close">×</button> </div> <div class="xhs-mode-switch"> <button class="xhs-mode-btn" data-mode="note">当前笔记</button> <button class="xhs-mode-btn active" data-mode="profile">自动下载</button> </div> <div style="padding:16px 0;line-height:1.8;font-size:13px;color:#666;"> <p style="margin:0 0 12px 0;">💡 <b>使用方法:</b></p> <ol style="margin:0;padding-left:20px;"> <li>点击下方按钮开启自动下载</li> <li>手动点击任意笔记打开详情</li> <li>脚本自动检测并下载该笔记原图</li> <li>下载完后关闭面板,点击下一个</li> </ol> <p style="margin:12px 0 0 0;color:#999;font-size:12px;">✅ 不会触发风控(所有点击由你操作)<br>✅ 自动跳过已下载过的笔记</p> </div> <input type="text" class="xhs-folder-input" placeholder="文件夹名" value="${getCurrentUsername()}" style="margin-bottom:12px;"> <button class="xhs-auto-btn" style="width:100%;border:none;border-radius:10px;padding:14px;color:white;font-size:15px;font-weight:600;cursor:pointer;box-shadow:0 4px 12px rgba(0,0,0,0.15);transition:all 0.2s;${autoOn ? 'background:#dc2626;' : 'background:linear-gradient(135deg,#16a34a,#22c55e);'}"> ${autoOn ? '🔴 关闭自动下载' : '🟢 开启自动下载'} </button> <div style="margin-top:16px;padding-top:12px;border-top:1px solid #f0f0f0;font-size:12px;color:#999;"> 已下载笔记记录保存在浏览器中,<button id="xhs-clear-history" style="background:none;border:none;color:#ff2442;cursor:pointer;padding:0;font-size:12px;text-decoration:underline;">清除记录</button> </div> `; document.body.appendChild(panel); panel.querySelector('.xhs-panel-close').onclick = () => panel.remove(); panel.querySelectorAll('.xhs-mode-btn').forEach(b => { b.onclick = () => b.dataset.mode === 'note' ? createNotePanel() : createProfilePanel(); }); const autoBtn = panel.querySelector('.xhs-auto-btn'); autoBtn.onclick = () => { setAutoDownload(!isAutoDownloadEnabled()); }; panel.querySelector('#xhs-clear-history').onclick = () => { localStorage.removeItem(DOWNLOADED_KEY); showBatchToast('已清除下载记录', 2000); }; } function createButton() { const old = document.querySelector('.xhs-download-btn'); if (old) old.remove(); state.isUserProfile = isProfilePage(); const btn = document.createElement('button'); btn.className = 'xhs-download-btn'; btn.innerHTML = state.isUserProfile ? '<span class="icon">⬇</span><span>下载设置</span>' : '<span class="icon">⬇</span><span>下载图片</span>'; btn.onclick = () => { const panel = document.querySelector('.xhs-download-panel'); if (panel) { panel.classList.toggle('show'); return; } const loadingPanel = document.createElement('div'); loadingPanel.className = 'xhs-download-panel show'; loadingPanel.innerHTML = ` <div class="xhs-panel-header"> <span class="xhs-panel-title">加载中...</span> <button class="xhs-panel-close">×</button> </div> <div style="padding: 40px; text-align: center; color: #666;"> 正在扫描页面,请稍候... </div> `; document.body.appendChild(loadingPanel); loadingPanel.querySelector('.xhs-panel-close').onclick = () => loadingPanel.remove(); setTimeout(() => { loadingPanel.remove(); if (state.isUserProfile) { createProfilePanel(); } else { createNotePanel(); } }, 10); }; document.body.appendChild(btn); } function init() { const createWithRetry = (attempt = 0) => { if (attempt > 5) return; setTimeout(() => { if (!document.querySelector('.xhs-download-btn')) { createButton(); } if (isProfilePage() && attempt < 3) { setTimeout(() => createButton(), 1000 * (attempt + 1)); } }, 1500 + attempt * 800); }; if (window.location.hostname === 'xhslink.com') { setTimeout(() => { if (window.location.hostname.includes('xiaohongshu.com')) createWithRetry(); }, 3000); } else if (window.location.hostname.includes('xiaohongshu.com')) { createWithRetry(); if (isAutoDownloadEnabled()) { setTimeout(() => { startAutoObserver(); showAutoStatus(); }, 2000); } } } let lastUrl = location.href; new MutationObserver(() => { if (location.href !== lastUrl) { debugLog('URL变化:', lastUrl, '->', location.href); lastUrl = location.href; const panel = document.querySelector('.xhs-download-panel'); if (panel) panel.remove(); lastAutoNoteId = null; lastSeenNoteId = null; autoDownloading = false; setTimeout(() => { createButton(); if (isAutoDownloadEnabled()) { setTimeout(() => { startAutoObserver(); showAutoStatus(); }, 1000); } }, 1000); } }).observe(document, { subtree: true, childList: true }); init(); })();