// ==UserScript== // @name 粘贴即传图 // @namespace https://cnb.cool/IIIStudio/Code/Greasemonkey/ImgNest // @version 0.8.2 // @description Ctrl+V 粘贴图片自动上传图床并回填链接|多图床配置|历史记录|导入导出 // @author IIIStudio // @match *://*/* // @run-at document-idle // @grant GM_xmlhttpRequest // @grant GM_setValue // @grant GM_getValue // @grant GM_registerMenuCommand // @connect p.sda1.dev // @connect dav.jianguoyun.com // @connect img.ink // ==/UserScript== /* * 粘贴即传图(ImgNest) * 作者:IIIStudio * 仓库:https://cnb.cool/IIIStudio/Code/Greasemonkey/ImgNest * AI 辅助开发:Deepseek-V4.1-Flash * * 需要连接新的图床 / WebDAV 域名时,在上面的元数据块里加一行: * // @connect example.com * 保存并刷新页面后生效(支持 *.example.com 通配)。 */ (function () { 'use strict'; /* ========================================================================= * 0. 环境与通用工具 * ========================================================================= */ const VERSION = '0.8.2'; const IS_TOP = (() => { try { return window.top === window.self; } catch (e) { return false; } })(); const HOST = location.hostname; const ZWSP = '\u200b'; const GMXHR = (typeof GM_xmlhttpRequest === 'function') ? GM_xmlhttpRequest : (typeof GM !== 'undefined' && GM && typeof GM.xmlHttpRequest === 'function' ? (details) => GM.xmlHttpRequest(details) : null); const hasGMXHR = typeof GMXHR === 'function'; function gmGet(key, fallback) { try { if (typeof GM_getValue === 'function') { const v = GM_getValue(key); return v === undefined ? fallback : v; } } catch (e) { /* ignore */ } try { const raw = localStorage.getItem(key); return raw === null ? fallback : raw; } catch (e) { /* ignore */ } return fallback; } function gmSet(key, value) { try { if (typeof GM_setValue === 'function') { GM_setValue(key, value); return; } } catch (e) { /* ignore */ } try { localStorage.setItem(key, value); } catch (e) { /* ignore */ } } function uuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = (Math.random() * 16) | 0; const v = c === 'x' ? r : (r & 0x3) | 0x8; return v.toString(16); }); } function escapeHtml(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ( { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c] )); } function fmtBytes(n) { if (!n && n !== 0) return ''; if (n < 1024) return n + ' B'; if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' KB'; return (n / 1024 / 1024).toFixed(2) + ' MB'; } function pad2(n) { return n < 10 ? '0' + n : '' + n; } function fmtTime(ts) { if (!ts) return ''; const d = new Date(ts); return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate()) + ' ' + pad2(d.getHours()) + ':' + pad2(d.getMinutes()); } function debounce(fn, ms) { let t = null; return function () { const args = arguments; clearTimeout(t); t = setTimeout(() => fn.apply(null, args), ms); }; } function node(tag, cls, text) { const el = document.createElement(tag); if (cls) el.className = cls; if (text != null) el.textContent = text; return el; } async function pool(items, limit, worker) { const queue = items.slice(); const n = Math.max(1, Math.min(limit, queue.length)); const runners = []; for (let i = 0; i < n; i++) { runners.push((async function run() { while (queue.length) { const item = queue.shift(); try { await worker(item); } catch (e) { /* worker 内部自行处理 */ } } })()); } await Promise.all(runners); } function download(filename, content, mime) { const blob = content instanceof Blob ? content : new Blob([content], { type: mime || 'application/json;charset=utf-8' }); const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; a.style.display = 'none'; (document.body || document.documentElement).appendChild(a); a.click(); setTimeout(() => { a.remove(); URL.revokeObjectURL(url); }, 2000); } async function copyText(text) { try { if (navigator.clipboard && window.isSecureContext) { await navigator.clipboard.writeText(text); return true; } } catch (e) { /* fallthrough */ } try { const ta = document.createElement('textarea'); ta.value = text; ta.style.cssText = 'position:fixed;top:-1000px;left:-1000px;opacity:0;'; document.body.appendChild(ta); ta.select(); const ok = document.execCommand('copy'); ta.remove(); return ok; } catch (e) { return false; } } // 只接受 http/https 绝对地址,阻断 javascript: / data: 等危险协议 function safeHttpUrl(raw) { const s = String(raw == null ? '' : raw).trim(); if (!s) return ''; try { const u = new URL(s); if (u.protocol === 'http:' || u.protocol === 'https:') return u.href; } catch (e) { /* 非法 URL */ } return ''; } // 合并对象时跳过原型相关的键,防止导入 JSON 造成原型污染 const BLOCKED_KEYS = new Set(['__proto__', 'constructor', 'prototype']); function safeAssign(target) { const out = target || {}; for (let i = 1; i < arguments.length; i++) { const src = arguments[i]; if (!src || typeof src !== 'object') continue; Object.keys(src).forEach((k) => { if (BLOCKED_KEYS.has(k)) return; out[k] = src[k]; }); } return out; } /* ========================================================================= * 1. 配置 * ========================================================================= */ const CONFIG_KEY = 'piu.config'; const RECORDS_KEY = 'piu.records'; const DEFAULT_DAV_FOLDER = 'ImgNest'; const DEFAULT_DAV_FILE = 'piu-backup.json'; const PSDA1_PROVIDER = { id: 'p-sda1', name: '流浪图床', enabled: true, uploadUrl: 'https://p.sda1.dev/api/v1/upload_external_noform', method: 'POST', bodyType: 'binary', // binary | multipart | base64json formField: 'file', query: [{ key: 'filename', value: '{{filename}}' }], headers: {}, withCredentials: false, urlPath: 'data.url', // 支持 data.url / $json:data.url$ / data[0].url urlRegex: '', deleteUrlPath: 'data.delete_url', maxSizeMB: 5, timeoutMs: 30000, retries: 1, }; // 默认只在白名单站点生效:黑名单 * 表示其余站点一律走原生粘贴 const DEFAULT_BLACKLIST = ['*']; const DEFAULT_WHITELIST = ['www.52pojie.cn', 'bbs.tampermonkey.net.cn']; function defaultConfig() { return { schemaVersion: 2, enabled: true, activeProviderId: PSDA1_PROVIDER.id, insertMode: 'url', // url | markdown | bbcode | html autoCopy: false, richTextPassthrough: true, showFab: true, shortcut: 'alt+shift+h', providers: [JSON.parse(JSON.stringify(PSDA1_PROVIDER))], blacklist: DEFAULT_BLACKLIST.slice(), whitelist: DEFAULT_WHITELIST.slice(), siteEnabled: {}, webdav: { url: '', username: '', password: '', folder: DEFAULT_DAV_FOLDER, file: DEFAULT_DAV_FILE, auto: false }, }; } function normalizeWebdav(raw) { return safeAssign({ url: '', username: '', password: '', folder: DEFAULT_DAV_FOLDER, file: DEFAULT_DAV_FILE, auto: false, }, raw || {}); } function normalizeProvider(p) { const base = { id: uuid(), name: '未命名图床', enabled: true, uploadUrl: '', method: 'POST', bodyType: 'binary', formField: 'file', query: [], fields: [], headers: {}, withCredentials: false, urlPath: 'data.url', urlRegex: '', deleteUrlPath: 'data.delete_url', maxSizeMB: 5, timeoutMs: 30000, retries: 1, }; const out = safeAssign(base, p || {}); const sizeMB = Number(out.maxSizeMB); out.maxSizeMB = Number.isFinite(sizeMB) && sizeMB > 0 ? Math.min(sizeMB, 200) : 5; const timeout = Number(out.timeoutMs); out.timeoutMs = Number.isFinite(timeout) && timeout > 0 ? Math.min(Math.max(timeout, 1000), 60000) : 30000; const retries = Number(out.retries); out.retries = Number.isFinite(retries) ? Math.min(Math.max(Math.floor(retries), 0), 5) : 1; if (!Array.isArray(out.query)) out.query = []; if (!Array.isArray(out.fields)) out.fields = []; if (!out.headers || typeof out.headers !== 'object') out.headers = {}; return out; } const state = { config: null, hostEl: null, shadow: null, ui: {}, list: { cursor: null, hasMore: true, loading: false, items: [], filters: { siteHost: '', providerId: '', status: '', q: '' }, observer: null, }, toastSeq: 0, }; function loadConfig() { let raw = null; try { raw = JSON.parse(gmGet(CONFIG_KEY, '') || 'null'); } catch (e) { raw = null; } const cfg = safeAssign(defaultConfig(), raw || {}); if (!Array.isArray(cfg.providers) || !cfg.providers.length) cfg.providers = defaultConfig().providers; cfg.providers = cfg.providers.map(normalizeProvider); if (!cfg.providers.some((p) => p.id === cfg.activeProviderId)) { cfg.activeProviderId = cfg.providers[0].id; } if (!Array.isArray(cfg.blacklist)) cfg.blacklist = []; if (!Array.isArray(cfg.whitelist)) cfg.whitelist = []; if (!cfg.siteEnabled || typeof cfg.siteEnabled !== 'object') cfg.siteEnabled = {}; cfg.webdav = normalizeWebdav(cfg.webdav); return cfg; } function saveConfig() { try { gmSet(CONFIG_KEY, JSON.stringify(state.config)); } catch (e) { console.warn('[粘贴即传图] 配置保存失败', e); } } function activeProvider() { const cfg = state.config; return cfg.providers.find((p) => p.id === cfg.activeProviderId && p.enabled) || cfg.providers.find((p) => p.enabled) || null; } function siteEnabled(host) { const v = state.config.siteEnabled[host]; return v === undefined ? true : !!v; } /* ========================================================================= * 2. 历史记录(脚本级存储,跨站点共享) * 注意:IndexedDB 按域名隔离,各站点互相读不到,因此历史记录必须放在 * GM_setValue 里,才能在任意网站的「全部站点」中看到。 * ========================================================================= */ const MAX_RECORDS = 5000; function readRecords() { try { const arr = JSON.parse(gmGet(RECORDS_KEY, '[]') || '[]'); return Array.isArray(arr) ? arr : []; } catch (e) { return []; } } function writeRecords(arr) { try { gmSet(RECORDS_KEY, JSON.stringify(arr)); } catch (e) { console.warn('[粘贴即传图] 历史记录写入失败', e); } } function sortDesc(arr) { arr.sort((a, b) => (b.createdAt || 0) - (a.createdAt || 0)); return arr; } function matchFilters(r, f) { if (f.siteHost && r.siteHost !== f.siteHost) return false; if (f.providerId && r.providerId !== f.providerId) return false; if (f.status && r.status !== f.status) return false; if (f.q) { const q = f.q.toLowerCase(); const hay = ((r.url || '') + ' ' + (r.filename || '') + ' ' + (r.pageTitle || '')).toLowerCase(); if (hay.indexOf(q) === -1) return false; } return true; } const History = { async add(rec) { const arr = readRecords(); if (!rec.createdAt) { const maxTs = arr.reduce((m, r) => Math.max(m, r.createdAt || 0), 0); rec.createdAt = Math.max(Date.now(), maxTs + 1); } arr.push(rec); sortDesc(arr); if (arr.length > MAX_RECORDS) arr.length = MAX_RECORDS; writeRecords(arr); return rec; }, async update(id, patch) { const arr = readRecords(); const i = arr.findIndex((r) => r.id === id); if (i === -1) return null; arr[i] = Object.assign({}, arr[i], patch); writeRecords(arr); return arr[i]; }, async remove(id) { writeRecords(readRecords().filter((r) => r.id !== id)); }, async get(id) { return readRecords().find((r) => r.id === id) || null; }, async list(filters, limit, before) { limit = limit || 24; return sortDesc(readRecords().filter((r) => matchFilters(r, filters) && (!before || r.createdAt < before) )).slice(0, limit); }, async all() { return sortDesc(readRecords()); }, async sites() { const all = await this.all(); const map = new Map(); all.forEach((r) => { const k = r.siteHost || '未知'; map.set(k, (map.get(k) || 0) + 1); }); return Array.from(map.entries()).sort((a, b) => b[1] - a[1]); }, async clear() { writeRecords([]); }, }; /* ========================================================================= * 3. 上传引擎 * ========================================================================= */ function parsePath(obj, path) { if (obj == null || !path) return undefined; let p = String(path).trim(); p = p.replace(/^\$json:/i, '').replace(/\$$/, '').trim(); if (!p) return undefined; const parts = p.replace(/\[(\d+)\]/g, '.$1').split('.').filter(Boolean); let cur = obj; for (const key of parts) { if (cur == null) return undefined; cur = cur[key]; } return cur; } // 取 JSON 里的值:兼容 data.url、$json:data.url$、{json:data.url}、{json:.file_code} function jsonValue(json, expr) { if (json == null) return undefined; let e = String(expr == null ? '' : expr).trim(); e = e.replace(/^\$json:/i, '').replace(/^\{json:/i, ''); e = e.replace(/\$$/, '').replace(/\}$/, '').trim(); if (e.charAt(0) === '.') e = e.slice(1); if (!e) return undefined; return parsePath(json, e); } const JSON_TOKEN_RE = /(\$json:[^$]+\$|\{json:[^}]+\})/gi; // 响应模板:整串是路径时按路径取值;含占位符时做字符串替换 // 例:data.url / {json:data.url} / https://userscloud.com/{json:.file_code} function resolveResponseTemplate(tpl, json) { const s = String(tpl == null ? '' : tpl); if (!s) return { text: '', touched: false }; let touched = false; const text = s.replace(JSON_TOKEN_RE, (m, token) => { touched = true; const v = jsonValue(json, token); return v == null ? '' : String(v); }); return { text: text, touched: touched }; } function firstUrlInText(text) { if (!text) return ''; const m = String(text).match(/https?:\/\/[^\s"'<>\\]+/i); return m ? m[0] : ''; } function fillTemplate(tpl, file, extra) { const name = file.name || 'image.png'; const dot = name.lastIndexOf('.'); const ext = dot > -1 ? name.slice(dot + 1) : ''; return String(tpl) .replace(/\{\{filename\}\}/g, name) .replace(/\{\{rawfilename\}\}/g, name) .replace(/\{\{ext\}\}/g, ext) .replace(/\{\{mime\}\}/g, file.type || 'application/octet-stream') .replace(/\{\{timestamp\}\}/g, String(Date.now())) .replace(/\{\{random\}\}/g, Math.random().toString(36).slice(2, 10)) .replace(/\{\{site\}\}/g, (extra && extra.site ? extra.site : '')); } function buildUploadUrl(provider, file) { let url = String(provider.uploadUrl || '').trim(); if (!url) throw new Error('图床未配置上传地址'); const params = []; (provider.query || []).forEach((q) => { if (!q || !q.key) return; const key = fillTemplate(q.key, file); const val = fillTemplate(q.value == null ? '' : q.value, file); params.push(encodeURIComponent(key) + '=' + encodeURIComponent(val)); }); if (params.length) url += (url.indexOf('?') > -1 ? '&' : '?') + params.join('&'); return url; } function xhrRequest(opts) { return new Promise((resolve, reject) => { if (!hasGMXHR) { reject(new Error('缺少 GM_xmlhttpRequest 权限')); return; } let finished = false; const done = (fn, v) => { if (!finished) { finished = true; fn(v); } }; try { GMXHR({ method: opts.method || 'POST', url: opts.url, headers: opts.headers || {}, data: opts.data, timeout: opts.timeout || 30000, withCredentials: !!opts.withCredentials, onload: (res) => done(resolve, res), onerror: () => done(reject, new Error('网络请求失败')), ontimeout: () => done(reject, new Error('请求超时')), onabort: () => done(reject, new Error('请求被取消')), }); } catch (e) { done(reject, e); } }); } function readAsDataUrl(file) { return new Promise((resolve, reject) => { const fr = new FileReader(); fr.onload = () => resolve(String(fr.result || '')); fr.onerror = () => reject(new Error('读取图片失败')); fr.readAsDataURL(file); }); } async function uploadOnce(file, provider, site) { const url = buildUploadUrl(provider, file); const headers = safeAssign({}, provider.headers || {}); let body; if (provider.bodyType === 'multipart') { const fd = new FormData(); fd.append(provider.formField || 'file', file, file.name || 'image.png'); (provider.fields || []).forEach((f) => { if (!f || !f.key) return; fd.append(fillTemplate(f.key, file), fillTemplate(f.value == null ? '' : f.value, file)); }); body = fd; } else if (provider.bodyType === 'base64json') { const dataUrl = await readAsDataUrl(file); const base64 = dataUrl.slice(dataUrl.indexOf(',') + 1); headers['Content-Type'] = headers['Content-Type'] || 'application/json'; body = JSON.stringify({ filename: file.name || 'image.png', content: base64, mime: file.type || 'application/octet-stream', }); } else { body = file; } const res = await xhrRequest({ method: provider.method || 'POST', url, headers, data: body, timeout: provider.timeoutMs, withCredentials: provider.withCredentials, }); const text = res.responseText || ''; const status = res.status || 0; if (status < 200 || status >= 300) { let msg = 'HTTP ' + status; try { const j = JSON.parse(text); if (j && (j.message || j.msg)) msg += ':' + (j.message || j.msg); } catch (e) { /* ignore */ } throw new Error(msg); } let json = null; try { json = JSON.parse(text); } catch (e) { json = null; } if (json && json.success === false) { throw new Error(json.message || json.msg || json.code || '图床返回失败'); } let imageUrl = ''; if (provider.urlPath) { const r = resolveResponseTemplate(provider.urlPath, json); imageUrl = r.touched ? r.text : (jsonValue(json, provider.urlPath) || ''); } if (typeof imageUrl !== 'string' || !imageUrl) { if (provider.urlRegex) { try { const m = text.match(new RegExp(provider.urlRegex)); if (m) imageUrl = m[1] || m[0]; } catch (e) { /* ignore */ } } } if (typeof imageUrl !== 'string' || !imageUrl) { imageUrl = firstUrlInText(text); } if (!imageUrl) throw new Error('无法从响应中解析出图片链接'); const safeUrl = safeHttpUrl(imageUrl); if (!safeUrl) throw new Error('图床返回的链接不是 http/https:' + String(imageUrl).slice(0, 80)); imageUrl = safeUrl; let deleteUrl = ''; if (provider.deleteUrlPath) { const d = resolveResponseTemplate(provider.deleteUrlPath, json); deleteUrl = d.touched ? d.text : (jsonValue(json, provider.deleteUrlPath) || ''); } deleteUrl = safeHttpUrl(deleteUrl); return { url: imageUrl, deleteUrl, raw: text, site: site || '' }; } async function uploadWithRetry(file, provider, site) { const retries = Math.max(0, Number(provider.retries) || 0); let lastErr = null; for (let i = 0; i <= retries; i++) { try { return await uploadOnce(file, provider, site); } catch (e) { lastErr = e; const msg = String(e && e.message || ''); if (/HTTP 4\d\d/.test(msg) && !/429/.test(msg)) break; if (i < retries) await new Promise((r) => setTimeout(r, 600 * (i + 1))); } } throw lastErr || new Error('上传失败'); } function makeTestFile() { const b64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='; const bin = atob(b64); const bytes = new Uint8Array(bin.length); for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i); return new File([bytes], 'piu-test.png', { type: 'image/png' }); } /* ========================================================================= * 4. 插入到输入框 * ========================================================================= */ function isTextInput(el) { if (!el || el.nodeType !== 1) return false; if (el.tagName === 'TEXTAREA') return true; if (el.tagName === 'INPUT') { const t = (el.type || 'text').toLowerCase(); return ['text', 'search', 'url', 'email', 'tel'].indexOf(t) > -1; } return false; } function isEditable(el) { return isTextInput(el) || (el && el.isContentEditable === true); } function findEditable(node) { let el = node && node.nodeType === 1 ? node : (node && node.parentElement); while (el) { if (isEditable(el)) return el; el = el.parentElement; } return null; } function editableRoot(el) { if (!el) return null; if (el.isContentEditable) { return el.closest('[contenteditable]') || el; } return el; } function isBlockedInput(el) { if (!el || el.nodeType !== 1) return true; if (el.disabled || el.readOnly) return true; if (el.tagName === 'INPUT' && String(el.type).toLowerCase() === 'password') return true; return false; } function formatLink(url, filename, mode) { const alt = escapeHtml(filename || '').replace(/"/g, ''); switch (mode) { case 'markdown': return '![' + (filename || '') + '](' + url + ')'; case 'bbcode': return '[img]' + url + '[/img]'; case 'html': return '' + alt + ''; default: return url; } } function insertTextInto(el, text) { el.focus({ preventScroll: true }); if (isTextInput(el)) { let ok = false; try { ok = document.execCommand('insertText', false, text); } catch (e) { ok = false; } if (ok && el.value.indexOf(text) > -1) return true; const start = el.selectionStart == null ? el.value.length : el.selectionStart; const end = el.selectionEnd == null ? start : el.selectionEnd; try { el.setRangeText(text, start, end, 'end'); } catch (e) { el.value = el.value.slice(0, start) + text + el.value.slice(end); } el.dispatchEvent(new Event('input', { bubbles: true })); return true; } try { if (document.execCommand('insertText', false, text)) return true; } catch (e) { /* ignore */ } return insertNodeInto(el, document.createTextNode(text)); } function insertNodeInto(el, domNode) { el.focus({ preventScroll: true }); const sel = window.getSelection(); if (!sel || !sel.rangeCount) { el.appendChild(domNode); return true; } const range = sel.getRangeAt(0); if (!el.contains(range.commonAncestorContainer)) { el.appendChild(domNode); return true; } range.deleteContents(); range.insertNode(domNode); range.setStartAfter(domNode); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); el.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' })); return true; } function setInputValue(el, value) { const proto = el.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; const desc = Object.getOwnPropertyDescriptor(proto, 'value'); if (desc && desc.set) desc.set.call(el, value); else el.value = value; el.dispatchEvent(new Event('input', { bubbles: true })); } function replaceInInput(el, token, text) { const val = el.value; const idx = val.indexOf(token); if (idx === -1) return false; const caret = el.selectionStart == null ? idx : el.selectionStart; const next = val.slice(0, idx) + text + val.slice(idx + token.length); setInputValue(el, next); let caretNext = caret; if (caret > idx) caretNext = Math.max(idx, caret - token.length + text.length); try { el.setSelectionRange(caretNext, caretNext); } catch (e) { /* ignore */ } return true; } function replaceInContentEditable(root, token, text, url, mode, filename) { const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, null); let tn; while ((tn = walker.nextNode())) { const value = tn.nodeValue || ''; const idx = value.indexOf(token); if (idx === -1) continue; const before = value.slice(0, idx); const after = value.slice(idx + token.length); if (mode === 'html' && url) { const frag = document.createDocumentFragment(); if (before) frag.appendChild(document.createTextNode(before)); const img = document.createElement('img'); img.src = url; img.alt = filename || ''; frag.appendChild(img); if (after) frag.appendChild(document.createTextNode(after)); tn.parentNode.replaceChild(frag, tn); } else { tn.nodeValue = before + text + after; } root.dispatchEvent(new InputEvent('input', { bubbles: true, inputType: 'insertText' })); return true; } return false; } /* ========================================================================= * 5. 站点规则 * ========================================================================= */ const BUILTIN_NATIVE_HOSTS = [ 'github.com', 'gist.github.com', 'gitlab.com', 'docs.google.com', 'notion.so', 'notion.site', 'feishu.cn', 'larksuite.com', 'yuque.com', 'slack.com', 'discord.com', 'telegram.org', 'dingtalk.com', 'wolai.com', 'ones.com', ]; function matchHost(pattern, host) { if (!pattern) return false; const p = String(pattern).trim().toLowerCase(); host = String(host || '').toLowerCase(); if (!p) return false; if (p === '*') return true; if (p.indexOf('*.') === 0) { const base = p.slice(2); return host === base || host.slice(-(base.length + 1)) === '.' + base; } return host === p || host.slice(-(p.length + 1)) === '.' + p; } // 与脚本头部的 @connect 列表保持一致,用于在导入 / 备份前提示用户补充白名单 const CONNECT_ALLOWLIST = ['p.sda1.dev', 'dav.jianguoyun.com', 'img.ink']; function hostAllowed(host) { if (!host) return false; const h = String(host).toLowerCase(); return CONNECT_ALLOWLIST.some((p) => matchHost(p, h)); } function allowHint(url) { try { const host = new URL(url).hostname; if (!hostAllowed(host)) { return '\n\n提示:域名 ' + host + ' 不在 @connect 白名单中,请在脚本头部添加 // @connect ' + host + ' 后刷新页面。'; } } catch (e) { /* ignore */ } return ''; } function parseRule(rule) { const text = String(rule || '').trim(); if (!text) return null; const m = text.match(/^(\S+)(?:\s+([\s\S]+))?$/); if (!m) return null; let host = m[1]; if (host !== '*') { // 支持直接粘贴完整 URL:https://www.example.com/path -> www.example.com if (/^[a-z][a-z0-9+.-]*:\/\//i.test(host)) { try { host = new URL(host).hostname; } catch (e) { /* ignore */ } } else { host = host.replace(/^\/+/, '').replace(/[/?#].*$/, '').replace(/:\d+$/, ''); } } if (!host) return null; return { host: host, selector: (m[2] || '').trim() }; } function matchRules(rules, host, el) { for (const rule of rules) { const r = parseRule(rule); if (!r) continue; if (!matchHost(r.host, host)) continue; if (!r.selector) return true; try { if (el.closest && el.closest(r.selector)) return true; } catch (e) { /* ignore */ } } return false; } function isNativePassthrough(el, cfg) { if (matchRules(cfg.whitelist, HOST, el)) return false; if (matchRules(cfg.blacklist, HOST, el)) return true; if (cfg.richTextPassthrough && el.isContentEditable) return true; if (BUILTIN_NATIVE_HOSTS.some((h) => matchHost(h, HOST))) return true; return false; } /* ========================================================================= * 6. Toast * ========================================================================= */ function toast(opts) { if (!state.shadow) return; const root = state.ui.toasts; if (!root) return; const id = ++state.toastSeq; const box = node('div', 'piu-toast ' + (opts.type || 'info')); box.dataset.id = String(id); const msg = node('div', 'piu-toast-msg'); msg.textContent = opts.message || ''; box.appendChild(msg); if (opts.actions && opts.actions.length) { const actWrap = node('div', 'piu-toast-actions'); opts.actions.forEach((a) => { const b = node('button', 'piu-toast-btn', a.label); b.addEventListener('click', () => { try { a.onClick && a.onClick(); } catch (e) { console.warn(e); } if (a.keepOpen !== true) box.remove(); }); actWrap.appendChild(b); }); box.appendChild(actWrap); } root.appendChild(box); requestAnimationFrame(() => box.classList.add('show')); const timeout = opts.timeout == null ? 4000 : opts.timeout; if (timeout > 0) { setTimeout(() => { box.classList.remove('show'); setTimeout(() => box.remove(), 220); }, timeout); } while (root.children.length > 4) root.firstElementChild.remove(); return box; } /* ========================================================================= * 7. 面板 UI * ========================================================================= */ const CSS = ` :host { all: initial; } * { box-sizing: border-box; } .piu-layer { position: fixed; inset: 0; pointer-events: none; z-index: 2147483646; font: 13px/1.5 -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC", "Microsoft YaHei", sans-serif; color: var(--fg); } .piu-layer > * { pointer-events: auto; } .piu-root { --bg: #ffffff; --bg2: #f6f7f9; --fg: #1f2328; --muted: #6b7280; --line: #e5e7eb; --acc: #2563eb; --acc-fg: #ffffff; --danger: #dc2626; --ok: #059669; --shadow: 0 18px 50px rgba(15, 23, 42, .18); } @media (prefers-color-scheme: dark) { .piu-root { --bg: #17191d; --bg2: #1f2228; --fg: #e6e8eb; --muted: #9aa2ae; --line: #2c3037; --acc: #3b82f6; --acc-fg: #ffffff; --danger: #f87171; --ok: #34d399; --shadow: 0 18px 50px rgba(0, 0, 0, .55); } } .piu-fab { position: fixed; right: 18px; bottom: 18px; width: 40px; height: 40px; border-radius: 50%; background: var(--acc); color: var(--acc-fg); border: 0; cursor: pointer; font-size: 14px; font-weight: 700; box-shadow: 0 6px 18px rgba(0,0,0,.25); opacity: .86; transition: opacity .15s, transform .15s; } .piu-fab:hover { opacity: 1; transform: translateY(-1px); } .piu-mask { position: fixed; inset: 0; background: rgba(15,23,42,.35); } .piu-panel { position: fixed; right: 16px; top: 16px; bottom: 16px; width: min(780px, calc(100vw - 32px)); background: var(--bg); border: 1px solid var(--line); border-radius: 14px; box-shadow: var(--shadow); display: flex; flex-direction: column; overflow: hidden; } .piu-panel[hidden], .piu-mask[hidden] { display: none !important; } .piu-head { display: flex; align-items: center; gap: 8px; padding: 12px 14px; border-bottom: 1px solid var(--line); background: var(--bg2); } .piu-brand { font-weight: 700; font-size: 14px; } .piu-ver { font-weight: 400; color: var(--muted); font-size: 11px; margin-left: 6px; } .piu-head-actions { margin-left: auto; display: flex; gap: 6px; } .piu-icon { border: 0; background: transparent; color: var(--muted); font-size: 16px; cursor: pointer; padding: 2px 6px; border-radius: 6px; } .piu-icon:hover { background: var(--line); color: var(--fg); } .piu-tabs { display: flex; gap: 4px; padding: 8px 14px 0; border-bottom: 1px solid var(--line); } .piu-tab { border: 0; background: transparent; color: var(--muted); padding: 7px 12px; cursor: pointer; border-bottom: 2px solid transparent; font-size: 13px; } .piu-tab.active { color: var(--acc); border-bottom-color: var(--acc); font-weight: 600; } .piu-panes { flex: 1; overflow: hidden; display: flex; } .piu-pane { flex: 1; overflow-y: auto; padding: 12px 14px 18px; } .piu-pane[hidden] { display: none; } .piu-toolbar { display: flex; gap: 6px; flex-wrap: wrap; margin-bottom: 10px; } .piu-toolbar select, .piu-toolbar input, .piu-field input, .piu-field select, .piu-field textarea { background: var(--bg2); color: var(--fg); border: 1px solid var(--line); border-radius: 7px; padding: 6px 8px; font: inherit; outline: none; } .piu-toolbar select:focus, .piu-toolbar input:focus, .piu-field input:focus, .piu-field textarea:focus { border-color: var(--acc); } .piu-toolbar input { flex: 1; min-width: 120px; } .piu-btn { background: var(--acc); color: var(--acc-fg); border: 0; border-radius: 7px; padding: 6px 12px; cursor: pointer; font: inherit; } .piu-btn:hover { filter: brightness(1.06); } .piu-btn.ghost { background: var(--bg2); color: var(--fg); border: 1px solid var(--line); } .piu-btn.danger { background: transparent; color: var(--danger); border: 1px solid var(--danger); } .piu-btn:disabled { opacity: .55; cursor: default; } .piu-list { display: flex; flex-direction: column; gap: 8px; } .piu-item { display: flex; gap: 10px; align-items: flex-start; padding: 8px; border: 1px solid var(--line); border-radius: 10px; background: var(--bg2); } .piu-thumb { width: 52px; height: 52px; object-fit: cover; border-radius: 7px; background: var(--line); flex: none; cursor: zoom-in; } .piu-viewer { position: fixed; inset: 0; z-index: 5; background: rgba(0,0,0,.82); display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px; cursor: zoom-out; } .piu-viewer[hidden] { display: none !important; } .piu-viewer img { max-width: 92vw; max-height: 88vh; border-radius: 8px; box-shadow: 0 12px 40px rgba(0,0,0,.5); background: #fff; } .piu-viewer-hint { color: #d9dde3; font-size: 12px; } .piu-dialog { position: fixed; inset: 0; z-index: 8; background: rgba(15,23,42,.45); display: flex; align-items: center; justify-content: center; padding: 16px; } .piu-dialog[hidden] { display: none !important; } .piu-dialog-box { background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-radius: 12px; box-shadow: var(--shadow); width: min(440px, 100%); padding: 14px 16px; } .piu-dialog-title { font-weight: 600; margin-bottom: 8px; } .piu-dialog-msg { color: var(--fg); font-size: 13px; white-space: pre-wrap; word-break: break-word; max-height: 40vh; overflow: auto; } .piu-dialog-input { width: 100%; min-height: 110px; margin-top: 10px; background: var(--bg2); color: var(--fg); border: 1px solid var(--line); border-radius: 7px; padding: 7px 8px; font: 12px/1.5 ui-monospace, Menlo, Consolas, monospace; resize: vertical; outline: none; } .piu-dialog-input:focus { border-color: var(--acc); } .piu-dialog-actions { display: flex; justify-content: flex-end; gap: 8px; margin-top: 12px; } .piu-btn.danger-solid { background: var(--danger); color: #fff; } .piu-info { flex: 1; min-width: 0; } .piu-url { font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .piu-meta { color: var(--muted); font-size: 11px; margin-top: 3px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .piu-badge { display: inline-block; padding: 0 6px; border-radius: 999px; font-size: 10px; background: var(--line); color: var(--muted); } .piu-actions { display: flex; gap: 4px; flex-wrap: wrap; justify-content: flex-end; max-width: 210px; flex: none; } .piu-actions button { background: transparent; border: 1px solid var(--line); color: var(--fg); border-radius: 6px; padding: 3px 7px; font-size: 11px; cursor: pointer; } .piu-actions button:hover { border-color: var(--acc); color: var(--acc); } .piu-actions button.danger:hover { border-color: var(--danger); color: var(--danger); } .piu-sentinel { text-align: center; color: var(--muted); font-size: 12px; padding: 14px 0; } .piu-empty { text-align: center; color: var(--muted); padding: 40px 0; font-size: 13px; } .piu-group { border: 1px solid var(--line); border-radius: 10px; padding: 10px 12px; margin-bottom: 10px; } .piu-group-title { font-weight: 600; margin-bottom: 8px; } .piu-row { display: flex; align-items: center; gap: 8px; padding: 4px 0; } .piu-row input[type=checkbox], .piu-row input[type=radio] { accent-color: var(--acc); } .piu-radios { display: flex; gap: 14px; flex-wrap: wrap; padding: 2px 0 4px; } .piu-radios label { display: flex; align-items: center; gap: 5px; cursor: pointer; } .piu-field { display: block; margin: 6px 0; } .piu-field > span { display: block; color: var(--muted); font-size: 11px; margin-bottom: 3px; } .piu-field input, .piu-field select, .piu-field textarea { width: 100%; } .piu-field textarea { resize: vertical; min-height: 54px; font-family: ui-monospace, Menlo, Consolas, monospace; font-size: 12px; } .piu-hint { color: var(--muted); font-size: 11px; margin-top: 6px; } .piu-hint a { color: var(--acc); text-decoration: none; } .piu-hint a:hover { text-decoration: underline; } .piu-about { text-align: center; padding: 18px 0 10px; } .piu-about-logo { width: 48px; height: 48px; border-radius: 12px; background: var(--acc); color: var(--acc-fg); display: flex; align-items: center; justify-content: center; font-size: 20px; font-weight: 700; margin: 0 auto 10px; } .piu-about-name { font-size: 16px; font-weight: 600; } .piu-about-ver { color: var(--muted); font-size: 12px; margin-top: 2px; } .piu-about-desc { color: var(--muted); font-size: 12px; margin-top: 8px; } .piu-provider { border: 1px solid var(--line); border-radius: 10px; margin-bottom: 10px; background: var(--bg2); overflow: hidden; } .piu-provider > summary { list-style: none; cursor: pointer; padding: 9px 12px; display: flex; align-items: center; gap: 8px; } .piu-provider > summary::-webkit-details-marker { display: none; } .piu-provider > summary .piu-name { font-weight: 600; } .piu-provider > summary .piu-grow { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; color: var(--muted); font-size: 11px; } .piu-provider-body { padding: 4px 12px 12px; background: var(--bg); border-top: 1px solid var(--line); } .piu-grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 0 12px; } .piu-provider-actions { display: flex; gap: 6px; margin-top: 8px; flex-wrap: wrap; } .piu-provider-head { display: flex; align-items: center; gap: 6px; } .piu-switch { display: inline-flex; align-items: center; gap: 4px; color: var(--muted); font-size: 11px; } .piu-toasts { position: fixed; left: 16px; bottom: 16px; z-index: 6; display: flex; flex-direction: column; gap: 8px; max-width: min(420px, calc(100vw - 32px)); } .piu-toast { background: var(--bg); color: var(--fg); border: 1px solid var(--line); border-left: 3px solid var(--acc); border-radius: 9px; box-shadow: var(--shadow); padding: 9px 11px; opacity: 0; transform: translateY(6px); transition: opacity .2s, transform .2s; } .piu-toast.show { opacity: 1; transform: none; } .piu-toast.success { border-left-color: var(--ok); } .piu-toast.error { border-left-color: var(--danger); } .piu-toast-msg { word-break: break-all; } .piu-toast-actions { display: flex; gap: 6px; margin-top: 7px; } .piu-toast-btn { background: transparent; border: 1px solid var(--line); color: var(--fg); border-radius: 6px; padding: 3px 8px; font-size: 11px; cursor: pointer; } .piu-toast-btn:hover { border-color: var(--acc); color: var(--acc); } `; const PANEL_HTML = `
`; function mountUI() { const host = document.createElement('div'); host.id = 'piu-host'; host.style.cssText = 'position:fixed;left:0;top:0;width:0;height:0;z-index:2147483647;'; (document.body || document.documentElement).appendChild(host); // closed:宿主页面的脚本无法通过 shadowRoot 读取面板内容(token、密码等) const shadow = host.attachShadow({ mode: 'closed' }); const style = document.createElement('style'); style.textContent = CSS; shadow.appendChild(style); const wrap = document.createElement('div'); wrap.innerHTML = PANEL_HTML; while (wrap.firstChild) shadow.appendChild(wrap.firstChild); state.hostEl = host; state.shadow = shadow; state.ui.panel = shadow.getElementById('piu-panel'); state.ui.mask = shadow.getElementById('piu-mask'); state.ui.fab = shadow.getElementById('piu-fab'); state.ui.listEl = shadow.getElementById('piu-list'); state.ui.sentinel = shadow.getElementById('piu-sentinel'); state.ui.toasts = shadow.getElementById('piu-toasts'); state.ui.viewer = shadow.getElementById('piu-viewer'); state.ui.viewerImg = shadow.getElementById('piu-viewer-img'); state.ui.dialog = shadow.getElementById('piu-dialog'); state.ui.dialogTitle = shadow.getElementById('piu-dialog-title'); state.ui.dialogMsg = shadow.getElementById('piu-dialog-msg'); state.ui.dialogInput = shadow.getElementById('piu-dialog-input'); state.ui.dialogOk = shadow.getElementById('piu-dialog-ok'); state.ui.dialogCancel = shadow.getElementById('piu-dialog-cancel'); bindPanelEvents(shadow); } function applyFabVisibility() { if (!state.ui.fab) return; if (!IS_TOP || (state.ui.panel && !state.ui.panel.hidden) || state.config.showFab === false) { state.ui.fab.style.display = 'none'; } else { state.ui.fab.style.display = ''; } } function openPanel(tab) { if (!state.ui.panel) return; state.ui.panel.hidden = false; state.ui.mask.hidden = false; state.ui.fab.style.display = 'none'; switchTab(tab || 'history'); } function closePanel() { if (!state.ui.panel) return; state.ui.panel.hidden = true; state.ui.mask.hidden = true; applyFabVisibility(); } function openViewer(src) { if (!state.ui.viewer || !state.ui.viewerImg) return; const safe = safeHttpUrl(src); if (!safe) { toast({ type: 'error', message: '图片链接无效,已阻止打开' }); return; } state.ui.viewerImg.src = safe; state.ui.viewer.hidden = false; } function closeViewer() { if (!state.ui.viewer) return; state.ui.viewer.hidden = true; if (state.ui.viewerImg) state.ui.viewerImg.removeAttribute('src'); } /* ---------------- 应用内弹窗(替代原生 confirm / prompt) ---------------- */ let dialogResolve = null; function openDialog(opts) { const o = opts || {}; if (!state.ui.dialog) { if (o.input) { const v = window.prompt(o.message || '', o.value || ''); return Promise.resolve({ ok: v != null, value: v == null ? '' : v }); } return Promise.resolve({ ok: !!window.confirm(o.message || ''), value: '' }); } return new Promise((resolve) => { dialogResolve = resolve; state.ui.dialogTitle.textContent = o.title || '确认'; state.ui.dialogMsg.textContent = o.message || ''; state.ui.dialogMsg.hidden = !o.message; const input = state.ui.dialogInput; input.hidden = !o.input; input.value = o.input ? (o.value || '') : ''; input.placeholder = o.placeholder || ''; state.ui.dialogOk.textContent = o.okText || '确定'; state.ui.dialogCancel.textContent = o.cancelText || '取消'; state.ui.dialogOk.classList.toggle('danger-solid', !!o.danger); state.ui.dialog.hidden = false; setTimeout(() => { if (o.input) input.focus(); else state.ui.dialogOk.focus(); }, 30); }); } function closeDialog(ok) { if (!state.ui.dialog || state.ui.dialog.hidden) return; const value = state.ui.dialogInput ? state.ui.dialogInput.value : ''; state.ui.dialog.hidden = true; const resolve = dialogResolve; dialogResolve = null; if (resolve) resolve({ ok: !!ok, value: value }); } function uiConfirm(message, opts) { return openDialog(Object.assign({ message: message }, opts || {})).then((r) => r.ok); } function uiPrompt(message, value, opts) { return openDialog(Object.assign({ title: '粘贴内容', message: message, input: true, value: value, }, opts || {})).then((r) => (r.ok ? r.value : null)); } function switchTab(tab) { const root = state.shadow; root.querySelectorAll('.piu-tab').forEach((b) => { b.classList.toggle('active', b.dataset.tab === tab); }); root.querySelectorAll('.piu-pane').forEach((p) => { p.hidden = p.dataset.pane !== tab; }); if (tab === 'history') { refreshSiteOptions(); refreshProviderOptions(); reloadHistory(); } else if (tab === 'providers') { renderProviders(); } else if (tab === 'settings') { renderSettings(); } } function bindPanelEvents(shadow) { shadow.getElementById('piu-fab').addEventListener('click', () => openPanel()); shadow.getElementById('piu-close').addEventListener('click', closePanel); shadow.getElementById('piu-mask').addEventListener('click', closePanel); shadow.querySelectorAll('.piu-tab').forEach((b) => { b.addEventListener('click', () => switchTab(b.dataset.tab)); }); // 历史筛选 const fSite = shadow.getElementById('piu-f-site'); const fProv = shadow.getElementById('piu-f-provider'); const fStatus = shadow.getElementById('piu-f-status'); const fQ = shadow.getElementById('piu-f-q'); const applyFilter = () => { state.list.filters = { siteHost: fSite.value, providerId: fProv.value, status: fStatus.value, q: fQ.value.trim(), }; reloadHistory(); }; fSite.addEventListener('change', applyFilter); fProv.addEventListener('change', applyFilter); fStatus.addEventListener('change', applyFilter); fQ.addEventListener('input', debounce(applyFilter, 250)); shadow.getElementById('piu-f-reset').addEventListener('click', () => { fSite.value = ''; fProv.value = ''; fStatus.value = ''; fQ.value = ''; applyFilter(); }); // 历史列表操作 state.ui.listEl.addEventListener('click', onListClick); state.ui.listEl.addEventListener('click', (e) => { if (e.target && e.target.closest && e.target.closest('button[data-act]')) return; const img = e.target && e.target.closest ? e.target.closest('.piu-thumb') : null; if (img && img.getAttribute('src')) openViewer(img.getAttribute('src')); }); if (state.ui.viewer) state.ui.viewer.addEventListener('click', closeViewer); if (state.ui.dialogOk) state.ui.dialogOk.addEventListener('click', () => closeDialog(true)); if (state.ui.dialogCancel) state.ui.dialogCancel.addEventListener('click', () => closeDialog(false)); if (state.ui.dialog) { state.ui.dialog.addEventListener('click', (e) => { if (e.target === state.ui.dialog) closeDialog(false); }); } // 无限滚动 const io = new IntersectionObserver((entries) => { entries.forEach((en) => { if (en.isIntersecting) loadMoreHistory(); }); }, { root: state.ui.listEl.parentElement, rootMargin: '120px' }); io.observe(state.ui.sentinel); state.list.observer = io; // 图床 shadow.getElementById('piu-provider-add').addEventListener('click', addProvider); shadow.getElementById('piu-provider-import').addEventListener('click', importShareX); shadow.getElementById('piu-providers').addEventListener('click', onProviderClick); shadow.getElementById('piu-providers').addEventListener('change', onProviderChange); // 设置 const pane = shadow.querySelector('[data-pane="settings"]'); pane.addEventListener('change', onSettingsChange); pane.addEventListener('click', onSettingsClick); // 快捷键(仅在顶层窗口生效,避免 iframe 重复触发) if (!IS_TOP) return; window.addEventListener('keydown', (e) => { if (e.altKey && e.shiftKey && (e.code === 'KeyH' || e.key === 'H' || e.key === 'h')) { e.preventDefault(); if (state.ui.panel.hidden) openPanel(); else closePanel(); } else if (e.key === 'Escape') { if (state.ui.dialog && !state.ui.dialog.hidden) { closeDialog(false); return; } if (state.ui.viewer && !state.ui.viewer.hidden) { closeViewer(); return; } if (!state.ui.panel.hidden) closePanel(); } else if (e.key === 'Enter' && state.ui.dialog && !state.ui.dialog.hidden && (!state.ui.dialogInput || state.ui.dialogInput.hidden)) { e.preventDefault(); closeDialog(true); } }, true); } /* ---------------- 历史列表 ---------------- */ async function refreshSiteOptions() { const sel = state.shadow.getElementById('piu-f-site'); const current = sel.value; const sites = await History.sites(); sel.innerHTML = '' + sites.map(([s, c]) => ``).join(''); if (current) sel.value = current; } function refreshProviderOptions() { const sel = state.shadow.getElementById('piu-f-provider'); const current = sel.value; sel.innerHTML = '' + state.config.providers.map((p) => ``).join(''); if (current) sel.value = current; } function recordItemHtml(r) { const site = escapeHtml(r.siteHost || ''); const meta = [ site, r.providerName || '', fmtBytes(r.size), fmtTime(r.createdAt), r.status === 'deleted' ? '已从图床删除' : '', ].filter(Boolean).map(escapeHtml).join(' · '); const safeUrl = safeHttpUrl(r.url); const thumb = safeUrl ? `` : '
'; return `
${thumb}
${escapeHtml(r.url)}
${meta}
${r.deleteUrl ? '' : ''}
`; } async function reloadHistory() { const l = state.list; l.cursor = null; l.hasMore = true; l.loading = false; l.items = []; state.ui.listEl.innerHTML = ''; state.ui.sentinel.textContent = '加载中…'; await loadMoreHistory(); } async function loadMoreHistory() { const l = state.list; if (l.loading || !l.hasMore) return; l.loading = true; state.ui.sentinel.textContent = '加载中…'; try { const page = await History.list(l.filters, 24, l.cursor); if (!page.length) { l.hasMore = false; state.ui.sentinel.textContent = l.items.length ? '没有更多了' : ''; if (!l.items.length) { state.ui.listEl.innerHTML = '
暂无记录,去任意输入框粘贴一张图片试试
'; } return; } l.items = l.items.concat(page); l.cursor = page[page.length - 1].createdAt; const html = page.map(recordItemHtml).join(''); state.ui.listEl.insertAdjacentHTML('beforeend', html); state.ui.sentinel.textContent = page.length < 24 ? '没有更多了' : '上滑加载更多'; if (page.length < 24) l.hasMore = false; } catch (e) { state.ui.sentinel.textContent = '加载失败:' + (e.message || e); } finally { l.loading = false; } } async function onListClick(e) { const btn = e.target.closest('button[data-act]'); if (!btn) return; const item = btn.closest('.piu-item'); if (!item) return; const id = item.dataset.id; const act = btn.dataset.act; const rec = state.list.items.find((r) => r.id === id) || await History.get(id); if (!rec) return; if (act === 'preview') { openViewer(rec.url); } else if (act === 'copy') { const ok = await copyText(rec.url); toast({ type: ok ? 'success' : 'error', message: ok ? '链接已复制' : '复制失败' }); } else if (act === 'copy-md') { const ok = await copyText(formatLink(rec.url, rec.filename, 'markdown')); toast({ type: ok ? 'success' : 'error', message: ok ? 'Markdown 已复制' : '复制失败' }); } else if (act === 'open') { const safe = safeHttpUrl(rec.url); if (!safe) { toast({ type: 'error', message: '链接无效,已阻止打开' }); return; } window.open(safe, '_blank', 'noopener'); } else if (act === 'delete') { if (!(await uiConfirm('仅删除本地记录,图床上的图片不受影响。继续?', { title: '删除记录', okText: '删除', danger: true, }))) return; await History.remove(id); state.list.items = state.list.items.filter((r) => r.id !== id); item.remove(); if (!state.list.items.length) reloadHistory(); toast({ type: 'success', message: '本地记录已删除' }); } else if (act === 'remote-delete') { await deleteRemote(rec, item); } } async function deleteRemote(rec, item) { const deleteUrl = safeHttpUrl(rec.deleteUrl); if (!deleteUrl) { toast({ type: 'error', message: '删除链接无效,无法请求' }); return; } if (!(await uiConfirm('将请求图床删除链接,删除后无法恢复:\n' + deleteUrl + '\n\n继续?', { title: '删除图床图片', okText: '删除', danger: true, }))) return; toast({ type: 'info', message: '正在请求图床删除…', timeout: 1500 }); try { const res = await xhrRequest({ method: 'GET', url: deleteUrl, timeout: 15000 }); const text = res.responseText || ''; const looksHtml = /^\s*= 200 && res.status < 400 && !looksHtml; if (ok) { await History.update(rec.id, { status: 'deleted' }); rec.status = 'deleted'; if (item) { const meta = item.querySelector('.piu-meta'); if (meta && meta.textContent.indexOf('已从图床删除') === -1) { meta.textContent += ' · 已从图床删除'; } } toast({ type: 'success', message: '图床图片已删除' }); } else { toast({ type: 'info', message: '该删除链接需要手动确认,已为你准备好', timeout: 8000, actions: [{ label: '打开删除页', keepOpen: false, onClick: () => window.open(deleteUrl, '_blank', 'noopener') }], }); } } catch (e) { toast({ type: 'error', message: '自动删除失败:' + (e.message || e), timeout: 8000, actions: [{ label: '打开删除页', keepOpen: false, onClick: () => window.open(deleteUrl, '_blank', 'noopener') }], }); } } /* ---------------- 图床管理 ---------------- */ function providerCardHtml(p, isActive) { return `
${escapeHtml(p.name)} ${escapeHtml(p.uploadUrl)} ${isActive ? '当前' : ''}
`; } function renderProviders() { const box = state.shadow.getElementById('piu-providers'); const cfg = state.config; box.innerHTML = cfg.providers.map((p) => providerCardHtml(p, p.id === cfg.activeProviderId)).join(''); } function readProviderForm(card) { const get = (f) => { const el = card.querySelector('[data-field="' + f + '"]'); return el ? el.value : ''; }; const queryText = get('query'); const fieldsText = get('fields'); const headersText = get('headers'); const parsePairs = (text) => String(text || '').split('\n').map((line) => line.trim()).filter(Boolean).map((line) => { const i = line.indexOf('='); if (i === -1) return { key: line, value: '' }; return { key: line.slice(0, i).trim(), value: line.slice(i + 1).trim() }; }); const query = parsePairs(queryText); const fields = parsePairs(fieldsText); const headers = {}; headersText.split('\n').map((l) => l.trim()).filter(Boolean).forEach((line) => { const i = line.indexOf(':'); if (i > 0) headers[line.slice(0, i).trim()] = line.slice(i + 1).trim(); }); const withCred = card.querySelector('[data-field="withCredentials"]'); const enabledEl = card.querySelector('[data-field="enabled"]'); return { enabled: !!(enabledEl && enabledEl.checked), name: get('name').trim() || '未命名图床', uploadUrl: get('uploadUrl').trim(), method: get('method') || 'POST', bodyType: get('bodyType') || 'binary', formField: get('formField').trim() || 'file', maxSizeMB: Number(get('maxSizeMB')) || 5, query, fields, headers, urlPath: get('urlPath').trim(), deleteUrlPath: get('deleteUrlPath').trim(), urlRegex: get('urlRegex').trim(), timeoutMs: Number(get('timeoutMs')) || 30000, retries: Number(get('retries')) || 0, withCredentials: !!(withCred && withCred.checked), }; } async function onProviderClick(e) { const btn = e.target.closest('button[data-act]'); if (!btn) return; const card = btn.closest('.piu-provider'); if (!card) return; const id = card.dataset.id; const provider = state.config.providers.find((p) => p.id === id); if (!provider) return; const act = btn.dataset.act; if (act === 'save') { const patch = readProviderForm(card); if (!patch.uploadUrl) { toast({ type: 'error', message: '请填写上传地址' }); return; } Object.assign(provider, patch); saveConfig(); renderProviders(); toast({ type: 'success', message: '已保存:' + provider.name }); } else if (act === 'test') { const patch = readProviderForm(card); if (!patch.uploadUrl) { toast({ type: 'error', message: '请填写上传地址' }); return; } const temp = Object.assign({}, provider, patch); btn.disabled = true; btn.textContent = '测试中…'; try { const r = await uploadWithRetry(makeTestFile(), temp, HOST); toast({ type: 'success', message: '测试成功:' + r.url, timeout: 8000 }); await copyText(r.url); } catch (err) { toast({ type: 'error', message: '测试失败:' + (err.message || err), timeout: 8000 }); } finally { btn.disabled = false; btn.textContent = '测试连接'; } } else if (act === 'copy') { const copy = Object.assign({}, provider, { id: uuid(), name: provider.name + ' 副本' }); state.config.providers.push(normalizeProvider(copy)); saveConfig(); renderProviders(); } else if (act === 'remove') { if (state.config.providers.length <= 1) { toast({ type: 'error', message: '至少保留一个图床' }); return; } if (!(await uiConfirm('删除图床「' + provider.name + '」?历史记录不受影响。', { title: '删除图床', okText: '删除', danger: true, }))) return; state.config.providers = state.config.providers.filter((p) => p.id !== id); if (state.config.activeProviderId === id) { state.config.activeProviderId = state.config.providers[0].id; } saveConfig(); renderProviders(); } } function onProviderChange(e) { const t = e.target; if (t && t.name === 'piu-active-provider') { state.config.activeProviderId = t.value; saveConfig(); renderProviders(); toast({ type: 'success', message: '当前图床:' + (activeProvider() || {}).name, timeout: 1800 }); } } function addProvider() { const p = normalizeProvider({ name: '新图床', uploadUrl: '', urlPath: 'data.url', deleteUrlPath: '' }); state.config.providers.push(p); saveConfig(); renderProviders(); const card = state.shadow.querySelector('.piu-provider[data-id="' + p.id + '"]'); if (card) { card.open = true; card.scrollIntoView({ block: 'nearest' }); } } async function importShareX() { const raw = await uiPrompt('把 ShareX 自定义上传器的 JSON 粘贴到这里:', '', { title: '导入 ShareX 配置', okText: '导入', placeholder: '{ "RequestURL": "...", "URL": "{json:data.url}" }', }); if (!raw) return; let j; try { j = JSON.parse(raw); } catch (e) { toast({ type: 'error', message: 'JSON 解析失败' }); return; } if (!j.RequestURL) { toast({ type: 'error', message: '缺少 RequestURL 字段' }); return; } const mapPairs = (obj) => Object.keys(obj || {}) .filter((k) => obj[k] != null) .map((k) => ({ key: k, value: String(obj[k]).replace(/\$filename\$/g, '{{filename}}') })); const query = mapPairs(j.Parameters); const fields = mapPairs(j.Arguments); const headers = {}; if (j.Headers && typeof j.Headers === 'object') { Object.keys(j.Headers).forEach((k) => { headers[k] = String(j.Headers[k]); }); } const bodyText = String(j.Body || '').toLowerCase(); const bodyType = bodyText.indexOf('binary') > -1 ? 'binary' : (bodyText.indexOf('json') > -1 ? 'base64json' : 'multipart'); let host = '自定义'; try { host = new URL(j.RequestURL).hostname; } catch (e) { /* ignore */ } if (host !== '自定义' && !hostAllowed(host)) { const go = await uiConfirm( '域名 ' + host + ' 不在脚本的 @connect 白名单中,上传请求会被浏览器扩展拦截。\n\n' + '请在脚本头部元数据里添加一行:\n// @connect ' + host + '\n\n' + '保存并刷新页面后生效。\n\n仍然导入该配置吗?', { title: '需要添加跨域白名单', okText: '仍然导入' } ); if (!go) return; } const p = normalizeProvider({ name: String(j.Name || '').trim() || (host + ' 图床'), uploadUrl: j.RequestURL, method: j.RequestMethod || 'POST', bodyType, formField: j.FileFormName || 'file', query, fields, headers, urlPath: j.URL || '', deleteUrlPath: j.DeletionURL || '', }); state.config.providers.push(p); saveConfig(); renderProviders(); toast({ type: 'success', message: '已导入:' + p.name + '(表单字段 ' + fields.length + ' 个,请求头 ' + Object.keys(headers).length + ' 个)' }); } /* ---------------- 设置 ---------------- */ const INSERT_HINTS = { url: '示例:https://p.sda1.dev/xxx.png', markdown: '示例:![](https://p.sda1.dev/xxx.png)', bbcode: '示例:[img]https://p.sda1.dev/xxx.png[/img]', html: '示例:image.png', }; function renderSettings() { const root = state.shadow; const cfg = state.config; root.getElementById('piu-s-enabled').checked = !!cfg.enabled; root.getElementById('piu-s-richtext').checked = !!cfg.richTextPassthrough; root.getElementById('piu-s-autocopy').checked = !!cfg.autoCopy; root.getElementById('piu-s-fab').checked = cfg.showFab !== false; root.getElementById('piu-s-siteoff').checked = !siteEnabled(HOST); root.getElementById('piu-s-host').textContent = HOST; root.getElementById('piu-s-blacklist').value = (cfg.blacklist || []).join('\n'); root.getElementById('piu-s-whitelist').value = (cfg.whitelist || []).join('\n'); root.querySelectorAll('input[name="piu-insert"]').forEach((r) => { r.checked = r.value === cfg.insertMode; }); root.getElementById('piu-insert-hint').textContent = INSERT_HINTS[cfg.insertMode] || ''; const w = cfg.webdav || {}; root.getElementById('piu-w-url').value = w.url || ''; root.getElementById('piu-w-user').value = w.username || ''; root.getElementById('piu-w-pass').value = w.password || ''; root.getElementById('piu-w-folder').value = w.folder == null ? DEFAULT_DAV_FOLDER : w.folder; root.getElementById('piu-w-file').value = w.file || DEFAULT_DAV_FILE; root.getElementById('piu-w-auto').checked = !!w.auto; } function onSettingsChange(e) { const t = e.target; if (!t) return; const cfg = state.config; if (t.id === 'piu-s-enabled') cfg.enabled = t.checked; else if (t.id === 'piu-s-richtext') cfg.richTextPassthrough = t.checked; else if (t.id === 'piu-s-autocopy') cfg.autoCopy = t.checked; else if (t.id === 'piu-s-fab') cfg.showFab = t.checked; else if (t.id === 'piu-s-siteoff') cfg.siteEnabled[HOST] = !t.checked; else if (t.id === 'piu-s-blacklist') cfg.blacklist = splitLines(t.value); else if (t.id === 'piu-s-whitelist') cfg.whitelist = splitLines(t.value); else if (t.id === 'piu-w-url') cfg.webdav.url = t.value.trim(); else if (t.id === 'piu-w-user') cfg.webdav.username = t.value.trim(); else if (t.id === 'piu-w-pass') cfg.webdav.password = t.value; else if (t.id === 'piu-w-folder') cfg.webdav.folder = t.value.trim(); else if (t.id === 'piu-w-file') cfg.webdav.file = t.value.trim() || DEFAULT_DAV_FILE; else if (t.id === 'piu-w-auto') cfg.webdav.auto = t.checked; else if (t.name === 'piu-insert') { cfg.insertMode = t.value; state.shadow.getElementById('piu-insert-hint').textContent = INSERT_HINTS[t.value] || ''; } else return; saveConfig(); if (t.id === 'piu-s-fab') applyFabVisibility(); } function splitLines(text) { return String(text || '').split('\n').map((s) => s.trim()).filter(Boolean); } // 配置恢复为出厂默认,历史记录不动 function resetConfigToDefault() { state.config = defaultConfig(); saveConfig(); state.list.filters = { siteHost: '', providerId: '', status: '', q: '' }; const fSite = state.shadow.getElementById('piu-f-site'); const fProvider = state.shadow.getElementById('piu-f-provider'); const fStatus = state.shadow.getElementById('piu-f-status'); const fQuery = state.shadow.getElementById('piu-f-q'); if (fSite) fSite.selectedIndex = 0; if (fProvider) fProvider.selectedIndex = 0; if (fStatus) fStatus.selectedIndex = 0; if (fQuery) fQuery.value = ''; renderSettings(); renderProviders(); applyFabVisibility(); } async function onSettingsClick(e) { const btn = e.target.closest('button[data-act]'); if (!btn) return; const act = btn.dataset.act; if (act === 'export-config') exportConfig(); else if (act === 'import-config') importConfig(); else if (act === 'export-history') exportHistory(); else if (act === 'import-history') importHistory(); else if (act === 'webdav-test') { btn.disabled = true; try { const msg = await webdavTest(); toast({ type: 'success', message: msg, timeout: 6000 }); } catch (err) { toast({ type: 'error', message: '连接失败:' + (err.message || err) + webdavAllowHint(), timeout: 9000 }); } finally { btn.disabled = false; } } else if (act === 'webdav-backup') { btn.disabled = true; try { await webdavBackup(); } catch (err) { toast({ type: 'error', message: '备份失败:' + (err.message || err) + webdavAllowHint(), timeout: 9000 }); } finally { btn.disabled = false; } } else if (act === 'webdav-restore') { btn.disabled = true; try { await webdavRestore(); } catch (err) { toast({ type: 'error', message: '恢复失败:' + (err.message || err) + webdavAllowHint(), timeout: 9000 }); } finally { btn.disabled = false; } } else if (act === 'reset-config') { if (!(await uiConfirm('恢复默认设置?图床、站点规则、WebDAV 等配置会重置为初始值,历史记录保留。', { title: '恢复默认设置', okText: '恢复默认', danger: true, }))) return; resetConfigToDefault(); refreshProviderOptions(); refreshSiteOptions(); toast({ type: 'success', message: '已恢复默认设置,历史记录已保留' }); } else if (act === 'clear-history') { if (!(await uiConfirm('清空所有历史记录?该操作不可恢复。', { title: '清空历史记录', okText: '清空', danger: true, }))) return; await History.clear(); state.list.items = []; reloadHistory(); toast({ type: 'success', message: '历史记录已清空' }); } else if (act === 'clear-all') { if (!(await uiConfirm('重置全部数据(配置 + 历史记录)?该操作不可恢复。', { title: '重置全部数据', okText: '重置', danger: true, }))) return; await History.clear(); resetConfigToDefault(); reloadHistory(); toast({ type: 'success', message: '已重置' }); } } function exportConfig() { const payload = { type: 'piu-config', schemaVersion: state.config.schemaVersion || 1, exportedAt: new Date().toISOString(), config: state.config, }; download('粘贴即传图-配置-' + stamp() + '.json', JSON.stringify(payload, null, 2)); const w = state.config.webdav || {}; const hasSecret = state.config.providers.some((p) => Object.keys(p.headers || {}).length) || !!w.password; if (hasSecret) { toast({ type: 'info', message: '注意:配置中包含图床 token / WebDAV 密码,请妥善保管', timeout: 6000 }); } } function importConfig() { pickFile('.json,application/json', async (text) => { let j; try { j = JSON.parse(text); } catch (e) { toast({ type: 'error', message: 'JSON 解析失败' }); return; } const cfg = j && j.config ? j.config : j; if (!cfg || !Array.isArray(cfg.providers)) { toast({ type: 'error', message: '不是有效的配置文件' }); return; } if (!(await uiConfirm('导入将覆盖当前配置(历史记录不受影响),继续?', { title: '导入配置', okText: '覆盖导入', danger: true, }))) return; state.config = safeAssign(defaultConfig(), cfg); state.config.providers = state.config.providers.map(normalizeProvider); state.config.webdav = normalizeWebdav(state.config.webdav); if (!state.config.providers.some((p) => p.id === state.config.activeProviderId)) { state.config.activeProviderId = state.config.providers[0].id; } saveConfig(); renderSettings(); renderProviders(); toast({ type: 'success', message: '配置已导入' }); }); } async function exportHistory() { const fmt = state.shadow.getElementById('piu-export-fmt').value; const all = await History.all(); if (!all.length) { toast({ type: 'info', message: '暂无历史记录' }); return; } const base = '粘贴即传图-历史-' + stamp(); if (fmt === 'json') { download(base + '.json', JSON.stringify({ type: 'piu-history', exportedAt: new Date().toISOString(), records: all }, null, 2)); } else if (fmt === 'csv') { const rows = [['url', 'deleteUrl', 'siteHost', 'providerName', 'filename', 'size', 'status', 'createdAt']]; all.forEach((r) => rows.push([ r.url, r.deleteUrl || '', r.siteHost || '', r.providerName || '', r.filename || '', r.size || '', r.status || '', new Date(r.createdAt).toISOString(), ])); const csv = rows.map((row) => row.map(csvCell).join(',')).join('\r\n'); download(base + '.csv', '\ufeff' + csv, 'text/csv;charset=utf-8'); } else if (fmt === 'md') { const md = all.map((r) => '- [' + (r.filename || 'image') + '](' + r.url + ') · ' + (r.siteHost || '') + ' · ' + fmtTime(r.createdAt)).join('\n'); download(base + '.md', md, 'text/markdown;charset=utf-8'); } else { download(base + '.txt', all.map((r) => r.url).join('\n'), 'text/plain;charset=utf-8'); } toast({ type: 'success', message: '已导出 ' + all.length + ' 条记录' }); } function csvCell(v) { const s = String(v == null ? '' : v); return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s; } function importHistory() { pickFile('.json,application/json', async (text) => { let j; try { j = JSON.parse(text); } catch (e) { toast({ type: 'error', message: 'JSON 解析失败' }); return; } const records = Array.isArray(j) ? j : (j && j.records); if (!Array.isArray(records)) { toast({ type: 'error', message: '文件中没有 records 数组' }); return; } if (!(await uiConfirm('将导入 ' + records.length + ' 条记录(与现有记录合并),继续?', { title: '导入历史记录', okText: '导入', }))) return; let n = 0; let skipped = 0; for (const r of records) { const safeUrl = r && safeHttpUrl(r.url); if (!safeUrl) { skipped++; continue; } await History.add(safeAssign({ id: uuid(), providerId: '', providerName: '', pageUrl: '', pageTitle: '', siteHost: '', filename: '', mime: '', size: 0, insertedAs: state.config.insertMode, status: 'ok', }, r, { id: uuid(), url: safeUrl, deleteUrl: safeHttpUrl(r.deleteUrl), })); n++; } reloadHistory(); toast({ type: 'success', message: '已导入 ' + n + ' 条记录' + (skipped ? ',跳过 ' + skipped + ' 条无效链接' : '') }); }); } /* ---------------- WebDAV 备份 ---------------- */ function b64utf8(str) { try { const bytes = new TextEncoder().encode(String(str)); let bin = ''; for (let i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]); return btoa(bin); } catch (e) { try { return btoa(unescape(encodeURIComponent(String(str)))); } catch (e2) { return ''; } } } // 补全协议、去掉尾部斜杠:dav.jianguoyun.com/dav/ -> https://dav.jianguoyun.com/dav function normalizeDavBase(raw) { let u = String(raw || '').trim(); if (!u) throw new Error('请先填写 WebDAV 地址'); if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(u)) u = 'https://' + u.replace(/^\/+/, ''); if (!/^https?:\/\//i.test(u)) throw new Error('WebDAV 地址只支持 http/https'); return u.replace(/\/+$/, ''); } // 去掉空段与 .. / . 段,避免通过配置写到预期目录之外 function sanitizeDavPath(str) { return String(str == null ? '' : str) .split('/') .map((s) => s.trim()) .filter((s) => s && s !== '.' && s !== '..') .join('/'); } // 目标文件地址://,文件夹留空时用 ImgNest function webdavTarget() { const w = state.config.webdav || {}; const base = normalizeDavBase(w.url); const rawFolder = sanitizeDavPath(w.folder == null ? DEFAULT_DAV_FOLDER : w.folder); const folder = rawFolder || DEFAULT_DAV_FOLDER; const rawFile = sanitizeDavPath(w.file || DEFAULT_DAV_FILE); if (!rawFile) throw new Error('WebDAV 文件名不能为空'); return { base, folder, file: rawFile, url: base + '/' + folder + '/' + rawFile }; } function webdavAllowHint() { try { return allowHint(webdavTarget().url); } catch (e) { return ''; } } function webdavHeaders(extra) { const w = state.config.webdav || {}; const headers = Object.assign({}, extra || {}); if (w.username) headers.Authorization = 'Basic ' + b64utf8(w.username + ':' + (w.password || '')); return headers; } async function webdavTest() { const target = webdavTarget(); const res = await xhrRequest({ method: 'PROPFIND', url: target.url, headers: webdavHeaders({ Depth: '0' }), timeout: 15000 }); if (res.status === 401 || res.status === 403) throw new Error('认证失败(HTTP ' + res.status + ')'); if (res.status === 404) return '服务器可访问:' + target.url + '(文件尚不存在,首次备份会自动创建目录)'; if (res.status === 405) return '服务器可访问(该服务器不支持 PROPFIND)'; if (res.status >= 200 && res.status < 300) return '连接成功,认证通过'; throw new Error('HTTP ' + res.status); } // 逐级创建目标所在目录(已存在时服务器一般返回 405,忽略即可) async function ensureDavParents(target) { const dir = target.url.slice(target.base.length + 1); const parts = dir.split('/').slice(0, -1).filter(Boolean); let cur = target.base; for (const p of parts) { cur += '/' + p; try { const res = await xhrRequest({ method: 'MKCOL', url: cur, headers: webdavHeaders(), timeout: 15000 }); if (res.status === 401 || res.status === 403) return false; } catch (e) { return false; } } return true; } async function webdavBackup(opts) { const silent = !!(opts && opts.silent); const target = webdavTarget(); const url = target.url; const records = await History.all(); const payload = { type: 'piu-backup', schemaVersion: 1, appVersion: VERSION, exportedAt: new Date().toISOString(), config: state.config, records, }; const body = JSON.stringify(payload, null, 2); const put = () => xhrRequest({ method: 'PUT', url, headers: webdavHeaders({ 'Content-Type': 'application/json;charset=utf-8' }), data: body, timeout: 30000, }); let res = await put(); if (res.status === 404 || res.status === 409) { if (await ensureDavParents(target)) res = await put(); } if (res.status === 401 || res.status === 403) throw new Error('认证失败(HTTP ' + res.status + ')'); if (res.status < 200 || res.status >= 300) throw new Error('HTTP ' + res.status); if (!silent) { toast({ type: 'success', message: '备份完成:' + records.length + ' 条记录,' + fmtBytes(body.length), timeout: 6000 }); } return { count: records.length, bytes: body.length, url }; } async function webdavRestore() { const target = webdavTarget(); const url = target.url; const res = await xhrRequest({ method: 'GET', url, headers: webdavHeaders(), timeout: 30000 }); if (res.status === 401 || res.status === 403) throw new Error('认证失败(HTTP ' + res.status + ')'); if (res.status === 404) throw new Error('备份文件不存在'); if (res.status < 200 || res.status >= 300) throw new Error('HTTP ' + res.status); let j; try { j = JSON.parse(res.responseText || ''); } catch (e) { throw new Error('备份文件不是有效 JSON'); } const cfg = j && !Array.isArray(j) ? j.config : null; const records = Array.isArray(j) ? j : (j && j.records); if (!cfg && !Array.isArray(records)) throw new Error('备份文件格式不正确'); const tips = []; if (cfg) tips.push('图床与设置将被覆盖'); if (Array.isArray(records)) tips.push('合并 ' + records.length + ' 条历史记录'); if (!(await uiConfirm('从 WebDAV 恢复备份?\n' + tips.join(';') + '。\n\n继续?', { title: '从备份恢复', okText: '恢复', danger: true, }))) return; if (cfg && Array.isArray(cfg.providers)) { const next = safeAssign(defaultConfig(), cfg); next.providers = next.providers.map(normalizeProvider); if (!next.providers.some((p) => p.id === next.activeProviderId)) next.activeProviderId = next.providers[0].id; next.webdav = normalizeWebdav(cfg.webdav); state.config = next; saveConfig(); if (!state.ui.panel.hidden) renderSettings(); renderProviders(); } let added = 0; let skipped = 0; if (Array.isArray(records)) { const arr = readRecords(); const seen = new Set(arr.map((r) => (r.url || '') + '|' + (r.createdAt || 0))); records.forEach((r) => { const safeUrl = r && safeHttpUrl(r.url); if (!safeUrl) { skipped++; return; } const key = safeUrl + '|' + (r.createdAt || 0); if (seen.has(key)) return; seen.add(key); arr.push(safeAssign({}, r, { id: r.id || uuid(), url: safeUrl, deleteUrl: safeHttpUrl(r.deleteUrl), })); added++; }); sortDesc(arr); if (arr.length > MAX_RECORDS) arr.length = MAX_RECORDS; writeRecords(arr); } state.list.items = []; if (!state.ui.panel.hidden && !state.shadow.querySelector('[data-pane="history"]').hidden) { refreshSiteOptions(); reloadHistory(); } toast({ type: 'success', message: '恢复完成:配置已更新,新增 ' + added + ' 条历史记录' + (skipped ? ',跳过 ' + skipped + ' 条无效链接' : ''), timeout: 6000, }); } let autoBackupTimer = null; function scheduleAutoBackup() { const w = state.config.webdav || {}; if (!w.auto || !w.url) return; clearTimeout(autoBackupTimer); autoBackupTimer = setTimeout(() => { webdavBackup({ silent: true }).catch(() => { /* 自动备份失败时静默 */ }); }, 5000); } function pickFile(accept, cb) { const input = document.createElement('input'); input.type = 'file'; input.accept = accept; input.style.display = 'none'; document.body.appendChild(input); input.addEventListener('change', () => { const file = input.files && input.files[0]; if (!file) { input.remove(); return; } const fr = new FileReader(); fr.onload = () => { cb(String(fr.result || '')); input.remove(); }; fr.onerror = () => { toast({ type: 'error', message: '读取文件失败' }); input.remove(); }; fr.readAsText(file); }); input.click(); } function stamp() { const d = new Date(); return d.getFullYear() + pad2(d.getMonth() + 1) + pad2(d.getDate()) + '-' + pad2(d.getHours()) + pad2(d.getMinutes()) + pad2(d.getSeconds()); } /* ========================================================================= * 8. 粘贴处理 * ========================================================================= */ let pasteMods = { shift: false, alt: false }; let modsTimer = null; // 同一次粘贴被重复派发时的去重(同一标签/输入框、同样的图片、400ms 内) let lastPaste = { sig: '', at: 0, target: null }; function trackMods(e) { const isV = e.code === 'KeyV' || String(e.key || '').toLowerCase() === 'v'; if (!isV) return; pasteMods = { shift: !!e.shiftKey, alt: !!e.altKey }; clearTimeout(modsTimer); modsTimer = setTimeout(() => { pasteMods = { shift: false, alt: false }; }, 800); } function getImageFiles(cd) { const out = []; const seen = new Set(); if (!cd) return out; // 同一张图片在剪贴板里可能出现多次(多格式/编辑器重复写入),按 名称+大小+类型 去重 const add = (f) => { if (!f || !/^image\//i.test(f.type || '')) return; const sig = [f.name || '', f.size || 0, f.type || ''].join('|'); if (seen.has(sig)) return; seen.add(sig); out.push(f); }; if (cd.items && cd.items.length) { for (let i = 0; i < cd.items.length; i++) { const item = cd.items[i]; if (!item || item.kind !== 'file') continue; if (!/^image\//i.test(item.type || '')) continue; add(item.getAsFile && item.getAsFile()); } } if (!out.length && cd.files && cd.files.length) { for (let i = 0; i < cd.files.length; i++) add(cd.files[i]); } return out; } function validateFile(file, provider) { if (!/^image\//i.test(file.type || '')) return '不是图片文件'; const maxMB = Number(provider.maxSizeMB) > 0 ? Number(provider.maxSizeMB) : 5; if (file.size > maxMB * 1024 * 1024) { return '图片超过 ' + maxMB + ' MB(' + fmtBytes(file.size) + ')'; } if (!file.size) return '图片为空'; return ''; } async function handleImageFiles(files, editable) { const provider = activeProvider(); if (!provider) { toast({ type: 'error', message: '没有可用的图床,请先在面板中配置' }); return; } if (!provider.uploadUrl) { toast({ type: 'error', message: '当前图床未填写上传地址' }); return; } const mode = state.config.insertMode || 'url'; const root = editableRoot(editable); const tasks = []; let seq = 0; for (const file of files) { const err = validateFile(file, provider); if (err) { toast({ type: 'error', message: (file.name || '图片') + ':' + err }); continue; } const token = '[上传中…]' + ZWSP.repeat(seq + 1); seq++; insertTextInto(root, token); tasks.push({ file, token }); } if (!tasks.length) return; await pool(tasks, 2, async (task) => { const { file, token } = task; const filename = file.name || 'image.png'; try { const result = await uploadWithRetry(file, provider, HOST); const text = formatLink(result.url, filename, mode); const isRich = !!root.isContentEditable; let replaced = false; if (isRich) { replaced = replaceInContentEditable(root, token, text, result.url, mode, filename); } else { replaced = replaceInInput(root, token, text); } if (!replaced) { insertTextInto(root, text); } const rec = { id: uuid(), url: result.url, deleteUrl: result.deleteUrl || '', providerId: provider.id, providerName: provider.name, pageUrl: location.href.slice(0, 2000), pageTitle: (document.title || '').slice(0, 200), siteHost: location.hostname, filename: filename, mime: file.type || '', size: file.size || 0, insertedAs: mode, status: 'ok', }; await History.add(rec); scheduleAutoBackup(); if (state.config.autoCopy) await copyText(result.url); toast({ type: 'success', message: '已上传并插入链接', actions: [ { label: '复制链接', keepOpen: false, onClick: () => copyText(result.url) }, { label: '查看历史', keepOpen: false, onClick: () => openPanel('history') }, ], }); if (!state.ui.panel.hidden && !state.shadow.querySelector('[data-pane="history"]').hidden) { state.list.items.unshift(rec); if (state.ui.listEl.querySelector('.piu-empty')) state.ui.listEl.innerHTML = ''; state.ui.listEl.insertAdjacentHTML('afterbegin', recordItemHtml(rec)); } } catch (err) { if (root.isContentEditable) { replaceInContentEditable(root, token, '', '', 'url', ''); } else { replaceInInput(root, token, ''); } const msg = (err && err.message) || String(err); toast({ type: 'error', message: '上传失败:' + msg, timeout: 8000, actions: [{ label: '打开图床设置', keepOpen: false, onClick: () => openPanel('providers') }], }); } }); } function onPaste(e) { const cfg = state.config; if (!cfg || !cfg.enabled) return; if (state.hostEl && e.composedPath && e.composedPath().indexOf(state.hostEl) > -1) return; const editable = findEditable(e.target); if (!editable) return; if (isBlockedInput(editable)) return; if (!siteEnabled(HOST)) return; const files = getImageFiles(e.clipboardData); if (!files.length) return; if (pasteMods.shift) return; if (!pasteMods.alt && isNativePassthrough(editable, cfg)) return; const provider = activeProvider(); if (!provider) { toast({ type: 'error', message: '没有可用的图床,请先在面板中配置' }); return; } if (!provider.uploadUrl) { toast({ type: 'error', message: '当前图床未填写上传地址' }); return; } // 全部文件都不合法(超限/非图片)时交给原生粘贴,避免丢图 if (!files.some((f) => !validateFile(f, provider))) return; // 同一张图片、同一个输入框,短时间内的重复 paste 事件只处理一次 const sig = files.map((f) => [f.name || '', f.size || 0, f.type || ''].join('|')).join(';'); const now = Date.now(); if (sig && lastPaste.sig === sig && lastPaste.target === editable && now - lastPaste.at < 400) { e.preventDefault(); e.stopPropagation(); if (e.stopImmediatePropagation) e.stopImmediatePropagation(); return; } lastPaste = { sig: sig, at: now, target: editable }; e.preventDefault(); e.stopPropagation(); if (e.stopImmediatePropagation) e.stopImmediatePropagation(); handleImageFiles(files, editable); } /* ========================================================================= * 9. 启动 * ========================================================================= */ const INSTANCE_ATTR = 'data-piu-instance'; function existingInstance() { try { const root = document.documentElement; const ver = root && root.getAttribute(INSTANCE_ATTR); if (ver) return ver; // 旧版本没有写标记,但会挂载同 id 的宿主节点 if (document.getElementById('piu-host')) return 'legacy'; } catch (e) { /* ignore */ } return ''; } function init() { const dup = existingInstance(); if (dup) { console.warn('[粘贴即传图] 本页已存在脚本实例(' + dup + '),当前实例 v' + VERSION + ' 已跳过。请检查是否重复安装了多个版本或多个管理器。'); return; } try { document.documentElement.setAttribute(INSTANCE_ATTR, VERSION); } catch (e) { /* ignore */ } state.config = loadConfig(); document.addEventListener('keydown', trackMods, true); document.addEventListener('paste', onPaste, true); mountUI(); if (IS_TOP) { bindMenu(); } else { // iframe 内也需要 UI 承载(Toast),但不显示悬浮按钮 state.ui.panel.hidden = true; } applyFabVisibility(); } function bindMenu() { if (typeof GM_registerMenuCommand !== 'function') return; try { GM_registerMenuCommand('打开面板', () => openPanel('history')); GM_registerMenuCommand('图床设置', () => openPanel('providers')); GM_registerMenuCommand('启用/禁用粘贴上传', () => { state.config.enabled = !state.config.enabled; saveConfig(); toast({ type: 'info', message: state.config.enabled ? '粘贴上传已启用' : '粘贴上传已禁用' }); }); GM_registerMenuCommand('当前站点启用/禁用', () => { const next = !siteEnabled(HOST); state.config.siteEnabled[HOST] = next; saveConfig(); toast({ type: 'info', message: HOST + (next ? ' 已启用' : ' 已禁用') }); }); GM_registerMenuCommand('显示/隐藏右下角图标', () => { state.config.showFab = state.config.showFab === false; saveConfig(); applyFabVisibility(); toast({ type: 'info', message: state.config.showFab ? '已显示悬浮图标' : '已隐藏悬浮图标(可用 Alt+Shift+H 打开面板)', }); }); } catch (e) { /* ignore */ } } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', init, { once: true }); } else { init(); } })();