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-02 提交的版本,查看 最新版本

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