Applied prettier and eslint tools on existing code

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

View file

@ -1,28 +1,28 @@
# MusicBrainz UserScripts
* [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)
## <a name="mb_relationship_shortcuts"></a> Display shortcut for relationships on MusicBrainz
@ -184,4 +184,3 @@ Various UI enhancements for Musicbrainz
[![Source](https://github.com/jerone/UserScripts/blob/master/_resources/Source-button.png)](https://github.com/murdos/musicbrainz-userscripts/blob/master/mb_ui_enhancements.user.js)
[![Install](https://raw.github.com/jerone/UserScripts/master/_resources/Install-button.png)](https://raw.githubusercontent.com/murdos/musicbrainz-userscripts/master/mb_ui_enhancements.user.js)

View file

@ -14,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(
'<p style="font-size:70%; font-style: italic; margin: 0.1em 0;">' +
'Warning: ' + numtracks + ' vs ' + showntracks + ' tracks' +
'</p>'
);
// 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(
`${'<p style="font-size:70%; font-style: italic; margin: 0.1em 0;">' + 'Warning: '}${numtracks} vs ${showntracks} tracks` +
`</p>`
);
// 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 = $(`<div id="mb_buttons">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`).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 = $('<div id="mb_buttons">'
+ MBImport.buildFormHTML(parameters)
+ MBImport.buildSearchButton(release)
+ '</div>').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 id='bci_link'><a class='custom-color' href='" + fullsizeimageurl +
"' title='Open original image in a new tab (Bandcamp importer)' target='_blank'>Original image</a></div>");
$("div#bci_link").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 id='bci_link'><a class='custom-color' href='${fullsizeimageurl}' title='Open original image in a new tab (Bandcamp importer)' target='_blank'>Original image</a></div>`
);
$('div#bci_link').css({ 'padding-top': '0.5em', 'text-align': 'right' });
$('div#bci_link a').css({ 'font-weight': 'bold' });
});

View file

@ -18,12 +18,13 @@ this.$ = this.jQuery = jQuery.noConflict(true);
if (!unsafeWindow) unsafeWindow = window;
$(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 = '<div id="bci_helper" style="padding-top: 5px;">' + '<a href="' + bandcampAlbumData.url +
'" title="Load album page and display Import to MB button">Album page (MB import)</a></div>';
$('#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 = `${'<div id="bci_helper" style="padding-top: 5px;">' + '<a href="'}${
bandcampAlbumData.url
}" title="Load album page and display Import to MB button">Album page (MB import)</a></div>`;
$('#name-section').append(innerHTML);
}
});

File diff suppressed because it is too large Load diff

View file

@ -17,119 +17,121 @@ this.$ = this.jQuery = jQuery.noConflict(true);
if (!unsafeWindow) unsafeWindow = window;
$(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 = $('<div class="musicbrainz-import">'
+ MBImport.buildFormHTML(parameters)
+ MBImport.buildSearchButton(release)
+ '</div>').hide();
let mbUI = $(
`<div class="musicbrainz-import">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`
).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();
}

View file

@ -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 = $('<li class="interior-release-chart-content-item musicbrainz-import">'
+ MBImport.buildFormHTML(parameters)
+ MBImport.buildSearchButton(release)
+ '</li>').hide();
let mbUI = $(
`<li class="interior-release-chart-content-item musicbrainz-import">${MBImport.buildFormHTML(
parameters
)}${MBImport.buildSearchButton(release)}</li>`
).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();
}

View file

@ -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 <td> 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 <td> 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 = $('<div id="mb_buttons">'
+ MBImport.buildFormHTML(parameters)
+ MBImport.buildSearchButton(release)
+ '</div>').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 = $(`<div id="mb_buttons">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`).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);
}
});

View file

