-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathBatchAddRecordingAliases.user.js
More file actions
329 lines (272 loc) · 9.88 KB
/
BatchAddRecordingAliases.user.js
File metadata and controls
329 lines (272 loc) · 9.88 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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*
* Built using mbz-loujine-common.js by loujine
* https://github.com/loujine/musicbrainz-scripts
* MIT License
*/
/* global $ helper edits sidebar requests GM_info aliases */
'use strict';
// ==UserScript==
// @name Batch Add Recording Aliases from another Release
// @namespace YoGo9
// @author YoGo9
// @version 12/26/25
// @description Paste a source release URL/MBID; copy its track titles as recording aliases on the current (target) release's recordings.
// @homepage https://github.com/YoGo9/Scripts
// @updateURL https://raw.githubusercontent.com/YoGo9/Scripts/main/BatchAddRecordingAliases.user.js
// @downloadURL https://raw.githubusercontent.com/YoGo9/Scripts/main/BatchAddRecordingAliases.user.js
// @require https://raw.githubusercontent.com/loujine/musicbrainz-scripts/master/mbz-loujine-common.js
// @include http*://musicbrainz.org/release/*
// @include http*://beta.musicbrainz.org/release/*
// @exclude http*://*musicbrainz.org/doc/*
// @grant GM_info
// @run-at document-end
// ==/UserScript==
'use strict';
if (!/^\/release\/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(location.pathname)) {
return;
}
(function () {
const HOST = location.origin;
const WS_HOST = 'https://musicbrainz.org';
const RELEASE_MBID_RE = /\/release\/([0-9a-f-]{36})/i;
const UUID_RE = /^[0-9a-f-]{36}$/i;
function parseReleaseMbid(input) {
const s = String(input || '').trim();
if (UUID_RE.test(s)) return s;
const m = s.match(RELEASE_MBID_RE);
return m ? m[1] : null;
}
function currentReleaseMbid() {
const m = location.pathname.match(RELEASE_MBID_RE);
return m ? m[1] : null;
}
async function wsRelease(releaseMbid) {
const url = `${WS_HOST}/ws/2/release/${releaseMbid}?inc=recordings+media&fmt=json`;
const r = await fetch(url, { headers: { Accept: 'application/json' } });
if (!r.ok) throw new Error(`WS fetch failed ${r.status} for release ${releaseMbid}`);
return r.json();
}
function flattenTracks(releaseJson) {
const out = [];
for (const medium of (releaseJson.media || [])) {
const mPos = medium.position;
for (const track of (medium.tracks || [])) {
out.push({
mediumPosition: mPos,
trackPosition: track.position,
trackTitle: track.title,
recordingMbid: track.recording?.id || null,
recordingTitle: track.recording?.title || null,
});
}
}
return out;
}
function mapByRecording(tracks) {
const m = new Map();
for (const t of tracks) {
if (t.recordingMbid) m.set(t.recordingMbid, t.trackTitle);
}
return m;
}
function mapByPosition(tracks) {
const m = new Map();
for (const t of tracks) {
m.set(`${t.mediumPosition}-${t.trackPosition}`, t.trackTitle);
}
return m;
}
function esc(s) {
return String(s ?? '').replace(/[&<>"']/g, c => (
{ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]
));
}
function editNote(sourceReleaseUrl) {
return `Batch Add Recording Alias from release ${sourceReleaseUrl}`;
}
function injectUI() {
const box = document.createElement('div');
box.style.border = '1px solid #ccc';
box.style.padding = '10px';
box.style.margin = '10px 0';
box.style.background = '#fff';
box.innerHTML = `
<div style="display:flex; gap:8px; align-items:center; flex-wrap:wrap;">
<span style="font-weight:600;">Copy track titles → recording aliases</span>
<input id="yomo-src" style="width:520px; max-width:100%;" placeholder="Paste SOURCE release URL or MBID">
<label style="display:flex; gap:6px; align-items:center;">
Type:
<span id="yomo-type-wrap">${aliases.type}</span>
</label>
<label style="display:flex; gap:6px; align-items:center;">
Locale:
<input id="yomo-locale" style="width:70px;" value="en">
</label>
<label style="display:flex; gap:6px; align-items:center;">
<input id="yomo-primary" type="checkbox">
Primary
</label>
<button id="yomo-preview" type="button">Preview</button>
<button id="yomo-submit" type="button" disabled>Submit</button>
</div>
<div id="yomo-status" style="margin-top:8px; white-space:pre-wrap;"></div>
<div id="yomo-table" style="margin-top:8px; max-height:320px; overflow:auto;"></div>
`;
(document.querySelector('#content') || document.body).prepend(box);
// Ensure the select has a stable ID we can read
const typeSel = box.querySelector('#yomo-type-wrap select');
if (typeSel) typeSel.id = 'yomo-type';
return box;
}
function setStatus(msg) {
const el = document.getElementById('yomo-status');
if (el) el.textContent = msg;
}
function render(rows) {
const wrap = document.getElementById('yomo-table');
if (!wrap) return;
wrap.innerHTML = `
<table class="tbl" style="width:100%;">
<thead>
<tr>
<th>Medium</th>
<th>#</th>
<th>Recording</th>
<th>Alias</th>
<th>Status</th>
</tr>
</thead>
<tbody>
${rows.map((r, i) => `
<tr data-idx="${i}">
<td>${esc(r.mediumPosition)}</td>
<td>${esc(r.trackPosition)}</td>
<td>
<a href="${HOST}/recording/${r.recordingMbid}" target="_blank" rel="noreferrer noopener">
${esc(r.recordingTitle || '(recording)')}
</a>
<div style="opacity:.65; font-size:11px;">${esc(r.recordingMbid)}</div>
</td>
<td>${esc(r.aliasName)}</td>
<td class="st" title="${esc(r.matchType)}"></td>
</tr>
`).join('')}
</tbody>
</table>
`;
}
function submitOneAlias({ recordingMbid, aliasName, locale, primary, typeId, sourceUrl }, onOk, onFail) {
const postData = {
name: edits.encodeName(aliasName),
sort_name: edits.encodeName(aliasName),
locale: locale,
primary_for_locale: primary ? 1 : 0,
edit_note: editNote(sourceUrl),
};
// Only send type_id if the user selected one (blank means default)
if (typeId) {
postData.type_id = typeId;
}
requests.POST(
`${HOST}/recording/${recordingMbid}/add-alias`,
edits.formatEdit('edit-alias', postData),
xhr => onOk(xhr),
xhr => onFail(xhr)
);
}
async function buildRows(sourceInput) {
const srcMbid = parseReleaseMbid(sourceInput);
if (!srcMbid) throw new Error('Could not parse SOURCE release MBID from input.');
const tgtMbid = currentReleaseMbid();
if (!tgtMbid) throw new Error('Could not parse TARGET release MBID from current page.');
const srcUrlNormalized = sourceInput.trim().startsWith('http')
? sourceInput.trim()
: `${HOST}/release/${srcMbid}`;
setStatus('Fetching releases from WS…');
const [src, tgt] = await Promise.all([wsRelease(srcMbid), wsRelease(tgtMbid)]);
const srcTracks = flattenTracks(src);
const tgtTracks = flattenTracks(tgt);
const byRec = mapByRecording(srcTracks);
const byPos = mapByPosition(srcTracks);
const rows = [];
for (const t of tgtTracks) {
if (!t.recordingMbid) continue;
let aliasName = byRec.get(t.recordingMbid);
let matchType = 'recording';
// Fallback if recordings differ (not ideal but better than nothing)
if (!aliasName) {
aliasName = byPos.get(`${t.mediumPosition}-${t.trackPosition}`);
matchType = aliasName ? 'position' : 'none';
}
if (!aliasName) continue;
rows.push({
mediumPosition: t.mediumPosition,
trackPosition: t.trackPosition,
recordingMbid: t.recordingMbid,
recordingTitle: t.recordingTitle,
aliasName,
matchType,
sourceUrl: srcUrlNormalized,
});
}
return rows;
}
function run() {
if (!helper.isUserLoggedIn()) return;
const ui = injectUI();
let lastRows = null;
ui.querySelector('#yomo-preview').addEventListener('click', async () => {
try {
const srcInput = ui.querySelector('#yomo-src').value;
lastRows = await buildRows(srcInput);
setStatus(`Preview ready. ${lastRows.length} aliases found to add.`);
render(lastRows);
ui.querySelector('#yomo-submit').disabled = lastRows.length === 0;
} catch (e) {
console.error(e);
setStatus(`Preview failed: ${e.message}`);
}
});
ui.querySelector('#yomo-submit').addEventListener('click', async () => {
if (!lastRows || !lastRows.length) return;
const locale = (ui.querySelector('#yomo-locale').value || 'en').trim() || 'en';
const primary = !!ui.querySelector('#yomo-primary').checked;
const typeId = ui.querySelector('#yomo-type')?.value || '';
setStatus(`Submitting ${lastRows.length} alias edits…`);
const trs = Array.from(document.querySelectorAll('#yomo-table tbody tr'));
// Send sequentially to be gentle
let i = 0;
const next = () => {
if (i >= lastRows.length) {
setStatus('Done.');
return;
}
const row = lastRows[i];
const st = trs[i]?.querySelector('.st');
if (st) st.textContent = 'Sending…';
submitOneAlias(
{
recordingMbid: row.recordingMbid,
aliasName: row.aliasName,
locale,
primary,
typeId,
sourceUrl: row.sourceUrl,
},
(xhr) => {
if (st) st.textContent = `OK (HTTP ${xhr.status})`;
i += 1;
setTimeout(next, 400);
},
(xhr) => {
if (st) st.textContent = `Error (HTTP ${xhr.status})`;
i += 1;
setTimeout(next, 400);
}
);
};
next();
});
}
$(document).ready(run);
})();