RED/NWCD Upload Assistant

Accurate filling of new upload/request and group/request edit forms based on foobar2000's playlist selection (via pasted output of copy command), release integrity check, two tracklist layouts, colours customization, featured artists extraction, classical works formatting, coverart fetching from store and more. As alternative to pasted playlist, e.g. for requests creation, valid URL to product page on supported web can be used -- see below for list of supported sites.

当前为 2019-10-06 提交的版本,查看 最新版本

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