Applied prettier and eslint tools on existing code

None of these changes are manual changes made a human
This commit is contained in:
Aurélien Mino 2018-11-20 23:18:49 +01:00
parent 6c721d7c96
commit 14a32dab62
28 changed files with 6205 additions and 5745 deletions

View file

@ -1,28 +1,28 @@
# MusicBrainz UserScripts # MusicBrainz UserScripts
* [Display shortcut for relationships on MusicBrainz](#mb_relationship_shortcuts) - [Display shortcut for relationships on MusicBrainz](#mb_relationship_shortcuts)
* [Import Bandcamp releases to MusicBrainz](#bandcamp_importer) - [Import Bandcamp releases to MusicBrainz](#bandcamp_importer)
* [Import Bandcamp releases to MusicBrainz Album Link Helper](#bandcamp_importer_helper) - [Import Bandcamp releases to MusicBrainz Album Link Helper](#bandcamp_importer_helper)
* [Import Beatport Pro releases to MusicBrainz](#beatport_pro_importer) - [Import Beatport Pro releases to MusicBrainz](#beatport_pro_importer)
* [Import Beatport releases to MusicBrainz](#beatport_importer) - [Import Beatport releases to MusicBrainz](#beatport_importer)
* [Import CD Baby releases to MusicBrainz](#cdbaby_importer) - [Import CD Baby releases to MusicBrainz](#cdbaby_importer)
* [Import CD1D releases to MusicBrainz](#cd1d_importer) - [Import CD1D releases to MusicBrainz](#cd1d_importer)
* [Import DG/Decca releases to MusicBrainz](#dgdecca_importer) - [Import DG/Decca releases to MusicBrainz](#dgdecca_importer)
* [Import Discogs releases to MusicBrainz](#discogs_importer) - [Import Discogs releases to MusicBrainz](#discogs_importer)
* [Import Encyclopedisque releases to MusicBrainz](#encyclopedisque_importer) - [Import Encyclopedisque releases to MusicBrainz](#encyclopedisque_importer)
* [Import FMA releases to MusicBrainz](#fma_importer) - [Import FMA releases to MusicBrainz](#fma_importer)
* [Import Juno Download releases to MusicBrainz](#juno_download_importer) - [Import Juno Download releases to MusicBrainz](#juno_download_importer)
* [Import Last.fm releases to MusicBrainz](#lastfm_importer) - [Import Last.fm releases to MusicBrainz](#lastfm_importer)
* [Import Loot releases to MusicBrainz](#loot_importer) - [Import Loot releases to MusicBrainz](#loot_importer)
* [Import Metal Archives releases into MusicBrainz](#metalarchives_importer) - [Import Metal Archives releases into MusicBrainz](#metalarchives_importer)
* [Import Qobuz releases to MusicBrainz](#qobuz_importer) - [Import Qobuz releases to MusicBrainz](#qobuz_importer)
* [Import Takealot releases to MusicBrainz](#takealot_importer) - [Import Takealot releases to MusicBrainz](#takealot_importer)
* [MusicBrainz: Batch-add "performance of" relationships](#batch-add-recording-relationships) - [MusicBrainz: Batch-add "performance of" relationships](#batch-add-recording-relationships)
* [MusicBrainz: Expand/collapse release groups](#expand-collapse-release-groups) - [MusicBrainz: Expand/collapse release groups](#expand-collapse-release-groups)
* [MusicBrainz: Fast cancel edits](#fast-cancel-edits) - [MusicBrainz: Fast cancel edits](#fast-cancel-edits)
* [MusicBrainz: Set recording comments for a release](#set-recording-comments) - [MusicBrainz: Set recording comments for a release](#set-recording-comments)
* [Musicbrainz DiscIds Detector](#mb_discids_detector) - [Musicbrainz DiscIds Detector](#mb_discids_detector)
* [Musicbrainz UI enhancements](#mb_ui_enhancements) - [Musicbrainz UI enhancements](#mb_ui_enhancements)
## <a name="mb_relationship_shortcuts"></a> Display shortcut for relationships on MusicBrainz ## <a name="mb_relationship_shortcuts"></a> Display shortcut for relationships on MusicBrainz
@ -184,4 +184,3 @@ Various UI enhancements for Musicbrainz
[![Source](https://github.com/jerone/UserScripts/blob/master/_resources/Source-button.png)](https://github.com/murdos/musicbrainz-userscripts/blob/master/mb_ui_enhancements.user.js) [![Source](https://github.com/jerone/UserScripts/blob/master/_resources/Source-button.png)](https://github.com/murdos/musicbrainz-userscripts/blob/master/mb_ui_enhancements.user.js)
[![Install](https://raw.github.com/jerone/UserScripts/master/_resources/Install-button.png)](https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/mb_ui_enhancements.user.js) [![Install](https://raw.github.com/jerone/UserScripts/master/_resources/Install-button.png)](https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/mb_ui_enhancements.user.js)

View file

@ -14,26 +14,22 @@
// @icon https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/assets/images/Musicbrainz_import_logo.png // @icon https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/assets/images/Musicbrainz_import_logo.png
// ==/UserScript== // ==/UserScript==
// prevent JQuery conflicts, see http://wiki.greasespot.net/@grant // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant
this.$ = this.jQuery = jQuery.noConflict(true); this.$ = this.jQuery = jQuery.noConflict(true);
if (!unsafeWindow) unsafeWindow = window; if (!unsafeWindow) unsafeWindow = window;
String.prototype.fix_bandcamp_url = function () { String.prototype.fix_bandcamp_url = function() {
return this.replace('http://', 'https://'); return this.replace('http://', 'https://');
}; };
var BandcampImport = { var BandcampImport = {
// Analyze Bandcamp data and return a release object // Analyze Bandcamp data and return a release object
retrieveReleaseInfo: function () { retrieveReleaseInfo: function() {
let bandcampAlbumData = unsafeWindow.TralbumData;
let bandcampEmbedData = unsafeWindow.EmbedData;
var bandcampAlbumData = unsafeWindow.TralbumData; let release = {
var bandcampEmbedData = unsafeWindow.EmbedData;
var release = {
discs: [], discs: [],
artist_credit: [], artist_credit: [],
title: '', title: '',
@ -53,16 +49,15 @@ var BandcampImport = {
url: bandcampAlbumData.url.fix_bandcamp_url() url: bandcampAlbumData.url.fix_bandcamp_url()
}; };
// Grab release title // Grab release title
release.title = bandcampAlbumData.current.title; release.title = bandcampAlbumData.current.title;
// Grab release event information // Grab release event information
var date = this.convdate(bandcampAlbumData.current.release_date); let date = this.convdate(bandcampAlbumData.current.release_date);
if (date) { if (date) {
if (!(date.year > 2008 || (date.year == 2008 && date.month >= 9))) { if (!(date.year > 2008 || (date.year == 2008 && date.month >= 9))) {
// use publish date if release date is before Bandcamp launch (2008-09) // use publish date if release date is before Bandcamp launch (2008-09)
var pdate = this.convdate(bandcampAlbumData.current.publish_date); let pdate = this.convdate(bandcampAlbumData.current.publish_date);
if (pdate) { if (pdate) {
date = pdate; date = pdate;
} }
@ -73,9 +68,9 @@ var BandcampImport = {
} }
// FIXME: implement a mapping between bandcamp release types and MB ones // FIXME: implement a mapping between bandcamp release types and MB ones
if (bandcampAlbumData.current.type == "track") { if (bandcampAlbumData.current.type == 'track') {
// map Bandcamp single tracks to singles // map Bandcamp single tracks to singles
release.type = "single"; release.type = 'single';
// if track belongs to an album, get its url. // if track belongs to an album, get its url.
if (bandcampEmbedData.album_embed_data) { if (bandcampEmbedData.album_embed_data) {
release.parent_album_url = bandcampEmbedData.album_embed_data.linkback.fix_bandcamp_url(); release.parent_album_url = bandcampEmbedData.album_embed_data.linkback.fix_bandcamp_url();
@ -84,7 +79,7 @@ var BandcampImport = {
} }
// Tracks // Tracks
var disc = { let disc = {
tracks: [], tracks: [],
format: release.format format: release.format
}; };
@ -94,66 +89,63 @@ var BandcampImport = {
// bandcamp formats them as 'artist - tracktitle' // bandcamp formats them as 'artist - tracktitle'
// only set to true if ALL tracks are formatted like this // only set to true if ALL tracks are formatted like this
// and if string doesn't start with a number (ie. 02 - title) // and if string doesn't start with a number (ie. 02 - title)
var various_artists = true; let various_artists = true;
for (var i=0; i < bandcampAlbumData.trackinfo.length; i++) { for (var i = 0; i < bandcampAlbumData.trackinfo.length; i++) {
if (!bandcampAlbumData.trackinfo[i].title.match(/ - /) if (!bandcampAlbumData.trackinfo[i].title.match(/ - /) || bandcampAlbumData.trackinfo[i].title.match(/^\d+ - /)) {
|| bandcampAlbumData.trackinfo[i].title.match(/^\d+ - /)) {
various_artists = false; various_artists = false;
break; break;
} }
} }
// Release artist credit // Release artist credit
if (bandcampAlbumData.artist.match(/^various(?: artists)?$/i) if (bandcampAlbumData.artist.match(/^various(?: artists)?$/i) && various_artists) {
&& various_artists) { release.artist_credit = [MBImport.specialArtist('various_artists')];
release.artist_credit = [ MBImport.specialArtist('various_artists') ];
} else { } else {
release.artist_credit = MBImport.makeArtistCredits([bandcampAlbumData.artist]); release.artist_credit = MBImport.makeArtistCredits([bandcampAlbumData.artist]);
} }
var tracks_streamable = 0; let tracks_streamable = 0;
$.each(bandcampAlbumData.trackinfo, function (index, bctrack) { $.each(bandcampAlbumData.trackinfo, function(index, bctrack) {
var title = bctrack.title; let title = bctrack.title;
var artist = []; let artist = [];
if (various_artists) { if (various_artists) {
var m = bctrack.title.match(/^(.+) - (.+)$/); let m = bctrack.title.match(/^(.+) - (.+)$/);
if (m) { if (m) {
title = m[2]; title = m[2];
artist = [m[1]]; artist = [m[1]];
} }
} }
if (bctrack.file) tracks_streamable++; if (bctrack.file) tracks_streamable++;
var track = { let track = {
'title': title, title: title,
'duration': Math.round(bctrack.duration * 1000), duration: Math.round(bctrack.duration * 1000),
'artist_credit': MBImport.makeArtistCredits(artist) artist_credit: MBImport.makeArtistCredits(artist)
}; };
disc.tracks.push(track); disc.tracks.push(track);
}); });
// Check for hidden tracks (more tracks in the download than shown for streaming ie.) // Check for hidden tracks (more tracks in the download than shown for streaming ie.)
var showntracks = bandcampAlbumData.trackinfo.length; let showntracks = bandcampAlbumData.trackinfo.length;
var numtracks = -1; let numtracks = -1;
var nostream = false; let nostream = false;
// album description indicates number of tracks in the download // album description indicates number of tracks in the download
var match = /^\d+ track album$/.exec($("meta[property='og:description']").attr("content")); let match = /^\d+ track album$/.exec($("meta[property='og:description']").attr('content'));
if (match) { if (match) {
numtracks = parseInt(match, 10); numtracks = parseInt(match, 10);
} }
if (numtracks > 0 && numtracks > showntracks) { if (numtracks > 0 && numtracks > showntracks) {
// display a warning if tracks in download differs from tracks shown // display a warning if tracks in download differs from tracks shown
$('h2.trackTitle').append( $('h2.trackTitle').append(
'<p style="font-size:70%; font-style: italic; margin: 0.1em 0;">' + `${'<p style="font-size:70%; font-style: italic; margin: 0.1em 0;">' + 'Warning: '}${numtracks} vs ${showntracks} tracks` +
'Warning: ' + numtracks + ' vs ' + showntracks + ' tracks' + `</p>`
'</p>'
); );
// append unknown tracks to the release // append unknown tracks to the release
for (var i = 0; i < numtracks - showntracks; i++) { for (var i = 0; i < numtracks - showntracks; i++) {
var track = { let track = {
'title': '[unknown]', title: '[unknown]',
'duration': null, duration: null,
'artist_credit': [] artist_credit: []
}; };
disc.tracks.push(track); disc.tracks.push(track);
} }
@ -162,44 +154,47 @@ var BandcampImport = {
} }
// URLs // URLs
var link_type = MBImport.URL_TYPES; let link_type = MBImport.URL_TYPES;
// Download for free vs. for purchase // Download for free vs. for purchase
if (bandcampAlbumData.current.download_pref !== null) { if (bandcampAlbumData.current.download_pref !== null) {
if (bandcampAlbumData.freeDownloadPage !== null || bandcampAlbumData.current.download_pref === 1 || ( if (
bandcampAlbumData.current.download_pref === 2 && bandcampAlbumData.current.minimum_price === 0)) { bandcampAlbumData.freeDownloadPage !== null ||
bandcampAlbumData.current.download_pref === 1 ||
(bandcampAlbumData.current.download_pref === 2 && bandcampAlbumData.current.minimum_price === 0)
) {
release.urls.push({ release.urls.push({
'url': release.url, url: release.url,
'link_type': link_type.download_for_free link_type: link_type.download_for_free
}); });
} }
if (bandcampAlbumData.current.download_pref === 2) { if (bandcampAlbumData.current.download_pref === 2) {
release.urls.push({ release.urls.push({
'url': release.url, url: release.url,
'link_type': link_type.purchase_for_download link_type: link_type.purchase_for_download
}); });
} }
} }
// Check if the release is streamable // Check if the release is streamable
if (bandcampAlbumData.hasAudio && !nostream && disc.tracks.length > 0 && disc.tracks.length == tracks_streamable) { if (bandcampAlbumData.hasAudio && !nostream && disc.tracks.length > 0 && disc.tracks.length == tracks_streamable) {
release.urls.push({ release.urls.push({
'url': release.url, url: release.url,
'link_type': link_type.stream_for_free link_type: link_type.stream_for_free
}); });
} }
// Check if release is Creative Commons licensed // Check if release is Creative Commons licensed
if ($("div#license a.cc-icons").length > 0) { if ($('div#license a.cc-icons').length > 0) {
release.urls.push({ release.urls.push({
'url': $("div#license a.cc-icons").attr("href"), url: $('div#license a.cc-icons').attr('href'),
'link_type': link_type.license link_type: link_type.license
}); });
} }
// Check if album has a back link to a label // Check if album has a back link to a label
var label = $("a.back-to-label-link span.back-to-label-name").text(); let label = $('a.back-to-label-link span.back-to-label-name').text();
if (label) { if (label) {
release.labels.push({ release.labels.push({
'name': label, name: label,
'mbid': '', mbid: '',
'catno': 'none' catno: 'none'
}); });
} }
@ -207,42 +202,39 @@ var BandcampImport = {
}, },
// Insert links in page // Insert links in page
insertLink: function (release) { insertLink: function(release) {
if (release.type == "track") { if (release.type == 'track') {
// only import album or single, tracks belong to an album // only import album or single, tracks belong to an album
return false; return false;
} }
// Form parameters // Form parameters
var edit_note = MBImport.makeEditNote(release.url, 'Bandcamp'); let edit_note = MBImport.makeEditNote(release.url, 'Bandcamp');
var parameters = MBImport.buildFormParameters(release, edit_note); let parameters = MBImport.buildFormParameters(release, edit_note);
// Build form // Build form
var mbUI = $('<div id="mb_buttons">' let mbUI = $(`<div id="mb_buttons">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`).hide();
+ MBImport.buildFormHTML(parameters)
+ MBImport.buildSearchButton(release)
+ '</div>').hide();
// Append MB import link // Append MB import link
$('#name-section').append(mbUI); $('#name-section').append(mbUI);
$('#mb_buttons').css({'margin-top': '6px'}); $('#mb_buttons').css({ 'margin-top': '6px' });
$('form.musicbrainz_import').css({display: 'inline-block'}); $('form.musicbrainz_import').css({ display: 'inline-block' });
mbUI.slideDown(); mbUI.slideDown();
}, },
// helper to convert bandcamp date to MB date // helper to convert bandcamp date to MB date
convdate: function (date) { convdate: function(date) {
if (typeof date != "undefined" && date !== "") { if (typeof date != 'undefined' && date !== '') {
var d = new Date(date); let d = new Date(date);
return { return {
"year": d.getUTCFullYear(), year: d.getUTCFullYear(),
"month": d.getUTCMonth() + 1, month: d.getUTCMonth() + 1,
"day": d.getUTCDate() day: d.getUTCDate()
}; };
} }
return false; return false;
} }
}; };
$(document).ready(function () { $(document).ready(function() {
/* keep the following line as first, it is required to skip /* keep the following line as first, it is required to skip
* pages which aren't actually a bandcamp page, since we support * pages which aren't actually a bandcamp page, since we support
* bandcamp pages under third-party domains. * bandcamp pages under third-party domains.
@ -253,48 +245,72 @@ $(document).ready(function () {
MBImportStyle(); MBImportStyle();
var mblinks = new MBLinks('BCI_MBLINKS_CACHE'); let mblinks = new MBLinks('BCI_MBLINKS_CACHE');
var release = BandcampImport.retrieveReleaseInfo(); let release = BandcampImport.retrieveReleaseInfo();
// add MB artist link // add MB artist link
var root_url = release.url.match(/^(https?:\/\/[^\/]+)/)[1].split('?')[0]; let root_url = release.url.match(/^(https?:\/\/[^\/]+)/)[1].split('?')[0];
var label_url = ""; let label_url = '';
mblinks.searchAndDisplayMbLink(root_url, 'artist', function (link) { $('div#name-section span[itemprop="byArtist"]').before(link); } ); mblinks.searchAndDisplayMbLink(root_url, 'artist', function(link) {
mblinks.searchAndDisplayMbLink(root_url, 'label', function (link) { $('p#band-name-location span.title').append(link); }, 'label:' + root_url ); $('div#name-section span[itemprop="byArtist"]').before(link);
var labelback = $("a.back-to-label-link"); });
mblinks.searchAndDisplayMbLink(
root_url,
'label',
function(link) {
$('p#band-name-location span.title').append(link);
},
`label:${root_url}`
);
let labelback = $('a.back-to-label-link');
if (labelback) { if (labelback) {
var labelbacklink = labelback.attr('href'); let labelbacklink = labelback.attr('href');
if (labelbacklink) { if (labelbacklink) {
label_url = labelbacklink.match(/^(https?:\/\/[^\/]+)/)[1].split('?')[0].fix_bandcamp_url(); label_url = labelbacklink
mblinks.searchAndDisplayMbLink(label_url, 'label', function (link) { $('a.back-to-label-link span.back-link-text').append(link); }, 'label:' + label_url ); .match(/^(https?:\/\/[^\/]+)/)[1]
.split('?')[0]
.fix_bandcamp_url();
mblinks.searchAndDisplayMbLink(
label_url,
'label',
function(link) {
$('a.back-to-label-link span.back-link-text').append(link);
},
`label:${label_url}`
);
} }
} }
if (release.artist_credit.length == 1) { if (release.artist_credit.length == 1) {
// try to get artist's mbid from cache // try to get artist's mbid from cache
var artist_mbid = mblinks.resolveMBID(root_url); let artist_mbid = mblinks.resolveMBID(root_url);
if (artist_mbid) { if (artist_mbid) {
release.artist_credit[0].mbid = artist_mbid; release.artist_credit[0].mbid = artist_mbid;
} }
} }
// try to get label mbid from cache // try to get label mbid from cache
var label_mbid = ""; let label_mbid = '';
var label_name = ""; let label_name = '';
if (label_url) { if (label_url) {
label_mbid = mblinks.resolveMBID('label:' + label_url); label_mbid = mblinks.resolveMBID(`label:${label_url}`);
label_name = $('a.back-to-label-link span.back-link-text ').contents().get(2).textContent; label_name = $('a.back-to-label-link span.back-link-text ')
.contents()
.get(2).textContent;
} else { } else {
label_mbid = mblinks.resolveMBID('label:' + root_url); label_mbid = mblinks.resolveMBID(`label:${root_url}`);
if (label_mbid) label_name = $('p#band-name-location span.title').text().trim(); if (label_mbid)
label_name = $('p#band-name-location span.title')
.text()
.trim();
} }
if (label_mbid || label_name) { if (label_mbid || label_name) {
if (release.labels.length == 0) { if (release.labels.length == 0) {
release.labels.push({ release.labels.push({
'name': '', name: '',
'mbid': '', mbid: '',
'catno': 'none' catno: 'none'
}); });
} }
release.labels[0].name = label_name; release.labels[0].name = label_name;
@ -302,25 +318,31 @@ $(document).ready(function () {
} }
BandcampImport.insertLink(release); BandcampImport.insertLink(release);
LOGGER.info("Parsed release: ", release); LOGGER.info('Parsed release: ', release);
if (release.type == 'track') { if (release.type == 'track') {
// add MB links to parent album // add MB links to parent album
mblinks.searchAndDisplayMbLink(release.parent_album_url, 'release', function (link) { $('div#name-section span[itemprop="inAlbum"] a:first').before(link); } ); mblinks.searchAndDisplayMbLink(release.parent_album_url, 'release', function(link) {
$('div#name-section span[itemprop="inAlbum"] a:first').before(link);
});
} else { } else {
// add MB release links to album or single // add MB release links to album or single
mblinks.searchAndDisplayMbLink(release.url, 'release', function (link) { $('div#name-section span[itemprop="byArtist"]').after(link); } ); mblinks.searchAndDisplayMbLink(release.url, 'release', function(link) {
$('div#name-section span[itemprop="byArtist"]').after(link);
});
} }
// append a comma after each tag to ease cut'n'paste to MB // append a comma after each tag to ease cut'n'paste to MB
$("div.tralbum-tags a:not(:last-child).tag").after(", "); $('div.tralbum-tags a:not(:last-child).tag').after(', ');
// append a link to the full size image // append a link to the full size image
var fullsizeimageurl = $("div#tralbumArt a").attr("href").replace('_10', '_0'); let fullsizeimageurl = $('div#tralbumArt a')
$("div#tralbumArt").after("<div id='bci_link'><a class='custom-color' href='" + fullsizeimageurl + .attr('href')
"' title='Open original image in a new tab (Bandcamp importer)' target='_blank'>Original image</a></div>"); .replace('_10', '_0');
$('div#tralbumArt').after(
$("div#bci_link").css({ 'padding-top': '0.5em', 'text-align': 'right' }); `<div id='bci_link'><a class='custom-color' href='${fullsizeimageurl}' title='Open original image in a new tab (Bandcamp importer)' target='_blank'>Original image</a></div>`
$("div#bci_link a").css({ 'font-weight': 'bold' }); );
$('div#bci_link').css({ 'padding-top': '0.5em', 'text-align': 'right' });
$('div#bci_link a').css({ 'font-weight': 'bold' });
}); });

View file

@ -18,12 +18,13 @@ this.$ = this.jQuery = jQuery.noConflict(true);
if (!unsafeWindow) unsafeWindow = window; if (!unsafeWindow) unsafeWindow = window;
$(document).ready(function () { $(document).ready(function() {
// Display a link to the correct album bandcamp url (ie. main page or releases page) // Display a link to the correct album bandcamp url (ie. main page or releases page)
var bandcampAlbumData = unsafeWindow.TralbumData; let bandcampAlbumData = unsafeWindow.TralbumData;
if (bandcampAlbumData && bandcampAlbumData.url) { if (bandcampAlbumData && bandcampAlbumData.url) {
var innerHTML = '<div id="bci_helper" style="padding-top: 5px;">' + '<a href="' + bandcampAlbumData.url + let innerHTML = `${'<div id="bci_helper" style="padding-top: 5px;">' + '<a href="'}${
'" title="Load album page and display Import to MB button">Album page (MB import)</a></div>'; bandcampAlbumData.url
}" title="Load album page and display Import to MB button">Album page (MB import)</a></div>`;
$('#name-section').append(innerHTML); $('#name-section').append(innerHTML);
} }
}); });

File diff suppressed because it is too large Load diff

View file

@ -17,119 +17,121 @@ this.$ = this.jQuery = jQuery.noConflict(true);
if (!unsafeWindow) unsafeWindow = window; if (!unsafeWindow) unsafeWindow = window;
$(document).ready(function(){ $(document).ready(function() {
MBImportStyle(); MBImportStyle();
var release_url = window.location.href.replace('/\?.*$/', '').replace(/#.*$/, ''); let release_url = window.location.href.replace('/?.*$/', '').replace(/#.*$/, '');
var release = retrieveReleaseInfo(release_url); let release = retrieveReleaseInfo(release_url);
insertLink(release, release_url); insertLink(release, release_url);
}); });
function retrieveReleaseInfo(release_url) { function retrieveReleaseInfo(release_url) {
function contains_or(selector, list) { function contains_or(selector, list) {
selectors = []; selectors = [];
$.each(list, function(ind, value) { $.each(list, function(ind, value) {
selectors.push(selector + ':contains("' + value.replace('"', '\\"') + '")'); selectors.push(`${selector}:contains("${value.replace('"', '\\"')}")`);
}); });
return selectors.join(','); return selectors.join(',');
} }
var release_date_strings = [ let release_date_strings = [
'Release Date', 'Fecha de lanzamiento', 'Date de sortie', 'Erscheinungsdatum', 'Data de lançamento', 'Releasedatum', "Data di uscita", "リリース予定日" 'Release Date',
'Fecha de lanzamiento',
'Date de sortie',
'Erscheinungsdatum',
'Data de lançamento',
'Releasedatum',
'Data di uscita',
'リリース予定日'
]; ];
var labels_strings = [ let labels_strings = ['Labels', 'Sello', 'Gravadoras', 'Label', 'Etichetta', 'Editora', 'レーベル'];
'Labels', 'Sello', 'Gravadoras', "Label", "Etichetta", "Editora", "レーベル" let catalog_strings = ['Catalog', 'Catálogo', 'Catalogue', 'Katalog', 'Catalogus', 'Catalogo', 'カタログ'];
]; let release = {};
var catalog_strings = [
'Catalog', 'Catálogo', 'Catalogue', 'Katalog', 'Catalogus', "Catalogo", "カタログ"
];
var release = {};
// Release information global to all Beatport releases // Release information global to all Beatport releases
release.packaging = 'None'; release.packaging = 'None';
release.country = "XW"; release.country = 'XW';
release.status = 'official'; release.status = 'official';
release.urls = []; release.urls = [];
release.urls.push({ release.urls.push({
'url': release_url, url: release_url,
'link_type': MBImport.URL_TYPES.purchase_for_download link_type: MBImport.URL_TYPES.purchase_for_download
}); });
var releaseDate = $(contains_or("td.meta-data-label", release_date_strings)).next().text().split("-"); let releaseDate = $(contains_or('td.meta-data-label', release_date_strings))
.next()
.text()
.split('-');
release.year = releaseDate[0]; release.year = releaseDate[0];
release.month = releaseDate[1]; release.month = releaseDate[1];
release.day = releaseDate[2]; release.day = releaseDate[2];
release.labels = []; release.labels = [];
release.labels.push( release.labels.push({
{ name: $(contains_or('td.meta-data-label', labels_strings))
name: $(contains_or("td.meta-data-label", labels_strings)).next().text(), .next()
catno: $(contains_or("td.meta-data-label", catalog_strings)).next().text() .text(),
} catno: $(contains_or('td.meta-data-label', catalog_strings))
); .next()
.text()
});
var release_artists = []; let release_artists = [];
// Tracks // Tracks
var tracks = []; let tracks = [];
unsafeWindow.$( "span[data-json]" ).each( unsafeWindow.$('span[data-json]').each(function(index, tagSoup) {
function ( index, tagSoup ) { let t = $.parseJSON($(tagSoup).attr('data-json'));
var t = $.parseJSON($(tagSoup).attr('data-json'));
release.title = t.release.name; release.title = t.release.name;
var artists = []; let artists = [];
t.artists.forEach( t.artists.forEach(function(artist) {
function (artist) {
artists.push(artist.name); artists.push(artist.name);
release_artists.push(artist.name); release_artists.push(artist.name);
} });
); let title = t.name;
var title = t.name;
if (t.mixName && t.mixName !== 'Original Mix' && t.mixName !== 'Original') { if (t.mixName && t.mixName !== 'Original Mix' && t.mixName !== 'Original') {
title += ' (' + t.mixName + ')'; title += ` (${t.mixName})`;
} }
tracks.push({ tracks.push({
'artist_credit': MBImport.makeArtistCredits(artists), artist_credit: MBImport.makeArtistCredits(artists),
'title': title, title: title,
'duration': t.lengthMs duration: t.lengthMs
});
}); });
}
);
var unique_artists = []; let unique_artists = [];
$.each(release_artists, function(i, el){ $.each(release_artists, function(i, el) {
if ($.inArray(el, unique_artists) === -1) { if ($.inArray(el, unique_artists) === -1) {
unique_artists.push(el); unique_artists.push(el);
} }
}); });
if (unique_artists.length > 4) { if (unique_artists.length > 4) {
release.artist_credit = [ MBImport.specialArtist('various_artists') ]; release.artist_credit = [MBImport.specialArtist('various_artists')];
} else { } else {
release.artist_credit = MBImport.makeArtistCredits(unique_artists); release.artist_credit = MBImport.makeArtistCredits(unique_artists);
} }
release.discs = []; release.discs = [];
release.discs.push( { release.discs.push({
'tracks': tracks, tracks: tracks,
'format': "Digital Media" format: 'Digital Media'
} ); });
LOGGER.info("Parsed release: ", release); LOGGER.info('Parsed release: ', release);
return release; return release;
} }
// Insert button into page under label information // Insert button into page under label information
function insertLink(release, release_url) { function insertLink(release, release_url) {
var edit_note = MBImport.makeEditNote(release_url, 'Beatport Classic'); let edit_note = MBImport.makeEditNote(release_url, 'Beatport Classic');
var parameters = MBImport.buildFormParameters(release, edit_note); let parameters = MBImport.buildFormParameters(release, edit_note);
var mbUI = $('<div class="musicbrainz-import">' let mbUI = $(
+ MBImport.buildFormHTML(parameters) `<div class="musicbrainz-import">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`
+ MBImport.buildSearchButton(release) ).hide();
+ '</div>').hide();
$(".release-detail-metadata").append(mbUI); $('.release-detail-metadata').append(mbUI);
$('form.musicbrainz_import').css({'display': 'inline-block', 'margin': '1px'}); $('form.musicbrainz_import').css({ display: 'inline-block', margin: '1px' });
$('form.musicbrainz_import img').css({'display': 'inline-block'}); $('form.musicbrainz_import img').css({ display: 'inline-block' });
mbUI.slideDown(); mbUI.slideDown();
} }

View file

@ -20,19 +20,19 @@ this.$ = this.jQuery = jQuery.noConflict(true);
if (!unsafeWindow) unsafeWindow = window; if (!unsafeWindow) unsafeWindow = window;
$(document).ready(function(){ $(document).ready(function() {
MBImportStyle(); MBImportStyle();
var release_url = window.location.href.replace('/\?.*$/', '').replace(/#.*$/, ''); let release_url = window.location.href.replace('/?.*$/', '').replace(/#.*$/, '');
var release = retrieveReleaseInfo(release_url); let release = retrieveReleaseInfo(release_url);
insertLink(release, release_url); insertLink(release, release_url);
}); });
function retrieveReleaseInfo(release_url) { function retrieveReleaseInfo(release_url) {
var releaseDate = ProductDetail.date.published.split("-"); let releaseDate = ProductDetail.date.published.split('-');
// Release information global to all Beatport releases // Release information global to all Beatport releases
var release = { let release = {
artist_credit: [], artist_credit: [],
title: ProductDetail.name, title: ProductDetail.name,
year: releaseDate[0], year: releaseDate[0],
@ -52,24 +52,21 @@ function retrieveReleaseInfo(release_url) {
// URLs // URLs
release.urls.push({ release.urls.push({
'url': release_url, url: release_url,
'link_type': MBImport.URL_TYPES.purchase_for_download link_type: MBImport.URL_TYPES.purchase_for_download
}); });
release.labels.push( release.labels.push({
{
name: ProductDetail.label.name, name: ProductDetail.label.name,
catno: ProductDetail.catalog catno: ProductDetail.catalog
} });
);
// Tracks // Tracks
var tracks = []; let tracks = [];
var the_tracks = unsafeWindow.Playables.tracks; let the_tracks = unsafeWindow.Playables.tracks;
var seen_tracks = {}; // to shoot duplicates ... let seen_tracks = {}; // to shoot duplicates ...
var release_artists = []; let release_artists = [];
$.each(the_tracks, $.each(the_tracks, function(idx, track) {
function (idx, track) {
if (track.release.id !== ProductDetail.id) { if (track.release.id !== ProductDetail.id) {
return; return;
} }
@ -78,59 +75,57 @@ function retrieveReleaseInfo(release_url) {
} }
seen_tracks[track.id] = true; seen_tracks[track.id] = true;
var artists = []; let artists = [];
$.each(track.artists, $.each(track.artists, function(idx2, artist) {
function (idx2, artist) {
artists.push(artist.name); artists.push(artist.name);
release_artists.push(artist.name); release_artists.push(artist.name);
} });
);
var title = track.name; let title = track.name;
if (track.mix && track.mix !== 'Original Mix') { if (track.mix && track.mix !== 'Original Mix') {
title += ' (' + track.mix + ')'; title += ` (${track.mix})`;
} }
tracks.push({ tracks.push({
'artist_credit': MBImport.makeArtistCredits(artists), artist_credit: MBImport.makeArtistCredits(artists),
'title': title, title: title,
'duration': track.duration.minutes duration: track.duration.minutes
});
}); });
}
);
var unique_artists = []; let unique_artists = [];
$.each(release_artists, function(i, el){ $.each(release_artists, function(i, el) {
if ($.inArray(el, unique_artists) === -1) { if ($.inArray(el, unique_artists) === -1) {
unique_artists.push(el); unique_artists.push(el);
} }
}); });
if (unique_artists.length > 4) { if (unique_artists.length > 4) {
release.artist_credit = [ MBImport.specialArtist('various_artists') ]; release.artist_credit = [MBImport.specialArtist('various_artists')];
} else { } else {
release.artist_credit = MBImport.makeArtistCredits(unique_artists); release.artist_credit = MBImport.makeArtistCredits(unique_artists);
} }
release.discs.push( { release.discs.push({
'tracks': tracks, tracks: tracks,
'format': release.format format: release.format
} ); });
LOGGER.info("Parsed release: ", release); LOGGER.info('Parsed release: ', release);
return release; return release;
} }
// Insert button into page under label information // Insert button into page under label information
function insertLink(release, release_url) { function insertLink(release, release_url) {
var edit_note = MBImport.makeEditNote(release_url, 'Beatport'); let edit_note = MBImport.makeEditNote(release_url, 'Beatport');
var parameters = MBImport.buildFormParameters(release, edit_note); let parameters = MBImport.buildFormParameters(release, edit_note);
var mbUI = $('<li class="interior-release-chart-content-item musicbrainz-import">' let mbUI = $(
+ MBImport.buildFormHTML(parameters) `<li class="interior-release-chart-content-item musicbrainz-import">${MBImport.buildFormHTML(
+ MBImport.buildSearchButton(release) parameters
+ '</li>').hide(); )}${MBImport.buildSearchButton(release)}</li>`
).hide();
$(".interior-release-chart-content-list").append(mbUI); $('.interior-release-chart-content-list').append(mbUI);
$('form.musicbrainz_import').css({'display': 'inline-block', 'margin-left': '5px'}); $('form.musicbrainz_import').css({ display: 'inline-block', 'margin-left': '5px' });
$('form.musicbrainz_import button').css({'width': '120px'}); $('form.musicbrainz_import button').css({ width: '120px' });
mbUI.slideDown(); mbUI.slideDown();
} }

View file

@ -25,18 +25,23 @@ if (!unsafeWindow) unsafeWindow = window;
this.$ = this.jQuery = jQuery.noConflict(true); this.$ = this.jQuery = jQuery.noConflict(true);
var CD1DImporter = { var CD1DImporter = {
getFormats: function() {
getFormats: function () {
// get a list of existing formats, return id of the fragment and name // get a list of existing formats, return id of the fragment and name
var formats = $('#container-1 ul li.ui-state-default').map(function () { let formats = $('#container-1 ul li.ui-state-default').map(function() {
return { return {
id: $(this).find('a:first').attr('href').split('#')[1].split('-'), id: $(this)
name: $(this).find('span:first').text() .find('a:first')
.attr('href')
.split('#')[1]
.split('-'),
name: $(this)
.find('span:first')
.text()
}; };
}); });
// remove "parent" formats : ie. digital when mp3 and flac are present // remove "parent" formats : ie. digital when mp3 and flac are present
for (var i = 0; i < formats.length; i++) { for (var i = 0; i < formats.length; i++) {
for (var j = i + 1; j < formats.length; j++) { for (let j = i + 1; j < formats.length; j++) {
if (formats[j].id.length > 1) { if (formats[j].id.length > 1) {
if (formats[i].id[1] == formats[j].id[1]) { if (formats[i].id[1] == formats[j].id[1]) {
// same prefix (ie. fragment-33123 and fragment-33123-1-2) // same prefix (ie. fragment-33123 and fragment-33123-1-2)
@ -49,7 +54,7 @@ var CD1DImporter = {
} }
} }
} }
var cleanformats = []; let cleanformats = [];
for (var i = 0; i < formats.length; i++) { for (var i = 0; i < formats.length; i++) {
if (!formats[i].toremove) { if (!formats[i].toremove) {
cleanformats.push({ cleanformats.push({
@ -61,70 +66,82 @@ var CD1DImporter = {
return cleanformats; return cleanformats;
}, },
getTracks: function (id) { getTracks: function(id) {
// extract discs & tracks // extract discs & tracks
var tracklists = 'div#' + id + ' div.tracklist table.tracklist-content'; let tracklists = `div#${id} div.tracklist table.tracklist-content`;
var discs = []; let discs = [];
$(tracklists).each(function () { $(tracklists).each(function() {
disc = $(this).find('tbody tr').map(function () { disc = $(this)
.find('tbody tr')
.map(function() {
// $(this) is used more than once; cache it for performance. // $(this) is used more than once; cache it for performance.
var row = $(this); let row = $(this);
// For each row that's "mapped", return an object that // For each row that's "mapped", return an object that
// describes the first and second <td> in the row. // describes the first and second <td> in the row.
var duration = row.find('td.tracklist-content-length').text().replace('"', '').replace('\' ', ':') let duration = row
.find('td.tracklist-content-length')
.text()
.replace('"', '')
.replace("' ", ':');
// drop track number prefix (A A2 C3 01 05 etc...) // drop track number prefix (A A2 C3 01 05 etc...)
var title = row.find('td.tracklist-content-title').text().replace(/^[0-9A-F][0-9]* /, ''); let title = row
.find('td.tracklist-content-title')
.text()
.replace(/^[0-9A-F][0-9]* /, '');
return { return {
title: title, title: title,
duration: MBImport.hmsToMilliSeconds(duration) duration: MBImport.hmsToMilliSeconds(duration)
}; };
}).get(); })
.get();
discs.push(disc); discs.push(disc);
}); });
return discs; return discs;
}, },
getArtists: function () { getArtists: function() {
// get artists // get artists
var artists = $('div.infos-releasegrp div.list-artist a').map(function () { let artists = $('div.infos-releasegrp div.list-artist a')
.map(function() {
return $(this).text(); return $(this).text();
}).get(); })
.get();
return MBImport.makeArtistCredits(artists); return MBImport.makeArtistCredits(artists);
}, },
getAlbum: function () { getAlbum: function() {
// get release title // get release title
return $('h1').text(); return $('h1').text();
}, },
fromCurrentTime: function (offset_in_seconds) { fromCurrentTime: function(offset_in_seconds) {
var millis = Date.now(); let millis = Date.now();
if (!isNaN(offset_in_seconds)) { if (!isNaN(offset_in_seconds)) {
millis += offset_in_seconds * 1000; millis += offset_in_seconds * 1000;
} }
var date = new Date(millis); let date = new Date(millis);
var dd = date.getDate(); let dd = date.getDate();
var mm = date.getMonth() + 1; //January is 0! let mm = date.getMonth() + 1; //January is 0!
var yyyy = date.getFullYear(); let yyyy = date.getFullYear();
return { return {
'year': yyyy, year: yyyy,
'month': mm, month: mm,
'day': dd day: dd
}; };
}, },
getReleaseDate: function () { getReleaseDate: function() {
// get release date and convert it to object // get release date and convert it to object
var text = $('div.infos-releasegrp div.row-date').text(); let text = $('div.infos-releasegrp div.row-date').text();
if (text == 'yesterday' || text == 'hier') { if (text == 'yesterday' || text == 'hier') {
return this.fromCurrentTime(-24 * 60 * 60); return this.fromCurrentTime(-24 * 60 * 60);
} }
if (text == 'today' || text == 'aujourd\'hui') { if (text == 'today' || text == "aujourd'hui") {
return this.fromCurrentTime(0); return this.fromCurrentTime(0);
} }
var date = text let date = text
.replace('janvier', '01') .replace('janvier', '01')
.replace('février', '02') .replace('février', '02')
.replace('mars', '03') .replace('mars', '03')
@ -151,64 +168,65 @@ var CD1DImporter = {
.replace('December', '12') .replace('December', '12')
.split(' '); .split(' ');
return { return {
'year': parseInt(date[2], 10), year: parseInt(date[2], 10),
'month': parseInt(date[1], 10), month: parseInt(date[1], 10),
'day': parseInt(date[0], 10) day: parseInt(date[0], 10)
}; };
}, },
currentURL: function () { currentURL: function() {
return window.location.href.replace(/\/[a-z]{2}\/album\//i, '/album/').split('#')[0]; return window.location.href.replace(/\/[a-z]{2}\/album\//i, '/album/').split('#')[0];
}, },
retrieveReleaseInfo: function (format) { retrieveReleaseInfo: function(format) {
// Analyze CD1D data and return a release object // Analyze CD1D data and return a release object
var release = { let release = {
artist_credit: this.getArtists(), artist_credit: this.getArtists(),
title: this.getAlbum(), title: this.getAlbum(),
country: "", // Worldwide country: '', // Worldwide
type: '', type: '',
status: 'official', status: 'official',
language: 'eng', language: 'eng',
script: 'latn', script: 'latn',
barcode: '', barcode: '',
urls: [], urls: [],
discs: [], discs: []
}; };
// Grab release event information // Grab release event information
var releasedate = this.getReleaseDate(); let releasedate = this.getReleaseDate();
release.year = releasedate.year; release.year = releasedate.year;
release.month = releasedate.month; release.month = releasedate.month;
release.day = releasedate.day; release.day = releasedate.day;
var link_type = MBImport.URL_TYPES; let link_type = MBImport.URL_TYPES;
if (format.name.match(/vinyl|lp/i)) { if (format.name.match(/vinyl|lp/i)) {
release.country = 'FR'; release.country = 'FR';
release.format = "Vinyl"; release.format = 'Vinyl';
release.urls.push({ release.urls.push({
'url': this.currentURL(), url: this.currentURL(),
'link_type': link_type.purchase_for_mail_order link_type: link_type.purchase_for_mail_order
}); });
} else if (format.name.match(/cd/i)) { } else if (format.name.match(/cd/i)) {
release.country = 'FR'; release.country = 'FR';
release.format = 'CD'; release.format = 'CD';
release.urls.push({ release.urls.push({
'url': this.currentURL(), url: this.currentURL(),
'link_type': link_type.purchase_for_mail_order link_type: link_type.purchase_for_mail_order
}); });
} else if (format.name.match(/digital|mp3|flac|ogg|wav/i)) { } else if (format.name.match(/digital|mp3|flac|ogg|wav/i)) {
release.country = 'XW'; release.country = 'XW';
release.packaging = 'None'; release.packaging = 'None';
release.format = "Digital Media"; release.format = 'Digital Media';
release.urls.push({ release.urls.push({
'url': this.currentURL(), url: this.currentURL(),
'link_type': link_type.purchase_for_download link_type: link_type.purchase_for_download
}); });
} }
release.labels = $('div.infos-details div.row-structure').map(function () { release.labels = $('div.infos-details div.row-structure')
.map(function() {
return { return {
name: $(this).text(), name: $(this).text(),
mbid: '', mbid: '',
@ -218,52 +236,49 @@ var CD1DImporter = {
.get(); .get();
// Tracks // Tracks
$.each(this.getTracks(format.id), function (ndisc, disc) { $.each(this.getTracks(format.id), function(ndisc, disc) {
var thisdisc = { let thisdisc = {
tracks: [], tracks: [],
format: release.format format: release.format
}; };
release.discs.push(thisdisc); release.discs.push(thisdisc);
$.each(this, function (ntrack, track) { $.each(this, function(ntrack, track) {
thisdisc.tracks.push({ thisdisc.tracks.push({
'title': track.title, title: track.title,
'duration': track.duration, duration: track.duration,
'artist_credit': [] artist_credit: []
}); });
}); });
}); });
LOGGER.info("Parsed release: ", format.name, release); LOGGER.info('Parsed release: ', format.name, release);
return release; return release;
}, },
insertLink: function (release, where, formatname) { insertLink: function(release, where, formatname) {
// Insert links in page // Insert links in page
// Form parameters // Form parameters
var edit_note = MBImport.makeEditNote(this.currentURL(), 'CD1D', formatname); let edit_note = MBImport.makeEditNote(this.currentURL(), 'CD1D', formatname);
var parameters = MBImport.buildFormParameters(release, edit_note); let parameters = MBImport.buildFormParameters(release, edit_note);
// Build form // Build form
var mbUI = $('<div id="mb_buttons">' let mbUI = $(`<div id="mb_buttons">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`).hide();
+ MBImport.buildFormHTML(parameters)
+ MBImport.buildSearchButton(release)
+ '</div>').hide();
$(where).append(mbUI); $(where).append(mbUI);
$('#mb_buttons').css({'margin-top': '6px'}); $('#mb_buttons').css({ 'margin-top': '6px' });
$('form.musicbrainz_import').css({display: 'inline-block', 'margin-right': '5px'}); $('form.musicbrainz_import').css({ display: 'inline-block', 'margin-right': '5px' });
mbUI.slideDown(); mbUI.slideDown();
} }
}; };
$(document).ready(function () { $(document).ready(function() {
MBImportStyle(); MBImportStyle();
/* CD1D uses same page with hidden tabs for all formats */ /* CD1D uses same page with hidden tabs for all formats */
var formats = CD1DImporter.getFormats(); let formats = CD1DImporter.getFormats();
//LOGGER.info('Formats:', formats); //LOGGER.info('Formats:', formats);
for (var i = 0; i < formats.length; i++) { for (let i = 0; i < formats.length; i++) {
var release = CD1DImporter.retrieveReleaseInfo(formats[i]); let release = CD1DImporter.retrieveReleaseInfo(formats[i]);
CD1DImporter.insertLink(release, 'div#' + formats[i].id, formats[i].name); CD1DImporter.insertLink(release, `div#${formats[i].id}`, formats[i].name);
} }
}); });

View file

@ -18,15 +18,17 @@ this.$ = this.jQuery = jQuery.noConflict(true);
if (!unsafeWindow) unsafeWindow = window; if (!unsafeWindow) unsafeWindow = window;
$(document).ready(function(){ $(document).ready(function() {
MBImportStyle(); MBImportStyle();
var release_url = window.location.href.replace('/\?.*$/', '').replace(/#.*$/, ''); let release_url = window.location.href.replace('/?.*$/', '').replace(/#.*$/, '');
release_url = release_url.replace(/^(?:https?:\/\/)?(?:store\.)?(?:cdbaby\.com)\//, "http://store.cdbaby.com/"); release_url = release_url.replace(/^(?:https?:\/\/)?(?:store\.)?(?:cdbaby\.com)\//, 'http://store.cdbaby.com/');
var release; let release;
var buttons = ""; let buttons = '';
$("div.album-page-buy-button-container a").each(function() { $('div.album-page-buy-button-container a').each(function() {
var format = $(this).attr("title").trim(); let format = $(this)
.attr('title')
.trim();
release = retrieveReleaseInfo(release_url, format); release = retrieveReleaseInfo(release_url, format);
buttons += getImportButton(release, release_url, format); buttons += getImportButton(release, release_url, format);
}); });
@ -34,16 +36,15 @@ $(document).ready(function(){
if (release) { if (release) {
insertImportLinks(release, buttons); insertImportLinks(release, buttons);
} }
}); });
function retrieveReleaseInfo(release_url, format) { function retrieveReleaseInfo(release_url, format) {
// Release defaults // Release defaults
var release = { let release = {
artist_credit: '', artist_credit: '',
title: $("h1 span[itemprop='name']").text().trim(), title: $("h1 span[itemprop='name']")
.text()
.trim(),
year: 0, year: 0,
month: 0, month: 0,
day: 0, day: 0,
@ -56,113 +57,120 @@ function retrieveReleaseInfo(release_url, format) {
type: '', type: '',
urls: [], urls: [],
labels: [], labels: [],
discs: [], discs: []
}; };
var link_type = MBImport.URL_TYPES; let link_type = MBImport.URL_TYPES;
release.urls = []; release.urls = [];
if (format.match(/^vinyl/i)) { if (format.match(/^vinyl/i)) {
release.country = 'US'; release.country = 'US';
release.format = "Vinyl"; release.format = 'Vinyl';
release.urls.push({ release.urls.push({
'url': release_url, url: release_url,
'link_type': link_type.purchase_for_mail_order link_type: link_type.purchase_for_mail_order
}); });
} else if (format.match(/^cd/i)) { } else if (format.match(/^cd/i)) {
release.country = 'US'; release.country = 'US';
release.format = 'CD'; release.format = 'CD';
release.urls.push({ release.urls.push({
'url': release_url, url: release_url,
'link_type': link_type.purchase_for_mail_order link_type: link_type.purchase_for_mail_order
}); });
} else if (format.match(/^download/i)) { } else if (format.match(/^download/i)) {
release.country = 'XW'; release.country = 'XW';
release.packaging = 'None'; release.packaging = 'None';
release.format = "Digital Media"; release.format = 'Digital Media';
release.urls.push({ release.urls.push({
'url': release_url, url: release_url,
'link_type': link_type.purchase_for_download link_type: link_type.purchase_for_download
}); });
} }
// Release artist // Release artist
var artist = $("h2 span[itemprop='byArtist'] a").text().trim(); let artist = $("h2 span[itemprop='byArtist'] a")
var various_artists = (artist == 'Various'); .text()
.trim();
let various_artists = artist == 'Various';
if (various_artists) { if (various_artists) {
release.artist_credit = [ MBImport.specialArtist('various_artists') ]; release.artist_credit = [MBImport.specialArtist('various_artists')];
} else { } else {
release.artist_credit = MBImport.makeArtistCredits([artist]); release.artist_credit = MBImport.makeArtistCredits([artist]);
} }
release.year = $("span[itemprop='datePublished']").text().trim() release.year = $("span[itemprop='datePublished']")
.text()
.trim();
// Tracks // Tracks
var tracks = []; let tracks = [];
var trackcount = 0 let trackcount = 0;
$("table.track-table tr[itemprop='track']").each(function() { $("table.track-table tr[itemprop='track']").each(function() {
var artists = []; let artists = [];
var trackno = tracks.length + 1; let trackno = tracks.length + 1;
if (trackno == 1 && tracks.length) { if (trackno == 1 && tracks.length) {
// multiple "discs" // multiple "discs"
release.discs.push( { release.discs.push({
'tracks': tracks, tracks: tracks,
'format': release.format format: release.format
} ); });
tracks = []; tracks = [];
} }
var trackname = $(this).find("meta[itemprop='name']").attr('content').trim(); let trackname = $(this)
var tracklength = $(this).find("meta[itemprop='duration']").attr('content').trim(); .find("meta[itemprop='name']")
.attr('content')
.trim();
let tracklength = $(this)
.find("meta[itemprop='duration']")
.attr('content')
.trim();
var track_artists = []; let track_artists = [];
// FIXME various artists releases ... // FIXME various artists releases ...
$(this).find("div.track-artist").each( $(this)
function () { .find('div.track-artist')
var artistname = $(this).text().trim(); .each(function() {
let artistname = $(this)
.text()
.trim();
if (artistname) { if (artistname) {
track_artists.push(artistname); track_artists.push(artistname);
} }
} });
);
var ac = { let ac = {
'artist_credit': '', artist_credit: '',
'title': trackname, title: trackname,
'duration': MBImport.ISO8601toMilliSeconds(tracklength) duration: MBImport.ISO8601toMilliSeconds(tracklength)
}; };
if (!track_artists.length && various_artists) { if (!track_artists.length && various_artists) {
ac.artist_credit = [ MBImport.specialArtist('unknown') ]; ac.artist_credit = [MBImport.specialArtist('unknown')];
} else { } else {
ac.artist_credit = MBImport.makeArtistCredits(track_artists); ac.artist_credit = MBImport.makeArtistCredits(track_artists);
} }
tracks.push(ac); tracks.push(ac);
}); });
release.discs.push( { release.discs.push({
'tracks': tracks, tracks: tracks,
'format': release.format format: release.format
} ); });
LOGGER.info("Parsed release: ", release); LOGGER.info('Parsed release: ', release);
return release; return release;
} }
function getImportButton(release, release_url, format) { function getImportButton(release, release_url, format) {
var edit_note = MBImport.makeEditNote(release_url, "CD Baby", format); let edit_note = MBImport.makeEditNote(release_url, 'CD Baby', format);
var parameters = MBImport.buildFormParameters(release, edit_note); let parameters = MBImport.buildFormParameters(release, edit_note);
return MBImport.buildFormHTML(parameters).replace('<span>Import into MB</span>', '<span>Import ' + format + '</span>'); return MBImport.buildFormHTML(parameters).replace('<span>Import into MB</span>', `<span>Import ${format}</span>`);
} }
function insertImportLinks(release, buttons) { function insertImportLinks(release, buttons) {
$("div.right-container-top-right").prepend( $('div.right-container-top-right').prepend($(`<div id="mb_buttons">${buttons}${MBImport.buildSearchButton(release)}</div>`).hide());
$('<div id="mb_buttons">'
+ buttons
+ MBImport.buildSearchButton(release)
+ '</div>').hide()
);
$('#mb_buttons').css({ $('#mb_buttons').css({
'margin-bottom': '5px', 'margin-bottom': '5px',
'padding': '2%', padding: '2%',
'background-color': '#fff' 'background-color': '#fff'
}); });

View file

@ -1,54 +1,59 @@
/* global $ MBImport */ /* global $ MBImport */
'use strict'; 'use strict';
var meta = function() { var meta = function() {
// ==UserScript== // ==UserScript==
// @name Import DG/Decca releases to MusicBrainz // @name Import DG/Decca releases to MusicBrainz
// @namespace https://github.com/murdos/musicbrainz-userscripts // @namespace https://github.com/murdos/musicbrainz-userscripts
// @author loujine // @author loujine
// @version 2018.2.18.1 // @version 2018.2.18.1
// @downloadURL https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/dgdecca_importer.user.js // @downloadURL https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/dgdecca_importer.user.js
// @updateURL https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/dgdecca_importer.user.js // @updateURL https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/dgdecca_importer.user.js
// @icon https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/assets/images/Musicbrainz_import_logo.png // @icon https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/assets/images/Musicbrainz_import_logo.png
// @description Add a button to import DG/Decca releases to MusicBrainz // @description Add a button to import DG/Decca releases to MusicBrainz
// @compatible firefox+greasemonkey // @compatible firefox+greasemonkey
// @licence CC BY-NC-SA 3.0 (https://creativecommons.org/licenses/by-nc-sa/3.0/) // @licence CC BY-NC-SA 3.0 (https://creativecommons.org/licenses/by-nc-sa/3.0/)
// @include http*://*deutschegrammophon.com/*/cat/* // @include http*://*deutschegrammophon.com/*/cat/*
// @include http*://*deccaclassics.com/*/cat/* // @include http*://*deccaclassics.com/*/cat/*
// @require lib/mbimport.js // @require lib/mbimport.js
// @require lib/mbimportstyle.js // @require lib/mbimportstyle.js
// @grant none // @grant none
// @run-at document-end // @run-at document-end
// ==/UserScript== // ==/UserScript==
}; };
if (meta && meta.toString && (meta = meta.toString())) { if (meta && meta.toString && (meta = meta.toString())) {
var meta = {'name': meta.match(/@name\s+(.+)/)[1], var meta = { name: meta.match(/@name\s+(.+)/)[1], version: meta.match(/@version\s+(.+)/)[1] };
'version': meta.match(/@version\s+(.+)/)[1]};
} }
var siteURL = document.URL.split('/')[2].replace('www.', ''); var siteURL = document.URL.split('/')[2].replace('www.', '');
var months = { var months = {
'Jan.': 1, 'Feb.': 2, 'Mar.': 3, 'Apr.': 4, 'Jan.': 1,
'May': 5, 'Jun.': 6, 'Jul.': 7, 'Aug.': 8, 'Feb.': 2,
'Sep.': 9, 'Oct.': 10, 'Nov.': 11, 'Dec.': 12 'Mar.': 3,
'Apr.': 4,
May: 5,
'Jun.': 6,
'Jul.': 7,
'Aug.': 8,
'Sep.': 9,
'Oct.': 10,
'Nov.': 11,
'Dec.': 12
}; };
var labels = { var labels = {
'deutschegrammophon.com': { 'deutschegrammophon.com': {
'name': 'Deutsche Grammophon', name: 'Deutsche Grammophon',
'mbid': '5a584032-dcef-41bb-9f8b-19540116fb1c', mbid: '5a584032-dcef-41bb-9f8b-19540116fb1c',
'catno': document.URL.split('/')[5] catno: document.URL.split('/')[5]
}, },
'deccaclassics.com': { 'deccaclassics.com': {
'name': 'Decca Classics', name: 'Decca Classics',
'mbid': '89a9993d-1dad-4445-a3d7-1d8df04f7e7b', mbid: '89a9993d-1dad-4445-a3d7-1d8df04f7e7b',
'catno': document.URL.split('/')[5] catno: document.URL.split('/')[5]
} }
} };
var editNote = ('Imported from ' var editNote = `Imported from ${document.URL}\n\n` + `GM script: "${meta.name}" (${meta.version})\n\n`;
+ document.URL
+ '\n —\n'
+ 'GM script: "' + meta.name + '" (' + meta.version + ')\n\n');
function _clean(s) { function _clean(s) {
return s return s
@ -74,27 +79,30 @@ function _clean(s) {
.replace(' - ', ': ') .replace(' - ', ': ')
.replace(' | ', ': ') .replace(' | ', ': ')
.replace('K.', 'K. ') // Mozart .replace('K.', 'K. ') // Mozart
.replace('S.', 'S. ') // Liszt .replace('S.', 'S. '); // Liszt
;
} }
function extract_release_data() { function extract_release_data() {
console.log('extract_release_data'); console.log('extract_release_data');
function _setTitle() { function _setTitle() {
var title = $('h4')[0].textContent; let title = $('h4')[0].textContent;
if ($('div.works').length) { if ($('div.works').length) {
title += ' ' + $('div.works')[0].innerHTML.replace(/<br><br>/g, ' / ').replace(/<br>/g, ' '); title += ` ${$('div.works')[0]
.innerHTML.replace(/<br><br>/g, ' / ')
.replace(/<br>/g, ' ')}`;
} }
return title; return title;
} }
function _setReleasePerformers() { function _setReleasePerformers() {
var list = $('div.artists')[0].innerHTML.split('<br>').map(function (artist) { let list = $('div.artists')[0]
.innerHTML.split('<br>')
.map(function(artist) {
return { return {
'credited_name': artist, credited_name: artist,
'artist_name': artist, artist_name: artist,
'artist_mbid': '', artist_mbid: '',
'joinphrase': ', ' joinphrase: ', '
}; };
}); });
list[list.length - 1]['joinphrase'] = ''; list[list.length - 1]['joinphrase'] = '';
@ -102,19 +110,21 @@ function extract_release_data() {
} }
function _setReleaseArtists() { function _setReleaseArtists() {
var composer = document.getElementsByTagName('h4')[0].textContent; let composer = document.getElementsByTagName('h4')[0].textContent;
var list = [{ let list = [
'credited_name': composer, {
'artist_name': composer, credited_name: composer,
'artist_mbid': '', artist_name: composer,
'joinphrase': '; ' artist_mbid: '',
}]; joinphrase: '; '
}
];
return list.concat(_setReleasePerformers()); return list.concat(_setReleasePerformers());
} }
function _indices(array, element) { function _indices(array, element) {
var indices = []; let indices = [];
var idx = array.indexOf(element); let idx = array.indexOf(element);
while (idx != -1) { while (idx != -1) {
indices.push(idx); indices.push(idx);
idx = array.indexOf(element, idx + 1); idx = array.indexOf(element, idx + 1);
@ -122,14 +132,14 @@ function extract_release_data() {
return indices; return indices;
} }
var date = document.getElementsByClassName('date')[0].textContent; let date = document.getElementsByClassName('date')[0].textContent;
date = date.replace('Int. Release ', '').split(' '); date = date.replace('Int. Release ', '').split(' ');
var nodes = []; let nodes = [];
var tracklist_node = document.getElementById('tracklist'); let tracklist_node = document.getElementById('tracklist');
$('.item,.hier0,.hier1,.hier2,.hier3').each(function (idx, node) { $('.item,.hier0,.hier1,.hier2,.hier3').each(function(idx, node) {
var idx; var idx;
var d = {}; let d = {};
if (node.classList.contains('hier0')) { if (node.classList.contains('hier0')) {
d['level'] = 0; d['level'] = 0;
} else if (node.classList.contains('hier1')) { } else if (node.classList.contains('hier1')) {
@ -155,9 +165,9 @@ function extract_release_data() {
console.log(nodes, tracklist_node); console.log(nodes, tracklist_node);
// complete track titles // complete track titles
var header0, header1, header2, idx; let header0, header1, header2, idx;
nodes.forEach(function (node, idx) { nodes.forEach(function(node, idx) {
var level = node['level'], let level = node['level'],
type = node['type'], type = node['type'],
content = node['title']; content = node['title'];
if (type === 'work') { if (type === 'work') {
@ -172,30 +182,30 @@ function extract_release_data() {
if (level === 0) { if (level === 0) {
nodes[idx]['title'] = content; nodes[idx]['title'] = content;
} else if (level === 1) { } else if (level === 1) {
nodes[idx]['title'] = header0 + ': ' + content; nodes[idx]['title'] = `${header0}: ${content}`;
} else if (level === 2) { } else if (level === 2) {
nodes[idx]['title'] = header0 + ', ' + header1 + ': ' + content; nodes[idx]['title'] = `${header0}, ${header1}: ${content}`;
} else if (level === 3) { } else if (level === 3) {
nodes[idx]['title'] = header0 + ', ' + header1 + ', ' + header2 + ': ' + content; nodes[idx]['title'] = `${header0}, ${header1}, ${header2}: ${content}`;
} }
} }
}); });
var discs = [], let discs = [],
tracks = [], tracks = [],
medium_title = ''; medium_title = '';
nodes.forEach(function (item, idx) { nodes.forEach(function(item, idx) {
if (item.type === 'track') { if (item.type === 'track') {
var track = extract_track_data(item.node); let track = extract_track_data(item.node);
track.title = _clean(item.title); track.title = _clean(item.title);
tracks.push(track); tracks.push(track);
} }
if (item.type === 'medium') { if (item.type === 'medium') {
if (idx > 0) { if (idx > 0) {
discs.push({ discs.push({
'title': '', // medium_title, title: '', // medium_title,
'format': 'CD', format: 'CD',
'tracks': tracks tracks: tracks
}); });
} }
medium_title = item.title; medium_title = item.title;
@ -204,105 +214,107 @@ function extract_release_data() {
}); });
// push last medium // push last medium
discs.push({ discs.push({
'title': '', // nodes[0].title, title: '', // nodes[0].title,
'format': 'CD', format: 'CD',
'tracks': tracks tracks: tracks
}); });
return { return {
'title': _setTitle(), title: _setTitle(),
'artist_credit': _setReleaseArtists(), artist_credit: _setReleaseArtists(),
'type': 'Album', type: 'Album',
'status': 'Official', status: 'Official',
'language': 'eng', // 'English', language: 'eng', // 'English',
'script': 'Latn', // 'Latin', script: 'Latn', // 'Latin',
'packaging': '', packaging: '',
'country': '', country: '',
'year': date[2], year: date[2],
'month': months[date[1]], month: months[date[1]],
'day': date[0], day: date[0],
'labels': [labels[siteURL]], labels: [labels[siteURL]],
'barcode': document.getElementById('upc').value.replace('00', ''), // too many 0s barcode: document.getElementById('upc').value.replace('00', ''), // too many 0s
'urls': [{ urls: [
'link_type': 288, // 'discography' {
'url': document.URL link_type: 288, // 'discography'
}], url: document.URL
'discs': discs }
],
discs: discs
}; };
} }
function extract_track_data(node) { function extract_track_data(node) {
function _setTrackArtists(artistString) { function _setTrackArtists(artistString) {
console.log('artistString', artistString); console.log('artistString', artistString);
var artists; let artists;
if (artistString.includes(' | ')) { if (artistString.includes(' | ')) {
artists = artistString.split(' | ').map(function (artist) { artists = artistString.split(' | ').map(function(artist) {
return { return {
'credited_name': artist.split(',')[0], credited_name: artist.split(',')[0],
'artist_name': artist.split(',')[0], artist_name: artist.split(',')[0],
'artist_mbid': '', artist_mbid: '',
'joinphrase': ', ' joinphrase: ', '
}; };
}); });
} else { } else {
artists = artistString.split(', ').map(function (artist, idx) { artists = artistString.split(', ').map(function(artist, idx) {
var mbid = ''; let mbid = '';
var url = '/ws/js/artist/?q=' + artist + '&fmt=json&limit=1'; let url = `/ws/js/artist/?q=${artist}&fmt=json&limit=1`;
return { return {
'credited_name': artist, credited_name: artist,
'artist_name': artist, artist_name: artist,
'artist_mbid': mbid, artist_mbid: mbid,
'joinphrase': ', ' joinphrase: ', '
}; };
}); });
} }
artists[artists.length - 1]['joinphrase'] = ''; artists[artists.length - 1]['joinphrase'] = '';
return artists return artists;
} }
var schema = {}; let schema = {};
if (node.querySelectorAll('meta').length) { if (node.querySelectorAll('meta').length) {
// https://schema.org/MusicRecording info available // https://schema.org/MusicRecording info available
for (var item of node.querySelectorAll('meta')) { for (let item of node.querySelectorAll('meta')) {
var attrs = item.attributes; let attrs = item.attributes;
schema[attrs.itemprop.value] = attrs.content.value; schema[attrs.itemprop.value] = attrs.content.value;
} }
} else { } else {
console.log('no meta data on ', node); console.log('no meta data on ', node);
schema.name = node.querySelectorAll('div.track-text > a.fancy')[0].textContent; schema.name = node.querySelectorAll('div.track-text > a.fancy')[0].textContent;
schema.byArtist = $(node).parent().nextAll('div.container-container').children('.artists-container')[0].textContent; schema.byArtist = $(node)
var previousComposers = $(node).parent().prevAll('div.container-container').children('.first-composer-container'); .parent()
schema.creator = previousComposers[previousComposers.length-1].textContent; .nextAll('div.container-container')
.children('.artists-container')[0].textContent;
let previousComposers = $(node)
.parent()
.prevAll('div.container-container')
.children('.first-composer-container');
schema.creator = previousComposers[previousComposers.length - 1].textContent;
} }
console.info('schema', schema); console.info('schema', schema);
return { return {
'number': parseInt(node.querySelectorAll('div.track-no')[0].textContent), number: parseInt(node.querySelectorAll('div.track-no')[0].textContent),
'title': _clean(schema.name), title: _clean(schema.name),
'duration': node.querySelectorAll('div.track-time')[0].textContent, duration: node.querySelectorAll('div.track-time')[0].textContent,
'artist_credit': _setTrackArtists(schema.byArtist), // CSG artist_credit: _setTrackArtists(schema.byArtist), // CSG
'performer': schema.byArtist, performer: schema.byArtist,
'composer': schema.creator, composer: schema.creator,
'url': node.querySelectorAll('div.track-text > a.fancy')[0].href url: node.querySelectorAll('div.track-text > a.fancy')[0].href
}; };
} }
// Insert links in page // Insert links in page
function insertMBSection(release) { function insertMBSection(release) {
var mbUI = $('<div class="section musicbrainz"><h3>MusicBrainz</h3></div>'); let mbUI = $('<div class="section musicbrainz"><h3>MusicBrainz</h3></div>');
var mbContentBlock = $('<div class="section_content"></div>'); let mbContentBlock = $('<div class="section_content"></div>');
mbUI.append(mbContentBlock); mbUI.append(mbContentBlock);
// Form parameters // Form parameters
var parameters = MBImport.buildFormParameters(release, editNote); let parameters = MBImport.buildFormParameters(release, editNote);
// Build form + search button // Build form + search button
var innerHTML = '<div id="mb_buttons">' let innerHTML = `<div id="mb_buttons">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`;
+ MBImport.buildFormHTML(parameters)
+ MBImport.buildSearchButton(release)
+ '</div>';
mbContentBlock.append(innerHTML); mbContentBlock.append(innerHTML);
$('div#product-text').append(mbUI[0]); $('div#product-text').append(mbUI[0]);
@ -311,11 +323,9 @@ function insertMBSection(release) {
display: 'inline-block', display: 'inline-block',
width: '100%' width: '100%'
}); });
$('form.musicbrainz_import').css({width: '49%', display: 'inline-block'}); $('form.musicbrainz_import').css({ width: '49%', display: 'inline-block' });
$('form.musicbrainz_import_search').css({'float': 'right'}) $('form.musicbrainz_import_search').css({ float: 'right' });
$('form.musicbrainz_import > button').css( $('form.musicbrainz_import > button').css({ width: '100%', 'box-sizing': 'border-box' });
{width: '100%', 'box-sizing': 'border-box'}
);
mbUI.slideDown(); mbUI.slideDown();
} }

File diff suppressed because it is too large Load diff

View file

@ -21,7 +21,7 @@ $(document).ready(function() {
MBImportStyle(); MBImportStyle();
if (window.location.href.match(/encyclopedisque\.fr\/disque\/(\d+)/)) { if (window.location.href.match(/encyclopedisque\.fr\/disque\/(\d+)/)) {
var release = parseEncyclopedisquePage(); let release = parseEncyclopedisquePage();
setupImportUI(release); setupImportUI(release);
} }
@ -32,57 +32,64 @@ $(document).ready(function() {
// Encyclopedisque functions // Encyclopedisque functions
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function setupImportUI(release) { function setupImportUI(release) {
// Form parameters // Form parameters
var edit_note = MBImport.makeEditNote(window.location.href, 'Encyclopedisque'); let edit_note = MBImport.makeEditNote(window.location.href, 'Encyclopedisque');
var parameters = MBImport.buildFormParameters(release, edit_note); let parameters = MBImport.buildFormParameters(release, edit_note);
// Build form // Build form
var mbUI = $(MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release)).hide(); let mbUI = $(MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release)).hide();
$('#recherchebox').append(mbUI); $('#recherchebox').append(mbUI);
$('form.musicbrainz_import button').css({width: '100%'}); $('form.musicbrainz_import button').css({ width: '100%' });
mbUI.slideDown(); mbUI.slideDown();
} }
function insertMBLinks() { function insertMBLinks() {
let current_url = window.location.href;
var current_url = window.location.href;
if (current_url.match(/\/disque\//)) { if (current_url.match(/\/disque\//)) {
mblinks.searchAndDisplayMbLink(current_url, 'release', function (link) { $('h2 span').before(link); } ); mblinks.searchAndDisplayMbLink(current_url, 'release', function(link) {
$('h2 span').before(link);
});
} else if (current_url.match(/\/artiste\//)) { } else if (current_url.match(/\/artiste\//)) {
mblinks.searchAndDisplayMbLink(current_url, 'artist', function (link) { $('h2').prepend(link); } ); mblinks.searchAndDisplayMbLink(current_url, 'artist', function(link) {
$('h2').prepend(link);
});
} }
$('div.v7P, div.v12P').find('a[href*="/disque/"]').each(function() { $('div.v7P, div.v12P')
var $link = $(this); .find('a[href*="/disque/"]')
var external_url = window.location.origin + $link.attr('href'); .each(function() {
mblinks.searchAndDisplayMbLink(external_url, 'release', function (link) { $link.after(link).after('<br />') } ); let $link = $(this);
let external_url = window.location.origin + $link.attr('href');
mblinks.searchAndDisplayMbLink(external_url, 'release', function(link) {
$link.after(link).after('<br />');
});
}); });
$('h2, div.main').find('a[href*="/artiste/"]').each(function() { $('h2, div.main')
var $link = $(this); .find('a[href*="/artiste/"]')
var external_url = window.location.origin + $link.attr('href'); .each(function() {
mblinks.searchAndDisplayMbLink(external_url, 'artist', function (link) { $link.before(link); } ); let $link = $(this);
let external_url = window.location.origin + $link.attr('href');
mblinks.searchAndDisplayMbLink(external_url, 'artist', function(link) {
$link.before(link);
});
}); });
} }
// Analyze Encyclopedisque data and prepare to release object // Analyze Encyclopedisque data and prepare to release object
function parseEncyclopedisquePage() { function parseEncyclopedisquePage() {
release = new Object(); release = new Object();
var infoHeader = document.body.querySelector("#contenu > h2:nth-of-type(1)"); let infoHeader = document.body.querySelector('#contenu > h2:nth-of-type(1)');
// Release artist credit // Release artist credit
release.artist_credit = new Array(); release.artist_credit = new Array();
var artist_name = infoHeader.querySelector("div.floatright:nth-of-type(1)").textContent.trim(); let artist_name = infoHeader.querySelector('div.floatright:nth-of-type(1)').textContent.trim();
release.artist_credit.push( { 'artist_name': artist_name } ); release.artist_credit.push({ artist_name: artist_name });
// Release title // Release title
release.title = infoHeader.querySelector("span:nth-of-type(1)").textContent.trim(); release.title = infoHeader.querySelector('span:nth-of-type(1)').textContent.trim();
// Default status is official, will change if "tirage promo" is found (see below) // Default status is official, will change if "tirage promo" is found (see below)
release.status = 'official'; release.status = 'official';
@ -91,60 +98,83 @@ function parseEncyclopedisquePage() {
release.language = 'fra'; release.language = 'fra';
release.script = 'Latn'; release.script = 'Latn';
var disc = {'position': 1, 'tracks': [] }; let disc = { position: 1, tracks: [] };
release.discs = [ disc ]; release.discs = [disc];
// Release URL // Release URL
release.urls = new Array(); release.urls = new Array();
release.urls.push( { 'url': window.location.href, 'link_type': MBImport.URL_TYPES.other_databases } ); release.urls.push({ url: window.location.href, link_type: MBImport.URL_TYPES.other_databases });
// Parse other infos // Parse other infos
var releaseInfos = document.body.querySelectorAll("div.main tr"); let releaseInfos = document.body.querySelectorAll('div.main tr');
var lastVinylFace = ''; let lastVinylFace = '';
var lastInfoType; let lastInfoType;
for (var i = 0; i < releaseInfos.length; i++) { for (let i = 0; i < releaseInfos.length; i++) {
var infoType = releaseInfos[i].querySelector("td:nth-of-type(1)").textContent.trim(); let infoType = releaseInfos[i].querySelector('td:nth-of-type(1)').textContent.trim();
// Release date // Release date
if (infoType == "Sortie :") { if (infoType == 'Sortie :') {
var infoValue = releaseInfos[i].querySelector("td:nth-of-type(2)").textContent.trim(); var infoValue = releaseInfos[i].querySelector('td:nth-of-type(2)').textContent.trim();
var re = /\s*(janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)?\s*([\d\?]{4})?\s*(?:chez)?\s*((?:\S+\s?)*)\s*\(?([^\)]*)?\)?/; let re = /\s*(janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)?\s*([\d\?]{4})?\s*(?:chez)?\s*((?:\S+\s?)*)\s*\(?([^\)]*)?\)?/;
m = infoValue.match(re); m = infoValue.match(re);
month = m[1]; month = m[1];
if (month != undefined) { if (month != undefined) {
switch (month) switch (month) {
{ case 'janvier':
case "janvier": release.month = 1; break; release.month = 1;
case "février": release.month = 2; break; break;
case "mars": release.month = 3; break; case 'février':
case "avril": release.month = 4; break; release.month = 2;
case "mai": release.month = 5; break; break;
case "juin": release.month = 6; break; case 'mars':
case "juillet": release.month = 7; break; release.month = 3;
case "août": release.month = 8; break; break;
case "septembre": release.month = 9; break; case 'avril':
case "octobre": release.month = 10; break; release.month = 4;
case "novembre": release.month = 11; break; break;
case "décembre": release.month = 12; break; case 'mai':
release.month = 5;
break;
case 'juin':
release.month = 6;
break;
case 'juillet':
release.month = 7;
break;
case 'août':
release.month = 8;
break;
case 'septembre':
release.month = 9;
break;
case 'octobre':
release.month = 10;
break;
case 'novembre':
release.month = 11;
break;
case 'décembre':
release.month = 12;
break;
} }
} }
release.year = m[2]; release.year = m[2];
release.labels = []; release.labels = [];
var labels = m[3]; let labels = m[3];
if (labels != undefined) { if (labels != undefined) {
$.each(labels.split("/"), function(index, label) { $.each(labels.split('/'), function(index, label) {
release.labels.push({ 'name': label.trim(), 'catno': m[4] }); release.labels.push({ name: label.trim(), catno: m[4] });
}); });
} else { } else {
release.labels.push({ 'catno': m[4] }); release.labels.push({ catno: m[4] });
} }
} else if (infoType.match(/^Face [A-Z]/) || (infoType == '' && lastInfoType.match(/^Face [A-Z]/))) { } else if (infoType.match(/^Face [A-Z]/) || (infoType == '' && lastInfoType.match(/^Face [A-Z]/))) {
// Tracks // Tracks
var track = new Object(); let track = new Object();
// First part of tracknumber (A, B, ...) // First part of tracknumber (A, B, ...)
var tnum_part1 = ''; let tnum_part1 = '';
if (m = infoType.match(/^Face ([A-Z])/)) { if ((m = infoType.match(/^Face ([A-Z])/))) {
lastVinylFace = m[1]; lastVinylFace = m[1];
tnum_part1 = m[1]; tnum_part1 = m[1];
} else { } else {
@ -152,43 +182,60 @@ function parseEncyclopedisquePage() {
} }
// Track title // Track title
if (releaseInfos[i].querySelector("td:nth-of-type(2) em") == null) { if (releaseInfos[i].querySelector('td:nth-of-type(2) em') == null) {
continue; continue;
} }
var title = releaseInfos[i].querySelector("td:nth-of-type(2) em").textContent.trim(); let title = releaseInfos[i].querySelector('td:nth-of-type(2) em').textContent.trim();
// 2nd part of tracknumber (1, 2, ...) // 2nd part of tracknumber (1, 2, ...)
var tnum_part2 = ''; let tnum_part2 = '';
if (m = infoType.match(/^Face [A-Z](\d+)/)) { if ((m = infoType.match(/^Face [A-Z](\d+)/))) {
tnum_part2 = m[1]; tnum_part2 = m[1];
} else if (m = title.match(/^(\d+)\.\s+(.*)$/)) { } else if ((m = title.match(/^(\d+)\.\s+(.*)$/))) {
tnum_part2 = m[1]; tnum_part2 = m[1];
title = m[2]; title = m[2];
} }
// Track length // Track length
if (m = releaseInfos[i].querySelector("td:nth-of-type(2)").textContent.trim().match(/- (\d+)(\d+)$/)) { if (
track.duration = m[1] + ':' + m[2]; (m = releaseInfos[i]
.querySelector('td:nth-of-type(2)')
.textContent.trim()
.match(/- (\d+)(\d+)$/))
) {
track.duration = `${m[1]}:${m[2]}`;
} }
track.number = tnum_part1 + tnum_part2; track.number = tnum_part1 + tnum_part2;
track.title = title; track.title = title;
disc.tracks.push(track); disc.tracks.push(track);
} else if (infoType == "Format :") { } else if (infoType == 'Format :') {
// Format => medium format, release-group type, release status // Format => medium format, release-group type, release status
var infoValue = releaseInfos[i].querySelector("td:nth-of-type(2)").textContent.trim(); var infoValue = releaseInfos[i].querySelector('td:nth-of-type(2)').textContent.trim();
var values = infoValue.split(" / "); let values = infoValue.split(' / ');
values.forEach(function(value) { values.forEach(function(value) {
if (value.indexOf('45 tours') > -1) { disc.format = '7" Vinyl'; } if (value.indexOf('45 tours') > -1) {
if (value.indexOf('33 tours') > -1) { disc.format = '12" Vinyl'; } disc.format = '7" Vinyl';
if (value.indexOf('LP') > -1) { release.type = 'album'; } }
if (value.indexOf('EP') > -1) { release.type = 'ep'; } if (value.indexOf('33 tours') > -1) {
if (value.indexOf('SP') > -1) { release.type = 'single'; } disc.format = '12" Vinyl';
if (value.indexOf('tirage promo') > -1) { release.status = 'promotion'; } }
if (value.indexOf('LP') > -1) {
release.type = 'album';
}
if (value.indexOf('EP') > -1) {
release.type = 'ep';
}
if (value.indexOf('SP') > -1) {
release.type = 'single';
}
if (value.indexOf('tirage promo') > -1) {
release.status = 'promotion';
}
}); });
} else if (infoType == "Pays :") { } else if (infoType == 'Pays :') {
// Country // Country
var infoValue = releaseInfos[i].querySelector("td:nth-of-type(2)").textContent.trim(); var infoValue = releaseInfos[i].querySelector('td:nth-of-type(2)').textContent.trim();
if (infoValue == 'France') { if (infoValue == 'France') {
release.country = 'FR'; release.country = 'FR';
} else if (infoValue == 'Royaume-uni') { } else if (infoValue == 'Royaume-uni') {
@ -211,7 +258,7 @@ function parseEncyclopedisquePage() {
release.no_barcode = '1'; release.no_barcode = '1';
} }
LOGGER.info("Parsed release: ", release); LOGGER.info('Parsed release: ', release);
return release; return release;
} }

View file

@ -41,7 +41,7 @@ var MBID_REGEX = /[0-9a-z]{8}\-[0-9a-z]{4}\-[0-9a-z]{4}\-[0-9a-z]{4}\-[0-9a-z]{1
var releasesOrReleaseGroups = document.querySelectorAll("#content table.tbl > tbody > tr > td a[href^='/release']"); var releasesOrReleaseGroups = document.querySelectorAll("#content table.tbl > tbody > tr > td a[href^='/release']");
for (var r = 0; r < releasesOrReleaseGroups.length; r++) { for (var r = 0; r < releasesOrReleaseGroups.length; r++) {
if (releasesOrReleaseGroups[r].getAttribute("href").match(/\/release-group\//)) { if (releasesOrReleaseGroups[r].getAttribute('href').match(/\/release-group\//)) {
inject_release_group_button(releasesOrReleaseGroups[r].parentNode); inject_release_group_button(releasesOrReleaseGroups[r].parentNode);
} else { } else {
inject_release_button(releasesOrReleaseGroups[r].parentNode); inject_release_button(releasesOrReleaseGroups[r].parentNode);
@ -49,23 +49,24 @@ for (var r = 0; r < releasesOrReleaseGroups.length; r++) {
} }
function inject_release_group_button(parent) { function inject_release_group_button(parent) {
var mbid = parent.querySelector("a").href.match(MBID_REGEX), let mbid = parent.querySelector('a').href.match(MBID_REGEX),
table = document.createElement("table"); table = document.createElement('table');
table.style.marginTop = "1em"; table.style.marginTop = '1em';
table.style.marginLeft = "1em"; table.style.marginLeft = '1em';
table.style.paddingLeft = "1em"; table.style.paddingLeft = '1em';
var button = create_button( let button = create_button(
"/ws/2/release?release-group=" + mbid + "&limit=100&inc=media&fmt=json", `/ws/2/release?release-group=${mbid}&limit=100&inc=media&fmt=json`,
function(toggled) { function(toggled) {
if (toggled) parent.appendChild(table); else parent.removeChild(table); if (toggled) parent.appendChild(table);
else parent.removeChild(table);
}, },
function(json) { function(json) {
parse_release_group(json, mbid, parent, table); parse_release_group(json, mbid, parent, table);
}, },
function(status) { function(status) {
table.innerHTML = '<tr><td style="color: #f00;">Error loading release group (HTTP status ' + status + ')</td></tr>'; table.innerHTML = `<tr><td style="color: #f00;">Error loading release group (HTTP status ${status})</td></tr>`;
} }
); );
@ -73,23 +74,24 @@ function inject_release_group_button(parent) {
} }
function inject_release_button(parent, _table_parent, _table, _mbid) { function inject_release_button(parent, _table_parent, _table, _mbid) {
var mbid = _mbid || parent.querySelector("a").href.match(MBID_REGEX), let mbid = _mbid || parent.querySelector('a').href.match(MBID_REGEX),
table = _table || document.createElement("table"); table = _table || document.createElement('table');
table.style.marginTop = "1em"; table.style.marginTop = '1em';
table.style.marginLeft = "1em"; table.style.marginLeft = '1em';
table.style.paddingLeft = "1em"; table.style.paddingLeft = '1em';
var button = create_button( let button = create_button(
"/ws/2/release/" + mbid + "?inc=media+recordings+artist-credits&fmt=json", `/ws/2/release/${mbid}?inc=media+recordings+artist-credits&fmt=json`,
function(toggled) { function(toggled) {
if (toggled) parent.appendChild(table); else parent.removeChild(table); if (toggled) parent.appendChild(table);
else parent.removeChild(table);
}, },
function(json) { function(json) {
parse_release(json, table); parse_release(json, table);
}, },
function(status) { function(status) {
table.innerHTML = '<tr><td style="color: #f00;">Error loading release (HTTP status ' + status + ')</td></tr>'; table.innerHTML = `<tr><td style="color: #f00;">Error loading release (HTTP status ${status})</td></tr>`;
} }
); );
@ -97,25 +99,31 @@ function inject_release_button(parent, _table_parent, _table, _mbid) {
} }
function create_button(url, dom_callback, success_callback, error_callback) { function create_button(url, dom_callback, success_callback, error_callback) {
var button = document.createElement("span"), toggled = false; let button = document.createElement('span'),
toggled = false;
button.innerHTML = "&#9654;"; button.innerHTML = '&#9654;';
button.style.cursor = "pointer"; button.style.cursor = 'pointer';
button.style.marginRight = "4px"; button.style.marginRight = '4px';
button.style.color = "#777"; button.style.color = '#777';
button.addEventListener("mousedown", function() { button.addEventListener(
'mousedown',
function() {
toggled = !toggled; toggled = !toggled;
if (toggled) if (toggled) button.innerHTML = '&#9660;';
button.innerHTML = "&#9660;"; else button.innerHTML = '&#9654;';
else button.innerHTML = "&#9654;";
dom_callback(toggled); dom_callback(toggled);
}, false); },
false
);
button.addEventListener("mousedown", function() { button.addEventListener(
var this_event = arguments.callee; 'mousedown',
button.removeEventListener("mousedown", this_event, false); function() {
var req = new XMLHttpRequest(); let this_event = arguments.callee;
button.removeEventListener('mousedown', this_event, false);
let req = new XMLHttpRequest();
req.onreadystatechange = function() { req.onreadystatechange = function() {
if (req.readyState != 4) return; if (req.readyState != 4) return;
@ -123,50 +131,60 @@ function create_button(url, dom_callback, success_callback, error_callback) {
if (req.status == 200 && req.responseText) { if (req.status == 200 && req.responseText) {
success_callback(JSON.parse(req.responseText)); success_callback(JSON.parse(req.responseText));
} else { } else {
button.addEventListener("mousedown", function() { button.addEventListener(
button.removeEventListener("mousedown", arguments.callee, false); 'mousedown',
button.addEventListener("mousedown", this_event, false); function() {
}, false); button.removeEventListener('mousedown', arguments.callee, false);
button.addEventListener('mousedown', this_event, false);
},
false
);
error_callback(req.status); error_callback(req.status);
} }
}; };
req.open("GET", url, true); req.open('GET', url, true);
req.send(null); req.send(null);
},
}, false); false
);
return button; return button;
} }
function format_time(ms) { function format_time(ms) {
var ts = ms / 1000, s = Math.round(ts % 60); let ts = ms / 1000,
return (Math.floor(ts / 60) + ":" + (s >= 10 ? s : "0" + s)); s = Math.round(ts % 60);
return `${Math.floor(ts / 60)}:${s >= 10 ? s : `0${s}`}`;
} }
function parse_release_group(json, mbid, parent, table) { function parse_release_group(json, mbid, parent, table) {
var releases = json.releases; let releases = json.releases;
table.innerHTML = ""; table.innerHTML = '';
for (var i = 0; i < releases.length; i++) { for (var i = 0; i < releases.length; i++) {
var release = releases[i], media = {}, tracks = [], formats = []; let release = releases[i],
media = {},
tracks = [],
formats = [];
for (var j = 0; j < release.media.length; j++) { for (let j = 0; j < release.media.length; j++) {
var medium = release.media[j], format = medium.format, count = medium["track-count"]; var medium = release.media[j],
if (format) format = medium.format,
format in media ? (media[format] += 1) : (media[format] = 1); count = medium['track-count'];
if (format) format in media ? (media[format] += 1) : (media[format] = 1);
tracks.push(count); tracks.push(count);
} }
for (format in media) { for (format in media) {
var count = media[format], txt; var count = media[format],
if (count > 1) txt;
formats.push(count.toString() + "&#215;" + format); if (count > 1) formats.push(`${count.toString()}&#215;${format}`);
else formats.push(format); else formats.push(format);
} }
release.tracks = tracks.join(" + "); release.tracks = tracks.join(' + ');
release.formats = formats.join(" + "); release.formats = formats.join(' + ');
} }
releases.sort(function(a, b) { releases.sort(function(a, b) {
@ -175,82 +193,77 @@ function parse_release_group(json, mbid, parent, table) {
return 0; return 0;
}); });
for (var i = 0; i < releases.length; i++) {(function(release) { for (var i = 0; i < releases.length; i++) {
var track_tr = document.createElement("tr"), (function(release) {
track_td = document.createElement("td"), let track_tr = document.createElement('tr'),
track_table = document.createElement("table"), track_td = document.createElement('td'),
format_td = document.createElement("td"), track_table = document.createElement('table'),
tr = document.createElement("tr"), format_td = document.createElement('td'),
td = document.createElement("td"), tr = document.createElement('tr'),
a = createLink("/release/" + release.id, release.title); td = document.createElement('td'),
a = createLink(`/release/${release.id}`, release.title);
track_td.colSpan = 6; track_td.colSpan = 6;
track_table.style.width = "100%"; track_table.style.width = '100%';
track_table.style.marginLeft = "1em"; track_table.style.marginLeft = '1em';
track_tr.appendChild(track_td); track_tr.appendChild(track_td);
inject_release_button(td, track_td, track_table, release.id); inject_release_button(td, track_td, track_table, release.id);
td.appendChild(a); td.appendChild(a);
if (release.disambiguation) { if (release.disambiguation) {
td.appendChild(document.createTextNode(" (" + release.disambiguation + ")")); td.appendChild(document.createTextNode(` (${release.disambiguation})`));
} }
tr.appendChild(td); tr.appendChild(td);
format_td.innerHTML = release.formats; format_td.innerHTML = release.formats;
tr.appendChild(format_td); tr.appendChild(format_td);
var columns = [ let columns = [release.tracks, release.date || '', release.country || '', release.status || ''];
release.tracks,
release.date || "",
release.country || "",
release.status || ""
];
for (var i = 0; i < columns.length; i++) for (let i = 0; i < columns.length; i++) tr.appendChild(createElement('td', columns[i]));
tr.appendChild(createElement("td", columns[i]));
table.appendChild(tr); table.appendChild(tr);
table.appendChild(track_tr); table.appendChild(track_tr);
})(releases[i]);
}
})(releases[i]);} let bottom_tr = document.createElement('tr'),
bottom_td = document.createElement('td');
var bottom_tr = document.createElement("tr"),
bottom_td = document.createElement("td");
bottom_td.colSpan = 6; bottom_td.colSpan = 6;
bottom_td.style.padding = "1em"; bottom_td.style.padding = '1em';
bottom_td.appendChild(createLink("/release-group/" + mbid + "/edit", "edit")); bottom_td.appendChild(createLink(`/release-group/${mbid}/edit`, 'edit'));
bottom_td.appendChild(document.createTextNode(" | ")); bottom_td.appendChild(document.createTextNode(' | '));
bottom_td.appendChild(createLink("/release/add?release-group=" + mbid, "add release")); bottom_td.appendChild(createLink(`/release/add?release-group=${mbid}`, 'add release'));
bottom_td.appendChild(document.createTextNode(" | ")); bottom_td.appendChild(document.createTextNode(' | '));
bottom_td.appendChild(createLink("/release-group/" + mbid + "/edits", "editing history")); bottom_td.appendChild(createLink(`/release-group/${mbid}/edits`, 'editing history'));
bottom_tr.appendChild(bottom_td); bottom_tr.appendChild(bottom_td);
table.appendChild(bottom_tr); table.appendChild(bottom_tr);
} }
function parse_release(json, table) { function parse_release(json, table) {
var media = json.media; let media = json.media;
table.innerHTML = ""; table.innerHTML = '';
for (var i = 0; i < media.length; i++) { for (let i = 0; i < media.length; i++) {
var medium = media[i], let medium = media[i],
format = medium.format ? medium.format + " " + (i + 1) : "Medium " + (i + 1); format = medium.format ? `${medium.format} ${i + 1}` : `Medium ${i + 1}`;
table.innerHTML += '<tr class="subh"><td colspan="4">' + format + "</td></tr>"; table.innerHTML += `<tr class="subh"><td colspan="4">${format}</td></tr>`;
for (var j = 0; j < medium.tracks.length; j++) { for (let j = 0; j < medium.tracks.length; j++) {
var track = medium.tracks[j], recording = track.recording, let track = medium.tracks[j],
disambiguation = recording.disambiguation ? " (" + recording.disambiguation + ")" : "", recording = track.recording,
length = track.length ? format_time(track.length) : "?:??" disambiguation = recording.disambiguation ? ` (${recording.disambiguation})` : '',
artist_credit = track["artist-credit"] || track.recording["artist-credit"], length = track.length ? format_time(track.length) : '?:??';
tr = document.createElement("tr"); (artist_credit = track['artist-credit'] || track.recording['artist-credit']), (tr = document.createElement('tr'));
tr.appendChild(createElement("td", j + 1)); tr.appendChild(createElement('td', j + 1));
var title_td = createElement("td", disambiguation); let title_td = createElement('td', disambiguation);
title_td.insertBefore(createLink("/recording/" + recording.id, recording.title), title_td.firstChild); title_td.insertBefore(createLink(`/recording/${recording.id}`, recording.title), title_td.firstChild);
tr.appendChild(title_td); tr.appendChild(title_td);
tr.appendChild(createElement("td", length)); tr.appendChild(createElement('td', length));
var ac_td = document.createElement("td"); let ac_td = document.createElement('td');
ac_td.appendChild(createAC(artist_credit)); ac_td.appendChild(createAC(artist_credit));
tr.appendChild(ac_td); tr.appendChild(ac_td);
@ -258,46 +271,46 @@ function parse_release(json, table) {
} }
} }
var bottom_tr = document.createElement("tr"), let bottom_tr = document.createElement('tr'),
bottom_td = document.createElement("td"); bottom_td = document.createElement('td');
bottom_td.colSpan = 4; bottom_td.colSpan = 4;
bottom_td.style.padding = "1em"; bottom_td.style.padding = '1em';
bottom_td.appendChild(createLink("/release/" + json.id + "/edit", "edit")); bottom_td.appendChild(createLink(`/release/${json.id}/edit`, 'edit'));
bottom_td.appendChild(document.createTextNode(" | ")); bottom_td.appendChild(document.createTextNode(' | '));
bottom_td.appendChild(createLink("/release/" + json.id + "/edit-relationships", "edit relationships")); bottom_td.appendChild(createLink(`/release/${json.id}/edit-relationships`, 'edit relationships'));
bottom_td.appendChild(document.createTextNode(" | ")); bottom_td.appendChild(document.createTextNode(' | '));
bottom_td.appendChild(createLink("/release/" + json.id + "/edits", "editing history")); bottom_td.appendChild(createLink(`/release/${json.id}/edits`, 'editing history'));
bottom_tr.appendChild(bottom_td); bottom_tr.appendChild(bottom_td);
table.appendChild(bottom_tr); table.appendChild(bottom_tr);
} }
function createAC(obj) { function createAC(obj) {
var span = document.createElement("span"); let span = document.createElement('span');
for (var i = 0; i < obj.length; i++) { for (let i = 0; i < obj.length; i++) {
var credit = obj[i], artist = credit.artist, let credit = obj[i],
link = createLink("/artist/" + artist.id, credit.name || artist.name); artist = credit.artist,
link = createLink(`/artist/${artist.id}`, credit.name || artist.name);
link.setAttribute("title", artist["sort-name"]); link.setAttribute('title', artist['sort-name']);
span.appendChild(link); span.appendChild(link);
if (credit.joinphrase) if (credit.joinphrase) span.appendChild(document.createTextNode(credit.joinphrase));
span.appendChild(document.createTextNode(credit.joinphrase));
} }
return span; return span;
} }
function createElement(name, text) { function createElement(name, text) {
var element = document.createElement(name); let element = document.createElement(name);
element.textContent = text; element.textContent = text;
return element; return element;
} }
function createLink(href, text) { function createLink(href, text) {
var element = createElement("a", text); let element = createElement('a', text);
element.href = href; element.href = href;
return element; return element;
} }

View file

@ -62,66 +62,63 @@
//**************************************************************************// //**************************************************************************//
var scr = document.createElement("script"); var scr = document.createElement('script');
scr.textContent = "(" + fastCancelScript + ")();"; scr.textContent = `(${fastCancelScript})();`;
document.body.appendChild(scr); document.body.appendChild(scr);
function fastCancelScript() { function fastCancelScript() {
var totalCancels = 0; let totalCancels = 0;
var $status = $("<div></div>") let $status = $('<div></div>')
.css({ .css({
"position": "fixed", position: 'fixed',
"right": "0", right: '0',
"bottom": "0", bottom: '0',
"background": "#FFBA58", background: '#FFBA58',
"border-top": "1px #000 solid", 'border-top': '1px #000 solid',
"border-left": "1px #000 solid", 'border-left': '1px #000 solid',
"padding": "0.5em" padding: '0.5em'
}) })
.appendTo("body") .appendTo('body')
.hide(); .hide();
function updateStatus() { function updateStatus() {
if (totalCancels === 0) { if (totalCancels === 0) {
$status.hide(); $status.hide();
} else { } else {
$status.text("Canceling " + totalCancels + " edit" + $status.text(`Canceling ${totalCancels} edit${totalCancels > 1 ? 's' : ''}...`).show();
(totalCancels > 1 ? "s" : "") + "...").show();
} }
} }
document.body.addEventListener("click", function (event) { document.body.addEventListener('click', function(event) {
if (event.target && event.target.tagName && event.target.tagName == "A" && event.target.classList.contains("negative")) { if (event.target && event.target.tagName && event.target.tagName == 'A' && event.target.classList.contains('negative')) {
event.stopPropagation(); event.stopPropagation();
event.preventDefault(); event.preventDefault();
totalCancels += 1; totalCancels += 1;
updateStatus(); updateStatus();
var $self = $(event.target), let $self = $(event.target),
$edit = $self.parents("div.edit-list:eq(0)"); $edit = $self.parents('div.edit-list:eq(0)');
pushRequest(function () { pushRequest(function() {
var editNote = $edit.find("div.add-edit-note textarea").val(); let editNote = $edit.find('div.add-edit-note textarea').val();
var data = { "confirm.edit_note": editNote }; let data = { 'confirm.edit_note': editNote };
$.ajax({ $.ajax({
type: "POST", type: 'POST',
url: $self.attr("href"), url: $self.attr('href'),
data: data, data: data,
error: function (request, status, error) { error: function(request, status, error) {
$self $self
.css({ .css({
"background": "red", background: 'red',
"color": "yellow", color: 'yellow',
"cursor": "help" cursor: 'help'
}) })
.attr("title", "Error cancelling this edit: “" + error + "”"); .attr('title', `Error cancelling this edit: “${error}`);
$edit $edit.css({ border: '6px solid red' }).show();
.css({border: "6px solid red"})
.show();
}, },
complete: function () { complete: function() {
$edit.remove(); $edit.remove();
totalCancels -= 1; totalCancels -= 1;
updateStatus(); updateStatus();
@ -132,15 +129,15 @@ function fastCancelScript() {
} }
}); });
$("div#edits > form[action$='/edit/enter_votes']").on("submit", function(event) { $("div#edits > form[action$='/edit/enter_votes']").on('submit', function(event) {
if (totalCancels > 0) { if (totalCancels > 0) {
event.preventDefault(); event.preventDefault();
alert("Please wait, " + (totalCancels > 1 ? totalCancels + " edits are" : "an edit is") + " being cancelled in the background."); alert(`Please wait, ${totalCancels > 1 ? `${totalCancels} edits are` : 'an edit is'} being cancelled in the background.`);
} }
}); });
var pushRequest = (function () { var pushRequest = (function() {
var queue = [], let queue = [],
last = 0, last = 0,
active = false, active = false,
rate = 2000; rate = 2000;
@ -155,19 +152,19 @@ function fastCancelScript() {
} }
} }
return function (req) { return function(req) {
queue.push(req); queue.push(req);
if (!active) { if (!active) {
active = true; active = true;
var now = new Date().getTime(); let now = new Date().getTime();
if (now - last >= rate) { if (now - last >= rate) {
next(); next();
} else { } else {
var timeout = rate - now + last; let timeout = rate - now + last;
setTimeout(next, timeout); setTimeout(next, timeout);
} }
} }
}; };
}()); })();
} }

View file

@ -25,13 +25,11 @@
* Radio program: http://freemusicarchive.org/music/Kyle_Eyre_Clyd/Live_on_WFMUs_Strength_Through_Failure_with_Fabio_Roberti_8132015/ * Radio program: http://freemusicarchive.org/music/Kyle_Eyre_Clyd/Live_on_WFMUs_Strength_Through_Failure_with_Fabio_Roberti_8132015/
*/ */
// prevent JQuery conflicts, see http://wiki.greasespot.net/@grant // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant
this.$ = this.jQuery = jQuery.noConflict(true); this.$ = this.jQuery = jQuery.noConflict(true);
// API Key assigned to registered user on FMA // API Key assigned to registered user on FMA
var FMA_API = "FMA API KEY Missing"; var FMA_API = 'FMA API KEY Missing';
if (!unsafeWindow) unsafeWindow = window; if (!unsafeWindow) unsafeWindow = window;
@ -45,7 +43,6 @@ if (DEBUG) {
var tracks_deferred = $.Deferred(); var tracks_deferred = $.Deferred();
var retrieve_tracks_promise = tracks_deferred.promise(); var retrieve_tracks_promise = tracks_deferred.promise();
// object to store all global attributes collected for the release // object to store all global attributes collected for the release
var release_attributes = {}; // albumid, total_pages, artist_name, label var release_attributes = {}; // albumid, total_pages, artist_name, label
@ -54,28 +51,27 @@ var album_api_array = []; // album information [0]
var tracks_api_array = []; // track information [0,1,2,..] one element for each pagination in FMA tracks API var tracks_api_array = []; // track information [0,1,2,..] one element for each pagination in FMA tracks API
$(document).ready(function() { $(document).ready(function() {
// if we have something on local storage place that // if we have something on local storage place that
if (localStorage.getItem('FMA_API_KEY')) { if (localStorage.getItem('FMA_API_KEY')) {
FMA_API = localStorage.getItem('FMA_API_KEY'); // -> YOURAPIKEY FMA_API = localStorage.getItem('FMA_API_KEY'); // -> YOURAPIKEY
} else { } else {
insertAPIKEYSection(); insertAPIKEYSection();
$("#api_key_submit").click(function() { $('#api_key_submit').click(function() {
var myval = $("#apikey_input").val(); let myval = $('#apikey_input').val();
localStorage.setItem('FMA_API_KEY', myval); localStorage.setItem('FMA_API_KEY', myval);
$("#musicbrainz_apikey").hide(); $('#musicbrainz_apikey').hide();
FMA_API = localStorage.getItem('FMA_API_KEY'); // -> YOURAPIKEY FMA_API = localStorage.getItem('FMA_API_KEY'); // -> YOURAPIKEY
LOGGER.debug("FMA API Key set: " + FMA_API); LOGGER.debug(`FMA API Key set: ${FMA_API}`);
location.reload(true); //as document loaded and FMA_API was set out of scope location.reload(true); //as document loaded and FMA_API was set out of scope
}); });
} }
// window.localStorage.clear() hint: to clear the localStorage if needed // window.localStorage.clear() hint: to clear the localStorage if needed
LOGGER.info("Document Ready & FMA Userscript Executing"); LOGGER.info('Document Ready & FMA Userscript Executing');
var fmaPage = parseFMApage(); let fmaPage = parseFMApage();
var mblinks = new MBLinks('FMA_CACHE', 7 * 24 * 60); let mblinks = new MBLinks('FMA_CACHE', 7 * 24 * 60);
if (DEBUG) { if (DEBUG) {
insertAPISection(); insertAPISection();
@ -83,33 +79,32 @@ $(document).ready(function() {
updateAPISection.ApiKey(FMA_API); updateAPISection.ApiKey(FMA_API);
} }
if ($('.minitag-album').length && FMA_API !== 'FMA API KEY Missing') {
if ($(".minitag-album").length && FMA_API !== "FMA API KEY Missing") { // To make sure API and release only build on Album page. // To make sure API and release only build on Album page.
// Track parameters: total number of pages / api calls limit hardcoded to max of 20 // Track parameters: total number of pages / api calls limit hardcoded to max of 20
var retrieve_track_info = new track_api_parameters(); let retrieve_track_info = new track_api_parameters();
// Album detail // Album detail
var retrieve_album_detail = new album_api(); let retrieve_album_detail = new album_api();
// Track detail // Track detail
$.when(retrieve_track_info) // ensure the track info is retrieved first (total_pages counter) $.when(retrieve_track_info) // ensure the track info is retrieved first (total_pages counter)
.then(function() { // loop and deferred promise for multiple ajax calls .then(function() {
// loop and deferred promise for multiple ajax calls
updateAPISection.TrackAjaxStatus('busy'); updateAPISection.TrackAjaxStatus('busy');
var track_api_calls = []; let track_api_calls = [];
for (var i = 1; i <= release_attributes.total_pages; i++) { for (let i = 1; i <= release_attributes.total_pages; i++) {
track_api_calls.push(track_api(i)); track_api_calls.push(track_api(i));
} }
$.when.apply(this, track_api_calls).done(function() { $.when.apply(this, track_api_calls).done(function() {
LOGGER.debug("Tracks loaded and done in DONE lets use it"); LOGGER.debug('Tracks loaded and done in DONE lets use it');
//console.log("total_pages " + release_attributes.total_pages); //console.log("total_pages " + release_attributes.total_pages);
tracks_deferred.resolve(); tracks_deferred.resolve();
}); });
}) })
.done(function() { .done(function() {
LOGGER.debug("Deferred for: Track info > track detail > resolved"); LOGGER.debug('Deferred for: Track info > track detail > resolved');
}); });
$.when(retrieve_tracks_promise) $.when(retrieve_tracks_promise)
@ -121,19 +116,21 @@ $(document).ready(function() {
}); });
$.when(retrieve_track_info, retrieve_tracks_promise, retrieve_album_detail).done(function() { $.when(retrieve_track_info, retrieve_tracks_promise, retrieve_album_detail).done(function() {
LOGGER.info("All the AJAX API calls are done continue to build the release object ..."); LOGGER.info('All the AJAX API calls are done continue to build the release object ...');
// LOGGER.debug("ALBUM Object > " + album_api_array[0]); // LOGGER.debug("ALBUM Object > " + album_api_array[0]);
// LOGGER.debug("TRACK Object > " + tracks_api_array); // LOGGER.debug("TRACK Object > " + tracks_api_array);
var FreeMusicArchiveRelease = new Parsefmarelease(album_api_array[0], tracks_api_array); let FreeMusicArchiveRelease = new Parsefmarelease(album_api_array[0], tracks_api_array);
insertMBSection(FreeMusicArchiveRelease); insertMBSection(FreeMusicArchiveRelease);
var album_link = window.location.href; let album_link = window.location.href;
var url = $(location).attr('href').split('/'); let url = $(location)
var artist_url = url[url.length - 3]; .attr('href')
var base_url = 'http://freemusicarchive.org/music/'; .split('/');
var artist_link = base_url + artist_url + '/'; let artist_url = url[url.length - 3];
let base_url = 'http://freemusicarchive.org/music/';
let artist_link = `${base_url + artist_url}/`;
mblinks.searchAndDisplayMbLink(album_link, 'release', function(link) { mblinks.searchAndDisplayMbLink(album_link, 'release', function(link) {
$('.subh1').before(link); $('.subh1').before(link);
@ -141,24 +138,18 @@ $(document).ready(function() {
mblinks.searchAndDisplayMbLink(artist_link, 'artist', function(link) { mblinks.searchAndDisplayMbLink(artist_link, 'artist', function(link) {
$('.subh1').after(link); $('.subh1').after(link);
}); });
}); });
} }
}); });
// Determine the location on page to add MusicBrainz Section // Determine the location on page to add MusicBrainz Section
function insertMbUI(mbUI) { function insertMbUI(mbUI) {
var e; let e;
if ((e = $("#header")) && e.length) { if ((e = $('#header')) && e.length) {
e.after(mbUI); e.after(mbUI);
} else if ((e = $('#content')) && e.length) { } else if ((e = $('#content')) && e.length) {
e.before(mbUI); e.before(mbUI);
} else if ((e = $(".brumbs")) && e.length) { } else if ((e = $('.brumbs')) && e.length) {
e.append(mbUI); e.append(mbUI);
} }
} }
@ -166,24 +157,26 @@ function insertMbUI(mbUI) {
// Insert link to high resolution image on FMA page // Insert link to high resolution image on FMA page
function insertIMGlinks() { function insertIMGlinks() {
//LOGGER.debug("FMA insertIMGlinks Function Executing"); //LOGGER.debug("FMA insertIMGlinks Function Executing");
var imgsrc = $('#image-1 img.sbar-fullimg').attr('src'); let imgsrc = $('#image-1 img.sbar-fullimg').attr('src');
imgsrc = imgsrc.substring(0, imgsrc.indexOf('?')); imgsrc = imgsrc.substring(0, imgsrc.indexOf('?'));
//LOGGER.debug(" insertIMGlinks > imgsrc:", imgsrc); //LOGGER.debug(" insertIMGlinks > imgsrc:", imgsrc);
$('#album-images').append('<p><img src="http://musicbrainz.org/favicon.ico" /><a href="' + imgsrc + '">MB High Res Image</a></p>'); $('#album-images').append(`<p><img src="http://musicbrainz.org/favicon.ico" /><a href="${imgsrc}">MB High Res Image</a></p>`);
} }
// Insert FreeMusicArchive API Status section on FMA page // Insert FreeMusicArchive API Status section on FMA page
function insertAPISection() { function insertAPISection() {
//LOGGER.debug("FMA insertAPISection Function Executing"); //LOGGER.debug("FMA insertAPISection Function Executing");
var fmaUI = $('<div id="fmaapistatus" class="sbar-stat"><h4 class="wlinepad"><span class="hd">FMA API</span></h4></div>').hide(); let fmaUI = $('<div id="fmaapistatus" class="sbar-stat"><h4 class="wlinepad"><span class="hd">FMA API</span></h4></div>').hide();
if (DEBUG) fmaUI.css({ if (DEBUG)
'border': '1px dotted red' fmaUI.css({
border: '1px dotted red'
}); });
let fmaStatusBlock = $(
var fmaStatusBlock = $('<a class="lbut-lt" id="lbut-lt-fma-api-album-id">»</a> <a class="lbut-lt" id="lbut-lt-fma-api-key-id">»</a> <a id="lbut-lt-fma-api-album" class="lbut-lt">Album info retrieved</a><a class="lbut-lt" id="lbut-lt-fma-api-tracks">Track info retrieved</a>'); '<a class="lbut-lt" id="lbut-lt-fma-api-album-id">»</a> <a class="lbut-lt" id="lbut-lt-fma-api-key-id">»</a> <a id="lbut-lt-fma-api-album" class="lbut-lt">Album info retrieved</a><a class="lbut-lt" id="lbut-lt-fma-api-tracks">Track info retrieved</a>'
);
fmaUI.append(fmaStatusBlock); fmaUI.append(fmaStatusBlock);
insertMbUI(fmaUI); // Insert the FMA API Status UI insertMbUI(fmaUI); // Insert the FMA API Status UI
@ -195,7 +188,6 @@ function insertAPISection() {
width: '49%' width: '49%'
}); });
fmaUI.slideDown(); fmaUI.slideDown();
} }
@ -212,27 +204,26 @@ var updateAPISection = {
return 'complete'; return 'complete';
}, },
AlbumAjaxStatus: function(ajaxstatus) { AlbumAjaxStatus: function(ajaxstatus) {
if (ajaxstatus === null) { if (ajaxstatus === null) {
this.ajaxstatus = "notcalled"; this.ajaxstatus = 'notcalled';
} else { } else {
this.ajaxstatus = ajaxstatus; this.ajaxstatus = ajaxstatus;
} }
switch (this.ajaxstatus) { switch (this.ajaxstatus) {
case "completed": // Definition is that api call was successfull hence busy retrieving data case 'completed': // Definition is that api call was successfull hence busy retrieving data
//test chaging status of album api to error retrieving data after 2 seconds //test chaging status of album api to error retrieving data after 2 seconds
$('#lbut-lt-fma-api-album').css({ $('#lbut-lt-fma-api-album').css({
'background-color': 'green' 'background-color': 'green'
}); });
break; break;
case "busy": // Definition is that api call was successfull hence busy retrieving data case 'busy': // Definition is that api call was successfull hence busy retrieving data
//test chaging status of album api to error retrieving data after 2 seconds //test chaging status of album api to error retrieving data after 2 seconds
$('#lbut-lt-fma-api-album').css({ $('#lbut-lt-fma-api-album').css({
'background-color': 'orange' 'background-color': 'orange'
}); });
break; break;
case "fail": // Definition is that api call was successfull hence busy retrieving data case 'fail': // Definition is that api call was successfull hence busy retrieving data
//test chaging status of album api to error retrieving data after 2 seconds //test chaging status of album api to error retrieving data after 2 seconds
$('#lbut-lt-fma-api-album').css({ $('#lbut-lt-fma-api-album').css({
'background-color': 'red' 'background-color': 'red'
@ -241,27 +232,26 @@ var updateAPISection = {
} }
}, },
TrackAjaxStatus: function(ajaxstatus) { TrackAjaxStatus: function(ajaxstatus) {
if (ajaxstatus === null) { if (ajaxstatus === null) {
this.ajaxstatus = "notcalled"; this.ajaxstatus = 'notcalled';
} else { } else {
this.ajaxstatus = ajaxstatus; this.ajaxstatus = ajaxstatus;
} }
switch (this.ajaxstatus) { switch (this.ajaxstatus) {
case "completed": // Definition is that api call was successfull hence busy retrieving data case 'completed': // Definition is that api call was successfull hence busy retrieving data
//test chaging status of album api to error retrieving data after 2 seconds //test chaging status of album api to error retrieving data after 2 seconds
$('#lbut-lt-fma-api-tracks').css({ $('#lbut-lt-fma-api-tracks').css({
'background-color': 'green' 'background-color': 'green'
}); });
break; break;
case "busy": // Definition is that api call was successfull hence busy retrieving data case 'busy': // Definition is that api call was successfull hence busy retrieving data
//test chaging status of album api to error retrieving data after 2 seconds //test chaging status of album api to error retrieving data after 2 seconds
$('#lbut-lt-fma-api-tracks').css({ $('#lbut-lt-fma-api-tracks').css({
'background-color': 'orange' 'background-color': 'orange'
}); });
break; break;
case "fail": // Definition is that api call was successfull hence busy retrieving data case 'fail': // Definition is that api call was successfull hence busy retrieving data
//test chaging status of album api to error retrieving data after 2 seconds //test chaging status of album api to error retrieving data after 2 seconds
$('#lbut-lt-fma-api-tracks').css({ $('#lbut-lt-fma-api-tracks').css({
'background-color': 'red' 'background-color': 'red'
@ -273,20 +263,22 @@ var updateAPISection = {
// Insert MusicBrainz section on FMA page // Insert MusicBrainz section on FMA page
function insertMBSection(release) { function insertMBSection(release) {
//LOGGER.debug(release); //LOGGER.debug(release);
var mbUI = $('<div id="musicbrainz" class="section musicbrainz"><h4 class="wlinepad"><span class="hd">MusicBrainz</span></h4></div>').hide(); let mbUI = $(
if (DEBUG) mbUI.css({ '<div id="musicbrainz" class="section musicbrainz"><h4 class="wlinepad"><span class="hd">MusicBrainz</span></h4></div>'
'border': '1px dotted red' ).hide();
if (DEBUG)
mbUI.css({
border: '1px dotted red'
}); });
var mbContentBlock = $('<div class="section_content"></div>'); let mbContentBlock = $('<div class="section_content"></div>');
mbUI.append(mbContentBlock); mbUI.append(mbContentBlock);
if (release.maybe_buggy) { if (release.maybe_buggy) {
var warning_buggy = $('<p><small><b>Warning</b>: this release is buggy, please check twice the data you import.</small><p').css({ let warning_buggy = $('<p><small><b>Warning</b>: this release is buggy, please check twice the data you import.</small><p').css({
'color': 'red', color: 'red',
float: 'left', float: 'left',
'margin-top': '4px', 'margin-top': '4px',
'margin-bottom': '4px' 'margin-bottom': '4px'
@ -295,18 +287,17 @@ function insertMBSection(release) {
} }
// Form parameters // Form parameters
var edit_note = "FMA_Album_Id: " + release_attributes.albumid + " "; // temp add album id here untill we can add easy way to schema let edit_note = `FMA_Album_Id: ${release_attributes.albumid} `; // temp add album id here untill we can add easy way to schema
edit_note = edit_note + MBImport.makeEditNote(window.location.href, 'FreeMusicArchive'); edit_note = edit_note + MBImport.makeEditNote(window.location.href, 'FreeMusicArchive');
var parameters = MBImport.buildFormParameters(release, edit_note); let parameters = MBImport.buildFormParameters(release, edit_note);
// Build form + search button // Build form + search button
var innerHTML = '<div id="mb_buttons">' + MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release) + '</div>'; let innerHTML = `<div id="mb_buttons">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`;
mbContentBlock.append(innerHTML); mbContentBlock.append(innerHTML);
insertMbUI(mbUI); // Insert the MusicBrainzUI insertMbUI(mbUI); // Insert the MusicBrainzUI
insertIMGlinks(); // Insert the link to high res image insertIMGlinks(); // Insert the link to high res image
$('#musicbrainz').css({ $('#musicbrainz').css({
display: 'block', display: 'block',
float: 'right', float: 'right',
@ -316,7 +307,7 @@ function insertMBSection(release) {
$('#mb_buttons').css({ $('#mb_buttons').css({
display: 'inline-block', display: 'inline-block',
'float': 'right', float: 'right',
height: '80px' height: '80px'
}); });
$('form.musicbrainz_import').css({ $('form.musicbrainz_import').css({
@ -324,7 +315,7 @@ function insertMBSection(release) {
display: 'inline-block' display: 'inline-block'
}); });
$('form.musicbrainz_import_search').css({ $('form.musicbrainz_import_search').css({
'float': 'right' float: 'right'
}); });
$('form.musicbrainz_import > button').css({ $('form.musicbrainz_import > button').css({
width: '63px', width: '63px',
@ -335,30 +326,29 @@ function insertMBSection(release) {
mbUI.slideDown(); mbUI.slideDown();
} }
// Insert MusicBrainz API section on FMA page to enter API Key // Insert MusicBrainz API section on FMA page to enter API Key
function insertAPIKEYSection() { function insertAPIKEYSection() {
LOGGER.debug("FMA insertAPIKEYSection Function Executing"); LOGGER.debug('FMA insertAPIKEYSection Function Executing');
let mbUI = $(
var mbUI = $('<div id="musicbrainz_apikey" class="section musicbrainz"><h4 class="wlinepad"><span class="hd">Import FMA API KEY for MusicBrainz</span></h4></div>').hide(); '<div id="musicbrainz_apikey" class="section musicbrainz"><h4 class="wlinepad"><span class="hd">Import FMA API KEY for MusicBrainz</span></h4></div>'
if (DEBUG) mbUI.css({ ).hide();
'border': '1px dotted red' if (DEBUG)
mbUI.css({
border: '1px dotted red'
}); });
var mbContentBlock = $('<div class="section_content"></div>'); let mbContentBlock = $('<div class="section_content"></div>');
mbUI.append(mbContentBlock); mbUI.append(mbContentBlock);
// Build section // Build section
var innerHTML = '<span class="mhd-nosep">Please enter API Key found <a class="donate" href="https://freemusicarchive.org/member/api_key" target="_blank">here</a></span>'; let innerHTML =
innerHTML = innerHTML + '<div id="mb_buttons"><input id="apikey_input" type="text" name="apikey_input" value=""><br><input id="api_key_submit" type="submit" value="Import API KEY"></div>'; '<span class="mhd-nosep">Please enter API Key found <a class="donate" href="https://freemusicarchive.org/member/api_key" target="_blank">here</a></span>';
innerHTML = `${innerHTML}<div id="mb_buttons"><input id="apikey_input" type="text" name="apikey_input" value=""><br><input id="api_key_submit" type="submit" value="Import API KEY"></div>`;
mbContentBlock.append(innerHTML); mbContentBlock.append(innerHTML);
insertMbUI(mbUI); // Insert the MusicBrainzUI insertMbUI(mbUI); // Insert the MusicBrainzUI
$('#musicbrainz_apikey').css({ $('#musicbrainz_apikey').css({
display: 'block', display: 'block',
float: 'right', float: 'right',
@ -368,33 +358,30 @@ function insertAPIKEYSection() {
$('#mb_buttons').css({ $('#mb_buttons').css({
display: 'inline-block', display: 'inline-block',
'float': 'right', float: 'right',
height: '80px' height: '80px'
}); });
mbUI.slideDown(); mbUI.slideDown();
} }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Retrieve data from FMA API // // Retrieve data from FMA API //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Retrieve Album JSON from API and push into array // Retrieve Album JSON from API and push into array
function album_api() { function album_api() {
let fmaWsUrl = `https://freemusicarchive.org/api/get/albums.json?api_key=${FMA_API}&album_id=${release_attributes.albumid}`;
var fmaWsUrl = 'https://freemusicarchive.org/api/get/albums.json?api_key=' + FMA_API + '&album_id=' + release_attributes.albumid;
var promise_variable = $.getJSON(fmaWsUrl, function() { var promise_variable = $.getJSON(fmaWsUrl, function() {
updateAPISection.AlbumAjaxStatus('busy'); updateAPISection.AlbumAjaxStatus('busy');
LOGGER.debug("promise_variable [state] in [getJSON] " + promise_variable.state()); LOGGER.debug(`promise_variable [state] in [getJSON] ${promise_variable.state()}`);
}).done(function(albumjson) { }).done(function(albumjson) {
LOGGER.debug(" >> Album > DONE"); LOGGER.debug(' >> Album > DONE');
updateAPISection.AlbumAjaxStatus('completed'); updateAPISection.AlbumAjaxStatus('completed');
//LOGGER.debug(albumjson); //LOGGER.debug(albumjson);
release_attributes.artist_name = albumjson.dataset[0].artist_name; release_attributes.artist_name = albumjson.dataset[0].artist_name;
album_api_array.push(albumjson.dataset[0]); album_api_array.push(albumjson.dataset[0]);
}); });
return promise_variable.promise(); return promise_variable.promise();
@ -402,13 +389,12 @@ function album_api() {
// Retrieve Album JSON from API and assign values to release object // Retrieve Album JSON from API and assign values to release object
function track_api_parameters() { function track_api_parameters() {
let fmaWsUrl = `https://freemusicarchive.org/api/get/tracks.json?api_key=${FMA_API}&album_id=${release_attributes.albumid}&limit=20`;
var fmaWsUrl = 'https://freemusicarchive.org/api/get/tracks.json?api_key=' + FMA_API + '&album_id=' + release_attributes.albumid + '&limit=20';
var promise_track_api_params = $.getJSON(fmaWsUrl, function() { var promise_track_api_params = $.getJSON(fmaWsUrl, function() {
LOGGER.debug("promise_track_api_params [state] in [getJSON] " + promise_track_api_params.state()); LOGGER.debug(`promise_track_api_params [state] in [getJSON] ${promise_track_api_params.state()}`);
}).done(function(trackinfojson) { }).done(function(trackinfojson) {
LOGGER.debug(" >> Track INFO > DONE"); LOGGER.debug(' >> Track INFO > DONE');
release_attributes.total_pages = trackinfojson.total_pages; release_attributes.total_pages = trackinfojson.total_pages;
//LOGGER.debug(trackinfojson); //LOGGER.debug(trackinfojson);
}); });
@ -418,15 +404,14 @@ function track_api_parameters() {
// Retrieve Track JSON from API and push into array, can handle page itteration // Retrieve Track JSON from API and push into array, can handle page itteration
function track_api(page) { function track_api(page) {
let fmaWsUrl = `https://freemusicarchive.org/api/get/tracks.json?api_key=${FMA_API}&album_id=${
var fmaWsUrl = 'https://freemusicarchive.org/api/get/tracks.json?api_key=' + FMA_API + '&album_id=' + release_attributes.albumid + '&limit=20&page=' + parseInt(page); release_attributes.albumid
}&limit=20&page=${parseInt(page)}`;
var promise_track_api = $.getJSON(fmaWsUrl, function() { var promise_track_api = $.getJSON(fmaWsUrl, function() {
LOGGER.debug("promise_track_api_params [state] in [getJSON] " + promise_track_api.state()); LOGGER.debug(`promise_track_api_params [state] in [getJSON] ${promise_track_api.state()}`);
}).done(function(tracksjson) { }).done(function(tracksjson) {
LOGGER.debug(" >> Track page " + page + " > DONE "); LOGGER.debug(` >> Track page ${page} > DONE `);
LOGGER.debug(tracksjson); LOGGER.debug(tracksjson);
tracks_api_array.push(tracksjson.dataset); tracks_api_array.push(tracksjson.dataset);
}); });
@ -434,52 +419,55 @@ function track_api(page) {
return promise_track_api.promise(); return promise_track_api.promise();
} }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Parse information from FMA Page // // Parse information from FMA Page //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function parseFMApage() { function parseFMApage() {
// Check to see if it is an album class is minitag-album div#content div.bcrumb h1 span.minitag-album // Check to see if it is an album class is minitag-album div#content div.bcrumb h1 span.minitag-album
var FMAtype = ""; let FMAtype = '';
// class inp-embed-code contain the album id // class inp-embed-code contain the album id
if ($(".minitag-album").length) { if ($('.minitag-album').length) {
FMAtype = "album"; FMAtype = 'album';
} else if ($(".minitag-song").length) { } else if ($('.minitag-song').length) {
FMAtype = "track"; FMAtype = 'track';
} else if ($(".minitag-artist").length) { } else if ($('.minitag-artist').length) {
FMAtype = "artist"; FMAtype = 'artist';
} }
if (FMAtype == 'album') {
if (FMAtype == "album") {
//LOGGER.debug("FMA parseFMApage Function Executing on ", FMAtype); //LOGGER.debug("FMA parseFMApage Function Executing on ", FMAtype);
var FMAEmbedCode = $(".inp-embed-code input").attr("value"); let FMAEmbedCode = $('.inp-embed-code input').attr('value');
FMAEmbedCodeRegex = /(\/embed\/album\/)(.+?(?=.xml))/; // regex to find the album id from the input object FMAEmbedCodeRegex = /(\/embed\/album\/)(.+?(?=.xml))/; // regex to find the album id from the input object
var FMAAlbumIdMatch = FMAEmbedCode.match(FMAEmbedCodeRegex); // match the Id let FMAAlbumIdMatch = FMAEmbedCode.match(FMAEmbedCodeRegex); // match the Id
release_attributes.albumid = FMAAlbumIdMatch[2].trim(); // assign the ID to a variable release_attributes.albumid = FMAAlbumIdMatch[2].trim(); // assign the ID to a variable
LOGGER.info("FreeMusicArchive Album identified as: ", release_attributes.albumid); LOGGER.info('FreeMusicArchive Album identified as: ', release_attributes.albumid);
} else { } else {
LOGGER.error("No unique album identified on page", window.location.href); LOGGER.error('No unique album identified on page', window.location.href);
release_attributes.albumid = ""; release_attributes.albumid = '';
} }
// Label parsed from webpage as it is not in API // Label parsed from webpage as it is not in API
$("div.sbar-stat span.lf105.stathd").each(function() { $('div.sbar-stat span.lf105.stathd').each(function() {
//var tester = $(this).eq(0).text().trim().toLowerCase(); // working //var tester = $(this).eq(0).text().trim().toLowerCase(); // working
var taglist = $(this).eq(0).text().trim().toLowerCase(); let taglist = $(this)
if (taglist == "label:") { .eq(0)
release_attributes.label = $(this).next().text(); .text()
.trim()
.toLowerCase();
if (taglist == 'label:') {
release_attributes.label = $(this)
.next()
.text();
// fmarelease.labels.push({ // fmarelease.labels.push({
// name: FMAAlbumLabel // name: FMAAlbumLabel
// }); // });
} else { } else {
release_attributes.label = ""; release_attributes.label = '';
} }
}); });
} }
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Analyze FMA data and return a release object // // Analyze FMA data and return a release object //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
@ -487,7 +475,7 @@ function parseFMApage() {
// Parse the date string and set object properties day, month, year // Parse the date string and set object properties day, month, year
function parse_MM_DD_YYYY(date, obj) { function parse_MM_DD_YYYY(date, obj) {
if (!date) return; if (!date) return;
var m = date.split(/\D+/, 3).map(function(e) { let m = date.split(/\D+/, 3).map(function(e) {
return parseInt(e, 10); return parseInt(e, 10);
}); });
if (m[0] !== undefined) { if (m[0] !== undefined) {
@ -515,22 +503,22 @@ function Parsefmarelease(albumobject, trackobject) {
trackobject = trackobject; trackobject = trackobject;
} }
var fmarelease = {}; let fmarelease = {};
// Create an empty object required for MBImport // Create an empty object required for MBImport
fmarelease.title = ""; fmarelease.title = '';
fmarelease.artist_credit = []; fmarelease.artist_credit = [];
fmarelease.type = ""; fmarelease.type = '';
fmarelease.status = ""; fmarelease.status = '';
fmarelease.language = ""; fmarelease.language = '';
fmarelease.script = ""; fmarelease.script = '';
fmarelease.packaging = ""; fmarelease.packaging = '';
fmarelease.country = ""; fmarelease.country = '';
fmarelease.year = ""; fmarelease.year = '';
fmarelease.month = ""; fmarelease.month = '';
fmarelease.day = ""; fmarelease.day = '';
fmarelease.labels = []; fmarelease.labels = [];
fmarelease.barcode = ""; fmarelease.barcode = '';
fmarelease.urls = []; fmarelease.urls = [];
fmarelease.discs = []; fmarelease.discs = [];
@ -539,11 +527,11 @@ function Parsefmarelease(albumobject, trackobject) {
// Title // Title
fmarelease.title = albumobject.album_title; fmarelease.title = albumobject.album_title;
LOGGER.debug("Title: ", fmarelease.title); LOGGER.debug('Title: ', fmarelease.title);
// Artist Credit // Artist Credit
var VariousArtistsRegex = /(Various Artists)/; //found "Various Artists || Various Artists [album name]" let VariousArtistsRegex = /(Various Artists)/; //found "Various Artists || Various Artists [album name]"
var various_artists = VariousArtistsRegex.test(albumobject.artist_name); let various_artists = VariousArtistsRegex.test(albumobject.artist_name);
if (various_artists) { if (various_artists) {
fmarelease.artist_credit = [MBImport.specialArtist('various_artists')]; fmarelease.artist_credit = [MBImport.specialArtist('various_artists')];
@ -553,8 +541,8 @@ function Parsefmarelease(albumobject, trackobject) {
// Type // Type
// TODO: match all FMA types to MB types // TODO: match all FMA types to MB types
if (albumobject.album_type == "Radio Program") { if (albumobject.album_type == 'Radio Program') {
fmarelease.type = "broadcast"; fmarelease.type = 'broadcast';
} else { } else {
fmarelease.type = albumobject.album_type.toLowerCase(); fmarelease.type = albumobject.album_type.toLowerCase();
} }
@ -566,27 +554,27 @@ function Parsefmarelease(albumobject, trackobject) {
fmarelease.script = 'Latn'; fmarelease.script = 'Latn';
// Check to see if a download button is available // Check to see if a download button is available
if ($(".sqbtn-downloadalbum").length) { if ($('.sqbtn-downloadalbum').length) {
fmarelease.packaging = 'none'; // Default packaging for download is none fmarelease.packaging = 'none'; // Default packaging for download is none
// Release URL // Release URL
fmarelease.urls.push({ fmarelease.urls.push({
'url': albumobject.album_url, url: albumobject.album_url,
'link_type': MBImport.URL_TYPES.download_for_free link_type: MBImport.URL_TYPES.download_for_free
}); });
} else { } else {
// Release URL // Release URL
fmarelease.urls.push({ fmarelease.urls.push({
'url': albumobject.album_url, url: albumobject.album_url,
'link_type': MBImport.URL_TYPES.other_databases link_type: MBImport.URL_TYPES.other_databases
}); });
} }
// Check to see if a play button is available // Check to see if a play button is available
if ($(".sqbtn-playpage").length) { if ($('.sqbtn-playpage').length) {
// Release URL // Release URL
fmarelease.urls.push({ fmarelease.urls.push({
'url': albumobject.album_url, url: albumobject.album_url,
'link_type': MBImport.URL_TYPES.stream_for_free link_type: MBImport.URL_TYPES.stream_for_free
}); });
} }
@ -600,24 +588,19 @@ function Parsefmarelease(albumobject, trackobject) {
name: release_attributes.label name: release_attributes.label
}); });
let discarray = [];
let trackarray = [];
var discarray = [];
var trackarray = [];
// release_attributes.total_pages // release_attributes.total_pages
for (var track_page_in_array = 0; track_page_in_array < trackobject.length; track_page_in_array++) { for (let track_page_in_array = 0; track_page_in_array < trackobject.length; track_page_in_array++) {
//LOGGER.debug(" ** Looping through array set for page " + track_page_in_array); //LOGGER.debug(" ** Looping through array set for page " + track_page_in_array);
let track_count_in_array_page = trackobject[track_page_in_array].length;
var track_count_in_array_page = trackobject[track_page_in_array].length;
//LOGGER.debug(" ** Track count in: trackobject[" + track_page_in_array + "] = " + track_count_in_array_page); //LOGGER.debug(" ** Track count in: trackobject[" + track_page_in_array + "] = " + track_count_in_array_page);
for (var tracknumber = 0; tracknumber < track_count_in_array_page; tracknumber++) { for (let tracknumber = 0; tracknumber < track_count_in_array_page; tracknumber++) {
//LOGGER.debug(" **** Track number in: trackobject[" + track_page_in_array + "][" + tracknumber + "] = " + tracknumber); //LOGGER.debug(" **** Track number in: trackobject[" + track_page_in_array + "][" + tracknumber + "] = " + tracknumber);
var track = {}; let track = {};
track.disc_number = trackobject[track_page_in_array][tracknumber].track_disc_number; track.disc_number = trackobject[track_page_in_array][tracknumber].track_disc_number;
track.number = trackobject[track_page_in_array][tracknumber].track_number; track.number = trackobject[track_page_in_array][tracknumber].track_number;
track.title = trackobject[track_page_in_array][tracknumber].track_title; track.title = trackobject[track_page_in_array][tracknumber].track_title;
@ -628,18 +611,18 @@ function Parsefmarelease(albumobject, trackobject) {
} }
} }
// Could not find a example where disc_number != 1 yet but started teh check so long // Could not find a example where disc_number != 1 yet but started teh check so long
var largest_disc = Math.max.apply(Math, trackarray.map(function(o) { let largest_disc = Math.max.apply(
Math,
trackarray.map(function(o) {
return o.disc_number; return o.disc_number;
})); })
);
//LOGGER.debug("Highest number disc:" + largest_disc); //LOGGER.debug("Highest number disc:" + largest_disc);
for (var disccount = 1; disccount <= largest_disc; disccount++) { for (var disccount = 1; disccount <= largest_disc; disccount++) {
// use this to map all the objects from trackarray with disc_number value of disccount to a new object // use this to map all the objects from trackarray with disc_number value of disccount to a new object
var tracklist_per_disc = $.map(trackarray, function(obj, index) { let tracklist_per_disc = $.map(trackarray, function(obj, index) {
if (obj.disc_number == disccount) { if (obj.disc_number == disccount) {
return obj; return obj;
} }
@ -650,7 +633,6 @@ function Parsefmarelease(albumobject, trackobject) {
return parseInt(a.number) - parseInt(b.number); return parseInt(a.number) - parseInt(b.number);
}); });
// remove the disc_number from the tracklist - not working // remove the disc_number from the tracklist - not working
// tracklist_per_disc = tracklist_per_disc.filter(function( obj ) { // tracklist_per_disc = tracklist_per_disc.filter(function( obj ) {
// return obj.field !== 'disc_number'; // return obj.field !== 'disc_number';
@ -661,18 +643,16 @@ function Parsefmarelease(albumobject, trackobject) {
delete tracklist_per_disc[i].disc_number; delete tracklist_per_disc[i].disc_number;
} }
//LOGGER.debug("Disc # " + disccount + " > " + JSON.stringify(tracklist_per_disc)); //LOGGER.debug("Disc # " + disccount + " > " + JSON.stringify(tracklist_per_disc));
var disc = { let disc = {
'position': disccount, position: disccount,
'format': 'Digital Media', format: 'Digital Media',
'tracks': tracklist_per_disc tracks: tracklist_per_disc
}; };
fmarelease.discs.push(disc); fmarelease.discs.push(disc);
} }
LOGGER.info("Release:", fmarelease); LOGGER.info('Release:', fmarelease);
return fmarelease; return fmarelease;
} }

View file

@ -19,46 +19,47 @@ this.$ = this.jQuery = jQuery.noConflict(true);
if (!unsafeWindow) unsafeWindow = window; if (!unsafeWindow) unsafeWindow = window;
$(document).ready(function(){ $(document).ready(function() {
MBImportStyle(); MBImportStyle();
var release_url = window.location.href.replace('/\?.*$/', '').replace(/#.*$/, ''); let release_url = window.location.href.replace('/?.*$/', '').replace(/#.*$/, '');
var release = retrieveReleaseInfo(release_url); let release = retrieveReleaseInfo(release_url);
insertLink(release, release_url); insertLink(release, release_url);
}); });
function parseReleaseDate(rdate) { function parseReleaseDate(rdate) {
var months = { let months = {
"January": 1, January: 1,
"February": 2, February: 2,
"March": 3, March: 3,
"April": 4, April: 4,
"May": 5, May: 5,
"June": 6, June: 6,
"July": 7, July: 7,
"August": 8, August: 8,
"September": 9, September: 9,
"October": 10, October: 10,
"November": 11, November: 11,
"December": 12 December: 12
}; };
var m = rdate.match(/(\d{1,2}) ([a-z]+), (\d{4})/i); let m = rdate.match(/(\d{1,2}) ([a-z]+), (\d{4})/i);
if (m) { if (m) {
return { return {
year: m[3], year: m[3],
month: months[m[2]], month: months[m[2]],
day: m[1] day: m[1]
} };
} }
return false; return false;
} }
function retrieveReleaseInfo(release_url) { function retrieveReleaseInfo(release_url) {
// Release defaults // Release defaults
var release = { let release = {
artist_credit: [], artist_credit: [],
title: $("#product_heading_title").text().trim(), title: $('#product_heading_title')
.text()
.trim(),
year: 0, year: 0,
month: 0, month: 0,
day: 0, day: 0,
@ -71,11 +72,15 @@ function retrieveReleaseInfo(release_url) {
type: '', type: '',
urls: [], urls: [],
labels: [], labels: [],
discs: [], discs: []
}; };
// Release date // Release date
var parsed_releaseDate = parseReleaseDate($("#product_info_released_on").text().trim()); let parsed_releaseDate = parseReleaseDate(
$('#product_info_released_on')
.text()
.trim()
);
if (parsed_releaseDate) { if (parsed_releaseDate) {
release.year = parsed_releaseDate.year; release.year = parsed_releaseDate.year;
release.month = parsed_releaseDate.month; release.month = parsed_releaseDate.month;
@ -84,63 +89,74 @@ function retrieveReleaseInfo(release_url) {
// URLs // URLs
release.urls.push({ release.urls.push({
'url': release_url, url: release_url,
'link_type': MBImport.URL_TYPES.purchase_for_download link_type: MBImport.URL_TYPES.purchase_for_download
}); });
release.labels.push( release.labels.push({
{ name: $('#product_heading_label')
name: $("#product_heading_label").text().trim(), .text()
catno: $("#product_info_cat_no").text().trim() .trim(),
} catno: $('#product_info_cat_no')
); .text()
.trim()
});
// Tracks // Tracks
var tracks = []; let tracks = [];
$(".product_tracklist_records[itemprop='tracks']").each(function() { $(".product_tracklist_records[itemprop='tracks']").each(function() {
var artists = []; let artists = [];
var trackno = $(this).find(".product_tracklist_heading_records_sn").text().trim() - 1; let trackno =
var trackname = $(this).find(".product_tracklist_heading_records_title").text().trim(); $(this)
var tracklength = $(this).find(".product_tracklist_heading_records_length").text().trim(); .find('.product_tracklist_heading_records_sn')
var m = trackname.match(/^([^-]+) - (.*)$/); .text()
.trim() - 1;
let trackname = $(this)
.find('.product_tracklist_heading_records_title')
.text()
.trim();
let tracklength = $(this)
.find('.product_tracklist_heading_records_length')
.text()
.trim();
let m = trackname.match(/^([^-]+) - (.*)$/);
if (m) { if (m) {
artists = [m[1]]; artists = [m[1]];
trackname = m[2]; trackname = m[2];
} }
tracks.push({ tracks.push({
'artist_credit': MBImport.makeArtistCredits(artists), artist_credit: MBImport.makeArtistCredits(artists),
'title': trackname, title: trackname,
'duration': tracklength duration: tracklength
}); });
}); });
var parsed_release_artist = $("#product_heading_artist").text().trim(); let parsed_release_artist = $('#product_heading_artist')
.text()
.trim();
if (parsed_release_artist == 'VARIOUS') { if (parsed_release_artist == 'VARIOUS') {
release.artist_credit = [ MBImport.specialArtist('various_artists') ]; release.artist_credit = [MBImport.specialArtist('various_artists')];
} else { } else {
release.artist_credit = MBImport.makeArtistCredits([ parsed_release_artist ]); release.artist_credit = MBImport.makeArtistCredits([parsed_release_artist]);
} }
release.discs.push( { release.discs.push({
'tracks': tracks, tracks: tracks,
'format': release.format format: release.format
} ); });
LOGGER.info("Parsed release: ", release); LOGGER.info('Parsed release: ', release);
return release; return release;
} }
// Insert button into page under label information // Insert button into page under label information
function insertLink(release, release_url) { function insertLink(release, release_url) {
var edit_note = MBImport.makeEditNote(release_url, 'Juno Download'); let edit_note = MBImport.makeEditNote(release_url, 'Juno Download');
var parameters = MBImport.buildFormParameters(release, edit_note); let parameters = MBImport.buildFormParameters(release, edit_note);
var mbUI = $('<div id="mb_buttons">' let mbUI = $(`<div id="mb_buttons">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`).hide();
+ MBImport.buildFormHTML(parameters)
+ MBImport.buildSearchButton(release)
+ '</div>').hide();
$("div.sociald").before(mbUI); $('div.sociald').before(mbUI);
$('#mb_buttons').css({'background': '#759d44', 'border': '2px solid #ddd', 'text-align': 'center'}); $('#mb_buttons').css({ background: '#759d44', border: '2px solid #ddd', 'text-align': 'center' });
$('form.musicbrainz_import button').css({width: '80%'}); $('form.musicbrainz_import button').css({ width: '80%' });
mbUI.slideDown(); mbUI.slideDown();
} }

View file

@ -18,23 +18,25 @@ this.$ = this.jQuery = jQuery.noConflict(true);
if (!unsafeWindow) unsafeWindow = window; if (!unsafeWindow) unsafeWindow = window;
$(document).ready(function(){ $(document).ready(function() {
MBImportStyle(); MBImportStyle();
var release_url = window.location.href.replace('/\?.*$/', '').replace(/#.*$/, ''); let release_url = window.location.href.replace('/?.*$/', '').replace(/#.*$/, '');
release_url = release_url.replace(/^(?:https?:\/\/)?(?:www\.)?(?:last\.fm|lastfm\.(?:com\.br|com\.tr|at|com|de|es|fr|it|jp|pl|pt|ru|se))\//, "http://www.last.fm/"); release_url = release_url.replace(
/^(?:https?:\/\/)?(?:www\.)?(?:last\.fm|lastfm\.(?:com\.br|com\.tr|at|com|de|es|fr|it|jp|pl|pt|ru|se))\//,
'http://www.last.fm/'
);
var release = retrieveReleaseInfo(release_url); let release = retrieveReleaseInfo(release_url);
insertLink(release, release_url); insertLink(release, release_url);
}); });
function retrieveReleaseInfo(release_url) { function retrieveReleaseInfo(release_url) {
// Release defaults // Release defaults
var release = { let release = {
artist_credit: '', artist_credit: '',
title: $("h1[itemprop='name']").text().trim(), title: $("h1[itemprop='name']")
.text()
.trim(),
year: 0, year: 0,
month: 0, month: 0,
day: 0, day: 0,
@ -47,82 +49,94 @@ function retrieveReleaseInfo(release_url) {
type: '', type: '',
urls: [], urls: [],
labels: [], labels: [],
discs: [], discs: []
}; };
// Release artist // Release artist
var artist = $("article span[itemprop='byArtist'] meta[itemprop='name']").attr('content').trim(); let artist = $("article span[itemprop='byArtist'] meta[itemprop='name']")
var various_artists = (artist == 'Various Artists'); .attr('content')
.trim();
let various_artists = artist == 'Various Artists';
if (various_artists) { if (various_artists) {
release.artist_credit = [ MBImport.specialArtist('various_artists') ]; release.artist_credit = [MBImport.specialArtist('various_artists')];
} else { } else {
release.artist_credit = MBImport.makeArtistCredits([artist]); release.artist_credit = MBImport.makeArtistCredits([artist]);
} }
// Tracks // Tracks
var tracks = []; let tracks = [];
$("#albumTracklist tr[itemprop='tracks']").each(function() { $("#albumTracklist tr[itemprop='tracks']").each(function() {
var artists = []; let artists = [];
var trackno = parseInt($(this).find("td.positionCell").text(), 10); let trackno = parseInt(
$(this)
.find('td.positionCell')
.text(),
10
);
if (trackno == 1 && tracks.length) { if (trackno == 1 && tracks.length) {
// multiple "discs" // multiple "discs"
release.discs.push( { release.discs.push({
'tracks': tracks, tracks: tracks,
'format': release.format format: release.format
} ); });
tracks = []; tracks = [];
} }
var trackname = $(this).find("td.subjectCell span[itemprop='name']").text().trim(); let trackname = $(this)
var tracklength = $(this).find("td.durationCell").text().trim(); .find("td.subjectCell span[itemprop='name']")
.text()
.trim();
let tracklength = $(this)
.find('td.durationCell')
.text()
.trim();
// VA releases have an additional link to the lastfm artist page // VA releases have an additional link to the lastfm artist page
var track_artists = []; let track_artists = [];
$(this).find("td.subjectCell > a:not(:last)").each( $(this)
function () { .find('td.subjectCell > a:not(:last)')
track_artists.push($(this).text().trim()); .each(function() {
} track_artists.push(
$(this)
.text()
.trim()
); );
var ac = { });
'artist_credit': '', let ac = {
'title': trackname, artist_credit: '',
'duration': tracklength title: trackname,
duration: tracklength
}; };
if (!track_artists.length && various_artists) { if (!track_artists.length && various_artists) {
ac.artist_credit = [ MBImport.specialArtist('unknown') ]; ac.artist_credit = [MBImport.specialArtist('unknown')];
} else { } else {
ac.artist_credit = MBImport.makeArtistCredits(track_artists); ac.artist_credit = MBImport.makeArtistCredits(track_artists);
} }
tracks.push(ac); tracks.push(ac);
}); });
release.discs.push( { release.discs.push({
'tracks': tracks, tracks: tracks,
'format': release.format format: release.format
} ); });
LOGGER.info("Parsed release: ", release); LOGGER.info('Parsed release: ', release);
return release; return release;
} }
// Insert button into page under label information // Insert button into page under label information
function insertLink(release, release_url) { function insertLink(release, release_url) {
var edit_note = MBImport.makeEditNote(release_url, 'Last.fm'); let edit_note = MBImport.makeEditNote(release_url, 'Last.fm');
var parameters = MBImport.buildFormParameters(release, edit_note); let parameters = MBImport.buildFormParameters(release, edit_note);
$("div.g4").prepend( $('div.g4').prepend($(`<div id="mb_buttons">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`).hide());
$('<div id="mb_buttons">'
+ MBImport.buildFormHTML(parameters)
+ MBImport.buildSearchButton(release)
+ '</div>').hide()
);
$('#mb_buttons').css({ $('#mb_buttons').css({
'margin-bottom': '5px', 'margin-bottom': '5px',
'padding': '2%', padding: '2%',
'background-color': '#444' 'background-color': '#444'
}); });
$('form.musicbrainz_import').css({width: '48%', display:'inline-block'}); $('form.musicbrainz_import').css({ width: '48%', display: 'inline-block' });
$('form.musicbrainz_import_search').css({'float': 'right'}) $('form.musicbrainz_import_search').css({ float: 'right' });
$('form.musicbrainz_import > button').css({width: '100%', 'box-sizing': 'border-box'}); $('form.musicbrainz_import > button').css({ width: '100%', 'box-sizing': 'border-box' });
$('#mb_buttons').slideDown(); $('#mb_buttons').slideDown();
} }

View file

@ -3,23 +3,22 @@
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var LOGGER = (function() { var LOGGER = (function() {
let LOG_LEVEL = 'info';
var LOG_LEVEL = 'info';
function fnDebug() { function fnDebug() {
if (LOG_LEVEL == 'debug') { if (LOG_LEVEL == 'debug') {
_log("DEBUG", arguments); _log('DEBUG', arguments);
} }
} }
function fnInfo() { function fnInfo() {
if (LOG_LEVEL == 'debug' || LOG_LEVEL === 'info') { if (LOG_LEVEL == 'debug' || LOG_LEVEL === 'info') {
_log("INFO", arguments); _log('INFO', arguments);
} }
} }
function fnError() { function fnError() {
_log("ERROR", arguments); _log('ERROR', arguments);
} }
function fnSetLevel(level) { function fnSetLevel(level) {
@ -31,16 +30,16 @@ var LOGGER = (function() {
function _log(level, args) { function _log(level, args) {
// Prepends log level to things that will be logged // Prepends log level to things that will be logged
args = Array.prototype.slice.call(args); args = Array.prototype.slice.call(args);
args.unshift('['+level+']'); args.unshift(`[${level}]`);
// Determine if there's a logger (console.log) available // Determine if there's a logger (console.log) available
var win = unsafeWindow || window; let win = unsafeWindow || window;
var console = win.console; let console = win.console;
if (console && console.log && console.log.apply) { if (console && console.log && console.log.apply) {
try { try {
console.log.apply(this, args); console.log.apply(this, args);
} catch(e) {} } catch (e) {}
}
} }
};
// ---------------------------------- expose publics here ------------------------------------ // // ---------------------------------- expose publics here ------------------------------------ //

View file

@ -58,10 +58,9 @@
*/ */
var MBImport = (function() { var MBImport = (function() {
// --------------------------------------- publics ----------------------------------------- // // --------------------------------------- publics ----------------------------------------- //
var special_artists = { let special_artists = {
various_artists: { various_artists: {
name: 'Various Artists', name: 'Various Artists',
mbid: '89ad4ac3-39f7-470e-963a-56509c546377' mbid: '89ad4ac3-39f7-470e-963a-56509c546377'
@ -72,7 +71,7 @@ var MBImport = (function() {
} }
}; };
var url_types = { let url_types = {
purchase_for_download: 74, purchase_for_download: 74,
download_for_free: 75, download_for_free: 75,
discogs: 76, discogs: 76,
@ -80,40 +79,42 @@ var MBImport = (function() {
other_databases: 82, other_databases: 82,
stream_for_free: 85, stream_for_free: 85,
license: 301 license: 301
} };
function fnSpecialArtist(key, ac) { function fnSpecialArtist(key, ac) {
var credited_name = ""; let credited_name = '';
var joinphrase = ""; let joinphrase = '';
if (typeof ac !== 'undefined') { if (typeof ac !== 'undefined') {
joinphrase = ac.joinphrase; joinphrase = ac.joinphrase;
} }
return { return {
'artist_name': special_artists[key].name, artist_name: special_artists[key].name,
'credited_name': credited_name, credited_name: credited_name,
'joinphrase': joinphrase, joinphrase: joinphrase,
'mbid': special_artists[key].mbid mbid: special_artists[key].mbid
}; };
} }
// compute HTML of search link // compute HTML of search link
function fnBuildSearchLink(release) { function fnBuildSearchLink(release) {
var parameters = searchParams(release); let parameters = searchParams(release);
var url_params = []; let url_params = [];
parameters.forEach(function(parameter) { parameters.forEach(function(parameter) {
var value = parameter.value + ""; let value = `${parameter.value}`;
url_params.push(encodeURI(parameter.name + '=' + value)); url_params.push(encodeURI(`${parameter.name}=${value}`));
}); });
return '<a class="musicbrainz_import" href="//musicbrainz.org/search?' + url_params.join('&') + '">Search in MusicBrainz</a>'; return `<a class="musicbrainz_import" href="//musicbrainz.org/search?${url_params.join('&')}">Search in MusicBrainz</a>`;
} }
// compute HTML of search button // compute HTML of search button
function fnBuildSearchButton(release) { function fnBuildSearchButton(release) {
var parameters = searchParams(release); let parameters = searchParams(release);
var html = '<form class="musicbrainz_import musicbrainz_import_search" action="//musicbrainz.org/search" method="get" target="_blank" accept-charset="UTF-8" charset="' + document.characterSet + '">'; let html = `<form class="musicbrainz_import musicbrainz_import_search" action="//musicbrainz.org/search" method="get" target="_blank" accept-charset="UTF-8" charset="${
document.characterSet
}">`;
parameters.forEach(function(parameter) { parameters.forEach(function(parameter) {
var value = parameter.value + ""; let value = `${parameter.value}`;
html += "<input type='hidden' value='" + value.replace(/'/g,"&apos;") + "' name='" + parameter.name + "'/>"; html += `<input type='hidden' value='${value.replace(/'/g, '&apos;')}' name='${parameter.name}'/>`;
}); });
html += '<button type="submit" title="Search for this release in MusicBrainz (open a new tab)"><span>Search in MB</span></button>'; html += '<button type="submit" title="Search for this release in MusicBrainz (open a new tab)"><span>Search in MB</span></button>';
html += '</form>'; html += '</form>';
@ -123,25 +124,23 @@ var MBImport = (function() {
function fnSearchUrlFor(type, what) { function fnSearchUrlFor(type, what) {
type = type.replace('-', '_'); type = type.replace('-', '_');
var params = [ let params = [`query=${luceneEscape(what)}`, `type=${type}`, 'indexed=1'];
'query=' + luceneEscape(what), return `//musicbrainz.org/search?${params.join('&')}`;
'type=' + type,
'indexed=1'
];
return '//musicbrainz.org/search?' + params.join('&');
} }
// compute HTML of import form // compute HTML of import form
function fnBuildFormHTML(parameters) { function fnBuildFormHTML(parameters) {
// Build form // Build form
var innerHTML = '<form class="musicbrainz_import musicbrainz_import_add" action="//musicbrainz.org/release/add" method="post" target="_blank" accept-charset="UTF-8" charset="' + document.characterSet + '">'; let innerHTML = `<form class="musicbrainz_import musicbrainz_import_add" action="//musicbrainz.org/release/add" method="post" target="_blank" accept-charset="UTF-8" charset="${
document.characterSet
}">`;
parameters.forEach(function(parameter) { parameters.forEach(function(parameter) {
var value = parameter.value + ""; let value = `${parameter.value}`;
innerHTML += "<input type='hidden' value='" + value.replace(/'/g,"&apos;") + "' name='" + parameter.name + "'/>"; innerHTML += `<input type='hidden' value='${value.replace(/'/g, '&apos;')}' name='${parameter.name}'/>`;
}); });
innerHTML += '<button type="submit" title="Import this release into MusicBrainz (open a new tab)"><img src="//musicbrainz.org/favicon.ico" /><span>Import into MB</span></button>'; innerHTML +=
'<button type="submit" title="Import this release into MusicBrainz (open a new tab)"><img src="//musicbrainz.org/favicon.ico" /><span>Import into MB</span></button>';
innerHTML += '</form>'; innerHTML += '</form>';
return innerHTML; return innerHTML;
@ -150,14 +149,14 @@ var MBImport = (function() {
// build form POST parameters that MB is waiting // build form POST parameters that MB is waiting
function fnBuildFormParameters(release, edit_note) { function fnBuildFormParameters(release, edit_note) {
// Form parameters // Form parameters
var parameters = new Array(); let parameters = new Array();
appendParameter(parameters, 'name', release.title); appendParameter(parameters, 'name', release.title);
// Release Artist credits // Release Artist credits
buildArtistCreditsFormParameters(parameters, "", release.artist_credit); buildArtistCreditsFormParameters(parameters, '', release.artist_credit);
if (release["secondary_types"]) { if (release['secondary_types']) {
for (var i=0; i < release.secondary_types.length; i++) { for (var i = 0; i < release.secondary_types.length; i++) {
appendParameter(parameters, 'type', release.secondary_types[i]); appendParameter(parameters, 'type', release.secondary_types[i]);
} }
} }
@ -171,55 +170,61 @@ var MBImport = (function() {
// Date + country // Date + country
appendParameter(parameters, 'country', release.country); appendParameter(parameters, 'country', release.country);
if (!isNaN(release.year) && release.year != 0) { appendParameter(parameters, 'date.year', release.year); }; if (!isNaN(release.year) && release.year != 0) {
if (!isNaN(release.month) && release.month != 0) { appendParameter(parameters, 'date.month', release.month); }; appendParameter(parameters, 'date.year', release.year);
if (!isNaN(release.day) && release.day != 0) { appendParameter(parameters, 'date.day', release.day); }; }
if (!isNaN(release.month) && release.month != 0) {
appendParameter(parameters, 'date.month', release.month);
}
if (!isNaN(release.day) && release.day != 0) {
appendParameter(parameters, 'date.day', release.day);
}
// Barcode // Barcode
appendParameter(parameters, 'barcode', release.barcode); appendParameter(parameters, 'barcode', release.barcode);
// Label + catnos // Label + catnos
for (var i=0; i < release.labels.length; i++) { for (var i = 0; i < release.labels.length; i++) {
var label = release.labels[i]; let label = release.labels[i];
appendParameter(parameters, 'labels.'+i+'.name', label.name); appendParameter(parameters, `labels.${i}.name`, label.name);
appendParameter(parameters, 'labels.'+i+'.mbid', label.mbid); appendParameter(parameters, `labels.${i}.mbid`, label.mbid);
if (label.catno != "none") { if (label.catno != 'none') {
appendParameter(parameters, 'labels.'+i+'.catalog_number', label.catno); appendParameter(parameters, `labels.${i}.catalog_number`, label.catno);
} }
} }
// URLs // URLs
for (var i=0; i < release.urls.length; i++) { for (var i = 0; i < release.urls.length; i++) {
var url = release.urls[i]; let url = release.urls[i];
appendParameter(parameters, 'urls.'+i+'.url', url.url); appendParameter(parameters, `urls.${i}.url`, url.url);
appendParameter(parameters, 'urls.'+i+'.link_type', url.link_type); appendParameter(parameters, `urls.${i}.link_type`, url.link_type);
} }
// Mediums // Mediums
var total_tracks = 0; let total_tracks = 0;
var total_tracks_with_duration = 0; let total_tracks_with_duration = 0;
var total_duration = 0; let total_duration = 0;
for (var i=0; i < release.discs.length; i++) { for (var i = 0; i < release.discs.length; i++) {
var disc = release.discs[i]; let disc = release.discs[i];
appendParameter(parameters, 'mediums.'+i+'.format', disc.format); appendParameter(parameters, `mediums.${i}.format`, disc.format);
appendParameter(parameters, 'mediums.'+i+'.name', disc.title); appendParameter(parameters, `mediums.${i}.name`, disc.title);
// Tracks // Tracks
for (var j=0; j < disc.tracks.length; j++) { for (let j = 0; j < disc.tracks.length; j++) {
var track = disc.tracks[j]; let track = disc.tracks[j];
total_tracks++; total_tracks++;
appendParameter(parameters, 'mediums.'+i+'.track.'+j+'.number', track.number); appendParameter(parameters, `mediums.${i}.track.${j}.number`, track.number);
appendParameter(parameters, 'mediums.'+i+'.track.'+j+'.name', track.title); appendParameter(parameters, `mediums.${i}.track.${j}.name`, track.title);
var tracklength = "?:??"; let tracklength = '?:??';
var duration_ms = hmsToMilliSeconds(track.duration); let duration_ms = hmsToMilliSeconds(track.duration);
if (!isNaN(duration_ms)) { if (!isNaN(duration_ms)) {
tracklength = duration_ms; tracklength = duration_ms;
total_tracks_with_duration++; total_tracks_with_duration++;
total_duration += duration_ms; total_duration += duration_ms;
} }
appendParameter(parameters, 'mediums.'+i+'.track.'+j+'.length', tracklength); appendParameter(parameters, `mediums.${i}.track.${j}.length`, tracklength);
buildArtistCreditsFormParameters(parameters, 'mediums.'+i+'.track.'+j+'.', track.artist_credit); buildArtistCreditsFormParameters(parameters, `mediums.${i}.track.${j}.`, track.artist_credit);
} }
} }
@ -237,13 +242,15 @@ var MBImport = (function() {
// Convert a list of artists to a list of artist credits with joinphrases // Convert a list of artists to a list of artist credits with joinphrases
function fnArtistCredits(artists_list) { function fnArtistCredits(artists_list) {
var artists = artists_list.map(function(item) { return {artist_name: item}; }); let artists = artists_list.map(function(item) {
return { artist_name: item };
});
if (artists.length > 2) { if (artists.length > 2) {
var last = artists.pop(); let last = artists.pop();
last.joinphrase = ''; last.joinphrase = '';
var prev = artists.pop(); let prev = artists.pop();
prev.joinphrase = ' & '; prev.joinphrase = ' & ';
for (var i = 0; i < artists.length; i++) { for (let i = 0; i < artists.length; i++) {
artists[i].joinphrase = ', '; artists[i].joinphrase = ', ';
} }
artists.push(prev); artists.push(prev);
@ -251,22 +258,22 @@ var MBImport = (function() {
} else if (artists.length == 2) { } else if (artists.length == 2) {
artists[0].joinphrase = ' & '; artists[0].joinphrase = ' & ';
} }
var credits = []; let credits = [];
// re-split artists if featuring or vs // re-split artists if featuring or vs
artists.map(function (item) { artists.map(function(item) {
var c = item.artist_name.replace(/\s*\b(?:feat\.?|ft\.?|featuring)\s+/gi, ' feat. '); let c = item.artist_name.replace(/\s*\b(?:feat\.?|ft\.?|featuring)\s+/gi, ' feat. ');
c = c.replace(/\s*\(( feat. )([^\)]+)\)/g, '$1$2'); c = c.replace(/\s*\(( feat. )([^\)]+)\)/g, '$1$2');
c = c.replace(/\s*\b(?:versus|vs\.?)\s+/gi, ' vs. '); c = c.replace(/\s*\b(?:versus|vs\.?)\s+/gi, ' vs. ');
c = c.replace(/\s+/g, ' '); c = c.replace(/\s+/g, ' ');
var splitted = c.split(/( feat\. | vs\. )/); let splitted = c.split(/( feat\. | vs\. )/);
if (splitted.length == 1) { if (splitted.length == 1) {
credits.push(item); // nothing to split credits.push(item); // nothing to split
} else { } else {
var new_items = []; let new_items = [];
var n = 0; let n = 0;
for (var i = 0; i < splitted.length; i++) { for (let i = 0; i < splitted.length; i++) {
if (n && (splitted[i] == ' feat. ' || splitted[i] == ' vs. ')) { if (n && (splitted[i] == ' feat. ' || splitted[i] == ' vs. ')) {
new_items[n-1].joinphrase = splitted[i]; new_items[n - 1].joinphrase = splitted[i];
} else { } else {
new_items[n++] = { new_items[n++] = {
artist_name: splitted[i].trim(), artist_name: splitted[i].trim(),
@ -274,9 +281,9 @@ var MBImport = (function() {
}; };
} }
} }
new_items[n-1].joinphrase = item.joinphrase; new_items[n - 1].joinphrase = item.joinphrase;
new_items.map(function (newit) { new_items.map(function(newit) {
credits.push(newit) credits.push(newit);
}); });
} }
}); });
@ -286,15 +293,15 @@ var MBImport = (function() {
// Try to guess release type using number of tracks, title and total duration (in millisecs) // Try to guess release type using number of tracks, title and total duration (in millisecs)
function fnGuessReleaseType(title, num_tracks, duration_ms) { function fnGuessReleaseType(title, num_tracks, duration_ms) {
if (num_tracks < 1) return ''; if (num_tracks < 1) return '';
var has_single = !!title.match(/\bsingle\b/i); let has_single = !!title.match(/\bsingle\b/i);
var has_EP = !!title.match(/\bEP\b/i); let has_EP = !!title.match(/\bEP\b/i);
if (has_single && has_EP) { if (has_single && has_EP) {
has_single = false; has_single = false;
has_EP = false; has_EP = false;
} }
var perhaps_single = ((has_single && num_tracks <= 4) || num_tracks <= 2); let perhaps_single = (has_single && num_tracks <= 4) || num_tracks <= 2;
var perhaps_EP = has_EP || (num_tracks > 2 && num_tracks <= 6); let perhaps_EP = has_EP || (num_tracks > 2 && num_tracks <= 6);
var perhaps_album = (num_tracks > 8); let perhaps_album = num_tracks > 8;
if (isNaN(duration_ms)) { if (isNaN(duration_ms)) {
// no duration, try to guess with title and number of tracks // no duration, try to guess with title and number of tracks
if (perhaps_single && !perhaps_EP && !perhaps_album) return 'single'; if (perhaps_single && !perhaps_EP && !perhaps_album) return 'single';
@ -302,7 +309,7 @@ var MBImport = (function() {
if (!perhaps_single && !perhaps_EP && perhaps_album) return 'album'; if (!perhaps_single && !perhaps_EP && perhaps_album) return 'album';
return ''; return '';
} }
var duration_mn = duration_ms / (60*1000); let duration_mn = duration_ms / (60 * 1000);
if (perhaps_single && duration_mn >= 1 && duration_mn < 7) return 'single'; if (perhaps_single && duration_mn >= 1 && duration_mn < 7) return 'single';
if (perhaps_EP && duration_mn > 7 && duration_mn <= 30) return 'EP'; if (perhaps_EP && duration_mn > 7 && duration_mn <= 30) return 'EP';
if (perhaps_album && duration_mn > 30) return 'album'; if (perhaps_album && duration_mn > 30) return 'album';
@ -311,80 +318,80 @@ var MBImport = (function() {
// convert HH:MM:SS or MM:SS to milliseconds // convert HH:MM:SS or MM:SS to milliseconds
function hmsToMilliSeconds(str) { function hmsToMilliSeconds(str) {
if (typeof str == 'undefined' || str === null || str === NaN || str === '') return NaN; if (typeof str == 'undefined' || str === null || str === NaN || str === '') return NaN;
if (typeof str == 'number') return str; if (typeof str == 'number') return str;
var t = str.split(':'); let t = str.split(':');
var s = 0; let s = 0;
var m = 1; let m = 1;
while (t.length > 0) { while (t.length > 0) {
s += m * parseInt(t.pop(), 10); s += m * parseInt(t.pop(), 10);
m *= 60; m *= 60;
} }
return s*1000; return s * 1000;
} }
// convert ISO8601 duration (limited to hours/minutes/seconds) to milliseconds // convert ISO8601 duration (limited to hours/minutes/seconds) to milliseconds
// format looks like PT1H45M5.789S (note: floats can be used) // format looks like PT1H45M5.789S (note: floats can be used)
// https://en.wikipedia.org/wiki/ISO_8601#Durations // https://en.wikipedia.org/wiki/ISO_8601#Durations
function fnISO8601toMilliSeconds(str) { function fnISO8601toMilliSeconds(str) {
var regex = /^PT(?:(\d*\.?\d*)H)?(?:(\d*\.?\d*)M)?(?:(\d*\.?\d*)S)?$/, let regex = /^PT(?:(\d*\.?\d*)H)?(?:(\d*\.?\d*)M)?(?:(\d*\.?\d*)S)?$/,
m = str.replace(',', '.').match(regex); m = str.replace(',', '.').match(regex);
if (!m) return NaN; if (!m) return NaN;
return (3600 * parseFloat(m[1] || 0) + 60 * parseFloat(m[2] || 0) + parseFloat(m[3] || 0)) * 1000; return (3600 * parseFloat(m[1] || 0) + 60 * parseFloat(m[2] || 0) + parseFloat(m[3] || 0)) * 1000;
} }
function fnMakeEditNote(release_url, importer_name, format) { function fnMakeEditNote(release_url, importer_name, format) {
var home = 'https://github.com/murdos/musicbrainz-userscripts'; let home = 'https://github.com/murdos/musicbrainz-userscripts';
return 'Imported from ' + release_url + (format ? ' (' + format + ')' : '') +' using ' + importer_name + ' import script from ' + home; return `Imported from ${release_url}${format ? ` (${format})` : ''} using ${importer_name} import script from ${home}`;
} }
// --------------------------------------- privates ----------------------------------------- // // --------------------------------------- privates ----------------------------------------- //
function appendParameter(parameters, paramName, paramValue) { function appendParameter(parameters, paramName, paramValue) {
if(!paramValue) return; if (!paramValue) return;
parameters.push( { name: paramName, value: paramValue } ); parameters.push({ name: paramName, value: paramValue });
} }
function luceneEscape(text) { function luceneEscape(text) {
var newtext = text.replace(/[-[\]{}()*+?~:\\^!"\/]/g, "\\$&"); let newtext = text.replace(/[-[\]{}()*+?~:\\^!"\/]/g, '\\$&');
return newtext.replace("&&", "\&&").replace("||", "\||"); return newtext.replace('&&', '&&').replace('||', '||');
} }
function buildArtistCreditsFormParameters(parameters, paramPrefix, artist_credit) { function buildArtistCreditsFormParameters(parameters, paramPrefix, artist_credit) {
if(!artist_credit) return; if (!artist_credit) return;
for (var i=0; i < artist_credit.length; i++) { for (let i = 0; i < artist_credit.length; i++) {
var ac = artist_credit[i]; let ac = artist_credit[i];
appendParameter(parameters, paramPrefix+'artist_credit.names.'+i+'.name', ac.credited_name); appendParameter(parameters, `${paramPrefix}artist_credit.names.${i}.name`, ac.credited_name);
appendParameter(parameters, paramPrefix+'artist_credit.names.'+i+'.artist.name', ac.artist_name); appendParameter(parameters, `${paramPrefix}artist_credit.names.${i}.artist.name`, ac.artist_name);
appendParameter(parameters, paramPrefix+'artist_credit.names.'+i+'.mbid', ac.mbid); appendParameter(parameters, `${paramPrefix}artist_credit.names.${i}.mbid`, ac.mbid);
if (typeof ac.joinphrase != 'undefined' && ac.joinphrase != "") { if (typeof ac.joinphrase != 'undefined' && ac.joinphrase != '') {
appendParameter(parameters, paramPrefix+'artist_credit.names.'+i+'.join_phrase', ac.joinphrase); appendParameter(parameters, `${paramPrefix}artist_credit.names.${i}.join_phrase`, ac.joinphrase);
} }
} }
} }
function searchParams(release) { function searchParams(release) {
var params = []; let params = [];
var totaltracks = 0; let totaltracks = 0;
for (var i=0; i < release.discs.length; i++) { for (var i = 0; i < release.discs.length; i++) {
totaltracks += release.discs[i].tracks.length; totaltracks += release.discs[i].tracks.length;
} }
var release_artist = ""; let release_artist = '';
for (var i=0; i < release.artist_credit.length; i++) { for (var i = 0; i < release.artist_credit.length; i++) {
var ac = release.artist_credit[i]; let ac = release.artist_credit[i];
release_artist += ac.artist_name; release_artist += ac.artist_name;
if (typeof ac.joinphrase != 'undefined' && ac.joinphrase != "") { if (typeof ac.joinphrase != 'undefined' && ac.joinphrase != '') {
release_artist += ac.joinphrase; release_artist += ac.joinphrase;
} else { } else {
if (i != release.artist_credit.length-1) release_artist += ", "; if (i != release.artist_credit.length - 1) release_artist += ', ';
} }
} }
var query = 'artist:(' + luceneEscape(release_artist) + ')' let query =
+ ' release:(' + luceneEscape(release.title) + ')' `artist:(${luceneEscape(release_artist)})` +
+ ' tracks:(' + totaltracks + ')' ` release:(${luceneEscape(release.title)})` +
+ (release.country ? ' country:' + release.country : ''); ` tracks:(${totaltracks})${release.country ? ` country:${release.country}` : ''}`;
appendParameter(params, 'query', query); appendParameter(params, 'query', query);
appendParameter(params, 'type', 'release'); appendParameter(params, 'type', 'release');

View file

@ -1,9 +1,10 @@
function _add_css(css) { function _add_css(css) {
$("<style type='text/css'>"+css.replace(/\s+/g, ' ') + "</style>").appendTo("head"); $(`<style type='text/css'>${css.replace(/\s+/g, ' ')}</style>`).appendTo('head');
} }
function MBImportStyle() { function MBImportStyle() {
var css_import_button = " \ let css_import_button =
' \
.musicbrainz_import button { \ .musicbrainz_import button { \
-moz-border-radius:5px; \ -moz-border-radius:5px; \
-webkit-border-radius:5px; \ -webkit-border-radius:5px; \
@ -34,12 +35,13 @@ function MBImportStyle() {
min-height: 16px; \ min-height: 16px; \
display: inline-block; \ display: inline-block; \
} \ } \
"; ';
_add_css(css_import_button); _add_css(css_import_button);
} }
function MBSearchItStyle() { function MBSearchItStyle() {
var css_search_it = " \ let css_search_it =
' \
.mb_valign { \ .mb_valign { \
display: inline-block; \ display: inline-block; \
vertical-align: top; \ vertical-align: top; \
@ -68,6 +70,6 @@ function MBSearchItStyle() {
.mb_wrapper { \ .mb_wrapper { \
display: inline-block; \ display: inline-block; \
} \ } \
"; ';
_add_css(css_search_it); _add_css(css_search_it);
} }

View file

@ -16,85 +16,87 @@
// user_cache_key = textual key used to store cached data in local storage // user_cache_key = textual key used to store cached data in local storage
// version = optionnal version, to force creation of a cache (ie. when format of keys changes) // version = optionnal version, to force creation of a cache (ie. when format of keys changes)
// expiration = time in minutes before an entry is refreshed, value <= 0 disables cache reads, if undefined or false, use defaults // expiration = time in minutes before an entry is refreshed, value <= 0 disables cache reads, if undefined or false, use defaults
var MBLinks = function (user_cache_key, version, expiration) { var MBLinks = function(user_cache_key, version, expiration) {
this.supports_local_storage = function () { this.supports_local_storage = (function() {
try { try {
return !!localStorage.getItem; return !!localStorage.getItem;
} catch (e) { } catch (e) {
return false; return false;
} }
}(); })();
this.ajax_requests = { this.ajax_requests = {
// properties: "key": {handler: function, next: property, context: {}} // properties: "key": {handler: function, next: property, context: {}}
first: "", first: '',
last: "", last: '',
empty: function() {return this.first == "";}, empty: function() {
return this.first == '';
},
push: function(key, handler, context) { push: function(key, handler, context) {
if (key in this) { if (key in this) {
this[key].handler = handler; this[key].handler = handler;
this[key].context = context; this[key].context = context;
} } else {
else { this[key] = { handler: handler, next: '', context: context };
this[key] = {handler: handler, next: "", context: context}; if (this.first == '') {
if (this.first == "") {
this.first = this.last = key; this.first = this.last = key;
} } else {
else {
this[this.last].next = key; this[this.last].next = key;
this.last = key; this.last = key;
} }
} }
}, },
shift: function() { shift: function() {
if (this.empty()) { return; } if (this.empty()) {
var key = this.first; return;
var handler = this[key].handler; }
var context = this[key].context; let key = this.first;
let handler = this[key].handler;
let context = this[key].context;
this.first = this[key].next; this.first = this[key].next;
delete this[key]; // delete this property delete this[key]; // delete this property
return $.proxy(handler, context); return $.proxy(handler, context);
} }
}; };
this.cache = {}; this.cache = {};
this.expirationMinutes = ((typeof expiration != 'undefined' && expiration !== false) ? parseInt(expiration, 10) : 90*24*60); // default to 90 days this.expirationMinutes = typeof expiration != 'undefined' && expiration !== false ? parseInt(expiration, 10) : 90 * 24 * 60; // default to 90 days
var cache_version = 2; let cache_version = 2;
this.user_cache_key = user_cache_key; this.user_cache_key = user_cache_key;
this.cache_key = this.user_cache_key + '-v' + cache_version + (typeof version != 'undefined' ? '.' + version : ''); this.cache_key = `${this.user_cache_key}-v${cache_version}${typeof version != 'undefined' ? `.${version}` : ''}`;
this.mb_server = '//musicbrainz.org'; this.mb_server = '//musicbrainz.org';
// overrides link title and img src url (per type), see createMusicBrainzLink() // overrides link title and img src url (per type), see createMusicBrainzLink()
this.type_link_info = { this.type_link_info = {
release_group: { release_group: {
title: 'See this release group on MusicBrainz', title: 'See this release group on MusicBrainz'
}, },
place: { place: {
img_src: '<img src="'+ this.mb_server + '/static/images/entity/place.svg" height=16 width=16 />' img_src: `<img src="${this.mb_server}/static/images/entity/place.svg" height=16 width=16 />`
}
} }
};
this.initAjaxEngine = function () { this.initAjaxEngine = function() {
var ajax_requests = this.ajax_requests; let ajax_requests = this.ajax_requests;
setInterval(function () { setInterval(function() {
if (!ajax_requests.empty()) { if (!ajax_requests.empty()) {
var request = ajax_requests.shift(); let request = ajax_requests.shift();
if (typeof request === "function") { if (typeof request === 'function') {
request(); request();
} }
} }
}, 1000); }, 1000);
}; };
this.initCache = function () { this.initCache = function() {
if (!this.supports_local_storage) return; if (!this.supports_local_storage) return;
// Check if we already added links for this content // Check if we already added links for this content
this.cache = JSON.parse(localStorage.getItem(this.cache_key) || '{}'); this.cache = JSON.parse(localStorage.getItem(this.cache_key) || '{}');
// remove old entries // remove old entries
this.clearCacheExpired(); this.clearCacheExpired();
// remove old cache versions // remove old cache versions
this.removeOldCacheVersions(); this.removeOldCacheVersions();
}; };
this.saveCache = function () { this.saveCache = function() {
if (!this.supports_local_storage) return; if (!this.supports_local_storage) return;
try { try {
localStorage.setItem(this.cache_key, JSON.stringify(this.cache)); localStorage.setItem(this.cache_key, JSON.stringify(this.cache));
@ -103,12 +105,13 @@ var MBLinks = function (user_cache_key, version, expiration) {
} }
}; };
this.removeOldCacheVersions = function () { this.removeOldCacheVersions = function() {
var to_remove = []; let to_remove = [];
for (var i = 0, len = localStorage.length; i < len; ++i) { for (var i = 0, len = localStorage.length; i < len; ++i) {
var key = localStorage.key(i); let key = localStorage.key(i);
if (key.indexOf(this.user_cache_key) === 0) { if (key.indexOf(this.user_cache_key) === 0) {
if (key != this.cache_key) { // we don't want to remove current cache if (key != this.cache_key) {
// we don't want to remove current cache
to_remove.push(key); to_remove.push(key);
} }
} }
@ -122,10 +125,10 @@ var MBLinks = function (user_cache_key, version, expiration) {
this.clearCacheExpired = function() { this.clearCacheExpired = function() {
//var old_cache_entries = Object.keys(this.cache).length; //var old_cache_entries = Object.keys(this.cache).length;
//console.log("clearCacheExpired " + old_cache_entries); //console.log("clearCacheExpired " + old_cache_entries);
var now = new Date().getTime(); let now = new Date().getTime();
var new_cache = {}; let new_cache = {};
var that = this; let that = this;
$.each(this.cache, function (key, value) { $.each(this.cache, function(key, value) {
if (that.is_cached(key)) { if (that.is_cached(key)) {
new_cache[key] = that.cache[key]; new_cache[key] = that.cache[key];
} }
@ -135,51 +138,54 @@ var MBLinks = function (user_cache_key, version, expiration) {
this.cache = new_cache; this.cache = new_cache;
}; };
this.is_cached = function (key) { this.is_cached = function(key) {
return (this.cache[key] && this.expirationMinutes > 0 && new Date().getTime() < this.cache[key].timestamp + this.expirationMinutes*60*1000); return (
this.cache[key] &&
this.expirationMinutes > 0 &&
new Date().getTime() < this.cache[key].timestamp + this.expirationMinutes * 60 * 1000
);
}; };
// Search for ressource 'url' in local cache, and return the matching MBID if there's only matching MB entity. // Search for ressource 'url' in local cache, and return the matching MBID if there's only matching MB entity.
// If the url is not known by the cache, no attempt will be made to request the MusicBrainz webservice, in order to keep this method synchronous. // If the url is not known by the cache, no attempt will be made to request the MusicBrainz webservice, in order to keep this method synchronous.
this.resolveMBID = function (key) { this.resolveMBID = function(key) {
if (this.is_cached(key) && this.cache[key].urls.length == 1) { if (this.is_cached(key) && this.cache[key].urls.length == 1) {
return this.cache[key].urls[0].slice(-36); return this.cache[key].urls[0].slice(-36);
} }
}; };
this.createMusicBrainzLink = function (mb_url, _type) { this.createMusicBrainzLink = function(mb_url, _type) {
var title = 'See this ' + _type + ' on MusicBrainz'; let title = `See this ${_type} on MusicBrainz`;
var img_url = this.mb_server + '/static/images/entity/' + _type + '.svg'; let img_url = `${this.mb_server}/static/images/entity/${_type}.svg`;
var img_src = '<img src="' + img_url + '" height=16 width=16 />'; let img_src = `<img src="${img_url}" height=16 width=16 />`;
// handle overrides // handle overrides
var ti = this.type_link_info[_type]; let ti = this.type_link_info[_type];
if (ti) { if (ti) {
if (ti.title) title = ti.title; if (ti.title) title = ti.title;
if (ti.img_url) img_url = ti.img_url; if (ti.img_url) img_url = ti.img_url;
if (ti.img_src) img_src = ti.img_src; if (ti.img_src) img_src = ti.img_src;
} }
return '<a href="' + mb_url + '" title="' + title + '">' + img_src + '</a> '; return `<a href="${mb_url}" title="${title}">${img_src}</a> `;
}; };
// Search for ressource 'url' on MB, for relation of type 'mb_type' (artist, release, label, release-group, ...) // Search for ressource 'url' on MB, for relation of type 'mb_type' (artist, release, label, release-group, ...)
// and call 'insert_func' function with matching MB links (a tag built in createMusicBrainzLink) for each // and call 'insert_func' function with matching MB links (a tag built in createMusicBrainzLink) for each
// entry found // entry found
this.searchAndDisplayMbLink = function (url, mb_type, insert_func, key) { this.searchAndDisplayMbLink = function(url, mb_type, insert_func, key) {
var mblinks = this; let mblinks = this;
var _type = mb_type.replace('-', '_'); // underscored type let _type = mb_type.replace('-', '_'); // underscored type
if (!key) key = url; if (!key) key = url;
if (this.is_cached(key)) { if (this.is_cached(key)) {
$.each(mblinks.cache[key].urls, function (idx, mb_url) { $.each(mblinks.cache[key].urls, function(idx, mb_url) {
insert_func(mblinks.createMusicBrainzLink(mb_url, _type)); insert_func(mblinks.createMusicBrainzLink(mb_url, _type));
}); });
} else { } else {
// webservice query url // webservice query url
var query = mblinks.mb_server + '/ws/2/url?resource=' + encodeURIComponent(url) + '&inc=' + mb_type + '-rels'; let query = `${mblinks.mb_server}/ws/2/url?resource=${encodeURIComponent(url)}&inc=${mb_type}-rels`;
// Merge with previous context if there's already a pending ajax request // Merge with previous context if there's already a pending ajax request
var handlers = []; let handlers = [];
if (query in mblinks.ajax_requests) { if (query in mblinks.ajax_requests) {
handlers = mblinks.ajax_requests[query].context.handlers; handlers = mblinks.ajax_requests[query].context.handlers;
} }
@ -190,41 +196,40 @@ var MBLinks = function (user_cache_key, version, expiration) {
query, query,
// handler // handler
function () { function() {
var ctx = this; // context from $.proxy() let ctx = this; // context from $.proxy()
var mbl = ctx.mblinks; let mbl = ctx.mblinks;
$.getJSON(ctx.query, $.getJSON(ctx.query, function(data) {
function (data) {
if ('relations' in data) { if ('relations' in data) {
mbl.cache[ctx.key] = { mbl.cache[ctx.key] = {
timestamp: new Date().getTime(), timestamp: new Date().getTime(),
urls: [] urls: []
}; };
$.each(data['relations'], function (idx, relation) { $.each(data['relations'], function(idx, relation) {
if (ctx._type in relation) { if (ctx._type in relation) {
var mb_url = mbl.mb_server + '/' + ctx.mb_type + '/' + relation[ctx._type]['id']; let mb_url = `${mbl.mb_server}/${ctx.mb_type}/${relation[ctx._type]['id']}`;
if ($.inArray(mb_url, mbl.cache[ctx.key].urls) == -1) { // prevent dupes if ($.inArray(mb_url, mbl.cache[ctx.key].urls) == -1) {
// prevent dupes
mbl.cache[ctx.key].urls.push(mb_url); mbl.cache[ctx.key].urls.push(mb_url);
$.each(ctx.handlers, function(i, handler) { $.each(ctx.handlers, function(i, handler) {
handler(mbl.createMusicBrainzLink(mb_url, ctx._type)) handler(mbl.createMusicBrainzLink(mb_url, ctx._type));
}) });
} }
} }
}); });
mbl.saveCache(); mbl.saveCache();
} }
} });
);
}, },
// context // context
{ {
'key': key, // cache key key: key, // cache key
'handlers': handlers, // list of handlers handlers: handlers, // list of handlers
'mb_type': mb_type, // musicbrainz type ie. release-group mb_type: mb_type, // musicbrainz type ie. release-group
'_type': _type, // musicbrainz type '-' replaced, ie. release_group _type: _type, // musicbrainz type '-' replaced, ie. release_group
'query': query, // json request url query: query, // json request url
'mblinks': mblinks // MBLinks object mblinks: mblinks // MBLinks object
} }
); );
} }

View file

@ -15,7 +15,6 @@
// @grant none // @grant none
// ==/UserScript== // ==/UserScript==
// prevent JQuery conflicts, see http://wiki.greasespot.net/@grant // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant
this.$ = this.jQuery = jQuery.noConflict(true); this.$ = this.jQuery = jQuery.noConflict(true);
@ -38,10 +37,9 @@ if (DEBUG) {
* - http://www.loot.co.za/product/bette-midler-a-gift-of-love/mhgm-3483-g060 *** NOT WORKING *** extra tab * - http://www.loot.co.za/product/bette-midler-a-gift-of-love/mhgm-3483-g060 *** NOT WORKING *** extra tab
*/ */
$(document).ready(function() { $(document).ready(function() {
LOGGER.info("Document Ready & Loot Userscript executing"); LOGGER.info('Document Ready & Loot Userscript executing');
var LootRelease = ParseLootPage(); let LootRelease = ParseLootPage();
insertMBSection(LootRelease); insertMBSection(LootRelease);
}); });
@ -49,42 +47,44 @@ $(document).ready(function() {
// Insert MusicBrainz section into Loot page // // Insert MusicBrainz section into Loot page //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
function insertMbUI(mbUI) { function insertMbUI(mbUI) {
LOGGER.debug("insertMbUI Firing"); LOGGER.debug('insertMbUI Firing');
var e; let e;
if ((e = $("#thumbs")) && e.length) { if ((e = $('#thumbs')) && e.length) {
e.after(mbUI); e.after(mbUI);
} else if ((e = $('#productContent')) && e.length) { } else if ((e = $('#productContent')) && e.length) {
e.before(mbUI); e.before(mbUI);
} else if ((e = $("div.buyNow")) && e.length) { } else if ((e = $('div.buyNow')) && e.length) {
e.before(mbUI); e.before(mbUI);
} }
} }
// Insert links to high res image in Loot page // Insert links to high res image in Loot page
function insertIMGlinks() { function insertIMGlinks() {
var imghref = $('#imagePreview0 a.fancybox').attr('href'); let imghref = $('#imagePreview0 a.fancybox').attr('href');
imghref = 'http://static.loot.co.za/' + imghref; imghref = `http://static.loot.co.za/${imghref}`;
LOGGER.debug("insertIMGlink Firing", imghref); LOGGER.debug('insertIMGlink Firing', imghref);
$('#imagePreview0').append('<p><a href="' + imghref + '">MB High Res Image</a></p>'); $('#imagePreview0').append(`<p><a href="${imghref}">MB High Res Image</a></p>`);
} }
// Insert links in Loot page // Insert links in Loot page
function insertMBSection(release) { function insertMBSection(release) {
LOGGER.debug("insertMBsection Firing"); LOGGER.debug('insertMBsection Firing');
var mbUI = $('<div class="section musicbrainz"><h1>MusicBrainz</h1></div>').hide(); let mbUI = $('<div class="section musicbrainz"><h1>MusicBrainz</h1></div>').hide();
if (DEBUG) mbUI.css({ if (DEBUG)
'border': '1px dotted red' mbUI.css({
border: '1px dotted red'
}); });
var mbContentBlock = $('<div class="section_content"></div>'); let mbContentBlock = $('<div class="section_content"></div>');
mbUI.append(mbContentBlock); mbUI.append(mbContentBlock);
if (release.maybe_buggy) { if (release.maybe_buggy) {
var warning_buggy = $('<p><small><b>Warning</b>: this release has perhaps a buggy title, please check twice the data you import.</small><p').css({ let warning_buggy = $(
'color': 'red', '<p><small><b>Warning</b>: this release has perhaps a buggy title, please check twice the data you import.</small><p'
).css({
color: 'red',
'margin-top': '4px', 'margin-top': '4px',
'margin-bottom': '4px' 'margin-bottom': '4px'
}); });
@ -92,12 +92,12 @@ function insertMBSection(release) {
} }
// Form parameters // Form parameters
var edit_note = MBImport.makeEditNote(window.location.href, 'Loot'); let edit_note = MBImport.makeEditNote(window.location.href, 'Loot');
LOGGER.debug("*** Edit Note: ", edit_note); LOGGER.debug('*** Edit Note: ', edit_note);
var parameters = MBImport.buildFormParameters(release, edit_note); let parameters = MBImport.buildFormParameters(release, edit_note);
LOGGER.debug("***Form parameters"); LOGGER.debug('***Form parameters');
// Build form + search button // Build form + search button
var innerHTML = '<div id="mb_buttons">' + MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release) + '</div>'; let innerHTML = `<div id="mb_buttons">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`;
mbContentBlock.append(innerHTML); mbContentBlock.append(innerHTML);
insertMbUI(mbUI); insertMbUI(mbUI);
@ -112,8 +112,8 @@ function insertMBSection(release) {
display: 'inline-block' display: 'inline-block'
}); });
$('form.musicbrainz_import_search').css({ $('form.musicbrainz_import_search').css({
'float': 'right' float: 'right'
}) });
$('form.musicbrainz_import > button').css({ $('form.musicbrainz_import > button').css({
width: '100%', width: '100%',
'box-sizing': 'border-box' 'box-sizing': 'border-box'
@ -123,50 +123,50 @@ function insertMBSection(release) {
} }
function parseReleaseDate(rdate) { function parseReleaseDate(rdate) {
var months = { let months = {
"January": 1, January: 1,
"February": 2, February: 2,
"March": 3, March: 3,
"April": 4, April: 4,
"May": 5, May: 5,
"June": 6, June: 6,
"July": 7, July: 7,
"August": 8, August: 8,
"September": 9, September: 9,
"October": 10, October: 10,
"November": 11, November: 11,
"December": 12 December: 12
}; };
var m = rdate.match(/([a-zA-Z]+) (\d{4})/i); let m = rdate.match(/([a-zA-Z]+) (\d{4})/i);
if (m) { if (m) {
return { return {
year: m[2], year: m[2],
month: months[m[1]] month: months[m[1]]
} };
} }
return false; return false;
} }
// Analyze Loot data and return a release object // Analyze Loot data and return a release object
function ParseLootPage() { function ParseLootPage() {
LOGGER.debug("ParseLootPage function firing"); LOGGER.debug('ParseLootPage function firing');
var releasebarcode = ""; let releasebarcode = '';
var releasecountry = ""; let releasecountry = '';
var releasedaterel = ""; let releasedaterel = '';
var releaselanguage = ""; let releaselanguage = '';
var releasetitle = ""; let releasetitle = '';
var releaseartist = ""; let releaseartist = '';
var prodlabels = []; let prodlabels = [];
var release_artist_array = []; let release_artist_array = [];
var release_format = ""; let release_format = '';
var release_maybe_buggy = false; let release_maybe_buggy = false;
// div#productContent table tbody tr.productOverview td.productInfo h1 // div#productContent table tbody tr.productOverview td.productInfo h1
var AlbumName = document.querySelectorAll("div#productContent > table > tbody > tr.productOverview > td.productInfo > *"); let AlbumName = document.querySelectorAll('div#productContent > table > tbody > tr.productOverview > td.productInfo > *');
releaseartist = AlbumName[1].innerText; releaseartist = AlbumName[1].innerText;
if (releaseartist == "Various Artists") { if (releaseartist == 'Various Artists') {
// Everything is: title(format) // Everything is: title(format)
releaseartisttitle_regex = /(.*?)\((.*)\)/; //match external parenthesis releaseartisttitle_regex = /(.*?)\((.*)\)/; //match external parenthesis
if (AlbumName[0].innerText.match(releaseartisttitle_regex)) { if (AlbumName[0].innerText.match(releaseartisttitle_regex)) {
@ -174,102 +174,110 @@ function ParseLootPage() {
releasetitle = releaseartisttitle[1].trim(); releasetitle = releaseartisttitle[1].trim();
release_format = releaseartisttitle[2]; release_format = releaseartisttitle[2];
} else { } else {
LOGGER.debug("Release Title for Various Artist album does not match the name convention. Hint: Change releaseartisttitle regex for Compilations"); LOGGER.debug(
'Release Title for Various Artist album does not match the name convention. Hint: Change releaseartisttitle regex for Compilations'
);
release_maybe_buggy = true; release_maybe_buggy = true;
releasetitle = ""; releasetitle = '';
release_format = ""; release_format = '';
} }
} else { } else {
// artist - title(format) // artist - title(format)
releaseartisttitle_regex = /(.*) (-|) (.*?)\((.*)\)/; releaseartisttitle_regex = /(.*) (-|) (.*?)\((.*)\)/;
if (AlbumName[0].innerText.match(releaseartisttitle_regex)) { if (AlbumName[0].innerText.match(releaseartisttitle_regex)) {
releaseartisttitle = AlbumName[0].innerText.match(releaseartisttitle_regex); releaseartisttitle = AlbumName[0].innerText.match(releaseartisttitle_regex);
releasetitle = releaseartisttitle[3].trim(); releasetitle = releaseartisttitle[3].trim();
releaseartist = releaseartisttitle[1]; releaseartist = releaseartisttitle[1];
release_format = releaseartisttitle[4]; release_format = releaseartisttitle[4];
} else { } else {
LOGGER.debug("Release Title for Various Artist album does not match the name convention. Hint: Change releaseartisttitle regex for non Compilations"); LOGGER.debug(
'Release Title for Various Artist album does not match the name convention. Hint: Change releaseartisttitle regex for non Compilations'
);
release_maybe_buggy = true; release_maybe_buggy = true;
releasetitle = ""; releasetitle = '';
releaseartist = ""; releaseartist = '';
release_format = ""; release_format = '';
} }
} }
LOGGER.debug("Release Title:", releasetitle, " Release Artist:", releaseartist, " Release Format:", release_format); LOGGER.debug('Release Title:', releasetitle, ' Release Artist:', releaseartist, ' Release Format:', release_format);
// extract all tr from table with class productDetails // extract all tr from table with class productDetails
$("table.productDetails tr").each(function() { $('table.productDetails tr').each(function() {
// get text from first td, trim and convert it to lowercase // get text from first td, trim and convert it to lowercase
var prodinfolabellowcase = $(this).children('td').eq(0).text().trim().toLowerCase(); let prodinfolabellowcase = $(this)
.children('td')
.eq(0)
.text()
.trim()
.toLowerCase();
prodinfolabellowcase = prodinfolabellowcase.replace(/\s+/g, ''); //removing white spaces as switch isnt matching spaces for some reason prodinfolabellowcase = prodinfolabellowcase.replace(/\s+/g, ''); //removing white spaces as switch isnt matching spaces for some reason
// get test from second td, which is the corresponding value // get test from second td, which is the corresponding value
var value = $(this).children('td').eq(1).text().trim(); let value = $(this)
.children('td')
.eq(1)
.text()
.trim();
// now compare and process // now compare and process
switch (prodinfolabellowcase) { switch (prodinfolabellowcase) {
case "label:": // use these cases to select the spesific text values case 'label:': // use these cases to select the spesific text values
prodlabels.push({ prodlabels.push({
name: value name: value
}); });
break; break;
case "releasedate:": case 'releasedate:':
releasedaterel = value; releasedaterel = value;
LOGGER.debug(" ** release date: **", releasedaterel) LOGGER.debug(' ** release date: **', releasedaterel);
break; break;
case "countryoforigin:": case 'countryoforigin:':
releasecountry = value; releasecountry = value;
LOGGER.debug(" ** country of origin: **", releasecountry); LOGGER.debug(' ** country of origin: **', releasecountry);
break; break;
case "performers:": case 'performers:':
LOGGER.debug(" ** performers: **", value); LOGGER.debug(' ** performers: **', value);
release_artist_array.push({ release_artist_array.push({
name: value name: value
}); });
break; break;
case "format:": case 'format:':
LOGGER.debug(" ** format: **"); LOGGER.debug(' ** format: **');
break; break;
case "categories:": case 'categories:':
//LOGGER.debug(" ** categories: **", value); //LOGGER.debug(" ** categories: **", value);
if ($('table.productDetails tr td a:contains("Afrikaans")').length) { if ($('table.productDetails tr td a:contains("Afrikaans")').length) {
LOGGER.debug("Language Afrikaans exists"); LOGGER.debug('Language Afrikaans exists');
releaselanguage = "Afrikaans"; releaselanguage = 'Afrikaans';
} }
if ($('table.productDetails tr td a:contains("South Africa")').length) { if ($('table.productDetails tr td a:contains("South Africa")').length) {
LOGGER.debug("Country South Africa exists in catagories"); LOGGER.debug('Country South Africa exists in catagories');
releasecountry = "South Africa"; releasecountry = 'South Africa';
} }
break; break;
} }
}); });
// Select all data in the "Tracks" div id = tab-2 // Select all data in the "Tracks" div id = tab-2
var allinfolist = document.querySelectorAll("div#tab-2 > table.productDetails > tbody"); let allinfolist = document.querySelectorAll('div#tab-2 > table.productDetails > tbody');
LOGGER.debug("Track Info: (allinfolist)", allinfolist); LOGGER.debug('Track Info: (allinfolist)', allinfolist);
// Select the Disc names // Select the Disc names
var disccount = document.querySelectorAll("div#tab-2 > h3"); let disccount = document.querySelectorAll('div#tab-2 > h3');
LOGGER.debug("Amount of discs: ", disccount.length); LOGGER.debug('Amount of discs: ', disccount.length);
var descriptionarray = []; let descriptionarray = [];
for (var disciterate = 0; disciterate < disccount.length; disciterate++) { for (let disciterate = 0; disciterate < disccount.length; disciterate++) {
LOGGER.debug(disciterate); LOGGER.debug(disciterate);
var tracklisting = allinfolist[disciterate].getElementsByTagName('tr'); let tracklisting = allinfolist[disciterate].getElementsByTagName('tr');
LOGGER.debug(" The Table: (tracklisting)", tracklisting); LOGGER.debug(' The Table: (tracklisting)', tracklisting);
for (var trackiterate = 0; trackiterate < tracklisting.length; trackiterate++) {
for (let trackiterate = 0; trackiterate < tracklisting.length; trackiterate++) {
descriptiontrack = new Object(); descriptiontrack = new Object();
var currenttrack = tracklisting[trackiterate].querySelectorAll("td"); let currenttrack = tracklisting[trackiterate].querySelectorAll('td');
// var artisttitle_regex = /(.*) - (.*)/; // regex: artist - title // var artisttitle_regex = /(.*) - (.*)/; // regex: artist - title
var artisttitle_regex = /(.*) (-|) (.*)/; // regex: artist - title char 45 or 8211 var artisttitle_regex = /(.*) (-|) (.*)/; // regex: artist - title char 45 or 8211
@ -293,23 +301,21 @@ function ParseLootPage() {
} }
} }
// Discs // Discs
var disclistarray = new Array(); // create the tracklist array to use later let disclistarray = new Array(); // create the tracklist array to use later
for (var desc_discs = 0; desc_discs < disccount.length; desc_discs++) { for (let desc_discs = 0; desc_discs < disccount.length; desc_discs++) {
var tracklistarray = new Array(); let tracklistarray = new Array();
for (var desc__track = 0; desc__track < descriptionarray.length; desc__track++) { for (let desc__track = 0; desc__track < descriptionarray.length; desc__track++) {
let desc_currentdiscnumber = descriptionarray[desc__track].disc;
var desc_currentdiscnumber = descriptionarray[desc__track].disc;
if (desc_currentdiscnumber == desc_discs + 1) { if (desc_currentdiscnumber == desc_discs + 1) {
var track = new Object(); let track = new Object();
var track_artist_credit = new Array(); let track_artist_credit = new Array();
track.number = descriptionarray[desc__track].track; track.number = descriptionarray[desc__track].track;
track.title = descriptionarray[desc__track].title; track.title = descriptionarray[desc__track].title;
var track_artist_credit_object = new Object(); let track_artist_credit_object = new Object();
track_artist_credit_object.artist_name = descriptionarray[desc__track].artist; track_artist_credit_object.artist_name = descriptionarray[desc__track].artist;
track_artist_credit.push(track_artist_credit_object); track_artist_credit.push(track_artist_credit_object);
@ -329,17 +335,15 @@ function ParseLootPage() {
// Release artist credit // Release artist credit
release.artist_credit = new Array(); release.artist_credit = new Array();
var artist_name = releaseartist; let artist_name = releaseartist;
var various_artists = (releaseartist == 'Various Artists'); let various_artists = releaseartist == 'Various Artists';
if (various_artists) { if (various_artists) {
release.artist_credit = [MBImport.specialArtist('various_artists')]; release.artist_credit = [MBImport.specialArtist('various_artists')];
} else { } else {
release.artist_credit = MBImport.makeArtistCredits([artist_name]); release.artist_credit = MBImport.makeArtistCredits([artist_name]);
} }
// Release title // Release title
release.title = releasetitle; release.title = releasetitle;
// Release Barcode // Release Barcode
@ -355,11 +359,11 @@ function ParseLootPage() {
release.language = Languages[releaselanguage]; release.language = Languages[releaselanguage];
release.discs = new Array(); release.discs = new Array();
for (var l = 0; l < disccount.length; l++) { for (let l = 0; l < disccount.length; l++) {
var disc = { let disc = {
'position': l + 1, position: l + 1,
'format': release_format, format: release_format,
'tracks': disclistarray[l] tracks: disclistarray[l]
}; };
release.discs.push(disc); release.discs.push(disc);
} }
@ -369,23 +373,21 @@ function ParseLootPage() {
// Release URL // Release URL
release.urls = new Array(); release.urls = new Array();
release.urls.push({ release.urls.push({
'url': window.location.href, url: window.location.href,
'link_type': MBImport.URL_TYPES.purchase_for_mail_order link_type: MBImport.URL_TYPES.purchase_for_mail_order
}); });
// TODO check format then change purchase medium // TODO check format then change purchase medium
// Release date // Release date
var parsed_releaseDate = parseReleaseDate(releasedaterel); let parsed_releaseDate = parseReleaseDate(releasedaterel);
if (parsed_releaseDate) { if (parsed_releaseDate) {
release.year = parsed_releaseDate.year; release.year = parsed_releaseDate.year;
release.month = parsed_releaseDate.month; release.month = parsed_releaseDate.month;
release.day = parsed_releaseDate.day; release.day = parsed_releaseDate.day;
} }
LOGGER.info('Release:', release);
LOGGER.info("Release:", release);
return release; return release;
} }
@ -393,266 +395,263 @@ function ParseLootPage() {
// Loot -> MusicBrainz mapping // // Loot -> MusicBrainz mapping //
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var Languages = new Array(); var Languages = new Array();
Languages["Afrikaans"] = "afr"; Languages['Afrikaans'] = 'afr';
var Countries = new Array(); var Countries = new Array();
Countries["Afghanistan"] = "AF"; Countries['Afghanistan'] = 'AF';
Countries["Albania"] = "AL"; Countries['Albania'] = 'AL';
Countries["Algeria"] = "DZ"; Countries['Algeria'] = 'DZ';
Countries["American Samoa"] = "AS"; Countries['American Samoa'] = 'AS';
Countries["Andorra"] = "AD"; Countries['Andorra'] = 'AD';
Countries["Angola"] = "AO"; Countries['Angola'] = 'AO';
Countries["Anguilla"] = "AI"; Countries['Anguilla'] = 'AI';
Countries["Antarctica"] = "AQ"; Countries['Antarctica'] = 'AQ';
Countries["Antigua and Barbuda"] = "AG"; Countries['Antigua and Barbuda'] = 'AG';
Countries["Argentina"] = "AR"; Countries['Argentina'] = 'AR';
Countries["Armenia"] = "AM"; Countries['Armenia'] = 'AM';
Countries["Aruba"] = "AW"; Countries['Aruba'] = 'AW';
Countries["Australia"] = "AU"; Countries['Australia'] = 'AU';
Countries["Austria"] = "AT"; Countries['Austria'] = 'AT';
Countries["Azerbaijan"] = "AZ"; Countries['Azerbaijan'] = 'AZ';
Countries["Bahamas"] = "BS"; Countries['Bahamas'] = 'BS';
Countries["Bahrain"] = "BH"; Countries['Bahrain'] = 'BH';
Countries["Bangladesh"] = "BD"; Countries['Bangladesh'] = 'BD';
Countries["Barbados"] = "BB"; Countries['Barbados'] = 'BB';
Countries["Belarus"] = "BY"; Countries['Belarus'] = 'BY';
Countries["Belgium"] = "BE"; Countries['Belgium'] = 'BE';
Countries["Belize"] = "BZ"; Countries['Belize'] = 'BZ';
Countries["Benin"] = "BJ"; Countries['Benin'] = 'BJ';
Countries["Bermuda"] = "BM"; Countries['Bermuda'] = 'BM';
Countries["Bhutan"] = "BT"; Countries['Bhutan'] = 'BT';
Countries["Bolivia"] = "BO"; Countries['Bolivia'] = 'BO';
Countries["Croatia"] = "HR"; Countries['Croatia'] = 'HR';
Countries["Botswana"] = "BW"; Countries['Botswana'] = 'BW';
Countries["Bouvet Island"] = "BV"; Countries['Bouvet Island'] = 'BV';
Countries["Brazil"] = "BR"; Countries['Brazil'] = 'BR';
Countries["British Indian Ocean Territory"] = "IO"; Countries['British Indian Ocean Territory'] = 'IO';
Countries["Brunei Darussalam"] = "BN"; Countries['Brunei Darussalam'] = 'BN';
Countries["Bulgaria"] = "BG"; Countries['Bulgaria'] = 'BG';
Countries["Burkina Faso"] = "BF"; Countries['Burkina Faso'] = 'BF';
Countries["Burundi"] = "BI"; Countries['Burundi'] = 'BI';
Countries["Cambodia"] = "KH"; Countries['Cambodia'] = 'KH';
Countries["Cameroon"] = "CM"; Countries['Cameroon'] = 'CM';
Countries["Canada"] = "CA"; Countries['Canada'] = 'CA';
Countries["Cape Verde"] = "CV"; Countries['Cape Verde'] = 'CV';
Countries["Cayman Islands"] = "KY"; Countries['Cayman Islands'] = 'KY';
Countries["Central African Republic"] = "CF"; Countries['Central African Republic'] = 'CF';
Countries["Chad"] = "TD"; Countries['Chad'] = 'TD';
Countries["Chile"] = "CL"; Countries['Chile'] = 'CL';
Countries["China"] = "CN"; Countries['China'] = 'CN';
Countries["Christmas Island"] = "CX"; Countries['Christmas Island'] = 'CX';
Countries["Cocos (Keeling) Islands"] = "CC"; Countries['Cocos (Keeling) Islands'] = 'CC';
Countries["Colombia"] = "CO"; Countries['Colombia'] = 'CO';
Countries["Comoros"] = "KM"; Countries['Comoros'] = 'KM';
Countries["Congo"] = "CG"; Countries['Congo'] = 'CG';
Countries["Cook Islands"] = "CK"; Countries['Cook Islands'] = 'CK';
Countries["Costa Rica"] = "CR"; Countries['Costa Rica'] = 'CR';
Countries["Virgin Islands, British"] = "VG"; Countries['Virgin Islands, British'] = 'VG';
Countries["Cuba"] = "CU"; Countries['Cuba'] = 'CU';
Countries["Cyprus"] = "CY"; Countries['Cyprus'] = 'CY';
Countries["Czech Republic"] = "CZ"; Countries['Czech Republic'] = 'CZ';
Countries["Denmark"] = "DK"; Countries['Denmark'] = 'DK';
Countries["Djibouti"] = "DJ"; Countries['Djibouti'] = 'DJ';
Countries["Dominica"] = "DM"; Countries['Dominica'] = 'DM';
Countries["Dominican Republic"] = "DO"; Countries['Dominican Republic'] = 'DO';
Countries["Ecuador"] = "EC"; Countries['Ecuador'] = 'EC';
Countries["Egypt"] = "EG"; Countries['Egypt'] = 'EG';
Countries["El Salvador"] = "SV"; Countries['El Salvador'] = 'SV';
Countries["Equatorial Guinea"] = "GQ"; Countries['Equatorial Guinea'] = 'GQ';
Countries["Eritrea"] = "ER"; Countries['Eritrea'] = 'ER';
Countries["Estonia"] = "EE"; Countries['Estonia'] = 'EE';
Countries["Ethiopia"] = "ET"; Countries['Ethiopia'] = 'ET';
Countries["Falkland Islands (Malvinas)"] = "FK"; Countries['Falkland Islands (Malvinas)'] = 'FK';
Countries["Faroe Islands"] = "FO"; Countries['Faroe Islands'] = 'FO';
Countries["Fiji"] = "FJ"; Countries['Fiji'] = 'FJ';
Countries["Finland"] = "FI"; Countries['Finland'] = 'FI';
Countries["France"] = "FR"; Countries['France'] = 'FR';
Countries["French Guiana"] = "GF"; Countries['French Guiana'] = 'GF';
Countries["French Polynesia"] = "PF"; Countries['French Polynesia'] = 'PF';
Countries["French Southern Territories"] = "TF"; Countries['French Southern Territories'] = 'TF';
Countries["Gabon"] = "GA"; Countries['Gabon'] = 'GA';
Countries["Gambia"] = "GM"; Countries['Gambia'] = 'GM';
Countries["Georgia"] = "GE"; Countries['Georgia'] = 'GE';
Countries["Germany"] = "DE"; Countries['Germany'] = 'DE';
Countries["Ghana"] = "GH"; Countries['Ghana'] = 'GH';
Countries["Gibraltar"] = "GI"; Countries['Gibraltar'] = 'GI';
Countries["Greece"] = "GR"; Countries['Greece'] = 'GR';
Countries["Greenland"] = "GL"; Countries['Greenland'] = 'GL';
Countries["Grenada"] = "GD"; Countries['Grenada'] = 'GD';
Countries["Guadeloupe"] = "GP"; Countries['Guadeloupe'] = 'GP';
Countries["Guam"] = "GU"; Countries['Guam'] = 'GU';
Countries["Guatemala"] = "GT"; Countries['Guatemala'] = 'GT';
Countries["Guinea"] = "GN"; Countries['Guinea'] = 'GN';
Countries["Guinea-Bissau"] = "GW"; Countries['Guinea-Bissau'] = 'GW';
Countries["Guyana"] = "GY"; Countries['Guyana'] = 'GY';
Countries["Haiti"] = "HT"; Countries['Haiti'] = 'HT';
Countries["Virgin Islands, U.S."] = "VI"; Countries['Virgin Islands, U.S.'] = 'VI';
Countries["Honduras"] = "HN"; Countries['Honduras'] = 'HN';
Countries["Hong Kong"] = "HK"; Countries['Hong Kong'] = 'HK';
Countries["Hungary"] = "HU"; Countries['Hungary'] = 'HU';
Countries["Iceland"] = "IS"; Countries['Iceland'] = 'IS';
Countries["India"] = "IN"; Countries['India'] = 'IN';
Countries["Indonesia"] = "ID"; Countries['Indonesia'] = 'ID';
Countries["Wallis and Futuna"] = "WF"; Countries['Wallis and Futuna'] = 'WF';
Countries["Iraq"] = "IQ"; Countries['Iraq'] = 'IQ';
Countries["Ireland"] = "IE"; Countries['Ireland'] = 'IE';
Countries["Israel"] = "IL"; Countries['Israel'] = 'IL';
Countries["Italy"] = "IT"; Countries['Italy'] = 'IT';
Countries["Jamaica"] = "JM"; Countries['Jamaica'] = 'JM';
Countries["Japan"] = "JP"; Countries['Japan'] = 'JP';
Countries["Jordan"] = "JO"; Countries['Jordan'] = 'JO';
Countries["Kazakhstan"] = "KZ"; Countries['Kazakhstan'] = 'KZ';
Countries["Kenya"] = "KE"; Countries['Kenya'] = 'KE';
Countries["Kiribati"] = "KI"; Countries['Kiribati'] = 'KI';
Countries["Kuwait"] = "KW"; Countries['Kuwait'] = 'KW';
Countries["Kyrgyzstan"] = "KG"; Countries['Kyrgyzstan'] = 'KG';
Countries["Lao People's Democratic Republic"] = "LA"; Countries["Lao People's Democratic Republic"] = 'LA';
Countries["Latvia"] = "LV"; Countries['Latvia'] = 'LV';
Countries["Lebanon"] = "LB"; Countries['Lebanon'] = 'LB';
Countries["Lesotho"] = "LS"; Countries['Lesotho'] = 'LS';
Countries["Liberia"] = "LR"; Countries['Liberia'] = 'LR';
Countries["Libyan Arab Jamahiriya"] = "LY"; Countries['Libyan Arab Jamahiriya'] = 'LY';
Countries["Liechtenstein"] = "LI"; Countries['Liechtenstein'] = 'LI';
Countries["Lithuania"] = "LT"; Countries['Lithuania'] = 'LT';
Countries["Luxembourg"] = "LU"; Countries['Luxembourg'] = 'LU';
Countries["Montserrat"] = "MS"; Countries['Montserrat'] = 'MS';
Countries["Macedonia, The Former Yugoslav Republic of"] = "MK"; Countries['Macedonia, The Former Yugoslav Republic of'] = 'MK';
Countries["Madagascar"] = "MG"; Countries['Madagascar'] = 'MG';
Countries["Malawi"] = "MW"; Countries['Malawi'] = 'MW';
Countries["Malaysia"] = "MY"; Countries['Malaysia'] = 'MY';
Countries["Maldives"] = "MV"; Countries['Maldives'] = 'MV';
Countries["Mali"] = "ML"; Countries['Mali'] = 'ML';
Countries["Malta"] = "MT"; Countries['Malta'] = 'MT';
Countries["Marshall Islands"] = "MH"; Countries['Marshall Islands'] = 'MH';
Countries["Martinique"] = "MQ"; Countries['Martinique'] = 'MQ';
Countries["Mauritania"] = "MR"; Countries['Mauritania'] = 'MR';
Countries["Mauritius"] = "MU"; Countries['Mauritius'] = 'MU';
Countries["Mayotte"] = "YT"; Countries['Mayotte'] = 'YT';
Countries["Mexico"] = "MX"; Countries['Mexico'] = 'MX';
Countries["Micronesia, Federated States of"] = "FM"; Countries['Micronesia, Federated States of'] = 'FM';
Countries["Morocco"] = "MA"; Countries['Morocco'] = 'MA';
Countries["Monaco"] = "MC"; Countries['Monaco'] = 'MC';
Countries["Mongolia"] = "MN"; Countries['Mongolia'] = 'MN';
Countries["Mozambique"] = "MZ"; Countries['Mozambique'] = 'MZ';
Countries["Myanmar"] = "MM"; Countries['Myanmar'] = 'MM';
Countries["Namibia"] = "NA"; Countries['Namibia'] = 'NA';
Countries["Nauru"] = "NR"; Countries['Nauru'] = 'NR';
Countries["Nepal"] = "NP"; Countries['Nepal'] = 'NP';
Countries["Netherlands"] = "NL"; Countries['Netherlands'] = 'NL';
Countries["Netherlands Antilles"] = "AN"; Countries['Netherlands Antilles'] = 'AN';
Countries["New Caledonia"] = "NC"; Countries['New Caledonia'] = 'NC';
Countries["New Zealand"] = "NZ"; Countries['New Zealand'] = 'NZ';
Countries["Nicaragua"] = "NI"; Countries['Nicaragua'] = 'NI';
Countries["Niger"] = "NE"; Countries['Niger'] = 'NE';
Countries["Nigeria"] = "NG"; Countries['Nigeria'] = 'NG';
Countries["Niue"] = "NU"; Countries['Niue'] = 'NU';
Countries["Norfolk Island"] = "NF"; Countries['Norfolk Island'] = 'NF';
Countries["Northern Mariana Islands"] = "MP"; Countries['Northern Mariana Islands'] = 'MP';
Countries["Norway"] = "NO"; Countries['Norway'] = 'NO';
Countries["Oman"] = "OM"; Countries['Oman'] = 'OM';
Countries["Pakistan"] = "PK"; Countries['Pakistan'] = 'PK';
Countries["Palau"] = "PW"; Countries['Palau'] = 'PW';
Countries["Panama"] = "PA"; Countries['Panama'] = 'PA';
Countries["Papua New Guinea"] = "PG"; Countries['Papua New Guinea'] = 'PG';
Countries["Paraguay"] = "PY"; Countries['Paraguay'] = 'PY';
Countries["Peru"] = "PE"; Countries['Peru'] = 'PE';
Countries["Philippines"] = "PH"; Countries['Philippines'] = 'PH';
Countries["Pitcairn"] = "PN"; Countries['Pitcairn'] = 'PN';
Countries["Poland"] = "PL"; Countries['Poland'] = 'PL';
Countries["Portugal"] = "PT"; Countries['Portugal'] = 'PT';
Countries["Puerto Rico"] = "PR"; Countries['Puerto Rico'] = 'PR';
Countries["Qatar"] = "QA"; Countries['Qatar'] = 'QA';
Countries["Reunion"] = "RE"; Countries['Reunion'] = 'RE';
Countries["Romania"] = "RO"; Countries['Romania'] = 'RO';
Countries["Russian Federation"] = "RU"; Countries['Russian Federation'] = 'RU';
Countries["Russia"] = "RU"; Countries['Russia'] = 'RU';
Countries["Rwanda"] = "RW"; Countries['Rwanda'] = 'RW';
Countries["Saint Kitts and Nevis"] = "KN"; Countries['Saint Kitts and Nevis'] = 'KN';
Countries["Saint Lucia"] = "LC"; Countries['Saint Lucia'] = 'LC';
Countries["Saint Vincent and The Grenadines"] = "VC"; Countries['Saint Vincent and The Grenadines'] = 'VC';
Countries["Samoa"] = "WS"; Countries['Samoa'] = 'WS';
Countries["San Marino"] = "SM"; Countries['San Marino'] = 'SM';
Countries["Sao Tome and Principe"] = "ST"; Countries['Sao Tome and Principe'] = 'ST';
Countries["Saudi Arabia"] = "SA"; Countries['Saudi Arabia'] = 'SA';
Countries["Senegal"] = "SN"; Countries['Senegal'] = 'SN';
Countries["Seychelles"] = "SC"; Countries['Seychelles'] = 'SC';
Countries["Sierra Leone"] = "SL"; Countries['Sierra Leone'] = 'SL';
Countries["Singapore"] = "SG"; Countries['Singapore'] = 'SG';
Countries["Slovenia"] = "SI"; Countries['Slovenia'] = 'SI';
Countries["Solomon Islands"] = "SB"; Countries['Solomon Islands'] = 'SB';
Countries["Somalia"] = "SO"; Countries['Somalia'] = 'SO';
Countries["South Africa"] = "ZA"; Countries['South Africa'] = 'ZA';
Countries["Spain"] = "ES"; Countries['Spain'] = 'ES';
Countries["Sri Lanka"] = "LK"; Countries['Sri Lanka'] = 'LK';
Countries["Sudan"] = "SD"; Countries['Sudan'] = 'SD';
Countries["Suriname"] = "SR"; Countries['Suriname'] = 'SR';
Countries["Swaziland"] = "SZ"; Countries['Swaziland'] = 'SZ';
Countries["Sweden"] = "SE"; Countries['Sweden'] = 'SE';
Countries["Switzerland"] = "CH"; Countries['Switzerland'] = 'CH';
Countries["Syrian Arab Republic"] = "SY"; Countries['Syrian Arab Republic'] = 'SY';
Countries["Tajikistan"] = "TJ"; Countries['Tajikistan'] = 'TJ';
Countries["Tanzania, United Republic of"] = "TZ"; Countries['Tanzania, United Republic of'] = 'TZ';
Countries["Thailand"] = "TH"; Countries['Thailand'] = 'TH';
Countries["Togo"] = "TG"; Countries['Togo'] = 'TG';
Countries["Tokelau"] = "TK"; Countries['Tokelau'] = 'TK';
Countries["Tonga"] = "TO"; Countries['Tonga'] = 'TO';
Countries["Trinidad and Tobago"] = "TT"; Countries['Trinidad and Tobago'] = 'TT';
Countries["Tunisia"] = "TN"; Countries['Tunisia'] = 'TN';
Countries["Turkey"] = "TR"; Countries['Turkey'] = 'TR';
Countries["Turkmenistan"] = "TM"; Countries['Turkmenistan'] = 'TM';
Countries["Turks and Caicos Islands"] = "TC"; Countries['Turks and Caicos Islands'] = 'TC';
Countries["Tuvalu"] = "TV"; Countries['Tuvalu'] = 'TV';
Countries["Uganda"] = "UG"; Countries['Uganda'] = 'UG';
Countries["Ukraine"] = "UA"; Countries['Ukraine'] = 'UA';
Countries["United Arab Emirates"] = "AE"; Countries['United Arab Emirates'] = 'AE';
Countries["UK"] = "GB"; Countries['UK'] = 'GB';
Countries["US"] = "US"; Countries['US'] = 'US';
Countries["United States Minor Outlying Islands"] = "UM"; Countries['United States Minor Outlying Islands'] = 'UM';
Countries["Uruguay"] = "UY"; Countries['Uruguay'] = 'UY';
Countries["Uzbekistan"] = "UZ"; Countries['Uzbekistan'] = 'UZ';
Countries["Vanuatu"] = "VU"; Countries['Vanuatu'] = 'VU';
Countries["Vatican City State (Holy See)"] = "VA"; Countries['Vatican City State (Holy See)'] = 'VA';
Countries["Venezuela"] = "VE"; Countries['Venezuela'] = 'VE';
Countries["Viet Nam"] = "VN"; Countries['Viet Nam'] = 'VN';
Countries["Western Sahara"] = "EH"; Countries['Western Sahara'] = 'EH';
Countries["Yemen"] = "YE"; Countries['Yemen'] = 'YE';
Countries["Zambia"] = "ZM"; Countries['Zambia'] = 'ZM';
Countries["Zimbabwe"] = "ZW"; Countries['Zimbabwe'] = 'ZW';
Countries["Taiwan"] = "TW"; Countries['Taiwan'] = 'TW';
Countries["[Worldwide]"] = "XW"; Countries['[Worldwide]'] = 'XW';
Countries["Europe"] = "XE"; Countries['Europe'] = 'XE';
Countries["Soviet Union (historical, 1922-1991)"] = "SU"; Countries['Soviet Union (historical, 1922-1991)'] = 'SU';
Countries["East Germany (historical, 1949-1990)"] = "XG"; Countries['East Germany (historical, 1949-1990)'] = 'XG';
Countries["Czechoslovakia (historical, 1918-1992)"] = "XC"; Countries['Czechoslovakia (historical, 1918-1992)'] = 'XC';
Countries["Congo, The Democratic Republic of the"] = "CD"; Countries['Congo, The Democratic Republic of the'] = 'CD';
Countries["Slovakia"] = "SK"; Countries['Slovakia'] = 'SK';
Countries["Bosnia and Herzegovina"] = "BA"; Countries['Bosnia and Herzegovina'] = 'BA';
Countries["Korea (North), Democratic People's Republic of"] = "KP"; Countries["Korea (North), Democratic People's Republic of"] = 'KP';
Countries["North Korea"] = "KP"; Countries['North Korea'] = 'KP';
Countries["Korea (South), Republic of"] = "KR"; Countries['Korea (South), Republic of'] = 'KR';
Countries["South Korea"] = "KR"; Countries['South Korea'] = 'KR';
Countries["Montenegro"] = "ME"; Countries['Montenegro'] = 'ME';
Countries["South Georgia and the South Sandwich Islands"] = "GS"; Countries['South Georgia and the South Sandwich Islands'] = 'GS';
Countries["Palestinian Territory"] = "PS"; Countries['Palestinian Territory'] = 'PS';
Countries["Macao"] = "MO"; Countries['Macao'] = 'MO';
Countries["Timor-Leste"] = "TL"; Countries['Timor-Leste'] = 'TL';
Countries["<85>land Islands"] = "AX"; Countries['<85>land Islands'] = 'AX';
Countries["Guernsey"] = "GG"; Countries['Guernsey'] = 'GG';
Countries["Isle of Man"] = "IM"; Countries['Isle of Man'] = 'IM';
Countries["Jersey"] = "JE"; Countries['Jersey'] = 'JE';
Countries["Serbia"] = "RS"; Countries['Serbia'] = 'RS';
Countries["Saint Barthélemy"] = "BL"; Countries['Saint Barthélemy'] = 'BL';
Countries["Saint Martin"] = "MF"; Countries['Saint Martin'] = 'MF';
Countries["Moldova"] = "MD"; Countries['Moldova'] = 'MD';
Countries["Yugoslavia (historical, 1918-2003)"] = "YU"; Countries['Yugoslavia (historical, 1918-2003)'] = 'YU';
Countries["Serbia and Montenegro (historical, 2003-2006)"] = "CS"; Countries['Serbia and Montenegro (historical, 2003-2006)'] = 'CS';
Countries["Côte d'Ivoire"] = "CI"; Countries["Côte d'Ivoire"] = 'CI';
Countries["Heard Island and McDonald Islands"] = "HM"; Countries['Heard Island and McDonald Islands'] = 'HM';
Countries["Iran, Islamic Republic of"] = "IR"; Countries['Iran, Islamic Republic of'] = 'IR';
Countries["Saint Pierre and Miquelon"] = "PM"; Countries['Saint Pierre and Miquelon'] = 'PM';
Countries["Saint Helena"] = "SH"; Countries['Saint Helena'] = 'SH';
Countries["Svalbard and Jan Mayen"] = "SJ"; Countries['Svalbard and Jan Mayen'] = 'SJ';

View file

@ -23,166 +23,193 @@ this.$ = this.jQuery = jQuery.noConflict(true);
LOGGER.setLevel('info'); LOGGER.setLevel('info');
var CHECK_IMAGE = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/gD+AP7rGNSCAAAACXBIWXMAAABIAAAASABGyWs+AAAACXZwQWcAAAAQAAAAEABcxq3DAAADKklEQVQ4y32TS2hcZRiGn/8/Z87MNNc2zczEmptO0jSXagJtXCjWhhSEXpCI4EYENy6KG8FFBYtgEbzQ4k5QqNp2VyMtJVGpRU0tGDNoQxvrmCbkMslkSJrJXM6cOef8v4ukQqX4wbP5eL/327wv/M/Em+qNeFO9ASDEwzUPrM+fP8dqOhXqeGJ/f21ddCAYCsfRyFLJvru2mvnh9mTil8am1uJLQ8ceNOhoa+XC8HfMJm81x1q63glV179oBMLVhpQYEiQKzy0VNtZWLs9OT53s6X3qrxPHX+bSyNVNgyujV8lvrDXG2vZ/7oWig64nAY0hwZCCgIRwUGBJRSGbvp6cHH91R33078ODTyNOnXqPxcRl88ibX5wuBJuP5x2BVhop2PwuBA01kn2tJo4HtxfL5DIzZ7+/8MHrOx7tcMQ3I9dwnWKvF+kfTdlVEc/10f59A0HAgMEui90xgxvTLn8u+9SYhXUnNX60smr7z7Jx3wG8UOSZhUI4spJTrGwo0lssZxVSQlOdZGrJYyzpks4qlvLBWhWMHOgb7Mfsq4PfXOvx+bwgk/WxSwrfUwRNQSgAh7oCFB3N1xNllrMK04A5V7PLMOOvCSFMgFzJl6u2Jl8Gx9XkCppSWdEWNWiPGZy9XmIs6WJKKHuasq+p3qlkOwhz9B54dnbOkorOR0yG9gZJ3fP5cNTm4J4Akws+FyfKOK5GCFAatm/T4ObmB7RWxt74k9hrC0LVtLwwmw2FwyY8323hK2iLGnz2U4lMTiHvR04IGiqLxbrS7x/np3NJozoEmcTFTLTz2U7bivTcXNSsFxWHeyyGE2XGZ7x/j7WGyhA0W3e/LU58eiY1N+0IgLc++or1VLLb6hz6MmPGe/M2NFTBzIpH3lYoX6MQhC1NkzV/p2Jp5JX6eP+vn7wxsJnEXXUVnL6T59K7J/u2tR96365oey7nVQTKnsDzNFr5hETBq3ZmbrB47cS5M2+PdTbHmJpL89+OGbv3dLc81n/kWLih+yDhnTGtEcpeXXHSUz/OJ64M3/ojMS3BUw9rI2BsIUxBsLYyEJYC1nNuqawpARrwtwDgHxTwbTT5CxY9AAAALnpUWHRjcmVhdGUtZGF0ZQAAeNozMjCw0DWw0DUyCTEwsDIyszIw0jUwtTIwAABB3gURQfNnBAAAAC56VFh0bW9kaWZ5LWRhdGUAAHjaMzIwsNA1sNA1MggxNLMyNLYyNtM1MLUyMAAAQgUFF56jVzIAAAAASUVORK5CYII%3D"; var CHECK_IMAGE =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/gD+AP7rGNSCAAAACXBIWXMAAABIAAAASABGyWs+AAAACXZwQWcAAAAQAAAAEABcxq3DAAADKklEQVQ4y32TS2hcZRiGn/8/Z87MNNc2zczEmptO0jSXagJtXCjWhhSEXpCI4EYENy6KG8FFBYtgEbzQ4k5QqNp2VyMtJVGpRU0tGDNoQxvrmCbkMslkSJrJXM6cOef8v4ukQqX4wbP5eL/327wv/M/Em+qNeFO9ASDEwzUPrM+fP8dqOhXqeGJ/f21ddCAYCsfRyFLJvru2mvnh9mTil8am1uJLQ8ceNOhoa+XC8HfMJm81x1q63glV179oBMLVhpQYEiQKzy0VNtZWLs9OT53s6X3qrxPHX+bSyNVNgyujV8lvrDXG2vZ/7oWig64nAY0hwZCCgIRwUGBJRSGbvp6cHH91R33078ODTyNOnXqPxcRl88ibX5wuBJuP5x2BVhop2PwuBA01kn2tJo4HtxfL5DIzZ7+/8MHrOx7tcMQ3I9dwnWKvF+kfTdlVEc/10f59A0HAgMEui90xgxvTLn8u+9SYhXUnNX60smr7z7Jx3wG8UOSZhUI4spJTrGwo0lssZxVSQlOdZGrJYyzpks4qlvLBWhWMHOgb7Mfsq4PfXOvx+bwgk/WxSwrfUwRNQSgAh7oCFB3N1xNllrMK04A5V7PLMOOvCSFMgFzJl6u2Jl8Gx9XkCppSWdEWNWiPGZy9XmIs6WJKKHuasq+p3qlkOwhz9B54dnbOkorOR0yG9gZJ3fP5cNTm4J4Akws+FyfKOK5GCFAatm/T4ObmB7RWxt74k9hrC0LVtLwwmw2FwyY8323hK2iLGnz2U4lMTiHvR04IGiqLxbrS7x/np3NJozoEmcTFTLTz2U7bivTcXNSsFxWHeyyGE2XGZ7x/j7WGyhA0W3e/LU58eiY1N+0IgLc++or1VLLb6hz6MmPGe/M2NFTBzIpH3lYoX6MQhC1NkzV/p2Jp5JX6eP+vn7wxsJnEXXUVnL6T59K7J/u2tR96365oey7nVQTKnsDzNFr5hETBq3ZmbrB47cS5M2+PdTbHmJpL89+OGbv3dLc81n/kWLih+yDhnTGtEcpeXXHSUz/OJ64M3/ojMS3BUw9rI2BsIUxBsLYyEJYC1nNuqawpARrwtwDgHxTwbTT5CxY9AAAALnpUWHRjcmVhdGUtZGF0ZQAAeNozMjCw0DWw0DUyCTEwsDIyszIw0jUwtTIwAABB3gURQfNnBAAAAC56VFh0bW9kaWZ5LWRhdGUAAHjaMzIwsNA1sNA1MggxNLMyNLYyNtM1MLUyMAAAQgUFF56jVzIAAAAASUVORK5CYII%3D';
$(document).ready(function () {
$(document).ready(function() {
if (window.location.host.match(/apollo\.rip|redacted\.ch|passtheheadphones\.me|lztr\.(us|me)|mutracker\.org|notwhat\.cd/)) { if (window.location.host.match(/apollo\.rip|redacted\.ch|passtheheadphones\.me|lztr\.(us|me)|mutracker\.org|notwhat\.cd/)) {
LOGGER.info("Gazelle site detected"); LOGGER.info('Gazelle site detected');
gazellePageHandler(); gazellePageHandler();
} else if (window.location.host.match(/avaxhome\.ws/)) { } else if (window.location.host.match(/avaxhome\.ws/)) {
avaxHomePageHandler(); avaxHomePageHandler();
} }
}); });
function avaxHomePageHandler() { function avaxHomePageHandler() {
// Find artist and release titles // Find artist and release titles
var artistName = ""; let artistName = '';
var releaseName = ""; let releaseName = '';
var m = $('div.title h1').text().match(/(.*) (?:-|) (.*)( \(\d{4}\))?/); let m = $('div.title h1')
.text()
.match(/(.*) (?:-|) (.*)( \(\d{4}\))?/);
if (m) { if (m) {
artistName = m[1]; artistName = m[1];
releaseName = m[2]; releaseName = m[2];
} }
if (artistName == "VA") artistName = "Various Artists"; if (artistName == 'VA') artistName = 'Various Artists';
// Find and analyze EAC log // Find and analyze EAC log
$('div.spoiler').filter(function () { $('div.spoiler')
return $(this).find('a').text().match(/(EAC|log)/i); .filter(function() {
return $(this)
.find('a')
.text()
.match(/(EAC|log)/i);
}) })
.find('div') .find('div')
.each(function () { .each(function() {
let $eacLog = $(this);
var $eacLog = $(this); let discs = analyze_log_files($eacLog);
var discs = analyze_log_files($eacLog);
// Check and display // Check and display
check_and_display_discs(artistName, releaseName, discs, check_and_display_discs(
function (mb_toc_numbers, discid, discNumber) { artistName,
$eacLog.parents('div.spoiler').prevAll('div.center:first').append('<br /><strong>' + (discs.length > 1 ? 'Disc ' + discNumber + ': ' : '' ) + 'MB DiscId </strong><span id="' + discid + '" />'); releaseName,
discs,
function(mb_toc_numbers, discid, discNumber) {
$eacLog
.parents('div.spoiler')
.prevAll('div.center:first')
.append(
`<br /><strong>${discs.length > 1 ? `Disc ${discNumber}: ` : ''}MB DiscId </strong><span id="${discid}" />`
);
}, },
function (mb_toc_numbers, discid, discNumber, found) { function(mb_toc_numbers, discid, discNumber, found) {
var url = computeAttachURL(mb_toc_numbers, artistName, releaseName); let url = computeAttachURL(mb_toc_numbers, artistName, releaseName);
var html = '<a href="' + url + '">' + discid + '</a>'; let html = `<a href="${url}">${discid}</a>`;
if (found) { if (found) {
html = html + '<img src="' + CHECK_IMAGE + '" />'; html = `${html}<img src="${CHECK_IMAGE}" />`;
} }
$('#' + discid.replace('.', '\\.')).html(html); $(`#${discid.replace('.', '\\.')}`).html(html);
} }
); );
}); });
} }
function gazellePageHandler() { function gazellePageHandler() {
let serverHost = window.location.host;
var serverHost = window.location.host;
// Determine Artist name and Release title // Determine Artist name and Release title
var titleAndArtists = $("#content div.thin h2:eq(0)").text(); let titleAndArtists = $('#content div.thin h2:eq(0)').text();
var pattern = /(.*) - (.*) \[.*\] \[.*/; let pattern = /(.*) - (.*) \[.*\] \[.*/;
var artistName, releaseName; let artistName, releaseName;
if (m = titleAndArtists.match(pattern)) { if ((m = titleAndArtists.match(pattern))) {
artistName = m[1]; artistName = m[1];
releaseName = m[2]; releaseName = m[2];
} }
LOGGER.debug("artist:", artistName, "- releaseName:", releaseName); LOGGER.debug('artist:', artistName, '- releaseName:', releaseName);
// Parse each torrent // Parse each torrent
$('tr.group_torrent').filter(function () { $('tr.group_torrent')
return $(this).attr("id"); .filter(function() {
}).each(function () { return $(this).attr('id');
var torrentInfo = $(this).next();
$(torrentInfo).find('a')
// Only investigate the ones with a log
.filter(function (index) {
return $(this).text().match(/View\s+Log/i);
}) })
.each(function () { .each(function() {
LOGGER.debug("Log link", this); let torrentInfo = $(this).next();
if ($(this).attr("onclick").match(/show_logs/)) {
$(torrentInfo)
.find('a')
// Only investigate the ones with a log
.filter(function(index) {
return $(this)
.text()
.match(/View\s+Log/i);
})
.each(function() {
LOGGER.debug('Log link', this);
if (
$(this)
.attr('onclick')
.match(/show_logs/)
) {
if (window.location.host.match(/apollo/)) { if (window.location.host.match(/apollo/)) {
LOGGER.debug("Apollo"); LOGGER.debug('Apollo');
var logAction = 'viewlog'; var logAction = 'viewlog';
} else if (window.location.host.match(/redacted|passtheheadphones/)){ } else if (window.location.host.match(/redacted|passtheheadphones/)) {
LOGGER.debug("RED"); LOGGER.debug('RED');
var logAction = 'loglist'; var logAction = 'loglist';
} }
} }
// LzTR // LzTR
else if ($(this).attr("onclick").match(/get_log/)) { else if (
LOGGER.debug("LzTR"); $(this)
.attr('onclick')
.match(/get_log/)
) {
LOGGER.debug('LzTR');
var logAction = 'log_ajax'; var logAction = 'log_ajax';
} }
// NotWhat.CD // NotWhat.CD
else if ($(this).attr("onclick").match(/show_log/)) { else if (
LOGGER.debug("NotWhat.CD"); $(this)
.attr('onclick')
.match(/show_log/)
) {
LOGGER.debug('NotWhat.CD');
var logAction = 'viewlog'; var logAction = 'viewlog';
} else { } else {
return true; return true;
} }
var targetContainer = $(this).parents(".linkbox"); let targetContainer = $(this).parents('.linkbox');
var torrentId = /(show_logs|get_log|show_log)\('(\d+)/.exec($(this).attr('onclick'))[2]; let torrentId = /(show_logs|get_log|show_log)\('(\d+)/.exec($(this).attr('onclick'))[2];
var logUrl = '/torrents.php?action=' + logAction + '&torrentid=' + torrentId; let logUrl = `/torrents.php?action=${logAction}&torrentid=${torrentId}`;
LOGGER.info("Log URL: ", logUrl); LOGGER.info('Log URL: ', logUrl);
LOGGER.debug("targetContainer: ", targetContainer); LOGGER.debug('targetContainer: ', targetContainer);
// Get log content // Get log content
$.get(logUrl, $.get(logUrl, function(data) {
function (data) { LOGGER.debug('Log content', $(data).find('pre'));
LOGGER.debug("Log content", $(data).find('pre')); let discs = analyze_log_files($(data).find('pre'));
var discs = analyze_log_files($(data).find('pre')); LOGGER.debug('Number of disc found', discs.length);
LOGGER.debug("Number of disc found", discs.length); check_and_display_discs(
check_and_display_discs(artistName, releaseName, discs, artistName,
function (mb_toc_numbers, discid, discNumber) { releaseName,
targetContainer.append('<br /><strong>' + (discs.length > 1 ? 'Disc ' + discNumber + ': ' : '' ) + 'MB DiscId: </strong><span id="' + torrentId + '_disc' + discNumber + '" />'); discs,
function(mb_toc_numbers, discid, discNumber) {
targetContainer.append(
`<br /><strong>${
discs.length > 1 ? `Disc ${discNumber}: ` : ''
}MB DiscId: </strong><span id="${torrentId}_disc${discNumber}" />`
);
}, },
function (mb_toc_numbers, discid, discNumber, found) { function(mb_toc_numbers, discid, discNumber, found) {
var url = computeAttachURL(mb_toc_numbers, artistName, releaseName); let url = computeAttachURL(mb_toc_numbers, artistName, releaseName);
var html = '<a href="' + url + '">' + discid + '</a>'; let html = `<a href="${url}">${discid}</a>`;
if (found) { if (found) {
html = html + '<img src="' + CHECK_IMAGE + '" />'; html = `${html}<img src="${CHECK_IMAGE}" />`;
} }
LOGGER.debug('#' + torrentId + '_disc' + discNumber); LOGGER.debug(`#${torrentId}_disc${discNumber}`);
$('#' + torrentId + '_disc' + discNumber).html(html); $(`#${torrentId}_disc${discNumber}`).html(html);
}
);
}
);
} }
); );
}); });
});
});
} }
// Common functions // Common functions
function computeAttachURL(mb_toc_numbers, artistName, releaseName) { function computeAttachURL(mb_toc_numbers, artistName, releaseName) {
var url = 'http://musicbrainz.org/cdtoc/attach' let url = `${'http://musicbrainz.org/cdtoc/attach' + '?toc='}${mb_toc_numbers.join('%20')}&artist-name=${encodeURIComponent(
+ '?toc=' + mb_toc_numbers.join("%20") artistName
+ '&artist-name=' + encodeURIComponent(artistName) )}&release-name=${encodeURIComponent(releaseName)}`;
+ '&release-name=' + encodeURIComponent(releaseName);
return url; return url;
} }
function analyze_log_files(log_files) { function analyze_log_files(log_files) {
var discs = []; let discs = [];
$.each(log_files, function (i, log_file) { $.each(log_files, function(i, log_file) {
var discsInLog = MBDiscid.log_input_to_entries($(log_file).text()); let discsInLog = MBDiscid.log_input_to_entries($(log_file).text());
for (var i = 0; i < discsInLog.length; i++) { for (var i = 0; i < discsInLog.length; i++) {
discs.push(discsInLog[i]); discs.push(discsInLog[i]);
} }
}); });
// Remove dupes discs // Remove dupes discs
var keys = new Object(); let keys = new Object();
var uniqueDiscs = new Array(); let uniqueDiscs = new Array();
for (var i = 0; i < discs.length; i++) { for (let i = 0; i < discs.length; i++) {
var discid = MBDiscid.calculate_mb_discid(discs[i]); let discid = MBDiscid.calculate_mb_discid(discs[i]);
if (discid in keys) { if (discid in keys) {
continue; continue;
} else { } else {
@ -195,26 +222,24 @@ function analyze_log_files(log_files) {
} }
function check_and_display_discs(artistName, releaseName, discs, displayDiscHandler, displayResultHandler) { function check_and_display_discs(artistName, releaseName, discs, displayDiscHandler, displayResultHandler) {
// For each disc, check if it's in MusicBrainz database // For each disc, check if it's in MusicBrainz database
for (var i = 0; i < discs.length; i++) { for (let i = 0; i < discs.length; i++) {
var entries = discs[i]; let entries = discs[i];
var discNumber = i + 1; let discNumber = i + 1;
if (entries.length > 0) { if (entries.length > 0) {
let mb_toc_numbers = MBDiscid.calculate_mb_toc_numbers(entries);
var mb_toc_numbers = MBDiscid.calculate_mb_toc_numbers(entries); let discid = MBDiscid.calculate_mb_discid(entries);
var discid = MBDiscid.calculate_mb_discid(entries); LOGGER.info(`Computed discid :${discid}`);
LOGGER.info("Computed discid :" + discid);
displayDiscHandler(mb_toc_numbers, discid, discNumber); displayDiscHandler(mb_toc_numbers, discid, discNumber);
// Now check if this discid is known by MusicBrainz // Now check if this discid is known by MusicBrainz
(function (discid, discNumber, mb_toc_numbers) { (function(discid, discNumber, mb_toc_numbers) {
var query = $.getJSON('//musicbrainz.org/ws/2/discid/' + discid + '?cdstubs=no'); let query = $.getJSON(`//musicbrainz.org/ws/2/discid/${discid}?cdstubs=no`);
query.done(function (data) { query.done(function(data) {
var existsInMusicbrainz = !('error' in data) && data.error != "Not found"; let existsInMusicbrainz = !('error' in data) && data.error != 'Not found';
displayResultHandler(mb_toc_numbers, discid, discNumber, existsInMusicbrainz); displayResultHandler(mb_toc_numbers, discid, discNumber, existsInMusicbrainz);
}); });
query.fail(function () { query.fail(function() {
// If discid is not found, the webservice returns a 404 http code // If discid is not found, the webservice returns a 404 http code
displayResultHandler(mb_toc_numbers, discid, discNumber, false); displayResultHandler(mb_toc_numbers, discid, discNumber, false);
}); });
@ -229,30 +254,29 @@ function check_and_display_discs(artistName, releaseName, discs, displayDiscHand
// Copyright 2010, kolen // Copyright 2010, kolen
// Released under the MIT License // Released under the MIT License
var MBDiscid = (function () { var MBDiscid = (function() {
this.SECTORS_PER_SECOND = 75; this.SECTORS_PER_SECOND = 75;
this.PREGAP = 150; this.PREGAP = 150;
this.DATA_TRACK_GAP = 11400; this.DATA_TRACK_GAP = 11400;
this.toc_entry_matcher = new RegExp( this.toc_entry_matcher = new RegExp(
"^\\s*" + '^\\s*' +
"(\\d+)" + // 1 - track number '(\\d+)' + // 1 - track number
"\\s*\\|\\s*" + '\\s*\\|\\s*' +
"([0-9:.]+)" + // 2 - time start '([0-9:.]+)' + // 2 - time start
"\\s*\\|\\s*" + '\\s*\\|\\s*' +
"([0-9:.]+)" + // 3 - time length '([0-9:.]+)' + // 3 - time length
"\\s*\\|\\s*" + '\\s*\\|\\s*' +
"(\\d+)" + // 4 - start sector '(\\d+)' + // 4 - start sector
"\\s*\\|\\s*" + '\\s*\\|\\s*' +
"(\\d+)" + // 5 - end sector '(\\d+)' + // 5 - end sector
"\\s*$" '\\s*$'
); );
this.log_input_to_entries = function (text) { this.log_input_to_entries = function(text) {
var discs = []; let discs = [];
var entries = []; var entries = [];
$.each(text.split("\n"), function (index, value) { $.each(text.split('\n'), function(index, value) {
var m = toc_entry_matcher.exec(value); let m = toc_entry_matcher.exec(value);
if (m) { if (m) {
// New disc // New disc
if (parseInt(m[1], 10) == 1) { if (parseInt(m[1], 10) == 1) {
@ -268,11 +292,11 @@ var MBDiscid = (function () {
discs.push(entries); discs.push(entries);
} }
for (var i = 0; i < discs.length; i++) { for (let i = 0; i < discs.length; i++) {
var entries = discs[i]; var entries = discs[i];
var layout_type = get_layout_type(entries); let layout_type = get_layout_type(entries);
var entries_audio; var entries_audio;
if (layout_type == "with_data") { if (layout_type == 'with_data') {
entries_audio = entries.slice(0, entries.length - 1); entries_audio = entries.slice(0, entries.length - 1);
} else { } else {
entries_audio = entries; entries_audio = entries;
@ -282,15 +306,15 @@ var MBDiscid = (function () {
return discs; return discs;
}; };
this.get_layout_type = function (entries) { this.get_layout_type = function(entries) {
var type = "standard"; let type = 'standard';
for (var i = 0; i < entries.length - 1; i++) { for (let i = 0; i < entries.length - 1; i++) {
var gap = parseInt(entries[i + 1][4], 10) - parseInt(entries[i][5], 10) - 1; let gap = parseInt(entries[i + 1][4], 10) - parseInt(entries[i][5], 10) - 1;
if (gap != 0) { if (gap != 0) {
if (i == entries.length - 2 && gap == DATA_TRACK_GAP) { if (i == entries.length - 2 && gap == DATA_TRACK_GAP) {
type = "with_data"; type = 'with_data';
} else { } else {
type = "unknown"; type = 'unknown';
break; break;
} }
} }
@ -298,84 +322,91 @@ var MBDiscid = (function () {
return type; return type;
}; };
this.calculate_mb_toc_numbers = function (entries) { this.calculate_mb_toc_numbers = function(entries) {
if (entries.length == 0) { if (entries.length == 0) {
return null; return null;
} }
var leadout_offset = parseInt(entries[entries.length - 1][5], 10) + PREGAP + 1; let leadout_offset = parseInt(entries[entries.length - 1][5], 10) + PREGAP + 1;
var offsets = $.map(entries, function (entry) { let offsets = $.map(entries, function(entry) {
return parseInt(entry[4], 10) + PREGAP; return parseInt(entry[4], 10) + PREGAP;
}) });
return [1, entries.length, leadout_offset].concat(offsets); return [1, entries.length, leadout_offset].concat(offsets);
}; };
this.calculate_cddb_id = function (entries) { this.calculate_cddb_id = function(entries) {
var sum_of_digits = function (n) { let sum_of_digits = function(n) {
var sum = 0; let sum = 0;
while (n > 0) { while (n > 0) {
sum = sum + (n % 10); sum = sum + (n % 10);
n = Math.floor(n / 10); n = Math.floor(n / 10);
} }
return sum; return sum;
} };
var decimalToHexString = function (number) { let decimalToHexString = function(number) {
if (number < 0) { if (number < 0) {
number = 0xFFFFFFFF + number + 1; number = 0xffffffff + number + 1;
} }
return number.toString(16).toUpperCase(); return number.toString(16).toUpperCase();
} };
var length_seconds = Math.floor((parseInt(entries[entries.length - 1][5], 10) - parseInt(entries[0][4], 10) + 1) / SECTORS_PER_SECOND); let length_seconds = Math.floor(
var checksum = 0; (parseInt(entries[entries.length - 1][5], 10) - parseInt(entries[0][4], 10) + 1) / SECTORS_PER_SECOND
$.each(entries, function (index, entry) { );
let checksum = 0;
$.each(entries, function(index, entry) {
checksum += sum_of_digits(Math.floor((parseInt(entry[4], 10) + PREGAP) / SECTORS_PER_SECOND)); checksum += sum_of_digits(Math.floor((parseInt(entry[4], 10) + PREGAP) / SECTORS_PER_SECOND));
}) });
var xx = checksum % 255; let xx = checksum % 255;
var discid_num = (xx << 24) | (length_seconds << 8) | entries.length; let discid_num = (xx << 24) | (length_seconds << 8) | entries.length;
//return discid_num //return discid_num
return decimalToHexString(discid_num); return decimalToHexString(discid_num);
}; };
this.calculate_mb_discid = function (entries) { this.calculate_mb_discid = function(entries) {
let hex_left_pad = function(input, totalChars) {
var hex_left_pad = function (input, totalChars) { input = `${parseInt(input, 10)
input = '' + parseInt(input, 10).toString(16).toUpperCase(); .toString(16)
var padWith = "0"; .toUpperCase()}`;
let padWith = '0';
if (input.length < totalChars) { if (input.length < totalChars) {
while (input.length < totalChars) { while (input.length < totalChars) {
input = padWith + input; input = padWith + input;
} }
} else { } else {
} }
if (input.length > totalChars) { //if padWith was a multiple character string and num was overpadded if (input.length > totalChars) {
input = input.substring((input.length - totalChars), totalChars); //if padWith was a multiple character string and num was overpadded
input = input.substring(input.length - totalChars, totalChars);
} else { } else {
} }
return input; return input;
}; };
var mb_toc_numbers = calculate_mb_toc_numbers(entries); let mb_toc_numbers = calculate_mb_toc_numbers(entries);
var message = ""; let message = '';
var first_track = mb_toc_numbers[0]; let first_track = mb_toc_numbers[0];
var last_track = mb_toc_numbers[1]; let last_track = mb_toc_numbers[1];
var leadout_offset = mb_toc_numbers[2]; let leadout_offset = mb_toc_numbers[2];
message = message + hex_left_pad(first_track, 2); message = message + hex_left_pad(first_track, 2);
message = message + hex_left_pad(last_track, 2); message = message + hex_left_pad(last_track, 2);
message = message + hex_left_pad(leadout_offset, 8); message = message + hex_left_pad(leadout_offset, 8);
for (var i = 0; i < 99; i++) { for (let i = 0; i < 99; i++) {
var offset = (i + 3 < mb_toc_numbers.length) ? mb_toc_numbers[i + 3] : 0; let offset = i + 3 < mb_toc_numbers.length ? mb_toc_numbers[i + 3] : 0;
message = message + hex_left_pad(offset, 8); message = message + hex_left_pad(offset, 8);
} }
b64pad = "="; b64pad = '=';
var discid = b64_sha1(message); let discid = b64_sha1(message);
discid = discid.replace(/\+/g, ".").replace(/\//g, "_").replace(/=/g, "-"); discid = discid
.replace(/\+/g, '.')
.replace(/\//g, '_')
.replace(/=/g, '-');
return discid; return discid;
}; };

View file

@ -14,38 +14,38 @@
// Definitions: relations-type and corresponding icons we are going to treat // Definitions: relations-type and corresponding icons we are going to treat
var relationsIconsURLs = { var relationsIconsURLs = {
'url': { url: {
"amazon asin": "https://musicbrainz.org/static/images/favicons/amazon-32.png", 'amazon asin': 'https://musicbrainz.org/static/images/favicons/amazon-32.png',
"discogs": "https://musicbrainz.org/static/images/favicons/discogs-32.png", discogs: 'https://musicbrainz.org/static/images/favicons/discogs-32.png',
"wikidata": "https://musicbrainz.org/static/images/favicons/wikidata-32.png", wikidata: 'https://musicbrainz.org/static/images/favicons/wikidata-32.png',
"imdb": "https://musicbrainz.org/static/images/favicons/imdb-32.png", imdb: 'https://musicbrainz.org/static/images/favicons/imdb-32.png',
"creative commons licensed download": "http://creativecommons.org/favicon.ico", 'creative commons licensed download': 'http://creativecommons.org/favicon.ico',
"cover art link": "http://www.cdcovers.cc/favicon.ico", 'cover art link': 'http://www.cdcovers.cc/favicon.ico',
"secondhandsongs": "https://musicbrainz.org/static/images/favicons/secondhandsongs-32.png", secondhandsongs: 'https://musicbrainz.org/static/images/favicons/secondhandsongs-32.png',
"lyrics": "http://www.nomy.nu/img/lyrics-icon.gif", lyrics: 'http://www.nomy.nu/img/lyrics-icon.gif',
"allmusic": "https://musicbrainz.org/static/images/favicons/allmusic-16.png" allmusic: 'https://musicbrainz.org/static/images/favicons/allmusic-16.png'
}, },
'release-group': { 'release-group': {
"single from": "http://www.amaesingtools.com/images/left_arrow_icon.gif" 'single from': 'http://www.amaesingtools.com/images/left_arrow_icon.gif'
}, },
'release': { release: {
"part of set": "http://web.archive.org/web/20060709091901/http://wiki.musicbrainz.org/-/musicbrainz/img/moin-inter.png", 'part of set': 'http://web.archive.org/web/20060709091901/http://wiki.musicbrainz.org/-/musicbrainz/img/moin-inter.png',
"remaster": "http://web.archive.org/web/20060708200714/http://wiki.musicbrainz.org/-/musicbrainz/img/moin-www.png", remaster: 'http://web.archive.org/web/20060708200714/http://wiki.musicbrainz.org/-/musicbrainz/img/moin-www.png'
} }
}; };
var otherDatabasesIconURLs = { var otherDatabasesIconURLs = {
"d-nb.info" : "https://musicbrainz.org/static/images/favicons/dnb-16.png", 'd-nb.info': 'https://musicbrainz.org/static/images/favicons/dnb-16.png',
"www.musik-sammler.de": "https://musicbrainz.org/static/images/favicons/musiksammler-32.png", 'www.musik-sammler.de': 'https://musicbrainz.org/static/images/favicons/musiksammler-32.png',
"www.worldcat.org": "https://musicbrainz.org/static/images/favicons/worldcat-32.png", 'www.worldcat.org': 'https://musicbrainz.org/static/images/favicons/worldcat-32.png',
"rateyourmusic.com": "https://musicbrainz.org/static/images/favicons/rateyourmusic-32.png" 'rateyourmusic.com': 'https://musicbrainz.org/static/images/favicons/rateyourmusic-32.png'
}; };
var incOptions = { var incOptions = {
'release-group': [ 'release-group-rels', 'url-rels' ], 'release-group': ['release-group-rels', 'url-rels'],
'release': [ 'release-rels', 'url-rels', 'discids' ], release: ['release-rels', 'url-rels', 'discids'],
'recording': [ 'work-rels' ], recording: ['work-rels'],
'work': [ 'url-rels' ] work: ['url-rels']
}; };
// prevent JQuery conflicts, see http://wiki.greasespot.net/@grant // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant
@ -53,20 +53,19 @@ this.$ = this.jQuery = jQuery.noConflict(true);
if (!unsafeWindow) unsafeWindow = window; if (!unsafeWindow) unsafeWindow = window;
$(document).ready(function(){ $(document).ready(function() {
// Get pageType (label or artist) // Get pageType (label or artist)
var parent = {}; let parent = {};
var child = {}; let child = {};
if (m = window.location.href.match("\/artist\/(.{36})[^\/]*$")) { if ((m = window.location.href.match('/artist/(.{36})[^/]*$'))) {
parent.type = 'artist'; parent.type = 'artist';
parent.mbid = m[1]; parent.mbid = m[1];
child.type = 'release-group'; child.type = 'release-group';
} else if (m = window.location.href.match("\/(release-group|label)\/(.{36})[^\/]*$")) { } else if ((m = window.location.href.match('/(release-group|label)/(.{36})[^/]*$'))) {
parent.type = m[1]; parent.type = m[1];
parent.mbid = m[2]; parent.mbid = m[2];
child.type = 'release'; child.type = 'release';
} else if (m = window.location.href.match("\/artist/(.{36})\/(releases|recordings|works)")) { } else if ((m = window.location.href.match('/artist/(.{36})/(releases|recordings|works)'))) {
parent.type = 'artist'; parent.type = 'artist';
parent.mbid = m[1]; parent.mbid = m[1];
child.type = m[2].replace(/s$/, ''); child.type = m[2].replace(/s$/, '');
@ -75,13 +74,25 @@ $(document).ready(function(){
return; return;
} }
var mbidRE = /(release|release-group|work)\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/; let mbidRE = /(release|release-group|work)\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/;
// Determine target column // Determine target column
var columnindex = 0; let columnindex = 0;
$("table.tbl tbody tr[class!='subh']").each(function() { $("table.tbl tbody tr[class!='subh']").each(function() {
$(this).children("td").each(function() { $(this)
if ($(this).find("a").attr("href") !== undefined && $(this).find("a").attr("href").match(mbidRE)) { return false; } .children('td')
.each(function() {
if (
$(this)
.find('a')
.attr('href') !== undefined &&
$(this)
.find('a')
.attr('href')
.match(mbidRE)
) {
return false;
}
columnindex++; columnindex++;
}); });
return false; return false;
@ -89,92 +100,106 @@ $(document).ready(function(){
// Set MBID to row in tables to get easiest fastest access // Set MBID to row in tables to get easiest fastest access
$("table.tbl tr[class!='subh']").each(function() { $("table.tbl tr[class!='subh']").each(function() {
var $tr = $(this); let $tr = $(this);
$tr.children("th:eq("+columnindex+")").after("<th style='width: 150px;'>Relationships</th>"); $tr.children(`th:eq(${columnindex})`).after("<th style='width: 150px;'>Relationships</th>");
$tr.children("td:eq("+columnindex+")").after("<td class='relationships'></td>"); $tr.children(`td:eq(${columnindex})`).after("<td class='relationships'></td>");
$(this).find("a").each(function() { $(this)
var href = $(this).attr("href"); .find('a')
if (m = href.match(mbidRE)) { .each(function() {
$tr.attr("id", m[2]); let href = $(this).attr('href');
if ((m = href.match(mbidRE))) {
$tr.attr('id', m[2]);
return false; return false;
} }
}); });
}); });
// Calculate offset for multi-page lists // Calculate offset for multi-page lists
var page = 1; let page = 1;
if (m = window.location.href.match("[\?&]page=([0-9]*)")) { if ((m = window.location.href.match('[?&]page=([0-9]*)'))) {
page = m[1]; page = m[1];
} }
var offset = (page - 1) * 100; let offset = (page - 1) * 100;
// Call the MB webservice // Call the MB webservice
var url = '/ws/2/' + child.type + '?' + parent.type + "=" + parent.mbid + '&inc=' + incOptions[child.type].join("+") + '&limit=100&offset=' + offset; let url = `/ws/2/${child.type}?${parent.type}=${parent.mbid}&inc=${incOptions[child.type].join('+')}&limit=100&offset=${offset}`;
//console.log("MB WS url: " + url); //console.log("MB WS url: " + url);
$.get(url, function(data, textStatus, jqXHR) { $.get(url, function(data, textStatus, jqXHR) {
// Parse each child // Parse each child
$(data).find(child.type).each(function() { $(data)
var mbid = $(this).attr("id"); .find(child.type)
.each(function() {
let mbid = $(this).attr('id');
// URL relationships // URL relationships
$(this).find("relation-list[target-type='url'] relation").each(function() { $(this)
var reltype = $(this).attr("type"); .find("relation-list[target-type='url'] relation")
var target = $(this).children("target").text(); .each(function() {
let reltype = $(this).attr('type');
let target = $(this)
.children('target')
.text();
if (relationsIconsURLs.url.hasOwnProperty(reltype)) { if (relationsIconsURLs.url.hasOwnProperty(reltype)) {
$("#" + mbid + " td.relationships").append( $(`#${mbid} td.relationships`).append(
"<a href='" + target.replace(/'/g,"&apos;") + "'>" + "<img style='max-height: 16px;' src='" + relationsIconsURLs.url[reltype] + "' />&nbsp;" + "</a>" `<a href='${target.replace(/'/g, '&apos;')}'>` +
`<img style='max-height: 16px;' src='${relationsIconsURLs.url[reltype]}' />&nbsp;` +
`</a>`
); );
} } else
else for (var rel in otherDatabasesIconURLs) { for (let rel in otherDatabasesIconURLs) {
if (target.indexOf(rel) != -1 ) { if (target.indexOf(rel) != -1) {
$("#" + mbid + " td.relationships").append( $(`#${mbid} td.relationships`).append(
"<a href='" + target.replace(/'/g,"&apos;") + "'>" + "<img style='max-height: 16px;' src='" + otherDatabasesIconURLs[rel] + "' />&nbsp;" + "</a>" `<a href='${target.replace(/'/g, '&apos;')}'>` +
`<img style='max-height: 16px;' src='${otherDatabasesIconURLs[rel]}' />&nbsp;` +
`</a>`
); );
} }
} }
}); });
// Other relationships // Other relationships
$(this).find("relation-list[target-type!='url']").each(function() { $(this)
var targettype = $(this).attr("target-type").replace("release_group", "release-group"); .find("relation-list[target-type!='url']")
var relations = {}; .each(function() {
let targettype = $(this)
.attr('target-type')
.replace('release_group', 'release-group');
let relations = {};
if (relationsIconsURLs[targettype] === undefined) { if (relationsIconsURLs[targettype] === undefined) {
return; return;
} }
$(this).children("relation").each(function() { $(this)
var reltype = $(this).attr("type"); .children('relation')
var target = $(this).children("target").text(); .each(function() {
var url = (targettype == 'url') ? target : "/" + targettype + "/" + target; let reltype = $(this).attr('type');
let target = $(this)
.children('target')
.text();
let url = targettype == 'url' ? target : `/${targettype}/${target}`;
if (relationsIconsURLs[targettype].hasOwnProperty(reltype)) { if (relationsIconsURLs[targettype].hasOwnProperty(reltype)) {
if (!relations.hasOwnProperty(reltype)) relations[reltype] = [url]; if (!relations.hasOwnProperty(reltype)) relations[reltype] = [url];
else relations[reltype].push(url); else relations[reltype].push(url);
} }
}); });
$.each(relations, function(reltype, urls) { $.each(relations, function(reltype, urls) {
var html = ""; let html = '';
if (urls.length < -1) { if (urls.length < -1) {
html += "<img src='" + relationsIconsURLs[targettype][reltype] + "' />(" + urls.length + ")&nbsp;"; html += `<img src='${relationsIconsURLs[targettype][reltype]}' />(${urls.length})&nbsp;`;
} else { } else {
$.each(urls, function(index, url) { $.each(urls, function(index, url) {
html += "<a href='" + url + "'><img src='" + relationsIconsURLs[targettype][reltype] + "' /></a>&nbsp;"; html += `<a href='${url}'><img src='${relationsIconsURLs[targettype][reltype]}' /></a>&nbsp;`;
}); });
} }
$("#" + mbid + " td.relationships").append(html); $(`#${mbid} td.relationships`).append(html);
}); });
}); });
}); });
}); });
}); });

View file

@ -14,114 +14,149 @@
// prevent JQuery conflicts, see http://wiki.greasespot.net/@grant // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant
this.$ = this.jQuery = jQuery.noConflict(true); this.$ = this.jQuery = jQuery.noConflict(true);
$(document).ready(function () { $(document).ready(function() {
LASTFM_APIKEY = null; LASTFM_APIKEY = null;
// Highlight table rows // Highlight table rows
$('table.tbl tbody tr').hover( $('table.tbl tbody tr').hover(
function () { function() {
$(this).children('td').each(function(){ $(this)
var backgroundColor = $(this).css("backgroundColor"); .children('td')
if (backgroundColor != 'rgb(255, 255, 0)') .each(function() {
$(this).css("backgroundColor", "#ffeea8"); let backgroundColor = $(this).css('backgroundColor');
if (backgroundColor != 'rgb(255, 255, 0)') $(this).css('backgroundColor', '#ffeea8');
}); });
}, },
function () { function() {
$(this).children('td').each(function(){ $(this)
var backgroundColor = $(this).css("backgroundColor"); .children('td')
if (backgroundColor != 'rgb(255, 255, 0)') .each(function() {
$(this).css("backgroundColor", ""); let backgroundColor = $(this).css('backgroundColor');
if (backgroundColor != 'rgb(255, 255, 0)') $(this).css('backgroundColor', '');
}); });
} }
); );
var re; let re;
// Top tracks from Lastfm // Top tracks from Lastfm
re = new RegExp("musicbrainz\.org\/artist\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$","i"); re = new RegExp('musicbrainz.org/artist/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})$', 'i');
if (LASTFM_APIKEY && window.location.href.match(re)) { if (LASTFM_APIKEY && window.location.href.match(re)) {
$('h2.discography').before('<h2 class="toptracks">Top Last.fm recordings</h2><ul class="toptracks" />'); $('h2.discography').before('<h2 class="toptracks">Top Last.fm recordings</h2><ul class="toptracks" />');
var mbid = window.location.href.match(re)[1]; var mbid = window.location.href.match(re)[1];
var toptracks = $.getJSON('http://ws.audioscrobbler.com/2.0/?method=artist.gettoptracks&mbid='+mbid+'&api_key='+LASTFM_APIKEY+'&format=json', function(data) { let toptracks = $.getJSON(
$.each(data.toptracks.track, function (index, track) { `http://ws.audioscrobbler.com/2.0/?method=artist.gettoptracks&mbid=${mbid}&api_key=${LASTFM_APIKEY}&format=json`,
function(data) {
$.each(data.toptracks.track, function(index, track) {
if (index >= 5) return true; if (index >= 5) return true;
var url = track.mbid ? '/recording/'+track.mbid : track.url; let url = track.mbid ? `/recording/${track.mbid}` : track.url;
$('ul.toptracks').append('<li><a href="'+url+'">'+track.name+'</a></li>'); $('ul.toptracks').append(`<li><a href="${url}">${track.name}</a></li>`);
});
}); });
} }
);
}
// Fix for http://tickets.musicbrainz.org/browse/MBS-750 // Fix for http://tickets.musicbrainz.org/browse/MBS-750
re = new RegExp("musicbrainz\.org\/release\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})","i"); re = new RegExp('musicbrainz.org/release/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})', 'i');
if (window.location.href.match(re)) { if (window.location.href.match(re)) {
if ($("table.medium thead").length == 1) { if ($('table.medium thead').length == 1) {
var text = $.trim($("table.medium thead").text()); let text = $.trim($('table.medium thead').text());
if (text.match(/ 1$/)) { if (text.match(/ 1$/)) {
$("table.medium thead a").text(text.replace(/ 1$/, '')); $('table.medium thead a').text(text.replace(/ 1$/, ''));
} }
} }
} }
// Better fix for http://tickets.musicbrainz.org/browse/MBS-1943 // Better fix for http://tickets.musicbrainz.org/browse/MBS-1943
re = new RegExp("musicbrainz\.org\/(artist|release-group|release|recording|work|label)\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})","i"); re = new RegExp(
'musicbrainz.org/(artist|release-group|release|recording|work|label)/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})',
'i'
);
if (window.location.href.match(re)) { if (window.location.href.match(re)) {
$("#sidebar h2:contains('Rating')").before($("#sidebar h2:contains('External links')")); $("#sidebar h2:contains('Rating')").before($("#sidebar h2:contains('External links')"));
var pageHasRGLinks = $("#sidebar h2:contains('Release group external links')").length > 0; let pageHasRGLinks = $("#sidebar h2:contains('Release group external links')").length > 0;
$("#sidebar h2:contains('Rating')").before( $("#sidebar h2:contains('Rating')").before(
$("#sidebar h2:contains('External links')").nextAll("ul.external_links").filter( function() { $("#sidebar h2:contains('External links')")
.nextAll('ul.external_links')
.filter(function() {
return !pageHasRGLinks || $(this).nextAll("h2:contains('Release group external links')").length > 0; return !pageHasRGLinks || $(this).nextAll("h2:contains('Release group external links')").length > 0;
})); })
);
$("#sidebar h2:contains('Rating')").before($("#sidebar h2:contains('Release group external links')")); $("#sidebar h2:contains('Rating')").before($("#sidebar h2:contains('Release group external links')"));
$("#sidebar h2:contains('Rating')").before($("#sidebar h2:contains('Release group external links')").nextAll("ul.external_links")); $("#sidebar h2:contains('Rating')").before($("#sidebar h2:contains('Release group external links')").nextAll('ul.external_links'));
} }
// Remove the affiliate section // Remove the affiliate section
re = new RegExp("musicbrainz\.org\/(artist|release-group|release|recording|work|label)\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})","i"); re = new RegExp(
'musicbrainz.org/(artist|release-group|release|recording|work|label)/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})',
'i'
);
if (window.location.href.match(re)) { if (window.location.href.match(re)) {
$('#sidebar-affiliates').remove(); $('#sidebar-affiliates').remove();
} }
// Batch merge -> open in a new tab/windows // Batch merge -> open in a new tab/windows
re = new RegExp("musicbrainz\.org\/artist\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/(recordings|releases|works)","i"); re = new RegExp(
'musicbrainz.org/artist/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/(recordings|releases|works)',
'i'
);
if (window.location.href.match(re)) { if (window.location.href.match(re)) {
$("form").filter(function() { $('form')
return $(this).prop("action").match("merge_queue"); .filter(function() {
}).attr("target", "_blank"); return $(this)
.prop('action')
.match('merge_queue');
})
.attr('target', '_blank');
} }
// Modify link to edits: remove " - <Edit type>" from the link "Edit XXXX - <Edit type>" // Modify link to edits: remove " - <Edit type>" from the link "Edit XXXX - <Edit type>"
re = new RegExp("musicbrainz\.org/.*/(open_)?edits","i"); re = new RegExp('musicbrainz.org/.*/(open_)?edits', 'i');
if (window.location.href.match(re)) { if (window.location.href.match(re)) {
$("div.edit-description ~ h2").each(function() { $('div.edit-description ~ h2').each(function() {
var parts = $(this).find("a").text().split(" - "); let parts = $(this)
$(this).find("a").text(parts[0]); .find('a')
$(this).append(" - " + parts[1]); .text()
.split(' - ');
$(this)
.find('a')
.text(parts[0]);
$(this).append(` - ${parts[1]}`);
}); });
} }
// Add direct link to cover art tab for Add cover art edits // Add direct link to cover art tab for Add cover art edits
re = new RegExp("musicbrainz\.org/(.*/(open_)?edits|edit\/\d+)","i"); re = new RegExp('musicbrainz.org/(.*/(open_)?edits|edit/d+)', 'i');
if (window.location.href.match(re)) { if (window.location.href.match(re)) {
$("div.edit-description ~ h2:contains('cover art')").each(function() { $("div.edit-description ~ h2:contains('cover art')").each(function() {
$editdetails = $(this).parents('.edit-header').siblings('.edit-details'); $editdetails = $(this)
mbid = $editdetails.find("a[href*='musicbrainz.org/release/']").attr('href').match(/\/release\/(.{36})/)[1]; .parents('.edit-header')
$editdetails.find('tbody td.edit-cover-art').after("<tr><th span='2'><a href='/release/"+mbid+"/cover-art'>See all artworks for this release</a></th></tr>"); .siblings('.edit-details');
mbid = $editdetails
.find("a[href*='musicbrainz.org/release/']")
.attr('href')
.match(/\/release\/(.{36})/)[1];
$editdetails
.find('tbody td.edit-cover-art')
.after(`<tr><th span='2'><a href='/release/${mbid}/cover-art'>See all artworks for this release</a></th></tr>`);
}); });
} }
// Embed Youtube videos // Embed Youtube videos
re = new RegExp("musicbrainz\.org\/recording\/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$","i"); re = new RegExp('musicbrainz.org/recording/[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$', 'i');
if (window.location.href.match(re)) { if (window.location.href.match(re)) {
var $youtube_link = $('#sidebar li.youtube-favicon a'); let $youtube_link = $('#sidebar li.youtube-favicon a');
if ($youtube_link.length > 0) { if ($youtube_link.length > 0) {
var youtube_id = $youtube_link.prop("href").match(/http:\/\/www\.youtube\.com\/watch\?v=(.*)/)[1]; let youtube_id = $youtube_link.prop('href').match(/http:\/\/www\.youtube\.com\/watch\?v=(.*)/)[1];
$("table.details").width("60%"); $('table.details').width('60%');
$("h2:contains('Relationships')").after('<iframe width="360" height="275" frameborder="0" style="float: right;" src="https://www.youtube.com/embed/'+ youtube_id +'?rel=0" allowfullscreen=""></iframe>'); $("h2:contains('Relationships')").after(
`<iframe width="360" height="275" frameborder="0" style="float: right;" src="https://www.youtube.com/embed/${youtube_id}?rel=0" allowfullscreen=""></iframe>`
);
} }
} }
// When attaching CDTOC, autoselect artist when there's only one result // When attaching CDTOC, autoselect artist when there's only one result
re = new RegExp("musicbrainz\.org\/cdtoc\/attach.*&filter-artist.query=.*","i"); re = new RegExp('musicbrainz.org/cdtoc/attach.*&filter-artist.query=.*', 'i');
if (window.location.href.match(re)) { if (window.location.href.match(re)) {
$artists = $('ul.radio-list li'); $artists = $('ul.radio-list li');
if ($artists.length == 1) { if ($artists.length == 1) {
@ -130,41 +165,46 @@ $(document).ready(function () {
} }
// Highlight Year in ISRCs codes // Highlight Year in ISRCs codes
re = new RegExp("musicbrainz\.org\/artist\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/recordings","i"); re = new RegExp('musicbrainz.org/artist/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/recordings', 'i');
if (window.location.href.match(re)) { if (window.location.href.match(re)) {
var isrcColNo; // = ($("#content table.tbl thead th:eq(2)").text() == "Artist") ? 3 : 2; let isrcColNo; // = ($("#content table.tbl thead th:eq(2)").text() == "Artist") ? 3 : 2;
$("#content table.tbl thead th").each(function(index, th) { $('#content table.tbl thead th').each(function(index, th) {
if ($(th).text() == "ISRCs") { if ($(th).text() == 'ISRCs') {
isrcColNo = index; isrcColNo = index;
return false; return false;
} }
}); });
var reg = new RegExp("([A-Z]{2}[A-Z0-9]{3}[0-9]{7})"); let reg = new RegExp('([A-Z]{2}[A-Z0-9]{3}[0-9]{7})');
$("#content table.tbl tbody tr").each(function() { $('#content table.tbl tbody tr').each(function() {
var $td = $(this).find("td:eq("+isrcColNo+")"); let $td = $(this).find(`td:eq(${isrcColNo})`);
var isrcs = $td.text().trim().split("\n<br>\n"); let isrcs = $td
var newHTML = ""; .text()
.trim()
.split('\n<br>\n');
let newHTML = '';
$.each(isrcs, function(index, isrc) { $.each(isrcs, function(index, isrc) {
isrc = isrc.trim(); isrc = isrc.trim();
newHTML += "<a href='/isrc/" + isrc + "'><code>"; newHTML += `<a href='/isrc/${isrc}'><code>`;
newHTML += isrc.substring(0,5) + "<b>" + isrc.substring(5,7) + "</b>" + isrc.substring(7); newHTML += `${isrc.substring(0, 5)}<b>${isrc.substring(5, 7)}</b>${isrc.substring(7)}`;
newHTML += "</code></a>"; newHTML += '</code></a>';
if (index != isrcs.length-1) { newHTML += "<br>" }; if (index != isrcs.length - 1) {
newHTML += '<br>';
}
}); });
$td.html(newHTML); $td.html(newHTML);
}); });
} }
// Display ISRCs and recording comment on release tracklisting // Display ISRCs and recording comment on release tracklisting
re = new RegExp("musicbrainz\.org\/release\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})#?$","i"); re = new RegExp('musicbrainz.org/release/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})#?$', 'i');
if (window.location.href.match(re)) { if (window.location.href.match(re)) {
var ISRC_COLUMN_POSITION = 2; let ISRC_COLUMN_POSITION = 2;
var mbid = window.location.href.match(re)[1]; var mbid = window.location.href.match(re)[1];
// Get tracks data from webservice // Get tracks data from webservice
var wsurl = "/ws/2/release/" + mbid + "?inc=isrcs+recordings"; let wsurl = `/ws/2/release/${mbid}?inc=isrcs+recordings`;
$.getJSON(wsurl, function(data) { $.getJSON(wsurl, function(data) {
// Store tracks data from webservice in a hash table // Store tracks data from webservice in a hash table
var tracks = {}; let tracks = {};
$.each(data.media, function(index, medium) { $.each(data.media, function(index, medium) {
$.each(medium.tracks, function(i, track) { $.each(medium.tracks, function(i, track) {
tracks[track.id] = track; tracks[track.id] = track;
@ -173,16 +213,20 @@ $(document).ready(function () {
// Different behavior depending on the number of mediums // Different behavior depending on the number of mediums
if ($('table.medium').length <= 10) { if ($('table.medium').length <= 10) {
// All mediums are already displayed: handle them now // All mediums are already displayed: handle them now
$("table.medium").each(function() { $('table.medium').each(function() {
handleMedium($(this), tracks) handleMedium($(this), tracks);
}); });
} else { } else {
// Each medium will be handled when it's loaded // Each medium will be handled when it's loaded
var HANDLED_ATTRIBUTE = 'ui_enh_isrcs_handled'; let HANDLED_ATTRIBUTE = 'ui_enh_isrcs_handled';
$('table.medium').attr(HANDLED_ATTRIBUTE, 'no'); $('table.medium').attr(HANDLED_ATTRIBUTE, 'no');
$('table.medium').bind("DOMNodeInserted", function(event) { $('table.medium').bind('DOMNodeInserted', function(event) {
$target = $(event.target); $target = $(event.target);
if ($target.prop('nodeName') == 'TBODY' && $target.parent().attr(HANDLED_ATTRIBUTE) == 'no' && $target.find('tr.subh').length > 0) { if (
$target.prop('nodeName') == 'TBODY' &&
$target.parent().attr(HANDLED_ATTRIBUTE) == 'no' &&
$target.find('tr.subh').length > 0
) {
$medium = $target.parent(); $medium = $target.parent();
$medium.attr(HANDLED_ATTRIBUTE, 'pending'); $medium.attr(HANDLED_ATTRIBUTE, 'pending');
handleMedium($medium, tracks); handleMedium($medium, tracks);
@ -194,48 +238,65 @@ $(document).ready(function () {
function handleMedium($medium, ws_tracks) { function handleMedium($medium, ws_tracks) {
// Extend colspan for medium table header // Extend colspan for medium table header
$medium.find("thead tr").each(function() { $medium.find('thead tr').each(function() {
$(this).find("th:eq(0)").attr("colspan", $(this).find("th:eq(0)").attr("colspan")*1+1); $(this)
.find('th:eq(0)')
.attr(
'colspan',
$(this)
.find('th:eq(0)')
.attr('colspan') *
1 +
1
);
}); });
// Table sub-header // Table sub-header
$medium.find("tbody tr.subh th:nth-last-child("+ISRC_COLUMN_POSITION+")").before("<th style='width: 150px;' class='isrc c'> ISRC </th>"); $medium
.find(`tbody tr.subh th:nth-last-child(${ISRC_COLUMN_POSITION})`)
.before("<th style='width: 150px;' class='isrc c'> ISRC </th>");
// Handle each track // Handle each track
$medium.find("tbody tr[id]").each(function(index, medium_track) { $medium.find('tbody tr[id]').each(function(index, medium_track) {
track_mbid = $(medium_track).attr('id'); track_mbid = $(medium_track).attr('id');
var isrcsLinks = ""; let isrcsLinks = '';
if (ws_tracks.hasOwnProperty(track_mbid)) { if (ws_tracks.hasOwnProperty(track_mbid)) {
track = ws_tracks[track_mbid]; track = ws_tracks[track_mbid];
var recording = track.recording; let recording = track.recording;
// Recording comment // Recording comment
if (recording.disambiguation != "") { if (recording.disambiguation != '') {
var td_title_index = $("#"+track_mbid).find("td:eq(1)").hasClass("video") ? 2 : 1; let td_title_index = $(`#${track_mbid}`)
$("#"+track_mbid).find("td:eq("+td_title_index+") a:eq(0)").after(' <span class="comment">(' + recording.disambiguation + ')</span>'); .find('td:eq(1)')
.hasClass('video')
? 2
: 1;
$(`#${track_mbid}`)
.find(`td:eq(${td_title_index}) a:eq(0)`)
.after(` <span class="comment">(${recording.disambiguation})</span>`);
} }
// ISRCS // ISRCS
if (recording.isrcs.length != 0) { if (recording.isrcs.length != 0) {
var links = jQuery.map(recording.isrcs, function(isrc, i) { let links = jQuery.map(recording.isrcs, function(isrc, i) {
return ("<a href='/isrc/" + isrc + "'>" + isrc + "</a>"); return `<a href='/isrc/${isrc}'>${isrc}</a>`;
}); });
isrcsLinks = links.join(", "); isrcsLinks = links.join(', ');
} }
} }
$('#'+track_mbid).find("td:nth-last-child("+ISRC_COLUMN_POSITION+")").before("<td class='isrc c'><small>"+isrcsLinks+"</small></td>"); $(`#${track_mbid}`)
.find(`td:nth-last-child(${ISRC_COLUMN_POSITION})`)
.before(`<td class='isrc c'><small>${isrcsLinks}</small></td>`);
}); });
} }
} }
// Display "Edit relationships" link for release besides "Edit" link // Display "Edit relationships" link for release besides "Edit" link
re = new RegExp("musicbrainz\.org\/release\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})","i"); re = new RegExp('musicbrainz.org/release/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})', 'i');
if (window.location.href.match(re)) { if (window.location.href.match(re)) {
var mbid = window.location.href.match(re)[1]; var mbid = window.location.href.match(re)[1];
$('ul.tabs').append('<li><a href="/release/' + mbid + '/edit-relationships">Edit relationships</a></li>'); $('ul.tabs').append(`<li><a href="/release/${mbid}/edit-relationships">Edit relationships</a></li>`);
} }
// Discogs link rollover // Discogs link rollover
// TODO... // TODO...
// -------------- End of script ------------------------ // -------------- End of script ------------------------
}); });

View file

@ -13,7 +13,6 @@
// @icon https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/assets/images/Musicbrainz_import_logo.png // @icon https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/assets/images/Musicbrainz_import_logo.png
// ==/UserScript== // ==/UserScript==
// prevent JQuery conflicts, see http://wiki.greasespot.net/@grant // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant
this.$ = this.jQuery = jQuery.noConflict(true); this.$ = this.jQuery = jQuery.noConflict(true);
@ -22,23 +21,23 @@ if (!unsafeWindow) unsafeWindow = window;
$(document).ready(function() { $(document).ready(function() {
MBImportStyle(); MBImportStyle();
var release_url = window.location.href.replace('/\?.*$/', '').replace(/#.*$/, ''); let release_url = window.location.href.replace('/?.*$/', '').replace(/#.*$/, '');
var release = retrieveReleaseInfo(release_url); let release = retrieveReleaseInfo(release_url);
insertLink(release, release_url); insertLink(release, release_url);
LOGGER.info("Parsed release: ", release); LOGGER.info('Parsed release: ', release);
}); });
function setreleasedate(release, datestring) { function setreleasedate(release, datestring) {
if (/^\d{4}$/.exec(datestring)) { if (/^\d{4}$/.exec(datestring)) {
release.year = datestring; release.year = datestring;
} else if (datestring.indexOf(',') != -1) { } else if (datestring.indexOf(',') != -1) {
var commaindex = datestring.indexOf(','); let commaindex = datestring.indexOf(',');
var d = new Date(datestring.substring(0, commaindex - 2) + datestring.substring(commaindex)); var d = new Date(datestring.substring(0, commaindex - 2) + datestring.substring(commaindex));
release.year = d.getFullYear(); release.year = d.getFullYear();
release.month = d.getMonth() + 1; release.month = d.getMonth() + 1;
release.day = d.getDate(); release.day = d.getDate();
} else { } else {
var d = new Date("2 " + datestring); var d = new Date(`2 ${datestring}`);
release.year = d.getFullYear(); release.year = d.getFullYear();
release.month = d.getMonth() + 1; release.month = d.getMonth() + 1;
} }
@ -46,14 +45,18 @@ function setreleasedate(release, datestring) {
} }
function getGenericalData() { function getGenericalData() {
var rdata = new Array(); let rdata = new Array();
var keydata = $('dl.float_left dt, dl.float_right dt').map(function() { let keydata = $('dl.float_left dt, dl.float_right dt')
var s = $.trim($(this).text()); .map(function() {
let s = $.trim($(this).text());
return s.substring(0, s.length - 1); return s.substring(0, s.length - 1);
}).get(); })
var valuedata = $('dl.float_left dd,dl.float_right dd').map(function() { .get();
let valuedata = $('dl.float_left dd,dl.float_right dd')
.map(function() {
return $.trim($(this).text()); return $.trim($(this).text());
}).get(); })
.get();
for (i = 0; i < keydata.length; i++) { for (i = 0; i < keydata.length; i++) {
rdata[keydata[i]] = valuedata[i]; rdata[keydata[i]] = valuedata[i];
} }
@ -61,12 +64,16 @@ function getGenericalData() {
} }
function getArtistsList() { function getArtistsList() {
return $.map($('h2.band_name').text().split('/'), $.trim); return $.map(
$('h2.band_name')
.text()
.split('/'),
$.trim
);
} }
function retrieveReleaseInfo(release_url) { function retrieveReleaseInfo(release_url) {
let release = {
var release = {
discs: [], discs: [],
artist_credit: [], artist_credit: [],
title: '', title: '',
@ -82,41 +89,40 @@ function retrieveReleaseInfo(release_url) {
packaging: '', packaging: '',
language: '', language: '',
script: '', script: '',
urls: [], urls: []
}; };
var rdata = getGenericalData(); let rdata = getGenericalData();
var artists = getArtistsList(); let artists = getArtistsList();
var joinphrase = ""; let joinphrase = '';
if (artists.length > 1) { if (artists.length > 1) {
if (rdata["Type"] == "Split") { if (rdata['Type'] == 'Split') {
joinphrase = " / "; joinphrase = ' / ';
} } else {
else { joinphrase = ' & ';
joinphrase = " & ";
} }
} }
for (var i = 0; i < artists.length; i++) { for (let i = 0; i < artists.length; i++) {
release.artist_credit.push({ release.artist_credit.push({
artist_name: artists[i], artist_name: artists[i],
credited_name: artists[i], credited_name: artists[i],
joinphrase: i != artists.length - 1 ? joinphrase : "" joinphrase: i != artists.length - 1 ? joinphrase : ''
}); });
} }
release.title = $('h1.album_name').text(); release.title = $('h1.album_name').text();
release = setreleasedate(release, rdata["Release date"]); release = setreleasedate(release, rdata['Release date']);
if ("Label" in rdata) { if ('Label' in rdata) {
// TODO: add case for multiple labels if such a case exist // TODO: add case for multiple labels if such a case exist
var label = rdata["Label"]; let label = rdata['Label'];
var label_mbid = ""; let label_mbid = '';
if (label == "Independent") { if (label == 'Independent') {
label = "[no label]"; label = '[no label]';
label_mbid = '157afde4-4bf5-4039-8ad2-5a15acc85176'; label_mbid = '157afde4-4bf5-4039-8ad2-5a15acc85176';
} }
var catno = rdata["Catalog ID"]; let catno = rdata['Catalog ID'];
if (catno == undefined || catno == "N/A") { if (catno == undefined || catno == 'N/A') {
catno = ""; catno = '';
} }
release.labels.push({ release.labels.push({
name: label, name: label,
@ -125,54 +131,56 @@ function retrieveReleaseInfo(release_url) {
}); });
} }
if (rdata["Type"] in ReleaseTypes) { if (rdata['Type'] in ReleaseTypes) {
var types = ReleaseTypes[rdata["Type"]]; let types = ReleaseTypes[rdata['Type']];
release.type = types[0]; release.type = types[0];
// NOTE: secondary type may not be selected on MB editor, but it still works, a bug on MB side // NOTE: secondary type may not be selected on MB editor, but it still works, a bug on MB side
release.secondary_types = types.slice(1); release.secondary_types = types.slice(1);
} }
// FIXME: multiple vinyls ie. http://www.metal-archives.com/albums/Reverend_Bizarre/III%3A_So_Long_Suckers/415313 // FIXME: multiple vinyls ie. http://www.metal-archives.com/albums/Reverend_Bizarre/III%3A_So_Long_Suckers/415313
if (rdata["Format"] in ReleaseFormat) { if (rdata['Format'] in ReleaseFormat) {
release.format = ReleaseFormat[rdata["Format"]]; release.format = ReleaseFormat[rdata['Format']];
} }
if ("Version desc." in rdata) { if ('Version desc.' in rdata) {
if (rdata["Version desc."].indexOf("Digipak") != -1) { if (rdata['Version desc.'].indexOf('Digipak') != -1) {
release.packaging = "Digipak"; release.packaging = 'Digipak';
} }
if (release.format == "CD" && rdata["Version desc."] == "CD-R") { if (release.format == 'CD' && rdata['Version desc.'] == 'CD-R') {
release.format = "CD-R"; release.format = 'CD-R';
} }
} }
var identifiers = $("#album_tabs_notes > div:nth-child(2)").find("p:not([class])").contents(); let identifiers = $('#album_tabs_notes > div:nth-child(2)')
for (var j = 0; j < identifiers.length; j++) { .find('p:not([class])')
if (identifiers[j].textContent.indexOf("Barcode:") != -1) { .contents();
for (let j = 0; j < identifiers.length; j++) {
if (identifiers[j].textContent.indexOf('Barcode:') != -1) {
release.barcode = $.trim(identifiers[j].textContent.substring(8)); release.barcode = $.trim(identifiers[j].textContent.substring(8));
break; break;
} }
} }
// URLs // URLs
var link_type = MBImport.URL_TYPES; let link_type = MBImport.URL_TYPES;
release.urls.push({ release.urls.push({
url: release_url, url: release_url,
link_type: link_type.other_databases link_type: link_type.other_databases
}); });
var releaseNumber = 0; let releaseNumber = 0;
var disc = { let disc = {
tracks: [], tracks: [],
format: release.format format: release.format
}; };
release.discs.push(disc); release.discs.push(disc);
var tracksline = $('table.table_lyrics tr.even,table.table_lyrics tr.odd'); let tracksline = $('table.table_lyrics tr.even,table.table_lyrics tr.odd');
tracksline.each(function(index, element) { tracksline.each(function(index, element) {
var trackNumber = $.trim(element.children[0].textContent).replace('.', ""); let trackNumber = $.trim(element.children[0].textContent).replace('.', '');
if (trackNumber == "1" && trackNumber != index + 1) { if (trackNumber == '1' && trackNumber != index + 1) {
releaseNumber++; releaseNumber++;
release.discs.push({ release.discs.push({
tracks: [], tracks: [],
@ -181,11 +189,11 @@ function retrieveReleaseInfo(release_url) {
} }
// TODO: handling of split and compilation artists (artist - title) // TODO: handling of split and compilation artists (artist - title)
var track = { let track = {
'number': trackNumber, number: trackNumber,
'title': $.trim(element.children[1].textContent.replace(/\s+/g, ' ')), title: $.trim(element.children[1].textContent.replace(/\s+/g, ' ')),
'duration': $.trim(element.children[2].textContent), duration: $.trim(element.children[2].textContent),
'artist_credit': [release.artist_credit] artist_credit: [release.artist_credit]
}; };
release.discs[releaseNumber].tracks.push(track); release.discs[releaseNumber].tracks.push(track);
}); });
@ -194,21 +202,21 @@ function retrieveReleaseInfo(release_url) {
// Insert button into page under label information // Insert button into page under label information
function insertLink(release, release_url) { function insertLink(release, release_url) {
var edit_note = MBImport.makeEditNote(release_url, 'Metal Archives'); let edit_note = MBImport.makeEditNote(release_url, 'Metal Archives');
var parameters = MBImport.buildFormParameters(release, edit_note); let parameters = MBImport.buildFormParameters(release, edit_note);
var mbUI = $('<div id="musicbrainz-import">' + MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release) + '</div>').hide(); let mbUI = $(`<div id="musicbrainz-import">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`).hide();
$('h2.band_name').after(mbUI); $('h2.band_name').after(mbUI);
$('#musicbrainz-import form').css({ $('#musicbrainz-import form').css({
'padding': '0' padding: '0'
}); });
$('form.musicbrainz_import').css({ $('form.musicbrainz_import').css({
'display': 'inline-block', display: 'inline-block',
'margin': '1px' margin: '1px'
}); });
$('form.musicbrainz_import img').css({ $('form.musicbrainz_import img').css({
'display': 'inline-block' display: 'inline-block'
}); });
mbUI.slideDown(); mbUI.slideDown();
@ -236,28 +244,28 @@ Split video
//ReleaseTypes[MAtype]=["primary type","secondary type on mb"]; //ReleaseTypes[MAtype]=["primary type","secondary type on mb"];
var ReleaseTypes = { var ReleaseTypes = {
"Full-length": ["album"], 'Full-length': ['album'],
"Live album": ["album", "live"], 'Live album': ['album', 'live'],
"Demo": ["album", "demo"], Demo: ['album', 'demo'],
"Single": ["single"], Single: ['single'],
"EP": ["ep"], EP: ['ep'],
"Compilation": ["album", "compilation"], Compilation: ['album', 'compilation'],
"Split": ["album"], Split: ['album'],
"Collaboration": [""], Collaboration: ['']
}; };
//ReleaseFormat[MAformat]="MBformat"; //ReleaseFormat[MAformat]="MBformat";
var ReleaseFormat = { var ReleaseFormat = {
"CD": "CD", CD: 'CD',
"2CD": "CD", '2CD': 'CD',
"Vinyl": "Vinyl", Vinyl: 'Vinyl',
"7\" vinyl": "7\" Vinyl", '7" vinyl': '7" Vinyl',
"7\" vinyl (33⅓ RPM)": "7\" Vinyl", '7" vinyl (33⅓ RPM)': '7" Vinyl',
"10\" vinyl (33⅓ RPM)": "10\" Vinyl", '10" vinyl (33⅓ RPM)': '10" Vinyl',
"10\" vinyl": "10\" Vinyl", '10" vinyl': '10" Vinyl',
"12\" vinyl": "12\" Vinyl", '12" vinyl': '12" Vinyl',
"2 12\" vinyls": "12\" Vinyl", '2 12" vinyls': '12" Vinyl',
"12\" vinyl (33⅓ RPM)": "12\" Vinyl", '12" vinyl (33⅓ RPM)': '12" Vinyl',
"Cassette": "Cassette", Cassette: 'Cassette',
"Digital": "Digital Media", Digital: 'Digital Media'
}; };

View file

@ -26,37 +26,37 @@ if (DEBUG) {
} }
// list of qobuz artist id which should be mapped to Various Artists // list of qobuz artist id which should be mapped to Various Artists
var various_artists_ids = [ 26887, 145383, 353325, 183869, 997899 ]; var various_artists_ids = [26887, 145383, 353325, 183869, 997899];
function parseRelease(data) { function parseRelease(data) {
var release = {}; let release = {};
release.script = 'Latn'; release.script = 'Latn';
release.url = 'https://www.qobuz.com' + data.relative_url; // no lang release.url = `https://www.qobuz.com${data.relative_url}`; // no lang
release.title = data.title; release.title = data.title;
release.artist_credit = MBImport.makeArtistCredits([data.artist.name]); // FIXME: various artists release.artist_credit = MBImport.makeArtistCredits([data.artist.name]); // FIXME: various artists
if ($.inArray(data.artist.id, various_artists_ids) != -1) { if ($.inArray(data.artist.id, various_artists_ids) != -1) {
release.artist_credit = [ MBImport.specialArtist('various_artists') ]; release.artist_credit = [MBImport.specialArtist('various_artists')];
} }
// Release information global to all Beatport releases // Release information global to all Beatport releases
release.packaging = 'None'; release.packaging = 'None';
release.barcode = data.upc; release.barcode = data.upc;
release.country = "XW"; release.country = 'XW';
if (i18n_global && i18n_global.zone) { if (i18n_global && i18n_global.zone) {
release.country = i18n_global.zone; release.country = i18n_global.zone;
} }
release.status = 'official'; release.status = 'official';
release.urls = []; release.urls = [];
release.urls.push({ release.urls.push({
'url': release.url, url: release.url,
'link_type': MBImport.URL_TYPES.purchase_for_download link_type: MBImport.URL_TYPES.purchase_for_download
}); });
// release timestamps are using France time + daylight saving (GMT+1 or GMT+2), // release timestamps are using France time + daylight saving (GMT+1 or GMT+2),
// add 3 hours to get the day of release (matching the one displayed) // add 3 hours to get the day of release (matching the one displayed)
var releaseDate = new Date((parseInt(data.released_at, 10) + 3*3600) * 1000); let releaseDate = new Date((parseInt(data.released_at, 10) + 3 * 3600) * 1000);
release.year = releaseDate.getUTCFullYear(); release.year = releaseDate.getUTCFullYear();
release.month = releaseDate.getUTCMonth() + 1; release.month = releaseDate.getUTCMonth() + 1;
release.day = releaseDate.getUTCDate(); release.day = releaseDate.getUTCDate();
@ -65,42 +65,44 @@ function parseRelease(data) {
$.each(data.label.name.split(' - '), function(index, label) { $.each(data.label.name.split(' - '), function(index, label) {
release.labels.push({ release.labels.push({
name: label, name: label,
catno: "[none]" // no catno on qobuz ? catno: '[none]' // no catno on qobuz ?
}); });
}); });
release.isrcs = []; release.isrcs = [];
release.comment = "Digital download"; release.comment = 'Digital download';
release.discs = []; release.discs = [];
var tracks = [], old_media_num = 1; let tracks = [],
old_media_num = 1;
$.each(data.tracks.items, function(index, trackobj) { $.each(data.tracks.items, function(index, trackobj) {
release.isrcs.push(trackobj.isrc); release.isrcs.push(trackobj.isrc);
if (trackobj.media_number != old_media_num) { if (trackobj.media_number != old_media_num) {
release.discs.push({ release.discs.push({
'tracks': tracks, tracks: tracks,
'format': "Digital Media" format: 'Digital Media'
}); });
old_media_num = trackobj.media_number; old_media_num = trackobj.media_number;
tracks = []; tracks = [];
} }
var track = {}; let track = {};
track.title = trackobj.title.replace('"','\"'); track.title = trackobj.title.replace('"', '"');
track.duration = trackobj.duration * 1000; track.duration = trackobj.duration * 1000;
var performers = (typeof trackobj.performers !== 'undefined') && trackobj.performers.split('\r - ').map(function(v) { let performers = (typeof trackobj.performers !== 'undefined' &&
var list = v.split(', '); trackobj.performers.split('\r - ').map(function(v) {
var name = list.shift(); let list = v.split(', ');
let name = list.shift();
return [name, list]; return [name, list];
}) || [trackobj.performer.name, ['Primary']]; })) || [trackobj.performer.name, ['Primary']];
var artists = []; let artists = [];
var featured_artists = []; let featured_artists = [];
$.each(performers, function(index, performer) { $.each(performers, function(index, performer) {
if ($.inArray('Featured Artist', performer[1]) != -1) { if ($.inArray('Featured Artist', performer[1]) != -1) {
featured_artists.push(performer[0]); featured_artists.push(performer[0]);
} } else if (
else if ($.inArray('Main Performer', performer[1]) != -1 $.inArray('Main Performer', performer[1]) != -1 ||
|| $.inArray('Primary', performer[1]) != -1 $.inArray('Primary', performer[1]) != -1 ||
|| $.inArray('interprète', performer[1]) != -1 $.inArray('interprète', performer[1]) != -1 ||
|| $.inArray('Performer', performer[1]) != -1 $.inArray('Performer', performer[1]) != -1 ||
|| $.inArray('Main Artist', performer[1]) != -1 $.inArray('Main Artist', performer[1]) != -1
) { ) {
artists.push(performer[0]); artists.push(performer[0]);
} }
@ -108,84 +110,90 @@ function parseRelease(data) {
track.artist_credit = MBImport.makeArtistCredits(artists); track.artist_credit = MBImport.makeArtistCredits(artists);
if (featured_artists.length) { if (featured_artists.length) {
if (track.artist_credit.length) { if (track.artist_credit.length) {
track.artist_credit[track.artist_credit.length-1].joinphrase = ' feat. '; track.artist_credit[track.artist_credit.length - 1].joinphrase = ' feat. ';
} }
$.merge(track.artist_credit, MBImport.makeArtistCredits(featured_artists)); $.merge(track.artist_credit, MBImport.makeArtistCredits(featured_artists));
} }
tracks.push(track); tracks.push(track);
}); });
release.discs.push({ release.discs.push({
'tracks': tracks, tracks: tracks,
'format': "Digital Media" format: 'Digital Media'
}); });
LOGGER.info("Parsed release: ", release); LOGGER.info('Parsed release: ', release);
return release; return release;
} }
// Insert button into page under label information // Insert button into page under label information
function insertLink(release) { function insertLink(release) {
var edit_note = MBImport.makeEditNote(release.url, 'Qobuz'); let edit_note = MBImport.makeEditNote(release.url, 'Qobuz');
var parameters = MBImport.buildFormParameters(release, edit_note); let parameters = MBImport.buildFormParameters(release, edit_note);
var mbUI = $('<p class="musicbrainz_import">').append(MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release)).hide(); let mbUI = $('<p class="musicbrainz_import">')
.append(MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release))
.hide();
mbUI.append($('<button id="isrcs" type="submit" title="Show list of ISRCs">Show ISRCs</button>')); mbUI.append($('<button id="isrcs" type="submit" title="Show list of ISRCs">Show ISRCs</button>'));
var isrclist = $('<p><textarea id="isrclist" style="display:none">' + release.isrcs.join("\n") + '</textarea></p>'); let isrclist = $(`<p><textarea id="isrclist" style="display:none">${release.isrcs.join('\n')}</textarea></p>`);
$("#info div.meta").append(mbUI).append(isrclist); $('#info div.meta')
.append(mbUI)
.append(isrclist);
$('form.musicbrainz_import').css({ $('form.musicbrainz_import').css({
'display': 'inline-block', display: 'inline-block',
'margin': '1px' margin: '1px'
}); });
$('form.musicbrainz_import img').css({ $('form.musicbrainz_import img').css({
'display': 'inline-block', display: 'inline-block',
'width': '16px', width: '16px',
'height': '16px' height: '16px'
}); });
mbUI.slideDown(); mbUI.slideDown();
} }
// Hook all XMLHttpRequest to use the data fetched by the official web-player. // Hook all XMLHttpRequest to use the data fetched by the official web-player.
(function() { (function() {
const send = XMLHttpRequest.prototype.send const send = XMLHttpRequest.prototype.send;
XMLHttpRequest.prototype.send = function() { XMLHttpRequest.prototype.send = function() {
this.addEventListener('load', function() { this.addEventListener('load', function() {
var wsUrl = 'https://www.qobuz.com/api.json/0.2/album/get?album_id='; let wsUrl = 'https://www.qobuz.com/api.json/0.2/album/get?album_id=';
var repUrl = arguments[0].originalTarget.responseURL; let repUrl = arguments[0].originalTarget.responseURL;
if (repUrl.startsWith(wsUrl)) { if (repUrl.startsWith(wsUrl)) {
var data = JSON.parse(this.responseText); let data = JSON.parse(this.responseText);
var release = parseRelease(data); let release = parseRelease(data);
insertLink(release); insertLink(release);
} }
}) });
return send.apply(this, arguments) return send.apply(this, arguments);
} };
})() })();
$(document).ready(function() { $(document).ready(function() {
MBImportStyle(); MBImportStyle();
// replace image zoom link by the maximum size image link // replace image zoom link by the maximum size image link
var maximgurl = $("#product-cover-link").attr("href").replace('_600', '_max'); let maximgurl = $('#product-cover-link')
var maximg = new Image(); .attr('href')
maximg.onerror = function (evt) { .replace('_600', '_max');
LOGGER.debug("No max image"); let maximg = new Image();
maximg.onerror = function(evt) {
LOGGER.debug('No max image');
}; };
maximg.onload = function (evt) { maximg.onload = function(evt) {
$("#product-cover-link").attr("href", maximgurl); $('#product-cover-link').attr('href', maximgurl);
$("#product-cover-link").attr("title", $("#product-cover-link").attr("title") + ' (Qobuz importer: ' + maximg.width + 'x' + maximg.height + ' image)'); $('#product-cover-link').attr(
'title',
`${$('#product-cover-link').attr('title')} (Qobuz importer: ${maximg.width}x${maximg.height} image)`
);
}; };
maximg.src = maximgurl; maximg.src = maximgurl;
}); });
$(document).on('click', '#isrcs', function (){ $(document).on('click', '#isrcs', function() {
$('#isrclist').toggle(); $('#isrclist').toggle();
if ($('#isrclist').is(':visible')) { if ($('#isrclist').is(':visible')) {
$('#isrclist').select(); $('#isrclist').select();
$(this).text('Hide ISRCs'); $(this).text('Hide ISRCs');
} } else $(this).text('Show ISRCs');
else $(this).text('Show ISRCs');
return false; return false;
}); });

View file

@ -41,19 +41,23 @@
// authorization. // authorization.
// ==/License== // ==/License==
var scr = document.createElement("script"); var scr = document.createElement('script');
scr.textContent = "$(" + setRecordingComments + ");"; scr.textContent = `$(${setRecordingComments});`;
document.body.appendChild(scr); document.body.appendChild(scr);
function setRecordingComments() { function setRecordingComments() {
var $tracks; let $tracks;
var $inputs = $(); let $inputs = $();
var EDIT_RECORDING_EDIT = 72; let EDIT_RECORDING_EDIT = 72;
$("head").append($("<style></style>").text("input.recording-comment { background: inherit; border: 1px #999 solid; width: 32em; margin-left: 0.5em; }")); $('head').append(
$('<style></style>').text(
'input.recording-comment { background: inherit; border: 1px #999 solid; width: 32em; margin-left: 0.5em; }'
)
);
var delay = setInterval(function () { var delay = setInterval(function() {
$tracks = $(".medium tbody tr[id]"); $tracks = $('.medium tbody tr[id]');
if ($tracks.length) { if ($tracks.length) {
clearInterval(delay); clearInterval(delay);
@ -61,10 +65,14 @@ function setRecordingComments() {
return; return;
} }
$tracks.each(function () { $tracks.each(function() {
var $td = $(this).children("td:not(.pos):not(.video):not(.rating):not(.treleases)").has("a[href^=\\/recording\\/]"), let $td = $(this)
node = $td.children("td > .mp, td > .name-variation, td > a[href^=\\/recording\\/]").filter(":first"), .children('td:not(.pos):not(.video):not(.rating):not(.treleases)')
$input = $("<input />").addClass("recording-comment").insertAfter(node); .has('a[href^=\\/recording\\/]'),
node = $td.children('td > .mp, td > .name-variation, td > a[href^=\\/recording\\/]').filter(':first'),
$input = $('<input />')
.addClass('recording-comment')
.insertAfter(node);
if (!editing) { if (!editing) {
$input.hide(); $input.hide();
@ -73,14 +81,17 @@ function setRecordingComments() {
$inputs = $inputs.add($input); $inputs = $inputs.add($input);
}); });
var release = location.pathname.match(MBID_REGEX)[0]; let release = location.pathname.match(MBID_REGEX)[0];
$.get("/ws/2/release/" + release + "?inc=recordings&fmt=json", function (data) { $.get(`/ws/2/release/${release}?inc=recordings&fmt=json`, function(data) {
var comments = _.map(_.map(_.flatten(_.map(data.media, "tracks")), "recording"), "disambiguation"); let comments = _.map(_.map(_.flatten(_.map(data.media, 'tracks')), 'recording'), 'disambiguation');
for (var i = 0, len = comments.length; i < len; i++) { for (let i = 0, len = comments.length; i < len; i++) {
var comment = comments[i]; let comment = comments[i];
$inputs.eq(i).val(comment).data("old", comment); $inputs
.eq(i)
.val(comment)
.data('old', comment);
} }
}); });
}, 1000); }, 1000);
@ -93,25 +104,28 @@ function setRecordingComments() {
editing = false, editing = false,
activeRequest = null; activeRequest = null;
$("body").on("input.rc", ".recording-comment", function () { $('body').on('input.rc', '.recording-comment', function() {
$(this).css("border-color", this.value === $(this).data("old") ? "#999" : "red"); $(this).css('border-color', this.value === $(this).data('old') ? '#999' : 'red');
}); });
var $container = $("<div></div>").insertAfter("h2.tracklist"); let $container = $('<div></div>').insertAfter('h2.tracklist');
$("<button>Edit recording comments</button>") $('<button>Edit recording comments</button>')
.addClass("styled-button") .addClass('styled-button')
.on("click", function () { .on('click', function() {
editing = !editing; editing = !editing;
$("#set-recording-comments").add($inputs).toggle(editing); $('#set-recording-comments')
$(this).text((editing ? "Hide" : "Edit") + " recording comments"); .add($inputs)
.toggle(editing);
$(this).text(`${editing ? 'Hide' : 'Edit'} recording comments`);
if (editing) { if (editing) {
$("#all-recording-comments").focus(); $('#all-recording-comments').focus();
} }
}) })
.appendTo($container); .appendTo($container);
$container.append('\ $container.append(
'\
<table id="set-recording-comments">\ <table id="set-recording-comments">\
<tr>\ <tr>\
<td><label for="all-recording-comments">Set all visible comments to:</label></td>\ <td><label for="all-recording-comments">Set all visible comments to:</label></td>\
@ -126,71 +140,80 @@ function setRecordingComments() {
<button id="submit-recording-comments" class="styled-button">Submit changes (visible and marked red)</button>\ <button id="submit-recording-comments" class="styled-button">Submit changes (visible and marked red)</button>\
</td>\ </td>\
</tr>\ </tr>\
</table>'); </table>'
);
$("#set-recording-comments").hide(); $('#set-recording-comments').hide();
$("#all-recording-comments").on("input", function () { $('#all-recording-comments').on('input', function() {
$inputs.filter(":visible").val(this.value).trigger("input.rc"); $inputs
.filter(':visible')
.val(this.value)
.trigger('input.rc');
}); });
var $submitButton = $("#submit-recording-comments").on("click", function () { var $submitButton = $('#submit-recording-comments').on('click', function() {
if (activeRequest) { if (activeRequest) {
activeRequest.abort(); activeRequest.abort();
activeRequest = null; activeRequest = null;
$submitButton.text("Submit changes (marked red)"); $submitButton.text('Submit changes (marked red)');
$inputs.prop("disabled", false).trigger("input.rc"); $inputs.prop('disabled', false).trigger('input.rc');
return; return;
} }
$submitButton.text("Submitting...click to cancel!"); $submitButton.text('Submitting...click to cancel!');
$inputs.prop("disabled", true); $inputs.prop('disabled', true);
var editData = [], deferred = $.Deferred(); let editData = [],
deferred = $.Deferred();
$.each($tracks, function (i, track) { $.each($tracks, function(i, track) {
if ($(track).filter(":visible").length > 0) { if ($(track).filter(':visible').length > 0) {
var $input = $inputs.eq(i), comment = $input.val(); let $input = $inputs.eq(i),
if (comment === $input.data("old")) { comment = $input.val();
$input.prop("disabled", false); if (comment === $input.data('old')) {
$input.prop('disabled', false);
return; return;
} }
deferred deferred
.done(function () { .done(function() {
$input.data("old", comment).trigger("input.rc").prop("disabled", false); $input
.data('old', comment)
.trigger('input.rc')
.prop('disabled', false);
}) })
.fail(function () { .fail(function() {
$input.css("border-color", "red").prop("disabled", false); $input.css('border-color', 'red').prop('disabled', false);
}); });
var link = track.querySelector("td a[href^='/recording/']"), let link = track.querySelector("td a[href^='/recording/']"),
mbid = link.href.match(MBID_REGEX)[0]; mbid = link.href.match(MBID_REGEX)[0];
editData.push({edit_type: EDIT_RECORDING_EDIT, to_edit: mbid, comment: comment}); editData.push({ edit_type: EDIT_RECORDING_EDIT, to_edit: mbid, comment: comment });
} }
}); });
if (editData.length === 0) { if (editData.length === 0) {
$inputs.prop("disabled", false); $inputs.prop('disabled', false);
$submitButton.prop("disabled", false).text("Submit changes (marked red)"); $submitButton.prop('disabled', false).text('Submit changes (marked red)');
} else { } else {
var editNote = $("#recording-comments-edit-note").val(); let editNote = $('#recording-comments-edit-note').val();
activeRequest = $.ajax({ activeRequest = $.ajax({
type: 'POST', type: 'POST',
url: '/ws/js/edit/create', url: '/ws/js/edit/create',
dataType: 'json', dataType: 'json',
data: JSON.stringify({edits: editData, editNote: editNote}), data: JSON.stringify({ edits: editData, editNote: editNote }),
contentType: 'application/json; charset=utf-8', contentType: 'application/json; charset=utf-8'
}) })
.always(function () { .always(function() {
$submitButton.prop("disabled", false).text("Submit changes (marked red)"); $submitButton.prop('disabled', false).text('Submit changes (marked red)');
}) })
.done(function () { .done(function() {
deferred.resolve(); deferred.resolve();
}) })
.fail(function () { .fail(function() {
deferred.reject(); deferred.reject();
}); });
} }

File diff suppressed because it is too large Load diff