-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutility_functions.js
288 lines (248 loc) · 10.5 KB
/
utility_functions.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
// ==UserScript==
// @name Utility functions
// @version 2019.4.23.0
// @namespace https://github.com/brianfreud
// @downloadURL https://raw.githubusercontent.com/brianfreud/Userscripts/edit/master/utility_functions.js
// @updateURL https://raw.githubusercontent.com/brianfreud/Userscripts/edit/master/utility_functions.js
/* globals MBImport */
/* eslint array-bracket-newline: off */
/* eslint array-element-newline: off */
/* eslint brace-style: ["error", "stroustrup", { "allowSingleLine": true }] */
/* eslint camelcase: off */
/* eslint capitalized-comments: off */
/* eslint dot-location: ["error", "property"] */
/* eslint-env es6, jquery */
/* eslint id-length: off */
/* eslint key-spacing: off */
/* eslint line-comment-position: off */
/* eslint max-len: off */
/* eslint max-lines: off */
/* eslint multiline-comment-style: off */
/* eslint newline-per-chained-call: off */
/* eslint no-extra-parens: ["error", "all", { "nestedBinaryExpressions": false }] */
/* eslint no-inline-comments: off */
/* eslint no-invalid-this: off */
/* eslint no-magic-numbers: off */
/* eslint no-param-reassign: off */
/* eslint no-plusplus: off */
/* eslint no-ternary: off */
/* eslint no-whitespace-before-property: off */
/* eslint object-curly-spacing: off */
/* eslint one-var: off */
/* eslint padded-blocks: off */
/* eslint prefer-destructuring: off */
/* eslint prefer-named-capture-group: off */
/* eslint prefer-reflect: off */
/* eslint quote-props: ["error", "as-needed"] */
/* eslint quotes: ["error", "backtick"] */
/* eslint sort-keys: off */
/* eslint sort-vars: off */
/* eslint spaced-comment: off */
// ==/UserScript==
const ß = {};
(function strictWrapper () {
'use strict';
Object.defineProperties(String.prototype, { // eslint-disable-line no-extend-native
/**
* Removes a string or regex match from a string.
* @extends external:String
* @param {string|regex} matcher - The match expression to remove
*/
remove: {
value: function value (matcher) {
return this.replace(matcher, ``);
}
},
/**
* Converts a string to titlecase.
* @extends external:String
*/
toTitleCase: {
value: function value () {
return this.toLowerCase()
.split(` `)
.map((a) => a.substr(0, 1).toUpperCase() + a.substr(1))
.join(` `);
}
}
});
Object.assign(ß, {
data: {},
/**
* Wrapper for handling track scraping.
* @param {Object} obj - An object containing 2 properties
* @param {string} obj.trackSelector - A selector {string} that selects all (or a group of) tracks
* @param {function} obj.trackParser - A function that extracts to an {object} the data for a single track
* @returns {Array} - Array of objects, one for each track's data
*/
getTracks: (obj) => {
const allTracks = Object.freeze(document.querySelectorAll(obj.trackSelector).entries()),
trackDB = [];
for (const [, element] of allTracks) {
trackDB.push(obj.trackParser(element));
}
return trackDB;
},
// Sorts the track array by track number
sortTracks () { ß.data.tracks = ß.data.tracks.sort((first, second) => parseInt(first.number, 10) - parseInt(second.number, 10)); },
// Sets the total number of tracks to the number of tracks in the track array.
// Warning: If the tracklist is incomplete on the site, this number may NOT be the same as the total number of tracks on the release!
setTotalTracks () { ß.data.totalTracks = ß.data.tracks.length; },
// Turns artist data for each tracks into an array of artist names.
cleanTrackArtists () {
// Turn variations of 'Foo Bar (BMI) 25% [362303688], Caz Dip (ASCAP) 75% [12345678]' into 'Foo Bar, Caz Dip'
const cleanArtistInfo = (str) => str
.remove(/\[\d+\]/gu)
.remove(/(\(…|\s)\d+%/gu) // handle the normal ' 50%' as well as ' (…50%'
.remove(new RegExp([
`APRA`,
`ASCAP`,
`BMI`,
`BUMA`,
`GEMA`,
`KODA`,
`PPL`,
`PRS`,
`SACM`,
`SACEM`,
`SESAC`,
`SOCAN`,
`STEMRA`
].join(`|`), `gu`))
.remove(/\(\)/gu)
.remove(/\s+(?=,)/gu)
.trim();
// Converts artist data into an array of artist names
const buildArtistArray = (data) => // eslint-disable-next-line implicit-arrow-linebreak
[Array.isArray(data)
? data
: data.split(/\s*,(?!\s?jr)\s*/gu)
].flat()
.map((name) => name.toTitleCase());
ß.data.artistList = new Set();
for (const track of ß.data.tracks) {
if (Array.isArray(track.artist)) {
for (let arrayEntry of track.artist) {
arrayEntry = cleanArtistInfo(arrayEntry);
}
}
else {
track.artist = buildArtistArray(cleanArtistInfo(track.artist));
}
track.artist = track.artist.sort();
ß.data.artistList.add(JSON.stringify(track.artist));
}
},
lookupTrackArtists () {
const getJoinPhrase = (artistList, i) => {
if (artistList.length > 1) {
if (artistList.length - 1 !== i) {
return artistList.length - 2 === i
? ` & `
: `, `;
}
} // else
return ``;
};
for (const track of ß.data.tracks) {
if (track.artist === `unknown`) {
track.artist_credit = [MBImport.specialArtist(`unknown`)];
}
else {
const creditArray = [];
for (const [i, name] of [...track.artist].entries()) {
const credit = {
artist_name: name.toTitleCase(),
joinphrase: getJoinPhrase(track.artist, i),
mbid: ß.artistDB.get(name.toLowerCase()) || ``
};
creditArray.push(credit);
}
track.artist_credit = creditArray;
}
}
},
// Sets the release artist
setReleaseArtist () {
ß.data.releaseArtist = ß.data.artistList.size === 1 // How many artists for for release's tracks?
? ß.data.tracks[0].artist_credit // One
: [MBImport.specialArtist(`various_artists`)]; // Multiple
},
buildLabelCredit: () => {
const label = ß.labelDB.filter((labelEntry) => labelEntry.name === ß.data.label.toLowerCase());
if (typeof label === `undefined` || !label.length) {
return [{
catno: ß.data.catNum,
name: ß.data.label.toTitleCase()
}];
} // else
return [{
catno: ß.data.catNum,
country: `country` in label[0]
? label[0].country
: ``,
mbid: label[0].mbid,
name: label[0].name
}];
},
buildReleaseObject: (format = `CD`) => {
const releaseObj = {
title: ß.data.releaseName.replace(/\s+(?:-\s)?Vol(?:ume)?\.?\s/ui, `, Volume `),
artist_credit: ß.data.releaseArtist,
type: `album`,
status: `official`,
language: `eng`,
script: `Latn`,
year: ß.data.year || ``,
month: ß.data.month || ``,
day: ß.data.day || ``,
labels: ß.buildLabelCredit(),
urls: [{
url: ß.data.url,
link_type: 288
}],
discs: [{
format,
tracks: ß.data.tracks
}]
};
releaseObj.country = releaseObj.labels[0].country;
return releaseObj;
},
buildImportButton: (args) => {
const edit_note = MBImport.makeEditNote(ß.data.url, args.site, ``, `https://github.com/brianfreud/Userscripts/`),
releaseObj = ß.buildReleaseObject(args.type || `Digital Media`);
return MBImport.buildFormParameters(releaseObj, edit_note);
},
extractDMY: (date) => ({
day: date.getDate(),
month: date.getMonth() + 1,
year: date.getFullYear()
}),
convertUNIXDate: (seconds) => {
const date = new Date(seconds * 1000); // multiply by 1000 to convert seconds to ms for Date()
return ß.extractDMY(date);
},
formatSeconds: (seconds) => {
seconds = Math.round(seconds);
return ((seconds - (seconds %= 60)) / 60) + (seconds > 9
? `:`
: `:0`) + seconds;
},
unSortname: (str) => { // Turns "Jones, Bob" back into "Bob Jones"
const name = str.split(`,`)
.map((a) => a.trim());
return [name.splice(-1), name].flat().join(` `);
},
// Turn ["Jones, Bob"] into ["bob jones"]
unSortnameArray: (arr) => arr.map((name) => ß.unSortname(name.toLowerCase())),
getIDText: (str) => ß.$getID(str).text(),
$getTDs: (node) => $(node).find(`td`),
getTDText: ($nodes, i) => $.trim($nodes.eq(i).text()),
buildImportTools: (prefix = ``) => {
Object.assign(ß, {
$getID: (str) => $(`#${prefix}${str}`)
});
}
});
}());