// ==UserScript== // @name 磁力链接自动识别与资源预览 // @namespace https://trae.local/magnet-preview // @version 1.1.0 // @description 自动识别网页磁力链接与百家姓加密磁力,预览时展示内容截图/文件列表;支持自动或手动 P2P 扫描、取消扫描、节点数提示、按站点隐私开关与首图速度优化。 // @author Trae // @match *://*/* // @grant GM_getValue // @grant GM_setValue // @grant GM_addStyle // @grant GM_registerMenuCommand // @grant GM_xmlhttpRequest // @grant unsafeWindow // @connect * // @run-at document-idle // @noframes // @license MIT // ==/UserScript== /* * 功能说明 * 1. 自动识别 、纯文本磁力链接与百家姓加密磁力, * 并在旁边追加“预览”按钮;百家姓暗号会自动转换成可点击的磁力链接。 * 2. 弹层展示资源名称、大小、哈希、追踪器数量、文件数与内容截图。 * 3. 内容预览节点: * - whatslink.info 公开 API(GET /api/v1/link),提供截图/大小/文件数 * - 呜呜呜 wuwuwu.makifx.com(POST /api/details),whatslink 的备用节点 * - itorrents.org(BT 缓存,WebRTC 连接失败时补全文件列表,并提供 .torrent 下载) * - 磁力预览 pics.magnetq.com(外部预览页,链接由 base64(fuli.today + infohash) 生成) * 4. 点击“预览”后按设置自动或手动加载 WebTorrent,仅通过 WebRTC/WebSocket 节点读取种子元数据; * 可随时取消扫描,查看已发现节点数;可在油猴菜单中全局/按站点关闭自动 P2P(会暴露本机 IP)。 * 5. 尽量多提取图片或按多个时间点截取视频帧(种子内最多补 12 张); * 图片并发生成、小图优先,同一视频只建立一次流并连续 seek 抓多帧; * 所有缩略图以三列网格展示,可滚动查看全部。 * * 说明:截图节点查询的是第三方索引数据库,不是实时 P2P;whatslink/呜呜呜 未收录的资源不会有截图。 */ (function () { 'use strict'; /* ============================== 配置 ============================== */ var CONFIG = { maxTextLinks: 600, // 单页最多自动转换多少条纯文本磁力 requestTimeout: 7000, // 接口请求超时 torrentTimeout: 30000, // 等待种子元数据超时 fileTimeout: 18000, // 下载单张预览图超时 contentCacheTtl: 7 * 24 * 3600 * 1000, cacheLimit: 300, corsProxies: [ 'https://api.allorigins.win/raw?url=', 'https://api.codetabs.com/v1/proxy?quest=' ], wtCdns: [ 'https://cdn.jsdelivr.net/npm/webtorrent@1.9.7/webtorrent.min.js', 'https://unpkg.com/webtorrent@1.9.7/webtorrent.min.js' ], extraTrackers: [ 'wss://tracker.openwebtorrent.com', 'wss://tracker.webtorrent.dev', 'wss://tracker.files.fm:7073/announce', 'wss://tracker.btorrent.xyz', 'wss://tracker.fastcast.nz', 'wss://tracker.sloppyta.co:443/announce', 'wss://tracker.novage.com.ua:443/announce', 'wss://tracker.webtorrent.io' ] }; var VERSION = '1.8.2'; try { if (typeof GM_info !== 'undefined' && GM_info.script && GM_info.script.version) { VERSION = GM_info.script.version; } } catch (e) { /* ignore */ } var STORE_KEYS = { content: 'mgp:contentCache', autoScan: 'mgp:autoScan', autoScanSites: 'mgp:autoScanSites' }; function getAutoScanGlobal() { return store.get(STORE_KEYS.autoScan, true) !== false; } function getAutoScanSites() { var value = store.get(STORE_KEYS.autoScanSites, {}); return value && typeof value === 'object' ? value : {}; } // 优先使用站点级设置;没有设置时跟随全局开关 function shouldAutoScan() { try { var origin = location.origin; var sites = getAutoScanSites(); if (Object.prototype.hasOwnProperty.call(sites, origin)) return sites[origin] !== false; return getAutoScanGlobal(); } catch (e) { return true; } } var CONTENT_SOURCES = { whatslink: 'whatslink', makifx: '呜呜呜', magnetq: '磁力预览', itorrents: 'itorrents' }; var FILE_TYPE_LABELS = { video: '视频', audio: '音频', image: '图片', software: '软件', archive: '压缩包', document: '文档', ebook: '电子书', folder: '文件夹', other: '其他' }; var BADGE_HTML = '预览'; /* ============================== 基础状态 ============================== */ var pageWin = (typeof unsafeWindow !== 'undefined' && unsafeWindow) ? unsafeWindow : window; var gmXhr = (typeof GM_xmlhttpRequest === 'function') ? GM_xmlhttpRequest : null; var gmGet = (typeof GM_getValue === 'function') ? GM_getValue : null; var gmSet = (typeof GM_setValue === 'function') ? GM_setValue : null; var host = null; var shadow = null; var pop = null; var state = { open: false, reqId: 0 }; var reqSeq = 0; var autoLinkCount = 0; var observer = null; var pendingRoots = new Set(); var flushTimer = 0; var inflightContent = new Map(); var wtPromise = null; var contentCache = {}; var styleInjected = false; var enhancedMagnets = new Map(); // 磁力哈希 -> { anchor, badge },同一资源只保留一个预览按钮 /* ============================== 工具函数 ============================== */ function h(tag, attrs) { var el = document.createElement(tag); attrs = attrs || {}; Object.keys(attrs).forEach(function (key) { var val = attrs[key]; if (val === null || val === undefined || val === false) return; if (key === 'class') el.className = val; else if (key === 'text') el.textContent = val; else if (key === 'style' && typeof val === 'object') Object.assign(el.style, val); else if (/^on[A-Z]/.test(key) && typeof val === 'function') { el.addEventListener(key.slice(2).toLowerCase(), val); } else if (val === true) el.setAttribute(key, ''); else el.setAttribute(key, String(val)); }); for (var i = 2; i < arguments.length; i++) { appendChild(el, arguments[i]); } return el; } function appendChild(parent, child) { if (child === null || child === undefined || child === false) return; if (Array.isArray(child)) { child.forEach(function (c) { appendChild(parent, c); }); return; } parent.appendChild(child.nodeType ? child : document.createTextNode(String(child))); } function fmtBytes(num) { var n = Number(num); if (!isFinite(n) || n <= 0) return ''; var units = ['B', 'KB', 'MB', 'GB', 'TB']; var i = 0; while (n >= 1024 && i < units.length - 1) { n /= 1024; i++; } return (n >= 100 ? Math.round(n) : n.toFixed(1)) + ' ' + units[i]; } function shortHash(hash) { if (!hash) return ''; if (hash.length <= 12) return hash; return hash.slice(0, 8) + '…' + hash.slice(-4); } function fmtTime(seconds) { var total = Math.max(0, Math.floor(Number(seconds) || 0)); var m = Math.floor(total / 60); var s = total % 60; return (m < 10 ? '0' : '') + m + ':' + (s < 10 ? '0' : '') + s; } function safeUrl(url) { return (typeof url === 'string' && /^https?:\/\//i.test(url.trim())) ? url.trim() : ''; } function waitEvent(target, type, timeout) { return new Promise(function (resolve, reject) { var timer = setTimeout(function () { cleanup(); reject(new Error('等待 ' + type + ' 超时')); }, timeout); function onEvent(e) { cleanup(); resolve(e); } function onError() { cleanup(); reject(new Error(type + ' 触发错误')); } function cleanup() { clearTimeout(timer); target.removeEventListener(type, onEvent); target.removeEventListener('error', onError); } target.addEventListener(type, onEvent, { once: true }); target.addEventListener('error', onError, { once: true }); }); } function copyText(text) { return Promise.resolve().then(function () { if (navigator.clipboard && window.isSecureContext) { return navigator.clipboard.writeText(text).then(function () { return true; }).catch(function () { return legacyCopy(text); }); } return legacyCopy(text); }); } function legacyCopy(text) { var ta = document.createElement('textarea'); ta.value = text; ta.setAttribute('readonly', ''); ta.style.cssText = 'position:fixed;left:-9999px;top:0;opacity:0;'; document.body.appendChild(ta); ta.select(); var ok = false; try { ok = document.execCommand('copy'); } catch (e) { ok = false; } ta.remove(); return ok; } function flashLabel(el, text, ms) { if (!el) return; var prev = el.textContent; el.textContent = text; setTimeout(function () { if (el.textContent === text) el.textContent = prev; }, ms || 1400); } /* ============================== 存储与缓存 ============================== */ var store = { get: function (key, def) { try { if (gmGet) { var v = gmGet(key, def); return v === undefined ? def : v; } var raw = localStorage.getItem(key); return raw === null ? def : JSON.parse(raw); } catch (e) { return def; } }, set: function (key, val) { try { if (gmSet) gmSet(key, val); else localStorage.setItem(key, JSON.stringify(val)); } catch (e) { /* ignore */ } } }; function loadContentCache() { var data = store.get(STORE_KEYS.content, {}); if (typeof data === 'string') { try { data = JSON.parse(data); } catch (e) { data = {}; } } if (!data || typeof data !== 'object' || Array.isArray(data)) data = {}; contentCache = data; } function readContentCache(hash) { var entry = contentCache[hash]; if (!entry) return undefined; if (Date.now() - entry.ts > CONFIG.contentCacheTtl) { delete contentCache[hash]; return undefined; } return entry.data || null; } function writeContentCache(hash, data) { if (!data) return; var shots = (data.screenshots || []).filter(function (item) { return item && safeUrl(item.screenshot); }).slice(0, 12).map(function (item) { return { screenshot: item.screenshot, time: Number(item.time) || 0 }; }); contentCache[hash] = { ts: Date.now(), data: { name: data.name || '', size: Number(data.size) || 0, count: Number(data.count) || 0, fileType: data.fileType || '', type: data.type || '', source: data.source || '', screenshots: shots } }; var keys = Object.keys(contentCache); if (keys.length > CONFIG.cacheLimit) { keys.sort(function (a, b) { return contentCache[a].ts - contentCache[b].ts; }); keys.slice(0, keys.length - CONFIG.cacheLimit).forEach(function (k) { delete contentCache[k]; }); } store.set(STORE_KEYS.content, contentCache); } /* ============================== 磁力解析 ============================== */ var B32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; function base32ToHex(input) { var s = String(input || '').toUpperCase().replace(/=+$/, ''); var bits = 0; var value = 0; var out = ''; for (var i = 0; i < s.length; i++) { var idx = B32.indexOf(s.charAt(i)); if (idx === -1) return ''; value = (value << 5) | idx; bits += 5; if (bits >= 8) { bits -= 8; var byte = (value >>> bits) & 0xff; out += (byte < 16 ? '0' : '') + byte.toString(16); value &= (1 << bits) - 1; } } return out.length === 40 ? out : ''; } function parseMagnet(raw) { var s = String(raw || '').trim(); if (!/^magnet:/i.test(s)) return null; var qi = s.indexOf('?'); var query = qi >= 0 ? s.slice(qi + 1) : ''; var params; try { params = new URLSearchParams(query); } catch (e) { return null; } var hash = ''; params.getAll('xt').forEach(function (xt) { var m = /^urn:btih:([a-z0-9]+)$/i.exec(String(xt).trim()); if (m && (m[1].length === 40 || m[1].length === 32)) hash = m[1]; }); if (!hash) return null; var isHex = hash.length === 40; var hashHex = isHex ? hash.toLowerCase() : base32ToHex(hash); var size = Number(params.get('xl')); return { raw: s, hash: hash, hashHex: hashHex || hash.toLowerCase(), dn: (params.get('dn') || '').trim(), size: isFinite(size) && size > 0 ? size : 0, trackers: params.getAll('tr') }; } function buildMagnet(info) { // 注意:不要使用 URLSearchParams.toString() 重建整个 magnet,部分 WebTorrent 版本 // 无法识别被编码成 %3A 的 xt=urn:btih: 前缀。这里只对参数值做编码。 var magnet = 'magnet:?xt=urn:btih:' + info.hash; if (info.dn) magnet += '&dn=' + encodeURIComponent(info.dn); var seen = new Set(); var trackers = info.trackers.concat(CONFIG.extraTrackers); trackers.forEach(function (tr) { if (!tr || seen.has(tr)) return; seen.add(tr); magnet += '&tr=' + encodeURIComponent(tr); }); return magnet; } // 部分预览接口只需要 infohash + dn,去掉 tr 可减少长度并避免被上游代理截断 function buildLookupMagnet(info) { var hash = info.hashHex || info.hash; var magnet = 'magnet:?xt=urn:btih:' + hash; if (info.dn) magnet += '&dn=' + encodeURIComponent(info.dn); return magnet; } // magnetq 的图片预览页格式:base64("fuli.today" + infohash) function magnetqPreviewUrl(info) { var hash = info && (info.hashHex || info.hash); if (hash) { try { return 'https://pics.magnetq.com/p/' + btoa('fuli.today' + hash); } catch (e) { /* ignore */ } } return 'https://pics.magnetq.com/'; } function buildMoreSites(info) { var hash = String(info && (info.hashHex || info.hash) || '').toLowerCase(); if (!/^[a-f0-9]{40}$/.test(hash)) return null; var upper = hash.toUpperCase(); var links = [ ['MagnetQ 搜索', 'https://www.magnetq.com/search.html?q=' + hash, '在 MagnetQ 搜索该资源'], ['磁力印象', 'https://alpha.magnet.pics/', '磁力印象(当前可能无法访问,打开后粘贴磁力)'], ['BT Cache', 'https://btcache.me/torrent/' + upper, 'BT Cache 种子缓存页'], ['itorrents', 'https://itorrents.org/torrent/' + upper + '.torrent', '下载 .torrent'] ]; var box = h('div', { class: 'more-sites' }, h('span', { class: 'more-label' }, '更多站点:')); links.forEach(function (item, index) { if (index) box.appendChild(document.createTextNode(' · ')); box.appendChild(h('a', { href: item[1], target: '_blank', rel: 'noopener noreferrer', title: item[2] }, item[0] + ' ↗')); }); return box; } /* ============================== 网络请求 ============================== */ function gmRequest(url, timeout, options) { options = options || {}; return new Promise(function (resolve, reject) { var req = null; var backup = setTimeout(function () { try { if (req && req.abort) req.abort(); } catch (e) {} reject(new Error('请求超时')); }, timeout + 800); function finish(fn, val) { clearTimeout(backup); fn(val); } var headers = { Accept: 'application/json, text/plain, */*' }; if (options.headers) { Object.keys(options.headers).forEach(function (key) { headers[key] = options.headers[key]; }); } try { req = gmXhr({ method: options.method || 'GET', url: url, data: options.data, timeout: timeout, headers: headers, onload: function (res) { if (res.status >= 200 && res.status < 300) finish(resolve, res.responseText); else finish(reject, new Error('HTTP ' + res.status)); }, onerror: function () { finish(reject, new Error('网络错误')); }, ontimeout: function () { finish(reject, new Error('请求超时')); }, onabort: function () { finish(reject, new Error('请求被取消')); } }); } catch (e) { finish(reject, e); } }); } // 统一处理原生 fetch 的超时、状态码和文本/二进制响应 function nativeRequestRaw(url, options, timeout, binary) { var ctrl = new AbortController(); var timer = setTimeout(function () { try { ctrl.abort(); } catch (e) {} }, timeout); var opts = options || {}; opts.signal = ctrl.signal; opts.credentials = 'omit'; opts.mode = 'cors'; return fetch(url, opts).then(function (res) { if (!res.ok) throw new Error('HTTP ' + res.status); return binary ? res.arrayBuffer() : res.text(); }).finally(function () { clearTimeout(timer); }); } function nativeRequest(url, timeout) { return nativeRequestRaw(url, null, timeout, false); } function nativePostJson(url, body, timeout) { return nativeRequestRaw(url, { method: 'POST', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, body: body }, timeout, false); } function gmRequestBinary(url, timeout) { return new Promise(function (resolve, reject) { var req = null; var backup = setTimeout(function () { try { if (req && req.abort) req.abort(); } catch (e) {} reject(new Error('请求超时')); }, timeout + 800); function finish(fn, val) { clearTimeout(backup); fn(val); } try { req = gmXhr({ method: 'GET', url: url, timeout: timeout, responseType: 'arraybuffer', headers: { Accept: 'application/x-bittorrent, application/octet-stream, */*' }, onload: function (res) { if (res.status >= 200 && res.status < 300 && res.response) finish(resolve, res.response); else finish(reject, new Error('HTTP ' + res.status)); }, onerror: function () { finish(reject, new Error('网络错误')); }, ontimeout: function () { finish(reject, new Error('请求超时')); }, onabort: function () { finish(reject, new Error('请求被取消')); } }); } catch (e) { finish(reject, e); } }); } function nativeRequestBinary(url, timeout) { return nativeRequestRaw(url, null, timeout, true); } function fetchBinary(url, timeout) { var ms = timeout || CONFIG.requestTimeout; if (gmXhr) return gmRequestBinary(url, ms); return nativeRequestBinary(url, ms); } function fetchText(url, timeout) { var ms = timeout || CONFIG.requestTimeout; if (gmXhr) { return gmRequest(url, ms).catch(function (firstError) { var proxy = CONFIG.corsProxies[0]; return gmRequest(proxy + encodeURIComponent(url), ms).catch(function () { throw firstError; }); }); } return nativeRequest(url, ms).catch(function (firstError) { var chain = Promise.reject(firstError); CONFIG.corsProxies.forEach(function (proxy) { chain = chain.catch(function () { return nativeRequest(proxy + encodeURIComponent(url), ms); }); }); return chain; }); } function fetchJson(url, timeout) { return fetchText(url, timeout).then(function (text) { return JSON.parse(text); }); } function postJson(url, payload, timeout) { var ms = timeout || CONFIG.requestTimeout; var body = JSON.stringify(payload); if (gmXhr) { return gmRequest(url, ms, { method: 'POST', data: body, headers: { 'Content-Type': 'application/json', Accept: 'application/json' } }).then(function (text) { return JSON.parse(text); }); } return nativePostJson(url, body, ms).then(function (text) { return JSON.parse(text); }); } function firstNonNull(promises) { return new Promise(function (resolve) { var left = promises.length; if (!left) return resolve(null); promises.forEach(function (p) { p.then(function (value) { if (value) resolve(value); }).catch(function () {}).finally(function () { left--; if (left === 0) resolve(null); }); }); }); } function withTimeout(promise, ms, fallback) { return new Promise(function (resolve) { var timer = setTimeout(function () { resolve(fallback); }, ms); promise.then(function (value) { clearTimeout(timer); resolve(value); }, function () { clearTimeout(timer); resolve(fallback); }); }); } /* ============================== 内容截图节点 ============================== */ function normalizeContentPayload(data, source) { if (!data || data.error) return null; var rawShots = Array.isArray(data.screenshots) ? data.screenshots : []; var seen = new Set(); var screenshots = []; for (var i = 0; i < rawShots.length; i++) { var row = rawShots[i]; var url = typeof row === 'string' ? row : (row && (row.screenshot || row.url)); if (!safeUrl(url) || seen.has(url)) continue; seen.add(url); screenshots.push({ screenshot: url, time: Number(row && row.time) || 0 }); if (screenshots.length >= 12) break; } var name = data.name || ''; var size = Number(data.size) || 0; var count = Number(data.count) || 0; var fileType = data.file_type || data.fileType || ''; var type = data.type || ''; if (!name && !size && !count && !screenshots.length) return null; return { name: name, size: size, count: count, fileType: fileType, type: type, screenshots: screenshots, source: source }; } function fetchWhatslinkContent(info) { var magnet = buildLookupMagnet(info); var url = 'https://whatslink.info/api/v1/link?url=' + encodeURIComponent(magnet); return fetchJson(url, 8000).then(function (data) { return normalizeContentPayload(data, CONTENT_SOURCES.whatslink); }).catch(function () { return null; }); } function fetchMakifxContent(info) { var magnet = buildLookupMagnet(info); return postJson('https://wuwuwu.makifx.com/api/details', { url: magnet }, 9000) .then(function (data) { return normalizeContentPayload(data, CONTENT_SOURCES.makifx); }).catch(function () { return null; }); } function resolveContentData(info) { return withTimeout(firstNonNull([ fetchWhatslinkContent(info), fetchMakifxContent(info) ]), 9500, null); } /* ============================== itorrents 缓存节点 ============================== */ function decodeUtf8(bytes) { try { return new TextDecoder('utf-8').decode(bytes); } catch (e) { var text = ''; for (var i = 0; i < bytes.length; i++) text += String.fromCharCode(bytes[i]); return text; } } function decodeBencode(buffer) { var data = new Uint8Array(buffer); var pos = 0; function parse() { if (pos >= data.length) throw new Error('无效的 torrent 数据'); var code = data[pos]; if (code === 0x69) { // i pos++; var start = pos; while (pos < data.length && data[pos] !== 0x65) pos++; var number = parseInt(decodeUtf8(data.subarray(start, pos)), 10); pos++; return number; } if (code === 0x6c) { // l pos++; var list = []; while (pos < data.length && data[pos] !== 0x65) list.push(parse()); pos++; return list; } if (code === 0x64) { // d pos++; var dict = Object.create(null); while (pos < data.length && data[pos] !== 0x65) { var key = decodeUtf8(parse()); dict[key] = parse(); } pos++; return dict; } var lenStart = pos; while (pos < data.length && data[pos] !== 0x3a) pos++; var length = parseInt(decodeUtf8(data.subarray(lenStart, pos)), 10); pos++; if (!isFinite(length) || length < 0 || pos + length > data.length) { throw new Error('无效的 torrent 字符串'); } var bytes = data.subarray(pos, pos + length); pos += length; return bytes; } return parse(); } function torrentFilesFromBencode(buffer) { var root = decodeBencode(buffer); var info = root && root.info; if (!info || !info.files && !info.length) return null; var name = decodeUtf8(info['name.utf-8'] || info.name || new Uint8Array()); var files = []; if (Array.isArray(info.files)) { info.files.forEach(function (item) { if (!item) return; var pathParts = item['path.utf-8'] || item.path || []; var path = Array.isArray(pathParts) ? pathParts.map(decodeUtf8).join('/') : ''; if (!path) path = name; files.push({ path: path, name: path.split('/').pop(), length: Number(item.length) || 0 }); }); } else if (info.length) { files.push({ path: name, name: name, length: Number(info.length) || 0 }); } if (!files.length) return null; var total = files.reduce(function (sum, file) { return sum + (file.length || 0); }, 0); return { name: name, files: files, total: total, count: files.length }; } function itorrentsTorrentUrl(info) { var hash = String(info && (info.hashHex || info.hash) || '').toLowerCase(); if (!/^[a-f0-9]{40}$/.test(hash)) return ''; return 'https://itorrents.org/torrent/' + hash.toUpperCase() + '.torrent'; } function fetchItorrentsFiles(info) { var url = itorrentsTorrentUrl(info); if (!url) return Promise.resolve(null); return fetchBinary(url, 9000).then(function (buffer) { var data = torrentFilesFromBencode(buffer); if (!data) return null; data.url = url; data.source = CONTENT_SOURCES.itorrents; return data; }).catch(function () { return null; }); } /* ============================== 样式 ============================== */ var PAGE_CSS = [ '.mgp-badge{display:inline-flex!important;align-items:center!important;justify-content:center!important;gap:3px!important;', 'height:20px!important;padding:0 6px!important;margin-left:5px!important;border-radius:6px!important;', 'background:linear-gradient(135deg,#5b8cff,#8b5cf6)!important;color:#fff!important;', 'font:600 11px/1 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif!important;', 'letter-spacing:.02em!important;vertical-align:middle!important;cursor:pointer!important;', 'box-shadow:0 1px 5px rgba(0,0,0,.35),inset 0 1px 0 rgba(255,255,255,.18)!important;', 'user-select:none!important;-webkit-user-select:none!important;text-decoration:none!important;', 'transition:transform .12s ease,box-shadow .12s ease,filter .12s ease!important;}', '.mgp-badge:hover{transform:translateY(-1px)!important;filter:brightness(1.08)!important;', 'box-shadow:0 3px 9px rgba(0,0,0,.4),inset 0 1px 0 rgba(255,255,255,.22)!important;}', '.mgp-badge:active{transform:translateY(0)!important;}', '.mgp-badge:focus-visible{outline:2px solid rgba(150,175,255,.85)!important;outline-offset:2px!important;}', '.mgp-badge.mgp-active{box-shadow:0 0 0 2px rgba(150,175,255,.55),0 2px 9px rgba(0,0,0,.4)!important;}', '.mgp-badge .mgp-badge-text{pointer-events:none!important;white-space:nowrap!important;}', '.mgp-badge.mgp-badge-corner{position:absolute!important;top:6px!important;right:6px!important;margin:0!important;z-index:3!important;}', '.mgp-auto-link{color:inherit!important;text-decoration:underline dotted!important;text-underline-offset:2px!important;', 'cursor:pointer!important;word-break:break-all!important;}' ].join(''); function injectPageStyles() { if (styleInjected) return; styleInjected = true; var css = PAGE_CSS; if (typeof GM_addStyle === 'function') { GM_addStyle(css); } else { var style = document.createElement('style'); style.textContent = css; (document.head || document.documentElement).appendChild(style); } } var POP_CSS = [ ':host{all:initial;}', '.pop,.pop *{box-sizing:border-box;}', '.pop{position:fixed;left:0;top:0;width:408px;max-width:calc(100vw - 16px);max-height:78vh;max-height:min(78vh,640px);', 'display:flex;flex-direction:column;overflow:hidden;pointer-events:auto;touch-action:pan-y;', 'background:linear-gradient(180deg,#171a22 0%,#101218 100%);color:#e8edf6;', 'border:1px solid rgba(255,255,255,.09);border-radius:14px;', 'box-shadow:0 24px 70px rgba(0,0,0,.6),0 2px 12px rgba(0,0,0,.35);', 'font:13px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Hiragino Sans GB","Microsoft YaHei",sans-serif;', 'opacity:0;transform:translateY(6px) scale(.985);transition:opacity .16s ease,transform .16s ease;}', '.pop.show{opacity:1;transform:none;}', '.pop[hidden]{display:none!important;}', '.pop [hidden]{display:none!important;}', '.head{display:flex;align-items:flex-start;gap:10px;padding:12px 14px;flex:0 0 auto;', 'border-bottom:1px solid rgba(255,255,255,.07);background:rgba(255,255,255,.02);}', '.head-main{min-width:0;flex:1;}', '.title{font-size:14px;font-weight:650;line-height:1.35;color:#f2f5fb;overflow:hidden;display:-webkit-box;', '-webkit-line-clamp:2;-webkit-box-orient:vertical;word-break:break-all;}', '.sub{margin-top:3px;font-size:11px;color:#8b94a7;display:flex;align-items:center;gap:5px;}', '.dot{width:3px;height:3px;border-radius:50%;background:#5f687b;display:inline-block;}', '.icon-btn{flex:0 0 auto;width:26px;height:26px;border:none;border-radius:7px;background:rgba(255,255,255,.055);', 'color:#9aa3b6;font:400 18px/1 sans-serif;cursor:pointer;display:flex;align-items:center;justify-content:center;', 'transition:background .15s,color .15s;appearance:none;}', '.icon-btn:hover{background:rgba(255,255,255,.12);color:#e8edf6;}', '.body{padding:13px 14px 4px;overflow-y:auto;overflow-x:hidden;touch-action:pan-y;overscroll-behavior:contain;flex:1 1 auto;min-height:0;}', '.info{display:flex;flex-direction:column;gap:7px;min-width:0;}', '.more-sites{font-size:10px;line-height:1.7;color:#6f788b;overflow-wrap:anywhere;}', '.more-sites .more-label{color:#59627a;}', '.more-sites a{color:#8aa4ff;text-decoration:none;}', '.more-sites a:hover{text-decoration:underline;}', '.ver{font-size:10px;color:#59627a;}', '.gallery-hint{font-size:10px;line-height:1.55;color:#6f788b;margin:0 0 6px;overflow-wrap:anywhere;}', '.chips{display:flex;flex-wrap:wrap;gap:6px;}', '.chip{display:inline-flex;align-items:center;gap:4px;padding:2px 7px;border-radius:999px;', 'background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.07);', 'font:11px/1.5 -apple-system,BlinkMacSystemFont,"Segoe UI","Microsoft YaHei",sans-serif;color:#c8d1e2;}', 'button.chip{cursor:pointer;appearance:none;font-family:inherit;}', 'a.chip{text-decoration:none;cursor:pointer;}', 'button.chip:hover,a.chip:hover{background:rgba(255,255,255,.11);}', '.section{margin-top:13px;}', '.section-head{display:flex;align-items:baseline;justify-content:space-between;gap:8px;', 'font-size:12px;font-weight:600;color:#cdd5e4;margin-bottom:6px;}', '.dim{font-weight:400;font-size:11px;color:#7f89a0;}', '.gallery{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;padding-bottom:4px;', 'overflow-x:hidden;touch-action:pan-y;}', '.shot{position:relative;width:100%;aspect-ratio:16/10;border-radius:7px;overflow:hidden;', 'background:#0b0d12;border:1px solid rgba(255,255,255,.06);display:block;}', '.shot img{width:100%;height:100%;object-fit:cover;display:block;}', '.shot .tag{position:absolute;left:4px;bottom:4px;max-width:calc(100% - 8px);padding:1px 5px;border-radius:4px;', 'background:rgba(0,0,0,.62);font-size:10px;color:#dfe6f2;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}', '.files{display:flex;flex-direction:column;gap:3px;max-height:132px;overflow-y:auto;overflow-x:hidden;', 'padding-right:2px;touch-action:pan-y;overscroll-behavior:contain;}', '.file{display:flex;gap:10px;justify-content:space-between;font:11px/1.6 ui-monospace,SFMono-Regular,Consolas,monospace;', 'color:#aeb7c9;padding:3px 6px;border-radius:5px;background:rgba(255,255,255,.025);}', '.file .fname{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}', '.file .fsize{color:#7f89a0;flex:0 0 auto;}', '.files-note{font-size:10px;color:#6f788b;margin-top:4px;}', '.files-note a{color:#8aa4ff;text-decoration:none;}', '.files-note a:hover{text-decoration:underline;}', '.foot{flex:0 0 auto;border-top:1px solid rgba(255,255,255,.07);background:rgba(0,0,0,.16);}', '.status{display:flex;align-items:center;gap:7px;font-size:11px;color:#8d97ab;padding:8px 14px 0;min-height:16px;', 'overflow-wrap:anywhere;word-break:break-word;}', '.status[hidden]{display:none;}', '.status.error{color:#ff9b9b;}', '.spinner{width:12px;height:12px;flex:0 0 auto;border-radius:50%;', 'border:2px solid rgba(255,255,255,.16);border-top-color:#8aa4ff;animation:mgp-spin .8s linear infinite;}', '.actions{display:flex;gap:8px;padding:9px 14px 12px;}', '.btn{flex:1;height:32px;border-radius:8px;border:1px solid transparent;font-family:inherit;', 'font-size:12px;font-weight:600;line-height:1;cursor:pointer;appearance:none;', 'transition:transform .1s ease,filter .15s ease,background .15s ease,opacity .15s;}', '.btn:active{transform:translateY(1px);}', '.btn.primary{background:linear-gradient(135deg,#5b8cff,#8b5cf6);color:#fff;box-shadow:0 4px 14px rgba(91,140,255,.25);}', '.btn.primary:hover{filter:brightness(1.07);}', '.btn.ghost{background:rgba(255,255,255,.055);border-color:rgba(255,255,255,.09);color:#d6dceb;}', '.btn.ghost:hover{background:rgba(255,255,255,.1);}', '.btn:disabled{opacity:.45;cursor:not-allowed;transform:none;}', '.files::-webkit-scrollbar,.body::-webkit-scrollbar{width:6px;height:6px;}', '.files::-webkit-scrollbar-thumb,.body::-webkit-scrollbar-thumb{', 'background:rgba(255,255,255,.16);border-radius:4px;}', '@keyframes mgp-spin{to{transform:rotate(360deg);}}' ].join(''); function ensureUI() { if (host) return; host = document.createElement('div'); host.id = 'mgp-host-root'; host.style.cssText = 'all:initial;display:block;position:fixed;left:0;top:0;width:0;height:0;z-index:2147483647;pointer-events:none;'; shadow = host.attachShadow({ mode: 'open' }); var style = document.createElement('style'); style.textContent = POP_CSS; pop = document.createElement('div'); pop.className = 'pop'; pop.hidden = true; pop.setAttribute('role', 'dialog'); pop.setAttribute('aria-label', '磁力资源预览'); shadow.appendChild(style); shadow.appendChild(pop); document.documentElement.appendChild(host); // 简介、截图、文件列表等异步内容会让弹层高度变化,需重新贴靠锚点 if (typeof ResizeObserver === 'function') { var resizeObserver = new ResizeObserver(function () { if (state.open) requestAnimationFrame(positionPopover); }); resizeObserver.observe(pop); } } /* ============================== 弹层 ============================== */ function isActive(s) { return !!s && state.open && state.reqId === s.reqId; } function setStatus(s, text, loading, isError) { if (!s || !s.refs) return; var box = s.refs.status; if (!text) { box.hidden = true; box.replaceChildren(); return; } box.hidden = false; box.classList.toggle('error', !!isError); var children = []; if (loading) children.push(h('span', { class: 'spinner' })); children.push(h('span', {}, text)); box.replaceChildren.apply(box, children); } function buildPopover(s) { var info = s.info; var title = h('div', { class: 'title', title: info.dn || '磁力资源' }, info.dn || '磁力资源'); var sub = h('div', { class: 'sub' }, h('span', {}, '磁力资源'), h('span', { class: 'dot' }), h('span', { title: info.hashHex }, shortHash(info.hashHex)), h('span', { class: 'dot' }), h('span', { class: 'ver', title: '当前脚本版本' }, 'v' + VERSION) ); var sizeChip = h('span', { class: 'chip' }, info.size ? '大小 ' + fmtBytes(info.size) : '大小未知'); var hashChip = h('button', { type: 'button', class: 'chip', title: '点击复制完整哈希:' + info.hashHex }, '哈希 ' + shortHash(info.hashHex)); var chips = h('div', { class: 'chips' }, sizeChip, hashChip); if (info.trackers.length) { chips.appendChild(h('span', { class: 'chip' }, '追踪器 ' + info.trackers.length)); } // 磁力预览节点:pics.magnetq.com 的图片预览页 chips.appendChild(h('a', { class: 'chip', href: magnetqPreviewUrl(info), target: '_blank', rel: 'noopener noreferrer', title: '在 pics.magnetq.com 查看该资源的图片预览页' }, CONTENT_SOURCES.magnetq + ' ↗')); var infoBox = h('div', { class: 'info' }, chips); var moreSites = buildMoreSites(info); if (moreSites) infoBox.appendChild(moreSites); var gallery = h('div', { class: 'gallery' }); var galleryInfo = h('span', { class: 'dim' }); var galleryHint = h('div', { class: 'gallery-hint', hidden: true }); var gallerySection = h('div', { class: 'section', hidden: true }, h('div', { class: 'section-head' }, h('span', {}, '内容预览'), galleryInfo), galleryHint, gallery ); var filesBox = h('div', { class: 'files' }); var filesInfo = h('span', { class: 'dim' }); var filesNote = h('div', { class: 'files-note', hidden: true }); var filesSection = h('div', { class: 'section', hidden: true }, h('div', { class: 'section-head' }, h('span', {}, '文件列表'), filesInfo), filesBox, filesNote ); var body = h('div', { class: 'body' }, infoBox, gallerySection, filesSection); var status = h('div', { class: 'status', hidden: true }); var copyBtn = h('button', { type: 'button', class: 'btn primary', onClick: function (e) { copyText(info.raw).then(function (ok) { flashLabel(e.currentTarget, ok ? '已复制' : '复制失败'); }); } }, '复制磁力'); var openBtn = h('button', { type: 'button', class: 'btn ghost', onClick: function () { var a = document.createElement('a'); a.href = info.raw; a.rel = 'noopener'; a.style.display = 'none'; document.body.appendChild(a); a.click(); a.remove(); } }, '打开链接'); var scanBtn = h('button', { type: 'button', class: 'btn ghost', onClick: function () { if (s.scanning) cancelContentScan(s); else startContentScan(s); } }, '扫描内容'); var actions = h('div', { class: 'actions' }, copyBtn, openBtn, scanBtn); var foot = h('div', { class: 'foot' }, status, actions); hashChip.addEventListener('click', function () { copyText(info.hashHex).then(function (ok) { flashLabel(hashChip, ok ? '已复制哈希' : '复制失败'); }); }); var closeBtn = h('button', { type: 'button', class: 'icon-btn', title: '关闭', 'aria-label': '关闭', onClick: closePopover }, '×'); var head = h('div', { class: 'head' }, h('div', { class: 'head-main' }, title, sub), closeBtn ); s.refs = { title: title, sizeChip: sizeChip, chips: chips, gallery: gallery, gallerySection: gallerySection, galleryInfo: galleryInfo, galleryHint: galleryHint, galleryCount: 0, filesSection: filesSection, filesBox: filesBox, filesInfo: filesInfo, filesNote: filesNote, status: status, scanBtn: scanBtn }; pop.replaceChildren(head, body, foot); } function positionPopover() { if (!state.open || !pop) return; var anchor = state.anchor; // 页面重渲染可能移除原链接,此时保持弹层当前位置,不强行关闭 if (!anchor || !anchor.isConnected) return; var anchorRect = anchor.getBoundingClientRect(); var rect = pop.getBoundingClientRect(); var margin = 8; var gap = 8; var vw = window.innerWidth; var vh = window.innerHeight; var left = Math.min(Math.max(margin, anchorRect.left), Math.max(margin, vw - rect.width - margin)); var top = anchorRect.bottom + gap; if (top + rect.height > vh - margin) { var above = anchorRect.top - rect.height - gap; top = above >= margin ? above : anchorRect.top; } // 锚点滚出视口时也把弹层限制在可视区域内 top = Math.min(Math.max(margin, top), Math.max(margin, vh - rect.height - margin)); pop.style.left = Math.round(left) + 'px'; pop.style.top = Math.round(top) + 'px'; } function openPopover(info, anchor, badge) { ensureUI(); if (!anchor || !anchor.isConnected) return; if (state.open && state.anchor === anchor && state.info && state.info.hash === info.hash) return; closePopover(); var s = { info: info, anchor: anchor, badge: badge, reqId: ++reqSeq, scanning: false, scanToken: 0, client: null, objectUrls: [], autoScanTimer: null, refs: null }; state = s; state.open = true; if (badge) badge.classList.add('mgp-active'); buildPopover(s); pop.hidden = false; pop.classList.remove('show'); pop.style.visibility = 'hidden'; positionPopover(); pop.style.visibility = ''; // 立即显示,避免后台标签页 rAF 被节流时弹层停留在 opacity:0 pop.classList.add('show'); requestAnimationFrame(function () { if (isActive(s)) positionPopover(); }); loadContentPreview(s); if (shouldAutoScan()) { // 点击“预览”打开后自动开始扫描;可在油猴菜单中按全局/站点关闭 s.autoScanTimer = setTimeout(function () { s.autoScanTimer = null; if (isActive(s)) startContentScan(s); }, 60); } else { setStatus(s, '已关闭自动 P2P 扫描;点“扫描内容”手动开始(WebRTC 会暴露本机 IP)'); s.refs.galleryHint.textContent = '自动 P2P 已关闭;额外截图需点“扫描内容”手动开始。'; s.refs.galleryHint.hidden = false; } } function closePopover() { if (!state.open) return; if (state.badge) state.badge.classList.remove('mgp-active'); stopTorrent(state); state.open = false; state.reqId = ++reqSeq; if (pop) { pop.classList.remove('show'); pop.hidden = true; } } var preconnectDone = false; function preconnectPreviewHosts() { if (preconnectDone) return; preconnectDone = true; ['https://whatslink.info', 'https://wuwuwu.makifx.com'].forEach(function (url) { try { var link = document.createElement('link'); link.rel = 'preconnect'; link.href = url; (document.head || document.documentElement).appendChild(link); } catch (e) { /* ignore */ } }); } function loadContentPreview(s) { preconnectPreviewHosts(); var key = String(s.info.hashHex || s.info.hash).toLowerCase(); var cached = readContentCache(key); if (cached !== undefined) { if (cached) applyContentData(s, cached); return; } var promise = inflightContent.get(key); if (!promise) { promise = resolveContentData(s.info).finally(function () { inflightContent.delete(key); }); inflightContent.set(key, promise); } promise.then(function (data) { if (data) writeContentCache(key, data); if (!isActive(s) || !data) return; applyContentData(s, data); }).catch(function () { /* 节点不可用时静默失败 */ }); } function applyContentData(s, data) { if (!isActive(s) || !s.refs || !data) return; var refs = s.refs; if (data.size > 0) { refs.sizeChip.textContent = '大小 ' + fmtBytes(data.size); refs.sizeChip.title = '资源索引大小(来源:' + (data.source || '预览节点') + ')'; } if (!s.info.dn && data.name) { refs.title.textContent = data.name; refs.title.title = data.name; } if (!s.contentChipsAdded) { if (data.count > 0) { refs.chips.appendChild(h('span', { class: 'chip mgp-content-chip' }, data.count + ' 个文件')); } var typeLabel = FILE_TYPE_LABELS[String(data.fileType || '').toLowerCase()]; if (!typeLabel && data.type) { var type = String(data.type).toLowerCase(); if (type === 'folder') typeLabel = '文件夹'; else if (type === 'video') typeLabel = '视频'; } if (typeLabel) { refs.chips.appendChild(h('span', { class: 'chip mgp-content-chip' }, typeLabel)); } s.contentChipsAdded = true; } if (data.screenshots && data.screenshots.length) { var sourceLabel = data.source || '预览节点'; addGalleryItems(s, data.screenshots.map(function (item) { return { url: item.screenshot, label: sourceLabel + ' 内容截图', tag: item.time > 0 ? fmtTime(item.time) : sourceLabel }; })); } } function addGalleryItems(s, items) { if (!isActive(s) || !items.length) return; var refs = s.refs; refs.gallerySection.hidden = false; items.forEach(function (item) { var index = refs.galleryCount; var img = h('img', { src: item.url, alt: '', referrerpolicy: 'no-referrer', loading: index < 3 ? 'eager' : 'lazy', decoding: 'async' }); if (index === 0) { try { img.setAttribute('fetchpriority', 'high'); } catch (e) {} } var link = h('a', { class: 'shot' + (item.sourceKind === 'torrent' ? ' mgp-torrent-thumb' : ''), href: item.url, target: '_blank', rel: 'noopener noreferrer', title: item.label || '' }, img, item.tag ? h('span', { class: 'tag' }, item.tag) : null ); refs.gallery.appendChild(link); refs.galleryCount++; }); refs.galleryInfo.textContent = refs.galleryCount + ' 张'; } /* ============================== WebTorrent 内容预览 ============================== */ function injectScript(src) { return new Promise(function (resolve, reject) { var script = document.createElement('script'); var done = false; var timer = setTimeout(function () { finish(new Error('加载预览组件超时')); }, 15000); function finish(err) { if (done) return; done = true; clearTimeout(timer); script.onload = script.onerror = null; if (err) { script.remove(); reject(err); } else { resolve(); } } script.src = src; script.async = true; script.onload = function () { finish(); }; script.onerror = function () { finish(new Error('加载预览组件失败')); }; (document.head || document.documentElement).appendChild(script); }); } function loadWebTorrent() { if (wtPromise) return wtPromise; wtPromise = (function () { var chain = Promise.resolve(); if (pageWin.WebTorrent) return Promise.resolve(pageWin.WebTorrent); CONFIG.wtCdns.forEach(function (url) { chain = chain.then(function () { if (pageWin.WebTorrent) return null; return injectScript(url).catch(function () { return null; }); }); }); chain = chain.then(function () { if (pageWin.WebTorrent) return pageWin.WebTorrent; return null; }); return chain.then(function (WT) { if (WT) return WT; return fetchText(CONFIG.wtCdns[0], 25000).then(function (code) { try { pageWin.eval(code); } catch (e) { /* CSP 可能拦截 */ } if (pageWin.WebTorrent) return pageWin.WebTorrent; throw new Error('无法加载内容预览组件,可能被当前网站的 CSP 拦截'); }); }); })(); wtPromise.catch(function () { wtPromise = null; }); return wtPromise; } function addTorrent(client, magnet, timeout, onTorrent) { return new Promise(function (resolve, reject) { var settled = false; var timer = setTimeout(function () { if (settled) return; settled = true; reject(new Error('获取种子元数据超时')); }, timeout); function fail(err) { if (settled) return; settled = true; clearTimeout(timer); reject(err || new Error('获取种子元数据失败')); } var torrent; try { torrent = client.add(magnet, { announce: CONFIG.extraTrackers }, function (t) { if (settled) return; settled = true; clearTimeout(timer); resolve(t); }); } catch (e) { fail(e); return; } if (torrent) { if (typeof onTorrent === 'function') { try { onTorrent(torrent); } catch (e) { /* ignore */ } } if (typeof torrent.on === 'function') torrent.on('error', fail); } }); } function startPeerMonitor(s, token) { stopPeerMonitor(s); function tick() { if (!s || !isActive(s) || s.scanToken !== token || !s.scanning) { stopPeerMonitor(s); return; } var peers = 0; try { peers = Number(s.scanTorrent && s.scanTorrent.numPeers) || 0; } catch (e) {} s.peerTicks = (s.peerTicks || 0) + 1; setStatus(s, '正在连接节点并获取种子元数据…已发现 ' + peers + ' 个节点', true); if (peers === 0 && s.peerTicks >= 8 && s.refs.galleryHint && !s.refs.galleryHint.hidden) { s.refs.galleryHint.textContent = '暂未发现 WebRTC 节点;可继续等待,或点“取消扫描”停止。'; } } tick(); s.peerTimer = setInterval(tick, 1000); } function stopPeerMonitor(s) { if (s && s.peerTimer) { clearInterval(s.peerTimer); s.peerTimer = null; } } function stopTorrent(s) { if (!s) return; stopPeerMonitor(s); s.scanToken++; s.scanning = false; if (s.autoScanTimer) { clearTimeout(s.autoScanTimer); s.autoScanTimer = null; } if (s.client) { try { s.client.destroy(); } catch (e) {} s.client = null; } s.scanTorrent = null; s.peerTicks = 0; (s.objectUrls || []).forEach(function (url) { if (url && url.indexOf('blob:') === 0) { try { URL.revokeObjectURL(url); } catch (e) {} } }); s.objectUrls = []; } function resetContentPreview(s) { if (!s || !s.refs) return; var refs = s.refs; // 只清理上一次 WebTorrent 扫描生成的缩略图,保留 whatslink/呜呜呜 节点截图 var oldThumbs = refs.gallery.querySelectorAll('.mgp-torrent-thumb'); for (var i = 0; i < oldThumbs.length; i++) oldThumbs[i].remove(); refs.galleryCount = refs.gallery.querySelectorAll('.shot').length; refs.galleryInfo.textContent = refs.galleryCount ? refs.galleryCount + ' 张' : ''; if (refs.galleryHint) { refs.galleryHint.hidden = true; refs.galleryHint.textContent = ''; } refs.gallerySection.hidden = refs.galleryCount === 0; refs.filesBox.replaceChildren(); refs.filesInfo.textContent = ''; refs.filesSection.hidden = true; refs.filesNote.hidden = true; s.filesSource = null; } function startContentScan(s) { if (!isActive(s) || s.scanning) return; // 结束上一轮客户端;节点截图保留,种子缩略图由 reset 清理 stopTorrent(s); s.scanning = true; var token = s.scanToken; resetContentPreview(s); s.refs.scanBtn.disabled = false; s.refs.scanBtn.textContent = '取消扫描'; s.refs.galleryHint.textContent = 'whatslink 固定最多 5 张;正在连接 WebRTC 节点补图(会暴露本机 IP)…'; s.refs.galleryHint.hidden = false; setStatus(s, '正在加载内容预览组件…', true); var client = null; loadWebTorrent() .then(function (lib) { if (!isActive(s) || s.scanToken !== token) throw new Error('已取消'); setStatus(s, '正在连接节点并获取种子元数据(仅支持 WebRTC 节点,可能需要等待)…', true); client = new lib({ tracker: { rtcConfig: { iceServers: [ { urls: 'stun:stun.l.google.com:19302' }, { urls: 'stun:stun.cloudflare.com:3478' } ] } } }); s.client = client; client.on('error', function (err) { if (typeof console !== 'undefined') console.warn('[磁力预览]', err); }); return addTorrent(client, buildMagnet(s.info), CONFIG.torrentTimeout, function (torrent) { s.scanTorrent = torrent; s.peerTicks = 0; startPeerMonitor(s, token); }); }) .then(function (torrent) { if (!isActive(s) || s.scanToken !== token) throw new Error('已取消'); stopPeerMonitor(s); renderTorrentFiles(s, torrent); setStatus(s, '已获取种子信息,正在尝试生成内容预览图…', true); return generateContentThumbs(s, torrent, token); }) .then(function (added) { if (!isActive(s) || s.scanToken !== token) return; if (added > 0) { s.refs.galleryHint.hidden = true; setStatus(s, '内容扫描完成,新增 ' + added + ' 张预览图'); } else { s.refs.galleryHint.textContent = 'whatslink 固定最多 5 张;未能从种子生成额外截图(可能无图片/视频或节点不足)。可点“重新扫描”重试。'; s.refs.galleryHint.hidden = false; setStatus(s, '已获取文件列表,但未能生成额外预览图(可能缺少 WebRTC 节点或格式不支持)'); } }) .catch(function (err) { stopPeerMonitor(s); if (!isActive(s) || s.scanToken !== token) return null; // 已有 WebTorrent 文件列表时保留它,不要用缓存列表覆盖 if (s.filesSource === 'webtorrent') { s.refs.galleryHint.textContent = '已获取种子文件列表,但生成额外截图时出错;索引节点截图仍保留。'; s.refs.galleryHint.hidden = false; setStatus(s, friendlyScanError(err), false, true); return null; } // WebRTC 不可用时,尝试 itorrents 的 BT 缓存补全文件列表 return fetchItorrentsFiles(s.info).then(function (data) { if (!isActive(s) || s.scanToken !== token) return; if (data) { renderTorrentFiles(s, { files: data.files, length: data.total }, 'cache'); s.refs.galleryHint.textContent = 'WebRTC 未连接,当前只有索引节点的 5 张截图;文件列表来自 itorrents 缓存。'; s.refs.galleryHint.hidden = false; setStatus(s, 'WebRTC 未连接,已从 itorrents 缓存获取文件列表;无法生成种子内缩略图'); } else { s.refs.galleryHint.textContent = 'whatslink 固定最多 5 张;未能连接种子节点,无法生成更多截图。可点“重新扫描”重试。'; s.refs.galleryHint.hidden = false; setStatus(s, friendlyScanError(err), false, true); } }); }) .finally(function () { stopPeerMonitor(s); if (client && s.client === client) { try { client.destroy(); } catch (e) {} s.client = null; } s.scanTorrent = null; if (s.scanToken !== token || !isActive(s)) return; s.scanning = false; s.refs.scanBtn.disabled = false; s.refs.scanBtn.textContent = '重新扫描'; }); } function cancelContentScan(s) { if (!s || !s.scanning) return; stopTorrent(s); resetContentPreview(s); s.refs.scanBtn.disabled = false; s.refs.scanBtn.textContent = '重新扫描'; setStatus(s, '已取消扫描'); s.refs.galleryHint.textContent = '扫描已取消;当前显示已有截图。'; s.refs.galleryHint.hidden = false; } function friendlyScanError(err) { var msg = (err && err.message) ? err.message : String(err); if (msg === '已取消') return '已取消扫描'; if (/超时/.test(msg)) { return '获取种子元数据超时:该资源当前没有可用的 WebRTC 节点,或节点响应过慢,请稍后重试。'; } return '内容预览失败:' + msg; } function renderTorrentFiles(s, torrent, source) { var files = (torrent.files || []).slice().sort(function (a, b) { return (b.length || 0) - (a.length || 0); }); var total = Number(torrent.length) || files.reduce(function (n, f) { return n + (f.length || 0); }, 0); var top = files.slice(0, 12); s.filesSource = source || 'webtorrent'; if ((!s.info.size || source === 'cache') && total) { s.refs.sizeChip.textContent = '大小 ' + fmtBytes(total); } s.refs.filesInfo.textContent = files.length + ' 个文件' + (total ? ' · ' + fmtBytes(total) : ''); s.refs.filesBox.replaceChildren.apply(s.refs.filesBox, top.map(function (f) { return h('div', { class: 'file' }, h('span', { class: 'fname', title: f.path || f.name }, f.path || f.name), h('span', { class: 'fsize' }, fmtBytes(f.length)) ); })); if (source === 'cache') { var note = h('span', {}, '文件列表来自 '); note.appendChild(h('a', { href: itorrentsTorrentUrl(s.info), target: '_blank', rel: 'noopener noreferrer' }, 'itorrents 缓存')); note.appendChild(document.createTextNode(' · 点击下载 .torrent')); if (files.length > top.length) { note.appendChild(document.createTextNode(' · 仅显示最大的 ' + top.length + ' 个文件')); } s.refs.filesNote.replaceChildren(note); s.refs.filesNote.hidden = false; } else if (files.length > top.length) { s.refs.filesNote.textContent = '仅显示最大的 ' + top.length + ' 个文件'; s.refs.filesNote.hidden = false; } s.refs.filesSection.hidden = false; } function isImageFile(file) { return /\.(jpe?g|png|webp|gif|bmp)$/i.test(file.name || '') && file.length > 8 * 1024 && file.length < 5 * 1024 * 1024; } function isVideoFile(file) { return /\.(mp4|m4v|webm)$/i.test(file.name || '') && file.length > 300 * 1024 && file.length < 2 * 1024 * 1024 * 1024; } function runPool(tasks, limit, worker) { return new Promise(function (resolve) { var index = 0; var active = 0; var done = 0; if (!tasks.length) { resolve(); return; } function launch() { while (active < limit && index < tasks.length) { (function (task) { active++; Promise.resolve().then(function () { return worker(task); }).catch(function (err) { if (typeof console !== 'undefined') console.warn('[磁力预览] 生成预览图失败', err); }).finally(function () { active--; done++; if (done === tasks.length) resolve(); else launch(); }); })(tasks[index++]); } } launch(); }); } function generateContentThumbs(s, torrent, token) { var files = torrent.files || []; // 小图优先,先出几张;最多 6 张图片 + 其余用视频截帧,总数不超过 12 var images = files.filter(isImageFile).sort(function (a, b) { return a.length - b.length; }).slice(0, 6); var videos = files.filter(isVideoFile).sort(function (a, b) { return a.length - b.length; }).slice(0, 2); var tasks = images.map(function (file) { return { kind: 'image', file: file }; }); var remaining = Math.max(0, 12 - tasks.length); videos.forEach(function (file, index) { if (remaining <= 0) return; var count = videos.length > 1 && index === 0 ? Math.ceil(remaining * 0.6) : remaining; count = Math.min(6, count, remaining); var fractions = []; for (var i = 1; i <= count; i++) fractions.push(i / (count + 1)); tasks.push({ kind: 'video', file: file, fractions: fractions }); remaining -= count; }); if (!tasks.length) return Promise.resolve(0); var added = 0; function addThumb(item) { if (!isActive(s) || s.scanToken !== token) { if (item.url && item.url.indexOf('blob:') === 0) URL.revokeObjectURL(item.url); return; } s.objectUrls.push(item.url); addGalleryItems(s, [item]); added++; setStatus(s, '正在并发生成预览图…已新增 ' + added + ' 张', true); } setStatus(s, '已获取种子信息,正在并发生成内容预览图…', true); return runPool(tasks, 3, function (task) { if (!isActive(s) || s.scanToken !== token) return Promise.resolve(); if (task.kind === 'image') { return downloadFileUrl(task.file, CONFIG.fileTimeout).then(function (url) { if (!url) return; addThumb({ url: url, label: task.file.name, tag: '内容图', sourceKind: 'torrent' }); }); } return captureVideoFrames(task.file, task.fractions, function (frame) { addThumb({ url: frame.url, label: task.file.name, tag: frame.time ? fmtTime(frame.time) : '视频截帧', sourceKind: 'torrent' }); }); }).then(function () { return added; }); } function downloadFileUrl(file, timeout) { return new Promise(function (resolve, reject) { var settled = false; var timer = setTimeout(function () { finish(new Error('下载预览图超时')); }, timeout); function finish(err, url) { if (settled) return; settled = true; clearTimeout(timer); try { if (file.removeListener) file.removeListener('done', onDone); } catch (e) {} try { if (file.removeListener) file.removeListener('error', onError); } catch (e) {} try { if (file.deselect) file.deselect(); } catch (e) {} if (err) reject(err); else resolve(url); } function onDone() { try { var maybe = file.getBlobURL(function (err, url) { finish(err, url); }); if (maybe && typeof maybe.then === 'function') { maybe.then(function (url) { finish(null, url); }, function (err) { finish(err); }); } } catch (e) { finish(e); } } function onError(err) { finish(err || new Error('下载预览图失败')); } file.once('done', onDone); file.once('error', onError); try { file.select(); } catch (e) { finish(e); } }); } function grabVideoFrame(video) { var w = video.videoWidth; var hh = video.videoHeight; if (!w || !hh) return Promise.reject(new Error('未能读取视频画面')); var scale = Math.min(1, 480 / w); var canvas = document.createElement('canvas'); canvas.width = Math.max(1, Math.round(w * scale)); canvas.height = Math.max(1, Math.round(hh * scale)); canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height); return new Promise(function (resolve, reject) { canvas.toBlob(function (blob) { if (!blob) reject(new Error('生成视频截帧失败')); else resolve(blob); }, 'image/jpeg', 0.76); }); } function seekVideo(video, time) { if (Math.abs((Number(video.currentTime) || 0) - time) < 0.15) return Promise.resolve(); var seeked = waitEvent(video, 'seeked', 10000); video.currentTime = time; return seeked; } // 同一个视频只建立一次流,连续 seek 抓取多帧,避免每帧重新加载 function captureVideoFrames(file, fractions, onFrame) { var video = document.createElement('video'); video.muted = true; video.playsInline = true; video.preload = 'auto'; video.style.cssText = 'position:fixed;left:-10000px;top:0;width:2px;height:2px;opacity:0;pointer-events:none;'; document.body.appendChild(video); // 先挂 loadeddata 监听,再开始 streamTo,避免事件早于监听 var loaded = waitEvent(video, 'loadeddata', 16000); try { if (typeof file.streamTo !== 'function') throw new Error('当前预览组件不支持视频流'); file.streamTo(video); } catch (e) { video.remove(); return Promise.reject(e); } return loaded.then(function () { var duration = Number(video.duration); var times = []; if (isFinite(duration) && duration > 2) { (fractions && fractions.length ? fractions : [0.12]).forEach(function (fraction) { var ratio = Number(fraction); if (!isFinite(ratio) || ratio <= 0) return; var time = Math.min(Math.max(duration * ratio, 0.5), duration - 0.2); var duplicate = times.some(function (existing) { return Math.abs(existing - time) < 0.25; }); if (!duplicate) times.push(time); }); } else { times = [Number(video.currentTime) || 0]; } var results = []; var chain = Promise.resolve(); times.forEach(function (time) { chain = chain.then(function () { return seekVideo(video, time).then(function () { return grabVideoFrame(video).then(function (blob) { var frame = { url: URL.createObjectURL(blob), time: Number(video.currentTime) || time }; results.push(frame); if (typeof onFrame === 'function') { try { onFrame(frame); } catch (e) { /* ignore */ } } }); }).catch(function (err) { if (typeof console !== 'undefined') console.warn('[磁力预览] 视频截帧失败', err); }); }); }); return chain.then(function () { return results; }); }).finally(function () { try { video.pause(); video.removeAttribute('src'); video.load(); } catch (e) {} video.remove(); try { if (file.deselect) file.deselect(); } catch (e) {} }); } /* ============================== 链接识别 ============================== */ var MAGNET_TEXT_RE = /magnet:\?[^\s"'<>`\\]+/gi; var IGNORED_TAGS = /^(SCRIPT|STYLE|NOSCRIPT|TEXTAREA|INPUT|SELECT|OPTION|BUTTON|TITLE|VIDEO|AUDIO|CANVAS|SVG|IFRAME|PRE|CODE)$/; /* ============================== 百家姓加密磁力 ============================== */ // 常见“百家姓加密”映射:姓 -> Base64/URL 字符。兼容标准写法“柏”和部分工具使用的“福”。 var BJX_MAP = { '赵': '0', '钱': '1', '孙': '2', '李': '3', '周': '4', '吴': '5', '郑': '6', '王': '7', '冯': '8', '陈': '9', '褚': 'a', '卫': 'b', '蒋': 'c', '沈': 'd', '韩': 'e', '杨': 'f', '朱': 'g', '秦': 'h', '尤': 'i', '许': 'j', '何': 'k', '吕': 'l', '施': 'm', '张': 'n', '孔': 'o', '曹': 'p', '严': 'q', '华': 'r', '金': 's', '魏': 't', '陶': 'u', '姜': 'v', '戚': 'w', '谢': 'x', '邹': 'y', '喻': 'z', '福': 'A', '柏': 'A', '水': 'B', '窦': 'C', '章': 'D', '云': 'E', '苏': 'F', '潘': 'G', '葛': 'H', '奚': 'I', '范': 'J', '彭': 'K', '郎': 'L', '鲁': 'M', '韦': 'N', '昌': 'O', '马': 'P', '苗': 'Q', '凤': 'R', '花': 'S', '方': 'T', '俞': 'U', '任': 'V', '袁': 'W', '柳': 'X', '唐': 'Y', '罗': 'Z', '薛': '.', '伍': '-', '余': '_', '米': '+', '贝': '=', '姚': '/', '孟': '?', '顾': '#', '尹': '%', '江': '&', '钟': '*' }; var BJX_CHARS = Object.keys(BJX_MAP).join(''); var BJX_RUN_RE = new RegExp('[' + BJX_CHARS + ']{32,}', 'g'); function bjxDecodeToken(token) { if (!token || token.length < 32) return null; var raw = ''; for (var i = 0; i < token.length; i++) { var val = BJX_MAP[token.charAt(i)]; if (val === undefined) return null; raw += val; } // 严格校验哈希,避免把普通“百家姓”文本误判成磁力 var hashPart = raw.split('&')[0]; var isHex = /^[0-9a-f]{40}$/i.test(hashPart); var isBase32 = /^[A-Z2-7]{32}$/.test(hashPart.toUpperCase()); if (!isHex && !isBase32) return null; var magnet = 'magnet:?xt=urn:btih:' + raw; var info = parseMagnet(magnet); if (!info) return null; return { magnet: magnet, info: info }; } function bjxFindMatches(text) { if (!text || text.length < 32) return []; var matches = []; BJX_RUN_RE.lastIndex = 0; var m; while ((m = BJX_RUN_RE.exec(text)) !== null) { var decoded = bjxDecodeToken(m[0]); if (decoded) { matches.push({ start: m.index, end: m.index + m[0].length, token: m[0], magnet: decoded.magnet, info: decoded.info }); } } BJX_RUN_RE.lastIndex = 0; return matches; } function bjxHasRun(text) { if (!text || text.length < 32) return false; BJX_RUN_RE.lastIndex = 0; var ok = BJX_RUN_RE.test(text); BJX_RUN_RE.lastIndex = 0; return ok; } function wrapBaiJiaXingText(node) { if (!node || node.nodeType !== 3) return false; if (autoLinkCount >= CONFIG.maxTextLinks) return false; var text = node.nodeValue; if (!text || text.length < 32 || text.length > 50000) return false; var parent = node.parentElement; if (!parent || isIgnoredElement(parent)) return false; var matches = bjxFindMatches(text); if (!matches.length) return false; var frag = document.createDocumentFragment(); var fresh = []; var cursor = 0; for (var i = 0; i < matches.length; i++) { if (autoLinkCount >= CONFIG.maxTextLinks) break; var item = matches[i]; if (item.start > cursor) frag.appendChild(document.createTextNode(text.slice(cursor, item.start))); var a = document.createElement('a'); a.href = item.magnet; a.className = 'mgp-auto-link mgp-bjx-link'; a.textContent = item.token; a.title = '百家姓加密磁力,已自动转换为磁力链接'; a.dataset.mgpBjx = '1'; frag.appendChild(a); fresh.push(a); cursor = item.end; autoLinkCount++; } if (cursor < text.length) frag.appendChild(document.createTextNode(text.slice(cursor))); if (!fresh.length) return false; parent.replaceChild(frag, node); fresh.forEach(enhanceAnchor); return true; } function isIgnoredElement(el) { if (!el || el.nodeType !== 1) return true; if (el.namespaceURI && el.namespaceURI !== 'http://www.w3.org/1999/xhtml') return true; if (el.closest('#mgp-host-root')) return true; if (IGNORED_TAGS.test(el.tagName)) return true; if (el.isContentEditable) return true; if (el.closest('a')) return true; return false; } function trimMagnetText(text) { return String(text).replace(/[)\]}>】》”’"',.;:!?,。;:!?、]+$/g, ''); } function createBadge(info, anchor) { var badge = document.createElement('span'); badge.className = 'mgp-badge'; badge.setAttribute('role', 'button'); badge.setAttribute('tabindex', '0'); badge.setAttribute('aria-label', '预览磁力资源'); badge.setAttribute('title', '预览磁力资源'); badge.draggable = false; badge.innerHTML = BADGE_HTML; function currentInfo() { return parseMagnet(anchor.getAttribute('href') || '') || info; } function toggle() { // 点击时提前加载 WebTorrent 组件,与截图接口并行,减少首次出图等待 if (shouldAutoScan()) { try { loadWebTorrent().catch(function () {}); } catch (e) {} } if (state.open && state.anchor === anchor) closePopover(); else openPopover(currentInfo(), anchor, badge); } badge.addEventListener('click', function (e) { e.preventDefault(); e.stopPropagation(); toggle(); }); badge.addEventListener('keydown', function (e) { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); toggle(); } }); return badge; } function magnetKey(info) { return String((info && (info.hashHex || info.hash)) || '').toLowerCase(); } function isAnchorVisible(anchor) { if (!anchor || !anchor.isConnected) return false; try { if (typeof anchor.checkVisibility === 'function') { return anchor.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true }); } } catch (e) { /* ignore */ } return anchor.getClientRects().length > 0; } function releaseBadgeOwner(key, entry) { enhancedMagnets.delete(key); if (entry.badge && entry.badge.isConnected) entry.badge.remove(); if (entry.anchor) { delete entry.anchor.dataset.mgpDone; delete entry.anchor.dataset.mgpBjxDone; } } function enhanceAnchor(anchor) { if (!anchor || anchor.nodeType !== 1) return; if (anchor.namespaceURI && anchor.namespaceURI !== 'http://www.w3.org/1999/xhtml') return; if (anchor.closest('#mgp-host-root')) return; if (anchor.isContentEditable) return; var href = anchor.getAttribute('href') || ''; var magnetHref = /^magnet:\?/i.test(href.trim()); var doneMark = magnetHref ? 'mgpDone' : 'mgpBjxDone'; if (anchor.dataset[doneMark] === '1') return; var info = null; if (magnetHref) { info = parseMagnet(href); } else { // 已有普通链接的文字如果是百家姓暗号,在旁边补一个预览按钮 var bjxMatches = bjxFindMatches(anchor.textContent || ''); if (bjxMatches.length) info = bjxMatches[0].info; } if (!info) return; // 同一磁力可能在页面多个位置出现(如磁力表格的多行),只保留一个预览按钮; // 已保留的位置隐藏或已被移除时,交给当前可见的位置 var key = magnetKey(info); var owner = key ? enhancedMagnets.get(key) : null; if (owner) { if (owner.anchor === anchor) { anchor.dataset[doneMark] = '1'; return; } var ownerValid = owner.anchor && owner.anchor.isConnected && owner.badge && owner.badge.isConnected; if (ownerValid && (isAnchorVisible(owner.anchor) || !isAnchorVisible(anchor))) return; releaseBadgeOwner(key, owner); } anchor.dataset[doneMark] = '1'; var badge = createBadge(info, anchor); var display = ''; try { display = getComputedStyle(anchor).display || ''; } catch (e) { display = ''; } if (/^inline/.test(display) || display === 'contents' || !display) { anchor.insertAdjacentElement('afterend', badge); } else { var pos = ''; try { pos = getComputedStyle(anchor).position; } catch (e) { pos = ''; } if (pos === 'static' || !pos) anchor.style.position = 'relative'; badge.classList.add('mgp-badge-corner'); anchor.appendChild(badge); } if (key) enhancedMagnets.set(key, { anchor: anchor, badge: badge }); } function wrapTextNode(node) { if (!node || node.nodeType !== 3) return; if (autoLinkCount >= CONFIG.maxTextLinks) return; var text = node.nodeValue; if (!text || text.length > 50000) return; var parent = node.parentElement; if (!parent || isIgnoredElement(parent)) return; // 没有 magnet 前缀时,尝试识别百家姓暗号 if (text.indexOf('magnet:') === -1) { wrapBaiJiaXingText(node); return; } MAGNET_TEXT_RE.lastIndex = 0; var matches = []; var m; while ((m = MAGNET_TEXT_RE.exec(text)) !== null) { var candidate = trimMagnetText(m[0]); var info = parseMagnet(candidate); if (info) matches.push({ start: m.index, end: m.index + candidate.length, raw: candidate }); if (autoLinkCount + matches.length >= CONFIG.maxTextLinks) break; } if (!matches.length) { wrapBaiJiaXingText(node); return; } var frag = document.createDocumentFragment(); var fresh = []; var cursor = 0; matches.forEach(function (item) { if (item.start > cursor) frag.appendChild(document.createTextNode(text.slice(cursor, item.start))); var a = document.createElement('a'); a.href = item.raw; a.className = 'mgp-auto-link'; a.textContent = item.raw; frag.appendChild(a); fresh.push(a); cursor = item.end; autoLinkCount++; }); if (cursor < text.length) frag.appendChild(document.createTextNode(text.slice(cursor))); parent.replaceChild(frag, node); // 新生成的链接立即增强,避免等待下一轮扫描 fresh.forEach(enhanceAnchor); } function scanRoot(root) { if (!root) return; if (root.nodeType === 3) { wrapTextNode(root); return; } if (root.nodeType !== 1) return; if (root.closest && root.closest('#mgp-host-root')) return; if (root.matches && root.matches('a[href]')) enhanceAnchor(root); var anchors = root.querySelectorAll ? root.querySelectorAll('a[href]') : []; for (var i = 0; i < anchors.length; i++) enhanceAnchor(anchors[i]); if (autoLinkCount >= CONFIG.maxTextLinks) return; var walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, { acceptNode: function (node) { var value = node.nodeValue; if (!value || value.length < 32) return NodeFilter.FILTER_REJECT; if (value.indexOf('magnet:') === -1 && !bjxHasRun(value)) return NodeFilter.FILTER_REJECT; var parent = node.parentElement; if (!parent || isIgnoredElement(parent)) return NodeFilter.FILTER_REJECT; return NodeFilter.FILTER_ACCEPT; } }); var nodes = []; while (walker.nextNode()) { nodes.push(walker.currentNode); if (autoLinkCount + nodes.length >= CONFIG.maxTextLinks) break; } nodes.forEach(wrapTextNode); } function scheduleFlush() { if (flushTimer) return; flushTimer = setTimeout(function () { flushTimer = 0; flushPending(); }, 220); } function flushPending() { if (!pendingRoots.size) return; var roots = Array.from(pendingRoots); pendingRoots.clear(); if (state.open && state.anchor && !state.anchor.isConnected) { // 页面重渲染导致原链接被替换时,保留弹层而不是直接消失 state.anchor = null; state.badge = null; } if (observer) observer.disconnect(); try { for (var i = 0; i < roots.length; i++) { var root = roots[i]; if (!root || !root.isConnected) continue; if (root.nodeType === 1 && root.closest && root.closest('#mgp-host-root')) continue; try { scanRoot(root); } catch (err) { if (typeof console !== 'undefined') console.warn('[磁力预览] 扫描失败', err); } if (autoLinkCount >= CONFIG.maxTextLinks) break; } } finally { observeDom(); } } function observeDom() { if (!observer) { observer = new MutationObserver(function (records) { for (var i = 0; i < records.length; i++) { var record = records[i]; if (record.type === 'characterData') { var target = record.target; if (target && target.nodeType === 3 && target.nodeValue && (target.nodeValue.indexOf('magnet:') !== -1 || bjxHasRun(target.nodeValue))) { pendingRoots.add(target); } continue; } for (var j = 0; j < record.addedNodes.length; j++) { var node = record.addedNodes[j]; if (node.nodeType === 1 || node.nodeType === 3) pendingRoots.add(node); } } if (pendingRoots.size) scheduleFlush(); }); } observer.observe(document, { childList: true, subtree: true, characterData: true }); } /* ============================== 菜单命令 ============================== */ function registerMenus() { if (typeof GM_registerMenuCommand !== 'function') return; GM_registerMenuCommand('磁力预览:清空内容缓存', function () { contentCache = {}; store.set(STORE_KEYS.content, {}); window.alert('已清空磁力预览内容缓存。'); }); GM_registerMenuCommand('磁力预览:自动 P2P 扫描开关(隐私)', function () { var cur = getAutoScanGlobal(); var ok = window.confirm( '当前全局自动 P2P 扫描:' + (cur ? '开启' : '关闭') + '。\n\n' + '点击“确定”切换为' + (cur ? '关闭' : '开启') + '。\n\n' + '注意:WebRTC 会连接种子节点并暴露本机 IP;关闭后仍可在弹层里手动点“扫描内容”。' ); if (!ok) return; store.set(STORE_KEYS.autoScan, !cur); window.alert('已' + (!cur ? '开启' : '关闭') + '全局自动 P2P 扫描;重新打开预览后生效。'); }); GM_registerMenuCommand('磁力预览:本站点自动 P2P 设置', function () { var origin = location.origin; var sites = getAutoScanSites(); var hasSite = Object.prototype.hasOwnProperty.call(sites, origin); var current = hasSite ? (sites[origin] ? '1' : '0') : ''; var value = window.prompt( '本站点:' + origin + '\n\n' + '输入 1 = 自动开启,0 = 自动关闭,留空 = 跟随全局。\n' + '当前全局:' + (getAutoScanGlobal() ? '开启' : '关闭'), current ); if (value === null) return; value = value.trim(); if (value === '') { delete sites[origin]; } else if (value === '1') { sites[origin] = true; } else if (value === '0') { sites[origin] = false; } else { window.alert('请输入 1、0 或留空。'); return; } store.set(STORE_KEYS.autoScanSites, sites); window.alert('已保存本站点设置;重新打开预览后生效。'); }); } /* ============================== 启动 ============================== */ function bindGlobalEvents() { document.addEventListener('pointerdown', function (e) { if (!state.open) return; var path = typeof e.composedPath === 'function' ? e.composedPath() : []; if (path.indexOf(host) !== -1 || path.indexOf(state.badge) !== -1 || path.indexOf(state.anchor) !== -1) return; closePopover(); }, true); document.addEventListener('keydown', function (e) { if (e.key === 'Escape' && state.open) { var badge = state.badge; closePopover(); if (badge && badge.focus) badge.focus(); } }, true); // 页面滚动时跟随锚点重新定位,而不是关闭弹层 var scrollRepositionRaf = 0; window.addEventListener('scroll', function (e) { if (!state.open) return; var target = e.target; if (target === shadow || (target && target.nodeType === 1 && shadow && shadow.contains(target))) return; if (scrollRepositionRaf) return; scrollRepositionRaf = requestAnimationFrame(function () { scrollRepositionRaf = 0; if (state.open) positionPopover(); }); }, true); window.addEventListener('resize', function () { if (state.open) positionPopover(); }, true); } function init() { loadContentCache(); injectPageStyles(); ensureUI(); try { scanRoot(document.body || document.documentElement); } catch (e) { if (typeof console !== 'undefined') console.warn('[磁力预览] 初始化扫描失败', e); } observeDom(); bindGlobalEvents(); registerMenus(); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init, { once: true }); } else { init(); } })();