您需要先安装一个扩展,例如 篡改猴、Greasemonkey 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 暴力猴,之后才能安装此脚本。
您需要先安装一个扩展,例如 篡改猴 或 Userscripts ,之后才能安装此脚本。
您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey,才能安装此脚本。
您需要先安装用户脚本管理器扩展后才能安装此脚本。
Adds robust song deletion (Selective & Bulk with Stop) and a Download Queue tool with multi-format selection and delay. Features: Main Menu, Independent Lists, Keyword Filters, Liked Filters/Selectors, Draggable & Minimizable UI, Auto List Reload, Resizable Lists. USE WITH CAUTION.
当前为
// ==UserScript== // @name Riffusion Multitool // @namespace http://tampermonkey.net/ // @version 1.60 // @description Adds robust song deletion (Selective & Bulk with Stop) and a Download Queue tool with multi-format selection and delay. Features: Main Menu, Independent Lists, Keyword Filters, Liked Filters/Selectors, Draggable & Minimizable UI, Auto List Reload, Resizable Lists. USE WITH CAUTION. // @author Graph1ks (assisted by GoogleAI) // @match https://www.riffusion.com/* // @grant GM_addStyle // @grant GM_info // ==/UserScript== (function() { 'use strict'; // --- Configuration --- const INITIAL_VIEW = 'menu'; const DELETION_DELAY = 500; const DOWNLOAD_MENU_DELAY = 550; const DOWNLOAD_ACTION_DELAY = 500; const DEFAULT_INTRA_FORMAT_DELAY_SECONDS = 6; const DROPDOWN_DELAY = 400; const DEFAULT_INTER_SONG_DELAY_SECONDS = 6; const MAX_RETRIES = 3; const MAX_SUB_MENU_OPEN_RETRIES = 4; const MAX_EMPTY_CHECKS = 3; const EMPTY_RETRY_DELAY = 6000; const KEYWORD_FILTER_DEBOUNCE = 500; const UI_INITIAL_TOP = '60px'; const UI_INITIAL_RIGHT = '20px'; const INITIAL_IGNORE_LIKED_DELETE = true; const MINIMIZED_ICON_SIZE = '40px'; const MINIMIZED_ICON_TOP = '15px'; const MINIMIZED_ICON_RIGHT = '15px'; const AUTO_RELOAD_INTERVAL = 3000; const DEFAULT_SONGLIST_HEIGHT = '22vh'; // --- State Variables --- let debugMode = false; let isDeleting = false; let isDownloading = false; let currentView = INITIAL_VIEW; let ignoreLikedSongsDeleteState = INITIAL_IGNORE_LIKED_DELETE; let downloadInterSongDelaySeconds = DEFAULT_INTER_SONG_DELAY_SECONDS; let downloadIntraFormatDelaySeconds = DEFAULT_INTRA_FORMAT_DELAY_SECONDS; let keywordFilterDebounceTimer = null; let stopBulkDeletionSignal = false; let isMinimized = true; let lastUiTop = UI_INITIAL_TOP; let lastUiLeft = null; let uiElement = null; let minimizedIconElement = null; let autoReloadEnabled = true; let autoReloadTimer = null; let lastKnownSongIdsDelete = []; let lastKnownSongIdsDownload = []; let selectedSongIdsDelete = new Set(); let selectedSongIdsDownload = new Set(); let currentDeleteListHeight = DEFAULT_SONGLIST_HEIGHT; let currentDownloadListHeight = DEFAULT_SONGLIST_HEIGHT; // --- Styling (Identical to previous, no changes here) --- GM_addStyle(` #riffControlUI { position: fixed; background: linear-gradient(145deg, #2a2a2a, #1e1e1e); border: 1px solid #444; border-radius: 10px; padding: 0; z-index: 10000; width: 300px; box-shadow: 0 6px 12px rgba(0, 0, 0, 0.4); color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; user-select: none; overflow: hidden; display: ${isMinimized ? 'none' : 'block'}; } #riffControlHeader { background: linear-gradient(90deg, #3a3a3a, #2c2c2c); padding: 8px 12px; cursor: move; border-bottom: 1px solid #444; border-radius: 10px 10px 0 0; position: relative; } #riffControlHeader h3 { margin: 0; font-size: 15px; font-weight: 600; color: #ffffff; text-align: center; text-shadow: 0 1px 1px rgba(0,0,0,0.2); padding-right: 25px; } #minimizeButton { position: absolute; top: 4px; right: 6px; background: none; border: none; color: #aaa; font-size: 18px; font-weight: bold; line-height: 1; cursor: pointer; padding: 2px 4px; border-radius: 4px; transition: color 0.2s, background-color 0.2s; } #minimizeButton:hover { color: #fff; background-color: rgba(255, 255, 255, 0.1); } #riffControlMinimizedIcon { position: fixed; top: ${MINIMIZED_ICON_TOP}; right: ${MINIMIZED_ICON_RIGHT}; width: ${MINIMIZED_ICON_SIZE}; height: ${MINIMIZED_ICON_SIZE}; background: linear-gradient(145deg, #3a3a3a, #2c2c2c); border: 1px solid #555; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.4); color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; font-size: 16px; font-weight: bold; display: ${isMinimized ? 'flex' : 'none'}; align-items: center; justify-content: center; cursor: pointer; z-index: 10001; transition: background 0.2s; user-select: none; } #riffControlMinimizedIcon:hover { background: linear-gradient(145deg, #4a4a4a, #3c3c3c); } #riffControlContent { padding: 12px; } .riffControlButton { display: block; border: none; border-radius: 6px; padding: 8px; font-size: 13px; font-weight: 500; text-align: center; cursor: pointer; transition: transform 0.15s, background 0.15s; width: 100%; margin-bottom: 8px; } .riffControlButton:hover:not(:disabled) { transform: translateY(-1px); } .riffControlButton:disabled { background: #555 !important; cursor: not-allowed; transform: none; opacity: 0.7; } .riffMenuButton { background: linear-gradient(90deg, #4d94ff, #3385ff); color: #fff; } .riffMenuButton:hover:not(:disabled) { background: linear-gradient(90deg, #3385ff, #1a75ff); } .riffBackButton { background: linear-gradient(90deg, #888, #666); color: #fff; margin-top: 12px; margin-bottom: 0; } .riffBackButton:hover:not(:disabled) { background: linear-gradient(90deg, #666, #444); } #deleteAllButton, #deleteButton { background: linear-gradient(90deg, #ff4d4d, #e63939); color: #fff; } #deleteAllButton:hover:not(:disabled), #deleteButton:hover:not(:disabled) { background: linear-gradient(90deg, #e63939, #cc3333); } #startDownloadQueueButton { background: linear-gradient(90deg, #1db954, #17a34a); color: #fff; } #startDownloadQueueButton:hover:not(:disabled) { background: linear-gradient(90deg, #17a34a, #158a3f); } #reloadDeleteButton, #reloadDownloadButton { background: linear-gradient(90deg, #ff9800, #e68a00); color: #fff; } #reloadDeleteButton:hover:not(:disabled), #reloadDownloadButton:hover:not(:disabled) { background: linear-gradient(90deg, #e68a00, #cc7a00); } #statusMessage { margin-top: 8px; font-size: 12px; color: #1db954; text-align: center; min-height: 1.1em; word-wrap: break-word; } .section-controls { display: none; } .songListContainer { margin-bottom: 0px; overflow-y: auto; padding-right: 5px; border: 1px solid #444; border-radius: 5px; background-color: rgba(0,0,0,0.1); padding: 6px; } .songListContainer label { display: flex; align-items: center; margin: 6px 0; color: #d0d0d0; font-size: 13px; transition: color 0.2s; } .songListContainer label:hover:not(.ignored) { color: #ffffff; } .songListContainer input[type="checkbox"] { margin-right: 8px; accent-color: #1db954; width: 15px; height: 15px; cursor: pointer; flex-shrink: 0; } .songListContainer input[type="checkbox"]:disabled { cursor: not-allowed; accent-color: #555; } .songListContainer label.ignored { color: #777; cursor: not-allowed; font-style: italic; } .songListContainer label.liked { font-weight: bold; color: #8c8cff; } .songListContainer label.liked:hover { color: #a0a0ff; } .listResizer { width: 100%; height: 8px; background-color: #4a4a4a; cursor: ns-resize; border-radius: 3px; margin-top: 2px; margin-bottom: 10px; display: block; transition: background-color 0.2s; } .listResizer:hover { background-color: #5c5c5c; } .selectAllContainer { margin-bottom: 8px; display: flex; align-items: center; color: #d0d0d0; font-size: 13px; font-weight: 500; cursor: pointer; } .selectAllContainer input[type="checkbox"] { margin-right: 8px; accent-color: #1db954; width: 15px; height: 15px; } .selectAllContainer:hover { color: #ffffff; } .counterDisplay { margin-bottom: 8px; font-size: 13px; color: #1db954; text-align: center; } .songListContainer::-webkit-scrollbar { width: 6px; } .songListContainer::-webkit-scrollbar-track { background: #333; border-radius: 3px; } .songListContainer::-webkit-scrollbar-thumb { background: #555; border-radius: 3px; } .songListContainer::-webkit-scrollbar-thumb:hover { background: #777; } .filterSettings { margin-top: 8px; margin-bottom: 8px; padding-top: 8px; border-top: 1px solid #444; } .settings-checkbox-label { display: flex; align-items: center; font-size: 12px; color: #ccc; cursor: pointer; margin-bottom: 6px; } .settings-checkbox-label:hover { color: #fff; } .settings-checkbox-label input[type="checkbox"] { margin-right: 6px; accent-color: #1db954; width: 14px; height: 14px; cursor: pointer; } .filterSettings input[type="text"], .filterSettings input[type="number"] { width: 100%; background-color: #333; border: 1px solid #555; color: #ddd; padding: 5px 8px; border-radius: 5px; font-size: 12px; box-sizing: border-box; margin-top: 4px; } .filterSettings input[type="text"]:focus, .filterSettings input[type="number"]:focus { outline: none; border-color: #777; } #downloadSelectLiked { background: linear-gradient(90deg, #6666ff, #4d4dff); color: #fff; } #downloadSelectLiked:hover:not(:disabled) { background: linear-gradient(90deg, #4d4dff, #3333cc); } .downloadButtonRow { display: flex; align-items: center; gap: 6px; margin-bottom: 8px; } #downloadSelectLiked { flex-grow: 1; } #downloadClearSelection { background: linear-gradient(90deg, #ff4d4d, #e63939); color: #fff; width: 28px; height: 28px; padding: 0; font-size: 15px; font-weight: bold; line-height: 1; border: none; border-radius: 5px; cursor: pointer; flex-shrink: 0; display: inline-flex; align-items: center; justify-content: center; margin-bottom: 0; transition: transform 0.15s, background 0.15s; } #downloadClearSelection:hover:not(:disabled) { background: linear-gradient(90deg, #e63939, #cc3333); transform: translateY(-1px); } #downloadClearSelection:disabled { background: #555 !important; cursor: not-allowed; transform: none; opacity: 0.7; } .downloadFormatContainer { margin-top: 8px; padding-top: 8px; border-top: 1px solid #444; } .downloadFormatContainer > label.settings-checkbox-label { margin-bottom: 4px; justify-content: center; display: block; text-align: center;} .downloadFormatContainer div { display: flex; justify-content: space-around; margin-top: 4px; } /* .downloadFormatContainer label.settings-checkbox-label { margin-bottom: 0; } */ /* Already covered by general .settings-checkbox-label */ .downloadDelayContainer { margin-top: 8px; padding-top: 8px; border-top: 1px solid #444; display: flex; justify-content: space-between; gap: 10px; } .downloadDelayContainer > div { flex: 1; } .downloadDelayContainer label.settings-checkbox-label { margin-bottom: 2px; display: block; } .downloadDelayContainer input[type="number"] { margin-top: 0; } #bulkModeControls p { font-size: 11px; color:#aaa; text-align:center; margin-top:4px; margin-bottom: 8px; } #commonSettingsFooter { margin-top: 10px; padding-top: 8px; border-top: 1px solid #444; } `); // --- Helper Functions --- function debounce(func, wait) { let t; return function(...a) { const l=()=> { clearTimeout(t); func.apply(this,a); }; clearTimeout(t); t=setTimeout(l, wait); }; } function log(m, l='info') { const p="[RiffTool]"; if(l==='error') console.error(`${p} ${m}`); else if(l==='warn') console.warn(`${p} ${m}`); else console.log(`${p} ${m}`); updateStatusMessage(m); } function logDebug(m, e=null) { if(!debugMode) return; console.log(`[RiffTool DEBUG] ${m}`, e instanceof Element ? e.outerHTML.substring(0,250)+'...' : e !== null ? e : ''); } function logWarn(m, e=null) { console.warn(`[RiffTool WARN] ${m}`, e instanceof Element ? e.outerHTML.substring(0,250)+'...' : e !== null ? e : ''); } function updateStatusMessage(m) { const s=document.getElementById('statusMessage'); if(s) s.textContent = m.length > 100 ? `... ${m.substring(m.length - 100)}` : m; } function simulateClick(e) { if (!e) { logDebug('Element null for click'); return false; } try { ['pointerdown', 'mousedown', 'pointerup', 'mouseup', 'click'].forEach(t => e.dispatchEvent(new MouseEvent(t, { bubbles: true, cancelable: true, composed: true })) ); logDebug('Sim Click (full event sequence):', e); return true; } catch (err) { log(`Click simulation failed: ${err.message}`, 'error'); console.error('[RiffTool] Click details:', err, e); return false; } } function delay(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } // --- UI Functions --- function createMainUI() { uiElement = document.createElement('div'); uiElement.id = 'riffControlUI'; if (UI_INITIAL_RIGHT) { const rightPx = parseInt(UI_INITIAL_RIGHT, 10); const widthPx = parseInt(uiElement.style.width, 10) || 300; lastUiLeft = `${Math.max(0, window.innerWidth - rightPx - widthPx)}px`; uiElement.style.left = lastUiLeft; uiElement.style.right = 'auto'; } else { lastUiLeft = '20px'; uiElement.style.left = lastUiLeft; } lastUiTop = UI_INITIAL_TOP; uiElement.style.top = lastUiTop; uiElement.style.display = isMinimized ? 'none' : 'block'; uiElement.innerHTML = ` <div id="riffControlHeader"> <h3>Riffusion Multitool v${GM_info.script.version}</h3> <button id="minimizeButton" title="Minimize UI">_</button> </div> <div id="riffControlContent"> <div id="mainMenuControls" class="section-controls"> <button id="goToSelectiveDelete" class="riffMenuButton riffControlButton">Selective Deletion</button> <button id="goToBulkDelete" class="riffMenuButton riffControlButton">Bulk Deletion</button> <button id="goToDownloadQueue" class="riffMenuButton riffControlButton">Download Queue</button> </div> <div id="selectiveModeControls" class="section-controls"> <button class="riffBackButton riffControlButton backToMenuButton">Back to Menu</button> <label class="selectAllContainer"><input type="checkbox" id="deleteSelectAll"> Select All Visible</label> <div id="deleteSongList" class="songListContainer" style="max-height: ${currentDeleteListHeight};">Loading...</div> <div class="listResizer" data-list-id="deleteSongList" data-height-var-name="currentDeleteListHeight"></div> <div id="deleteCounter" class="counterDisplay">Deleted: 0 / 0</div> <button id="deleteButton" class="riffControlButton">Delete Selected</button> <button id="reloadDeleteButton" class="riffControlButton" style="display: ${autoReloadEnabled ? 'none' : 'block'};">Reload List</button> <div class="filterSettings"> <label class="settings-checkbox-label"><input type="checkbox" id="ignoreLikedToggleDelete"> Ignore Liked</label> <input type="text" id="deleteKeywordFilterInput" placeholder="Keywords to ignore (comma-sep)..."> </div> </div> <div id="bulkModeControls" class="section-controls"> <button class="riffBackButton riffControlButton backToMenuButton">Back to Menu</button> <button id="deleteAllButton" class="riffControlButton">Delete Entire Library</button> <p>Deletes all songs without scrolling. Retries if needed. Click "Stop Deletion" to halt.</p> </div> <div id="downloadQueueControls" class="section-controls"> <button class="riffBackButton riffControlButton backToMenuButton">Back to Menu</button> <label class="selectAllContainer"><input type="checkbox" id="downloadSelectAll"> Select All</label> <div class="downloadButtonRow"> <button id="downloadSelectLiked" class="riffControlButton">Select/Deselect Liked</button> <button id="downloadClearSelection" title="Clear Selection" class="riffControlButton">C</button> </div> <div id="downloadSongList" class="songListContainer" style="max-height: ${currentDownloadListHeight};">Loading...</div> <div class="listResizer" data-list-id="downloadSongList" data-height-var-name="currentDownloadListHeight"></div> <div id="downloadCounter" class="counterDisplay">Downloaded: 0 / 0</div> <button id="startDownloadQueueButton" class="riffControlButton">Start Download Queue</button> <button id="reloadDownloadButton" class="riffControlButton" style="display: ${autoReloadEnabled ? 'none' : 'block'};">Reload List</button> <div class="filterSettings"> <label class="settings-checkbox-label" for="downloadKeywordFilterInput">Filter list by keywords:</label> <input type="text" id="downloadKeywordFilterInput" placeholder="Keywords to show (comma-sep)..."> <div class="downloadFormatContainer"> <label class="settings-checkbox-label">Download Formats:</label> <div> <label class="settings-checkbox-label"><input type="checkbox" id="formatMP3" value="MP3" checked> MP3</label> <label class="settings-checkbox-label"><input type="checkbox" id="formatM4A" value="M4A"> M4A</label> <label class="settings-checkbox-label"><input type="checkbox" id="formatWAV" value="WAV"> WAV</label> </div> </div> <div class="downloadDelayContainer"> <div> <label class="settings-checkbox-label" for="downloadIntraFormatDelayInput">Format Delay (s):</label> <input type="number" id="downloadIntraFormatDelayInput" min="0" step="0.1" value="${DEFAULT_INTRA_FORMAT_DELAY_SECONDS}"> </div> <div> <label class="settings-checkbox-label" for="downloadInterSongDelayInput">Song Delay (s):</label> <input type="number" id="downloadInterSongDelayInput" min="1" value="${DEFAULT_INTER_SONG_DELAY_SECONDS}"> </div> </div> </div> </div> <div id="commonSettingsFooter"> <label id="autoReloadToggleContainer" class="settings-checkbox-label" style="display: none;"><input type="checkbox" id="autoReloadToggle"> Auto-Update Lists</label> <label id="debugToggleContainer" class="settings-checkbox-label" style="display: none;"><input type="checkbox" id="debugToggleCheckbox"> Enable Debug</label> </div> <div id="statusMessage">Ready.</div> </div>`; document.body.appendChild(uiElement); minimizedIconElement = document.createElement('div'); minimizedIconElement.id = 'riffControlMinimizedIcon'; minimizedIconElement.textContent = 'RM'; minimizedIconElement.title = 'Restore Riffusion Multitool'; minimizedIconElement.style.display = isMinimized ? 'flex' : 'none'; document.body.appendChild(minimizedIconElement); const header = uiElement.querySelector('#riffControlHeader'); enableDrag(uiElement, header); document.getElementById('minimizeButton')?.addEventListener('click', minimizeUI); minimizedIconElement?.addEventListener('click', restoreUI); document.getElementById('goToSelectiveDelete')?.addEventListener('click', () => navigateToView('selective')); document.getElementById('goToBulkDelete')?.addEventListener('click', () => navigateToView('bulk')); document.getElementById('goToDownloadQueue')?.addEventListener('click', () => navigateToView('download')); uiElement.querySelectorAll('.backToMenuButton').forEach(btn => btn.addEventListener('click', () => navigateToView('menu'))); document.getElementById('deleteSelectAll')?.addEventListener('change', (e) => toggleSelectAll(e, '#deleteSongList', selectedSongIdsDelete)); document.getElementById('deleteButton')?.addEventListener('click', deleteSelectedSongs); document.getElementById('reloadDeleteButton')?.addEventListener('click', () => { if (currentView === 'selective') populateDeleteSongList(); }); const ignoreLikedToggle = document.getElementById('ignoreLikedToggleDelete'); if (ignoreLikedToggle) { ignoreLikedToggle.checked = ignoreLikedSongsDeleteState; ignoreLikedToggle.addEventListener('change', (e) => { ignoreLikedSongsDeleteState = e.target.checked; log(`Ignore Liked Songs (Delete): ${ignoreLikedSongsDeleteState}`); populateDeleteSongList(); });} const deleteKeywordInput = document.getElementById('deleteKeywordFilterInput'); if (deleteKeywordInput) { deleteKeywordInput.addEventListener('input', debounce(() => { log('Delete keywords changed, refreshing list...'); populateDeleteSongList(); }, KEYWORD_FILTER_DEBOUNCE)); } initListResizer(document.querySelector('.listResizer[data-list-id="deleteSongList"]'), document.getElementById('deleteSongList'), 'currentDeleteListHeight'); document.getElementById('deleteAllButton')?.addEventListener('click', () => { if (currentView === 'bulk') { if (isDeleting) { stopBulkDeletionByUser(); } else { if (isDownloading) { log("Download operation in progress. Cannot start deletion.", "warn"); return; } if (confirm("ARE YOU SURE? This will attempt to delete ALL songs in your library without scrolling. NO UNDO.")) { deleteAllSongsInLibrary(); } } } }); document.getElementById('downloadSelectAll')?.addEventListener('change', (e) => toggleSelectAll(e, '#downloadSongList', selectedSongIdsDownload)); document.getElementById('downloadSelectLiked')?.addEventListener('click', toggleSelectLiked); document.getElementById('downloadClearSelection')?.addEventListener('click', clearDownloadSelection); document.getElementById('startDownloadQueueButton')?.addEventListener('click', startDownloadQueue); document.getElementById('reloadDownloadButton')?.addEventListener('click', () => { if (currentView === 'download') populateDownloadSongList(); }); const downloadKeywordInput = document.getElementById('downloadKeywordFilterInput'); if (downloadKeywordInput) { downloadKeywordInput.addEventListener('input', debounce(() => { log('Download filter changed, refreshing list...'); populateDownloadSongList(); }, KEYWORD_FILTER_DEBOUNCE)); } const interSongDelayInput = document.getElementById('downloadInterSongDelayInput'); if (interSongDelayInput) { interSongDelayInput.value = downloadInterSongDelaySeconds; interSongDelayInput.addEventListener('input', (e) => { const val = parseInt(e.target.value, 10); if (!isNaN(val) && val >= 0) { downloadInterSongDelaySeconds = val; log(`Inter-Song delay set to: ${downloadInterSongDelaySeconds}s`); } }); } const intraFormatDelayInput = document.getElementById('downloadIntraFormatDelayInput'); if (intraFormatDelayInput) { intraFormatDelayInput.value = downloadIntraFormatDelaySeconds; intraFormatDelayInput.addEventListener('input', (e) => { const val = parseFloat(e.target.value); if (!isNaN(val) && val >= 0) { downloadIntraFormatDelaySeconds = val; log(`Intra-Format delay set to: ${downloadIntraFormatDelaySeconds}s`); } }); } initListResizer(document.querySelector('.listResizer[data-list-id="downloadSongList"]'), document.getElementById('downloadSongList'), 'currentDownloadListHeight'); const autoReloadCheckbox = document.getElementById('autoReloadToggle'); if (autoReloadCheckbox) { autoReloadCheckbox.checked = autoReloadEnabled; autoReloadCheckbox.addEventListener('change', handleAutoReloadToggle); } const debugCheckbox = document.getElementById('debugToggleCheckbox'); if (debugCheckbox) { debugCheckbox.checked = debugMode; debugCheckbox.addEventListener('change', handleDebugToggle); } updateUIVisibility(); startAutoReloadPolling(); } function minimizeUI() { if (!uiElement || !minimizedIconElement) return; if (!isMinimized) { lastUiTop = uiElement.style.top || UI_INITIAL_TOP; lastUiLeft = uiElement.style.left || lastUiLeft; } uiElement.style.display = 'none'; minimizedIconElement.style.display = 'flex'; isMinimized = true; logDebug("UI Minimized"); } function restoreUI() { if (!uiElement || !minimizedIconElement) return; minimizedIconElement.style.display = 'none'; uiElement.style.display = 'block'; uiElement.style.top = lastUiTop; uiElement.style.left = lastUiLeft; uiElement.style.right = 'auto'; isMinimized = false; logDebug("UI Restored to:", { top: lastUiTop, left: lastUiLeft }); updateUIVisibility(); } function navigateToView(view) { if (isDeleting || isDownloading) { if (!(currentView === 'bulk' && isDeleting)) { log("Cannot switch views while an operation is in progress.", "warn"); return; } } logDebug(`Navigating to view: ${view}`); const oldView = currentView; currentView = view; updateUIVisibility(); if (!autoReloadEnabled || (view === 'selective' && lastKnownSongIdsDelete.length === 0) || (view === 'download' && lastKnownSongIdsDownload.length === 0)) { if (view === 'selective') populateDeleteSongListIfNeeded(); else if (view === 'download') populateDownloadSongListIfNeeded(); } if (autoReloadEnabled && oldView !== currentView) { checkAndReloadLists(true); } } function updateUIVisibility() { if (isMinimized || !uiElement) { if (uiElement) uiElement.style.display = 'none'; if (minimizedIconElement) minimizedIconElement.style.display = isMinimized ? 'flex' : 'none'; return; } if (minimizedIconElement) minimizedIconElement.style.display = 'none'; if (uiElement) uiElement.style.display = 'block'; const sections = { menu: document.getElementById('mainMenuControls'), selective: document.getElementById('selectiveModeControls'), bulk: document.getElementById('bulkModeControls'), download: document.getElementById('downloadQueueControls') }; const headerTitle = uiElement.querySelector('#riffControlHeader h3'); const statusMsg = document.getElementById('statusMessage'); let title = `Riffusion Multitool v${GM_info.script.version}`; Object.values(sections).forEach(section => { if (section) section.style.display = 'none'; }); const autoReloadContainer = document.getElementById('autoReloadToggleContainer'); const debugContainer = document.getElementById('debugToggleContainer'); if (autoReloadContainer) autoReloadContainer.style.display = 'none'; if (debugContainer) debugContainer.style.display = 'none'; if (sections[currentView]) { sections[currentView].style.display = 'block'; switch (currentView) { case 'menu': title += " - Menu"; if(!isDeleting && !isDownloading) updateStatusMessage("Select a tool."); if (debugContainer) debugContainer.style.display = 'flex'; break; case 'selective': title += " - Selective Deletion"; populateDeleteSongListIfNeeded(); if(!isDeleting && !isDownloading) updateStatusMessage("Select songs to delete."); if (autoReloadContainer) autoReloadContainer.style.display = 'flex'; break; case 'bulk': title += " - Bulk Deletion"; const deleteAllBtn = document.getElementById('deleteAllButton'); if (deleteAllBtn) { deleteAllBtn.textContent = isDeleting ? "Stop Deletion" : "Delete Entire Library"; } if(!isDeleting && !isDownloading) updateStatusMessage("Warning: Deletes entire library."); break; case 'download': title += " - Download Queue"; populateDownloadSongListIfNeeded(); if(!isDeleting && !isDownloading) updateStatusMessage("Select songs to download."); if (autoReloadContainer) autoReloadContainer.style.display = 'flex'; break; } } else { log(`View '${currentView}' not found, showing menu.`, 'warn'); sections.menu.style.display = 'block'; currentView = 'menu'; title += " - Menu"; if(!isDeleting && !isDownloading) updateStatusMessage("Select a tool."); if (debugContainer) debugContainer.style.display = 'flex'; } if (headerTitle) headerTitle.textContent = title; if (statusMsg) statusMsg.style.display = 'block'; const reloadDelBtn = document.getElementById('reloadDeleteButton'); if (reloadDelBtn) reloadDelBtn.style.display = autoReloadEnabled ? 'none' : 'block'; const reloadDownBtn = document.getElementById('reloadDownloadButton'); if (reloadDownBtn) reloadDownBtn.style.display = autoReloadEnabled ? 'none' : 'block'; logDebug(`UI Visibility Updated. Current View: ${currentView}`); } function handleDebugToggle(event) { debugMode = event.target.checked; log(`Debug mode ${debugMode ? 'enabled' : 'disabled'}.`); } function enableDrag(element, handle) { let isDragging = false, offsetX, offsetY; handle.addEventListener('mousedown', (e) => { if (e.button !== 0 || e.target.closest('button')) return; if (isMinimized) return; isDragging = true; const rect = element.getBoundingClientRect(); offsetX = e.clientX - rect.left; offsetY = e.clientY - rect.top; element.style.cursor = 'grabbing'; handle.style.cursor = 'grabbing'; document.addEventListener('mousemove', onMouseMove); document.addEventListener('mouseup', onMouseUp, { once: true }); e.preventDefault(); }); function onMouseMove(e) { if (!isDragging) return; let newX = e.clientX - offsetX; let newY = e.clientY - offsetY; const winWidth = window.innerWidth; const winHeight = window.innerHeight; const elWidth = element.offsetWidth; const elHeight = element.offsetHeight; if (newX < 0) newX = 0; if (newY < 0) newY = 0; if (newX + elWidth > winWidth) newX = winWidth - elWidth; if (newY + elHeight > winHeight) newY = winHeight - elHeight; element.style.left = `${newX}px`; element.style.top = `${newY}px`; element.style.right = 'auto'; } function onMouseUp(e) { if (e.button !== 0 || !isDragging) return; isDragging = false; element.style.cursor = 'default'; handle.style.cursor = 'move'; document.removeEventListener('mousemove', onMouseMove); if (!isMinimized) { lastUiTop = element.style.top; lastUiLeft = element.style.left; logDebug("Stored new position after drag:", { top: lastUiTop, left: lastUiLeft }); } } } function initListResizer(resizerElem, listContentElem, heightVarName) { if (!resizerElem || !listContentElem) return; let startY, startHeight; resizerElem.addEventListener('mousedown', function(e) { if (e.button !== 0) return; e.preventDefault(); startY = e.clientY; startHeight = parseInt(window.getComputedStyle(listContentElem).maxHeight, 10); if (isNaN(startHeight)) { startHeight = listContentElem.offsetHeight; } document.addEventListener('mousemove', onMouseMove); document.addEventListener('mouseup', onMouseUp, { once: true }); }); function onMouseMove(e) { if (e.buttons === 0) { onMouseUp(); return; } const dy = e.clientY - startY; let newHeight = startHeight + dy; newHeight = Math.max(50, newHeight); newHeight = Math.min(window.innerHeight * 0.8, newHeight); listContentElem.style.maxHeight = newHeight + 'px'; } function onMouseUp() { document.removeEventListener('mousemove', onMouseMove); const finalHeight = listContentElem.style.maxHeight; if (heightVarName === 'currentDeleteListHeight') currentDeleteListHeight = finalHeight; else if (heightVarName === 'currentDownloadListHeight') currentDownloadListHeight = finalHeight; logDebug(`List ${listContentElem.id} height set to ${finalHeight}`); } } // --- Song List Population & Filtering --- function getSongDataFromPage() { let listContainer = document.querySelector('div[data-sentry-component="InfiniteScroll"] > div.grow'); if (!listContainer || listContainer.children.length === 0) { const allRiffRows = document.querySelectorAll('div[data-sentry-component="DraggableRiffRow"]'); if (allRiffRows.length > 0 && allRiffRows[0].parentElement.childElementCount > 1) { if (Array.from(allRiffRows[0].parentElement.children).every(child => child.getAttribute('data-sentry-component') === 'DraggableRiffRow' || child.tagName === 'HR')) { listContainer = allRiffRows[0].parentElement; } } } const songElements = listContainer ? listContainer.querySelectorAll(':scope > div[data-sentry-component="DraggableRiffRow"]') : document.querySelectorAll('div[data-sentry-component="DraggableRiffRow"]'); const songs = []; songElements.forEach((songElement, index) => { const titleLink = songElement.querySelector('a[href^="/song/"]'); let titleElement = titleLink ? titleLink.querySelector('h4.text-primary') : null; if (!titleElement) titleElement = songElement.querySelector('[data-sentry-element="RiffTitle"]'); if (!titleElement && titleLink) titleElement = titleLink.querySelector('div[class*="truncate"], h4'); const title = titleElement ? titleElement.textContent.trim() : `Untitled Song ${index + 1}`; let songId = null; if (titleLink) { const match = titleLink.href.match(/\/song\/([a-f0-9-]+)/); if (match && match[1]) songId = match[1]; } if (!songId) songId = songElement.dataset.songId; if (!songId) { return; } const unfavoriteButton = songElement.querySelector('button[aria-label^="Unfavorite"]'); const solidHeartIcon = songElement.querySelector('button svg[data-prefix="fas"][data-icon="heart"]'); let isLiked = !!unfavoriteButton || (!!solidHeartIcon && !songElement.querySelector('button[aria-label^="Favorite"]')); songs.push({ id: songId, title: title, titleLower: title.toLowerCase(), isLiked: isLiked, element: songElement }); }); return songs; } function populateDeleteSongListIfNeeded() { const songListDiv = document.getElementById('deleteSongList'); if (!songListDiv) return; if (isDeleting || isDownloading) { logDebug("Skipping delete list population during active operation."); return; } if (songListDiv.innerHTML === '' || songListDiv.innerHTML === 'Loading...' || songListDiv.children.length === 0 || (songListDiv.children.length === 1 && songListDiv.firstElementChild.tagName === 'P')) { populateDeleteSongList(); } } function populateDeleteSongList() { if (currentView !== 'selective' || isMinimized) return; if (isDeleting || isDownloading) { logDebug("Skipping delete list population during active operation."); return; } logDebug('Populating DELETE song list...'); const songListDiv = document.getElementById('deleteSongList'); const deleteCounter = document.getElementById('deleteCounter'); if (!songListDiv || !deleteCounter) return; songListDiv.innerHTML = 'Loading...'; deleteCounter.textContent = 'Deleted: 0 / 0'; const selectAllCheckbox = document.getElementById('deleteSelectAll'); if (selectAllCheckbox) selectAllCheckbox.checked = false; const ignoreLikedCheckbox = document.getElementById('ignoreLikedToggleDelete'); if(ignoreLikedCheckbox) ignoreLikedCheckbox.checked = ignoreLikedSongsDeleteState; const keywordInput = document.getElementById('deleteKeywordFilterInput'); const keywordString = keywordInput ? keywordInput.value : ''; const dynamicIgnoreKeywords = keywordString.split(',').map(k => k.trim().toLowerCase()).filter(k => k !== ''); setTimeout(() => { const songsFromPage = getSongDataFromPage(); songListDiv.innerHTML = ''; songListDiv.style.maxHeight = currentDeleteListHeight; if (songsFromPage.length === 0) { songListDiv.innerHTML = '<p style="color:#d0d0d0;text-align:center;font-size:12px;">No songs found on page.</p>'; if(!isDeleting && !isDownloading) updateStatusMessage("No songs found."); lastKnownSongIdsDelete = []; return; } let ignoredCount = 0; let visibleCount = 0; songsFromPage.forEach(song => { const keywordMatch = dynamicIgnoreKeywords.length > 0 && dynamicIgnoreKeywords.some(keyword => song.titleLower.includes(keyword)); const likedMatch = ignoreLikedSongsDeleteState && song.isLiked; const shouldIgnore = keywordMatch || likedMatch; let ignoreReason = ''; if (keywordMatch) ignoreReason += 'Keyword'; if (likedMatch) ignoreReason += (keywordMatch ? ' & Liked' : 'Liked'); const label = document.createElement('label'); const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.dataset.songId = song.id; checkbox.disabled = shouldIgnore; checkbox.checked = selectedSongIdsDelete.has(song.id) && !shouldIgnore; checkbox.addEventListener('change', (event) => { if (event.target.checked) selectedSongIdsDelete.add(song.id); else selectedSongIdsDelete.delete(song.id); updateSelectAllCheckboxState('#deleteSelectAll', '#deleteSongList'); }); label.appendChild(checkbox); label.appendChild(document.createTextNode(` ${song.title}`)); if (song.isLiked) label.classList.add('liked'); if (shouldIgnore) { label.classList.add('ignored'); label.title = `Ignoring for delete: ${ignoreReason}`; ignoredCount++; } else { visibleCount++; } songListDiv.appendChild(label); }); updateSelectAllCheckboxState('#deleteSelectAll', '#deleteSongList'); logDebug(`Populated DELETE list: ${songsFromPage.length} total, ${visibleCount} selectable, ${ignoredCount} ignored. ${selectedSongIdsDelete.size} selected.`); if(!isDeleting && !isDownloading) updateStatusMessage(`Loaded ${songsFromPage.length} songs (${ignoredCount} ignored).`); lastKnownSongIdsDelete = songsFromPage.map(s => s.id); }, 100); } function populateDownloadSongListIfNeeded() { const songListDiv = document.getElementById('downloadSongList'); if (!songListDiv) return; if (isDeleting || isDownloading) { logDebug("Skipping download list population during active operation."); return; } if (songListDiv.innerHTML === '' || songListDiv.innerHTML === 'Loading...' || songListDiv.children.length === 0 || (songListDiv.children.length === 1 && songListDiv.firstElementChild.tagName === 'P')) { populateDownloadSongList(); } } function populateDownloadSongList() { if (currentView !== 'download' || isMinimized) return; if (isDeleting || isDownloading) { logDebug("Skipping download list population during active operation."); return; } logDebug('Populating DOWNLOAD song list...'); const songListDiv = document.getElementById('downloadSongList'); const downloadCounter = document.getElementById('downloadCounter'); if (!songListDiv || !downloadCounter) return; songListDiv.innerHTML = 'Loading...'; downloadCounter.textContent = 'Downloaded: 0 / 0'; const selectAllCheckbox = document.getElementById('downloadSelectAll'); if (selectAllCheckbox) selectAllCheckbox.checked = false; const keywordInput = document.getElementById('downloadKeywordFilterInput'); const keywordString = keywordInput ? keywordInput.value : ''; const filterKeywords = keywordString.split(',').map(k => k.trim().toLowerCase()).filter(k => k !== ''); setTimeout(() => { const songsFromPage = getSongDataFromPage(); songListDiv.innerHTML = ''; songListDiv.style.maxHeight = currentDownloadListHeight; if (songsFromPage.length === 0) { songListDiv.innerHTML = '<p style="color:#d0d0d0;text-align:center;font-size:12px;">No songs found on page.</p>'; if(!isDeleting && !isDownloading) updateStatusMessage("No songs found."); updateSelectLikedButtonText(); lastKnownSongIdsDownload = []; return; } let displayedCount = 0; songsFromPage.forEach(song => { const keywordMatch = filterKeywords.length === 0 || filterKeywords.some(keyword => song.titleLower.includes(keyword)); if (keywordMatch) { const label = document.createElement('label'); const checkbox = document.createElement('input'); checkbox.type = 'checkbox'; checkbox.dataset.songId = song.id; checkbox.dataset.isLiked = song.isLiked.toString(); checkbox.checked = selectedSongIdsDownload.has(song.id); checkbox.addEventListener('change', (event) => { if (event.target.checked) selectedSongIdsDownload.add(song.id); else selectedSongIdsDownload.delete(song.id); updateSelectAllCheckboxState('#downloadSelectAll', '#downloadSongList'); updateSelectLikedButtonText(); }); label.appendChild(checkbox); label.appendChild(document.createTextNode(` ${song.title}`)); if (song.isLiked) label.classList.add('liked'); songListDiv.appendChild(label); displayedCount++; } }); updateSelectAllCheckboxState('#downloadSelectAll', '#downloadSongList'); logDebug(`Populated DOWNLOAD list: ${songsFromPage.length} total, ${displayedCount} displayed. ${selectedSongIdsDownload.size} selected.`); if(!isDeleting && !isDownloading) updateStatusMessage(`Showing ${displayedCount} of ${songsFromPage.length} songs.`); updateSelectLikedButtonText(); lastKnownSongIdsDownload = songsFromPage.map(s => s.id); }, 100); } function updateSelectAllCheckboxState(selectAllSelector, listSelector) { const selectAllCb = document.querySelector(selectAllSelector); if (!selectAllCb) return; const visibleCheckboxes = document.querySelectorAll(`${listSelector} input[type="checkbox"]:not(:disabled)`); const checkedVisibleCheckboxes = document.querySelectorAll(`${listSelector} input[type="checkbox"]:not(:disabled):checked`); selectAllCb.checked = visibleCheckboxes.length > 0 && visibleCheckboxes.length === checkedVisibleCheckboxes.length; } function toggleSelectAll(event, listSelector, selectionSet) { if (isMinimized || isDeleting || isDownloading) return; const isChecked = event.target.checked; const checkboxes = document.querySelectorAll(`${listSelector} input[type="checkbox"]:not(:disabled)`); checkboxes.forEach(cb => { cb.checked = isChecked; const songId = cb.dataset.songId; if (isChecked) selectionSet.add(songId); else selectionSet.delete(songId); }); logDebug(`Select All Toggled in ${listSelector}: ${isChecked} (${checkboxes.length} items). Selection Set: ${selectionSet.size}`); if(listSelector === '#downloadSongList') updateSelectLikedButtonText(); } function updateSelectLikedButtonText() { if (currentView !== 'download' || isMinimized) return; const button = document.getElementById('downloadSelectLiked'); if (!button) return; const checkboxes = document.querySelectorAll('#downloadSongList input[type="checkbox"]:not(:disabled)'); if (checkboxes.length === 0) { button.textContent = 'Select Liked'; button.disabled = true; return; } button.disabled = false; let shouldOfferSelect = false; checkboxes.forEach(cb => { if (cb.dataset.isLiked === 'true' && !cb.checked) { shouldOfferSelect = true; } }); button.textContent = shouldOfferSelect ? 'Select Liked' : 'Deselect Liked'; } function toggleSelectLiked() { if (currentView !== 'download' || isMinimized || isDeleting || isDownloading) return; const checkboxes = document.querySelectorAll('#downloadSongList input[type="checkbox"]:not(:disabled)'); if (checkboxes.length === 0) { logWarn("No songs available."); return; } let shouldSelect = false; for (const cb of checkboxes) { if (cb.dataset.isLiked === 'true' && !cb.checked) { shouldSelect = true; break; } } let changedCount = 0; checkboxes.forEach(cb => { if (cb.dataset.isLiked === 'true') { if (cb.checked !== shouldSelect) { cb.checked = shouldSelect; const songId = cb.dataset.songId; if (shouldSelect) selectedSongIdsDownload.add(songId); else selectedSongIdsDownload.delete(songId); changedCount++; } } }); log(`Toggled selection for ${changedCount} liked songs. Action: ${shouldSelect ? 'Select' : 'Deselect'}`); updateStatusMessage(`${shouldSelect ? 'Selected' : 'Deselected'} ${changedCount} liked songs.`); updateSelectAllCheckboxState('#downloadSelectAll', '#downloadSongList'); updateSelectLikedButtonText(); } function clearDownloadSelection() { if (currentView !== 'download' || isMinimized || isDeleting || isDownloading) return; const checkboxes = document.querySelectorAll('#downloadSongList input[type="checkbox"]:checked'); if (checkboxes.length === 0) { log("No songs selected.", "info"); return; } checkboxes.forEach(cb => cb.checked = false); selectedSongIdsDownload.clear(); const selectAllCheckbox = document.getElementById('downloadSelectAll'); if (selectAllCheckbox) selectAllCheckbox.checked = false; log(`Cleared selection for ${checkboxes.length} songs.`); updateStatusMessage("Selection cleared."); updateSelectLikedButtonText(); } function updateCounter(type, count, total) { if (isMinimized) return; let counterElementId = ''; if (type === 'delete') counterElementId = 'deleteCounter'; else if (type === 'download') counterElementId = 'downloadCounter'; else return; const counterElement = document.getElementById(counterElementId); if (counterElement) { const prefix = type === 'delete' ? 'Deleted' : 'Downloaded'; counterElement.textContent = `${prefix}: ${count} / ${total}`; } } // --- Auto Reload Logic --- function handleAutoReloadToggle(event) { autoReloadEnabled = event.target.checked; log(`Automatic list reload ${autoReloadEnabled ? 'enabled' : 'disabled'}.`); const reloadDelBtn = document.getElementById('reloadDeleteButton'); if (reloadDelBtn) reloadDelBtn.style.display = autoReloadEnabled ? 'none' : 'block'; const reloadDownBtn = document.getElementById('reloadDownloadButton'); if (reloadDownBtn) reloadDownBtn.style.display = autoReloadEnabled ? 'none' : 'block'; if (autoReloadEnabled) { startAutoReloadPolling(); checkAndReloadLists(true); } else { stopAutoReloadPolling(); } } function startAutoReloadPolling() { if (autoReloadTimer) clearInterval(autoReloadTimer); if (autoReloadEnabled) { autoReloadTimer = setInterval(() => checkAndReloadLists(false), AUTO_RELOAD_INTERVAL); logDebug("Auto-reload polling started."); } } function stopAutoReloadPolling() { if (autoReloadTimer) { clearInterval(autoReloadTimer); autoReloadTimer = null; logDebug("Auto-reload polling stopped."); } } function checkAndReloadLists(forceCheckCurrentView = false) { if ((!autoReloadEnabled && !forceCheckCurrentView) || isMinimized || isDeleting || isDownloading || !uiElement || uiElement.style.display === 'none') { return; } const songsOnPage = getSongDataFromPage(); const currentPageSongIds = songsOnPage.map(s => s.id); const currentPageSongIdsString = [...currentPageSongIds].sort().join(','); let changed = false; if (currentView === 'selective' || forceCheckCurrentView && currentView === 'selective') { const knownIdsString = [...lastKnownSongIdsDelete].sort().join(','); if (currentPageSongIdsString !== knownIdsString) { logDebug("Page song list changed for Selective Deletion. Reloading UI list."); populateDeleteSongList(); changed = true; } else if (forceCheckCurrentView && document.getElementById('deleteSongList')?.children.length === 0 && songsOnPage.length > 0) { populateDeleteSongList(); } } else if (currentView === 'download' || forceCheckCurrentView && currentView === 'download') { const knownIdsString = [...lastKnownSongIdsDownload].sort().join(','); if (currentPageSongIdsString !== knownIdsString) { logDebug("Page song list changed for Download Queue. Reloading UI list."); populateDownloadSongList(); changed = true; } else if (forceCheckCurrentView && document.getElementById('downloadSongList')?.children.length === 0 && songsOnPage.length > 0) { populateDownloadSongList(); } } } // --- Deletion Logic --- function getCurrentSongElements() { let listContainer = document.querySelector('div[data-sentry-component="InfiniteScroll"] > div.grow'); if (!listContainer || listContainer.children.length === 0) { const allRiffRows = document.querySelectorAll('div[data-sentry-component="DraggableRiffRow"]'); if (allRiffRows.length > 0 && allRiffRows[0].parentElement.childElementCount > 1) { if (Array.from(allRiffRows[0].parentElement.children).every(child => child.getAttribute('data-sentry-component') === 'DraggableRiffRow' || child.tagName === 'HR')) { listContainer = allRiffRows[0].parentElement; } } } if(listContainer) { return listContainer.querySelectorAll(':scope > div[data-sentry-component="DraggableRiffRow"]'); } return document.querySelectorAll('div[data-sentry-component="DraggableRiffRow"]'); } async function deleteSelectedSongs() { if (isMinimized) { log("Restore UI to delete.", "warn"); return; } if (currentView !== 'selective') { log("Selective delete only in Selective View.", "warn"); return; } if (isDeleting || isDownloading) { log("Operation in progress.", "warn"); return; } const songIdsToDeleteArray = Array.from(selectedSongIdsDelete); const totalToDelete = songIdsToDeleteArray.length; if (totalToDelete === 0) { updateCounter('delete', 0, 0); log('No songs selected for deletion.'); updateStatusMessage('No songs selected or all selected are ignored.'); return; } isDeleting = true; setAllButtonsDisabled(true); log(`Starting deletion for ${totalToDelete} selected: [${songIdsToDeleteArray.join(', ')}]`); updateCounter('delete', 0, totalToDelete); updateStatusMessage(`Deleting ${totalToDelete} selected...`); let deletedCount = 0, criticalErrorOccurred = false; for (const songId of songIdsToDeleteArray) { if (criticalErrorOccurred || !isDeleting) { break; } const songElement = document.querySelector(`div[data-sentry-component="DraggableRiffRow"] a[href="/song/${songId}"]`)?.closest('div[data-sentry-component="DraggableRiffRow"]'); if (!songElement) { log(`Song ID ${songId} not found (deleted?). Removing from selection.`, "warn"); selectedSongIdsDelete.delete(songId); continue; } const title = getSongDataFromPage().find(s => s.id === songId)?.title || `song ID ${songId}`; const success = await processSingleAction(songElement, 'delete', songId); if (success) { deletedCount++; selectedSongIdsDelete.delete(songId); updateCounter('delete', deletedCount, totalToDelete); updateStatusMessage(`Deleted ${deletedCount}/${totalToDelete}...`); } else { log(`Failed to delete ${title}. Stopping.`, "error"); updateStatusMessage(`Error deleting ${title}. Stopped.`); criticalErrorOccurred = true; } await delay(50); } log(`Selective deletion: ${deletedCount}/${totalToDelete} attempted.`); updateStatusMessage(criticalErrorOccurred ? `Deletion stopped. ${deletedCount} deleted.` : `Selected deletion complete. ${deletedCount} deleted.`); isDeleting = false; setAllButtonsDisabled(false); populateDeleteSongList(); } function stopBulkDeletionByUser() { if (!isDeleting || currentView !== 'bulk') { return; } log("Bulk deletion stop by user."); updateStatusMessage("Stopping bulk deletion..."); stopBulkDeletionSignal = true; isDeleting = false; } async function deleteAllSongsInLibrary() { if (isMinimized) { log("Restore UI to delete.", "warn"); return; } if (currentView !== 'bulk') { log("Bulk delete only in Bulk View.", "warn"); return; } stopBulkDeletionSignal = false; isDeleting = true; setAllButtonsDisabled(true); const deleteAllBtn = document.getElementById('deleteAllButton'); if (deleteAllBtn) deleteAllBtn.textContent = "Stop Deletion"; log("--- STARTING BULK LIBRARY DELETION ---"); updateStatusMessage("Starting full library deletion..."); let totalDeleted = 0, emptyChecks = 0, currentElements; while (isDeleting) { await delay(500); if (!isDeleting || stopBulkDeletionSignal) { break; } currentElements = getCurrentSongElements(); let currentSize = currentElements.length; if (currentSize === 0) { emptyChecks++; if (emptyChecks >= MAX_EMPTY_CHECKS) { log("No songs after retries. Assuming empty."); isDeleting = false; break; } updateStatusMessage(`No songs. Re-checking (${emptyChecks}/${MAX_EMPTY_CHECKS})...`); await delay(EMPTY_RETRY_DELAY); continue; } emptyChecks = 0; let batchDeleted = 0; while (currentSize > 0 && isDeleting && !stopBulkDeletionSignal) { const firstElement = getCurrentSongElements()[0]; if (!firstElement || !firstElement.parentNode) { await delay(100); currentSize = getCurrentSongElements().length; continue; } const title = (firstElement.querySelector('a[href^="/song/"] h4, [data-sentry-element="RiffTitle"], div[class*="truncate"]') || {textContent: 'Top song'}).textContent.trim(); updateStatusMessage(`Deleting ${title} (${totalDeleted + batchDeleted + 1} total...)`); const success = await processSingleAction(firstElement, 'delete', `Bulk ${totalDeleted + batchDeleted + 1}`); if (success) { batchDeleted++; await delay(DELETION_DELAY / 2); currentSize = getCurrentSongElements().length; } else { log(`Failed to delete ${title}. Stopping.`, "error"); updateStatusMessage(`Error deleting ${title}.`); isDeleting = false; break; } await delay(50); } totalDeleted += batchDeleted; if (isDeleting && !stopBulkDeletionSignal) updateStatusMessage(`Batch done. Total: ${totalDeleted}. Checking more...`); } if (deleteAllBtn) deleteAllBtn.textContent = "Delete Entire Library"; let finalMsg = stopBulkDeletionSignal ? `Stopped by user. Total: ${totalDeleted}.` : (emptyChecks >= MAX_EMPTY_CHECKS ? `Complete. No more songs. Total: ${totalDeleted}.` : `Finished. Total: ${totalDeleted}.`); log(`--- BULK DELETION FINISHED --- ${finalMsg}`); updateStatusMessage(finalMsg); isDeleting = false; stopBulkDeletionSignal = false; setAllButtonsDisabled(false); } // --- Download Logic --- async function startDownloadQueue() { if (isMinimized) { log("Restore UI to download.", "warn"); return; } if (currentView !== 'download') { log("Download only in Download View.", "warn"); return; } if (isDeleting || isDownloading) { log("Operation in progress.", "warn"); return; } const songIdsToDownloadArray = Array.from(selectedSongIdsDownload); const totalSongsToDownload = songIdsToDownloadArray.length; if (totalSongsToDownload === 0) { updateCounter('download', 0, 0); log('No songs selected.'); updateStatusMessage('No songs selected.'); return; } const selectedFormats = []; if (document.getElementById('formatMP3')?.checked) selectedFormats.push('MP3'); if (document.getElementById('formatM4A')?.checked) selectedFormats.push('M4A'); if (document.getElementById('formatWAV')?.checked) selectedFormats.push('WAV'); if (selectedFormats.length === 0) { log('No formats selected.', 'error'); updateStatusMessage('Select download format(s).'); return; } isDownloading = true; setAllButtonsDisabled(true); const interSongDelayMs = downloadInterSongDelaySeconds * 1000, intraFormatDelayMs = downloadIntraFormatDelaySeconds * 1000; log(`Starting download: ${totalSongsToDownload} songs. Formats: [${selectedFormats.join(', ')}]`); updateCounter('download', 0, totalSongsToDownload); updateStatusMessage(`Downloading ${totalSongsToDownload} (${selectedFormats.join('/')})...`); let songsProcessedCount = 0, criticalErrorOccurred = false; for (const songId of songIdsToDownloadArray) { if (criticalErrorOccurred || !isDownloading) { break; } const songElement = document.querySelector(`div[data-sentry-component="DraggableRiffRow"] a[href="/song/${songId}"]`)?.closest('div[data-sentry-component="DraggableRiffRow"]'); if (!songElement) { log(`Song ID ${songId} not found. Skipping.`, "warn"); selectedSongIdsDownload.delete(songId); continue; } const title = getSongDataFromPage().find(s => s.id === songId)?.title || `song ID ${songId}`; let songDownloadSuccessThisSong = false, formatIndex = 0; for (const format of selectedFormats) { if (!isDownloading) { criticalErrorOccurred = true; break; } const currentSongElCheck = document.querySelector(`div[data-sentry-component="DraggableRiffRow"] a[href="/song/${songId}"]`)?.closest('div[data-sentry-component="DraggableRiffRow"]'); if (!currentSongElCheck) { logWarn(`${title} disappeared. Skipping formats.`); criticalErrorOccurred = true; break; } updateStatusMessage(`DL ${songsProcessedCount + 1}/${totalSongsToDownload}: ${title} (${format})...`); const success = await processSingleAction(currentSongElCheck, 'download', `${songId}-${format}`, format); if (success) { songDownloadSuccessThisSong = true; formatIndex++; if (formatIndex < selectedFormats.length && isDownloading && intraFormatDelayMs > 0) await delay(intraFormatDelayMs); else if (isDownloading && intraFormatDelayMs <= 0 && formatIndex < selectedFormats.length) await delay(50); } else { log(`Failed DL ${title} (${format}). Stopping.`, "error"); updateStatusMessage(`Error DL ${title} (${format}).`); criticalErrorOccurred = true; break; } } if (songDownloadSuccessThisSong) songsProcessedCount++; if (criticalErrorOccurred || !isDownloading) break; if (songsProcessedCount < totalSongsToDownload && isDownloading && (songIdsToDownloadArray.indexOf(songId) < songIdsToDownloadArray.length -1) ) { updateStatusMessage(`Wait ${downloadInterSongDelaySeconds}s for next song...`); await delay(interSongDelayMs); } } log(`DL queue finished. Processed ${songsProcessedCount}/${totalSongsToDownload}.`); updateStatusMessage(criticalErrorOccurred ? `DL stopped. ${songsProcessedCount} processed.` : `DL queue complete. ${songsProcessedCount} processed.`); isDownloading = false; setAllButtonsDisabled(false); populateDownloadSongList(); } // --- Generic Action Processor --- async function processSingleAction(songElement, actionType, identifier, format = null, retryCount = 0) { const logPrefix = `(${actionType} - ${identifier}) -`; if ((!isDownloading && actionType === 'download') || (!isDeleting && actionType === 'delete')) { log(`${logPrefix} Op cancelled.`, "warn"); return false; } if (!songElement || !songElement.parentNode) { log(`${logPrefix} Element gone. OK.`, "warn"); return true; } const menuButton = songElement.querySelector('button[data-sentry-element="MenuTrigger"]'); if (!menuButton) { log(`${logPrefix} No MenuTrigger.`, "error"); return false; } logDebug(`${logPrefix} Clicking 'More options' button:`, menuButton); if (!simulateClick(menuButton)) { log(`${logPrefix} Fail click MenuTrigger.`, "error"); return false; } await delay(DROPDOWN_DELAY); let primaryActionText = actionType === 'delete' ? 'delete' : 'download'; let primaryActionItem = null, downloadMenuItemId = null, menuContentElement = null; let potentialItems = []; let popperWrapper = document.querySelector(`div[data-radix-popper-content-wrapper][style*="transform: translate"]`); if (popperWrapper) menuContentElement = popperWrapper.querySelector('div[data-radix-menu-content][data-state="open"]'); if (!menuContentElement) { // Fallback: Search globally if specific popper method fails const openMenus = document.querySelectorAll('div[data-radix-menu-content][data-state="open"]'); if (openMenus.length > 0) menuContentElement = openMenus[openMenus.length - 1]; // Assume last opened } if (!menuContentElement) { if (retryCount < MAX_RETRIES) { logWarn(`${logPrefix} No open menu content. Retrying (Attempt ${retryCount + 1}/${MAX_RETRIES})`); try { document.body.click(); await delay(150); } catch(e){} // Click away to close stale menus return processSingleAction(songElement, actionType, identifier, format, retryCount + 1); } log(`${logPrefix} No open menu content after retries.`, "error"); try { document.body.click(); await delay(50); } catch(e){} return false; } potentialItems = menuContentElement.querySelectorAll(':scope > [role="menuitem"], :scope > [data-radix-collection-item]'); logDebug(`${logPrefix} Found ${potentialItems.length} potential menu items.`); // --- REVERTED/IMPROVED TEXT FINDING LOGIC FOR primaryActionItem --- primaryActionItem = Array.from(potentialItems).find(el => { const isVisible = el.offsetParent !== null; if (!isVisible) return false; let itemText = ''; const lineClampDiv = el.querySelector('.line-clamp-2'); if (lineClampDiv) { itemText = lineClampDiv.textContent.trim().toLowerCase(); } else { // This fallback structure was more robust and used in previously working versions const mainContentContainer = el.querySelector('.flex.items-center.gap-4'); if (mainContentContainer) { let textFromNodes = ''; mainContentContainer.childNodes.forEach(node => { if (node.nodeType === Node.TEXT_NODE && node.textContent.trim() !== '') { textFromNodes += node.textContent.trim() + ' '; } else if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains('overflow-hidden') && !node.querySelector('svg')) { textFromNodes += node.textContent.trim() + ' '; } }); itemText = textFromNodes.trim().toLowerCase(); } else { itemText = el.textContent.trim().toLowerCase(); // Simplest fallback } } logDebug(`${logPrefix} Checking menu item, text: '${itemText}' vs target: '${primaryActionText}'`); if (itemText === primaryActionText) { if (primaryActionText === 'download') { downloadMenuItemId = el.getAttribute('aria-controls'); logDebug(`${logPrefix} Found '${primaryActionText}' item, controls submenu: ${downloadMenuItemId || 'N/A'}`); } else { logDebug(`${logPrefix} Found '${primaryActionText}' item`); } return true; } return false; }); // --- END REVERTED/IMPROVED TEXT FINDING LOGIC --- if (!primaryActionItem && retryCount < MAX_RETRIES) { logWarn(`${logPrefix} '${primaryActionText}' option not found in menu (Attempt ${retryCount + 1}/${MAX_RETRIES}). Retrying...`); try { document.body.click(); await delay(150); } catch(e){} // Close current menu if (!songElement?.parentNode) { logWarn(`${logPrefix} Song element disappeared before retry for '${primaryActionText}'.`); return (actionType === 'delete'); // If deleting, assume success. If downloading, fail. } if (!songElement.querySelector('button[data-sentry-element="MenuTrigger"]')) { logWarn(`${logPrefix} Song's menu button disappeared before retry for '${primaryActionText}'.`); return false; } return processSingleAction(songElement, actionType, identifier, format, retryCount + 1); } if (!primaryActionItem) { log(`${logPrefix} '${primaryActionText}' option not found after ${MAX_RETRIES} retries. Aborting. Menu HTML:`, menuContentElement.innerHTML.substring(0, 700) + '...'); try { document.body.click(); await delay(50); } catch(e){} return false; } logDebug(`${logPrefix} Clicking primary action '${primaryActionText}' (controls: ${primaryActionItem.getAttribute('aria-controls') || 'N/A'}):`, primaryActionItem); if (!simulateClick(primaryActionItem)) { log(`${logPrefix} Failed to simulate click on '${primaryActionText}' option.`, "error"); try { document.body.click(); await delay(50); } catch(e){} return false; } if (actionType === 'delete') { await delay(DELETION_DELAY); logDebug(`--- Finished processing ${logPrefix} (Delete action assumed successful) ---`); return true; } else if (actionType === 'download') { if (!downloadMenuItemId) { log(`${logPrefix} No submenu ID for Download. Aborting format ${format}.`, "error"); try { document.body.click(); await delay(50); } catch(e){} return false; } let subMenuContent = null, subMenuOpenRetries = 0; while (isDownloading && subMenuOpenRetries < MAX_SUB_MENU_OPEN_RETRIES) { await delay(DOWNLOAD_MENU_DELAY); subMenuContent = document.getElementById(downloadMenuItemId); if (subMenuContent?.getAttribute('data-state') === 'open') { logDebug(`${logPrefix} Download sub-menu (ID: ${downloadMenuItemId}) found by ID and open.`); break; } else { const allPoppers = Array.from(document.querySelectorAll(`div[data-radix-popper-content-wrapper][style*="transform: translate"]`)); if (allPoppers.some(p => { const sm = p.querySelector(`div[data-radix-menu-content][data-state="open"][id="${downloadMenuItemId}"]`); if (sm) { subMenuContent = sm; logDebug(`${logPrefix} Found download sub-menu in popper.`);} return sm; })) break; } subMenuOpenRetries++; if (subMenuOpenRetries > 1 && primaryActionItem?.offsetParent !== null && primaryActionItem.getAttribute('data-state') === 'closed') { logWarn(`${logPrefix} Submenu not opening. Re-clicking 'Download'. Attempt ${subMenuOpenRetries}.`); if(!simulateClick(primaryActionItem)) { logWarn("Re-click download for submenu failed."); break;} } } if (!isDownloading) { log(`${logPrefix} Download cancelled while waiting for sub-menu.`, "warn"); return false; } if (!subMenuContent || subMenuContent.getAttribute('data-state') !== 'open') { log(`${logPrefix} Download sub-menu (ID: ${downloadMenuItemId}) did not open. Aborting for this format.`, "error"); try { document.body.click(); await delay(50); } catch(e){} return false; } let formatItem = null; const formatTextUpper = format.toUpperCase(); logDebug(`${logPrefix} Open sub-menu (ID: ${subMenuContent.id}). Searching for format '${formatTextUpper}'.`); const potentialFormatItems = subMenuContent.querySelectorAll(':scope > [role="menuitem"], :scope > [data-radix-collection-item]'); // Use simpler text finding for format items, usually less complex formatItem = Array.from(potentialFormatItems).find(el => { const textDiv = el.querySelector('.line-clamp-2'); const itemText = textDiv ? textDiv.textContent.trim().toUpperCase() : el.textContent.trim().toUpperCase(); return itemText === formatTextUpper && el.offsetParent !== null && !el.querySelector('svg[data-icon="angle-right"]'); }); if (!formatItem && retryCount < MAX_RETRIES) { logWarn(`${logPrefix} Format '${formatTextUpper}' not in sub-menu (Attempt ${retryCount +1}/${MAX_RETRIES}). Re-checking...`, "warn"); await delay(DOWNLOAD_MENU_DELAY / 2); if (subMenuContent?.getAttribute('data-state') === 'open') { const potentialFormatItemsAgain = subMenuContent.querySelectorAll(':scope > [role="menuitem"], :scope > [data-radix-collection-item]'); formatItem = Array.from(potentialFormatItemsAgain).find(el => { const textDiv = el.querySelector('.line-clamp-2'); const itemText = textDiv ? textDiv.textContent.trim().toUpperCase() : el.textContent.trim().toUpperCase(); return itemText === formatTextUpper && el.offsetParent !== null && !el.querySelector('svg[data-icon="angle-right"]'); }); if (formatItem) logDebug(`${logPrefix} Found format '${formatTextUpper}' after re-check.`); } else { log(`${logPrefix} Sub-menu closed unexpectedly.`, 'error'); return false; } } if (!formatItem) { log(`${logPrefix} Format '${formatTextUpper}' not found. Submenu:`, subMenuContent.innerHTML.substring(0,700)); return false; } logDebug(`${logPrefix} Clicking format '${formatTextUpper}' option:`, formatItem); if (!simulateClick(formatItem)) { log(`${logPrefix} Failed click format '${formatTextUpper}'.`, "error"); return false; } await delay(DOWNLOAD_ACTION_DELAY); logDebug(`--- Finished processing ${logPrefix} (Format ${format} assumed initiated) ---`); return true; } return false; } // --- Utility --- function setAllButtonsDisabled(disabled) { if (!uiElement) return; if (isMinimized && disabled) { return; } const buttons = uiElement.querySelectorAll('#riffControlContent button'); buttons.forEach(btn => { if (btn.id === 'minimizeButton') return; if (btn.id === 'deleteAllButton' && currentView === 'bulk' && isDeleting && disabled) btn.disabled = false; else btn.disabled = disabled; }); const inputs = uiElement.querySelectorAll('#riffControlContent input, #riffControlContent select'); inputs.forEach(input => { if (input.type === 'checkbox' && (input.id === 'autoReloadToggle' || input.id === 'debugToggleCheckbox' || input.id.startsWith('format') || input.id === 'ignoreLikedToggleDelete')) { // Note: ignoreLikedToggleDelete is specific to its section input.disabled = false; } else if (input.id.includes('DelayInput')) { input.disabled = false; } else input.disabled = disabled; }); const labels = uiElement.querySelectorAll('#riffControlContent label.settings-checkbox-label, #riffControlContent label.selectAllContainer, #riffControlContent .downloadFormatContainer > label.settings-checkbox-label, #riffControlContent .downloadDelayContainer label.settings-checkbox-label'); labels.forEach(label => { const forActiveStop = label.htmlFor === 'deleteAllButton' && currentView === 'bulk' && isDeleting && disabled; const isAlwaysInteractive = label.closest('#commonSettingsFooter') || label.closest('.downloadFormatContainer') || label.closest('.downloadDelayContainer') || label.htmlFor === 'ignoreLikedToggleDelete'; // Check for 'for' attribute for ignoreLiked if (forActiveStop || isAlwaysInteractive) { label.style.cursor = 'pointer'; label.style.opacity = '1'; } else { label.style.cursor = disabled ? 'not-allowed' : 'pointer'; label.style.opacity = disabled ? '0.7' : '1'; } }); const songListCheckboxes = uiElement.querySelectorAll('.songListContainer input[type="checkbox"]'); songListCheckboxes.forEach(cb => { if (!cb.classList.contains('ignored')) cb.disabled = disabled; }); if (!disabled) { if(currentView === 'selective' && document.getElementById('selectiveModeControls')?.style.display === 'block') populateDeleteSongListIfNeeded(); if(currentView === 'download' && document.getElementById('downloadQueueControls')?.style.display === 'block') populateDownloadSongListIfNeeded(); } const status = document.getElementById('statusMessage'); if (status) status.style.pointerEvents = (disabled && !(currentView === 'bulk' && isDeleting && disabled)) ? 'none' : 'auto'; logDebug(`Controls ${disabled ? 'mostly disabled' : 'enabled'}.`); } // --- Initialization --- function waitForAppReady(callback) { const checkInterval = 500, maxWaitTime = 20000; let elapsedTime = 0; const intervalId = setInterval(() => { elapsedTime += checkInterval; const appReadyElement = document.querySelector('div#__next main, div#__next nav, div#__next header'); if (appReadyElement) { clearInterval(intervalId); setTimeout(callback, 300); } else if (elapsedTime >= maxWaitTime) { clearInterval(intervalId); logWarn("Riffusion app not fully detected. Initializing anyway."); setTimeout(callback, 300); } }, checkInterval); } function init() { try { log(`Riffusion Multitool Script Loaded (v${GM_info.script.version}).`); createMainUI(); log(`Initialized. UI is ${isMinimized ? 'minimized' : 'visible'}. Auto-reload: ${autoReloadEnabled}. Debug: ${debugMode}.`); if (isMinimized) updateStatusMessage("Ready. Click icon to expand."); logDebug("Initial debug log test post-UI creation."); // Test debug log } catch (e) { console.error("[RiffTool] Initialization failed:", e); alert("RiffTool Init Error"); } } waitForAppReady(init); })();
QingJ © 2025
镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址