// ==UserScript==
// @name 百度网盘分享批量转存|非会员自动分批、按文件名和大小去重、可续跑
// @name:zh-CN 百度网盘分享批量转存|非会员自动分批、按文件名和大小去重、可续跑
// @name:en Baidu Netdisk Share Batch Saver — Auto-batched, Deduplicated, Resumable
// @namespace https://github.com/yilecoding/helper-scripts
// @version 2026.10.29.10
// @description 在百度网盘分享页把整个文件夹转存到自己的网盘:自动拆成每批 500 个(非会员单次上限),先和目标文件夹按文件名 + 大小核对,已有的跳过;每批转存后核对到齐再继续,中途停了重新扫描就能续跑。
// @description:zh-CN 在百度网盘分享页把整个文件夹转存到自己的网盘:自动拆成每批 500 个(非会员单次上限),先和目标文件夹按文件名 + 大小核对,已有的跳过;每批转存后核对到齐再继续,中途停了重新扫描就能续跑。
// @description:en Saves a whole folder from a Baidu Netdisk share link into your own netdisk: splits it into batches of 500 (the per-transfer limit for non-members), compares against the target folder by file name and size so existing files are skipped, verifies each batch before the next, and resumes after a rescan if stopped.
// @author 壹樂(V:ita1125)
// @match https://pan.baidu.com/s/*
// @match https://pan.baidu.com/share/*
// @noframes
// @grant GM_getValue
// @grant GM_setValue
// @grant GM_registerMenuCommand
// @grant unsafeWindow
// @license MIT
// @run-at document-idle
// @homepageURL https://github.com/yile2020/helper-scripts
// @supportURL https://github.com/yile2020/helper-scripts/issues
// @updateURL https://raw.githubusercontent.com/yile2020/helper-scripts/main/baidu-share-dedupe/baidu-share-dedupe.user.js
// @downloadURL https://raw.githubusercontent.com/yile2020/helper-scripts/main/baidu-share-dedupe/baidu-share-dedupe.user.js
// ==/UserScript==
// 脚本持续更新维护,欢迎 star / watch 仓库获取最新版本:
// https://github.com/yile2020/helper-scripts
(function () {
'use strict';
/** 日志前缀。控制台过滤框输入「分享转存」只看本脚本。 */
const TAG = '[分享转存]';
// =========================================================================
// 配置
// =========================================================================
const CONFIG = {
batchSize: 500, // 每批转存多少个:非会员单次转存上限是 500
sharePageSize: 100, // 分享目录每页条数(网页版分享页就是 100)
diskPageSize: 1000, // 自己网盘目录每页条数(接口上限 1000)
verifyDelayMs: 3000, // 转存成功后隔这么久查一次目标文件夹,看这批到齐没有
verifyTries: 20, // 最多查这么多次(约 1 分钟)还没到齐就停下
maxPages: 1000, // 翻这么多页还没完就当接口异常,停下来别死循环
};
/** 网页版固定带的几个公共参数。 */
const WEB_PARAMS = { app_id: 250528, channel: 'chunlei', clienttype: 0, web: 1 };
// =========================================================================
// 分享链接
// =========================================================================
/**
* 当前页面的分享短链(接口里的 shorturl)。两种地址:
* /s/1AbCdEf… → AbCdEf…(去掉开头的 1)
* /share/init?surl=AbC… → AbC…(输提取码的页面)
* 不是分享页返回空串。
*/
function shareKey(loc) {
const m = /^\/s\/1([\w-]+)/.exec(loc.pathname);
if (m) return m[1];
if (/^\/share\/(init|link)\b/.test(loc.pathname)) return new URL(loc.href).searchParams.get('surl') || '';
return '';
}
// =========================================================================
// 接口
// =========================================================================
/**
* fs_id 是 19 位左右的整数,超过 Number.MAX_SAFE_INTEGER,JSON.parse 会把末几位变成 0,
* 转存时就会指向别的文件(或报文件不存在)。解析前先把它变成字符串。
*/
function parseJSON(raw) {
return JSON.parse(raw.replace(/("fs_id"\s*:\s*)(\d+)/g, '$1"$2"'));
}
/** 常见 errno 的人话说明;其余照接口的 show_msg 显示。 */
const ERRNO_HINT = {
'-6': '未登录或登录已失效,请先在这个浏览器登录百度网盘',
'-9': '文件夹不存在',
};
/** 同源请求(带登录 Cookie)。errno 非 0 抛错,错误信息带上接口名方便排查。 */
async function request(endpoint, query, form) {
const url = new URL(endpoint, location.origin);
for (const [key, value] of Object.entries(query || {})) {
if (value !== undefined && value !== null && value !== '') url.searchParams.set(key, String(value));
}
const response = await fetch(url, {
method: form ? 'POST' : 'GET',
credentials: 'include',
headers: form ? { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } : {},
body: form ? new URLSearchParams(form) : undefined,
});
if (!response.ok) throw new Error(endpoint + ':HTTP ' + response.status);
let data;
try {
data = parseJSON(await response.text());
} catch (e) {
throw new Error(endpoint + ':返回的不是 JSON,可能要先过验证码或重新登录');
}
const errno = Number(data.errno ?? data.errNo ?? 0);
if (errno !== 0) {
const err = new Error(endpoint + ':' + (ERRNO_HINT[errno] || data.show_msg || data.errmsg || data.error_msg || '出错了') + '(errno ' + errno + ')');
err.errno = errno;
throw err;
}
return data;
}
function cookie(name) {
const item = document.cookie.split('; ').find((x) => x.startsWith(name + '='));
return item ? decodeURIComponent(item.slice(name.length + 1)) : '';
}
/**
* 分享页把 shareid / 分享者 uk / bdstoken 放在全局变量里:老版是 window.yunData,
* 新版是 window.locals(有的是普通对象,有的带 get())。都试一遍。
*/
function pageVar(key) {
const w = unsafeWindow;
if (w.yunData && w.yunData[key] != null) return w.yunData[key];
const locals = w.locals;
if (locals) {
if (typeof locals.get === 'function') {
const v = locals.get(key);
if (v != null) return v;
}
if (locals[key] != null) return locals[key];
}
return null;
}
let cachedInfo = null;
/** { shareid, uk, token }。bdstoken 页面上没有时问一次接口。成功后记住,选文件夹和扫描共用。 */
async function shareInfo() {
if (!cachedInfo) cachedInfo = await readShareInfo();
return cachedInfo;
}
async function readShareInfo() {
const shareid = pageVar('shareid') ?? pageVar('share_id');
const uk = pageVar('share_uk') ?? pageVar('shareUk') ?? pageVar('uk');
if (!shareid || !uk) throw new Error('页面上没找到分享信息。如果还没输提取码,先输提取码进入分享页;已经进入的话刷新一下再试');
let token = pageVar('bdstoken') || '';
if (!token) {
const data = await request('/api/gettemplatevariable', { clienttype: 0, app_id: 250528, fields: '["bdstoken"]' });
token = (data.result && data.result.bdstoken) || data.bdstoken || '';
}
if (!token) throw new Error('没取到 bdstoken,请确认这个浏览器已经登录百度网盘');
return { shareid: String(shareid), uk: String(uk), token };
}
// =========================================================================
// 读目录
// =========================================================================
/** 接口里的一行 → { id, name, size, isdir }。 */
function normalize(row) {
return {
id: String(row.fs_id ?? row.fsid ?? ''),
name: row.server_filename || row.filename || '',
size: Number(row.size ?? row.file_size ?? -1),
isdir: Number(row.isdir || 0) === 1,
path: row.path || '',
};
}
/**
* 一页一页读到底。一页不满就是最后一页。
* 翻页时出现重复的 fs_id 说明分页错位了(接口缓存、排序不稳定),继续读可能漏文件,直接停。
*/
async function readAll(label, fetchPage, pageSize, quiet) {
const files = [];
const ids = new Set();
for (let page = 1; page <= CONFIG.maxPages; page++) {
const data = await fetchPage(page);
const rows = data.list || data.records || [];
if (!Array.isArray(rows)) throw new Error(label + '第 ' + page + ' 页没有文件列表');
for (const row of rows) {
const file = normalize(row);
if (!file.id || !file.name) throw new Error(label + '第 ' + page + ' 页有文件信息不完整');
if (ids.has(file.id)) throw new Error(label + '翻页时出现重复文件,为防漏文件已停止,请稍后重试');
ids.add(file.id);
files.push(file);
}
if (!quiet) Panel.say(label + ':已读取 ' + files.length + ' 项', 'busy');
if (rows.length < pageSize) return files;
}
throw new Error(label + '超过 ' + CONFIG.maxPages + ' 页,已停止');
}
/** '/a/b/' → '/a/b','' → '/'。 */
function cleanPath(value) {
return '/' + String(value || '').trim().replace(/^\/+|\/+$/g, '');
}
/** 分享里的一个文件夹。'/' 是分享的最外层,要用 root=1 列。 */
function readShareDir(info, dir, quiet) {
const sekey = cookie('BDCLND') || pageVar('sekey') || '';
const where = dir === '/' ? { root: 1 } : { dir };
return readAll('分享文件夹', (page) => request('/share/list', {
...WEB_PARAMS, shareid: info.shareid, uk: info.uk, shorturl: SURL, sekey, ...where,
page, num: CONFIG.sharePageSize, order: 'name', desc: 0,
}), CONFIG.sharePageSize, quiet);
}
/**
* 自己网盘里的一个文件夹。quiet:转存后反复核对时不刷状态行。
* 每次请求带一个不重复的 _t:转存后同样的 URL 可能一直拿到缓存的旧列表,
* 核对就永远等不到新文件。
*/
async function readDiskDir(dir, quiet) {
try {
return await readAll('目标文件夹', (page) => request('/api/list', {
clienttype: 0, web: 1, dir, order: 'name', desc: 0, num: CONFIG.diskPageSize, page,
_t: Date.now() + '-' + (++listSeq),
}), CONFIG.diskPageSize, quiet);
} catch (error) {
if (error.errno === -9) throw new Error('我的网盘里没有文件夹 ' + dir + ',请先在网盘里新建,或点「浏览」选一个已有的');
throw error;
}
}
let listSeq = 0;
// =========================================================================
// 核对
// =========================================================================
/**
* 按文件名 + 大小核对来源和目标(来源里的子文件夹不在这里,见 splitDirs):
* 目标里没有同名的 → 待转存
* 同名且大小相同 → 已存在,跳过
* 同名但大小不同 / 是文件夹 → 停下来。转存过去百度会自动改名(xxx(1).jpg),
* 悄悄多出一份比漏掉更难发现,交给人判断。
* 来源自己有重名也停:按名字核对时分不清是哪一个。
*/
function compare(source, target) {
const byName = new Map(target.map((file) => [file.name, file]));
const seen = new Set();
const missing = [];
let existing = 0;
for (const file of source) {
if (seen.has(file.name)) throw new Error('分享文件夹里有重名文件:' + file.name);
seen.add(file.name);
const found = byName.get(file.name);
if (!found) missing.push(file);
else if (found.isdir || found.size !== file.size) {
throw new Error('目标里已有同名' + (found.isdir ? '文件夹' : '但大小不同的文件') + ':' + file.name
+ (found.isdir ? '' : '(分享 ' + file.size + ' 字节,目标 ' + found.size + ' 字节)') + '。为避免重复或覆盖已停止');
} else existing++;
}
return { missing, existing };
}
/**
* 来源里的子文件夹不转:整个文件夹转过去没法按文件去重,也绕不开 500 个的上限
* (文件夹里的文件也算数)。列出名字,需要的话选进去单独转。
*/
function splitDirs(rows) {
return { files: rows.filter((row) => !row.isdir), dirs: rows.filter((row) => row.isdir).map((row) => row.name) };
}
/** 名字列表太长时只列前几个。 */
function nameList(names, max = 3) {
return names.slice(0, max).join('、') + (names.length > max ? ' 等 ' + names.length + ' 个' : '');
}
// =========================================================================
// 转存
// =========================================================================
/** 把一批文件(来自分享)转存到目标文件夹。fsidlist 里的 id 是原样的字符串,不经过 Number。 */
function transfer(info, files, targetDir) {
return request('/share/transfer', {
...WEB_PARAMS, shareid: info.shareid, from: info.uk, bdstoken: info.token,
}, {
fsidlist: '[' + files.map((file) => file.id).join(',') + ']',
path: targetDir,
});
}
const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
// =========================================================================
// 默认值
// =========================================================================
/**
* 分享页当前打开的文件夹。分享页在地址里记路径,见过两种写法:
* /s/1xxx#list/path=%2F照片%2F2024 (老版,hash)
* /s/1xxx?path=%2F照片%2F2024 (新版,query)
* 都没有(或在最外层)返回空串。
*/
function browsingPath(loc) {
const url = new URL(loc.href);
let raw = url.searchParams.get('path');
if (!raw) {
const m = /[#&/]path=([^&]*)/.exec(url.hash);
if (m) {
try { raw = decodeURIComponent(m[1]); } catch (e) { raw = ''; }
}
}
const dir = raw ? cleanPath(raw) : '/';
return dir === '/' ? '' : dir;
}
const Defaults = {
/** 用户自己改过来源就不再自动填。 */
sourceTouched: false,
init() {
const target = GM_getValue('lastTarget', '');
if (target) Panel.$('[data-ref=target]').value = target;
Panel.$('[data-ref=source]').addEventListener('input', (e) => { if (e.isTrusted) this.sourceTouched = true; });
window.addEventListener('hashchange', () => this.fillSource());
// 预填完成后在宿主元素上打个标记(测试靠它等预填结束)
this.fillSource().finally(() => { Panel.host.dataset.ready = '1'; });
},
/**
* 来源:地址里有路径就用;在最外层的话,最外层只有一个文件夹(最常见的分享方式)就直接选它。
* 只是预填,读不到不报错。
*/
async fillSource() {
if (this.sourceTouched || Job.running) return;
const set = (dir) => {
const input = Panel.$('[data-ref=source]');
if (this.sourceTouched || input.value === dir) return;
input.value = dir;
input.dispatchEvent(new Event('input'));
};
const here = browsingPath(location);
if (here) return set(here);
try {
const top = await readShareDir(await shareInfo(), '/', true);
if (top.length === 1 && top[0].isdir) set(top[0].path || '/' + top[0].name);
} catch (e) {
console.info(TAG, '没能预填来源:', e.message);
}
},
/** 扫描成功后记住目标文件夹,下次打开别的分享直接用。 */
rememberTarget(dir) {
GM_setValue('lastTarget', dir);
},
};
// =========================================================================
// 面板
// =========================================================================
const UI_CSS = `
:host { all: initial; }
:host([hidden]), [hidden] { display: none !important; }
* { box-sizing: border-box; }
.panel {
--blue: #06a7ff; --blue-d: #0590dd; --blue-l: #e8f6ff;
--ink: #1f2933; --sub: #6b7785; --line: #e6ebf1; --bg: #f7f9fc;
--ok: #12b76a; --warn: #f79009; --bad: #f04438;
position: fixed; right: 20px; bottom: 20px; z-index: 2147483647;
width: 392px; max-width: calc(100vw - 40px); max-height: calc(100vh - 40px); overflow: auto;
background: #fff; color: var(--ink); border-radius: 16px;
box-shadow: 0 12px 40px rgba(15, 35, 70, .18), 0 0 0 1px rgba(15, 35, 70, .06);
font: 13px/1.55 system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
}
.head {
display: flex; align-items: center; gap: 10px; padding: 14px 14px 12px 16px;
background: linear-gradient(135deg, #06a7ff 0%, #3b7cff 100%); color: #fff;
border-radius: 16px 16px 0 0; position: sticky; top: 0; z-index: 1;
}
.panel.folded .head { border-radius: 16px; }
.logo {
flex: none; width: 32px; height: 32px; border-radius: 9px; display: grid; place-items: center;
background: rgba(255,255,255,.22); font-size: 17px;
}
.title { flex: 1; min-width: 0; }
.title b { display: block; font-size: 15px; letter-spacing: .3px; }
.title small { display: block; font-size: 11.5px; opacity: .85; }
.icon {
all: unset; flex: none; width: 28px; height: 28px; border-radius: 8px; display: grid; place-items: center;
cursor: pointer; font-size: 15px; color: #fff; transition: background .15s;
}
.icon:hover { background: rgba(255,255,255,.2); }
.body { padding: 14px 16px 16px; }
.status {
display: flex; align-items: flex-start; gap: 8px; padding: 9px 11px; border-radius: 10px;
background: var(--bg); color: var(--ink);
}
.status::before { content: ""; flex: none; width: 8px; height: 8px; margin-top: 6px; border-radius: 50%; background: var(--sub); }
.status[data-tone=busy]::before { background: var(--blue); animation: pulse 1.2s ease-in-out infinite; }
.status[data-tone=ok] { background: #ecfdf3; }
.status[data-tone=ok]::before { background: var(--ok); }
.status[data-tone=warn] { background: #fffaeb; color: #93370d; }
.status[data-tone=warn]::before { background: var(--warn); }
.status[data-tone=bad] { background: #fef3f2; color: #b42318; }
.status[data-tone=bad]::before { background: var(--bad); }
@keyframes pulse { 0%, 100% { opacity: 1 } 50% { opacity: .3 } }
.steps { display: flex; gap: 6px; margin: 0 0 14px; padding: 0; list-style: none; }
.steps li {
flex: 1; display: flex; align-items: center; gap: 6px; padding: 6px 8px; border-radius: 9px;
background: var(--bg); color: var(--sub); font-size: 12px; white-space: nowrap;
}
.steps li i {
flex: none; width: 18px; height: 18px; border-radius: 50%; display: grid; place-items: center;
background: #dfe5ec; color: #fff; font: 600 11px/1 system-ui, sans-serif;
}
.steps li.on { background: var(--blue-l); color: var(--blue-d); font-weight: 600; }
.steps li.on i { background: var(--blue); }
.steps li.done { color: var(--ink); }
.steps li.done i { background: var(--ok); font-size: 0; }
.steps li.done i::after { content: "✓"; font-size: 11px; }
.field { display: block; margin-bottom: 10px; }
.field > span { display: block; margin-bottom: 4px; color: var(--sub); font-size: 12px; }
.row { display: flex; gap: 6px; }
input {
flex: 1; min-width: 0; height: 32px; padding: 0 10px; font: inherit; color: var(--ink);
border: 1px solid var(--line); border-radius: 8px; background: #fff; outline: none; transition: border-color .15s, box-shadow .15s;
}
input:focus { border-color: var(--blue); box-shadow: 0 0 0 3px rgba(6,167,255,.15); }
input:disabled { background: var(--bg); color: var(--sub); }
.btn {
all: unset; box-sizing: border-box; height: 32px; padding: 0 14px; border-radius: 8px; cursor: pointer;
display: inline-flex; align-items: center; justify-content: center; gap: 4px; white-space: nowrap;
font-size: 13px; font-weight: 500; border: 1px solid var(--line); background: #fff; color: var(--ink);
transition: background .15s, border-color .15s, opacity .15s;
}
.btn:hover { background: var(--bg); }
.btn.primary { background: var(--blue); border-color: var(--blue); color: #fff; }
.btn.primary:hover { background: var(--blue-d); }
.btn.danger { color: var(--bad); }
.btn[disabled] { opacity: .45; cursor: not-allowed; pointer-events: none; }
.stats { display: grid; grid-template-columns: repeat(4, 1fr); gap: 6px; margin: 2px 0 10px; }
.stat { padding: 8px 6px 7px; border-radius: 10px; background: var(--bg); text-align: center; }
.stat b { display: block; font-size: 17px; line-height: 1.2; font-variant-numeric: tabular-nums; }
.stat span { font-size: 11px; color: var(--sub); }
.stat.todo b { color: var(--blue); }
.stat.done b { color: var(--ok); }
.progress { margin: 0 0 10px; }
.bar { height: 6px; border-radius: 99px; background: var(--line); overflow: hidden; }
.bar i { display: block; height: 100%; width: 0; border-radius: inherit; background: linear-gradient(90deg, #06a7ff, #3b7cff); transition: width .4s ease; }
.progress small { display: flex; justify-content: space-between; margin-top: 4px; color: var(--sub); font-size: 11.5px; font-variant-numeric: tabular-nums; }
.btn.sm { height: 32px; padding: 0 11px; font-size: 12.5px; }
.picker {
margin-top: 6px; border: 1px solid var(--line); border-radius: 10px; overflow: hidden;
box-shadow: 0 4px 14px rgba(15,35,70,.08);
}
.crumbs {
display: flex; align-items: center; gap: 2px; flex-wrap: wrap; padding: 7px 8px; background: var(--bg);
border-bottom: 1px solid var(--line); font-size: 12px;
}
.crumbs button { all: unset; cursor: pointer; padding: 1px 5px; border-radius: 5px; color: var(--blue-d); }
.crumbs button:hover { background: var(--blue-l); }
.crumbs .here { color: var(--ink); font-weight: 600; cursor: default; background: none !important; }
.crumbs i { color: #b6c0cc; font-style: normal; }
.crumbs .x { margin-left: auto; color: var(--sub); }
.folders { max-height: 188px; overflow: auto; padding: 4px; }
.folders button {
all: unset; box-sizing: border-box; display: flex; align-items: center; gap: 8px; width: 100%;
padding: 6px 8px; border-radius: 7px; cursor: pointer; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;
}
.folders button:hover { background: var(--blue-l); }
.folders button::before { content: "📁"; flex: none; }
.folders .up::before { content: "↩"; color: var(--sub); }
.folders .hint { padding: 10px 8px; color: var(--sub); font-size: 12px; }
.folders .hint.bad { color: var(--bad); }
.pick-foot { display: flex; align-items: center; gap: 8px; padding: 8px; border-top: 1px solid var(--line); }
.pick-foot span { flex: 1; min-width: 0; color: var(--sub); font-size: 12px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.actions { display: flex; gap: 8px; margin-top: 12px; }
.actions .btn { flex: 1; }
details.more { margin: -2px 0 10px; }
details.more summary { cursor: pointer; color: var(--sub); font-size: 12px; user-select: none; }
details.more .field { margin: 8px 0 0; }
details.more small { display: block; margin-top: 4px; color: var(--sub); font-size: 11.5px; }
details.logbox { margin-top: 12px; }
details.logbox summary { cursor: pointer; color: var(--sub); font-size: 12px; user-select: none; }
.log {
max-height: 160px; overflow: auto; white-space: pre-wrap; word-break: break-all; margin: 6px 0 0; padding: 8px 10px;
background: #0f1b2d; color: #c9d6e8; border-radius: 10px; font: 11px/1.5 ui-monospace, Menlo, Consolas, monospace;
}
.log:empty::before { content: "暂无日志"; color: #6b7785; }
`;
const Panel = {
host: null,
root: null,
mount() {
this.host = document.createElement('div');
this.host.id = 'baidu-share-dedupe';
this.root = this.host.attachShadow({ mode: 'open' });
this.root.innerHTML = `
更多选项
运行日志