RED/NWCD Upload Assistant

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

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

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