// ==UserScript== // @name Wavez Tools // @namespace https://wavez.fm/ // @author fluteds // @icon https://wavez.fm/favicon.ico // @version 2026.11.01 // @updateURL https://raw.githubusercontent.com/fluteds/wavez/main/userscripts/wavez-all.user.js // @downloadURL https://raw.githubusercontent.com/fluteds/wavez/main/userscripts/wavez-all.user.js // @description Every Wavez userscript in one install, switched on and off from the Wavez Tools panel (Alt+T) or the userscript manager menu. // @match https://wavez.fm/* // @grant GM_registerMenuCommand // @grant GM_notification // @grant GM_xmlhttpRequest // @grant unsafeWindow // @connect clients5.google.com // @connect localhost // @connect niceatc.api.br // @connect woot.niceatc.api.br // @run-at document-start // ==/UserScript== // GENERATED by sync-scripts.sh. Edit the individual scripts, not this file. (function () { 'use strict'; // Taking a @grant sandboxes us, and the page-context scripts below reach for // page globals (window.WavezFM). Hand them the real window so they still work. var PAGE = typeof unsafeWindow !== "undefined" ? unsafeWindow : window; var KEY = "wavez-tools:"; function on(id, dflt) { return (localStorage.getItem(KEY + id) || dflt) === "on"; } // A saved panel value wins over the constant the script ships with. function setting(id, name, dflt) { try { var v = localStorage.getItem(KEY + id + ":" + name); return v === null ? dflt : JSON.parse(v); } catch (e) { return dflt; } } // Each addon is a row in the panel (wavez-panel reads ADDONS) and a menu entry as the fallback. var ADDONS = []; function menu(id, label, dflt, cat, settings) { var isOn = on(id, dflt); var list = settings.map(function (s) { return { name: s[0], label: s[1], dflt: s[2], opts: s[3] ? s[3].split(",") : null, value: setting(id, s[0], s[2]) }; }); var entry = { label: label, cat: cat, on: isOn, flip: function () { entry.on = !entry.on; localStorage.setItem(KEY + id, entry.on ? "on" : "off"); }, settings: list, save: function (name, v) { localStorage.setItem(KEY + id + ":" + name, JSON.stringify(v)); } }; ADDONS.push(entry); // The panel shows a reload reminder; the menu has no UI, so it reloads to show the change. if (typeof GM_registerMenuCommand === "function") GM_registerMenuCommand((isOn ? "✓ " : "✕ ") + label, function () { entry.flip(); location.reload(); }); return isOn; } // We start at document-start for Imgur; scripts written for document-idle wait for the DOM. function ready(fn) { if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", function () { fn(PAGE); }, { once: true }); else fn(PAGE); } if (menu('translate', 'Translate', 'off', 'Chat', [["TARGET_LANG", "Language", "en", ""], ["DISPLAY_MODE", "How it shows", "append", "append,replace,hover"], ["ONLY_NON_TARGET", "Skip my language", true, ""], ["MAX_INFLIGHT", "Request limit", 4, ""], ["ENGINE", "Engine", "google", "google,ollama"]])) ready(function (window) { var TARGET_LANG = setting("translate", "TARGET_LANG", "en"); var DISPLAY_MODE = setting("translate", "DISPLAY_MODE", "append"); var ONLY_NON_TARGET = setting("translate", "ONLY_NON_TARGET", true); var ENGINE = setting("translate", "ENGINE", "google"); var MAX_INFLIGHT = setting("translate", "MAX_INFLIGHT", 4); (function () { "use strict"; var MSG_SELECTOR = '[class*="wavezfm-chat-text-size"], .wavezfm-centered-icon + div > p'; var config = { target: TARGET_LANG, mode: DISPLAY_MODE, onlyNonTarget: ONLY_NON_TARGET, enabled: true, }; var style = document.createElement("style"); style.textContent = ".wz-translation{display:block;margin-top:2px;opacity:.6;font-style:italic;" + "font-size:var(--wavezfm-chat-text-size,13px);line-height:var(--wavezfm-chat-line-height,1.25rem)}" + ".wz-translation::before{content:'\\1F310\\00A0';opacity:.7}" + ".wz-replaced::before{content:'\\1F310\\00A0';opacity:.5;font-size:.85em}" + ".wz-hover{cursor:pointer;transition:opacity .15s ease,transform .15s ease}" + ".wz-hover.wz-swap{opacity:0;transform:translateY(3px)}"; (document.head || document.documentElement).appendChild(style); function httpGet(url) { return new Promise(function (resolve, reject) { if (typeof GM_xmlhttpRequest === "function") { GM_xmlhttpRequest({ method: "GET", url: url, onload: function (r) { resolve(r.responseText); }, onerror: reject, ontimeout: reject, }); return; } if (typeof GM !== "undefined" && GM.xmlHttpRequest) { GM.xmlHttpRequest({ method: "GET", url: url, onload: function (r) { resolve(r.responseText); }, onerror: reject, ontimeout: reject, }); return; } fetch(url) .then(function (r) { return r.text(); }) .then(resolve, reject); }); } var inflight = 0; var queue = []; function pump() { while (inflight < MAX_INFLIGHT && queue.length) { var job = queue.shift(); inflight++; job().then(release, release); } } function release() { inflight--; pump(); } function enqueue(fn) { return new Promise(function (resolve, reject) { queue.push(function () { return fn().then(resolve, reject); }); pump(); }); } var cache = Object.create(null); function aiSetting(name, dflt) { try { var v = localStorage.getItem("wavez-tools:ai:" + name); return v === null ? dflt : JSON.parse(v); } catch (e) { return dflt; } } function ollamaTranslate(text) { return new Promise(function (resolve, reject) { GM_xmlhttpRequest({ method: "POST", url: aiSetting("OLLAMA_URL", "http://localhost:11434").replace(/\/+$/, "") + "/api/chat", headers: { "content-type": "application/json" }, data: JSON.stringify({ model: aiSetting("MODEL", "qwen3.5:4b"), stream: false, think: false, format: "json", messages: [{ role: "system", content: 'Translate the chat message into the language with ISO code "' + config.target + '". Keep slang, names, emotes and links as they are. Reply as JSON {"lang": "", "text": ""}.' }, { role: "user", content: text }] }), timeout: 60000, onload: function (r) { try { var d = JSON.parse(JSON.parse(r.responseText).message.content); resolve({ text: String(d.text || ""), src: String(d.lang || "") }); } catch (e) { reject(new Error("Ollama " + r.status + " " + r.responseText.slice(0, 200))); } }, onerror: reject, ontimeout: reject, }); }); } function translate(text) { if (cache[text]) return Promise.resolve(cache[text]); return enqueue(function () { if (ENGINE === "ollama") return ollamaTranslate(text).then(function (result) { cache[text] = result; return result; }); var url = "https://clients5.google.com/translate_a/t?client=dict-chrome-ex&sl=auto&tl=" + encodeURIComponent(config.target) + "&q=" + encodeURIComponent(text); return httpGet(url).then(function (raw) { var data = JSON.parse(raw); var seg = data[0] || []; var result = { text: seg[0] || "", src: seg[1] || "" }; cache[text] = result; return result; }); }); } function clearTranslation(el) { if (el._wzNode && el._wzNode.parentNode) { el._wzNode.parentNode.removeChild(el._wzNode); } el._wzNode = null; if (el._wzOriginal != null) { el.textContent = el._wzOriginal; el._wzOriginal = null; } if (el._wzHover) { if (el._wzHover.shown) el.innerHTML = el._wzHover.html; el._wzHover = null; } el.classList.remove("wz-hover", "wz-swap", "wz-replaced"); el.removeAttribute("title"); } function swapHover(el, toTranslated) { var h = el._wzHover; if (!h || h.shown === toTranslated) return; h.shown = toTranslated; el._wzBusy = true; el.classList.add("wz-swap"); window.setTimeout(function () { if (!el._wzHover) { el.classList.remove("wz-swap"); el._wzBusy = false; return; } if (toTranslated) el.textContent = h.translated; else el.innerHTML = h.html; el.classList.remove("wz-swap"); window.setTimeout(function () { el._wzBusy = false; }, 0); }, 150); } function setupHover(el, translated) { el._wzHover = { html: el.innerHTML, translated: translated, shown: false }; el.classList.add("wz-hover"); if (!el._wzHoverBound) { el._wzHoverBound = true; el.addEventListener("mouseenter", function () { swapHover(el, true); }); el.addEventListener("mouseleave", function () { swapHover(el, false); }); } } function render(el, original, translated) { clearTranslation(el); if (config.mode === "replace") { el._wzOriginal = original; el.textContent = translated; el.classList.add("wz-replaced"); el.title = original; return; } if (config.mode === "hover") { setupHover(el, translated); return; } var node = document.createElement("span"); node.className = "wz-translation"; node.textContent = translated; el._wzNode = node; el.parentNode.insertBefore(node, el.nextSibling); } var LETTERS = /\p{L}{2,}/u; function process(el) { if (!config.enabled || el._wzBusy) return; var original = (el.textContent || "").trim(); if (!original || !LETTERS.test(original)) return; if (original === el._wzSrc || original === el._wzTranslated) return; el._wzSrc = original; translate(original) .then(function (res) { if ((el.textContent || "").trim() !== original) return; el._wzTranslated = res.text.trim(); var sameLang = res.src && res.src.toLowerCase().split("-")[0] === config.target.toLowerCase(); var unchanged = res.text.trim().toLowerCase() === original.toLowerCase(); if (config.onlyNonTarget && (sameLang || unchanged)) { clearTranslation(el); return; } if (unchanged) { clearTranslation(el); return; } render(el, original, res.text); }) .catch(function (err) { if (!process._warned) { process._warned = true; console.warn("%c[wz-translate]", "color:#30C7FB;font-weight:bold", "translation request failed - the endpoint is likely blocking (bot check / CORS / rate-limit), not the selector:", err); } if (el._wzSrc === original) el._wzSrc = null; }); } function scan(root) { if (!root || root.nodeType !== 1) return; if (root.matches && root.matches(MSG_SELECTOR)) process(root); var nodes = root.querySelectorAll ? root.querySelectorAll(MSG_SELECTOR) : []; for (var i = 0; i < nodes.length; i++) process(nodes[i]); } var observer = new MutationObserver(function (mutations) { for (var i = 0; i < mutations.length; i++) { var m = mutations[i]; for (var j = 0; j < m.addedNodes.length; j++) scan(m.addedNodes[j]); if (m.type === "characterData" && m.target.parentNode) { var p = m.target.parentNode; if (p.matches && p.matches(MSG_SELECTOR)) process(p); } } }); function observeChat() { observer.observe(document.body, { childList: true, subtree: true, characterData: true, }); scan(document.body); } if (document.body) observeChat(); else document.addEventListener("DOMContentLoaded", observeChat, { once: true }); function retranslateAll() { var nodes = document.querySelectorAll(MSG_SELECTOR); for (var i = 0; i < nodes.length; i++) { nodes[i]._wzSrc = null; process(nodes[i]); } } var pageWindow = typeof unsafeWindow !== "undefined" ? unsafeWindow : window; pageWindow.WZTranslate = { config: config, setMode: function (mode) { config.mode = mode; var nodes = document.querySelectorAll(MSG_SELECTOR); for (var i = 0; i < nodes.length; i++) { nodes[i]._wzSrc = null; clearTranslation(nodes[i]); process(nodes[i]); } }, setTarget: function (lang) { config.target = lang; cache = Object.create(null); retranslateAll(); }, enable: function () { config.enabled = true; retranslateAll(); }, disable: function () { config.enabled = false; var nodes = document.querySelectorAll(MSG_SELECTOR); for (var i = 0; i < nodes.length; i++) clearTranslation(nodes[i]); }, retranslateAll: retranslateAll, }; console.log( "%c[wz-translate] active → " + config.target + " (mode: " + config.mode + "). Controls: WZTranslate.setMode('append'|'replace'|'hover')", "color:#30C7FB;font-weight:bold", ); })(); }); if (menu('spotify', 'Open in Spotify', 'off', 'Music', [])) ready(function (window) { (function () { 'use strict'; const log = (...a) => console.log('%c[wz-spotify]', 'color:#1DB954;font-weight:bold', ...a); const ID = 'wavez-open-spotify-btn'; const stripNoise = (s) => (s || '') .replace(/[([][^)\]]*\b(officials?|video|audio|lyrics?|visuali[sz]er|m\/?v|hd|4k|remaster(?:ed)?|explicit)\b[^)\]]*[)\]]/gi, '') .replace(/\s{2,}/g, ' ') .trim(); function spotifyUrl(titleEl) { const pb = window.WavezFM?.version === '1' ? window.WavezFM.room.getState()?.playback : null; const query = stripNoise(pb?.title || titleEl.textContent); return 'https://open.spotify.com/search/' + encodeURIComponent(query); } function addButton() { const title = document.querySelector('#wavezfm-current-track-title-desktop'); const yt = document.querySelector('a[aria-label="Open on YouTube"]'); if (!title || !yt || document.getElementById(ID)) return; const row = title.closest('.flex'); if (!row) return; const wrap = document.createElement('div'); wrap.className = 'inline-flex shrink-0'; wrap.id = ID; const link = yt.cloneNode(false); link.href = '#'; link.setAttribute('aria-label', 'Open on Spotify'); link.title = 'Open on Spotify'; link.style.color = '#ffffff'; link.style.display = 'inline-flex'; link.style.visibility = 'visible'; link.style.opacity = '1'; link.innerHTML = ` `; link.onclick = (e) => { e.preventDefault(); e.stopPropagation(); window.open(spotifyUrl(title), '_blank'); }; wrap.appendChild(link); const titleBox = title.parentElement; row.insertBefore(wrap, titleBox); } setInterval(addButton, 500); if (location.hash === '#wz-spotify-test') { const cases = [ ['Groove Is In The Heart (Official Video)', 'Groove Is In The Heart'], ['Song [Official Audio]', 'Song'], ['Track (Official Music Video) [HD]', 'Track'], ['Title (Lyrics)', 'Title'], ['Da Funk (Remastered)', 'Da Funk'], ['Power (feat. Dwele)', 'Power (feat. Dwele)'], ]; cases.forEach(([raw, want]) => console.assert(stripNoise(raw) === want, 'stripNoise:', raw, '->', stripNoise(raw), 'want', want)); log('self-check passed'); } })(); }); if (menu('chat-toggle', 'Chat Toggle', 'off', 'Chat', [])) ready(function (window) { (function () { 'use strict'; const KEY = 'wavez-chat-hidden'; const css = document.createElement('style'); css.textContent = ` #wavez-chat-rail-toggle { position: fixed; top: 50%; transform: translateY(-50%); width: 20px; height: 58px; padding: 0; border: 1px solid var(--theme-border); border-right: 0; border-radius: 8px 0 0 8px; background: var(--theme-room-nav); color: color-mix(in srgb, var(--theme-text-primary) 56%, transparent); box-shadow: -8px 0 18px rgba(0,0,0,.22); z-index: 2147483647; cursor: pointer; display: flex; align-items: center; justify-content: center; opacity: .82; transition: opacity .2s ease, color .2s ease, background .2s ease; } #wavez-chat-rail-toggle:hover { opacity: 1; color: white; background: var(--theme-button-neutral-hover); } #wavez-chat-rail-toggle svg { width: 11px; height: 11px; flex-shrink: 0; transition: transform .2s ease; } #wavez-chat-rail-toggle:hover svg { transform: scale(1.12); } #wavez-chat-rail-toggle.chat-hidden svg { transform: rotate(180deg); } #wavez-chat-rail-toggle.chat-hidden:hover svg { transform: rotate(180deg) scale(1.12); } #wavez-chat-rail-toggle.has-new::after { content: ''; position: absolute; top: 6px; right: 6px; width: 7px; height: 7px; border-radius: 50%; background: var(--theme-accent, #f43f5e); box-shadow: 0 0 0 2px var(--theme-room-nav); } `; (document.head || document.documentElement).appendChild(css); function getRail() { return document.querySelector('[data-room-desktop-rail="true"]'); } function makeButton() { const btn = document.createElement('button'); btn.id = 'wavez-chat-rail-toggle'; btn.type = 'button'; btn.setAttribute('aria-label', 'Toggle chat'); btn.innerHTML = ` `; document.body.appendChild(btn); return btn; } function init() { const rail = getRail(); if (!rail || document.getElementById('wavez-chat-rail-toggle')) { return false; } const btn = makeButton(); function apply() { const hidden = localStorage.getItem(KEY) === 'true'; rail.style.display = hidden ? 'none' : ''; btn.classList.toggle('chat-hidden', hidden); if (!hidden) btn.classList.remove('has-new'); if (hidden) { btn.style.right = '0px'; } else { const rect = rail.getBoundingClientRect(); btn.style.right = `${window.innerWidth - rect.left - 1}px`; } } btn.addEventListener('click', () => { const hidden = localStorage.getItem(KEY) === 'true'; localStorage.setItem(KEY, String(!hidden)); apply(); }); window.addEventListener('resize', apply); const markUnread = () => { if (localStorage.getItem(KEY) === 'true') btn.classList.add('has-new'); }; const api = window.WavezFM; if (api && api.version === '1') { api.room.subscribe('chat_message', markUnread); } else { new MutationObserver((records) => { if (records.some((r) => r.addedNodes.length)) markUnread(); }).observe(rail, { childList: true, subtree: true }); } apply(); return true; } const wait = setInterval(() => { if (init()) { clearInterval(wait); } }, 500); })(); }); if (menu('imgur', 'Imgur Fix', 'off', 'Chat', [["ALTSITE", "Proxy", 'https://imgur.artemislena.eu', "https://imgur.artemislena.eu,https://rimgo.4o1x5.dev,https://rimgo.manerakai.com,https://ri.nadeko.net,https://rimgo.ducks.party"]])) (function (window) { (function () { 'use strict'; const ALTSITE = setting("imgur", "ALTSITE", 'https://imgur.artemislena.eu'); function rewrite(value) { if (!value || !value.includes('imgur.com')) return value; return value.replace( /https?:\/\/(?:i\.|m\.|www\.)?imgur\.com/gi, ALTSITE ); } function patchImageSrc() { const proto = HTMLImageElement.prototype; for (const prop of ['src', 'srcset']) { const desc = Object.getOwnPropertyDescriptor(proto, prop); if (!desc || !desc.set) continue; Object.defineProperty(proto, prop, { configurable: true, enumerable: desc.enumerable, get() { return desc.get.call(this); }, set(v) { desc.set.call(this, rewrite(v)); } }); } const setAttr = proto.setAttribute; proto.setAttribute = function (name, value) { if (name === 'src' || name === 'srcset') value = rewrite(value); return setAttr.call(this, name, value); }; } try { patchImageSrc(); } catch (e) {} function fixElement(el) { if (!el || el.nodeType !== 1) return; for (const attr of ['href', 'src', 'srcset', 'data-src', 'poster', 'style']) { const oldValue = el.getAttribute(attr); if (!oldValue || !oldValue.includes('imgur.com')) continue; const newValue = rewrite(oldValue); if (newValue !== oldValue) { el.setAttribute(attr, newValue); } } } function fixStyleEl(el) { if (!el || el.tagName !== 'STYLE') return; const css = el.textContent; if (!css || !css.includes('imgur.com')) return; const next = rewrite(css); if (next !== css) el.textContent = next; } function fixRules(parent) { let rules; try { rules = parent.cssRules; } catch (e) { return; } if (!rules) return; for (let i = 0; i < rules.length; i++) { const rule = rules[i]; if (rule.cssRules && rule.cssRules.length) { fixRules(rule); continue; } const text = rule.cssText; if (!text || !text.includes('imgur.com')) continue; const next = rewrite(text); if (next === text) continue; try { parent.deleteRule(i); parent.insertRule(next, i); } catch (e) { } } } function fixSheets(root) { let sheets = []; try { if (root.styleSheets) sheets = sheets.concat(Array.from(root.styleSheets)); } catch (e) {} try { if (root.adoptedStyleSheets) sheets = sheets.concat(Array.from(root.adoptedStyleSheets)); } catch (e) {} sheets.forEach(fixRules); } function scanStyles(root) { root = root || document; root.querySelectorAll?.('style').forEach(fixStyleEl); fixSheets(root); } const REMOTE_CSS_HOST = 'niceatc'; const remoteCss = new Map(); function gmFetch() { if (typeof GM_xmlhttpRequest !== 'undefined') return GM_xmlhttpRequest; if (typeof GM !== 'undefined' && GM.xmlHttpRequest) return GM.xmlHttpRequest; return null; } function importRemoteCss(link) { const href = link.href; if (!href) return; let url; try { url = new URL(href, location.href); } catch (e) { return; } if (url.origin === location.origin) return; if (!url.hostname.includes(REMOTE_CSS_HOST)) return; const state = remoteCss.get(href); if (state === 'done') { link.disabled = true; return; } if (state) return; const fetcher = gmFetch(); if (!fetcher) return; remoteCss.set(href, 'pending'); fetcher({ method: 'GET', url: href, onload(res) { const css = res.responseText || ''; if (!css.includes('imgur.com')) { remoteCss.set(href, 'clean'); return; } const style = document.createElement('style'); style.setAttribute('data-rimgo-import', href); style.textContent = rewrite(css); (document.head || document.documentElement).appendChild(style); link.disabled = true; remoteCss.set(href, 'done'); }, onerror() { remoteCss.set(href, 'failed'); } }); } function scanRemoteCss() { document.querySelectorAll('link[rel~="stylesheet"]').forEach(importRemoteCss); } function scan(root) { if (!root) return; if (root.nodeType === 1) { fixElement(root); fixStyleEl(root); } root.querySelectorAll?.('[href*="imgur.com"], [src*="imgur.com"], [srcset*="imgur.com"], [data-src*="imgur.com"], [poster*="imgur.com"], [style*="imgur.com"]') .forEach(fixElement); root.querySelectorAll?.('style').forEach(fixStyleEl); root.querySelectorAll?.('*').forEach(el => { if (el.shadowRoot) { scan(el.shadowRoot); scanStyles(el.shadowRoot); } }); } function fullScan() { scan(document.body); scanStyles(); scanRemoteCss(); } function start() { const observer = new MutationObserver(mutations => { for (const mutation of mutations) { if (mutation.type === 'childList') { mutation.addedNodes.forEach(scan); } if (mutation.type === 'attributes') { fixElement(mutation.target); } } }); observer.observe(document.documentElement, { childList: true, subtree: true, attributes: true, attributeFilter: ['href', 'src', 'srcset', 'data-src', 'poster', 'style'] }); fullScan(); if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', fullScan); setInterval(fullScan, 1500); } start(); })(); })(PAGE); if (menu('scrobble', 'Scrobble Toggle', 'off', 'Music', [])) (function (window) { (function () { var API = "https://api.wavez.fm/settings"; var state = null; var busy = false; var btn = null; function read(body) { if (body && typeof body.lastFmScrobblingEnabled === "boolean") state = body.lastFmScrobblingEnabled; return state; } function getState() { return fetch(API, { credentials: "include" }).then(function (r) { return r.json(); }).then(read); } function setState(v) { return fetch(API, { method: "PATCH", credentials: "include", headers: { "content-type": "application/json" }, body: JSON.stringify({ lastFmScrobblingEnabled: v }), }).then(function (r) { if (!r.ok) throw new Error("PATCH " + r.status); return r.json(); }).then(read); } function toggle() { if (busy) return; busy = true; render(); var ready = state === null ? getState() : Promise.resolve(state); ready .then(function (cur) { return setState(!cur); }) .catch(function () { state = null; }) .then(function () { busy = false; render(); }); } function render() { if (!btn || !btn.isConnected) return; var on = state === true, off = state === false; var label = busy ? "Scrobbling…" : "Last.fm scrobbling: " + (on ? "on" : off ? "off" : "unknown"); btn.title = label; btn.setAttribute("aria-label", label); btn.style.opacity = busy ? "0.6" : "1"; if (on) { btn.style.borderColor = "rgba(52,211,153,.26)"; btn.style.background = "rgba(16,185,129,.10)"; btn.style.color = "#d1fae5"; } else if (off) { btn.style.borderColor = "rgba(248,113,113,.26)"; btn.style.background = "rgba(239,68,68,.10)"; btn.style.color = "#fee2e2"; } else { btn.style.borderColor = ""; btn.style.background = ""; btn.style.color = "rgba(255,255,255,.4)"; } } function build() { var wrap = document.createElement("div"); wrap.className = "inline-flex"; wrap.innerHTML = '"; btn = wrap.firstChild; btn.addEventListener("click", toggle); return wrap; } function footerWrap() { var btns = document.querySelectorAll('[data-wavezfm-room-footer-action]'); for (var i = btns.length - 1; i >= 0; i--) { if (btns[i].offsetParent === null) continue; var w = btns[i].closest("div.inline-flex"); if (w && w.parentElement) return w; } return null; } function ensure() { if (document.getElementById("wz-scrobble-btn")) return; var anchor = footerWrap(); if (!anchor) return; anchor.after(build()); render(); if (state === null) getState().then(render).catch(function () {}); } new MutationObserver(ensure).observe(document.documentElement, { childList: true, subtree: true }); ensure(); if (typeof GM_registerMenuCommand === "function") GM_registerMenuCommand("Toggle Last.fm scrobbling", toggle); })(); })(PAGE); if (menu('auto-grab', 'Auto Grab', 'off', 'Automation', [["PLAYLIST", "Playlist", 'Recs', ""]])) ready(function (window) { (function () { 'use strict'; var PLAYLIST = setting("auto-grab", "PLAYLIST", 'Recs'); var GRAB_BTN_SELECTOR = ''; var PICKER_SELECTOR = ''; var LS_KEY = 'wavez-autograb'; var enabled = localStorage.getItem(LS_KEY) === 'on'; var lastKey = null; var log = function () { console.log.apply(console, ["%c[wz-grab]", "color:#FFCA28;font-weight:bold"].concat([].slice.call(arguments))); }; var warn = function () { console.warn.apply(console, ["%c[wz-grab]", "color:#FFCA28;font-weight:bold"].concat([].slice.call(arguments))); }; function shouldGrab(key, last, votes) { return !!key && key !== last && !!votes && votes.clientVote === 'woot' && !votes.clientGrabbed; } function visible(el) { return el.offsetParent !== null; } function findGrabButton() { if (GRAB_BTN_SELECTOR) return document.querySelector(GRAB_BTN_SELECTOR); var btns = document.querySelectorAll('button'); var byLabel = null; for (var i = 0; i < btns.length; i++) { if (btns[i].querySelector('[style*="theme-vote-grab"]')) return btns[i]; if (byLabel) continue; var spans = btns[i].querySelectorAll('span'); for (var j = 0; j < spans.length; j++) { if (spans[j].textContent.trim().toLowerCase() === 'grab') { byLabel = btns[i]; break; } } } return byLabel; } function findPicker() { if (PICKER_SELECTOR) return document.querySelector(PICKER_SELECTOR); var btn = findGrabButton(); var roots = document.querySelectorAll('[data-wavezfm-grab-menu-root]'); for (var i = 0; i < roots.length; i++) { if (btn && roots[i].contains(btn)) continue; if (visible(roots[i])) return roots[i]; } return null; } function nameOf(el) { var span = el.querySelector('span.truncate'); return (span ? span.textContent : el.textContent).trim(); } function detailOf(el) { var spans = el.querySelectorAll('span.truncate'); return spans.length > 1 ? spans[1].textContent.trim() : ''; } function optionsIn(picker) { var items = picker.querySelectorAll('button'); var out = []; for (var i = 0; i < items.length; i++) { if (items[i].getAttribute('aria-label') === 'Cancel') continue; if (visible(items[i])) out.push(items[i]); } return out; } function closePicker(picker) { var cancel = picker.querySelector('[aria-label="Cancel"]'); if (cancel) cancel.click(); } function withPicker(cb) { var open = findPicker(); if (open) return cb(optionsIn(open), null); var btn = findGrabButton(); if (!btn) { log('grab button not found - are you in a room?'); return cb([], null); } btn.click(); waitFor(findPicker, 2000, function (picker) { if (!picker) { log('picker did not open'); return cb([], null); } cb(optionsIn(picker), picker); }); } function waitFor(fn, ms, cb) { var waited = 0; var t = setInterval(function () { var v = fn(); if (v) { clearInterval(t); cb(v); } else if ((waited += 100) >= ms) { clearInterval(t); cb(null); } }, 100); } function choosePlaylist(picker) { var options = optionsIn(picker).filter(function (el) { return !el.disabled; }); if (!options.length) { log('picker opened but listed no playlists'); return; } var pick = options[0]; if (PLAYLIST) { pick = options.filter(function (el) { return nameOf(el).toLowerCase() === PLAYLIST.toLowerCase(); })[0]; if (!pick) { log('playlist "' + PLAYLIST + '" not in the picker (full or renamed?), skipping'); return; } } pick.click(); log('grabbed into "' + nameOf(pick) + '"'); } function doGrab() { var btn = findGrabButton(); if (!btn) { log('grab button not found - set GRAB_BTN_SELECTOR'); return; } btn.click(); waitFor(findPicker, 2000, function (picker) { if (!picker) { log('no picker appeared, assuming the grab went straight through'); return; } choosePlaylist(picker); }); } function grabCurrent(api) { if (!enabled) return; var state = api.room.getState(); var pb = state && state.playback; if (!pb) return; if (!shouldGrab(pb.playbackKey, lastKey, state.votes)) return; lastKey = pb.playbackKey; doGrab(); } function buildUI(api) { var css = document.createElement('style'); css.textContent = '#wz-grab-pill{position:fixed;right:14px;bottom:14px;z-index:99999;' + 'display:flex;gap:6px;align-items:center;padding:7px 12px;border-radius:999px;' + 'background:rgba(20,20,26,.86);border:1px solid rgba(255,255,255,.12);' + 'font:500 12px/1 system-ui,sans-serif;color:#e7e7ea;cursor:pointer;user-select:none;opacity:.6}' + '#wz-grab-pill.on{opacity:1}' + '#wz-grab-pill input{accent-color:#ff5c8a;margin:0;cursor:pointer}'; document.head.appendChild(css); var pill = document.createElement('label'); pill.id = 'wz-grab-pill'; pill.title = 'Grab a track into "' + (PLAYLIST || 'the first playlist') + '" whenever you woot it'; if (enabled) pill.className = 'on'; var box = document.createElement('input'); box.type = 'checkbox'; box.checked = enabled; box.addEventListener('change', function () { enabled = box.checked; localStorage.setItem(LS_KEY, enabled ? 'on' : 'off'); pill.className = enabled ? 'on' : ''; if (enabled) grabCurrent(api); }); pill.appendChild(box); pill.appendChild(document.createTextNode('auto grab')); document.body.appendChild(pill); } function init(api) { grabCurrent(api); api.room.subscribe('votes_changed', function () { grabCurrent(api); }); buildUI(api); window.WZGrab = { on: function () { enabled = true; localStorage.setItem(LS_KEY, 'on'); grabCurrent(api); }, off: function () { enabled = false; localStorage.setItem(LS_KEY, 'off'); }, now: function () { lastKey = null; doGrab(); }, get enabled() { return enabled; }, playlists: function () { withPicker(function (options, opened) { if (options.length) { console.table(options.map(function (el) { return { playlist: nameOf(el), detail: detailOf(el), full: !!el.disabled, target: nameOf(el).toLowerCase() === PLAYLIST.toLowerCase() }; })); } if (opened) closePicker(opened); }); }, debug: function () { console.log('grab button:', findGrabButton()); console.log('picker (open it first):', findPicker()); } }; log('auto grab ' + (enabled ? 'on' : 'off') + ' - toggle with the corner pill or WZGrab.on()/off()'); } log('loaded, waiting for the WavezFM bridge...'); var tries = 0; var wait = setInterval(function () { var api = window.WavezFM; if (api && api.version === '1') { clearInterval(wait); init(api); } else if (++tries > 40) { clearInterval(wait); warn('WavezFM bridge never appeared, so WZGrab is unavailable. Are you inside a room? window.WavezFM is currently ' + typeof window.WavezFM + '.'); } }, 500); if (location.hash === '#wz-grab-test') { var wooted = { clientVote: 'woot', clientGrabbed: false }; console.assert(shouldGrab('k1', null, wooted) === true, 'wooted, not grabbed'); console.assert(shouldGrab('k1', 'k1', wooted) === false, 'already grabbed this track, skip'); console.assert(shouldGrab('k2', 'k1', { clientVote: null, clientGrabbed: false }) === false, 'not wooted yet, skip'); console.assert(shouldGrab('k2', 'k1', { clientVote: 'meh', clientGrabbed: false }) === false, 'mehed, skip'); console.assert(shouldGrab('k2', 'k1', { clientVote: 'woot', clientGrabbed: true }) === false, 'already in a playlist, skip'); console.assert(shouldGrab(null, 'k1', wooted) === false, 'no playbackKey, skip'); log('tests passed'); } })(); }); if (menu('region-check', 'Region Check', 'off', 'Music', [["YT_API_KEY", "API key", '', ""], ["REGIONS", "Regions", ['US', 'CA'], ""]])) ready(function (window) { (function () { 'use strict'; var REGIONS = setting("region-check", "REGIONS", ['US', 'CA']); var YT_API_KEY = setting("region-check", "YT_API_KEY", ''); var API = 'https://api.wavez.fm'; var KEY_LS = 'wavez-region-ytkey'; var FLAGS_LS = 'wavez-region-flags-v1'; var YT = 'https://www.googleapis.com/youtube/v3/videos'; var lockedTitles = {}; var lastOffenders = []; var log = function () { console.log.apply(console, ["%c[wz-region]", "color:#9CCC65;font-weight:bold"].concat([].slice.call(arguments))); }; var authHeader = null; (function captureAuth() { var of = window.fetch; window.fetch = function (input, init) { try { var url = typeof input === 'string' ? input : (input && input.url) || ''; if (url.indexOf('api.wavez.fm') !== -1) { var h = new Headers((init && init.headers) || (typeof input === 'object' && input.headers) || {}); var a = h.get('authorization'); if (a) authHeader = a; } } catch (e) {} return of.apply(this, arguments); }; })(); function apiKey() { var k = YT_API_KEY || localStorage.getItem(KEY_LS) || ''; if (!k) { k = (window.prompt('YouTube Data API key (stored in localStorage, only used for videos.list):') || '').trim(); if (k) localStorage.setItem(KEY_LS, k); } return k; } function apiGet(path) { var headers = {}; if (authHeader) headers['Authorization'] = authHeader; return fetch(API + path, { credentials: 'include', headers: headers }).then(function (res) { if (!res.ok) throw new Error(path + ' -> ' + res.status); return res.json(); }).then(function (j) { return Array.isArray(j) ? j : (j && j.data) || []; }); } function apiDelete(path) { var headers = {}; if (authHeader) headers['Authorization'] = authHeader; return fetch(API + path, { method: 'DELETE', credentials: 'include', headers: headers }).then(function (res) { if (!res.ok) throw new Error('DELETE ' + path + ' -> ' + res.status); return true; }); } function readJSON(lsKey) { try { return JSON.parse(localStorage.getItem(lsKey)) || null; } catch (e) { return null; } } function writeJSON(lsKey, obj) { try { localStorage.setItem(lsKey, JSON.stringify(obj)); } catch (e) {} } function saveFlags() { writeJSON(FLAGS_LS, { regions: REGIONS.join(','), titles: lockedTitles }); } function limitedTo(allowed, regions) { if (!allowed || !allowed.length) return false; return allowed.every(function (r) { return regions.indexOf(r) !== -1; }); } function restrictions(ids) { var key = apiKey(); if (!key) return Promise.reject(new Error('no API key')); var found = {}; var batches = []; for (var i = 0; i < ids.length; i += 50) batches.push(ids.slice(i, i + 50)); return batches.reduce(function (chain, batch) { return chain.then(function () { return fetch(YT + '?part=contentDetails&maxResults=50&key=' + encodeURIComponent(key) + '&id=' + batch.join(',')) .then(function (res) { if (!res.ok) return res.text().then(function (t) { throw new Error('youtube ' + res.status + ': ' + t); }); return res.json(); }) .then(function (j) { (j.items || []).forEach(function (item) { var rr = item.contentDetails && item.contentDetails.regionRestriction; found[item.id] = (rr && rr.allowed) || null; }); }); }); }, Promise.resolve()).then(function () { var map = {}; ids.forEach(function (id) { map[id] = (id in found) ? { status: 'ok', allowed: found[id] } : { status: 'gone', allowed: null }; }); return map; }); } function checkPlaylist(playlist) { return apiGet('/playlists/' + encodeURIComponent(playlist.id) + '/tracks').then(function (tracks) { var yt = tracks.filter(function (t) { return t.source === 'youtube' && t.sourceId; }); if (!yt.length) return { playlist: playlist.name, total: 0, locked: [], gone: [] }; return restrictions(yt.map(function (t) { return t.sourceId; })).then(function (map) { var locked = [], gone = []; yt.forEach(function (t) { var r = map[t.sourceId]; var row = { playlistId: playlist.id, playlistName: playlist.name, trackId: t.id, title: t.title, track: t.title + (t.artist ? ' - ' + t.artist : ''), url: 'https://youtu.be/' + t.sourceId }; if (r.status === 'gone') gone.push(row); else if (r.status === 'ok' && limitedTo(r.allowed, REGIONS)) { locked.push(Object.assign(row, { allowed: r.allowed.join(',') })); lockedTitles[norm(t.title)] = r.allowed.length; } }); return { playlist: playlist.name, total: yt.length, locked: locked, gone: gone }; }); }); } function checkAll(only) { if (!apiKey()) { log('no API key, cancelled'); return Promise.resolve([]); } return apiGet('/playlists').then(function (playlists) { var wanted = only ? playlists.filter(function (p) { return p.id === only || p.name.toLowerCase() === String(only).toLowerCase(); }) : playlists; if (!wanted.length) { log('no playlist matched "' + only + '"'); return []; } if (!only) lockedTitles = {}; return wanted.reduce(function (chain, p) { return chain.then(function (acc) { return checkPlaylist(p).then(function (r) { log(r.playlist + ': ' + r.locked.length + ' locked, ' + r.gone.length + ' gone, of ' + r.total + ' youtube tracks'); return acc.concat([r]); }); }); }, Promise.resolve([])).then(function (results) { saveFlags(); return results; }); }); } function report(results) { var locked = [], gone = []; results.forEach(function (r) { locked = locked.concat(r.locked); gone = gone.concat(r.gone); }); var lockedCols = function (r) { return { playlist: r.playlistName, track: r.track, allowed: r.allowed }; }; var goneCols = function (r) { return { playlist: r.playlistName, track: r.track, url: r.url }; }; if (locked.length) { log('playable only in ' + REGIONS.join('/') + ':'); console.table(locked.map(lockedCols)); } if (gone.length) { log('deleted or private:'); console.table(gone.map(goneCols)); } if (!locked.length && !gone.length) log('nothing region-locked or missing'); return locked.length; } function offendersOf(results) { var out = []; results.forEach(function (r) { r.gone.forEach(function (g) { out.push(Object.assign({ why: 'deleted or private on YouTube' }, g)); }); r.locked.forEach(function (l) { out.push(Object.assign({ why: 'only playable in ' + REGIONS.join('/') }, l)); }); }); return out; } function removeOffender(o) { return apiDelete('/playlists/' + encodeURIComponent(o.playlistId) + '/tracks/' + encodeURIComponent(o.trackId)).then(function () { delete lockedTitles[norm(o.title)]; markRemoved(o.title); log('removed "' + o.track + '" from ' + o.playlistName); return true; }).catch(function (e) { log('remove failed for "' + o.track + '": ' + e.message); toast('Remove failed', o.track); return false; }); } var WORLD = ''; function toolbar() { var create = document.querySelector('button[aria-label="Create playlist" i]'); var wrap = create && create.parentElement; var bar = wrap && wrap.parentElement; return bar && bar.classList.contains('flex') ? { bar: bar, before: wrap } : null; } function runCheck(btn) { if (btn.disabled) return; btn.disabled = true; var label = btn.getAttribute('aria-label'); btn.setAttribute('aria-label', 'Checking regions...'); btn.style.opacity = '.5'; checkAll(null).then(function (results) { var n = report(results); btn.setAttribute('aria-label', n ? n + ' track(s) playable only in ' + REGIONS.join('/') + ' - see console' : 'No region-locked tracks'); markRows(); if (!toastUnavailable(results)) toast('Every track is available', 'nothing region-locked or missing'); if (n && !document.querySelector('.wz-region-flag')) log('found ' + n + ' locked track(s) but could not tag any row - run WZRegion.debug()'); }).catch(function (e) { log('failed: ' + e.message); btn.setAttribute('aria-label', 'Region check failed - see console'); }).then(function () { btn.disabled = false; btn.style.opacity = ''; setTimeout(function () { btn.setAttribute('aria-label', label); }, 8000); }); } function addButton() { if (document.getElementById('wz-region-btn')) return; var spot = toolbar(); if (!spot) return; var wrap = document.createElement('div'); wrap.className = 'inline-flex'; var btn = document.createElement('button'); btn.id = 'wz-region-btn'; btn.type = 'button'; btn.className = 'theme-button-neutral inline-flex h-9 w-9 items-center justify-center rounded-md'; btn.setAttribute('aria-label', 'Region check'); btn.title = 'Flag tracks YouTube only allows in ' + REGIONS.join('/'); btn.innerHTML = WORLD; btn.addEventListener('click', function () { runCheck(btn); }); wrap.appendChild(btn); spot.bar.insertBefore(wrap, spot.before); } function pill(count, key) { var el = document.createElement('span'); el.className = 'wz-region-flag inline-flex shrink-0 items-center gap-1 rounded-md border border-rose-300/24 bg-rose-400/12 px-2 py-0.5 text-[10px] font-semibold tracking-[0.12em] text-rose-100 uppercase'; el.dataset.wzTitle = key; var msg = 'YouTube only allows this track in ' + count + ' countr' + (count === 1 ? 'y' : 'ies') + ', all inside ' + REGIONS.join('/') + '.'; el.title = msg; el.setAttribute('aria-label', msg); el.innerHTML = WORLD.replace('width="16" height="16"', 'width="11" height="11"') + REGIONS.join('/') + ' only'; return el; } function markRemoved(title) { var key = norm(title); var pills = document.querySelectorAll('.wz-region-flag'); for (var i = 0; i < pills.length; i++) { if (norm(pills[i].dataset.wzTitle) !== key) continue; var p = pills[i]; p.className = 'wz-region-flag inline-flex shrink-0 items-center gap-1 rounded-md border border-emerald-300/24 bg-emerald-400/12 px-2 py-0.5 text-[10px] font-semibold tracking-[0.12em] text-emerald-100 uppercase'; p.innerHTML = 'removed - reload'; if (p.parentElement) { p.parentElement.style.opacity = '.5'; p.parentElement.style.textDecoration = 'line-through'; } } } function norm(s) { return (s || '').replace(/\s+/g, ' ').trim().toLowerCase(); } function tag(el, n, key) { var host = el.parentElement; if (!host || host.querySelector('.wz-region-flag')) return false; host.appendChild(pill(n, key)); return true; } function markRows() { var titles = Object.keys(lockedTitles); if (!titles.length) return; var nodes = document.querySelectorAll('span, p, div, a, h1, h2, h3, h4'); var seen = {}; var i, el, text; for (i = 0; i < nodes.length; i++) { el = nodes[i]; if (el.children.length > 1) continue; text = norm(el.textContent); if (lockedTitles[text] === undefined) continue; if (el.children.length === 1 && norm(el.children[0].textContent) === text) continue; seen[text] = true; tag(el, lockedTitles[text], text); } var missing = titles.filter(function (t) { return !seen[t]; }); if (!missing.length) return; for (i = 0; i < nodes.length; i++) { el = nodes[i]; if (el.children.length) continue; text = norm(el.textContent); for (var j = 0; j < missing.length; j++) { if (text.length > missing[j].length && text.length < missing[j].length + 40 && text.indexOf(missing[j]) === 0) tag(el, lockedTitles[missing[j]], missing[j]); } } } var TOAST_HOST = ''; function toastHost() { var host = document.querySelector(TOAST_HOST || '[data-sonner-toaster], [data-radix-toast-viewport], .toaster, #toast-root'); if (host) return { el: host, native: true }; var own = document.getElementById('wz-region-toasts'); if (!own) { own = document.createElement('div'); own.id = 'wz-region-toasts'; own.style.cssText = 'position:fixed;right:16px;bottom:16px;z-index:99999;display:flex;flex-direction:column;gap:8px;max-width:360px'; document.body.appendChild(own); } return { el: own, native: false }; } function toast(title, detail, action) { var host = toastHost(); var el = document.createElement('div'); el.className = 'wz-region-toast flex items-start gap-2 rounded-md border px-3 py-2 text-sm'; if (!host.native) el.style.cssText = 'display:flex;gap:8px;align-items:flex-start;padding:10px 12px;border-radius:8px;border:1px solid var(--theme-field-border,rgba(255,255,255,.12));background:var(--theme-dropdown-bg,rgba(20,20,26,.96));color:var(--theme-text-primary,#e7e7ea);box-shadow:0 8px 20px rgba(0,0,0,.16);font:500 13px/1.35 system-ui,sans-serif'; el.innerHTML = WORLD.replace('width="16" height="16"', 'width="14" height="14"') + '' + esc(title) + '' + (detail ? '
' + esc(detail) + '' : '') + '
'; if (action) { var btn = document.createElement('button'); btn.type = 'button'; btn.className = 'theme-button-neutral shrink-0 rounded-md px-2 py-1 text-xs font-semibold'; btn.style.cssText = 'border:1px solid var(--theme-field-border,rgba(255,255,255,.18));background:var(--theme-dropdown-hover,rgba(255,255,255,.06));color:inherit;cursor:pointer'; btn.textContent = action.label; btn.addEventListener('click', function (e) { e.stopPropagation(); btn.disabled = true; btn.textContent = '...'; Promise.resolve(action.fn()).then(function (ok) { if (ok !== false) el.remove(); else { btn.disabled = false; btn.textContent = action.label; } }); }); el.appendChild(btn); } else { el.addEventListener('click', function () { el.remove(); }); } host.el.appendChild(el); setTimeout(function () { el.remove(); }, action ? 20000 : 8000); } function esc(s) { var d = document.createElement('div'); d.textContent = s; return d.innerHTML; } function toastUnavailable(results) { var offenders = offendersOf(results); lastOffenders = offenders; offenders.slice(0, 5).forEach(function (o) { toast(o.track, o.why + ' - in ' + o.playlistName, { label: 'Remove', fn: function () { return removeOffender(o); } }); }); if (offenders.length > 5) { var rest = offenders.slice(5); toast(rest.length + ' more unavailable', 'full list in the console', { label: 'Remove all', fn: function () { return removeMany(rest); } }); } return offenders.length; } function removeMany(list) { return list.reduce(function (chain, o) { return chain.then(function (done) { return removeOffender(o).then(function (ok) { return done + (ok ? 1 : 0); }); }); }, Promise.resolve(0)).then(function (done) { toast('Removed ' + done + ' of ' + list.length, 'reload to refresh the list'); return done; }); } (function restoreFlags() { var f = readJSON(FLAGS_LS); if (f && f.regions === REGIONS.join(',') && f.titles) lockedTitles = f.titles; })(); var pending = null; new MutationObserver(function () { clearTimeout(pending); pending = setTimeout(function () { addButton(); markRows(); }, 200); }).observe(document.body, { childList: true, subtree: true }); addButton(); markRows(); window.WZRegion = { check: function (only) { return checkAll(only).then(function (r) { var n = report(r); markRows(); toastUnavailable(r); return n; }); }, debug: function () { console.log('toolbar:', toolbar()); console.log('toast host:', toastHost()); console.log('locked titles:', lockedTitles); }, toast: function (a, b) { toast(a || 'Test toast', b || 'from wavez-region-check'); }, find: function (text) { var want = norm(text); var hits = []; var all = document.body.querySelectorAll('*'); for (var i = 0; i < all.length; i++) { if (norm(all[i].textContent).indexOf(want) === -1) continue; if (all[i].querySelector('#wz-region-toasts, #wz-region-btn')) continue; if (!all[i].children.length) hits.push(all[i]); } hits.forEach(function (el) { console.log(el, '\nparent markup:\n' + (el.parentElement ? el.parentElement.outerHTML.slice(0, 700) : '(none)')); }); if (!hits.length) log('nothing on screen contains "' + text + '"'); return hits; }, playlists: function () { return apiGet('/playlists').then(function (p) { console.table(p.map(function (x) { return { id: x.id, name: x.name, active: !!x.isActive }; })); return p; }); }, setKey: function (k) { localStorage.setItem(KEY_LS, k); return 'saved'; }, clearFlags: function () { localStorage.removeItem(FLAGS_LS); lockedTitles = {}; return 'cleared'; }, unavailable: function () { console.table(lastOffenders.map(function (o) { return { playlist: o.playlistName, track: o.track, why: o.why }; })); return lastOffenders; }, remove: function (filter) { if (!lastOffenders.length) { log('run a check first (nothing to remove)'); return Promise.resolve(0); } var want = lastOffenders.filter(function (o) { if (!filter) return true; if (filter === 'gone') return o.why.indexOf('deleted') === 0; if (filter === 'locked') return o.why.indexOf('only playable') === 0; return norm(o.track).indexOf(norm(filter)) !== -1; }); if (!want.length) { log('no offenders match ' + JSON.stringify(filter)); return Promise.resolve(0); } if (!window.confirm('Remove ' + want.length + ' track(s) from your playlists? This cannot be undone.')) return Promise.resolve(0); return removeMany(want); }, regions: REGIONS }; log('loaded - hit the globe in the playlist toolbar or run WZRegion.check()'); if (location.hash === '#wz-region-test') { console.assert(limitedTo(['US', 'CA'], REGIONS) === true, 'US+CA only, flag it'); console.assert(limitedTo(['US'], REGIONS) === true, 'US only, flag it'); console.assert(limitedTo(['US', 'CA', 'GB'], REGIONS) === false, 'GB can play it, leave it'); console.assert(limitedTo(['JP'], REGIONS) === false, 'JP only is not a US/CA lock'); console.assert(limitedTo(null, REGIONS) === false, 'no restriction at all'); console.assert(limitedTo([], REGIONS) === false, 'empty allowed list is not a lock'); log('self-check passed'); } })(); }); if (menu('auto-idle', 'Auto Idle', 'off', 'Automation', [["IDLE_MINUTES", "Idle minutes", 5, ""]])) ready(function (window) { (function () { 'use strict'; var log = function () { console.log.apply(console, ["%c[wz-idle]", "color:#90A4AE;font-weight:bold"].concat([].slice.call(arguments))); }; var IDLE_MINUTES = setting("auto-idle", "IDLE_MINUTES", 5); var AWAY = "away"; var ACTIVE = "online"; var DND = "dnd"; var API = "https://api.wavez.fm/settings"; var timer = null; var current = ACTIVE; var authHeader = null; (function captureAuth() { var of = window.fetch; window.fetch = function (input, init) { try { var url = typeof input === "string" ? input : (input && input.url) || ""; if (url.indexOf("api.wavez.fm") !== -1) { var h = new Headers((init && init.headers) || (typeof input === "object" && input.headers) || {}); var a = h.get("authorization"); if (a) authHeader = a; } } catch (e) {} return of.apply(this, arguments); }; })(); function remotePresence() { var headers = {}; if (authHeader) headers["Authorization"] = authHeader; return fetch(API, { credentials: "include", headers: headers }).then(function (res) { return res.json(); }).then(function (j) { return j && j.presenceStatus; }).catch(function () { return null; }); } function setPresence(status) { if (status === current) return Promise.resolve(); return remotePresence().then(function (remote) { if (remote === DND) { current = DND; return; } current = status; var headers = { "Content-Type": "application/json" }; if (authHeader) headers["Authorization"] = authHeader; return fetch(API, { method: "PATCH", credentials: "include", headers: headers, body: JSON.stringify({ presenceStatus: status }), }).then(function (res) { if (!res.ok) current = status === AWAY ? ACTIVE : AWAY; }).catch(function () { current = status === AWAY ? ACTIVE : AWAY; }); }); } function onHidden() { clearTimeout(timer); timer = setTimeout(function () { setPresence(AWAY); }, IDLE_MINUTES * 60 * 1000); } function onVisible() { clearTimeout(timer); setPresence(ACTIVE); } document.addEventListener("visibilitychange", function () { if (document.hidden) onHidden(); else onVisible(); }); if (location.hash === "#wz-idle-test") { var calls = []; var realFetch = window.fetch; var remote = ACTIVE; window.fetch = function (u, o) { if (!o || o.method !== "PATCH") return Promise.resolve({ json: function () { return Promise.resolve({ presenceStatus: remote }); } }); calls.push(JSON.parse(o.body).presenceStatus); return Promise.resolve({ ok: true }); }; current = ACTIVE; Promise.resolve() .then(function () { return setPresence(ACTIVE); }) .then(function () { return setPresence(AWAY); }) .then(function () { return setPresence(AWAY); }) .then(function () { return setPresence(ACTIVE); }) .then(function () { remote = DND; return setPresence(AWAY); }) .then(function () { return setPresence(ACTIVE); }) .then(function () { window.fetch = realFetch; console.assert(calls.join(",") === "away,online", "idle dnd/dedupe broken:", calls); log("self-check passed"); }); } })(); }); if (menu('new-users', 'New Users', 'off', 'Moderation', [["NEW_DAYS", "Days flagged", 2, ""], ["BADGE", "Pill text", "NEW", ""], ["COLOR_NAME", "Colour the name", false, ""], ["COLOR", "Colour", "#00E5A0", ""], ["NOTIFY", "Desktop alert", true, ""]])) ready(function (window) { var NEW_DAYS = setting("new-users", "NEW_DAYS", 2); var BADGE = setting("new-users", "BADGE", "NEW"); var COLOR_NAME = setting("new-users", "COLOR_NAME", false); var COLOR = setting("new-users", "COLOR", "#00E5A0"); var NOTIFY = setting("new-users", "NOTIFY", true); (function () { "use strict"; var TAG = ["%c[wz-new]", "color:#00E5A0;font-weight:bold"]; var KEY = "wavez-user-joined-v2"; var API = "https://api.wavez.fm/users/by-username/"; var NAME_SELECTOR = '[data-wavezfm-chat-name="true"], [data-wavezfm-people-name="true"], [data-wavezfm-user-preview-name="true"]'; var joined = (function () { try { return JSON.parse(localStorage.getItem(KEY)) || {}; } catch (e) { return {}; } })(); var pending = {}; function save() { localStorage.setItem(KEY, JSON.stringify(joined)); } function isNew(name, now) { return joined[name] > 0 && now - joined[name] < NEW_DAYS * 86400000; } var SAFE_COLOR = /^#[0-9a-f]{3,8}$/i.test(COLOR) ? COLOR : "#00E5A0"; var css = document.createElement("style"); css.textContent = (COLOR_NAME ? ".wz-new-user { color: " + SAFE_COLOR + " !important; }" : "") + (BADGE ? ".wz-new-user::after { content: " + JSON.stringify(String(BADGE)).replace(/ 0 ? at : 0; save(); if (isNew(name, Date.now())) console.log.apply(console, TAG.concat([name + " joined " + new Date(at).toISOString().slice(0, 10)])); remark(name); }) .catch(function () {}) .then(function () { delete pending[name]; }); } function notify(body) { if (typeof GM_notification === "function") return GM_notification({ title: "Wavez New Users", text: body, onclick: function () { window.focus(); } }); if (window.Notification && Notification.permission === "granted") new Notification("Wavez New Users", { body: body }); } var started = Date.now(); var pinged = {}; function ping(name) { if (pinged[name]) return; pinged[name] = true; if (!NOTIFY || Date.now() - started < 10000 || !(document.hidden || !document.hasFocus())) return; notify(name + " is a new account (under " + NEW_DAYS + " day" + (NEW_DAYS === 1 ? "" : "s") + " old)"); } function apply(el, name) { var fresh = isNew(name, Date.now()); el.classList.toggle("wz-new-user", fresh); if (fresh) ping(name); } function mark(el) { var name = (el.textContent || "").trim().toLowerCase(); if (!name || el.dataset.wzName === name) return; el.dataset.wzName = name; if (name in joined) apply(el, name); else lookup(name); } function remark(name) { var nodes = document.querySelectorAll(NAME_SELECTOR); for (var i = 0; i < nodes.length; i++) if (nodes[i].dataset.wzName === name) apply(nodes[i], name); } function scan(root) { if (root.nodeType !== 1) return; if (root.matches && root.matches(NAME_SELECTOR)) mark(root); var nodes = root.querySelectorAll(NAME_SELECTOR); for (var i = 0; i < nodes.length; i++) mark(nodes[i]); } scan(document.body); new MutationObserver(function (records) { for (var i = 0; i < records.length; i++) { var added = records[i].addedNodes; for (var j = 0; j < added.length; j++) scan(added[j]); } }).observe(document.body, { childList: true, subtree: true }); var pageWindow = typeof unsafeWindow !== "undefined" ? unsafeWindow : window; pageWindow.WZNew = { list: function () { var now = Date.now(); return Object.keys(joined).filter(function (n) { return isNew(n, now); }); }, joined: function () { return joined; }, forget: function (name) { delete joined[String(name).toLowerCase()]; save(); }, reset: function () { localStorage.removeItem(KEY); joined = {}; }, }; console.log.apply(console, TAG.concat(["watching for accounts under " + NEW_DAYS + " days old. WZNew.list() / WZNew.forget(name) / WZNew.reset()"])); if (location.hash === "#wz-new-test") { var real = joined; var now = Date.now(); joined = { fresh: now - 1000, stale: now - (NEW_DAYS + 1) * 86400000, missing: 0 }; console.assert(isNew("fresh", now) === true, "joined a second ago is new"); console.assert(isNew("stale", now) === false, "joined before the window is not new"); console.assert(isNew("missing", now) === false, "no known date is never new"); console.assert(isNew("nobody", now) === false, "unlooked-up name is not new"); joined = real; console.log.apply(console, TAG.concat(["tests passed"])); } })(); }); if (menu('sos-alert', 'SOS Alert', 'off', 'Moderation', [["SOS_ACTION", "Button watched", "moderation", ""], ["COOLDOWN_SECONDS", "Quiet seconds", 15, ""], ["VOLUME", "Volume", 0.35, ""], ["NOTIFY", "Desktop alert", true, ""], ["SOUND_URL", "Sound URL", "", ""]])) ready(function (window) { var SOS_ACTION = setting("sos-alert", "SOS_ACTION", "moderation"); var BADGE_SELECTOR = '[data-room-action-menu-attention], [class*="bg-rose"], [class*="bg-red"], [class*="-top-1"]'; var COOLDOWN_SECONDS = setting("sos-alert", "COOLDOWN_SECONDS", 15); var VOLUME = setting("sos-alert", "VOLUME", 0.35); var NOTIFY = setting("sos-alert", "NOTIFY", true); var SOUND_URL = setting("sos-alert", "SOUND_URL", ""); (function () { "use strict"; var TAG = ["%c[wz-sos]", "color:#FF1744;font-weight:bold"]; var HOST_SELECTORS = ['[data-wavezfm-room-footer-action="' + SOS_ACTION + '"]', ".tabler-icon-shield-exclamation", '[data-wavezfm-room-footer-action][aria-label*="' + SOS_ACTION + '" i]']; var config = { enabled: true }; var host = null; var count = 0; var lastFire = 0; var ctx = null; var FLAG = "(!) "; function audio() { if (!ctx) ctx = new (window.AudioContext || window.webkitAudioContext)(); if (ctx.state === "suspended") ctx.resume(); return ctx; } document.addEventListener("pointerdown", function () { audio(); if (window.Notification && Notification.permission === "default") Notification.requestPermission(); }, { once: true }); function tone(ac, at, len, freq) { var osc = ac.createOscillator(); var gain = ac.createGain(); osc.type = "sine"; osc.frequency.value = freq; gain.gain.setValueAtTime(0.0001, at); gain.gain.exponentialRampToValueAtTime(VOLUME, at + 0.015); gain.gain.exponentialRampToValueAtTime(0.0001, at + len); osc.connect(gain).connect(ac.destination); osc.start(at); osc.stop(at + len + 0.02); } function alarm() { if (SOUND_URL) { var el = new Audio(SOUND_URL); el.volume = VOLUME; el.play().catch(function (err) { console.warn.apply(console, TAG.concat(["sound file blocked or missing:", err])); }); return; } var ac = audio(); var at = ac.currentTime + 0.05; tone(ac, at, 0.5, 660); tone(ac, at + 0.16, 0.6, 880); } function away() { return document.hidden || !document.hasFocus(); } function notify(body) { if (typeof GM_notification === "function") return GM_notification({ title: "Wavez SOS", text: body, onclick: function () { window.focus(); } }); if (!window.Notification || Notification.permission !== "granted") return console.warn.apply(console, TAG.concat(["no desktop notification: GM_notification missing and site permission is " + (window.Notification ? Notification.permission : "unsupported")])); var note = new Notification("Wavez SOS", { body: body, tag: "wz-sos", renotify: true, requireInteraction: true }); note.onclick = function () { window.focus(); note.close(); }; } function alertAway(n, force, body) { if (!force && !away()) return; if (!force && !NOTIFY) return; if (document.title.indexOf(FLAG) !== 0) document.title = FLAG + document.title; notify(body || (n > 1 ? n + " moderation alerts need attention" : "A moderation alert needs attention")); } function unflag() { if (!away() && document.title.indexOf(FLAG) === 0) document.title = document.title.slice(FLAG.length); } document.addEventListener("visibilitychange", unflag); window.addEventListener("focus", unflag); function findHost() { for (var i = 0; i < HOST_SELECTORS.length; i++) { var el = document.querySelector(HOST_SELECTORS[i]); if (el) return el; } return null; } function scope(el) { return (el.closest && el.closest('button, a, li, [role="button"], [role="tab"]')) || el.parentElement || el; } function visible(el) { var s = el.ownerDocument.defaultView.getComputedStyle(el); return s.display !== "none" && s.visibility !== "hidden" && s.opacity !== "0"; } function badgeCount() { if (!host) return 0; var nodes = scope(host).querySelectorAll(BADGE_SELECTOR); for (var i = 0; i < nodes.length; i++) { if (!visible(nodes[i])) continue; var n = parseInt((nodes[i].textContent || "").trim(), 10); return n > 0 ? n : 1; } return 0; } function check() { if (host && !document.contains(host)) host = null; if (!host) { host = findHost(); if (!host) return; count = badgeCount(); return; } var now = badgeCount(); if (now > count && config.enabled && Date.now() - lastFire >= COOLDOWN_SECONDS * 1000) { lastFire = Date.now(); console.log.apply(console, TAG.concat(["SOS badge -> " + now])); alarm(); alertAway(now); } count = now; } host = findHost(); count = badgeCount(); new MutationObserver(check).observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ["class", "style", "hidden"] }); document.addEventListener("wavez-ai:help", function (e) { if (!config.enabled || Date.now() - lastFire < COOLDOWN_SECONDS * 1000) return; lastFire = Date.now(); var m = {}; try { m = JSON.parse(e.detail); } catch (err) {} console.log.apply(console, TAG.concat(["AI flagged help ->", m])); alarm(); alertAway(1, false, (m.who || "Someone") + " may need help: " + (m.text || "")); }); var pageWindow = typeof unsafeWindow !== "undefined" ? unsafeWindow : window; pageWindow.WZSos = { config: config, test: function () { alarm(); alertAway(1, true); }, on: function () { config.enabled = true; }, off: function () { config.enabled = false; }, debug: function () { var h = host || findHost(); console.log.apply(console, TAG.concat(["control:", h, "\nwrapper:", h ? scope(h).outerHTML : "(not found)", "\ncount now:", badgeCount()])); return h; }, }; console.log.apply(console, TAG.concat([host ? "active - watching the SOS badge (currently " + count + "). WZSos.test() / WZSos.debug() / WZSos.off()" : "no footer button matching '" + SOS_ACTION + "' on screen yet - will keep looking. WZSos.debug() once one appears."])); })(); }); menu('panel', 'Show Panel UI', 'on', 'Panel', []); ready(function (window) { (function () { 'use strict'; var TAG = ['%c[wavez-tools]', 'color:#22D3EE;font-weight:bold']; var log = function () { console.log.apply(console, TAG.concat([].slice.call(arguments))); }; var KEY = 'wavez-tools'; var HISTORY_KEY = 'wavez-tools-history'; var HISTORY_MAX = 60; var ACTIVITY_KEY = 'wavez-tools-activity'; var LASTKEY_KEY = 'wavez-tools-lastkey'; var MEHS_KEY = 'wavez-tools-mehs'; var PLAYS_KEY = 'wavez-tools-plays'; var TOP = 72; var VOLUME = 0.25; var ACTIVITY_MAX = 25; var VERSION = '1.0'; var AUTHOR = 'fluteds'; var DEFAULTS = { open: true, pos: null, sections: { addons: false, addonset: false, tools: true, alerts: false, actions: false, activity: false }, autowoot: true, voteDelay: '1-10', autojoin: false, booth: false, history: false, mehs: false, mentions: false, joins: false, turn: false, unlock: false, whispers: false, desktop: 'away', boothAt: 3, autoleave: false, leaveAfter: 3, joinMode: 'everyone', sound: 'soft', keywords: [], kwMatch: 'anywhere' }; var DELAYS = { instant: [0, 0], '1-5': [1000, 5000], '1-10': [1000, 10000], '5-20': [5000, 20000] }; var SOUNDS = { none: [], soft: [[660, 0.09], [880, 0.12]], beep: [[880, 0.08], [880, 0.08]], chime: [[784, 0.09], [988, 0.09], [1319, 0.16]] }; var cfg = (function () { try { return Object.assign({}, DEFAULTS, JSON.parse(localStorage.getItem(KEY)) || {}); } catch (e) { return Object.assign({}, DEFAULTS); } })(); function save() { localStorage.setItem(KEY, JSON.stringify(cfg)); } function load(key, fallback) { try { return JSON.parse(localStorage.getItem(key)) || fallback; } catch (e) { return fallback; } } var recent = load(HISTORY_KEY, []); var activity = load(ACTIVITY_KEY, []); function esc(s) { return String(s).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); } function html(s) { return String(s).replace(/[&<>"']/g, function (c) { return '&#' + c.charCodeAt(0) + ';'; }); } function word(w) { return new RegExp('(^|[^a-z0-9_])' + esc(w) + '([^a-z0-9_]|$)'); } function mentionHit(text, keywords, username, whole) { var t = String(text || '').toLowerCase(); if (!t) return null; if (username && new RegExp('(^|[^a-z0-9_])@?' + esc(username.toLowerCase()) + '([^a-z0-9_]|$)').test(t)) return username; for (var i = 0; i < keywords.length; i++) { var k = String(keywords[i]).trim().toLowerCase(); if (k && (whole ? word(k).test(t) : t.indexOf(k) !== -1)) return keywords[i]; } return null; } function playedAgo(list, id) { var i = list.lastIndexOf(id); return i === -1 ? -1 : list.length - i; } function boothHit(pos, at, last) { return pos > 0 && pos <= at && (last === null || last > at); } function joinable(user, mode) { return mode === 'everyone' || (mode === 'following' && !!user.isFollowing) || (mode === 'superfans' && !!user.isSuperfan); } function shouldLeave(plays, after, q) { return plays >= after && !!q && !!q.isJoined && !q.isCurrentDj; } function delayFor(kind) { var d = DELAYS[kind] || DELAYS.instant; return d[0] + Math.random() * (d[1] - d[0]); } var ctx = null; function audio() { if (!ctx) ctx = new (window.AudioContext || window.webkitAudioContext)(); if (ctx.state === 'suspended') ctx.resume(); return ctx; } document.addEventListener('pointerdown', audio, { once: true }); function play(kind) { var seq = SOUNDS[kind || cfg.sound] || []; if (!seq.length) return; var ac = audio(); var at = ac.currentTime + 0.03; seq.forEach(function (step) { var osc = ac.createOscillator(); var gain = ac.createGain(); osc.type = 'sine'; osc.frequency.value = step[0]; gain.gain.setValueAtTime(0, at); gain.gain.linearRampToValueAtTime(VOLUME, at + 0.01); gain.gain.setValueAtTime(VOLUME, at + step[1] - 0.01); gain.gain.linearRampToValueAtTime(0, at + step[1]); osc.connect(gain).connect(ac.destination); osc.start(at); osc.stop(at + step[1] + 0.02); at += step[1] + 0.03; }); } var css = document.createElement('style'); css.textContent = ` #wt { position: fixed; top: ${TOP}px; right: 16px; width: 272px; max-height: min(560px, calc(100vh - ${TOP + 16}px)); overflow-x: hidden; overflow-y: auto; z-index: 2147483647; --e: cubic-bezier(.32,.72,0,1); transition: width .5s var(--e); background: #000; color: #e8e8e8; border: 1px solid #222; border-radius: 16px; font: 400 13px/1.4 "Space Grotesk", system-ui, sans-serif; box-shadow: 0 20px 50px rgba(0,0,0,.6); scrollbar-width: thin; scrollbar-color: #333 transparent; } #wt.wt-collapsed { width: var(--pill, 200px); } #wt .wt-main { display: grid; grid-template-rows: 1fr; transition: grid-template-rows .5s var(--e); } #wt .wt-main > div { width: 270px; min-height: 0; overflow: hidden; transition: opacity .35s var(--e), transform .5s var(--e); } #wt.wt-collapsed .wt-main { grid-template-rows: 0fr; } #wt.wt-collapsed .wt-main > div { opacity: 0; transform: translateY(-8px); } #wt.wt-collapsed .wt-top { border-bottom-color: transparent; } #wt .wt-top { display: flex; justify-content: space-between; align-items: center; gap: 16px; padding: 14px 16px 12px; border-bottom: 1px solid #222; background-image: radial-gradient(circle, #2a2a2a 1px, transparent 1px); background-size: 8px 8px; transition: border-color .5s var(--e); cursor: grab; user-select: none; touch-action: none; } #wt .wt-top:active { cursor: grabbing; } #wt h1 { flex: none; margin: 0; padding-right: 6px; white-space: nowrap; background: #000; font: 500 20px/1 "Doto", "Space Mono", monospace; letter-spacing: .02em; text-transform: uppercase; color: #fff; } #wt .wt-top button { width: 24px; height: 24px; padding: 0; border: 1px solid #333; border-radius: 999px; color: #999; background: linear-gradient(currentColor, currentColor) center / 9px 1px no-repeat, linear-gradient(currentColor, currentColor) center / 1px 0 no-repeat, #000; cursor: pointer; transition: background-size .5s var(--e), transform .5s var(--e), border-color .2s, color .2s; } #wt.wt-collapsed .wt-top button { background-size: 9px 1px, 1px 9px; transform: rotate(90deg); } #wt .wt-top button:hover { border-color: #e8e8e8; color: #fff; } #wt .wt-label { font: 400 10px/1.2 "Space Mono", monospace; letter-spacing: .08em; text-transform: uppercase; color: #999; } #wt .wt-now { padding: 14px 16px; border-bottom: 1px solid #222; } #wt .wt-track { margin-top: 6px; font-size: 15px; font-weight: 500; color: #fff; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } #wt .wt-artist { color: #999; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } #wt .wt-notice { font: 400 11px/1.4 "Space Mono", monospace; color: #e8e8e8; } #wt .wt-notice:not(:empty) { margin-top: 10px; } #wt .wt-notice:not(:empty)::before { content: ''; display: inline-block; width: 6px; height: 6px; margin-right: 8px; border-radius: 50%; background: #d71921; vertical-align: 1px; } #wt .wt-sw { display: flex; width: 100%; justify-content: space-between; align-items: center; gap: 12px; padding: 9px 16px; border: 0; background: none; color: inherit; font: inherit; text-align: left; cursor: pointer; } #wt .wt-sw:hover { background: #111; } #wt .wt-sw i { position: relative; flex: none; width: 30px; height: 16px; border: 1px solid #333; border-radius: 999px; transition: border-color .3s var(--e); } #wt .wt-sw i::after { content: ''; position: absolute; top: 3px; left: 3px; width: 8px; height: 8px; border-radius: 50%; background: #666; transition: transform .3s var(--e), background .3s var(--e); } #wt .wt-sw[aria-checked="true"] i { border-color: #d71921; } #wt .wt-sw[aria-checked="true"] i::after { background: #d71921; transform: translateX(14px); } #wt .wt-line { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 6px 16px; } #wt select, #wt input, #wt .wt-btn { border: 1px solid #333; border-radius: 999px; background: #111; color: #e8e8e8; font: 400 11px "Space Mono", monospace; padding: 5px 10px; } #wt .wt-btn { cursor: pointer; text-transform: uppercase; letter-spacing: .06em; } #wt .wt-btn:hover, #wt select:hover { border-color: #e8e8e8; } #wt input:focus, #wt select:focus { outline: none; border-color: #e8e8e8; } #wt .wt-group { border-top: 1px solid #222; } #wt .wt-now + .wt-sw { margin-top: 4px; } #wt .wt-head { display: flex; justify-content: space-between; padding: 12px 16px; cursor: pointer; user-select: none; } #wt .wt-head:hover { color: #fff; } #wt .wt-head::after { content: ''; align-self: center; width: 9px; height: 9px; background: linear-gradient(currentColor, currentColor) center / 9px 1px no-repeat, linear-gradient(currentColor, currentColor) center / 1px 0 no-repeat; transition: background-size .45s var(--e), transform .45s var(--e); } #wt .wt-shut .wt-head::after { background-size: 9px 1px, 1px 9px; transform: rotate(90deg); } #wt .wt-body { display: grid; grid-template-rows: 1fr; transition: grid-template-rows .45s var(--e); } #wt .wt-body > div { min-height: 0; overflow: hidden; transition: opacity .35s var(--e), transform .45s var(--e); } #wt .wt-body > div::after { content: ''; display: block; height: 8px; } #wt .wt-shut .wt-body { grid-template-rows: 0fr; } #wt .wt-shut .wt-body > div { opacity: 0; transform: translateY(-6px); } #wt .wt-queue { padding: 6px 16px 2px; font: 400 11px "Space Mono", monospace; color: #666; } #wt .wt-sec { padding: 12px 16px 4px; } #wt .wt-line input { width: 128px; } #wt .wt-line input[type="number"] { width: 72px; } #wt .wt-line input[type="color"] { width: 40px; height: 24px; padding: 2px; cursor: pointer; } #wt .wt-field { display: flex; gap: 6px; padding: 4px 16px 8px; } #wt .wt-field input { flex: 1; min-width: 0; } #wt .wt-chips { display: flex; flex-wrap: wrap; gap: 4px; padding: 0 16px 4px; } #wt .wt-chip { padding: 2px 8px; border: 1px solid #333; border-radius: 999px; font: 400 11px "Space Mono", monospace; cursor: pointer; } #wt .wt-chip:hover { border-color: #d71921; color: #d71921; } #wt .wt-arow { display: flex; align-items: center; } #wt .wt-arow .wt-sw { flex: 1; min-width: 0; padding-right: 8px; } #wt .wt-cog { flex: none; display: grid; place-items: center; width: 26px; height: 26px; margin-right: 10px; padding: 0; border: 0; border-radius: 999px; background: none; color: #666; cursor: pointer; transition: color .2s, background .2s, transform .3s var(--e); } #wt button.wt-cog:hover { color: #fff; background: #111; } #wt span.wt-cog { cursor: default; } #wt .wt-cog[aria-expanded="true"] { color: #d71921; transform: rotate(60deg); } #wt .wt-aset { margin: 0 10px 6px; padding: 4px 0; border: 1px solid #1a1a1a; border-radius: 12px; background: #0a0a0a; } #wt .wt-aset .wt-line, #wt .wt-aset .wt-sw { padding-left: 12px; padding-right: 12px; } #wt .wt-log { max-height: 120px; overflow-y: auto; padding: 0 16px; font-size: 12px; } #wt .wt-log div { padding: 5px 0; border-bottom: 1px solid #1a1a1a; } #wt .wt-log div:last-child { border-bottom: 0; } #wt .wt-log span { margin-right: 8px; font: 400 10px "Space Mono", monospace; color: #666; } #wt .wt-empty { color: #666; } #wt .wt-foot { display: flex; justify-content: space-between; align-items: center; padding: 10px 16px 12px; border-top: 1px solid #222; color: #666; } #wt .wt-foot button { border: 0; background: none; padding: 0; color: inherit; font: inherit; letter-spacing: inherit; text-transform: inherit; cursor: pointer; } #wt .wt-foot button:hover { color: #fff; } #wt.wt-still, #wt.wt-still *, #wt.wt-still *::after { transition: none !important; } @media (prefers-reduced-motion: reduce) { #wt, #wt *, #wt *::after { transition: none !important; } } `; (document.head || document.documentElement).appendChild(css); var font = document.createElement('link'); font.rel = 'stylesheet'; font.href = 'https://fonts.googleapis.com/css2?family=Doto:wght@500&family=Space+Grotesk:wght@400;500&family=Space+Mono&display=swap'; (document.head || document.documentElement).appendChild(font); font.onload = function () { if (document.fonts) document.fonts.ready.then(pill); }; var BUNDLED = typeof ADDONS !== 'undefined'; var ADDON_LIST = BUNDLED ? ADDONS : []; var HEADLESS = BUNDLED && localStorage.getItem('wavez-tools:panel') === 'off'; if (BUNDLED && typeof GM_registerMenuCommand === 'function') GM_registerMenuCommand((cfg.autowoot ? '\u2713 ' : '\u2715 ') + 'Auto Woot', function () { cfg.autowoot = !cfg.autowoot; save(); location.reload(); }); function addStandalone(spec) { if (ADDON_LIST.some(function (a) { return a.id === spec.id; })) return; var k = 'wavez-tools:' + spec.id; var on = localStorage.getItem(k) !== 'off'; var stored = function (n, d) { try { var v = localStorage.getItem(k + ':' + n); return v === null ? d : JSON.parse(v); } catch (e) { return d; } }; var entry = { id: spec.id, label: spec.label, cat: spec.cat || 'Other', on: on, flip: function () { entry.on = !entry.on; localStorage.setItem(k, entry.on ? 'on' : 'off'); }, settings: spec.settings.map(function (s) { return { name: s[0], label: s[1], dflt: s[2], opts: s[3] ? s[3].split(',') : null, value: stored(s[0], s[2]) }; }), save: function (n, v) { localStorage.setItem(k + ':' + n, JSON.stringify(v)); } }; ADDON_LIST.push(entry); renderAddons(); } var TOGGLES = [['autojoin', 'Auto Join'], ['autoleave', 'Auto Leave'], ['mehs', 'Meh Tracker']]; var ALERTS = [['booth', 'Booth Alert'], ['turn', 'Your Turn Alert'], ['unlock', 'Queue Open Alert'], ['history', 'History Alert'], ['mentions', 'Chat Mentions'], ['joins', 'Join Notifications'], ['whispers', 'Whisper Alert']]; function rows(list) { return list.map(function (t) { return row(t[0], t[1]); }).join(''); } function row(id, label) { return ``; } function select(name, options) { var opts = options.map(function (o) { return ``; }).join(''); return ``; } function addonSettings(a, i) { if (!a.settings || !a.settings.length) return ''; return a.settings.map(function (s) { var key = i + ':' + s.name; if (typeof s.dflt === 'boolean') return ``; var type = typeof s.dflt === 'number' ? 'number' : /^#[0-9a-f]{6}$/i.test(s.dflt) ? 'color' : 'text'; var control = s.opts ? `` : ``; return ``; }).join(''); } function setAddon(t, value) { var p = t.dataset.aset.split(':'); var a = ADDON_LIST[p[0]]; var s = a.settings.filter(function (x) { return x.name === p[1]; })[0]; var d = s.dflt; var v = typeof d === 'boolean' ? value : typeof d === 'number' ? Number(value) : Array.isArray(d) ? String(value).split(',').map(function (x) { return x.trim(); }).filter(Boolean) : String(value); if (typeof d === 'number' && (value === '' || isNaN(v))) return; s.value = v; a.save(s.name, v); notice(a.label + ': ' + s.label + ' saved, reload to apply', false, true); } function group(id, label, body) { return `
${label}
${body}
`; } var panel = document.createElement('div'); panel.id = 'wt'; panel.innerHTML = `

