// ==UserScript== // @name HiFiNi 助手 // @namespace tampermonkey.net // @version 0.6.3 // @description HiFiNi、5song 下载助手。1、快速回复;2、处理提取码;3、连环签到; 4、连环搜索; // @tag HiFiNi // @author foobar // @match https://www.hifini.net/*.htm* // @match https://hifiki.com/*.htm* // @match https://www.hifiti.cc/*.htm* // @match https://www.hifiii.com/*.htm* // @match https://www.5song.xyz/*/*.html // @match https://www.openflac.com/* // @match https://*.lanzoui.com/* // @match https://*.lanzouo.com/* // @match https://*.lanzoux.com/* // @match https://*.lanzn.com/* // @icon https://www.hifini.net/view/img/logo.png // @grant GM.setValue // @grant GM.getValue // @run-at document-end // @license LGPL // ==/UserScript== (function () { 'use strict'; /** * @typedef {Object} Site * @property {string} name * @property {string} alias * @property {string} hostname * @property {boolean} current */ const CHANNEL = '[HiFiNi]'; /** * * @type {Site[]} */ const sites = [ {name: 'HiFiNi', alias: 'Ni', current: false, hostname: 'www.hifini.net'}, {name: 'HiFiTi', alias: 'Ti', current: false, hostname: 'www.hifiti.cc'}, {name: 'HiFiKi', alias: 'Ki', current: false, hostname: 'hifiki.com'}, {name: 'HiFiIi', alias: 'Ii', current: false, hostname: 'www.hifiii.com'}, ]; let logger = window.console; //region utils function displaying(el) { return window.getComputedStyle(el).display !== 'none'; } function copyText(text) { return navigator.clipboard.writeText(text); } function domesticate(text) { const doc = new DOMParser().parseFromString(text, 'text/html'); return doc.body.firstElementChild; } function createConsole() { const iframe = document.createElement('iframe'); iframe.name = 'guardian-' + Date.now().toString(36); iframe.style.display = 'none'; document.documentElement.appendChild(iframe); return iframe.contentWindow.console; } function debounce(func, wait, immediate) { let timeout; let result; const later = () => setTimeout(() => { timeout = null; if (!immediate) result = func.apply(this, arguments); }, wait); return function (...args) { const context = this; const callNow = immediate && !timeout; clearTimeout(timeout); timeout = later(); if (callNow) result = func.apply(context, args); return result; }; } //endregion //region HiFiNi /** * @typedef {Object} Adaptor * @property {string} [name] - 名称 * @property {string} postSelector - 主帖选择器 * @property {string} mainContainerSelector - 签到页的 main_container选择器 * @property {function(post:HTMLElement): boolean} hasReplied - 是否已回复 * @property {boolean} [suppressConsole] - 是否拦截 console */ /** * * @returns {Partial} */ function customAdaptor() { const host = location.hostname; if (host.includes('hifini.com')) { return {name: 'HiFiNi', postSelector: '.card.jan'} } if (host.includes('hifini.net')) { return { name: 'HiFiNi', /** * @param post {HTMLElement} * @returns {boolean} */ hasReplied(post) { const el = post.querySelector('.alert.alert-warning'); if (el) { logger.info(CHANNEL, '添加回复链接'); el.insertAdjacentHTML('beforeend', ' 回复 '); } return !el; } } } if (host.includes('hifiki.com')) { return {name: 'HiFiKi'}; } if (host.includes('hifiti.cc')) { return {suppressConsole: true}; } return {}; } /** * * @type {Adaptor} */ const adaptor = Object.assign({ name: location.hostname.split('.').at(-2), postSelector: '.card.card-thread', mainContainerSelector: 'main > .container', hasReplied() { return !document.querySelector('.alert.alert-warning .post_reply'); } }, customAdaptor()); if (adaptor.suppressConsole) { logger = window._logger = createConsole(); logger.info(`%c${CHANNEL} guard logger`, 'color: green; font-weight: bold; padding: 2px 5px; border:solid 1px blue;'); } function processPin() { const post = document.querySelector(adaptor.postSelector); const list = post.querySelectorAll('.alert.alert-success'); if (list.length < 1) { logger.info(CHANNEL, '未发现 pin', `原因:len=${list.length}`); return; } /** * @param {string} text * @return {string|null} */ function truncatePin(text) { const words = ['提取码:', '提取码:', '密码:', '密码:']; for (let word of words) { const b = text.indexOf(word) if (b >= 0) { return text.substring(b + word.length).trim(); } } return null; } for (let i = 0; i < list.length; i++) { const el = list[i]; const link = el.querySelector('a'); if (link) { const pin = truncatePin(el.textContent); if (pin) { link.href += `?pwd=${pin}`; link.textContent += `?pwd=${pin}`; } } else { const pin = filterText(el).replace('提取码: ', ''); if (pin.length > 8 || pin.length === 1) { logger.info(CHANNEL, '未发现 pin', `原因:文本过长,${pin}`); continue; } let links; if (i > 0) { links = list[i - 1].querySelectorAll('a'); } if (i === 0 || links.length === 0) { let s = el.previousElementSibling; for (let j = 0; j < 6; j++) { if (!s || s.classList.contains('alert-success')) { break; } links = s.querySelectorAll('a') if (links.length > 0) { break; } s = s.previousElementSibling; } } if (links && links.length > 1) { logger.info(CHANNEL, 'found pin', pin, links.length); } for (let j = 0; j < links.length; j++) { const link = links[j]; if (!link.href.includes('pwd=')) { link.href += `?pwd=${pin}`; link.textContent += `?pwd=${pin}`; } } } } } function shorthandReply(waiting) { function extractTitle() { const titles = document.title.split('['); let title = titles[0] ?? '卧槽,这么好的歌你怎么不早点告诉我'; const n = title.indexOf('》'); if (n > 0 && n !== title.length) { title = title.substring(0, n); return title.replace('《', ' - '); } return title; } const title = extractTitle(); document.getElementById('message').value = title; copyText(title).then(); let btn = document.querySelector('#submit'); btn.textContent = btn.textContent + `(${adaptor.name})`; async function waitReply() { for (let i = 0; i < 100; i++) { await new Promise(resolve => setTimeout(resolve, 500)); const post = document.querySelector(adaptor.postSelector); if (post?.querySelector('.alert.alert-success')) { // location.hash = 'body'; window.scrollTo({top: 50, behavior: 'smooth'}); processPin(); return true; } } logger.warn(CHANNEL, '等待回复超时'); return false; } if (waiting) { if (btn) { btn.addEventListener('click', () => { waitReply().then(); }); } } } /** * @param el * @returns {string} */ function filterText(el) { const spans = el.querySelectorAll('span'); if (el.length > 0) { return Array.from(spans).filter(x => displaying(x)).map(x => x.innerText).join(''); } return el.textContent.trim(); } /** * * @returns {Promise<{replied:boolean}>} * */ function waitHiFiNi() { /** * @param {HTMLElement} post */ function handleLrc(post) { const list = post.querySelectorAll('p:has(> br)'); let found = false; for (let i = 0; i < list.length; i++) { let p = list[i]; if (p.querySelectorAll('br').length > 6) { found = true; p.style.maxHeight = '120px'; p.style.overflowY = 'scroll'; logger.info(CHANNEL, '缩减歌词高度', i); } } if (found) return; const box = post.querySelector('.message.break-all'); if (!box) return; const range = document.createRange(); let start; if (box.querySelectorAll('br').length > 6) { // hifiki.com 大段 br 的歌词 const headings = box.querySelectorAll('h5'); if (headings.length < 2) { logger.warn(CHANNEL, '主帖内未找到足够的 h5 标签'); } else { start = headings[0]; range.setStartAfter(start); range.setEndBefore(headings[1]); } } else { // hifini.net 大段 p 的歌词 const list = box.querySelectorAll(':scope > p'); if (list.length > 6) { let sibling = list[0]; while (sibling) { if (sibling.tagName === 'H5') { start = list[0]; range.setStartAfter(start); range.setEndBefore(sibling); break; } sibling = sibling.nextElementSibling } /* if (start) { start.insertAdjacentHTML('beforebegin', '
歌词:
'); }*/ } } if (start) { const fragment = range.extractContents(); const p = document.createElement('div'); p.appendChild(fragment); start.insertAdjacentElement('afterend', p); p.classList.add('lrc-body'); p.style.maxHeight = '120px'; p.style.overflowY = 'scroll'; logger.info(CHANNEL, '缩减歌词高度', 'after-player'); } } return new Promise((resolve, reject) => { let n = 1; let id = setInterval(() => { const el = document.querySelector(adaptor.postSelector); if (el) { const replied = adaptor.hasReplied(el); handleLrc(el); clearInterval(id); resolve({replied}); } if (n++ > 10) { clearInterval(id); reject(`10s内未找到主贴 (${adaptor.postSelector})`); } }, 1e3); }); } async function handleHiFini() { try { const {replied} = await waitHiFiNi(); logger.info(CHANNEL, '已回复:' + replied); if (replied) { if (window.scrollY > 240) { window.scrollTo({top: 50, behavior: 'smooth'}); } processPin(); } else { shorthandReply(true); } } catch (e) { logger.error(CHANNEL, e); } } //endregion //region HiFini sign function handleHiFiniSign() { /** * @typedef {Record} SignNote * @property {string} date - 日期字符串 */ const keyOfSignNote = 'sign_note'; function applySearch() { const box = document.querySelector(adaptor.mainContainerSelector); if (!box) { logger.warn(CHANNEL, '未找到 mainContainer'); return; } if (box.querySelector('.search-container')) { logger.info(CHANNEL, '发现 search-container , do nothing'); return; } const s = `
`; const el = domesticate(s); /** * @type {HTMLFormElement} */ const form = el.firstElementChild; form.addEventListener('submit', (e) => { const word = form.elements.keyword.value.trim(); if (word) { // const kw = [...new TextEncoder().encode(word)].map(x => x.toString(16).toUpperCase()).join('_'); const kw = encodeURIComponent(word).replaceAll('%', '_') window.location = `/search-${kw}-1.htm`; } e.preventDefault(); }); // box.insertAdjacentHTML('afterbegin', s); box.insertAdjacentElement('afterbegin', el); } /** * @return {Promise} */ async function getSignNote() { /** * @type {SignNote} */ let note = await GM.getValue(keyOfSignNote); const today = new Date().toLocaleDateString(); if (!note || note.date !== today) { note = {date: today}; sites.forEach(site => note[site.hostname] = 0); await GM.setValue(keyOfSignNote, note); localStorage.setItem(keyOfSignNote, JSON.stringify(note)); } return note; } async function noteAsSigned(s = 1) { const key = location.hostname; const note = await getSignNote(); if (note[key] !== s) { logger.info(CHANNEL, `save sign "${key}"`, `${note[key]} -> ${s}`); note[key] = s; await GM.setValue(keyOfSignNote, note); localStorage.setItem(keyOfSignNote, JSON.stringify(note)); } function autoSign() { for (let site of sites) { if (!note[site.hostname]) { window.open(`http://${site.hostname}/sg_sign.htm`, '_blank'); return; } } logger.info(CHANNEL, '所有网站已签到'); } setTimeout(autoSign, 2e3); } function applySign() { const sign = document.querySelector('#sign'); if (!sign) { logger.warn(CHANNEL, '未找到 sign'); noteAsSigned(404).then(); return; } if (sign.textContent.includes('已签')) { noteAsSigned().then(); document.querySelector('.search-container input')?.focus(); } else { sign.click(); noteAsSigned().then(); } } applySearch(); setTimeout(applySign, 2e3); } function handleHiFiSearch() { logger.info(CHANNEL, 'handle HiFiSearch'); function querySearchBox() { const box = document.querySelector('main .container .card:last-child'); if (box) return box; const list = document.querySelectorAll('main .container .card'); if (list.length > 0) { //ni.net 在 keyword 参数的搜索结果下,需要此种方式查询。 return list[list.length - 1]; } } const box = querySearchBox(); if (!box) { logger.warn(CHANNEL, '未找到搜索结果'); return; } const s = `
` const el = domesticate(s); let arr = []; for (let site of sites) { if (site.current) continue; arr.push( ``); } el.firstElementChild.innerHTML = arr.join('\n'); logger.info(CHANNEL, 'handle HiFiSearch insert html'); box.insertAdjacentElement('beforeend', el); } //endregion //region LanZou function rushLanZou() { const params = new URLSearchParams(document.location.search); const pickup = params.get('pwd'); if (!pickup) return; const pwd = document.getElementById("pwd"); if (!pwd) return; pwd.value = pickup; const btn = document.querySelector('.passwddiv-btn, .btnpwd'); btn?.click(); const timerId = setInterval(autoDown, 500); let times = 0; function autoDown() { times++; const link = document.querySelector("#downajax a") if (link) { link.style.backgroundColor = 'green'; link.innerHTML += ' !'; link.click(); // link.dispatchEvent(new MouseEvent('click', {bubbles: true})); clearInterval(timerId) } else if (times > 10) { clearInterval(timerId); alert("无法下载,未找到下载按钮"); } } } //endregion //region 5song function handle5Song() { let el = document.querySelector('.mobileDown'); if (!el) { return; } el = el.parentElement; el.addEventListener('click', (e) => { const url = e.target.parentElement.dataset.url; if (url) { window.open(url, '_blank') e.preventDefault(); e.stopPropagation(); } else { logger.warn('没找到 url. target:', e.target); alert('没找到 url') } }, {capture: true}); } //endregion //region OpenFlac function handleOpenFlac() { async function loadScript(src) { const script = document.createElement('script'); script.src = src; document.documentElement.appendChild(script); return new Promise((resolve, reject) => { script.onload = resolve; script.onerror = reject; }); } async function readQrFromSvg(svgEl) { const serializer = new XMLSerializer(); const svgStr = serializer.serializeToString(svgEl); const blob = new Blob([svgStr], {type: 'image/svg+xml;charset=utf-8'}); const url = URL.createObjectURL(blob); const img = new Image(); img.src = url; await new Promise((res, rej) => { img.onload = res; img.onerror = rej; }) const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); canvas.width = img.width; canvas.height = img.height; ctx.drawImage(img, 0, 0); const imgData = ctx.getImageData(0, 0, canvas.width, canvas.height); const result = jsQR(imgData.data, imgData.width, imgData.height); URL.revokeObjectURL(url); return result?.data || null; } /** * * @param {HTMLElement} box */ async function handleDialog(box) { const el = box.querySelector('svg:not(.lucide)') if (!el) { return; } function makeLink(url, pin) { const href = pin ? `${url}?pwd=${pin}` : url; return `
打开连接(${pin ?? 'T_T'})
` } /** * @param {HTMLElement} p * @returns {HTMLInputElement|null} */ function findPinInput(p) { const inputs = p.querySelectorAll('input'); for (let input of inputs) { if (input.type === 'text') { return input; } } return null; } const url = await readQrFromSvg(el); logger.info(CHANNEL, '识别 QR', url); const container = box.querySelector('.flex.h-full'); if (!container) { return; } let input = findPinInput(box); const target = container.firstElementChild.firstElementChild.firstElementChild.firstElementChild; target.innerHTML = makeLink(url, input?.value); if (input) { container.lastElementChild.firstElementChild.insertAdjacentHTML('beforeend', target.innerHTML); return; } const findPinInputLazily = debounce(() => { const input_ = findPinInput(box); if (input_) { logger.info(CHANNEL, 'after container mutation found pin-input ', input_.value); container.lastElementChild.firstElementChild.insertAdjacentHTML('beforeend', makeLink(url, input_.value)); observer.disconnect(); } else { logger.info(CHANNEL, 'container mutation', '未发现 input'); } }, 500); const observer = new MutationObserver((mutations) => { logger.info(CHANNEL, 'container mutation'); findPinInputLazily(); }); observer.observe(container, {childList: true, subtree: true}); } function observeDialog() { new MutationObserver((list) => { const noted = location.pathname.includes('/songs/') logger.info(CHANNEL, 'Mutation', new Date().toLocaleTimeString(), noted); if (!noted) { return; } for (let m of list) { m.addedNodes.forEach(node => { const role = node.getAttribute('role'); logger.info(CHANNEL, 'Mutation addedNode', node.tagName, role, node.nodeType); if (node.nodeType === 1 && role === 'dialog') { handleDialog(node).then(); } }); } logger.info(CHANNEL, 'Mutation',); }).observe(document.body, {childList: true}); } loadScript('https://cdn.jsdelivr.net/npm/jsqr@1.4.0/dist/jsQR.min.js').then(() => { logger.info(CHANNEL, '加载 QR 脚本完成'); observeDialog(); }).catch((err) => { logger.error(CHANNEL, '加载 QR 脚本出错', err); }); } //endregion const hostname = window.location.hostname; function maybeHiFi() { for (let site of sites) { if (hostname.includes(site.hostname)) { site.current = true; logger.info(CHANNEL, '检测到 HiFiNi', site.hostname); return true; } } return false; } if (hostname.includes("lanz")) { rushLanZou(); } else if (hostname.includes("openflac.com")) { handleOpenFlac(); } else if (hostname.includes("5song.xyz")) { handle5Song(); } else if (maybeHiFi()) { const pathname = window.location.pathname; if (pathname.startsWith("/sg_sign.htm")) { handleHiFiniSign(); } else if (pathname.startsWith('/thread-')) { handleHiFini().then(); } else if (pathname.startsWith('/search-') || pathname.startsWith('/search.htm')) { handleHiFiSearch(); } else { logger.warn(CHANNEL, ' pathname', pathname); } } else { logger.warn(' host:', hostname); } })();