蜜柑計劃 一鍵複製全部磁連(短版)

在各字幕組分區新增一鍵『複製磁連』按鈕

// ==UserScript==
// @name         蜜柑計劃 一鍵複製全部磁連(短版)
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  在各字幕組分區新增一鍵『複製磁連』按鈕
// @author       shanlan(ChatGPT o3-mini)
// @match        https://mikanani.me/Home/Bangumi/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=mikanani.me
// @grant        none
// @run-at       document-end
// @license      MIT
// ==/UserScript==

(function() {
'use strict';

// 建立一個非阻斷性提示函數,在頁面右下角短暫顯示訊息
function notify(msg) {
const n = document.createElement('div');
n.style.position = 'fixed';
n.style.left = '50%';
n.style.top = '50%';
n.style.transform = 'translate(-50%, -50%)';
n.style.backgroundColor = 'rgba(0,0,0,0.7)';
n.style.color = 'white';
n.style.padding = '12px 24px';
n.style.borderRadius = '8px';
n.style.zIndex = '9999';
n.style.fontSize = '30px';
n.style.boxShadow = '0 2px 12px rgba(0,0,0,0.2)';
n.textContent = msg;
document.body.appendChild(n);
setTimeout(() => {
n.style.transition = 'opacity 1s';
n.style.opacity = '0';
setTimeout(() => { n.remove(); }, 1000);
}, 3000);
}

function main() {
// 尋找所有分區標題區塊 (以 div.subgroup-text 為目標)
const subgroupDivs = document.querySelectorAll('div.subgroup-text');
subgroupDivs.forEach(div => {
// 建立按鈕
const btn = document.createElement('button');
btn.textContent = '複製磁連';
btn.style.marginLeft = '10px';
btn.style.padding = '2px 6px';
btn.style.fontSize = '12px';
// 插入按鈕至分區標題(最後)
div.appendChild(btn);

btn.addEventListener('click', () => {
// 從該分區區塊之後找第一個 table 元素(以防中間有其他元素)
let sibling = div.nextElementSibling;
let table = null;
while(sibling) {
if(sibling.tagName && sibling.tagName.toLowerCase() === 'table') {
table = sibling;
break;
}
sibling = sibling.nextElementSibling;
}
if (!table) {
console.log('未找到對應的磁連列表 (table)');
notify('未找到對應的磁連列表');
return;
}
// 從該 table 中搜尋所有 class 為 js-magnet 的 a 元素
const magnetAnchors = table.querySelectorAll('a.js-magnet');
const magnets = [];
magnetAnchors.forEach(anchor => {
const fullText = anchor.getAttribute('data-clipboard-text');
if (fullText) {
// 使用正規表達式取得 magnet:?xt=urn:btih: 後面,直到遇到 & 的部分
const match = fullText.match(/^(magnet:\?xt=urn:btih:[^&]+)/);
if (match) {
magnets.push(match[1]);
}
}
});
if (magnets.length === 0) {
console.log('未找到任何磁連!');
notify('未找到任何磁連');
return;
}
// 將所有磁連以換行符號連接成一個文字字串
const result = magnets.join('\n');
// 利用 GM_setClipboard 複製到剪貼簿,若沒有則以 textarea 作為備援
if (typeof GM_setClipboard !== 'undefined') {
GM_setClipboard(result, 'text');
} else {
const textarea = document.createElement('textarea');
textarea.value = result;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
}
notify('已複製 ' + magnets.length + ' 個磁連,如果有沒複製到的請點擊右下角『顯示更多』');
});
});
}

if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', main);
} else {
main();
}
})();