// ==UserScript== // @name HiFiNi 助手 // @namespace tampermonkey.net // @version 0.5.1 // @description HiFiNi、5song 下载助手。1、自动填写回复内容;2、自动提取蓝奏(修改超链接),自动下载(下载窗口可能会被浏览器拦截); // @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://*.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; } //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 < 2) { logger.info(CHANNEL, '未发现 pin', `原因:len=${list.length}`); return; } for (let i = 0; i < list.length; i++) { const el = list[i]; if (el.querySelector('a')) { continue; } const pin = filterText(el).replace('提取码: ', ''); if (pin.length > 8) { continue; } let links; if (i === 0) { let s = el.previousElementSibling; for (let j = 0; j < 6; j++) { if (!s) { break; } links = s.querySelectorAll('a') if (links.length > 0) { break; } s = s.previousElementSibling; } } else { links = list[i - 1].querySelectorAll('a'); } 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(); if (waiting) { let btn = document.querySelector('#submit'); const post = document.querySelector(adaptor.postSelector); btn.textContent = btn.textContent + `(${adaptor.name})`; let timerId; function waitReply() { if (post.querySelector('.alert.alert-success')) { clearInterval(timerId); location.hash = 'body'; processPin(); } } if (btn) { btn.addEventListener('click', () => { timerId = setInterval(waitReply, 500); }); } } } /** * @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) { 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 = `
`; box.insertAdjacentHTML('afterbegin', s); } /** * @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 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 (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 if (hostname.includes("5song.xyz")) { handle5Song(); } else if (hostname.includes("lanz")) { rushLanZou(); } else { logger.warn(' host:', hostname); } })();