RED (+ NWCD, Orpheus) 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, image 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-09-30 提交的版本,查看 最新版本

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