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

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