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

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