@ -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('<span>Import into MB</span>', '<span>Import ' + format + '</span>');
let edit_note = MBImport.makeEditNote(release_url, 'CD Baby', format);
let parameters = MBImport.buildFormParameters(release, edit_note);
return MBImport.buildFormHTML(parameters).replace('<span>Import into MB</span>', `<span>Import ${format}</span>`);
}
function insertImportLinks(release, buttons) {
$("div.right-container-top-right").prepend(
$('<div id="mb_buttons">'
+ buttons
+ MBImport.buildSearchButton(release)
+ '</div>').hide()
);
$('#mb_buttons').css({
'margin-bottom': '5px',
'padding': '2%',
'background-color': '#fff'
});
$('div.right-container-top-right').prepend($(`<div id="mb_buttons">${buttons}${MBImport.buildSearchButton(release)}</div>`).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();
}

View file

@ -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(/<br><br>/g, ' / ').replace(/<br>/g, ' ');
title += ` ${$('div.works')[0]
.innerHTML.replace(/<br><br>/g, ' / ')
.replace(/<br>/g, ' ')}`;
}
return title;
}
function _setReleasePerformers() {
var list = $('div.artists')[0].innerHTML.split('<br>').map(function (artist) {
return {
'credited_name': artist,
'artist_name': artist,
'artist_mbid': '',
'joinphrase': ', '
};
});
let list = $('div.artists')[0]
.innerHTML.split('<br>')
.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 = $('<div class="section musicbrainz"><h3>MusicBrainz</h3></div>');
var mbContentBlock = $('<div class="section_content"></div>');
let mbUI = $('<div class="section musicbrainz"><h3>MusicBrainz</h3></div>');
let mbContentBlock = $('<div class="section_content"></div>');
mbUI.append(mbContentBlock);
// Form parameters
var parameters = MBImport.buildFormParameters(release, editNote);
let parameters = MBImport.buildFormParameters(release, editNote);
// Build form + search button
var innerHTML = '<div id="mb_buttons">'
+ MBImport.buildFormHTML(parameters)
+ MBImport.buildSearchButton(release)
+ '</div>';
let innerHTML = `<div id="mb_buttons">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`;
mbContentBlock.append(innerHTML);
$('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();
}

File diff suppressed because it is too large Load diff

View file

@ -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('<br />') } );
});
$('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('<br />');
});
});
$('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;
}

View file

