-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplay-chart-songs.user.js
More file actions
241 lines (214 loc) · 6.85 KB
/
play-chart-songs.user.js
File metadata and controls
241 lines (214 loc) · 6.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// ==UserScript==
// @name RateYourMusic Chart Song Player
// @namespace https://github.com/dbeley/rym-userscripts
// @version 1.2.0
// @description Adds a play button to each RYM song chart entry and opens a YouTube search for the song.
// @author dbeley
// @match https://rateyourmusic.com/charts/top/song/*
// @match https://rateyourmusic.com/charts/popular/song/*
// @match https://rateyourmusic.com/charts/esoteric/song/*
// @match https://rateyourmusic.com/charts/diverse/song/*
// @grant GM_xmlhttpRequest
// @grant GM.xmlHttpRequest
// @connect youtube.com
// @connect www.youtube.com
// ==/UserScript==
(function () {
"use strict";
const CONFIG = {
youtube: {
openInNewTab: true,
extraTerms: "audio",
autoPlayFirstResult: true,
},
};
const SELECTORS = {
chartItem: ".page_charts_section_charts_item.object_song",
title:
".page_charts_section_charts_item_title .ui_name_locale_original, .page_charts_section_charts_item_title .ui_name_locale",
artist: ".page_charts_section_charts_item_credited_text a.artist",
actionTarget: ".page_charts_section_charts_top_line_title_artist",
};
function init() {
injectStyles();
enhanceExistingItems();
observeNewItems();
}
function injectStyles() {
const style = document.createElement("style");
style.textContent = `
.rym-play-button {
margin-left: 0.65rem;
padding: 0.2rem 0.6rem;
border-radius: 999px;
border: 1px solid var(--color-border, #a1a1a1);
background: var(--color-background-secondary, #fafafa);
font-size: 0.8rem;
cursor: pointer;
transition: transform 0.15s ease, opacity 0.15s ease;
}
.rym-play-button:hover {
transform: scale(1.03);
}
.rym-play-button:disabled {
opacity: 0.6;
cursor: progress;
}
`;
document.head.appendChild(style);
}
function enhanceExistingItems() {
document.querySelectorAll(SELECTORS.chartItem).forEach(addButtonToItem);
}
function observeNewItems() {
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
mutation.addedNodes.forEach((node) => {
if (!(node instanceof HTMLElement)) {
return;
}
if (node.matches?.(SELECTORS.chartItem)) {
addButtonToItem(node);
} else {
node
.querySelectorAll?.(SELECTORS.chartItem)
.forEach(addButtonToItem);
}
});
});
});
observer.observe(document.body, { childList: true, subtree: true });
}
function addButtonToItem(item) {
if (item.dataset.rymPlayButtonAttached === "true") {
return;
}
const song = extractSongData(item);
if (!song.title || !song.artist) {
return;
}
const target =
item.querySelector(SELECTORS.actionTarget) ||
item.querySelector(".page_charts_section_charts_item_title");
if (!target) {
return;
}
const button = document.createElement("button");
button.type = "button";
button.className = "rym-play-button";
button.textContent = "▶ Play";
button.title = "Open a YouTube search for this song";
button.addEventListener("click", () => handlePlayClick(song, button));
target.appendChild(button);
item.dataset.rymPlayButtonAttached = "true";
}
function extractSongData(item) {
const titleElement = item.querySelector(SELECTORS.title);
const artistElements = item.querySelectorAll(SELECTORS.artist);
return {
title: titleElement ? sanitizeText(titleElement.textContent) : "",
artist:
artistElements.length > 0
? sanitizeText(
Array.from(artistElements)
.map((el) => el.textContent)
.join(" ")
)
: "",
};
}
function sanitizeText(text) {
return (text || "").replace(/\s+/g, " ").trim();
}
async function handlePlayClick(song, button) {
setButtonBusy(button, true);
try {
const query = buildYouTubeQuery(song);
const searchUrl = buildYouTubeSearchUrl(query);
const directVideoUrl = CONFIG.youtube.autoPlayFirstResult
? await fetchTopYouTubeResult(searchUrl)
: null;
const targetUrl = directVideoUrl || searchUrl;
window.open(
targetUrl,
CONFIG.youtube.openInNewTab ? "_blank" : "_self",
"noopener"
);
} finally {
setButtonBusy(button, false);
}
}
function setButtonBusy(button, isBusy) {
button.disabled = isBusy;
if (isBusy) {
button.dataset.originalText = button.textContent;
button.textContent = "Loading...";
} else if (button.dataset.originalText) {
button.textContent = button.dataset.originalText;
delete button.dataset.originalText;
}
}
function buildYouTubeQuery(song) {
return `${song.artist} ${song.title} ${CONFIG.youtube.extraTerms || ""}`
.replace(/\s+/g, " ")
.trim();
}
function buildYouTubeSearchUrl(query) {
return `https://www.youtube.com/results?search_query=${encodeURIComponent(query)}`;
}
async function fetchTopYouTubeResult(searchUrl) {
if (!canUseGmRequest()) {
return null;
}
try {
const responseText = await gmGet(searchUrl);
const videoId = extractFirstVideoId(responseText);
return videoId ? `https://www.youtube.com/watch?v=${videoId}` : null;
} catch (error) {
console.warn(
"[RYM Play Button] Unable to fetch first YouTube result:",
error
);
return null;
}
}
function extractFirstVideoId(responseText) {
const match = responseText.match(/"videoId":"([a-zA-Z0-9_-]{11})"/);
return match ? match[1] : null;
}
function gmGet(url) {
return new Promise((resolve, reject) => {
const details = {
method: "GET",
url,
headers: {
Accept: "text/html",
},
onload: (response) => resolve(response.responseText),
onerror: reject,
ontimeout: () => reject(new Error("Request timed out")),
};
if (typeof GM_xmlhttpRequest === "function") {
GM_xmlhttpRequest(details);
} else if (
typeof GM !== "undefined" &&
typeof GM.xmlHttpRequest === "function"
) {
GM.xmlHttpRequest(details);
} else {
reject(new Error("GM_xmlhttpRequest is not available"));
}
});
}
function canUseGmRequest() {
return (
typeof GM_xmlhttpRequest === "function" ||
(typeof GM !== "undefined" && typeof GM.xmlHttpRequest === "function")
);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
})();