-
Notifications
You must be signed in to change notification settings - Fork 2
/
voiceActorCredits.user.js
1641 lines (1442 loc) · 55.1 KB
/
voiceActorCredits.user.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
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
// ==UserScript==
// @name MusicBrainz: Voice actor credits
// @version 2024.7.1
// @namespace https://github.com/kellnerd/musicbrainz-scripts
// @author kellnerd
// @description Parses voice actor credits from text and automates the process of creating release or recording relationships for these. Also imports credits from Discogs.
// @homepageURL https://github.com/kellnerd/musicbrainz-scripts#voice-actor-credits
// @downloadURL https://raw.github.com/kellnerd/musicbrainz-scripts/main/dist/voiceActorCredits.user.js
// @updateURL https://raw.github.com/kellnerd/musicbrainz-scripts/main/dist/voiceActorCredits.user.js
// @supportURL https://github.com/kellnerd/musicbrainz-scripts/issues
// @grant GM.getValue
// @grant GM.setValue
// @run-at document-idle
// @match *://*.musicbrainz.org/release/*/edit-relationships
// ==/UserScript==
(function () {
'use strict';
// Adapted from https://stackoverflow.com/a/46012210
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
const nativeTextareaValueSetter = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value').set;
/**
* Sets the value of a textarea input element which has been manipulated by React.
* @param {HTMLTextAreaElement} input
* @param {string} value
*/
function setReactTextareaValue(input, value) {
nativeTextareaValueSetter.call(input, value);
input.dispatchEvent(new Event('input', { bubbles: true }));
}
/**
* Returns a reference to the first DOM element with the specified value of the ID attribute.
* @param {string} elementId String that specifies the ID value.
*/
function dom(elementId) {
return document.getElementById(elementId);
}
/**
* Returns the first element that is a descendant of node that matches selectors.
* @param {string} selectors
* @param {ParentNode} node
*/
function qs(selectors, node = document) {
return node.querySelector(selectors);
}
/**
* Returns all element descendants of node that match selectors.
* @param {string} selectors
* @param {ParentNode} node
*/
function qsa(selectors, node = document) {
return node.querySelectorAll(selectors);
}
/**
* Adds the given message and a footer for the active userscript to the edit note.
* @param {string} message Edit note message.
*/
function addMessageToEditNote(message) {
/** @type {HTMLTextAreaElement} */
const editNoteInput = qs('#edit-note-text, .edit-note');
const previousContent = editNoteInput.value.split(editNoteSeparator);
setReactTextareaValue(editNoteInput, buildEditNote(...previousContent, message));
}
/**
* Builds an edit note for the given message sections and adds a footer section for the active userscript.
* Automatically de-duplicates the sections to reduce auto-generated message and footer spam.
* @param {...string} sections Edit note sections.
* @returns {string} Complete edit note content.
*/
function buildEditNote(...sections) {
sections = sections.map((section) => section.trim());
if (typeof GM_info !== 'undefined') {
sections.push(`${GM_info.script.name} (v${GM_info.script.version}, ${GM_info.script.namespace})`);
}
// drop empty sections and keep only the last occurrence of duplicate sections
return sections
.filter((section, index) => section && sections.lastIndexOf(section) === index)
.join(editNoteSeparator);
}
const editNoteSeparator = '\n—\n';
/**
* Transforms the given value using the given substitution rules.
* @param {string} value
* @param {import('../types').SubstitutionRule[]} substitutionRules Pairs of values for search & replace.
* @returns {string}
*/
function transform(value, substitutionRules) {
substitutionRules.forEach(([searchValue, replaceValue]) => {
value = value.replace(searchValue, replaceValue);
});
return value;
}
/** @type {CreditParserOptions} */
const parserDefaults = {
nameRE: /.+?(?:,?\s(?:LLC|LLP|(?:Corp|Inc|Ltd)\.?|Co\.(?:\sKG)?|(?:\p{Letter}\.){2,}))*/,
nameSeparatorRE: /[/|](?=\s|\w{2})|\s[–-]\s/,
terminatorRE: /$|(?=,|(?<!Bros)\.(?:\W|$)|\sunder\s)|(?<=(?<!Bros)\.)\W/,
};
/**
* Returns a promise that resolves after the given delay.
* @param {number} ms Delay in milliseconds.
*/
function delay(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Retries the given operation until the result is no longer undefined.
* @template T
* @param {() => T | Promise<T>} operation
* @param {Object} [options]
* @param {number} [options.retries] Maximum number of retries.
* @param {number} [options.wait] Number of ms to wait before the next try, disabled by default.
* @returns The final result of the operation.
*/
async function retry(operation, { retries = 10, wait = 0 } = {}) {
do {
const result = await operation();
if (result !== undefined) return result;
if (wait) await delay(wait);
} while (retries--)
}
/**
* Periodically calls the given function until it returns `true` and resolves afterwards.
* @param {(...params) => boolean} pollingFunction
* @param {number} pollingInterval
*/
function waitFor(pollingFunction, pollingInterval) {
return new Promise(async (resolve) => {
while (pollingFunction() === false) {
await delay(pollingInterval);
}
resolve();
});
}
/** Resolves as soon as the React relationship editor is ready. */
function readyRelationshipEditor() {
const reactRelEditor = qs('.release-relationship-editor');
if (!reactRelEditor) return Promise.reject(new Error('Release relationship editor has not been found'));
// wait for the loading message to disappear (takes ~1s)
return waitFor(() => !qs('.release-relationship-editor > .loading-message'), 100);
}
// adapted from https://stackoverflow.com/a/25621277
/**
* Resizes the bound element to be as tall as necessary for its content.
* @this {HTMLElement}
*/
function automaticHeight() {
this.style.height = 'auto';
this.style.height = this.scrollHeight + 'px';
}
/**
* Resizes the bound element to be as wide as necessary for its content.
* @this {HTMLElement} this
*/
function automaticWidth() {
this.style.width = 'auto';
this.style.width = this.scrollWidth + 10 + 'px'; // account for border and padding
}
/**
* Creates a DOM element from the given HTML fragment.
* @param {string} html HTML fragment.
*/
function createElement(html) {
const template = document.createElement('template');
template.innerHTML = html;
return template.content.firstElementChild;
}
/**
* Creates a style element from the given CSS fragment and injects it into the document's head.
* @param {string} css CSS fragment.
* @param {string} userscriptName Name of the userscript, used to generate an ID for the style element.
*/
function injectStylesheet(css, userscriptName) {
const style = document.createElement('style');
if (userscriptName) {
style.id = [userscriptName, 'userscript-css'].join('-');
}
style.innerText = css;
document.head.append(style);
}
/** Pattern to match an ES RegExp string representation. */
const regexPattern = /^\/(.+?)\/([gimsuy]*)$/;
/**
* Escapes special characters in the given string to use it as part of a regular expression.
* @param {string} string
* @link https://stackoverflow.com/a/6969486
*/
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}
/**
* Returns the value of the given pattern as a regular expression if it is enclosed between slashes.
* Otherwise it returns the input string or throws for invalid regular expressions.
* @param {string} pattern
* @returns {RegExp | string}
*/
function getPattern(pattern) {
const match = pattern.match(regexPattern);
if (match) {
return new RegExp(match[1], match[2]);
} else {
return pattern;
}
}
/**
* Converts the value of the given pattern into a regular expression and returns it.
* @param {string} pattern
*/
function getPatternAsRegExp(pattern) {
try {
let value = getPattern(pattern);
if (typeof value === 'string') {
value = new RegExp(escapeRegExp(value));
}
return value;
} catch {
return;
}
}
/**
* Converts a string into an identifier that is compatible with Markdown's heading anchors.
* @param {string} string
*/
function slugify(string) {
return encodeURIComponent(
string.trim()
.toLowerCase()
.replace(/\s+/g, '-')
);
}
/**
* Persists the desired attribute of the given element across page loads and origins.
* @param {HTMLElement} element
* @param {keyof HTMLElement} attribute
* @param {keyof HTMLElementEventMap} eventType
* @param {string | number | boolean} [defaultValue] Default value of the attribute.
*/
async function persistElement(element, attribute, eventType, defaultValue) {
if (!element.id) {
throw new Error('Can not persist an element without ID');
}
const key = ['persist', element.id, attribute].join('.');
// initialize attribute
const persistedValue = await GM.getValue(key, defaultValue);
if (persistedValue) {
element[attribute] = persistedValue;
}
// persist attribute once the event occurs
element.addEventListener(eventType, () => {
GM.setValue(key, element[attribute]);
});
return element;
}
/**
* Persists the state of the checkbox with the given ID across page loads and origins.
* @param {string} id
* @param {boolean} [checkedByDefault]
* @returns {Promise<HTMLInputElement>}
*/
function persistCheckbox(id, checkedByDefault) {
return persistElement(dom(id), 'checked', 'change', checkedByDefault);
}
/**
* Persists the state of the collapsible details container with the given ID across page loads and origins.
* @param {string} id
* @param {boolean} [openByDefault]
* @returns {Promise<HTMLDetailsElement>}
*/
function persistDetails(id, openByDefault) {
return persistElement(dom(id), 'open', 'toggle', openByDefault);
}
/**
* Persists the value of the given input field across page loads and origins.
* @param {HTMLInputElement | HTMLTextAreaElement} element
* @param {string} [defaultValue]
* @returns {Promise<HTMLInputElement>}
*/
function persistInput(element, defaultValue) {
return persistElement(element, 'value', 'change', defaultValue);
}
const creditParserUI = `
<details id="credit-parser">
<summary>
<h2>Credit Parser</h2>
</summary>
<form>
<details id="credit-parser-config">
<summary><h3>Advanced configuration</h3></summary>
<ul id="credit-patterns"></ul>
</details>
<div class="row">
<textarea name="credit-input" id="credit-input" cols="120" rows="1" placeholder="Paste credits here…"></textarea>
</div>
<div class="row">
Identified relationships will be added to the release and/or the matching recordings and works (only if these are selected).
</div>
<div class="row">
<input type="checkbox" name="remove-parsed-lines" id="remove-parsed-lines" />
<label class="inline" for="remove-parsed-lines">Remove parsed lines</label>
<input type="checkbox" name="parser-autofocus" id="parser-autofocus" />
<label class="inline" for="parser-autofocus">Autofocus the parser on page load</label>
</div>
<div class="row buttons">
</div>
</form>
</details>`;
const css = `
details#credit-parser summary {
cursor: pointer;
display: block;
}
details#credit-parser summary > h2, details#credit-parser summary > h3 {
display: list-item;
}
textarea#credit-input {
overflow-y: hidden;
}
#credit-parser label[title] {
border-bottom: 1px dotted;
cursor: help;
}`;
const uiReadyEventType = 'credit-parser-ui-ready';
/**
* Injects the basic UI of the credit parser and waits until the UI has been expanded before it continues with the build tasks.
* @param {...(() => void)} buildTasks Handlers which can be registered for additional UI build tasks.
*/
async function buildCreditParserUI(...buildTasks) {
await readyRelationshipEditor();
/** @type {HTMLDetailsElement} */
const existingUI = dom('credit-parser');
// possibly called by multiple userscripts, do not inject the UI again
if (!existingUI) {
// inject credit parser between the sections for track and release relationships,
// use the "Release Relationships" heading as orientation since #tracklist is missing for releases without mediums
qs('.release-relationship-editor > h2:nth-of-type(2)').insertAdjacentHTML('beforebegin', creditParserUI);
injectStylesheet(css, 'credit-parser');
}
// execute all additional build tasks once the UI is open and ready
if (existingUI && existingUI.open) {
// our custom event already happened because the UI builder code is synchronous
buildTasks.forEach((task) => task());
} else {
// wait for our custom event if the UI is not (fully) initialized or is collapsed
buildTasks.forEach((task) => document.addEventListener(uiReadyEventType, () => task(), { once: true }));
}
if (existingUI) return;
// continue initialization of the UI once it has been opened
persistDetails('credit-parser', true).then((UI) => {
if (UI.open) {
initializeUI();
} else {
UI.addEventListener('toggle', initializeUI, { once: true });
}
});
}
async function initializeUI() {
const creditInput = dom('credit-input');
// persist the state of the UI
persistCheckbox('remove-parsed-lines');
await persistCheckbox('parser-autofocus');
persistDetails('credit-parser-config').then((config) => {
// hidden pattern inputs have a zero width, so they have to be resized if the config has not been open initially
if (!config.open) {
config.addEventListener('toggle', () => {
qsa('input.pattern', config).forEach((input) => automaticWidth.call(input));
}, { once: true });
}
});
// auto-resize the credit textarea on input
creditInput.addEventListener('input', automaticHeight);
// load seeded data from hash
const seededData = new URLSearchParams(window.location.hash.slice(1));
const seededCredits = seededData.get('credits');
if (seededCredits) {
setTextarea(creditInput, seededCredits);
const seededEditNote = seededData.get('edit-note');
if (seededEditNote) {
addMessageToEditNote(seededEditNote);
}
}
addButton('Load annotation', (creditInput) => {
/** @type {ReleaseT} */
const release = MB.getSourceEntityInstance();
const annotation = release.latest_annotation;
if (annotation) {
setTextarea(creditInput, annotation.text);
}
});
addPatternInput({
label: 'Credit terminator',
description: 'Matches the end of a credit (default when empty: end of line)',
defaultValue: parserDefaults.terminatorRE,
});
addPatternInput({
label: 'Credit separator',
description: 'Splits a credit into role and artist (disabled when empty)',
defaultValue: /\s[–-]\s|:\s|\t+/,
});
addPatternInput({
label: 'Name separator',
description: 'Splits the extracted name into multiple names (disabled when empty)',
defaultValue: parserDefaults.nameSeparatorRE,
});
// trigger all additional UI build tasks
document.dispatchEvent(new CustomEvent(uiReadyEventType));
// focus the credit parser input (if this setting is enabled)
if (dom('parser-autofocus').checked) {
creditInput.scrollIntoView();
creditInput.focus();
}
}
/**
* Adds a new button with the given label and click handler to the credit parser UI.
* @param {string} label
* @param {(creditInput: HTMLTextAreaElement, event: MouseEvent) => any} clickHandler
* @param {string} [description] Description of the button, shown as tooltip.
*/
function addButton(label, clickHandler, description) {
/** @type {HTMLTextAreaElement} */
const creditInput = dom('credit-input');
/** @type {HTMLButtonElement} */
const button = createElement(`<button type="button">${label}</button>`);
if (description) {
button.title = description;
}
button.addEventListener('click', (event) => clickHandler(creditInput, event));
return qs('#credit-parser .buttons').appendChild(button);
}
/**
* Adds a new parser button with the given label and handler to the credit parser UI.
* @param {string} label
* @param {(creditLine: string, event: MouseEvent) => import('@kellnerd/es-utils').MaybePromise<CreditParserLineStatus>} parser
* Handler which parses the given credit line and returns whether it was successful.
* @param {string} [description] Description of the button, shown as tooltip.
*/
function addParserButton(label, parser, description) {
/** @type {HTMLInputElement} */
const removeParsedLines = dom('remove-parsed-lines');
return addButton(label, async (creditInput, event) => {
const credits = creditInput.value.split('\n').map((line) => line.trim());
const parsedLines = [], skippedLines = [];
for (const line of credits) {
// skip empty lines, but keep them for display of skipped lines
if (!line) {
skippedLines.push(line);
continue;
}
// treat partially parsed lines as both skipped and parsed
const parserStatus = await parser(line, event);
if (parserStatus !== 'skipped') {
parsedLines.push(line);
}
if (parserStatus !== 'done') {
skippedLines.push(line);
}
}
if (parsedLines.length) {
addMessageToEditNote(parsedLines.join('\n'));
}
if (removeParsedLines.checked) {
setTextarea(creditInput, skippedLines.join('\n'));
}
}, description);
}
/**
* Adds a persisted input field for regular expressions with a validation handler to the credit parser UI.
* @param {object} config
* @param {string} [config.id] ID and name of the input element (derived from `label` if missing).
* @param {string} config.label Content of the label (without punctuation).
* @param {string} config.description Description which should be used as tooltip.
* @param {string} config.defaultValue Default value of the input.
*/
function addPatternInput(config) {
const id = config.id || slugify(config.label);
/** @type {HTMLInputElement} */
const patternInput = createElement(`<input type="text" class="pattern" name="${id}" id="${id}" placeholder="String or /RegExp/" />`);
const explanationLink = document.createElement('a');
explanationLink.innerText = 'help';
explanationLink.target = '_blank';
explanationLink.title = 'Displays a diagram representation of this RegExp';
const resetButton = createElement(`<button type="button" title="Reset the input to its default value">Reset</button>`);
resetButton.addEventListener('click', () => setInput(patternInput, config.defaultValue));
// auto-resize the pattern input on input
patternInput.addEventListener('input', automaticWidth);
// validate pattern and update explanation link on change
patternInput.addEventListener('change', function () {
explanationLink.href = 'https://kellnerd.github.io/regexper/#' + encodeURIComponent(getPatternAsRegExp(this.value) ?? this.value);
this.classList.remove('error', 'success');
this.title = '';
try {
if (getPattern(this.value) instanceof RegExp) {
this.classList.add('success');
this.title = 'Valid regular expression';
}
} catch (error) {
this.classList.add('error');
this.title = `Invalid regular expression: ${error.message}\nThe default value will be used.`;
}
});
// inject label, input, reset button and explanation link
const container = document.createElement('li');
container.insertAdjacentHTML('beforeend', `<label for="${id}" title="${config.description}">${config.label}:</label>`);
container.append(' ', patternInput, ' ', resetButton, ' ', explanationLink);
dom('credit-patterns').appendChild(container);
// persist the input and calls the setter for the initial value (persisted value or the default)
persistInput(patternInput, config.defaultValue).then(setInput);
return patternInput;
}
/**
* Sets the input to the given value (optional), resizes it and triggers persister and validation.
* @param {HTMLInputElement} input
* @param {string} [value]
*/
function setInput(input, value) {
if (value) input.value = value;
automaticWidth.call(input);
input.dispatchEvent(new Event('change'));
}
/**
* Sets the textarea to the given value and adjusts the height.
* @param {HTMLTextAreaElement} textarea
* @param {string} value
*/
function setTextarea(textarea, value) {
textarea.value = value;
automaticHeight.call(textarea);
}
/**
* Extracts the entity type and ID from a MusicBrainz URL (can be incomplete and/or with additional path components and query parameters).
* @param {string} url URL of a MusicBrainz entity page.
* @returns {{ type: CoreEntityTypeT | 'mbid', mbid: MB.MBID } | undefined} Type and ID.
*/
function extractEntityFromURL$1(url) {
const entity = url.match(/(area|artist|event|genre|instrument|label|mbid|place|recording|release|release-group|series|url|work)\/([0-9a-f-]{36})(?:$|\/|\?)/);
return entity ? {
type: entity[1],
mbid: entity[2]
} : undefined;
}
/**
* @param {CoreEntityTypeT} entityType
* @param {MB.MBID | 'add' | 'create'} mbid MBID of an existing entity or `create` for the entity creation page (`add` for releases).
*/
function buildEntityURL$1(entityType, mbid) {
return `https://musicbrainz.org/${entityType}/${mbid}`;
}
/**
* @template Params
* @template Result
* @template {string | number} Key
*/
class FunctionCache {
/**
* @param {(...params: Params) => Result | Promise<Result>} expensiveFunction Expensive function whose results should be cached.
* @param {Object} options
* @param {(...params: Params) => Key[]} options.keyMapper Maps the function parameters to the components of the cache's key.
* @param {string} [options.name] Name of the cache, used as storage key (optional).
* @param {Storage} [options.storage] Storage which should be used to persist the cache (optional).
* @param {Record<Key, Result>} [options.data] Record which should be used as cache (defaults to an empty record).
*/
constructor(expensiveFunction, options) {
this.expensiveFunction = expensiveFunction;
this.keyMapper = options.keyMapper;
this.name = options.name ?? `defaultCache`;
this.storage = options.storage;
this.data = options.data ?? {};
}
/**
* Looks up the result for the given parameters and returns it.
* If the result is not cached, it will be calculated and added to the cache.
* @param {Params} params
*/
async get(...params) {
const keys = this.keyMapper(...params);
const lastKey = keys.pop();
if (!lastKey) return;
const record = this._get(keys);
if (record[lastKey] === undefined) {
// create a new entry to cache the result of the expensive function
const newEntry = await this.expensiveFunction(...params);
if (newEntry !== undefined) {
record[lastKey] = newEntry;
}
}
return record[lastKey];
}
/**
* Manually sets the cache value for the given key.
* @param {Key[]} keys Components of the key.
* @param {Result} value
*/
set(keys, value) {
const lastKey = keys.pop();
this._get(keys)[lastKey] = value;
}
/**
* Loads the persisted cache entries.
*/
load() {
const storedData = this.storage?.getItem(this.name);
if (storedData) {
this.data = JSON.parse(storedData);
}
}
/**
* Persists all entries of the cache.
*/
store() {
this.storage?.setItem(this.name, JSON.stringify(this.data));
}
/**
* Clears all entries of the cache and persists the changes.
*/
clear() {
this.data = {};
this.store();
}
/**
* Returns the cache record which is indexed by the key.
* @param {Key[]} keys Components of the key.
*/
_get(keys) {
let record = this.data;
keys.forEach((key) => {
if (record[key] === undefined) {
// create an empty record for all missing keys
record[key] = {};
}
record = record[key];
});
return record;
}
}
/**
* @template Params
* @template Result
* @template {string | number} Key
* @extends {FunctionCache<Params, Result, Key>}
*/
class SimpleCache extends FunctionCache {
/**
* @param {Object} options
* @param {string} [options.name] Name of the cache, used as storage key (optional).
* @param {Storage} [options.storage] Storage which should be used to persist the cache (optional).
* @param {Record<Key, Result>} [options.data] Record which should be used as cache (defaults to an empty record).
*/
constructor(options) {
// use a dummy function to make the function cache fail without actually running an expensive function
super((...params) => undefined, {
...options,
keyMapper: (...params) => params,
});
}
}
/** @type {SimpleCache<[entityType: CoreEntityTypeT, name: string], MB.MBID>} */
const nameToMBIDCache = new SimpleCache({
name: 'nameToMBIDCache',
storage: window.localStorage,
});
/**
* Extracts the entity type and ID from a Discogs URL.
* @param {string} url URL of a Discogs entity page.
* @returns {[Discogs.EntityType,string]|undefined} Type and ID.
*/
function extractEntityFromURL(url) {
return url.match(/(artist|label|master|release)\/(\d+)/)?.slice(1);
}
/**
* @param {Discogs.EntityType} entityType
* @param {number} entityId
*/
function buildEntityURL(entityType, entityId) {
return `https://www.discogs.com/${entityType}/${entityId}`;
}
/**
* @param {Discogs.EntityType} entityType
* @param {number} entityId
*/
function buildApiURL(entityType, entityId) {
return `https://api.discogs.com/${entityType}s/${entityId}`;
}
// Adapted from https://thoughtspile.github.io/2018/07/07/rate-limit-promises/
function rateLimitedQueue(operation, interval) {
let queue = Promise.resolve(); // empty queue is ready
return (...args) => {
const result = queue.then(() => operation(...args)); // queue the next operation
// start the next delay, regardless of the last operation's success
queue = queue.then(() => delay(interval), () => delay(interval));
return result;
};
}
/**
* Limits the number of requests for the given operation within a time interval.
* @template Params
* @template Result
* @param {(...args: Params) => Result} operation Operation that should be rate-limited.
* @param {number} interval Time interval (in ms).
* @param {number} requestsPerInterval Maximum number of requests within the interval.
* @returns {(...args: Params) => Promise<Result>} Rate-limited version of the given operation.
*/
function rateLimit(operation, interval, requestsPerInterval = 1) {
if (requestsPerInterval == 1) {
return rateLimitedQueue(operation, interval);
}
const queues = Array(requestsPerInterval).fill().map(() => rateLimitedQueue(operation, interval));
let queueIndex = 0;
return (...args) => {
queueIndex = (queueIndex + 1) % requestsPerInterval; // use the next queue
return queues[queueIndex](...args); // return the result of the operation
};
}
/**
* Calls to the MusicBrainz API are limited to one request per second.
* https://musicbrainz.org/doc/MusicBrainz_API
*/
const callAPI$1 = rateLimit(fetch, 1000);
/**
* Requests the given entity from the MusicBrainz API.
* @param {string} url (Partial) URL which contains the entity type and the entity's MBID.
* @param {string[]} inc Include parameters which should be added to the API request.
* @returns {Promise<MB.Entity>}
*/
function fetchEntity$1(url, inc) {
const entity = extractEntityFromURL$1(url);
if (!entity) throw new Error('Invalid entity URL');
const endpoint = [entity.type, entity.mbid].join('/');
return fetchFromAPI(endpoint, {}, inc);
}
/**
* Returns the entity of the desired type which is associated to the given resource URL.
* @param {CoreEntityTypeT} entityType Desired type of the entity.
* @param {string} resourceURL
* @returns {Promise<MB.Entity>} The first matching entity. (TODO: handle ambiguous URLs)
*/
async function getEntityForResourceURL(entityType, resourceURL) {
try {
const url = await fetchFromAPI('url', { resource: resourceURL }, [`${entityType}-rels`]);
return url?.relations.filter((rel) => rel['target-type'] === entityType)?.[0][entityType];
} catch (error) {
return null;
}
}
/**
* Makes a request to the MusicBrainz API of the currently used server and returns the results as JSON.
* @param {string} endpoint Endpoint (e.g. the entity type) which should be queried.
* @param {Record<string,string>} query Query parameters.
* @param {string[]} inc Include parameters which should be added to the query parameters.
*/
async function fetchFromAPI(endpoint, query = {}, inc = []) {
if (inc.length) {
query.inc = inc.join(' '); // spaces will be encoded as `+`
}
query.fmt = 'json';
const headers = {
'Accept': 'application/json',
// 'User-Agent': 'Application name/<version> ( contact-url )',
};
const response = await callAPI$1(`https://musicbrainz.org/ws/2/${endpoint}?${new URLSearchParams(query)}`, { headers });
if (response.ok) {
return response.json();
} else {
throw response;
}
}
const DISCOGS_ENTITY_TYPES = {
artist: 'artist',
label: 'label',
release: 'release',
'release_group': 'master',
};
/**
* Maps Discogs IDs to MBIDs.
* @param {MB.EntityType} entityType
* @param {number} discogsId
*/
async function discogsToMBID(entityType, discogsId) {
const discogsType = DISCOGS_ENTITY_TYPES[entityType];
if (!discogsType) return;
const entity = await getEntityForResourceURL(entityType, buildEntityURL(discogsType, discogsId));
return entity?.id;
}
/**
* Cache for the mapping of Discogs entities to the MBIDs of their equivalent entities on MusicBrainz.
*/
const discogsToMBIDCache = new FunctionCache(discogsToMBID, {
keyMapper: (type, id) => [type, id],
name: 'discogsToMBIDCache',
storage: window.localStorage,
});
/**
* Creates an URL to seed the editor of the given entity with the given external link.
* @param {MB.EntityType} type Type of the target entity.
* @param {MB.MBID} mbid MBID of the target entity.
* @param {string} url External link.
* @param {number} linkTypeID
* @param {string} [editNote]
*/
function seedURLForEntity(type, mbid, url, linkTypeID, editNote) {
const seedingParams = new URLSearchParams({
[`edit-${type}.url.0.text`]: url,
[`edit-${type}.url.0.link_type_id`]: linkTypeID,
});
if (editNote) {
seedingParams.set(`edit-${type}.edit_note`, buildEditNote(editNote));
}
return `${buildEntityURL$1(type, mbid)}/edit?${seedingParams}`;
}
/**
* Creates a dialog to add a relationship to the given source entity.
* @param {Object} options
* @param {CoreEntityT} [options.source] Source entity, defaults to the currently edited entity.
* @param {CoreEntityT | string} [options.target] Target entity object or name.
* @param {CoreEntityTypeT} [options.targetType] Target entity type, fallback if there is no full entity given.
* @param {number} [options.linkTypeId] Internal ID of the relationship type.
* @param {ExternalLinkAttrT[]} [options.attributes] Attributes for the relationship type.
* @param {boolean} [options.batchSelection] Batch-edit all selected entities which have the same type as the source.
* The source entity only acts as a placeholder in this case.
*/
async function createDialog({
source = MB.relationshipEditor.state.entity,
target,
targetType,
linkTypeId,
attributes,
batchSelection = false,
} = {}) {
const onlyTargetName = (typeof target === 'string');
// prefer an explicit target entity option over only a target type
if (target && !onlyTargetName) {
targetType = target.entityType;
}
// open dialog modal for the source entity
MB.relationshipEditor.dispatch({
type: 'update-dialog-location',
location: {
source,
batchSelection,
},
});
// TODO: currently it takes ~2ms until `relationshipDialogDispatch` is exposed
await waitFor(() => !!MB.relationshipEditor.relationshipDialogDispatch, 1);
if (targetType) {
MB.relationshipEditor.relationshipDialogDispatch({
type: 'update-target-type',
source,
targetType,
});
}
if (linkTypeId) {
const linkTypeItem = await retry(() => {
// the available items are only valid for the current target type,
// ensure that they have already been updated after a target type change
const availableLinkTypes = MB.relationshipEditor.relationshipDialogState.linkType.autocomplete.items;
return availableLinkTypes.find((item) => (item.id == linkTypeId));
}, { wait: 10 });
if (linkTypeItem) {
MB.relationshipEditor.relationshipDialogDispatch({
type: 'update-link-type',
source,
action: {
type: 'update-autocomplete',
source,
action: {
type: 'select-item',
item: linkTypeItem,
},
},
});
}
}
if (attributes) {
setAttributes(attributes);
}
if (!target) return;
/** @type {AutocompleteActionT[]} */
const autocompleteActions = onlyTargetName ? [{
type: 'type-value',
value: target,
}, { // search dropdown is unaffected by future actions which set credits or date periods
type: 'search-after-timeout',
searchTerm: target,
}] : [{
type: 'select-item',