Wavez Tools

Now playing
${row('autowoot', 'Auto Woot')}
Vote delay${select('voteDelay', [['instant', 'Instant'], ['1-5', '1–5s'], ['1-10', '1–10s'], ['5-20', '5–20s']])}
${group('tools', 'Room tools', rows(TOGGLES) + `
Auto leave after${select('leaveAfter', [[1, '1 play'], [2, '2 plays'], [3, '3 plays'], [5, '5 plays'], [10, '10 plays']])}
Queue: -
`)} ${group('alerts', 'Notifications', `
Desktop alerts${select('desktop', [['away', 'When away'], ['always', 'Always'], ['off', 'Off']])}
Alert sound${select('sound', [['soft', 'Soft'], ['beep', 'Beep'], ['chime', 'Chime'], ['none', 'None']])}
${rows(ALERTS)}
Alert options
Booth alert at${select('boothAt', [[1, 'Position 1'], [2, 'Position 2'], [3, 'Position 3'], [5, 'Position 5']])}
Join notices${select('joinMode', [['everyone', 'Everyone'], ['following', 'Following'], ['superfans', 'Superfans']])}
Keyword match${select('kwMatch', [['anywhere', 'Anywhere'], ['word', 'Whole word']])}
Mention keywords
`)} ${group('actions', 'Commands', `
`)} ${group('activity', 'Activity', '
')}
v${VERSION} / ${AUTHOR}
`; if (!HEADLESS) document.body.appendChild(panel); var COG = ''; var RELOAD = '
Applies on reload
'; var CATS = ['Automation', 'Chat', 'Music', 'Moderation', 'Panel']; function rank(c) { var i = CATS.indexOf(c); return i === -1 ? CATS.length : i; } function renderAddons() { var box = panel.querySelector('[data-addons]'); if (!box) return; var cats = []; ADDON_LIST.forEach(function (a) { var c = a.cat || 'Other'; if (cats.indexOf(c) === -1) cats.push(c); }); cats.sort(function (x, y) { return rank(x) - rank(y); }); box.innerHTML = ADDON_LIST.length ? group('addons', 'Addons', cats.map(function (c) { return `
${html(c)}
` + ADDON_LIST.map(function (a, i) { if ((a.cat || 'Other') !== c) return ''; var cog = a.settings && a.settings.length ? `` : ''; return `
${cog}
` + (a.settings && a.settings.length ? `` : ''); }).join(''); }).join('') + RELOAD) : ''; } renderAddons(); if (!BUNDLED) { document.addEventListener('wavez-tools:addon', function (e) { try { addStandalone(JSON.parse(e.detail)); } catch (err) {} }); document.dispatchEvent(new CustomEvent('wavez-tools:ping')); } var el = { track: panel.querySelector('.wt-track'), artist: panel.querySelector('.wt-artist'), notice: panel.querySelector('.wt-notice'), queue: panel.querySelector('.wt-queue'), chips: panel.querySelector('[data-chips]'), kw: panel.querySelector('[data-kw]'), cmd: panel.querySelector('[data-cmd]'), log: panel.querySelector('[data-log]') }; function pill() { panel.style.setProperty('--pill', Math.ceil(panel.querySelector('h1').getBoundingClientRect().width + 74) + 'px'); } function showPanel(open, now) { cfg.open = open; save(); if (now) { panel.classList.add('wt-still'); requestAnimationFrame(function () { requestAnimationFrame(function () { panel.classList.remove('wt-still'); }); }); } pill(); panel.querySelector('[data-fold]').setAttribute('aria-label', open ? 'Collapse' : 'Expand'); panel.classList.toggle('wt-collapsed', !open); place(); } function mount() { if (HEADLESS) return; panel.style.display = location.pathname.startsWith('/~/') ? '' : 'none'; var host = [].filter.call(document.querySelectorAll('.wavezfm-stage-layer'), function (l) { return l.getClientRects().length; }).pop() || document.body; if (panel.parentNode !== host) host.appendChild(panel); } function place() { mount(); if (cfg.pos) { cfg.pos = { left: clamp(cfg.pos.left, 0, Math.max(0, window.innerWidth - 80)), top: clamp(cfg.pos.top, 0, Math.max(0, window.innerHeight - 30)) }; panel.style.right = 'auto'; panel.style.left = cfg.pos.left + 'px'; panel.style.top = cfg.pos.top + 'px'; placedAt = null; return; } panel.style.left = 'auto'; panel.style.top = TOP + 'px'; var rail = document.querySelector('[data-room-desktop-rail="true"]'); var box = rail && rail.offsetParent !== null ? rail.getBoundingClientRect() : null; var right = box && box.width > 0 ? Math.round(window.innerWidth - box.left + 8) : 16; if (right !== placedAt) { placedAt = right; panel.style.right = right + 'px'; } } function clamp(n, lo, hi) { return Math.max(lo, Math.min(hi, n)); } var drag = null; panel.addEventListener('pointerdown', function (e) { if (!e.target.closest('[data-drag]') || e.target.closest('button')) return; var box = panel.getBoundingClientRect(); drag = { dx: e.clientX - box.left, dy: e.clientY - box.top }; if (panel.setPointerCapture) panel.setPointerCapture(e.pointerId); e.preventDefault(); }); panel.addEventListener('pointermove', function (e) { if (!drag) return; cfg.pos = { left: Math.round(clamp(e.clientX - drag.dx, 0, window.innerWidth - 80)), top: Math.round(clamp(e.clientY - drag.dy, 0, window.innerHeight - 30)) }; place(); }); function endDrag() { if (drag) { drag = null; save(); } } panel.addEventListener('pointerup', endDrag); panel.addEventListener('pointercancel', endDrag); function paintToggle(id) { panel.querySelector('[data-toggle="' + id + '"]').setAttribute('aria-checked', !!cfg[id]); } function paintChips() { el.chips.innerHTML = cfg.keywords.map(function (k) { return `${html(k)} ×`; }).join(''); } function foldGroup(id, open) { cfg.sections[id] = open; save(); panel.querySelector('[data-group="' + id + '"]').classList.toggle('wt-shut', !open); } function paintLog() { el.log.innerHTML = activity.length ? activity.map(function (a) { return `
${html(a.at)}${html(a.text)}
`; }).join('') : '
Nothing yet
'; } function saveLog() { localStorage.setItem(ACTIVITY_KEY, JSON.stringify(activity)); } var FLAG = '(!) '; function away() { return document.hidden || !document.hasFocus(); } function desktop(text) { if (cfg.desktop === 'off' || (cfg.desktop === 'away' && !away())) return; if (away() && document.title.indexOf(FLAG) !== 0) document.title = FLAG + document.title; if (typeof GM_notification === 'function') GM_notification({ title: 'Wavez Tools', text: text, onclick: function () { window.focus(); } }); else if (window.Notification && Notification.permission === 'granted') new Notification('Wavez Tools', { body: text, tag: 'wavez-tools', renotify: true }); } function unflag() { if (!away() && document.title.indexOf(FLAG) === 0) document.title = document.title.slice(FLAG.length); } document.addEventListener('visibilitychange', unflag); window.addEventListener('focus', unflag); var noticeTimer = null; function notice(text, sound, quiet) { el.notice.textContent = text; log(text); if (sound) { play(); desktop(text); } if (!quiet) { activity.unshift({ at: new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }), text: text }); if (activity.length > ACTIVITY_MAX) activity.pop(); saveLog(); paintLog(); } clearTimeout(noticeTimer); noticeTimer = setTimeout(function () { el.notice.textContent = ''; }, 20000); } panel.addEventListener('click', function (e) { var t = e.target.closest('[data-toggle], [data-addon], [data-cog], button[data-aset], [data-reload], [data-fold], [data-fold-group], [data-test], [data-addkw], [data-run], [data-del], [data-clearlog], [data-reset]'); if (!t) return; if (window.Notification && Notification.permission === 'default') Notification.requestPermission(); if (t.dataset.cog) { var box = panel.querySelector('[data-aset-for="' + t.dataset.cog + '"]'); box.hidden = !box.hidden; t.setAttribute('aria-expanded', !box.hidden); } else if (t.dataset.addon) { var a = ADDON_LIST[t.dataset.addon]; a.flip(); t.setAttribute('aria-checked', a.on); notice(a.label + (a.on ? ' on' : ' off') + ', reload to apply', false, true); } else if (t.dataset.aset) { var on = t.getAttribute('aria-checked') !== 'true'; t.setAttribute('aria-checked', on); setAddon(t, on); } else if (t.hasAttribute('data-reload')) location.reload(); else if (t.dataset.toggle) { cfg[t.dataset.toggle] = !cfg[t.dataset.toggle]; save(); paintToggle(t.dataset.toggle); tick(); } else if (t.dataset.foldGroup) foldGroup(t.dataset.foldGroup, !cfg.sections[t.dataset.foldGroup]); else if (t.hasAttribute('data-clearlog')) { activity = []; saveLog(); paintLog(); } else if (t.hasAttribute('data-reset')) { cfg.pos = null; save(); place(); } else if (t.hasAttribute('data-fold')) showPanel(!cfg.open); else if (t.hasAttribute('data-test')) play(); else if (t.hasAttribute('data-addkw')) addKeyword(); else if (t.hasAttribute('data-run')) runCommand(el.cmd.value); else if (t.dataset.del) { cfg.keywords = cfg.keywords.filter(function (k) { return k !== t.dataset.del; }); save(); paintChips(); } }); panel.addEventListener('change', function (e) { if (e.target.dataset && e.target.dataset.aset) return setAddon(e.target, e.target.value); var name = e.target.dataset && e.target.dataset.set; if (!name) return; cfg[name] = name === 'boothAt' || name === 'leaveAfter' ? Number(e.target.value) : e.target.value; save(); }); panel.addEventListener('keydown', function (e) { if (e.key !== 'Enter') return; if (e.target === el.kw) addKeyword(); if (e.target === el.cmd) runCommand(el.cmd.value); if (e.target.dataset.foldGroup) foldGroup(e.target.dataset.foldGroup, !cfg.sections[e.target.dataset.foldGroup]); }); document.addEventListener('keydown', function (e) { if (!e.altKey || e.ctrlKey || e.metaKey || e.code !== 'KeyT') return; if (e.target.closest && e.target.closest('input, textarea, select, [contenteditable="true"]')) return; e.preventDefault(); showPanel(!cfg.open); }); var placedAt = null; window.addEventListener('resize', place); setInterval(place, 1000); function addKeyword() { var words = el.kw.value.split(',').map(function (w) { return w.trim(); }).filter(Boolean); words.forEach(function (w) { if (cfg.keywords.indexOf(w) === -1) cfg.keywords.push(w); }); el.kw.value = ''; save(); paintChips(); } paintChips(); paintLog(); showPanel(cfg.open, true); var api = null; var wootTimer = null; var wootKey = null; var wootAt = 0; var wootDelay = 1000; var joinAt = 0; var joinDelay = 2000; var myPlays = load(PLAYS_KEY, 0); var playingMine = false; var seenMehs = {}; var mehTally = load(MEHS_KEY, {}); var knownUsers = null; var lastBooth = null; var lastKey = load(LASTKEY_KEY, null); var lastRoom = null; var wasDj = null; var wasLocked = null; var hadWhisper = null; function state() { return api && api.room.getState(); } function pushHistory(id) { recent.push(id); if (recent.length > HISTORY_MAX) recent = recent.slice(-HISTORY_MAX); localStorage.setItem(HISTORY_KEY, JSON.stringify(recent)); } function autoWoot(s) { if (!cfg.autowoot || !s || !s.playback || !s.votes || !s.queue) return; var v = s.votes; if (s.playback.playbackKey !== wootKey) { wootKey = s.playback.playbackKey; wootAt = 0; wootDelay = 1000; } if (s.queue.isCurrentDj || v.clientVote || v.clientVotePending) return; if (v.trackId !== s.playback.trackId || !v.canVote) return; if (wootTimer || Date.now() < wootAt) return; wootTimer = setTimeout(function () { wootTimer = null; var now = state(); if (!cfg.autowoot || !now || !now.playback || !now.votes || !now.queue || now.playback.playbackKey !== wootKey) return; if (now.votes.clientVote || now.votes.clientVotePending || !now.votes.canVote || now.queue.isCurrentDj) return; wootAt = Date.now() + wootDelay; wootDelay = Math.min(wootDelay * 2, 15000); var res = api.actions.vote('woot'); if (res && res.ok) notice('\u2665 Wooted!', false, true); else notice('Woot failed: ' + (res && res.code)); }, delayFor(cfg.voteDelay)); } function autoJoin(s) { if (!cfg.autojoin || !s || !s.queue) return; var q = s.queue; if (q.isJoined || q.isCurrentDj || q.isLocked || q.isFull || !(s.permissions && s.permissions.joinQueue)) { joinDelay = 2000; return; } if (Date.now() < joinAt) return; var res = api.actions.joinQueue(); if (res && res.ok) { joinDelay = 2000; notice('Joined the queue'); return; } joinAt = Date.now() + joinDelay; joinDelay = Math.min(joinDelay * 2, 60000); } function countPlays(s, newTrack) { var me = s.currentUser && s.currentUser.username; var before = myPlays; var mine = !!(s.queue && s.queue.isCurrentDj) || !!(s.playback && me && String(s.playback.djUsername).toLowerCase() === me.toLowerCase()); if (newTrack) { if (playingMine) myPlays++; playingMine = mine; } else playingMine = playingMine || mine; if (s.queue && !s.queue.isJoined && !s.queue.isCurrentDj) myPlays = 0; if (myPlays !== before) localStorage.setItem(PLAYS_KEY, JSON.stringify(myPlays)); } function autoLeave(s) { if (!cfg.autoleave || !shouldLeave(myPlays, cfg.leaveAfter, s.queue)) return; var res = api.actions.leaveQueue(); if (!res || !res.ok) return; myPlays = 0; localStorage.setItem(PLAYS_KEY, '0'); if (cfg.autojoin) { cfg.autojoin = false; save(); paintToggle('autojoin'); } notice('Left the queue after ' + cfg.leaveAfter + ' play' + (cfg.leaveAfter === 1 ? '' : 's'), true); } function boothAlert(s) { if (!s || !s.queue || !s.currentUser) return; var mine = (s.queue.entries || []).filter(function (e) { return e.userId === s.currentUser.id; })[0]; if (!mine || s.queue.isCurrentDj) { lastBooth = null; return; } if (cfg.booth && boothHit(mine.position, cfg.boothAt, lastBooth)) notice('Booth alert - position ' + mine.position, true); lastBooth = mine.position; } function historyAlert(s) { if (!s || !s.playback) return; var ago = playedAgo(recent, s.playback.trackId); if (cfg.history && ago > 0) notice('Replay - played ' + ago + ' track' + (ago === 1 ? '' : 's') + ' ago', true); } function mehTracker(s) { if (!cfg.mehs || !s || !s.votes) return; var track = s.votes.trackId; if (!seenMehs[track]) { seenMehs = {}; seenMehs[track] = {}; } var names = {}; (s.users || []).concat((s.queue && s.queue.entries) || []).forEach(function (u) { names[u.id || u.userId] = u.displayUsername || u.username; }); (s.votes.mehUserIds || []).forEach(function (id) { if (seenMehs[track][id]) return; seenMehs[track][id] = true; var name = names[id] || id; mehTally[name] = (mehTally[name] || 0) + 1; localStorage.setItem(MEHS_KEY, JSON.stringify(mehTally)); notice(name + ' mehed (' + mehTally[name] + ' total)'); }); } function joinWatch(s) { if (!s || !s.users) return; var ids = {}; s.users.forEach(function (u) { ids[u.id] = u; }); if (knownUsers === null) { knownUsers = ids; return; } var joined = s.users.filter(function (u) { return !knownUsers[u.id]; }); knownUsers = ids; if (!cfg.joins) return; joined.filter(function (u) { return joinable(u, cfg.joinMode); }).forEach(function (u) { var t = (u.displayUsername || u.username) + ' joined'; notice(t); desktop(t); }); } function onChat(msg) { if (!cfg.mentions || !msg) return; var text = msg.content || msg.message || msg.text || ''; var u = msg.user; var from = msg.username || (u && (typeof u === 'string' ? u : u.displayUsername || u.username)) || 'someone'; var s = state(); var me = s && s.currentUser && s.currentUser.username; if (String(from).toLowerCase() === String(me).toLowerCase()) return; var hit = mentionHit(text, cfg.keywords, me, cfg.kwMatch === 'word'); if (hit) notice(from + ' said "' + hit + '"', true); } function turnAlert(s) { var dj = !!(s.queue && s.queue.isCurrentDj); if (cfg.turn && dj && wasDj === false) notice("You're up - your track is playing", true); wasDj = dj; } function unlockAlert(s) { if (!s.queue) return; var locked = !!s.queue.isLocked; if (cfg.unlock && wasLocked && !locked) notice('The queue is open', true); wasLocked = locked; } function whisperAlert() { var btn = document.querySelector('[data-wavezfm-room-footer-action="whispers"]'); if (!btn) return; var unread = !!btn.querySelector('span'); if (cfg.whispers && unread && hadWhisper === false) notice('New whisper', true); hadWhisper = unread; } new MutationObserver(whisperAlert).observe(document.body, { childList: true, subtree: true }); function text(node, t) { t = t == null ? '' : String(t); if (node.textContent !== t) node.textContent = t; } function paint(s) { if (!s) { text(el.track, 'Not in a room'); text(el.artist, ''); text(el.queue, 'Queue: -'); return; } text(el.track, s.playback ? s.playback.title : ''); text(el.artist, s.playback ? s.playback.artist : ''); if (!s.room) return; text(el.queue, 'Queue: ' + s.room.queueCount + ' \u00b7 ' + (s.room.queueLocked ? 'Locked' : 'Open')); } function tick() { var s = state(); paint(s); if (!s) return; var room = s.room && s.room.slug; if (room !== lastRoom) { lastRoom = room; knownUsers = null; lastBooth = null; seenMehs = {}; wasDj = null; wasLocked = null; } var key = s.playback && (s.playback.playbackKey || s.playback.trackId); countPlays(s, !!key && key !== lastKey); if (key && key !== lastKey) { lastKey = key; localStorage.setItem(LASTKEY_KEY, JSON.stringify(key)); historyAlert(s); pushHistory(s.playback.trackId); } autoWoot(s); autoLeave(s); autoJoin(s); boothAlert(s); turnAlert(s); unlockAlert(s); mehTracker(s); joinWatch(s); } var COMMANDS = { help: function () { return 'Commands: ' + Object.keys(COMMANDS).map(function (c) { return '/' + c; }).join(' '); }, np: function () { var s = state(); return s && s.playback ? s.playback.title + ' - ' + s.playback.artist + ' (dj ' + s.playback.djUsername + ')' : 'Nothing playing'; }, queue: function () { var s = state(); return s ? 'Queue ' + s.queue.count + (s.queue.isJoined ? ', you are in it' : '') + (s.queue.isLocked ? ', locked' : '') : 'Not in a room'; }, mehs: function () { var names = Object.keys(mehTally); return names.length ? names.map(function (n) { return n + ': ' + mehTally[n]; }).join(', ') : 'No mehs seen yet'; }, users: function () { var s = state(); return s ? s.users.length + ' in the room' : 'Not in a room'; }, woot: function () { var r = api.actions.vote('woot'); return r.ok ? 'Wooted' : 'Failed: ' + r.code; }, meh: function () { var r = api.actions.vote('meh'); return r.ok ? 'Mehed' : 'Failed: ' + r.code; }, join: function () { var r = api.actions.joinQueue(); return r.ok ? 'Joined' : 'Failed: ' + r.code; }, leave: function () { var r = api.actions.leaveQueue(); return r.ok ? 'Left' : 'Failed: ' + r.code; }, vol: function (arg) { if (!/^\d+(\.\d+)?$/.test(arg)) return 'Usage: /vol '; var r = api.actions.setVolume(Number(arg)); return r.ok ? 'Volume ' + Number(arg) : 'Failed: ' + r.code; }, say: function (arg) { if (!arg) return 'Usage: /say '; var r = api.actions.sendChat(arg); return r.ok ? 'Sent' : 'Failed: ' + r.code; }, history: function () { return recent.length + ' tracks remembered'; }, clear: function () { recent = []; localStorage.removeItem(HISTORY_KEY); mehTally = {}; localStorage.removeItem(MEHS_KEY); activity = []; saveLog(); paintLog(); return 'History, meh tally and activity cleared'; }, }; function runCommand(line) { var parts = String(line || '').replace(/^\//, '').trim().split(/\s+(.*)/); var fn = COMMANDS[parts[0].toLowerCase()]; notice(!fn ? 'Unknown command - try /help' : !api ? 'Bridge not ready' : fn(parts[1] || '')); el.cmd.value = ''; } function init(bridge) { api = bridge; ['playback_changed', 'votes_changed', 'queue_changed', 'users_changed', 'room_changed', 'social_changed'].forEach(function (e) { api.room.subscribe(e, tick); }); api.room.subscribe('chat_message', onChat); setInterval(tick, 5000); tick(); log('ready - window.WavezTools for scripting'); } window.WavezTools = { cfg: cfg, run: runCommand, mehs: function () { return mehTally; }, activity: function () { return activity; }, state: state, panel: showPanel, test: play, helpers: { mentionHit: mentionHit, playedAgo: playedAgo, boothHit: boothHit, joinable: joinable, shouldLeave: shouldLeave, html: html, delayFor: delayFor } }; var tries = 0; var wait = setInterval(function () { var bridge = window.WavezFM; if (bridge && bridge.version === '1') { clearInterval(wait); init(bridge); } else if (++tries === 40) el.track.textContent = 'Bridge not found'; }, 500); })(); }); })();