From 14a32dab623099a48684a6a06c8a9e11f2812221 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aur=C3=A9lien=20Mino?= Date: Tue, 20 Nov 2018 23:18:49 +0100 Subject: [PATCH] Applied prettier and eslint tools on existing code None of these changes are manual changes made a human --- README.md | 47 +- bandcamp_importer.user.js | 576 ++++--- bandcamp_importer_helper.user.js | 17 +- batch-add-recording-relationships.user.js | 1113 ++++++------ beatport_classic_importer.user.js | 188 +- beatport_importer.user.js | 183 +- cd1d_importer.user.js | 457 ++--- cdbaby_importer.user.js | 280 +-- dgdecca_importer.user.js | 284 ++-- discogs_importer.user.js | 1334 ++++++++------- encyclopedisque_importer.user.js | 203 ++- expand-collapse-release-groups.user.js | 291 ++-- fast-cancel-edits.user.js | 83 +- fma_importer.user.js | 968 ++++++----- juno_download_importer.user.js | 224 +-- lastfm_importer.user.js | 192 ++- lib/logger.js | 21 +- lib/mbimport.js | 397 ++--- lib/mbimportstyle.js | 16 +- lib/mblinks.js | 429 ++--- loot_importer.user.js | 1103 ++++++------ mb_discids_detector.user.js | 381 +++-- mb_relationship_shortcuts.user.js | 227 +-- mb_ui_enhancements.user.js | 243 ++- metalarchives_importer.user.js | 376 ++-- qobuz_importer.user.js | 278 +-- set-recording-comments.user.js | 147 +- takealot_importer.user.js | 1892 +++++++++++---------- 28 files changed, 6205 insertions(+), 5745 deletions(-) diff --git a/README.md b/README.md index d30b809..c30bb6b 100644 --- a/README.md +++ b/README.md @@ -1,28 +1,28 @@ # MusicBrainz UserScripts -* [Display shortcut for relationships on MusicBrainz](#mb_relationship_shortcuts) -* [Import Bandcamp releases to MusicBrainz](#bandcamp_importer) -* [Import Bandcamp releases to MusicBrainz Album Link Helper](#bandcamp_importer_helper) -* [Import Beatport Pro releases to MusicBrainz](#beatport_pro_importer) -* [Import Beatport releases to MusicBrainz](#beatport_importer) -* [Import CD Baby releases to MusicBrainz](#cdbaby_importer) -* [Import CD1D releases to MusicBrainz](#cd1d_importer) -* [Import DG/Decca releases to MusicBrainz](#dgdecca_importer) -* [Import Discogs releases to MusicBrainz](#discogs_importer) -* [Import Encyclopedisque releases to MusicBrainz](#encyclopedisque_importer) -* [Import FMA releases to MusicBrainz](#fma_importer) -* [Import Juno Download releases to MusicBrainz](#juno_download_importer) -* [Import Last.fm releases to MusicBrainz](#lastfm_importer) -* [Import Loot releases to MusicBrainz](#loot_importer) -* [Import Metal Archives releases into MusicBrainz](#metalarchives_importer) -* [Import Qobuz releases to MusicBrainz](#qobuz_importer) -* [Import Takealot releases to MusicBrainz](#takealot_importer) -* [MusicBrainz: Batch-add "performance of" relationships](#batch-add-recording-relationships) -* [MusicBrainz: Expand/collapse release groups](#expand-collapse-release-groups) -* [MusicBrainz: Fast cancel edits](#fast-cancel-edits) -* [MusicBrainz: Set recording comments for a release](#set-recording-comments) -* [Musicbrainz DiscIds Detector](#mb_discids_detector) -* [Musicbrainz UI enhancements](#mb_ui_enhancements) +- [Display shortcut for relationships on MusicBrainz](#mb_relationship_shortcuts) +- [Import Bandcamp releases to MusicBrainz](#bandcamp_importer) +- [Import Bandcamp releases to MusicBrainz Album Link Helper](#bandcamp_importer_helper) +- [Import Beatport Pro releases to MusicBrainz](#beatport_pro_importer) +- [Import Beatport releases to MusicBrainz](#beatport_importer) +- [Import CD Baby releases to MusicBrainz](#cdbaby_importer) +- [Import CD1D releases to MusicBrainz](#cd1d_importer) +- [Import DG/Decca releases to MusicBrainz](#dgdecca_importer) +- [Import Discogs releases to MusicBrainz](#discogs_importer) +- [Import Encyclopedisque releases to MusicBrainz](#encyclopedisque_importer) +- [Import FMA releases to MusicBrainz](#fma_importer) +- [Import Juno Download releases to MusicBrainz](#juno_download_importer) +- [Import Last.fm releases to MusicBrainz](#lastfm_importer) +- [Import Loot releases to MusicBrainz](#loot_importer) +- [Import Metal Archives releases into MusicBrainz](#metalarchives_importer) +- [Import Qobuz releases to MusicBrainz](#qobuz_importer) +- [Import Takealot releases to MusicBrainz](#takealot_importer) +- [MusicBrainz: Batch-add "performance of" relationships](#batch-add-recording-relationships) +- [MusicBrainz: Expand/collapse release groups](#expand-collapse-release-groups) +- [MusicBrainz: Fast cancel edits](#fast-cancel-edits) +- [MusicBrainz: Set recording comments for a release](#set-recording-comments) +- [Musicbrainz DiscIds Detector](#mb_discids_detector) +- [Musicbrainz UI enhancements](#mb_ui_enhancements) ## 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) [![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) - diff --git a/bandcamp_importer.user.js b/bandcamp_importer.user.js index 24dc7e3..eea87db 100644 --- a/bandcamp_importer.user.js +++ b/bandcamp_importer.user.js @@ -14,313 +14,335 @@ // @icon https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/assets/images/Musicbrainz_import_logo.png // ==/UserScript== - // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant this.$ = this.jQuery = jQuery.noConflict(true); if (!unsafeWindow) unsafeWindow = window; -String.prototype.fix_bandcamp_url = function () { +String.prototype.fix_bandcamp_url = function() { return this.replace('http://', 'https://'); }; var BandcampImport = { + // Analyze Bandcamp data and return a release object + retrieveReleaseInfo: function() { + let bandcampAlbumData = unsafeWindow.TralbumData; + let bandcampEmbedData = unsafeWindow.EmbedData; - - // Analyze Bandcamp data and return a release object - retrieveReleaseInfo: function () { - - var bandcampAlbumData = unsafeWindow.TralbumData; - var bandcampEmbedData = unsafeWindow.EmbedData; - - var release = { - discs: [], - artist_credit: [], - title: '', - year: 0, - month: 0, - day: 0, - parent_album_url: '', - labels: [], - format: 'Digital Media', - country: 'XW', - type: '', - status: 'official', - packaging: 'None', - language: 'eng', - script: 'Latn', - urls: [], - url: bandcampAlbumData.url.fix_bandcamp_url() - }; - - - // Grab release title - release.title = bandcampAlbumData.current.title; - - // Grab release event information - var date = this.convdate(bandcampAlbumData.current.release_date); - if (date) { - if (!(date.year > 2008 || (date.year == 2008 && date.month >= 9))) { - // use publish date if release date is before Bandcamp launch (2008-09) - var pdate = this.convdate(bandcampAlbumData.current.publish_date); - if (pdate) { - date = pdate; - } - } - release.year = date.year; - release.month = date.month; - release.day = date.day; - } - - // FIXME: implement a mapping between bandcamp release types and MB ones - if (bandcampAlbumData.current.type == "track") { - // map Bandcamp single tracks to singles - release.type = "single"; - // if track belongs to an album, get its url. - if (bandcampEmbedData.album_embed_data) { - release.parent_album_url = bandcampEmbedData.album_embed_data.linkback.fix_bandcamp_url(); - release.type = 'track'; // <-- no import - } - } - - // Tracks - var disc = { - tracks: [], - format: release.format - }; - release.discs.push(disc); - - // attempt to detect multiple artists tracks - // bandcamp formats them as 'artist - tracktitle' - // only set to true if ALL tracks are formatted like this - // and if string doesn't start with a number (ie. 02 - title) - var various_artists = true; - for (var i=0; i < bandcampAlbumData.trackinfo.length; i++) { - if (!bandcampAlbumData.trackinfo[i].title.match(/ - /) - || bandcampAlbumData.trackinfo[i].title.match(/^\d+ - /)) { - various_artists = false; - break; - } - } - - // Release artist credit - if (bandcampAlbumData.artist.match(/^various(?: artists)?$/i) - && various_artists) { - release.artist_credit = [ MBImport.specialArtist('various_artists') ]; - } else { - release.artist_credit = MBImport.makeArtistCredits([bandcampAlbumData.artist]); - } - - var tracks_streamable = 0; - $.each(bandcampAlbumData.trackinfo, function (index, bctrack) { - var title = bctrack.title; - var artist = []; - if (various_artists) { - var m = bctrack.title.match(/^(.+) - (.+)$/); - if (m) { - title = m[2]; - artist = [m[1]]; - } - } - if (bctrack.file) tracks_streamable++; - var track = { - 'title': title, - 'duration': Math.round(bctrack.duration * 1000), - 'artist_credit': MBImport.makeArtistCredits(artist) - }; - disc.tracks.push(track); - }); - - // Check for hidden tracks (more tracks in the download than shown for streaming ie.) - var showntracks = bandcampAlbumData.trackinfo.length; - var numtracks = -1; - var nostream = false; - // album description indicates number of tracks in the download - var match = /^\d+ track album$/.exec($("meta[property='og:description']").attr("content")); - if (match) { - numtracks = parseInt(match, 10); - } - if (numtracks > 0 && numtracks > showntracks) { - // display a warning if tracks in download differs from tracks shown - $('h2.trackTitle').append( - '

' + - 'Warning: ' + numtracks + ' vs ' + showntracks + ' tracks' + - '

' - ); - - // append unknown tracks to the release - for (var i = 0; i < numtracks - showntracks; i++) { - var track = { - 'title': '[unknown]', - 'duration': null, - 'artist_credit': [] + let release = { + discs: [], + artist_credit: [], + title: '', + year: 0, + month: 0, + day: 0, + parent_album_url: '', + labels: [], + format: 'Digital Media', + country: 'XW', + type: '', + status: 'official', + packaging: 'None', + language: 'eng', + script: 'Latn', + urls: [], + url: bandcampAlbumData.url.fix_bandcamp_url() }; - disc.tracks.push(track); - } - // disable stream link as only part of the album can be streamed - nostream = true; - } - // URLs - var link_type = MBImport.URL_TYPES; - // Download for free vs. for purchase - if (bandcampAlbumData.current.download_pref !== null) { - if (bandcampAlbumData.freeDownloadPage !== null || bandcampAlbumData.current.download_pref === 1 || ( - bandcampAlbumData.current.download_pref === 2 && bandcampAlbumData.current.minimum_price === 0)) { - release.urls.push({ - 'url': release.url, - 'link_type': link_type.download_for_free + // Grab release title + release.title = bandcampAlbumData.current.title; + + // Grab release event information + let date = this.convdate(bandcampAlbumData.current.release_date); + if (date) { + if (!(date.year > 2008 || (date.year == 2008 && date.month >= 9))) { + // use publish date if release date is before Bandcamp launch (2008-09) + let pdate = this.convdate(bandcampAlbumData.current.publish_date); + if (pdate) { + date = pdate; + } + } + release.year = date.year; + release.month = date.month; + release.day = date.day; + } + + // FIXME: implement a mapping between bandcamp release types and MB ones + if (bandcampAlbumData.current.type == 'track') { + // map Bandcamp single tracks to singles + release.type = 'single'; + // if track belongs to an album, get its url. + if (bandcampEmbedData.album_embed_data) { + release.parent_album_url = bandcampEmbedData.album_embed_data.linkback.fix_bandcamp_url(); + release.type = 'track'; // <-- no import + } + } + + // Tracks + let disc = { + tracks: [], + format: release.format + }; + release.discs.push(disc); + + // attempt to detect multiple artists tracks + // bandcamp formats them as 'artist - tracktitle' + // only set to true if ALL tracks are formatted like this + // and if string doesn't start with a number (ie. 02 - title) + let various_artists = true; + for (var i = 0; i < bandcampAlbumData.trackinfo.length; i++) { + if (!bandcampAlbumData.trackinfo[i].title.match(/ - /) || bandcampAlbumData.trackinfo[i].title.match(/^\d+ - /)) { + various_artists = false; + break; + } + } + + // Release artist credit + if (bandcampAlbumData.artist.match(/^various(?: artists)?$/i) && various_artists) { + release.artist_credit = [MBImport.specialArtist('various_artists')]; + } else { + release.artist_credit = MBImport.makeArtistCredits([bandcampAlbumData.artist]); + } + + let tracks_streamable = 0; + $.each(bandcampAlbumData.trackinfo, function(index, bctrack) { + let title = bctrack.title; + let artist = []; + if (various_artists) { + let m = bctrack.title.match(/^(.+) - (.+)$/); + if (m) { + title = m[2]; + artist = [m[1]]; + } + } + if (bctrack.file) tracks_streamable++; + let track = { + title: title, + duration: Math.round(bctrack.duration * 1000), + artist_credit: MBImport.makeArtistCredits(artist) + }; + disc.tracks.push(track); }); - } - if (bandcampAlbumData.current.download_pref === 2) { - release.urls.push({ - 'url': release.url, - 'link_type': link_type.purchase_for_download - }); - } - } - // Check if the release is streamable - if (bandcampAlbumData.hasAudio && !nostream && disc.tracks.length > 0 && disc.tracks.length == tracks_streamable) { - release.urls.push({ - 'url': release.url, - 'link_type': link_type.stream_for_free - }); - } - // Check if release is Creative Commons licensed - if ($("div#license a.cc-icons").length > 0) { - release.urls.push({ - 'url': $("div#license a.cc-icons").attr("href"), - 'link_type': link_type.license - }); - } - // Check if album has a back link to a label - var label = $("a.back-to-label-link span.back-to-label-name").text(); - if (label) { - release.labels.push({ - 'name': label, - 'mbid': '', - 'catno': 'none' - }); - } - return release; - }, + // Check for hidden tracks (more tracks in the download than shown for streaming ie.) + let showntracks = bandcampAlbumData.trackinfo.length; + let numtracks = -1; + let nostream = false; + // album description indicates number of tracks in the download + let match = /^\d+ track album$/.exec($("meta[property='og:description']").attr('content')); + if (match) { + numtracks = parseInt(match, 10); + } + if (numtracks > 0 && numtracks > showntracks) { + // display a warning if tracks in download differs from tracks shown + $('h2.trackTitle').append( + `${'

' + 'Warning: '}${numtracks} vs ${showntracks} tracks` + + `

` + ); - // Insert links in page - insertLink: function (release) { - if (release.type == "track") { - // only import album or single, tracks belong to an album - return false; + // append unknown tracks to the release + for (var i = 0; i < numtracks - showntracks; i++) { + let track = { + title: '[unknown]', + duration: null, + artist_credit: [] + }; + disc.tracks.push(track); + } + // disable stream link as only part of the album can be streamed + nostream = true; + } + + // URLs + let link_type = MBImport.URL_TYPES; + // Download for free vs. for purchase + if (bandcampAlbumData.current.download_pref !== null) { + if ( + bandcampAlbumData.freeDownloadPage !== null || + bandcampAlbumData.current.download_pref === 1 || + (bandcampAlbumData.current.download_pref === 2 && bandcampAlbumData.current.minimum_price === 0) + ) { + release.urls.push({ + url: release.url, + link_type: link_type.download_for_free + }); + } + if (bandcampAlbumData.current.download_pref === 2) { + release.urls.push({ + url: release.url, + link_type: link_type.purchase_for_download + }); + } + } + // Check if the release is streamable + if (bandcampAlbumData.hasAudio && !nostream && disc.tracks.length > 0 && disc.tracks.length == tracks_streamable) { + release.urls.push({ + url: release.url, + link_type: link_type.stream_for_free + }); + } + // Check if release is Creative Commons licensed + if ($('div#license a.cc-icons').length > 0) { + release.urls.push({ + url: $('div#license a.cc-icons').attr('href'), + link_type: link_type.license + }); + } + // Check if album has a back link to a label + let label = $('a.back-to-label-link span.back-to-label-name').text(); + if (label) { + release.labels.push({ + name: label, + mbid: '', + catno: 'none' + }); + } + + return release; + }, + + // Insert links in page + insertLink: function(release) { + if (release.type == 'track') { + // only import album or single, tracks belong to an album + return false; + } + // Form parameters + let edit_note = MBImport.makeEditNote(release.url, 'Bandcamp'); + let parameters = MBImport.buildFormParameters(release, edit_note); + // Build form + let mbUI = $(`
${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}
`).hide(); + + // Append MB import link + $('#name-section').append(mbUI); + $('#mb_buttons').css({ 'margin-top': '6px' }); + $('form.musicbrainz_import').css({ display: 'inline-block' }); + mbUI.slideDown(); + }, + + // helper to convert bandcamp date to MB date + convdate: function(date) { + if (typeof date != 'undefined' && date !== '') { + let d = new Date(date); + return { + year: d.getUTCFullYear(), + month: d.getUTCMonth() + 1, + day: d.getUTCDate() + }; + } + return false; } - // Form parameters - var edit_note = MBImport.makeEditNote(release.url, 'Bandcamp'); - var parameters = MBImport.buildFormParameters(release, edit_note); - // Build form - var mbUI = $('
' - + MBImport.buildFormHTML(parameters) - + MBImport.buildSearchButton(release) - + '
').hide(); - - // Append MB import link - $('#name-section').append(mbUI); - $('#mb_buttons').css({'margin-top': '6px'}); - $('form.musicbrainz_import').css({display: 'inline-block'}); - mbUI.slideDown(); - }, - - // helper to convert bandcamp date to MB date - convdate: function (date) { - if (typeof date != "undefined" && date !== "") { - var d = new Date(date); - return { - "year": d.getUTCFullYear(), - "month": d.getUTCMonth() + 1, - "day": d.getUTCDate() - }; - } - return false; - } }; -$(document).ready(function () { - /* keep the following line as first, it is required to skip - * pages which aren't actually a bandcamp page, since we support - * bandcamp pages under third-party domains. - * see @include - */ - if (!unsafeWindow.TralbumData) return; - /***/ +$(document).ready(function() { + /* keep the following line as first, it is required to skip + * pages which aren't actually a bandcamp page, since we support + * bandcamp pages under third-party domains. + * see @include + */ + if (!unsafeWindow.TralbumData) return; + /***/ - 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 - var root_url = release.url.match(/^(https?:\/\/[^\/]+)/)[1].split('?')[0]; - var label_url = ""; - mblinks.searchAndDisplayMbLink(root_url, 'artist', function (link) { $('div#name-section span[itemprop="byArtist"]').before(link); } ); - mblinks.searchAndDisplayMbLink(root_url, 'label', function (link) { $('p#band-name-location span.title').append(link); }, 'label:' + root_url ); - var labelback = $("a.back-to-label-link"); - if (labelback) { - var labelbacklink = labelback.attr('href'); - if (labelbacklink) { - label_url = labelbacklink.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 ); + // add MB artist link + let root_url = release.url.match(/^(https?:\/\/[^\/]+)/)[1].split('?')[0]; + let label_url = ''; + mblinks.searchAndDisplayMbLink(root_url, 'artist', function(link) { + $('div#name-section span[itemprop="byArtist"]').before(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) { + let labelbacklink = labelback.attr('href'); + if (labelbacklink) { + label_url = labelbacklink + .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) { - // try to get artist's mbid from cache - var artist_mbid = mblinks.resolveMBID(root_url); - if (artist_mbid) { - release.artist_credit[0].mbid = artist_mbid; + if (release.artist_credit.length == 1) { + // try to get artist's mbid from cache + let artist_mbid = mblinks.resolveMBID(root_url); + if (artist_mbid) { + release.artist_credit[0].mbid = artist_mbid; + } } - } - // try to get label mbid from cache - var label_mbid = ""; - var label_name = ""; - if (label_url) { - label_mbid = mblinks.resolveMBID('label:' + label_url); - label_name = $('a.back-to-label-link span.back-link-text ').contents().get(2).textContent; - } else { - 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) { - if (release.labels.length == 0) { - release.labels.push({ - 'name': '', - 'mbid': '', - 'catno': 'none' - }); + // try to get label mbid from cache + let label_mbid = ''; + let label_name = ''; + if (label_url) { + label_mbid = mblinks.resolveMBID(`label:${label_url}`); + label_name = $('a.back-to-label-link span.back-link-text ') + .contents() + .get(2).textContent; + } else { + 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) { + if (release.labels.length == 0) { + release.labels.push({ + name: '', + mbid: '', + catno: 'none' + }); + } + release.labels[0].name = label_name; + release.labels[0].mbid = label_mbid; } - release.labels[0].name = label_name; - release.labels[0].mbid = label_mbid; - } - BandcampImport.insertLink(release); - LOGGER.info("Parsed release: ", release); + BandcampImport.insertLink(release); + LOGGER.info('Parsed release: ', release); - if (release.type == 'track') { - // 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); } ); - } else { - // add MB release links to album or single - mblinks.searchAndDisplayMbLink(release.url, 'release', function (link) { $('div#name-section span[itemprop="byArtist"]').after(link); } ); - } + if (release.type == 'track') { + // 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); + }); + } else { + // add MB release links to album or single + 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 - $("div.tralbum-tags a:not(:last-child).tag").after(", "); + // append a comma after each tag to ease cut'n'paste to MB + $('div.tralbum-tags a:not(:last-child).tag').after(', '); - // append a link to the full size image - var fullsizeimageurl = $("div#tralbumArt a").attr("href").replace('_10', '_0'); - $("div#tralbumArt").after(""); - - $("div#bci_link").css({ 'padding-top': '0.5em', 'text-align': 'right' }); - $("div#bci_link a").css({ 'font-weight': 'bold' }); + // append a link to the full size image + let fullsizeimageurl = $('div#tralbumArt a') + .attr('href') + .replace('_10', '_0'); + $('div#tralbumArt').after( + `` + ); + $('div#bci_link').css({ 'padding-top': '0.5em', 'text-align': 'right' }); + $('div#bci_link a').css({ 'font-weight': 'bold' }); }); diff --git a/bandcamp_importer_helper.user.js b/bandcamp_importer_helper.user.js index 8592c7d..21858fe 100644 --- a/bandcamp_importer_helper.user.js +++ b/bandcamp_importer_helper.user.js @@ -18,12 +18,13 @@ this.$ = this.jQuery = jQuery.noConflict(true); if (!unsafeWindow) unsafeWindow = window; -$(document).ready(function () { - // Display a link to the correct album bandcamp url (ie. main page or releases page) - var bandcampAlbumData = unsafeWindow.TralbumData; - if (bandcampAlbumData && bandcampAlbumData.url) { - var innerHTML = '
' + 'Album page (MB import)
'; - $('#name-section').append(innerHTML); - } +$(document).ready(function() { + // Display a link to the correct album bandcamp url (ie. main page or releases page) + let bandcampAlbumData = unsafeWindow.TralbumData; + if (bandcampAlbumData && bandcampAlbumData.url) { + let innerHTML = `${'
' + 'Album page (MB import)
`; + $('#name-section').append(innerHTML); + } }); diff --git a/batch-add-recording-relationships.user.js b/batch-add-recording-relationships.user.js index 35ab895..5fd6b41 100644 --- a/batch-add-recording-relationships.user.js +++ b/batch-add-recording-relationships.user.js @@ -39,14 +39,13 @@ // authorization. // ==/License== -var scr = document.createElement("script"); -scr.textContent = "(" + batch_recording_rels + ")();"; +var scr = document.createElement('script'); +scr.textContent = `(${batch_recording_rels})();`; document.body.appendChild(scr); function batch_recording_rels() { - function setting(name) { - name = 'bpr_' + name; + name = `bpr_${name}`; if (arguments.length === 2) { localStorage.setItem(name, arguments[1]); @@ -64,8 +63,8 @@ function batch_recording_rels() { return 0; } - var aLen = a.length; - var bLen = b.length; + let aLen = a.length; + let bLen = b.length; if (aLen === 0) { return bLen; @@ -75,14 +74,14 @@ function batch_recording_rels() { return aLen; } - var bCharCode; - var ret; - var tmp; - var tmp2; - var i = 0; - var j = 0; - var arr = []; - var charCodeCache = []; + let bCharCode; + let ret; + let tmp; + let tmp2; + let i = 0; + let j = 0; + let arr = []; + let charCodeCache = []; while (i < aLen) { charCodeCache[i] = a.charCodeAt(i); @@ -97,7 +96,7 @@ function batch_recording_rels() { for (i = 0; i < aLen; i++) { tmp2 = bCharCode === charCodeCache[i] ? tmp : tmp + 1; tmp = arr[i]; - ret = arr[i] = tmp > ret ? tmp2 > ret ? ret + 1 : tmp2 : tmp2 > tmp ? tmp + 1 : tmp2; + ret = arr[i] = tmp > ret ? (tmp2 > ret ? ret + 1 : tmp2) : tmp2 > tmp ? tmp + 1 : tmp2; } } @@ -107,41 +106,41 @@ function batch_recording_rels() { // HTML helpers function make_element(el_name, args) { - var el = $("<"+el_name+">"); + let el = $(`<${el_name}>`); el.append.apply(el, args); return el; } function td() { - return make_element("td", arguments); + return make_element('td', arguments); } function tr() { - return make_element("tr", arguments); + return make_element('tr', arguments); } function table() { - return make_element("table", arguments); + return make_element('table', arguments); } function label() { - return make_element("label", arguments); + return make_element('label', arguments); } function goBtn(func) { - return $("").click(func); + return $('').click(func); } // Date parsing utils - var dateRegex = /^(\d{4}|\?{4})(?:-(\d{2}|\?{2})(?:-(\d{2}|\?{2}))?)?$/; - var integerRegex = /^[0-9]+$/; + let dateRegex = /^(\d{4}|\?{4})(?:-(\d{2}|\?{2})(?:-(\d{2}|\?{2}))?)?$/; + let integerRegex = /^[0-9]+$/; function parseInteger(num) { return integerRegex.test(num) ? parseInt(num, 10) : NaN; } function parseIntegerOrNull(str) { - var integer = parseInteger(str); + let integer = parseInteger(str); return isNaN(integer) ? null : integer; } function parseDate(str) { - var match = str.match(dateRegex) || []; + let match = str.match(dateRegex) || []; return { year: parseIntegerOrNull(match[1]), month: parseIntegerOrNull(match[2]), @@ -153,9 +152,9 @@ function batch_recording_rels() { return value !== null && value !== undefined && value !== ''; } - var daysInMonth = { - "true": [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], - "false": [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + let daysInMonth = { + true: [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], + false: [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] }; function isDateValid(y, m, d) { @@ -166,15 +165,15 @@ function batch_recording_rels() { if (y !== null && y < 1) return false; if (m !== null && (m < 1 || m > 12)) return false; if (d === null) return true; - var isLeapYear = y % 400 ? (y % 100 ? !(y % 4) : false) : true; + let isLeapYear = y % 400 ? (y % 100 ? !(y % 4) : false) : true; if (d < 1 || d > 31 || d > daysInMonth[isLeapYear.toString()][m]) return false; return true; } // Request rate limiting - var REQUEST_COUNT = 0; - setInterval(function () { + let REQUEST_COUNT = 0; + setInterval(function() { if (REQUEST_COUNT > 0) { REQUEST_COUNT -= 1; } @@ -189,7 +188,7 @@ function batch_recording_rels() { this.stopped = false; } - RequestManager.prototype.next = function () { + RequestManager.prototype.next = function() { if (this.stopped || !this.queue.length) { this.active = false; return; @@ -199,317 +198,361 @@ function batch_recording_rels() { REQUEST_COUNT += this.count; if (REQUEST_COUNT >= 10) { - var diff = REQUEST_COUNT - 9; - var timeout = diff * 1000; + let diff = REQUEST_COUNT - 9; + let timeout = diff * 1000; - setTimeout(function (self) { self.next() }, this.rate + timeout, this); + setTimeout( + function(self) { + self.next(); + }, + this.rate + timeout, + this + ); } else { - setTimeout(function (self) { self.next() }, this.rate, this); + setTimeout( + function(self) { + self.next(); + }, + this.rate, + this + ); } }; - RequestManager.prototype.push_get = function (url, cb) { - this.push(function () {$.get(url, cb);}); + RequestManager.prototype.push_get = function(url, cb) { + this.push(function() { + $.get(url, cb); + }); }; - RequestManager.prototype.unshift_get = function (url, cb) { - this.unshift(function () {$.get(url, cb);}); + RequestManager.prototype.unshift_get = function(url, cb) { + this.unshift(function() { + $.get(url, cb); + }); }; - RequestManager.prototype.push = function (req) { + RequestManager.prototype.push = function(req) { this.queue.push(req); this.maybe_start_queue(); }; - RequestManager.prototype.unshift = function (req) { + RequestManager.prototype.unshift = function(req) { this.queue.unshift(req); this.maybe_start_queue(); }; - RequestManager.prototype.maybe_start_queue = function () { + RequestManager.prototype.maybe_start_queue = function() { if (!(this.active || this.stopped)) { this.start_queue(); } }; - RequestManager.prototype.start_queue = function () { + RequestManager.prototype.start_queue = function() { if (this.active) { return; } this.active = true; this.stopped = false; - var now = new Date().getTime(); + let now = new Date().getTime(); if (now - this.last >= this.rate) { this.next(); } else { - var timeout = this.rate - now + this.last; - setTimeout(function (self) { self.next() }, timeout, this); + let timeout = this.rate - now + this.last; + setTimeout( + function(self) { + self.next(); + }, + timeout, + this + ); } }; - var ws_requests = new RequestManager(1000, 1); - var edit_requests = new RequestManager(1500, 2); + let ws_requests = new RequestManager(1000, 1); + let edit_requests = new RequestManager(1500, 2); // Get recordings on the page - var TITLE_SELECTOR = "a[href*='/recording/']"; - var $recordings = $('tr:has(' + TITLE_SELECTOR + ')').data('filtered', false); + let TITLE_SELECTOR = "a[href*='/recording/']"; + let $recordings = $(`tr:has(${TITLE_SELECTOR})`).data('filtered', false); if (!$recordings.length) { return; } - var MBID_REGEX = /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/; - var WITHOUT_PAREN_CLAUSES_REGEX = /^(.+?)(?:(?: \([^()]+\))+)?$/; - var ASCII_PUNCTUATION = [ - [/…/g, "..."], + let MBID_REGEX = /[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}/; + let WITHOUT_PAREN_CLAUSES_REGEX = /^(.+?)(?:(?: \([^()]+\))+)?$/; + let ASCII_PUNCTUATION = [ + [/…/g, '...'], [/‘/g, "'"], [/’/g, "'"], [/‚/g, "'"], - [/“/g, "\""], - [/”/g, "\""], - [/„/g, "\""], + [/“/g, '"'], + [/”/g, '"'], + [/„/g, '"'], [/′/g, "'"], - [/″/g, "\""], - [/‹/g, "<"], - [/›/g, ">"], - [/‐/g, "-"], - [/‒/g, "-"], - [/–/g, "-"], - [/−/g, "-"], - [/—/g, "-"], - [/―/g, "--"] + [/″/g, '"'], + [/‹/g, '<'], + [/›/g, '>'], + [/‐/g, '-'], + [/‒/g, '-'], + [/–/g, '-'], + [/−/g, '-'], + [/—/g, '-'], + [/―/g, '--'] ]; function normalizeTitle(title) { title = title.toLowerCase().replace(/\s+/g, ''); - _.each(ASCII_PUNCTUATION, function (val) { + _.each(ASCII_PUNCTUATION, function(val) { title = title.replace(val[0], val[1]); }); return title; } - var RECORDING_TITLES = _.chain($recordings) - .map(function (row) { - var $title = $(row).find(TITLE_SELECTOR), - mbid = $title.attr('href').match(MBID_REGEX)[0], - norm_title = normalizeTitle($title.text().match(WITHOUT_PAREN_CLAUSES_REGEX)[1]); + let RECORDING_TITLES = _.chain($recordings) + .map(function(row) { + let $title = $(row).find(TITLE_SELECTOR), + mbid = $title.attr('href').match(MBID_REGEX)[0], + norm_title = normalizeTitle($title.text().match(WITHOUT_PAREN_CLAUSES_REGEX)[1]); return [mbid, norm_title]; }) .fromPairs() .value(); - var $work_options = _.chain(['type', 'language']) - .map(function (kind) { return [kind, $('')]; }) + let $work_options = _.chain(['type', 'language']) + .map(function(kind) { + return [kind, $(``)]; + }) .fromPairs() .value(); // Add button to manage performance ARs - var $relate_table = table( - tr(td(label("New work with this title:").attr('for',"bpr-new-work")), - td('', - goBtn(relate_to_new_titled_work))), - tr(td(label("Existing work (URL/MBID):").attr('for',"bpr-existing-work")), - td(entity_lookup('existing-work', "work"), - goBtn(relate_to_existing_work))), - tr(td("New works using recording titles"), - td(goBtn(relate_to_new_works))), - tr(td("Their suggested works"), - td(goBtn(relate_to_suggested_works))), - tr(td(label("Work type:").attr('for',"bpr-work-type")), - td($work_options['type'])), - tr(td(label("Lyrics language:").attr('for', "bpr-work-language")), - td($work_options['language']))).hide(); + let $relate_table = table( + tr( + td(label('New work with this title:').attr('for', 'bpr-new-work')), + td('', goBtn(relate_to_new_titled_work)) + ), + tr( + td(label('Existing work (URL/MBID):').attr('for', 'bpr-existing-work')), + td(entity_lookup('existing-work', 'work'), goBtn(relate_to_existing_work)) + ), + tr(td('New works using recording titles'), td(goBtn(relate_to_new_works))), + tr(td('Their suggested works'), td(goBtn(relate_to_suggested_works))), + tr(td(label('Work type:').attr('for', 'bpr-work-type')), td($work_options['type'])), + tr(td(label('Lyrics language:').attr('for', 'bpr-work-language')), td($work_options['language'])) + ).hide(); - var $works_table = table( - $('').append( - td(label("Load another artist’s works (URL/MBID):").attr('for', "bpr-load-artist")), - td(entity_lookup('load-artist', "artist"), - goBtn(load_artist_works_btn))) - .hide()); + let $works_table = table( + $('') + .append( + td(label('Load another artist’s works (URL/MBID):').attr('for', 'bpr-load-artist')), + td(entity_lookup('load-artist', 'artist'), goBtn(load_artist_works_btn)) + ) + .hide() + ); - var $container = table( - tr(td("

Relate checked recordings to…

"), - td("

Cached works

", - $("(These are used to auto-suggest works.)") - .css("font-size", "0.9em"))), - tr(td($relate_table), - td($works_table))) - .css({"margin": "0.5em", "background": "#F2F2F2", "border": "1px #999 solid"}) - .insertAfter($("div#content h2")[0]); + let $container = table( + tr( + td('

Relate checked recordings to…

'), + td('

Cached works

', $('(These are used to auto-suggest works.)').css('font-size', '0.9em')) + ), + tr(td($relate_table), td($works_table)) + ) + .css({ margin: '0.5em', background: '#F2F2F2', border: '1px #999 solid' }) + .insertAfter($('div#content h2')[0]); - var hide_performed_recs = setting('hide_performed_recs') === 'true' ? true : false; - var hide_pending_edits = setting('hide_pending_edits') === 'true' ? true : false; + let hide_performed_recs = setting('hide_performed_recs') === 'true' ? true : false; + let hide_pending_edits = setting('hide_pending_edits') === 'true' ? true : false; function make_checkbox(func, default_val, lbl) { - var chkbox = $('') - .on("change", func) - .attr("checked", default_val); - return label(chkbox, lbl) + let chkbox = $('') + .on('change', func) + .attr('checked', default_val); + return label(chkbox, lbl); } - var $display_table = table( - tr(td(label("Filter recordings list: ", - $('').on("input", filter_recordings))), - td(make_checkbox(toggle_performed_recordings, hide_performed_recs, - "Hide recordings with performance ARs"), - " ", - make_checkbox(toggle_pending_edits, hide_pending_edits, - "Hide recordings with pending edits")))) - .css("margin", "0.5em") + let $display_table = table( + tr( + td(label('Filter recordings list: ', $('').on('input', filter_recordings))), + td( + make_checkbox(toggle_performed_recordings, hide_performed_recs, 'Hide recordings with performance ARs'), + ' ', + make_checkbox(toggle_pending_edits, hide_pending_edits, 'Hide recordings with pending edits') + ) + ) + ) + .css('margin', '0.5em') .insertAfter($container); - var $recordings_load_msg = $("Loading performance relationships…"); + let $recordings_load_msg = $('Loading performance relationships…'); - $container.find("table").find("td").css("width", "auto"); - $container.children("tbody").children("tr").children("td").css({ padding: "0.5em", "vertical-align": "top" }); + $container + .find('table') + .find('td') + .css('width', 'auto'); + $container + .children('tbody') + .children('tr') + .children('td') + .css({ padding: '0.5em', 'vertical-align': 'top' }); // Get actual work types/languages - ws_requests.unshift_get('/dialog?path=%2Fwork%2Fcreate', function (data) { - var nodes = $.parseHTML(data); + ws_requests.unshift_get('/dialog?path=%2Fwork%2Fcreate', function(data) { + let nodes = $.parseHTML(data); function populate($obj, kind) { - $obj - .append($('#id-edit-work\\.' + kind + '_id', nodes).children()) - .val(setting('work_'+ kind) || 0) - .on('change', function () { - setting('work_' + kind, this.value); + $obj.append($(`#id-edit-work\\.${kind}_id`, nodes).children()) + .val(setting(`work_${kind}`) || 0) + .on('change', function() { + setting(`work_${kind}`, this.value); }); } _.each($work_options, populate); }); - $("") + $('') .append(' ', $recordings_load_msg) .insertBefore($relate_table); // Add additional column - $(".tbl > thead > tr").append("Performance Attributes"); + $('.tbl > thead > tr').append('Performance Attributes'); - var $date_element = $('') + let $date_element = $('') .attr('type', 'text') .attr('placeholder', 'yyyy-mm-dd') .addClass('date') .addClass('bpr-date-input') - .css({ color : "#ddd", "width": "7em", border: "1px #999 solid" }); + .css({ color: '#ddd', width: '7em', border: '1px #999 solid' }); - $recordings.append(td( - $('part./' + - 'live/' + - 'inst./' + - 'cover') - .css("cursor", "pointer") - .data("checked", false), - ' ', - $date_element).addClass("bpr_attrs")); + $recordings.append( + td( + $( + 'part./' + + 'live/' + + 'inst./' + + 'cover' + ) + .css('cursor', 'pointer') + .data('checked', false), + ' ', + $date_element + ).addClass('bpr_attrs') + ); $(document) - .on('input', 'input.bpr-date-input', function () { - var $input = $(this); + .on('input', 'input.bpr-date-input', function() { + let $input = $(this); - $input.css("border-color", "#999"); + $input.css('border-color', '#999'); if (this.value) { - $input.css("color", "#000"); + $input.css('color', '#000'); - var parsedDate = parseDate(this.value); - if ((parsedDate.year || parsedDate.month || parsedDate.day) && - isDateValid(parsedDate.year, parsedDate.month, parsedDate.day)) { + let parsedDate = parseDate(this.value); + if ( + (parsedDate.year || parsedDate.month || parsedDate.day) && + isDateValid(parsedDate.year, parsedDate.month, parsedDate.day) + ) { } else { - $input.css("border-color", "#f00"); + $input.css('border-color', '#f00'); parsedDate = null; } - $input.parent().data("date", parsedDate); + $input.parent().data('date', parsedDate); } else { - $input.css("color", "#ddd"); + $input.css('color', '#ddd'); } }) - .on('click', 'span.bpr-attr', function () { - var $this = $(this); - var checked = !$this.data('checked'); + .on('click', 'span.bpr-attr', function() { + let $this = $(this); + let checked = !$this.data('checked'); - $this - .data('checked', checked) - .css({ - background: checked ? 'blue': 'inherit', - color: checked ? 'white' : 'black' - }); - }) + $this.data('checked', checked).css({ + background: checked ? 'blue' : 'inherit', + color: checked ? 'white' : 'black' + }); + }); // Style buttons function style_buttons($buttons) { return $buttons.css({ - "color": "#565656", - "background-color": "#FFFFFF", - "border": "1px solid #D0D0D0", - "border-top": "1px solid #EAEAEA", - "border-left": "1px solid #EAEAEA"}); + color: '#565656', + 'background-color': '#FFFFFF', + border: '1px solid #D0D0D0', + 'border-top': '1px solid #EAEAEA', + 'border-left': '1px solid #EAEAEA' + }); } - style_buttons($container.find("button")); + style_buttons($container.find('button')); // Don't check hidden rows when the "select all" checkbox is pressed function uncheckRows($rows) { - $rows.find("input[name=add-to-merge]").attr("checked", false); + $rows.find('input[name=add-to-merge]').attr('checked', false); } - $(".tbl > thead input[type=checkbox]") - .on("change", function () { - if (this.checked) { - uncheckRows($recordings.filter(":hidden")); - } - }); + $('.tbl > thead input[type=checkbox]').on('change', function() { + if (this.checked) { + uncheckRows($recordings.filter(':hidden')); + } + }); - var ARTIST_MBID = window.location.href.match(MBID_REGEX)[0]; - var ARTIST_NAME = $("h1 a").text(); - var $artist_works_msg = $(""); + let ARTIST_MBID = window.location.href.match(MBID_REGEX)[0]; + let ARTIST_NAME = $('h1 a').text(); + let $artist_works_msg = $(''); // Load performance relationships - var CURRENT_PAGE = 1; - var TOTAL_PAGES = 1; - var page_numbers = $(".pagination .sel")[0]; - var recordings_not_parsed = $recordings.length; + let CURRENT_PAGE = 1; + let TOTAL_PAGES = 1; + let page_numbers = $('.pagination .sel')[0]; + let recordings_not_parsed = $recordings.length; if (page_numbers !== undefined) { - CURRENT_PAGE = parseInt(page_numbers.href.match(/.+\?page=(\d+)/)[1] || "1", 10); - var re_match = $("a[rel=xhv\\:last]:first").next("em").text().match(/Page \d+ of (\d+)/); + CURRENT_PAGE = parseInt(page_numbers.href.match(/.+\?page=(\d+)/)[1] || '1', 10); + let re_match = $('a[rel=xhv\\:last]:first') + .next('em') + .text() + .match(/Page \d+ of (\d+)/); TOTAL_PAGES = Math.ceil((re_match ? parseInt(re_match[1], 10) : 1) / 2); } - var NAME_FILTER = $.trim($("#id-filter\\.name").val()); - var ARTIST_FILTER = $.trim($("#id-filter\\.artist_credit_id").find("option:selected").text()); + let NAME_FILTER = $.trim($('#id-filter\\.name').val()); + let ARTIST_FILTER = $.trim( + $('#id-filter\\.artist_credit_id') + .find('option:selected') + .text() + ); if (NAME_FILTER || ARTIST_FILTER) { get_filtered_page(0); } else { queue_recordings_request( - "/ws/2/recording?artist=" + ARTIST_MBID + - "&inc=work-rels" + - "&limit=100" + - "&offset=" + ((CURRENT_PAGE - 1) * 100) + - "&fmt=json" + `/ws/2/recording?artist=${ARTIST_MBID}&inc=work-rels` + `&limit=100` + `&offset=${(CURRENT_PAGE - 1) * 100}&fmt=json` ); } function request_recordings(url) { - var attempts = 1; + let attempts = 1; - $.get(url, function (data) { - var recs = data.recordings; - var cache = {}; + $.get(url, function(data) { + let recs = data.recordings; + let cache = {}; function extract_rec(node) { - var row = cache[node.id]; + let row = cache[node.id]; if (row === undefined) { - for (var j = 0; j < $recordings.length; j++) { - var row_ = $recordings[j]; - var row_id = $(row_).find(TITLE_SELECTOR).attr("href").match(MBID_REGEX)[0]; + for (let j = 0; j < $recordings.length; j++) { + let row_ = $recordings[j]; + let row_id = $(row_) + .find(TITLE_SELECTOR) + .attr('href') + .match(MBID_REGEX)[0]; if (node.id === row_id) { row = row_; @@ -533,44 +576,37 @@ function batch_recording_rels() { } if (hide_performed_recs) { - $recordings.filter(".performed").hide(); + $recordings.filter('.performed').hide(); restripeRows(); } }) - .done(function () { - $recordings_load_msg.parent().remove(); - $relate_table.show(); - load_works_init(); - }) - .fail(function () { - $recordings_load_msg - .text("Error loading relationships. Retry #" + attempts + "...") - .css("color", "red"); - attempts += 1; - ws_requests.unshift(request_recordings); - }); + .done(function() { + $recordings_load_msg.parent().remove(); + $relate_table.show(); + load_works_init(); + }) + .fail(function() { + $recordings_load_msg.text(`Error loading relationships. Retry #${attempts}...`).css('color', 'red'); + attempts += 1; + ws_requests.unshift(request_recordings); + }); } function queue_recordings_request(url) { - ws_requests.push(function () { + ws_requests.push(function() { request_recordings(url); }); } function get_filtered_page(page) { - var url = ( - "/ws/2/recording?query=" + - (NAME_FILTER ? encodeURIComponent(NAME_FILTER) + "%20AND%20" : "") + - (ARTIST_FILTER ? "creditname:" + encodeURIComponent(ARTIST_FILTER) + "%20AND%20" : "") + - " arid:" + ARTIST_MBID + - "&limit=100" + - "&offset=" + (page * 100) + - "&fmt=json" - ); + let url = + `/ws/2/recording?query=${NAME_FILTER ? `${encodeURIComponent(NAME_FILTER)}%20AND%20` : ''}${ + ARTIST_FILTER ? `creditname:${encodeURIComponent(ARTIST_FILTER)}%20AND%20` : '' + } arid:${ARTIST_MBID}&limit=100` + `&offset=${page * 100}&fmt=json`; - ws_requests.push_get(url, function (data) { - _.each(data.recordings, function (r) { - queue_recordings_request("/ws/2/recording/" + r.id + "?inc=work-rels&fmt=json"); + ws_requests.push_get(url, function(data) { + _.each(data.recordings, function(r) { + queue_recordings_request(`/ws/2/recording/${r.id}?inc=work-rels&fmt=json`); }); if (recordings_not_parsed > 0 && page < TOTAL_PAGES - 1) { @@ -580,67 +616,73 @@ function batch_recording_rels() { } function parse_recording(node, $row) { - var $attrs = $row.children("td.bpr_attrs"); - var performed = false; + let $attrs = $row.children('td.bpr_attrs'); + let performed = false; - $row.data("performances", []); - $attrs.data("checked", false).css("color", "black"); + $row.data('performances', []); + $attrs.data('checked', false).css('color', 'black'); - _.each(node.relations, function (rel) { + _.each(node.relations, function(rel) { if (rel.type.match(/performance/)) { if (!performed) { - $row.addClass("performed"); + $row.addClass('performed'); performed = true; } if (rel.begin) { - $attrs.find("input.date").val(rel.begin).trigger("input"); + $attrs + .find('input.date') + .val(rel.begin) + .trigger('input'); } - var attrs = []; - _.each(rel.attributes, function (name) { - var cannonical_name = name.toLowerCase(); - var $button = $attrs.find("span." + cannonical_name); + let attrs = []; + _.each(rel.attributes, function(name) { + let cannonical_name = name.toLowerCase(); + let $button = $attrs.find(`span.${cannonical_name}`); attrs.push(cannonical_name); - if (!$button.data("checked")) { + if (!$button.data('checked')) { $button.click(); } }); add_work_link($row, rel.work.id, rel.work.title, rel.work.disambiguation, attrs); - $row.data("performances").push(rel.work.id); + $row.data('performances').push(rel.work.id); } }); //Use the dates in "live YYYY-MM-DD" disambiguation comments - var comment = node.disambiguation; - var date = comment && comment.match && comment.match(/live(?: .+)?, ([0-9]{4}(?:-[0-9]{2}(?:-[0-9]{2})?)?)(?:\: .+)?$/); + let comment = node.disambiguation; + let date = comment && comment.match && comment.match(/live(?: .+)?, ([0-9]{4}(?:-[0-9]{2}(?:-[0-9]{2})?)?)(?:\: .+)?$/); if (date) { - $attrs.find("input.date").val(date[1]).trigger("input"); + $attrs + .find('input.date') + .val(date[1]) + .trigger('input'); } if (!performed) { if (node.title.match(/.+\(live.*\)/) || (comment && comment.match && comment.match(/^live.*/))) { - $attrs.find("span.live").click(); + $attrs.find('span.live').click(); } else { - var url = "/ws/2/recording/" + node.id + "?inc=releases+release-groups&fmt=json"; + let url = `/ws/2/recording/${node.id}?inc=releases+release-groups&fmt=json`; - var request_rec = function () { - $.get(url, function (data) { - var releases = data.releases; + var request_rec = function() { + $.get(url, function(data) { + let releases = data.releases; - for (var i = 0; i < releases.length; i++) { - if (_.includes(releases[i]["release-group"]["secondary-types"], "Live")) { - $attrs.find("span.live").click(); + for (let i = 0; i < releases.length; i++) { + if (_.includes(releases[i]['release-group']['secondary-types'], 'Live')) { + $attrs.find('span.live').click(); break; } } - }).fail(function () { + }).fail(function() { ws_requests.push(request_rec); }); - } + }; ws_requests.push(request_rec); } } @@ -648,23 +690,23 @@ function batch_recording_rels() { // Load works - var WORKS_LOAD_CACHE = []; - var LOADED_WORKS = {}; - var LOADED_ARTISTS = {}; + let WORKS_LOAD_CACHE = []; + let LOADED_WORKS = {}; + let LOADED_ARTISTS = {}; function load_works_init() { - var artists_string = localStorage.getItem("bpr_artists " + ARTIST_MBID); - var artists = []; + let artists_string = localStorage.getItem(`bpr_artists ${ARTIST_MBID}`); + let artists = []; if (artists_string) { - artists = artists_string.split("\n"); + artists = artists_string.split('\n'); } function callback() { if (artists.length > 0) { - var parts = artists.pop(); - var mbid = parts.slice(0, 36); - var name = parts.slice(36); + let parts = artists.pop(); + let mbid = parts.slice(0, 36); + let name = parts.slice(36); if (mbid && name) { load_artist_works(mbid, name).done(callback); @@ -676,7 +718,7 @@ function batch_recording_rels() { } function load_artist_works(mbid, name) { - var deferred = $.Deferred(); + let deferred = $.Deferred(); if (LOADED_ARTISTS[mbid]) { return deferred.promise(); @@ -684,50 +726,51 @@ function batch_recording_rels() { LOADED_ARTISTS[mbid] = true; - var $table_row = $(""); - var $button_cell = $("").css("display", "none"); - var $msg = $artist_works_msg; + let $table_row = $(''); + let $button_cell = $('').css('display', 'none'); + let $msg = $artist_works_msg; if (mbid !== ARTIST_MBID) { - $msg = $(""); + $msg = $(''); $button_cell.append( - style_buttons($("")) - .click(function () { - $table_row.remove(); - remove_artist_works(mbid); - })); + style_buttons($('')).click(function() { + $table_row.remove(); + remove_artist_works(mbid); + }) + ); } - var $reload = style_buttons($("")) - .click(function () { - $button_cell.css("display", "none"); - $msg.text("Loading works for " + name + "..."); + let $reload = style_buttons($('')) + .click(function() { + $button_cell.css('display', 'none'); + $msg.text(`Loading works for ${name}...`); load(); }) .prependTo($button_cell); - $msg.text("Loading works for " + name + "...").css("color", "green"), - $table_row.append($msg, $button_cell); - $("tr#bpr-works-row").css("display", "none").before($table_row); + $msg.text(`Loading works for ${name}...`).css('color', 'green'), $table_row.append($msg, $button_cell); + $('tr#bpr-works-row') + .css('display', 'none') + .before($table_row); - var works_date = localStorage.getItem("bpr_works_date " + mbid); - var result = []; + let works_date = localStorage.getItem(`bpr_works_date ${mbid}`); + let result = []; function finished(result) { - var parsed = load_works_finish(result); + let parsed = load_works_finish(result); update_artist_works_msg($msg, result.length, name, works_date); - $button_cell.css("display", "table-cell"); - $("tr#bpr-works-row").css("display", "table-row"); + $button_cell.css('display', 'table-cell'); + $('tr#bpr-works-row').css('display', 'table-row'); deferred.resolve(); match_works(parsed[0], parsed[1], parsed[2], parsed[3]); } if (works_date) { - var works_string = localStorage.getItem("bpr_works " + mbid); + let works_string = localStorage.getItem(`bpr_works ${mbid}`); if (works_string) { - finished(works_string.split("\n")); + finished(works_string.split('\n')); return deferred.promise(); } } @@ -735,21 +778,21 @@ function batch_recording_rels() { load(); function load() { works_date = new Date().toString(); - localStorage.setItem("bpr_works_date " + mbid, works_date); + localStorage.setItem(`bpr_works_date ${mbid}`, works_date); result = []; - var callback = function (loaded, remaining) { + let callback = function(loaded, remaining) { result.push.apply(result, loaded); if (remaining > 0) { - $msg.text("Loading " + remaining.toString() + " works for " + name + "..."); + $msg.text(`Loading ${remaining.toString()} works for ${name}...`); } else { - localStorage.setItem("bpr_works " + mbid, result.join("\n")); + localStorage.setItem(`bpr_works ${mbid}`, result.join('\n')); finished(result); } }; - var works_url = "/ws/2/work?artist=" + mbid + "&inc=aliases&limit=100&fmt=json"; - ws_requests.unshift(function () { + let works_url = `/ws/2/work?artist=${mbid}&inc=aliases&limit=100&fmt=json`; + ws_requests.unshift(function() { request_works(works_url, 0, -1, callback); }); } @@ -758,47 +801,47 @@ function batch_recording_rels() { } function load_works_finish(result) { - var tmp_mbids = []; - var tmp_titles = []; - var tmp_comments = []; - var tmp_norm_titles = []; + let tmp_mbids = []; + let tmp_titles = []; + let tmp_comments = []; + let tmp_norm_titles = []; - _.each(result, function (parts) { - var mbid = parts.slice(0, 36); - var rest = parts.slice(36).split("\u00a0"); + _.each(result, function(parts) { + let mbid = parts.slice(0, 36); + let rest = parts.slice(36).split('\u00a0'); LOADED_WORKS[mbid] = true; tmp_mbids.push(mbid); tmp_titles.push(rest[0]); - tmp_comments.push(rest[1] || ""); + tmp_comments.push(rest[1] || ''); tmp_norm_titles.push(normalizeTitle(rest[0])); }); return [tmp_mbids, tmp_titles, tmp_comments, tmp_norm_titles]; } function request_works(url, offset, count, callback) { - $.get(url + "&offset=" + offset, function (data, textStatus, jqXHR) { + $.get(`${url}&offset=${offset}`, function(data, textStatus, jqXHR) { if (count < 0) { count = data['work-count']; } - var works = data.works; - var loaded = []; + let works = data.works; + let loaded = []; - _.each(works, function (work) { - var comment = work.disambiguation; - loaded.push(work.id + work.title + (comment ? "\u00a0" + comment : "")); + _.each(works, function(work) { + let comment = work.disambiguation; + loaded.push(work.id + work.title + (comment ? `\u00a0${comment}` : '')); }); callback(loaded, count - offset - works.length); if (works.length + offset < count) { - ws_requests.unshift(function () { + ws_requests.unshift(function() { request_works(url, offset + 100, count, callback); }); } - }).fail(function () { - ws_requests.unshift(function () { + }).fail(function() { + ws_requests.unshift(function() { request_works(url, offset, count, callback); }); }); @@ -809,7 +852,7 @@ function batch_recording_rels() { return; } - var $not_performed = $recordings.filter(":not(.performed)"); + let $not_performed = $recordings.filter(':not(.performed)'); if (!$not_performed.length) { return; } @@ -820,27 +863,28 @@ function batch_recording_rels() { return r == w ? 0 : leven(r, w) / ((r.length + w.length) / 2); } - var matches = {}; + let matches = {}; - var to_recording = function ($rec, rec_title) { + let to_recording = function($rec, rec_title) { if (rec_title in matches) { - var match = matches[rec_title]; + let match = matches[rec_title]; suggested_work_link($rec, match[0], match[1], match[2]); return; } - var $progress = $(""); + let $progress = $(''); rowTitleCell($rec).append( - $('
').append( - $("Looking for matching work…"), " ", $progress) - .css({"font-size": "0.9em", "padding": "0.3em", "padding-left": "1em", "color": "orange"})); + $('
') + .append($('Looking for matching work…'), ' ', $progress) + .css({ 'font-size': '0.9em', padding: '0.3em', 'padding-left': '1em', color: 'orange' }) + ); - var current = 0; - var context = { minScore: 0.250001, match: null }; - var total = mbids.length; + let current = 0; + let context = { minScore: 0.250001, match: null }; + let total = mbids.length; - var done = function () { - var match = context.match; + let done = function() { + let match = context.match; if (match !== null) { matches[rec_title] = match; suggested_work_link($rec, match[0], match[1], match[2]); @@ -849,13 +893,13 @@ function batch_recording_rels() { } }; - var iid = setInterval(function () { - var j = current++; - var norm_work_title = norm_titles[j]; - var score = sim(rec_title, norm_work_title); + var iid = setInterval(function() { + let j = current++; + let norm_work_title = norm_titles[j]; + let score = sim(rec_title, norm_work_title); if (current % 12 === 0) { - $progress.text(current.toString() + "/" + total.toString()); + $progress.text(`${current.toString()}/${total.toString()}`); } if (score < context.minScore) { @@ -874,28 +918,35 @@ function batch_recording_rels() { }, 0); }; - for (var i = 0; i < $not_performed.length; i++) { - var $rec = $not_performed.eq(i); - var mbid = $rec.find(TITLE_SELECTOR).attr("href").match(MBID_REGEX)[0]; + for (let i = 0; i < $not_performed.length; i++) { + let $rec = $not_performed.eq(i); + let mbid = $rec + .find(TITLE_SELECTOR) + .attr('href') + .match(MBID_REGEX)[0]; to_recording($rec, RECORDING_TITLES[mbid]); } } function suggested_work_link($rec, mbid, title, comment) { - var $title_cell = rowTitleCell($rec); - $title_cell.children("div.suggested-work").remove(); + let $title_cell = rowTitleCell($rec); + $title_cell.children('div.suggested-work').remove(); $title_cell.append( - $('
').append( - $("Suggested work:").css({"color": "green", "font-weight": "bold"}), " ", - $("") - .attr("href", "/work/" + mbid) - .text(title), - (comment ? " " : null), - (comment ? $("").text("(" + comment + ")") : null)) - .css({"font-size": "0.9em", "padding": "0.3em", "padding-left": "1em"})); - $rec.data("suggested_work_mbid", mbid); - $rec.data("suggested_work_title", title); + $('
') + .append( + $('Suggested work:').css({ color: 'green', 'font-weight': 'bold' }), + ' ', + $('') + .attr('href', `/work/${mbid}`) + .text(title), + comment ? ' ' : null, + comment ? $('').text(`(${comment})`) : null + ) + .css({ 'font-size': '0.9em', padding: '0.3em', 'padding-left': '1em' }) + ); + $rec.data('suggested_work_mbid', mbid); + $rec.data('suggested_work_title', title); } function remove_artist_works(mbid) { @@ -904,21 +955,22 @@ function batch_recording_rels() { } delete LOADED_ARTISTS[mbid]; - var item_key = "bpr_artists " + ARTIST_MBID; + let item_key = `bpr_artists ${ARTIST_MBID}`; localStorage.setItem( item_key, - _.filter(localStorage.getItem(item_key).split("\n"), - function (artist) { return artist.slice(0, 36) !== mbid; }) - .join("\n")); + _.filter(localStorage.getItem(item_key).split('\n'), function(artist) { + return artist.slice(0, 36) !== mbid; + }).join('\n') + ); } function cache_work(mbid, title, comment) { LOADED_WORKS[mbid] = true; - WORKS_LOAD_CACHE.push(mbid + title + (comment ? "\u00a0" + comment : "")); + WORKS_LOAD_CACHE.push(mbid + title + (comment ? `\u00a0${comment}` : '')); - var norm_title = normalizeTitle(title); - var works_date = localStorage.getItem("bpr_works_date " + ARTIST_MBID); - var count = $artist_works_msg.data("works_count") + 1; + let norm_title = normalizeTitle(title); + let works_date = localStorage.getItem(`bpr_works_date ${ARTIST_MBID}`); + let count = $artist_works_msg.data('works_count') + 1; update_artist_works_msg($artist_works_msg, count, ARTIST_NAME, works_date); match_works([mbid], [title], [comment], [norm_title]); @@ -928,69 +980,70 @@ function batch_recording_rels() { if (!WORKS_LOAD_CACHE.length) { return; } - var works_string = localStorage.getItem("bpr_works " + ARTIST_MBID); + let works_string = localStorage.getItem(`bpr_works ${ARTIST_MBID}`); if (works_string) { - works_string += "\n" + WORKS_LOAD_CACHE.join("\n"); + works_string += `\n${WORKS_LOAD_CACHE.join('\n')}`; } else { - works_string = WORKS_LOAD_CACHE.join("\n"); + works_string = WORKS_LOAD_CACHE.join('\n'); } - localStorage.setItem("bpr_works " + ARTIST_MBID, works_string); + localStorage.setItem(`bpr_works ${ARTIST_MBID}`, works_string); WORKS_LOAD_CACHE = []; } function load_artist_works_btn() { - var $input = $("#bpr-load-artist"); + let $input = $('#bpr-load-artist'); - if (!$input.data("selected")) { + if (!$input.data('selected')) { return; } - var mbid = $input.data("mbid"); - var name = $input.data("name"); + let mbid = $input.data('mbid'); + let name = $input.data('name'); - load_artist_works(mbid, name).done(function () { - var artists_string = localStorage.getItem("bpr_artists " + ARTIST_MBID); + load_artist_works(mbid, name).done(function() { + let artists_string = localStorage.getItem(`bpr_artists ${ARTIST_MBID}`); if (artists_string) { - artists_string += "\n" + mbid + name; + artists_string += `\n${mbid}${name}`; } else { artists_string = mbid + name; } - localStorage.setItem("bpr_artists " + ARTIST_MBID, artists_string); + localStorage.setItem(`bpr_artists ${ARTIST_MBID}`, artists_string); }); } function update_artist_works_msg($msg, count, name, works_date) { - $msg - .html("") - .append( - count + " works loaded for " + name + "
", - $('(cached ' + works_date + ')').css({"font-size": "0.8em"}) - ) - .data("works_count", count); + $msg.html('') + .append(`${count} works loaded for ${name}
`, $(`(cached ${works_date})`).css({ 'font-size': '0.8em' })) + .data('works_count', count); } // Edit creation function relate_all_to_work(mbid, title, comment) { - var deferred = $.Deferred(); - var $rows = checked_recordings(); - var total = $rows.length; + let deferred = $.Deferred(); + let $rows = checked_recordings(); + let total = $rows.length; if (!total) { deferred.resolve(); return deferred.promise(); } - for (var i = 0; i < total; i++) { - var $row = $rows.eq(i); + for (let i = 0; i < total; i++) { + let $row = $rows.eq(i); - $row.children("td").not(":has(input)").first() - .css("color", "LightSlateGray") - .find("a").css("color", "LightSlateGray"); + $row.children('td') + .not(':has(input)') + .first() + .css('color', 'LightSlateGray') + .find('a') + .css('color', 'LightSlateGray'); - var promise = relate_to_work($row, mbid, title, comment, false, false); + let promise = relate_to_work($row, mbid, title, comment, false, false); if (i === total - 1) { - promise.done(function () { deferred.resolve() }); + promise.done(function() { + deferred.resolve(); + }); } } @@ -1003,9 +1056,9 @@ function batch_recording_rels() { } function relate_to_new_titled_work() { - var $rows = checked_recordings(); - var total = $rows.length; - var title = $("#bpr-new-work").val(); + let $rows = checked_recordings(); + let total = $rows.length; + let title = $('#bpr-new-work').val(); if (!total || !title) { return; @@ -1013,49 +1066,46 @@ function batch_recording_rels() { ws_requests.stopped = true; - var $button = $(this).attr("disabled", true).css("color", "#EAEAEA"); + let $button = $(this) + .attr('disabled', true) + .css('color', '#EAEAEA'); function callback() { ws_requests.stopped = false; ws_requests.start_queue(); - $button.attr("disabled", false).css("color", "#565656"); + $button.attr('disabled', false).css('color', '#565656'); } - create_new_work(title, function (data) { - var work = data.match(/\/work\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/); - relate_all_to_work(work[1], title, "").done(callback) + create_new_work(title, function(data) { + let work = data.match(/\/work\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/); + relate_all_to_work(work[1], title, '').done(callback); }); } function relate_to_existing_work() { - var $input = $("input#bpr-existing-work"); - var $button = $(this); + let $input = $('input#bpr-existing-work'); + let $button = $(this); function callback() { ws_requests.stopped = false; ws_requests.start_queue(); - $button.attr("disabled", false).css("color", "#565656"); + $button.attr('disabled', false).css('color', '#565656'); } - if ($input.data("selected")) { + if ($input.data('selected')) { ws_requests.stopped = true; - $button.attr("disabled", true).css("color", "#EAEAEA"); + $button.attr('disabled', true).css('color', '#EAEAEA'); - relate_all_to_work( - $input.data("mbid"), - $input.data("name"), - $input.data("comment") || "" - ) - .done(callback); + relate_all_to_work($input.data('mbid'), $input.data('name'), $input.data('comment') || '').done(callback); } else { - $input.css("background", "#ffaaaa"); + $input.css('background', '#ffaaaa'); } } function relate_to_new_works() { - var $rows = checked_recordings(); - var total_rows = $rows.length; + let $rows = checked_recordings(); + let total_rows = $rows.length; if (!total_rows) { return; @@ -1063,27 +1113,30 @@ function batch_recording_rels() { ws_requests.stopped = true; - var $button = $(this) - .attr("disabled", true) - .css("color", "#EAEAEA"); + let $button = $(this) + .attr('disabled', true) + .css('color', '#EAEAEA'); - $.each($rows, function (i, row) { - var $row = $(row); - var $title_cell = rowTitleCell($row); - var title = $title_cell.find(TITLE_SELECTOR).text(); + $.each($rows, function(i, row) { + let $row = $(row); + let $title_cell = rowTitleCell($row); + let title = $title_cell.find(TITLE_SELECTOR).text(); - $title_cell.css("color", "LightSlateGray").find("a").css("color", "LightSlateGray"); + $title_cell + .css('color', 'LightSlateGray') + .find('a') + .css('color', 'LightSlateGray'); - create_new_work(title, function (data) { - var work = data.match(/\/work\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/); - var promise = relate_to_work($row, work[1], title, "", true, true); + create_new_work(title, function(data) { + let work = data.match(/\/work\/([a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12})/); + let promise = relate_to_work($row, work[1], title, '', true, true); if (--total_rows === 0) { - promise.done(function () { + promise.done(function() { flush_work_cache(); ws_requests.stopped = false; ws_requests.start_queue(); - $button.attr("disabled", false).css("color", "#565656"); + $button.attr('disabled', false).css('color', '#565656'); }); } }); @@ -1092,14 +1145,14 @@ function batch_recording_rels() { function create_new_work(title, callback) { function post_edit() { - var data = "edit-work.name=" + title; + let data = `edit-work.name=${title}`; _.each($work_options, function($obj, kind) { if ($obj.val()) { - data += "&edit-work." + kind + "_id=" + $obj.val(); + data += `&edit-work.${kind}_id=${$obj.val()}`; } }); - $.post("/work/create", data, callback).fail(function () { + $.post('/work/create', data, callback).fail(function() { edit_requests.unshift(post_edit); }); } @@ -1107,33 +1160,38 @@ function batch_recording_rels() { } function relate_to_suggested_works() { - var $rows = checked_recordings().filter(function () { - return $(this).data("suggested_work_mbid"); + let $rows = checked_recordings().filter(function() { + return $(this).data('suggested_work_mbid'); }); - var total = $rows.length; + let total = $rows.length; if (!total) { return; } - var $button = $(this).attr("disabled", true).css("color", "#EAEAEA"); + let $button = $(this) + .attr('disabled', true) + .css('color', '#EAEAEA'); ws_requests.stopped = true; function callback() { ws_requests.stopped = false; ws_requests.start_queue(); - $button.attr("disabled", false).css("color", "#565656"); - }; + $button.attr('disabled', false).css('color', '#565656'); + } - $.each($rows, function (i, row) { - var $row = $(row); - var mbid = $row.data("suggested_work_mbid"); - var title = $row.data("suggested_work_title"); - var $title_cell = rowTitleCell($row); + $.each($rows, function(i, row) { + let $row = $(row); + let mbid = $row.data('suggested_work_mbid'); + let title = $row.data('suggested_work_title'); + let $title_cell = rowTitleCell($row); - $title_cell.css("color", "LightSlateGray").find("a").css("color", "LightSlateGray"); + $title_cell + .css('color', 'LightSlateGray') + .find('a') + .css('color', 'LightSlateGray'); - var promise = relate_to_work($row, mbid, title, "", false, false); + let promise = relate_to_work($row, mbid, title, '', false, false); if (i === total - 1) { promise.done(callback); } @@ -1141,22 +1199,26 @@ function batch_recording_rels() { } function add_work_link($row, mbid, title, comment, attrs) { - var $title_cell = rowTitleCell($row); - $title_cell.children("div.suggested-work").remove(); - $row.removeData("suggested_work_mbid").removeData("suggested_work_title"); - $title_cell - .removeAttr("style") - .append($('
') - .text(attrs.join(' ') + " recording of ") - .css({"font-size": "0.9em", "padding": "0.3em", "padding-left": "1em"}) - .append($("").attr("href", "/work/" + mbid).text(title), - (comment ? " " : null), - (comment ? $("").text("(" + comment + ")") : null))); + let $title_cell = rowTitleCell($row); + $title_cell.children('div.suggested-work').remove(); + $row.removeData('suggested_work_mbid').removeData('suggested_work_title'); + $title_cell.removeAttr('style').append( + $('
') + .text(`${attrs.join(' ')} recording of `) + .css({ 'font-size': '0.9em', padding: '0.3em', 'padding-left': '1em' }) + .append( + $('') + .attr('href', `/work/${mbid}`) + .text(title), + comment ? ' ' : null, + comment ? $('').text(`(${comment})`) : null + ) + ); } function relate_to_work($row, work_mbid, work_title, work_comment, check_loaded, priority) { - var deferred = $.Deferred(); - var performances = $row.data("performances"); + let deferred = $.Deferred(); + let performances = $row.data('performances'); if (performances) { if (performances.indexOf(work_mbid) === -1) { @@ -1166,60 +1228,63 @@ function batch_recording_rels() { return deferred.promise(); } } else { - $row.data("performances", [work_mbid]); + $row.data('performances', [work_mbid]); } - var rec_mbid = $row.find(TITLE_SELECTOR).attr("href").match(MBID_REGEX)[0]; - var $title_cell = rowTitleCell($row); - var title_link = $title_cell.children("a")[0]; - var $attrs = $row.children("td.bpr_attrs"); - var selectedAttrs = []; + let rec_mbid = $row + .find(TITLE_SELECTOR) + .attr('href') + .match(MBID_REGEX)[0]; + let $title_cell = rowTitleCell($row); + let title_link = $title_cell.children('a')[0]; + let $attrs = $row.children('td.bpr_attrs'); + let selectedAttrs = []; function selected(attr) { - var checked = $attrs.children("span." + attr).data("checked") ? 1 : 0; + let checked = $attrs.children(`span.${attr}`).data('checked') ? 1 : 0; if (checked) { selectedAttrs.push(attr); } return checked; } - var data = { - "rel-editor.rels.0.action": "add", - "rel-editor.rels.0.link_type": "278", - "rel-editor.rels.0.entity.1.type": "work", - "rel-editor.rels.0.entity.1.gid": work_mbid, - "rel-editor.rels.0.entity.0.type": "recording", - "rel-editor.rels.0.entity.0.gid": rec_mbid + let data = { + 'rel-editor.rels.0.action': 'add', + 'rel-editor.rels.0.link_type': '278', + 'rel-editor.rels.0.entity.1.type': 'work', + 'rel-editor.rels.0.entity.1.gid': work_mbid, + 'rel-editor.rels.0.entity.0.type': 'recording', + 'rel-editor.rels.0.entity.0.gid': rec_mbid }; - var attrs = []; - if (selected("live")) attrs.push("70007db6-a8bc-46d7-a770-80e6a0bb551a"); - if (selected("partial")) attrs.push("d2b63be6-91ec-426a-987a-30b47f8aae2d"); - if (selected("instrumental")) attrs.push("c031ed4f-c9bb-4394-8cf5-e8ce4db512ae"); - if (selected("cover")) attrs.push("1e8536bd-6eda-3822-8e78-1c0f4d3d2113"); + let attrs = []; + if (selected('live')) attrs.push('70007db6-a8bc-46d7-a770-80e6a0bb551a'); + if (selected('partial')) attrs.push('d2b63be6-91ec-426a-987a-30b47f8aae2d'); + if (selected('instrumental')) attrs.push('c031ed4f-c9bb-4394-8cf5-e8ce4db512ae'); + if (selected('cover')) attrs.push('1e8536bd-6eda-3822-8e78-1c0f4d3d2113'); - _.each(attrs, function (attr, index) { - data["rel-editor.rels.0.attributes." + index + ".type.gid"] = attr; + _.each(attrs, function(attr, index) { + data[`rel-editor.rels.0.attributes.${index}.type.gid`] = attr; }); - var date = $attrs.data("date"); + let date = $attrs.data('date'); if (date != null) { - data["rel-editor.rels.0.period.begin_date.year"] = date["year"]; - data["rel-editor.rels.0.period.begin_date.month"] = date["month"] || ""; - data["rel-editor.rels.0.period.begin_date.day"] = date["day"] || ""; - data["rel-editor.rels.0.period.end_date.year"] = date["year"]; - data["rel-editor.rels.0.period.end_date.month"] = date["month"] || ""; - data["rel-editor.rels.0.period.end_date.day"] = date["day"] || ""; + data['rel-editor.rels.0.period.begin_date.year'] = date['year']; + data['rel-editor.rels.0.period.begin_date.month'] = date['month'] || ''; + data['rel-editor.rels.0.period.begin_date.day'] = date['day'] || ''; + data['rel-editor.rels.0.period.end_date.year'] = date['year']; + data['rel-editor.rels.0.period.end_date.month'] = date['month'] || ''; + data['rel-editor.rels.0.period.end_date.day'] = date['day'] || ''; } function post_edit() { - $(title_link).css("color", "green"); + $(title_link).css('color', 'green'); - $.post('/relationship-editor', data, function () { + $.post('/relationship-editor', data, function() { add_work_link($row, work_mbid, work_title, work_comment, selectedAttrs); - $(title_link).removeAttr("style"); - $row.addClass("performed"); + $(title_link).removeAttr('style'); + $row.addClass('performed'); if (hide_performed_recs) { uncheckRows($row.hide()); @@ -1227,7 +1292,7 @@ function batch_recording_rels() { } deferred.resolve(); - }).fail(function () { + }).fail(function() { edit_requests.unshift(post_edit); }); } @@ -1247,47 +1312,62 @@ function batch_recording_rels() { } function filter_recordings() { - var string = this.value.toLowerCase(); + let string = this.value.toLowerCase(); - for (var i = 0; i < $recordings.length; i++) { - var $rec = $recordings.eq(i); - var title = $rec.find(TITLE_SELECTOR).text().toLowerCase(); + for (let i = 0; i < $recordings.length; i++) { + let $rec = $recordings.eq(i); + let title = $rec + .find(TITLE_SELECTOR) + .text() + .toLowerCase(); if (title.indexOf(string) !== -1) { - $rec.data("filtered", false); - if (!hide_performed_recs || !$rec.hasClass("performed")) { + $rec.data('filtered', false); + if (!hide_performed_recs || !$rec.hasClass('performed')) { $rec.show(); } } else { - $rec.hide().data("filtered", true); + $rec.hide().data('filtered', true); } } restripeRows(); } function toggle_performed_recordings() { - var $performed = $recordings.filter(".performed"); + let $performed = $recordings.filter('.performed'); hide_performed_recs = this.checked; if (hide_performed_recs) { uncheckRows($performed.hide()); } else { - $performed.filter(function () { return !$(this).data("filtered") }).show(); + $performed + .filter(function() { + return !$(this).data('filtered'); + }) + .show(); } restripeRows(); setting('hide_performed_recs', hide_performed_recs.toString()); } function toggle_pending_edits(event, checked) { - var $pending = $recordings.filter(function () { - return $(this).find(TITLE_SELECTOR).parent().parent().is("span.mp"); + let $pending = $recordings.filter(function() { + return $(this) + .find(TITLE_SELECTOR) + .parent() + .parent() + .is('span.mp'); }); hide_pending_edits = checked !== undefined ? checked : this.checked; if (hide_pending_edits) { uncheckRows($pending.hide()); } else { - $pending.filter(function () { return !$(this).data("filtered") }).show(); + $pending + .filter(function() { + return !$(this).data('filtered'); + }) + .show(); } restripeRows(); setting('hide_pending_edits', hide_pending_edits.toString()); @@ -1295,46 +1375,53 @@ function batch_recording_rels() { toggle_pending_edits(null, hide_pending_edits); function checked_recordings() { - return $recordings - .filter(":visible") - .filter(function () { return $(this).find("input[name=add-to-merge]:checked").length }); + return $recordings.filter(':visible').filter(function() { + return $(this).find('input[name=add-to-merge]:checked').length; + }); } function entity_lookup(id_suffix, entity) { - var $input = $('') - $input.on("input", function () { - var match = this.value.match(MBID_REGEX); - $(this).data("selected", false); - if (match) { - var mbid = match[0]; - ws_requests.unshift_get("/ws/2/" + entity + "/" + mbid + "?fmt=json", function (data) { - var value = data.title || data.name; - var out_data = {"selected": true, "mbid": mbid, "name": value}; + let $input = $(``); + $input + .on('input', function() { + let match = this.value.match(MBID_REGEX); + $(this).data('selected', false); + if (match) { + let mbid = match[0]; + ws_requests + .unshift_get(`/ws/2/${entity}/${mbid}?fmt=json`, function(data) { + let value = data.title || data.name; + let out_data = { selected: true, mbid: mbid, name: value }; - if (entity === "work" && data.disambiguation) { - out_data.comment = data.disambiguation; - } + if (entity === 'work' && data.disambiguation) { + out_data.comment = data.disambiguation; + } - $input.val(value).data(out_data).css("background", "#bbffbb"); - }).fail(function () { - $input.css("background", "#ffaaaa"); - }); - } else { - $input.css("background", "#ffaaaa"); - } - }).data("selected", false); + $input + .val(value) + .data(out_data) + .css('background', '#bbffbb'); + }) + .fail(function() { + $input.css('background', '#ffaaaa'); + }); + } else { + $input.css('background', '#ffaaaa'); + } + }) + .data('selected', false); return $input; } function restripeRows() { - $recordings.filter(":visible").each(function (index, row) { - var even = (index + 1) % 2 === 0; + $recordings.filter(':visible').each(function(index, row) { + let even = (index + 1) % 2 === 0; row.className = row.className.replace(even ? 'odd' : 'even', even ? 'even' : 'odd'); }); } function rowTitleCell($row) { - return $row.children('td:has(' + TITLE_SELECTOR + ')'); + return $row.children(`td:has(${TITLE_SELECTOR})`); } } diff --git a/beatport_classic_importer.user.js b/beatport_classic_importer.user.js index 03da9dc..8b9a817 100644 --- a/beatport_classic_importer.user.js +++ b/beatport_classic_importer.user.js @@ -17,119 +17,121 @@ this.$ = this.jQuery = jQuery.noConflict(true); if (!unsafeWindow) unsafeWindow = window; -$(document).ready(function(){ +$(document).ready(function() { MBImportStyle(); - var release_url = window.location.href.replace('/\?.*$/', '').replace(/#.*$/, ''); - var release = retrieveReleaseInfo(release_url); + let release_url = window.location.href.replace('/?.*$/', '').replace(/#.*$/, ''); + let release = retrieveReleaseInfo(release_url); insertLink(release, release_url); - }); function retrieveReleaseInfo(release_url) { - function contains_or(selector, list) { - selectors = []; - $.each(list, function(ind, value) { - selectors.push(selector + ':contains("' + value.replace('"', '\\"') + '")'); + function contains_or(selector, list) { + selectors = []; + $.each(list, function(ind, value) { + selectors.push(`${selector}:contains("${value.replace('"', '\\"')}")`); + }); + return selectors.join(','); + } + let release_date_strings = [ + 'Release Date', + 'Fecha de lanzamiento', + 'Date de sortie', + 'Erscheinungsdatum', + 'Data de lançamento', + 'Releasedatum', + 'Data di uscita', + 'リリース予定日' + ]; + let labels_strings = ['Labels', 'Sello', 'Gravadoras', 'Label', 'Etichetta', 'Editora', 'レーベル']; + let catalog_strings = ['Catalog', 'Catálogo', 'Catalogue', 'Katalog', 'Catalogus', 'Catalogo', 'カタログ']; + let release = {}; + + // Release information global to all Beatport releases + release.packaging = 'None'; + release.country = 'XW'; + release.status = 'official'; + release.urls = []; + release.urls.push({ + url: release_url, + link_type: MBImport.URL_TYPES.purchase_for_download }); - return selectors.join(','); - } - var release_date_strings = [ - 'Release Date', 'Fecha de lanzamiento', 'Date de sortie', 'Erscheinungsdatum', 'Data de lançamento', 'Releasedatum', "Data di uscita", "リリース予定日" - ]; - var labels_strings = [ - 'Labels', 'Sello', 'Gravadoras', "Label", "Etichetta", "Editora", "レーベル" - ]; - var catalog_strings = [ - 'Catalog', 'Catálogo', 'Catalogue', 'Katalog', 'Catalogus', "Catalogo", "カタログ" - ]; - var release = {}; - // Release information global to all Beatport releases - release.packaging = 'None'; - release.country = "XW"; - release.status = 'official'; - release.urls = []; - release.urls.push({ - 'url': release_url, - 'link_type': MBImport.URL_TYPES.purchase_for_download - }); + let releaseDate = $(contains_or('td.meta-data-label', release_date_strings)) + .next() + .text() + .split('-'); + release.year = releaseDate[0]; + release.month = releaseDate[1]; + release.day = releaseDate[2]; - var releaseDate = $(contains_or("td.meta-data-label", release_date_strings)).next().text().split("-"); - release.year = releaseDate[0]; - release.month = releaseDate[1]; - release.day = releaseDate[2]; + release.labels = []; + release.labels.push({ + name: $(contains_or('td.meta-data-label', labels_strings)) + .next() + .text(), + catno: $(contains_or('td.meta-data-label', catalog_strings)) + .next() + .text() + }); - release.labels = []; - release.labels.push( - { - name: $(contains_or("td.meta-data-label", labels_strings)).next().text(), - catno: $(contains_or("td.meta-data-label", catalog_strings)).next().text() - } - ); + let release_artists = []; - var release_artists = []; + // Tracks + let tracks = []; + unsafeWindow.$('span[data-json]').each(function(index, tagSoup) { + let t = $.parseJSON($(tagSoup).attr('data-json')); + release.title = t.release.name; - // Tracks - var tracks = []; - unsafeWindow.$( "span[data-json]" ).each( - function ( index, tagSoup ) { - var t = $.parseJSON($(tagSoup).attr('data-json')); - release.title = t.release.name; - - var artists = []; - t.artists.forEach( - function (artist) { - artists.push(artist.name); - release_artists.push(artist.name); + let artists = []; + t.artists.forEach(function(artist) { + artists.push(artist.name); + release_artists.push(artist.name); + }); + let title = t.name; + if (t.mixName && t.mixName !== 'Original Mix' && t.mixName !== 'Original') { + title += ` (${t.mixName})`; } - ); - var title = t.name; - if (t.mixName && t.mixName !== 'Original Mix' && t.mixName !== 'Original') { - title += ' (' + t.mixName + ')'; - } - tracks.push({ - 'artist_credit': MBImport.makeArtistCredits(artists), - 'title': title, - 'duration': t.lengthMs - }); + tracks.push({ + artist_credit: MBImport.makeArtistCredits(artists), + title: title, + duration: t.lengthMs + }); + }); + + let unique_artists = []; + $.each(release_artists, function(i, el) { + if ($.inArray(el, unique_artists) === -1) { + unique_artists.push(el); + } + }); + + if (unique_artists.length > 4) { + release.artist_credit = [MBImport.specialArtist('various_artists')]; + } else { + release.artist_credit = MBImport.makeArtistCredits(unique_artists); } - ); + release.discs = []; + release.discs.push({ + tracks: tracks, + format: 'Digital Media' + }); - var unique_artists = []; - $.each(release_artists, function(i, el){ - if ($.inArray(el, unique_artists) === -1) { - unique_artists.push(el); - } - }); - - if (unique_artists.length > 4) { - release.artist_credit = [ MBImport.specialArtist('various_artists') ]; - } else { - release.artist_credit = MBImport.makeArtistCredits(unique_artists); - } - release.discs = []; - release.discs.push( { - 'tracks': tracks, - 'format': "Digital Media" - } ); - - LOGGER.info("Parsed release: ", release); - return release; + LOGGER.info('Parsed release: ', release); + return release; } // Insert button into page under label information function insertLink(release, release_url) { - var edit_note = MBImport.makeEditNote(release_url, 'Beatport Classic'); - var parameters = MBImport.buildFormParameters(release, edit_note); + let edit_note = MBImport.makeEditNote(release_url, 'Beatport Classic'); + let parameters = MBImport.buildFormParameters(release, edit_note); - var mbUI = $('
' - + MBImport.buildFormHTML(parameters) - + MBImport.buildSearchButton(release) - + '
').hide(); + let mbUI = $( + `
${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}
` + ).hide(); - $(".release-detail-metadata").append(mbUI); - $('form.musicbrainz_import').css({'display': 'inline-block', 'margin': '1px'}); - $('form.musicbrainz_import img').css({'display': 'inline-block'}); + $('.release-detail-metadata').append(mbUI); + $('form.musicbrainz_import').css({ display: 'inline-block', margin: '1px' }); + $('form.musicbrainz_import img').css({ display: 'inline-block' }); mbUI.slideDown(); } diff --git a/beatport_importer.user.js b/beatport_importer.user.js index bc25781..4380a20 100644 --- a/beatport_importer.user.js +++ b/beatport_importer.user.js @@ -20,117 +20,112 @@ this.$ = this.jQuery = jQuery.noConflict(true); if (!unsafeWindow) unsafeWindow = window; -$(document).ready(function(){ - MBImportStyle(); +$(document).ready(function() { + MBImportStyle(); - var release_url = window.location.href.replace('/\?.*$/', '').replace(/#.*$/, ''); - var release = retrieveReleaseInfo(release_url); - insertLink(release, release_url); + let release_url = window.location.href.replace('/?.*$/', '').replace(/#.*$/, ''); + let release = retrieveReleaseInfo(release_url); + insertLink(release, 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 - var release = { - artist_credit: [], - title: ProductDetail.name, - year: releaseDate[0], - month: releaseDate[1], - day: releaseDate[2], - format: 'Digital Media', - packaging: 'None', - country: 'XW', - status: 'official', - language: 'eng', - script: 'Latn', - type: '', - urls: [], - labels: [], - discs: [] - }; + // Release information global to all Beatport releases + let release = { + artist_credit: [], + title: ProductDetail.name, + year: releaseDate[0], + month: releaseDate[1], + day: releaseDate[2], + format: 'Digital Media', + packaging: 'None', + country: 'XW', + status: 'official', + language: 'eng', + script: 'Latn', + type: '', + urls: [], + labels: [], + discs: [] + }; - // URLs - release.urls.push({ - 'url': release_url, - 'link_type': MBImport.URL_TYPES.purchase_for_download - }); + // URLs + release.urls.push({ + url: release_url, + link_type: MBImport.URL_TYPES.purchase_for_download + }); - release.labels.push( - { - name: ProductDetail.label.name, - catno: ProductDetail.catalog - } - ); + release.labels.push({ + name: ProductDetail.label.name, + catno: ProductDetail.catalog + }); - // Tracks - var tracks = []; - var the_tracks = unsafeWindow.Playables.tracks; - var seen_tracks = {}; // to shoot duplicates ... - var release_artists = []; - $.each(the_tracks, - function (idx, track) { - if (track.release.id !== ProductDetail.id) { - return; - } - if (seen_tracks[track.id]) { - return; - } - seen_tracks[track.id] = true; - - var artists = []; - $.each(track.artists, - function (idx2, artist) { - artists.push(artist.name); - release_artists.push(artist.name); + // Tracks + let tracks = []; + let the_tracks = unsafeWindow.Playables.tracks; + let seen_tracks = {}; // to shoot duplicates ... + let release_artists = []; + $.each(the_tracks, function(idx, track) { + if (track.release.id !== ProductDetail.id) { + return; } - ); + if (seen_tracks[track.id]) { + return; + } + seen_tracks[track.id] = true; - var title = track.name; - if (track.mix && track.mix !== 'Original Mix') { - title += ' (' + track.mix + ')'; - } - tracks.push({ - 'artist_credit': MBImport.makeArtistCredits(artists), - 'title': title, - 'duration': track.duration.minutes - }); + let artists = []; + $.each(track.artists, function(idx2, artist) { + artists.push(artist.name); + release_artists.push(artist.name); + }); + + let title = track.name; + if (track.mix && track.mix !== 'Original Mix') { + title += ` (${track.mix})`; + } + tracks.push({ + artist_credit: MBImport.makeArtistCredits(artists), + title: title, + duration: track.duration.minutes + }); + }); + + let unique_artists = []; + $.each(release_artists, function(i, el) { + if ($.inArray(el, unique_artists) === -1) { + unique_artists.push(el); + } + }); + + if (unique_artists.length > 4) { + release.artist_credit = [MBImport.specialArtist('various_artists')]; + } else { + release.artist_credit = MBImport.makeArtistCredits(unique_artists); } - ); + release.discs.push({ + tracks: tracks, + format: release.format + }); - var unique_artists = []; - $.each(release_artists, function(i, el){ - if ($.inArray(el, unique_artists) === -1) { - unique_artists.push(el); - } - }); - - if (unique_artists.length > 4) { - release.artist_credit = [ MBImport.specialArtist('various_artists') ]; - } else { - release.artist_credit = MBImport.makeArtistCredits(unique_artists); - } - release.discs.push( { - 'tracks': tracks, - 'format': release.format - } ); - - LOGGER.info("Parsed release: ", release); - return release; + LOGGER.info('Parsed release: ', release); + return release; } // Insert button into page under label information function insertLink(release, release_url) { - var edit_note = MBImport.makeEditNote(release_url, 'Beatport'); - var parameters = MBImport.buildFormParameters(release, edit_note); + let edit_note = MBImport.makeEditNote(release_url, 'Beatport'); + let parameters = MBImport.buildFormParameters(release, edit_note); - var mbUI = $('
  • ' - + MBImport.buildFormHTML(parameters) - + MBImport.buildSearchButton(release) - + '
  • ').hide(); + let mbUI = $( + `
  • ${MBImport.buildFormHTML( + parameters + )}${MBImport.buildSearchButton(release)}
  • ` + ).hide(); - $(".interior-release-chart-content-list").append(mbUI); - $('form.musicbrainz_import').css({'display': 'inline-block', 'margin-left': '5px'}); - $('form.musicbrainz_import button').css({'width': '120px'}); + $('.interior-release-chart-content-list').append(mbUI); + $('form.musicbrainz_import').css({ display: 'inline-block', 'margin-left': '5px' }); + $('form.musicbrainz_import button').css({ width: '120px' }); mbUI.slideDown(); } diff --git a/cd1d_importer.user.js b/cd1d_importer.user.js index 428a14e..ad50cba 100644 --- a/cd1d_importer.user.js +++ b/cd1d_importer.user.js @@ -25,245 +25,260 @@ if (!unsafeWindow) unsafeWindow = window; this.$ = this.jQuery = jQuery.noConflict(true); var CD1DImporter = { - - getFormats: function () { - // get a list of existing formats, return id of the fragment and name - var formats = $('#container-1 ul li.ui-state-default').map(function () { - return { - id: $(this).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 - for (var i = 0; i < formats.length; i++) { - for (var j = i + 1; j < formats.length; j++) { - if (formats[j].id.length > 1) { - if (formats[i].id[1] == formats[j].id[1]) { - // same prefix (ie. fragment-33123 and fragment-33123-1-2) - if (formats[i].id.length < formats[j].id.length) { - formats[i].toremove = true; - } else if (formats[i].id.length > formats[j].id.length) { - formats[j].toremove = true; + getFormats: function() { + // get a list of existing formats, return id of the fragment and name + let formats = $('#container-1 ul li.ui-state-default').map(function() { + return { + id: $(this) + .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 + for (var i = 0; i < formats.length; i++) { + for (let j = i + 1; j < formats.length; j++) { + if (formats[j].id.length > 1) { + if (formats[i].id[1] == formats[j].id[1]) { + // same prefix (ie. fragment-33123 and fragment-33123-1-2) + if (formats[i].id.length < formats[j].id.length) { + formats[i].toremove = true; + } else if (formats[i].id.length > formats[j].id.length) { + formats[j].toremove = true; + } + } + } } - } } - } - } - var cleanformats = []; - for (var i = 0; i < formats.length; i++) { - if (!formats[i].toremove) { - cleanformats.push({ - id: formats[i].id.join('-'), - name: formats[i].name + let cleanformats = []; + for (var i = 0; i < formats.length; i++) { + if (!formats[i].toremove) { + cleanformats.push({ + id: formats[i].id.join('-'), + name: formats[i].name + }); + } + } + return cleanformats; + }, + + getTracks: function(id) { + // extract discs & tracks + let tracklists = `div#${id} div.tracklist table.tracklist-content`; + let discs = []; + $(tracklists).each(function() { + disc = $(this) + .find('tbody tr') + .map(function() { + // $(this) is used more than once; cache it for performance. + let row = $(this); + + // For each row that's "mapped", return an object that + // describes the first and second in the row. + let duration = row + .find('td.tracklist-content-length') + .text() + .replace('"', '') + .replace("' ", ':'); + + // drop track number prefix (A A2 C3 01 05 etc...) + let title = row + .find('td.tracklist-content-title') + .text() + .replace(/^[0-9A-F][0-9]* /, ''); + return { + title: title, + duration: MBImport.hmsToMilliSeconds(duration) + }; + }) + .get(); + discs.push(disc); }); - } - } - return cleanformats; - }, + return discs; + }, - getTracks: function (id) { - // extract discs & tracks - var tracklists = 'div#' + id + ' div.tracklist table.tracklist-content'; - var discs = []; - $(tracklists).each(function () { - disc = $(this).find('tbody tr').map(function () { - // $(this) is used more than once; cache it for performance. - var row = $(this); + getArtists: function() { + // get artists + let artists = $('div.infos-releasegrp div.list-artist a') + .map(function() { + return $(this).text(); + }) + .get(); + return MBImport.makeArtistCredits(artists); + }, - // For each row that's "mapped", return an object that - // describes the first and second in the row. - var duration = row.find('td.tracklist-content-length').text().replace('"', '').replace('\' ', ':') + getAlbum: function() { + // get release title + return $('h1').text(); + }, - // 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]* /, ''); + fromCurrentTime: function(offset_in_seconds) { + let millis = Date.now(); + if (!isNaN(offset_in_seconds)) { + millis += offset_in_seconds * 1000; + } + let date = new Date(millis); + let dd = date.getDate(); + let mm = date.getMonth() + 1; //January is 0! + let yyyy = date.getFullYear(); return { - title: title, - duration: MBImport.hmsToMilliSeconds(duration) + year: yyyy, + month: mm, + day: dd }; - }).get(); - discs.push(disc); - }); - return discs; - }, + }, - getArtists: function () { - // get artists - var artists = $('div.infos-releasegrp div.list-artist a').map(function () { - return $(this).text(); - }).get(); - return MBImport.makeArtistCredits(artists); - }, - - getAlbum: function () { - // get release title - return $('h1').text(); - }, - - fromCurrentTime: function (offset_in_seconds) { - var millis = Date.now(); - if (!isNaN(offset_in_seconds)) { - millis += offset_in_seconds * 1000; - } - var date = new Date(millis); - var dd = date.getDate(); - var mm = date.getMonth() + 1; //January is 0! - var yyyy = date.getFullYear(); - return { - 'year': yyyy, - 'month': mm, - 'day': dd - }; - }, - - getReleaseDate: function () { - // get release date and convert it to object - var text = $('div.infos-releasegrp div.row-date').text(); - if (text == 'yesterday' || text == 'hier') { - return this.fromCurrentTime(-24 * 60 * 60); - } - if (text == 'today' || text == 'aujourd\'hui') { - return this.fromCurrentTime(0); - } - var date = text - .replace('janvier', '01') - .replace('février', '02') - .replace('mars', '03') - .replace('avril', '04') - .replace('mai', '05') - .replace('juin', '06') - .replace('juillet', '07') - .replace('août', '08') - .replace('septembre', '09') - .replace('octobre', '10') - .replace('novembre', '11') - .replace('décembre', '12') - .replace('January', '01') - .replace('February', '02') - .replace('March', '03') - .replace('April', '04') - .replace('May', '05') - .replace('June', '06') - .replace('July', '07') - .replace('August', '08') - .replace('September', '09') - .replace('October', '10') - .replace('November', '11') - .replace('December', '12') - .split(' '); - return { - 'year': parseInt(date[2], 10), - 'month': parseInt(date[1], 10), - 'day': parseInt(date[0], 10) - }; - }, - - currentURL: function () { - return window.location.href.replace(/\/[a-z]{2}\/album\//i, '/album/').split('#')[0]; - }, - - retrieveReleaseInfo: function (format) { - // Analyze CD1D data and return a release object - var release = { - artist_credit: this.getArtists(), - title: this.getAlbum(), - country: "", // Worldwide - type: '', - status: 'official', - language: 'eng', - script: 'latn', - barcode: '', - urls: [], - discs: [], - }; - - // Grab release event information - var releasedate = this.getReleaseDate(); - release.year = releasedate.year; - release.month = releasedate.month; - release.day = releasedate.day; - - var link_type = MBImport.URL_TYPES; - - if (format.name.match(/vinyl|lp/i)) { - release.country = 'FR'; - release.format = "Vinyl"; - release.urls.push({ - 'url': this.currentURL(), - 'link_type': link_type.purchase_for_mail_order - }); - } else if (format.name.match(/cd/i)) { - release.country = 'FR'; - release.format = 'CD'; - release.urls.push({ - 'url': this.currentURL(), - 'link_type': link_type.purchase_for_mail_order - }); - } else if (format.name.match(/digital|mp3|flac|ogg|wav/i)) { - release.country = 'XW'; - release.packaging = 'None'; - release.format = "Digital Media"; - release.urls.push({ - 'url': this.currentURL(), - 'link_type': link_type.purchase_for_download - }); - } - - release.labels = $('div.infos-details div.row-structure').map(function () { + getReleaseDate: function() { + // get release date and convert it to object + let text = $('div.infos-releasegrp div.row-date').text(); + if (text == 'yesterday' || text == 'hier') { + return this.fromCurrentTime(-24 * 60 * 60); + } + if (text == 'today' || text == "aujourd'hui") { + return this.fromCurrentTime(0); + } + let date = text + .replace('janvier', '01') + .replace('février', '02') + .replace('mars', '03') + .replace('avril', '04') + .replace('mai', '05') + .replace('juin', '06') + .replace('juillet', '07') + .replace('août', '08') + .replace('septembre', '09') + .replace('octobre', '10') + .replace('novembre', '11') + .replace('décembre', '12') + .replace('January', '01') + .replace('February', '02') + .replace('March', '03') + .replace('April', '04') + .replace('May', '05') + .replace('June', '06') + .replace('July', '07') + .replace('August', '08') + .replace('September', '09') + .replace('October', '10') + .replace('November', '11') + .replace('December', '12') + .split(' '); return { - name: $(this).text(), - mbid: '', - catno: 'none' + year: parseInt(date[2], 10), + month: parseInt(date[1], 10), + day: parseInt(date[0], 10) }; - }) - .get(); + }, - // Tracks - $.each(this.getTracks(format.id), function (ndisc, disc) { - var thisdisc = { - tracks: [], - format: release.format - }; - release.discs.push(thisdisc); - $.each(this, function (ntrack, track) { - thisdisc.tracks.push({ - 'title': track.title, - 'duration': track.duration, - 'artist_credit': [] + currentURL: function() { + return window.location.href.replace(/\/[a-z]{2}\/album\//i, '/album/').split('#')[0]; + }, + + retrieveReleaseInfo: function(format) { + // Analyze CD1D data and return a release object + let release = { + artist_credit: this.getArtists(), + title: this.getAlbum(), + country: '', // Worldwide + type: '', + status: 'official', + language: 'eng', + script: 'latn', + barcode: '', + urls: [], + discs: [] + }; + + // Grab release event information + let releasedate = this.getReleaseDate(); + release.year = releasedate.year; + release.month = releasedate.month; + release.day = releasedate.day; + + let link_type = MBImport.URL_TYPES; + + if (format.name.match(/vinyl|lp/i)) { + release.country = 'FR'; + release.format = 'Vinyl'; + release.urls.push({ + url: this.currentURL(), + link_type: link_type.purchase_for_mail_order + }); + } else if (format.name.match(/cd/i)) { + release.country = 'FR'; + release.format = 'CD'; + release.urls.push({ + url: this.currentURL(), + link_type: link_type.purchase_for_mail_order + }); + } else if (format.name.match(/digital|mp3|flac|ogg|wav/i)) { + release.country = 'XW'; + release.packaging = 'None'; + release.format = 'Digital Media'; + release.urls.push({ + url: this.currentURL(), + link_type: link_type.purchase_for_download + }); + } + + release.labels = $('div.infos-details div.row-structure') + .map(function() { + return { + name: $(this).text(), + mbid: '', + catno: 'none' + }; + }) + .get(); + + // Tracks + $.each(this.getTracks(format.id), function(ndisc, disc) { + let thisdisc = { + tracks: [], + format: release.format + }; + release.discs.push(thisdisc); + $.each(this, function(ntrack, track) { + thisdisc.tracks.push({ + title: track.title, + duration: track.duration, + artist_credit: [] + }); + }); }); - }); - }); - LOGGER.info("Parsed release: ", format.name, release); - return release; - }, + LOGGER.info('Parsed release: ', format.name, release); + return release; + }, - insertLink: function (release, where, formatname) { - // Insert links in page + insertLink: function(release, where, formatname) { + // Insert links in page - // Form parameters - var edit_note = MBImport.makeEditNote(this.currentURL(), 'CD1D', formatname); - var parameters = MBImport.buildFormParameters(release, edit_note); + // Form parameters + let edit_note = MBImport.makeEditNote(this.currentURL(), 'CD1D', formatname); + let parameters = MBImport.buildFormParameters(release, edit_note); - // Build form - var mbUI = $('
    ' - + MBImport.buildFormHTML(parameters) - + MBImport.buildSearchButton(release) - + '
    ').hide(); - $(where).append(mbUI); - $('#mb_buttons').css({'margin-top': '6px'}); - $('form.musicbrainz_import').css({display: 'inline-block', 'margin-right': '5px'}); - mbUI.slideDown(); - } + // Build form + let mbUI = $(`
    ${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}
    `).hide(); + $(where).append(mbUI); + $('#mb_buttons').css({ 'margin-top': '6px' }); + $('form.musicbrainz_import').css({ display: 'inline-block', 'margin-right': '5px' }); + mbUI.slideDown(); + } }; -$(document).ready(function () { - MBImportStyle(); - /* CD1D uses same page with hidden tabs for all formats */ - var formats = CD1DImporter.getFormats(); - //LOGGER.info('Formats:', formats); +$(document).ready(function() { + MBImportStyle(); + /* CD1D uses same page with hidden tabs for all formats */ + let formats = CD1DImporter.getFormats(); + //LOGGER.info('Formats:', formats); - for (var i = 0; i < formats.length; i++) { - var release = CD1DImporter.retrieveReleaseInfo(formats[i]); - CD1DImporter.insertLink(release, 'div#' + formats[i].id, formats[i].name); - } + for (let i = 0; i < formats.length; i++) { + let release = CD1DImporter.retrieveReleaseInfo(formats[i]); + CD1DImporter.insertLink(release, `div#${formats[i].id}`, formats[i].name); + } }); diff --git a/cdbaby_importer.user.js b/cdbaby_importer.user.js index 0164bd0..17c3fdd 100644 --- a/cdbaby_importer.user.js +++ b/cdbaby_importer.user.js @@ -18,157 +18,165 @@ this.$ = this.jQuery = jQuery.noConflict(true); if (!unsafeWindow) unsafeWindow = window; -$(document).ready(function(){ - MBImportStyle(); - var release_url = window.location.href.replace('/\?.*$/', '').replace(/#.*$/, ''); - release_url = release_url.replace(/^(?:https?:\/\/)?(?:store\.)?(?:cdbaby\.com)\//, "http://store.cdbaby.com/"); +$(document).ready(function() { + MBImportStyle(); + let release_url = window.location.href.replace('/?.*$/', '').replace(/#.*$/, ''); + release_url = release_url.replace(/^(?:https?:\/\/)?(?:store\.)?(?:cdbaby\.com)\//, 'http://store.cdbaby.com/'); - var release; - var buttons = ""; - $("div.album-page-buy-button-container a").each(function() { - var format = $(this).attr("title").trim(); - release = retrieveReleaseInfo(release_url, format); - buttons += getImportButton(release, release_url, format); - }); - - if (release) { - insertImportLinks(release, buttons); - } + let release; + let buttons = ''; + $('div.album-page-buy-button-container a').each(function() { + let format = $(this) + .attr('title') + .trim(); + release = retrieveReleaseInfo(release_url, format); + buttons += getImportButton(release, release_url, format); + }); + if (release) { + insertImportLinks(release, buttons); + } }); - function retrieveReleaseInfo(release_url, format) { - - // Release defaults - var release = { - artist_credit: '', - title: $("h1 span[itemprop='name']").text().trim(), - year: 0, - month: 0, - day: 0, - format: '', - packaging: '', - country: '', - status: 'official', - language: 'eng', - script: 'Latn', - type: '', - urls: [], - labels: [], - discs: [], - }; - - var link_type = MBImport.URL_TYPES; - - release.urls = []; - if (format.match(/^vinyl/i)) { - release.country = 'US'; - release.format = "Vinyl"; - release.urls.push({ - 'url': release_url, - 'link_type': link_type.purchase_for_mail_order - }); - } else if (format.match(/^cd/i)) { - release.country = 'US'; - release.format = 'CD'; - release.urls.push({ - 'url': release_url, - 'link_type': link_type.purchase_for_mail_order - }); - } else if (format.match(/^download/i)) { - release.country = 'XW'; - release.packaging = 'None'; - release.format = "Digital Media"; - release.urls.push({ - 'url': release_url, - 'link_type': link_type.purchase_for_download - }); - } - - // Release artist - var artist = $("h2 span[itemprop='byArtist'] a").text().trim(); - var various_artists = (artist == 'Various'); - if (various_artists) { - release.artist_credit = [ MBImport.specialArtist('various_artists') ]; - } else { - release.artist_credit = MBImport.makeArtistCredits([artist]); - } - - release.year = $("span[itemprop='datePublished']").text().trim() - - // Tracks - var tracks = []; - var trackcount = 0 - $("table.track-table tr[itemprop='track']").each(function() { - var artists = []; - var trackno = tracks.length + 1; - if (trackno == 1 && tracks.length) { - // multiple "discs" - release.discs.push( { - 'tracks': tracks, - 'format': release.format - } ); - tracks = []; - } - var trackname = $(this).find("meta[itemprop='name']").attr('content').trim(); - var tracklength = $(this).find("meta[itemprop='duration']").attr('content').trim(); - - var track_artists = []; - // FIXME various artists releases ... - $(this).find("div.track-artist").each( - function () { - var artistname = $(this).text().trim(); - if (artistname) { - track_artists.push(artistname); - } - } - ); - - var ac = { - 'artist_credit': '', - 'title': trackname, - 'duration': MBImport.ISO8601toMilliSeconds(tracklength) + // Release defaults + let release = { + artist_credit: '', + title: $("h1 span[itemprop='name']") + .text() + .trim(), + year: 0, + month: 0, + day: 0, + format: '', + packaging: '', + country: '', + status: 'official', + language: 'eng', + script: 'Latn', + type: '', + urls: [], + labels: [], + discs: [] }; - if (!track_artists.length && various_artists) { - ac.artist_credit = [ MBImport.specialArtist('unknown') ]; - } else { - ac.artist_credit = MBImport.makeArtistCredits(track_artists); + + let link_type = MBImport.URL_TYPES; + + release.urls = []; + if (format.match(/^vinyl/i)) { + release.country = 'US'; + release.format = 'Vinyl'; + release.urls.push({ + url: release_url, + link_type: link_type.purchase_for_mail_order + }); + } else if (format.match(/^cd/i)) { + release.country = 'US'; + release.format = 'CD'; + release.urls.push({ + url: release_url, + link_type: link_type.purchase_for_mail_order + }); + } else if (format.match(/^download/i)) { + release.country = 'XW'; + release.packaging = 'None'; + release.format = 'Digital Media'; + release.urls.push({ + url: release_url, + link_type: link_type.purchase_for_download + }); } - tracks.push(ac); - }); - release.discs.push( { - 'tracks': tracks, - 'format': release.format - } ); + // Release artist + let artist = $("h2 span[itemprop='byArtist'] a") + .text() + .trim(); + let various_artists = artist == 'Various'; + if (various_artists) { + release.artist_credit = [MBImport.specialArtist('various_artists')]; + } else { + release.artist_credit = MBImport.makeArtistCredits([artist]); + } - LOGGER.info("Parsed release: ", release); - return release; + release.year = $("span[itemprop='datePublished']") + .text() + .trim(); + + // Tracks + let tracks = []; + let trackcount = 0; + $("table.track-table tr[itemprop='track']").each(function() { + let artists = []; + let trackno = tracks.length + 1; + if (trackno == 1 && tracks.length) { + // multiple "discs" + release.discs.push({ + tracks: tracks, + format: release.format + }); + tracks = []; + } + let trackname = $(this) + .find("meta[itemprop='name']") + .attr('content') + .trim(); + let tracklength = $(this) + .find("meta[itemprop='duration']") + .attr('content') + .trim(); + + let track_artists = []; + // FIXME various artists releases ... + $(this) + .find('div.track-artist') + .each(function() { + let artistname = $(this) + .text() + .trim(); + if (artistname) { + track_artists.push(artistname); + } + }); + + let ac = { + artist_credit: '', + title: trackname, + duration: MBImport.ISO8601toMilliSeconds(tracklength) + }; + if (!track_artists.length && various_artists) { + ac.artist_credit = [MBImport.specialArtist('unknown')]; + } else { + ac.artist_credit = MBImport.makeArtistCredits(track_artists); + } + tracks.push(ac); + }); + + release.discs.push({ + tracks: tracks, + format: release.format + }); + + LOGGER.info('Parsed release: ', release); + return release; } function getImportButton(release, release_url, format) { - var edit_note = MBImport.makeEditNote(release_url, "CD Baby", format); - var parameters = MBImport.buildFormParameters(release, edit_note); - return MBImport.buildFormHTML(parameters).replace('Import into MB', 'Import ' + format + ''); + let edit_note = MBImport.makeEditNote(release_url, 'CD Baby', format); + let parameters = MBImport.buildFormParameters(release, edit_note); + return MBImport.buildFormHTML(parameters).replace('Import into MB', `Import ${format}`); } function insertImportLinks(release, buttons) { - $("div.right-container-top-right").prepend( - $('
    ' - + buttons - + MBImport.buildSearchButton(release) - + '
    ').hide() - ); - $('#mb_buttons').css({ - 'margin-bottom': '5px', - 'padding': '2%', - 'background-color': '#fff' - }); + $('div.right-container-top-right').prepend($(`
    ${buttons}${MBImport.buildSearchButton(release)}
    `).hide()); + $('#mb_buttons').css({ + 'margin-bottom': '5px', + padding: '2%', + 'background-color': '#fff' + }); - $('form.musicbrainz_import').css({ - 'margin-bottom': '5px' - }); + $('form.musicbrainz_import').css({ + 'margin-bottom': '5px' + }); - $('#mb_buttons').slideDown(); + $('#mb_buttons').slideDown(); } diff --git a/dgdecca_importer.user.js b/dgdecca_importer.user.js index 75e9402..75b5b2e 100644 --- a/dgdecca_importer.user.js +++ b/dgdecca_importer.user.js @@ -1,54 +1,59 @@ /* global $ MBImport */ 'use strict'; var meta = function() { -// ==UserScript== -// @name Import DG/Decca releases to MusicBrainz -// @namespace https://github.com/murdos/musicbrainz-userscripts -// @author loujine -// @version 2018.2.18.1 -// @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 -// @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 -// @compatible firefox+greasemonkey -// @licence CC BY-NC-SA 3.0 (https://creativecommons.org/licenses/by-nc-sa/3.0/) -// @include http*://*deutschegrammophon.com/*/cat/* -// @include http*://*deccaclassics.com/*/cat/* -// @require lib/mbimport.js -// @require lib/mbimportstyle.js -// @grant none -// @run-at document-end -// ==/UserScript== + // ==UserScript== + // @name Import DG/Decca releases to MusicBrainz + // @namespace https://github.com/murdos/musicbrainz-userscripts + // @author loujine + // @version 2018.2.18.1 + // @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 + // @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 + // @compatible firefox+greasemonkey + // @licence CC BY-NC-SA 3.0 (https://creativecommons.org/licenses/by-nc-sa/3.0/) + // @include http*://*deutschegrammophon.com/*/cat/* + // @include http*://*deccaclassics.com/*/cat/* + // @require lib/mbimport.js + // @require lib/mbimportstyle.js + // @grant none + // @run-at document-end + // ==/UserScript== }; if (meta && meta.toString && (meta = meta.toString())) { - var meta = {'name': meta.match(/@name\s+(.+)/)[1], - 'version': meta.match(/@version\s+(.+)/)[1]}; + var meta = { name: meta.match(/@name\s+(.+)/)[1], version: meta.match(/@version\s+(.+)/)[1] }; } var siteURL = document.URL.split('/')[2].replace('www.', ''); var months = { - 'Jan.': 1, 'Feb.': 2, 'Mar.': 3, 'Apr.': 4, - 'May': 5, 'Jun.': 6, 'Jul.': 7, 'Aug.': 8, - 'Sep.': 9, 'Oct.': 10, 'Nov.': 11, 'Dec.': 12 + 'Jan.': 1, + 'Feb.': 2, + 'Mar.': 3, + 'Apr.': 4, + May: 5, + 'Jun.': 6, + 'Jul.': 7, + 'Aug.': 8, + 'Sep.': 9, + 'Oct.': 10, + 'Nov.': 11, + 'Dec.': 12 }; var labels = { 'deutschegrammophon.com': { - 'name': 'Deutsche Grammophon', - 'mbid': '5a584032-dcef-41bb-9f8b-19540116fb1c', - 'catno': document.URL.split('/')[5] + name: 'Deutsche Grammophon', + mbid: '5a584032-dcef-41bb-9f8b-19540116fb1c', + catno: document.URL.split('/')[5] }, 'deccaclassics.com': { - 'name': 'Decca Classics', - 'mbid': '89a9993d-1dad-4445-a3d7-1d8df04f7e7b', - 'catno': document.URL.split('/')[5] + name: 'Decca Classics', + mbid: '89a9993d-1dad-4445-a3d7-1d8df04f7e7b', + catno: document.URL.split('/')[5] } -} +}; -var editNote = ('Imported from ' - + document.URL - + '\n —\n' - + 'GM script: "' + meta.name + '" (' + meta.version + ')\n\n'); +var editNote = `Imported from ${document.URL}\n —\n` + `GM script: "${meta.name}" (${meta.version})\n\n`; function _clean(s) { return s @@ -74,47 +79,52 @@ function _clean(s) { .replace(' - ', ': ') .replace(' | ', ': ') .replace('K.', 'K. ') // Mozart - .replace('S.', 'S. ') // Liszt - ; + .replace('S.', 'S. '); // Liszt } function extract_release_data() { console.log('extract_release_data'); function _setTitle() { - var title = $('h4')[0].textContent; + let title = $('h4')[0].textContent; if ($('div.works').length) { - title += ' ' + $('div.works')[0].innerHTML.replace(/

    /g, ' / ').replace(/
    /g, ' '); + title += ` ${$('div.works')[0] + .innerHTML.replace(/

    /g, ' / ') + .replace(/
    /g, ' ')}`; } return title; } function _setReleasePerformers() { - var list = $('div.artists')[0].innerHTML.split('
    ').map(function (artist) { - return { - 'credited_name': artist, - 'artist_name': artist, - 'artist_mbid': '', - 'joinphrase': ', ' - }; - }); + let list = $('div.artists')[0] + .innerHTML.split('
    ') + .map(function(artist) { + return { + credited_name: artist, + artist_name: artist, + artist_mbid: '', + joinphrase: ', ' + }; + }); list[list.length - 1]['joinphrase'] = ''; return list; } function _setReleaseArtists() { - var composer = document.getElementsByTagName('h4')[0].textContent; - var list = [{ - 'credited_name': composer, - 'artist_name': composer, - 'artist_mbid': '', - 'joinphrase': '; ' - }]; + let composer = document.getElementsByTagName('h4')[0].textContent; + let list = [ + { + credited_name: composer, + artist_name: composer, + artist_mbid: '', + joinphrase: '; ' + } + ]; return list.concat(_setReleasePerformers()); } function _indices(array, element) { - var indices = []; - var idx = array.indexOf(element); + let indices = []; + let idx = array.indexOf(element); while (idx != -1) { indices.push(idx); idx = array.indexOf(element, idx + 1); @@ -122,14 +132,14 @@ function extract_release_data() { return indices; } - var date = document.getElementsByClassName('date')[0].textContent; + let date = document.getElementsByClassName('date')[0].textContent; date = date.replace('Int. Release ', '').split(' '); - var nodes = []; - var tracklist_node = document.getElementById('tracklist'); + let nodes = []; + 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 d = {}; + let d = {}; if (node.classList.contains('hier0')) { d['level'] = 0; } else if (node.classList.contains('hier1')) { @@ -155,9 +165,9 @@ function extract_release_data() { console.log(nodes, tracklist_node); // complete track titles - var header0, header1, header2, idx; - nodes.forEach(function (node, idx) { - var level = node['level'], + let header0, header1, header2, idx; + nodes.forEach(function(node, idx) { + let level = node['level'], type = node['type'], content = node['title']; if (type === 'work') { @@ -172,30 +182,30 @@ function extract_release_data() { if (level === 0) { nodes[idx]['title'] = content; } else if (level === 1) { - nodes[idx]['title'] = header0 + ': ' + content; + nodes[idx]['title'] = `${header0}: ${content}`; } else if (level === 2) { - nodes[idx]['title'] = header0 + ', ' + header1 + ': ' + content; + nodes[idx]['title'] = `${header0}, ${header1}: ${content}`; } else if (level === 3) { - nodes[idx]['title'] = header0 + ', ' + header1 + ', ' + header2 + ': ' + content; + nodes[idx]['title'] = `${header0}, ${header1}, ${header2}: ${content}`; } } }); - var discs = [], + let discs = [], tracks = [], medium_title = ''; - nodes.forEach(function (item, idx) { + nodes.forEach(function(item, idx) { if (item.type === 'track') { - var track = extract_track_data(item.node); + let track = extract_track_data(item.node); track.title = _clean(item.title); tracks.push(track); } if (item.type === 'medium') { if (idx > 0) { discs.push({ - 'title': '', // medium_title, - 'format': 'CD', - 'tracks': tracks + title: '', // medium_title, + format: 'CD', + tracks: tracks }); } medium_title = item.title; @@ -204,118 +214,118 @@ function extract_release_data() { }); // push last medium discs.push({ - 'title': '', // nodes[0].title, - 'format': 'CD', - 'tracks': tracks + title: '', // nodes[0].title, + format: 'CD', + tracks: tracks }); return { - 'title': _setTitle(), - 'artist_credit': _setReleaseArtists(), - 'type': 'Album', - 'status': 'Official', - 'language': 'eng', // 'English', - 'script': 'Latn', // 'Latin', - 'packaging': '', - 'country': '', - 'year': date[2], - 'month': months[date[1]], - 'day': date[0], - 'labels': [labels[siteURL]], - 'barcode': document.getElementById('upc').value.replace('00', ''), // too many 0s - 'urls': [{ - 'link_type': 288, // 'discography' - 'url': document.URL - }], - 'discs': discs + title: _setTitle(), + artist_credit: _setReleaseArtists(), + type: 'Album', + status: 'Official', + language: 'eng', // 'English', + script: 'Latn', // 'Latin', + packaging: '', + country: '', + year: date[2], + month: months[date[1]], + day: date[0], + labels: [labels[siteURL]], + barcode: document.getElementById('upc').value.replace('00', ''), // too many 0s + urls: [ + { + link_type: 288, // 'discography' + url: document.URL + } + ], + discs: discs }; } - - function extract_track_data(node) { function _setTrackArtists(artistString) { console.log('artistString', artistString); - var artists; + let artists; if (artistString.includes(' | ')) { - artists = artistString.split(' | ').map(function (artist) { + artists = artistString.split(' | ').map(function(artist) { return { - 'credited_name': artist.split(',')[0], - 'artist_name': artist.split(',')[0], - 'artist_mbid': '', - 'joinphrase': ', ' + credited_name: artist.split(',')[0], + artist_name: artist.split(',')[0], + artist_mbid: '', + joinphrase: ', ' }; }); } else { - artists = artistString.split(', ').map(function (artist, idx) { - var mbid = ''; - var url = '/ws/js/artist/?q=' + artist + '&fmt=json&limit=1'; + artists = artistString.split(', ').map(function(artist, idx) { + let mbid = ''; + let url = `/ws/js/artist/?q=${artist}&fmt=json&limit=1`; return { - 'credited_name': artist, - 'artist_name': artist, - 'artist_mbid': mbid, - 'joinphrase': ', ' + credited_name: artist, + artist_name: artist, + artist_mbid: mbid, + joinphrase: ', ' }; }); } artists[artists.length - 1]['joinphrase'] = ''; - return artists + return artists; } - var schema = {}; + let schema = {}; if (node.querySelectorAll('meta').length) { // https://schema.org/MusicRecording info available - for (var item of node.querySelectorAll('meta')) { - var attrs = item.attributes; + for (let item of node.querySelectorAll('meta')) { + let attrs = item.attributes; schema[attrs.itemprop.value] = attrs.content.value; } } else { console.log('no meta data on ', node); schema.name = node.querySelectorAll('div.track-text > a.fancy')[0].textContent; - schema.byArtist = $(node).parent().nextAll('div.container-container').children('.artists-container')[0].textContent; - var previousComposers = $(node).parent().prevAll('div.container-container').children('.first-composer-container'); - schema.creator = previousComposers[previousComposers.length-1].textContent; + schema.byArtist = $(node) + .parent() + .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); return { - 'number': parseInt(node.querySelectorAll('div.track-no')[0].textContent), - 'title': _clean(schema.name), - 'duration': node.querySelectorAll('div.track-time')[0].textContent, - 'artist_credit': _setTrackArtists(schema.byArtist), // CSG - 'performer': schema.byArtist, - 'composer': schema.creator, - 'url': node.querySelectorAll('div.track-text > a.fancy')[0].href + number: parseInt(node.querySelectorAll('div.track-no')[0].textContent), + title: _clean(schema.name), + duration: node.querySelectorAll('div.track-time')[0].textContent, + artist_credit: _setTrackArtists(schema.byArtist), // CSG + performer: schema.byArtist, + composer: schema.creator, + url: node.querySelectorAll('div.track-text > a.fancy')[0].href }; } - // Insert links in page function insertMBSection(release) { - var mbUI = $('

    MusicBrainz

    '); - var mbContentBlock = $('
    '); + let mbUI = $('

    MusicBrainz

    '); + let mbContentBlock = $('
    '); mbUI.append(mbContentBlock); // Form parameters - var parameters = MBImport.buildFormParameters(release, editNote); + let parameters = MBImport.buildFormParameters(release, editNote); // Build form + search button - var innerHTML = '
    ' - + MBImport.buildFormHTML(parameters) - + MBImport.buildSearchButton(release) - + '
    '; + let innerHTML = `
    ${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}
    `; mbContentBlock.append(innerHTML); $('div#product-text').append(mbUI[0]); $('#mb_buttons').css({ - display: 'inline-block', - width: '100%' + display: 'inline-block', + width: '100%' }); - $('form.musicbrainz_import').css({width: '49%', display: 'inline-block'}); - $('form.musicbrainz_import_search').css({'float': 'right'}) - $('form.musicbrainz_import > button').css( - {width: '100%', 'box-sizing': 'border-box'} - ); + $('form.musicbrainz_import').css({ width: '49%', display: 'inline-block' }); + $('form.musicbrainz_import_search').css({ float: 'right' }); + $('form.musicbrainz_import > button').css({ width: '100%', 'box-sizing': 'border-box' }); mbUI.slideDown(); } diff --git a/discogs_importer.user.js b/discogs_importer.user.js index 8c8b582..891b49e 100644 --- a/discogs_importer.user.js +++ b/discogs_importer.user.js @@ -18,7 +18,6 @@ // @icon https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/assets/images/Musicbrainz_import_logo.png // ==/UserScript== - // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant this.$ = this.jQuery = jQuery.noConflict(true); @@ -27,7 +26,7 @@ if (!unsafeWindow) unsafeWindow = window; var DEBUG = false; //DEBUG = true; if (DEBUG) { - LOGGER.setLevel('debug'); + LOGGER.setLevel('debug'); } //////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -39,57 +38,61 @@ if (DEBUG) { var mblinks = new MBLinks('DISCOGS_MBLINKS_CACHE', '1'); -$(document).ready(function(){ - +$(document).ready(function() { MBImportStyle(); MBSearchItStyle(); - var current_page_key = getDiscogsLinkKey(window.location.href.replace(/\?.*$/, '').replace(/#.*$/, '').replace('/master/view/', '/master/')); + let current_page_key = getDiscogsLinkKey( + window.location.href + .replace(/\?.*$/, '') + .replace(/#.*$/, '') + .replace('/master/view/', '/master/') + ); if (!current_page_key) return; // disable evil pjax (used for artist page navigation) // it causes various annoying issues with our code; // it should be possible to react to pjax events - $("div#pjax_container").attr('id', 'pjax_disabled'); + $('div#pjax_container').attr('id', 'pjax_disabled'); // Display links of equivalent MusicBrainz entities insertMBLinks(current_page_key); // Add an import button in a new section in sidebar, if we're on a release page - var current_page_info = link_infos[current_page_key]; + let current_page_info = link_infos[current_page_key]; if (current_page_info.type == 'release') { - // Discogs Webservice URL - var discogsWsUrl = 'https://api.discogs.com/releases/' + current_page_info.id; + let discogsWsUrl = `https://api.discogs.com/releases/${current_page_info.id}`; $.ajax({ url: discogsWsUrl, dataType: 'json', crossDomain: true, - success: function (data, textStatus, jqXHR) { - LOGGER.debug("Discogs JSON Data from API:", data); + success: function(data, textStatus, jqXHR) { + LOGGER.debug('Discogs JSON Data from API:', data); try { - var release = parseDiscogsRelease(data); - insertMBSection(release, current_page_key); - } catch (e) { - $('div.musicbrainz').remove(); - var mbUI = $('

    MusicBrainz

    ').hide(); - var mbContentBlock = $('
    '); - mbUI.append(mbContentBlock); - var mbError = $('

    ' + e + '
    Please report this error, along the current page URL.

    '); - mbContentBlock.prepend(mbError); - insertMbUI(mbUI); - mbError.css({'background-color': '#fbb', 'margin-top': '4px', 'margin-bottom': '4px'}); - mbUI.slideDown(); - throw e; + let release = parseDiscogsRelease(data); + insertMBSection(release, current_page_key); + } catch (e) { + $('div.musicbrainz').remove(); + let mbUI = $('

    MusicBrainz

    ').hide(); + let mbContentBlock = $('
    '); + mbUI.append(mbContentBlock); + let mbError = $( + `

    ${e}
    Please report this error, along the current page URL.

    ` + ); + mbContentBlock.prepend(mbError); + insertMbUI(mbUI); + mbError.css({ 'background-color': '#fbb', 'margin-top': '4px', 'margin-bottom': '4px' }); + mbUI.slideDown(); + throw e; } }, error: function(jqXHR, textStatus, errorThrown) { - LOGGER.error("AJAX Status: ", textStatus); - LOGGER.error("AJAX error thrown: ", errorThrown); + LOGGER.error('AJAX Status: ', textStatus); + LOGGER.error('AJAX error thrown: ', errorThrown); } }); - } }); @@ -99,142 +102,156 @@ $(document).ready(function(){ // Insert MusicBrainz links in a section of the page function insertMBLinks(current_page_key) { - function searchAndDisplayMbLinkInSection($tr, discogs_type, mb_type, nosearch) { if (!mb_type) mb_type = defaultMBtype(discogs_type); - $tr.find('a[mlink^="' + discogs_type + '/"]').each(function() { - var $link = $(this); + $tr.find(`a[mlink^="${discogs_type}/"]`).each(function() { + let $link = $(this); if ($link.attr('mlink_stop')) return; // for places - var mlink = $link.attr('mlink'); + let mlink = $link.attr('mlink'); // ensure we do it only once per link - var done = ($link.attr('mlink_done') || "").split(","); - for (var i=0; i'); - } - if (!nosearch) { - // add search link for the current link text - var entities = { - 'artist': { mark: 'A'}, - 'release': { mark: 'R'}, - 'release-group': { mark: 'G'}, - 'place': { mark: 'P'}, - 'label': { mark: 'L'} + let discogs_url = link_infos[mlink].clean_url; + let cachekey = getCacheKeyFromInfo(mlink, mb_type); + let has_wrapper = $link.closest('span.mb_wrapper').length; + if (!has_wrapper) { + $link.wrap(''); } - var mark = ''; - var entity_name = 'entity'; - if (mb_type in entities) { - mark = entities[mb_type].mark; - entity_name = mb_type.replace(/[_-]/g, ' '); + if (!nosearch) { + // add search link for the current link text + let entities = { + artist: { mark: 'A' }, + release: { mark: 'R' }, + 'release-group': { mark: 'G' }, + place: { mark: 'P' }, + label: { mark: 'L' } + }; + let mark = ''; + let entity_name = 'entity'; + if (mb_type in entities) { + mark = entities[mb_type].mark; + entity_name = mb_type.replace(/[_-]/g, ' '); + } + $link + .closest('span.mb_wrapper') + .prepend( + `${mark}?` + ); } - $link.closest('span.mb_wrapper').prepend(''+mark+'?'); - } - var insert_normal = function (link) { - $link.closest('span.mb_valign').before(''+link+''); - $link.closest('span.mb_wrapper').find('.mb_searchit').remove(); - }; + let insert_normal = function(link) { + $link.closest('span.mb_valign').before(`${link}`); + $link + .closest('span.mb_wrapper') + .find('.mb_searchit') + .remove(); + }; - var insert_stop = function (link) { - insert_normal(link); - $link.attr('mlink_stop', true); - }; + let insert_stop = function(link) { + insert_normal(link); + $link.attr('mlink_stop', true); + }; - var insert_func = insert_normal; - if (mb_type == 'place') { - // if a place link was added we stop, we don't want further queries for this 'label' - insert_func = insert_stop; - } - mblinks.searchAndDisplayMbLink(discogs_url, mb_type, insert_func, cachekey); + let insert_func = insert_normal; + if (mb_type == 'place') { + // if a place link was added we stop, we don't want further queries for this 'label' + insert_func = insert_stop; + } + mblinks.searchAndDisplayMbLink(discogs_url, mb_type, insert_func, cachekey); } }); } function debug_color(what, n, id) { - var colors = [ - '#B3C6FF', - '#C6B3FF', - '#ECB3FF', - '#FFB3EC', - '#FFB3C6', - '#FFC6B3', - '#FFECB3', - '#ECFFB3', - '#C6FFB3', - '#B3FFC6', - '#B3FFEC', - '#B3ECFF', - '#7598FF', - ]; - if (DEBUG) { - $(what).css('border', '2px dotted ' + colors[n%colors.length]); - var debug_attr = $(what).attr('debug_discogs'); - if (!id) id = ''; - if (debug_attr) { - $(what).attr('debug_discogs', debug_attr + ' || ' + id + '(' + n + ')'); - } else { - $(what).attr('debug_discogs', id + '(' + n + ')'); + let colors = [ + '#B3C6FF', + '#C6B3FF', + '#ECB3FF', + '#FFB3EC', + '#FFB3C6', + '#FFC6B3', + '#FFECB3', + '#ECFFB3', + '#C6FFB3', + '#B3FFC6', + '#B3FFEC', + '#B3ECFF', + '#7598FF' + ]; + if (DEBUG) { + $(what).css('border', `2px dotted ${colors[n % colors.length]}`); + let debug_attr = $(what).attr('debug_discogs'); + if (!id) id = ''; + if (debug_attr) { + $(what).attr('debug_discogs', `${debug_attr} || ${id}(${n})`); + } else { + $(what).attr('debug_discogs', `${id}(${n})`); + } } - } } - var add_mblinks_counter = 0; + let add_mblinks_counter = 0; function add_mblinks(_root, selector, types, nosearch) { - // types can be: - // 'discogs type 1' - // ['discogs_type 1', 'discogs_type 2'] - // [['discogs_type 1', 'mb type 1'], 'discogs_type 2'] - // etc. - if (!$.isArray(types)) { - // just one string - types = [types]; - } - $.each(types, - function (idx, val) { - if (!$.isArray(val)) { - types[idx] = [val, undefined]; - } + // types can be: + // 'discogs type 1' + // ['discogs_type 1', 'discogs_type 2'] + // [['discogs_type 1', 'mb type 1'], 'discogs_type 2'] + // etc. + if (!$.isArray(types)) { + // just one string + types = [types]; } - ); + $.each(types, function(idx, val) { + if (!$.isArray(val)) { + types[idx] = [val, undefined]; + } + }); - LOGGER.debug('add_mblinks: ' + selector + ' / ' + JSON.stringify(types)); + LOGGER.debug(`add_mblinks: ${selector} / ${JSON.stringify(types)}`); - _root.find(selector).each(function() { - var node = $(this).get(0); - magnifyLinks(node); - debug_color(this, ++add_mblinks_counter, selector); - var that = this; - $.each(types, function (idx, val) { - var discogs_type = val[0]; - var mb_type = val[1]; - searchAndDisplayMbLinkInSection($(that), discogs_type, mb_type, nosearch); - }); - }); + _root.find(selector).each(function() { + let node = $(this).get(0); + magnifyLinks(node); + debug_color(this, ++add_mblinks_counter, selector); + let that = this; + $.each(types, function(idx, val) { + let discogs_type = val[0]; + let mb_type = val[1]; + searchAndDisplayMbLinkInSection($(that), discogs_type, mb_type, nosearch); + }); + }); } // Find MB link for the current page and display it next to page title - var mbLinkInsert = function (link) { - var $h1 = $('h1'); - var $titleSpan = $h1.children('span[itemprop="name"]'); - if ($titleSpan.length > 0) { - $titleSpan.before(link); - } else { - $h1.prepend(link); - } - } - var current_page_info = link_infos[current_page_key]; - var mb_type = defaultMBtype(current_page_info.type); - var cachekey = getCacheKeyFromInfo(current_page_key, mb_type); + let mbLinkInsert = function(link) { + let $h1 = $('h1'); + let $titleSpan = $h1.children('span[itemprop="name"]'); + if ($titleSpan.length > 0) { + $titleSpan.before(link); + } else { + $h1.prepend(link); + } + }; + let current_page_info = link_infos[current_page_key]; + let mb_type = defaultMBtype(current_page_info.type); + let cachekey = getCacheKeyFromInfo(current_page_key, mb_type); mblinks.searchAndDisplayMbLink(current_page_info.clean_url, mb_type, mbLinkInsert, cachekey); - var $root = $('body'); + let $root = $('body'); add_mblinks($root, 'div.profile', ['artist', 'label']); add_mblinks($root, 'tr[data-object-type="release"] td.artist,td.title', 'artist'); add_mblinks($root, 'tr[data-object-type="release"] td.title', 'release'); @@ -244,10 +261,8 @@ function insertMBLinks(current_page_key) { add_mblinks($root, 'div#companies', [['label', 'place'], 'label']); add_mblinks($root, 'div#credits', ['label', 'artist']); add_mblinks($root, 'div#page_aside div.section_content:first', 'master', true); - } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Normalize Discogs URLs in a DOM tree // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -255,25 +270,22 @@ var mlink_processed = 0; // Normalize Discogs URLs in a DOM tree function magnifyLinks(rootNode) { - if (!rootNode) { rootNode = document.body; } // Check if we already added links for this content - if (rootNode.hasAttribute('mlink_processed')) - return; + if (rootNode.hasAttribute('mlink_processed')) return; rootNode.setAttribute('mlink_processed', ++mlink_processed); - var elems = rootNode.getElementsByTagName('a'); - for (var i = 0; i < elems.length; i++) { - var elem = elems[i]; + let elems = rootNode.getElementsByTagName('a'); + for (let i = 0; i < elems.length; i++) { + let elem = elems[i]; // Ignore empty links - if (!elem.href || $.trim(elem.textContent) == '' || elem.textContent.substring(4,0) == 'http') - continue; + if (!elem.href || $.trim(elem.textContent) == '' || elem.textContent.substring(4, 0) == 'http') continue; if (!elem.hasAttribute('mlink')) { - elem.setAttribute('mlink', getDiscogsLinkKey(elem.href)); + elem.setAttribute('mlink', getDiscogsLinkKey(elem.href)); } } } @@ -284,82 +296,80 @@ var link_infos = {}; // Parse discogs url to extract info, returns a key and set link_infos for this key // the key is in the form discogs_type/discogs_id function getDiscogsLinkKey(url) { - var re = /^https?:\/\/(?:www|api)\.discogs\.com\/(?:(?:(?!sell).+|sell.+)\/)?(master|release|artist|label)s?\/(\d+)(?:[^\?#]*)(?:\?noanv=1|\?anv=[^=]+)?$/i; - if (m = re.exec(url)) { - var key = m[1] + '/' + m[2]; - if (!link_infos[key]) { - link_infos[key] = { - type: m[1], - id: m[2], - clean_url: 'https://www.discogs.com/' + m[1] + '/' + m[2] + let re = /^https?:\/\/(?:www|api)\.discogs\.com\/(?:(?:(?!sell).+|sell.+)\/)?(master|release|artist|label)s?\/(\d+)(?:[^\?#]*)(?:\?noanv=1|\?anv=[^=]+)?$/i; + if ((m = re.exec(url))) { + let key = `${m[1]}/${m[2]}`; + if (!link_infos[key]) { + link_infos[key] = { + type: m[1], + id: m[2], + clean_url: `https://www.discogs.com/${m[1]}/${m[2]}` + }; + LOGGER.debug(`getDiscogsLinkKey:${url} --> ${key}`); + } else { + LOGGER.debug(`getDiscogsLinkKey:${url} --> ${key} (key exists)`); } - LOGGER.debug('getDiscogsLinkKey:' + url + ' --> ' + key); - } else { - LOGGER.debug('getDiscogsLinkKey:' + url + ' --> ' + key + ' (key exists)'); - } - return key; + return key; } - LOGGER.debug('getDiscogsLinkKey:' + url + ' ?'); + LOGGER.debug(`getDiscogsLinkKey:${url} ?`); return false; } function getCleanUrl(url, discogs_type) { - try { - var key = getDiscogsLinkKey(url); - if (key) { - if (!discogs_type || link_infos[key].type == discogs_type) { - LOGGER.debug('getCleanUrl: ' + key + ', ' + url + ' --> ' + link_infos[key].clean_url); - return link_infos[key].clean_url; - } else { - LOGGER.debug('getCleanUrl: ' + key + ', ' + url + ' --> unmatched type: ' + discogs_type); - } + try { + let key = getDiscogsLinkKey(url); + if (key) { + if (!discogs_type || link_infos[key].type == discogs_type) { + LOGGER.debug(`getCleanUrl: ${key}, ${url} --> ${link_infos[key].clean_url}`); + return link_infos[key].clean_url; + } else { + LOGGER.debug(`getCleanUrl: ${key}, ${url} --> unmatched type: ${discogs_type}`); + } + } + } catch (err) { + LOGGER.error(err); } - } - catch (err) { - LOGGER.error(err); - } - LOGGER.debug('getCleanUrl: ' + url + ' (' + discogs_type + ') failed'); - return false; + LOGGER.debug(`getCleanUrl: ${url} (${discogs_type}) failed`); + return false; } function defaultMBtype(discogs_type) { - if (discogs_type == 'master') return 'release-group'; - return discogs_type; + if (discogs_type == 'master') return 'release-group'; + return discogs_type; } function getCacheKeyFromInfo(info_key, mb_type) { - var inf = link_infos[info_key]; - if (inf) { - if (!mb_type) mb_type = defaultMBtype(inf.type); - return inf.type + '/' + inf.id + '/' + mb_type; - } - return ''; + let inf = link_infos[info_key]; + if (inf) { + if (!mb_type) mb_type = defaultMBtype(inf.type); + return `${inf.type}/${inf.id}/${mb_type}`; + } + return ''; } function getCacheKeyFromUrl(url, discogs_type, mb_type) { - try { - var key = getDiscogsLinkKey(url); - if (key) { - if (!discogs_type || link_infos[key].type == discogs_type) { - var cachekey = getCacheKeyFromInfo(key, mb_type); - LOGGER.debug('getCacheKeyFromUrl: ' + key + ', ' + url + ' --> ' + cachekey); - return cachekey; - } else { - LOGGER.debug('getCacheKeyFromUrl: ' + key + ', ' + url + ' --> unmatched type: ' + discogs_type); - } + try { + let key = getDiscogsLinkKey(url); + if (key) { + if (!discogs_type || link_infos[key].type == discogs_type) { + let cachekey = getCacheKeyFromInfo(key, mb_type); + LOGGER.debug(`getCacheKeyFromUrl: ${key}, ${url} --> ${cachekey}`); + return cachekey; + } else { + LOGGER.debug(`getCacheKeyFromUrl: ${key}, ${url} --> unmatched type: ${discogs_type}`); + } + } + } catch (err) { + LOGGER.error(err); } - } - catch (err) { - LOGGER.error(err); - } - LOGGER.debug('getCacheKeyFromUrl: ' + url + ' (' + discogs_type + ') failed'); - return false; + LOGGER.debug(`getCacheKeyFromUrl: ${url} (${discogs_type}) failed`); + return false; } function MBIDfromUrl(url, discogs_type, mb_type) { - var cachekey = getCacheKeyFromUrl(url, discogs_type, mb_type); - if (!cachekey) return ''; - return mblinks.resolveMBID(cachekey); + let cachekey = getCacheKeyFromUrl(url, discogs_type, mb_type); + if (!cachekey) return ''; + return mblinks.resolveMBID(cachekey); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -367,52 +377,51 @@ function MBIDfromUrl(url, discogs_type, mb_type) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function insertMbUI(mbUI) { - var e; - if ((e = $("div.section.collections")) && e.length) { - e.after(mbUI); - } else if ((e = $('#statistics')) && e.length) { - e.before(mbUI); - } else if ((e = $("div.section.social")) && e.length) { - e.before(mbUI); - } + let e; + if ((e = $('div.section.collections')) && e.length) { + e.after(mbUI); + } else if ((e = $('#statistics')) && e.length) { + e.before(mbUI); + } else if ((e = $('div.section.social')) && e.length) { + e.before(mbUI); + } } // Insert links in Discogs page function insertMBSection(release, current_page_key) { - var current_page_info = link_infos[current_page_key]; + let current_page_info = link_infos[current_page_key]; - var mbUI = $('

    MusicBrainz

    ').hide(); + let mbUI = $('

    MusicBrainz

    ').hide(); - if (DEBUG) mbUI.css({'border': '1px dotted red'}); + if (DEBUG) mbUI.css({ border: '1px dotted red' }); - var mbContentBlock = $('
    '); + let mbContentBlock = $('
    '); mbUI.append(mbContentBlock); if (release.maybe_buggy) { - var warning_buggy = $('

    Warning: this release has perhaps a buggy tracklist, please check twice the data you import.Warning: this release has perhaps a buggy tracklist, please check twice the data you import.'; + let innerHTML = `

    ${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}
    `; mbContentBlock.append(innerHTML); insertMbUI(mbUI); $('#mb_buttons').css({ - display: 'inline-block', - width: '100%' + display: 'inline-block', + width: '100%' }); - $('form.musicbrainz_import').css({width: '49%', display:'inline-block'}); - $('form.musicbrainz_import_search').css({'float': 'right'}) - $('form.musicbrainz_import > button').css({width: '100%', 'box-sizing': 'border-box'}); + $('form.musicbrainz_import').css({ width: '49%', display: 'inline-block' }); + $('form.musicbrainz_import_search').css({ float: 'right' }); + $('form.musicbrainz_import > button').css({ width: '100%', 'box-sizing': 'border-box' }); mbUI.slideDown(); } @@ -422,43 +431,42 @@ function insertMBSection(release, current_page_key) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function cleanup_discogs_artist_credit(obj) { - // Fix some odd Discogs release (e.g. http://api.discogs.com/releases/1566223) that have a ',' join phrase after the last artist - // Discogs set a join phrase even there's only one artist or when extraartists is set (ie. remix) - var last = obj.artist_credit.length-1; - if (last == 0 || obj.artist_credit[last].joinphrase == ", ") { - obj.artist_credit[last].joinphrase = ""; - } + // Fix some odd Discogs release (e.g. http://api.discogs.com/releases/1566223) that have a ',' join phrase after the last artist + // Discogs set a join phrase even there's only one artist or when extraartists is set (ie. remix) + let last = obj.artist_credit.length - 1; + if (last == 0 || obj.artist_credit[last].joinphrase == ', ') { + obj.artist_credit[last].joinphrase = ''; + } } // Returns the name without the numerical suffic Discogs adds as disambiguation // ie. "ABC (123)" -> "ABC" function artistNoNum(artist_name) { - return artist_name.replace(/ \(\d+\)$/, ""); + return artist_name.replace(/ \(\d+\)$/, ''); } // Parse a US date string and set object properties year, month, day function parse_YYYY_MM_DD(date, obj) { - if (!date) return; - var m = date.split(/\D+/, 3).map(function (e) { - return parseInt(e, 10); - }); - if (m[0] !== undefined) { - obj.year = m[0]; - if (m[1] !== undefined) { - obj.month = m[1]; - if (m[2] !== undefined) { - obj.day = m[2]; - } + if (!date) return; + let m = date.split(/\D+/, 3).map(function(e) { + return parseInt(e, 10); + }); + if (m[0] !== undefined) { + obj.year = m[0]; + if (m[1] !== undefined) { + obj.month = m[1]; + if (m[2] !== undefined) { + obj.day = m[2]; + } + } } - } } // Analyze Discogs data and return a release object function parseDiscogsRelease(data) { + let discogsRelease = data; - var discogsRelease = data; - - var release = {}; + let release = {}; release.discs = []; //buggy tracklist indicator, used to warn user @@ -467,14 +475,15 @@ function parseDiscogsRelease(data) { // Release artist credit release.artist_credit = []; $.each(discogsRelease.artists, function(index, artist) { - var ac = { - 'artist_name': artistNoNum(artist.name), - 'credited_name': (artist.anv != "" ? artist.anv : artistNoNum(artist.name)), - 'joinphrase': decodeDiscogsJoinphrase(artist.join), - 'mbid': MBIDfromUrl(artist.resource_url, 'artist') + let ac = { + artist_name: artistNoNum(artist.name), + credited_name: artist.anv != '' ? artist.anv : artistNoNum(artist.name), + joinphrase: decodeDiscogsJoinphrase(artist.join), + mbid: MBIDfromUrl(artist.resource_url, 'artist') }; - if (artist.id == 194) { // discogs place holder for various - ac = MBImport.specialArtist('various_artists', ac); + if (artist.id == 194) { + // discogs place holder for various + ac = MBImport.specialArtist('various_artists', ac); } release.artist_credit.push(ac); }); @@ -482,7 +491,7 @@ function parseDiscogsRelease(data) { // ReleaseGroup if (discogsRelease.master_url) { - release.release_group_mbid = MBIDfromUrl(discogsRelease.master_url, 'master'); + release.release_group_mbid = MBIDfromUrl(discogsRelease.master_url, 'master'); } // Release title @@ -490,7 +499,7 @@ function parseDiscogsRelease(data) { // Release date if (discogsRelease.released) { - parse_YYYY_MM_DD(discogsRelease.released, release); + parse_YYYY_MM_DD(discogsRelease.released, release); } // Release country @@ -502,25 +511,24 @@ function parseDiscogsRelease(data) { release.labels = []; if (discogsRelease.labels) { $.each(discogsRelease.labels, function(index, label) { - var labelinfo = { - name: label.name, - catno: (label.catno == "none" ? "[none]" : label.catno), - mbid: MBIDfromUrl(label.resource_url, 'label') - }; - release.labels.push(labelinfo); + let labelinfo = { + name: label.name, + catno: label.catno == 'none' ? '[none]' : label.catno, + mbid: MBIDfromUrl(label.resource_url, 'label') + }; + release.labels.push(labelinfo); }); } // Release URL - release.urls = [ { url: getCleanUrl(discogsRelease.uri, 'release'), link_type: MBImport.URL_TYPES.discogs } ]; + release.urls = [{ url: getCleanUrl(discogsRelease.uri, 'release'), link_type: MBImport.URL_TYPES.discogs }]; // Release format - var release_formats = []; + let release_formats = []; release.secondary_types = []; if (discogsRelease.formats.length > 0) { - for (var i = 0; i < discogsRelease.formats.length; i++) { - + for (let i = 0; i < discogsRelease.formats.length; i++) { // Release format var discogs_format = discogsRelease.formats[i].name; var mb_format = undefined; @@ -532,41 +540,41 @@ function parseDiscogsRelease(data) { $.each(discogsRelease.formats[i].descriptions, function(index, desc) { if (!(discogs_format in ['Box Set'])) { // Release format: special handling of Vinyl and Shellac 7", 10" and 12" - if (desc.match(/7"|10"|12"/) && (discogs_format.concat(desc) in MediaTypes)) mb_format = MediaTypes[discogs_format.concat(desc)]; + if (desc.match(/7"|10"|12"/) && discogs_format.concat(desc) in MediaTypes) + mb_format = MediaTypes[discogs_format.concat(desc)]; // Release format: special handling of specific CD/DVD formats - if (desc.match(/^VCD|SVCD|CD\+G|HDCD|DVD-Audio|DVD-Video/) && (desc in MediaTypes)) mb_format = MediaTypes[desc]; + if (desc.match(/^VCD|SVCD|CD\+G|HDCD|DVD-Audio|DVD-Video/) && desc in MediaTypes) mb_format = MediaTypes[desc]; } // Release format: special handling of Vinyl, LP == 12" (http://www.discogs.com/help/submission-guidelines-release-format.html#LP) - if (discogs_format == "Vinyl" && desc == "LP") mb_format = '12" Vinyl'; + if (discogs_format == 'Vinyl' && desc == 'LP') mb_format = '12" Vinyl'; // Release format: special handling of CD, Mini == 8cm CD - if (discogs_format == "CD" && desc == "Mini") mb_format = '8cm CD'; + if (discogs_format == 'CD' && desc == 'Mini') mb_format = '8cm CD'; // Release status - if (desc.match(/Promo|Smplr/)) release.status = "promotion"; - if (desc.match(/Unofficial Release/)) release.status = "bootleg"; + if (desc.match(/Promo|Smplr/)) release.status = 'promotion'; + if (desc.match(/Unofficial Release/)) release.status = 'bootleg'; // Release type - if (desc.match(/Compilation/)) release.secondary_types.push("compilation"); - if (desc.match(/^Album/)) release.type = "album"; - if (desc.match(/Single(?! Sided)/)) release.type = "single"; - if (desc.match(/EP|Mini-Album/)) release.type = "ep"; + if (desc.match(/Compilation/)) release.secondary_types.push('compilation'); + if (desc.match(/^Album/)) release.type = 'album'; + if (desc.match(/Single(?! Sided)/)) release.type = 'single'; + if (desc.match(/EP|Mini-Album/)) release.type = 'ep'; }); } if (mb_format) { - for (var j = 0; j < discogsRelease.formats[i].qty; j++) { + for (let j = 0; j < discogsRelease.formats[i].qty; j++) { release_formats.push(mb_format); } } // Release packaging if (discogsRelease.formats[i].text) { - var freetext = discogsRelease.formats[i].text.toLowerCase().replace(/[\s-]/g, ''); - if (freetext.match(/cardboard|paper/)) release.packaging = "cardboard/paper sleeve"; - else if (freetext.match(/digipak/)) release.packaging = "digipak"; - else if (freetext.match(/keepcase/)) release.packaging = "keep case"; + let freetext = discogsRelease.formats[i].text.toLowerCase().replace(/[\s-]/g, ''); + if (freetext.match(/cardboard|paper/)) release.packaging = 'cardboard/paper sleeve'; + else if (freetext.match(/digipak/)) release.packaging = 'digipak'; + else if (freetext.match(/keepcase/)) release.packaging = 'keep case'; else if (freetext.match(/jewel/)) { - release.packaging = freetext.match(/slim/) ? "slim jewel case" : "jewel case"; - } - else if (freetext.match(/gatefold|digisleeve/)) release.packaging = "gatefold cover"; + release.packaging = freetext.match(/slim/) ? 'slim jewel case' : 'jewel case'; + } else if (freetext.match(/gatefold|digisleeve/)) release.packaging = 'gatefold cover'; } } } @@ -574,7 +582,7 @@ function parseDiscogsRelease(data) { // Barcode if (discogsRelease.identifiers) { $.each(discogsRelease.identifiers, function(index, identifier) { - if (identifier.type == "Barcode") { + if (identifier.type == 'Barcode') { release.barcode = identifier.value.replace(/ /g, ''); return false; } @@ -582,22 +590,21 @@ function parseDiscogsRelease(data) { } // Inspect tracks - var tracks = []; + let tracks = []; - var heading = ""; - var releaseNumber = 1; - var lastPosition = 0; + let heading = ''; + let releaseNumber = 1; + let lastPosition = 0; $.each(discogsRelease.tracklist, function(index, discogsTrack) { - if (discogsTrack.type_ == 'heading') { - heading = discogsTrack.title; - return; + heading = discogsTrack.title; + return; } if (discogsTrack.type_ != 'track' && discogsTrack.type_ != 'index') { - return; + return; } - var track = new Object(); + let track = new Object(); track.title = discogsTrack.title.replace(/´/g, '’'); track.duration = MBImport.hmsToMilliSeconds(discogsTrack.duration); // MB in milliseconds @@ -606,11 +613,11 @@ function parseDiscogsRelease(data) { track.artist_credit = []; if (discogsTrack.artists) { $.each(discogsTrack.artists, function(index, artist) { - var ac = { - 'artist_name': artistNoNum(artist.name), - 'credited_name': (artist.anv != "" ? artist.anv : artistNoNum(artist.name)), - 'joinphrase': decodeDiscogsJoinphrase(artist.join), - 'mbid': MBIDfromUrl(artist.resource_url, 'artist') + let ac = { + artist_name: artistNoNum(artist.name), + credited_name: artist.anv != '' ? artist.anv : artistNoNum(artist.name), + joinphrase: decodeDiscogsJoinphrase(artist.join), + mbid: MBIDfromUrl(artist.resource_url, 'artist') }; track.artist_credit.push(ac); }); @@ -618,73 +625,77 @@ function parseDiscogsRelease(data) { } // Track position and release number - var trackPosition = discogsTrack.position; + let trackPosition = discogsTrack.position; // Handle sub-tracks - if (trackPosition == "" && discogsTrack.sub_tracks) { + if (trackPosition == '' && discogsTrack.sub_tracks) { trackPosition = discogsTrack.sub_tracks[0].position; // Append titles of sub-tracks to main track title - var subtrack_titles = []; - var subtrack_total_duration = 0; + let subtrack_titles = []; + let subtrack_total_duration = 0; $.each(discogsTrack.sub_tracks, function(subtrack_index, subtrack) { - if (subtrack.type_ != 'track') { - return; - } - if (subtrack.duration) { - subtrack_total_duration += MBImport.hmsToMilliSeconds(subtrack.duration); - } - if (subtrack.title) { - subtrack_titles.push(subtrack.title); - } else { - subtrack_titles.push('[unknown]'); - } + if (subtrack.type_ != 'track') { + return; + } + if (subtrack.duration) { + subtrack_total_duration += MBImport.hmsToMilliSeconds(subtrack.duration); + } + if (subtrack.title) { + subtrack_titles.push(subtrack.title); + } else { + subtrack_titles.push('[unknown]'); + } }); if (subtrack_titles.length) { - if (track.title) { - track.title += ': '; - } - track.title += subtrack_titles.join(' / '); + if (track.title) { + track.title += ': '; + } + track.title += subtrack_titles.join(' / '); } if (isNaN(track.duration) && !isNaN(subtrack_total_duration)) { - track.duration = subtrack_total_duration; + track.duration = subtrack_total_duration; } } // Skip special tracks if (trackPosition.match(/^(?:video|mp3)/i)) { - trackPosition = ""; + trackPosition = ''; } // Possible track position: // A1 or A => Vinyl or Cassette : guess releaseNumber from vinyl side // 1-1 or 1.1 => releaseNumber.trackNumber // 1 => trackNumber - var tmp = trackPosition.match(/(\d+|[A-Z])(?:[\.-]+(\d+))?/i); + let tmp = trackPosition.match(/(\d+|[A-Z])(?:[\.-]+(\d+))?/i); if (tmp) { tmp[1] = parseInt(tmp[1], 10); var buggyTrackNumber = false; - var prevReleaseNumber = releaseNumber; + let prevReleaseNumber = releaseNumber; if (Number.isInteger(tmp[1])) { - if (tmp[2]) { // 1-1, 1-2, 2-1, ... - we can get release number and track number from this - releaseNumber = tmp[1]; - lastPosition = parseInt(tmp[2], 10); - } else if (tmp[1] <= lastPosition) { // 1, 2, 3, ... - We've moved onto a new medium - releaseNumber++; - lastPosition = tmp[1]; - } else { - lastPosition = tmp[1]; - } + if (tmp[2]) { + // 1-1, 1-2, 2-1, ... - we can get release number and track number from this + releaseNumber = tmp[1]; + lastPosition = parseInt(tmp[2], 10); + } else if (tmp[1] <= lastPosition) { + // 1, 2, 3, ... - We've moved onto a new medium + releaseNumber++; + lastPosition = tmp[1]; + } else { + lastPosition = tmp[1]; + } } else { - if (trackPosition.match(/^[A-Z]\d*$/i)) { // Vinyl or cassette, handle it specially - // A,B -> 1; C,D -> 2; E,F -> 3, etc... - releaseNumber = ((32|trackPosition.charCodeAt(0))-97>>1)+1; - lastPosition++; - } else if (trackPosition.match(/^[A-Z]+\d*$/i)) { // Vinyl or cassette, handle it specially - // something like AA1, exemple : http://www.discogs.com/release/73531 - // TODO: find a better fix - buggyTrackNumber = true; - } + if (trackPosition.match(/^[A-Z]\d*$/i)) { + // Vinyl or cassette, handle it specially + // A,B -> 1; C,D -> 2; E,F -> 3, etc... + releaseNumber = (((32 | trackPosition.charCodeAt(0)) - 97) >> 1) + 1; + lastPosition++; + } else if (trackPosition.match(/^[A-Z]+\d*$/i)) { + // Vinyl or cassette, handle it specially + // something like AA1, exemple : http://www.discogs.com/release/73531 + // TODO: find a better fix + buggyTrackNumber = true; + } } if (releaseNumber > release_formats.length) { @@ -693,58 +704,60 @@ function parseDiscogsRelease(data) { releaseNumber = prevReleaseNumber; } if (buggyTrackNumber) { - // well, it went wrong so ... - lastPosition++; + // well, it went wrong so ... + lastPosition++; } } // Create release if needed - var discindex = releaseNumber-1; + let discindex = releaseNumber - 1; if (!release.discs[discindex]) { - var newdisc = { - tracks: [], - format: release_formats[discindex], + let newdisc = { + tracks: [], + format: release_formats[discindex] }; if (heading) { - newdisc.title = heading; - heading = ""; + newdisc.title = heading; + heading = ''; } release.discs.push(newdisc); } // Track number (only for Vinyl and Cassette) - if (buggyTrackNumber || (release.discs[discindex].format.match(/(Vinyl|Cassette)/) - && discogsTrack.position.match(/^[A-Z]+[\.-]?\d*/i))) { + if ( + buggyTrackNumber || + (release.discs[discindex].format.match(/(Vinyl|Cassette)/) && discogsTrack.position.match(/^[A-Z]+[\.-]?\d*/i)) + ) { track.number = discogsTrack.position; } // Trackposition is empty e.g. for release title - if (trackPosition != "" && trackPosition != null) { + if (trackPosition != '' && trackPosition != null) { release.discs[discindex].tracks.push(track); } if (buggyTrackNumber && !release.maybe_buggy) { - release.maybe_buggy = true; + release.maybe_buggy = true; } }); if (release.discs.length == 1 && release.discs[0].title) { - // remove title if there is only one disc - // https://github.com/murdos/musicbrainz-userscripts/issues/69 - release.discs[0].title = ''; + // remove title if there is only one disc + // https://github.com/murdos/musicbrainz-userscripts/issues/69 + release.discs[0].title = ''; } - LOGGER.info("Parsed release: ", release); + LOGGER.info('Parsed release: ', release); return release; } function decodeDiscogsJoinphrase(join) { - var joinphrase = ""; - var trimedjoin = join.replace(/^\s*/, "").replace(/\s*$/, ""); - if (trimedjoin == "") return trimedjoin; - if (trimedjoin != ",") joinphrase += " "; + let joinphrase = ''; + let trimedjoin = join.replace(/^\s*/, '').replace(/\s*$/, ''); + if (trimedjoin == '') return trimedjoin; + if (trimedjoin != ',') joinphrase += ' '; joinphrase += trimedjoin; - joinphrase += " "; + joinphrase += ' '; return joinphrase; } @@ -753,311 +766,310 @@ function decodeDiscogsJoinphrase(join) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// var MediaTypes = { - "8-Track Cartridge": "Cartridge", - "Acetate": "Vinyl", - "Betamax": "Betamax", - "Blu-ray": "Blu-ray", - "Blu-ray-R": "Blu-ray", - "Cassette": "Cassette", - "CD": "CD", - "CDr": "CD-R", - "CDV": "CDV", - "CD+G": "CD+G", - "Cylinder": "Wax Cylinder", - "DAT": "DAT", - "Datassette": "Other", - "DCC": "DCC", - "DVD": "DVD", - "DVDr": "DVD", - "DVD-Audio": "DVD-Audio", - "DVD-Video": "DVD-Video", - "Edison Disc": "Vinyl", - "File": "Digital Media", - "Flexi-disc": "Vinyl", - "Floppy Disk": "Other", - "HDCD": "HDCD", - "HD DVD": "HD-DVD", - "HD DVD-R": "HD-DVD", - "Hybrid": "Other", - "Laserdisc": "LaserDisc", - "Memory Stick": "Other", - "Microcassette": "Other", - "Minidisc": "MiniDisc", - "MVD": "Other", - "Reel-To-Reel": "Reel-to-reel", - "SACD": "SACD", - "SelectaVision": "Other", - "Shellac": "Shellac", + '8-Track Cartridge': 'Cartridge', + Acetate: 'Vinyl', + Betamax: 'Betamax', + 'Blu-ray': 'Blu-ray', + 'Blu-ray-R': 'Blu-ray', + Cassette: 'Cassette', + CD: 'CD', + CDr: 'CD-R', + CDV: 'CDV', + 'CD+G': 'CD+G', + Cylinder: 'Wax Cylinder', + DAT: 'DAT', + Datassette: 'Other', + DCC: 'DCC', + DVD: 'DVD', + DVDr: 'DVD', + 'DVD-Audio': 'DVD-Audio', + 'DVD-Video': 'DVD-Video', + 'Edison Disc': 'Vinyl', + File: 'Digital Media', + 'Flexi-disc': 'Vinyl', + 'Floppy Disk': 'Other', + HDCD: 'HDCD', + 'HD DVD': 'HD-DVD', + 'HD DVD-R': 'HD-DVD', + Hybrid: 'Other', + Laserdisc: 'LaserDisc', + 'Memory Stick': 'Other', + Microcassette: 'Other', + Minidisc: 'MiniDisc', + MVD: 'Other', + 'Reel-To-Reel': 'Reel-to-reel', + SACD: 'SACD', + SelectaVision: 'Other', + Shellac: 'Shellac', 'Shellac7"': '7" Shellac', 'Shellac10"': '10" Shellac', 'Shellac12"': '12" Shellac', - "SVCD": "SVCD", - "UMD": "UMD", - "VCD": "VCD", - "VHS": "VHS", - "Video 2000": "Other", - "Vinyl": "Vinyl", + SVCD: 'SVCD', + UMD: 'UMD', + VCD: 'VCD', + VHS: 'VHS', + 'Video 2000': 'Other', + Vinyl: 'Vinyl', 'Vinyl7"': '7" Vinyl', 'Vinyl10"': '10" Vinyl', 'Vinyl12"': '12" Vinyl' }; var Countries = { - "Afghanistan": "AF", - "Albania": "AL", - "Algeria": "DZ", - "American Samoa": "AS", - "Andorra": "AD", - "Angola": "AO", - "Anguilla": "AI", - "Antarctica": "AQ", - "Antigua and Barbuda": "AG", - "Argentina": "AR", - "Armenia": "AM", - "Aruba": "AW", - "Australia": "AU", - "Austria": "AT", - "Azerbaijan": "AZ", - "Bahamas": "BS", - "Bahrain": "BH", - "Bangladesh": "BD", - "Barbados": "BB", - "Belarus": "BY", - "Belgium": "BE", - "Belize": "BZ", - "Benin": "BJ", - "Bermuda": "BM", - "Bhutan": "BT", - "Bolivia": "BO", - "Croatia": "HR", - "Botswana": "BW", - "Bouvet Island": "BV", - "Brazil": "BR", - "British Indian Ocean Territory": "IO", - "Brunei Darussalam": "BN", - "Bulgaria": "BG", - "Burkina Faso": "BF", - "Burundi": "BI", - "Cambodia": "KH", - "Cameroon": "CM", - "Canada": "CA", - "Cape Verde": "CV", - "Cayman Islands": "KY", - "Central African Republic": "CF", - "Chad": "TD", - "Chile": "CL", - "China": "CN", - "Christmas Island": "CX", - "Cocos (Keeling) Islands": "CC", - "Colombia": "CO", - "Comoros": "KM", - "Congo": "CG", - "Cook Islands": "CK", - "Costa Rica": "CR", - "Virgin Islands, British": "VG", - "Cuba": "CU", - "Cyprus": "CY", - "Czech Republic": "CZ", - "Denmark": "DK", - "Djibouti": "DJ", - "Dominica": "DM", - "Dominican Republic": "DO", - "Ecuador": "EC", - "Egypt": "EG", - "El Salvador": "SV", - "Equatorial Guinea": "GQ", - "Eritrea": "ER", - "Estonia": "EE", - "Ethiopia": "ET", - "Falkland Islands (Malvinas)": "FK", - "Faroe Islands": "FO", - "Fiji": "FJ", - "Finland": "FI", - "France": "FR", - "French Guiana": "GF", - "French Polynesia": "PF", - "French Southern Territories": "TF", - "Gabon": "GA", - "Gambia": "GM", - "Georgia": "GE", - "Germany": "DE", - "Ghana": "GH", - "Gibraltar": "GI", - "Greece": "GR", - "Greenland": "GL", - "Grenada": "GD", - "Guadeloupe": "GP", - "Guam": "GU", - "Guatemala": "GT", - "Guinea": "GN", - "Guinea-Bissau": "GW", - "Guyana": "GY", - "Haiti": "HT", - "Virgin Islands, U.S.": "VI", - "Honduras": "HN", - "Hong Kong": "HK", - "Hungary": "HU", - "Iceland": "IS", - "India": "IN", - "Indonesia": "ID", - "Wallis and Futuna": "WF", - "Iraq": "IQ", - "Ireland": "IE", - "Israel": "IL", - "Italy": "IT", - "Jamaica": "JM", - "Japan": "JP", - "Jordan": "JO", - "Kazakhstan": "KZ", - "Kenya": "KE", - "Kiribati": "KI", - "Kuwait": "KW", - "Kyrgyzstan": "KG", - "Lao People's Democratic Republic": "LA", - "Latvia": "LV", - "Lebanon": "LB", - "Lesotho": "LS", - "Liberia": "LR", - "Libyan Arab Jamahiriya": "LY", - "Liechtenstein": "LI", - "Lithuania": "LT", - "Luxembourg": "LU", - "Montserrat": "MS", - "Macedonia": "MK", - "Madagascar": "MG", - "Malawi": "MW", - "Malaysia": "MY", - "Maldives": "MV", - "Mali": "ML", - "Malta": "MT", - "Marshall Islands": "MH", - "Martinique": "MQ", - "Mauritania": "MR", - "Mauritius": "MU", - "Mayotte": "YT", - "Mexico": "MX", - "Micronesia, Federated States of": "FM", - "Morocco": "MA", - "Monaco": "MC", - "Mongolia": "MN", - "Mozambique": "MZ", - "Myanmar": "MM", - "Namibia": "NA", - "Nauru": "NR", - "Nepal": "NP", - "Netherlands": "NL", - "Netherlands Antilles": "AN", - "New Caledonia": "NC", - "New Zealand": "NZ", - "Nicaragua": "NI", - "Niger": "NE", - "Nigeria": "NG", - "Niue": "NU", - "Norfolk Island": "NF", - "Northern Mariana Islands": "MP", - "Norway": "NO", - "Oman": "OM", - "Pakistan": "PK", - "Palau": "PW", - "Panama": "PA", - "Papua New Guinea": "PG", - "Paraguay": "PY", - "Peru": "PE", - "Philippines": "PH", - "Pitcairn": "PN", - "Poland": "PL", - "Portugal": "PT", - "Puerto Rico": "PR", - "Qatar": "QA", - "Reunion": "RE", - "Romania": "RO", - "Russian Federation": "RU", - "Russia": "RU", - "Rwanda": "RW", - "Saint Kitts and Nevis": "KN", - "Saint Lucia": "LC", - "Saint Vincent and The Grenadines": "VC", - "Samoa": "WS", - "San Marino": "SM", - "Sao Tome and Principe": "ST", - "Saudi Arabia": "SA", - "Senegal": "SN", - "Seychelles": "SC", - "Sierra Leone": "SL", - "Singapore": "SG", - "Slovenia": "SI", - "Solomon Islands": "SB", - "Somalia": "SO", - "South Africa": "ZA", - "Spain": "ES", - "Sri Lanka": "LK", - "Sudan": "SD", - "Suriname": "SR", - "Swaziland": "SZ", - "Sweden": "SE", - "Switzerland": "CH", - "Syrian Arab Republic": "SY", - "Tajikistan": "TJ", - "Tanzania, United Republic of": "TZ", - "Thailand": "TH", - "Togo": "TG", - "Tokelau": "TK", - "Tonga": "TO", - "Trinidad & Tobago": "TT", - "Tunisia": "TN", - "Turkey": "TR", - "Turkmenistan": "TM", - "Turks and Caicos Islands": "TC", - "Tuvalu": "TV", - "Uganda": "UG", - "Ukraine": "UA", - "United Arab Emirates": "AE", - "UK": "GB", - "US": "US", - "United States Minor Outlying Islands": "UM", - "Uruguay": "UY", - "Uzbekistan": "UZ", - "Vanuatu": "VU", - "Vatican City State (Holy See)": "VA", - "Venezuela": "VE", - "Viet Nam": "VN", - "Western Sahara": "EH", - "Yemen": "YE", - "Zambia": "ZM", - "Zimbabwe": "ZW", - "Taiwan": "TW", - "[Worldwide]": "XW", - "Europe": "XE", - "USSR": "SU", - "East Germany (historical, 1949-1990)": "XG", - "Czechoslovakia": "XC", - "Congo, Republic of the": "CD", - "Slovakia": "SK", - "Bosnia & Herzegovina": "BA", - "Korea (North), Democratic People's Republic of": "KP", - "North Korea": "KP", - "Korea (South), Republic of": "KR", - "South Korea": "KR", - "Montenegro": "ME", - "South Georgia and the South Sandwich Islands": "GS", - "Palestinian Territory": "PS", - "Macao": "MO", - "Timor-Leste": "TL", - "<85>land Islands": "AX", - "Guernsey": "GG", - "Isle of Man": "IM", - "Jersey": "JE", - "Serbia": "RS", - "Saint Barthélemy": "BL", - "Saint Martin": "MF", - "Moldova": "MD", - "Yugoslavia": "YU", - "Serbia and Montenegro": "CS", - "Côte d'Ivoire": "CI", - "Heard Island and McDonald Islands": "HM", - "Iran, Islamic Republic of": "IR", - "Saint Pierre and Miquelon": "PM", - "Saint Helena": "SH", - "Svalbard and Jan Mayen": "SJ" + Afghanistan: 'AF', + Albania: 'AL', + Algeria: 'DZ', + 'American Samoa': 'AS', + Andorra: 'AD', + Angola: 'AO', + Anguilla: 'AI', + Antarctica: 'AQ', + 'Antigua and Barbuda': 'AG', + Argentina: 'AR', + Armenia: 'AM', + Aruba: 'AW', + Australia: 'AU', + Austria: 'AT', + Azerbaijan: 'AZ', + Bahamas: 'BS', + Bahrain: 'BH', + Bangladesh: 'BD', + Barbados: 'BB', + Belarus: 'BY', + Belgium: 'BE', + Belize: 'BZ', + Benin: 'BJ', + Bermuda: 'BM', + Bhutan: 'BT', + Bolivia: 'BO', + Croatia: 'HR', + Botswana: 'BW', + 'Bouvet Island': 'BV', + Brazil: 'BR', + 'British Indian Ocean Territory': 'IO', + 'Brunei Darussalam': 'BN', + Bulgaria: 'BG', + 'Burkina Faso': 'BF', + Burundi: 'BI', + Cambodia: 'KH', + Cameroon: 'CM', + Canada: 'CA', + 'Cape Verde': 'CV', + 'Cayman Islands': 'KY', + 'Central African Republic': 'CF', + Chad: 'TD', + Chile: 'CL', + China: 'CN', + 'Christmas Island': 'CX', + 'Cocos (Keeling) Islands': 'CC', + Colombia: 'CO', + Comoros: 'KM', + Congo: 'CG', + 'Cook Islands': 'CK', + 'Costa Rica': 'CR', + 'Virgin Islands, British': 'VG', + Cuba: 'CU', + Cyprus: 'CY', + 'Czech Republic': 'CZ', + Denmark: 'DK', + Djibouti: 'DJ', + Dominica: 'DM', + 'Dominican Republic': 'DO', + Ecuador: 'EC', + Egypt: 'EG', + 'El Salvador': 'SV', + 'Equatorial Guinea': 'GQ', + Eritrea: 'ER', + Estonia: 'EE', + Ethiopia: 'ET', + 'Falkland Islands (Malvinas)': 'FK', + 'Faroe Islands': 'FO', + Fiji: 'FJ', + Finland: 'FI', + France: 'FR', + 'French Guiana': 'GF', + 'French Polynesia': 'PF', + 'French Southern Territories': 'TF', + Gabon: 'GA', + Gambia: 'GM', + Georgia: 'GE', + Germany: 'DE', + Ghana: 'GH', + Gibraltar: 'GI', + Greece: 'GR', + Greenland: 'GL', + Grenada: 'GD', + Guadeloupe: 'GP', + Guam: 'GU', + Guatemala: 'GT', + Guinea: 'GN', + 'Guinea-Bissau': 'GW', + Guyana: 'GY', + Haiti: 'HT', + 'Virgin Islands, U.S.': 'VI', + Honduras: 'HN', + 'Hong Kong': 'HK', + Hungary: 'HU', + Iceland: 'IS', + India: 'IN', + Indonesia: 'ID', + 'Wallis and Futuna': 'WF', + Iraq: 'IQ', + Ireland: 'IE', + Israel: 'IL', + Italy: 'IT', + Jamaica: 'JM', + Japan: 'JP', + Jordan: 'JO', + Kazakhstan: 'KZ', + Kenya: 'KE', + Kiribati: 'KI', + Kuwait: 'KW', + Kyrgyzstan: 'KG', + "Lao People's Democratic Republic": 'LA', + Latvia: 'LV', + Lebanon: 'LB', + Lesotho: 'LS', + Liberia: 'LR', + 'Libyan Arab Jamahiriya': 'LY', + Liechtenstein: 'LI', + Lithuania: 'LT', + Luxembourg: 'LU', + Montserrat: 'MS', + Macedonia: 'MK', + Madagascar: 'MG', + Malawi: 'MW', + Malaysia: 'MY', + Maldives: 'MV', + Mali: 'ML', + Malta: 'MT', + 'Marshall Islands': 'MH', + Martinique: 'MQ', + Mauritania: 'MR', + Mauritius: 'MU', + Mayotte: 'YT', + Mexico: 'MX', + 'Micronesia, Federated States of': 'FM', + Morocco: 'MA', + Monaco: 'MC', + Mongolia: 'MN', + Mozambique: 'MZ', + Myanmar: 'MM', + Namibia: 'NA', + Nauru: 'NR', + Nepal: 'NP', + Netherlands: 'NL', + 'Netherlands Antilles': 'AN', + 'New Caledonia': 'NC', + 'New Zealand': 'NZ', + Nicaragua: 'NI', + Niger: 'NE', + Nigeria: 'NG', + Niue: 'NU', + 'Norfolk Island': 'NF', + 'Northern Mariana Islands': 'MP', + Norway: 'NO', + Oman: 'OM', + Pakistan: 'PK', + Palau: 'PW', + Panama: 'PA', + 'Papua New Guinea': 'PG', + Paraguay: 'PY', + Peru: 'PE', + Philippines: 'PH', + Pitcairn: 'PN', + Poland: 'PL', + Portugal: 'PT', + 'Puerto Rico': 'PR', + Qatar: 'QA', + Reunion: 'RE', + Romania: 'RO', + 'Russian Federation': 'RU', + Russia: 'RU', + Rwanda: 'RW', + 'Saint Kitts and Nevis': 'KN', + 'Saint Lucia': 'LC', + 'Saint Vincent and The Grenadines': 'VC', + Samoa: 'WS', + 'San Marino': 'SM', + 'Sao Tome and Principe': 'ST', + 'Saudi Arabia': 'SA', + Senegal: 'SN', + Seychelles: 'SC', + 'Sierra Leone': 'SL', + Singapore: 'SG', + Slovenia: 'SI', + 'Solomon Islands': 'SB', + Somalia: 'SO', + 'South Africa': 'ZA', + Spain: 'ES', + 'Sri Lanka': 'LK', + Sudan: 'SD', + Suriname: 'SR', + Swaziland: 'SZ', + Sweden: 'SE', + Switzerland: 'CH', + 'Syrian Arab Republic': 'SY', + Tajikistan: 'TJ', + 'Tanzania, United Republic of': 'TZ', + Thailand: 'TH', + Togo: 'TG', + Tokelau: 'TK', + Tonga: 'TO', + 'Trinidad & Tobago': 'TT', + Tunisia: 'TN', + Turkey: 'TR', + Turkmenistan: 'TM', + 'Turks and Caicos Islands': 'TC', + Tuvalu: 'TV', + Uganda: 'UG', + Ukraine: 'UA', + 'United Arab Emirates': 'AE', + UK: 'GB', + US: 'US', + 'United States Minor Outlying Islands': 'UM', + Uruguay: 'UY', + Uzbekistan: 'UZ', + Vanuatu: 'VU', + 'Vatican City State (Holy See)': 'VA', + Venezuela: 'VE', + 'Viet Nam': 'VN', + 'Western Sahara': 'EH', + Yemen: 'YE', + Zambia: 'ZM', + Zimbabwe: 'ZW', + Taiwan: 'TW', + '[Worldwide]': 'XW', + Europe: 'XE', + USSR: 'SU', + 'East Germany (historical, 1949-1990)': 'XG', + Czechoslovakia: 'XC', + 'Congo, Republic of the': 'CD', + Slovakia: 'SK', + 'Bosnia & Herzegovina': 'BA', + "Korea (North), Democratic People's Republic of": 'KP', + 'North Korea': 'KP', + 'Korea (South), Republic of': 'KR', + 'South Korea': 'KR', + Montenegro: 'ME', + 'South Georgia and the South Sandwich Islands': 'GS', + 'Palestinian Territory': 'PS', + Macao: 'MO', + 'Timor-Leste': 'TL', + '<85>land Islands': 'AX', + Guernsey: 'GG', + 'Isle of Man': 'IM', + Jersey: 'JE', + Serbia: 'RS', + 'Saint Barthélemy': 'BL', + 'Saint Martin': 'MF', + Moldova: 'MD', + Yugoslavia: 'YU', + 'Serbia and Montenegro': 'CS', + "Côte d'Ivoire": 'CI', + 'Heard Island and McDonald Islands': 'HM', + 'Iran, Islamic Republic of': 'IR', + 'Saint Pierre and Miquelon': 'PM', + 'Saint Helena': 'SH', + 'Svalbard and Jan Mayen': 'SJ' }; - diff --git a/encyclopedisque_importer.user.js b/encyclopedisque_importer.user.js index 4b3933b..b852701 100644 --- a/encyclopedisque_importer.user.js +++ b/encyclopedisque_importer.user.js @@ -21,7 +21,7 @@ $(document).ready(function() { MBImportStyle(); if (window.location.href.match(/encyclopedisque\.fr\/disque\/(\d+)/)) { - var release = parseEncyclopedisquePage(); + let release = parseEncyclopedisquePage(); setupImportUI(release); } @@ -32,57 +32,64 @@ $(document).ready(function() { // Encyclopedisque functions /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - function setupImportUI(release) { - // Form parameters - var edit_note = MBImport.makeEditNote(window.location.href, 'Encyclopedisque'); - var parameters = MBImport.buildFormParameters(release, edit_note); + let edit_note = MBImport.makeEditNote(window.location.href, 'Encyclopedisque'); + let parameters = MBImport.buildFormParameters(release, edit_note); // Build form - var mbUI = $(MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release)).hide(); + let mbUI = $(MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release)).hide(); $('#recherchebox').append(mbUI); - $('form.musicbrainz_import button').css({width: '100%'}); + $('form.musicbrainz_import button').css({ width: '100%' }); mbUI.slideDown(); } function insertMBLinks() { - - var current_url = window.location.href; + let current_url = window.location.href; 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\//)) { - 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() { - var $link = $(this); - var external_url = window.location.origin + $link.attr('href'); - mblinks.searchAndDisplayMbLink(external_url, 'release', function (link) { $link.after(link).after('
    ') } ); - }); - - $('h2, div.main').find('a[href*="/artiste/"]').each(function() { - var $link = $(this); - var external_url = window.location.origin + $link.attr('href'); - mblinks.searchAndDisplayMbLink(external_url, 'artist', function (link) { $link.before(link); } ); - }); + $('div.v7P, div.v12P') + .find('a[href*="/disque/"]') + .each(function() { + let $link = $(this); + let external_url = window.location.origin + $link.attr('href'); + mblinks.searchAndDisplayMbLink(external_url, 'release', function(link) { + $link.after(link).after('
    '); + }); + }); + $('h2, div.main') + .find('a[href*="/artiste/"]') + .each(function() { + 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 function parseEncyclopedisquePage() { - 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 = new Array(); - var artist_name = infoHeader.querySelector("div.floatright:nth-of-type(1)").textContent.trim(); - release.artist_credit.push( { 'artist_name': artist_name } ); + let artist_name = infoHeader.querySelector('div.floatright:nth-of-type(1)').textContent.trim(); + release.artist_credit.push({ artist_name: artist_name }); // 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) release.status = 'official'; @@ -91,60 +98,83 @@ function parseEncyclopedisquePage() { release.language = 'fra'; release.script = 'Latn'; - var disc = {'position': 1, 'tracks': [] }; - release.discs = [ disc ]; + let disc = { position: 1, tracks: [] }; + release.discs = [disc]; // Release URL 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 - var releaseInfos = document.body.querySelectorAll("div.main tr"); - var lastVinylFace = ''; - var lastInfoType; - for (var i = 0; i < releaseInfos.length; i++) { - var infoType = releaseInfos[i].querySelector("td:nth-of-type(1)").textContent.trim(); + let releaseInfos = document.body.querySelectorAll('div.main tr'); + let lastVinylFace = ''; + let lastInfoType; + for (let i = 0; i < releaseInfos.length; i++) { + let infoType = releaseInfos[i].querySelector('td:nth-of-type(1)').textContent.trim(); // Release date - if (infoType == "Sortie :") { - 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*\(?([^\)]*)?\)?/; + if (infoType == 'Sortie :') { + var infoValue = releaseInfos[i].querySelector('td:nth-of-type(2)').textContent.trim(); + 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); month = m[1]; if (month != undefined) { - switch (month) - { - case "janvier": release.month = 1; break; - case "février": release.month = 2; break; - case "mars": release.month = 3; break; - case "avril": release.month = 4; 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; + switch (month) { + case 'janvier': + release.month = 1; + break; + case 'février': + release.month = 2; + break; + case 'mars': + release.month = 3; + break; + case 'avril': + release.month = 4; + 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.labels = []; - var labels = m[3]; + let labels = m[3]; if (labels != undefined) { - $.each(labels.split("/"), function(index, label) { - release.labels.push({ 'name': label.trim(), 'catno': m[4] }); + $.each(labels.split('/'), function(index, label) { + release.labels.push({ name: label.trim(), catno: m[4] }); }); } 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]/))) { // Tracks - var track = new Object(); + let track = new Object(); // First part of tracknumber (A, B, ...) - var tnum_part1 = ''; - if (m = infoType.match(/^Face ([A-Z])/)) { + let tnum_part1 = ''; + if ((m = infoType.match(/^Face ([A-Z])/))) { lastVinylFace = m[1]; tnum_part1 = m[1]; } else { @@ -152,43 +182,60 @@ function parseEncyclopedisquePage() { } // 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; } - 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, ...) - var tnum_part2 = ''; - if (m = infoType.match(/^Face [A-Z](\d+)/)) { + let tnum_part2 = ''; + if ((m = infoType.match(/^Face [A-Z](\d+)/))) { tnum_part2 = m[1]; - } else if (m = title.match(/^(\d+)\.\s+(.*)$/)) { + } else if ((m = title.match(/^(\d+)\.\s+(.*)$/))) { tnum_part2 = m[1]; title = m[2]; } // Track length - if (m = releaseInfos[i].querySelector("td:nth-of-type(2)").textContent.trim().match(/- (\d+)’(\d+)$/)) { - track.duration = m[1] + ':' + m[2]; + if ( + (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.title = title; disc.tracks.push(track); - } else if (infoType == "Format :") { + } else if (infoType == 'Format :') { // Format => medium format, release-group type, release status - var infoValue = releaseInfos[i].querySelector("td:nth-of-type(2)").textContent.trim(); - var values = infoValue.split(" / "); + var infoValue = releaseInfos[i].querySelector('td:nth-of-type(2)').textContent.trim(); + let values = infoValue.split(' / '); values.forEach(function(value) { - if (value.indexOf('45 tours') > -1) { disc.format = '7" Vinyl'; } - if (value.indexOf('33 tours') > -1) { disc.format = '12" Vinyl'; } - 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'; } + if (value.indexOf('45 tours') > -1) { + disc.format = '7" Vinyl'; + } + if (value.indexOf('33 tours') > -1) { + disc.format = '12" Vinyl'; + } + 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 - 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') { release.country = 'FR'; } else if (infoValue == 'Royaume-uni') { @@ -211,7 +258,7 @@ function parseEncyclopedisquePage() { release.no_barcode = '1'; } - LOGGER.info("Parsed release: ", release); + LOGGER.info('Parsed release: ', release); return release; } diff --git a/expand-collapse-release-groups.user.js b/expand-collapse-release-groups.user.js index e94ab76..6722c61 100644 --- a/expand-collapse-release-groups.user.js +++ b/expand-collapse-release-groups.user.js @@ -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']"); 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); } else { inject_release_button(releasesOrReleaseGroups[r].parentNode); @@ -49,23 +49,24 @@ for (var r = 0; r < releasesOrReleaseGroups.length; r++) { } function inject_release_group_button(parent) { - var mbid = parent.querySelector("a").href.match(MBID_REGEX), - table = document.createElement("table"); + let mbid = parent.querySelector('a').href.match(MBID_REGEX), + table = document.createElement('table'); - table.style.marginTop = "1em"; - table.style.marginLeft = "1em"; - table.style.paddingLeft = "1em"; + table.style.marginTop = '1em'; + table.style.marginLeft = '1em'; + table.style.paddingLeft = '1em'; - var button = create_button( - "/ws/2/release?release-group=" + mbid + "&limit=100&inc=media&fmt=json", + let button = create_button( + `/ws/2/release?release-group=${mbid}&limit=100&inc=media&fmt=json`, function(toggled) { - if (toggled) parent.appendChild(table); else parent.removeChild(table); + if (toggled) parent.appendChild(table); + else parent.removeChild(table); }, function(json) { parse_release_group(json, mbid, parent, table); }, function(status) { - table.innerHTML = 'Error loading release group (HTTP status ' + status + ')'; + table.innerHTML = `Error loading release group (HTTP status ${status})`; } ); @@ -73,23 +74,24 @@ function inject_release_group_button(parent) { } function inject_release_button(parent, _table_parent, _table, _mbid) { - var mbid = _mbid || parent.querySelector("a").href.match(MBID_REGEX), - table = _table || document.createElement("table"); + let mbid = _mbid || parent.querySelector('a').href.match(MBID_REGEX), + table = _table || document.createElement('table'); - table.style.marginTop = "1em"; - table.style.marginLeft = "1em"; - table.style.paddingLeft = "1em"; + table.style.marginTop = '1em'; + table.style.marginLeft = '1em'; + table.style.paddingLeft = '1em'; - var button = create_button( - "/ws/2/release/" + mbid + "?inc=media+recordings+artist-credits&fmt=json", + let button = create_button( + `/ws/2/release/${mbid}?inc=media+recordings+artist-credits&fmt=json`, function(toggled) { - if (toggled) parent.appendChild(table); else parent.removeChild(table); + if (toggled) parent.appendChild(table); + else parent.removeChild(table); }, function(json) { parse_release(json, table); }, function(status) { - table.innerHTML = 'Error loading release (HTTP status ' + status + ')'; + table.innerHTML = `Error loading release (HTTP status ${status})`; } ); @@ -97,76 +99,92 @@ function inject_release_button(parent, _table_parent, _table, _mbid) { } 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 = "▶"; - button.style.cursor = "pointer"; - button.style.marginRight = "4px"; - button.style.color = "#777"; + button.innerHTML = '▶'; + button.style.cursor = 'pointer'; + button.style.marginRight = '4px'; + button.style.color = '#777'; - button.addEventListener("mousedown", function() { - toggled = !toggled; - if (toggled) - button.innerHTML = "▼"; - else button.innerHTML = "▶"; - dom_callback(toggled); - }, false); + button.addEventListener( + 'mousedown', + function() { + toggled = !toggled; + if (toggled) button.innerHTML = '▼'; + else button.innerHTML = '▶'; + dom_callback(toggled); + }, + false + ); - button.addEventListener("mousedown", function() { - var this_event = arguments.callee; - button.removeEventListener("mousedown", this_event, false); - var req = new XMLHttpRequest(); + button.addEventListener( + 'mousedown', + function() { + let this_event = arguments.callee; + button.removeEventListener('mousedown', this_event, false); + let req = new XMLHttpRequest(); - req.onreadystatechange = function() { - if (req.readyState != 4) return; + req.onreadystatechange = function() { + if (req.readyState != 4) return; - if (req.status == 200 && req.responseText) { - success_callback(JSON.parse(req.responseText)); - } else { - button.addEventListener("mousedown", function() { - button.removeEventListener("mousedown", arguments.callee, false); - button.addEventListener("mousedown", this_event, false); - }, false); - error_callback(req.status); - } - }; + if (req.status == 200 && req.responseText) { + success_callback(JSON.parse(req.responseText)); + } else { + button.addEventListener( + 'mousedown', + function() { + button.removeEventListener('mousedown', arguments.callee, false); + button.addEventListener('mousedown', this_event, false); + }, + false + ); + error_callback(req.status); + } + }; - req.open("GET", url, true); - req.send(null); - - }, false); + req.open('GET', url, true); + req.send(null); + }, + false + ); return button; } function format_time(ms) { - var ts = ms / 1000, s = Math.round(ts % 60); - return (Math.floor(ts / 60) + ":" + (s >= 10 ? s : "0" + s)); + let ts = ms / 1000, + s = Math.round(ts % 60); + return `${Math.floor(ts / 60)}:${s >= 10 ? s : `0${s}`}`; } function parse_release_group(json, mbid, parent, table) { - var releases = json.releases; - table.innerHTML = ""; + let releases = json.releases; + table.innerHTML = ''; 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++) { - var medium = release.media[j], format = medium.format, count = medium["track-count"]; - if (format) - format in media ? (media[format] += 1) : (media[format] = 1); + for (let j = 0; j < release.media.length; j++) { + var medium = release.media[j], + format = medium.format, + count = medium['track-count']; + if (format) format in media ? (media[format] += 1) : (media[format] = 1); tracks.push(count); } for (format in media) { - var count = media[format], txt; - if (count > 1) - formats.push(count.toString() + "×" + format); + var count = media[format], + txt; + if (count > 1) formats.push(`${count.toString()}×${format}`); else formats.push(format); } - release.tracks = tracks.join(" + "); - release.formats = formats.join(" + "); + release.tracks = tracks.join(' + '); + release.formats = formats.join(' + '); } releases.sort(function(a, b) { @@ -175,82 +193,77 @@ function parse_release_group(json, mbid, parent, table) { return 0; }); - for (var i = 0; i < releases.length; i++) {(function(release) { - var track_tr = document.createElement("tr"), - track_td = document.createElement("td"), - track_table = document.createElement("table"), - format_td = document.createElement("td"), - tr = document.createElement("tr"), - td = document.createElement("td"), - a = createLink("/release/" + release.id, release.title); + for (var i = 0; i < releases.length; i++) { + (function(release) { + let track_tr = document.createElement('tr'), + track_td = document.createElement('td'), + track_table = document.createElement('table'), + format_td = document.createElement('td'), + tr = document.createElement('tr'), + td = document.createElement('td'), + a = createLink(`/release/${release.id}`, release.title); - track_td.colSpan = 6; - track_table.style.width = "100%"; - track_table.style.marginLeft = "1em"; - track_tr.appendChild(track_td); - inject_release_button(td, track_td, track_table, release.id); - td.appendChild(a); - if (release.disambiguation) { - td.appendChild(document.createTextNode(" (" + release.disambiguation + ")")); - } - tr.appendChild(td); - format_td.innerHTML = release.formats; - tr.appendChild(format_td); + track_td.colSpan = 6; + track_table.style.width = '100%'; + track_table.style.marginLeft = '1em'; + track_tr.appendChild(track_td); + inject_release_button(td, track_td, track_table, release.id); + td.appendChild(a); + if (release.disambiguation) { + td.appendChild(document.createTextNode(` (${release.disambiguation})`)); + } + tr.appendChild(td); + format_td.innerHTML = release.formats; + tr.appendChild(format_td); - var columns = [ - release.tracks, - release.date || "", - release.country || "", - release.status || "" - ]; + let columns = [release.tracks, release.date || '', release.country || '', release.status || '']; - for (var i = 0; i < columns.length; i++) - tr.appendChild(createElement("td", columns[i])); + for (let i = 0; i < columns.length; i++) tr.appendChild(createElement('td', columns[i])); - table.appendChild(tr); - table.appendChild(track_tr); + table.appendChild(tr); + table.appendChild(track_tr); + })(releases[i]); + } - })(releases[i]);} - - var bottom_tr = document.createElement("tr"), - bottom_td = document.createElement("td"); + let bottom_tr = document.createElement('tr'), + bottom_td = document.createElement('td'); 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(document.createTextNode(" | ")); - bottom_td.appendChild(createLink("/release/add?release-group=" + mbid, "add release")); - bottom_td.appendChild(document.createTextNode(" | ")); - bottom_td.appendChild(createLink("/release-group/" + mbid + "/edits", "editing history")); + bottom_td.appendChild(createLink(`/release-group/${mbid}/edit`, 'edit')); + bottom_td.appendChild(document.createTextNode(' | ')); + bottom_td.appendChild(createLink(`/release/add?release-group=${mbid}`, 'add release')); + bottom_td.appendChild(document.createTextNode(' | ')); + bottom_td.appendChild(createLink(`/release-group/${mbid}/edits`, 'editing history')); bottom_tr.appendChild(bottom_td); table.appendChild(bottom_tr); } function parse_release(json, table) { - var media = json.media; - table.innerHTML = ""; + let media = json.media; + table.innerHTML = ''; - for (var i = 0; i < media.length; i++) { - var medium = media[i], - format = medium.format ? medium.format + " " + (i + 1) : "Medium " + (i + 1); + for (let i = 0; i < media.length; i++) { + let medium = media[i], + format = medium.format ? `${medium.format} ${i + 1}` : `Medium ${i + 1}`; - table.innerHTML += '' + format + ""; + table.innerHTML += `${format}`; - for (var j = 0; j < medium.tracks.length; j++) { - var track = medium.tracks[j], recording = track.recording, - disambiguation = recording.disambiguation ? " (" + recording.disambiguation + ")" : "", - length = track.length ? format_time(track.length) : "?:??" - artist_credit = track["artist-credit"] || track.recording["artist-credit"], - tr = document.createElement("tr"); + for (let j = 0; j < medium.tracks.length; j++) { + let track = medium.tracks[j], + recording = track.recording, + disambiguation = recording.disambiguation ? ` (${recording.disambiguation})` : '', + length = track.length ? format_time(track.length) : '?:??'; + (artist_credit = track['artist-credit'] || track.recording['artist-credit']), (tr = document.createElement('tr')); - tr.appendChild(createElement("td", j + 1)); - var title_td = createElement("td", disambiguation); - title_td.insertBefore(createLink("/recording/" + recording.id, recording.title), title_td.firstChild); + tr.appendChild(createElement('td', j + 1)); + let title_td = createElement('td', disambiguation); + title_td.insertBefore(createLink(`/recording/${recording.id}`, recording.title), title_td.firstChild); tr.appendChild(title_td); - tr.appendChild(createElement("td", length)); - var ac_td = document.createElement("td"); + tr.appendChild(createElement('td', length)); + let ac_td = document.createElement('td'); ac_td.appendChild(createAC(artist_credit)); tr.appendChild(ac_td); @@ -258,46 +271,46 @@ function parse_release(json, table) { } } - var bottom_tr = document.createElement("tr"), - bottom_td = document.createElement("td"); + let bottom_tr = document.createElement('tr'), + bottom_td = document.createElement('td'); 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(document.createTextNode(" | ")); - bottom_td.appendChild(createLink("/release/" + json.id + "/edit-relationships", "edit relationships")); - bottom_td.appendChild(document.createTextNode(" | ")); - bottom_td.appendChild(createLink("/release/" + json.id + "/edits", "editing history")); + bottom_td.appendChild(createLink(`/release/${json.id}/edit`, 'edit')); + bottom_td.appendChild(document.createTextNode(' | ')); + bottom_td.appendChild(createLink(`/release/${json.id}/edit-relationships`, 'edit relationships')); + bottom_td.appendChild(document.createTextNode(' | ')); + bottom_td.appendChild(createLink(`/release/${json.id}/edits`, 'editing history')); bottom_tr.appendChild(bottom_td); table.appendChild(bottom_tr); } function createAC(obj) { - var span = document.createElement("span"); + let span = document.createElement('span'); - for (var i = 0; i < obj.length; i++) { - var credit = obj[i], artist = credit.artist, - link = createLink("/artist/" + artist.id, credit.name || artist.name); + for (let i = 0; i < obj.length; i++) { + let credit = obj[i], + 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); - if (credit.joinphrase) - span.appendChild(document.createTextNode(credit.joinphrase)); + if (credit.joinphrase) span.appendChild(document.createTextNode(credit.joinphrase)); } return span; } function createElement(name, text) { - var element = document.createElement(name); + let element = document.createElement(name); element.textContent = text; return element; } function createLink(href, text) { - var element = createElement("a", text); + let element = createElement('a', text); element.href = href; return element; } diff --git a/fast-cancel-edits.user.js b/fast-cancel-edits.user.js index 15ea2db..7fee8cd 100644 --- a/fast-cancel-edits.user.js +++ b/fast-cancel-edits.user.js @@ -62,66 +62,63 @@ //**************************************************************************// -var scr = document.createElement("script"); -scr.textContent = "(" + fastCancelScript + ")();"; +var scr = document.createElement('script'); +scr.textContent = `(${fastCancelScript})();`; document.body.appendChild(scr); function fastCancelScript() { - var totalCancels = 0; + let totalCancels = 0; - var $status = $("
    ") + let $status = $('
    ') .css({ - "position": "fixed", - "right": "0", - "bottom": "0", - "background": "#FFBA58", - "border-top": "1px #000 solid", - "border-left": "1px #000 solid", - "padding": "0.5em" + position: 'fixed', + right: '0', + bottom: '0', + background: '#FFBA58', + 'border-top': '1px #000 solid', + 'border-left': '1px #000 solid', + padding: '0.5em' }) - .appendTo("body") + .appendTo('body') .hide(); function updateStatus() { if (totalCancels === 0) { $status.hide(); } else { - $status.text("Canceling " + totalCancels + " edit" + - (totalCancels > 1 ? "s" : "") + "...").show(); + $status.text(`Canceling ${totalCancels} edit${totalCancels > 1 ? 's' : ''}...`).show(); } } - document.body.addEventListener("click", function (event) { - if (event.target && event.target.tagName && event.target.tagName == "A" && event.target.classList.contains("negative")) { + document.body.addEventListener('click', function(event) { + if (event.target && event.target.tagName && event.target.tagName == 'A' && event.target.classList.contains('negative')) { event.stopPropagation(); event.preventDefault(); totalCancels += 1; updateStatus(); - var $self = $(event.target), - $edit = $self.parents("div.edit-list:eq(0)"); + let $self = $(event.target), + $edit = $self.parents('div.edit-list:eq(0)'); - pushRequest(function () { - var editNote = $edit.find("div.add-edit-note textarea").val(); - var data = { "confirm.edit_note": editNote }; + pushRequest(function() { + let editNote = $edit.find('div.add-edit-note textarea').val(); + let data = { 'confirm.edit_note': editNote }; $.ajax({ - type: "POST", - url: $self.attr("href"), + type: 'POST', + url: $self.attr('href'), data: data, - error: function (request, status, error) { + error: function(request, status, error) { $self .css({ - "background": "red", - "color": "yellow", - "cursor": "help" + background: 'red', + color: 'yellow', + cursor: 'help' }) - .attr("title", "Error cancelling this edit: “" + error + "”"); - $edit - .css({border: "6px solid red"}) - .show(); + .attr('title', `Error cancelling this edit: “${error}”`); + $edit.css({ border: '6px solid red' }).show(); }, - complete: function () { + complete: function() { $edit.remove(); totalCancels -= 1; updateStatus(); @@ -132,15 +129,15 @@ function fastCancelScript() { } }); - $("div#edits > form[action$='/edit/enter_votes']").on("submit", function(event) { - if (totalCancels > 0) { - event.preventDefault(); - alert("Please wait, " + (totalCancels > 1 ? totalCancels + " edits are" : "an edit is") + " being cancelled in the background."); - } + $("div#edits > form[action$='/edit/enter_votes']").on('submit', function(event) { + if (totalCancels > 0) { + event.preventDefault(); + alert(`Please wait, ${totalCancels > 1 ? `${totalCancels} edits are` : 'an edit is'} being cancelled in the background.`); + } }); - var pushRequest = (function () { - var queue = [], + var pushRequest = (function() { + let queue = [], last = 0, active = false, rate = 2000; @@ -155,19 +152,19 @@ function fastCancelScript() { } } - return function (req) { + return function(req) { queue.push(req); if (!active) { active = true; - var now = new Date().getTime(); + let now = new Date().getTime(); if (now - last >= rate) { next(); } else { - var timeout = rate - now + last; + let timeout = rate - now + last; setTimeout(next, timeout); } } }; - }()); + })(); } diff --git a/fma_importer.user.js b/fma_importer.user.js index b93286e..a7f4779 100644 --- a/fma_importer.user.js +++ b/fma_importer.user.js @@ -25,27 +25,24 @@ * 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 this.$ = this.jQuery = jQuery.noConflict(true); // 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; var DEBUG = false; // true | false if (DEBUG) { - LOGGER.setLevel('debug'); + LOGGER.setLevel('debug'); } // promise to ensure all api calls are done before we parse the release var tracks_deferred = $.Deferred(); var retrieve_tracks_promise = tracks_deferred.promise(); - // object to store all global attributes collected for the release var release_attributes = {}; // albumid, total_pages, artist_name, label @@ -54,625 +51,608 @@ 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 $(document).ready(function() { + // if we have something on local storage place that + if (localStorage.getItem('FMA_API_KEY')) { + FMA_API = localStorage.getItem('FMA_API_KEY'); // -> YOURAPIKEY + } else { + insertAPIKEYSection(); + $('#api_key_submit').click(function() { + let myval = $('#apikey_input').val(); + localStorage.setItem('FMA_API_KEY', myval); + $('#musicbrainz_apikey').hide(); + FMA_API = localStorage.getItem('FMA_API_KEY'); // -> YOURAPIKEY + LOGGER.debug(`FMA API Key set: ${FMA_API}`); + location.reload(true); //as document loaded and FMA_API was set out of scope + }); + } - // if we have something on local storage place that - if (localStorage.getItem('FMA_API_KEY')) { - FMA_API = localStorage.getItem('FMA_API_KEY'); // -> YOURAPIKEY - } else { - insertAPIKEYSection(); - $("#api_key_submit").click(function() { - var myval = $("#apikey_input").val(); - localStorage.setItem('FMA_API_KEY', myval); - $("#musicbrainz_apikey").hide(); - FMA_API = localStorage.getItem('FMA_API_KEY'); // -> YOURAPIKEY - LOGGER.debug("FMA API Key set: " + FMA_API); - 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"); + let fmaPage = parseFMApage(); + let mblinks = new MBLinks('FMA_CACHE', 7 * 24 * 60); - var fmaPage = parseFMApage(); - var mblinks = new MBLinks('FMA_CACHE', 7 * 24 * 60); + if (DEBUG) { + insertAPISection(); + updateAPISection.AlbumId(release_attributes.albumid); + updateAPISection.ApiKey(FMA_API); + } - if (DEBUG) { - insertAPISection(); - updateAPISection.AlbumId(release_attributes.albumid); - updateAPISection.ApiKey(FMA_API); - } + if ($('.minitag-album').length && FMA_API !== 'FMA API KEY Missing') { + // 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 + let retrieve_track_info = new track_api_parameters(); + // Album detail + let retrieve_album_detail = new album_api(); - if ($(".minitag-album").length && FMA_API !== "FMA API KEY Missing") { // To make sure API and release only build on Album page. + // Track detail + $.when(retrieve_track_info) // ensure the track info is retrieved first (total_pages counter) + .then(function() { + // loop and deferred promise for multiple ajax calls + updateAPISection.TrackAjaxStatus('busy'); + let track_api_calls = []; + for (let i = 1; i <= release_attributes.total_pages; i++) { + track_api_calls.push(track_api(i)); + } + $.when.apply(this, track_api_calls).done(function() { + LOGGER.debug('Tracks loaded and done in DONE lets use it'); + //console.log("total_pages " + release_attributes.total_pages); + tracks_deferred.resolve(); + }); + }) + .done(function() { + LOGGER.debug('Deferred for: Track info > track detail > resolved'); + }); - // Track parameters: total number of pages / api calls limit hardcoded to max of 20 - var retrieve_track_info = new track_api_parameters(); - // Album detail - var retrieve_album_detail = new album_api(); + $.when(retrieve_tracks_promise) + .done(function() { + updateAPISection.TrackAjaxStatus('completed'); + }) + .fail(function() { + updateAPISection.TrackAjaxStatus('fail'); + }); - // Track detail - $.when(retrieve_track_info) // ensure the track info is retrieved first (total_pages counter) - .then(function() { // loop and deferred promise for multiple ajax calls - updateAPISection.TrackAjaxStatus('busy'); - var track_api_calls = []; - for (var i = 1; i <= release_attributes.total_pages; i++) { - track_api_calls.push(track_api(i)); - } + $.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.debug("ALBUM Object > " + album_api_array[0]); + // LOGGER.debug("TRACK Object > " + tracks_api_array); - $.when.apply(this, track_api_calls).done(function() { - LOGGER.debug("Tracks loaded and done in DONE lets use it"); - //console.log("total_pages " + release_attributes.total_pages); - tracks_deferred.resolve(); - - }); - }) - .done(function() { - LOGGER.debug("Deferred for: Track info > track detail > resolved"); - }); - - $.when(retrieve_tracks_promise) - .done(function() { - updateAPISection.TrackAjaxStatus('completed'); - }) - .fail(function() { - updateAPISection.TrackAjaxStatus('fail'); - }); - - $.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.debug("ALBUM Object > " + album_api_array[0]); - // LOGGER.debug("TRACK Object > " + tracks_api_array); - - var FreeMusicArchiveRelease = new Parsefmarelease(album_api_array[0], tracks_api_array); - insertMBSection(FreeMusicArchiveRelease); - - var album_link = window.location.href; - - var url = $(location).attr('href').split('/'); - var artist_url = url[url.length - 3]; - var base_url = 'http://freemusicarchive.org/music/'; - var artist_link = base_url + artist_url + '/'; - - mblinks.searchAndDisplayMbLink(album_link, 'release', function(link) { - $('.subh1').before(link); - }); - mblinks.searchAndDisplayMbLink(artist_link, 'artist', function(link) { - $('.subh1').after(link); - }); - - }); - } + let FreeMusicArchiveRelease = new Parsefmarelease(album_api_array[0], tracks_api_array); + insertMBSection(FreeMusicArchiveRelease); + let album_link = window.location.href; + let url = $(location) + .attr('href') + .split('/'); + 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) { + $('.subh1').before(link); + }); + mblinks.searchAndDisplayMbLink(artist_link, 'artist', function(link) { + $('.subh1').after(link); + }); + }); + } }); - - // Determine the location on page to add MusicBrainz Section function insertMbUI(mbUI) { - var e; - if ((e = $("#header")) && e.length) { - e.after(mbUI); - } else if ((e = $('#content')) && e.length) { - e.before(mbUI); - } else if ((e = $(".brumbs")) && e.length) { - e.append(mbUI); - } + let e; + if ((e = $('#header')) && e.length) { + e.after(mbUI); + } else if ((e = $('#content')) && e.length) { + e.before(mbUI); + } else if ((e = $('.brumbs')) && e.length) { + e.append(mbUI); + } } // Insert link to high resolution image on FMA page function insertIMGlinks() { - //LOGGER.debug("FMA insertIMGlinks Function Executing"); - var imgsrc = $('#image-1 img.sbar-fullimg').attr('src'); - imgsrc = imgsrc.substring(0, imgsrc.indexOf('?')); - //LOGGER.debug(" insertIMGlinks > imgsrc:", imgsrc); - $('#album-images').append('

    MB High Res Image

    '); + //LOGGER.debug("FMA insertIMGlinks Function Executing"); + let imgsrc = $('#image-1 img.sbar-fullimg').attr('src'); + imgsrc = imgsrc.substring(0, imgsrc.indexOf('?')); + //LOGGER.debug(" insertIMGlinks > imgsrc:", imgsrc); + $('#album-images').append(`

    MB High Res Image

    `); } // Insert FreeMusicArchive API Status section on FMA page function insertAPISection() { - //LOGGER.debug("FMA insertAPISection Function Executing"); + //LOGGER.debug("FMA insertAPISection Function Executing"); - var fmaUI = $('

    FMA API

    ').hide(); + let fmaUI = $('

    FMA API

    ').hide(); - if (DEBUG) fmaUI.css({ - 'border': '1px dotted red' - }); + if (DEBUG) + fmaUI.css({ + border: '1px dotted red' + }); + let fmaStatusBlock = $( + '» » Album info retrievedTrack info retrieved' + ); + fmaUI.append(fmaStatusBlock); - var fmaStatusBlock = $('» » Album info retrievedTrack info retrieved'); - fmaUI.append(fmaStatusBlock); + insertMbUI(fmaUI); // Insert the FMA API Status UI - insertMbUI(fmaUI); // Insert the FMA API Status UI + $('#fmaapistatus').css({ + display: 'inline-block', + float: 'left', + height: '120px', + width: '49%' + }); - $('#fmaapistatus').css({ - display: 'inline-block', - float: 'left', - height: '120px', - width: '49%' - }); - - - fmaUI.slideDown(); + fmaUI.slideDown(); } // Update FreeMusicArchive API Status section on FMA page var updateAPISection = { - AlbumId: function(albumid) { - this.albumid = albumid; - $('#lbut-lt-fma-api-album-id').text(this.albumid); - return 'complete'; - }, - ApiKey: function(apikey) { - this.apikey = apikey; - $('#lbut-lt-fma-api-key-id').text(FMA_API); - return 'complete'; - }, - AlbumAjaxStatus: function(ajaxstatus) { + AlbumId: function(albumid) { + this.albumid = albumid; + $('#lbut-lt-fma-api-album-id').text(this.albumid); + return 'complete'; + }, + ApiKey: function(apikey) { + this.apikey = apikey; + $('#lbut-lt-fma-api-key-id').text(FMA_API); + return 'complete'; + }, + AlbumAjaxStatus: function(ajaxstatus) { + if (ajaxstatus === null) { + this.ajaxstatus = 'notcalled'; + } else { + this.ajaxstatus = ajaxstatus; + } - if (ajaxstatus === null) { - this.ajaxstatus = "notcalled"; - } else { - this.ajaxstatus = ajaxstatus; - } + switch (this.ajaxstatus) { + 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 + $('#lbut-lt-fma-api-album').css({ + 'background-color': 'green' + }); + break; + 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 + $('#lbut-lt-fma-api-album').css({ + 'background-color': 'orange' + }); + break; + 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 + $('#lbut-lt-fma-api-album').css({ + 'background-color': 'red' + }); + break; + } + }, + TrackAjaxStatus: function(ajaxstatus) { + if (ajaxstatus === null) { + this.ajaxstatus = 'notcalled'; + } else { + this.ajaxstatus = ajaxstatus; + } - switch (this.ajaxstatus) { - 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 - $('#lbut-lt-fma-api-album').css({ - 'background-color': 'green' - }); - break; - 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 - $('#lbut-lt-fma-api-album').css({ - 'background-color': 'orange' - }); - break; - 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 - $('#lbut-lt-fma-api-album').css({ - 'background-color': 'red' - }); - break; - } - }, - TrackAjaxStatus: function(ajaxstatus) { - - if (ajaxstatus === null) { - this.ajaxstatus = "notcalled"; - } else { - this.ajaxstatus = ajaxstatus; - } - - switch (this.ajaxstatus) { - 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 - $('#lbut-lt-fma-api-tracks').css({ - 'background-color': 'green' - }); - break; - 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 - $('#lbut-lt-fma-api-tracks').css({ - 'background-color': 'orange' - }); - break; - 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 - $('#lbut-lt-fma-api-tracks').css({ - 'background-color': 'red' - }); - break; - } - } + switch (this.ajaxstatus) { + 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 + $('#lbut-lt-fma-api-tracks').css({ + 'background-color': 'green' + }); + break; + 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 + $('#lbut-lt-fma-api-tracks').css({ + 'background-color': 'orange' + }); + break; + 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 + $('#lbut-lt-fma-api-tracks').css({ + 'background-color': 'red' + }); + break; + } + } }; // Insert MusicBrainz section on FMA page function insertMBSection(release) { + //LOGGER.debug(release); - //LOGGER.debug(release); + let mbUI = $( + '

    MusicBrainz

    ' + ).hide(); + if (DEBUG) + mbUI.css({ + border: '1px dotted red' + }); - var mbUI = $('

    MusicBrainz

    ').hide(); - if (DEBUG) mbUI.css({ - 'border': '1px dotted red' - }); + let mbContentBlock = $('
    '); + mbUI.append(mbContentBlock); - var mbContentBlock = $('
    '); - mbUI.append(mbContentBlock); + if (release.maybe_buggy) { + let warning_buggy = $('

    Warning: this release is buggy, please check twice the data you import.Warning: this release is buggy, please check twice the data you import.${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}`; + mbContentBlock.append(innerHTML); - // Build form + search button - var innerHTML = '

    ' + MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release) + '
    '; - mbContentBlock.append(innerHTML); + insertMbUI(mbUI); // Insert the MusicBrainzUI + insertIMGlinks(); // Insert the link to high res image - insertMbUI(mbUI); // Insert the MusicBrainzUI - insertIMGlinks(); // Insert the link to high res image + $('#musicbrainz').css({ + display: 'block', + float: 'right', + height: '120px', + width: '49%' + }); + $('#mb_buttons').css({ + display: 'inline-block', + float: 'right', + height: '80px' + }); + $('form.musicbrainz_import').css({ + width: '49%', + display: 'inline-block' + }); + $('form.musicbrainz_import_search').css({ + float: 'right' + }); + $('form.musicbrainz_import > button').css({ + width: '63px', + height: '80px', + 'box-sizing': 'border-box' + }); - $('#musicbrainz').css({ - display: 'block', - float: 'right', - height: '120px', - width: '49%' - }); - - $('#mb_buttons').css({ - display: 'inline-block', - 'float': 'right', - height: '80px' - }); - $('form.musicbrainz_import').css({ - width: '49%', - display: 'inline-block' - }); - $('form.musicbrainz_import_search').css({ - 'float': 'right' - }); - $('form.musicbrainz_import > button').css({ - width: '63px', - height: '80px', - 'box-sizing': 'border-box' - }); - - mbUI.slideDown(); + mbUI.slideDown(); } - // Insert MusicBrainz API section on FMA page to enter API Key function insertAPIKEYSection() { - LOGGER.debug("FMA insertAPIKEYSection Function Executing"); + LOGGER.debug('FMA insertAPIKEYSection Function Executing'); + let mbUI = $( + '

    Import FMA API KEY for MusicBrainz

    ' + ).hide(); + if (DEBUG) + mbUI.css({ + border: '1px dotted red' + }); - var mbUI = $('

    Import FMA API KEY for MusicBrainz

    ').hide(); - if (DEBUG) mbUI.css({ - 'border': '1px dotted red' - }); + let mbContentBlock = $('
    '); + mbUI.append(mbContentBlock); - var mbContentBlock = $('
    '); - mbUI.append(mbContentBlock); + // Build section + let innerHTML = + 'Please enter API Key found '; + innerHTML = `${innerHTML}

    `; + mbContentBlock.append(innerHTML); + insertMbUI(mbUI); // Insert the MusicBrainzUI - // Build section - var innerHTML = 'Please enter API Key found '; - innerHTML = innerHTML + '

    '; - mbContentBlock.append(innerHTML); + $('#musicbrainz_apikey').css({ + display: 'block', + float: 'right', + height: '120px', + width: '49%' + }); - insertMbUI(mbUI); // Insert the MusicBrainzUI + $('#mb_buttons').css({ + display: 'inline-block', + float: 'right', + height: '80px' + }); - - - $('#musicbrainz_apikey').css({ - display: 'block', - float: 'right', - height: '120px', - width: '49%' - }); - - $('#mb_buttons').css({ - display: 'inline-block', - 'float': 'right', - height: '80px' - }); - - mbUI.slideDown(); + mbUI.slideDown(); } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Retrieve data from FMA API // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Retrieve Album JSON from API and push into array 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() { + updateAPISection.AlbumAjaxStatus('busy'); + LOGGER.debug(`promise_variable [state] in [getJSON] ${promise_variable.state()}`); + }).done(function(albumjson) { + LOGGER.debug(' >> Album > DONE'); + updateAPISection.AlbumAjaxStatus('completed'); + //LOGGER.debug(albumjson); + release_attributes.artist_name = albumjson.dataset[0].artist_name; + album_api_array.push(albumjson.dataset[0]); + }); - var promise_variable = $.getJSON(fmaWsUrl, function() { - updateAPISection.AlbumAjaxStatus('busy'); - LOGGER.debug("promise_variable [state] in [getJSON] " + promise_variable.state()); - }).done(function(albumjson) { - LOGGER.debug(" >> Album > DONE"); - updateAPISection.AlbumAjaxStatus('completed'); - //LOGGER.debug(albumjson); - release_attributes.artist_name = albumjson.dataset[0].artist_name; - album_api_array.push(albumjson.dataset[0]); - - }); - - return promise_variable.promise(); + return promise_variable.promise(); } // Retrieve Album JSON from API and assign values to release object 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() { + LOGGER.debug(`promise_track_api_params [state] in [getJSON] ${promise_track_api_params.state()}`); + }).done(function(trackinfojson) { + LOGGER.debug(' >> Track INFO > DONE'); + release_attributes.total_pages = trackinfojson.total_pages; + //LOGGER.debug(trackinfojson); + }); - var promise_track_api_params = $.getJSON(fmaWsUrl, function() { - LOGGER.debug("promise_track_api_params [state] in [getJSON] " + promise_track_api_params.state()); - }).done(function(trackinfojson) { - LOGGER.debug(" >> Track INFO > DONE"); - release_attributes.total_pages = trackinfojson.total_pages; - //LOGGER.debug(trackinfojson); - }); - - return promise_track_api_params.promise(); + return promise_track_api_params.promise(); } // Retrieve Track JSON from API and push into array, can handle page itteration function track_api(page) { + let fmaWsUrl = `https://freemusicarchive.org/api/get/tracks.json?api_key=${FMA_API}&album_id=${ + release_attributes.albumid + }&limit=20&page=${parseInt(page)}`; - var fmaWsUrl = 'https://freemusicarchive.org/api/get/tracks.json?api_key=' + FMA_API + '&album_id=' + release_attributes.albumid + '&limit=20&page=' + parseInt(page); + var promise_track_api = $.getJSON(fmaWsUrl, function() { + LOGGER.debug(`promise_track_api_params [state] in [getJSON] ${promise_track_api.state()}`); + }).done(function(tracksjson) { + LOGGER.debug(` >> Track page ${page} > DONE `); + LOGGER.debug(tracksjson); + tracks_api_array.push(tracksjson.dataset); + }); - - var promise_track_api = $.getJSON(fmaWsUrl, function() { - LOGGER.debug("promise_track_api_params [state] in [getJSON] " + promise_track_api.state()); - - }).done(function(tracksjson) { - LOGGER.debug(" >> Track page " + page + " > DONE "); - LOGGER.debug(tracksjson); - tracks_api_array.push(tracksjson.dataset); - }); - - return promise_track_api.promise(); + return promise_track_api.promise(); } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Parse information from FMA Page // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function parseFMApage() { - // Check to see if it is an album class is minitag-album div#content div.bcrumb h1 span.minitag-album - var FMAtype = ""; - // class inp-embed-code contain the album id - if ($(".minitag-album").length) { - FMAtype = "album"; - } else if ($(".minitag-song").length) { - FMAtype = "track"; - } else if ($(".minitag-artist").length) { - FMAtype = "artist"; - } + // Check to see if it is an album class is minitag-album div#content div.bcrumb h1 span.minitag-album + let FMAtype = ''; + // class inp-embed-code contain the album id + if ($('.minitag-album').length) { + FMAtype = 'album'; + } else if ($('.minitag-song').length) { + FMAtype = 'track'; + } else if ($('.minitag-artist').length) { + FMAtype = 'artist'; + } + if (FMAtype == 'album') { + //LOGGER.debug("FMA parseFMApage Function Executing on ", FMAtype); + let FMAEmbedCode = $('.inp-embed-code input').attr('value'); + FMAEmbedCodeRegex = /(\/embed\/album\/)(.+?(?=.xml))/; // regex to find the album id from the input object + let FMAAlbumIdMatch = FMAEmbedCode.match(FMAEmbedCodeRegex); // match the Id + release_attributes.albumid = FMAAlbumIdMatch[2].trim(); // assign the ID to a variable + LOGGER.info('FreeMusicArchive Album identified as: ', release_attributes.albumid); + } else { + LOGGER.error('No unique album identified on page', window.location.href); + release_attributes.albumid = ''; + } - if (FMAtype == "album") { - //LOGGER.debug("FMA parseFMApage Function Executing on ", FMAtype); - var FMAEmbedCode = $(".inp-embed-code input").attr("value"); - FMAEmbedCodeRegex = /(\/embed\/album\/)(.+?(?=.xml))/; // regex to find the album id from the input object - var FMAAlbumIdMatch = FMAEmbedCode.match(FMAEmbedCodeRegex); // match the Id - release_attributes.albumid = FMAAlbumIdMatch[2].trim(); // assign the ID to a variable - LOGGER.info("FreeMusicArchive Album identified as: ", release_attributes.albumid); - } else { - LOGGER.error("No unique album identified on page", window.location.href); - release_attributes.albumid = ""; - } - - // Label parsed from webpage as it is not in API - $("div.sbar-stat span.lf105.stathd").each(function() { - //var tester = $(this).eq(0).text().trim().toLowerCase(); // working - var taglist = $(this).eq(0).text().trim().toLowerCase(); - if (taglist == "label:") { - release_attributes.label = $(this).next().text(); - // fmarelease.labels.push({ - // name: FMAAlbumLabel - // }); - } else { - release_attributes.label = ""; - } - }); + // Label parsed from webpage as it is not in API + $('div.sbar-stat span.lf105.stathd').each(function() { + //var tester = $(this).eq(0).text().trim().toLowerCase(); // working + let taglist = $(this) + .eq(0) + .text() + .trim() + .toLowerCase(); + if (taglist == 'label:') { + release_attributes.label = $(this) + .next() + .text(); + // fmarelease.labels.push({ + // name: FMAAlbumLabel + // }); + } else { + release_attributes.label = ''; + } + }); } - //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Analyze FMA data and return a release object // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Parse the date string and set object properties day, month, year function parse_MM_DD_YYYY(date, obj) { - if (!date) return; - var m = date.split(/\D+/, 3).map(function(e) { - return parseInt(e, 10); - }); - if (m[0] !== undefined) { - obj.month = m[0]; - if (m[1] !== undefined) { - obj.day = m[1]; - if (m[2] !== undefined) { - obj.year = m[2]; - } - } - } + if (!date) return; + let m = date.split(/\D+/, 3).map(function(e) { + return parseInt(e, 10); + }); + if (m[0] !== undefined) { + obj.month = m[0]; + if (m[1] !== undefined) { + obj.day = m[1]; + if (m[2] !== undefined) { + obj.year = m[2]; + } + } + } } // parse the release from the album and track objects function Parsefmarelease(albumobject, trackobject) { - if (albumobject === undefined) { - albumobject = []; - } else { - albumobject = albumobject; - } + if (albumobject === undefined) { + albumobject = []; + } else { + albumobject = albumobject; + } - if (trackobject === undefined) { - trackobject = []; - } else { - trackobject = trackobject; - } + if (trackobject === undefined) { + trackobject = []; + } else { + trackobject = trackobject; + } - var fmarelease = {}; + let fmarelease = {}; - // Create an empty object required for MBImport - fmarelease.title = ""; - fmarelease.artist_credit = []; - fmarelease.type = ""; - fmarelease.status = ""; - fmarelease.language = ""; - fmarelease.script = ""; - fmarelease.packaging = ""; - fmarelease.country = ""; - fmarelease.year = ""; - fmarelease.month = ""; - fmarelease.day = ""; - fmarelease.labels = []; - fmarelease.barcode = ""; - fmarelease.urls = []; - fmarelease.discs = []; + // Create an empty object required for MBImport + fmarelease.title = ''; + fmarelease.artist_credit = []; + fmarelease.type = ''; + fmarelease.status = ''; + fmarelease.language = ''; + fmarelease.script = ''; + fmarelease.packaging = ''; + fmarelease.country = ''; + fmarelease.year = ''; + fmarelease.month = ''; + fmarelease.day = ''; + fmarelease.labels = []; + fmarelease.barcode = ''; + fmarelease.urls = []; + fmarelease.discs = []; - // LOGGER.debug("Album object for parsing", albumobject); - // LOGGER.debug("Track object for parsing", trackobject); + // LOGGER.debug("Album object for parsing", albumobject); + // LOGGER.debug("Track object for parsing", trackobject); - // Title - fmarelease.title = albumobject.album_title; - LOGGER.debug("Title: ", fmarelease.title); + // Title + fmarelease.title = albumobject.album_title; + LOGGER.debug('Title: ', fmarelease.title); - // Artist Credit - var VariousArtistsRegex = /(Various Artists)/; //found "Various Artists || Various Artists [album name]" - var various_artists = VariousArtistsRegex.test(albumobject.artist_name); + // Artist Credit + let VariousArtistsRegex = /(Various Artists)/; //found "Various Artists || Various Artists [album name]" + let various_artists = VariousArtistsRegex.test(albumobject.artist_name); - if (various_artists) { - fmarelease.artist_credit = [MBImport.specialArtist('various_artists')]; - } else { - fmarelease.artist_credit = MBImport.makeArtistCredits([albumobject.artist_name]); - } + if (various_artists) { + fmarelease.artist_credit = [MBImport.specialArtist('various_artists')]; + } else { + fmarelease.artist_credit = MBImport.makeArtistCredits([albumobject.artist_name]); + } - // Type - // TODO: match all FMA types to MB types - if (albumobject.album_type == "Radio Program") { - fmarelease.type = "broadcast"; - } else { - fmarelease.type = albumobject.album_type.toLowerCase(); - } - - // Default status is official - fmarelease.status = 'official'; + // Type + // TODO: match all FMA types to MB types + if (albumobject.album_type == 'Radio Program') { + fmarelease.type = 'broadcast'; + } else { + fmarelease.type = albumobject.album_type.toLowerCase(); + } - // Script - fmarelease.script = 'Latn'; + // Default status is official + fmarelease.status = 'official'; - // Check to see if a download button is available - if ($(".sqbtn-downloadalbum").length) { - fmarelease.packaging = 'none'; // Default packaging for download is none - // Release URL - fmarelease.urls.push({ - 'url': albumobject.album_url, - 'link_type': MBImport.URL_TYPES.download_for_free - }); - } else { - // Release URL - fmarelease.urls.push({ - 'url': albumobject.album_url, - 'link_type': MBImport.URL_TYPES.other_databases - }); - } - - // Check to see if a play button is available - if ($(".sqbtn-playpage").length) { - // Release URL - fmarelease.urls.push({ - 'url': albumobject.album_url, - 'link_type': MBImport.URL_TYPES.stream_for_free - }); - } + // Script + fmarelease.script = 'Latn'; - // Release date - if (albumobject.album_date_released) { - parse_MM_DD_YYYY(albumobject.album_date_released, fmarelease); - } + // Check to see if a download button is available + if ($('.sqbtn-downloadalbum').length) { + fmarelease.packaging = 'none'; // Default packaging for download is none + // Release URL + fmarelease.urls.push({ + url: albumobject.album_url, + link_type: MBImport.URL_TYPES.download_for_free + }); + } else { + // Release URL + fmarelease.urls.push({ + url: albumobject.album_url, + link_type: MBImport.URL_TYPES.other_databases + }); + } - // Label parsed from webpage as it is not in API - fmarelease.labels.push({ - name: release_attributes.label - }); + // Check to see if a play button is available + if ($('.sqbtn-playpage').length) { + // Release URL + fmarelease.urls.push({ + url: albumobject.album_url, + link_type: MBImport.URL_TYPES.stream_for_free + }); + } + // Release date + if (albumobject.album_date_released) { + parse_MM_DD_YYYY(albumobject.album_date_released, fmarelease); + } + // Label parsed from webpage as it is not in API + fmarelease.labels.push({ + name: release_attributes.label + }); - var discarray = []; - var trackarray = []; + let discarray = []; + let trackarray = []; + // release_attributes.total_pages + 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); - // release_attributes.total_pages - for (var track_page_in_array = 0; track_page_in_array < trackobject.length; track_page_in_array++) { + let 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(" ** Looping through array set for page " + track_page_in_array); + for (let tracknumber = 0; tracknumber < track_count_in_array_page; tracknumber++) { + //LOGGER.debug(" **** Track number in: trackobject[" + track_page_in_array + "][" + tracknumber + "] = " + tracknumber); + let track = {}; + track.disc_number = trackobject[track_page_in_array][tracknumber].track_disc_number; + track.number = trackobject[track_page_in_array][tracknumber].track_number; + track.title = trackobject[track_page_in_array][tracknumber].track_title; + track.duration = trackobject[track_page_in_array][tracknumber].track_duration; + track.artist_credit = MBImport.makeArtistCredits([trackobject[track_page_in_array][tracknumber].artist_name]); + trackarray.push(track); + } + } - 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); + // Could not find a example where disc_number != 1 yet but started teh check so long + let largest_disc = Math.max.apply( + Math, + trackarray.map(function(o) { + return o.disc_number; + }) + ); + //LOGGER.debug("Highest number disc:" + largest_disc); - for (var tracknumber = 0; tracknumber < track_count_in_array_page; tracknumber++) { - //LOGGER.debug(" **** Track number in: trackobject[" + track_page_in_array + "][" + tracknumber + "] = " + tracknumber); - var track = {}; - track.disc_number = trackobject[track_page_in_array][tracknumber].track_disc_number; - track.number = trackobject[track_page_in_array][tracknumber].track_number; - track.title = trackobject[track_page_in_array][tracknumber].track_title; - track.duration = trackobject[track_page_in_array][tracknumber].track_duration; - track.artist_credit = MBImport.makeArtistCredits([trackobject[track_page_in_array][tracknumber].artist_name]); + 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 + let tracklist_per_disc = $.map(trackarray, function(obj, index) { + if (obj.disc_number == disccount) { + return obj; + } + }); - trackarray.push(track); - } - } + // use this to sort the tracks per disc from low to high + tracklist_per_disc = tracklist_per_disc.sort(function(a, b) { + return parseInt(a.number) - parseInt(b.number); + }); + // remove the disc_number from the tracklist - not working + // tracklist_per_disc = tracklist_per_disc.filter(function( obj ) { + // return obj.field !== 'disc_number'; + // }); - // 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) { - return o.disc_number; - })); - //LOGGER.debug("Highest number disc:" + largest_disc); + // current solution to remove disc_number + for (i = tracklist_per_disc.length - 1; i >= 0; i--) { + delete tracklist_per_disc[i].disc_number; + } + //LOGGER.debug("Disc # " + disccount + " > " + JSON.stringify(tracklist_per_disc)); - for (var disccount = 1; disccount <= largest_disc; disccount++) { + let disc = { + position: disccount, + format: 'Digital Media', + tracks: tracklist_per_disc + }; + fmarelease.discs.push(disc); + } - // 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) { - if (obj.disc_number == disccount) { - return obj; - } - }); - - // use this to sort the tracks per disc from low to high - tracklist_per_disc = tracklist_per_disc.sort(function(a, b) { - return parseInt(a.number) - parseInt(b.number); - }); - - - // remove the disc_number from the tracklist - not working - // tracklist_per_disc = tracklist_per_disc.filter(function( obj ) { - // return obj.field !== 'disc_number'; - // }); - - // current solution to remove disc_number - for (i = tracklist_per_disc.length - 1; i >= 0; i--) { - delete tracklist_per_disc[i].disc_number; - } - - - //LOGGER.debug("Disc # " + disccount + " > " + JSON.stringify(tracklist_per_disc)); - - var disc = { - 'position': disccount, - 'format': 'Digital Media', - 'tracks': tracklist_per_disc - }; - fmarelease.discs.push(disc); - - } - - LOGGER.info("Release:", fmarelease); - return fmarelease; + LOGGER.info('Release:', fmarelease); + return fmarelease; } diff --git a/juno_download_importer.user.js b/juno_download_importer.user.js index e941640..22986a3 100644 --- a/juno_download_importer.user.js +++ b/juno_download_importer.user.js @@ -19,128 +19,144 @@ this.$ = this.jQuery = jQuery.noConflict(true); if (!unsafeWindow) unsafeWindow = window; -$(document).ready(function(){ - MBImportStyle(); - var release_url = window.location.href.replace('/\?.*$/', '').replace(/#.*$/, ''); - var release = retrieveReleaseInfo(release_url); - insertLink(release, release_url); +$(document).ready(function() { + MBImportStyle(); + let release_url = window.location.href.replace('/?.*$/', '').replace(/#.*$/, ''); + let release = retrieveReleaseInfo(release_url); + insertLink(release, release_url); }); function parseReleaseDate(rdate) { - var months = { - "January": 1, - "February": 2, - "March": 3, - "April": 4, - "May": 5, - "June": 6, - "July": 7, - "August": 8, - "September": 9, - "October": 10, - "November": 11, - "December": 12 - }; + let months = { + January: 1, + February: 2, + March: 3, + April: 4, + May: 5, + June: 6, + July: 7, + August: 8, + September: 9, + October: 10, + November: 11, + December: 12 + }; - var m = rdate.match(/(\d{1,2}) ([a-z]+), (\d{4})/i); - if (m) { - return { - year: m[3], - month: months[m[2]], - day: m[1] + let m = rdate.match(/(\d{1,2}) ([a-z]+), (\d{4})/i); + if (m) { + return { + year: m[3], + month: months[m[2]], + day: m[1] + }; } - } - return false; + return false; } function retrieveReleaseInfo(release_url) { + // Release defaults + let release = { + artist_credit: [], + title: $('#product_heading_title') + .text() + .trim(), + year: 0, + month: 0, + day: 0, + format: 'Digital Media', + packaging: 'None', + country: 'XW', + status: 'official', + language: 'eng', + script: 'Latn', + type: '', + urls: [], + labels: [], + discs: [] + }; - // Release defaults - var release = { - artist_credit: [], - title: $("#product_heading_title").text().trim(), - year: 0, - month: 0, - day: 0, - format: 'Digital Media', - packaging: 'None', - country: 'XW', - status: 'official', - language: 'eng', - script: 'Latn', - type: '', - urls: [], - labels: [], - discs: [], - }; - - // Release date - var parsed_releaseDate = parseReleaseDate($("#product_info_released_on").text().trim()); - if (parsed_releaseDate) { - release.year = parsed_releaseDate.year; - release.month = parsed_releaseDate.month; - release.day = parsed_releaseDate.day; - } - - // URLs - release.urls.push({ - 'url': release_url, - 'link_type': MBImport.URL_TYPES.purchase_for_download - }); - - release.labels.push( - { - name: $("#product_heading_label").text().trim(), - catno: $("#product_info_cat_no").text().trim() + // Release date + let parsed_releaseDate = parseReleaseDate( + $('#product_info_released_on') + .text() + .trim() + ); + if (parsed_releaseDate) { + release.year = parsed_releaseDate.year; + release.month = parsed_releaseDate.month; + release.day = parsed_releaseDate.day; } - ); - // Tracks - var tracks = []; - $(".product_tracklist_records[itemprop='tracks']").each(function() { - var artists = []; - var trackno = $(this).find(".product_tracklist_heading_records_sn").text().trim() - 1; - var trackname = $(this).find(".product_tracklist_heading_records_title").text().trim(); - var tracklength = $(this).find(".product_tracklist_heading_records_length").text().trim(); - var m = trackname.match(/^([^-]+) - (.*)$/); - if (m) { - artists = [m[1]]; - trackname = m[2]; + // URLs + release.urls.push({ + url: release_url, + link_type: MBImport.URL_TYPES.purchase_for_download + }); + + release.labels.push({ + name: $('#product_heading_label') + .text() + .trim(), + catno: $('#product_info_cat_no') + .text() + .trim() + }); + + // Tracks + let tracks = []; + $(".product_tracklist_records[itemprop='tracks']").each(function() { + let artists = []; + let trackno = + $(this) + .find('.product_tracklist_heading_records_sn') + .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) { + artists = [m[1]]; + trackname = m[2]; + } + tracks.push({ + artist_credit: MBImport.makeArtistCredits(artists), + title: trackname, + duration: tracklength + }); + }); + + let parsed_release_artist = $('#product_heading_artist') + .text() + .trim(); + if (parsed_release_artist == 'VARIOUS') { + release.artist_credit = [MBImport.specialArtist('various_artists')]; + } else { + release.artist_credit = MBImport.makeArtistCredits([parsed_release_artist]); } - tracks.push({ - 'artist_credit': MBImport.makeArtistCredits(artists), - 'title': trackname, - 'duration': tracklength - }); - }); + release.discs.push({ + tracks: tracks, + format: release.format + }); - var parsed_release_artist = $("#product_heading_artist").text().trim(); - if (parsed_release_artist == 'VARIOUS') { - release.artist_credit = [ MBImport.specialArtist('various_artists') ]; - } else { - release.artist_credit = MBImport.makeArtistCredits([ parsed_release_artist ]); - } - release.discs.push( { - 'tracks': tracks, - 'format': release.format - } ); - - LOGGER.info("Parsed release: ", release); - return release; + LOGGER.info('Parsed release: ', release); + return release; } // Insert button into page under label information function insertLink(release, release_url) { - var edit_note = MBImport.makeEditNote(release_url, 'Juno Download'); - var parameters = MBImport.buildFormParameters(release, edit_note); + let edit_note = MBImport.makeEditNote(release_url, 'Juno Download'); + let parameters = MBImport.buildFormParameters(release, edit_note); - var mbUI = $('
    ' - + MBImport.buildFormHTML(parameters) - + MBImport.buildSearchButton(release) - + '
    ').hide(); + let mbUI = $(`
    ${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}
    `).hide(); - $("div.sociald").before(mbUI); - $('#mb_buttons').css({'background': '#759d44', 'border': '2px solid #ddd', 'text-align': 'center'}); - $('form.musicbrainz_import button').css({width: '80%'}); + $('div.sociald').before(mbUI); + $('#mb_buttons').css({ background: '#759d44', border: '2px solid #ddd', 'text-align': 'center' }); + $('form.musicbrainz_import button').css({ width: '80%' }); mbUI.slideDown(); } diff --git a/lastfm_importer.user.js b/lastfm_importer.user.js index d66d2ae..bea9fe0 100644 --- a/lastfm_importer.user.js +++ b/lastfm_importer.user.js @@ -18,111 +18,125 @@ this.$ = this.jQuery = jQuery.noConflict(true); if (!unsafeWindow) unsafeWindow = window; -$(document).ready(function(){ - MBImportStyle(); - var 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/"); +$(document).ready(function() { + MBImportStyle(); + 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/' + ); - var release = retrieveReleaseInfo(release_url); - insertLink(release, release_url); + let release = retrieveReleaseInfo(release_url); + insertLink(release, release_url); }); - function retrieveReleaseInfo(release_url) { - - - // Release defaults - var release = { - artist_credit: '', - title: $("h1[itemprop='name']").text().trim(), - year: 0, - month: 0, - day: 0, - format: '', - packaging: '', - country: '', - status: 'official', - language: 'eng', - script: 'Latn', - type: '', - urls: [], - labels: [], - discs: [], - }; - - // Release artist - var artist = $("article span[itemprop='byArtist'] meta[itemprop='name']").attr('content').trim(); - var various_artists = (artist == 'Various Artists'); - if (various_artists) { - release.artist_credit = [ MBImport.specialArtist('various_artists') ]; - } else { - release.artist_credit = MBImport.makeArtistCredits([artist]); - } - - // Tracks - var tracks = []; - $("#albumTracklist tr[itemprop='tracks']").each(function() { - var artists = []; - var trackno = parseInt($(this).find("td.positionCell").text(), 10); - if (trackno == 1 && tracks.length) { - // multiple "discs" - release.discs.push( { - 'tracks': tracks, - 'format': release.format - } ); - tracks = []; - } - var trackname = $(this).find("td.subjectCell span[itemprop='name']").text().trim(); - var tracklength = $(this).find("td.durationCell").text().trim(); - - // VA releases have an additional link to the lastfm artist page - var track_artists = []; - $(this).find("td.subjectCell > a:not(:last)").each( - function () { - track_artists.push($(this).text().trim()); - } - ); - var ac = { - 'artist_credit': '', - 'title': trackname, - 'duration': tracklength + // Release defaults + let release = { + artist_credit: '', + title: $("h1[itemprop='name']") + .text() + .trim(), + year: 0, + month: 0, + day: 0, + format: '', + packaging: '', + country: '', + status: 'official', + language: 'eng', + script: 'Latn', + type: '', + urls: [], + labels: [], + discs: [] }; - if (!track_artists.length && various_artists) { - ac.artist_credit = [ MBImport.specialArtist('unknown') ]; + + // Release artist + let artist = $("article span[itemprop='byArtist'] meta[itemprop='name']") + .attr('content') + .trim(); + let various_artists = artist == 'Various Artists'; + if (various_artists) { + release.artist_credit = [MBImport.specialArtist('various_artists')]; } else { - ac.artist_credit = MBImport.makeArtistCredits(track_artists); + release.artist_credit = MBImport.makeArtistCredits([artist]); } - tracks.push(ac); - }); - release.discs.push( { - 'tracks': tracks, - 'format': release.format - } ); + // Tracks + let tracks = []; + $("#albumTracklist tr[itemprop='tracks']").each(function() { + let artists = []; + let trackno = parseInt( + $(this) + .find('td.positionCell') + .text(), + 10 + ); + if (trackno == 1 && tracks.length) { + // multiple "discs" + release.discs.push({ + tracks: tracks, + format: release.format + }); + tracks = []; + } + let trackname = $(this) + .find("td.subjectCell span[itemprop='name']") + .text() + .trim(); + let tracklength = $(this) + .find('td.durationCell') + .text() + .trim(); - LOGGER.info("Parsed release: ", release); - return release; + // VA releases have an additional link to the lastfm artist page + let track_artists = []; + $(this) + .find('td.subjectCell > a:not(:last)') + .each(function() { + track_artists.push( + $(this) + .text() + .trim() + ); + }); + let ac = { + artist_credit: '', + title: trackname, + duration: tracklength + }; + if (!track_artists.length && various_artists) { + ac.artist_credit = [MBImport.specialArtist('unknown')]; + } else { + ac.artist_credit = MBImport.makeArtistCredits(track_artists); + } + tracks.push(ac); + }); + + release.discs.push({ + tracks: tracks, + format: release.format + }); + + LOGGER.info('Parsed release: ', release); + return release; } // Insert button into page under label information function insertLink(release, release_url) { - var edit_note = MBImport.makeEditNote(release_url, 'Last.fm'); - var parameters = MBImport.buildFormParameters(release, edit_note); + let edit_note = MBImport.makeEditNote(release_url, 'Last.fm'); + let parameters = MBImport.buildFormParameters(release, edit_note); - $("div.g4").prepend( - $('
    ' - + MBImport.buildFormHTML(parameters) - + MBImport.buildSearchButton(release) - + '
    ').hide() - ); + $('div.g4').prepend($(`
    ${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}
    `).hide()); $('#mb_buttons').css({ - 'margin-bottom': '5px', - 'padding': '2%', - 'background-color': '#444' + 'margin-bottom': '5px', + padding: '2%', + 'background-color': '#444' }); - $('form.musicbrainz_import').css({width: '48%', display:'inline-block'}); - $('form.musicbrainz_import_search').css({'float': 'right'}) - $('form.musicbrainz_import > button').css({width: '100%', 'box-sizing': 'border-box'}); + $('form.musicbrainz_import').css({ width: '48%', display: 'inline-block' }); + $('form.musicbrainz_import_search').css({ float: 'right' }); + $('form.musicbrainz_import > button').css({ width: '100%', 'box-sizing': 'border-box' }); $('#mb_buttons').slideDown(); } diff --git a/lib/logger.js b/lib/logger.js index 80a79dd..f911374 100644 --- a/lib/logger.js +++ b/lib/logger.js @@ -3,23 +3,22 @@ /////////////////////////////////////////////////////////////////////////////////////////////////////////////////// var LOGGER = (function() { - - var LOG_LEVEL = 'info'; + let LOG_LEVEL = 'info'; function fnDebug() { if (LOG_LEVEL == 'debug') { - _log("DEBUG", arguments); + _log('DEBUG', arguments); } } function fnInfo() { if (LOG_LEVEL == 'debug' || LOG_LEVEL === 'info') { - _log("INFO", arguments); + _log('INFO', arguments); } } function fnError() { - _log("ERROR", arguments); + _log('ERROR', arguments); } function fnSetLevel(level) { @@ -31,16 +30,16 @@ var LOGGER = (function() { function _log(level, args) { // Prepends log level to things that will be logged args = Array.prototype.slice.call(args); - args.unshift('['+level+']'); + args.unshift(`[${level}]`); // Determine if there's a logger (console.log) available - var win = unsafeWindow || window; - var console = win.console; + let win = unsafeWindow || window; + let console = win.console; if (console && console.log && console.log.apply) { try { console.log.apply(this, args); - } catch(e) {} + } catch (e) {} } - }; + } // ---------------------------------- expose publics here ------------------------------------ // @@ -50,4 +49,4 @@ var LOGGER = (function() { error: fnError, setLevel: fnSetLevel }; -})(); \ No newline at end of file +})(); diff --git a/lib/mbimport.js b/lib/mbimport.js index cff24b6..ec06227 100644 --- a/lib/mbimport.js +++ b/lib/mbimport.js @@ -58,62 +58,63 @@ */ var MBImport = (function() { - // --------------------------------------- publics ----------------------------------------- // - var special_artists = { - various_artists: { - name: 'Various Artists', - mbid: '89ad4ac3-39f7-470e-963a-56509c546377' - }, - unknown: { - name: '[unknown]', - mbid: '125ec42a-7229-4250-afc5-e057484327fe' - } + let special_artists = { + various_artists: { + name: 'Various Artists', + mbid: '89ad4ac3-39f7-470e-963a-56509c546377' + }, + unknown: { + name: '[unknown]', + mbid: '125ec42a-7229-4250-afc5-e057484327fe' + } }; - var url_types = { - purchase_for_download: 74, - download_for_free: 75, - discogs: 76, - purchase_for_mail_order: 79, - other_databases: 82, - stream_for_free: 85, - license: 301 - } + let url_types = { + purchase_for_download: 74, + download_for_free: 75, + discogs: 76, + purchase_for_mail_order: 79, + other_databases: 82, + stream_for_free: 85, + license: 301 + }; function fnSpecialArtist(key, ac) { - var credited_name = ""; - var joinphrase = ""; - if (typeof ac !== 'undefined') { - joinphrase = ac.joinphrase; - } - return { - 'artist_name': special_artists[key].name, - 'credited_name': credited_name, - 'joinphrase': joinphrase, - 'mbid': special_artists[key].mbid - }; + let credited_name = ''; + let joinphrase = ''; + if (typeof ac !== 'undefined') { + joinphrase = ac.joinphrase; + } + return { + artist_name: special_artists[key].name, + credited_name: credited_name, + joinphrase: joinphrase, + mbid: special_artists[key].mbid + }; } // compute HTML of search link function fnBuildSearchLink(release) { - var parameters = searchParams(release); - var url_params = []; + let parameters = searchParams(release); + let url_params = []; parameters.forEach(function(parameter) { - var value = parameter.value + ""; - url_params.push(encodeURI(parameter.name + '=' + value)); + let value = `${parameter.value}`; + url_params.push(encodeURI(`${parameter.name}=${value}`)); }); - return 'Search in MusicBrainz'; + return `Search in MusicBrainz`; } // compute HTML of search button function fnBuildSearchButton(release) { - var parameters = searchParams(release); - var html = ''; @@ -121,27 +122,25 @@ var MBImport = (function() { } function fnSearchUrlFor(type, what) { - type = type.replace('-', '_'); + type = type.replace('-', '_'); - var params = [ - 'query=' + luceneEscape(what), - 'type=' + type, - 'indexed=1' - ]; - return '//musicbrainz.org/search?' + params.join('&'); + let params = [`query=${luceneEscape(what)}`, `type=${type}`, 'indexed=1']; + return `//musicbrainz.org/search?${params.join('&')}`; } // compute HTML of import form function fnBuildFormHTML(parameters) { - // Build form - var innerHTML = '
    '; + let innerHTML = ``; parameters.forEach(function(parameter) { - var value = parameter.value + ""; - innerHTML += ""; + let value = `${parameter.value}`; + innerHTML += ``; }); - innerHTML += ''; + innerHTML += + ''; innerHTML += '
    '; return innerHTML; @@ -150,14 +149,14 @@ var MBImport = (function() { // build form POST parameters that MB is waiting function fnBuildFormParameters(release, edit_note) { // Form parameters - var parameters = new Array(); + let parameters = new Array(); appendParameter(parameters, 'name', release.title); // Release Artist credits - buildArtistCreditsFormParameters(parameters, "", release.artist_credit); + buildArtistCreditsFormParameters(parameters, '', release.artist_credit); - if (release["secondary_types"]) { - for (var i=0; i < release.secondary_types.length; i++) { + if (release['secondary_types']) { + for (var i = 0; i < release.secondary_types.length; i++) { appendParameter(parameters, 'type', release.secondary_types[i]); } } @@ -171,61 +170,67 @@ var MBImport = (function() { // Date + country appendParameter(parameters, 'country', release.country); - if (!isNaN(release.year) && release.year != 0) { appendParameter(parameters, 'date.year', release.year); }; - 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); }; + if (!isNaN(release.year) && release.year != 0) { + appendParameter(parameters, 'date.year', release.year); + } + 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 appendParameter(parameters, 'barcode', release.barcode); // Label + catnos - for (var i=0; i < release.labels.length; i++) { - var label = release.labels[i]; - appendParameter(parameters, 'labels.'+i+'.name', label.name); - appendParameter(parameters, 'labels.'+i+'.mbid', label.mbid); - if (label.catno != "none") { - appendParameter(parameters, 'labels.'+i+'.catalog_number', label.catno); + for (var i = 0; i < release.labels.length; i++) { + let label = release.labels[i]; + appendParameter(parameters, `labels.${i}.name`, label.name); + appendParameter(parameters, `labels.${i}.mbid`, label.mbid); + if (label.catno != 'none') { + appendParameter(parameters, `labels.${i}.catalog_number`, label.catno); } } // URLs - for (var i=0; i < release.urls.length; i++) { - var url = release.urls[i]; - appendParameter(parameters, 'urls.'+i+'.url', url.url); - appendParameter(parameters, 'urls.'+i+'.link_type', url.link_type); + for (var i = 0; i < release.urls.length; i++) { + let url = release.urls[i]; + appendParameter(parameters, `urls.${i}.url`, url.url); + appendParameter(parameters, `urls.${i}.link_type`, url.link_type); } // Mediums - var total_tracks = 0; - var total_tracks_with_duration = 0; - var total_duration = 0; - for (var i=0; i < release.discs.length; i++) { - var disc = release.discs[i]; - appendParameter(parameters, 'mediums.'+i+'.format', disc.format); - appendParameter(parameters, 'mediums.'+i+'.name', disc.title); + let total_tracks = 0; + let total_tracks_with_duration = 0; + let total_duration = 0; + for (var i = 0; i < release.discs.length; i++) { + let disc = release.discs[i]; + appendParameter(parameters, `mediums.${i}.format`, disc.format); + appendParameter(parameters, `mediums.${i}.name`, disc.title); // Tracks - for (var j=0; j < disc.tracks.length; j++) { - var track = disc.tracks[j]; + for (let j = 0; j < disc.tracks.length; j++) { + let track = disc.tracks[j]; total_tracks++; - appendParameter(parameters, 'mediums.'+i+'.track.'+j+'.number', track.number); - appendParameter(parameters, 'mediums.'+i+'.track.'+j+'.name', track.title); - var tracklength = "?:??"; - var duration_ms = hmsToMilliSeconds(track.duration); + appendParameter(parameters, `mediums.${i}.track.${j}.number`, track.number); + appendParameter(parameters, `mediums.${i}.track.${j}.name`, track.title); + let tracklength = '?:??'; + let duration_ms = hmsToMilliSeconds(track.duration); if (!isNaN(duration_ms)) { - tracklength = duration_ms; - total_tracks_with_duration++; - total_duration += duration_ms; + tracklength = duration_ms; + total_tracks_with_duration++; + 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); } } // Guess release type if not given if (!release.type && release.title && total_tracks == total_tracks_with_duration) { - release.type = fnGuessReleaseType(release.title, total_tracks, total_duration); + release.type = fnGuessReleaseType(release.title, total_tracks, total_duration); } appendParameter(parameters, 'type', release.type); @@ -237,154 +242,156 @@ var MBImport = (function() { // Convert a list of artists to a list of artist credits with joinphrases function fnArtistCredits(artists_list) { - var artists = artists_list.map(function(item) { return {artist_name: item}; }); - if (artists.length > 2) { - var last = artists.pop(); - last.joinphrase = ''; - var prev = artists.pop(); - prev.joinphrase = ' & '; - for (var i = 0; i < artists.length; i++) { - artists[i].joinphrase = ', '; - } - artists.push(prev); - artists.push(last); - } else if (artists.length == 2) { - artists[0].joinphrase = ' & '; - } - var credits = []; - // re-split artists if featuring or vs - artists.map(function (item) { - var 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*\b(?:versus|vs\.?)\s+/gi, ' vs. '); - c = c.replace(/\s+/g, ' '); - var splitted = c.split(/( feat\. | vs\. )/); - if (splitted.length == 1) { - credits.push(item); // nothing to split - } else { - var new_items = []; - var n = 0; - for (var i = 0; i < splitted.length; i++) { - if (n && (splitted[i] == ' feat. ' || splitted[i] == ' vs. ')) { - new_items[n-1].joinphrase = splitted[i]; - } else { - new_items[n++] = { - artist_name: splitted[i].trim(), - joinphrase: '' - }; + let artists = artists_list.map(function(item) { + return { artist_name: item }; + }); + if (artists.length > 2) { + let last = artists.pop(); + last.joinphrase = ''; + let prev = artists.pop(); + prev.joinphrase = ' & '; + for (let i = 0; i < artists.length; i++) { + artists[i].joinphrase = ', '; } - } - new_items[n-1].joinphrase = item.joinphrase; - new_items.map(function (newit) { - credits.push(newit) - }); + artists.push(prev); + artists.push(last); + } else if (artists.length == 2) { + artists[0].joinphrase = ' & '; } - }); - return credits; + let credits = []; + // re-split artists if featuring or vs + artists.map(function(item) { + 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*\b(?:versus|vs\.?)\s+/gi, ' vs. '); + c = c.replace(/\s+/g, ' '); + let splitted = c.split(/( feat\. | vs\. )/); + if (splitted.length == 1) { + credits.push(item); // nothing to split + } else { + let new_items = []; + let n = 0; + for (let i = 0; i < splitted.length; i++) { + if (n && (splitted[i] == ' feat. ' || splitted[i] == ' vs. ')) { + new_items[n - 1].joinphrase = splitted[i]; + } else { + new_items[n++] = { + artist_name: splitted[i].trim(), + joinphrase: '' + }; + } + } + new_items[n - 1].joinphrase = item.joinphrase; + new_items.map(function(newit) { + credits.push(newit); + }); + } + }); + return credits; } // Try to guess release type using number of tracks, title and total duration (in millisecs) function fnGuessReleaseType(title, num_tracks, duration_ms) { - if (num_tracks < 1) return ''; - var has_single = !!title.match(/\bsingle\b/i); - var has_EP = !!title.match(/\bEP\b/i); - if (has_single && has_EP) { - has_single = false; - has_EP = false; - } - var perhaps_single = ((has_single && num_tracks <= 4) || num_tracks <= 2); - var perhaps_EP = has_EP || (num_tracks > 2 && num_tracks <= 6); - var perhaps_album = (num_tracks > 8); - if (isNaN(duration_ms)) { - // 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 'EP'; - if (!perhaps_single && !perhaps_EP && perhaps_album) return 'album'; + if (num_tracks < 1) return ''; + let has_single = !!title.match(/\bsingle\b/i); + let has_EP = !!title.match(/\bEP\b/i); + if (has_single && has_EP) { + has_single = false; + has_EP = false; + } + let perhaps_single = (has_single && num_tracks <= 4) || num_tracks <= 2; + let perhaps_EP = has_EP || (num_tracks > 2 && num_tracks <= 6); + let perhaps_album = num_tracks > 8; + if (isNaN(duration_ms)) { + // 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 'EP'; + if (!perhaps_single && !perhaps_EP && perhaps_album) return 'album'; + return ''; + } + let duration_mn = duration_ms / (60 * 1000); + if (perhaps_single && duration_mn >= 1 && duration_mn < 7) return 'single'; + if (perhaps_EP && duration_mn > 7 && duration_mn <= 30) return 'EP'; + if (perhaps_album && duration_mn > 30) return 'album'; return ''; - } - var duration_mn = duration_ms / (60*1000); - if (perhaps_single && duration_mn >= 1 && duration_mn < 7) return 'single'; - if (perhaps_EP && duration_mn > 7 && duration_mn <= 30) return 'EP'; - if (perhaps_album && duration_mn > 30) return 'album'; - return ''; } // convert HH:MM:SS or MM:SS to milliseconds 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; - var t = str.split(':'); - var s = 0; - var m = 1; + let t = str.split(':'); + let s = 0; + let m = 1; while (t.length > 0) { s += m * parseInt(t.pop(), 10); m *= 60; } - return s*1000; + return s * 1000; } // convert ISO8601 duration (limited to hours/minutes/seconds) to milliseconds // format looks like PT1H45M5.789S (note: floats can be used) // https://en.wikipedia.org/wiki/ISO_8601#Durations 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); if (!m) return NaN; return (3600 * parseFloat(m[1] || 0) + 60 * parseFloat(m[2] || 0) + parseFloat(m[3] || 0)) * 1000; } function fnMakeEditNote(release_url, importer_name, format) { - var home = 'https://github.com/murdos/musicbrainz-userscripts'; - return 'Imported from ' + release_url + (format ? ' (' + format + ')' : '') +' using ' + importer_name + ' import script from ' + home; + let home = 'https://github.com/murdos/musicbrainz-userscripts'; + return `Imported from ${release_url}${format ? ` (${format})` : ''} using ${importer_name} import script from ${home}`; } // --------------------------------------- privates ----------------------------------------- // function appendParameter(parameters, paramName, paramValue) { - if(!paramValue) return; - parameters.push( { name: paramName, value: paramValue } ); + if (!paramValue) return; + parameters.push({ name: paramName, value: paramValue }); } function luceneEscape(text) { - var newtext = text.replace(/[-[\]{}()*+?~:\\^!"\/]/g, "\\$&"); - return newtext.replace("&&", "\&&").replace("||", "\||"); + let newtext = text.replace(/[-[\]{}()*+?~:\\^!"\/]/g, '\\$&'); + return newtext.replace('&&', '&&').replace('||', '||'); } function buildArtistCreditsFormParameters(parameters, paramPrefix, artist_credit) { - if(!artist_credit) return; - for (var i=0; i < artist_credit.length; i++) { - var ac = artist_credit[i]; - 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+'.mbid', ac.mbid); - if (typeof ac.joinphrase != 'undefined' && ac.joinphrase != "") { - appendParameter(parameters, paramPrefix+'artist_credit.names.'+i+'.join_phrase', ac.joinphrase); + if (!artist_credit) return; + for (let i = 0; i < artist_credit.length; i++) { + let ac = artist_credit[i]; + 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}.mbid`, ac.mbid); + if (typeof ac.joinphrase != 'undefined' && ac.joinphrase != '') { + appendParameter(parameters, `${paramPrefix}artist_credit.names.${i}.join_phrase`, ac.joinphrase); } } } function searchParams(release) { - var params = []; + let params = []; - var totaltracks = 0; - for (var i=0; i < release.discs.length; i++) { + let totaltracks = 0; + for (var i = 0; i < release.discs.length; i++) { totaltracks += release.discs[i].tracks.length; } - var release_artist = ""; - for (var i=0; i < release.artist_credit.length; i++) { - var ac = release.artist_credit[i]; + let release_artist = ''; + for (var i = 0; i < release.artist_credit.length; i++) { + let ac = release.artist_credit[i]; release_artist += ac.artist_name; - if (typeof ac.joinphrase != 'undefined' && ac.joinphrase != "") { + if (typeof ac.joinphrase != 'undefined' && ac.joinphrase != '') { release_artist += ac.joinphrase; } 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) + ')' - + ' release:(' + luceneEscape(release.title) + ')' - + ' tracks:(' + totaltracks + ')' - + (release.country ? ' country:' + release.country : ''); + let query = + `artist:(${luceneEscape(release_artist)})` + + ` release:(${luceneEscape(release.title)})` + + ` tracks:(${totaltracks})${release.country ? ` country:${release.country}` : ''}`; appendParameter(params, 'query', query); appendParameter(params, 'type', 'release'); @@ -395,18 +402,18 @@ var MBImport = (function() { // ---------------------------------- expose publics here ------------------------------------ // return { - buildSearchLink: fnBuildSearchLink, - buildSearchButton: fnBuildSearchButton, - buildFormHTML: fnBuildFormHTML, - buildFormParameters: fnBuildFormParameters, - makeArtistCredits: fnArtistCredits, - guessReleaseType: fnGuessReleaseType, - hmsToMilliSeconds: hmsToMilliSeconds, - ISO8601toMilliSeconds: fnISO8601toMilliSeconds, - makeEditNote: fnMakeEditNote, - searchUrlFor: fnSearchUrlFor, - URL_TYPES: url_types, - SPECIAL_ARTISTS: special_artists, - specialArtist: fnSpecialArtist + buildSearchLink: fnBuildSearchLink, + buildSearchButton: fnBuildSearchButton, + buildFormHTML: fnBuildFormHTML, + buildFormParameters: fnBuildFormParameters, + makeArtistCredits: fnArtistCredits, + guessReleaseType: fnGuessReleaseType, + hmsToMilliSeconds: hmsToMilliSeconds, + ISO8601toMilliSeconds: fnISO8601toMilliSeconds, + makeEditNote: fnMakeEditNote, + searchUrlFor: fnSearchUrlFor, + URL_TYPES: url_types, + SPECIAL_ARTISTS: special_artists, + specialArtist: fnSpecialArtist }; })(); diff --git a/lib/mbimportstyle.js b/lib/mbimportstyle.js index 02031a7..99bd1b5 100644 --- a/lib/mbimportstyle.js +++ b/lib/mbimportstyle.js @@ -1,9 +1,10 @@ function _add_css(css) { - $("").appendTo("head"); + $(``).appendTo('head'); } function MBImportStyle() { - var css_import_button = " \ + let css_import_button = + ' \ .musicbrainz_import button { \ -moz-border-radius:5px; \ -webkit-border-radius:5px; \ @@ -34,12 +35,13 @@ function MBImportStyle() { min-height: 16px; \ display: inline-block; \ } \ - "; - _add_css(css_import_button); + '; + _add_css(css_import_button); } function MBSearchItStyle() { - var css_search_it = " \ + let css_search_it = + ' \ .mb_valign { \ display: inline-block; \ vertical-align: top; \ @@ -68,6 +70,6 @@ function MBSearchItStyle() { .mb_wrapper { \ display: inline-block; \ } \ - "; - _add_css(css_search_it); + '; + _add_css(css_search_it); } diff --git a/lib/mblinks.js b/lib/mblinks.js index b2f7016..733be5f 100644 --- a/lib/mblinks.js +++ b/lib/mblinks.js @@ -16,222 +16,227 @@ // 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) // 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) { - this.supports_local_storage = function () { - try { - return !!localStorage.getItem; - } catch (e) { - return false; - } - }(); - - this.ajax_requests = { - // properties: "key": {handler: function, next: property, context: {}} - first: "", - last: "", - empty: function() {return this.first == "";}, - push: function(key, handler, context) { - if (key in this) { - this[key].handler = handler; - this[key].context = context; +var MBLinks = function(user_cache_key, version, expiration) { + this.supports_local_storage = (function() { + try { + return !!localStorage.getItem; + } catch (e) { + return false; } - else { - this[key] = {handler: handler, next: "", context: context}; - if (this.first == "") { - this.first = this.last = key; - } - else { - this[this.last].next = key; - this.last = key; - } - } - }, - shift: function() { - if (this.empty()) { return; } - var key = this.first; - var handler = this[key].handler; - var context = this[key].context; - this.first = this[key].next; - delete this[key]; // delete this property - return $.proxy(handler, context); - } - }; - this.cache = {}; - this.expirationMinutes = ((typeof expiration != 'undefined' && expiration !== false) ? parseInt(expiration, 10) : 90*24*60); // default to 90 days - var cache_version = 2; - this.user_cache_key = user_cache_key; - this.cache_key = this.user_cache_key + '-v' + cache_version + (typeof version != 'undefined' ? '.' + version : ''); - this.mb_server = '//musicbrainz.org'; - // overrides link title and img src url (per type), see createMusicBrainzLink() - this.type_link_info = { - release_group: { - title: 'See this release group on MusicBrainz', - }, - place: { - img_src: '' - } - } + })(); - this.initAjaxEngine = function () { - var ajax_requests = this.ajax_requests; - setInterval(function () { - if (!ajax_requests.empty()) { - var request = ajax_requests.shift(); - if (typeof request === "function") { - request(); - } - } - }, 1000); - }; - - this.initCache = function () { - if (!this.supports_local_storage) return; - // Check if we already added links for this content - this.cache = JSON.parse(localStorage.getItem(this.cache_key) || '{}'); - // remove old entries - this.clearCacheExpired(); - // remove old cache versions - this.removeOldCacheVersions(); - }; - - this.saveCache = function () { - if (!this.supports_local_storage) return; - try { - localStorage.setItem(this.cache_key, JSON.stringify(this.cache)); - } catch (e) { - alert(e); - } - }; - - this.removeOldCacheVersions = function () { - var to_remove = []; - for (var i = 0, len = localStorage.length; i < len; ++i) { - var key = localStorage.key(i); - if (key.indexOf(this.user_cache_key) === 0) { - if (key != this.cache_key) { // we don't want to remove current cache - to_remove.push(key); - } - } - } - // remove old cache keys - for (var i = 0; i < to_remove.length; i++) { - localStorage.removeItem(to_remove[i]); - } - }; - - this.clearCacheExpired = function() { - //var old_cache_entries = Object.keys(this.cache).length; - //console.log("clearCacheExpired " + old_cache_entries); - var now = new Date().getTime(); - var new_cache = {}; - var that = this; - $.each(this.cache, function (key, value) { - if (that.is_cached(key)) { - new_cache[key] = that.cache[key]; - } - }); - //var new_cache_entries = Object.keys(new_cache).length; - //console.log("Cleared cache entries: " + old_cache_entries + ' -> ' + new_cache_entries); - this.cache = new_cache; - }; - - this.is_cached = function (key) { - 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. - // 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) { - if (this.is_cached(key) && this.cache[key].urls.length == 1) { - return this.cache[key].urls[0].slice(-36); - } - }; - - this.createMusicBrainzLink = function (mb_url, _type) { - var title = 'See this ' + _type + ' on MusicBrainz'; - var img_url = this.mb_server + '/static/images/entity/' + _type + '.svg'; - var img_src = ''; - // handle overrides - var ti = this.type_link_info[_type]; - if (ti) { - if (ti.title) title = ti.title; - if (ti.img_url) img_url = ti.img_url; - if (ti.img_src) img_src = ti.img_src; - } - return '' + img_src + ' '; - }; - - // 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 - // entry found - this.searchAndDisplayMbLink = function (url, mb_type, insert_func, key) { - var mblinks = this; - var _type = mb_type.replace('-', '_'); // underscored type - - if (!key) key = url; - if (this.is_cached(key)) { - $.each(mblinks.cache[key].urls, function (idx, mb_url) { - insert_func(mblinks.createMusicBrainzLink(mb_url, _type)); - }); - } else { - - // webservice query url - var 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 - var handlers = []; - if (query in mblinks.ajax_requests) { - handlers = mblinks.ajax_requests[query].context.handlers; - } - handlers.push(insert_func); - - mblinks.ajax_requests.push( - // key - query, - - // handler - function () { - var ctx = this; // context from $.proxy() - var mbl = ctx.mblinks; - $.getJSON(ctx.query, - function (data) { - if ('relations' in data) { - mbl.cache[ctx.key] = { - timestamp: new Date().getTime(), - urls: [] - }; - $.each(data['relations'], function (idx, relation) { - if (ctx._type in relation) { - var mb_url = mbl.mb_server + '/' + ctx.mb_type + '/' + relation[ctx._type]['id']; - if ($.inArray(mb_url, mbl.cache[ctx.key].urls) == -1) { // prevent dupes - mbl.cache[ctx.key].urls.push(mb_url); - $.each(ctx.handlers, function(i, handler) { - handler(mbl.createMusicBrainzLink(mb_url, ctx._type)) - }) - } - } - }); - mbl.saveCache(); - } - } - ); + this.ajax_requests = { + // properties: "key": {handler: function, next: property, context: {}} + first: '', + last: '', + empty: function() { + return this.first == ''; }, - - // context - { - 'key': key, // cache key - 'handlers': handlers, // list of handlers - 'mb_type': mb_type, // musicbrainz type ie. release-group - '_type': _type, // musicbrainz type '-' replaced, ie. release_group - 'query': query, // json request url - 'mblinks': mblinks // MBLinks object + push: function(key, handler, context) { + if (key in this) { + this[key].handler = handler; + this[key].context = context; + } else { + this[key] = { handler: handler, next: '', context: context }; + if (this.first == '') { + this.first = this.last = key; + } else { + this[this.last].next = key; + this.last = key; + } + } + }, + shift: function() { + if (this.empty()) { + return; + } + let key = this.first; + let handler = this[key].handler; + let context = this[key].context; + this.first = this[key].next; + delete this[key]; // delete this property + return $.proxy(handler, context); } - ); - } - }; + }; + this.cache = {}; + this.expirationMinutes = typeof expiration != 'undefined' && expiration !== false ? parseInt(expiration, 10) : 90 * 24 * 60; // default to 90 days + let cache_version = 2; + this.user_cache_key = user_cache_key; + this.cache_key = `${this.user_cache_key}-v${cache_version}${typeof version != 'undefined' ? `.${version}` : ''}`; + this.mb_server = '//musicbrainz.org'; + // overrides link title and img src url (per type), see createMusicBrainzLink() + this.type_link_info = { + release_group: { + title: 'See this release group on MusicBrainz' + }, + place: { + img_src: `` + } + }; - this.initCache(); - this.initAjaxEngine(); + this.initAjaxEngine = function() { + let ajax_requests = this.ajax_requests; + setInterval(function() { + if (!ajax_requests.empty()) { + let request = ajax_requests.shift(); + if (typeof request === 'function') { + request(); + } + } + }, 1000); + }; - return this; + this.initCache = function() { + if (!this.supports_local_storage) return; + // Check if we already added links for this content + this.cache = JSON.parse(localStorage.getItem(this.cache_key) || '{}'); + // remove old entries + this.clearCacheExpired(); + // remove old cache versions + this.removeOldCacheVersions(); + }; + + this.saveCache = function() { + if (!this.supports_local_storage) return; + try { + localStorage.setItem(this.cache_key, JSON.stringify(this.cache)); + } catch (e) { + alert(e); + } + }; + + this.removeOldCacheVersions = function() { + let to_remove = []; + for (var i = 0, len = localStorage.length; i < len; ++i) { + let key = localStorage.key(i); + if (key.indexOf(this.user_cache_key) === 0) { + if (key != this.cache_key) { + // we don't want to remove current cache + to_remove.push(key); + } + } + } + // remove old cache keys + for (var i = 0; i < to_remove.length; i++) { + localStorage.removeItem(to_remove[i]); + } + }; + + this.clearCacheExpired = function() { + //var old_cache_entries = Object.keys(this.cache).length; + //console.log("clearCacheExpired " + old_cache_entries); + let now = new Date().getTime(); + let new_cache = {}; + let that = this; + $.each(this.cache, function(key, value) { + if (that.is_cached(key)) { + new_cache[key] = that.cache[key]; + } + }); + //var new_cache_entries = Object.keys(new_cache).length; + //console.log("Cleared cache entries: " + old_cache_entries + ' -> ' + new_cache_entries); + this.cache = new_cache; + }; + + this.is_cached = function(key) { + 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. + // 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) { + if (this.is_cached(key) && this.cache[key].urls.length == 1) { + return this.cache[key].urls[0].slice(-36); + } + }; + + this.createMusicBrainzLink = function(mb_url, _type) { + let title = `See this ${_type} on MusicBrainz`; + let img_url = `${this.mb_server}/static/images/entity/${_type}.svg`; + let img_src = ``; + // handle overrides + let ti = this.type_link_info[_type]; + if (ti) { + if (ti.title) title = ti.title; + if (ti.img_url) img_url = ti.img_url; + if (ti.img_src) img_src = ti.img_src; + } + return `${img_src} `; + }; + + // 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 + // entry found + this.searchAndDisplayMbLink = function(url, mb_type, insert_func, key) { + let mblinks = this; + let _type = mb_type.replace('-', '_'); // underscored type + + if (!key) key = url; + if (this.is_cached(key)) { + $.each(mblinks.cache[key].urls, function(idx, mb_url) { + insert_func(mblinks.createMusicBrainzLink(mb_url, _type)); + }); + } else { + // webservice query url + 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 + let handlers = []; + if (query in mblinks.ajax_requests) { + handlers = mblinks.ajax_requests[query].context.handlers; + } + handlers.push(insert_func); + + mblinks.ajax_requests.push( + // key + query, + + // handler + function() { + let ctx = this; // context from $.proxy() + let mbl = ctx.mblinks; + $.getJSON(ctx.query, function(data) { + if ('relations' in data) { + mbl.cache[ctx.key] = { + timestamp: new Date().getTime(), + urls: [] + }; + $.each(data['relations'], function(idx, relation) { + if (ctx._type in relation) { + 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 + mbl.cache[ctx.key].urls.push(mb_url); + $.each(ctx.handlers, function(i, handler) { + handler(mbl.createMusicBrainzLink(mb_url, ctx._type)); + }); + } + } + }); + mbl.saveCache(); + } + }); + }, + + // context + { + key: key, // cache key + handlers: handlers, // list of handlers + mb_type: mb_type, // musicbrainz type ie. release-group + _type: _type, // musicbrainz type '-' replaced, ie. release_group + query: query, // json request url + mblinks: mblinks // MBLinks object + } + ); + } + }; + + this.initCache(); + this.initAjaxEngine(); + + return this; }; diff --git a/loot_importer.user.js b/loot_importer.user.js index 9d71d92..1ebd3a1 100644 --- a/loot_importer.user.js +++ b/loot_importer.user.js @@ -15,7 +15,6 @@ // @grant none // ==/UserScript== - // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant this.$ = this.jQuery = jQuery.noConflict(true); @@ -24,7 +23,7 @@ if (!unsafeWindow) unsafeWindow = window; var DEBUG = false; //DEBUG = true; if (DEBUG) { - LOGGER.setLevel('debug'); + LOGGER.setLevel('debug'); } //////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -38,621 +37,621 @@ if (DEBUG) { * - http://www.loot.co.za/product/bette-midler-a-gift-of-love/mhgm-3483-g060 *** NOT WORKING *** extra tab */ - $(document).ready(function() { - LOGGER.info("Document Ready & Loot Userscript executing"); - var LootRelease = ParseLootPage(); - insertMBSection(LootRelease); + LOGGER.info('Document Ready & Loot Userscript executing'); + let LootRelease = ParseLootPage(); + insertMBSection(LootRelease); }); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Insert MusicBrainz section into Loot page // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - function insertMbUI(mbUI) { - LOGGER.debug("insertMbUI Firing"); - var e; - if ((e = $("#thumbs")) && e.length) { - e.after(mbUI); - } else if ((e = $('#productContent')) && e.length) { - e.before(mbUI); - } else if ((e = $("div.buyNow")) && e.length) { - e.before(mbUI); - } + LOGGER.debug('insertMbUI Firing'); + let e; + if ((e = $('#thumbs')) && e.length) { + e.after(mbUI); + } else if ((e = $('#productContent')) && e.length) { + e.before(mbUI); + } else if ((e = $('div.buyNow')) && e.length) { + e.before(mbUI); + } } // Insert links to high res image in Loot page function insertIMGlinks() { - var imghref = $('#imagePreview0 a.fancybox').attr('href'); - imghref = 'http://static.loot.co.za/' + imghref; - LOGGER.debug("insertIMGlink Firing", imghref); - $('#imagePreview0').append('

    MB High Res Image

    '); + let imghref = $('#imagePreview0 a.fancybox').attr('href'); + imghref = `http://static.loot.co.za/${imghref}`; + LOGGER.debug('insertIMGlink Firing', imghref); + $('#imagePreview0').append(`

    MB High Res Image

    `); } // Insert links in Loot page function insertMBSection(release) { - LOGGER.debug("insertMBsection Firing"); - var mbUI = $('

    MusicBrainz

    ').hide(); + LOGGER.debug('insertMBsection Firing'); + let mbUI = $('

    MusicBrainz

    ').hide(); - if (DEBUG) mbUI.css({ - 'border': '1px dotted red' - }); + if (DEBUG) + mbUI.css({ + border: '1px dotted red' + }); - var mbContentBlock = $('
    '); - mbUI.append(mbContentBlock); + let mbContentBlock = $('
    '); + mbUI.append(mbContentBlock); - if (release.maybe_buggy) { - var warning_buggy = $('

    Warning: this release has perhaps a buggy title, please check twice the data you import.Warning: this release has perhaps a buggy title, please check twice the data you import.${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}`; + mbContentBlock.append(innerHTML); + + insertMbUI(mbUI); + insertIMGlinks(); + + $('#mb_buttons').css({ + display: 'inline-block', + width: '100%' + }); + $('form.musicbrainz_import').css({ + width: '49%', + display: 'inline-block' + }); + $('form.musicbrainz_import_search').css({ + float: 'right' + }); + $('form.musicbrainz_import > button').css({ + width: '100%', + 'box-sizing': 'border-box' }); - mbContentBlock.prepend(warning_buggy); - } - // Form parameters - var edit_note = MBImport.makeEditNote(window.location.href, 'Loot'); - LOGGER.debug("*** Edit Note: ", edit_note); - var parameters = MBImport.buildFormParameters(release, edit_note); - LOGGER.debug("***Form parameters"); - // Build form + search button - var innerHTML = '

    ' + MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release) + '
    '; - mbContentBlock.append(innerHTML); - - insertMbUI(mbUI); - insertIMGlinks(); - - $('#mb_buttons').css({ - display: 'inline-block', - width: '100%' - }); - $('form.musicbrainz_import').css({ - width: '49%', - display: 'inline-block' - }); - $('form.musicbrainz_import_search').css({ - 'float': 'right' - }) - $('form.musicbrainz_import > button').css({ - width: '100%', - 'box-sizing': 'border-box' - }); - - mbUI.slideDown(); + mbUI.slideDown(); } function parseReleaseDate(rdate) { - var months = { - "January": 1, - "February": 2, - "March": 3, - "April": 4, - "May": 5, - "June": 6, - "July": 7, - "August": 8, - "September": 9, - "October": 10, - "November": 11, - "December": 12 - }; + let months = { + January: 1, + February: 2, + March: 3, + April: 4, + May: 5, + June: 6, + July: 7, + August: 8, + September: 9, + October: 10, + November: 11, + December: 12 + }; - var m = rdate.match(/([a-zA-Z]+) (\d{4})/i); - if (m) { - return { - year: m[2], - month: months[m[1]] + let m = rdate.match(/([a-zA-Z]+) (\d{4})/i); + if (m) { + return { + year: m[2], + month: months[m[1]] + }; } - } - return false; + return false; } // Analyze Loot data and return a release object function ParseLootPage() { - LOGGER.debug("ParseLootPage function firing"); + LOGGER.debug('ParseLootPage function firing'); - var releasebarcode = ""; - var releasecountry = ""; - var releasedaterel = ""; - var releaselanguage = ""; - var releasetitle = ""; - var releaseartist = ""; - var prodlabels = []; - var release_artist_array = []; - var release_format = ""; - var release_maybe_buggy = false; + let releasebarcode = ''; + let releasecountry = ''; + let releasedaterel = ''; + let releaselanguage = ''; + let releasetitle = ''; + let releaseartist = ''; + let prodlabels = []; + let release_artist_array = []; + let release_format = ''; + let release_maybe_buggy = false; - // div#productContent table tbody tr.productOverview td.productInfo h1 - var AlbumName = document.querySelectorAll("div#productContent > table > tbody > tr.productOverview > td.productInfo > *"); + // div#productContent table tbody tr.productOverview td.productInfo h1 + let AlbumName = document.querySelectorAll('div#productContent > table > tbody > tr.productOverview > td.productInfo > *'); - releaseartist = AlbumName[1].innerText; - if (releaseartist == "Various Artists") { - // Everything is: title(format) - releaseartisttitle_regex = /(.*?)\((.*)\)/; //match external parenthesis - if (AlbumName[0].innerText.match(releaseartisttitle_regex)) { - releaseartisttitle = AlbumName[0].innerText.match(releaseartisttitle_regex); - releasetitle = releaseartisttitle[1].trim(); - release_format = releaseartisttitle[2]; - } else { - LOGGER.debug("Release Title for Various Artist album does not match the name convention. Hint: Change releaseartisttitle regex for Compilations"); - release_maybe_buggy = true; - releasetitle = ""; - release_format = ""; - } - } else { - // artist - title(format) - releaseartisttitle_regex = /(.*) (-|–) (.*?)\((.*)\)/; - - if (AlbumName[0].innerText.match(releaseartisttitle_regex)) { - - releaseartisttitle = AlbumName[0].innerText.match(releaseartisttitle_regex); - - releasetitle = releaseartisttitle[3].trim(); - releaseartist = releaseartisttitle[1]; - release_format = releaseartisttitle[4]; - - } else { - 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; - releasetitle = ""; - releaseartist = ""; - release_format = ""; - } - } - LOGGER.debug("Release Title:", releasetitle, " Release Artist:", releaseartist, " Release Format:", release_format); - - - // extract all tr from table with class productDetails - $("table.productDetails tr").each(function() { - // get text from first td, trim and convert it to lowercase - var 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 - // get test from second td, which is the corresponding value - var value = $(this).children('td').eq(1).text().trim(); - // now compare and process - switch (prodinfolabellowcase) { - case "label:": // use these cases to select the spesific text values - prodlabels.push({ - name: value - }); - break; - case "releasedate:": - releasedaterel = value; - LOGGER.debug(" ** release date: **", releasedaterel) - break; - case "countryoforigin:": - releasecountry = value; - LOGGER.debug(" ** country of origin: **", releasecountry); - break; - case "performers:": - LOGGER.debug(" ** performers: **", value); - release_artist_array.push({ - name: value - }); - break; - case "format:": - LOGGER.debug(" ** format: **"); - break; - case "categories:": - //LOGGER.debug(" ** categories: **", value); - - if ($('table.productDetails tr td a:contains("Afrikaans")').length) { - LOGGER.debug("Language Afrikaans exists"); - releaselanguage = "Afrikaans"; + releaseartist = AlbumName[1].innerText; + if (releaseartist == 'Various Artists') { + // Everything is: title(format) + releaseartisttitle_regex = /(.*?)\((.*)\)/; //match external parenthesis + if (AlbumName[0].innerText.match(releaseartisttitle_regex)) { + releaseartisttitle = AlbumName[0].innerText.match(releaseartisttitle_regex); + releasetitle = releaseartisttitle[1].trim(); + release_format = releaseartisttitle[2]; + } else { + LOGGER.debug( + 'Release Title for Various Artist album does not match the name convention. Hint: Change releaseartisttitle regex for Compilations' + ); + release_maybe_buggy = true; + releasetitle = ''; + release_format = ''; } + } else { + // artist - title(format) + releaseartisttitle_regex = /(.*) (-|–) (.*?)\((.*)\)/; - if ($('table.productDetails tr td a:contains("South Africa")').length) { - LOGGER.debug("Country South Africa exists in catagories"); - releasecountry = "South Africa"; + if (AlbumName[0].innerText.match(releaseartisttitle_regex)) { + releaseartisttitle = AlbumName[0].innerText.match(releaseartisttitle_regex); + + releasetitle = releaseartisttitle[3].trim(); + releaseartist = releaseartisttitle[1]; + release_format = releaseartisttitle[4]; + } else { + 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; + releasetitle = ''; + releaseartist = ''; + release_format = ''; } + } + LOGGER.debug('Release Title:', releasetitle, ' Release Artist:', releaseartist, ' Release Format:', release_format); - break; + // extract all tr from table with class productDetails + $('table.productDetails tr').each(function() { + // get text from first td, trim and convert it to lowercase + 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 + // get test from second td, which is the corresponding value + let value = $(this) + .children('td') + .eq(1) + .text() + .trim(); + // now compare and process + switch (prodinfolabellowcase) { + case 'label:': // use these cases to select the spesific text values + prodlabels.push({ + name: value + }); + break; + case 'releasedate:': + releasedaterel = value; + LOGGER.debug(' ** release date: **', releasedaterel); + break; + case 'countryoforigin:': + releasecountry = value; + LOGGER.debug(' ** country of origin: **', releasecountry); + break; + case 'performers:': + LOGGER.debug(' ** performers: **', value); + release_artist_array.push({ + name: value + }); + break; + case 'format:': + LOGGER.debug(' ** format: **'); + break; + case 'categories:': + //LOGGER.debug(" ** categories: **", value); + + if ($('table.productDetails tr td a:contains("Afrikaans")').length) { + LOGGER.debug('Language Afrikaans exists'); + releaselanguage = 'Afrikaans'; + } + + if ($('table.productDetails tr td a:contains("South Africa")').length) { + LOGGER.debug('Country South Africa exists in catagories'); + releasecountry = 'South Africa'; + } + + break; + } + }); + // Select all data in the "Tracks" div id = tab-2 + let allinfolist = document.querySelectorAll('div#tab-2 > table.productDetails > tbody'); + LOGGER.debug('Track Info: (allinfolist)', allinfolist); + + // Select the Disc names + let disccount = document.querySelectorAll('div#tab-2 > h3'); + LOGGER.debug('Amount of discs: ', disccount.length); + + let descriptionarray = []; + + for (let disciterate = 0; disciterate < disccount.length; disciterate++) { + LOGGER.debug(disciterate); + let tracklisting = allinfolist[disciterate].getElementsByTagName('tr'); + LOGGER.debug(' The Table: (tracklisting)', tracklisting); + + for (let trackiterate = 0; trackiterate < tracklisting.length; trackiterate++) { + descriptiontrack = new Object(); + + let currenttrack = tracklisting[trackiterate].querySelectorAll('td'); + // var artisttitle_regex = /(.*) - (.*)/; // regex: artist - title + var artisttitle_regex = /(.*) (-|–) (.*)/; // regex: artist - title char 45 or 8211 + + // need to check if this can be replaced with single regex for now check artist-title if + // not matching check just title + if (currenttrack[1].innerText.match(artisttitle_regex)) { + var artisttitle = currenttrack[1].innerText.match(artisttitle_regex); + descriptiontrack.title = artisttitle[3]; + descriptiontrack.artist = artisttitle[1]; + } else { + var artisttitle_regex = /(.*)/; // regex: title + var artisttitle = currenttrack[1].innerText.match(artisttitle_regex); + descriptiontrack.title = artisttitle[1]; + descriptiontrack.artist = releaseartist; + } + + descriptiontrack.disc = disciterate + 1; + descriptiontrack.track = parseInt(currenttrack[0].innerText); + + descriptionarray.push(descriptiontrack); + } } - }); - // Select all data in the "Tracks" div id = tab-2 - var allinfolist = document.querySelectorAll("div#tab-2 > table.productDetails > tbody"); - LOGGER.debug("Track Info: (allinfolist)", allinfolist); + // Discs + let disclistarray = new Array(); // create the tracklist array to use later - // Select the Disc names - var disccount = document.querySelectorAll("div#tab-2 > h3"); - LOGGER.debug("Amount of discs: ", disccount.length); + for (let desc_discs = 0; desc_discs < disccount.length; desc_discs++) { + let tracklistarray = new Array(); + for (let desc__track = 0; desc__track < descriptionarray.length; desc__track++) { + let desc_currentdiscnumber = descriptionarray[desc__track].disc; + if (desc_currentdiscnumber == desc_discs + 1) { + let track = new Object(); + let track_artist_credit = new Array(); - var descriptionarray = []; + track.number = descriptionarray[desc__track].track; + track.title = descriptionarray[desc__track].title; - for (var disciterate = 0; disciterate < disccount.length; disciterate++) { - LOGGER.debug(disciterate); - var tracklisting = allinfolist[disciterate].getElementsByTagName('tr'); - LOGGER.debug(" The Table: (tracklisting)", tracklisting); + let track_artist_credit_object = new Object(); + track_artist_credit_object.artist_name = descriptionarray[desc__track].artist; + track_artist_credit.push(track_artist_credit_object); - for (var trackiterate = 0; trackiterate < tracklisting.length; trackiterate++) { - - descriptiontrack = new Object(); - - var currenttrack = tracklisting[trackiterate].querySelectorAll("td"); - // var artisttitle_regex = /(.*) - (.*)/; // regex: artist - title - var artisttitle_regex = /(.*) (-|–) (.*)/; // regex: artist - title char 45 or 8211 - - // need to check if this can be replaced with single regex for now check artist-title if - // not matching check just title - if (currenttrack[1].innerText.match(artisttitle_regex)) { - var artisttitle = currenttrack[1].innerText.match(artisttitle_regex); - descriptiontrack.title = artisttitle[3]; - descriptiontrack.artist = artisttitle[1]; - } else { - var artisttitle_regex = /(.*)/; // regex: title - var artisttitle = currenttrack[1].innerText.match(artisttitle_regex); - descriptiontrack.title = artisttitle[1]; - descriptiontrack.artist = releaseartist; - } - - descriptiontrack.disc = disciterate + 1; - descriptiontrack.track = parseInt(currenttrack[0].innerText); - - descriptionarray.push(descriptiontrack); + track.artist_credit = track_artist_credit; + tracklistarray.push(track); + } + } + disclistarray.push(tracklistarray); } - } + //LOGGER.debug(disclistarray); + release = new Object(); - // Discs - var disclistarray = new Array(); // create the tracklist array to use later + // Check if anything is untoward and highlight to importer + release.maybe_buggy = release_maybe_buggy; - for (var desc_discs = 0; desc_discs < disccount.length; desc_discs++) { - var tracklistarray = new Array(); - for (var desc__track = 0; desc__track < descriptionarray.length; desc__track++) { + // Release artist credit + release.artist_credit = new Array(); - var desc_currentdiscnumber = descriptionarray[desc__track].disc; - if (desc_currentdiscnumber == desc_discs + 1) { - var track = new Object(); - var track_artist_credit = new Array(); + let artist_name = releaseartist; - track.number = descriptionarray[desc__track].track; - track.title = descriptionarray[desc__track].title; - - var track_artist_credit_object = new Object(); - track_artist_credit_object.artist_name = descriptionarray[desc__track].artist; - track_artist_credit.push(track_artist_credit_object); - - track.artist_credit = track_artist_credit; - tracklistarray.push(track); - } + let various_artists = releaseartist == 'Various Artists'; + if (various_artists) { + release.artist_credit = [MBImport.specialArtist('various_artists')]; + } else { + release.artist_credit = MBImport.makeArtistCredits([artist_name]); } - disclistarray.push(tracklistarray); - } - //LOGGER.debug(disclistarray); - release = new Object(); + // Release title + release.title = releasetitle; + // Release Barcode + release.barcode = releasebarcode; - // Check if anything is untoward and highlight to importer - release.maybe_buggy = release_maybe_buggy; + // Default status is official + release.status = 'official'; - // Release artist credit - release.artist_credit = new Array(); + // Other hard-coded info + release.script = 'Latn'; - var artist_name = releaseartist; + release.country = Countries[releasecountry]; + release.language = Languages[releaselanguage]; - var various_artists = (releaseartist == 'Various Artists'); - if (various_artists) { - release.artist_credit = [MBImport.specialArtist('various_artists')]; - } else { - release.artist_credit = MBImport.makeArtistCredits([artist_name]); - } + release.discs = new Array(); + for (let l = 0; l < disccount.length; l++) { + let disc = { + position: l + 1, + format: release_format, + tracks: disclistarray[l] + }; + release.discs.push(disc); + } + release.labels = prodlabels; + // Release URL + release.urls = new Array(); + release.urls.push({ + url: window.location.href, + link_type: MBImport.URL_TYPES.purchase_for_mail_order + }); - // Release title - release.title = releasetitle; - // Release Barcode - release.barcode = releasebarcode; + // TODO check format then change purchase medium - // Default status is official - release.status = 'official'; + // Release date + let parsed_releaseDate = parseReleaseDate(releasedaterel); + if (parsed_releaseDate) { + release.year = parsed_releaseDate.year; + release.month = parsed_releaseDate.month; + release.day = parsed_releaseDate.day; + } - // Other hard-coded info - release.script = 'Latn'; + LOGGER.info('Release:', release); - release.country = Countries[releasecountry]; - release.language = Languages[releaselanguage]; - - release.discs = new Array(); - for (var l = 0; l < disccount.length; l++) { - var disc = { - 'position': l + 1, - 'format': release_format, - 'tracks': disclistarray[l] - }; - release.discs.push(disc); - } - - release.labels = prodlabels; - - // Release URL - release.urls = new Array(); - release.urls.push({ - 'url': window.location.href, - 'link_type': MBImport.URL_TYPES.purchase_for_mail_order - }); - - // TODO check format then change purchase medium - - // Release date - var parsed_releaseDate = parseReleaseDate(releasedaterel); - if (parsed_releaseDate) { - release.year = parsed_releaseDate.year; - release.month = parsed_releaseDate.month; - release.day = parsed_releaseDate.day; - } - - - - LOGGER.info("Release:", release); - - return release; + return release; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // Loot -> MusicBrainz mapping // //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - var Languages = new Array(); -Languages["Afrikaans"] = "afr"; - - +Languages['Afrikaans'] = 'afr'; var Countries = new Array(); -Countries["Afghanistan"] = "AF"; -Countries["Albania"] = "AL"; -Countries["Algeria"] = "DZ"; -Countries["American Samoa"] = "AS"; -Countries["Andorra"] = "AD"; -Countries["Angola"] = "AO"; -Countries["Anguilla"] = "AI"; -Countries["Antarctica"] = "AQ"; -Countries["Antigua and Barbuda"] = "AG"; -Countries["Argentina"] = "AR"; -Countries["Armenia"] = "AM"; -Countries["Aruba"] = "AW"; -Countries["Australia"] = "AU"; -Countries["Austria"] = "AT"; -Countries["Azerbaijan"] = "AZ"; -Countries["Bahamas"] = "BS"; -Countries["Bahrain"] = "BH"; -Countries["Bangladesh"] = "BD"; -Countries["Barbados"] = "BB"; -Countries["Belarus"] = "BY"; -Countries["Belgium"] = "BE"; -Countries["Belize"] = "BZ"; -Countries["Benin"] = "BJ"; -Countries["Bermuda"] = "BM"; -Countries["Bhutan"] = "BT"; -Countries["Bolivia"] = "BO"; -Countries["Croatia"] = "HR"; -Countries["Botswana"] = "BW"; -Countries["Bouvet Island"] = "BV"; -Countries["Brazil"] = "BR"; -Countries["British Indian Ocean Territory"] = "IO"; -Countries["Brunei Darussalam"] = "BN"; -Countries["Bulgaria"] = "BG"; -Countries["Burkina Faso"] = "BF"; -Countries["Burundi"] = "BI"; -Countries["Cambodia"] = "KH"; -Countries["Cameroon"] = "CM"; -Countries["Canada"] = "CA"; -Countries["Cape Verde"] = "CV"; -Countries["Cayman Islands"] = "KY"; -Countries["Central African Republic"] = "CF"; -Countries["Chad"] = "TD"; -Countries["Chile"] = "CL"; -Countries["China"] = "CN"; -Countries["Christmas Island"] = "CX"; -Countries["Cocos (Keeling) Islands"] = "CC"; -Countries["Colombia"] = "CO"; -Countries["Comoros"] = "KM"; -Countries["Congo"] = "CG"; -Countries["Cook Islands"] = "CK"; -Countries["Costa Rica"] = "CR"; -Countries["Virgin Islands, British"] = "VG"; -Countries["Cuba"] = "CU"; -Countries["Cyprus"] = "CY"; -Countries["Czech Republic"] = "CZ"; -Countries["Denmark"] = "DK"; -Countries["Djibouti"] = "DJ"; -Countries["Dominica"] = "DM"; -Countries["Dominican Republic"] = "DO"; -Countries["Ecuador"] = "EC"; -Countries["Egypt"] = "EG"; -Countries["El Salvador"] = "SV"; -Countries["Equatorial Guinea"] = "GQ"; -Countries["Eritrea"] = "ER"; -Countries["Estonia"] = "EE"; -Countries["Ethiopia"] = "ET"; -Countries["Falkland Islands (Malvinas)"] = "FK"; -Countries["Faroe Islands"] = "FO"; -Countries["Fiji"] = "FJ"; -Countries["Finland"] = "FI"; -Countries["France"] = "FR"; -Countries["French Guiana"] = "GF"; -Countries["French Polynesia"] = "PF"; -Countries["French Southern Territories"] = "TF"; -Countries["Gabon"] = "GA"; -Countries["Gambia"] = "GM"; -Countries["Georgia"] = "GE"; -Countries["Germany"] = "DE"; -Countries["Ghana"] = "GH"; -Countries["Gibraltar"] = "GI"; -Countries["Greece"] = "GR"; -Countries["Greenland"] = "GL"; -Countries["Grenada"] = "GD"; -Countries["Guadeloupe"] = "GP"; -Countries["Guam"] = "GU"; -Countries["Guatemala"] = "GT"; -Countries["Guinea"] = "GN"; -Countries["Guinea-Bissau"] = "GW"; -Countries["Guyana"] = "GY"; -Countries["Haiti"] = "HT"; -Countries["Virgin Islands, U.S."] = "VI"; -Countries["Honduras"] = "HN"; -Countries["Hong Kong"] = "HK"; -Countries["Hungary"] = "HU"; -Countries["Iceland"] = "IS"; -Countries["India"] = "IN"; -Countries["Indonesia"] = "ID"; -Countries["Wallis and Futuna"] = "WF"; -Countries["Iraq"] = "IQ"; -Countries["Ireland"] = "IE"; -Countries["Israel"] = "IL"; -Countries["Italy"] = "IT"; -Countries["Jamaica"] = "JM"; -Countries["Japan"] = "JP"; -Countries["Jordan"] = "JO"; -Countries["Kazakhstan"] = "KZ"; -Countries["Kenya"] = "KE"; -Countries["Kiribati"] = "KI"; -Countries["Kuwait"] = "KW"; -Countries["Kyrgyzstan"] = "KG"; -Countries["Lao People's Democratic Republic"] = "LA"; -Countries["Latvia"] = "LV"; -Countries["Lebanon"] = "LB"; -Countries["Lesotho"] = "LS"; -Countries["Liberia"] = "LR"; -Countries["Libyan Arab Jamahiriya"] = "LY"; -Countries["Liechtenstein"] = "LI"; -Countries["Lithuania"] = "LT"; -Countries["Luxembourg"] = "LU"; -Countries["Montserrat"] = "MS"; -Countries["Macedonia, The Former Yugoslav Republic of"] = "MK"; -Countries["Madagascar"] = "MG"; -Countries["Malawi"] = "MW"; -Countries["Malaysia"] = "MY"; -Countries["Maldives"] = "MV"; -Countries["Mali"] = "ML"; -Countries["Malta"] = "MT"; -Countries["Marshall Islands"] = "MH"; -Countries["Martinique"] = "MQ"; -Countries["Mauritania"] = "MR"; -Countries["Mauritius"] = "MU"; -Countries["Mayotte"] = "YT"; -Countries["Mexico"] = "MX"; -Countries["Micronesia, Federated States of"] = "FM"; -Countries["Morocco"] = "MA"; -Countries["Monaco"] = "MC"; -Countries["Mongolia"] = "MN"; -Countries["Mozambique"] = "MZ"; -Countries["Myanmar"] = "MM"; -Countries["Namibia"] = "NA"; -Countries["Nauru"] = "NR"; -Countries["Nepal"] = "NP"; -Countries["Netherlands"] = "NL"; -Countries["Netherlands Antilles"] = "AN"; -Countries["New Caledonia"] = "NC"; -Countries["New Zealand"] = "NZ"; -Countries["Nicaragua"] = "NI"; -Countries["Niger"] = "NE"; -Countries["Nigeria"] = "NG"; -Countries["Niue"] = "NU"; -Countries["Norfolk Island"] = "NF"; -Countries["Northern Mariana Islands"] = "MP"; -Countries["Norway"] = "NO"; -Countries["Oman"] = "OM"; -Countries["Pakistan"] = "PK"; -Countries["Palau"] = "PW"; -Countries["Panama"] = "PA"; -Countries["Papua New Guinea"] = "PG"; -Countries["Paraguay"] = "PY"; -Countries["Peru"] = "PE"; -Countries["Philippines"] = "PH"; -Countries["Pitcairn"] = "PN"; -Countries["Poland"] = "PL"; -Countries["Portugal"] = "PT"; -Countries["Puerto Rico"] = "PR"; -Countries["Qatar"] = "QA"; -Countries["Reunion"] = "RE"; -Countries["Romania"] = "RO"; -Countries["Russian Federation"] = "RU"; -Countries["Russia"] = "RU"; -Countries["Rwanda"] = "RW"; -Countries["Saint Kitts and Nevis"] = "KN"; -Countries["Saint Lucia"] = "LC"; -Countries["Saint Vincent and The Grenadines"] = "VC"; -Countries["Samoa"] = "WS"; -Countries["San Marino"] = "SM"; -Countries["Sao Tome and Principe"] = "ST"; -Countries["Saudi Arabia"] = "SA"; -Countries["Senegal"] = "SN"; -Countries["Seychelles"] = "SC"; -Countries["Sierra Leone"] = "SL"; -Countries["Singapore"] = "SG"; -Countries["Slovenia"] = "SI"; -Countries["Solomon Islands"] = "SB"; -Countries["Somalia"] = "SO"; -Countries["South Africa"] = "ZA"; -Countries["Spain"] = "ES"; -Countries["Sri Lanka"] = "LK"; -Countries["Sudan"] = "SD"; -Countries["Suriname"] = "SR"; -Countries["Swaziland"] = "SZ"; -Countries["Sweden"] = "SE"; -Countries["Switzerland"] = "CH"; -Countries["Syrian Arab Republic"] = "SY"; -Countries["Tajikistan"] = "TJ"; -Countries["Tanzania, United Republic of"] = "TZ"; -Countries["Thailand"] = "TH"; -Countries["Togo"] = "TG"; -Countries["Tokelau"] = "TK"; -Countries["Tonga"] = "TO"; -Countries["Trinidad and Tobago"] = "TT"; -Countries["Tunisia"] = "TN"; -Countries["Turkey"] = "TR"; -Countries["Turkmenistan"] = "TM"; -Countries["Turks and Caicos Islands"] = "TC"; -Countries["Tuvalu"] = "TV"; -Countries["Uganda"] = "UG"; -Countries["Ukraine"] = "UA"; -Countries["United Arab Emirates"] = "AE"; -Countries["UK"] = "GB"; -Countries["US"] = "US"; -Countries["United States Minor Outlying Islands"] = "UM"; -Countries["Uruguay"] = "UY"; -Countries["Uzbekistan"] = "UZ"; -Countries["Vanuatu"] = "VU"; -Countries["Vatican City State (Holy See)"] = "VA"; -Countries["Venezuela"] = "VE"; -Countries["Viet Nam"] = "VN"; -Countries["Western Sahara"] = "EH"; -Countries["Yemen"] = "YE"; -Countries["Zambia"] = "ZM"; -Countries["Zimbabwe"] = "ZW"; -Countries["Taiwan"] = "TW"; -Countries["[Worldwide]"] = "XW"; -Countries["Europe"] = "XE"; -Countries["Soviet Union (historical, 1922-1991)"] = "SU"; -Countries["East Germany (historical, 1949-1990)"] = "XG"; -Countries["Czechoslovakia (historical, 1918-1992)"] = "XC"; -Countries["Congo, The Democratic Republic of the"] = "CD"; -Countries["Slovakia"] = "SK"; -Countries["Bosnia and Herzegovina"] = "BA"; -Countries["Korea (North), Democratic People's Republic of"] = "KP"; -Countries["North Korea"] = "KP"; -Countries["Korea (South), Republic of"] = "KR"; -Countries["South Korea"] = "KR"; -Countries["Montenegro"] = "ME"; -Countries["South Georgia and the South Sandwich Islands"] = "GS"; -Countries["Palestinian Territory"] = "PS"; -Countries["Macao"] = "MO"; -Countries["Timor-Leste"] = "TL"; -Countries["<85>land Islands"] = "AX"; -Countries["Guernsey"] = "GG"; -Countries["Isle of Man"] = "IM"; -Countries["Jersey"] = "JE"; -Countries["Serbia"] = "RS"; -Countries["Saint Barthélemy"] = "BL"; -Countries["Saint Martin"] = "MF"; -Countries["Moldova"] = "MD"; -Countries["Yugoslavia (historical, 1918-2003)"] = "YU"; -Countries["Serbia and Montenegro (historical, 2003-2006)"] = "CS"; -Countries["Côte d'Ivoire"] = "CI"; -Countries["Heard Island and McDonald Islands"] = "HM"; -Countries["Iran, Islamic Republic of"] = "IR"; -Countries["Saint Pierre and Miquelon"] = "PM"; -Countries["Saint Helena"] = "SH"; -Countries["Svalbard and Jan Mayen"] = "SJ"; +Countries['Afghanistan'] = 'AF'; +Countries['Albania'] = 'AL'; +Countries['Algeria'] = 'DZ'; +Countries['American Samoa'] = 'AS'; +Countries['Andorra'] = 'AD'; +Countries['Angola'] = 'AO'; +Countries['Anguilla'] = 'AI'; +Countries['Antarctica'] = 'AQ'; +Countries['Antigua and Barbuda'] = 'AG'; +Countries['Argentina'] = 'AR'; +Countries['Armenia'] = 'AM'; +Countries['Aruba'] = 'AW'; +Countries['Australia'] = 'AU'; +Countries['Austria'] = 'AT'; +Countries['Azerbaijan'] = 'AZ'; +Countries['Bahamas'] = 'BS'; +Countries['Bahrain'] = 'BH'; +Countries['Bangladesh'] = 'BD'; +Countries['Barbados'] = 'BB'; +Countries['Belarus'] = 'BY'; +Countries['Belgium'] = 'BE'; +Countries['Belize'] = 'BZ'; +Countries['Benin'] = 'BJ'; +Countries['Bermuda'] = 'BM'; +Countries['Bhutan'] = 'BT'; +Countries['Bolivia'] = 'BO'; +Countries['Croatia'] = 'HR'; +Countries['Botswana'] = 'BW'; +Countries['Bouvet Island'] = 'BV'; +Countries['Brazil'] = 'BR'; +Countries['British Indian Ocean Territory'] = 'IO'; +Countries['Brunei Darussalam'] = 'BN'; +Countries['Bulgaria'] = 'BG'; +Countries['Burkina Faso'] = 'BF'; +Countries['Burundi'] = 'BI'; +Countries['Cambodia'] = 'KH'; +Countries['Cameroon'] = 'CM'; +Countries['Canada'] = 'CA'; +Countries['Cape Verde'] = 'CV'; +Countries['Cayman Islands'] = 'KY'; +Countries['Central African Republic'] = 'CF'; +Countries['Chad'] = 'TD'; +Countries['Chile'] = 'CL'; +Countries['China'] = 'CN'; +Countries['Christmas Island'] = 'CX'; +Countries['Cocos (Keeling) Islands'] = 'CC'; +Countries['Colombia'] = 'CO'; +Countries['Comoros'] = 'KM'; +Countries['Congo'] = 'CG'; +Countries['Cook Islands'] = 'CK'; +Countries['Costa Rica'] = 'CR'; +Countries['Virgin Islands, British'] = 'VG'; +Countries['Cuba'] = 'CU'; +Countries['Cyprus'] = 'CY'; +Countries['Czech Republic'] = 'CZ'; +Countries['Denmark'] = 'DK'; +Countries['Djibouti'] = 'DJ'; +Countries['Dominica'] = 'DM'; +Countries['Dominican Republic'] = 'DO'; +Countries['Ecuador'] = 'EC'; +Countries['Egypt'] = 'EG'; +Countries['El Salvador'] = 'SV'; +Countries['Equatorial Guinea'] = 'GQ'; +Countries['Eritrea'] = 'ER'; +Countries['Estonia'] = 'EE'; +Countries['Ethiopia'] = 'ET'; +Countries['Falkland Islands (Malvinas)'] = 'FK'; +Countries['Faroe Islands'] = 'FO'; +Countries['Fiji'] = 'FJ'; +Countries['Finland'] = 'FI'; +Countries['France'] = 'FR'; +Countries['French Guiana'] = 'GF'; +Countries['French Polynesia'] = 'PF'; +Countries['French Southern Territories'] = 'TF'; +Countries['Gabon'] = 'GA'; +Countries['Gambia'] = 'GM'; +Countries['Georgia'] = 'GE'; +Countries['Germany'] = 'DE'; +Countries['Ghana'] = 'GH'; +Countries['Gibraltar'] = 'GI'; +Countries['Greece'] = 'GR'; +Countries['Greenland'] = 'GL'; +Countries['Grenada'] = 'GD'; +Countries['Guadeloupe'] = 'GP'; +Countries['Guam'] = 'GU'; +Countries['Guatemala'] = 'GT'; +Countries['Guinea'] = 'GN'; +Countries['Guinea-Bissau'] = 'GW'; +Countries['Guyana'] = 'GY'; +Countries['Haiti'] = 'HT'; +Countries['Virgin Islands, U.S.'] = 'VI'; +Countries['Honduras'] = 'HN'; +Countries['Hong Kong'] = 'HK'; +Countries['Hungary'] = 'HU'; +Countries['Iceland'] = 'IS'; +Countries['India'] = 'IN'; +Countries['Indonesia'] = 'ID'; +Countries['Wallis and Futuna'] = 'WF'; +Countries['Iraq'] = 'IQ'; +Countries['Ireland'] = 'IE'; +Countries['Israel'] = 'IL'; +Countries['Italy'] = 'IT'; +Countries['Jamaica'] = 'JM'; +Countries['Japan'] = 'JP'; +Countries['Jordan'] = 'JO'; +Countries['Kazakhstan'] = 'KZ'; +Countries['Kenya'] = 'KE'; +Countries['Kiribati'] = 'KI'; +Countries['Kuwait'] = 'KW'; +Countries['Kyrgyzstan'] = 'KG'; +Countries["Lao People's Democratic Republic"] = 'LA'; +Countries['Latvia'] = 'LV'; +Countries['Lebanon'] = 'LB'; +Countries['Lesotho'] = 'LS'; +Countries['Liberia'] = 'LR'; +Countries['Libyan Arab Jamahiriya'] = 'LY'; +Countries['Liechtenstein'] = 'LI'; +Countries['Lithuania'] = 'LT'; +Countries['Luxembourg'] = 'LU'; +Countries['Montserrat'] = 'MS'; +Countries['Macedonia, The Former Yugoslav Republic of'] = 'MK'; +Countries['Madagascar'] = 'MG'; +Countries['Malawi'] = 'MW'; +Countries['Malaysia'] = 'MY'; +Countries['Maldives'] = 'MV'; +Countries['Mali'] = 'ML'; +Countries['Malta'] = 'MT'; +Countries['Marshall Islands'] = 'MH'; +Countries['Martinique'] = 'MQ'; +Countries['Mauritania'] = 'MR'; +Countries['Mauritius'] = 'MU'; +Countries['Mayotte'] = 'YT'; +Countries['Mexico'] = 'MX'; +Countries['Micronesia, Federated States of'] = 'FM'; +Countries['Morocco'] = 'MA'; +Countries['Monaco'] = 'MC'; +Countries['Mongolia'] = 'MN'; +Countries['Mozambique'] = 'MZ'; +Countries['Myanmar'] = 'MM'; +Countries['Namibia'] = 'NA'; +Countries['Nauru'] = 'NR'; +Countries['Nepal'] = 'NP'; +Countries['Netherlands'] = 'NL'; +Countries['Netherlands Antilles'] = 'AN'; +Countries['New Caledonia'] = 'NC'; +Countries['New Zealand'] = 'NZ'; +Countries['Nicaragua'] = 'NI'; +Countries['Niger'] = 'NE'; +Countries['Nigeria'] = 'NG'; +Countries['Niue'] = 'NU'; +Countries['Norfolk Island'] = 'NF'; +Countries['Northern Mariana Islands'] = 'MP'; +Countries['Norway'] = 'NO'; +Countries['Oman'] = 'OM'; +Countries['Pakistan'] = 'PK'; +Countries['Palau'] = 'PW'; +Countries['Panama'] = 'PA'; +Countries['Papua New Guinea'] = 'PG'; +Countries['Paraguay'] = 'PY'; +Countries['Peru'] = 'PE'; +Countries['Philippines'] = 'PH'; +Countries['Pitcairn'] = 'PN'; +Countries['Poland'] = 'PL'; +Countries['Portugal'] = 'PT'; +Countries['Puerto Rico'] = 'PR'; +Countries['Qatar'] = 'QA'; +Countries['Reunion'] = 'RE'; +Countries['Romania'] = 'RO'; +Countries['Russian Federation'] = 'RU'; +Countries['Russia'] = 'RU'; +Countries['Rwanda'] = 'RW'; +Countries['Saint Kitts and Nevis'] = 'KN'; +Countries['Saint Lucia'] = 'LC'; +Countries['Saint Vincent and The Grenadines'] = 'VC'; +Countries['Samoa'] = 'WS'; +Countries['San Marino'] = 'SM'; +Countries['Sao Tome and Principe'] = 'ST'; +Countries['Saudi Arabia'] = 'SA'; +Countries['Senegal'] = 'SN'; +Countries['Seychelles'] = 'SC'; +Countries['Sierra Leone'] = 'SL'; +Countries['Singapore'] = 'SG'; +Countries['Slovenia'] = 'SI'; +Countries['Solomon Islands'] = 'SB'; +Countries['Somalia'] = 'SO'; +Countries['South Africa'] = 'ZA'; +Countries['Spain'] = 'ES'; +Countries['Sri Lanka'] = 'LK'; +Countries['Sudan'] = 'SD'; +Countries['Suriname'] = 'SR'; +Countries['Swaziland'] = 'SZ'; +Countries['Sweden'] = 'SE'; +Countries['Switzerland'] = 'CH'; +Countries['Syrian Arab Republic'] = 'SY'; +Countries['Tajikistan'] = 'TJ'; +Countries['Tanzania, United Republic of'] = 'TZ'; +Countries['Thailand'] = 'TH'; +Countries['Togo'] = 'TG'; +Countries['Tokelau'] = 'TK'; +Countries['Tonga'] = 'TO'; +Countries['Trinidad and Tobago'] = 'TT'; +Countries['Tunisia'] = 'TN'; +Countries['Turkey'] = 'TR'; +Countries['Turkmenistan'] = 'TM'; +Countries['Turks and Caicos Islands'] = 'TC'; +Countries['Tuvalu'] = 'TV'; +Countries['Uganda'] = 'UG'; +Countries['Ukraine'] = 'UA'; +Countries['United Arab Emirates'] = 'AE'; +Countries['UK'] = 'GB'; +Countries['US'] = 'US'; +Countries['United States Minor Outlying Islands'] = 'UM'; +Countries['Uruguay'] = 'UY'; +Countries['Uzbekistan'] = 'UZ'; +Countries['Vanuatu'] = 'VU'; +Countries['Vatican City State (Holy See)'] = 'VA'; +Countries['Venezuela'] = 'VE'; +Countries['Viet Nam'] = 'VN'; +Countries['Western Sahara'] = 'EH'; +Countries['Yemen'] = 'YE'; +Countries['Zambia'] = 'ZM'; +Countries['Zimbabwe'] = 'ZW'; +Countries['Taiwan'] = 'TW'; +Countries['[Worldwide]'] = 'XW'; +Countries['Europe'] = 'XE'; +Countries['Soviet Union (historical, 1922-1991)'] = 'SU'; +Countries['East Germany (historical, 1949-1990)'] = 'XG'; +Countries['Czechoslovakia (historical, 1918-1992)'] = 'XC'; +Countries['Congo, The Democratic Republic of the'] = 'CD'; +Countries['Slovakia'] = 'SK'; +Countries['Bosnia and Herzegovina'] = 'BA'; +Countries["Korea (North), Democratic People's Republic of"] = 'KP'; +Countries['North Korea'] = 'KP'; +Countries['Korea (South), Republic of'] = 'KR'; +Countries['South Korea'] = 'KR'; +Countries['Montenegro'] = 'ME'; +Countries['South Georgia and the South Sandwich Islands'] = 'GS'; +Countries['Palestinian Territory'] = 'PS'; +Countries['Macao'] = 'MO'; +Countries['Timor-Leste'] = 'TL'; +Countries['<85>land Islands'] = 'AX'; +Countries['Guernsey'] = 'GG'; +Countries['Isle of Man'] = 'IM'; +Countries['Jersey'] = 'JE'; +Countries['Serbia'] = 'RS'; +Countries['Saint Barthélemy'] = 'BL'; +Countries['Saint Martin'] = 'MF'; +Countries['Moldova'] = 'MD'; +Countries['Yugoslavia (historical, 1918-2003)'] = 'YU'; +Countries['Serbia and Montenegro (historical, 2003-2006)'] = 'CS'; +Countries["Côte d'Ivoire"] = 'CI'; +Countries['Heard Island and McDonald Islands'] = 'HM'; +Countries['Iran, Islamic Republic of'] = 'IR'; +Countries['Saint Pierre and Miquelon'] = 'PM'; +Countries['Saint Helena'] = 'SH'; +Countries['Svalbard and Jan Mayen'] = 'SJ'; diff --git a/mb_discids_detector.user.js b/mb_discids_detector.user.js index 3bbf207..ba036cd 100644 --- a/mb_discids_detector.user.js +++ b/mb_discids_detector.user.js @@ -23,166 +23,193 @@ this.$ = this.jQuery = jQuery.noConflict(true); 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"; - -$(document).ready(function () { +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() { 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(); } else if (window.location.host.match(/avaxhome\.ws/)) { avaxHomePageHandler(); } - }); function avaxHomePageHandler() { - // Find artist and release titles - var artistName = ""; - var releaseName = ""; - var m = $('div.title h1').text().match(/(.*) (?:-|–) (.*)( \(\d{4}\))?/); + let artistName = ''; + let releaseName = ''; + let m = $('div.title h1') + .text() + .match(/(.*) (?:-|–) (.*)( \(\d{4}\))?/); if (m) { artistName = m[1]; releaseName = m[2]; } - if (artistName == "VA") artistName = "Various Artists"; + if (artistName == 'VA') artistName = 'Various Artists'; // Find and analyze EAC log - $('div.spoiler').filter(function () { - return $(this).find('a').text().match(/(EAC|log)/i); - }) + $('div.spoiler') + .filter(function() { + return $(this) + .find('a') + .text() + .match(/(EAC|log)/i); + }) .find('div') - .each(function () { - - var $eacLog = $(this); - var discs = analyze_log_files($eacLog); + .each(function() { + let $eacLog = $(this); + let discs = analyze_log_files($eacLog); // Check and display - check_and_display_discs(artistName, releaseName, discs, - function (mb_toc_numbers, discid, discNumber) { - $eacLog.parents('div.spoiler').prevAll('div.center:first').append('
    ' + (discs.length > 1 ? 'Disc ' + discNumber + ': ' : '' ) + 'MB DiscId '); + check_and_display_discs( + artistName, + releaseName, + discs, + function(mb_toc_numbers, discid, discNumber) { + $eacLog + .parents('div.spoiler') + .prevAll('div.center:first') + .append( + `
    ${discs.length > 1 ? `Disc ${discNumber}: ` : ''}MB DiscId ` + ); }, - function (mb_toc_numbers, discid, discNumber, found) { - var url = computeAttachURL(mb_toc_numbers, artistName, releaseName); - var html = '' + discid + ''; + function(mb_toc_numbers, discid, discNumber, found) { + let url = computeAttachURL(mb_toc_numbers, artistName, releaseName); + let html = `${discid}`; if (found) { - html = html + ''; + html = `${html}`; } - $('#' + discid.replace('.', '\\.')).html(html); + $(`#${discid.replace('.', '\\.')}`).html(html); } ); - }); } function gazellePageHandler() { - - var serverHost = window.location.host; + let serverHost = window.location.host; // Determine Artist name and Release title - var titleAndArtists = $("#content div.thin h2:eq(0)").text(); - var pattern = /(.*) - (.*) \[.*\] \[.*/; - var artistName, releaseName; - if (m = titleAndArtists.match(pattern)) { + let titleAndArtists = $('#content div.thin h2:eq(0)').text(); + let pattern = /(.*) - (.*) \[.*\] \[.*/; + let artistName, releaseName; + if ((m = titleAndArtists.match(pattern))) { artistName = m[1]; releaseName = m[2]; } - LOGGER.debug("artist:", artistName, "- releaseName:", releaseName); + LOGGER.debug('artist:', artistName, '- releaseName:', releaseName); // Parse each torrent - $('tr.group_torrent').filter(function () { - return $(this).attr("id"); - }).each(function () { - var torrentInfo = $(this).next(); + $('tr.group_torrent') + .filter(function() { + return $(this).attr('id'); + }) + .each(function() { + let 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 () { - LOGGER.debug("Log link", this); - if ($(this).attr("onclick").match(/show_logs/)) { - if (window.location.host.match(/apollo/)) { - LOGGER.debug("Apollo"); - var logAction = 'viewlog'; - } else if (window.location.host.match(/redacted|passtheheadphones/)){ - LOGGER.debug("RED"); - var logAction = 'loglist'; + $(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/)) { + LOGGER.debug('Apollo'); + var logAction = 'viewlog'; + } else if (window.location.host.match(/redacted|passtheheadphones/)) { + LOGGER.debug('RED'); + var logAction = 'loglist'; + } } - } - // LzTR - else if ($(this).attr("onclick").match(/get_log/)) { - LOGGER.debug("LzTR"); - var logAction = 'log_ajax'; - } - // NotWhat.CD - else if ($(this).attr("onclick").match(/show_log/)) { - LOGGER.debug("NotWhat.CD"); - var logAction = 'viewlog'; - } else { - return true; - } - var targetContainer = $(this).parents(".linkbox"); - var torrentId = /(show_logs|get_log|show_log)\('(\d+)/.exec($(this).attr('onclick'))[2]; - var logUrl = '/torrents.php?action=' + logAction + '&torrentid=' + torrentId; - LOGGER.info("Log URL: ", logUrl); - LOGGER.debug("targetContainer: ", targetContainer); + // LzTR + else if ( + $(this) + .attr('onclick') + .match(/get_log/) + ) { + LOGGER.debug('LzTR'); + var logAction = 'log_ajax'; + } + // NotWhat.CD + else if ( + $(this) + .attr('onclick') + .match(/show_log/) + ) { + LOGGER.debug('NotWhat.CD'); + var logAction = 'viewlog'; + } else { + return true; + } + let targetContainer = $(this).parents('.linkbox'); + let torrentId = /(show_logs|get_log|show_log)\('(\d+)/.exec($(this).attr('onclick'))[2]; + let logUrl = `/torrents.php?action=${logAction}&torrentid=${torrentId}`; + LOGGER.info('Log URL: ', logUrl); + LOGGER.debug('targetContainer: ', targetContainer); - // Get log content - $.get(logUrl, - function (data) { - LOGGER.debug("Log content", $(data).find('pre')); - var discs = analyze_log_files($(data).find('pre')); - LOGGER.debug("Number of disc found", discs.length); - check_and_display_discs(artistName, releaseName, discs, - function (mb_toc_numbers, discid, discNumber) { - targetContainer.append('
    ' + (discs.length > 1 ? 'Disc ' + discNumber + ': ' : '' ) + 'MB DiscId: '); + // Get log content + $.get(logUrl, function(data) { + LOGGER.debug('Log content', $(data).find('pre')); + let discs = analyze_log_files($(data).find('pre')); + LOGGER.debug('Number of disc found', discs.length); + check_and_display_discs( + artistName, + releaseName, + discs, + function(mb_toc_numbers, discid, discNumber) { + targetContainer.append( + `
    ${ + discs.length > 1 ? `Disc ${discNumber}: ` : '' + }MB DiscId: ` + ); }, - function (mb_toc_numbers, discid, discNumber, found) { - var url = computeAttachURL(mb_toc_numbers, artistName, releaseName); - var html = '' + discid + ''; + function(mb_toc_numbers, discid, discNumber, found) { + let url = computeAttachURL(mb_toc_numbers, artistName, releaseName); + let html = `${discid}`; if (found) { - html = html + ''; + html = `${html}`; } - LOGGER.debug('#' + torrentId + '_disc' + discNumber); - $('#' + torrentId + '_disc' + discNumber).html(html); + LOGGER.debug(`#${torrentId}_disc${discNumber}`); + $(`#${torrentId}_disc${discNumber}`).html(html); } ); - } - ); - - } - ); - }); + }); + }); + }); } - // Common functions function computeAttachURL(mb_toc_numbers, artistName, releaseName) { - var url = 'http://musicbrainz.org/cdtoc/attach' - + '?toc=' + mb_toc_numbers.join("%20") - + '&artist-name=' + encodeURIComponent(artistName) - + '&release-name=' + encodeURIComponent(releaseName); + let url = `${'http://musicbrainz.org/cdtoc/attach' + '?toc='}${mb_toc_numbers.join('%20')}&artist-name=${encodeURIComponent( + artistName + )}&release-name=${encodeURIComponent(releaseName)}`; return url; } function analyze_log_files(log_files) { - var discs = []; - $.each(log_files, function (i, log_file) { - var discsInLog = MBDiscid.log_input_to_entries($(log_file).text()); + let discs = []; + $.each(log_files, function(i, log_file) { + let discsInLog = MBDiscid.log_input_to_entries($(log_file).text()); for (var i = 0; i < discsInLog.length; i++) { discs.push(discsInLog[i]); } }); // Remove dupes discs - var keys = new Object(); - var uniqueDiscs = new Array(); - for (var i = 0; i < discs.length; i++) { - var discid = MBDiscid.calculate_mb_discid(discs[i]); + let keys = new Object(); + let uniqueDiscs = new Array(); + for (let i = 0; i < discs.length; i++) { + let discid = MBDiscid.calculate_mb_discid(discs[i]); if (discid in keys) { continue; } else { @@ -195,26 +222,24 @@ function analyze_log_files(log_files) { } function check_and_display_discs(artistName, releaseName, discs, displayDiscHandler, displayResultHandler) { - // For each disc, check if it's in MusicBrainz database - for (var i = 0; i < discs.length; i++) { - var entries = discs[i]; - var discNumber = i + 1; + for (let i = 0; i < discs.length; i++) { + let entries = discs[i]; + let discNumber = i + 1; if (entries.length > 0) { - - var mb_toc_numbers = MBDiscid.calculate_mb_toc_numbers(entries); - var discid = MBDiscid.calculate_mb_discid(entries); - LOGGER.info("Computed discid :" + discid); + let mb_toc_numbers = MBDiscid.calculate_mb_toc_numbers(entries); + let discid = MBDiscid.calculate_mb_discid(entries); + LOGGER.info(`Computed discid :${discid}`); displayDiscHandler(mb_toc_numbers, discid, discNumber); // Now check if this discid is known by MusicBrainz - (function (discid, discNumber, mb_toc_numbers) { - var query = $.getJSON('//musicbrainz.org/ws/2/discid/' + discid + '?cdstubs=no'); - query.done(function (data) { - var existsInMusicbrainz = !('error' in data) && data.error != "Not found"; + (function(discid, discNumber, mb_toc_numbers) { + let query = $.getJSON(`//musicbrainz.org/ws/2/discid/${discid}?cdstubs=no`); + query.done(function(data) { + let existsInMusicbrainz = !('error' in data) && data.error != 'Not found'; 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 displayResultHandler(mb_toc_numbers, discid, discNumber, false); }); @@ -229,30 +254,29 @@ function check_and_display_discs(artistName, releaseName, discs, displayDiscHand // Copyright 2010, kolen // Released under the MIT License -var MBDiscid = (function () { - +var MBDiscid = (function() { this.SECTORS_PER_SECOND = 75; this.PREGAP = 150; this.DATA_TRACK_GAP = 11400; this.toc_entry_matcher = new RegExp( - "^\\s*" + - "(\\d+)" + // 1 - track number - "\\s*\\|\\s*" + - "([0-9:.]+)" + // 2 - time start - "\\s*\\|\\s*" + - "([0-9:.]+)" + // 3 - time length - "\\s*\\|\\s*" + - "(\\d+)" + // 4 - start sector - "\\s*\\|\\s*" + - "(\\d+)" + // 5 - end sector - "\\s*$" + '^\\s*' + + '(\\d+)' + // 1 - track number + '\\s*\\|\\s*' + + '([0-9:.]+)' + // 2 - time start + '\\s*\\|\\s*' + + '([0-9:.]+)' + // 3 - time length + '\\s*\\|\\s*' + + '(\\d+)' + // 4 - start sector + '\\s*\\|\\s*' + + '(\\d+)' + // 5 - end sector + '\\s*$' ); - this.log_input_to_entries = function (text) { - var discs = []; + this.log_input_to_entries = function(text) { + let discs = []; var entries = []; - $.each(text.split("\n"), function (index, value) { - var m = toc_entry_matcher.exec(value); + $.each(text.split('\n'), function(index, value) { + let m = toc_entry_matcher.exec(value); if (m) { // New disc if (parseInt(m[1], 10) == 1) { @@ -268,11 +292,11 @@ var MBDiscid = (function () { discs.push(entries); } - for (var i = 0; i < discs.length; i++) { + for (let i = 0; i < discs.length; i++) { var entries = discs[i]; - var layout_type = get_layout_type(entries); + let layout_type = get_layout_type(entries); var entries_audio; - if (layout_type == "with_data") { + if (layout_type == 'with_data') { entries_audio = entries.slice(0, entries.length - 1); } else { entries_audio = entries; @@ -282,15 +306,15 @@ var MBDiscid = (function () { return discs; }; - this.get_layout_type = function (entries) { - var type = "standard"; - for (var i = 0; i < entries.length - 1; i++) { - var gap = parseInt(entries[i + 1][4], 10) - parseInt(entries[i][5], 10) - 1; + this.get_layout_type = function(entries) { + let type = 'standard'; + for (let i = 0; i < entries.length - 1; i++) { + let gap = parseInt(entries[i + 1][4], 10) - parseInt(entries[i][5], 10) - 1; if (gap != 0) { if (i == entries.length - 2 && gap == DATA_TRACK_GAP) { - type = "with_data"; + type = 'with_data'; } else { - type = "unknown"; + type = 'unknown'; break; } } @@ -298,84 +322,91 @@ var MBDiscid = (function () { return type; }; - this.calculate_mb_toc_numbers = function (entries) { + this.calculate_mb_toc_numbers = function(entries) { if (entries.length == 0) { 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 [1, entries.length, leadout_offset].concat(offsets); }; - this.calculate_cddb_id = function (entries) { - var sum_of_digits = function (n) { - var sum = 0; + this.calculate_cddb_id = function(entries) { + let sum_of_digits = function(n) { + let sum = 0; while (n > 0) { sum = sum + (n % 10); n = Math.floor(n / 10); } return sum; - } + }; - var decimalToHexString = function (number) { + let decimalToHexString = function(number) { if (number < 0) { - number = 0xFFFFFFFF + number + 1; + number = 0xffffffff + number + 1; } 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); - var checksum = 0; - $.each(entries, function (index, entry) { + let length_seconds = Math.floor( + (parseInt(entries[entries.length - 1][5], 10) - parseInt(entries[0][4], 10) + 1) / SECTORS_PER_SECOND + ); + let checksum = 0; + $.each(entries, function(index, entry) { checksum += sum_of_digits(Math.floor((parseInt(entry[4], 10) + PREGAP) / SECTORS_PER_SECOND)); - }) + }); - var xx = checksum % 255; - var discid_num = (xx << 24) | (length_seconds << 8) | entries.length; + let xx = checksum % 255; + let discid_num = (xx << 24) | (length_seconds << 8) | entries.length; //return discid_num return decimalToHexString(discid_num); }; - this.calculate_mb_discid = function (entries) { - - var hex_left_pad = function (input, totalChars) { - input = '' + parseInt(input, 10).toString(16).toUpperCase(); - var padWith = "0"; + this.calculate_mb_discid = function(entries) { + let hex_left_pad = function(input, totalChars) { + input = `${parseInt(input, 10) + .toString(16) + .toUpperCase()}`; + let padWith = '0'; if (input.length < totalChars) { while (input.length < totalChars) { input = padWith + input; } } else { } - if (input.length > totalChars) { //if padWith was a multiple character string and num was overpadded - input = input.substring((input.length - totalChars), totalChars); + if (input.length > totalChars) { + //if padWith was a multiple character string and num was overpadded + input = input.substring(input.length - totalChars, totalChars); } else { } return input; }; - var mb_toc_numbers = calculate_mb_toc_numbers(entries); - var message = ""; - var first_track = mb_toc_numbers[0]; - var last_track = mb_toc_numbers[1]; - var leadout_offset = mb_toc_numbers[2]; + let mb_toc_numbers = calculate_mb_toc_numbers(entries); + let message = ''; + let first_track = mb_toc_numbers[0]; + let last_track = mb_toc_numbers[1]; + let leadout_offset = mb_toc_numbers[2]; message = message + hex_left_pad(first_track, 2); message = message + hex_left_pad(last_track, 2); message = message + hex_left_pad(leadout_offset, 8); - for (var i = 0; i < 99; i++) { - var offset = (i + 3 < mb_toc_numbers.length) ? mb_toc_numbers[i + 3] : 0; + for (let i = 0; i < 99; i++) { + let offset = i + 3 < mb_toc_numbers.length ? mb_toc_numbers[i + 3] : 0; message = message + hex_left_pad(offset, 8); } - b64pad = "="; - var discid = b64_sha1(message); - discid = discid.replace(/\+/g, ".").replace(/\//g, "_").replace(/=/g, "-"); + b64pad = '='; + let discid = b64_sha1(message); + discid = discid + .replace(/\+/g, '.') + .replace(/\//g, '_') + .replace(/=/g, '-'); return discid; }; diff --git a/mb_relationship_shortcuts.user.js b/mb_relationship_shortcuts.user.js index ed54aac..82d1e69 100644 --- a/mb_relationship_shortcuts.user.js +++ b/mb_relationship_shortcuts.user.js @@ -14,38 +14,38 @@ // Definitions: relations-type and corresponding icons we are going to treat var relationsIconsURLs = { - 'url': { - "amazon asin": "https://musicbrainz.org/static/images/favicons/amazon-32.png", - "discogs": "https://musicbrainz.org/static/images/favicons/discogs-32.png", - "wikidata": "https://musicbrainz.org/static/images/favicons/wikidata-32.png", - "imdb": "https://musicbrainz.org/static/images/favicons/imdb-32.png", - "creative commons licensed download": "http://creativecommons.org/favicon.ico", - "cover art link": "http://www.cdcovers.cc/favicon.ico", - "secondhandsongs": "https://musicbrainz.org/static/images/favicons/secondhandsongs-32.png", - "lyrics": "http://www.nomy.nu/img/lyrics-icon.gif", - "allmusic": "https://musicbrainz.org/static/images/favicons/allmusic-16.png" + url: { + 'amazon asin': 'https://musicbrainz.org/static/images/favicons/amazon-32.png', + discogs: 'https://musicbrainz.org/static/images/favicons/discogs-32.png', + wikidata: 'https://musicbrainz.org/static/images/favicons/wikidata-32.png', + imdb: 'https://musicbrainz.org/static/images/favicons/imdb-32.png', + 'creative commons licensed download': 'http://creativecommons.org/favicon.ico', + 'cover art link': 'http://www.cdcovers.cc/favicon.ico', + secondhandsongs: 'https://musicbrainz.org/static/images/favicons/secondhandsongs-32.png', + lyrics: 'http://www.nomy.nu/img/lyrics-icon.gif', + allmusic: 'https://musicbrainz.org/static/images/favicons/allmusic-16.png' }, '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': { - "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", + release: { + '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' } }; var otherDatabasesIconURLs = { - "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.worldcat.org": "https://musicbrainz.org/static/images/favicons/worldcat-32.png", - "rateyourmusic.com": "https://musicbrainz.org/static/images/favicons/rateyourmusic-32.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.worldcat.org': 'https://musicbrainz.org/static/images/favicons/worldcat-32.png', + 'rateyourmusic.com': 'https://musicbrainz.org/static/images/favicons/rateyourmusic-32.png' }; var incOptions = { - 'release-group': [ 'release-group-rels', 'url-rels' ], - 'release': [ 'release-rels', 'url-rels', 'discids' ], - 'recording': [ 'work-rels' ], - 'work': [ 'url-rels' ] + 'release-group': ['release-group-rels', 'url-rels'], + release: ['release-rels', 'url-rels', 'discids'], + recording: ['work-rels'], + work: ['url-rels'] }; // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant @@ -53,20 +53,19 @@ this.$ = this.jQuery = jQuery.noConflict(true); if (!unsafeWindow) unsafeWindow = window; -$(document).ready(function(){ - +$(document).ready(function() { // Get pageType (label or artist) - var parent = {}; - var child = {}; - if (m = window.location.href.match("\/artist\/(.{36})[^\/]*$")) { + let parent = {}; + let child = {}; + if ((m = window.location.href.match('/artist/(.{36})[^/]*$'))) { parent.type = 'artist'; parent.mbid = m[1]; 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.mbid = m[2]; 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.mbid = m[1]; child.type = m[2].replace(/s$/, ''); @@ -75,106 +74,132 @@ $(document).ready(function(){ 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 - var columnindex = 0; + let columnindex = 0; $("table.tbl tbody tr[class!='subh']").each(function() { - $(this).children("td").each(function() { - if ($(this).find("a").attr("href") !== undefined && $(this).find("a").attr("href").match(mbidRE)) { return false; } - columnindex++; - }); + $(this) + .children('td') + .each(function() { + if ( + $(this) + .find('a') + .attr('href') !== undefined && + $(this) + .find('a') + .attr('href') + .match(mbidRE) + ) { + return false; + } + columnindex++; + }); return false; }); // Set MBID to row in tables to get easiest fastest access $("table.tbl tr[class!='subh']").each(function() { - var $tr = $(this); + let $tr = $(this); - $tr.children("th:eq("+columnindex+")").after("Relationships"); - $tr.children("td:eq("+columnindex+")").after(""); + $tr.children(`th:eq(${columnindex})`).after("Relationships"); + $tr.children(`td:eq(${columnindex})`).after(""); - $(this).find("a").each(function() { - var href = $(this).attr("href"); - if (m = href.match(mbidRE)) { - $tr.attr("id", m[2]); - return false; - } - }); + $(this) + .find('a') + .each(function() { + let href = $(this).attr('href'); + if ((m = href.match(mbidRE))) { + $tr.attr('id', m[2]); + return false; + } + }); }); // Calculate offset for multi-page lists - var page = 1; - if (m = window.location.href.match("[\?&]page=([0-9]*)")) { + let page = 1; + if ((m = window.location.href.match('[?&]page=([0-9]*)'))) { page = m[1]; } - var offset = (page - 1) * 100; + let offset = (page - 1) * 100; // 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); $.get(url, function(data, textStatus, jqXHR) { - // Parse each child - $(data).find(child.type).each(function() { - var mbid = $(this).attr("id"); + $(data) + .find(child.type) + .each(function() { + let mbid = $(this).attr('id'); - // URL relationships - $(this).find("relation-list[target-type='url'] relation").each(function() { - var reltype = $(this).attr("type"); - var target = $(this).children("target").text(); - if (relationsIconsURLs.url.hasOwnProperty(reltype)) { - $("#" + mbid + " td.relationships").append( - "" + " " + "" - ); - } - else for (var rel in otherDatabasesIconURLs) { - if (target.indexOf(rel) != -1 ) { - $("#" + mbid + " td.relationships").append( - "" + " " + "" - ); - } - } - }); + // URL relationships + $(this) + .find("relation-list[target-type='url'] relation") + .each(function() { + let reltype = $(this).attr('type'); + let target = $(this) + .children('target') + .text(); + if (relationsIconsURLs.url.hasOwnProperty(reltype)) { + $(`#${mbid} td.relationships`).append( + `` + + ` ` + + `` + ); + } else + for (let rel in otherDatabasesIconURLs) { + if (target.indexOf(rel) != -1) { + $(`#${mbid} td.relationships`).append( + `` + + ` ` + + `` + ); + } + } + }); - // Other relationships - $(this).find("relation-list[target-type!='url']").each(function() { - var targettype = $(this).attr("target-type").replace("release_group", "release-group"); - var relations = {}; + // Other relationships + $(this) + .find("relation-list[target-type!='url']") + .each(function() { + let targettype = $(this) + .attr('target-type') + .replace('release_group', 'release-group'); + let relations = {}; - if (relationsIconsURLs[targettype] === undefined) { - return; - } + if (relationsIconsURLs[targettype] === undefined) { + return; + } - $(this).children("relation").each(function() { - var reltype = $(this).attr("type"); - var target = $(this).children("target").text(); - var url = (targettype == 'url') ? target : "/" + targettype + "/" + target; + $(this) + .children('relation') + .each(function() { + 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]; + else relations[reltype].push(url); + } + }); - if (!relations.hasOwnProperty(reltype)) relations[reltype] = [url]; - else relations[reltype].push(url); - } - }); - - $.each(relations, function(reltype, urls) { - var html = ""; - if (urls.length < -1) { - html += "(" + urls.length + ") "; - } else { - $.each(urls, function(index, url) { - html += " "; + $.each(relations, function(reltype, urls) { + let html = ''; + if (urls.length < -1) { + html += `(${urls.length}) `; + } else { + $.each(urls, function(index, url) { + html += ` `; + }); + } + $(`#${mbid} td.relationships`).append(html); }); - } - $("#" + mbid + " td.relationships").append(html); - - }); + }); }); - - }); - }); - }); diff --git a/mb_ui_enhancements.user.js b/mb_ui_enhancements.user.js index a5490dc..9b19c76 100644 --- a/mb_ui_enhancements.user.js +++ b/mb_ui_enhancements.user.js @@ -14,114 +14,149 @@ // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant this.$ = this.jQuery = jQuery.noConflict(true); -$(document).ready(function () { +$(document).ready(function() { LASTFM_APIKEY = null; // Highlight table rows $('table.tbl tbody tr').hover( - function () { - $(this).children('td').each(function(){ - var backgroundColor = $(this).css("backgroundColor"); - if (backgroundColor != 'rgb(255, 255, 0)') - $(this).css("backgroundColor", "#ffeea8"); - }); + function() { + $(this) + .children('td') + .each(function() { + let backgroundColor = $(this).css('backgroundColor'); + if (backgroundColor != 'rgb(255, 255, 0)') $(this).css('backgroundColor', '#ffeea8'); + }); }, - function () { - $(this).children('td').each(function(){ - var backgroundColor = $(this).css("backgroundColor"); - if (backgroundColor != 'rgb(255, 255, 0)') - $(this).css("backgroundColor", ""); - }); + function() { + $(this) + .children('td') + .each(function() { + let backgroundColor = $(this).css('backgroundColor'); + if (backgroundColor != 'rgb(255, 255, 0)') $(this).css('backgroundColor', ''); + }); } ); - var re; + let re; // 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)) { $('h2.discography').before('

    Top Last.fm recordings

      '); 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) { - $.each(data.toptracks.track, function (index, track) { - if (index >= 5) return true; - var url = track.mbid ? '/recording/'+track.mbid : track.url; - $('ul.toptracks').append('
    • '+track.name+'
    • '); - }); - }); + let toptracks = $.getJSON( + `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; + let url = track.mbid ? `/recording/${track.mbid}` : track.url; + $('ul.toptracks').append(`
    • ${track.name}
    • `); + }); + } + ); } // 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 ($("table.medium thead").length == 1) { - var text = $.trim($("table.medium thead").text()); + if ($('table.medium thead').length == 1) { + let text = $.trim($('table.medium thead').text()); 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 - 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)) { $("#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('External links')").nextAll("ul.external_links").filter( function() { - return !pageHasRGLinks || $(this).nextAll("h2:contains('Release group external links')").length > 0; - })); + $("#sidebar h2:contains('External links')") + .nextAll('ul.external_links') + .filter(function() { + 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')").nextAll("ul.external_links")); + $("#sidebar h2:contains('Rating')").before($("#sidebar h2:contains('Release group external links')").nextAll('ul.external_links')); } // 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)) { $('#sidebar-affiliates').remove(); } // 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)) { - $("form").filter(function() { - return $(this).prop("action").match("merge_queue"); - }).attr("target", "_blank"); + $('form') + .filter(function() { + return $(this) + .prop('action') + .match('merge_queue'); + }) + .attr('target', '_blank'); } // Modify link to edits: remove " - " from the link "Edit XXXX - " - re = new RegExp("musicbrainz\.org/.*/(open_)?edits","i"); + re = new RegExp('musicbrainz.org/.*/(open_)?edits', 'i'); if (window.location.href.match(re)) { - $("div.edit-description ~ h2").each(function() { - var parts = $(this).find("a").text().split(" - "); - $(this).find("a").text(parts[0]); - $(this).append(" - " + parts[1]); + $('div.edit-description ~ h2').each(function() { + let parts = $(this) + .find('a') + .text() + .split(' - '); + $(this) + .find('a') + .text(parts[0]); + $(this).append(` - ${parts[1]}`); }); } // 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)) { $("div.edit-description ~ h2:contains('cover art')").each(function() { - $editdetails = $(this).parents('.edit-header').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("See all artworks for this release"); + $editdetails = $(this) + .parents('.edit-header') + .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(`See all artworks for this release`); }); } // 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)) { - var $youtube_link = $('#sidebar li.youtube-favicon a'); + let $youtube_link = $('#sidebar li.youtube-favicon a'); if ($youtube_link.length > 0) { - var youtube_id = $youtube_link.prop("href").match(/http:\/\/www\.youtube\.com\/watch\?v=(.*)/)[1]; - $("table.details").width("60%"); - $("h2:contains('Relationships')").after(''); + let youtube_id = $youtube_link.prop('href').match(/http:\/\/www\.youtube\.com\/watch\?v=(.*)/)[1]; + $('table.details').width('60%'); + $("h2:contains('Relationships')").after( + `` + ); } } // 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)) { $artists = $('ul.radio-list li'); if ($artists.length == 1) { @@ -130,41 +165,46 @@ $(document).ready(function () { } // 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)) { - var isrcColNo; // = ($("#content table.tbl thead th:eq(2)").text() == "Artist") ? 3 : 2; - $("#content table.tbl thead th").each(function(index, th) { - if ($(th).text() == "ISRCs") { + let isrcColNo; // = ($("#content table.tbl thead th:eq(2)").text() == "Artist") ? 3 : 2; + $('#content table.tbl thead th').each(function(index, th) { + if ($(th).text() == 'ISRCs') { isrcColNo = index; return false; } }); - var reg = new RegExp("([A-Z]{2}[A-Z0-9]{3}[0-9]{7})"); - $("#content table.tbl tbody tr").each(function() { - var $td = $(this).find("td:eq("+isrcColNo+")"); - var isrcs = $td.text().trim().split("\n
      \n"); - var newHTML = ""; + let reg = new RegExp('([A-Z]{2}[A-Z0-9]{3}[0-9]{7})'); + $('#content table.tbl tbody tr').each(function() { + let $td = $(this).find(`td:eq(${isrcColNo})`); + let isrcs = $td + .text() + .trim() + .split('\n
      \n'); + let newHTML = ''; $.each(isrcs, function(index, isrc) { isrc = isrc.trim(); - newHTML += ""; - newHTML += isrc.substring(0,5) + "" + isrc.substring(5,7) + "" + isrc.substring(7); - newHTML += ""; - if (index != isrcs.length-1) { newHTML += "
      " }; + newHTML += ``; + newHTML += `${isrc.substring(0, 5)}${isrc.substring(5, 7)}${isrc.substring(7)}`; + newHTML += ''; + if (index != isrcs.length - 1) { + newHTML += '
      '; + } }); $td.html(newHTML); }); } // 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)) { - var ISRC_COLUMN_POSITION = 2; + let ISRC_COLUMN_POSITION = 2; var mbid = window.location.href.match(re)[1]; // 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) { // Store tracks data from webservice in a hash table - var tracks = {}; + let tracks = {}; $.each(data.media, function(index, medium) { $.each(medium.tracks, function(i, track) { tracks[track.id] = track; @@ -173,16 +213,20 @@ $(document).ready(function () { // Different behavior depending on the number of mediums if ($('table.medium').length <= 10) { // All mediums are already displayed: handle them now - $("table.medium").each(function() { - handleMedium($(this), tracks) + $('table.medium').each(function() { + handleMedium($(this), tracks); }); } else { // 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').bind("DOMNodeInserted", function(event) { + $('table.medium').bind('DOMNodeInserted', function(event) { $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.attr(HANDLED_ATTRIBUTE, 'pending'); handleMedium($medium, tracks); @@ -194,48 +238,65 @@ $(document).ready(function () { function handleMedium($medium, ws_tracks) { // Extend colspan for medium table header - $medium.find("thead tr").each(function() { - $(this).find("th:eq(0)").attr("colspan", $(this).find("th:eq(0)").attr("colspan")*1+1); + $medium.find('thead tr').each(function() { + $(this) + .find('th:eq(0)') + .attr( + 'colspan', + $(this) + .find('th:eq(0)') + .attr('colspan') * + 1 + + 1 + ); }); // Table sub-header - $medium.find("tbody tr.subh th:nth-last-child("+ISRC_COLUMN_POSITION+")").before(" ISRC "); + $medium + .find(`tbody tr.subh th:nth-last-child(${ISRC_COLUMN_POSITION})`) + .before(" ISRC "); // 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'); - var isrcsLinks = ""; + let isrcsLinks = ''; if (ws_tracks.hasOwnProperty(track_mbid)) { track = ws_tracks[track_mbid]; - var recording = track.recording; + let recording = track.recording; // Recording comment - if (recording.disambiguation != "") { - var td_title_index = $("#"+track_mbid).find("td:eq(1)").hasClass("video") ? 2 : 1; - $("#"+track_mbid).find("td:eq("+td_title_index+") a:eq(0)").after(' (' + recording.disambiguation + ')'); + if (recording.disambiguation != '') { + let td_title_index = $(`#${track_mbid}`) + .find('td:eq(1)') + .hasClass('video') + ? 2 + : 1; + $(`#${track_mbid}`) + .find(`td:eq(${td_title_index}) a:eq(0)`) + .after(` (${recording.disambiguation})`); } // ISRCS if (recording.isrcs.length != 0) { - var links = jQuery.map(recording.isrcs, function(isrc, i) { - return ("" + isrc + ""); + let links = jQuery.map(recording.isrcs, function(isrc, i) { + return `${isrc}`; }); - isrcsLinks = links.join(", "); + isrcsLinks = links.join(', '); } } - $('#'+track_mbid).find("td:nth-last-child("+ISRC_COLUMN_POSITION+")").before(""+isrcsLinks+""); + $(`#${track_mbid}`) + .find(`td:nth-last-child(${ISRC_COLUMN_POSITION})`) + .before(`${isrcsLinks}`); }); } } // 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)) { var mbid = window.location.href.match(re)[1]; - $('ul.tabs').append('
    • Edit relationships
    • '); + $('ul.tabs').append(`
    • Edit relationships
    • `); } // Discogs link rollover // TODO... // -------------- End of script ------------------------ - }); - diff --git a/metalarchives_importer.user.js b/metalarchives_importer.user.js index 1fe7cde..4d89143 100644 --- a/metalarchives_importer.user.js +++ b/metalarchives_importer.user.js @@ -13,205 +13,213 @@ // @icon https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/assets/images/Musicbrainz_import_logo.png // ==/UserScript== - // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant this.$ = this.jQuery = jQuery.noConflict(true); if (!unsafeWindow) unsafeWindow = window; $(document).ready(function() { - MBImportStyle(); + MBImportStyle(); - var release_url = window.location.href.replace('/\?.*$/', '').replace(/#.*$/, ''); - var release = retrieveReleaseInfo(release_url); - insertLink(release, release_url); - LOGGER.info("Parsed release: ", release); + let release_url = window.location.href.replace('/?.*$/', '').replace(/#.*$/, ''); + let release = retrieveReleaseInfo(release_url); + insertLink(release, release_url); + LOGGER.info('Parsed release: ', release); }); function setreleasedate(release, datestring) { - if (/^\d{4}$/.exec(datestring)) { - release.year = datestring; - } else if (datestring.indexOf(',') != -1) { - var commaindex = datestring.indexOf(','); - var d = new Date(datestring.substring(0, commaindex - 2) + datestring.substring(commaindex)); - release.year = d.getFullYear(); - release.month = d.getMonth() + 1; - release.day = d.getDate(); - } else { - var d = new Date("2 " + datestring); - release.year = d.getFullYear(); - release.month = d.getMonth() + 1; - } - return release; + if (/^\d{4}$/.exec(datestring)) { + release.year = datestring; + } else if (datestring.indexOf(',') != -1) { + let commaindex = datestring.indexOf(','); + var d = new Date(datestring.substring(0, commaindex - 2) + datestring.substring(commaindex)); + release.year = d.getFullYear(); + release.month = d.getMonth() + 1; + release.day = d.getDate(); + } else { + var d = new Date(`2 ${datestring}`); + release.year = d.getFullYear(); + release.month = d.getMonth() + 1; + } + return release; } function getGenericalData() { - var rdata = new Array(); - var keydata = $('dl.float_left dt, dl.float_right dt').map(function() { - var s = $.trim($(this).text()); - return s.substring(0, s.length - 1); - }).get(); - var valuedata = $('dl.float_left dd,dl.float_right dd').map(function() { - return $.trim($(this).text()); - }).get(); - for (i = 0; i < keydata.length; i++) { - rdata[keydata[i]] = valuedata[i]; - } - return rdata; + let rdata = new Array(); + let keydata = $('dl.float_left dt, dl.float_right dt') + .map(function() { + let s = $.trim($(this).text()); + return s.substring(0, s.length - 1); + }) + .get(); + let valuedata = $('dl.float_left dd,dl.float_right dd') + .map(function() { + return $.trim($(this).text()); + }) + .get(); + for (i = 0; i < keydata.length; i++) { + rdata[keydata[i]] = valuedata[i]; + } + return rdata; } function getArtistsList() { - return $.map($('h2.band_name').text().split('/'), $.trim); + return $.map( + $('h2.band_name') + .text() + .split('/'), + $.trim + ); } function retrieveReleaseInfo(release_url) { + let release = { + discs: [], + artist_credit: [], + title: '', + year: 0, + month: 0, + day: 0, + parent_album_url: '', + labels: [], + format: '', + country: '', + type: '', + status: 'official', + packaging: '', + language: '', + script: '', + urls: [] + }; - var release = { - discs: [], - artist_credit: [], - title: '', - year: 0, - month: 0, - day: 0, - parent_album_url: '', - labels: [], - format: '', - country: '', - type: '', - status: 'official', - packaging: '', - language: '', - script: '', - urls: [], - }; + let rdata = getGenericalData(); + let artists = getArtistsList(); + let joinphrase = ''; + if (artists.length > 1) { + if (rdata['Type'] == 'Split') { + joinphrase = ' / '; + } else { + joinphrase = ' & '; + } + } + for (let i = 0; i < artists.length; i++) { + release.artist_credit.push({ + artist_name: artists[i], + credited_name: artists[i], + joinphrase: i != artists.length - 1 ? joinphrase : '' + }); + } + release.title = $('h1.album_name').text(); - var rdata = getGenericalData(); - var artists = getArtistsList(); - var joinphrase = ""; - if (artists.length > 1) { - if (rdata["Type"] == "Split") { - joinphrase = " / "; + release = setreleasedate(release, rdata['Release date']); + if ('Label' in rdata) { + // TODO: add case for multiple labels if such a case exist + let label = rdata['Label']; + let label_mbid = ''; + if (label == 'Independent') { + label = '[no label]'; + label_mbid = '157afde4-4bf5-4039-8ad2-5a15acc85176'; + } + let catno = rdata['Catalog ID']; + if (catno == undefined || catno == 'N/A') { + catno = ''; + } + release.labels.push({ + name: label, + catno: catno, + mbid: label_mbid + }); } - else { - joinphrase = " & "; + + if (rdata['Type'] in ReleaseTypes) { + let types = ReleaseTypes[rdata['Type']]; + release.type = types[0]; + // 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); } - } - for (var i = 0; i < artists.length; i++) { - release.artist_credit.push({ - artist_name: artists[i], - credited_name: artists[i], - joinphrase: i != artists.length - 1 ? joinphrase : "" + + // FIXME: multiple vinyls ie. http://www.metal-archives.com/albums/Reverend_Bizarre/III%3A_So_Long_Suckers/415313 + if (rdata['Format'] in ReleaseFormat) { + release.format = ReleaseFormat[rdata['Format']]; + } + + if ('Version desc.' in rdata) { + if (rdata['Version desc.'].indexOf('Digipak') != -1) { + release.packaging = 'Digipak'; + } + if (release.format == 'CD' && rdata['Version desc.'] == 'CD-R') { + release.format = 'CD-R'; + } + } + + let identifiers = $('#album_tabs_notes > div:nth-child(2)') + .find('p:not([class])') + .contents(); + for (let j = 0; j < identifiers.length; j++) { + if (identifiers[j].textContent.indexOf('Barcode:') != -1) { + release.barcode = $.trim(identifiers[j].textContent.substring(8)); + break; + } + } + + // URLs + let link_type = MBImport.URL_TYPES; + release.urls.push({ + url: release_url, + link_type: link_type.other_databases }); - } - release.title = $('h1.album_name').text(); - release = setreleasedate(release, rdata["Release date"]); - if ("Label" in rdata) { - // TODO: add case for multiple labels if such a case exist - var label = rdata["Label"]; - var label_mbid = ""; - if (label == "Independent") { - label = "[no label]"; - label_mbid = '157afde4-4bf5-4039-8ad2-5a15acc85176'; - } - var catno = rdata["Catalog ID"]; - if (catno == undefined || catno == "N/A") { - catno = ""; - } - release.labels.push({ - name: label, - catno: catno, - mbid: label_mbid - }); - } - - if (rdata["Type"] in ReleaseTypes) { - var types = ReleaseTypes[rdata["Type"]]; - release.type = types[0]; - // 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); - } - - // FIXME: multiple vinyls ie. http://www.metal-archives.com/albums/Reverend_Bizarre/III%3A_So_Long_Suckers/415313 - if (rdata["Format"] in ReleaseFormat) { - release.format = ReleaseFormat[rdata["Format"]]; - } - - if ("Version desc." in rdata) { - if (rdata["Version desc."].indexOf("Digipak") != -1) { - release.packaging = "Digipak"; - } - if (release.format == "CD" && rdata["Version desc."] == "CD-R") { - release.format = "CD-R"; - } - } - - var identifiers = $("#album_tabs_notes > div:nth-child(2)").find("p:not([class])").contents(); - for (var j = 0; j < identifiers.length; j++) { - if (identifiers[j].textContent.indexOf("Barcode:") != -1) { - release.barcode = $.trim(identifiers[j].textContent.substring(8)); - break; - } - } - - // URLs - var link_type = MBImport.URL_TYPES; - release.urls.push({ - url: release_url, - link_type: link_type.other_databases - }); - - var releaseNumber = 0; - var disc = { - tracks: [], - format: release.format - }; - release.discs.push(disc); - - var tracksline = $('table.table_lyrics tr.even,table.table_lyrics tr.odd'); - - tracksline.each(function(index, element) { - var trackNumber = $.trim(element.children[0].textContent).replace('.', ""); - if (trackNumber == "1" && trackNumber != index + 1) { - releaseNumber++; - release.discs.push({ + let releaseNumber = 0; + let disc = { tracks: [], format: release.format - }); - } - - // TODO: handling of split and compilation artists (artist - title) - var track = { - 'number': trackNumber, - 'title': $.trim(element.children[1].textContent.replace(/\s+/g, ' ')), - 'duration': $.trim(element.children[2].textContent), - 'artist_credit': [release.artist_credit] }; - release.discs[releaseNumber].tracks.push(track); - }); - return release; + release.discs.push(disc); + + let tracksline = $('table.table_lyrics tr.even,table.table_lyrics tr.odd'); + + tracksline.each(function(index, element) { + let trackNumber = $.trim(element.children[0].textContent).replace('.', ''); + if (trackNumber == '1' && trackNumber != index + 1) { + releaseNumber++; + release.discs.push({ + tracks: [], + format: release.format + }); + } + + // TODO: handling of split and compilation artists (artist - title) + let track = { + number: trackNumber, + title: $.trim(element.children[1].textContent.replace(/\s+/g, ' ')), + duration: $.trim(element.children[2].textContent), + artist_credit: [release.artist_credit] + }; + release.discs[releaseNumber].tracks.push(track); + }); + return release; } // Insert button into page under label information function insertLink(release, release_url) { - var edit_note = MBImport.makeEditNote(release_url, 'Metal Archives'); - var parameters = MBImport.buildFormParameters(release, edit_note); + let edit_note = MBImport.makeEditNote(release_url, 'Metal Archives'); + let parameters = MBImport.buildFormParameters(release, edit_note); - var mbUI = $('
      ' + MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release) + '
      ').hide(); + let mbUI = $(`
      ${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}
      `).hide(); - $('h2.band_name').after(mbUI); - $('#musicbrainz-import form').css({ - 'padding': '0' - }); - $('form.musicbrainz_import').css({ - 'display': 'inline-block', - 'margin': '1px' - }); - $('form.musicbrainz_import img').css({ - 'display': 'inline-block' - }); + $('h2.band_name').after(mbUI); + $('#musicbrainz-import form').css({ + padding: '0' + }); + $('form.musicbrainz_import').css({ + display: 'inline-block', + margin: '1px' + }); + $('form.musicbrainz_import img').css({ + display: 'inline-block' + }); - mbUI.slideDown(); + mbUI.slideDown(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -236,28 +244,28 @@ Split video //ReleaseTypes[MAtype]=["primary type","secondary type on mb"]; var ReleaseTypes = { - "Full-length": ["album"], - "Live album": ["album", "live"], - "Demo": ["album", "demo"], - "Single": ["single"], - "EP": ["ep"], - "Compilation": ["album", "compilation"], - "Split": ["album"], - "Collaboration": [""], + 'Full-length': ['album'], + 'Live album': ['album', 'live'], + Demo: ['album', 'demo'], + Single: ['single'], + EP: ['ep'], + Compilation: ['album', 'compilation'], + Split: ['album'], + Collaboration: [''] }; //ReleaseFormat[MAformat]="MBformat"; var ReleaseFormat = { - "CD": "CD", - "2CD": "CD", - "Vinyl": "Vinyl", - "7\" vinyl": "7\" Vinyl", - "7\" vinyl (33⅓ RPM)": "7\" Vinyl", - "10\" vinyl (33⅓ RPM)": "10\" Vinyl", - "10\" vinyl": "10\" Vinyl", - "12\" vinyl": "12\" Vinyl", - "2 12\" vinyls": "12\" Vinyl", - "12\" vinyl (33⅓ RPM)": "12\" Vinyl", - "Cassette": "Cassette", - "Digital": "Digital Media", + CD: 'CD', + '2CD': 'CD', + Vinyl: 'Vinyl', + '7" vinyl': '7" Vinyl', + '7" vinyl (33⅓ RPM)': '7" Vinyl', + '10" vinyl (33⅓ RPM)': '10" Vinyl', + '10" vinyl': '10" Vinyl', + '12" vinyl': '12" Vinyl', + '2 12" vinyls': '12" Vinyl', + '12" vinyl (33⅓ RPM)': '12" Vinyl', + Cassette: 'Cassette', + Digital: 'Digital Media' }; diff --git a/qobuz_importer.user.js b/qobuz_importer.user.js index 82033cf..acf2c76 100644 --- a/qobuz_importer.user.js +++ b/qobuz_importer.user.js @@ -22,170 +22,178 @@ if (!unsafeWindow) unsafeWindow = window; var DEBUG = false; //DEBUG = true; if (DEBUG) { - LOGGER.setLevel('debug'); + LOGGER.setLevel('debug'); } // 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) { - var release = {}; + let release = {}; - release.script = 'Latn'; - release.url = 'https://www.qobuz.com' + data.relative_url; // no lang + release.script = 'Latn'; + release.url = `https://www.qobuz.com${data.relative_url}`; // no lang - release.title = data.title; - release.artist_credit = MBImport.makeArtistCredits([data.artist.name]); // FIXME: various artists - if ($.inArray(data.artist.id, various_artists_ids) != -1) { - release.artist_credit = [ MBImport.specialArtist('various_artists') ]; - } - - // Release information global to all Beatport releases - release.packaging = 'None'; - release.barcode = data.upc; - release.country = "XW"; - if (i18n_global && i18n_global.zone) { - release.country = i18n_global.zone; - } - release.status = 'official'; - release.urls = []; - release.urls.push({ - 'url': release.url, - 'link_type': MBImport.URL_TYPES.purchase_for_download - }); - - // 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) - var releaseDate = new Date((parseInt(data.released_at, 10) + 3*3600) * 1000); - release.year = releaseDate.getUTCFullYear(); - release.month = releaseDate.getUTCMonth() + 1; - release.day = releaseDate.getUTCDate(); - - release.labels = []; - $.each(data.label.name.split(' - '), function(index, label) { - release.labels.push({ - name: label, - catno: "[none]" // no catno on qobuz ? - }); - }); - release.isrcs = []; - release.comment = "Digital download"; - release.discs = []; - var tracks = [], old_media_num = 1; - $.each(data.tracks.items, function(index, trackobj) { - release.isrcs.push(trackobj.isrc); - if (trackobj.media_number != old_media_num) { - release.discs.push({ - 'tracks': tracks, - 'format': "Digital Media" - }); - old_media_num = trackobj.media_number; - tracks = []; + release.title = data.title; + release.artist_credit = MBImport.makeArtistCredits([data.artist.name]); // FIXME: various artists + if ($.inArray(data.artist.id, various_artists_ids) != -1) { + release.artist_credit = [MBImport.specialArtist('various_artists')]; } - var track = {}; - track.title = trackobj.title.replace('"','\"'); - track.duration = trackobj.duration * 1000; - var performers = (typeof trackobj.performers !== 'undefined') && trackobj.performers.split('\r - ').map(function(v) { - var list = v.split(', '); - var name = list.shift(); - return [name, list]; - }) || [trackobj.performer.name, ['Primary']]; - var artists = []; - var featured_artists = []; - $.each(performers, function(index, performer) { - if ($.inArray('Featured Artist', performer[1]) != -1) { - featured_artists.push(performer[0]); - } - else if ($.inArray('Main Performer', performer[1]) != -1 - || $.inArray('Primary', performer[1]) != -1 - || $.inArray('interprète', performer[1]) != -1 - || $.inArray('Performer', performer[1]) != -1 - || $.inArray('Main Artist', performer[1]) != -1 - ) { - artists.push(performer[0]); - } - }); - track.artist_credit = MBImport.makeArtistCredits(artists); - if (featured_artists.length) { - if (track.artist_credit.length) { - track.artist_credit[track.artist_credit.length-1].joinphrase = ' feat. '; - } - $.merge(track.artist_credit, MBImport.makeArtistCredits(featured_artists)); - } - tracks.push(track); - }); - release.discs.push({ - 'tracks': tracks, - 'format': "Digital Media" - }); - LOGGER.info("Parsed release: ", release); - return release; + // Release information global to all Beatport releases + release.packaging = 'None'; + release.barcode = data.upc; + release.country = 'XW'; + if (i18n_global && i18n_global.zone) { + release.country = i18n_global.zone; + } + release.status = 'official'; + release.urls = []; + release.urls.push({ + url: release.url, + link_type: MBImport.URL_TYPES.purchase_for_download + }); + + // 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) + let releaseDate = new Date((parseInt(data.released_at, 10) + 3 * 3600) * 1000); + release.year = releaseDate.getUTCFullYear(); + release.month = releaseDate.getUTCMonth() + 1; + release.day = releaseDate.getUTCDate(); + + release.labels = []; + $.each(data.label.name.split(' - '), function(index, label) { + release.labels.push({ + name: label, + catno: '[none]' // no catno on qobuz ? + }); + }); + release.isrcs = []; + release.comment = 'Digital download'; + release.discs = []; + let tracks = [], + old_media_num = 1; + $.each(data.tracks.items, function(index, trackobj) { + release.isrcs.push(trackobj.isrc); + if (trackobj.media_number != old_media_num) { + release.discs.push({ + tracks: tracks, + format: 'Digital Media' + }); + old_media_num = trackobj.media_number; + tracks = []; + } + let track = {}; + track.title = trackobj.title.replace('"', '"'); + track.duration = trackobj.duration * 1000; + let performers = (typeof trackobj.performers !== 'undefined' && + trackobj.performers.split('\r - ').map(function(v) { + let list = v.split(', '); + let name = list.shift(); + return [name, list]; + })) || [trackobj.performer.name, ['Primary']]; + let artists = []; + let featured_artists = []; + $.each(performers, function(index, performer) { + if ($.inArray('Featured Artist', performer[1]) != -1) { + featured_artists.push(performer[0]); + } else if ( + $.inArray('Main Performer', performer[1]) != -1 || + $.inArray('Primary', performer[1]) != -1 || + $.inArray('interprète', performer[1]) != -1 || + $.inArray('Performer', performer[1]) != -1 || + $.inArray('Main Artist', performer[1]) != -1 + ) { + artists.push(performer[0]); + } + }); + track.artist_credit = MBImport.makeArtistCredits(artists); + if (featured_artists.length) { + if (track.artist_credit.length) { + track.artist_credit[track.artist_credit.length - 1].joinphrase = ' feat. '; + } + $.merge(track.artist_credit, MBImport.makeArtistCredits(featured_artists)); + } + tracks.push(track); + }); + release.discs.push({ + tracks: tracks, + format: 'Digital Media' + }); + + LOGGER.info('Parsed release: ', release); + return release; } // Insert button into page under label information function insertLink(release) { - var edit_note = MBImport.makeEditNote(release.url, 'Qobuz'); - var parameters = MBImport.buildFormParameters(release, edit_note); + let edit_note = MBImport.makeEditNote(release.url, 'Qobuz'); + let parameters = MBImport.buildFormParameters(release, edit_note); - var mbUI = $('

      ').append(MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release)).hide(); - mbUI.append($('')); - var isrclist = $('

      '); + let mbUI = $('

      ') + .append(MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release)) + .hide(); + mbUI.append($('')); + let isrclist = $(`

      `); - $("#info div.meta").append(mbUI).append(isrclist); - $('form.musicbrainz_import').css({ - 'display': 'inline-block', - 'margin': '1px' - }); - $('form.musicbrainz_import img').css({ - 'display': 'inline-block', - 'width': '16px', - 'height': '16px' - }); - mbUI.slideDown(); + $('#info div.meta') + .append(mbUI) + .append(isrclist); + $('form.musicbrainz_import').css({ + display: 'inline-block', + margin: '1px' + }); + $('form.musicbrainz_import img').css({ + display: 'inline-block', + width: '16px', + height: '16px' + }); + mbUI.slideDown(); } // Hook all XMLHttpRequest to use the data fetched by the official web-player. (function() { - const send = XMLHttpRequest.prototype.send + const send = XMLHttpRequest.prototype.send; XMLHttpRequest.prototype.send = function() { this.addEventListener('load', function() { - var wsUrl = 'https://www.qobuz.com/api.json/0.2/album/get?album_id='; - var repUrl = arguments[0].originalTarget.responseURL; + let wsUrl = 'https://www.qobuz.com/api.json/0.2/album/get?album_id='; + let repUrl = arguments[0].originalTarget.responseURL; if (repUrl.startsWith(wsUrl)) { - var data = JSON.parse(this.responseText); - var release = parseRelease(data); + let data = JSON.parse(this.responseText); + let release = parseRelease(data); insertLink(release); } - }) - return send.apply(this, arguments) - } -})() + }); + return send.apply(this, arguments); + }; +})(); $(document).ready(function() { + MBImportStyle(); - MBImportStyle(); - - // replace image zoom link by the maximum size image link - var maximgurl = $("#product-cover-link").attr("href").replace('_600', '_max'); - var maximg = new Image(); - maximg.onerror = function (evt) { - LOGGER.debug("No max image"); - }; - maximg.onload = function (evt) { - $("#product-cover-link").attr("href", maximgurl); - $("#product-cover-link").attr("title", $("#product-cover-link").attr("title") + ' (Qobuz importer: ' + maximg.width + 'x' + maximg.height + ' image)'); - }; - maximg.src = maximgurl; - + // replace image zoom link by the maximum size image link + let maximgurl = $('#product-cover-link') + .attr('href') + .replace('_600', '_max'); + let maximg = new Image(); + maximg.onerror = function(evt) { + LOGGER.debug('No max image'); + }; + maximg.onload = function(evt) { + $('#product-cover-link').attr('href', maximgurl); + $('#product-cover-link').attr( + 'title', + `${$('#product-cover-link').attr('title')} (Qobuz importer: ${maximg.width}x${maximg.height} image)` + ); + }; + maximg.src = maximgurl; }); -$(document).on('click', '#isrcs', function (){ +$(document).on('click', '#isrcs', function() { $('#isrclist').toggle(); if ($('#isrclist').is(':visible')) { - $('#isrclist').select(); - $(this).text('Hide ISRCs'); - } - else $(this).text('Show ISRCs'); + $('#isrclist').select(); + $(this).text('Hide ISRCs'); + } else $(this).text('Show ISRCs'); return false; -}); \ No newline at end of file +}); diff --git a/set-recording-comments.user.js b/set-recording-comments.user.js index d1adf2b..3983510 100644 --- a/set-recording-comments.user.js +++ b/set-recording-comments.user.js @@ -41,19 +41,23 @@ // authorization. // ==/License== -var scr = document.createElement("script"); -scr.textContent = "$(" + setRecordingComments + ");"; +var scr = document.createElement('script'); +scr.textContent = `$(${setRecordingComments});`; document.body.appendChild(scr); function setRecordingComments() { - var $tracks; - var $inputs = $(); - var EDIT_RECORDING_EDIT = 72; + let $tracks; + let $inputs = $(); + let EDIT_RECORDING_EDIT = 72; - $("head").append($("").text("input.recording-comment { background: inherit; border: 1px #999 solid; width: 32em; margin-left: 0.5em; }")); + $('head').append( + $('').text( + 'input.recording-comment { background: inherit; border: 1px #999 solid; width: 32em; margin-left: 0.5em; }' + ) + ); - var delay = setInterval(function () { - $tracks = $(".medium tbody tr[id]"); + var delay = setInterval(function() { + $tracks = $('.medium tbody tr[id]'); if ($tracks.length) { clearInterval(delay); @@ -61,10 +65,14 @@ function setRecordingComments() { return; } - $tracks.each(function () { - var $td = $(this).children("td:not(.pos):not(.video):not(.rating):not(.treleases)").has("a[href^=\\/recording\\/]"), - node = $td.children("td > .mp, td > .name-variation, td > a[href^=\\/recording\\/]").filter(":first"), - $input = $("").addClass("recording-comment").insertAfter(node); + $tracks.each(function() { + let $td = $(this) + .children('td:not(.pos):not(.video):not(.rating):not(.treleases)') + .has('a[href^=\\/recording\\/]'), + node = $td.children('td > .mp, td > .name-variation, td > a[href^=\\/recording\\/]').filter(':first'), + $input = $('') + .addClass('recording-comment') + .insertAfter(node); if (!editing) { $input.hide(); @@ -73,14 +81,17 @@ function setRecordingComments() { $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) { - var comments = _.map(_.map(_.flatten(_.map(data.media, "tracks")), "recording"), "disambiguation"); + $.get(`/ws/2/release/${release}?inc=recordings&fmt=json`, function(data) { + let comments = _.map(_.map(_.flatten(_.map(data.media, 'tracks')), 'recording'), 'disambiguation'); - for (var i = 0, len = comments.length; i < len; i++) { - var comment = comments[i]; - $inputs.eq(i).val(comment).data("old", comment); + for (let i = 0, len = comments.length; i < len; i++) { + let comment = comments[i]; + $inputs + .eq(i) + .val(comment) + .data('old', comment); } }); }, 1000); @@ -93,25 +104,28 @@ function setRecordingComments() { editing = false, activeRequest = null; - $("body").on("input.rc", ".recording-comment", function () { - $(this).css("border-color", this.value === $(this).data("old") ? "#999" : "red"); + $('body').on('input.rc', '.recording-comment', function() { + $(this).css('border-color', this.value === $(this).data('old') ? '#999' : 'red'); }); - var $container = $("
      ").insertAfter("h2.tracklist"); + let $container = $('
      ').insertAfter('h2.tracklist'); - $("") - .addClass("styled-button") - .on("click", function () { + $('') + .addClass('styled-button') + .on('click', function() { editing = !editing; - $("#set-recording-comments").add($inputs).toggle(editing); - $(this).text((editing ? "Hide" : "Edit") + " recording comments"); + $('#set-recording-comments') + .add($inputs) + .toggle(editing); + $(this).text(`${editing ? 'Hide' : 'Edit'} recording comments`); if (editing) { - $("#all-recording-comments").focus(); + $('#all-recording-comments').focus(); } }) .appendTo($container); - $container.append('\ + $container.append( + '\ \ \ \ @@ -126,71 +140,80 @@ function setRecordingComments() { \ \ \ -
      '); +' + ); - $("#set-recording-comments").hide(); + $('#set-recording-comments').hide(); - $("#all-recording-comments").on("input", function () { - $inputs.filter(":visible").val(this.value).trigger("input.rc"); + $('#all-recording-comments').on('input', function() { + $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) { activeRequest.abort(); activeRequest = null; - $submitButton.text("Submit changes (marked red)"); - $inputs.prop("disabled", false).trigger("input.rc"); + $submitButton.text('Submit changes (marked red)'); + $inputs.prop('disabled', false).trigger('input.rc'); return; } - $submitButton.text("Submitting...click to cancel!"); - $inputs.prop("disabled", true); + $submitButton.text('Submitting...click to cancel!'); + $inputs.prop('disabled', true); - var editData = [], deferred = $.Deferred(); + let editData = [], + deferred = $.Deferred(); - $.each($tracks, function (i, track) { - if ($(track).filter(":visible").length > 0) { - var $input = $inputs.eq(i), comment = $input.val(); - if (comment === $input.data("old")) { - $input.prop("disabled", false); + $.each($tracks, function(i, track) { + if ($(track).filter(':visible').length > 0) { + let $input = $inputs.eq(i), + comment = $input.val(); + if (comment === $input.data('old')) { + $input.prop('disabled', false); return; } deferred - .done(function () { - $input.data("old", comment).trigger("input.rc").prop("disabled", false); + .done(function() { + $input + .data('old', comment) + .trigger('input.rc') + .prop('disabled', false); }) - .fail(function () { - $input.css("border-color", "red").prop("disabled", false); + .fail(function() { + $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]; - 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) { - $inputs.prop("disabled", false); - $submitButton.prop("disabled", false).text("Submit changes (marked red)"); + $inputs.prop('disabled', false); + $submitButton.prop('disabled', false).text('Submit changes (marked red)'); } else { - var editNote = $("#recording-comments-edit-note").val(); + let editNote = $('#recording-comments-edit-note').val(); activeRequest = $.ajax({ - type: 'POST', - url: '/ws/js/edit/create', - dataType: 'json', - data: JSON.stringify({edits: editData, editNote: editNote}), - contentType: 'application/json; charset=utf-8', + type: 'POST', + url: '/ws/js/edit/create', + dataType: 'json', + data: JSON.stringify({ edits: editData, editNote: editNote }), + contentType: 'application/json; charset=utf-8' + }) + .always(function() { + $submitButton.prop('disabled', false).text('Submit changes (marked red)'); }) - .always(function () { - $submitButton.prop("disabled", false).text("Submit changes (marked red)"); - }) - .done(function () { + .done(function() { deferred.resolve(); }) - .fail(function () { + .fail(function() { deferred.reject(); }); } diff --git a/takealot_importer.user.js b/takealot_importer.user.js index d3381b4..3c66680 100644 --- a/takealot_importer.user.js +++ b/takealot_importer.user.js @@ -15,7 +15,6 @@ // @grant none // ==/UserScript== - // prevent JQuery conflicts, see http://wiki.greasespot.net/@grant this.$ = this.jQuery = jQuery.noConflict(true); @@ -24,7 +23,7 @@ if (!unsafeWindow) unsafeWindow = window; var DEBUG = false; //DEBUG = true; if (DEBUG) { - LOGGER.setLevel('debug'); + LOGGER.setLevel('debug'); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -41,11 +40,10 @@ if (DEBUG) { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// - $(document).ready(function() { - LOGGER.info("Document Ready & Takealot Userscript executing"); - var TakealotRelease = ParseTakealotPage(); - insertMBSection(TakealotRelease); + LOGGER.info('Document Ready & Takealot Userscript executing'); + let TakealotRelease = ParseTakealotPage(); + insertMBSection(TakealotRelease); }); //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -53,734 +51,810 @@ $(document).ready(function() { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// function insertMbUI(mbUI) { - var e; - if ((e = $("div.section.box-summary")) && e.length) { - e.after(mbUI); - } else if ((e = $('#buybox')) && e.length) { - e.before(mbUI); - } else if ((e = $("div.section.more-choices")) && e.length) { - e.before(mbUI); - } + let e; + if ((e = $('div.section.box-summary')) && e.length) { + e.after(mbUI); + } else if ((e = $('#buybox')) && e.length) { + e.before(mbUI); + } else if ((e = $('div.section.more-choices')) && e.length) { + e.before(mbUI); + } } - // Insert links to high res image in Takealot page function insertIMGlinks() { - var imghref = $('#slideshow a.jqzoom').attr('href'); - LOGGER.debug("insertIMGlink Firing", imghref); - $('#slideshow').append('

      MB High Res Image

      '); + let imghref = $('#slideshow a.jqzoom').attr('href'); + LOGGER.debug('insertIMGlink Firing', imghref); + $('#slideshow').append(`

      MB High Res Image

      `); } - // Artist in product information is without diacritics // Remove Diacritics from Artist in header to comapre with product information function removeDiacritics(str) { + let defaultDiacriticsRemovalMap = [ + { + base: 'A', + letters: /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g + }, + { + base: 'AA', + letters: /[\uA732]/g + }, + { + base: 'AE', + letters: /[\u00C6\u01FC\u01E2]/g + }, + { + base: 'AO', + letters: /[\uA734]/g + }, + { + base: 'AU', + letters: /[\uA736]/g + }, + { + base: 'AV', + letters: /[\uA738\uA73A]/g + }, + { + base: 'AY', + letters: /[\uA73C]/g + }, + { + base: 'B', + letters: /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g + }, + { + base: 'C', + letters: /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g + }, + { + base: 'D', + letters: /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g + }, + { + base: 'DZ', + letters: /[\u01F1\u01C4]/g + }, + { + base: 'Dz', + letters: /[\u01F2\u01C5]/g + }, + { + base: 'E', + letters: /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g + }, + { + base: 'F', + letters: /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g + }, + { + base: 'G', + letters: /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g + }, + { + base: 'H', + letters: /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g + }, + { + base: 'I', + letters: /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g + }, + { + base: 'J', + letters: /[\u004A\u24BF\uFF2A\u0134\u0248]/g + }, + { + base: 'K', + letters: /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g + }, + { + base: 'L', + letters: /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g + }, + { + base: 'LJ', + letters: /[\u01C7]/g + }, + { + base: 'Lj', + letters: /[\u01C8]/g + }, + { + base: 'M', + letters: /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g + }, + { + base: 'N', + letters: /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g + }, + { + base: 'NJ', + letters: /[\u01CA]/g + }, + { + base: 'Nj', + letters: /[\u01CB]/g + }, + { + base: 'O', + letters: /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g + }, + { + base: 'OI', + letters: /[\u01A2]/g + }, + { + base: 'OO', + letters: /[\uA74E]/g + }, + { + base: 'OU', + letters: /[\u0222]/g + }, + { + base: 'P', + letters: /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g + }, + { + base: 'Q', + letters: /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g + }, + { + base: 'R', + letters: /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g + }, + { + base: 'S', + letters: /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g + }, + { + base: 'T', + letters: /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g + }, + { + base: 'TZ', + letters: /[\uA728]/g + }, + { + base: 'U', + letters: /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g + }, + { + base: 'V', + letters: /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g + }, + { + base: 'VY', + letters: /[\uA760]/g + }, + { + base: 'W', + letters: /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g + }, + { + base: 'X', + letters: /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g + }, + { + base: 'Y', + letters: /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g + }, + { + base: 'Z', + letters: /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g + }, + { + base: 'a', + letters: /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g + }, + { + base: 'aa', + letters: /[\uA733]/g + }, + { + base: 'ae', + letters: /[\u00E6\u01FD\u01E3]/g + }, + { + base: 'ao', + letters: /[\uA735]/g + }, + { + base: 'au', + letters: /[\uA737]/g + }, + { + base: 'av', + letters: /[\uA739\uA73B]/g + }, + { + base: 'ay', + letters: /[\uA73D]/g + }, + { + base: 'b', + letters: /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g + }, + { + base: 'c', + letters: /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g + }, + { + base: 'd', + letters: /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g + }, + { + base: 'dz', + letters: /[\u01F3\u01C6]/g + }, + { + base: 'e', + letters: /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g + }, + { + base: 'f', + letters: /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g + }, + { + base: 'g', + letters: /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g + }, + { + base: 'h', + letters: /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g + }, + { + base: 'hv', + letters: /[\u0195]/g + }, + { + base: 'i', + letters: /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g + }, + { + base: 'j', + letters: /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g + }, + { + base: 'k', + letters: /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g + }, + { + base: 'l', + letters: /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g + }, + { + base: 'lj', + letters: /[\u01C9]/g + }, + { + base: 'm', + letters: /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g + }, + { + base: 'n', + letters: /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g + }, + { + base: 'nj', + letters: /[\u01CC]/g + }, + { + base: 'o', + letters: /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g + }, + { + base: 'oi', + letters: /[\u01A3]/g + }, + { + base: 'ou', + letters: /[\u0223]/g + }, + { + base: 'oo', + letters: /[\uA74F]/g + }, + { + base: 'p', + letters: /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g + }, + { + base: 'q', + letters: /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g + }, + { + base: 'r', + letters: /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g + }, + { + base: 's', + letters: /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g + }, + { + base: 't', + letters: /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g + }, + { + base: 'tz', + letters: /[\uA729]/g + }, + { + base: 'u', + letters: /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g + }, + { + base: 'v', + letters: /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g + }, + { + base: 'vy', + letters: /[\uA761]/g + }, + { + base: 'w', + letters: /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g + }, + { + base: 'x', + letters: /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g + }, + { + base: 'y', + letters: /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g + }, + { + base: 'z', + letters: /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g + } + ]; - var defaultDiacriticsRemovalMap = [{ - 'base': 'A', - 'letters': /[\u0041\u24B6\uFF21\u00C0\u00C1\u00C2\u1EA6\u1EA4\u1EAA\u1EA8\u00C3\u0100\u0102\u1EB0\u1EAE\u1EB4\u1EB2\u0226\u01E0\u00C4\u01DE\u1EA2\u00C5\u01FA\u01CD\u0200\u0202\u1EA0\u1EAC\u1EB6\u1E00\u0104\u023A\u2C6F]/g - }, { - 'base': 'AA', - 'letters': /[\uA732]/g - }, { - 'base': 'AE', - 'letters': /[\u00C6\u01FC\u01E2]/g - }, { - 'base': 'AO', - 'letters': /[\uA734]/g - }, { - 'base': 'AU', - 'letters': /[\uA736]/g - }, { - 'base': 'AV', - 'letters': /[\uA738\uA73A]/g - }, { - 'base': 'AY', - 'letters': /[\uA73C]/g - }, { - 'base': 'B', - 'letters': /[\u0042\u24B7\uFF22\u1E02\u1E04\u1E06\u0243\u0182\u0181]/g - }, { - 'base': 'C', - 'letters': /[\u0043\u24B8\uFF23\u0106\u0108\u010A\u010C\u00C7\u1E08\u0187\u023B\uA73E]/g - }, { - 'base': 'D', - 'letters': /[\u0044\u24B9\uFF24\u1E0A\u010E\u1E0C\u1E10\u1E12\u1E0E\u0110\u018B\u018A\u0189\uA779]/g - }, { - 'base': 'DZ', - 'letters': /[\u01F1\u01C4]/g - }, { - 'base': 'Dz', - 'letters': /[\u01F2\u01C5]/g - }, { - 'base': 'E', - 'letters': /[\u0045\u24BA\uFF25\u00C8\u00C9\u00CA\u1EC0\u1EBE\u1EC4\u1EC2\u1EBC\u0112\u1E14\u1E16\u0114\u0116\u00CB\u1EBA\u011A\u0204\u0206\u1EB8\u1EC6\u0228\u1E1C\u0118\u1E18\u1E1A\u0190\u018E]/g - }, { - 'base': 'F', - 'letters': /[\u0046\u24BB\uFF26\u1E1E\u0191\uA77B]/g - }, { - 'base': 'G', - 'letters': /[\u0047\u24BC\uFF27\u01F4\u011C\u1E20\u011E\u0120\u01E6\u0122\u01E4\u0193\uA7A0\uA77D\uA77E]/g - }, { - 'base': 'H', - 'letters': /[\u0048\u24BD\uFF28\u0124\u1E22\u1E26\u021E\u1E24\u1E28\u1E2A\u0126\u2C67\u2C75\uA78D]/g - }, { - 'base': 'I', - 'letters': /[\u0049\u24BE\uFF29\u00CC\u00CD\u00CE\u0128\u012A\u012C\u0130\u00CF\u1E2E\u1EC8\u01CF\u0208\u020A\u1ECA\u012E\u1E2C\u0197]/g - }, { - 'base': 'J', - 'letters': /[\u004A\u24BF\uFF2A\u0134\u0248]/g - }, { - 'base': 'K', - 'letters': /[\u004B\u24C0\uFF2B\u1E30\u01E8\u1E32\u0136\u1E34\u0198\u2C69\uA740\uA742\uA744\uA7A2]/g - }, { - 'base': 'L', - 'letters': /[\u004C\u24C1\uFF2C\u013F\u0139\u013D\u1E36\u1E38\u013B\u1E3C\u1E3A\u0141\u023D\u2C62\u2C60\uA748\uA746\uA780]/g - }, { - 'base': 'LJ', - 'letters': /[\u01C7]/g - }, { - 'base': 'Lj', - 'letters': /[\u01C8]/g - }, { - 'base': 'M', - 'letters': /[\u004D\u24C2\uFF2D\u1E3E\u1E40\u1E42\u2C6E\u019C]/g - }, { - 'base': 'N', - 'letters': /[\u004E\u24C3\uFF2E\u01F8\u0143\u00D1\u1E44\u0147\u1E46\u0145\u1E4A\u1E48\u0220\u019D\uA790\uA7A4]/g - }, { - 'base': 'NJ', - 'letters': /[\u01CA]/g - }, { - 'base': 'Nj', - 'letters': /[\u01CB]/g - }, { - 'base': 'O', - 'letters': /[\u004F\u24C4\uFF2F\u00D2\u00D3\u00D4\u1ED2\u1ED0\u1ED6\u1ED4\u00D5\u1E4C\u022C\u1E4E\u014C\u1E50\u1E52\u014E\u022E\u0230\u00D6\u022A\u1ECE\u0150\u01D1\u020C\u020E\u01A0\u1EDC\u1EDA\u1EE0\u1EDE\u1EE2\u1ECC\u1ED8\u01EA\u01EC\u00D8\u01FE\u0186\u019F\uA74A\uA74C]/g - }, { - 'base': 'OI', - 'letters': /[\u01A2]/g - }, { - 'base': 'OO', - 'letters': /[\uA74E]/g - }, { - 'base': 'OU', - 'letters': /[\u0222]/g - }, { - 'base': 'P', - 'letters': /[\u0050\u24C5\uFF30\u1E54\u1E56\u01A4\u2C63\uA750\uA752\uA754]/g - }, { - 'base': 'Q', - 'letters': /[\u0051\u24C6\uFF31\uA756\uA758\u024A]/g - }, { - 'base': 'R', - 'letters': /[\u0052\u24C7\uFF32\u0154\u1E58\u0158\u0210\u0212\u1E5A\u1E5C\u0156\u1E5E\u024C\u2C64\uA75A\uA7A6\uA782]/g - }, { - 'base': 'S', - 'letters': /[\u0053\u24C8\uFF33\u1E9E\u015A\u1E64\u015C\u1E60\u0160\u1E66\u1E62\u1E68\u0218\u015E\u2C7E\uA7A8\uA784]/g - }, { - 'base': 'T', - 'letters': /[\u0054\u24C9\uFF34\u1E6A\u0164\u1E6C\u021A\u0162\u1E70\u1E6E\u0166\u01AC\u01AE\u023E\uA786]/g - }, { - 'base': 'TZ', - 'letters': /[\uA728]/g - }, { - 'base': 'U', - 'letters': /[\u0055\u24CA\uFF35\u00D9\u00DA\u00DB\u0168\u1E78\u016A\u1E7A\u016C\u00DC\u01DB\u01D7\u01D5\u01D9\u1EE6\u016E\u0170\u01D3\u0214\u0216\u01AF\u1EEA\u1EE8\u1EEE\u1EEC\u1EF0\u1EE4\u1E72\u0172\u1E76\u1E74\u0244]/g - }, { - 'base': 'V', - 'letters': /[\u0056\u24CB\uFF36\u1E7C\u1E7E\u01B2\uA75E\u0245]/g - }, { - 'base': 'VY', - 'letters': /[\uA760]/g - }, { - 'base': 'W', - 'letters': /[\u0057\u24CC\uFF37\u1E80\u1E82\u0174\u1E86\u1E84\u1E88\u2C72]/g - }, { - 'base': 'X', - 'letters': /[\u0058\u24CD\uFF38\u1E8A\u1E8C]/g - }, { - 'base': 'Y', - 'letters': /[\u0059\u24CE\uFF39\u1EF2\u00DD\u0176\u1EF8\u0232\u1E8E\u0178\u1EF6\u1EF4\u01B3\u024E\u1EFE]/g - }, { - 'base': 'Z', - 'letters': /[\u005A\u24CF\uFF3A\u0179\u1E90\u017B\u017D\u1E92\u1E94\u01B5\u0224\u2C7F\u2C6B\uA762]/g - }, { - 'base': 'a', - 'letters': /[\u0061\u24D0\uFF41\u1E9A\u00E0\u00E1\u00E2\u1EA7\u1EA5\u1EAB\u1EA9\u00E3\u0101\u0103\u1EB1\u1EAF\u1EB5\u1EB3\u0227\u01E1\u00E4\u01DF\u1EA3\u00E5\u01FB\u01CE\u0201\u0203\u1EA1\u1EAD\u1EB7\u1E01\u0105\u2C65\u0250]/g - }, { - 'base': 'aa', - 'letters': /[\uA733]/g - }, { - 'base': 'ae', - 'letters': /[\u00E6\u01FD\u01E3]/g - }, { - 'base': 'ao', - 'letters': /[\uA735]/g - }, { - 'base': 'au', - 'letters': /[\uA737]/g - }, { - 'base': 'av', - 'letters': /[\uA739\uA73B]/g - }, { - 'base': 'ay', - 'letters': /[\uA73D]/g - }, { - 'base': 'b', - 'letters': /[\u0062\u24D1\uFF42\u1E03\u1E05\u1E07\u0180\u0183\u0253]/g - }, { - 'base': 'c', - 'letters': /[\u0063\u24D2\uFF43\u0107\u0109\u010B\u010D\u00E7\u1E09\u0188\u023C\uA73F\u2184]/g - }, { - 'base': 'd', - 'letters': /[\u0064\u24D3\uFF44\u1E0B\u010F\u1E0D\u1E11\u1E13\u1E0F\u0111\u018C\u0256\u0257\uA77A]/g - }, { - 'base': 'dz', - 'letters': /[\u01F3\u01C6]/g - }, { - 'base': 'e', - 'letters': /[\u0065\u24D4\uFF45\u00E8\u00E9\u00EA\u1EC1\u1EBF\u1EC5\u1EC3\u1EBD\u0113\u1E15\u1E17\u0115\u0117\u00EB\u1EBB\u011B\u0205\u0207\u1EB9\u1EC7\u0229\u1E1D\u0119\u1E19\u1E1B\u0247\u025B\u01DD]/g - }, { - 'base': 'f', - 'letters': /[\u0066\u24D5\uFF46\u1E1F\u0192\uA77C]/g - }, { - 'base': 'g', - 'letters': /[\u0067\u24D6\uFF47\u01F5\u011D\u1E21\u011F\u0121\u01E7\u0123\u01E5\u0260\uA7A1\u1D79\uA77F]/g - }, { - 'base': 'h', - 'letters': /[\u0068\u24D7\uFF48\u0125\u1E23\u1E27\u021F\u1E25\u1E29\u1E2B\u1E96\u0127\u2C68\u2C76\u0265]/g - }, { - 'base': 'hv', - 'letters': /[\u0195]/g - }, { - 'base': 'i', - 'letters': /[\u0069\u24D8\uFF49\u00EC\u00ED\u00EE\u0129\u012B\u012D\u00EF\u1E2F\u1EC9\u01D0\u0209\u020B\u1ECB\u012F\u1E2D\u0268\u0131]/g - }, { - 'base': 'j', - 'letters': /[\u006A\u24D9\uFF4A\u0135\u01F0\u0249]/g - }, { - 'base': 'k', - 'letters': /[\u006B\u24DA\uFF4B\u1E31\u01E9\u1E33\u0137\u1E35\u0199\u2C6A\uA741\uA743\uA745\uA7A3]/g - }, { - 'base': 'l', - 'letters': /[\u006C\u24DB\uFF4C\u0140\u013A\u013E\u1E37\u1E39\u013C\u1E3D\u1E3B\u017F\u0142\u019A\u026B\u2C61\uA749\uA781\uA747]/g - }, { - 'base': 'lj', - 'letters': /[\u01C9]/g - }, { - 'base': 'm', - 'letters': /[\u006D\u24DC\uFF4D\u1E3F\u1E41\u1E43\u0271\u026F]/g - }, { - 'base': 'n', - 'letters': /[\u006E\u24DD\uFF4E\u01F9\u0144\u00F1\u1E45\u0148\u1E47\u0146\u1E4B\u1E49\u019E\u0272\u0149\uA791\uA7A5]/g - }, { - 'base': 'nj', - 'letters': /[\u01CC]/g - }, { - 'base': 'o', - 'letters': /[\u006F\u24DE\uFF4F\u00F2\u00F3\u00F4\u1ED3\u1ED1\u1ED7\u1ED5\u00F5\u1E4D\u022D\u1E4F\u014D\u1E51\u1E53\u014F\u022F\u0231\u00F6\u022B\u1ECF\u0151\u01D2\u020D\u020F\u01A1\u1EDD\u1EDB\u1EE1\u1EDF\u1EE3\u1ECD\u1ED9\u01EB\u01ED\u00F8\u01FF\u0254\uA74B\uA74D\u0275]/g - }, { - 'base': 'oi', - 'letters': /[\u01A3]/g - }, { - 'base': 'ou', - 'letters': /[\u0223]/g - }, { - 'base': 'oo', - 'letters': /[\uA74F]/g - }, { - 'base': 'p', - 'letters': /[\u0070\u24DF\uFF50\u1E55\u1E57\u01A5\u1D7D\uA751\uA753\uA755]/g - }, { - 'base': 'q', - 'letters': /[\u0071\u24E0\uFF51\u024B\uA757\uA759]/g - }, { - 'base': 'r', - 'letters': /[\u0072\u24E1\uFF52\u0155\u1E59\u0159\u0211\u0213\u1E5B\u1E5D\u0157\u1E5F\u024D\u027D\uA75B\uA7A7\uA783]/g - }, { - 'base': 's', - 'letters': /[\u0073\u24E2\uFF53\u00DF\u015B\u1E65\u015D\u1E61\u0161\u1E67\u1E63\u1E69\u0219\u015F\u023F\uA7A9\uA785\u1E9B]/g - }, { - 'base': 't', - 'letters': /[\u0074\u24E3\uFF54\u1E6B\u1E97\u0165\u1E6D\u021B\u0163\u1E71\u1E6F\u0167\u01AD\u0288\u2C66\uA787]/g - }, { - 'base': 'tz', - 'letters': /[\uA729]/g - }, { - 'base': 'u', - 'letters': /[\u0075\u24E4\uFF55\u00F9\u00FA\u00FB\u0169\u1E79\u016B\u1E7B\u016D\u00FC\u01DC\u01D8\u01D6\u01DA\u1EE7\u016F\u0171\u01D4\u0215\u0217\u01B0\u1EEB\u1EE9\u1EEF\u1EED\u1EF1\u1EE5\u1E73\u0173\u1E77\u1E75\u0289]/g - }, { - 'base': 'v', - 'letters': /[\u0076\u24E5\uFF56\u1E7D\u1E7F\u028B\uA75F\u028C]/g - }, { - 'base': 'vy', - 'letters': /[\uA761]/g - }, { - 'base': 'w', - 'letters': /[\u0077\u24E6\uFF57\u1E81\u1E83\u0175\u1E87\u1E85\u1E98\u1E89\u2C73]/g - }, { - 'base': 'x', - 'letters': /[\u0078\u24E7\uFF58\u1E8B\u1E8D]/g - }, { - 'base': 'y', - 'letters': /[\u0079\u24E8\uFF59\u1EF3\u00FD\u0177\u1EF9\u0233\u1E8F\u00FF\u1EF7\u1E99\u1EF5\u01B4\u024F\u1EFF]/g - }, { - 'base': 'z', - 'letters': /[\u007A\u24E9\uFF5A\u017A\u1E91\u017C\u017E\u1E93\u1E95\u01B6\u0225\u0240\u2C6C\uA763]/g - }]; - - for (var i = 0; i < defaultDiacriticsRemovalMap.length; i++) { - str = str.replace(defaultDiacriticsRemovalMap[i].letters, defaultDiacriticsRemovalMap[i].base); - } - - return str; + for (let i = 0; i < defaultDiacriticsRemovalMap.length; i++) { + str = str.replace(defaultDiacriticsRemovalMap[i].letters, defaultDiacriticsRemovalMap[i].base); + } + return str; } // Insert links in Takealot page function insertMBSection(release) { - //LOGGER.debug("insertMBsection Firing"); + //LOGGER.debug("insertMBsection Firing"); - var mbUI = $('

      MusicBrainz

      ').hide(); + let mbUI = $('

      MusicBrainz

      ').hide(); - if (DEBUG) mbUI.css({ - 'border': '3px dotted red' - }); + if (DEBUG) + mbUI.css({ + border: '3px dotted red' + }); - var mbContentBlock = $('
      '); - mbUI.append(mbContentBlock); + let mbContentBlock = $('
      '); + mbUI.append(mbContentBlock); - if (release.maybe_buggy) { - var warning_buggy = $('

      Warning: this release is buggy, please check twice the data you import.Warning: this release is buggy, please check twice the data you import.'; - mbContentBlock.append(innerHTML); + // Form parameters + let edit_note = MBImport.makeEditNote(window.location.href, 'Takealot'); + LOGGER.debug('Edit Note: ', edit_note); + let parameters = MBImport.buildFormParameters(release, edit_note); + // LOGGER.debug("*** Form parameters: ", parameters); + // Build form + search button + let innerHTML = `

      ${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}
      `; + mbContentBlock.append(innerHTML); - insertMbUI(mbUI); - insertIMGlinks(); - insertMBLinks(); + insertMbUI(mbUI); + insertIMGlinks(); + insertMBLinks(); - $('#mb_buttons').css({ - display: 'inline-block', - width: '100%' - }); - $('form.musicbrainz_import').css({ - width: '49%', - display: 'inline-block' - }); - $('form.musicbrainz_import_search').css({ - 'float': 'right' - }); - $('form.musicbrainz_import > button').css({ - width: '100%', - 'box-sizing': 'border-box' - }); + $('#mb_buttons').css({ + display: 'inline-block', + width: '100%' + }); + $('form.musicbrainz_import').css({ + width: '49%', + display: 'inline-block' + }); + $('form.musicbrainz_import_search').css({ + float: 'right' + }); + $('form.musicbrainz_import > button').css({ + width: '100%', + 'box-sizing': 'border-box' + }); - mbUI.slideDown(); + mbUI.slideDown(); } // Insert link to MB release (MB Release need a URL entry to match ) function insertMBLinks() { - var mblinks = new MBLinks('TAKEALOT_CACHE', 7 * 24 * 60); // force refresh of cached links once a week + let mblinks = new MBLinks('TAKEALOT_CACHE', 7 * 24 * 60); // force refresh of cached links once a week - // var artist_link = 'http://' + window.location.href.match( /^https?:\/\/(.*)\/album\/.+$/i)[1]; - // mblinks.searchAndDisplayMbLink(artist_link, 'artist', function (link) { $('div#there').before(link); } ); - - var album_link = window.location.href; - mblinks.searchAndDisplayMbLink(album_link, 'release', function(link) { - $('h1.fn').append(link); - }); + // var artist_link = 'http://' + window.location.href.match( /^https?:\/\/(.*)\/album\/.+$/i)[1]; + // mblinks.searchAndDisplayMbLink(artist_link, 'artist', function (link) { $('div#there').before(link); } ); + let album_link = window.location.href; + mblinks.searchAndDisplayMbLink(album_link, 'release', function(link) { + $('h1.fn').append(link); + }); } // Analyze Takealot data and return a release object function ParseTakealotPage() { - LOGGER.debug("ParseTakealotPage function firing"); + LOGGER.debug('ParseTakealotPage function firing'); - var releasebarcode = ""; - var releasecountry = ""; - var releasedaterel = ""; - var releaselanguage = ""; - var releasetitle = ""; - var releaselabel = []; - var releaseformat = ""; - var release_maybe_buggy = false; + let releasebarcode = ''; + let releasecountry = ''; + let releasedaterel = ''; + let releaselanguage = ''; + let releasetitle = ''; + let releaselabel = []; + let releaseformat = ''; + let release_maybe_buggy = false; - // Select all DL data in the "Product Info" div id = second div class = details - var allinfolist = document.querySelectorAll("div#second > div.details > dl > *"); - // Iterate all over the lines - for (var i = 0; i < allinfolist.length; i++) { - var artistitemlabel = allinfolist[i]; + // Select all DL data in the "Product Info" div id = second div class = details + let allinfolist = document.querySelectorAll('div#second > div.details > dl > *'); + // Iterate all over the lines + for (let i = 0; i < allinfolist.length; i++) { + let artistitemlabel = allinfolist[i]; - if (artistitemlabel.tagName == "DT") { - var artistitem = artistitemlabel.textContent.toLowerCase(); - switch (artistitem) { - case "barcode": // use these cases to select the spesific text values - releasebarcode = artistitemlabel.nextSibling.textContent.trim(); - LOGGER.debug('The value is :' + artistitem + ' > ' + releasebarcode); - break; - case "country": // use these cases to select the spesific text values - releasecountry = artistitemlabel.nextSibling.textContent.trim(); - LOGGER.debug('The value is :' + artistitem + ' > ' + releasecountry); - break; - case "artists": // use these cases to select the spesific text values - releaseartist = artistitemlabel.nextSibling.textContent.trim(); - LOGGER.debug('The value is :' + artistitem + ' > ' + releaseartist); - break; - case "label": // use these cases to select the spesific text values - releaselabel.push({ - name: artistitemlabel.nextSibling.textContent.trim() - }); - LOGGER.debug('The value is :' + artistitem + ' > ' + releaselabel); - break; - case "date released": // use these cases to select the spesific text values - releasedaterel = artistitemlabel.nextSibling.textContent.trim(); - LOGGER.debug('The value is :' + artistitem + ' > ' + releasedaterel); - break; - case "format": // use these cases to select the spesific text values - releaseformat = artistitemlabel.nextSibling.textContent.trim(); - LOGGER.debug('The value is :' + artistitem + ' > ' + releaseformat); - break; - case "language": // use these cases to select the spesific text values - releaselanguage = artistitemlabel.nextSibling.textContent.trim(); - LOGGER.debug('The value is :' + artistitem + ' > ' + releaselanguage); - break; - case "title": // use these cases to select the spesific text values - releasetitle = artistitemlabel.nextSibling.textContent.trim(); - LOGGER.debug('The value is :' + artistitem + ' > ' + releasetitle); - break; - case "tracks": // use these cases to select the spesific text values - LOGGER.debug('The label chosen is :' + artistitem); + if (artistitemlabel.tagName == 'DT') { + let artistitem = artistitemlabel.textContent.toLowerCase(); + switch (artistitem) { + case 'barcode': // use these cases to select the spesific text values + releasebarcode = artistitemlabel.nextSibling.textContent.trim(); + LOGGER.debug(`The value is :${artistitem} > ${releasebarcode}`); + break; + case 'country': // use these cases to select the spesific text values + releasecountry = artistitemlabel.nextSibling.textContent.trim(); + LOGGER.debug(`The value is :${artistitem} > ${releasecountry}`); + break; + case 'artists': // use these cases to select the spesific text values + releaseartist = artistitemlabel.nextSibling.textContent.trim(); + LOGGER.debug(`The value is :${artistitem} > ${releaseartist}`); + break; + case 'label': // use these cases to select the spesific text values + releaselabel.push({ + name: artistitemlabel.nextSibling.textContent.trim() + }); + LOGGER.debug(`The value is :${artistitem} > ${releaselabel}`); + break; + case 'date released': // use these cases to select the spesific text values + releasedaterel = artistitemlabel.nextSibling.textContent.trim(); + LOGGER.debug(`The value is :${artistitem} > ${releasedaterel}`); + break; + case 'format': // use these cases to select the spesific text values + releaseformat = artistitemlabel.nextSibling.textContent.trim(); + LOGGER.debug(`The value is :${artistitem} > ${releaseformat}`); + break; + case 'language': // use these cases to select the spesific text values + releaselanguage = artistitemlabel.nextSibling.textContent.trim(); + LOGGER.debug(`The value is :${artistitem} > ${releaselanguage}`); + break; + case 'title': // use these cases to select the spesific text values + releasetitle = artistitemlabel.nextSibling.textContent.trim(); + LOGGER.debug(`The value is :${artistitem} > ${releasetitle}`); + break; + case 'tracks': // use these cases to select the spesific text values + LOGGER.debug(`The label chosen is :${artistitem}`); - // Iterate over all the tracks - changed * to li to try and only catch tracks - var alltracklist = document.querySelectorAll("div#second > div.details > dl > dd > ol:last-child > li"); - LOGGER.debug(" *** Dump the tracks nodeList to see what is going on ***"); - LOGGER.debug(alltracklist); - // Tracks - var tracklistarray = new Array(); // create the tracklist array to use later + // Iterate over all the tracks - changed * to li to try and only catch tracks + var alltracklist = document.querySelectorAll('div#second > div.details > dl > dd > ol:last-child > li'); + LOGGER.debug(' *** Dump the tracks nodeList to see what is going on ***'); + LOGGER.debug(alltracklist); + // Tracks + var tracklistarray = new Array(); // create the tracklist array to use later - // var releaseartist = alltracklist[0].textContent.trim(); - // The format on Takealot changed and Artist is not the first element in li anymore but last - // remember this is a nodeList and not an array - var releaseartist = alltracklist[alltracklist.length - 1].textContent.trim(); - LOGGER.debug('The album artist:' + releaseartist); + // var releaseartist = alltracklist[0].textContent.trim(); + // The format on Takealot changed and Artist is not the first element in li anymore but last + // remember this is a nodeList and not an array + var releaseartist = alltracklist[alltracklist.length - 1].textContent.trim(); + LOGGER.debug(`The album artist:${releaseartist}`); - // Last track to find last disc number - var lasttrack = alltracklist[alltracklist.length - 2].textContent.trim(); - LOGGER.debug('The last track:' + lasttrack); + // Last track to find last disc number + var lasttrack = alltracklist[alltracklist.length - 2].textContent.trim(); + LOGGER.debug(`The last track:${lasttrack}`); - lastdiscnumberregex = /\[ Disc (.*) Track./; // regex to match disc number from last track - var lastdiscnumbermatch = lasttrack.match(lastdiscnumberregex); - var lastdiscnumber = parseInt(lastdiscnumbermatch[1]); - LOGGER.debug("Last Disc Number: ", lastdiscnumber); + lastdiscnumberregex = /\[ Disc (.*) Track./; // regex to match disc number from last track + var lastdiscnumbermatch = lasttrack.match(lastdiscnumberregex); + var lastdiscnumber = parseInt(lastdiscnumbermatch[1]); + LOGGER.debug('Last Disc Number: ', lastdiscnumber); - // Discs - var disclistarray = new Array(); // create the tracklist array to use later + // Discs + var disclistarray = new Array(); // create the tracklist array to use later - for (var k = 1; k < lastdiscnumber + 1; k++) { // start at 1 to keep array in sync with disc numbers - LOGGER.debug("Disc iterate: ", k); + for (var k = 1; k < lastdiscnumber + 1; k++) { + // start at 1 to keep array in sync with disc numbers + LOGGER.debug('Disc iterate: ', k); - // Tracks - var tracklistarray = new Array(); // create the track list array + // Tracks + var tracklistarray = new Array(); // create the track list array - for (var j = 0; j < alltracklist.length - 1; j++) { // changed j to 0 and length-1 as Artist is at end - // do regex here and if current disc listed in track = k then push the track into the array for that disc - var trackdetails = alltracklist[j].textContent.trim(); - disctracktitleregex = /\[ Disc (\d{2}) Track.(\b\d{2}) \] (.*)/; - var disctracktitle = trackdetails.match(disctracktitleregex); + for (let j = 0; j < alltracklist.length - 1; j++) { + // changed j to 0 and length-1 as Artist is at end + // do regex here and if current disc listed in track = k then push the track into the array for that disc + let trackdetails = alltracklist[j].textContent.trim(); + disctracktitleregex = /\[ Disc (\d{2}) Track.(\b\d{2}) \] (.*)/; + let disctracktitle = trackdetails.match(disctracktitleregex); - var currentdiscnumber = parseInt(disctracktitle[1]); + let currentdiscnumber = parseInt(disctracktitle[1]); - if (currentdiscnumber == k) { - var track = new Object(); - track.number = parseInt(disctracktitle[2]); - track.title = disctracktitle[3]; - LOGGER.debug("The track object: ", currentdiscnumber + ' - ' + track.number + " - " + track.title); - tracklistarray.push(track); - } - } - disclistarray.push(tracklistarray); - } + if (currentdiscnumber == k) { + var track = new Object(); + track.number = parseInt(disctracktitle[2]); + track.title = disctracktitle[3]; + LOGGER.debug('The track object: ', `${currentdiscnumber} - ${track.number} - ${track.title}`); + tracklistarray.push(track); + } + } + disclistarray.push(tracklistarray); + } - LOGGER.debug("** Disclist Array *** ", disclistarray); - break; - } - } + LOGGER.debug('** Disclist Array *** ', disclistarray); + break; + } + } + } - } + // Logic added to derive the release title from the heading if missing from product info + if (releasetitle == '') { + let MediaHeading = document.querySelectorAll('h1.fn'); + let TitleStr = MediaHeading[0].innerText; + var TitleRegex = /(.*)-(.*)+\s\(([^)]+)\)/; - // Logic added to derive the release title from the heading if missing from product info - if (releasetitle == "") { - var MediaHeading = document.querySelectorAll("h1.fn"); - var TitleStr = MediaHeading[0].innerText; - var TitleRegex = /(.*)-(.*)+\s\(([^)]+)\)/; + if (TitleStr.match(TitleRegex)) { + var HeadArray = TitleStr.match(TitleRegex); + LOGGER.debug('HeadArray', HeadArray); + if (removeDiacritics(HeadArray[1].trim()) == releaseartist) { + LOGGER.debug('matched title equal the releaseartist therefore swapped'); + releasetitle = HeadArray[2].trim(); + } else { + LOGGER.debug('matched title equal the title therefore not swapped'); + releasetitle = HeadArray[1].trim(); + LOGGER.debug('Title:', releasetitle, ' Artist:', releaseartist); + // check if artist assigned else make the remaining value the artist and mark buggy true + if (releaseartist == null) { + releaseartist = HeadArray[2].trim(); + release_maybe_buggy = true; + } + } + } else { + LOGGER.debug('The Heading REGEX not matched!!'); + var TitleRegex = /(.*)+\s\(([^)]+)\)/; + var HeadArray = TitleStr.match(TitleRegex); + LOGGER.debug('HeadArray', HeadArray); + releasetitle = HeadArray[1].trim(); + if (releaseformat == null) { + releaseformat = HeadArray[2].trim(); + } + } - if (TitleStr.match(TitleRegex)) { - var HeadArray = TitleStr.match(TitleRegex); - LOGGER.debug("HeadArray", HeadArray); - if (removeDiacritics(HeadArray[1].trim()) == releaseartist) { - LOGGER.debug('matched title equal the releaseartist therefore swapped'); - releasetitle = HeadArray[2].trim(); - } else { - LOGGER.debug('matched title equal the title therefore not swapped'); - releasetitle = HeadArray[1].trim(); - LOGGER.debug("Title:", releasetitle, " Artist:", releaseartist); - // check if artist assigned else make the remaining value the artist and mark buggy true - if (releaseartist == null) { - releaseartist = HeadArray[2].trim(); - release_maybe_buggy = true; - } - } - } else { + LOGGER.debug('Release Title from heading:', releasetitle); + } - LOGGER.debug("The Heading REGEX not matched!!"); - var TitleRegex = /(.*)+\s\(([^)]+)\)/; - var HeadArray = TitleStr.match(TitleRegex); - LOGGER.debug("HeadArray", HeadArray); - releasetitle = HeadArray[1].trim(); - if (releaseformat == null) { - releaseformat = HeadArray[2].trim(); - } - } + var thediscnumber = 0; + let allprodinfo = ''; + let descriptionarray = []; - LOGGER.debug("Release Title from heading:", releasetitle); - } + if (lastdiscnumber > 0) { + LOGGER.debug('** Tracklist present in Product Info tab **'); + } else { + LOGGER.debug(" ** No tracks in Product Info tab let's have a look in description tab"); + // TODO logic to check VA and below or artist with "Tracklisting:" and no Disc 1... + if (document.querySelectorAll('div#prod-desc > br').length != 0) { + // Known format based on
      + LOGGER.debug(' ** Formatting based on
      '); + allprodinfo = document.querySelectorAll('div#prod-desc > br'); // Select all data in the "Description" div id = prod-desc with
      + for (var k = 0; k < allprodinfo.length - 1; k++) { + descriptionrow = allprodinfo[k].nextSibling.textContent.trim(); + // LOGGER.debug("PROD-INFO > BR > ",descriptionrow); + // regex to find Disc 1 and add 1 to a group ^Disc+(.\d) + descriptionrowregex = /^Disc+(.\d)/; + var founddisc = descriptionrow.match(descriptionrowregex); + LOGGER.debug(' **** DISC FOUND ****', founddisc); + if (founddisc != null) { + var thediscnumber = parseInt(founddisc[1]); + // LOGGER.debug(" **** DISC FOUND NUMBER ****", thediscnumber); + } + LOGGER.debug('PROD-INFO > BR > ', `${thediscnumber}-${descriptionrow}`); + if (thediscnumber == 0) { + thediscnumber = 1; + LOGGER.debug(' **** DISC NUMBER ****', thediscnumber); + } - var thediscnumber = 0; - var allprodinfo = ""; - var descriptionarray = []; + // regex to split the description row into track, title and artist (^\d).(.*)-(.*) + var descriptionrowregex = /(^\d+).(.*)-(.*)/; + //var descriptionrow_tracktitleartist = descriptionrow.match(descriptionrowregex); + if (descriptionrow.match(descriptionrowregex) != null) { + LOGGER.debug('Track. title - Artist'); + var descriptionrow_tracktitleartist = descriptionrow.match(descriptionrowregex); + // do the same as in tracklist and push the disc numbers into an array + descriptiontrack = new Object(); - if (lastdiscnumber > 0) { - LOGGER.debug("** Tracklist present in Product Info tab **"); - } else { - LOGGER.debug(" ** No tracks in Product Info tab let's have a look in description tab"); - // TODO logic to check VA and below or artist with "Tracklisting:" and no Disc 1... - if (document.querySelectorAll("div#prod-desc > br").length != 0) { // Known format based on
      - LOGGER.debug(" ** Formatting based on
      "); - allprodinfo = document.querySelectorAll("div#prod-desc > br"); // Select all data in the "Description" div id = prod-desc with
      - for (var k = 0; k < allprodinfo.length - 1; k++) { - descriptionrow = allprodinfo[k].nextSibling.textContent.trim(); - // LOGGER.debug("PROD-INFO > BR > ",descriptionrow); - // regex to find Disc 1 and add 1 to a group ^Disc+(.\d) - descriptionrowregex = /^Disc+(.\d)/; - var founddisc = descriptionrow.match(descriptionrowregex); - LOGGER.debug(" **** DISC FOUND ****", founddisc); - if (founddisc != null) { - var thediscnumber = parseInt(founddisc[1]); - // LOGGER.debug(" **** DISC FOUND NUMBER ****", thediscnumber); - } - LOGGER.debug("PROD-INFO > BR > ", thediscnumber + '-' + descriptionrow); + if (descriptionrow_tracktitleartist != null) { + descriptiontrack.disc = thediscnumber; + descriptiontrack.track = descriptionrow_tracktitleartist[1]; + descriptiontrack.title = descriptionrow_tracktitleartist[2].trim(); + descriptiontrack.artist = descriptionrow_tracktitleartist[3]; - if (thediscnumber == 0) { - thediscnumber = 1; - LOGGER.debug(" **** DISC NUMBER ****", thediscnumber); - } + //to get the last disc number via iterate + var description_lastdisc = parseInt(thediscnumber); + descriptionarray.push(descriptiontrack); + } + } else { + LOGGER.debug('Assume Track. title'); + // regex to split the description row into track. title (^\d).(.*) + var descriptionrowregex = /(^\d+).(.*)/; + descriptionrow_tracktitleartist = descriptionrow.match(descriptionrowregex); + // do the same as in tracklist and push the disc numbers into an array + descriptiontrack = new Object(); - // regex to split the description row into track, title and artist (^\d).(.*)-(.*) - var descriptionrowregex = /(^\d+).(.*)-(.*)/; - //var descriptionrow_tracktitleartist = descriptionrow.match(descriptionrowregex); + if (descriptionrow_tracktitleartist != null) { + descriptiontrack.disc = thediscnumber; + descriptiontrack.track = descriptionrow_tracktitleartist[1]; + descriptiontrack.title = descriptionrow_tracktitleartist[2]; + descriptiontrack.artist = releaseartist; - if (descriptionrow.match(descriptionrowregex) != null) { - LOGGER.debug("Track. title - Artist"); - var descriptionrow_tracktitleartist = descriptionrow.match(descriptionrowregex); - // do the same as in tracklist and push the disc numbers into an array - descriptiontrack = new Object(); + //to get the last disc number via iterate + var description_lastdisc = parseInt(thediscnumber); + descriptionarray.push(descriptiontrack); + } + } + } + } else if (document.querySelectorAll('div#prod-desc > div').length != 0) { + // New format encountered based on
      LOGGER.debug(" ** Formatting based on
      "); + LOGGER.debug(' ** Formatting based on
      '); + allprodinfo = document.querySelectorAll('div#prod-desc > div'); // Select all data in the "Description" div id = prod-desc with
      + for (let div_iterate = 0; div_iterate < allprodinfo.length; div_iterate++) { + //LOGGER.debug(div_iterate," - ",allprodinfo[div_iterate].textContent.trim()); + descriptionrow = allprodinfo[div_iterate].textContent.trim(); - if (descriptionrow_tracktitleartist != null) { - descriptiontrack.disc = thediscnumber; - descriptiontrack.track = descriptionrow_tracktitleartist[1]; - descriptiontrack.title = descriptionrow_tracktitleartist[2].trim(); - descriptiontrack.artist = descriptionrow_tracktitleartist[3]; + descriptionrowdiscregex = /^[Disc|CD]+(.\d)/; // need to find more div samples to test variants + var founddisc = descriptionrow.match(descriptionrowdiscregex); - //to get the last disc number via iterate - var description_lastdisc = parseInt(thediscnumber); - descriptionarray.push(descriptiontrack); - } - } else { - LOGGER.debug("Assume Track. title"); - // regex to split the description row into track. title (^\d).(.*) - var descriptionrowregex = /(^\d+).(.*)/; - descriptionrow_tracktitleartist = descriptionrow.match(descriptionrowregex); - // do the same as in tracklist and push the disc numbers into an array - descriptiontrack = new Object(); + if (founddisc != null) { + var thediscnumber = parseInt(founddisc[1]); + LOGGER.debug(' **** DISC FOUND NUMBER ****', thediscnumber); + } - if (descriptionrow_tracktitleartist != null) { - descriptiontrack.disc = thediscnumber; - descriptiontrack.track = descriptionrow_tracktitleartist[1]; - descriptiontrack.title = descriptionrow_tracktitleartist[2]; - descriptiontrack.artist = releaseartist; + LOGGER.debug('FOUNDDISC# ', founddisc); + // else if (founddisc == null) { + // var thediscnumber = 1; + // LOGGER.debug(" **** DISC NUMBER ****", thediscnumber); + // } - //to get the last disc number via iterate - var description_lastdisc = parseInt(thediscnumber); - descriptionarray.push(descriptiontrack); - } - } - } - } else if (document.querySelectorAll("div#prod-desc > div").length != 0) { // New format encountered based on
      LOGGER.debug(" ** Formatting based on
      "); - LOGGER.debug(" ** Formatting based on
      "); - allprodinfo = document.querySelectorAll("div#prod-desc > div"); // Select all data in the "Description" div id = prod-desc with
      - for (var div_iterate = 0; div_iterate < allprodinfo.length; div_iterate++) { - //LOGGER.debug(div_iterate," - ",allprodinfo[div_iterate].textContent.trim()); - descriptionrow = allprodinfo[div_iterate].textContent.trim(); + if (founddisc == null) { + var thediscnumber = 1; + LOGGER.debug(' **** DISC NUMBER ****', thediscnumber); + } - descriptionrowdiscregex = /^[Disc|CD]+(.\d)/; // need to find more div samples to test variants - var founddisc = descriptionrow.match(descriptionrowdiscregex); + descriptionrowregex = /(^\d+).(.*)/; + let descriptionrow_tracknumtitle = descriptionrow.match(descriptionrowregex); + descriptiontrack = new Object(); - if (founddisc != null) { - var thediscnumber = parseInt(founddisc[1]); - LOGGER.debug(" **** DISC FOUND NUMBER ****", thediscnumber); - } + if (descriptionrow_tracknumtitle != null) { + LOGGER.debug('** Track **', descriptionrow_tracknumtitle); + descriptiontrack.disc = thediscnumber; + descriptiontrack.track = descriptionrow_tracknumtitle[1]; + descriptiontrack.title = descriptionrow_tracknumtitle[2].trim(); + descriptiontrack.artist = releaseartist; // need to do logic to check regex with and without artist - LOGGER.debug("FOUNDDISC# ", founddisc); - // else if (founddisc == null) { - // var thediscnumber = 1; - // LOGGER.debug(" **** DISC NUMBER ****", thediscnumber); - // } + //to get the last disc number via iterate + var description_lastdisc = parseInt(thediscnumber); + descriptionarray.push(descriptiontrack); + } + } + } else { + LOGGER.info(' ***** Unknown formatting ****** '); + release_maybe_buggy = true; + } - if (founddisc == null) { - var thediscnumber = 1; - LOGGER.debug(" **** DISC NUMBER ****", thediscnumber); - } + // Discs + var disclistarray = new Array(); // create the tracklist array to use later - descriptionrowregex = /(^\d+).(.*)/; - var descriptionrow_tracknumtitle = descriptionrow.match(descriptionrowregex); + for (let desc_discs = 0; desc_discs < description_lastdisc; desc_discs++) { + var tracklistarray = new Array(); + for (let desc__track = 0; desc__track < descriptionarray.length; desc__track++) { + let desc_currentdiscnumber = descriptionarray[desc__track].disc; + if (desc_currentdiscnumber == desc_discs + 1) { + var track = new Object(); + let track_artist_credit = new Array(); - descriptiontrack = new Object(); + track.number = descriptionarray[desc__track].track; + track.title = descriptionarray[desc__track].title; - if (descriptionrow_tracknumtitle != null) { - LOGGER.debug("** Track **", descriptionrow_tracknumtitle); - descriptiontrack.disc = thediscnumber; - descriptiontrack.track = descriptionrow_tracknumtitle[1]; - descriptiontrack.title = descriptionrow_tracknumtitle[2].trim(); - descriptiontrack.artist = releaseartist; // need to do logic to check regex with and without artist + let track_artist_credit_object = new Object(); + track_artist_credit_object.artist_name = descriptionarray[desc__track].artist; + track_artist_credit.push(track_artist_credit_object); + //track_artist_credit.artist_name = descriptionarray[desc__track].artist; + track.artist_credit = track_artist_credit; + tracklistarray.push(track); + } + } + disclistarray.push(tracklistarray); + } + lastdiscnumber = description_lastdisc; + } - //to get the last disc number via iterate - var description_lastdisc = parseInt(thediscnumber); - descriptionarray.push(descriptiontrack); - } + // do final checks to determine if it may be buggy + if (releaseartist == null) { + release_maybe_buggy = true; + } - } - } else { - LOGGER.info(" ***** Unknown formatting ****** "); - release_maybe_buggy = true; - } + release = new Object(); + release.maybe_buggy = release_maybe_buggy; - // Discs - var disclistarray = new Array(); // create the tracklist array to use later + // Release artist credit + release.artist_credit = new Array(); + let artist_name = releaseartist; + release.artist_credit.push({ + artist_name: artist_name + }); - for (var desc_discs = 0; desc_discs < description_lastdisc; desc_discs++) { - var tracklistarray = new Array(); - for (var desc__track = 0; desc__track < descriptionarray.length; desc__track++) { + // Release title + release.title = releasetitle; + // Release Barcode + release.barcode = releasebarcode; - var desc_currentdiscnumber = descriptionarray[desc__track].disc; - if (desc_currentdiscnumber == desc_discs + 1) { - var track = new Object(); - var track_artist_credit = new Array(); + // Default status is official + release.status = 'official'; - track.number = descriptionarray[desc__track].track; - track.title = descriptionarray[desc__track].title; + // Other hard-coded info + release.script = 'Latn'; - var track_artist_credit_object = new Object(); - track_artist_credit_object.artist_name = descriptionarray[desc__track].artist; - track_artist_credit.push(track_artist_credit_object); - //track_artist_credit.artist_name = descriptionarray[desc__track].artist; - track.artist_credit = track_artist_credit; - tracklistarray.push(track); - } - } - disclistarray.push(tracklistarray); - } - lastdiscnumber = description_lastdisc; - } + release.country = Countries[releasecountry]; + release.language = Languages[releaselanguage]; - // do final checks to determine if it may be buggy - if (releaseartist == null) { - release_maybe_buggy = true; - } + release.discs = new Array(); + for (let l = 0; l < lastdiscnumber; l++) { + // LOGGER.debug("Disc position:", l + 1); + // LOGGER.debug("Tracklist for the selected disc: ", disclistarray[l]); + let disc = { + position: l + 1, + format: DiscFormats[releaseformat], + tracks: disclistarray[l] + }; + release.discs.push(disc); + } - release = new Object(); + release.labels = releaselabel; - release.maybe_buggy = release_maybe_buggy; + // Release URL + release.urls = new Array(); + release.urls.push({ + url: window.location.href, + link_type: MBImport.URL_TYPES.purchase_for_mail_order + }); //type 74 is purchase for download + // TODO check if CD then add purchase medium - // Release artist credit - release.artist_credit = new Array(); + // Release date + let releasedate = releasedaterel; + if (typeof releasedate != 'undefined' && releasedate != '') { + let tmp = releasedate.split('-'); + if (tmp[0] != 'undefined' && tmp[0] != '') { + release.year = parseInt(tmp[0], 10); + if (tmp[1] != 'undefined' && tmp[1] != '') { + release.month = parseInt(tmp[1], 10); + if (tmp[2] != 'undefined' && tmp[2] != '') { + release.day = parseInt(tmp[2], 10); + } + } + } + } - var artist_name = releaseartist; - release.artist_credit.push({ - 'artist_name': artist_name - }); + LOGGER.info('Release:', release); - // Release title - release.title = releasetitle; - // Release Barcode - release.barcode = releasebarcode; - - // Default status is official - release.status = 'official'; - - // Other hard-coded info - release.script = 'Latn'; - - release.country = Countries[releasecountry]; - release.language = Languages[releaselanguage]; - - release.discs = new Array(); - for (var l = 0; l < lastdiscnumber; l++) { - // LOGGER.debug("Disc position:", l + 1); - // LOGGER.debug("Tracklist for the selected disc: ", disclistarray[l]); - var disc = { - 'position': l + 1, - 'format': DiscFormats[releaseformat], - 'tracks': disclistarray[l] - }; - release.discs.push(disc); - } - - release.labels = releaselabel; - - // Release URL - release.urls = new Array(); - release.urls.push({ - 'url': window.location.href, - 'link_type': MBImport.URL_TYPES.purchase_for_mail_order - }); //type 74 is purchase for download - // TODO check if CD then add purchase medium - - // Release date - var releasedate = releasedaterel; - if (typeof releasedate != "undefined" && releasedate != "") { - var tmp = releasedate.split('-'); - if (tmp[0] != "undefined" && tmp[0] != "") { - release.year = parseInt(tmp[0], 10); - if (tmp[1] != "undefined" && tmp[1] != "") { - release.month = parseInt(tmp[1], 10); - if (tmp[2] != "undefined" && tmp[2] != "") { - release.day = parseInt(tmp[2], 10); - } - } - } - } - - LOGGER.info("Release:", release); - - return release; + return release; } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// @@ -788,267 +862,267 @@ function ParseTakealotPage() { //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// var DiscFormats = new Array(); -DiscFormats["CD"] = "CD"; -DiscFormats["DVD"] = "DVD"; -DiscFormats["Audio CD"] = "CD"; +DiscFormats['CD'] = 'CD'; +DiscFormats['DVD'] = 'DVD'; +DiscFormats['Audio CD'] = 'CD'; var Languages = new Array(); -Languages["Afrikaans"] = "afr"; +Languages['Afrikaans'] = 'afr'; var Countries = new Array(); -Countries["Afghanistan"] = "AF"; -Countries["Albania"] = "AL"; -Countries["Algeria"] = "DZ"; -Countries["American Samoa"] = "AS"; -Countries["Andorra"] = "AD"; -Countries["Angola"] = "AO"; -Countries["Anguilla"] = "AI"; -Countries["Antarctica"] = "AQ"; -Countries["Antigua and Barbuda"] = "AG"; -Countries["Argentina"] = "AR"; -Countries["Armenia"] = "AM"; -Countries["Aruba"] = "AW"; -Countries["Australia"] = "AU"; -Countries["Austria"] = "AT"; -Countries["Azerbaijan"] = "AZ"; -Countries["Bahamas"] = "BS"; -Countries["Bahrain"] = "BH"; -Countries["Bangladesh"] = "BD"; -Countries["Barbados"] = "BB"; -Countries["Belarus"] = "BY"; -Countries["Belgium"] = "BE"; -Countries["Belize"] = "BZ"; -Countries["Benin"] = "BJ"; -Countries["Bermuda"] = "BM"; -Countries["Bhutan"] = "BT"; -Countries["Bolivia"] = "BO"; -Countries["Croatia"] = "HR"; -Countries["Botswana"] = "BW"; -Countries["Bouvet Island"] = "BV"; -Countries["Brazil"] = "BR"; -Countries["British Indian Ocean Territory"] = "IO"; -Countries["Brunei Darussalam"] = "BN"; -Countries["Bulgaria"] = "BG"; -Countries["Burkina Faso"] = "BF"; -Countries["Burundi"] = "BI"; -Countries["Cambodia"] = "KH"; -Countries["Cameroon"] = "CM"; -Countries["Canada"] = "CA"; -Countries["Cape Verde"] = "CV"; -Countries["Cayman Islands"] = "KY"; -Countries["Central African Republic"] = "CF"; -Countries["Chad"] = "TD"; -Countries["Chile"] = "CL"; -Countries["China"] = "CN"; -Countries["Christmas Island"] = "CX"; -Countries["Cocos (Keeling) Islands"] = "CC"; -Countries["Colombia"] = "CO"; -Countries["Comoros"] = "KM"; -Countries["Congo"] = "CG"; -Countries["Cook Islands"] = "CK"; -Countries["Costa Rica"] = "CR"; -Countries["Virgin Islands, British"] = "VG"; -Countries["Cuba"] = "CU"; -Countries["Cyprus"] = "CY"; -Countries["Czech Republic"] = "CZ"; -Countries["Denmark"] = "DK"; -Countries["Djibouti"] = "DJ"; -Countries["Dominica"] = "DM"; -Countries["Dominican Republic"] = "DO"; -Countries["Ecuador"] = "EC"; -Countries["Egypt"] = "EG"; -Countries["El Salvador"] = "SV"; -Countries["Equatorial Guinea"] = "GQ"; -Countries["Eritrea"] = "ER"; -Countries["Estonia"] = "EE"; -Countries["Ethiopia"] = "ET"; -Countries["Falkland Islands (Malvinas)"] = "FK"; -Countries["Faroe Islands"] = "FO"; -Countries["Fiji"] = "FJ"; -Countries["Finland"] = "FI"; -Countries["France"] = "FR"; -Countries["French Guiana"] = "GF"; -Countries["French Polynesia"] = "PF"; -Countries["French Southern Territories"] = "TF"; -Countries["Gabon"] = "GA"; -Countries["Gambia"] = "GM"; -Countries["Georgia"] = "GE"; -Countries["Germany"] = "DE"; -Countries["Ghana"] = "GH"; -Countries["Gibraltar"] = "GI"; -Countries["Greece"] = "GR"; -Countries["Greenland"] = "GL"; -Countries["Grenada"] = "GD"; -Countries["Guadeloupe"] = "GP"; -Countries["Guam"] = "GU"; -Countries["Guatemala"] = "GT"; -Countries["Guinea"] = "GN"; -Countries["Guinea-Bissau"] = "GW"; -Countries["Guyana"] = "GY"; -Countries["Haiti"] = "HT"; -Countries["Virgin Islands, U.S."] = "VI"; -Countries["Honduras"] = "HN"; -Countries["Hong Kong"] = "HK"; -Countries["Hungary"] = "HU"; -Countries["Iceland"] = "IS"; -Countries["India"] = "IN"; -Countries["Indonesia"] = "ID"; -Countries["Wallis and Futuna"] = "WF"; -Countries["Iraq"] = "IQ"; -Countries["Ireland"] = "IE"; -Countries["Israel"] = "IL"; -Countries["Italy"] = "IT"; -Countries["Jamaica"] = "JM"; -Countries["Japan"] = "JP"; -Countries["Jordan"] = "JO"; -Countries["Kazakhstan"] = "KZ"; -Countries["Kenya"] = "KE"; -Countries["Kiribati"] = "KI"; -Countries["Kuwait"] = "KW"; -Countries["Kyrgyzstan"] = "KG"; -Countries["Lao People's Democratic Republic"] = "LA"; -Countries["Latvia"] = "LV"; -Countries["Lebanon"] = "LB"; -Countries["Lesotho"] = "LS"; -Countries["Liberia"] = "LR"; -Countries["Libyan Arab Jamahiriya"] = "LY"; -Countries["Liechtenstein"] = "LI"; -Countries["Lithuania"] = "LT"; -Countries["Luxembourg"] = "LU"; -Countries["Montserrat"] = "MS"; -Countries["Macedonia, The Former Yugoslav Republic of"] = "MK"; -Countries["Madagascar"] = "MG"; -Countries["Malawi"] = "MW"; -Countries["Malaysia"] = "MY"; -Countries["Maldives"] = "MV"; -Countries["Mali"] = "ML"; -Countries["Malta"] = "MT"; -Countries["Marshall Islands"] = "MH"; -Countries["Martinique"] = "MQ"; -Countries["Mauritania"] = "MR"; -Countries["Mauritius"] = "MU"; -Countries["Mayotte"] = "YT"; -Countries["Mexico"] = "MX"; -Countries["Micronesia, Federated States of"] = "FM"; -Countries["Morocco"] = "MA"; -Countries["Monaco"] = "MC"; -Countries["Mongolia"] = "MN"; -Countries["Mozambique"] = "MZ"; -Countries["Myanmar"] = "MM"; -Countries["Namibia"] = "NA"; -Countries["Nauru"] = "NR"; -Countries["Nepal"] = "NP"; -Countries["Netherlands"] = "NL"; -Countries["Netherlands Antilles"] = "AN"; -Countries["New Caledonia"] = "NC"; -Countries["New Zealand"] = "NZ"; -Countries["Nicaragua"] = "NI"; -Countries["Niger"] = "NE"; -Countries["Nigeria"] = "NG"; -Countries["Niue"] = "NU"; -Countries["Norfolk Island"] = "NF"; -Countries["Northern Mariana Islands"] = "MP"; -Countries["Norway"] = "NO"; -Countries["Oman"] = "OM"; -Countries["Pakistan"] = "PK"; -Countries["Palau"] = "PW"; -Countries["Panama"] = "PA"; -Countries["Papua New Guinea"] = "PG"; -Countries["Paraguay"] = "PY"; -Countries["Peru"] = "PE"; -Countries["Philippines"] = "PH"; -Countries["Pitcairn"] = "PN"; -Countries["Poland"] = "PL"; -Countries["Portugal"] = "PT"; -Countries["Puerto Rico"] = "PR"; -Countries["Qatar"] = "QA"; -Countries["Reunion"] = "RE"; -Countries["Romania"] = "RO"; -Countries["Russian Federation"] = "RU"; -Countries["Russia"] = "RU"; -Countries["Rwanda"] = "RW"; -Countries["Saint Kitts and Nevis"] = "KN"; -Countries["Saint Lucia"] = "LC"; -Countries["Saint Vincent and The Grenadines"] = "VC"; -Countries["Samoa"] = "WS"; -Countries["San Marino"] = "SM"; -Countries["Sao Tome and Principe"] = "ST"; -Countries["Saudi Arabia"] = "SA"; -Countries["Senegal"] = "SN"; -Countries["Seychelles"] = "SC"; -Countries["Sierra Leone"] = "SL"; -Countries["Singapore"] = "SG"; -Countries["Slovenia"] = "SI"; -Countries["Solomon Islands"] = "SB"; -Countries["Somalia"] = "SO"; -Countries["South Africa"] = "ZA"; -Countries["Spain"] = "ES"; -Countries["Sri Lanka"] = "LK"; -Countries["Sudan"] = "SD"; -Countries["Suriname"] = "SR"; -Countries["Swaziland"] = "SZ"; -Countries["Sweden"] = "SE"; -Countries["Switzerland"] = "CH"; -Countries["Syrian Arab Republic"] = "SY"; -Countries["Tajikistan"] = "TJ"; -Countries["Tanzania, United Republic of"] = "TZ"; -Countries["Thailand"] = "TH"; -Countries["Togo"] = "TG"; -Countries["Tokelau"] = "TK"; -Countries["Tonga"] = "TO"; -Countries["Trinidad and Tobago"] = "TT"; -Countries["Tunisia"] = "TN"; -Countries["Turkey"] = "TR"; -Countries["Turkmenistan"] = "TM"; -Countries["Turks and Caicos Islands"] = "TC"; -Countries["Tuvalu"] = "TV"; -Countries["Uganda"] = "UG"; -Countries["Ukraine"] = "UA"; -Countries["United Arab Emirates"] = "AE"; -Countries["UK"] = "GB"; -Countries["US"] = "US"; -Countries["United States Minor Outlying Islands"] = "UM"; -Countries["Uruguay"] = "UY"; -Countries["Uzbekistan"] = "UZ"; -Countries["Vanuatu"] = "VU"; -Countries["Vatican City State (Holy See)"] = "VA"; -Countries["Venezuela"] = "VE"; -Countries["Viet Nam"] = "VN"; -Countries["Western Sahara"] = "EH"; -Countries["Yemen"] = "YE"; -Countries["Zambia"] = "ZM"; -Countries["Zimbabwe"] = "ZW"; -Countries["Taiwan"] = "TW"; -Countries["[Worldwide]"] = "XW"; -Countries["Europe"] = "XE"; -Countries["Soviet Union (historical, 1922-1991)"] = "SU"; -Countries["East Germany (historical, 1949-1990)"] = "XG"; -Countries["Czechoslovakia (historical, 1918-1992)"] = "XC"; -Countries["Congo, The Democratic Republic of the"] = "CD"; -Countries["Slovakia"] = "SK"; -Countries["Bosnia and Herzegovina"] = "BA"; -Countries["Korea (North), Democratic People's Republic of"] = "KP"; -Countries["North Korea"] = "KP"; -Countries["Korea (South), Republic of"] = "KR"; -Countries["South Korea"] = "KR"; -Countries["Montenegro"] = "ME"; -Countries["South Georgia and the South Sandwich Islands"] = "GS"; -Countries["Palestinian Territory"] = "PS"; -Countries["Macao"] = "MO"; -Countries["Timor-Leste"] = "TL"; -Countries["<85>land Islands"] = "AX"; -Countries["Guernsey"] = "GG"; -Countries["Isle of Man"] = "IM"; -Countries["Jersey"] = "JE"; -Countries["Serbia"] = "RS"; -Countries["Saint Barthélemy"] = "BL"; -Countries["Saint Martin"] = "MF"; -Countries["Moldova"] = "MD"; -Countries["Yugoslavia (historical, 1918-2003)"] = "YU"; -Countries["Serbia and Montenegro (historical, 2003-2006)"] = "CS"; -Countries["Côte d'Ivoire"] = "CI"; -Countries["Heard Island and McDonald Islands"] = "HM"; -Countries["Iran, Islamic Republic of"] = "IR"; -Countries["Saint Pierre and Miquelon"] = "PM"; -Countries["Saint Helena"] = "SH"; -Countries["Svalbard and Jan Mayen"] = "SJ"; \ No newline at end of file +Countries['Afghanistan'] = 'AF'; +Countries['Albania'] = 'AL'; +Countries['Algeria'] = 'DZ'; +Countries['American Samoa'] = 'AS'; +Countries['Andorra'] = 'AD'; +Countries['Angola'] = 'AO'; +Countries['Anguilla'] = 'AI'; +Countries['Antarctica'] = 'AQ'; +Countries['Antigua and Barbuda'] = 'AG'; +Countries['Argentina'] = 'AR'; +Countries['Armenia'] = 'AM'; +Countries['Aruba'] = 'AW'; +Countries['Australia'] = 'AU'; +Countries['Austria'] = 'AT'; +Countries['Azerbaijan'] = 'AZ'; +Countries['Bahamas'] = 'BS'; +Countries['Bahrain'] = 'BH'; +Countries['Bangladesh'] = 'BD'; +Countries['Barbados'] = 'BB'; +Countries['Belarus'] = 'BY'; +Countries['Belgium'] = 'BE'; +Countries['Belize'] = 'BZ'; +Countries['Benin'] = 'BJ'; +Countries['Bermuda'] = 'BM'; +Countries['Bhutan'] = 'BT'; +Countries['Bolivia'] = 'BO'; +Countries['Croatia'] = 'HR'; +Countries['Botswana'] = 'BW'; +Countries['Bouvet Island'] = 'BV'; +Countries['Brazil'] = 'BR'; +Countries['British Indian Ocean Territory'] = 'IO'; +Countries['Brunei Darussalam'] = 'BN'; +Countries['Bulgaria'] = 'BG'; +Countries['Burkina Faso'] = 'BF'; +Countries['Burundi'] = 'BI'; +Countries['Cambodia'] = 'KH'; +Countries['Cameroon'] = 'CM'; +Countries['Canada'] = 'CA'; +Countries['Cape Verde'] = 'CV'; +Countries['Cayman Islands'] = 'KY'; +Countries['Central African Republic'] = 'CF'; +Countries['Chad'] = 'TD'; +Countries['Chile'] = 'CL'; +Countries['China'] = 'CN'; +Countries['Christmas Island'] = 'CX'; +Countries['Cocos (Keeling) Islands'] = 'CC'; +Countries['Colombia'] = 'CO'; +Countries['Comoros'] = 'KM'; +Countries['Congo'] = 'CG'; +Countries['Cook Islands'] = 'CK'; +Countries['Costa Rica'] = 'CR'; +Countries['Virgin Islands, British'] = 'VG'; +Countries['Cuba'] = 'CU'; +Countries['Cyprus'] = 'CY'; +Countries['Czech Republic'] = 'CZ'; +Countries['Denmark'] = 'DK'; +Countries['Djibouti'] = 'DJ'; +Countries['Dominica'] = 'DM'; +Countries['Dominican Republic'] = 'DO'; +Countries['Ecuador'] = 'EC'; +Countries['Egypt'] = 'EG'; +Countries['El Salvador'] = 'SV'; +Countries['Equatorial Guinea'] = 'GQ'; +Countries['Eritrea'] = 'ER'; +Countries['Estonia'] = 'EE'; +Countries['Ethiopia'] = 'ET'; +Countries['Falkland Islands (Malvinas)'] = 'FK'; +Countries['Faroe Islands'] = 'FO'; +Countries['Fiji'] = 'FJ'; +Countries['Finland'] = 'FI'; +Countries['France'] = 'FR'; +Countries['French Guiana'] = 'GF'; +Countries['French Polynesia'] = 'PF'; +Countries['French Southern Territories'] = 'TF'; +Countries['Gabon'] = 'GA'; +Countries['Gambia'] = 'GM'; +Countries['Georgia'] = 'GE'; +Countries['Germany'] = 'DE'; +Countries['Ghana'] = 'GH'; +Countries['Gibraltar'] = 'GI'; +Countries['Greece'] = 'GR'; +Countries['Greenland'] = 'GL'; +Countries['Grenada'] = 'GD'; +Countries['Guadeloupe'] = 'GP'; +Countries['Guam'] = 'GU'; +Countries['Guatemala'] = 'GT'; +Countries['Guinea'] = 'GN'; +Countries['Guinea-Bissau'] = 'GW'; +Countries['Guyana'] = 'GY'; +Countries['Haiti'] = 'HT'; +Countries['Virgin Islands, U.S.'] = 'VI'; +Countries['Honduras'] = 'HN'; +Countries['Hong Kong'] = 'HK'; +Countries['Hungary'] = 'HU'; +Countries['Iceland'] = 'IS'; +Countries['India'] = 'IN'; +Countries['Indonesia'] = 'ID'; +Countries['Wallis and Futuna'] = 'WF'; +Countries['Iraq'] = 'IQ'; +Countries['Ireland'] = 'IE'; +Countries['Israel'] = 'IL'; +Countries['Italy'] = 'IT'; +Countries['Jamaica'] = 'JM'; +Countries['Japan'] = 'JP'; +Countries['Jordan'] = 'JO'; +Countries['Kazakhstan'] = 'KZ'; +Countries['Kenya'] = 'KE'; +Countries['Kiribati'] = 'KI'; +Countries['Kuwait'] = 'KW'; +Countries['Kyrgyzstan'] = 'KG'; +Countries["Lao People's Democratic Republic"] = 'LA'; +Countries['Latvia'] = 'LV'; +Countries['Lebanon'] = 'LB'; +Countries['Lesotho'] = 'LS'; +Countries['Liberia'] = 'LR'; +Countries['Libyan Arab Jamahiriya'] = 'LY'; +Countries['Liechtenstein'] = 'LI'; +Countries['Lithuania'] = 'LT'; +Countries['Luxembourg'] = 'LU'; +Countries['Montserrat'] = 'MS'; +Countries['Macedonia, The Former Yugoslav Republic of'] = 'MK'; +Countries['Madagascar'] = 'MG'; +Countries['Malawi'] = 'MW'; +Countries['Malaysia'] = 'MY'; +Countries['Maldives'] = 'MV'; +Countries['Mali'] = 'ML'; +Countries['Malta'] = 'MT'; +Countries['Marshall Islands'] = 'MH'; +Countries['Martinique'] = 'MQ'; +Countries['Mauritania'] = 'MR'; +Countries['Mauritius'] = 'MU'; +Countries['Mayotte'] = 'YT'; +Countries['Mexico'] = 'MX'; +Countries['Micronesia, Federated States of'] = 'FM'; +Countries['Morocco'] = 'MA'; +Countries['Monaco'] = 'MC'; +Countries['Mongolia'] = 'MN'; +Countries['Mozambique'] = 'MZ'; +Countries['Myanmar'] = 'MM'; +Countries['Namibia'] = 'NA'; +Countries['Nauru'] = 'NR'; +Countries['Nepal'] = 'NP'; +Countries['Netherlands'] = 'NL'; +Countries['Netherlands Antilles'] = 'AN'; +Countries['New Caledonia'] = 'NC'; +Countries['New Zealand'] = 'NZ'; +Countries['Nicaragua'] = 'NI'; +Countries['Niger'] = 'NE'; +Countries['Nigeria'] = 'NG'; +Countries['Niue'] = 'NU'; +Countries['Norfolk Island'] = 'NF'; +Countries['Northern Mariana Islands'] = 'MP'; +Countries['Norway'] = 'NO'; +Countries['Oman'] = 'OM'; +Countries['Pakistan'] = 'PK'; +Countries['Palau'] = 'PW'; +Countries['Panama'] = 'PA'; +Countries['Papua New Guinea'] = 'PG'; +Countries['Paraguay'] = 'PY'; +Countries['Peru'] = 'PE'; +Countries['Philippines'] = 'PH'; +Countries['Pitcairn'] = 'PN'; +Countries['Poland'] = 'PL'; +Countries['Portugal'] = 'PT'; +Countries['Puerto Rico'] = 'PR'; +Countries['Qatar'] = 'QA'; +Countries['Reunion'] = 'RE'; +Countries['Romania'] = 'RO'; +Countries['Russian Federation'] = 'RU'; +Countries['Russia'] = 'RU'; +Countries['Rwanda'] = 'RW'; +Countries['Saint Kitts and Nevis'] = 'KN'; +Countries['Saint Lucia'] = 'LC'; +Countries['Saint Vincent and The Grenadines'] = 'VC'; +Countries['Samoa'] = 'WS'; +Countries['San Marino'] = 'SM'; +Countries['Sao Tome and Principe'] = 'ST'; +Countries['Saudi Arabia'] = 'SA'; +Countries['Senegal'] = 'SN'; +Countries['Seychelles'] = 'SC'; +Countries['Sierra Leone'] = 'SL'; +Countries['Singapore'] = 'SG'; +Countries['Slovenia'] = 'SI'; +Countries['Solomon Islands'] = 'SB'; +Countries['Somalia'] = 'SO'; +Countries['South Africa'] = 'ZA'; +Countries['Spain'] = 'ES'; +Countries['Sri Lanka'] = 'LK'; +Countries['Sudan'] = 'SD'; +Countries['Suriname'] = 'SR'; +Countries['Swaziland'] = 'SZ'; +Countries['Sweden'] = 'SE'; +Countries['Switzerland'] = 'CH'; +Countries['Syrian Arab Republic'] = 'SY'; +Countries['Tajikistan'] = 'TJ'; +Countries['Tanzania, United Republic of'] = 'TZ'; +Countries['Thailand'] = 'TH'; +Countries['Togo'] = 'TG'; +Countries['Tokelau'] = 'TK'; +Countries['Tonga'] = 'TO'; +Countries['Trinidad and Tobago'] = 'TT'; +Countries['Tunisia'] = 'TN'; +Countries['Turkey'] = 'TR'; +Countries['Turkmenistan'] = 'TM'; +Countries['Turks and Caicos Islands'] = 'TC'; +Countries['Tuvalu'] = 'TV'; +Countries['Uganda'] = 'UG'; +Countries['Ukraine'] = 'UA'; +Countries['United Arab Emirates'] = 'AE'; +Countries['UK'] = 'GB'; +Countries['US'] = 'US'; +Countries['United States Minor Outlying Islands'] = 'UM'; +Countries['Uruguay'] = 'UY'; +Countries['Uzbekistan'] = 'UZ'; +Countries['Vanuatu'] = 'VU'; +Countries['Vatican City State (Holy See)'] = 'VA'; +Countries['Venezuela'] = 'VE'; +Countries['Viet Nam'] = 'VN'; +Countries['Western Sahara'] = 'EH'; +Countries['Yemen'] = 'YE'; +Countries['Zambia'] = 'ZM'; +Countries['Zimbabwe'] = 'ZW'; +Countries['Taiwan'] = 'TW'; +Countries['[Worldwide]'] = 'XW'; +Countries['Europe'] = 'XE'; +Countries['Soviet Union (historical, 1922-1991)'] = 'SU'; +Countries['East Germany (historical, 1949-1990)'] = 'XG'; +Countries['Czechoslovakia (historical, 1918-1992)'] = 'XC'; +Countries['Congo, The Democratic Republic of the'] = 'CD'; +Countries['Slovakia'] = 'SK'; +Countries['Bosnia and Herzegovina'] = 'BA'; +Countries["Korea (North), Democratic People's Republic of"] = 'KP'; +Countries['North Korea'] = 'KP'; +Countries['Korea (South), Republic of'] = 'KR'; +Countries['South Korea'] = 'KR'; +Countries['Montenegro'] = 'ME'; +Countries['South Georgia and the South Sandwich Islands'] = 'GS'; +Countries['Palestinian Territory'] = 'PS'; +Countries['Macao'] = 'MO'; +Countries['Timor-Leste'] = 'TL'; +Countries['<85>land Islands'] = 'AX'; +Countries['Guernsey'] = 'GG'; +Countries['Isle of Man'] = 'IM'; +Countries['Jersey'] = 'JE'; +Countries['Serbia'] = 'RS'; +Countries['Saint Barthélemy'] = 'BL'; +Countries['Saint Martin'] = 'MF'; +Countries['Moldova'] = 'MD'; +Countries['Yugoslavia (historical, 1918-2003)'] = 'YU'; +Countries['Serbia and Montenegro (historical, 2003-2006)'] = 'CS'; +Countries["Côte d'Ivoire"] = 'CI'; +Countries['Heard Island and McDonald Islands'] = 'HM'; +Countries['Iran, Islamic Republic of'] = 'IR'; +Countries['Saint Pierre and Miquelon'] = 'PM'; +Countries['Saint Helena'] = 'SH'; +Countries['Svalbard and Jan Mayen'] = 'SJ';