// ==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 '';
case 'bbcode': return '[img]' + url + '[/img]';
case 'html': return '';
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 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('/');
}
// 目标文件地址: