1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
|
// ==UserScript==
// @name B站资源下载助手 - 增强版
// @namespace http://tampermonkey.net/
// @version 2.0.0
// @description 一键下载B站视频、音频、封面等资源,支持多画质选择
// @author YourName
// @match https://www.bilibili.com/video/*
// @match https://m.bilibili.com/video/*
// @grant GM_xmlhttpRequest
// @grant GM_setValue
// @grant GM_getValue
// @grant GM_download
// @connect bilibili.com
// @connect api.bilibili.com
// @require https://cdn.jsdelivr.net/npm/file-saver@2.0.5/dist/FileSaver.min.js
// @license MIT
// ==/UserScript==
(function () {
"use strict";
// 配置项
const CONFIG = {
scriptName: "B站资源下载助手",
version: "2.0.0",
author: "YourName",
updateUrl: "https://example.com/your-script.meta.js",
};
// 本地存储键名
const STORAGE_KEYS = {
COVER: "bili_downloader_cover_enabled",
AUDIO: "bili_downloader_audio_enabled",
VIDEO: "bili_downloader_video_enabled",
QUALITY: "bili_downloader_preferred_quality",
};
// 视频质量选项
const QUALITY_OPTIONS = [
{ value: 120, label: "超清 4K" },
{ value: 116, label: "高清 1080P60" },
{ value: 112, label: "高清 1080P+" },
{ value: 80, label: "高清 1080P" },
{ value: 64, label: "清晰 720P" },
{ value: 32, label: "流畅 480P" },
{ value: 16, label: "流畅 360P" },
];
// DOM 工具函数
const $ = (selector, parent = document) => parent.querySelector(selector);
const $$ = (selector, parent = document) => parent.querySelectorAll(selector);
const createElement = (tag, className = "", innerHTML = "") => {
const el = document.createElement(tag);
if (className) el.className = className;
if (innerHTML) el.innerHTML = innerHTML;
return el;
};
class BiliDownloader {
constructor() {
this.isInitialized = false;
this.currentTask = null;
this.init();
}
init() {
if (this.isInitialized) return;
this.injectStyles();
this.waitForPageLoad().then(() => {
this.renderUI();
this.checkUpdate();
this.isInitialized = true;
console.log(`${CONFIG.scriptName} 初始化完成`);
});
}
// 注入CSS样式
injectStyles() {
if ($(".bili-downloader-styles")) return;
const styles = `
.bili-downloader-btn {
background: linear-gradient(135deg, #00a1d6, #0084b4);
border: none;
color: white;
border-radius: 20px;
cursor: pointer;
padding: 6px 12px;
font-size: 12px;
margin: 0 4px;
transition: all 0.3s ease;
font-weight: 500;
}
.bili-downloader-btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 161, 214, 0.4);
}
.bili-downloader-btn:disabled {
background: #cccccc;
cursor: not-allowed;
transform: none;
}
.bili-downloader-btn.downloading {
background: linear-gradient(135deg, #ff9500, #ff6600);
}
.bili-downloader-btn.success {
background: linear-gradient(135deg, #34c759, #28a745);
}
.bili-downloader-btn.error {
background: linear-gradient(135deg, #ff3b30, #dc3545);
}
.bili-downloader-settings-btn {
background: transparent;
border: 1px solid #00a1d6;
color: #00a1d6;
}
.bili-downloader-dialog {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
border-radius: 12px;
padding: 20px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
z-index: 10000;
min-width: 300px;
max-width: 90vw;
}
.bili-downloader-dialog-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0,0,0,0.5);
z-index: 9999;
}
.bili-downloader-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding-bottom: 15px;
border-bottom: 1px solid #eee;
}
.bili-downloader-title {
font-size: 18px;
font-weight: bold;
color: #00a1d6;
}
.bili-downloader-close {
background: none;
border: none;
font-size: 20px;
cursor: pointer;
color: #666;
}
.bili-downloader-option {
display: flex;
justify-content: space-between;
align-items: center;
margin: 12px 0;
padding: 8px 0;
}
.bili-downloader-quality-select {
padding: 4px 8px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 12px;
}
.bili-downloader-status {
font-size: 11px;
color: #666;
margin-top: 4px;
}`;
const styleEl = createElement("style", "bili-downloader-styles");
styleEl.textContent = styles;
document.head.appendChild(styleEl);
}
// 等待页面加载完成
waitForPageLoad() {
return new Promise((resolve) => {
const checkReady = () => {
if (window.__INITIAL_STATE__ && $(".video-data")) {
resolve();
} else {
setTimeout(checkReady, 500);
}
};
checkReady();
});
}
// 获取视频信息
getVideoInfo() {
if (!window.__INITIAL_STATE__) return null;
const state = window.__INITIAL_STATE__;
return {
aid: state.aid,
bvid: state.bvid,
title: $(".video-title")?.textContent?.trim() || "B站视频",
cover: state.videoData?.pic,
cid: state.cidMap?.[state.bvid]?.cids?.[state.p || 0],
};
}
// 下载封面
async downloadCover() {
const info = this.getVideoInfo();
if (!info?.cover) {
this.showMessage("无法获取封面地址", "error");
return;
}
try {
const response = await fetch(info.cover);
const blob = await response.blob();
const link = createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `${info.title}_封面.jpg`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
this.showMessage("封面下载成功", "success");
} catch (error) {
this.showMessage("封面下载失败", "error");
console.error("封面下载错误:", error);
}
}
// 下载音频
async downloadAudio(btn) {
if (this.currentTask) {
this.currentTask.abort();
this.currentTask = null;
btn.textContent = "音频";
btn.classList.remove("downloading");
return;
}
const info = this.getVideoInfo();
if (!info) {
this.showMessage("无法获取视频信息", "error");
return;
}
btn.textContent = "准备中...";
btn.classList.add("downloading");
try {
const audioUrl = `https://api.bilibili.com/x/player/playurl?avid=${info.aid}&bvid=${info.bvid}&cid=${info.cid}&fnval=4048`;
const response = await fetch(audioUrl);
const data = await response.json();
if (data.code !== 0 || !data.data?.dash?.audio?.[0]) {
throw new Error("无法获取音频信息");
}
const audioInfo = data.data.dash.audio[0];
const xhr = new XMLHttpRequest();
this.currentTask = xhr;
xhr.responseType = "blob";
xhr.open("GET", audioInfo.base_url, true);
xhr.onprogress = (event) => {
if (event.lengthComputable) {
const percent = Math.round((event.loaded / event.total) * 100);
btn.textContent = `下载中 ${percent}%`;
}
xhr.onload = () => {
if (xhr.status === 200) {
const blob = xhr.response;
const link = createElement("a");
link.href = URL.createObjectURL(blob);
link.download = `${info.title}.mp3`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(link.href);
btn.textContent = "音频";
btn.classList.remove("downloading");
btn.classList.add("success");
setTimeout(() => btn.classList.remove("success"), 2000);
this.showMessage("音频下载成功", "success");
}
this.currentTask = null;
};
xhr.onerror = () => {
btn.textContent = "下载失败";
btn.classList.remove("downloading");
btn.classList.add("error");
setTimeout(() => {
btn.textContent = "音频";
btn.classList.remove("error");
}, 2000);
this.currentTask = null;
};
xhr.send();
};
} catch (error) {
console.error("音频下载错误:", error);
btn.textContent = "下载失败";
btn.classList.remove("downloading");
btn.classList.add("error");
setTimeout(() => {
btn.textContent = "音频";
btn.classList.remove("error");
}, 2000);
this.showMessage("音频下载失败", "error");
}
}
// 下载视频
async downloadVideo(btn) {
const info = this.getVideoInfo();
if (!info) {
this.showMessage("无法获取视频信息", "error");
return;
}
const quality = GM_getValue(STORAGE_KEYS.QUALITY, 80);
btn.textContent = "准备中...";
btn.disabled = true;
try {
// 这里可以使用我们自己的视频解析服务
const videoUrl = `https://api.bilibili.com/x/player/playurl?cid=${info.cid}&bvid=${info.bvid}&qn=${quality}`;
const response = await fetch(videoUrl);
const data = await response.json();
if (data.code !== 0) {
throw new Error("无法获取视频地址");
}
this.showMessage("正在获取视频链接...", "info");
// 实际项目中这里应该处理视频流
// 这里简化处理,实际使用时需要完整实现
window.open(
`https://your-video-service.com/download?url=${encodeURIComponent(
window.location.href
)}`
);
} catch (error) {
console.error("视频下载错误:", error);
this.showMessage("视频下载失败,请稍后重试", "error");
} finally {
btn.textContent = "视频";
btn.disabled = false;
}
}
// 显示消息
showMessage(message, type = "info") {
const messageEl = createElement("div", `bili-downloader-message ${type}`);
messageEl.textContent = message;
messageEl.style.cssText = `
position: fixed;
top: 20px;
right: 20px;
padding: 12px 20px;
background: ${
type === "error"
? "#ff3b30"
: type === "success"
? "#34c759"
: "#007aff"
};
color: white;
border-radius: 8px;
z-index: 10001;
animation: slideInRight 0.3s ease;
`;
document.body.appendChild(messageEl);
setTimeout(() => {
if (messageEl.parentNode) {
messageEl.parentNode.removeChild(messageEl);
}
}, 3000);
}
// 渲染用户界面
renderUI() {
const container = $(".video-data") || $(".video-info-detail-list");
if (!container) {
console.warn("找不到视频信息容器");
return;
}
// 渲染设置按钮
this.renderSettingsButton(container);
// 渲染功能按钮
this.renderFunctionButtons(container);
}
// 渲染设置按钮
renderSettingsButton(container) {
if ($(".bili-downloader-settings-btn")) return;
const settingsBtn = createElement(
"button",
"bili-downloader-btn bili-downloader-settings-btn"
);
settingsBtn.textContent = "设置";
settingsBtn.title = "B站下载助手设置";
settingsBtn.addEventListener("click", () => this.showSettingsDialog());
container.appendChild(settingsBtn);
}
// 渲染功能按钮
renderFunctionButtons(container) {
// 移除旧按钮
$$(".bili-downloader-func-btn").forEach((btn) => btn.remove());
// 封面按钮
if (GM_getValue(STORAGE_KEYS.COVER, true)) {
const coverBtn = createElement(
"button",
"bili-downloader-btn bili-downloader-func-btn"
);
coverBtn.textContent = "封面";
coverBtn.addEventListener("click", () => this.downloadCover());
container.appendChild(coverBtn);
}
// 音频按钮
if (GM_getValue(STORAGE_KEYS.AUDIO, true)) {
const audioBtn = createElement(
"button",
"bili-downloader-btn bili-downloader-func-btn"
);
audioBtn.textContent = "音频";
audioBtn.addEventListener("click", () => this.downloadAudio(audioBtn));
container.appendChild(audioBtn);
}
// 视频按钮
if (GM_getValue(STORAGE_KEYS.VIDEO, true)) {
const videoBtn = createElement(
"button",
"bili-downloader-btn bili-downloader-func-btn"
);
videoBtn.textContent = "视频";
videoBtn.addEventListener("click", () => this.downloadVideo(videoBtn));
container.appendChild(videoBtn);
}
}
// 显示设置对话框
showSettingsDialog() {
// 移除现有对话框
$(".bili-downloader-dialog-overlay")?.remove();
$(".bili-downloader-dialog")?.remove();
const overlay = createElement("div", "bili-downloader-dialog-overlay");
const dialog = createElement("div", "bili-downloader-dialog");
dialog.innerHTML = `
<div class="bili-downloader-header">
<div class="bili-downloader-title">${CONFIG.scriptName}</div>
<button class="bili-downloader-close">×</button>
</div>
<div class="bili-downloader-content">
<div class="bili-downloader-option">
<label>启用封面下载</label>
<input type="checkbox" id="cover-enabled" ${
GM_getValue(STORAGE_KEYS.COVER, true) ? "checked" : ""
}>
</div>
<div class="bili-downloader-option">
<label>启用音频下载</label>
<input type="checkbox" id="audio-enabled" ${
GM_getValue(STORAGE_KEYS.AUDIO, true) ? "checked" : ""
}>
</div>
<div class="bili-downloader-option">
<label>启用视频下载</label>
<input type="checkbox" id="video-enabled" ${
GM_getValue(STORAGE_KEYS.VIDEO, true) ? "checked" : ""
}>
</div>
<div class="bili-downloader-option">
<label>默认画质</label>
<select class="bili-downloader-quality-select" id="quality-select">
${QUALITY_OPTIONS.map(
(opt) =>
`<option value="${opt.value}" ${
GM_getValue(STORAGE_KEYS.QUALITY, 80) ===
opt.value
? "selected"
: ""
}>${opt.label}</option>`
).join("")}
</select>
</div>
</div>
`;
overlay.appendChild(dialog);
document.body.appendChild(overlay);
// 关闭按钮事件
$(".bili-downloader-close", dialog).addEventListener("click", () => {
overlay.remove();
});
// 点击遮罩关闭
overlay.addEventListener("click", (e) => {
if (e.target === overlay) {
overlay.remove();
}
});
// 设置项变更事件
$("#cover-enabled", dialog).addEventListener("change", (e) => {
GM_setValue(STORAGE_KEYS.COVER, e.target.checked);
this.refreshButtons();
});
$("#audio-enabled", dialog).addEventListener("change", (e) => {
GM_setValue(STORAGE_KEYS.AUDIO, e.target.checked);
this.refreshButtons();
});
$("#video-enabled", dialog).addEventListener("change", (e) => {
GM_setValue(STORAGE_KEYS.VIDEO, e.target.checked);
this.refreshButtons();
});
$("#quality-select", dialog).addEventListener("change", (e) => {
GM_setValue(STORAGE_KEYS.QUALITY, parseInt(e.target.value));
});
}
// 刷新按钮
refreshButtons() {
const container = $(".video-data") || $(".video-info-detail-list");
if (container) {
this.renderFunctionButtons(container);
}
}
// 检查更新
async checkUpdate() {
try {
const response = await fetch(CONFIG.updateUrl + "?t=" + Date.now());
const text = await response.text();
// 简化的版本检查逻辑
const versionMatch = text.match(/@version\s+([\d.]+)/);
if (versionMatch && versionMatch[1] !== CONFIG.version) {
this.showMessage(`发现新版本 ${versionMatch[1]},请前往更新`, "info");
}
} catch (error) {
console.log("检查更新失败:", error);
}
}
}
// 初始化脚本
let downloader;
const initScript = () => {
if (!downloader) {
downloader = new BiliDownloader();
}
};
// 页面加载完成后初始化
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", initScript);
} else {
initScript();
}
// 监听URL变化(单页应用)
let lastUrl = location.href;
new MutationObserver(() => {
const url = location.href;
if (url !== lastUrl) {
lastUrl = url;
setTimeout(initScript, 1000);
}
}).observe(document, { subtree: true, childList: true });
})();
|