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

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