|
// ==UserScript== |
|
// @name LastFM automated duplicate scrobble deletion script |
|
// @namespace https://gist.github.com/muhdiboy |
|
// @version 2.0.0 |
|
// @downloadURL https://gist.github.com/muhdiboy/a293cbff355af750e3b8f45ec816d1f1/raw/lastfm-automated-remove-duplicates.user.js |
|
// @updateURL https://gist.github.com/muhdiboy/a293cbff355af750e3b8f45ec816d1f1/raw/lastfm-automated-remove-duplicates.user.js |
|
// @description Based on https://gist.github.com/sk22/39cc280840f9d82df574c15d6eda6629#gistcomment-3046698, thanks to previous contributors (@CennoxX, @mattsson, @gms8994, @huw and @sk22) and new contributors (@Eiron). |
|
// @author muhdiboy |
|
// @match https://www.last.fm/*user/* |
|
// @icon https://www.last.fm/static/images/favicon.ico |
|
// @grant none |
|
// ==/UserScript== |
|
|
|
(function() { |
|
let runScript = localStorage.getItem('runScript') === 'true'; |
|
let rmOnlyRealDup = localStorage.getItem('rmOnlyRealDup') !== 'false'; // checkbox defaults to checked |
|
let numTracks = localStorage.getItem('numTracks') || "5"; |
|
let stopAtPage = localStorage.getItem('stopAtPage') || "0"; |
|
|
|
// Always read the page number fresh from the current URL. A cached value |
|
// goes stale when the user clicks through Last.fm's own pagination (the |
|
// click handler fires before the URL updates), and it also misreads the |
|
// /library/delete (405) page as "page 1" because that URL has no page param. |
|
function getCurrentPage() { |
|
return extractQueryParam('page', window.location.href) || 1; |
|
} |
|
|
|
// Add/remove the panel as the URL changes, and keep the current-page label live. |
|
setInterval(function () { |
|
if (this.lastPathStr !== location.pathname || this.lastQueryStr !== location.search) { |
|
this.lastPathStr = location.pathname; |
|
this.lastQueryStr = location.search; |
|
if (shouldMatchPage()) buildPanel(); else removePanel(); |
|
} |
|
const pageLbl = document.getElementById('lfm-stop-page-lbl'); |
|
if (pageLbl) pageLbl.textContent = 'Stop at which page? (current: ' + getCurrentPage() + ')'; |
|
}, 125); |
|
|
|
function replaceQueryParam(param, newval, search) { |
|
const regex = new RegExp("([?;&])" + param + "[^&;]*[;&]?"); |
|
const query = search.replace(regex, "$1").replace(/&$/, ''); |
|
return (query.length > 2 ? query + "&" : "?") + (newval ? param + "=" + newval : ''); |
|
} |
|
|
|
function extractQueryParam(name, url) { |
|
if (!url) url = window.location.href; |
|
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); |
|
const regexS = "[\\?&]" + name + "=([^&#]*)"; |
|
const regex = new RegExp(regexS); |
|
const results = regex.exec(url); |
|
return results == null ? null : results[1]; |
|
} |
|
|
|
function shouldMatchPage() { |
|
const url = window.location.href; |
|
const excludeUrlRegex = /^https:\/\/www\.last\.fm\/.*user\/.*\/library\/(albums|artists|tracks|music).*/; |
|
const matchUrlRegex = /^https:\/\/www\.last\.fm\/.*user\/.*\/library.*/; |
|
return matchUrlRegex.test(url) && !excludeUrlRegex.test(url); |
|
} |
|
|
|
// ---- Logging ---------------------------------------------------------- |
|
// The page reloads constantly while running, so the log is persisted in |
|
// localStorage and re-rendered each time the panel is built. |
|
function loadLog() { |
|
try { return JSON.parse(localStorage.getItem('lfmLog')) || []; } |
|
catch (e) { return []; } |
|
} |
|
|
|
function log(msg, level) { |
|
const entries = loadLog(); |
|
const now = new Date(); |
|
const ts = String(now.getHours()).padStart(2, '0') + ':' + |
|
String(now.getMinutes()).padStart(2, '0') + ':' + |
|
String(now.getSeconds()).padStart(2, '0'); |
|
entries.unshift({ ts: ts, msg: msg, level: level || 'info' }); |
|
while (entries.length > 60) entries.pop(); |
|
localStorage.setItem('lfmLog', JSON.stringify(entries)); |
|
renderLog(); |
|
} |
|
|
|
function renderLog() { |
|
const logEl = document.getElementById('lfm-log'); |
|
if (!logEl) return; |
|
logEl.textContent = ''; |
|
loadLog().forEach(function (e) { |
|
const line = document.createElement('div'); |
|
line.className = 'log-' + e.level; |
|
line.textContent = '[' + e.ts + '] ' + e.msg; |
|
logEl.appendChild(line); |
|
}); |
|
} |
|
|
|
function setStatus(text, running) { |
|
const statusEl = document.getElementById('lfm-status'); |
|
if (!statusEl) return; |
|
statusEl.innerHTML = ''; |
|
if (running) { |
|
const spin = document.createElement('span'); |
|
spin.className = 'lfm-spin'; |
|
statusEl.appendChild(spin); |
|
} |
|
statusEl.appendChild(document.createTextNode(text)); |
|
} |
|
|
|
function removePanel() { |
|
const panel = document.getElementById('lfm-panel'); |
|
if (panel) panel.remove(); |
|
} |
|
|
|
// ---- Actions ---------------------------------------------------------- |
|
function startScript() { |
|
const pageInput = document.getElementById('lfm-stop-page'); |
|
const tracksInput = document.getElementById('lfm-num-tracks'); |
|
|
|
const inputStopAtPage = (pageInput.value || '').trim(); |
|
if (!/^\d+$/.test(inputStopAtPage)) { |
|
log('\u2715 Invalid stop page. Enter a valid number.', 'err'); |
|
return; |
|
} |
|
const curPage = getCurrentPage(); |
|
if (parseInt(inputStopAtPage) > curPage && !(curPage === 0 && parseInt(inputStopAtPage) === 1)) { |
|
log('\u2715 Stop page must be \u2264 current page (' + curPage + ').', 'err'); |
|
return; |
|
} |
|
localStorage.setItem('stopAtPage', inputStopAtPage); |
|
|
|
if (!rmOnlyRealDup) { |
|
const inputNumTracks = (tracksInput.value || '').trim(); |
|
if (!/^\d+$/.test(inputNumTracks) || inputNumTracks < 2 || inputNumTracks > 50) { |
|
log('\u2715 Tracks to compare must be a number between 2 and 50.', 'err'); |
|
return; |
|
} |
|
localStorage.setItem('numTracks', inputNumTracks); |
|
} |
|
|
|
localStorage.setItem('runScript', 'true'); |
|
localStorage.setItem('totalDeleted', '0'); |
|
localStorage.removeItem('lfmDone'); |
|
log('\u25B6 Started. Stopping at page ' + inputStopAtPage + '.', 'life'); |
|
location.reload(); |
|
} |
|
|
|
function stopScript() { |
|
localStorage.setItem('runScript', 'false'); |
|
localStorage.removeItem('savedUrl'); |
|
localStorage.removeItem('refreshTimeout'); |
|
localStorage.removeItem('totalDeleted'); |
|
log('\u25A0 Stopped by user.', 'life'); |
|
location.reload(); |
|
} |
|
|
|
// ---- Panel ------------------------------------------------------------ |
|
function buildPanel() { |
|
if (document.getElementById('lfm-panel')) return; |
|
|
|
const style = document.createElement('style'); |
|
style.textContent = ` |
|
#lfm-panel { |
|
position:fixed;left:18px;bottom:90px;z-index:2147483647; |
|
width:300px;background:#111;color:#eee; |
|
border:1px solid #333;border-radius:10px; |
|
font:12px/1.4 "Inter","Segoe UI",sans-serif; |
|
box-shadow:0 8px 40px rgba(0,0,0,.85); |
|
display:flex;flex-direction:column;overflow:hidden; |
|
} |
|
#lfm-panel * { box-sizing:border-box; } |
|
#lfm-header { |
|
display:flex;align-items:center;justify-content:space-between; |
|
padding:10px 14px;background:#1a1a1a;border-bottom:1px solid #2a2a2a; |
|
cursor:pointer;user-select:none; |
|
} |
|
.lfm-h-title{font-weight:700;color:#e11d48;font-size:13px;} |
|
.lfm-h-hint{color:#444;font-size:11px;} |
|
#lfm-body{display:flex;flex-direction:column;gap:9px;padding:12px;} |
|
.lfm-lbl{font-size:10px;color:#888;margin-bottom:-4px;} |
|
.lfm-input{ |
|
width:100%;padding:6px 8px;background:#1e1e1e; |
|
border:1px solid #333;border-radius:6px;color:#eee; |
|
font-size:12px;font-family:inherit; |
|
} |
|
.lfm-input::placeholder{color:#555;} |
|
.lfm-row{display:flex;gap:8px;} |
|
.lfm-check{display:flex;align-items:center;gap:7px;cursor:pointer;user-select:none;color:#ccc;} |
|
.lfm-check input{accent-color:#e11d48;width:14px;height:14px;cursor:pointer;} |
|
.lfm-btn{flex:1;padding:7px 0;border:none;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;} |
|
.lfm-btn:hover{opacity:.85;} |
|
.lfm-btn-primary{background:#e11d48;color:#fff;} |
|
.lfm-btn-secondary{background:#2a2a2a;color:#ccc;border:1px solid #3a3a3a;} |
|
#lfm-status{font-size:11px;color:#bbb;padding:5px 0;border-top:1px solid #1c1c1c;min-height:20px;} |
|
#lfm-log{ |
|
height:120px;overflow-y:auto;background:#050505; |
|
border:1px solid #1a1a1a;border-radius:6px; |
|
padding:5px 7px;font-family:monospace;font-size:10px; |
|
display:flex;flex-direction:column;gap:1px; |
|
} |
|
.log-ok{color:#4ade80;}.log-warn{color:#fbbf24;}.log-err{color:#f87171;}.log-info{color:#888;}.log-life{color:#22d3ee;} |
|
@keyframes lfm-spin{to{transform:rotate(360deg);}} |
|
.lfm-spin{ |
|
display:inline-block;width:10px;height:10px; |
|
border:2px solid #e11d48;border-top-color:transparent; |
|
border-radius:50%;animation:lfm-spin .7s linear infinite; |
|
vertical-align:middle;margin-right:6px; |
|
} |
|
`; |
|
document.head.appendChild(style); |
|
|
|
const panel = document.createElement('div'); panel.id = 'lfm-panel'; |
|
|
|
const hdr = document.createElement('div'); hdr.id = 'lfm-header'; |
|
const ht = document.createElement('span'); ht.className = 'lfm-h-title'; ht.textContent = 'LastFM Duplicate Remover'; |
|
const hh = document.createElement('span'); hh.className = 'lfm-h-hint'; hh.textContent = '\u25BC collapse'; |
|
hdr.append(ht, hh); |
|
let collapsed = localStorage.getItem('lfmCollapsed') === 'true'; |
|
hdr.addEventListener('click', () => { |
|
collapsed = !collapsed; |
|
body.style.display = collapsed ? 'none' : ''; |
|
hh.textContent = collapsed ? '\u25B6 expand' : '\u25BC collapse'; |
|
localStorage.setItem('lfmCollapsed', collapsed); |
|
}); |
|
panel.appendChild(hdr); |
|
|
|
const body = document.createElement('div'); body.id = 'lfm-body'; |
|
|
|
const lblPage = document.createElement('div'); lblPage.className = 'lfm-lbl'; |
|
lblPage.id = 'lfm-stop-page-lbl'; |
|
lblPage.textContent = 'Stop at which page? (current: ' + getCurrentPage() + ')'; |
|
const pageInput = document.createElement('input'); |
|
pageInput.id = 'lfm-stop-page'; pageInput.className = 'lfm-input'; |
|
pageInput.type = 'text'; pageInput.value = stopAtPage; pageInput.placeholder = '0'; |
|
|
|
const checkWrap = document.createElement('label'); checkWrap.className = 'lfm-check'; |
|
const check = document.createElement('input'); check.type = 'checkbox'; |
|
check.id = 'lfm-real-dup'; check.checked = rmOnlyRealDup; |
|
const checkTxt = document.createElement('span'); checkTxt.textContent = 'Only compare real duplicates'; |
|
checkWrap.append(check, checkTxt); |
|
|
|
const lblTracks = document.createElement('div'); lblTracks.className = 'lfm-lbl'; |
|
lblTracks.textContent = 'Tracks to compare (2\u201350):'; |
|
const tracksInput = document.createElement('input'); |
|
tracksInput.id = 'lfm-num-tracks'; tracksInput.className = 'lfm-input'; |
|
tracksInput.type = 'text'; tracksInput.value = numTracks; tracksInput.placeholder = '5'; |
|
|
|
// The num-tracks field is only relevant when "real duplicates" is off. |
|
function syncTracksVisibility() { |
|
const show = !check.checked; |
|
lblTracks.style.display = show ? '' : 'none'; |
|
tracksInput.style.display = show ? '' : 'none'; |
|
} |
|
check.addEventListener('change', function () { |
|
rmOnlyRealDup = check.checked; |
|
localStorage.setItem('rmOnlyRealDup', check.checked); |
|
syncTracksVisibility(); |
|
}); |
|
|
|
const row = document.createElement('div'); row.className = 'lfm-row'; |
|
const startBtn = document.createElement('button'); |
|
startBtn.className = 'lfm-btn lfm-btn-primary'; startBtn.textContent = '\u25B6 START'; |
|
startBtn.onclick = startScript; |
|
const stopBtn = document.createElement('button'); |
|
stopBtn.className = 'lfm-btn lfm-btn-secondary'; stopBtn.textContent = '\u25A0 STOP'; |
|
stopBtn.onclick = stopScript; |
|
row.append(startBtn, stopBtn); |
|
|
|
const statusEl = document.createElement('div'); statusEl.id = 'lfm-status'; |
|
const lblLog = document.createElement('div'); lblLog.className = 'lfm-lbl'; lblLog.textContent = 'Log (newest first):'; |
|
const logEl = document.createElement('div'); logEl.id = 'lfm-log'; |
|
|
|
body.append(lblPage, pageInput, checkWrap, lblTracks, tracksInput, row, statusEl, lblLog, logEl); |
|
panel.appendChild(body); |
|
document.body.appendChild(panel); |
|
|
|
if (collapsed) { body.style.display = 'none'; hh.textContent = '\u25B6 expand'; } |
|
syncTracksVisibility(); |
|
|
|
// Lock inputs while a run is in progress. |
|
if (runScript) { |
|
startBtn.disabled = true; startBtn.style.opacity = '.4'; startBtn.style.cursor = 'default'; |
|
pageInput.disabled = true; tracksInput.disabled = true; check.disabled = true; |
|
} |
|
|
|
renderLog(); |
|
|
|
// Status line: running spinner, last completion message, or idle. |
|
const done = localStorage.getItem('lfmDone'); |
|
if (runScript) { |
|
setStatus('Running\u2026 ' + (parseInt(localStorage.getItem('totalDeleted')) || 0) + ' deleted so far.', true); |
|
} else if (done) { |
|
setStatus(done, false); |
|
} else { |
|
setStatus('Idle', false); |
|
} |
|
} |
|
|
|
// ---- Deletion + navigation engine ------------------------------------- |
|
if (shouldMatchPage()) { |
|
window.addEventListener('load', function () { |
|
if (!runScript) return; |
|
|
|
let found = 0; |
|
const initialRefreshTimeout = 5000; |
|
let refreshTimeout = parseInt(localStorage.getItem('refreshTimeout')) || initialRefreshTimeout; |
|
const sections = Array.from(document.getElementsByTagName("tbody")); |
|
const savedUrl = localStorage.getItem('savedUrl') || window.location.href; |
|
|
|
// Page number for this load. If the live URL has no page param (e.g. a |
|
// transient bounce), fall back to savedUrl so the log/stop check don't |
|
// spuriously report "page 1". |
|
let pageNow = extractQueryParam('page', window.location.href); |
|
if (pageNow == null) pageNow = extractQueryParam('page', savedUrl); |
|
if (pageNow == null) pageNow = 1; |
|
pageNow = parseInt(pageNow); |
|
|
|
// A "delete" URL is the 405 (Method Not Allowed) page after a delete |
|
// click. Bounce back to the last good page. The return is required so we |
|
// don't fall through into deletion on a page that's mid-navigation. |
|
if (window.location.toString().includes("delete")) { |
|
log('\u26A0 Hit 405 page, returning to last good page.', 'warn'); |
|
window.location.href = savedUrl; |
|
return; |
|
} |
|
|
|
// No track list means the rate-limit page ("requesting too many pages"). |
|
// Detecting via the .chartlist table rather than page text keeps this |
|
// language-independent. Wait the current backoff, retry, and escalate so |
|
// repeated rate-limits wait progressively longer. |
|
if (!document.querySelector('.chartlist')) { |
|
log('\u26A0 Rate-limited. Waiting ' + (refreshTimeout / 1000) + 's then retrying.', 'warn'); |
|
setTimeout(function() { |
|
window.location.href = savedUrl; |
|
}, refreshTimeout); |
|
localStorage.setItem('refreshTimeout', refreshTimeout + 5000); |
|
return; |
|
} else { |
|
refreshTimeout = initialRefreshTimeout; |
|
localStorage.setItem('refreshTimeout', initialRefreshTimeout); |
|
localStorage.setItem('savedUrl', window.location.href); |
|
} |
|
|
|
sections.forEach(function (section) { |
|
const els = Array.from(section.rows); |
|
const names = els.map(function (el) { |
|
const nmEl = el.querySelector('.chartlist-name'); |
|
const artEl = el.querySelector('.chartlist-artist'); |
|
if (rmOnlyRealDup) { |
|
const tstEl = el.querySelector('.chartlist-timestamp'); |
|
return nmEl && artEl && tstEl && nmEl.textContent.replace(/\s+/g, ' ').trim() + ':' + artEl.textContent.replace(/\s+/g, ' ').trim() + ':' + tstEl.textContent.replace(/\s+/g, ' ').trim(); |
|
} else { |
|
return nmEl && artEl && nmEl.textContent.replace(/\s+/g, ' ').trim() + ':' + artEl.textContent.replace(/\s+/g, ' ').trim(); |
|
} |
|
}); |
|
|
|
names.forEach(function (name, i) { |
|
if (!name) return; |
|
// Real-duplicate mode: duplicates share an identical timestamp but |
|
// can be far apart or span page boundaries, so compare against the |
|
// whole remaining list. "n tracks" mode: limited look-ahead window. |
|
const rest = rmOnlyRealDup |
|
? names.slice(i + 1) |
|
: names.slice(i + 1, i + 1 + parseInt(numTracks)); |
|
if (!rest.includes(name)) return; |
|
const delBtn = els[i].querySelector('[data-ajax-form-sets-state="deleted"]'); |
|
if (delBtn) { delBtn.click(); found++; } |
|
}); |
|
}); |
|
|
|
if (found > 0) { |
|
const totalDeleted = (parseInt(localStorage.getItem('totalDeleted')) || 0) + found; |
|
localStorage.setItem('totalDeleted', totalDeleted); |
|
log('\u2713 Page ' + pageNow + ': deleted ' + found + ' (total ' + totalDeleted + ').', 'ok'); |
|
setTimeout(function() { |
|
location.reload(); |
|
}, refreshTimeout); |
|
return; |
|
} |
|
|
|
if (pageNow <= stopAtPage) { |
|
const totalDeleted = parseInt(localStorage.getItem('totalDeleted')) || 0; |
|
const msg = 'Complete. ' + totalDeleted + ' duplicate scrobble' + (totalDeleted === 1 ? '' : 's') + ' deleted.'; |
|
localStorage.setItem('runScript', 'false'); |
|
localStorage.removeItem('savedUrl'); |
|
localStorage.removeItem('refreshTimeout'); |
|
localStorage.removeItem('totalDeleted'); |
|
localStorage.setItem('lfmDone', msg); |
|
log('\u25A0 ' + msg, 'life'); |
|
location.reload(); |
|
return; |
|
} |
|
|
|
// Otherwise go up one page. |
|
window.location.href = window.location.pathname + replaceQueryParam('page', extractQueryParam('page', window.location.href) - 1, window.location.search); |
|
}); |
|
} |
|
})(); |
I leave mine on for a bit and I have years and years of scrobbles to delete and I come back and it didn't actually delete anything, its moving from page to page without doing anything