@ -41,7 +41,7 @@ var MBID_REGEX = /[0-9a-z]{8}\-[0-9a-z]{4}\-[0-9a-z]{4}\-[0-9a-z]{4}\-[0-9a-z]{1
var releasesOrReleaseGroups = document.querySelectorAll("#content table.tbl > tbody > tr > td a[href^='/release']");
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 = '<tr><td style="color: #f00;">Error loading release group (HTTP status ' + status + ')</td></tr>';
table.innerHTML = `<tr><td style="color: #f00;">Error loading release group (HTTP status ${status})</td></tr>`;
}
);
@ -73,23 +74,24 @@ function inject_release_group_button(parent) {
}
function inject_release_button(parent, _table_parent, _table, _mbid) {
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 = '<tr><td style="color: #f00;">Error loading release (HTTP status ' + status + ')</td></tr>';
table.innerHTML = `<tr><td style="color: #f00;">Error loading release (HTTP status ${status})</td></tr>`;
}
);
@ -97,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 = "&#9654;";
button.style.cursor = "pointer";
button.style.marginRight = "4px";
button.style.color = "#777";
button.innerHTML = '&#9654;';
button.style.cursor = 'pointer';
button.style.marginRight = '4px';
button.style.color = '#777';
button.addEventListener("mousedown", function() {
toggled = !toggled;
if (toggled)
button.innerHTML = "&#9660;";
else button.innerHTML = "&#9654;";
dom_callback(toggled);
}, false);
button.addEventListener(
'mousedown',
function() {
toggled = !toggled;
if (toggled) button.innerHTML = '&#9660;';
else button.innerHTML = '&#9654;';
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() + "&#215;" + format);
var count = media[format],
txt;
if (count > 1) formats.push(`${count.toString()}&#215;${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 += '<tr class="subh"><td colspan="4">' + format + "</td></tr>";
table.innerHTML += `<tr class="subh"><td colspan="4">${format}</td></tr>`;
for (var j = 0; j < medium.tracks.length; j++) {
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;
}

View file

@ -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 = $("<div></div>")
let $status = $('<div></div>')
.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);
}
}
};
}());
})();
}

File diff suppressed because it is too large Load diff

View file

@ -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 = $('<div id="mb_buttons">'
+ MBImport.buildFormHTML(parameters)
+ MBImport.buildSearchButton(release)
+ '</div>').hide();
let mbUI = $(`<div id="mb_buttons">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`).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();
}

View file

@ -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(
$('<div id="mb_buttons">'
+ MBImport.buildFormHTML(parameters)
+ MBImport.buildSearchButton(release)
+ '</div>').hide()
);
$('div.g4').prepend($(`<div id="mb_buttons">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`).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();
}

View file

@ -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
};
})();
})();

View file

@ -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 '<a class="musicbrainz_import" href="//musicbrainz.org/search?' + url_params.join('&') + '">Search in MusicBrainz</a>';
return `<a class="musicbrainz_import" href="//musicbrainz.org/search?${url_params.join('&')}">Search in MusicBrainz</a>`;
}
// compute HTML of search button
function fnBuildSearchButton(release) {
var parameters = searchParams(release);
var html = '<form class="musicbrainz_import musicbrainz_import_search" action="//musicbrainz.org/search" method="get" target="_blank" accept-charset="UTF-8" charset="' + document.characterSet + '">';
let parameters = searchParams(release);
let html = `<form class="musicbrainz_import musicbrainz_import_search" action="//musicbrainz.org/search" method="get" target="_blank" accept-charset="UTF-8" charset="${
document.characterSet
}">`;
parameters.forEach(function(parameter) {
var value = parameter.value + "";
html += "<input type='hidden' value='" + value.replace(/'/g,"&apos;") + "' name='" + parameter.name + "'/>";
let value = `${parameter.value}`;
html += `<input type='hidden' value='${value.replace(/'/g, '&apos;')}' name='${parameter.name}'/>`;
});
html += '<button type="submit" title="Search for this release in MusicBrainz (open a new tab)"><span>Search in MB</span></button>';
html += '</form>';
@ -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 = '<form class="musicbrainz_import musicbrainz_import_add" action="//musicbrainz.org/release/add" method="post" target="_blank" accept-charset="UTF-8" charset="' + document.characterSet + '">';
let innerHTML = `<form class="musicbrainz_import musicbrainz_import_add" action="//musicbrainz.org/release/add" method="post" target="_blank" accept-charset="UTF-8" charset="${
document.characterSet
}">`;
parameters.forEach(function(parameter) {
var value = parameter.value + "";
innerHTML += "<input type='hidden' value='" + value.replace(/'/g,"&apos;") + "' name='" + parameter.name + "'/>";
let value = `${parameter.value}`;
innerHTML += `<input type='hidden' value='${value.replace(/'/g, '&apos;')}' name='${parameter.name}'/>`;
});
innerHTML += '<button type="submit" title="Import this release into MusicBrainz (open a new tab)"><img src="//musicbrainz.org/favicon.ico" /><span>Import into MB</span></button>';
innerHTML +=
'<button type="submit" title="Import this release into MusicBrainz (open a new tab)"><img src="//musicbrainz.org/favicon.ico" /><span>Import into MB</span></button>';
innerHTML += '</form>';
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
};
})();

View file

@ -1,9 +1,10 @@
function _add_css(css) {
$("<style type='text/css'>"+css.replace(/\s+/g, ' ') + "</style>").appendTo("head");
$(`<style type='text/css'>${css.replace(/\s+/g, ' ')}</style>`).appendTo('head');
}
function MBImportStyle() {
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);
}

