RED (+ NWCD, Orpheus) Upload Assistant

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

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

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