-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.html
1102 lines (980 loc) · 37 KB
/
index.html
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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>kepstin’s MagicISRC</title>
<link rel="stylesheet" href="bootstrap.css">
<link rel="stylesheet" href="fonts.css">
<script type="text/javascript">
"use strict";
// Disable automatic scroll restoration where possible, the app handles it.
if ('scrollRestoration' in history) { history.scrollRestoration = 'manual'; }
// Configuration
var mb_site = new URL("https://musicbrainz.org/");
var mb_ws2_base = new URL("ws/2/", mb_site);
var mb_client = "kepstin-magicisrc";
var mb_oauth_base = new URL("oauth2/", mb_site);
var mb_oauth_redirect_uri = "https://magicisrc.kepstin.ca/";
var mb_oauth_client_id = "oxqZoCJWy9BQXgS7UTikeA";
var mb_oauth_client_secret = "tbE6uiFKK8wBmO6cq2Pg0Q"; // Not so secret after all, are you?
// Internal State
// Information about currently logged in user - auth token and user info
var login = {};
// ID of the release to operate on
var mbid = null;
// Set to true if MBID parsing fails
var mbidInvalid = false;
// A cached copy of the current release info fetched from MusicBrainz
var currentRelease = {};
// The list of ISRCs to be added. Structure is as follows:
// Array of media, each containing:
// Array of tracks, each containing:
// Object, with properties:
// isrc: The ISRC string
// invalid: Boolean, true if ISRC cannot be submitted
// checks: Array of check results, each containing:
// Object, with properties:
// type: One of "danger", "warning", "info"
// message: A human-readable check message
var isrcs = null;
// List of ISRCs for pregap tracks. Structure is as follows:
// Array of media, each containing:
// Object, with properties:
// (same as in `isrcs`)
var pregapISRCs = null;
// Edit note to include with ISRC submission edit
var editNote = "";
// True if any ISRCs are valid, and the edit preview should be shown
var anyISRCsValid = false;
// State from the most recently popped history
var poppedState = null;
// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(self){
var cache = {};
self.tmpl = function tmpl(str, data){
// Figure out if we're getting a template, or if we need to
// load the template - and be sure to cache the result.
var fn = !/\W/.test(str) ?
cache[str] = cache[str] ||
tmpl(document.getElementById(str).innerHTML) :
// Generate a reusable function that will serve as a template
// generator (and which will be cached).
new Function("obj",
"var p=[],print=function(){p.push.apply(p,arguments);};" +
// Introduce the data as local variables using with(){}
"with(obj){p.push('" +
// Convert the template into pure JavaScript
str
.replace(/[\r\t\n]/g, " ")
.split("<%").join("\t")
.replace(/((^|%>)[^\t]*)'/g, "$1\r")
.replace(/\t=(.*?)%>/g, "',$1,'")
.split("\t").join("');")
.split("%>").join("p.push('")
.split("\r").join("\\'")
+ "');}return p.join('');");
// Provide some basic currying to the user
return data ? fn( data ) : fn;
};
})(window);
(function(self) {
var entityMap = { "&": "&", "<": "<", ">": ">", '"': '"', "'": ''', "/": '/' };
self.escapeHtml = function escapeHtml(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
};
})(window);
function bufferToHex(buffer) {
return Array
.from (new Uint8Array (buffer))
.map (b => b.toString (16).padStart (2, "0"))
.join ("");
}
function generateStateId() {
var stateArray = new Uint8Array(16);
crypto.getRandomValues(stateArray);
return bufferToHex(stateArray);
}
function bufferToBase64Url(buffer) {
return btoa(String.fromCharCode.apply(null, buffer))
.split("=", 1)[0]
.replace(/\+/g, '-')
.replace(/\//g, '_');
}
function generateCodeVerifier() {
var codeVerifierArray = new Uint8Array(32);
crypto.getRandomValues(codeVerifierArray);
return bufferToBase64Url(codeVerifierArray);
}
async function generateS256CodeChallenge(codeVerifier) {
var codeVerifierArray = new Uint8Array(codeVerifier.split("").map(c => c.charCodeAt(0)));
var codeChallengeArray = new Uint8Array(await crypto.subtle.digest("SHA-256", codeVerifierArray));
return bufferToBase64Url(codeChallengeArray);
}
var query = {};
var errors = [];
// Return the full URL for the location indicated by params
function updateLocation(params) {
var location = new URL(window.location.href);
if (params == "") {
location.search = "";
} else {
location.search = "?" + params;
}
return location;
}
// Perform a navigation to a new state, represented by a set of URL search
// parameters. This pushes the new URL as a new history item, and then
// loads the page as if it was just navigated to.
function pushState(params) {
window.history.replaceState({scrollX: window.scrollX, scrollY: window.scrollY}, "", window.location.href);
window.history.pushState({scrollX: 0, scrollY: 0}, "", updateLocation(params));
onPopState();
}
// Update the URL for an existing state.
// This is used to save parameter cleanup values, primarily. Unlike pushState
// it does not trigger a page load
function replaceState(params) {
window.history.replaceState(null, "", updateLocation(params));
}
function onPopState(event) {
errors = [];
console.log("New location: " + window.location);
if (event) {
poppedState = event.state;
} else {
poppedState = window.history.state;
}
console.log("poppedState", poppedState);
let params = new URLSearchParams(window.location.search);
loadState(params);
}
function loadState(params) {
checkLogin();
checkMbid(params);
if (params.has("state") && (params.has("code") || params.has("error"))) {
// This is the OAuth callback
handleLoginCallback(params);
} else if (params.has("submit")) {
handleSubmit(params);
} else if (mbid && !mbidInvalid) {
handleRelease(params);
} else {
// Fallback: render index page
renderIndex(params);
}
}
function checkLogin() {
login = JSON.parse(window.localStorage.getItem("mb_login"));
// Ensure that login is always a hash
if (!login) { login = {} }
console.log("login", login);
// Clear expired login credentials
if (login.expires <= new Date().getTime()) {
login = {};
window.localStorage.removeItem("mb_login");
}
renderNavbar();
}
function checkMbid(params) {
// Check for the "mbid" parameter
mbid = params.get("mbid");
mbidInvalid = true;
if (!mbid || mbid == "") {
// "mbid" isn't found. Let's check for the alias
mbid = params.get("musicbrainzid");
params.delete("musicbrainzid");
}
if (!mbid || mbid == "") {
mbid = null;
mbidInvalid = false;
return;
}
let newMbid = parseMbid(mbid);
if (newMbid) {
mbid = newMbid;
mbidInvalid = false;
params.set("mbid", mbid);
replaceState(params);
return;
}
}
function parseMbid(str) {
let match = str.match(/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/);
if (match && match[1]) {
return match[1];
}
return null;
}
function checkISRCs(release, params) {
isrcs = [];
pregapISRCs = [];
anyISRCsValid = false;
let isrcHistory = {};
// Initialize ISRC history with existing ISRCs on the release
for (const medium of release.media) {
// Mediums from Musicbrainz with no tracks don't include the "tracks"
// property in the response at all; provide an empty array instead.
if (!medium.tracks) { medium.tracks = []; }
if (medium.pregap) {
for (const isrc of medium.pregap.recording.isrcs) {
isrcHistory[isrc] = {medium: `${medium.format ?? "Medium"} ${medium.position}`, track: medium.pregap.number};
}
}
for (const track of medium.tracks) {
for (const isrc of track.recording.isrcs) {
isrcHistory[isrc] = {medium: `${medium.format ?? "Medium"} ${medium.position}`, track: track.number};
}
}
}
var linearcount = 0;
for (const [i, medium] of release.media.entries()) {
isrcs[i] = [];
pregapISRCs[i] = null;
if (medium.pregap) {
let isrc = params.get(`isrc${medium.position}-${medium.pregap.position}`);
let checkedISRC;
if (isrc) {
checkedISRC = checkOneISRC(isrc, medium, medium.pregap, isrcHistory);
if (checkedISRC.isrc && !checkedISRC.invalid) {
anyISRCsValid = true;
}
} else {
checkedISRC = {isrc: null, invalid: false, checks: []};
}
pregapISRCs[i] = checkedISRC;
}
for (const [j, track] of medium.tracks.entries()) {
linearcount++;
let isrc = params.get(`isrc${medium.position}-${track.position}`);
if (!isrc) { isrc = params.get(`isrc${linearcount}`); }
let checkedISRC;
if (isrc) {
checkedISRC = checkOneISRC(isrc, medium, track, isrcHistory);
if (checkedISRC.isrc && !checkedISRC.invalid) {
anyISRCsValid = true;
}
} else {
checkedISRC = {isrc: null, invalid: false, checks: []};
}
isrcs[i][j] = checkedISRC;
}
}
console.log(pregapISRCs, isrcs);
}
/* https://isrc.ifpi.org/downloads/ISRC_Bulletin-2015-01.pdf Updated July 20 2022 */
/* https://isrc.ifpi.org/downloads/Valid_Characters.pdf June 2024 */
var ccodesUpdated = '2024-06-07';
var ccodes = [
'AL', 'DZ', 'AD', 'AO', 'AI', 'AG', 'AR', 'AM', 'AW', 'AU', 'AT', 'AZ',
'BS', 'BH', 'BD', 'BB', 'BY', 'BE', 'BZ', 'BM', 'BO', 'BA', 'BR', 'BP',
'BX', 'BC', 'BK', 'BG', 'BF',
'CM', 'CA', 'CB', 'KY', 'CL', 'CN', 'TW', 'CO', 'CD', 'CI', 'HR', 'CU', 'CW',
'CY', 'CZ',
'DK', 'GL', 'FO', 'DM', 'DO',
'EC', 'EG', 'SV', 'EE', 'ET',
'FJ', 'FI', 'FR', 'FX', 'PF',
'GM', 'GE', 'DE', 'GH', 'GI', 'GR', 'GD', 'GT', 'GG', 'GY',
'HT', 'HN', 'HK', 'HU',
'IS', 'IN', 'ID', 'IR', 'IQ', 'IE', 'IL', 'IT',
'JM', 'JP', 'JE', 'JO',
'KZ', 'KE', 'KR', 'KS', 'XK',
'LA', 'LV', 'LB', 'LS', 'LI', 'LT', 'LU',
'MO', 'MK', 'MW', 'MY', 'MV', 'MT', 'MU', 'MX', 'MD', 'MC', 'ME', 'MS',
'MA', 'MZ',
'NA', 'NP', 'NL', 'NZ', 'NG', 'MP', 'NO',
'PK', 'PA', 'PG', 'PY', 'PE', 'PH', 'PL', 'PT', 'PR',
'QA',
'RO', 'RU',
'KN', 'LC', 'VC', 'SM', 'SA', 'SN', 'RS', 'SC', 'SL', 'SG', 'SX', 'SK',
'SI', 'SB', 'ZA', 'ZB', 'ES', 'LK', 'SZ', 'SE', 'CH',
'TZ', 'TH', 'TO', 'TT', 'TN', 'TR', 'DG',
'UG', 'UA', 'AE', 'GB', 'UK', 'GX', 'US', 'QM', 'QT', 'QZ', 'UY', 'UZ',
'VU', 'VE', 'VN', 'VG',
'ZM', 'ZW',
'TC', /* TuneCore */
'CP', 'DG', 'QN', 'ZZ', /* Worldwide IIRA direct allocations */
'CS', 'YU' /* Historical */
];
function checkOneISRC(isrc, medium, track, isrcHistory) {
let checks = [];
// Normalize ISRC formatting
isrc = isrc.trim().replace(/[\s\.+-]/g, '').toUpperCase();
// Ignore blank ISRCs
if (isrc == '') {
return {isrc: null, invalid: false, checkType: "", checks: checks};
}
// Parse the ISRC fields
const match = isrc.match(/^([A-Z]{2})([A-Z0-9]{3})([0-9]{2})([0-9]{5})$/);
if (!match) {
checks.push({type: "danger", message: "ISRC is malformed"});
return {isrc: isrc, invalid: true, checkType: "danger", checks: checks};
}
const [, country, registrant, year, designation] = match;
let invalid = false;
if ((country == 'US' && registrant == 'S1Z') ||
(country == 'JM' && registrant == 'K40') ||
(country == 'NZ' && registrant == 'AA0')) {
checks.push({type: "danger", message: `${country} registration code “${registrant}” is reserved for documentation`});
invalid = true;
}
if (ccodes.indexOf(country) === -1) {
checks.push({type: "danger", message: `${country} is not allocated by the IFPI (last updated ${ccodesUpdated})`});
}
if (registrant == '000') {
checks.push({type: "warning", message: `Registrant code “${registrant}” may indicate blank or dummy data`});
}
if (country == 'CS' && (year > 6 && year < 86)) {
checks.push({type: "warning", message: "CS is a historical code for Serbia & Montenegro – recordings prior to 2006 only"});
}
if (country == 'YU' && (year > 3 && year < 86)) {
checks.push({type: "warning", message: "YU is a historical code for Yugoslavia – recordings prior to 2003 only"});
}
// Add a message if the ISRC was already present
if (track.recording.isrcs.indexOf(isrc) != -1) {
checks.push({type: "info", message: "This ISRC is already attached to this track (it will be skipped)"});
invalid = true;
// Check for duplicate ISRCs
} else if (isrcHistory[isrc]) {
checks.push({type: "warning", message: `This ISRC is repeated from ${isrcHistory[isrc].medium} track ${isrcHistory[isrc].track}`});
}
isrcHistory[isrc] = {medium: `${medium.format ?? "Medium"} ${medium.position}`, track: track.number};
if (country == 'PR') {
checks.push({type: "info", message: "PR is a historical allocation for Puerto Rico, new recordings are expected to be US/QM/QZ"});
}
if (country == 'TC') {
checks.push({type: "info", message: "TC is allocated to TuneCore - Turks and Caicos Islands use DG"});
}
return {
isrc: isrc,
invalid: invalid,
checkType: checks.length > 0 ? checks[0].type : "success",
checks: checks
};
}
function doLogin() {
var stateId = generateStateId();
var codeVerifier = generateCodeVerifier();
var state = {
stateId: stateId,
date: new Date().getTime(),
params: new URL(window.location).searchParams.toString(),
codeVerifier: codeVerifier
};
window.sessionStorage.setItem("mb_oauth_state", JSON.stringify(state));
console.log("saved state:", state);
generateS256CodeChallenge(codeVerifier).then(codeChallenge => {
var url = new URL("authorize", mb_oauth_base);
var params = url.searchParams;
params.set("response_type", "code");
params.set("client_id", mb_oauth_client_id);
params.set("redirect_uri", mb_oauth_redirect_uri);
params.set("scope", "profile submit_isrc");
params.set("approval_prompt", "force");
params.set("state", stateId);
params.set("code_challenge", codeChallenge);
params.set("code_challenge_method", "S256");
window.location = url;
});
}
function handleLoginCallback(params) {
renderLoginProgress();
var stateId = params.get('state');
var state = JSON.parse(window.sessionStorage.getItem("mb_oauth_state"));
if (state["stateId"] != stateId) {
return renderError("State returned from OAuth2 callback did not match saved state.", null);
}
var code = params.get('code');
if (!code) {
return renderError("OAuth2 callback did not return a code. Error: " + params.get("error_description"), null);
}
console.log("restored state:", state);
// Fetch the auth token and userinfo
fetchAccessToken(state, code)
.catch(error => { renderError("When fetching OAuth2 token: " + error, error) })
.then(fetchUserinfo)
.catch(error => { renderError("When fetching OAuth2 userinfo: " + error, error) })
.then(() => {
// We want to do a full navigation here, so that a reload won't try
// to fetch the access token again
window.location = updateLocation(new URLSearchParams(state["params"]));
});
}
function fetchAccessToken(state, code) {
var url = new URL("token", mb_oauth_base);
var data = new URLSearchParams();
data.set("grant_type", "authorization_code");
data.set("code", code);
data.set("client_id", mb_oauth_client_id);
data.set("client_secret", mb_oauth_client_secret);
data.set("redirect_uri", mb_oauth_redirect_uri);
data.set("code_verifier", state.codeVerifier);
return window.fetch(url, { method: "POST", body: data })
.then(resolveOauthResponse)
.then(response => {
login = {
accessToken: response["access_token"],
expires: new Date().getTime() + (response["expires_in"] * 1000)
};
window.localStorage.setItem("mb_login", JSON.stringify(login));
});
}
function fetchUserinfo() {
var url = new URL("userinfo", mb_oauth_base);
return window.fetch(url, { headers: { "Authorization": "Bearer " + login["accessToken"] } })
.then(resolveOauthResponse)
.then(response => {
login["userInfo"] = response;
window.localStorage.setItem("mb_login", JSON.stringify(login));
});
}
function checkEditNote(params) {
editNote = params.get("edit-note") || "";
}
function handleRelease(params) {
renderReleaseProgress();
checkEditNote(params);
fetchRelease(mbid)
.then(release => {
checkISRCs(release, params);
renderRelease(release);
}, error => {
renderError("When fetching MusicBrainz release: " + error, error);
})
.catch(error => {
renderError("When displaying MusicBrainz release: " + error, error);
});
}
function fetchRelease(mbid) {
// Check if the loaded release is the right one; if so, just use it.
if (currentRelease.id == mbid) {
return Promise.resolve(currentRelease);
}
// Load data for the requested release
var url = new URL("release/" + mbid, mb_ws2_base);
var params = url.searchParams;
params.set("fmt", "json");
params.set("inc", "artist-credits+isrcs+labels+recordings");
return window.fetch(url)
.then(resolveWs2ResponseJson)
.then(response => {
console.log(response);
currentRelease = response;
return response;
});
}
function resolveOauthResponse(response) {
if (response.ok) {
return Promise.resolve(response.json());
}
return response.text()
.then(text => {
return Promise.reject(new Error(text));
});
}
function resolveWs2ResponseJson(response) {
return response.json()
.then(body => {
if (body["error"]) {
return Promise.reject(new Error(body["error"]));
}
return body;
});
}
function resolveWs2ResponseXml(response) {
return response.text()
.then(body => {
let parser = new DOMParser();
let doc = parser.parseFromString(body, "application/xml");
let firstChild = doc.firstElementChild;
if (firstChild.nodeName == "parseerror" && firstChild.namespaceURI == "http://www.mozilla.org/newlayout/xml/parsererror.xml") {
return Promise.reject(new Error(firstChild.textContent));
}
return doc;
});
}
function doLogout() {
window.localStorage.removeItem("mb_login");
onPopState();
}
function doSubmitMbid() {
let mbidSubmitBtn = document.getElementById("index-mbid-submit");
mbidSubmitBtn.disabled = true;
let newMbid = document.getElementById("mbid").value;
let parsedMbid = parseMbid(newMbid);
if (parsedMbid) {
newMbid = parsedMbid;
}
let params = new URLSearchParams(window.location.search);
params.set("mbid", newMbid);
pushState(params);
}
function doCheckIsrcs(event) {
event.preventDefault();
let submitBtn = document.getElementById("check-isrcs-submit");
submitBtn.disabled = true;
let form = document.getElementById("check-isrcs");
let formData = new FormData(form);
let params = new URLSearchParams();
for (const [key, value] of formData.entries()) {
if (value) {
params.set(key, value);
}
}
pushState(params);
}
function doSubmitISRCs() {
let editSubmitBtn = document.getElementById("edit-submit");
editSubmitBtn.disabled = true;
renderSubmitProgress();
postISRCs()
.then(() => {
let params = new URLSearchParams(window.location.search);
params.set("submit", 1);
pushState(params);
})
.catch(error => {
renderError("When submitting ISRCs: " + error, error);
});
}
function postISRCs() {
let doc = buildISRCXML();
let body = new XMLSerializer().serializeToString(doc);
console.log(body);
// Load data for the requested release
var url = new URL("recording/", mb_ws2_base);
var params = url.searchParams;
params.set("client", mb_client);
return window.fetch(url, {
method: "POST",
headers: {
"Authorization": "Bearer " + login["accessToken"],
"Content-Type": "application/xml"
},
body: body
})
.then(resolveWs2ResponseXml)
.then(response => {
console.log(response);
});
}
function buildISRCXML() {
// Invert the isrcs structure to be a map of isrcs per mbid
let recordingISRCMap = {};
for (const [i, isrc] of pregapISRCs.entries()) {
if (!isrc || !isrc.isrc || isrc.invalid) { continue; }
const mbid = currentRelease.media[i].pregap.recording.id;
if (!recordingISRCMap[mbid]) { recordingISRCMap[mbid] = []; }
recordingISRCMap[mbid].push(isrc.isrc);
}
for (const [i, isrcMedium] of isrcs.entries()) {
for (const [j, isrc] of isrcMedium.entries()) {
if (!isrc.isrc || isrc.invalid) { continue; }
const mbid = currentRelease.media[i].tracks[j].recording.id;
if (!recordingISRCMap[mbid]) { recordingISRCMap[mbid] = []; }
recordingISRCMap[mbid].push(isrc.isrc);
}
}
// Create the XML document for the edit submission
let xmlns = "http://musicbrainz.org/ns/mmd-2.0#";
let doc = document.implementation.createDocument(xmlns, "", null);
let metadata = doc.createElementNS(xmlns, "metadata");
doc.appendChild(metadata);
let recordingList = doc.createElementNS(xmlns, "recording-list");
metadata.appendChild(recordingList);
for (let mbid in recordingISRCMap) {
let isrcs = recordingISRCMap[mbid];
console.log("mbid", mbid, "isrcs", isrcs);
let recording = doc.createElementNS(xmlns, "recording");
recording.setAttribute("id", mbid);
recordingList.appendChild(recording);
let isrcList = doc.createElementNS(xmlns, "isrc-list");
isrcList.setAttribute("count", isrcs.length);
recording.appendChild(isrcList);
for (let isrc of isrcs) {
let isrcEl = doc.createElementNS(xmlns, "isrc");
isrcEl.setAttribute("id", isrc);
isrcList.appendChild(isrcEl);
}
}
if (editNote) {
const editNoteEl = doc.createElementNS(xmlns, "edit-note");
editNoteEl.textContent = editNote;
metadata.appendChild(editNoteEl);
}
return doc;
}
function handleSubmit(params) {
var container = document.getElementById("container");
container.innerHTML = tmpl("template_submit", {});
restoreScrollPosition();
}
function parseISRC(str) {
const match = /[A-Za-z]{2}-?[A-Za-z0-9]{3}-?[0-9]{2}-?[0-9]{5}/.exec(str);
if (!match) { return ""; }
return match[0];
}
function handleISRCPaste(event) {
let text = event.clipboardData.getData("text").split(/\r\n|\r|\n/);
if (text.length == 1) { return; }
event.preventDefault();
let input = event.target;
let line = text.shift();
input.setRangeText(parseISRC(line), input.selectionStart, input.selectionEnd, "end");
while (text.length > 0) {
line = text.shift();
input = getNextISRCInput(input);
if (!input) { return; }
input.value = parseISRC(line);
input.focus();
}
}
function handleISRCKeydown(event) {
let code = event.code;
let input = event.target;
if (event.code == "Enter" || event.code == "NumpadEnter" || code == "ArrowDown") {
input = getNextISRCInput(input);
if (input) {
event.preventDefault();
input.focus();
input.select();
return;
}
let submit = document.getElementById("check-isrcs-submit");
event.preventDefault();
submit.focus();
} else if (event.code == "ArrowUp") {
input = getPrevISRCInput(input);
if (input) {
event.preventDefault();
input.focus();
input.select();
return;
}
}
}
function handleCheckISRCKeydown(event) {
let code = event.code;
if (event.code == "ArrowUp") {
let input = getPrevISRCInput(null);
if (input) {
event.preventDefault();
input.focus();
input.select();
return;
}
}
}
function getNextISRCInput(input) {
let medium = +input.dataset.medium;
let track = +input.dataset.track;
track += 1;
while (medium <= isrcs.length) {
if (track <= isrcs[medium - 1].length) { break; }
medium += 1;
track = pregapISRCs[medium - 1] ? 0 : 1;
}
return document.getElementById(`isrc${medium}-${track}`);
}
function getPrevISRCInput(input) {
let medium, track;
if (input) {
medium = +input.dataset.medium;
track = +input.dataset.track;
} else {
medium = isrcs.length;
track = isrcs[medium - 1].length + 1;
}
track -= 1;
while (medium > 1) {
if (track > 0 || (track == 0 && pregapISRCs[medium - 1])) { break; }
medium -= 1;
track = isrcs[medium - 1].length;
}
return document.getElementById(`isrc${medium}-${track}`);
}
function renderIndex(params) {
var container = document.getElementById("container");
container.innerHTML = tmpl("template_index", {
mbid: params.get("mbid") || ""
});
restoreScrollPosition();
}
function renderNavbar() {
var navbar = document.getElementById("navbar");
var rootLocation = new URL(window.location);
rootLocation.search = "";
navbar.innerHTML = tmpl("template_navbar", {
rootLocation: rootLocation
});
}
function renderLoginProgress() {
document.getElementById("container").innerHTML = tmpl("template_login_progress", {});
resetScrollPosition();
}
function renderError(message, error) {
console.log(message);
console.log(error);
document.getElementById("container").innerHTML = tmpl("template_error", {error: message});
resetScrollPosition();
}
function renderReleaseProgress() {
document.getElementById("container").innerHTML = tmpl("template_release_progress", {});
resetScrollPosition();
}
function renderRelease(release) {
let container = document.getElementById("container");
container.innerHTML = tmpl("template_release", {
release: release
});
document.getElementById("check-isrcs").onsubmit = doCheckIsrcs;
document.getElementById("check-isrcs-submit").onkeydown = handleCheckISRCKeydown;
document.querySelectorAll("[data-isrc]").forEach(el => {
el.onpaste = handleISRCPaste;
el.onkeydown = handleISRCKeydown;
})
restoreScrollPosition();
}
function renderSubmitProgress() {
let container = document.getElementById("container");
container.innerHTML = tmpl("template_submit_progress", {});
resetScrollPosition();
}
function resetScrollPosition() {
window.scrollTo(0, 0);
}
function restoreScrollPosition() {
if (poppedState) {
console.log("restoring scroll position", poppedState);
window.scrollTo(+poppedState["scrollX"], +poppedState["scrollY"]);
} else {
resetScrollPosition();
}
}
</script>
<script type="text/x-ejs" id="template_index">
<p class="lead">MagicISRC is a tool that makes it easy to submit ISRCs for every track on a <a href="https://musicbrainz.org/">MusicBrainz</a> release.</p>
<form method="get" onsubmit="doSubmitMbid(); return false;">
<h1 class="h3"><label for="mbid">Enter a release MBID:</label></h1>
<div class="input-group has-validation">
<input type="text" class="form-control form-control-lg<% if (mbidInvalid) { %> is-invalid <% } %>" id="mbid" value="<%= escapeHtml(mbid) %>">
<button id="index-mbid-submit" type="submit" class="btn btn-lg btn-primary">Load</button>
<div class="invalid-feedback">The provided value doesn’t contain an MBID</div>
</div>
<small class="text-secondary">
You can also paste in a URL to a release page, or any string containing a release MBID.
</small>
</form>
</script>
<script type="text/x-ejs" id="template_submit">
<p>The ISRCs have been successfully submitted.</p>
<% if (login.userInfo) { %>
<p><a href="<%= escapeHtml(mb_site) %>search/edits?order=desc&negation=0&combinator=and&conditions.0.field=editor&conditions.0.operator=%3D&conditions.0.name=<%= escapeHtml(login.userInfo.sub) %>&conditions.0.args.0=<%= escapeHtml(login.userInfo.metabrainz_user_id) %>&conditions.1.field=type&conditions.1.operator=%3D&conditions.1.args=76">View your ISRC submission history.</a></p>
<% } %>
</script>
<script type="text/x-ejs" id="template_navbar">
<a class="navbar-brand" href="<%= escapeHtml(rootLocation) %>" onclick="pushState(""); return false;">kepstin’s MagicISRC</a>
<div class="show navbar-collapse me-auto">
<ul class="navbar-nav">
<li class="nav-item">
<a class="nav-link" href="https://github.com/kepstin/magicisrc/releases">Release Notes</a>
</li>
<li class="nav-item">
<a class="nav-link" href="seeding.html">Seeding and Importing</a>
</li>
<li class="nav-item">
<a class="nav-link" href="privacy.html">Privacy Policy</a>
</li>
</ul>
</div>
<% if (login.userInfo) { %>
<span class="navbar-text me-3"><%= escapeHtml(login.userInfo.sub) %></span>
<form class="d-flex">
<button class="btn btn-outline-light" type="button" onClick="doLogout(); return false;">Logout</button>
</form>
<% } else { %>
<form class="d-flex">
<button class="btn btn-outline-light" type="button" onClick="doLogin(); return false;">Login</button>
</form>
<% } %>
</script>
<script type="text/x-ejs" id="template_release">
<h1 class="h3">
<a class="text-decoration-none" href="<%= new URL("release/" + release["id"], mb_site) %>"><bdi><%= escapeHtml(release["title"]) %></bdi></a>
<% if (release["disambiguation"]) { %><small class="text-secondary fs-6 fw-normal">(<bdi><%= escapeHtml(release["disambiguation"]) %></bid>)</small><% } %>
</h1>
<p class="mb-4"><span class="text-secondary">~</span> Release by <%= tmpl("template_ac", {ac: release["artist-credit"]}) %></p>
<form id="check-isrcs" method="get">
<input type="hidden" name="mbid" value="<%= release["id"] %>">
<% for (var i = 0; i < release["media"].length; i++) { %>
<% var medium = release["media"][i]; %>
<h2 class="h4">
<%= medium["format"] ? escapeHtml(medium["format"]) : "Medium" %> <%= escapeHtml(medium["position"]) %><% if (medium["title"]) { %>: <bdi><%= escapeHtml(medium["title"]) %></bdi><% } %>
</h2>
<% if (medium["tracks"].length > 0) { %>
<table class="d-block mb-3">
<thead class="d-block">
<tr class="row py-2 border-bottom">
<th scope="col" class="col-1 col-sm-1">#</th>
<th scope="col" class="col-11 col-sm-6 col-md-7 col-lg-8 order-sm-2">
<div class="row">
<div class="col-lg-7">Track</div>
<div class="col-lg-5 d-none d-lg-block">Artist</div>
</div>
</th>
<th scope="col" class="col-11 offset-1 col-sm-5 col-md-4 col-lg-3 order-sm-1 offset-sm-0">ISRCs</th>
</tr>
</thead>
<tbody class="d-block">
<% if (medium.pregap) { %>
<%= tmpl("template_track", {medium: medium, track: medium.pregap, isrc: pregapISRCs[i]}) %>
<% } %>
<% for (var j = 0; j < medium["tracks"].length; j++) { %>
<% var track = medium["tracks"][j]; %>
<% var isrc = isrcs[i][j]; %>
<%= tmpl("template_track", {medium: medium, track: track, isrc: isrc}) %>
<% } %>
</tbody>
</table>
<% } else { %>
<p class="text-secondary">(no tracks)</p>
<% } %>
<% } %>
<button id="check-isrcs-submit" type="submit" class="btn btn-primary">Check ISRCs & update edit preview</button>
<% if (anyISRCsValid) { %>
<h1 class="mt-3 h3">Edit Preview</h1>
<div class="row">
<div class="col-12 col-sm-2 offset-lg-1 form-label fw-bold">
Additions
</div>
<div class="col-12 col-sm-10 col-lg-9">
<ul class="list-unstyled">
<% for (let i = 0; i < isrcs.length; i++) { %>
<% if (pregapISRCs[i]) { %>
<%= tmpl("template_track_preview", {isrc: pregapISRCs[i], recording: release.media[i].pregap.recording}) %>
<% } %>
<% for (let j = 0; j < isrcs[i].length; j++) { %>
<%= tmpl("template_track_preview", {isrc: isrcs[i][j], recording: release.media[i].tracks[j].recording}) %>
<% } %>
<% } %>
</ul>
</div>
</div>
<% } %>
<h2 class="h4 mt-3"><label for="edit-note">Edit note</label></h2>
<p>Entering an <a href="https://musicbrainz.org/doc/Edit_Note">edit note</a> that describes where you got your information is highly recommended. Not only does it make your sources clear (both now and to users who see the edit years later), but it can also encourage other users to vote on the edit — thus making it get applied faster.</p>
<p>Even just providing a URL or two is helpful! For more suggestions, see <a href="https://musicbrainz.org/doc/How_to_Write_Edit_Notes">the MusicBrainz guide for writing good edit notes</a>.</p>
<textarea class="form-control mb-3" rows="5" name="edit-note"><%= escapeHtml(editNote) %></textarea>
<% if (!login.userInfo) { %>
<button class="btn btn-primary" type="button" onclick="doLogin(); return false;">Login to MusicBrainz</button>
<% } else if (anyISRCsValid) { %>
<button id="edit-submit" class="btn btn-primary" type="button" onclick="doSubmitISRCs(); return false;">Enter edit</button>
<% } %>
</form>
</script>
<script type="text/x-ejs" id="template_track">