View file

@ -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: '<img src="'+ this.mb_server + '/static/images/entity/place.svg" height=16 width=16 />'
}
}
})();
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 = '<img src="' + img_url + '" height=16 width=16 />';
// 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 '<a href="' + mb_url + '" title="' + title + '">' + img_src + '</a> ';
};
// Search for ressource 'url' on MB, for relation of type 'mb_type' (artist, release, label, release-group, ...)
// 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: `<img src="${this.mb_server}/static/images/entity/place.svg" height=16 width=16 />`
}
};
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 = `<img src="${img_url}" height=16 width=16 />`;
// 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 `<a href="${mb_url}" title="${title}">${img_src}</a> `;
};
// Search for ressource 'url' on MB, for relation of type 'mb_type' (artist, release, label, release-group, ...)
// 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;
};

File diff suppressed because it is too large Load diff

View file

@ -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('<br /><strong>' + (discs.length > 1 ? 'Disc ' + discNumber + ': ' : '' ) + 'MB DiscId </strong><span id="' + discid + '" />');
check_and_display_discs(
artistName,
releaseName,
discs,
function(mb_toc_numbers, discid, discNumber) {
$eacLog
.parents('div.spoiler')
.prevAll('div.center:first')
.append(
`<br /><strong>${discs.length > 1 ? `Disc ${discNumber}: ` : ''}MB DiscId </strong><span id="${discid}" />`
);
},
function (mb_toc_numbers, discid, discNumber, found) {
var url = computeAttachURL(mb_toc_numbers, artistName, releaseName);
var html = '<a href="' + url + '">' + discid + '</a>';
function(mb_toc_numbers, discid, discNumber, found) {
let url = computeAttachURL(mb_toc_numbers, artistName, releaseName);
let html = `<a href="${url}">${discid}</a>`;
if (found) {
html = html + '<img src="' + CHECK_IMAGE + '" />';
html = `${html}<img src="${CHECK_IMAGE}" />`;
}
$('#' + 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('<br /><strong>' + (discs.length > 1 ? 'Disc ' + discNumber + ': ' : '' ) + 'MB DiscId: </strong><span id="' + torrentId + '_disc' + discNumber + '" />');
// 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(
`<br /><strong>${
discs.length > 1 ? `Disc ${discNumber}: ` : ''
}MB DiscId: </strong><span id="${torrentId}_disc${discNumber}" />`
);
},
function (mb_toc_numbers, discid, discNumber, found) {
var url = computeAttachURL(mb_toc_numbers, artistName, releaseName);
var html = '<a href="' + url + '">' + discid + '</a>';
function(mb_toc_numbers, discid, discNumber, found) {
let url = computeAttachURL(mb_toc_numbers, artistName, releaseName);
let html = `<a href="${url}">${discid}</a>`;
if (found) {
html = html + '<img src="' + CHECK_IMAGE + '" />';
html = `${html}<img src="${CHECK_IMAGE}" />`;
}
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;
};

View file

@ -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("<th style='width: 150px;'>Relationships</th>");
$tr.children("td:eq("+columnindex+")").after("<td class='relationships'></td>");
$tr.children(`th:eq(${columnindex})`).after("<th style='width: 150px;'>Relationships</th>");
$tr.children(`td:eq(${columnindex})`).after("<td class='relationships'></td>");
$(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(
"<a href='" + target.replace(/'/g,"&apos;") + "'>" + "<img style='max-height: 16px;' src='" + relationsIconsURLs.url[reltype] + "' />&nbsp;" + "</a>"
);
}
else for (var rel in otherDatabasesIconURLs) {
if (target.indexOf(rel) != -1 ) {
$("#" + mbid + " td.relationships").append(
"<a href='" + target.replace(/'/g,"&apos;") + "'>" + "<img style='max-height: 16px;' src='" + otherDatabasesIconURLs[rel] + "' />&nbsp;" + "</a>"
);
}
}
});
// 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(
`<a href='${target.replace(/'/g, '&apos;')}'>` +
`<img style='max-height: 16px;' src='${relationsIconsURLs.url[reltype]}' />&nbsp;` +
`</a>`
);
} else
for (let rel in otherDatabasesIconURLs) {
if (target.indexOf(rel) != -1) {
$(`#${mbid} td.relationships`).append(
`<a href='${target.replace(/'/g, '&apos;')}'>` +
`<img style='max-height: 16px;' src='${otherDatabasesIconURLs[rel]}' />&nbsp;` +
`</a>`
);
}
}
});
// 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 += "<img src='" + relationsIconsURLs[targettype][reltype] + "' />(" + urls.length + ")&nbsp;";
} else {
$.each(urls, function(index, url) {
html += "<a href='" + url + "'><img src='" + relationsIconsURLs[targettype][reltype] + "' /></a>&nbsp;";
$.each(relations, function(reltype, urls) {
let html = '';
if (urls.length < -1) {
html += `<img src='${relationsIconsURLs[targettype][reltype]}' />(${urls.length})&nbsp;`;
} else {
$.each(urls, function(index, url) {
html += `<a href='${url}'><img src='${relationsIconsURLs[targettype][reltype]}' /></a>&nbsp;`;
});
}
$(`#${mbid} td.relationships`).append(html);
});
}
$("#" + mbid + " td.relationships").append(html);
});
});
});
});
});
});

