-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathparseCopyrightNotice.user.js
1412 lines (1246 loc) · 44.9 KB
/
parseCopyrightNotice.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: Parse copyright notice
// @version 2024.7.1
// @namespace https://github.com/kellnerd/musicbrainz-scripts
// @author kellnerd
// @description Parses copyright notices and automates the process of creating release and recording relationships for these.
// @homepageURL https://github.com/kellnerd/musicbrainz-scripts#parse-copyright-notice
// @downloadURL https://raw.github.com/kellnerd/musicbrainz-scripts/main/dist/parseCopyrightNotice.user.js
// @updateURL https://raw.github.com/kellnerd/musicbrainz-scripts/main/dist/parseCopyrightNotice.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';
/** @returns {DatePeriodRoleT} */
function createDatePeriodForYear(year) {
return {
begin_date: { year },
end_date: { year },
ended: true,
};
}
/**
* @param {CoreEntityTypeT} sourceType
* @param {CoreEntityTypeT} targetType
*/
function isRelBackward(sourceType, targetType, changeDirection = false) {
if (sourceType === targetType) return changeDirection;
return sourceType > targetType;
}
/**
* Taken from https://github.com/metabrainz/musicbrainz-server/blob/bf0d5ec41c7ddb6c5a8396bf3a64f74acaef9337/root/static/scripts/relationship-editor/hooks/useRelationshipDialogContent.js
* @type {Partial<import('../types/MBS/scripts/relationship-editor/state').RelationshipStateT>}
*/
const RELATIONSHIP_DEFAULTS = {
_lineage: [],
_original: null,
_status: 1, // add relationship
attributes: null,
begin_date: null,
editsPending: false,
end_date: null,
ended: false,
entity0_credit: '',
entity1_credit: '',
id: null,
linkOrder: 0,
linkTypeID: null,
};
/**
* 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();
});
}
/**
* 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);
}
/**
* 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',
item: entityToSelectItem(target),
}];
// autofill the target entity as good as possible
autocompleteActions.forEach((autocompleteAction) => {
MB.relationshipEditor.relationshipDialogDispatch({
type: 'update-target-entity',
source,
action: {
type: 'update-autocomplete',
source,
action: autocompleteAction,
},
});
});
// focus target entity input if it could not be auto-selected
if (onlyTargetName) {
qs('input.relationship-target').focus();
}
}
/**
* Creates a dialog to batch-add a relationship to each of the selected source entities.
* @param {import('weight-balanced-tree').ImmutableTree<CoreEntityT>} sourceSelection Selected source entities.
* @param {Omit<Parameters<typeof createDialog>[0], 'batchSelection' | 'source'>} options
*/
function createBatchDialog(sourceSelection, options = {}) {
return createDialog({
...options,
source: sourceSelection.value, // use the root node entity as a placeholder
batchSelection: true,
});
}
/**
* Resolves after the current/next relationship dialog has been closed.
* @returns {Promise<RelationshipDialogFinalStateT>} The final state of the dialog when it was closed by the user.
*/
async function closingDialog() {
return new Promise((resolve) => {
// wait for the user to accept or cancel the dialog
document.addEventListener('mb-close-relationship-dialog', (event) => {
const finalState = event.dialogState;
finalState.closeEventType = event.closeEventType;
resolve(finalState);
}, { once: true });
});
}
/** @param {string} creditedAs Credited name of the target entity. */
function creditTargetAs(creditedAs) {
MB.relationshipEditor.relationshipDialogDispatch({
type: 'update-target-entity',
source: MB.relationshipEditor.state.dialogLocation.source,
action: {
type: 'update-credit',
action: {
type: 'set-credit',
creditedAs,
},
},
});
}
/**
* Sets the begin or end date of the current dialog.
* @param {PartialDateT} date
*/
function setDate(date, isBegin = true) {
MB.relationshipEditor.relationshipDialogDispatch({
type: 'update-date-period',
action: {
type: isBegin ? 'update-begin-date' : 'update-end-date',
action: {
type: 'set-date',
date: date,
},
},
});
}
/** @param {DatePeriodRoleT} datePeriod */
function setDatePeriod(datePeriod) {
setDate(datePeriod.begin_date, true);
setDate(datePeriod.end_date, false);
MB.relationshipEditor.relationshipDialogDispatch({
type: 'update-date-period',
action: {
type: 'set-ended',
enabled: datePeriod.ended,
},
});
}
/** @param {number} year */
function setYear(year) {
setDatePeriod({
begin_date: { year },
end_date: { year },
ended: true,
});
}
/**
* Sets the relationship attributes of the current dialog.
* @param {ExternalLinkAttrT[]} attributes
*/
function setAttributes(attributes) {
MB.relationshipEditor.relationshipDialogDispatch({
type: 'set-attributes',
attributes,
});
}
/**
* @param {EntityItemT} entity
* @returns {OptionItemT}
*/
function entityToSelectItem(entity) {
return {
type: 'option',
id: entity.id,
name: entity.name,
entity,
};
}
/**
* @typedef {import('../types/MBS/scripts/autocomplete2.js').EntityItemT} EntityItemT
* @typedef {import('../types/MBS/scripts/autocomplete2.js').OptionItemT<EntityItemT>} OptionItemT
* @typedef {import('../types/MBS/scripts/autocomplete2.js').ActionT<EntityItemT>} AutocompleteActionT
* @typedef {import('../types/MBS/scripts/relationship-editor/state.js').ExternalLinkAttrT} ExternalLinkAttrT
* @typedef {import('../types/MBS/scripts/relationship-editor/state.js').RelationshipDialogStateT & { closeEventType: 'accept' | 'cancel' }} RelationshipDialogFinalStateT
*/
/**
* Creates a relationship between the given source and target entity.
* @param {RelationshipProps & { source?: CoreEntityT, target: CoreEntityT, batchSelectionCount?: number }} options
* @param {CoreEntityT} [options.source] Source entity, defaults to the currently edited entity.
* @param {CoreEntityT} options.target Target entity.
* @param {number} [options.batchSelectionCount] Batch-edit all selected entities which have the same type as the source.
* The source entity only acts as a placeholder in this case.
* @param {RelationshipProps} props Relationship properties.
*/
function createRelationship({
source = MB.relationshipEditor.state.entity,
target,
batchSelectionCount = null,
...props
}) {
const backward = isRelBackward(source.entityType, target.entityType, props.backward ?? false);
MB.relationshipEditor.dispatch({
type: 'update-relationship-state',
sourceEntity: source,
batchSelectionCount,
creditsToChangeForSource: '',
creditsToChangeForTarget: '',
newRelationshipState: {
...RELATIONSHIP_DEFAULTS,
entity0: backward ? target : source,
entity1: backward ? source : target,
id: MB.relationshipEditor.getRelationshipStateId(),
...props,
},
oldRelationshipState: null,
});
}
/**
* Creates the same relationship between each of the selected source entities and the given target entity.
* @param {import('weight-balanced-tree').ImmutableTree<CoreEntityT>} sourceSelection Selected source entities.
* @param {CoreEntityT} target Target entity.
* @param {RelationshipProps} props Relationship properties.
*/
function batchCreateRelationships(sourceSelection, target, props) {
return createRelationship({
source: sourceSelection.value, // use the root node entity as a placeholder
target,
batchSelectionCount: sourceSelection.size,
...props,
});
}
/**
* @typedef {import('weight-balanced-tree').ImmutableTree<LinkAttrT>} LinkAttrTree
* @typedef {Partial<Omit<RelationshipT, 'attributes'> & { attributes: LinkAttrTree }>} RelationshipProps
* @typedef {import('../types/MBS/scripts/relationship-editor/state.js').ExternalLinkAttrT} ExternalLinkAttrT
*/
/**
* MBS relationship link type IDs (incomplete).
* @type {Record<CoreEntityTypeT, Record<CoreEntityTypeT, Record<string, number>>>}
*/
const LINK_TYPES = {
release: {
artist: {
'©': 709,
'℗': 710,
},
label: {
'©': 708,
'℗': 711,
'licensed from': 712,
'licensed to': 833,
'distributed by': 361,
'manufactured by': 360,
'marketed by': 848,
},
},
recording: {
artist: {
'℗': 869,
},
label: {
'℗': 867,
},
},
};
/**
* Returns the internal ID of the requested relationship link type.
* @param {CoreEntityTypeT} sourceType Type of the source entity.
* @param {CoreEntityTypeT} targetType Type of the target entity.
* @param {string} relType
*/
function getLinkTypeId(sourceType, targetType, relType) {
const linkTypeId = LINK_TYPES[targetType]?.[sourceType]?.[relType];
if (linkTypeId) {
return linkTypeId;
} else {
throw new Error(`Unsupported ${sourceType}-${targetType} relationship type '${relType}'`);
}
}
/**
* Fetches the entity with the given MBID from the internal API ws/js.
* @param {MB.MBID} gid MBID of the entity.
* @returns {Promise<CoreEntityT>}
*/
async function fetchEntity(gid) {
const result = await fetch(`/ws/js/entity/${gid}`);
return result.json();
}
/**
* @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;
}
}
/**
* Temporary cache for fetched entities from the ws/js API.
*/
const entityCache = new FunctionCache(fetchEntity, {
keyMapper: (gid) => [gid],
});
/**
* @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,
});
/**
* Converts an array with a single element into a scalar.
* @template T
* @param {T | T[]} maybeArray
* @returns A scalar or the input array if the conversion is not possible.
*/
function preferScalar(maybeArray) {
if (Array.isArray(maybeArray) && maybeArray.length === 1) return maybeArray[0];
return maybeArray;
}
/**
* Converts a scalar into an array with a single element.
* @template T
* @param {T | T[]} maybeArray
*/
function preferArray(maybeArray) {
if (!Array.isArray(maybeArray)) return [maybeArray];
return maybeArray;
}
/**
* Simplifies the given name to ease matching of strings.
* @param {string} name
*/
function simplifyName(name) {
return name.normalize('NFKD') // Unicode NFKD compatibility decomposition
.replace(/[^\p{L}\d]/ug, '') // keep only letters and numbers, remove e.g. combining diacritical marks of decompositions
.toLowerCase();
}
/**
* Creates and fills an "Add relationship" dialog for each piece of copyright information.
* Lets the user choose the appropriate target label or artist and waits for the dialog to close before continuing with the next one.
* @param {CopyrightItem[]} copyrightInfo List of copyright items.
* @param {object} [customOptions]
* @param {boolean} [customOptions.bypassCache] Bypass the name to MBID cache to overwrite wrong entries, disabled by default.
* @param {boolean} [customOptions.forceArtist] Force names to be treated as artist names, disabled by default.
* @param {boolean} [customOptions.useAllYears] Adds one (release) relationship for each given year instead of a single undated relationship, disabled by default.
* @returns {Promise<CreditParserLineStatus>} Status of the given copyright info (Have relationships been added for all copyright items?).
*/
async function addCopyrightRelationships(copyrightInfo, customOptions = {}) {
// provide default options
const options = {
bypassCache: false,
forceArtist: false,
useAllYears: false,
...customOptions,
};
/** @type {ReleaseT} */
const release = MB.getSourceEntityInstance();
const releaseArtistNames = release.artistCredit.names // all release artists
.flatMap((name) => [name.name, name.artist.name]) // entity name & credited name (possible redundancy doesn't matter)
.map(simplifyName);
/** @type {import('weight-balanced-tree').ImmutableTree<RecordingT> | null} */
const selectedRecordings = MB.relationshipEditor.state.selectedRecordings;
let addedRelCount = 0;
let skippedDialogs = false;
for (const copyrightItem of copyrightInfo) {
// detect artists who own the copyright of their own release
const targetType = options.forceArtist || releaseArtistNames.includes(simplifyName(copyrightItem.name)) ? 'artist' : 'label';
/**
* There are multiple ways to fill the relationship's target entity:
* (1) Directly map the name to an MBID (if the name is already cached).
* (2) Just fill in the name and let the user select an entity (in manual mode or when the cache is bypassed).
*/
const targetMBID = !options.bypassCache && await nameToMBIDCache.get(targetType, copyrightItem.name); // (1a)
let targetEntity = targetMBID
? await entityCache.get(targetMBID) // (1b)
: copyrightItem.name; // (2a)
for (const type of copyrightItem.types) {
// add all copyright rels to the release
try {
const linkTypeId = getLinkTypeId(targetType, 'release', type);
let years = preferArray(copyrightItem.year);
// do not use all years if there are multiple unspecific ones (unless enabled)
if (years.length !== 1 && !options.useAllYears) {
years = [undefined]; // prefer a single undated relationship
}
for (const year of years) {
if (typeof targetEntity === 'string') { // (2b)
await createDialog({
target: targetEntity,
targetType: targetType,
linkTypeId,
});
targetEntity = await fillAndProcessDialog({ ...copyrightItem, year });
} else { // (1c)
createRelationship({
target: targetEntity,
linkTypeID: linkTypeId,
entity0_credit: copyrightItem.name,
...(year ? createDatePeriodForYear(year) : {}),
});
addedRelCount++;
}
}
} catch (error) {
console.warn(`Skipping copyright item for '${copyrightItem.name}':`, error.message);
skippedDialogs = true;
}
// also add phonographic copyright rels to all selected recordings
if (type === '℗' && selectedRecordings) {
try {
const linkTypeId = getLinkTypeId(targetType, 'recording', type);
if (typeof targetEntity === 'string') {
await createBatchDialog(selectedRecordings, {
target: targetEntity,
linkTypeId,
});
targetEntity = await fillAndProcessDialog(copyrightItem);
} else {
// do not fill the date if there are multiple unspecific years
let datePeriod = {};
if (copyrightItem.year && !Array.isArray(copyrightItem.year)) {
datePeriod = createDatePeriodForYear(copyrightItem.year);
}
batchCreateRelationships(selectedRecordings, targetEntity, {
linkTypeID: linkTypeId,
entity0_credit: copyrightItem.name,
...datePeriod,
});
addedRelCount += selectedRecordings.size;
}
} catch (error) {
console.warn(`Skipping copyright item for '${copyrightItem.name}':`, error.message);
skippedDialogs = true;
}
}
}
}
return addedRelCount > 0 ? (skippedDialogs ? 'partial' : 'done') : 'skipped';
/**
* @param {CopyrightItem} copyrightItem
*/
async function fillAndProcessDialog(copyrightItem) {
creditTargetAs(copyrightItem.name);
// do not fill the date if there are multiple unspecific years
if (copyrightItem.year && !Array.isArray(copyrightItem.year)) {
setYear(copyrightItem.year);
}
// remember the entity which the user has chosen for the given name
const finalState = await closingDialog();
if (finalState.closeEventType === 'accept') {
const targetEntity = finalState.targetEntity.target;
const creditedName = finalState.targetEntity.creditedAs;
nameToMBIDCache.set([targetEntity.entityType, creditedName || targetEntity.name], targetEntity.gid);
addedRelCount++;
return targetEntity;
} else {
skippedDialogs = true;
return copyrightItem.name; // keep name as target entity
}
}
}
// 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 }));
}
/**
* 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';
/**
* Returns the unique elements of the given array (JSON comparison).
* @template T
* @param {T[]} array
*/
function getUniqueElementsByJSON(array) {
// use a Map to keep the order of elements, the JSON representation is good enough as a unique key for our use
return Array.from(new Map(
array.map((element) => [JSON.stringify(element), element])
).values());
}
/**
* 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;
}
const copyrightRE = /([©℗](?:\s*[&+]?\s*[©℗])?)(?:.+?;)?\s*(\d{4}(?:\s*[,&/+]\s*\d{4})*)?(?:[^,.]*\sby|\sthis\scompilation)?\s+/;
const legalInfoRE = /((?:(?:licen[sc]ed?\s(?:to|from)|(?:distributed|manufactured|marketed)(?:\sby)?)(?:\sand)?\s)+)/;
/** @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/,
};
/**
* Extracts all copyright and legal information from the given text.
* @param {string} text
* @param {Partial<CreditParserOptions>} [customOptions]
*/
function parseCopyrightNotice(text, customOptions = {}) {
// provide default options
const options = {
...parserDefaults,
...customOptions,
};
/** @type {CopyrightItem[]} */
const copyrightInfo = [];
const namePattern = options.nameRE.source;
const terminatorPattern = options.terminatorRE.source;
// standardize copyright notice
text = transform(text, [
[/\(C\)/gi, '©'],
[/\(P\)/gi, '℗'],
// remove a-tisket's French quotes
[/«(.+?)»/g, '$1'],
// simplify region-specific copyrights
[/for (.+?) and (.+?) for the world outside (?:of )?\1/g, '/ $2'],
// simplify license text
[/as licen[sc]ee for/gi, 'under license from'],
// drop confusingly used ℗ symbols and text between ℗ symbol and year
[/℗\s*(under\s)/gi, '$1'],
[/(?<=℗\s*)digital remaster/gi, ''],
// split © & ℗ with different years into two lines
[/([©℗]\s*\d{4})\s*[&+]?\s*([©℗]\s*\d{4})(.+)$/g, '$1$3\n$2$3'],
]);
const copyrightMatches = text.matchAll(new RegExp(
String.raw`${copyrightRE.source}(?:\s*[–-]\s+)?(${namePattern}(?:\s*/\s*${namePattern})*)(?:${terminatorPattern})`,
'gimu'));
for (const match of copyrightMatches) {
const names = match[3].split(options.nameSeparatorRE).map((name) => name.trim());
const types = match[1].split(/[&+]|(?<=[©℗])\s*(?=[©℗])/).map(cleanType);
const years = match[2]?.split(/[,&/+]/).map((year) => year.trim());
names.forEach((name) => {
// skip fake copyrights which contain the release label
if (/an?\s(.+?)\srelease/i.test(name)) return;
copyrightInfo.push({
name,
types,
year: preferScalar(years),
});
});
}
const legalInfoMatches = text.matchAll(new RegExp(
String.raw`${legalInfoRE.source}(?:\s*[–-]\s+)?(${namePattern})(?:${terminatorPattern})`,
'gimu'));
for (const match of legalInfoMatches) {
const types = match[1].split(/\sand\s/).map(cleanType);
copyrightInfo.push({
name: match[2],
types,
});
}
return getUniqueElementsByJSON(copyrightInfo);
}
/**
* Cleans and standardizes the given free text copyright/legal type.
* @param {string} type
*/
function cleanType(type) {
return transform(type.toLowerCase().trim(), [
[/licen[sc]ed?/g, 'licensed'],
[/(distributed|manufactured|marketed)(\sby)?/, '$1 by'],
]);
}
/** 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) {