RED (+ NWCD, Orpheus) Upload Assistant

Accurate filling the upload and group edit forms based on foobar2000's playlist selection via pasted output of copy command, release consistency check, two tracklist layouts, basic colours customization, featured artists extraction, image URl fetching from store and more. As alternative to copied playlist, URL to product in supported webstore can be used -- see below for the list.

当前为 2019-09-23 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RED (+ NWCD, Orpheus) Upload Assistant
  3. // @namespace https://greasyfork.org/users/321857-anakunda
  4. // @version 1.136
  5. // @description Accurate filling the upload and group edit forms based on foobar2000's playlist selection via pasted output of copy command, release consistency check, two tracklist layouts, basic colours customization, featured artists extraction, image URl fetching from store and more. As alternative to copied playlist, URL to product in supported webstore can be used -- see below for the list.
  6. // @author Anakunda
  7. // @iconURL https://redacted.ch/favicon.ico
  8. // @match https://redacted.ch/upload.php*
  9. // @match https://redacted.ch/torrents.php?action=editgroup*
  10. // @match https://redacted.ch/requests.php?action=new*
  11. // @match https://notwhat.cd/upload.php*
  12. // @match https://notwhat.cd/torrents.php?action=editgroup*
  13. // @match https://notwhat.cd/requests.php?action=new*
  14. // @match https://orpheus.network/upload.php*
  15. // @match https://orpheus.network/torrents.php?action=editgroup*
  16. // @match https://orpheus.network/requests.php?action=new*
  17. // @connect file://*
  18. // @connect *
  19. // @grant GM_xmlhttpRequest
  20. // @grant GM_getValue
  21. // @grant GM_setValue
  22. // @grant GM_deleteValue
  23. // @grant GM_log
  24. // ==/UserScript==
  25.  
  26. // The pattern for built-in copy command or custom Text Tools quick copy command, which is handled by this helper is:
  27. // [$fix_eol(%album artist%,)]$char(30)[$fix_eol(%album%,)]$char(30)[$if3(%date%,%ORIGINAL RELEASE DATE%,%year%)]$char(30)[$if3(%releasedate%,%retail date%,%date%,%year%)]$char(30)[$fix_eol($if3(%label%,%publisher%,%COPYRIGHT%),)]$char(30)[$fix_eol($if3(%catalog%,%CATALOGNUMBER%,%CATALOG NUMBER%,%labelno%,%catalog #%,%barcode%,%UPC%,%EAN%,%MCN%),)]$char(30)[%country%]$char(30)%__encoding%$char(30)%__codec%$char(30)[%__codec_profile%]$char(30)[%__bitrate%]$char(30)[%__bitspersample%]$char(30)[%__samplerate%]$char(30)[%__channels%]$char(30)[$if3(%media%,%format%,%source%,%MEDIATYPE%,%SOURCEMEDIA%,%discogs_format%)]$char(30)[$fix_eol(%genre%,)]|[$fix_eol(%style%,)]$char(30)[$num(%discnumber%,0)]$char(30)[$num($if2(%totaldiscs%,%disctotal%),0)]$char(30)[$fix_eol(%discsubtitle%,)]$char(30)[%track number%]$char(30)[$num($if2(%totaltracks%,%TRACKTOTAL%),0)]$char(30)[$fix_eol(%title%,)]$char(30)[$fix_eol(%track artist%,)]$char(30)[$if($strcmp($fix_eol(%performer%,),$fix_eol(%artist%,)),,$fix_eol(%performer%,))]$char(30)[$fix_eol($if3(%composer%,%writer%,%SONGWRITER%,%author%,%LYRICIST%),)]$char(30)[$fix_eol(%conductor%,)]$char(30)[$fix_eol(%remixer%,)]$char(30)[$fix_eol($if2(%compiler%,%mixer%),)]$char(30)[$fix_eol($if2(%producer%,%producedby%),)]$char(30)%length_seconds_fp%$char(30)%length_samples%$char(30)[%replaygain_album_gain%]$char(30)[%album dynamic range%]$char(30)[%__tool%][ | %ENCODER%][ | %ENCODER_OPTIONS%]$char(30)[$fix_eol($if2(%url%,%www%),)]$char(30)$directory_path(%path%)$char(30)[$replace($replace($if2(%comment%,%description%),$char(13),$char(29)),$char(10),$char(28))]$char(30)$trim([RELEASETYPE=$replace($if2(%RELEASETYPE%,%RELEASE TYPE%), ,_) ][COMPILATION=%compilation% ][ISRC=%isrc% ][EXPLICIT=%EXPLICIT% ][ASIN=%ASIN% ][DISCOGS_ID=%discogs_release_id% ][SOURCEID=%SOURCEID% ][BPM=%BPM% ])
  28. //
  29. // Fetch release description from URL:
  30. //
  31. // Supported sites for music:
  32. // - qobuz.com
  33. // - highresaudio.com
  34. // - bandcamp.com
  35. // - prestomusic.com
  36. // - discogs.com
  37. //
  38. // Supported sites for ebooks:
  39. // - martinus.cz, martinus.sk
  40. // - goodreads.com
  41. // - databazeknih.cz
  42. //
  43. // Supported sites for applications:
  44. // - sanet.st
  45.  
  46. 'use strict';
  47.  
  48. var prefs = {
  49. set: function(prop, def) { this[prop] = GM_getValue(prop, def) },
  50. save: function() {
  51. for (var iter in this) { if (typeof this[iter] != 'function') GM_setValue(iter, this[iter]) }
  52. },
  53. };
  54. prefs.set('remap_texttools_newlines', 0); // convert underscores to linebreaks (ambiguous)
  55. prefs.set('clean_on_apply', 0); // clean the input box on successfull fill
  56. prefs.set('keep_meaningles_composers', 0); // keep composers from file tags also for non-composer emphasis works
  57. prefs.set('always_hide_dnu_list', 0); // risky!
  58. prefs.set('single_threshold', 8 * 60); // Max length of single in s
  59. prefs.set('EP_threshold', 28 * 60); // Max time of EP in s
  60. prefs.set('auto_preview_cover', 1);
  61. prefs.set('auto_rehost_cover', 1);
  62. prefs.set('fetch_tags_from_artist', 0); // add n most used tags from release artist (if one) - experimental
  63. prefs.set('always_request_perfect_flac', 0);
  64. prefs.set('request_default_bounty', 0);
  65. // tracklist specific
  66. prefs.set('tracklist_style', 1); // 1: classical, 2: propertional right aligned
  67. prefs.set('max_tracklist_width', 80); // right margin of the right aligned tracklist. should not exceed the group description width on any device
  68. prefs.set('title_separator', '. '); // divisor of track# and title
  69. prefs.set('pad_leader', ' ');
  70. prefs.set('tracklist_head_color', '#4682B4'); // #a7bdd0
  71. prefs.set('tracklist_single_color', '#708080');
  72. // classical tracklist only components colouring
  73. prefs.set('tracklist_disctitle_color', '#008B8B');
  74. prefs.set('tracklist_classicalblock_color', 'Olive');
  75. prefs.set('tracklist_tracknumber_color', '#8899AA');
  76. prefs.set('tracklist_artist_color', '#889B2F');
  77. prefs.set('tracklist_composer_color', '#556B2F');
  78. prefs.set('tracklist_duration_color', '#4682B4');
  79.  
  80. document.head.appendChild(document.createElement('style')).innerHTML = `
  81. .ua-messages { text-indent: -2em; margin-left: 2em; }
  82. .ua-messages-bg { padding: 15px; text-align: left; background-color: darkslategray; }
  83. .ua-critical { color: red; font-weight: bold; }
  84. .ua-warning { color: #ff8d00; font-weight: 500; }
  85. .ua-info { color: white; }
  86.  
  87. .ua-button { vertical-align: middle; background-color: transparent; }
  88. .ua-input {
  89. width: 610px; height: 3em;
  90. margin-top: 8px; margin-bottom: 8px;
  91. background-color: antiquewhite;
  92. font-size: small;
  93. }
  94. `;
  95.  
  96. const isUpload = document.URL.toLowerCase().includes('/upload\.php');
  97. const isRequest = document.URL.toLowerCase().includes('/requests.php?action=new');
  98. const isEdit = document.URL.toLowerCase().includes('/torrents.php?action=editgroup');
  99.  
  100. var ref, tbl, elem, child, tb, messages = null, domparser = new DOMParser(), dom;
  101.  
  102. if (isUpload) {
  103. ref = document.querySelector('form#upload_table > div#dynamic_form');
  104. if (ref == null) return;
  105. common1();
  106. let x = [];
  107. x.push(document.createElement('tr'));
  108. x[0].classList.add('ua-button');
  109. child = document.createElement('input');
  110. child.id = 'fill-from-text';
  111. child.value = 'Fill from text (overwrite)';
  112. child.type = 'button';
  113. child.style.width = '13em';
  114. child.onclick = fill_from_text;
  115. x[0].append(child);
  116. elem.append(x[0]);
  117. x.push(document.createElement('tr'));
  118. x[1].classList.add('ua-button');
  119. child = document.createElement('input');
  120. child.id = 'fill-from-text-weak';
  121. child.value = 'Fill from text (keep values)';
  122. child.type = 'button';
  123. child.style.width = '13em';
  124. child.onclick = fill_from_text;
  125. x[1].append(child);
  126. elem.append(x[1]);
  127. common2();
  128. ref.parentNode.insertBefore(tbl, ref);
  129. } else if (isEdit) {
  130. ref = document.querySelector('form.edit_form > div > div > input[type="submit"]');
  131. if (ref == null) return;
  132. ref = ref.parentNode;
  133. ref.parentNode.insertBefore(document.createElement('br'), ref);
  134. common1();
  135. child = document.createElement('input');
  136. child.id = 'append-from-text';
  137. child.value = 'Fill from text (append)';
  138. child.type = 'button';
  139. child.onclick = fill_from_text;
  140. elem.append(child);
  141. common2();
  142. tbl.style.marginBottom = '10px';
  143. ref.parentNode.insertBefore(tbl, ref);
  144. } else if (isRequest) {
  145. ref = document.getElementById('categories');
  146. if (ref == null) return;
  147. ref = ref.parentNode.parentNode.nextElementSibling;
  148. ref.parentNode.insertBefore(document.createElement('br'), ref);
  149. common1();
  150. child = document.createElement('input');
  151. child.id = 'fill-from-text-weak';
  152. child.value = 'Fill from URL';
  153. child.type = 'button';
  154. child.onclick = fill_from_text;
  155. elem.append(child);
  156. common2();
  157. child = document.createElement('td');
  158. child.colSpan = 2;
  159. child.append(tbl);
  160. elem = document.createElement('tr');
  161. elem.append(child);
  162. ref.parentNode.insertBefore(elem, ref);
  163. }
  164.  
  165. if ((ref = document.getElementById('image') || document.querySelector('input[name="image"]')) != null) {
  166. ref.ondblclick = clear0;
  167. ref.onmousedown = clear1;
  168. ref.ondrop = clear0;
  169. }
  170.  
  171. function clear0() { this.value = '' }
  172. function clear1(e) { if (e.button == 1) this.value = '' }
  173.  
  174. function common1() {
  175. tbl = document.createElement('tr');
  176. tbl.style.backgroundColor = 'darkgoldenrod';
  177. tbl.style.verticalAlign = 'middle';
  178. elem = document.createElement('td');
  179. elem.style.textAlign = 'center';
  180. child = document.createElement('textarea');
  181. child.id = 'UA data';
  182. child.name = 'UA data';
  183. child.classList.add('ua-input');
  184. child.spellcheck = false;
  185. //child.ondblclick = clear0;
  186. child.onmousedown = clear1;
  187. child.ondrop = clear0;
  188. //child.onpaste = fill_from_text;
  189. elem.append(child);
  190. tbl.append(elem);
  191. elem = document.createElement('td');
  192. elem.style.textAlign = 'center';
  193. }
  194. function common2() {
  195. tbl.append(elem);
  196. tb = document.createElement('tbody');
  197. tb.append(tbl);
  198. tbl = document.createElement('table');
  199. tbl.id = 'upload assistant';
  200. tbl.append(tb);
  201. }
  202.  
  203. // if (prefs.always_hide_dnu_list && (ref = document.querySelector('div#content > div:first-of-type')) != null) {
  204. // ref.style.display = 'none'; // Hide DNU list (warning - risky!)
  205. // }
  206.  
  207. if ((ref = document.getElementById('yadg_input')) != null) ref.ondrop = clear0;
  208.  
  209. Array.prototype.includesCaseless = function(str) {
  210. return typeof str == 'string' && this.find(it => it.toLowerCase() == str.toLowerCase()) != undefined;
  211. };
  212. Array.prototype.pushUnique = function(item) {
  213. return item && !this.includes(item) ? this.push(item) : false;
  214. };
  215. Array.prototype.pushUniqueCaseless = function(item) {
  216. return item && !this.includesCaseless(item) ? this.push(item) : false;
  217. };
  218. // Array.prototype.getUnique = function(prop) {
  219. // return this.every((it) => it[prop] && it[prop] == this[0][prop]) ? this[0][prop] : null;
  220. // };
  221. Array.prototype.equalTo = function(arr) {
  222. return arr instanceof Array && arr.length == this.length && arr.sort().toString() == this.sort().toString();
  223. }
  224.  
  225. const excludedCountries = [
  226. /\b(?:United States|USA?)\b/,
  227. /\b(?:United Kingdom|Great Britain|England|GB|UK)\b/,
  228. /\b(?:Europe|European Union|EU)\b/,
  229. /\b(?:Unknown)\b/,
  230. ];
  231.  
  232. class TagManager extends Array {
  233. constructor() {
  234. super();
  235. this.presubstitutions = [
  236. [/\b(?:Singer\/Songwriter)\b/i, 'singer.songwriter'],
  237. [/\b(?:Pop\/Rock)\b/i, 'pop.rock'],
  238. [/\b(?:Folk\/Rock)\b/i, 'folk.rock'],
  239. ];
  240. this.substitutions = [
  241. [/^(?:Alternative)(?:\s+and\s+|\s*[&+]\s*)(?:Indie)$/i, 'alternative', 'indie'],
  242. [/^(?:Alternativ)(?:\s+und\s+|\s*[&+]\s*)(?:indie)$/i, 'alternative', 'indie'],
  243. [/^(?:Alternatif)(?:\s+et\s+|\s*[&+]\s*)(?:Inde)$/i, 'alternative', 'indie'],
  244. [/^Pop(?:\s+and\s+|\s*[&+]\s*)Rock$/i, 'pop', 'rock'],
  245. [/^Pop\s*(?:[\-\−\—\–]\s*)?Rock$/i, 'pop.rock'],
  246. [/^Rock(?:\s+and\s+|\s*[&+]\s*)Pop$/i, 'pop', 'rock'],
  247. [/^Rock\s*(?:[\-\−\—\–]\s*)?Pop$/i, 'pop.rock'],
  248. [/^Alt\.Rock$/i, 'alternative.rock'],
  249. [/^AOR$/, 'album.oriented.rock'],
  250. [/^Synth[\s\-\−\—\–]+Pop$/i, 'synthpop'],
  251. [/^Soul(?:\s+and\s+|\s*[&+]\s*)Funk$/i, 'soul', 'funk'],
  252. [/^Funk(?:\s+and\s+|\s*[&+]\s*)Soul$/i, 'soul', 'funk'],
  253. [/^World(?:\s+and\s+|\s*[&+]\s*)Country$/i, 'world.music', 'country'],
  254. [/^Jazz Fusion\s*&\s*Jazz Rock$/i, 'jazz.fusion', 'jazz.rock'],
  255. [/^(?:Singer(?:\s+and\s+|\s*[&+]\s*))?Songwriter$/i, 'singer.songwriter'],
  256. [/^(?:R\s*(?:[\'\’\`][Nn](?:\s+|[\'\’\`]\s*)|&\s*)B|RnB)$/i, 'rhytm.and.blues'],
  257. [/\b(?:Soundtracks?)$/i, 'score'],
  258. [/^(?:Electro)$/i, 'electronic'],
  259. [/^(?:Metal)$/i, 'heavy.metal'],
  260. [/^(?:NonFiction)$/i, 'non.fiction'],
  261. [/^(?:Rap)$/i, 'hip.hop'],
  262. [/^NeoSoul$/i, 'neo.soul'],
  263. [/^(?:NuJazz)$/i, 'nu.jazz'],
  264. [/^(?:Hardcore)$/i, 'hardcore.punk'],
  265. [/^(?:garage)$/i, 'garage.rock'],
  266. [/^(?:Ambiente)$/i, 'ambient'],
  267. [/^(?:Neo[\s\-\−\—\–]+Classical)$/i, 'neoclassical'],
  268. [/^(?:Bluesy[\s\-\−\—\–]+Rock)$/i, 'blues.rock'],
  269. [/^(?:Be[\s\-\−\—\–]+Bop)$/i, 'bebop'],
  270. [/^(?:Chill)[\s\-\−\—\–]+(?:Out)$/i, 'chillout'],
  271. [/^(?:Atmospheric)[\s\-\−\—\–]+(?:Black)$/, 'atmospheric.black.metal'],
  272. [/^GoaTrance$/i, 'goa.trance'],
  273. // Country aliases
  274. [/^(?:Canada)$/i, 'canadian'],
  275. [/^(?:Australia)$/i, 'australian'],
  276. [/^(?:Japan)$/i, 'japanese'],
  277. [/^(?:Taiwan)$/i, 'thai'],
  278. [/^(?:China)$/i, 'chinese'],
  279. [/^(?:Russia|USSR)$/i, 'russian'],
  280. [/^(?:France)$/i, 'french'],
  281. [/^(?:Germany)$/i, 'german'],
  282. [/^(?:Spain)$/i, 'spanish'],
  283. [/^(?:Italy)$/i, 'italian'],
  284. [/^(?:Sweden)$/i, 'swedish'],
  285. [/^(?:Norway)$/i, 'norwegian'],
  286. [/^(?:Finland)$/i, 'finnish'],
  287. [/^(?:Greece)$/i, 'greek'],
  288. [/^(?:Netherlands|Holland)$/i, 'dutch'],
  289. [/^(?:Belgium)$/i, 'belgian'],
  290. [/^(?:Denmark)$/i, 'danish'],
  291. [/^(?:Austria)$/i, 'austrian'],
  292. [/^(?:Portugal)$/i, 'portugese'],
  293. [/^(?:Switzerland)$/i, 'swiss'],
  294. [/^(?:Czech\s+Republic|Czechia)$/i, 'czech'],
  295. [/^(?:Slovak\s+Republic|Slovakia)$/i, 'slovak'],
  296. [/^(?:Poland)$/i, 'polish'],
  297. [/^(?:Hungary)$/i, 'hungarian'],
  298. [/^(?:Yugoslavia)$/i, 'yugoslav'],
  299. [/^(?:Brazil)$/i, 'brazilian'],
  300. [/^(?:Mexico)$/i, 'mexican'],
  301. [/^(?:Argentina)$/i, 'argentinean'],
  302. [/^(?:Jamaica)$/i, 'jamaican'],
  303. ];
  304. this.additions = [
  305. [/^(?:(?:(?:Be|Post|Neo)[\s\-\−\—\–]*)?Bop|Modal|Fusion|Free[\s\-\−\—\–]+Improvisation|Jazz[\s\-\−\—\–]+Fusion|Big[\s\-\−\—\–]*Band)$/i, 'jazz'],
  306. [/^(?:(?:Free|Cool|Avant[\s\-\−\—\–]*Garde|Contemporary|Vocal|Instrumental|Crossover|Modal|Mainstream|Modern|Soul|Smooth|Piano|Latin|Afro[\s\-\−\—\–]*Cuban)[\s\-\−\—\–]+Jazz)$/i, 'jazz'],
  307. [/^(?:Opera)$/i, 'classical'],
  308. [/\b(?:Chamber[\s\-\−\—\–]+Music)\b/i, 'classical'],
  309. ];
  310. this.removals = [
  311. /^(?:unknown)$/,
  312. ].concat(excludedCountries);
  313. }
  314.  
  315. add(...tags) {
  316. var added = 0;
  317. for (var tag of tags) {
  318. if (typeof tag != 'string') continue;
  319. this.presubstitutions.forEach(k => { if (k[0].test(tag)) tag = tag.replace(k[0], k[1]) });
  320. tag.split(/\s*[\,\/\;\>\|]+\s*/).forEach(function(tag) {
  321. tag = tag.normalize("NFD").
  322. replace(/[\u0300-\u036f]/g, '').
  323. replace(/\(.*?\)|\[.*?\]|\{.*?\}/g, '').
  324. trim();
  325. if (tag.length <= 0 || tag == '?') return null;
  326. function test(obj) {
  327. return obj instanceof RegExp && obj.test(tag)
  328. || typeof obj == 'string' && tag.toLowerCase() == obj.toLowerCase();
  329. }
  330. if (this.removals.some(k => test(k))) {
  331. addMessage('Warning: bad tag \'' + tag + '\' found', 'ua-warning');
  332. return;
  333. }
  334. for (var k of this.additions) {
  335. if (test(k[0])) added += this.add(...k.slice(1));
  336. }
  337. for (k of this.substitutions) {
  338. if (test(k[0])) { added += this.add(...k.slice(1)); return; }
  339. }
  340. tag = tag.
  341. replace(/\bAlt\.(?=\s+)/i, 'Alternative').
  342. replace(/^[3-9]0s$/i, '19$0').
  343. replace(/^[0-2]0s$/i, '20$0').
  344. replace(/\b(Psy)[\s\-\−\—\–]+(Trance|Core|Chill)\b/i, '$1$2').
  345. replace(/\s*(?:[\'\’\`][Nn](?:\s+|[\'\’\`]\s*)|[\&\+]\s*)/, ' and ').
  346. replace(/[\s\-\−\—\–\_\.\,\'\`\~]+/g, '.').
  347. replace(/[^\w\.]+/g, '').
  348. toLowerCase();
  349. if (tag.length >= 2 && !this.includes(tag)) {
  350. this.push(tag);
  351. ++added;
  352. }
  353. }.bind(this));
  354. }
  355. return added;
  356. }
  357. toString() {
  358. return this.length > 0 ? this.sort().join(', ') : null;
  359. }
  360. };
  361.  
  362. if ((ref = document.getElementById('categories')) != null) {
  363. ref.addEventListener('change', function(e) {
  364. elem = document.getElementById('upload assistant');
  365. if (elem != null) elem.style.visibility = this.value < 4
  366. || ['Music', 'Applications', 'E-Books', 'Audiobooks'].includes(this.value) ? 'visible' : 'collapse';
  367. });
  368. }
  369.  
  370. return;
  371.  
  372. function fill_from_text(e) {
  373. var overwrite = this.id == 'fill-from-text';
  374. var clipBoard = document.getElementById('UA data');
  375. if (clipBoard == null) return false;
  376. const urlParser = /^\s*(https?:\/\/[\S]+)\s*$/i;
  377. messages = document.getElementById('UA messages');
  378. //let promise = clientInformation.clipboard.readText().then(text => clipBoard = text);
  379. //if (typeof clipBoard != 'string') return false;
  380. var i, matches, url, category = document.getElementById('categories');
  381. if (category == null && document.getElementById('releasetype') != null
  382. || category != null && (category.value == 0 || category.value == 'Music')) return fill_from_text_music();
  383. if (category != null && (category.value == 1 || category.value == 'Applications')) return fill_from_text_apps();
  384. if (category != null && (category.value == 2 || category.value == 3
  385. || category.value == 'E-Books' || category.value == 'Audiobooks')) return fill_from_text_books();
  386. return category == null ? fill_from_text_apps() || fill_from_text_books() : false;
  387.  
  388. function fill_from_text_music() {
  389. if (messages != null) messages.parentNode.removeChild(messages);
  390. const divs = ['—', '⸺', '⸻'];
  391. var track, tracks = [], totalDiscs = 1;
  392. const multiArtistParser = /\s*(?:[;\/\|]|,(?!\s*(?:[JjSs]r)\b)(?:\s*and\s+)?)\s*/;
  393. const ampersandParser = /\s+(?:[\&\+]|and)(?!\s*(?:The|his|her|Friends)\b)\s+/i;
  394. const featParsers = [
  395. /\s+(?:meets)\s+(.*?)\s*$/,
  396. /\s+(?:featuring|with)\s+(.*?)\s*$/,
  397. /\s+feat\.\s+(.*?)\s*$/,
  398. /\s+\[(?:feat(?:\.|uring)|with)\s+([^\[\]]+?)\s*\]/,
  399. /\s+\((?:feat(?:\.|uring)|with)\s+([^\(\)]+?)\s*\)/,
  400. ];
  401. if (urlParser.test(clipBoard.value)) return init_from_url_music(RegExp.$1);
  402. function ruleLink(rule) { return ' (<a href="https://redacted.ch/rules.php?p=upload#r' + rule + '" target="_blank">' + rule + '</a>)' }
  403. var albumBitrate = 0, totalTime = 0;
  404. for (iter of clipBoard.value.split(/[\r\n]+/)) {
  405. if (!iter.trim()) continue; // skip empty lines
  406. let metaData = iter.split('\x1E');
  407. track = {
  408. artist: metaData.shift().trim() || undefined,
  409. album: metaData.shift().trim() || undefined,
  410. album_year: safeParseYear(metaData.shift().trim()),
  411. release_date: metaData.shift().trim() || undefined,
  412. label: metaData.shift().trim() || undefined,
  413. catalog: metaData.shift().trim() || undefined,
  414. country: metaData.shift().trim() || undefined,
  415. encoding: metaData.shift().trim() || undefined,
  416. codec: metaData.shift().trim() || undefined,
  417. codec_profile: metaData.shift().trim() || undefined,
  418. bitrate: safeParseInt(metaData.shift()),
  419. bd: safeParseInt(metaData.shift()),
  420. sr: safeParseInt(metaData.shift()),
  421. channels: safeParseInt(metaData.shift()),
  422. media: metaData.shift().trim() || undefined,
  423. genre: metaData.shift().trim() || undefined,
  424. discnumber: safeParseInt(metaData.shift()),
  425. totaldiscs: safeParseInt(metaData.shift()),
  426. discsubtitle: metaData.shift().trim() || undefined,
  427. tracknumber: metaData.shift().trim() || undefined,
  428. totaltracks: safeParseInt(metaData.shift()),
  429. title: metaData.shift().trim() || undefined,
  430. track_artist: metaData.shift().trim() || undefined,
  431. performer: metaData.shift().trim() || undefined,
  432. composer: metaData.shift().trim() || undefined,
  433. conductor: metaData.shift().trim() || undefined,
  434. remixer: metaData.shift().trim() || undefined,
  435. compiler: metaData.shift().trim() || undefined,
  436. producer: metaData.shift().trim() || undefined,
  437. duration: safeParseFloat(metaData.shift()),
  438. samples: safeParseInt(metaData.shift()),
  439. rg: metaData.shift().trim() || undefined,
  440. dr: metaData.shift().trim() || undefined,
  441. vendor: metaData.shift().trim() || undefined,
  442. url: metaData.shift().trim() || undefined,
  443. dirpath: metaData.shift() || undefined,
  444. comment: metaData.shift().trim() || undefined,
  445. identifiers: {},
  446. };
  447. if (!track.artist) {
  448. addMessage('FATAL: album artist must be defined in every track' + ruleLink('2.3.16.4'), 'ua-critical', true);
  449. clipBoard.value = '';
  450. throw new Error('artist missing');
  451. }
  452. if (!track.album) {
  453. addMessage('FATAL: album title must be defined in every track' + ruleLink('2.3.16.4'), 'ua-critical', true);
  454. clipBoard.value = '';
  455. throw new Error('album mising');
  456. }
  457. if (!track.tracknumber) {
  458. addMessage('FATAL: all track numbers must be defined' + ruleLink('2.3.16.4'), 'ua-critical', true);
  459. clipBoard.value = '';
  460. throw new Error('tracknumber missing');
  461. }
  462. if (!track.title) {
  463. addMessage('FATAL: all track titles must be defined' + ruleLink('2.3.16.4'), 'ua-critical', true);
  464. clipBoard.value = '';
  465. throw new Error('track title missing');
  466. }
  467. if (track.duration != undefined && isUpload && (isNaN(track.duration) || track.duration <= 0)) {
  468. addMessage('FATAL: invalid track #' + track.tracknumber + ' length: ' + track.duration, 'ua-critical');
  469. clipBoard.value = '';
  470. throw new Error('invalid duration');
  471. }
  472. if (track.codec && !['FLAC', 'MP3', 'AAC', 'DTS', 'AC3'].includes(track.codec)) {
  473. addMessage('FATAL: disallowed codec present (' + track.codec + ')', 'ua-critical');
  474. clipBoard.value = '';
  475. throw new Error('invalid format');
  476. }
  477. if (track.discnumber > totalDiscs) totalDiscs = track.discnumber;
  478. if (track.comment == '.') track.comment = undefined;
  479. if (track.comment) {
  480. track.comment = track.comment.replace(/\x1D/g, '\r').replace(/\x1C/g, '\n');
  481. if (prefs.remap_texttools_newlines) track.comment = track.comment.replace(/__/g, '\r\n').replace(/_/g, '\n') // ambiguous
  482. }
  483. if (track.dr != null) track.dr = parseInt(track.dr); // DR0
  484. metaData.shift().trim().split(/\s+/).forEach(function(it) {
  485. if (/([\w\-]+)[=:](.*)/.test(it)) track.identifiers[RegExp.$1.toUpperCase()] = RegExp.$2.replace(/\x1B/g, ' ');
  486. });
  487. totalTime += track.duration || NaN;
  488. albumBitrate += (track.duration || NaN) * (track.bitrate || NaN);
  489.  
  490. tracks.push(track);
  491.  
  492. function safeParseInt(x) { return typeof x != 'string' ? null : x.length <= 0 ? undefined : parseInt(x) }
  493. function safeParseFloat(x) { return typeof x != 'string' ? null : x.length <= 0 ? undefined : parseFloat(x) }
  494. function safeParseYear(x) { return typeof x != 'string' ? null : x.length <= 0 ? undefined : extract_year(x) || NaN }
  495. }
  496. if (tracks.length <= 0) {
  497. addMessage('FATAL: no tracks found', 'ua-critical', true);
  498. clipBoard.value = '';
  499. throw new Error('no tracks');
  500. }
  501. if (!tracks.every(it => it.discnumber > 0) && !tracks.every(it => !it.discnumber)) {
  502. addMessage('FATAL: inconsistent release (mix of tracks with and without disc number)', 'ua-critical', true);
  503. clipBoard.value = '';
  504. throw new Error('inconsistent disc numbering');
  505. }
  506.  
  507. var release = {};
  508. function setUniqueProperty(propName, propNameLiteral) {
  509. let homogenous = new Set(tracks.map(it => it[propName]).filter(it => it != undefined && it != null));
  510. if (homogenous.size > 1) {
  511. var diverses = '', it = homogenous.values(), val;
  512. while (!(val = it.next()).done) diverses += '<br>\t' + val.value;
  513. addMessage('FATAL: mixed releases not accepted (' + propNameLiteral + ') - supposedly user compilation' + diverses, 'ua-critical', true);
  514. clipBoard.value = '';
  515. throw new Error('mixed release (' + propNameLiteral + ')');
  516. }
  517. release[propName] = homogenous.values().next().value;
  518. }
  519. setUniqueProperty('artist', 'album artist', true);
  520. setUniqueProperty('album', 'album title', true);
  521. setUniqueProperty('album_year', 'album year');
  522. setUniqueProperty('release_date', 'release date');
  523. setUniqueProperty('encoding', 'encoding');
  524. setUniqueProperty('codec', 'codec');
  525. setUniqueProperty('codec_profile', 'codec profile');
  526. setUniqueProperty('vendor', 'vendor');
  527. setUniqueProperty('media', 'media');
  528. setUniqueProperty('channels', 'channels');
  529. setUniqueProperty('label', 'label');
  530. setUniqueProperty('country', 'country');
  531.  
  532. var composerEmphasis = false, isFromDVD = false, isClassical = false;
  533. var yadg_prefil = '', releaseType, editionTitle, media, isVA, iter, rx;
  534.  
  535. ['catalogs', 'bds', 'genres', 'srs', 'urls', 'comments', 'trackArtists', 'bitrates',
  536. 'drs', 'rgs', 'dirpaths'].forEach(it => { release[it] = [] });
  537.  
  538. tracks.forEach(function(iter) {
  539. push_unique('trackArtists', 'track_artist');
  540. push_unique('catalogs', 'catalog');
  541. push_unique('bitrates', 'bitrate');
  542. push_unique('bds', 'bd');
  543. push_unique('rgs', 'rg');
  544. push_unique('drs', 'dr');
  545. if (iter.sr) {
  546. if (typeof release.srs[iter.sr] != 'number') {
  547. release.srs[iter.sr] = iter.duration;
  548. } else {
  549. release.srs[iter.sr] += iter.duration;
  550. }
  551. }
  552. push_unique('dirpaths', 'dirpath');
  553. push_unique('comments', 'comment');
  554. push_unique('genres', 'genre');
  555. push_unique('urls', 'url');
  556.  
  557. function push_unique(relProp, prop) {
  558. if (iter[prop] !== undefined && iter[prop] !== null && (typeof iter[prop] != 'string'
  559. || iter[prop].length > 0) && !release[relProp].includes(iter[prop])) release[relProp].push(iter[prop]);
  560. }
  561. });
  562. function validatorFunc(arr, validator, str) {
  563. if (arr.length <= 0 || !arr.some(validator)) return true;
  564. addMessage('FATAL: disallowed ' + str + ' present (' + arr.filter(validator) + ')', 'ua-critical');
  565. clipBoard.value = '';
  566. throw new Error('disallowed ' + str);
  567. }
  568. validatorFunc(release.bds, (bd) => ![16, 24].includes(bd), 'bit depths');
  569. validatorFunc(Object.keys(release.srs),
  570. (sr) => sr < 44100 || sr > 192000 || sr % 44100 != 0 && sr % 48000 != 0, 'sample rates');
  571.  
  572. albumBitrate /= totalTime;
  573. var tags = new TagManager();
  574. if (tracks.every(it => /^single$/i.test(it.identifiers.RELEASETYPE))
  575. || totalTime > 0 && totalTime <= prefs.single_threshold) {
  576. releaseType = getReleaseIndex('Single');
  577. } else if (tracks.every(it => it.identifiers.RELEASETYPE == 'EP')
  578. || totalTime > 0 && totalTime <= prefs.EP_threshold) {
  579. releaseType = getReleaseIndex('EP');
  580. } else if (tracks.every(it => /^soundtrack$/i.test(it.identifiers.RELEASETYPE))) {
  581. releaseType = getReleaseIndex('Soundtrack');
  582. tags.add('score');
  583. composerEmphasis = true;
  584. }
  585.  
  586. // Processing artists: recognition, splitting and dividing to categores
  587. const remixParsers = [
  588. /\s+\(Remix(?:e[sd])?\)/i,
  589. /\s+\[Remix(?:e[sd])?\]/i,
  590. /\s+Remix(?:e[sd])?\s*$/i,
  591. /\s+\(([^\(\)]+?)(?:[\'\’\`]s)? remix\)/i,
  592. /\s+\[([^\[\]]+?)(?:[\'\’\`]s)? remix\]/i,
  593. /\s+\(remix(?:ed)? by ([^\(\)]+)\)/i,
  594. /\s+\[remix(?:ed)? by ([^\[\]]+)\]/i,
  595. ];
  596. const otherArtistsParsers = [
  597. [/^(.*?)\s+(?:under|(?:conducted) by)\s+(.*)$/, 4],
  598. [/^()(.*?)\s+\(conductor\)$/i, 4],
  599. //[/^()(.*?)\s+\(.*\)$/i, 1],
  600. ];
  601. const noAkas = /\s+(?:aka|AKA)\s+(.*)/;
  602. const invalidArtist = /^(?:#?N\/?A|[JS]r\.?)$/i;
  603. isVA = release.artist == 'VA' || /^(?:Various(?:\s+Artists?)?)$/i.test(release.artist);
  604. var artists = [], xhr = new XMLHttpRequest();
  605. for (iter = 0; iter < 7; ++iter) artists[iter] = [];
  606.  
  607. if (!isVA) addArtists(0, yadg_prefil = spliceGuests(release.artist));
  608.  
  609. featParsers.slice(3).forEach(function(rx) {
  610. if (rx.test(release.album)) {
  611. addArtists(1, RegExp.$1);
  612. addMessage('Warning: featured artist(s) in album title (' + release.album + ')', 'ua-warning');
  613. release.album = release.album.replace(rx, '');
  614. }
  615. });
  616. remixParsers.slice(3).forEach(function(rx) {
  617. if (rx.test(release.album)) addArtists(2, RegExp.$1);
  618. })
  619.  
  620. for (iter of tracks) {
  621. addTrackPerformers(iter.track_artist);
  622. addTrackPerformers(iter.performer);
  623. addArtists(2, iter.remixer);
  624. addArtists(3, iter.composer);
  625. addArtists(4, iter.conductor);
  626. addArtists(5, iter.compiler);
  627. addArtists(6, iter.producer);
  628.  
  629. if (iter.title) {
  630. featParsers.slice(3).forEach(function(rx) {
  631. if (rx.test(iter.title)) {
  632. addArtists(1, RegExp.$1);
  633. iter.track_artist = (!isVA && (!iter.track_artist || iter.track_artist.includes(RegExp.$1)) ?
  634. iter.artist : iter.track_artist) + ' feat. ' + RegExp.$1;
  635. addMessage('Warning: featured artist(s) in track title (#' + iter.tracknumber + ': ' + iter.title + ')', 'ua-warning');
  636. iter.title = iter.title.replace(rx, '');
  637. }
  638. });
  639. remixParsers.slice(3).forEach(function(rx) {
  640. if (rx.test(iter.title)) addArtists(2, RegExp.$1);
  641. });
  642. }
  643. }
  644. // Split ampersands
  645. for (iter = 0; iter < Math.round(tracks.length / 2); ++iter) {
  646. for (let ndx = 0; ndx < 7; ++ndx) {
  647. for (i = artists[ndx].length; i > 0; --i) {
  648. let j = artists[ndx][i - 1].split(ampersandParser);
  649. if (j.length >= 2 && j.every(twoOrMore) && !getSiteArtist(artists[ndx][i - 1])
  650. && (j.some(it1 => artists.some(it2 => it2.includesCaseless(it1))) || j.every(looksLikeTrueName))) {
  651. artists[ndx].splice(i - 1, 1, ...j.filter(function(it) {
  652. return !artists[ndx].includesCaseless(it) && (ndx != 1 || !artists[0].includesCaseless(it));
  653. }));
  654. }
  655. }
  656. }
  657. }
  658.  
  659. function addArtists(index, str) {
  660. if (str) splitArtists(str).forEach(function(it) {
  661. it = index != 0 ? it.replace(noAkas, '') : guessOtherArtists(it);
  662. if (it.length > 0 && !invalidArtist.test(it) && !artists[index].includesCaseless(it)
  663. && (index != 1 || !artists[0].includesCaseless(it))) artists[index].push(it);
  664. });
  665. }
  666. function addTrackPerformers(str) {
  667. if (str) splitArtists(spliceGuests(str, 1)).forEach(function(it) {
  668. it = guessOtherArtists(it);
  669. if (it.length > 0 && !invalidArtist.test(it) && !artists[0].includesCaseless(it)
  670. && (isVA || !artists[1].includesCaseless(it))) artists[isVA ? 0 : 1].push(it);
  671. });
  672. }
  673. function splitArtists(str) {
  674. var j = str.split(multiArtistParser);
  675. return j.length == 1 || j.every(twoOrMore)
  676. && !j.some(a => invalidArtist.test(a)) && !getSiteArtist(str) ? j : [ str ];
  677. }
  678. function spliceGuests(str, level) {
  679. (level ? featParsers.slice(level) : featParsers).forEach(function(it) {
  680. if (it.test(str)) {
  681. addArtists(1, RegExp.$1);
  682. str = str.replace(it, '');
  683. }
  684. });
  685. return str;
  686. }
  687. function guessOtherArtists(name) {
  688. otherArtistsParsers.forEach(function(it) {
  689. if (!it[0].test(name)) return;
  690. addArtists(it[1], RegExp.$2);
  691. name = RegExp.$1;
  692. });
  693. return name.replace(noAkas, '');
  694. }
  695. function getSiteArtist(artist) {
  696. if (!artist) return null;
  697. xhr.open('GET', 'https://' + document.domain + '/ajax.php?action=artist&artistname=' + encodeURIComponent(artist), false);
  698. xhr.send();
  699. if (xhr.readyState != 4 || xhr.status != 200) {
  700. console.log('getSiteArtist("' + artist + '"): XMLHttpRequest readyState:' + xhr.readyState + ' status:' + xhr.status);
  701. return undefined; // error
  702. }
  703. var response = JSON.parse(xhr.responseText);
  704. return response.status == 'success' ? response.response : null;
  705. }
  706. function twoOrMore(artist) { return artist.length >= 2 && !invalidArtist.test(artist) };
  707. function looksLikeTrueName(artist, index) {
  708. return (index == 0 || !/^(?:The|his|her|Friends)\s+/i.test(artist)) && artist.split(/\s+/).length >= 2
  709. || getSiteArtist(artist);
  710. }
  711.  
  712. if (element_writable(document.getElementById('artist'))) {
  713. const artistSel = 'input[name="artists[]"]';
  714. let artist_index = 0;
  715. feedArtistCategory(artists[0].filter(k => !artists[4].includesCaseless(k)), 1);
  716. feedArtistCategory(artists[1].filter(k => !artists[0].includesCaseless(k) && !artists[4].includesCaseless(k)), 2);
  717. for (i = 2; i < 7; ++i) feedArtistCategory(artists[i], i + 1);
  718. if (overwrite) while (document.getElementById('artist_' + artist_index) != null) {
  719. exec(function() { RemoveArtistField() });
  720. }
  721.  
  722. function feedArtistCategory(list, type) {
  723. for (iter of list.sort()) {
  724. if (isUpload) {
  725. var id = 'artist';
  726. if (artist_index > 0) id += '_' + artist_index;
  727. while ((ref = document.getElementById(id)) == null) add_artist();
  728. } else {
  729. ref = document.querySelectorAll(artistSel);
  730. if (ref.length < artist_index + 1) {
  731. for (i = ref.length; i < artist_index + 1; ++i) add_artist();
  732. ref = document.querySelectorAll(artistSel);
  733. }
  734. ref = ref[artist_index];
  735. }
  736. if (ref == null) continue;
  737. ref.value = iter;
  738. ref.nextElementSibling.value = type;
  739. ++artist_index;
  740. }
  741. }
  742. }
  743.  
  744. // Processing album title
  745. const remasterParsers = [
  746. /\s+\(([^\(\)]*\b(?:Remaster(?:ed)?\b[^\(\)]*|Reissue|Edition|Version|Promo|Enhanced|Release))\)$/i,
  747. /\s+\[([^\[\]]*\b(?:Remaster(?:ed)?\b[^\[\]]*|Reissue|Edition|Version|Promo|Enhanced|Release))\]$/i,
  748. /\s+-\s+([^\[\]\(\)\-\−\—\–]*\b(?:(?:Remaster(?:ed)?|Bonus\s+Track)\b[^\[\]\(\)\-\−\—\–]*|Reissue|Edition|Version|Promo|Enhanced|Release))$/i
  749. ];
  750. const mediaParsers = [
  751. [/\s+(?:\[(?:LP|Vinyl|12"|7")\]|\((?:LP|Vinyl|12"|7")\))$/, 'Vinyl'],
  752. [/\s+(?:\[SA-?CD\]|\(SA-?CD\))$/, 'SACD'],
  753. [/\s+(?:\[(?:Blu[\s\-\−\—\–]?Ray|B[DR])\]|\((?:Blu[\s\-\−\—\–]?Ray|B[DR])\))$/, 'Blu-Ray'],
  754. [/\s+(?:\[DVD(?:-?A)?\]|\(DVD(?:-?A)?\))$/, 'DVD'],
  755. ];
  756. const releaseTypeParsers = [
  757. [/\s+(?:-\s+Single|\[Single\]|\(Single\))$/i, 'Single', true, true],
  758. [/\s+(?:(?:-\s+)?EP|\[EP\]|\(EP\))$/, 'EP', true, true],
  759. [/\s+\((?:Live|En\s+directo?|Ao\s+Vivo)\b[^\(\)]*\)$/i, 'Live album', false, false],
  760. [/\s+\[(?:Live|En\s+directo?|Ao\s+Vivo)\b[^\[\]]*\]$/i, 'Live album', false, false],
  761. [/(?:^Live\s+(?:[aA]t|[Ii]n)\b|^Directo?\s+[Ee]n\b|\bUnplugged\b|\bAcoustic\s+Stage\b|\s+Live$)/, 'Live album', false, false],
  762. [/\b(?:Best [Oo]f|Greatest Hits|Complete\s+(.+?\s+)(?:Albums|Recordings))\b/, 'Anthology', false, false],
  763. ];
  764. var album = release.album;
  765. releaseTypeParsers.forEach(function(it) {
  766. if (it[0].test(album)) {
  767. if (it[2] || !releaseType) releaseType = getReleaseIndex(it[1]);
  768. if (it[3]) album = album.replace(it[0], '');
  769. }
  770. });
  771. rx = '\\b(?:Soundtrack|Score|Motion\\s+Picture|Series|Television|Original(?:\\s+\\w+)?\\s+Cast|Music\\s+from|(?:Musique|Bande)\\s+originale)\\b';
  772. if (reInParenthesis(rx).test(album) || reInBrackets(rx).test(album)) {
  773. if (!releaseType) releaseType = getReleaseIndex('Soundtrack');
  774. tags.add('score');
  775. composerEmphasis = true;
  776. }
  777. remixParsers.forEach(function(rx) {
  778. if (rx.test(album) && !releaseType) releaseType = getReleaseIndex('Remix');
  779. });
  780. remasterParsers.forEach(function(rx) {
  781. if (rx.test(album)) {
  782. album = album.replace(rx, '');
  783. editionTitle = RegExp.$1;
  784. }
  785. });
  786. mediaParsers.forEach(function(it) {
  787. if (it[0].test(album)) {
  788. album = album.replace(it[0], '');
  789. media = it[1];
  790. }
  791. });
  792. if (element_writable(ref = document.getElementById('title') || document.querySelector('input[name="title"]'))) {
  793. ref.value = album;
  794. }
  795.  
  796. if (yadg_prefil) yadg_prefil += ' ';
  797. yadg_prefil += album;
  798. if (element_writable(ref = document.getElementById('yadg_input'))) {
  799. ref.value = yadg_prefil || '';
  800. if (yadg_prefil && (ref = document.getElementById('yadg_submit')) != null && !ref.disabled) ref.click();
  801. }
  802.  
  803. if (element_writable(ref = document.getElementById('year'))) {
  804. ref.value = release.album_year || '';
  805. }
  806. i = release.release_date && extract_year(release.release_date);
  807. if (element_writable(ref = document.getElementById('remaster_year'))
  808. || !isUpload && i > 0 && (ref = document.querySelector('input[name="year"]')) != null && !ref.disabled) {
  809. ref.value = i || '';
  810. }
  811. //if (tracks.every(it => it.identifiers.EXPLICIT == '0')) editionTitle = 'Clean' + (editionTitle ? ' / ' + editionTitle : '');
  812. if (element_writable(ref = document.getElementById('remaster_title'))) {
  813. ref.value = editionTitle || '';
  814. }
  815. rx = /\s*[\,\;]\s*/g;
  816. if (element_writable(ref = document.getElementById('remaster_record_label') || document.querySelector('input[name="recordlabel"]'))) {
  817. ref.value = release.label && release.label.replace(rx, ' / ') || '';
  818. }
  819. if (element_writable(ref = document.getElementById('remaster_catalogue_number') || document.querySelector('input[name="cataloguenumber"]'))) {
  820. let barcode = tracks.every(function(it, ndx, arr) {
  821. return it.identifiers.BARCODE && it.identifiers.BARCODE == arr[0].identifiers.BARCODE;
  822. }) && tracks[0].identifiers.BARCODE;
  823. ref.value = release.catalogs.length >= 1 && release.catalogs.map(k => k.replace(rx, ' / ')).join(' / ')
  824. || barcode || '';
  825. }
  826. var br_isSet = (ref = document.getElementById('bitrate')) != null && ref.value;
  827. if (element_writable(ref = document.getElementById('format'))) {
  828. ref.value = release.codec || '';
  829. ref.onchange(); //exec(function() { Format() });
  830. }
  831. if (isRequest) {
  832. if (prefs.always_request_perfect_flac) reqSelectFormats('FLAC');
  833. else if (release.codec) reqSelectFormats(release.codec);
  834. }
  835. var sel;
  836. if (release.encoding == 'lossless') {
  837. sel = release.bds.includes(24) ? '24bit Lossless' : 'Lossless';
  838. } else if (release.bitrates.length >= 1) {
  839. let lame_version = release.codec == 'MP3' && /^LAME(\d+)\.(\d+)/i.test(release.vendor) ?
  840. parseInt(RegExp.$1) * 1000 + parseInt(RegExp.$2) : undefined;
  841. if (release.codec == 'MP3' && release.codec_profile == 'VBR V0') {
  842. sel = lame_version >= 3094 ? 'V0 (VBR)' : 'APX (VBR)'
  843. } else if (release.codec == 'MP3' && release.codec_profile == 'VBR V1') {
  844. sel = 'V1 (VBR)'
  845. } else if (release.codec == 'MP3' && release.codec_profile == 'VBR V2') {
  846. sel = lame_version >= 3094 ? sel = 'V2 (VBR)' : 'APS (VBR)'
  847. } else if (release.bitrates.length == 1 && [192, 256, 320].includes(Math.round(release.bitrates[0]))) {
  848. sel = Math.round(release.bitrates[0]);
  849. } else {
  850. sel = 'Other';
  851. }
  852. }
  853. if ((ref = document.getElementById('bitrate')) != null && !ref.disabled && (overwrite || !br_isSet)) {
  854. ref.value = sel || '';
  855. ref.onchange(); //exec(function() { Bitrate() });
  856. if (sel == 'Other' && (ref = document.getElementById('other_bitrate')) != null) {
  857. ref.value = Math.round(release.bitrates.length == 1 ? release.bitrates[0] : albumBitrate);
  858. if ((ref = document.getElementById('vbr')) != null) ref.checked = release.bitrates.length > 1;
  859. }
  860. }
  861. if (sel && isRequest) {
  862. if (prefs.always_request_perfect_flac) {
  863. reqSelectBitrates('Lossless', '24bit Lossless');
  864. } else reqSelectBitrates(sel);
  865. }
  866. if (release.media) {
  867. sel = undefined;
  868. [
  869. [/\b(?:WEB|File|Download|digital\s+media)\b/i, 'WEB'],
  870. [/\bCD\b/, 'CD'],
  871. [/\b(?:SA-?CD|[Hh]ybrid)\b/, 'SACD'],
  872. [/\b(?:[Bb]lu[\-\−\—\–\s]?[Rr]ay|BR|BD)\b/, 'Blu-Ray'],
  873. [/\bDVD(?:-?A)?\b/, 'DVD'],
  874. [/\b(?:[Vv]inyl\b|LP\b|12"|7")/, 'Vinyl'],
  875. ].forEach(k => { if (k[0].test(release.media)) sel = k[1] });
  876. media = sel || media;
  877. }
  878. if (element_writable(ref = document.getElementById('media'))) ref.value = media || '';
  879. if (isRequest) {
  880. if (prefs.always_request_perfect_flac) reqSelectMedias('WEB', 'CD', 'Blu-Ray', 'DVD', 'SACD');
  881. else if (media) reqSelectMedias(media);
  882. }
  883. function isRedBook(t) {
  884. return t.bd == 16 && t.sr == 44100 && t.channels == 2 && t.samples > 0 && t.samples % 588 == 0;
  885. }
  886. if (!media) {
  887. if (tracks.every(isRedBook)) {
  888. addMessage('Info: media not determined - CD estimated', 'ua-info');
  889. } else if (tracks.some(t => t.bd > 16 || (t.sr > 0 && t.sr != 44100) || t.samples > 0 && t.samples % 588 != 0)) {
  890. addMessage('Info: media not determined - NOT CD', 'ua-info');
  891. }
  892. } else if (media != 'CD' && tracks.every(isRedBook)) {
  893. addMessage('Info: CD as source media is estimated (' + media + ')', 'ua-info');
  894. }
  895. if (media == 'WEB') for (iter of tracks) {
  896. if (iter.duration > 29.5 && iter.duration < 30.5) {
  897. addMessage('Warning: track ' + iter.tracknumber + ' possible preview', 'ua-warning');
  898. }
  899. }
  900. if (release.genres.length >= 1) {
  901. release.genres.forEach(function(genre) {
  902. if (/\b(?:Classical|Symphony|Symphonic(?:al)?$|Chamber|Choral|Etude|Opera|Duets|Klassik)\b/i.test(genre)
  903. && !/\b(?:metal|rock|pop)\b/i.test(genre)) {
  904. composerEmphasis = true;
  905. isClassical = true
  906. }
  907. if (/\b(?:Jazz|Vocal)\b/i.test(genre) && !/\b(?:Nu|Future|Acid)[\s\-\−\—\–]*Jazz\b/i.test(genre)
  908. && !/\bElectr(?:o|ic)[\s\-\−\—\–]?Swing\b/i.test(genre)) {
  909. composerEmphasis = true;
  910. }
  911. if (/\b(?:Soundtracks?|Score|Films?|Games?|Video|Series?|Theatre|Musical)\b/i.test(genre)) {
  912. composerEmphasis = true;
  913. if (!releaseType) releaseType = getReleaseIndex('Soundtrack');
  914. tags.add('score');
  915. composerEmphasis = true;
  916. }
  917. tags.add(genre);
  918. });
  919. if (release.genres.length > 1) {
  920. addMessage('Warning: inconsistent genre accross album: ' + release.genres, 'ua-warning');
  921. }
  922. }
  923. if (release.country) {
  924. if (!excludedCountries.some(it => it.test(release.country))) tags.add(release.country);
  925. }
  926. if (element_writable(ref = document.getElementById('tags'))) {
  927. ref.value = tags.length >= 1 ? tags.toString() : '';
  928. if (artists[0].length == 1 && prefs.fetch_tags_from_artist > 0) setTimeout(function() {
  929. var artist = getSiteArtist(artists[0][0]);
  930. if (!artist) return;
  931. tags.add(...artist.tags.sort((a, b) => b.count - a.count).map(it => it.name).slice(0, prefs.fetch_tags_from_artist));
  932. var ref = document.getElementById('tags');
  933. ref.value = tags.toString();
  934. }, 2000);
  935. }
  936. if (isClassical && !tracks.every(it => it.composer)) {
  937. addMessage('FATAL: all tracks composers must be defined' + ruleLink('2.3.17'), 'ua-critical', true);
  938. return false;
  939. }
  940. if (!releaseType) {
  941. if (isVA) {
  942. releaseType = getReleaseIndex('Compilation');
  943. } else if (tracks.every(it => it.identifiers.COMPILATION == 1)) {
  944. releaseType = getReleaseIndex('Anthology');
  945. }
  946. }
  947. if ((ref = document.getElementById('releasetype')) != null && !ref.disabled && (overwrite || ref.value == 0)) {
  948. ref.value = releaseType || getReleaseIndex('Album');
  949. }
  950. if (!composerEmphasis && !prefs.keep_meaningles_composers) {
  951. document.querySelectorAll('input[name="artists[]"]').forEach(function(i) {
  952. if (['4', '5'].includes(i.nextElementSibling.value)) i.value = '';
  953. });
  954. }
  955. const doubleParsParsers = [
  956. /\(+(\([^\(\)]*\))\)+/,
  957. /\[+(\[[^\[\]]*\])\]+/,
  958. /\{+(\{[^\{\}]*\})\}+/,
  959. ];
  960. for (iter of tracks) {
  961. doubleParsParsers.forEach(function(rx) {
  962. if (rx.test(iter.title)) {
  963. addMessage('Warning: doubled parentheses in track #' + iter.tracknumber +
  964. ' title ("' + iter.title + '")', 'ua-warning');
  965. //iter.title.replace(rx, RegExp.$1);
  966. }
  967. });
  968. }
  969. if (tracks.length > 1 && array_homogenous(tracks.map(k => k.title))) {
  970. addMessage('Warning: all tracks having same title: ' + tracks[0].title, 'ua-warning');
  971. }
  972. var description;
  973. url = release.urls.length == 1 && release.urls[0];
  974. if (!url && tracks.every(it => it.identifiers.DISCOGS_ID && it.identifiers.DISCOGS_ID == tracks[0].identifiers.DISCOGS_ID)) {
  975. url = 'https://www.discogs.com/release/' + tracks[0].identifiers.DISCOGS_ID;
  976. }
  977. if (!isRequest) {
  978. var ripinfo, dur;
  979. const vinylTest = /^((?:Vinyl|LP) rip by\s+)(.*)$/im;
  980. description = artists[0].length >= 3 ?
  981. '[size=4]' + joinArtists(artists[0], '[artist]', '[/artist]') + ' – ' + release.album + '[/size]\n\n' : '';
  982. // ============================================= The Playlist =============================================
  983. if (tracks.length > 1) {
  984. gen_full_tracklist();
  985. } else { // single
  986. description += '[align=center]';
  987. description += isRED() ? '[pad=20|20|20|20]' : '';
  988. description += '[size=4][b][color=' + prefs.tracklist_artist_color + ']' + release.artist + '[/color][hr]';
  989. //description += '[color=' + prefs.tracklist_single_color + ']';
  990. description += tracks[0].title;
  991. //description += '[/color]'
  992. description += '[/b]';
  993. if (tracks[0].composer) {
  994. description += '\n[i][color=' + prefs.tracklist_composer_color + '](' + tracks[0].composer + ')[/color][/i]';
  995. }
  996. description += '\n\n[color=' + prefs.tracklist_duration_color +'][' +
  997. makeTimeString(tracks[0].duration) + '][/color][/size]';
  998. if (isRED()) description += '[/pad]';
  999. description += '[/align]';
  1000. }
  1001. if (release.comments.length == 1 && release.comments[0]) {
  1002. if (matches = release.comments[0].match(vinylTest)) {
  1003. ripinfo = release.comments[0].slice(matches.index).trim().split(/[\r\n]+/);
  1004. description = description.concat('\n\n', release.comments[0].slice(0, matches.index).trim());
  1005. } else {
  1006. description += '\n\n' + release.comments[0];
  1007. }
  1008. }
  1009. if (element_writable(ref = document.getElementById('album_desc'))) {
  1010. ref.value = description;
  1011. preview(0);
  1012. }
  1013. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  1014. let editioninfo;
  1015. if (editionTitle) {
  1016. editioninfo = '[size=5][b]' + editionTitle;
  1017. if (release.release_date && (i = extract_year(release.release_date)) > 0) editioninfo += ' (' + i + ')';
  1018. editioninfo = editioninfo.concat('[/b][/size]\n\n');
  1019. } else { editioninfo = '' }
  1020. if (ref.textLength > 0) {
  1021. ref.value = ref.value.concat('\n\n', editioninfo, description);
  1022. } else {
  1023. ref.value = editioninfo + description;
  1024. }
  1025. preview(0);
  1026. }
  1027. var lineage = '', comment = '', drinfo, srcinfo;
  1028. if (element_writable(ref = document.getElementById('release_samplerate'))) {
  1029. ref.value = Object.keys(release.srs).length == 1 ? Math.floor(Object.keys(release.srs)[0] / 1000) :
  1030. Object.keys(release.srs).length > 1 ? '999' : null;
  1031. }
  1032. if (Object.keys(release.srs).length > 0) {
  1033. let kHz = Object.keys(release.srs).sort((a, b) => release.srs[b] - release.srs[a])
  1034. .map(f => f / 1000).join('/').concat('kHz');
  1035. if (release.bds.some(bd => bd > 16)) {
  1036. drinfo = '[hide=DR' + (release.drs.length == 1 ? release.drs[0] : '') + '][pre][/pre]';
  1037. if (media == 'Vinyl') {
  1038. let hassr = ref == null || Object.keys(release.srs).length > 1;
  1039. lineage = hassr ? kHz + ' ' : '';
  1040. if (ripinfo) {
  1041. ripinfo[0] = ripinfo[0].replace(vinylTest, '$1[color=blue]$2[/color]');
  1042. if (hassr) { ripinfo[0] = ripinfo[0].replace(/^Vinyl\b/, 'vinyl') }
  1043. lineage += ripinfo[0] + '\n\n[u]Lineage:[/u]' + ripinfo.slice(1).map(k => '\n' + k).join('');
  1044. } else {
  1045. lineage += (hassr ? 'Vinyl' : ' vinyl') + ' rip by [color=blue][/color]\n\n[u]Lineage:[/u]';
  1046. }
  1047. drinfo += '\n\n[img][/img]\n[img][/img]\n[img][/img][/hide]';
  1048. } else if (['Blu-Ray', 'DVD', 'SACD'].includes(media)) {
  1049. lineage = ref ? '' : kHz;
  1050. if (release.channels) add_channel_info();
  1051. if (media == 'SACD' || isFromDVD) {
  1052. lineage += ' from DSD64 using foobar2000\'s SACD decoder (direct-fp64)';
  1053. lineage += '\nOutput gain +0dB';
  1054. }
  1055. drinfo += '[/hide]';
  1056. //add_rg_info();
  1057. } else { // WEB Hi-Res
  1058. if (ref == null || Object.keys(release.srs).length > 1) lineage = kHz;
  1059. if (release.channels && release.channels != 2) add_channel_info();
  1060. add_dr_info();
  1061. //if (lineage.length > 0) add_rg_info();
  1062. if (release.bds.length > 1) release.bds.filter(bd => bd != 24).forEach(function(bd) {
  1063. let hybrid_tracks = tracks.filter(k => k.bd == bd).map(k => k.tracknumber);
  1064. if (hybrid_tracks.length < 1) return;
  1065. if (lineage) lineage += '\n';
  1066. lineage += 'Note: track';
  1067. if (hybrid_tracks.length > 1) lineage += 's';
  1068. lineage += ' #' + hybrid_tracks.sort().join(', ') +
  1069. (hybrid_tracks.length > 1 ? ' are' : ' is') + ' ' + bd + 'bit lossless';
  1070. });
  1071. if (Object.keys(release.srs).length == 1 && Object.keys(release.srs)[0] == 88200) {
  1072. drinfo += '[/hide]';
  1073. } else {
  1074. drinfo = null;
  1075. }
  1076. }
  1077. } else { // 16bit or lossy
  1078. if (Object.keys(release.srs).some(f => f != 44100)) lineage = kHz;
  1079. if (release.channels && release.channels != 2) add_channel_info();
  1080. //add_dr_info();
  1081. //if (lineage.length > 0) add_rg_info();
  1082. if (['AAC', 'Opus', 'Vorbis'].includes(release.codec) && release.vendor) {
  1083. let _encoder_settings = release.vendor;
  1084. if (release.codec == 'AAC' && /^qaac\s+[\d\.]+/i.test(release.vendor)) {
  1085. let enc = [];
  1086. if (matches = release.vendor.match(/\bqaac\s+([\d\.]+)\b/i)) enc[0] = matches[1];
  1087. if (matches = release.vendor.match(/\bCoreAudioToolbox\s+([\d\.]+)\b/i)) enc[1] = matches[1];
  1088. if (matches = release.vendor.match(/\b(AAC-\S+)\s+Encoder\b/i)) enc[2] = matches[1];
  1089. if (matches = release.vendor.match(/\b([TC]VBR|ABR|CBR)\s+(\S+)\b/)) { enc[3] = matches[1]; enc[4] = matches[2]; }
  1090. if (matches = release.vendor.match(/\bQuality\s+(\d+)\b/i)) enc[5] = matches[1];
  1091. _encoder_settings = 'Converted by Apple\'s ' + enc[2] + ' encoder (' + enc[3] + '-' + enc[4] + ')';
  1092. }
  1093. if (lineage) lineage += '\n\n';
  1094. lineage += _encoder_settings;
  1095. }
  1096. }
  1097. }
  1098. function add_dr_info() {
  1099. if (release.drs.length != 1 || document.getElementById('release_dynamicrange') != null) return false;
  1100. if (lineage.length > 0) lineage += ' | ';
  1101. if (release.drs[0] < 4) lineage += '[color=red]';
  1102. lineage += 'DR' + release.drs[0];
  1103. if (release.drs[0] < 4) lineage += '[/color]';
  1104. return true;
  1105. }
  1106. function add_rg_info() {
  1107. if (release.rgs.length != 1) return false;
  1108. if (lineage.length > 0) lineage += ' | ';
  1109. lineage += 'RG'; //lineage += 'RG ' + rgs[0];
  1110. return true;
  1111. }
  1112. function add_channel_info() {
  1113. if (!release.channels) return false;
  1114. let chi = getChanString(release.channels);
  1115. if (lineage.length > 0 && chi.length > 0) lineage += ', ';
  1116. lineage += chi;
  1117. return chi.length > 0;
  1118. }
  1119. if (url) srcinfo = '[url]' + url + '[/url]';
  1120. if ((ref = document.getElementById('release_lineage')) != null) {
  1121. if (element_writable(ref)) {
  1122. if (drinfo) comment = drinfo;
  1123. if (lineage && srcinfo) lineage += '\n\n';
  1124. if (srcinfo) lineage += srcinfo;
  1125. ref.value = lineage;
  1126. preview(1);
  1127. }
  1128. } else {
  1129. comment = lineage;
  1130. if (comment && drinfo) comment += '\n\n';
  1131. if (drinfo) comment += drinfo;
  1132. if (comment && srcinfo) comment += '\n\n';
  1133. if (srcinfo) comment += srcinfo;
  1134. }
  1135. if (element_writable(ref = document.getElementById('release_desc'))) {
  1136. ref.value = comment;
  1137. if (comment.length > 0) preview(isNWCD() ? 2 : 1);
  1138. }
  1139. if (release.encoding == 'lossless' && release.codec == 'FLAC'
  1140. && release.bds.includes(24) && release.dirpaths.length == 1) {
  1141. var uri = new URL(release.dirpaths[0] + '\\foo_dr.txt');
  1142. GM_xmlhttpRequest({
  1143. method: 'GET',
  1144. url: uri.href,
  1145. responseType: 'blob',
  1146. onload: function(response) {
  1147. if (response.readyState != 4 || !response.responseText) return;
  1148. var rlsDesc = document.getElementById('release_lineage') || document.getElementById('release_desc');
  1149. if (rlsDesc == null) return;
  1150. var value = rlsDesc.value;
  1151. matches = value.match(/(^\[hide=DR\d*\]\[pre\])\[\/pre\]/im);
  1152. if (matches == null) return;
  1153. var index = matches.index + matches[1].length;
  1154. rlsDesc.value = value.slice(0, index).concat(response.responseText, value.slice(index));
  1155. }
  1156. });
  1157. }
  1158. } else { // isRequest
  1159. description = []
  1160. if (release.release_date) {
  1161. i = new Date(release.release_date);
  1162. description.push('Releasing ' + (isNaN(i) ? release.release_date : i.toString().replace(/\s+\d+:.*/, '')));
  1163. }
  1164. if (url) description.push('[url]' + url + '[/url]');
  1165. if (release.catalogs.length == 1 && /^\d{10,}$/.test(release.catalogs[0])) {
  1166. description.push('[url=https://www.google.com/search?q=' + RegExp.$_ + ']Find more stores...[/url]');
  1167. }
  1168. if (release.comments.length == 1) description.push(release.comments[0]);
  1169. description = description.join('\n\n');
  1170. if (description.length > 0 && element_writable(ref = document.getElementById('description'))) ref.value = description;
  1171. }
  1172. if (element_writable(document.getElementById('image') || document.querySelector('input[name="image"]'))) {
  1173. if (/^https?:\/\/(\w+\.)?discogs\.com\/release\/[\w\-]+\/?$/i.test(url)) url += '/images';
  1174. GM_xmlhttpRequest({ method: 'GET', url: url, onload: fetch_image_from_store });
  1175. }
  1176. // } else if (element_writable(document.getElementById('image') || document.querySelector('input[name="image"]'))
  1177. // && ((ref = document.getElementById('album_desc')) != null || (ref = document.getElementById('body')) != null)
  1178. // && ref.textLength > 0 && (matches = ref.value.matchAll(/\b(https?\/\/[\w\-\&\_\?\=]+)/i)) != null) {
  1179.  
  1180. if (element_writable(ref = document.getElementById('release_dynamicrange'))) {
  1181. ref.value = release.drs.length == 1 ? release.drs[0] : '';
  1182. }
  1183. if (isRequest && prefs.request_default_bounty > 0) {
  1184. let amount = prefs.request_default_bounty < 1024 ? prefs.request_default_bounty : prefs.request_default_bounty / 1024;
  1185. if ((ref = document.getElementById('amount_box')) != null && !ref.disabled) ref.value = amount;
  1186. if ((ref = document.getElementById('unit')) != null && !ref.disabled) {
  1187. ref.value = prefs.request_default_bounty < 1024 ? 'mb' : 'gb';
  1188. }
  1189. exec(function() { Calculate() });
  1190. }
  1191. if (prefs.clean_on_apply) clipBoard.value = '';
  1192. prefs.save();
  1193. return true;
  1194.  
  1195. function gen_full_tracklist() { // ========================= TACKLIST =========================
  1196. description += isRED() ? '[pad=5|0|0|0]' : '';
  1197. description += '[size=4][color=' + prefs.tracklist_head_color + '][b]Tracklisting[/b][/color][/size]';
  1198. if (isRED()) '[/pad]';
  1199. description += '\n'; //'[hr]';
  1200. let classical_units = new Set();
  1201. if (isClassical && !tracks.some(k => k.discsubtitle)) {
  1202. for (track of tracks) {
  1203. if (matches = track.title.match(/^(.+?)\s*:\s+(.*)$/)) {
  1204. classical_units.add(track.classical_unit_title = matches[1]);
  1205. track.classical_title = matches[2];
  1206. } else {
  1207. track.classical_unit_title = null;
  1208. }
  1209. }
  1210. for (let unit of classical_units.keys()) {
  1211. let group_performer = array_homogenous(tracks.filter(k => k.classical_unit_title === unit).map(k => k.track_artist));
  1212. let group_composer = array_homogenous(tracks.filter(k => k.classical_unit_title === unit).map(k => k.composer));
  1213. for (track of tracks) {
  1214. if (track.classical_unit_title !== unit) continue;
  1215. if (group_composer) track.classical_unit_composer = track.composer;
  1216. if (group_performer) track.classical_unit_performer = track.track_artist;
  1217. }
  1218. }
  1219. }
  1220. let block = 1, lastdisc, lastsubtitle, lastside, vinyl_trackwidth;
  1221. let lastwork = classical_units.size > 0 ? null : undefined;
  1222. let volumes = new Map(tracks.map(k => [k.discnumber, undefined]));
  1223. volumes.forEach(function(val, key) {
  1224. volumes.set(key, array_homogenous(tracks.filter(k => k.discnumber == key).map(k => k.discsubtitle)));
  1225. });
  1226. if (media == 'Vinyl') {
  1227. let max_side_track = undefined;
  1228. rx = /^([A-Z])(\d+)?(\.(\d+))?/i;
  1229. for (iter of tracks) {
  1230. if (matches = iter.tracknumber.match(rx)) {
  1231. max_side_track = Math.max(parseInt(matches[2]) || 1, max_side_track || 0);
  1232. }
  1233. }
  1234. if (typeof max_side_track == 'number') {
  1235. max_side_track = max_side_track.toString().length;
  1236. vinyl_trackwidth = 1 + max_side_track;
  1237. for (iter of tracks) {
  1238. if (matches = iter.tracknumber.match(rx)) {
  1239. iter.tracknumber = matches[1].toUpperCase();
  1240. if (matches[2]) iter.tracknumber += matches[2].padStart(max_side_track, '0');
  1241. }
  1242. }
  1243. }
  1244. }
  1245. function prologue(prefix, postfix) {
  1246. function block1() {
  1247. if (block == 3) description += postfix;
  1248. description += '\n';
  1249. block = 1;
  1250. }
  1251. function block2() {
  1252. if (block == 3) description += postfix;
  1253. description += '\n';
  1254. block = 2;
  1255. }
  1256. function block3() {
  1257. if (block == 2) { description += '[hr]' } else { description += '\n' }
  1258. if (block != 3) description += prefix;
  1259. block = 3;
  1260. }
  1261. if (totalDiscs > 1 && iter.discnumber != lastdisc) {
  1262. block1();
  1263. description += '[size=3][color=' + prefs.tracklist_disctitle_color + '][b]';
  1264. if (iter.identifiers.VOL_MEDIA && tracks.filter(it => it.discnumber == iter.discnumber)
  1265. .every(it => it.identifiers.VOL_MEDIA == iter.identifiers.VOL_MEDIA)) {
  1266. description += iter.identifiers.VOL_MEDIA.toUpperCase() + ' ';
  1267. }
  1268. description += 'Disc ' + iter.discnumber;
  1269. if (iter.discsubtitle && (!volumes.has(iter.discnumber) || volumes.get(iter.discnumber))) {
  1270. description += ' - ' + iter.discsubtitle;
  1271. lastsubtitle = iter.discsubtitle;
  1272. }
  1273. description += '[/b][/color][/size]';
  1274. lastdisc = iter.discnumber;
  1275. }
  1276. if (iter.discsubtitle != lastsubtitle) {
  1277. block1();
  1278. if (iter.discsubtitle) {
  1279. description += '[size=2][color=' + prefs.tracklist_disctitle_color + '][b]' +
  1280. iter.discsubtitle + '[/b][/color][/size]';
  1281. }
  1282. lastsubtitle = iter.discsubtitle;
  1283. }
  1284. if (iter.classical_unit_title !== lastwork) {
  1285. if (iter.classical_unit_composer || iter.classical_unit_title || iter.classical_unit_performer) {
  1286. block2();
  1287. description += '[size=2][color=' + prefs.tracklist_classicalblock_color + '][b]';
  1288. if (iter.classical_unit_composer) description += iter.classical_unit_composer + ': ';
  1289. if (iter.classical_unit_title) description += iter.classical_unit_title;
  1290. description += '[/b]';
  1291. if (iter.classical_unit_performer) description += ' (' + iter.classical_unit_performer + ')';
  1292. description += '[/color][/size]';
  1293. } else {
  1294. if (block != 2) block1();
  1295. }
  1296. lastwork = iter.classical_unit_title;
  1297. }
  1298. block3();
  1299. if (media == 'Vinyl') {
  1300. let c = iter.tracknumber[0].toUpperCase();
  1301. if (lastside != undefined && c != lastside) description += '\n';
  1302. lastside = c;
  1303. }
  1304. }
  1305. var varying_composer = !array_homogenous(tracks.map(k => k.composer));
  1306. for (iter of tracks.sort(function(a, b) {
  1307. var d = a.discnumber - b.discnumber;
  1308. var t = a.tracknumber - b.tracknumber;
  1309. return isNaN(d) || d == 0 ? isNaN(t) ? a.tracknumber.localeCompare(b.tracknumber) : t : d;
  1310. })) {
  1311. let title = '';
  1312. let ttwidth = vinyl_trackwidth || (totalDiscs > 1 && iter.discnumber > 0 ?
  1313. tracks.filter(it => it.discnumber == iter.discnumber) : tracks).reduce(function (accumulator, it) {
  1314. return Math.max(accumulator, iter.tracknumber.toString().length);
  1315. }, 2);
  1316. if (prefs.tracklist_style == 1) {
  1317. // STYLE 1 ----------------------------------------
  1318. prologue('[size=2]', '[/size]\n');
  1319. track = '[b][color=' + prefs.tracklist_tracknumber_color + ']';
  1320. track += isNaN(parseInt(iter.tracknumber)) ? iter.tracknumber : iter.tracknumber.padStart(ttwidth, '0');
  1321. track += '[/color][/b]' + prefs.title_separator;
  1322. if (iter.track_artist && !iter.classical_unit_performer) {
  1323. title = '[color=' + prefs.tracklist_artist_color + ']' + iter.track_artist + '[/color] - ';
  1324. }
  1325. title += iter.classical_title || iter.title;
  1326. if (iter.composer && composerEmphasis && varying_composer && !iter.classical_unit_composer) {
  1327. title = title.concat(' [color=', prefs.tracklist_composer_color, '](', iter.composer, ')[/color]');
  1328. }
  1329. description += track + title;
  1330. if (iter.duration) description += ' [i][color=' + prefs.tracklist_duration_color +'][' +
  1331. makeTimeString(iter.duration) + '][/color][/i]';
  1332. } else if (prefs.tracklist_style == 2) {
  1333. // STYLE 2 ----------------------------------------
  1334. prologue('[size=2][pre]', '[/pre][/size]');
  1335. track = isNaN(parseInt(iter.tracknumber)) ? iter.tracknumber : iter.tracknumber.padStart(ttwidth, '0');
  1336. track += prefs.title_separator;
  1337. if (iter.track_artist && !iter.classical_unit_performer) title = iter.track_artist + ' - ';
  1338. title += iter.classical_title || iter.title;
  1339. if (iter.composer && composerEmphasis && varying_composer && !iter.classical_unit_composer) {
  1340. title = title.concat(' (', iter.composer, ')');
  1341. }
  1342. dur = iter.duration ? '[' + makeTimeString(iter.duration) + ']' : null;
  1343. let l = 0, j, left, padding, spc;
  1344. let width = prefs.max_tracklist_width - track.length;
  1345. if (dur) width -= dur.length + 1;
  1346. while (title.length > 0) {
  1347. j = width;
  1348. if (title.length > width) {
  1349. while (j > 0 && title[j] != ' ') { --j }
  1350. if (j <= 0) j = width;
  1351. }
  1352. left = title.slice(0, j).trim();
  1353. if (++l <= 1) {
  1354. description += track + left;
  1355. if (dur) {
  1356. spc = width - left.length;
  1357. padding = (spc < 2 ? ' '.repeat(spc) : ' ' + prefs.pad_leader.repeat(spc - 1)) + ' ';
  1358. description += padding + dur;
  1359. }
  1360. width = prefs.max_tracklist_width - track.length - 2;
  1361. } else {
  1362. description += '\n' + ' '.repeat(track.length) + left;
  1363. }
  1364. title = title.slice(j).trim();
  1365. }
  1366. }
  1367. }
  1368. if (prefs.tracklist_style == 1 && totalTime > 0) {
  1369. description += '\n\n' + divs[0].repeat(10) + '\n[color=' + prefs.tracklist_duration_color +
  1370. ']Total time: [i]' + makeTimeString(totalTime) + '[/i][/color][/size]';
  1371. } else if (prefs.tracklist_style == 2) {
  1372. if (totalTime > 0) {
  1373. dur = '[' + makeTimeString(totalTime) + ']';
  1374. description = description.concat('\n\n', divs[0].repeat(32).padStart(prefs.max_tracklist_width));
  1375. description = description.concat('\n', 'Total time:'.padEnd(prefs.max_tracklist_width - dur.length), dur);
  1376. }
  1377. description = description.concat('[/pre][/size]');
  1378. }
  1379. }
  1380.  
  1381. function getChanString(n) {
  1382. if (!n) return null;
  1383. const chanmap = [
  1384. 'mono',
  1385. 'stereo',
  1386. '2.1',
  1387. '4.0 surround sound',
  1388. '5.0 surround sound',
  1389. '5.1 surround sound',
  1390. '7.0 surround sound',
  1391. '7.1 surround sound',
  1392. ];
  1393. return n >= 1 && n <= 8 ? chanmap[n - 1] : n + 'chn surround sound';
  1394. }
  1395.  
  1396. function init_from_url_music(url) {
  1397. if (!/^https?:\/\//i.test(url)) return false;
  1398. var artist, album, albumYear, releaseDate, channels, label, composer, bd, sr = 44.1,
  1399. description, compiler, producer, totalTracks, discSubtitle, discNumber, trackNumber,
  1400. title, trackArtist, catalogue, encoding, format, bitrate, duration, country;
  1401. if (url.toLowerCase().includes('qobuz.com')) {
  1402. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1403. if (response.readyState != 4 || response.status != 200) return;
  1404. dom = domparser.parseFromString(response.responseText, "text/html");
  1405. if (dom == null) return;
  1406.  
  1407. if ((ref = dom.querySelector('h2.album-meta__artist')) != null) artist = ref.textContent.trim();
  1408. if ((ref = dom.querySelector('h1.album-meta__title')) != null) album = ref.textContent.trim();
  1409. ref = dom.querySelector('div.album-meta > ul > li:first-of-type');
  1410. if (ref != null) releaseDate = normalizeDate(ref.textContent);
  1411. ref = dom.querySelector('p.album-about__copyright');
  1412. albumYear = ref != null && extract_year(ref.textContent) || extract_year(releaseDate);
  1413. let genres = [];
  1414. dom.querySelectorAll('section#about > ul > li').forEach(function(k) {
  1415. if (/\b(\d+)\s*(?:dis[ck]|disco|disque)(?:s?\b|\(s\))/i.test(k.textContent)) {
  1416. totalDiscs = parseInt(RegExp.$1);
  1417. }
  1418. if (/\b(\d+)\s*(?:track|pist[ae]|tracce)(?:s?\b|\(s\))/i.test(k.textContent)) {
  1419. totalTracks = parseInt(RegExp.$1);
  1420. }
  1421. if (k.textContent.includes('Label')) label = k.children[0].textContent.trim()
  1422. else if (k.textContent.includes('Composer')) {
  1423. composer = k.children[0].textContent.trim();
  1424. if (/\bVarious\b/i.test(composer)) composer = null;
  1425. } else if (k.textContent.includes('Genre') && k.children.length > 0) {
  1426. k.querySelectorAll('a').forEach(k => { genres.push(k.textContent.trim()) });
  1427. if (genres.length > 0 && ['Pop/Rock'].includes(genres[0])) genres.shift();
  1428. if (genres.length > 0 && ['Metal', 'Heavy Metal'].some(genre => genres.includes(genre))) {
  1429. while (genres.length > 1) genres.shift();
  1430. }
  1431. }
  1432. });
  1433. bd = 16; channels = 2;
  1434. dom.querySelectorAll('span.album-quality__info').forEach(function(k) {
  1435. if (/\b([\d\.\,]+)\s*kHz\b/i.test(k.textContent) != null) sr = parseFloat(RegExp.$1.replace(/,/g, '.'));
  1436. if (/\b(\d+)[\-\s]*Bits?\b/i.test(k.textContent) != null) bd = parseInt(RegExp.$1);
  1437. if (/\b(?:Stereo)\b/i.test(k.textContent)) channels = 2;
  1438. if (/\b(\d)\.(\d)\b/.test(k.textContent)) channels = parseInt(RegExp.$1) + parseInt(RegExp.$2);
  1439. });
  1440. get_desc_from_node('section#description > p', response.finalUrl, true);
  1441. if ((ref = dom.querySelector('a[title="Qobuzissime"]')) != null) {
  1442. description += '\x1C[align=center][url=https://www.qobuz.com' + ref.pathname +
  1443. '][img]https://ptpimg.me/4z35uj.png[/img][/url][/align]';
  1444. }
  1445. ref = dom.querySelectorAll('div.player__tracks > div.track > div.track__items');
  1446. let works = dom.querySelectorAll('div.player__tracks > p.player__work');
  1447. if (!totalTracks) totalTracks = ref.length;
  1448. ref.forEach(function(k) {
  1449. discSubtitle = null;
  1450. works.forEach(function(j) {
  1451. if (j.compareDocumentPosition(k) == Node.DOCUMENT_POSITION_FOLLOWING) discSubtitle = j
  1452. });
  1453. discSubtitle = discSubtitle != null ? discSubtitle.textContent.trim() : undefined;
  1454. if (/^\s*(?:dis[ck]|disco|disque)\s+(\d+)\s*$/i.test(discSubtitle)) {
  1455. discNumber = parseInt(RegExp.$1);
  1456. discSubtitle = undefined;
  1457. } else discNumber = undefined;
  1458. if (discNumber > totalDiscs) totalDiscs = discNumber;
  1459. trackNumber = parseInt(k.querySelector('span[itemprop="position"]').textContent.trim());
  1460. title = k.querySelector('span.track__item--name').textContent.trim().replace(/\s+/g, ' ');
  1461. duration = timeStringToTime(k.querySelector('span.track__item--duration').textContent);
  1462. trackArtist = undefined;
  1463. track = [
  1464. artist,
  1465. album,
  1466. albumYear,
  1467. releaseDate,
  1468. label,
  1469. undefined, // catalogue
  1470. undefined, // country
  1471. 'lossless',
  1472. 'FLAC',
  1473. undefined,
  1474. undefined,
  1475. bd,
  1476. sr * 1000,
  1477. channels,
  1478. 'WEB',
  1479. genres.join(', '),
  1480. discNumber,
  1481. totalDiscs,
  1482. discSubtitle,
  1483. trackNumber,
  1484. totalTracks,
  1485. title,
  1486. trackArtist,
  1487. undefined,
  1488. composer,
  1489. undefined,
  1490. undefined,
  1491. compiler,
  1492. producer,
  1493. duration,
  1494. undefined,
  1495. undefined,
  1496. undefined,
  1497. undefined,
  1498. response.finalUrl,
  1499. undefined,
  1500. description,
  1501. undefined,
  1502. ];
  1503. tracks.push(track.join('\x1E'));
  1504. });
  1505. clipBoard.value = tracks.join('\n');
  1506. fill_from_text_music();
  1507. } });
  1508. return true;
  1509. } else if (url.toLowerCase().includes('highresaudio.com')) {
  1510. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1511. if (response.readyState != 4 || response.status != 200) return;
  1512. dom = domparser.parseFromString(response.responseText, "text/html");
  1513. if (dom == null) return;
  1514.  
  1515. ref = dom.querySelector('h1 > span.artist');
  1516. if (ref != null) artist = ref.textContent.trim();
  1517. ref = dom.getElementById('h1-album-title');
  1518. if (ref != null) album = ref.firstChild.textContent.trim();
  1519. let genres = [], format;
  1520. dom.querySelectorAll('div.album-col-info-data > div > p').forEach(function(k) {
  1521. if (/\b(?:Genre|Subgenre)\b/i.test(k.firstChild.textContent)) genres.push(k.lastChild.textContent.trim());
  1522. if (/\b(?:Label)\b/i.test(k.firstChild.textContent)) label = k.lastChild.textContent.trim();
  1523. if (/\b(?:Album[\s\-]Release)\b/i.test(k.firstChild.textContent)) {
  1524. albumYear = normalizeDate(k.lastChild.textContent);
  1525. }
  1526. if (/\b(?:HRA[\s\-]Release)\b/i.test(k.firstChild.textContent)) {
  1527. releaseDate = normalizeDate(k.lastChild.textContent);
  1528. }
  1529. });
  1530. i = 0;
  1531. dom.querySelectorAll('tbody > tr > td.col-format').forEach(function(k) {
  1532. if (/^(FLAC)\s*([\d\.\,]+)\b/.exec(k.textContent) != null) {
  1533. format = RegExp.$1;
  1534. sr = parseFloat(RegExp.$2.replace(/,/g, '.'));
  1535. ++i;
  1536. }
  1537. });
  1538. if (i > 1) sr = undefined; // ambiguous
  1539. get_desc_from_node('div#albumtab-info > p', response.finalUrl);
  1540. ref = dom.querySelectorAll('ul.playlist > li.pltrack');
  1541. totalTracks = ref.length;
  1542. ref.forEach(function(k) {
  1543. discSubtitle = k;
  1544. while ((discSubtitle = discSubtitle.previousElementSibling) != null) {
  1545. if (discSubtitle.nodeName == 'LI' && discSubtitle.className == 'plinfo') {
  1546. discSubtitle = discSubtitle.textContent.replace(/\s*:$/, '').trim();
  1547. if (/\b(?:DIS[CK]|Volume|CD)\s*(\d+)\b/i.exec(discSubtitle)) discNumber = parseInt(RegExp.$1);
  1548. break;
  1549. }
  1550. }
  1551. //if (discnumber > totalDiscs) totalDiscs = discnumber;
  1552. trackNumber = parseInt(k.querySelector('span.track').textContent.trim());
  1553. title = k.querySelector('span.title').textContent.trim().replace(/\s+/g, ' ');
  1554. duration = timeStringToTime(k.querySelector('span.time').textContent);
  1555. trackArtist = undefined;
  1556. track = [
  1557. artist,
  1558. album,
  1559. albumYear,
  1560. releaseDate,
  1561. label,
  1562. undefined, // catalogue
  1563. undefined, // country
  1564. 'lossless',
  1565. 'FLAC', //format,
  1566. undefined,
  1567. undefined,
  1568. 24,
  1569. sr * 1000,
  1570. 2,
  1571. 'WEB',
  1572. genres.join(', '),
  1573. discNumber,
  1574. totalDiscs,
  1575. discSubtitle,
  1576. trackNumber,
  1577. totalTracks,
  1578. title,
  1579. trackArtist,
  1580. undefined,
  1581. composer,
  1582. undefined,
  1583. undefined,
  1584. compiler,
  1585. producer,
  1586. duration,
  1587. undefined,
  1588. undefined,
  1589. undefined,
  1590. undefined,
  1591. response.finalUrl,
  1592. undefined,
  1593. description,
  1594. undefined,
  1595. ];
  1596. tracks.push(track.join('\x1E'));
  1597. });
  1598. clipBoard.value = tracks.join('\n');
  1599. fill_from_text_music();
  1600. } });
  1601. return true;
  1602. } else if (url.toLowerCase().includes('bandcamp.com')) {
  1603. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1604. if (response.readyState != 4 || response.status != 200) return;
  1605. dom = domparser.parseFromString(response.responseText, "text/html");
  1606. if (dom == null) return;
  1607.  
  1608. ref = dom.querySelector('span[itemprop="byArtist"] > a');
  1609. if (ref != null) artist = ref.textContent.trim();
  1610. ref = dom.querySelector('h2[itemprop="name"]');
  1611. if (ref != null) album = ref.textContent.trim();
  1612. ref = dom.querySelector('div.tralbum-credits');
  1613. if (ref != null && /\breleased\s+(.*?\b\d{4})\b/i.test(ref.textContent)) {
  1614. releaseDate = RegExp.$1;
  1615. albumYear = releaseDate;
  1616. }
  1617. ref = dom.querySelector('p#band-name-location > span.title');
  1618. if (ref != null) label = ref.textContent.trim();
  1619. let tags = new TagManager;
  1620. dom.querySelectorAll('div.tralbum-tags > a.tag').forEach(k => { tags.add(k.textContent.trim()) });
  1621. description = [];
  1622. dom.querySelectorAll('div.tralbumData').forEach(function(k) {
  1623. if (!k.classList.contains('tralbum-tags')) description.push(html2php(k, response.finalUrl))
  1624. });
  1625. description = description.join('\n\n').replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  1626. ref = dom.querySelectorAll('table.track_list > tbody > tr[itemprop="tracks"]');
  1627. totalTracks = ref.length;
  1628. ref.forEach(function(k) {
  1629. trackNumber = parseInt(k.querySelector('div.track_number').textContent);
  1630. title = k.querySelector('span.track-title').textContent.trim().replace(/\s+/g, ' ');
  1631. duration = timeStringToTime(k.querySelector('span.time').textContent);
  1632. trackArtist = undefined;
  1633. track = [
  1634. artist,
  1635. album,
  1636. albumYear,
  1637. releaseDate,
  1638. label,
  1639. undefined, // catalogue
  1640. undefined, // country
  1641. undefined, //'lossless',
  1642. undefined, //'FLAC',
  1643. undefined,
  1644. undefined,
  1645. undefined,
  1646. undefined,
  1647. 2,
  1648. 'WEB',
  1649. tags.toString(),
  1650. discNumber,
  1651. totalDiscs,
  1652. undefined,
  1653. trackNumber,
  1654. totalTracks,
  1655. title,
  1656. trackArtist,
  1657. undefined,
  1658. composer,
  1659. undefined,
  1660. undefined,
  1661. compiler,
  1662. producer,
  1663. duration,
  1664. undefined,
  1665. undefined,
  1666. undefined,
  1667. undefined,
  1668. response.finalUrl,
  1669. undefined,
  1670. description,
  1671. undefined,
  1672. ];
  1673. tracks.push(track.join('\x1E'));
  1674. });
  1675. clipBoard.value = tracks.join('\n');
  1676. fill_from_text_music();
  1677. } });
  1678. return true;
  1679. } else if (url.toLowerCase().includes('prestomusic.com')) {
  1680. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1681. if (response.readyState != 4 || response.status != 200) return;
  1682. dom = domparser.parseFromString(response.responseText, "text/html");
  1683. if (dom == null) return;
  1684.  
  1685. artist = getArtists(dom.querySelector('div.c-product-block__contributors > p'));
  1686. ref = dom.querySelector('h1.c-product-block__title');
  1687. if (ref != null) album = ref.lastChild.textContent.trim();
  1688. dom.querySelectorAll('div.c-product-block__metadata > ul > li').forEach(function(k) {
  1689. if (k.firstChild.textContent.includes('Release Date')) {
  1690. releaseDate = extract_year(k.lastChild.textContent);
  1691. } else if (k.firstChild.textContent.includes('Label')) {
  1692. label = k.lastChild.textContent.trim();
  1693. } else if (k.firstChild.textContent.includes('Catalogue No')) {
  1694. catalogue = k.lastChild.textContent.trim();
  1695. }
  1696. });
  1697. albumYear = releaseDate;
  1698. let genre;
  1699. if (/\/jazz\//i.test(response.finalUrl)) genre = 'Jazz';
  1700. if (/\/classical\//i.test(response.finalUrl)) genre = 'Classical';
  1701. get_desc_from_node('div#about > div > p', response.finalUrl, true);
  1702. ref = dom.querySelectorAll('div#related > div > ul > li');
  1703. composer = [];
  1704. ref.forEach(function(k) {
  1705. if (k.parentNode.previousElementSibling.textContent.includes('Composers')) {
  1706. composer.push(k.firstChild.textContent.trim().replace(/^(.*?)\s*,\s+(.*)$/, '$2 $1'));
  1707. }
  1708. });
  1709. composer = composer.join(', ') || undefined;
  1710. ref = dom.querySelectorAll('div.has--sample');
  1711. totalTracks = ref.length;
  1712. let tracknumber = 0;
  1713. ref.forEach(function(k) {
  1714. tracknumber = ++tracknumber;
  1715. title = k.querySelector('p.c-track__title').textContent.trim().replace(/\s+/g, ' ');
  1716. duration = timeStringToTime(k.querySelector('div.c-track__duration').textContent);
  1717. if (k.classList.contains('c-track')) {
  1718. trackArtist = getArtists(k.parentNode.parentNode.querySelector(':scope > div.c-track__details > ul > li'));
  1719. discSubtitle = k.parentNode.parentNode.querySelector(':scope > div > div > div > p.c-track__title');
  1720. discSubtitle = discSubtitle != null ? discSubtitle.textContent.trim() : undefined;
  1721. } else {
  1722. trackArtist = getArtists(k.querySelector(':scope > div.c-track__details > ul > li'));
  1723. discSubtitle = undefined;
  1724. }
  1725. if (trackArtist == artist) trackArtist = undefined;
  1726. track = [
  1727. artist,
  1728. album,
  1729. albumYear,
  1730. releaseDate,
  1731. label,
  1732. catalogue,
  1733. undefined, // country
  1734. undefined, //encoding,
  1735. undefined, //format,
  1736. undefined,
  1737. undefined, //bitrate,
  1738. undefined, //bd,
  1739. undefined, //sr * 1000,
  1740. 2,
  1741. 'WEB',
  1742. genre,
  1743. discNumber,
  1744. totalDiscs,
  1745. discSubtitle,
  1746. tracknumber,
  1747. totalTracks,
  1748. title,
  1749. trackArtist,
  1750. undefined,
  1751. composer,
  1752. undefined,
  1753. undefined,
  1754. compiler,
  1755. producer,
  1756. duration,
  1757. undefined,
  1758. undefined,
  1759. undefined,
  1760. undefined,
  1761. response.finalUrl,
  1762. undefined,
  1763. description,
  1764. undefined,
  1765. ];
  1766. tracks.push(track.join('\x1E'));
  1767. });
  1768. clipBoard.value = tracks.join('\n');
  1769. fill_from_text_music();
  1770.  
  1771. function getArtists(elem) {
  1772. if (elem == null) return undefined;
  1773. var artists = [];
  1774. elem.textContent.trim().split(multiArtistParser).forEach(function(it) {
  1775. artists.push(it.replace(/\s*\([^\(\)]*\)$/, ''));
  1776. });
  1777. return artists.join(', ');
  1778. }
  1779. } });
  1780. return true;
  1781. } else if (url.toLowerCase().includes('discogs.com/') && /\/releases?\/(\d+)\b/i.test(url)) {
  1782. GM_xmlhttpRequest({ method: 'GET', url: 'https://api.discogs.com/releases/' + RegExp.$1, onload: function(response) {
  1783. if (response.readyState != 4 || response.status != 200) return;
  1784. var json = JSON.parse(response.responseText);
  1785. if (json == null) return;
  1786.  
  1787. const removeArtistNdx = /\s*\(\d+\)$/;
  1788. function getArtists(root) {
  1789. function filterArtists(rx, anv = true) {
  1790. return root.extraartists instanceof Array && rx instanceof RegExp ?
  1791. root.extraartists
  1792. .filter(it => rx.test(it.role))
  1793. .map(it => (anv && it.anv || it.name || '').replace(removeArtistNdx, '')) : [];
  1794. }
  1795. var artists = [];
  1796. for (var ndx = 0; ndx < 7; ++ndx) artists[ndx] = [];
  1797. ndx = 0;
  1798. if (root.artists) root.artists.forEach(function(it) {
  1799. artists[ndx].push((it.anv || it.name).replace(removeArtistNdx, ''));
  1800. if (/^feat/i.test(it.join)) ndx = 1;
  1801. });
  1802. return [
  1803. artists[0],
  1804. artists[1].concat(filterArtists(/^(?:featuring)$/i)),
  1805. artists[2].concat(filterArtists(/\b(?:Remixed[\s\-]By|Remixer)\b/i)),
  1806. artists[3].concat(filterArtists(/\b(?:(?:Written|Composed)[\s\-]By|Composer)\b/i, false)),
  1807. artists[4].concat(filterArtists(/\b(?:Conducted[\s\-]By|Conductor)\b/i)),
  1808. artists[5].concat(filterArtists(/\b(?:Compiled[\s\-]By|Compiler)\b/i)),
  1809. artists[6].concat(filterArtists(/\b(?:Produced[\s\-]By|Producer)\b/i)),
  1810. // filter off from performers
  1811. filterArtists(/\b(?:(?:Mixed)[\s\-]By|Mixer)\b/i),
  1812. filterArtists(/\b(?:(?:Written|Composed)[\s\-]By|Composer)\b/i, true),
  1813. ];
  1814. }
  1815.  
  1816. var albumArtists = getArtists(json);
  1817. if (albumArtists[0].length > 0) {
  1818. artist = joinArtists(albumArtists[0]);
  1819. if (albumArtists[1].length > 0) artist += ' feat. ' + joinArtists(albumArtists[1]);
  1820. }
  1821. album = json.title;
  1822. var editions = [];
  1823. if (editions.length > 0) album += ' (' + editions.join(' / ') + ')';
  1824. releaseDate = json.released;
  1825. albumYear = json.year;
  1826. label = [];
  1827. catalogue = [];
  1828. json.labels.forEach(function(it) {
  1829. //if (it.entity_type_name != 'Label') return;
  1830. if (!/^Not On Label\b/i.test(it.name)) label.pushUniqueCaseless(it.name.replace(removeArtistNdx, ''));
  1831. catalogue.pushUniqueCaseless(it.catno);
  1832. });
  1833. description = '';
  1834. if (json.companies && json.companies.length > 0) {
  1835. description = '[b]Companies, etc.[/b]\n';
  1836. let type_names = new Set(json.companies.map(it => it.entity_type_name));
  1837. type_names.forEach(function(type_name) {
  1838. description += '\n' + type_name + ' – ' + json.companies
  1839. .filter(it => it.entity_type_name == type_name)
  1840. .map(function(it) {
  1841. var result = it.name.replace(removeArtistNdx, '');
  1842. if (it.catno) result += ' – ' + it.catno;
  1843. return result;
  1844. })
  1845. .join(', ');
  1846. });
  1847. }
  1848. if (json.extraartists && json.extraartists.length > 0) {
  1849. if (description) description += '\n\n';
  1850. description += '[b]Credits[/b]\n';
  1851. let roles = new Set(json.extraartists.map(it => it.role));
  1852. roles.forEach(function(role) {
  1853. description += '\n' + role + ' – ' + json.extraartists
  1854. .filter(it => it.role == role)
  1855. .map(function(it) {
  1856. var result = '[artist]' + (it.anv || it.name).replace(removeArtistNdx, '') + '[/artist]';
  1857. if (it.tracks) result += ' (tracks: ' + it.tracks + ')';
  1858. return result;
  1859. })
  1860. .join(', ');
  1861. });
  1862. }
  1863. if (json.notes) {
  1864. if (description) description += '\n\n';
  1865. description += '[b]Notes[/b]\n\n' + json.notes.trim();
  1866. }
  1867. if (json.identifiers && json.identifiers.length > 0) {
  1868. if (description) description += '\n\n';
  1869. description += '[b]Barcode and Other Identifiers[/b]\n';
  1870. json.identifiers.forEach(function(it) {
  1871. description += '\n' + it.type;
  1872. if (it.description) description += ' (' + it.description + ')';
  1873. description += ': ' + it.value;
  1874. });
  1875. }
  1876. country = json.country;
  1877. totalTracks = json.tracklist.length;
  1878. totalDiscs = json.format_quantity;
  1879. var identifiers = ['DISCOGS_ID=' + json.id];
  1880. [
  1881. ['Single', 'Single'],
  1882. ['EP', 'EP'],
  1883. ['Compilation', 'Compilation'],
  1884. ['Soundtrack', 'Soundtrack'],
  1885. ].forEach(function(k) {
  1886. if (json.formats.every(it => it.descriptions && it.descriptions.includesCaseless(k[0]))) {
  1887. identifiers.push('RELEASETYPE=' + k[1]);
  1888. }
  1889. });
  1890. json.identifiers.forEach(function(it) {
  1891. identifiers.push(it.type.replace(/\W+/g, '_').toUpperCase() + '=' + it.value.replace(/\s/g, '\x1B'));
  1892. });
  1893. json.formats.forEach(function(it) {
  1894. if (it.descriptions) it.descriptions.forEach(function(it) {
  1895. if (/^(?:.+?\s+Edition|Remaster(?:ed)|Reissue|.+?\s+Release|Enhanced|Promo)$/.test(it)) {
  1896. editions.push(it);
  1897. }
  1898. });
  1899. });
  1900. json.tracklist.forEach(function(it) {
  1901. if (it.type_.toLowerCase() == 'heading') {
  1902. discSubtitle = it.title;
  1903. } else if (it.type_.toLowerCase() == 'track') {
  1904. if (/^([a-zA-Z]+)?(\d+)-(\w+)$/.test(it.position)) {
  1905. if (RegExp.$1) identifiers.push('VOL_MEDIA=' + RegExp.$1.replace(/\s/g, '\x1B'));
  1906. discNumber = RegExp.$2;
  1907. trackNumber = RegExp.$3;
  1908. } else {
  1909. discNumber = undefined;
  1910. trackNumber = it.position;
  1911. }
  1912. let trackArtists = getArtists(it);
  1913. if (trackArtists[0].length > 0 && !trackArtists[0].equalTo(albumArtists[0])
  1914. || trackArtists[1].length > 0 && !trackArtists[1].equalTo(albumArtists[1])) {
  1915. trackArtist = joinArtists((trackArtists[0].length > 0 ? trackArtists : albumArtists)[0]);
  1916. if (trackArtists[1].length > 0) trackArtist += ' feat. ' + joinArtists(trackArtists[1]);
  1917. } else {
  1918. trackArtist = null;
  1919. }
  1920. title = it.title;
  1921. duration = timeStringToTime(it.duration);
  1922. let performer = it.extraartists instanceof Array && it.extraartists
  1923. .map(it => (it.anv || it.name).replace(removeArtistNdx, ''))
  1924. .filter(function(artist) {
  1925. return !albumArtists.slice(2).some(it => it instanceof Array && it.includes(artist))
  1926. && !trackArtists.slice(2).some(it => it instanceof Array && it.includes(artist))
  1927. });
  1928. track = [
  1929. artist,
  1930. album,
  1931. albumYear,
  1932. releaseDate,
  1933. label.join(' / '),
  1934. catalogue.join(' / '),
  1935. country,
  1936. undefined, // encoding
  1937. undefined, // format
  1938. undefined,
  1939. undefined,
  1940. undefined, // bit depth
  1941. undefined, // samplerate
  1942. undefined, // channels
  1943. json.formats.map(it => it.name).join(', '),
  1944. (json.genres ? json.genres.join(', ') : '') + (json.styles ? '|' + json.styles.join(', ') : ''),
  1945. discNumber,
  1946. totalDiscs,
  1947. discSubtitle,
  1948. trackNumber,
  1949. totalTracks,
  1950. title,
  1951. trackArtist,
  1952. performer instanceof Array && performer.join('; ') || undefined,
  1953. stringyfyRole(3), // composers
  1954. stringyfyRole(4), // conductors
  1955. stringyfyRole(2), // remixers
  1956. stringyfyRole(5), // DJs/compilers
  1957. stringyfyRole(6), // producers
  1958. duration,
  1959. undefined,
  1960. undefined,
  1961. undefined,
  1962. undefined,
  1963. undefined, // URL
  1964. undefined,
  1965. description.replace(/\n/g, '\x1C').replace(/\r/g, '\x1D'),
  1966. identifiers.join(' '),
  1967. ];
  1968. tracks.push(track.join('\x1E'));
  1969.  
  1970. function stringyfyRole(ndx) {
  1971. return (trackArtists[ndx] instanceof Array && trackArtists[ndx].length > 0 ?
  1972. trackArtists : albumArtists)[ndx].join('; ');
  1973. }
  1974. }
  1975. });
  1976. clipBoard.value = tracks.join('\n');
  1977. fill_from_text_music();
  1978. } });
  1979. return true;
  1980. }
  1981. addMessage('This domain not supported', 'ua-critical');
  1982. return false;
  1983.  
  1984. function get_desc_from_node(selector, url, quote = false) {
  1985. description = [];
  1986. dom.querySelectorAll(selector).forEach(k => { description.push(html2php(k, url).trim()) });
  1987. description = description.join('\n\n').trim().replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  1988. if (quote && description.length > 0) description = '[quote]' + description + '[/quote]';
  1989. }
  1990. } // init_from_url_music
  1991.  
  1992. function normalizeDate(str) {
  1993. if (typeof str != 'string') return null;
  1994. return /\b(d{4}-\d+-\d+|\d{1,2}\/\d{1,2}\/\d{2})\b/.test(str) ? RegExp.$1 :
  1995. /\b(\d{1,2})\/(\d{1,2})\/(\d{4})\b/.test(str) ? RegExp.$2 + '/' + RegExp.$1 + '/' + RegExp.$3 :
  1996. /\b(\d{1,2})\.\s?(\d{1,2})\.\s?(\d{2}|\d{4})\b/.test(str) ? RegExp.$2 + '/' + RegExp.$1 + '/' + RegExp.$3 :
  1997. extract_year(str);
  1998. }
  1999.  
  2000. function fetch_image_from_store(response) {
  2001. if (response.readyState != 4 || !response.responseText) return;
  2002. dom = domparser.parseFromString(response.responseText, "text/html");
  2003. if (dom == null) return;
  2004. function testDomain(str) {
  2005. return typeof str == 'string' && response.finalUrl.toLowerCase().includes(str.toLowerCase());
  2006. }
  2007. if (testDomain('qobuz.com') && (ref = dom.querySelector('div.album-cover > img')) != null) {
  2008. setImage(ref.src);
  2009. } else if (testDomain('highresaudio.com') && (ref = dom.querySelector('div.albumbody > img.cover[data-pin-media]')) != null) {
  2010. setImage(ref.dataset.pinMedia);
  2011. } else if (testDomain('bandcamp.com') && (ref = dom.querySelector('div#tralbumArt > a.popupImage')) != null) {
  2012. setImage(ref.href);
  2013. } else if (testDomain('7digital.com') && (ref = dom.querySelector('span.release-packshot-image > img[itemprop="image"]')) != null) {
  2014. setImage(ref.src);
  2015. } else if (testDomain('hdtracks.com') && (ref = dom.querySelector('p.product-image > img')) != null) {
  2016. setImage(ref.src);
  2017. } else if (testDomain('discogs.com') && (ref = dom.querySelector('div#view_images > p:first-of-type > span > img')) != null) {
  2018. setImage(ref.src);
  2019. } else if (testDomain('junodownload.com') && (ref = dom.querySelector('a.productimage')) != null) {
  2020. setImage(ref.href);
  2021. } else if (testDomain('supraphonline.cz') && (ref = dom.querySelector('div.sexycover > img')) != null) {
  2022. setImage(ref.src.replace(/\?\d+$/, ''));
  2023. } else if (testDomain('prestomusic.com') && (ref = dom.querySelector('div.c-product-block__aside > a')) != null) {
  2024. setImage(ref.href.replace(/\?\d+$/, ''));
  2025. }
  2026. }
  2027.  
  2028. function reqSelectFormats(...vals) {
  2029. vals.forEach(function(val) {
  2030. [
  2031. ['MP3', 0],
  2032. ['FLAC', 1],
  2033. ['AAC', 2],
  2034. ['AC3', 3],
  2035. ['DTS', 4],
  2036. ].forEach(function(fmt) {
  2037. if (val == fmt[0] && (ref = document.getElementById('format_' + fmt[1])) != null) {
  2038. ref.checked = true;
  2039. ref.onchange();
  2040. }
  2041. });
  2042. });
  2043. }
  2044.  
  2045. function reqSelectBitrates(...vals) {
  2046. vals.forEach(function(val) {
  2047. var ndx = 10;
  2048. [
  2049. [192, 0],
  2050. ['APS (VBR)', 1],
  2051. ['V2 (VBR)', 2],
  2052. ['V1 (VBR)', 3],
  2053. [256, 4],
  2054. ['APX (VBR)', 5],
  2055. ['V0 (VBR)', 6],
  2056. [320, 7],
  2057. ['Lossless', 8],
  2058. ['24bit Lossless', 9],
  2059. ['Other', 10],
  2060. ].forEach(k => { if (val == k[0]) ndx = k[1] });
  2061. if ((ref = document.getElementById('bitrate_' + ndx)) != null) {
  2062. ref.checked = true;
  2063. ref.onchange();
  2064. }
  2065. });
  2066. }
  2067.  
  2068. function reqSelectMedias(...vals) {
  2069. vals.forEach(function(val) {
  2070. [
  2071. ['CD', 0],
  2072. ['DVD', 1],
  2073. ['Vinyl', 2],
  2074. ['Soundboard', 3],
  2075. ['SACD', 4],
  2076. ['DAT', 5],
  2077. ['Cassette', 6],
  2078. ['WEB', 7],
  2079. ['Blu-Ray', 8],
  2080. ].forEach(function(med) {
  2081. if (val == med[0] && (ref = document.getElementById('media_' + med[1])) != null) {
  2082. ref.checked = true;
  2083. ref.onchange();
  2084. }
  2085. });
  2086. if (val == 'CD') {
  2087. if ((ref = document.getElementById('needlog')) != null) {
  2088. ref.checked = true;
  2089. ref.onchange();
  2090. if ((ref = document.getElementById('minlogscore')) != null) ref.value = 100;
  2091. }
  2092. if ((ref = document.getElementById('needcue')) != null) ref.checked = true;
  2093. //if ((ref = document.getElementById('needchecksum')) != null) ref.checked = true;
  2094. }
  2095. });
  2096. }
  2097.  
  2098. function getReleaseIndex(str) {
  2099. var ndx;
  2100. [
  2101. ['Album', 1],
  2102. ['Soundtrack', 3],
  2103. ['EP', 5],
  2104. ['Anthology', 6],
  2105. ['Compilation', 7],
  2106. ['Single', 9],
  2107. ['Live album', 11],
  2108. ['Remix', 13],
  2109. ['Bootleg', 14],
  2110. ['Interview', 15],
  2111. ['Mixtape', 16],
  2112. ['Demo', 17],
  2113. ['Concert Recording', 18],
  2114. ['DJ Mix', 19],
  2115. ['Unknown', 21],
  2116. ].forEach(k => { if (str.toLowerCase() == k[0].toLowerCase()) ndx = k[1] });
  2117. return ndx || 21;
  2118. }
  2119.  
  2120. function joinArtists(arr, prefix, postfix) {
  2121. if (!(arr instanceof Array)) return null;
  2122. if (arr.find(it => it.includes('&')) != undefined) return arr.map(decorator).join(', ');
  2123. if (arr.length < 3) return arr.map(decorator).join(' & ');
  2124. var foo = arr.slice(-1).map(decorator);
  2125. foo.unshift(arr.slice(0, -1).map(decorator).join(', '));
  2126. return foo.join(' & ');
  2127.  
  2128. function decorator(it) {
  2129. var result = it;
  2130. if (prefix) result = prefix.concat(result);
  2131. if (postfix) result += postfix;
  2132. return result;
  2133. }
  2134. }
  2135. } // fill_from_text_music
  2136.  
  2137. function fill_from_text_apps() {
  2138. if (messages != null) messages.parentNode.removeChild(messages);
  2139. if (!urlParser.test(clipBoard.value)) {
  2140. addMessage('Only URL accepted for this category', 'ua-critical');
  2141. return false;
  2142. }
  2143. url = RegExp.$1;
  2144. var description, tags = new TagManager();
  2145. if (url.toLowerCase().includes('//sanet')) {
  2146. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2147. if (response.readyState != 4 || response.status != 200) return;
  2148. dom = domparser.parseFromString(response.responseText, "text/html");
  2149.  
  2150. i = dom.querySelector('h1.item_title > span');
  2151. if (element_writable(ref = document.getElementById('title'))) {
  2152. ref.value = i != null ? i.textContent.
  2153. replace(/\(x64\)$/i, '(64-bit)').
  2154. replace(/\b(?:Build)\s+(\d+)/, 'build $1').
  2155. replace(/\b(?:Multilingual|Multilanguage)\b/, 'multilingual') : null;
  2156. }
  2157. description = html2php(dom.querySelector('section.descr'), response.finalUrl);
  2158. if (/\s*^(?:\[i\]\[\/i\])?Homepage$.*/m.test(description)) description = RegExp.leftContext;
  2159. description = description.trim().split(/\n/).slice(5).map(k => k.trimRight()).join('\n').trim();
  2160. ref = dom.querySelector('section.descr > div.release-info');
  2161. var releaseInfo = ref != null && ref.textContent.trim();
  2162. if (/\b(?:Languages?)\s*:\s*(.*?)\s*(?:$|\|)/i.exec(releaseInfo) != null) {
  2163. description += '\n\n[b]Languages:[/b]\n' + RegExp.$1;
  2164. }
  2165. ref = dom.querySelector('div.txtleft > a');
  2166. if (ref != null) description += '\n\n[b]Product page:[/b]\n[url]' + de_anonymize(ref.href) + '[/url]';
  2167. write_description(description);
  2168. if ((ref = dom.querySelector('section.descr > div.center > a.mfp-image')) != null) {
  2169. setImage(ref.href);
  2170. } else {
  2171. ref = dom.querySelector('section.descr > div.center > img[data-src]');
  2172. if (ref != null) setImage(ref.dataset.src);
  2173. }
  2174. var cat = dom.querySelector('a.cat:last-of-type > span');
  2175. if (cat != null) {
  2176. if (cat.textContent.toLowerCase() == 'windows') {
  2177. tags.add('apps.windows');
  2178. if (/\b(?:x64)\b/i.test(releaseInfo)) tags.add('win64');
  2179. if (/\b(?:x86)\b/i.test(releaseInfo)) tags.add('win32');
  2180. }
  2181. if (cat.textContent.toLowerCase() == 'macos') tags.add('apps.mac');
  2182. if (cat.textContent.toLowerCase() == 'linux' || cat.textContent.toLowerCase() == 'unix') tags.add('apps.linux');
  2183. if (cat.textContent.toLowerCase() == 'android') tags.add('apps.android');
  2184. if (cat.textContent.toLowerCase() == 'ios') tags.add('apps.ios');
  2185. }
  2186. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  2187. ref.value = tags.toString();
  2188. }
  2189. }, });
  2190. return true;
  2191. }
  2192. addMessage('This domain not supported', 'ua-critical');
  2193. return false;
  2194. }
  2195.  
  2196. function fill_from_text_books() {
  2197. if (messages != null) messages.parentNode.removeChild(messages);
  2198. if (!urlParser.test(clipBoard.value)) {
  2199. addMessage('Only URL accepted for this category', 'ua-critical');
  2200. return false;
  2201. }
  2202. url = RegExp.$1;
  2203. var description, tags = new TagManager();
  2204. if (url.toLowerCase().includes('martinus.cz') || url.toLowerCase().includes('martinus.sk')) {
  2205. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2206. if (response.readyState != 4 || response.status != 200) return;
  2207. dom = domparser.parseFromString(response.responseText, "text/html");
  2208.  
  2209. function get_detail(x, y) {
  2210. var ref = dom.querySelector('section#details > div > div > div:first-of-type > div:nth-child(' +
  2211. x + ') > dl:nth-child(' + y + ') > dd');
  2212. return ref != null ? ref.textContent.trim() : null;
  2213. }
  2214.  
  2215. i = dom.querySelectorAll('article > ul > li > a');
  2216. if (i.length > 0 && element_writable(ref = document.getElementById('title'))) {
  2217. description = joinAuthors(i);
  2218. if ((i = dom.querySelector('article > h1')) != null) description += ' - ' + i.textContent.trim();
  2219. i = dom.querySelector('div.bar.mb-medium > div:nth-child(1) > dl > dd > span');
  2220. if (i != null && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  2221. ref.value = description;
  2222. }
  2223.  
  2224. description = '[quote]' + html2php(dom.querySelector('section#description > div')).
  2225. replace(/^\s*\[img\].*?\[\/img\]\s*/i, '') + '[/quote]';
  2226. const translation_map = [
  2227. [/\b(?:originál)/i, 'Original title'],
  2228. [/\b(?:datum|dátum|rok)\b/i, 'Release date'],
  2229. [/\b(?:katalog|katalóg)/i, 'Catalogue #'],
  2230. [/\b(?:stran|strán)\b/i, 'Page count'],
  2231. [/\bjazyk/i, 'Language'],
  2232. [/\b(?:nakladatel|vydavatel)/i, 'Publisher'],
  2233. [/\b(?:doporuč|ODPORÚČ)/i, 'Age rating'],
  2234. ];
  2235. dom.querySelectorAll('section#details > div > div > div:first-of-type > div > dl').forEach(function(detail) {
  2236. var lbl = detail.children[0].textContent.trim();
  2237. var val = detail.children[1].textContent.trim();
  2238. if (/\b(?:rozm)/i.test(lbl) || /\b(?:vazba|vázba)\b/i.test(lbl)) return;
  2239. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  2240. if (/\b(?:ISBN)\b/i.test(lbl)) {
  2241. val = '[url=https://www.worldcat.org/isbn/' + detail.children[1].textContent.trim() +
  2242. ']' + detail.children[1].textContent.trim() + '[/url]';
  2243. // } else if (/\b(?:ISBN)\b/i.test(lbl)) {
  2244. // val = '[url=https://www.goodreads.com/search/search?q=' + detail.children[1].textContent.trim() +
  2245. // '&search_type=books]' + detail.children[1].textContent.trim() + '[/url]';
  2246. }
  2247. description += '\n[b]' + lbl + ':[/b] ' + val;
  2248. });
  2249. description += '\n[b]More info:[/b] ' + response.finalUrl;
  2250. write_description(description);
  2251.  
  2252. if ((i = dom.querySelector('a.mj-product-preview > img')) != null) {
  2253. setImage(i.src.replace(/\?.*/, ''));
  2254. } else if ((i = dom.querySelector('head > meta[property="og:image"]')) != null) {
  2255. setImage(i.content.replace(/\?.*/, ''));
  2256. }
  2257.  
  2258. dom.querySelectorAll('dd > ul > li > a').forEach(x => { tags.add(x.textContent) });
  2259. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  2260. ref.value = tags.toString();
  2261. }
  2262. }, });
  2263. return true;
  2264. } else if (url.toLowerCase().includes('goodreads.com')) {
  2265. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2266. if (response.readyState != 4 || response.status != 200) return;
  2267. dom = domparser.parseFromString(response.responseText, "text/html");
  2268.  
  2269. i = dom.querySelectorAll('a.authorName > span');
  2270. if (i.length > 0 && element_writable(ref = document.getElementById('title'))) {
  2271. description = joinAuthors(i);
  2272. if ((i = dom.querySelector('h1#bookTitle')) != null) description += ' - ' + i.textContent.trim();
  2273. if ((i = dom.querySelector('div#details > div.row:nth-of-type(2)')) != null
  2274. && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  2275. ref.value = description;
  2276. }
  2277.  
  2278. description = '[quote]' + html2php(dom.querySelector('div#description > span:last-of-type'), response.finalUrl) + '[/quote]';
  2279.  
  2280. function strip(str) {
  2281. return typeof str == 'string' ?
  2282. str.replace(/\s{2,}/g, ' ').replace(/[\n\r]+/, '').replace(/\s*\.{3}(?:less|more)\b/g, '').trim() : null;
  2283. }
  2284.  
  2285. dom.querySelectorAll('div#details > div.row').forEach(k => { description += '\n' + strip(k.innerText) });
  2286. description += '\n';
  2287.  
  2288. dom.querySelectorAll('div#bookDataBox > div.clearFloats').forEach(function(detail) {
  2289. var lbl = detail.children[0].textContent.trim();
  2290. var val = strip(detail.children[1].textContent);
  2291. if (/\b(?:ISBN)\b/i.test(lbl) && ((matches = val.match(/\b(\d{13})\b/)) != null
  2292. || (matches = val.match(/\b(\d{10})\b/)) != null)) {
  2293. val = '[url=https://www.worldcat.org/isbn/' + matches[1] + ']' + strip(detail.children[1].textContent) + '[/url]';
  2294. }
  2295. description += '\n[b]' + lbl + ':[/b] ' + val;
  2296. });
  2297. description += '\n[b]More info:[/b] ' + response.finalUrl;
  2298. write_description(description);
  2299.  
  2300. if ((i = dom.querySelector('div.editionCover > img')) != null) {
  2301. setImage(i.src.replace(/\?.*/, ''));
  2302. }
  2303.  
  2304. dom.querySelectorAll('div.elementList > div.left').forEach(x => { tags.add(x.textContent.trim()) });
  2305. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  2306. ref.value = tags.toString();
  2307. }
  2308. }, });
  2309. return true;
  2310. } else if (url.toLowerCase().includes('databazeknih.cz')) {
  2311. if (!url.toLowerCase().includes('show=alldesc')) {
  2312. if (!url.includes('?')) { url += '?show=alldesc' } else { url += '&show=alldesc' }
  2313. }
  2314. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2315. if (response.readyState != 4 || response.status != 200) return;
  2316. dom = domparser.parseFromString(response.responseText, "text/html");
  2317.  
  2318. i = dom.querySelectorAll('span[itemprop="author"] > a');
  2319. if (i != null && element_writable(ref = document.getElementById('title'))) {
  2320. description = joinAuthors(i);
  2321. if ((i = dom.querySelector('h1[itemprop="name"]')) != null) description += ' - ' + i.textContent.trim();
  2322. i = dom.querySelector('span[itemprop="datePublished"]');
  2323. if (i != null && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  2324. ref.value = description;
  2325. }
  2326.  
  2327. description = '[quote]' + html2php(dom.querySelector('p[itemprop="description"]'), response.finalUrl) + '[/quote]';
  2328. const translation_map = [
  2329. [/\b(?:orig)/i, 'Original title'],
  2330. [/\b(?:série)\b/i, 'Series'],
  2331. [/\b(?:vydáno)\b/i, 'Released'],
  2332. [/\b(?:stran)\b/i, 'Page count'],
  2333. [/\b(?:jazyk)\b/i, 'Language'],
  2334. [/\b(?:překlad)/i, 'Translation'],
  2335. [/\b(?:autor obálky)\b/i, 'Cover author'],
  2336. ];
  2337. dom.querySelectorAll('table.bdetail tr').forEach(function(detail) {
  2338. var lbl = detail.children[0].textContent.trim();
  2339. var val = detail.children[1].textContent.trim();
  2340. if (/(?:žánr|\bvazba)\b/i.test(lbl)) return;
  2341. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  2342. if (/\b(?:ISBN)\b/i.test(lbl) && /\b(\d+(?:-\d+)*)\b/.exec(val) != null) {
  2343. val = '[url=https://www.worldcat.org/isbn/' + RegExp.$1.replace(/-/g, '') +
  2344. ']' + detail.children[1].textContent.trim() + '[/url]';
  2345. }
  2346. description += '\n[b]' + lbl + '[/b] ' + val;
  2347. });
  2348. description += '\n[b]More info:[/b] ' + response.finalUrl.replace(/\?.*/, '');
  2349. write_description(description);
  2350.  
  2351. if ((i = dom.querySelector('div#icover_mid > a')) != null) setImage(i.href.replace(/\?.*/, ''));
  2352. if ((i = dom.querySelector('div#lbImage')) != null
  2353. && (matches = i.style.backgroundImage.match(/\burl\("(.*)"\)/i)) != null) {
  2354. setImage(matches[1].replace(/\?.*/, ''));
  2355. }
  2356.  
  2357. dom.querySelectorAll('h5[itemprop="genre"] > a').forEach(x => { tags.add(x.textContent.trim()) });
  2358. dom.querySelectorAll('a.tag').forEach(x => { tags.add(x.textContent.trim()) });
  2359. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  2360. ref.value = tags.toString();
  2361. }
  2362. }, });
  2363. return true;
  2364. }
  2365. addMessage('This domain not supported', 'ua-critical');
  2366. return false;
  2367.  
  2368. function joinAuthors(nodeList) {
  2369. if (typeof nodeList != 'object') return null;
  2370. var authors = [];
  2371. nodeList.forEach(k => { authors.push(k.textContent.trim()) });
  2372. return authors.join(' & ');
  2373. }
  2374. }
  2375.  
  2376. function preview(n) {
  2377. if (!prefs.auto_preview) return;
  2378. var btn = document.querySelector('input.button_preview_' + n + '[type="button"][value="Preview"]');
  2379. if (btn != null) btn.click();
  2380. }
  2381.  
  2382. function html2php(node, url) {
  2383. var text = '';
  2384. if (node instanceof HTMLElement) node.childNodes.forEach(function(ch) {
  2385. if (ch.nodeType == 3) {
  2386. text += ch.data.replace(/\s+/g, ' ');
  2387. } else if (ch.nodeName == 'P') {
  2388. text += '\n' + html2php(ch, url);
  2389. } else if (ch.nodeName == 'DIV') {
  2390. text += '\n' + html2php(ch, url) + '\n\n';
  2391. } else if (ch.nodeName == 'LABEL') {
  2392. text += '\n\n[b]' + html2php(ch, url) + '[/b]';
  2393. } else if (ch.nodeName == 'SPAN') {
  2394. text += html2php(ch, url);
  2395. } else if (ch.nodeName == 'BR' || ch.nodeName == 'HR') {
  2396. text += '\n';
  2397. } else if (ch.nodeName == 'B' || ch.nodeName == 'STRONG') {
  2398. text += '[b]' + html2php(ch, url) + '[/b]';
  2399. } else if (ch.nodeName == 'I' || ch.nodeName == 'EM') {
  2400. text += '[i]' + html2php(ch, url) + '[/i]';
  2401. } else if (ch.nodeName == 'U') {
  2402. text += '[u]' + html2php(ch, url) + '[/u]';
  2403. } else if (ch.nodeName == 'CODE') {
  2404. text += '[pre]' + ch.textContent + '[/pre]';
  2405. } else if (ch.nodeName == 'A') {
  2406. text += ch.textContent.trim() ?
  2407. '[url=' + de_anonymize(ch.href) + ']' + ch.textContent.replace(/\s+/g, ' ') + '[/url]' :
  2408. '[url]' + de_anonymize(ch.href) + '[/url]';
  2409. } else if (ch.nodeName == 'IMG') {
  2410. text += '[img]' + (ch.dataset.src || ch.src) + '[/img]';
  2411. }
  2412. });
  2413. return text; //.replace(/\n{3,}/, '\n\n');
  2414. }
  2415.  
  2416. function de_anonymize(uri) {
  2417. return typeof uri == 'string' ? uri.replace(/^https?:\/\/(?:www\.)?anonymz\.com\/\?/i, '') : null;
  2418. }
  2419.  
  2420. function write_description(desc) {
  2421. if (typeof desc != 'string') return;
  2422. if (element_writable(ref = document.getElementById('desc'))) ref.value = desc;
  2423. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  2424. if (ref.textLength > 0) ref.value += '\n\n';
  2425. ref.value += desc;
  2426. }
  2427. }
  2428.  
  2429. function setImage(url) {
  2430. var image = document.getElementById('image') || document.querySelector('input[name="image"]');
  2431. if (!element_writable(image)) return false;
  2432. image.value = url;
  2433.  
  2434. if (prefs.auto_preview_cover) {
  2435. if ((child = document.getElementById('cover preview')) == null) {
  2436. elem = document.createElement('div');
  2437. elem.style.paddingTop = '10px';
  2438. child = document.createElement('img');
  2439. child.id = 'cover preview';
  2440. child.style.width = '90%';
  2441. elem.append(child);
  2442. image.parentNode.previousElementSibling.append(elem);
  2443. }
  2444. child.src = url;
  2445. }
  2446. // Re-Host to PTPIMG
  2447. if (prefs.auto_rehost_cover) {
  2448. var rehost_btn = document.querySelector('input.rehost_it_cover[type="button"]');
  2449. if (rehost_btn != null) {
  2450. rehost_btn.click();
  2451. } else {
  2452. var pr = rehostImgs([url]);
  2453. if (pr != null) pr.then(new_urls => { image.value = new_urls[0] });
  2454. }
  2455. }
  2456. }
  2457.  
  2458. // PTPIMG rehoster taken from `PTH PTPImg It`
  2459. function rehostImgs(urls) {
  2460. if (!Array.isArray(urls)) return null;
  2461. var config = JSON.parse(window.localStorage.ptpimg_it);
  2462. return config.api_key ? new Promise(ptpimg_upload_urls).catch(m => { alert(m) }) : null;
  2463.  
  2464. function ptpimg_upload_urls(resolve, reject) {
  2465. const boundary = 'NN-GGn-PTPIMG';
  2466. var data = '--' + boundary + "\n";
  2467. data += 'Content-Disposition: form-data; name="link-upload"\n\n';
  2468. data += urls.map(function(url) {
  2469. return !url.toLowerCase().includes('://reho.st/') && url.toLowerCase().includes('discogs.com') ?
  2470. 'https://reho.st/' + url : url;
  2471. }).join('\n') + '\n';
  2472. data += '--' + boundary + '\n';
  2473. data += 'Content-Disposition: form-data; name="api_key"\n\n';
  2474. data += config.api_key + '\n';
  2475. data += '--' + boundary + '--';
  2476. GM_xmlhttpRequest({
  2477. method: 'POST',
  2478. url: 'https://ptpimg.me/upload.php',
  2479. responseType: 'json',
  2480. headers: {
  2481. 'Content-type': 'multipart/form-data; boundary=' + boundary,
  2482. },
  2483. data: data,
  2484. onload: response => {
  2485. if (response.status != 200) reject('Response error ' + response.status);
  2486. resolve(response.response.map(item => 'https://ptpimg.me/' + item.code + '.' + item.ext));
  2487. },
  2488. });
  2489. }
  2490. }
  2491.  
  2492. function element_writable(elem) { return elem != null && !elem.disabled && (overwrite || !elem.value) }
  2493. }
  2494.  
  2495. function add_artist() { exec(function() { AddArtistField() }) }
  2496.  
  2497. function array_homogenous(arr) { return arr.every(k => k === arr[0]) }
  2498.  
  2499. function exec(fn) {
  2500. let script = document.createElement('script');
  2501. script.type = 'application/javascript';
  2502. script.textContent = '(' + fn + ')();';
  2503. document.body.appendChild(script); // run the script
  2504. document.body.removeChild(script); // clean up
  2505. }
  2506.  
  2507. function makeTimeString(duration) {
  2508. let t = Math.abs(Math.round(duration));
  2509. let H = Math.floor(t / 60 ** 2);
  2510. let M = Math.floor(t / 60 % 60);
  2511. let S = t % 60;
  2512. return (duration < 0 ? '-' : '') + (H > 0 ? H + ':' + M.toString().padStart(2, '0') : M.toString()) +
  2513. ':' + S.toString().padStart(2, '0');
  2514. }
  2515.  
  2516. function timeStringToTime(str) {
  2517. if (!/(-\s*)?\b(\d+(?::\d{2})*(?:\.\d+)?)\b/.test(str)) return null;
  2518. var t = 0, a = RegExp.$2.split(':');
  2519. while (a.length > 0) t = t * 60 + parseFloat(a.shift());
  2520. return RegExp.$1 ? -t : t;
  2521. }
  2522.  
  2523. function extract_year(expr) {
  2524. if (typeof expr != 'string') return null;
  2525. if (/\b(\d{4})\b/.test(expr)) return parseInt(RegExp.$1);
  2526. var d = new Date(expr);
  2527. return parseInt(isNaN(d) ? expr : d.getFullYear());
  2528. }
  2529.  
  2530. function isRED() { return document.domain.toLowerCase().endsWith('redacted.ch') }
  2531. function isNWCD() { return document.domain.toLowerCase().endsWith('notwhat.cd') }
  2532. function isOrpheus() { return document.domain.toLowerCase().endsWith('orpheus.network') }
  2533.  
  2534. function reInParenthesis(expr) { return new RegExp('\\s+\\([^\\(\\)]*'.concat(expr, '[^\\(\\)]*\\)$'), 'i') }
  2535. function reInBrackets(expr) { return new RegExp('\\s+\\[[^\\[\\]]*'.concat(expr, '[^\\[\\]]*\\]$'), 'i') }
  2536.  
  2537. function addMessage(text, cls, html = false) {
  2538. messages = document.getElementById('UA messages');
  2539. if (messages == null) {
  2540. var ua = document.getElementById('upload assistant');
  2541. if (ua == null) return null;
  2542. messages = document.createElement('TR');
  2543. if (messages == null) return null;
  2544. messages.id = 'UA messages';
  2545. ua.children[0].append(messages);
  2546.  
  2547. elem = document.createElement('TD');
  2548. if (elem == null) return null;
  2549. elem.colSpan = 2;
  2550. elem.className = 'ua-messages-bg';
  2551. messages.append(elem);
  2552. } else {
  2553. elem = messages.children[0]; // tbody
  2554. if (elem == null) return null;
  2555. }
  2556. var div = document.createElement('DIV');
  2557. div.classList.add('ua-messages', cls);
  2558. div[html ? 'innerHTML' : 'textContent'] = text;
  2559. return elem.appendChild(div);
  2560. }