-
Notifications
You must be signed in to change notification settings - Fork 16
/
mbz-loujine-common.js
934 lines (874 loc) · 24.7 KB
/
mbz-loujine-common.js
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
/* global MB */
'use strict';
// ==UserScript==
// @name mbz-loujine-common
// @namespace mbz-loujine
// @author loujine
// @version 2023.3.12
// @description musicbrainz.org: common functions
// @compatible firefox+greasemonkey
// @license MIT
// @grant none
// @run-at document-end
// ==/UserScript==
// github wiki
const wikiUrl = 'https://github.com/loujine/musicbrainz-scripts/wiki';
// from musicbrainz-server/root/static/scripts/tests/typeInfo.js
class Server {
constructor() {
this.recordingLinkType = {
instrument: 148,
vocals: 149,
orchestra: 150,
conductor: 151,
chorusmaster: 152,
concertmaster: 760,
performer: 156,
work: 278,
place: 693,
area: 698,
};
this.instrumentType = {
instrument: 14,
strings: 69,
bass: 70,
double_bass: 71,
acoustic_bass_guitar: 73,
electric_bass_guitar: 74,
guitar_family: 75,
violin_family: 82,
cello: 84,
violin: 86,
membranophone: 125,
drums: 126,
harpsichord: 174,
piano: 180,
guitar: 229,
bass_guitar: 277,
string_quartet: 1067,
};
this.vocalType = {
vocal: 3,
lead: 4,
alto: 5,
bass: 7,
soprano: 10,
tenor: 11,
choir: 13,
};
this.workType = {
'Song': 17,
'Aria': 1,
'Audio drama': 25,
'Ballet': 2,
'Beijing opera': 26,
'Cantata': 3,
'Concerto': 4,
'Étude': 20,
'Incidental music': 30,
'Madrigal': 7,
'Mass': 8,
'Motet': 9,
'Musical': 29,
'Opera': 10,
'Operetta': 24,
'Oratorio': 11,
'Overture': 12,
'Partita': 13,
'Play': 28,
'Poem': 21,
'Prose': 23,
'Quartet': 14,
'Sonata': 5,
'Song-cycle': 15,
'Soundtrack': 22,
'Suite': 6,
'Symphonic poem': 18,
'Symphony': 16,
'Zarzuela': 19,
};
this.workLinkType = {
arrangement: 350,
composer: 168,
subwork: 281,
writer: 167,
};
this.releaseLinkTypeID = {
44: 'instrument',
60: 'vocals',
45: 'orchestra',
46: 'conductor',
53: 'chorusmaster',
51: 'performer',
};
this._performingRoles = [
'instrument',
'vocals',
'orchestra',
'conductor',
'performer',
];
this._minorPerformingRoles = [
'concertmaster',
'chorusmaster',
];
this.aliasArtistType = {
'Artist name': 1,
'Legal name': 2,
'Search hint': 3,
};
this.aliasInstrumentType = {
'Instrument name': 1,
'Search hint': 2,
'Brand name': 3,
};
this.aliasType = {
'Name': 1,
'Search hint': 2,
};
this.attr = {
additional: 1,
strings: 69,
cello: 84,
violin: 86,
piano: 180,
guest: 194,
bowedStrings: 275,
string_quartet: 1067,
piano_trio: 1070,
string_trio: 1074,
cover: 567,
live: 578,
partial: 579,
instrumental: 580,
video: 582,
solo: 596,
medley: 750,
};
this.language = {
'[Multiple languages]': 284,
'[No lyrics]': 486,
'Arabic': 18,
'Chinese': 76,
'Czech': 98,
'Danish': 100,
'Dutch': 113,
'English': 120,
'Finnish': 131,
'French': 134,
'German': 145,
'Greek': 159,
'Hungarian': 176,
'Italian': 195,
'Japanese': 198,
'Korean': 224,
'Norwegian': 309,
'Occitan': 318,
'Polish': 338,
'Portuguese': 340,
'Russian': 353,
'Spanish': 393,
'Swedish': 403,
'Turkish': 433,
};
this.languageFromISO = {
ara: 'Arabic',
zho: 'Chinese',
ces: 'Czech',
dan: 'Danish',
nld: 'Dutch',
eng: 'English',
fin: 'Finnish',
fra: 'French',
deu: 'German',
ell: 'Greek',
hun: 'Hungarian',
ita: 'Italian',
jpn: 'Japanese',
kor: 'Korean',
mul: '[Multiple languages]',
nor: 'Norwegian',
oci: 'Occitan',
pol: 'Polish',
por: 'Portuguese',
rus: 'Russian',
spa: 'Spanish',
swe: 'Swedish',
tur: 'Turkish',
zxx: '[No lyrics]',
};
this.locale = {
'Afrikaans': 'af',
'Albanian': 'sq',
'Amharic': 'am',
'Arab in Egypt': 'arz',
'Arabic': 'ar',
'Aragonese': 'an',
'Armenian': 'hy',
'Asturian': 'ast',
'Azerbaijani': 'az',
'Bangla': 'bn',
'Bashkir': 'ba',
'Basque': 'eu',
'Belarusian': 'be',
'Bosnian': 'bs',
'Breton': 'br',
'Bulgarian': 'bg',
'Burmese': 'my',
'Cantonese': 'yue',
'Catalan': 'ca',
'Central Kurdish/Sorani': 'ckb',
'Cherokee': 'chr',
'Chinese Hong Kong SAR China Traditional': 'zh_Hant_HK',
'Chinese Simplified': 'zh_Hans',
'Chinese Singapore Simplified': 'zh_Hans_SG',
'Chinese Taiwan Traditional': 'zh_Hant_TW',
'Chinese Traditional': 'zh_Hant',
'Chinese': 'zh',
'Chuvash': 'cv',
'Corsican': 'co',
'Croatian': 'hr',
'Czech': 'cs',
'Danish': 'da',
'Dutch': 'nl',
'English': 'en',
'Esperanto': 'eo',
'Estonian': 'et',
'Faroese': 'fo',
'Filipino': 'fil',
'Finnish': 'fi',
'French': 'fr',
'Galician': 'gl',
'Georgian': 'ka',
'German': 'de',
'Greek': 'el',
'Guarani': 'gn',
'Gujarati': 'gu',
'Hawai’ian': 'haw',
'Hebrew': 'he',
'Hindi': 'hi',
'Hungarian': 'hu',
'Icelandic': 'is',
'Ido': 'io',
'Indonesian': 'id',
'Interlingua': 'ia',
'Irish': 'ga',
'Italian': 'it',
'Japanese': 'ja',
'Javanese': 'jv',
'Kannada': 'kn',
'Kazakh': 'kk',
'Khmer': 'km',
'Korean': 'ko',
'Kyrgyz': 'ky',
'Latin': 'la',
'Latvian': 'lv',
'Ligurian': 'lij',
'Lithuanian': 'lt',
'Lombard': 'lmo',
'Low German': 'nds',
'Lule Sami': 'smj',
'Luxembourgish': 'lb',
'Māori': 'mi',
'Macedonian': 'mk',
'Maithili': 'mai',
'Malay': 'ms',
'Malayalam': 'ml',
'Manx': 'gv',
'Marathi': 'mr',
'Mongolian': 'mn',
'Nepali': 'ne',
'Norwegian Bokmål': 'nb',
'Norwegian Nynorsk': 'nn',
'Norwegian': 'no',
'Occitan': 'oc',
'Persian': 'fa',
'Polish': 'pl',
'Portuguese': 'pt',
'Punjabi': 'pa',
'Quechua': 'qu',
'Romanian': 'ro',
'Romansh': 'rm',
'Russian': 'ru',
'Sanskrit': 'sa',
'Sardinian': 'sc',
'Scottish Gaelic': 'gd',
'Serbian': 'sr',
'Sicilian': 'scn',
'Silesian': 'slz',
'Sinhala': 'si',
'Skolt Sami': 'sms',
'Slovak': 'sk',
'Slovenian': 'sl',
'Somali': 'so',
'Southern Kurdish': 'sdh',
'Southern Sami': 'sma',
'Spanish': 'es',
'Sundanese Latin': 'su_Latn',
'Sundanese': 'su',
'Swahili': 'sw',
'Swedish': 'sv',
'Tajik': 'tg',
'Tamil': 'ta',
'Tatar': 'tt',
'Telugu': 'te',
'Thai': 'th',
'Tok Pisin': 'tpi',
'Turkish': 'tr',
'Ukrainian': 'uk',
'Urdu': 'ur',
'Uyghur': 'ug',
'Uzbek': 'uz',
'Venetian': 'vec',
'Vietnamese': 'vi',
'Wallon': 'wa',
'Welsh': 'cy',
'Western Frisian': 'fy',
'Yiddish': 'yi',
'Yoruba': 'yo',
'Zulu': 'zu',
};
this.workKeyAttr = {
'C major': 2,
'C minor': 3,
'C-sharp major': 4,
'C-sharp minor': 5,
'D-flat major': 6,
'D-flat minor': 7,
'D major': 8,
'D minor': 9,
'D-sharp minor': 10,
'E-flat major': 11,
'E-flat minor': 12,
'E major': 13,
'E minor': 14,
'E-sharp minor': 15,
'F-flat major': 16,
'F major': 17,
'F minor': 18,
'F-sharp major': 19,
'F-sharp minor': 20,
'G-flat major': 21,
'G major': 22,
'G minor': 23,
'G-sharp major': 24,
'G-sharp minor': 25,
'A-flat major': 26,
'A-flat minor': 27,
'A major': 28,
'A minor': 29,
'A-sharp minor': 30,
'B-flat major': 31,
'B-flat minor': 32,
'B major': 33,
'B minor': 34,
'C Dorian': 789,
'D Dorian': 790,
'E Dorian': 791,
'F Dorian': 792,
'G Dorian': 793,
'A Dorian': 794,
'B Dorian': 795,
};
this.unknownArtistId = 97546;
// https://musicbrainz.org/doc/XML_Web_Service/Rate_Limiting
// we wait for 'server.timeout' milliseconds between two queries
this.timeout = 1000;
}
releaseToRecordingLink(linkTypeID) {
return this.recordingLinkType[this.releaseLinkTypeID[linkTypeID]];
}
performingLinkTypes(skipMinorRoles = false) {
const roles = skipMinorRoles ? this._performingRoles : [
...this._performingRoles, ...this._minorPerformingRoles
];
return roles.map(role => this.recordingLinkType[role]);
}
}
const server = new Server();
function buildOptions(obj) {
// to be replaced by Object.entries when all supported browser versions
// recognize it
return Object.entries(obj)
.map(([type, code]) => `<option value="${code}">${type}</option>`)
.join('');
}
function buildLanguageOptions(obj) {
return Object.entries(obj)
.map(
([type, code]) =>
`<option class="language" value="${code}">${type}</option>`
)
.join('');
}
function buildLocaleOptions(obj) {
return Object.entries(obj)
.map(
([type, code]) =>
`<option class="language" value="${code}">${code} ${type}</option>`
)
.sort()
.join('');
}
// eslint-disable-next-line no-unused-vars
const aliases = {
artistType: `
<select>
<option selected> </option>
${buildOptions(server.aliasArtistType)}
</select>
`,
instrumentType: `
<select>
<option selected> </option>
${buildOptions(server.aliasInstrumentType)}
</select>
`,
type: `
<select>
<option selected> </option>
${buildOptions(server.aliasType)}
</select>
`,
locale: `
<select>
<option> </option>
${buildLocaleOptions(server.locale)}
</select>
`,
};
// eslint-disable-next-line no-unused-vars
const works = {
type: `
<select class="setwork">
<option selected> </option>
${buildOptions(server.workType)}
</select>
`,
lang: `
<select class="setlang">
<option> </option>
<optgroup label="Frequently used">
${buildLanguageOptions(server.language)}
</optgroup>
<optgroup label="Other">
<option class="language" value="238">Latin</option>
</optgroup>
</select>
`,
key: `
<select class="setkey">
<option selected> </option>
${buildOptions(server.workKeyAttr)}
</select>
`,
};
// eslint-disable-next-line no-unused-vars
const roles = {
roles: `
<option value="122" disabled="">performance</option>
<option value="156"> performer</option>
<option value="148"> instruments</option>
<option value="149"> vocals</option>
<option value="150"> orchestra</option>
<option value="151"> conductor</option>
<option value="152"> chorus master</option>
<option value="760"> concertmaster</option>
<option value="297">arranger</option>
<option value="158"> instruments arranger</option>
<option value="300"> orchestrator</option>
<option value="298"> vocals arranger</option>
<option value="157" disabled="">remixes and compilations</option>
<option value="153"> remixer</option>
<option value="147"> compiler</option>
<option value="155"> DJ-mixer</option>
<option value="154"> contains samples by</option>
<option value="160" disabled="">production</option>
<option value="141"> producer</option>
<option value="138"> engineer</option>
<option value="140"> audio engineer</option>
<option value="136"> mastering</option>
<option value="133"> sound engineer</option>
<option value="143"> mixer</option>
<option value="128"> recording engineer</option>
<option value="132"> programming</option>
<option value="144"> editor</option>
<option value="726"> balance engineer</option>
<option value="129"> miscellaneous support</option>
<option value="142"> legal representation</option>
<option value="869"> phonographic copyright by</option>
<option value="858"> visual appearances</option>
<option value="134"> booking</option>
<option value="135"> artist & repertoire support</option>
<option value="146"> creative direction</option>
<option value="137"> art direction</option>
<option value="130"> design/illustration</option>
<option value="125"> graphic design</option>
<option value="123"> photography</option>
<option value="931"> piano technician</option>
<option value="127"> publisher</option>
`,
roleAttrs: `
<option selected> </option>
<option disabled="">instruments</option>
${buildOptions(server.instrumentType)}
<option disabled="">vocals</option>
${buildOptions(server.vocalType)}
`,
};
const requests = (function () {
const self = {};
self._request = function (verb, url, param, callback) {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
callback(xhr); // eslint-disable-line callback-return
}
};
xhr.open(verb, url, true);
if (verb === 'POST') {
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
);
}
xhr.timeout = 10000;
xhr.ontimeout = function () {
console.error('The request for ' + url + ' timed out.');
};
xhr.send(param);
};
self.GET = function (url, callback) {
self._request('GET', url, null, function (xhr) {
if (xhr.status === 200 && xhr.responseText !== null) {
callback(xhr.responseText); // eslint-disable-line callback-return
} else {
console.log('Error ', xhr.status, ': ', url);
}
});
};
self.POST = function (url, param, successCallback, failCallback) {
self._request('POST', url, param, function (xhr) {
if (xhr.status === 200 || xhr.status === 0) {
successCallback(xhr);
} else {
failCallback(xhr);
}
});
};
return self;
})();
class Edits {
urlFromMbid(entityType, mbid) {
return `/${entityType}/${encodeURIComponent(mbid)}/edit`;
}
/* in order to determine the edit parameters required by POST
* we first load the /edit page and parse the JSON data
* in the sourceData (before 2023) or source_entity block
*/
getEditParams(url, callback) {
requests.GET(url, resp => {
let data;
if (resp.includes('source_entity')) {
data = new RegExp(/source_entity":(.*)},"user":/).exec(resp)[1];
} else {
// pre PR musicbrainz-server#2582
data = new RegExp(/sourceData: (.*),\n/).exec(resp)[1];
}
callback(JSON.parse(data));
});
}
getWorkEditParams(url, callback) {
this.getEditParams(url, data => {
const editData = {
name: data.name,
type_id: data.typeID,
languages: data.languages.map(it => it.language.id),
iswcs: data.iswcs.map(it => it.iswc),
attributes: data.attributes.map(attr => ({
type_id: attr.typeID,
value: attr.value,
})),
};
callback(editData);
});
}
/* get edit POST parameters from a JSON API call
* need to reconvert all values to internal ids */
getWorkEditParamsFromJSON(url, callback) {
fetch(url)
.then(resp => resp.json())
.then(data => {
const editData = {
name: data.title,
type_id: server.workType[data.type],
languages: data.languages.map(l => server.languageFromISO[l]),
iswcs: data.iswcs,
relations: data.relations,
};
editData.attributes = data.attributes.filter(
attr => attr.type === 'Key'
).map(attr =>
({
type_id: 1,
value: server.workKeyAttr[attr.value],
})
);
callback(editData);
});
}
encodeName(name) {
return encodeURIComponent(name).replace(/%20/g, '+');
}
prepareEdit(editData) {
const data = {
name: this.encodeName(editData.name),
type_id: editData.type_id || ' ',
};
editData.languages.forEach((lang, idx) => {
// FIXME error message if unknown language, edit will fail
data['languages.' + idx] = server.language[lang] ? server.language[lang] : lang;
});
if (editData.iswcs === undefined || !editData.iswcs.length) {
data['iswcs.0'] = null;
} else {
editData.iswcs.forEach((iswc, idx) => {
data['iswcs.' + idx] = iswc;
});
}
// attributes (key)
if (editData.attributes) {
editData.attributes.forEach((attr, idx) => {
data['attributes.' + idx + '.type_id'] = attr.type_id;
data['attributes.' + idx + '.value'] = attr.value;
});
}
return data;
}
formatEdit(editType, info) {
return Object.entries(info)
.map(([prop, val]) =>
val === null
? `${editType}.${prop}`
: `${editType}.${prop}=${val}`
)
.join('&');
}
}
// eslint-disable-next-line no-unused-vars
const edits = new Edits();
class Helper {
comparefct(a, b) {
// Sort function for performers in the recording artist list
const link = server.recordingLinkType;
const order = [
link.vocals,
link.instrument,
link.orchestra,
link.conductor,
link.performer,
];
if (a.link === b.link) {
return 0;
}
return order.indexOf(a.link) > order.indexOf(b.link) ? 1 : -1;
}
mbidFromURL(url) {
return (url || document.URL).split('/')[4].slice(0, 36);
}
wsUrl(entityType, options, mbid) {
let url = `/ws/2/${entityType}/`;
mbid = mbid || this.mbidFromURL();
options = options || [];
url += encodeURIComponent(mbid);
url += '?fmt=json';
options.forEach((option, idx) => {
const prefix = idx === 0 ? '&inc=' : encodeURIComponent(' ');
url += prefix + option;
});
return new URL(
url,
document.location.protocol + '//' + document.location.host
);
}
_isEntityTypeURL(entityType) {
return document.URL.split('/')[3] === entityType;
}
isArtistURL() {
return this._isEntityTypeURL('artist');
}
isInstrumentURL() {
return this._isEntityTypeURL('instrument');
}
isReleaseURL() {
return this._isEntityTypeURL('release');
}
isWorkURL() {
return this._isEntityTypeURL('work');
}
sortBy(key) {
return (a, b) => (a[key] > b[key] ? 1 : b[key] > a[key] ? -1 : 0);
}
sortSubworks(work) {
let rels = work.relationships;
rels = rels.filter(
rel =>
rel.linkTypeID === server.workLinkType.subwork &&
!rel.backward
);
rels = rels.sort(this.sortBy('linkOrder'));
return rels.map(rel => rel.target);
}
isUserLoggedIn() {
const isLoggedIn = !document.querySelector('a[href*="/register"]');
if (!isLoggedIn) {
console.debug('User is not logged in, exiting the script');
}
return isLoggedIn;
}
delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
waitFor(pollingFunction, pollingInterval) {
return new Promise(async (resolve) => { // eslint-disable-line no-async-promise-executor
while (pollingFunction() === false) {
await this.delay(pollingInterval);
}
resolve();
});
}
}
// eslint-disable-next-line no-unused-vars
const helper = new Helper();
class Sidebar {
editNote(meta, msg) {
const separator = '\n —\n';
msg = msg ? '\n' + msg : '';
const signature = `GM script: "${meta.name}" (${meta.version})\n`;
return [msg, signature].join(separator);
}
container() {
const container = document.getElementById('loujine-sidebar');
if (container !== null) {
return container;
}
document.querySelector('#sidebar h2.editing + ul.links').insertAdjacentHTML('afterend', `
<div id="loujine-sidebar"
style="background-color: white;
padding: 8px; margin: 0px -6px 6px;
border: 5px dotted rgb(115, 109, 171);">
<h2>loujine GM tools</h2>
<a href="${wikiUrl}" target="_blank">documentation</a>
</div>
`);
return document.getElementById('loujine-sidebar');
}
}
// eslint-disable-next-line no-unused-vars
const sidebar = new Sidebar();
class RelationshipEditor {
constructor() {
this.dispatchDefaults = {
batchSelectionCount: null,
creditsToChangeForSource: '',
creditsToChangeForTarget: '',
oldRelationshipState: null,
};
this.stateDefaults = {
_lineage: [],
_original: null,
_status: 0,
attributes: null,
begin_date: null,
editsPending: false,
end_date: null,
ended: false,
entity0_credit: '',
entity1_credit: '',
id: null,
linkOrder: 0,
linkTypeID: null,
};
}
// from https://github.com/kellnerd/musicbrainz-scripts/blob/main/utils/dom/react.js
setReactTextareaValue(input, value) {
const setter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set;
setter.call(input, value);
input.dispatchEvent(new Event('input', { bubbles: true }));
}
editNote(meta, msg) {
const node = document.getElementById('edit-note-text');
msg = msg ? '\n' + msg : '';
const separator = '\n —\n';
const signature = `GM script: "${meta.name}" (${meta.version})\n`;
let existingMsg = node.value;
let existingSign;
if (existingMsg.includes(separator)) {
[existingMsg, existingSign] = existingMsg.split(separator);
this.setReactTextareaValue(
node,
[existingMsg + msg, existingSign + signature].join(separator),
);
} else {
this.setReactTextareaValue(
node,
[existingMsg + msg, signature].join(separator),
);
}
}
container(node) {
const container = document.getElementById('loujine-menu');
if (container !== null) {
return container;
}
node.insertAdjacentHTML('afterend', `
<div id="loujine-menu"
style="background-color: white;
padding: 8px; margin: 0px -6px 6px;
border: 5px dotted rgb(115, 109, 171);">
<h2>loujine GM tools</h2>
<a href="${wikiUrl}" target="_blank">documentation</a>
</div>
`);
return document.getElementById('loujine-menu');
}
// from https://github.com/kellnerd/musicbrainz-scripts/blob/main/src/relationship-editor/createRelationship.js
createAttributeTree(attributes) {
return MB.tree.fromDistinctAscArray(attributes
.map((attribute) => {
const attributeType = MB.linkedEntities.link_attribute_type[attribute.type.gid];
return {
...attribute,
type: attributeType,
typeID: attributeType.id,
};
})
);
}
orderedSelectedRecordings() {
const recordings = MB.tree.toArray(MB.relationshipEditor.state.selectedRecordings);
if (!recordings.length) {
alert('No relation selected');
}
// sort recordings by order in tracklist to avoid having the dialog jump everywhere
const recOrder = MB.getSourceEntityInstance().mediums.flatMap(
// tracks on mediums 1-10 loaded by default
m => m.tracks
).concat(
// tracks on unfolded mediums
Array.from(MB.relationshipEditor.state.loadedTracks.keys()).sort().flatMap(
k => MB.relationshipEditor.state.loadedTracks.get(k)
)
).map(t => t.recording.id);
recordings.sort((r1, r2) => recOrder.indexOf(r1.id) - recOrder.indexOf(r2.id));
return recordings;
}
parseDate(dateProp) {
if (dateProp === null) {
return {year: '', month: '', day: ''};
}
return {year: dateProp.year ?? '', month: dateProp.month ?? '', day: dateProp.day ?? ''};
}
}
// eslint-disable-next-line no-unused-vars
const relEditor = new RelationshipEditor();