View file

@ -14,114 +14,149 @@
// prevent JQuery conflicts, see http://wiki.greasespot.net/@grant
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('<h2 class="toptracks">Top Last.fm recordings</h2><ul class="toptracks" />');
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('<li><a href="'+url+'">'+track.name+'</a></li>');
});
});
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(`<li><a href="${url}">${track.name}</a></li>`);
});
}
);
}
// 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 " - <Edit type>" from the link "Edit XXXX - <Edit type>"
re = new RegExp("musicbrainz\.org/.*/(open_)?edits","i");
re = new RegExp('musicbrainz.org/.*/(open_)?edits', 'i');
if (window.location.href.match(re)) {
$("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("<tr><th span='2'><a href='/release/"+mbid+"/cover-art'>See all artworks for this release</a></th></tr>");
$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(`<tr><th span='2'><a href='/release/${mbid}/cover-art'>See all artworks for this release</a></th></tr>`);
});
}
// 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('<iframe width="360" height="275" frameborder="0" style="float: right;" src="https://www.youtube.com/embed/'+ youtube_id +'?rel=0" allowfullscreen=""></iframe>');
let youtube_id = $youtube_link.prop('href').match(/http:\/\/www\.youtube\.com\/watch\?v=(.*)/)[1];
$('table.details').width('60%');
$("h2:contains('Relationships')").after(
`<iframe width="360" height="275" frameborder="0" style="float: right;" src="https://www.youtube.com/embed/${youtube_id}?rel=0" allowfullscreen=""></iframe>`
);
}
}
// 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<br>\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<br>\n');
let newHTML = '';
$.each(isrcs, function(index, isrc) {
isrc = isrc.trim();
newHTML += "<a href='/isrc/" + isrc + "'><code>";
newHTML += isrc.substring(0,5) + "<b>" + isrc.substring(5,7) + "</b>" + isrc.substring(7);
newHTML += "</code></a>";
if (index != isrcs.length-1) { newHTML += "<br>" };
newHTML += `<a href='/isrc/${isrc}'><code>`;
newHTML += `${isrc.substring(0, 5)}<b>${isrc.substring(5, 7)}</b>${isrc.substring(7)}`;
newHTML += '</code></a>';
if (index != isrcs.length - 1) {
newHTML += '<br>';
}
});
$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("<th style='width: 150px;' class='isrc c'> ISRC </th>");
$medium
.find(`tbody tr.subh th:nth-last-child(${ISRC_COLUMN_POSITION})`)
.before("<th style='width: 150px;' class='isrc c'> ISRC </th>");
// Handle each track
$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(' <span class="comment">(' + recording.disambiguation + ')</span>');
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(` <span class="comment">(${recording.disambiguation})</span>`);
}
// ISRCS
if (recording.isrcs.length != 0) {
var links = jQuery.map(recording.isrcs, function(isrc, i) {
return ("<a href='/isrc/" + isrc + "'>" + isrc + "</a>");
let links = jQuery.map(recording.isrcs, function(isrc, i) {
return `<a href='/isrc/${isrc}'>${isrc}</a>`;
});
isrcsLinks = links.join(", ");
isrcsLinks = links.join(', ');
}
}
$('#'+track_mbid).find("td:nth-last-child("+ISRC_COLUMN_POSITION+")").before("<td class='isrc c'><small>"+isrcsLinks+"</small></td>");
$(`#${track_mbid}`)
.find(`td:nth-last-child(${ISRC_COLUMN_POSITION})`)
.before(`<td class='isrc c'><small>${isrcsLinks}</small></td>`);
});
}
}
// Display "Edit relationships" link for release besides "Edit" link
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('<li><a href="/release/' + mbid + '/edit-relationships">Edit relationships</a></li>');
$('ul.tabs').append(`<li><a href="/release/${mbid}/edit-relationships">Edit relationships</a></li>`);
}
// Discogs link rollover
// TODO...
// -------------- End of script ------------------------
});

View file

@ -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 = $('<div id="musicbrainz-import">' + MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release) + '</div>').hide();
let mbUI = $(`<div id="musicbrainz-import">${MBImport.buildFormHTML(parameters)}${MBImport.buildSearchButton(release)}</div>`).hide();
$('h2.band_name').after(mbUI);
$('#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'
};

View file

@ -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 = $('<p class="musicbrainz_import">').append(MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release)).hide();
mbUI.append($('<button id="isrcs" type="submit" title="Show list of ISRCs">Show ISRCs</button>'));
var isrclist = $('<p><textarea id="isrclist" style="display:none">' + release.isrcs.join("\n") + '</textarea></p>');
let mbUI = $('<p class="musicbrainz_import">')
.append(MBImport.buildFormHTML(parameters) + MBImport.buildSearchButton(release))
.hide();
mbUI.append($('<button id="isrcs" type="submit" title="Show list of ISRCs">Show ISRCs</button>'));
let isrclist = $(`<p><textarea id="isrclist" style="display:none">${release.isrcs.join('\n')}</textarea></p>`);
$("#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;
});
});

View file

@ -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($("<style></style>").text("input.recording-comment { background: inherit; border: 1px #999 solid; width: 32em; margin-left: 0.5em; }"));
$('head').append(
$('<style></style>').text(
'input.recording-comment { background: inherit; border: 1px #999 solid; width: 32em; margin-left: 0.5em; }'
)
);
var delay = setInterval(function () {
$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 = $("<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 = $('<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 = $("<div></div>").insertAfter("h2.tracklist");
let $container = $('<div></div>').insertAfter('h2.tracklist');
$("<button>Edit recording comments</button>")
.addClass("styled-button")
.on("click", function () {
$('<button>Edit recording comments</button>')
.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(
'\
<table id="set-recording-comments">\
<tr>\
<td><label for="all-recording-comments">Set all visible comments to:</label></td>\
@ -126,71 +140,80 @@ function setRecordingComments() {
<button id="submit-recording-comments" class="styled-button">Submit changes (visible and marked red)</button>\
</td>\
</tr>\
</table>');
</table>'
);
$("#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();
});
}

File diff suppressed because it is too large Load diff