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, checking for previous upload 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.

目前為 2019-11-22 提交的版本,檢視 最新版本

  1. // ==UserScript==
  2. // @name RED/NWCD Upload Assistant
  3. // @namespace https://greasyfork.org/users/321857-anakunda
  4. // @version 1.185
  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, checking for previous upload 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.
  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. // //@require https://connect.soundcloud.com/sdk/sdk-3.3.2.js
  28. // ==/UserScript==
  29.  
  30. // Additional setup: to work, set the pattern below as built-in foobar2000 copy command or custom Text Tools plugin quick copy command
  31. // [$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 #%,%SKU%,%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)[%filesize%]$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% ])
  32. //
  33. // List of supported domains for online capturing of release details:
  34. //
  35. // Music releases:
  36. // - qobuz.com
  37. // - highresaudio.com
  38. // - bandcamp.com
  39. // - prestomusic.com
  40. // - discogs.com
  41. // - supraphonline.cz
  42. // - bontonland.cz (closing soon)
  43. // - nativedsd.com
  44. // - junodownload.com
  45. // - hdtracks.com
  46. // - deezer.com
  47. // - spotify.com
  48. // - prostudiomasters.com
  49. //
  50. // Ebooks releases:
  51. // - martinus.cz, martinus.sk
  52. // - goodreads.com
  53. // - databazeknih.cz
  54. //
  55. // Application releases:
  56. // - sanet.st
  57.  
  58. 'use strict';
  59.  
  60. const isRED = document.domain.toLowerCase().endsWith('redacted.ch');
  61. const isNWCD = document.domain.toLowerCase().endsWith('notwhat.cd');
  62. const isOrpheus = document.domain.toLowerCase().endsWith('orpheus.network');
  63.  
  64. const isUpload = document.URL.toLowerCase().includes('/upload\.php');
  65. const isEdit = document.URL.toLowerCase().includes('/torrents.php?action=editgroup');
  66. const isRequestNew = document.URL.toLowerCase().includes('/requests.php?action=new');
  67. const isRequestEdit = document.URL.toLowerCase().includes('/requests.php?action=edit');
  68.  
  69. var prefs = {
  70. set: function(prop, def) { this[prop] = GM_getValue(prop, def) },
  71. save: function() {
  72. for (var iter in this) {
  73. if (typeof this[iter] != 'function' && this[iter] != undefined) GM_setValue(iter, this[iter]);
  74. }
  75. },
  76. };
  77. prefs.set('remap_texttools_newlines', 0); // convert underscores to linebreaks (ambiguous)
  78. prefs.set('clean_on_apply', 0); // clean the input box on successfull fill
  79. prefs.set('keep_meaningles_composers', 0); // keep composers from file tags also for non-composer emphasis works
  80. prefs.set('always_hide_dnu_list', 0); // risky!
  81. prefs.set('single_threshold', 8 * 60); // Max length of single in s
  82. prefs.set('EP_threshold', 29 * 60); // Max time of EP in s
  83. prefs.set('autfill_delay', 1000); // delay in ms to autofill for after pasting text into box, 0 to disable
  84. prefs.set('auto_preview_cover', 1);
  85. prefs.set('auto_rehost_cover', 1);
  86. prefs.set('fetch_tags_from_artist', 0); // add n most used tags from release artist (if one) - experimental
  87. prefs.set('always_request_perfect_flac', 0);
  88. prefs.set('request_default_bounty', 0);
  89. prefs.set('ptpimg_api_key');
  90. prefs.set('spotify_clientid');
  91. prefs.set('spotify_clientsecret');
  92. prefs.set('soundcloud_clientid');
  93. prefs.set('catbox_userhash');
  94. prefs.set('dragdrop_patch_to_ptpimgit', 1);
  95. prefs.set('upcoming_tags', ''); // add this tag(s) to upcoming releases (requests); empty to disable
  96. prefs.set('estimate_decade_tag', 1); // deduce decade tag (1980s, etc.) from album year for regular albums
  97. // tracklist specific
  98. prefs.set('tracklist_style', 1); // 1: classical, 2: propertional right aligned
  99. prefs.set('max_tracklist_width', 80); // right margin of the right aligned tracklist. should not exceed the group description width on any device
  100. prefs.set('title_separator', '. '); // divisor of track# and title
  101. prefs.set('pad_leader', ' ');
  102. prefs.set('tracklist_head_color', '#4682B4'); // #a7bdd0
  103. prefs.set('tracklist_single_color', '#708080');
  104. // classical tracklist only components colouring
  105. prefs.set('tracklist_disctitle_color', '#008B8B');
  106. prefs.set('tracklist_work_color', 'Olive'); //#b16890
  107. prefs.set('tracklist_tracknumber_color', '#8899AA');
  108. prefs.set('tracklist_artist_color', '#889B2F');
  109. prefs.set('tracklist_composer_color', '#556B2F');
  110. prefs.set('tracklist_duration_color', '#8bb500');
  111.  
  112. document.head.appendChild(document.createElement('style')).innerHTML = `
  113. .ua-messages { text-indent: -2em; margin-left: 2em; }
  114. .ua-messages-bg { padding: 15px; text-align: left; background-color: darkslategray; }
  115. .ua-critical { color: red; font-weight: bold; }
  116. .ua-warning { color: #ff8d00; font-weight: 500; }
  117. .ua-info { color: white; }
  118.  
  119. .ua-button { vertical-align: middle; background-color: transparent; }
  120. .ua-input {
  121. width: 610px; height: 3em;
  122. margin-top: 8px; margin-bottom: 8px;
  123. background-color: antiquewhite;
  124. font-size: small;
  125. }
  126. `;
  127.  
  128. var ref, tbl, elem, child, tb, spotifyCredentials = {};
  129. var messages = null, autofill = false, domParser = new DOMParser(), dom;
  130.  
  131. if (isUpload) {
  132. ref = document.querySelector('form#upload_table > div#dynamic_form');
  133. if (ref == null) return;
  134. common1();
  135. let x = [];
  136. x.push(document.createElement('tr'));
  137. x[0].classList.add('ua-button');
  138. child = document.createElement('input');
  139. child.id = 'fill-from-text';
  140. child.value = 'Fill from text (overwrite)';
  141. child.type = 'button';
  142. child.style.width = '13em';
  143. child.onclick = fill_from_text;
  144. x[0].append(child);
  145. elem.append(x[0]);
  146. x.push(document.createElement('tr'));
  147. x[1].classList.add('ua-button');
  148. child = document.createElement('input');
  149. child.id = 'fill-from-text-weak';
  150. child.value = 'Fill from text (keep values)';
  151. child.type = 'button';
  152. child.style.width = '13em';
  153. child.onclick = fill_from_text;
  154. x[1].append(child);
  155. elem.append(x[1]);
  156. common2();
  157. ref.parentNode.insertBefore(tbl, ref);
  158. } else if (isEdit) {
  159. ref = document.querySelector('form.edit_form > div > div > input[type="submit"]');
  160. if (ref == null) return;
  161. ref = ref.parentNode;
  162. ref.parentNode.insertBefore(document.createElement('br'), ref);
  163. common1();
  164. child = document.createElement('input');
  165. child.id = 'append-from-text';
  166. child.value = 'Fill from text (append)';
  167. child.type = 'button';
  168. child.onclick = fill_from_text;
  169. elem.append(child);
  170. common2();
  171. tbl.style.marginBottom = '10px';
  172. ref.parentNode.insertBefore(tbl, ref);
  173. } else if (isRequestNew) {
  174. ref = document.getElementById('categories');
  175. if (ref == null) return;
  176. ref = ref.parentNode.parentNode.nextElementSibling;
  177. ref.parentNode.insertBefore(document.createElement('br'), ref);
  178. common1();
  179. child = document.createElement('input');
  180. child.id = 'fill-from-text-weak';
  181. child.value = 'Fill from URL';
  182. child.type = 'button';
  183. child.onclick = fill_from_text;
  184. elem.append(child);
  185. common2();
  186. child = document.createElement('td');
  187. child.colSpan = 2;
  188. child.append(tbl);
  189. elem = document.createElement('tr');
  190. elem.append(child);
  191. ref.parentNode.insertBefore(elem, ref);
  192. } else if (isRequestEdit) {
  193. ref = document.querySelector('input#button[type="submit"]');
  194. if (ref == null) return;
  195. ref = ref.parentNode.parentNode;
  196. ref.parentNode.insertBefore(document.createElement('br'), ref);
  197. common1();
  198. child = document.createElement('input');
  199. child.id = 'append-from-text';
  200. child.value = 'Fill from text (append)';
  201. child.type = 'button';
  202. child.onclick = fill_from_text;
  203. elem.append(child);
  204. common2();
  205. tbl.style.marginBottom = '10px';
  206. elem = document.createElement('tr');
  207. child = document.createElement('td');
  208. child.colSpan = 2;
  209. child.append(tbl);
  210. elem.append(child);
  211. ref.parentNode.insertBefore(elem, ref);
  212. }
  213.  
  214. if ((ref = document.getElementById('image') || document.querySelector('input[name="image"]')) != null) {
  215. ref.ondblclick = clear0;
  216. ref.onmousedown = clear1;
  217. ref.ondrop = clear0;
  218. }
  219.  
  220. function clear0() { this.value = '' }
  221. function clear1(e) { if (e.button == 1) this.value = '' }
  222. function autoFill(e) {
  223. autofill = true;
  224. setTimeout(fill_from_text, prefs.autfill_delay);
  225. }
  226.  
  227. function common1() {
  228. tbl = document.createElement('tr');
  229. tbl.style.backgroundColor = 'darkgoldenrod';
  230. tbl.style.verticalAlign = 'middle';
  231. elem = document.createElement('td');
  232. elem.style.textAlign = 'center';
  233. child = document.createElement('textarea');
  234. child.id = 'UA data';
  235. child.name = 'UA data';
  236. child.classList.add('ua-input');
  237. child.spellcheck = false;
  238. //child.ondblclick = clear0;
  239. child.onmousedown = clear1;
  240. child.ondrop = clear0;
  241. if (prefs.autfill_delay > 0) {
  242. child.onpaste = autoFill;
  243. child.ondrop = autoFill;
  244. }
  245. elem.append(child);
  246. tbl.append(elem);
  247. elem = document.createElement('td');
  248. elem.style.textAlign = 'center';
  249. }
  250. function common2() {
  251. tbl.append(elem);
  252. tb = document.createElement('tbody');
  253. tb.append(tbl);
  254. tbl = document.createElement('table');
  255. tbl.id = 'upload assistant';
  256. tbl.append(tb);
  257. }
  258.  
  259. // if (prefs.always_hide_dnu_list && (ref = document.querySelector('div#content > div:first-of-type')) != null) {
  260. // ref.style.display = 'none'; // Hide DNU list (warning - risky!)
  261. // }
  262.  
  263. if ((ref = document.getElementById('yadg_input')) != null) ref.ondrop = clear0;
  264.  
  265. Array.prototype.includesCaseless = function(str) {
  266. return typeof str == 'string' && this.find(it => typeof it == 'string' && it.toLowerCase() == str.toLowerCase()) != undefined;
  267. };
  268. Array.prototype.pushUnique = function(...items) {
  269. items.forEach(it => { if (!this.includes(it)) this.push(it) });
  270. return this.length;
  271. };
  272. Array.prototype.pushUniqueCaseless = function(...items) {
  273. items.forEach(it => { if (!this.includesCaseless(it)) this.push(it) });
  274. return this.length;
  275. };
  276. // Array.prototype.getUnique = function(prop) {
  277. // return this.every((it) => it[prop] && it[prop] == this[0][prop]) ? this[0][prop] : null;
  278. // };
  279. Array.prototype.equalTo = function(arr) {
  280. return arr instanceof Array && arr.length == this.length && arr.sort().toString() == this.sort().toString();
  281. };
  282. String.prototype.toASCII = function() {
  283. return this.normalize("NFKD").replace(/[\x00-\x1F\u0080-\uFFFF]/g, '');
  284. };
  285. String.prototype.trueLength = function() {
  286. return this.normalize('NFKD').replace(/[\u0300-\u036f]/g, '').length;
  287. // var index = 0, width = 0, len = 0;
  288. // while (index < this.length) {
  289. // var point = this.codePointAt(index);
  290. // width = 0;
  291. // while (point) {
  292. // ++width;
  293. // point = point >> 8;
  294. // }
  295. // index += Math.round(width / 2);
  296. // ++len;
  297. // }
  298. // return len;
  299. };
  300. Date.prototype.getDateValue = function() {
  301. return Math.floor((this.getTime() / 1000 / 60 - this.getTimezoneOffset()) / 60 / 24);
  302. };
  303.  
  304. const excludedCountries = [
  305. /\b(?:United\s+States|USA?)\b/,
  306. /\b(?:United\s+Kingdom|(?:Great\s+)?Britain|England|GB|UK)\b/,
  307. /\b(?:Europe|European\s+Union|EU)\b/,
  308. /\b(?:Unknown)\b/,
  309. ];
  310.  
  311. class TagManager extends Array {
  312. constructor(...tags) {
  313. super();
  314. this.presubstitutions = [
  315. [/\b(?:Singer\/Songwriter)\b/i, 'singer.songwriter'],
  316. [/\b(?:Pop\/Rock)\b/i, 'pop.rock'],
  317. [/\b(?:Folk\/Rock)\b/i, 'folk.rock'],
  318. ];
  319. this.substitutions = [
  320. [/^Pop\s*(?:[\-\−\—\–]\s*)?Rock$/i, 'pop.rock'],
  321. [/^Rock\s*(?:[\-\−\—\–]\s*)?Pop$/i, 'pop.rock'],
  322. [/^Rock\s+n\s+Roll$/i, 'rock.and.roll'],
  323. ['AOR', 'album.oriented.rock'],
  324. [/^(?:Prog)\.?\s*(?:Rock)$/i, 'progressive.rock'],
  325. [/^Synth[\s\-\−\—\–]+Pop$/i, 'synthpop'],
  326. [/^World(?:\s+and\s+|\s*[&+]\s*)Country$/i, 'world.music', 'country'],
  327. ['World', 'world.music'],
  328. [/^(?:Singer(?:\s+and\s+|\s*[&+]\s*))?Songwriter$/i, 'singer.songwriter'],
  329. [/^(?:R\s*(?:[\'\’\`][Nn](?:\s+|[\'\’\`]\s*)|&\s*)B|RnB)$/i, 'rhytm.and.blues'],
  330. [/\b(?:Soundtracks?)$/i, 'score'],
  331. ['Electro', 'electronic'],
  332. ['Metal', 'heavy.metal'],
  333. ['NonFiction', 'non.fiction'],
  334. ['Rap', 'hip.hop'],
  335. ['NeoSoul', 'neo.soul'],
  336. ['NuJazz', 'nu.jazz'],
  337. ['Hardcore', 'hardcore.punk'],
  338. ['Garage', 'garage.rock'],
  339. [/^(?:Neo[\s\-\−\—\–]+Classical)$/i, 'neoclassical'],
  340. [/^(?:Bluesy[\s\-\−\—\–]+Rock)$/i, 'blues.rock'],
  341. [/^(?:Be[\s\-\−\—\–]+Bop)$/i, 'bebop'],
  342. [/^(?:Chill)[\s\-\−\—\–]+(?:Out)$/i, 'chillout'],
  343. [/^(?:Atmospheric)[\s\-\−\—\–]+(?:Black)$/i, 'atmospheric.black.metal'],
  344. ['GoaTrance', 'goa.trance'],
  345. [/^Female\s+Vocal\w*$/i, 'female.vocalist'],
  346. // French translation
  347. [/^(?:Alternatif)(?:\s+et\s+|\s*[&+]\s*)(?:Inde)$/i, 'alternative', 'indie'],
  348. ['Ambiente', 'ambient'],
  349. ['Électronique', 'electronic'],
  350. ['Electronique', 'electronic'],
  351. ['Musiques du monde', 'world.music'],
  352. ['Musique du monde', 'world.music'],
  353. ['Rock progressif', 'progressive.rock'],
  354. ['Cantates sacrées', 'cantatas', 'sacred', 'classical'],
  355. ['Cantates (profanes)', 'cantatas', 'profane', 'classical'],
  356. ['Cantatas (secular)', 'cantatas', 'secular', 'classical'],
  357. ['Chœurs sacrés', 'choral', 'sacred', 'classical'],
  358. ['Classique', 'classical'],
  359. ['Concertos pour clavier', 'piano.concertos', 'classical'],
  360. ['Concertos pour instruments à vent', 'concertos.for.wind.instruments', 'classical'],
  361. ['Concertos pour violon', 'violin.concertos', 'classical'],
  362. ['Concertos pour violoncelle', 'cello.concertos', 'classical'],
  363. ['Duos', 'duets', 'classical'],
  364. //['Électronique ou concrète', '??', 'classical'],
  365. ['Enfants', 'children'],
  366. ['Extraits d\'opéra', 'opera.extracts', 'classical'],
  367. ['Intégrales d\'opéra', 'opera.integrals', 'classical'],
  368. ['Lieder (Allemagne)', 'lieder', 'german'],
  369. ['Messes', 'masses', 'classical'],
  370. ['Mélodies (Europe du Nord)', 'melodies', 'north.europe'],
  371. ['Mélodies', 'melodies', 'classical'],
  372. ['Mélodies (France)', 'melodies', 'french', 'classical'],
  373. ['Musique chorale (pour chœur)', 'choral.music', 'classical'],
  374. ['Musique concertante', 'concerto.music', 'classical'],
  375. ['Musique de chambre', 'chamber.music', 'classical'],
  376. ['Musique de scène', 'scenic.music', 'classical'],
  377. ['Musique vocale (profane et sacrée)', 'vocal.music', 'classical'],
  378. ['Musique vocale profane', 'vocal.music', 'profane', 'classical'],
  379. ['Musique vocale sacrée', 'vocal.music', 'sacred', 'classical'],
  380. ['Musique symphonique', 'symphonic.music', 'classical'],
  381. ['Musiques de Noël', 'christmas.music'],
  382. ['Musiques pour le cinéma', 'music.for.film'],
  383. ['Opéra', 'opera', 'classical'],
  384. ['Opérette', 'operetta', 'classical'],
  385. ['Oratorios sacrés', 'oratorios', 'sacred', 'classical'],
  386. ['Piano solo', 'solo.piano', 'classical'],
  387. ['Poèmes symphoniques', 'symphonic.poems', 'classical'],
  388. ['Quatuors', 'quartets', 'classical'],
  389. ['Quintettes', 'quintets', 'classical'],
  390. ['Récitals vocaux', 'voice.recitals', 'classical'],
  391. ['Violin Solos', 'solo.violin', 'classical'],
  392. // German translation
  393. [/^(?:Alternativ)(?:\s+und\s+|\s*[&+]\s*)(?:indie)$/i, 'alternative', 'indie'],
  394. // Country aliases
  395. ['Canada', 'canadian'],
  396. ['Australia', 'australian'],
  397. ['Japan', 'japanese'],
  398. ['Taiwan', 'thai'],
  399. ['China', 'chinese'],
  400. ['Singapore', 'singaporean'],
  401. [/^(?:Russia|Russian\s+Federation|Россия|USSR|СССР)$/i, 'russian'],
  402. ['Turkey', 'turkish'],
  403. ['France', 'french'],
  404. ['Germany', 'german'],
  405. ['Spain', 'spanish'],
  406. ['Italy', 'italian'],
  407. ['Sweden', 'swedish'],
  408. ['Norway', 'norwegian'],
  409. ['Finland', 'finnish'],
  410. ['Greece', 'greek'],
  411. [/^(?:Netherlands|Holland)$/i, 'dutch'],
  412. ['Belgium', 'belgian'],
  413. ['Luxembourg', 'luxembourgish'],
  414. ['Denmark', 'danish'],
  415. ['Switzerland', 'swiss'],
  416. ['Austria', 'austrian'],
  417. ['Portugal', 'portugese'],
  418. ['Ireland', 'irish'],
  419. ['Scotland', 'scotish'],
  420. ['Iceland', 'icelandic'],
  421. [/^(?:Czech\s+Republic|Czechia)$/i, 'czech'],
  422. [/^(?:Slovak\s+Republic|Slovakia)$/i, 'slovak'],
  423. ['Hungary', 'hungarian'],
  424. ['Poland', 'polish'],
  425. ['Estonia', 'estonian'],
  426. ['Latvia', 'latvian'],
  427. ['Lithuania', 'lithuanian'],
  428. ['Moldova', 'moldovan'],
  429. ['Armenia', 'armenian'],
  430. ['Ukraine', 'ukrainian'],
  431. ['Yugoslavia', 'yugoslav'],
  432. ['Serbia', 'serbian'],
  433. ['Slovenia', 'slovenian'],
  434. ['Croatia', 'croatian'],
  435. ['Macedonia', 'macedonian'],
  436. ['Montenegro', 'montenegrin'],
  437. ['Romania', 'romanian'],
  438. ['Malta', 'maltese'],
  439. ['Brazil', 'brazilian'],
  440. ['Mexico', 'mexican'],
  441. ['Argentina', 'argentinean'],
  442. ['Jamaica', 'jamaican'],
  443. // Books
  444. ['Beletrie', 'fiction'],
  445. ['Satira', 'satire'],
  446. ['Komiks', 'comics'],
  447. ['Komix', 'comics'],
  448. // Removals
  449. ['Unknown'],
  450. ['Other'],
  451. ['New'],
  452. ['Ostatni'],
  453. ['Knihy'],
  454. ['Audioknihy'],
  455. [/^(?:Audio\s*kniha|Audio\s*Book)$/i],
  456. ].concat(excludedCountries.map(it => [it]));
  457. this.splits = [
  458. ['Alternative', 'Indie'],
  459. ['Rock', 'Pop'],
  460. ['Soul', 'Funk'],
  461. ['Ska', 'Rocksteady'],
  462. ['Jazz Fusion', 'Jazz Rock'],
  463. ['Rock', 'Pop'],
  464. ];
  465. this.additions = [
  466. [/^(?:(?:(?:Be|Post|Neo)[\s\-\−\—\–]*)?Bop|Modal|Fusion|Free[\s\-\−\—\–]+Improvisation|Jazz[\s\-\−\—\–]+Fusion|Big[\s\-\−\—\–]*Band)$/i, 'jazz'],
  467. [/^(?:(?:Free|Cool|Avant[\s\-\−\—\–]*Garde|Contemporary|Vocal|Instrumental|Crossover|Modal|Mainstream|Modern|Soul|Smooth|Piano|Latin|Afro[\s\-\−\—\–]*Cuban)[\s\-\−\—\–]+Jazz)$/i, 'jazz'],
  468. [/^(?:Opera)$/i, 'classical'],
  469. [/\b(?:Chamber[\s\-\−\—\–]+Music)\b/i, 'classical'],
  470. [/\b(?:Orchestral[\s\-\−\—\–]+Music)\b/i, 'classical'],
  471. [/^(?:Symphony)$/i, 'classical'],
  472. [/^(?:Sacred\s+Vocal)\b/i, 'classical'],
  473. [/\b(?:Soundtracks?|Films?|Games?|Video|Series?|Theatre|Musical)\b/i, 'score'],
  474. ];
  475. if (tags.length > 0) this.add(...tags);
  476. }
  477.  
  478. add(...tags) {
  479. var added = 0;
  480. for (var tag of tags) {
  481. if (typeof tag != 'string') continue;
  482. this.presubstitutions.forEach(k => { if (k[0].test(tag)) tag = tag.replace(k[0], k[1]) });
  483. tag.split(/\s*[\,\/\;\>\|]+\s*/).forEach(function(tag) {
  484. tag = tag.toASCII().replace(/\(.*?\)|\[.*?\]|\{.*?\}/g, '').trim();
  485. if (tag.length <= 0 || tag == '?') return null;
  486. function test(obj) {
  487. return typeof obj == 'string' && tag.toLowerCase() == obj.toLowerCase()
  488. || obj instanceof RegExp && obj.test(tag);
  489. }
  490. for (var k of this.substitutions) {
  491. if (test(k[0])) {
  492. if (k.length >= 1) added += this.add(...k.slice(1));
  493. else addMessage('Warning: invalid tag \'' + tag + '\' found', 'ua-warning');
  494. return;
  495. }
  496. }
  497. for (k of this.additions) {
  498. if (test(k[0])) added += this.add(...k.slice(1));
  499. }
  500. for (k of this.splits) {
  501. if (new RegExp('^' + k[0] + '(?:\\s+and\\s+|\\s*[&+]\\s*)' + k[1] + '$', 'i').test(tag)) {
  502. added += this.add(k[0], k[1]); return;
  503. }
  504. if (new RegExp('^' + k[1] + '(?:\\s+and\\s+|\\s*[&+]\\s*)' + k[0] + '$', 'i').test(tag)) {
  505. added += this.add(k[0], k[1]); return;
  506. }
  507. }
  508. tag = tag.
  509. replace(/^(?:Alt\.)\s*(\w+)$/i, 'Alternative $1').
  510. replace(/\b(?:Alt\.)(?=\s+)/i, 'Alternative').
  511. replace(/^[3-9]0s$/i, '19$0').
  512. replace(/^[0-2]0s$/i, '20$0').
  513. replace(/\b(Psy)[\s\-\−\—\–]+(Trance|Core|Chill)\b/i, '$1$2').
  514. replace(/\s*(?:[\'\’\`][Nn](?:\s+|[\'\’\`]\s*)|[\&\+]\s*)/, ' and ').
  515. replace(/[\s\-\−\—\–\_\.\,\'\`\~]+/g, '.').
  516. replace(/[^\w\.]+/g, '').
  517. toLowerCase();
  518. if (tag.length >= 2 && !this.includes(tag)) {
  519. this.push(tag);
  520. ++added;
  521. }
  522. }.bind(this));
  523. }
  524. return added;
  525. }
  526. toString() { return this.sort().join(', ') }
  527. };
  528.  
  529. if ((ref = document.getElementById('categories')) != null) {
  530. ref.addEventListener('change', function(e) {
  531. elem = document.getElementById('upload assistant');
  532. if (elem != null) elem.style.visibility = this.value < 4
  533. || ['Music', 'Applications', 'E-Books', 'Audiobooks'].includes(this.value) ? 'visible' : 'collapse';
  534. });
  535. }
  536.  
  537. var rehostItBtn = document.querySelector('input.rehost_it_cover[type="button"]');
  538. if (prefs.dragdrop_patch_to_ptpimgit && rehostItBtn != null && !isNWCD) {
  539. rehostItBtn.ondragover = voidDragHandler;
  540. rehostItBtn.ondrop = imageDropHandler;
  541. }
  542.  
  543. return;
  544.  
  545. function fill_from_text(e) {
  546. if (e == undefined && !autofill) return;
  547. autofill = false;
  548. var overwrite = this.id == 'fill-from-text';
  549. var clipBoard = document.getElementById('UA data');
  550. if (clipBoard == null) return false;
  551. const urlParser = /^\s*(https?:\/\/[\S]+)\s*$/i;
  552. messages = document.getElementById('UA messages');
  553. //let promise = clientInformation.clipboard.readText().then(text => clipBoard = text);
  554. //if (typeof clipBoard != 'string') return false;
  555. var i, matches, url, category = document.getElementById('categories');
  556. if (category == null && document.getElementById('releasetype') != null
  557. || category != null && (category.value == 0 || category.value == 'Music')) return fill_from_text_music();
  558. if (category != null && (category.value == 1 || category.value == 'Applications')) return fill_from_text_apps();
  559. if (category != null && (category.value == 2 || category.value == 3
  560. || category.value == 'E-Books' || category.value == 'Audiobooks')) return fill_from_text_books();
  561. return category == null ? fill_from_text_apps(true) || fill_from_text_books() : false;
  562.  
  563. function fill_from_text_music() {
  564. if (messages != null) messages.parentNode.removeChild(messages);
  565. const divs = ['—', '⸺', '⸻'];
  566. const vaParser = /^(?:Various(?:\s+Artists)?|VA|Různí(?:\s+interpreti)?)$/i;
  567. const multiArtistParsers = [
  568. /(?:\s+[\/\|\×]|\s*(?:;|,(?!\s*(?:[JjSs]r)\b)(?:\s*[Aa]nd\s+)?))\s+/,
  569. ];
  570. const ampersandParsers = [
  571. /\s+(?:meets|vs\.?|X)\s+/i,
  572. /\s*[;\/\|\×]\s*/,
  573. /\s+(?:[\&\+]|and)\s+(?!(?:his|her|Friends)\b)/i, // /\s+(?:[\&\+]|and)\s+(?!(?:The|his|her|Friends)\b)/i,
  574. /\s*\+\s*(?!(?:The|his|her|Friends)\b)/i,
  575. ];
  576. const featParsers = [
  577. /\s+(?:meets)\s+(.*?)\s*$/i,
  578. /\s+(?:[Ff]eaturing|[Ww]ith)\s+(.*?)\s*$/,
  579. /\s+(?:[Ff]eat|[Ff]t)\.\s+(.*?)\s*$/,
  580. /\s+\[\s*f(?:eat(?:\.|uring)|t\.)\s+([^\[\]]+?)\s*\]/i,
  581. /\s+\(\s*f(?:eat(?:\.|uring)|t\.)\s+([^\(\)]+?)\s*\)/i,
  582. /\s+\[\s*with\s+([^\[\]]+?)\s*\]/i,
  583. /\s+\(\s*with\s+([^\(\)]+?)\s*\)/i,
  584. /\s+\[\s*(?:(?:en\s+)?duo\s+)?avec\s+([^\[\]]+?)\s*\]/i,
  585. /\s+\(\s*(?:(?:en\s+)?duo\s+)?avec\s+([^\(\)]+?)\s*\)/i,
  586. ];
  587. const remixParsers = [
  588. /\s+\((?:The\s+)Remix(?:e[sd])?\)/i,
  589. /\s+\[(?:The\s+)Remix(?:e[sd])?\]/i,
  590. /\s+(?:The\s+)Remix(?:e[sd])?\s*$/i,
  591. /\s+\(([^\(\)]+?)(?:[\'\’\`]s)?\s+(?:(?:Extended|Enhanced)\s+)?Remix\)/i,
  592. /\s+\[([^\[\]]+?)(?:[\'\’\`]s)?\s+(?:(?:Extended|Enhanced)\s+)?Remix\]/i,
  593. /\s+\(\s*(?:(Extended|Enhanced)\s+)?Remix(?:ed)?\s+by\s+([^\(\)]+)\)/i,
  594. /\s+\[\s*(?:(Extended|Enhanced)\s+)?Remix(?:ed)?\s+by\s+([^\[\]]+)\]/i,
  595. ];
  596. const otherArtistsParsers = [
  597. [/^(.*?)\s+(?:under|(?:conducted)\s+by)\s+(.*)$/, 4],
  598. [/^()(.*?)\s+\(conductor\)$/i, 4],
  599. //[/^()(.*?)\s+\(.*\)$/i, 1],
  600. ];
  601. const pseudoArtistParsers = [
  602. /^(?:#?N\/?A|[JS]r\.?)$/i,
  603. /^(?:traditional|lidová)$/i,
  604. /\b(?:traditional|lidová)$/,
  605. /^(?:[Aa]nonym)/,
  606. /^(?:[Ll]iturgical\b|[Ll]iturgick[áý])/,
  607. /^(?:auditorium|[Oo]becenstvo|[Pp]ublikum)$/,
  608. /^(?:Various\s+Composers)$/i,
  609. ];
  610. const noAKAs = /\s+(?:aka|AKA)\s+(.*)/;
  611. var track, tracks = [], totalDiscs = 1, media, xhr = new XMLHttpRequest();
  612. if (urlParser.test(clipBoard.value)) return init_from_url_music(RegExp.$1);
  613. function ruleLink(rule) { return ' (<a href="https://redacted.ch/rules.php?p=upload#r' + rule + '" target="_blank">' + rule + '</a>)' }
  614. var albumBitrate = 0, totalTime = 0, albumSize = 0;
  615. for (iter of clipBoard.value.split(/[\r\n]+/)) {
  616. if (!iter.trim()) continue; // skip empty lines
  617. let metaData = iter.split('\x1E');
  618. track = {
  619. artist: metaData.shift().trim() || undefined,
  620. album: metaData.shift().trim() || undefined,
  621. album_year: safeParseYear(metaData.shift().trim()),
  622. release_date: metaData.shift().trim() || undefined,
  623. label: metaData.shift().trim() || undefined,
  624. catalog: metaData.shift().trim() || undefined,
  625. country: metaData.shift().trim() || undefined,
  626. encoding: metaData.shift().trim() || undefined,
  627. codec: metaData.shift().trim() || undefined,
  628. codec_profile: metaData.shift().trim() || undefined,
  629. bitrate: safeParseInt(metaData.shift()),
  630. bd: safeParseInt(metaData.shift()),
  631. sr: safeParseInt(metaData.shift()),
  632. channels: safeParseInt(metaData.shift()),
  633. media: metaData.shift().trim() || undefined,
  634. genre: metaData.shift().trim() || undefined,
  635. discnumber: safeParseInt(metaData.shift()),
  636. totaldiscs: safeParseInt(metaData.shift()),
  637. discsubtitle: metaData.shift().trim() || undefined,
  638. tracknumber: metaData.shift().trim() || undefined,
  639. totaltracks: safeParseInt(metaData.shift()),
  640. title: metaData.shift().trim() || undefined,
  641. track_artist: metaData.shift().trim() || undefined,
  642. performer: metaData.shift().trim() || undefined,
  643. composer: metaData.shift().trim() || undefined,
  644. conductor: metaData.shift().trim() || undefined,
  645. remixer: metaData.shift().trim() || undefined,
  646. compiler: metaData.shift().trim() || undefined,
  647. producer: metaData.shift().trim() || undefined,
  648. duration: safeParseFloat(metaData.shift()),
  649. samples: safeParseInt(metaData.shift()),
  650. filesize: safeParseInt(metaData.shift()),
  651. rg: metaData.shift().trim() || undefined,
  652. dr: metaData.shift().trim() || undefined,
  653. vendor: metaData.shift().trim() || undefined,
  654. url: metaData.shift().trim() || undefined,
  655. dirpath: metaData.shift() || undefined,
  656. comment: metaData.shift().trim() || undefined,
  657. identifiers: {},
  658. };
  659. if (!track.artist) {
  660. addMessage('FATAL: main artist must be defined in every track' + ruleLink('2.3.16.4'), 'ua-critical', true);
  661. clipBoard.value = '';
  662. throw new Error('artist missing');
  663. }
  664. if (!track.album) {
  665. addMessage('FATAL: album title must be defined in every track' + ruleLink('2.3.16.4'), 'ua-critical', true);
  666. clipBoard.value = '';
  667. throw new Error('album mising');
  668. }
  669. if (!track.tracknumber) {
  670. addMessage('FATAL: all track numbers must be defined' + ruleLink('2.3.16.4'), 'ua-critical', true);
  671. clipBoard.value = '';
  672. throw new Error('tracknumber missing');
  673. }
  674. if (!track.title) {
  675. addMessage('FATAL: all track titles must be defined' + ruleLink('2.3.16.4'), 'ua-critical', true);
  676. clipBoard.value = '';
  677. throw new Error('track title missing');
  678. }
  679. if (track.duration != undefined && isUpload && (isNaN(track.duration) || track.duration <= 0)) {
  680. addMessage('FATAL: invalid track #' + track.tracknumber + ' length: ' + track.duration, 'ua-critical');
  681. clipBoard.value = '';
  682. throw new Error('invalid duration');
  683. }
  684. if (track.codec && !['FLAC', 'MP3', 'AAC', 'DTS', 'AC3'].includes(track.codec)) {
  685. addMessage('FATAL: disallowed codec present (' + track.codec + ')', 'ua-critical');
  686. clipBoard.value = '';
  687. throw new Error('invalid format');
  688. }
  689. if (track.discnumber > totalDiscs) totalDiscs = track.discnumber;
  690. if (track.comment == '.') track.comment = undefined;
  691. if (track.comment) {
  692. track.comment = track.comment.replace(/\x1D/g, '\r').replace(/\x1C/g, '\n');
  693. if (prefs.remap_texttools_newlines) track.comment = track.comment.replace(/__/g, '\r\n').replace(/_/g, '\n') // ambiguous
  694. track.comment = track.comment.replace(/(?:[ \t]*\r?\n){3,}/g, '\n\n'); // reduce excessive empty lines
  695. }
  696. if (track.dr != null) track.dr = parseInt(track.dr); // DR0
  697. metaData.shift().trim().split(/\s+/).forEach(function(it) {
  698. if (/([\w\-]+)[=:](.*)/.test(it)) track.identifiers[RegExp.$1.toUpperCase()] = RegExp.$2.replace(/\x1B/g, ' ');
  699. });
  700. totalTime += track.duration || NaN;
  701. albumBitrate += (track.duration || NaN) * (track.bitrate || NaN);
  702. albumSize += track.filesize;
  703.  
  704. tracks.push(track);
  705.  
  706. function safeParseInt(x) { return typeof x != 'string' ? null : x.length <= 0 ? undefined : parseInt(x) }
  707. function safeParseFloat(x) { return typeof x != 'string' ? null : x.length <= 0 ? undefined : parseFloat(x) }
  708. function safeParseYear(x) { return typeof x != 'string' ? null : x.length <= 0 ? undefined : extractYear(x) || NaN }
  709. }
  710. if (tracks.length <= 0) {
  711. addMessage('FATAL: no tracks found', 'ua-critical', true);
  712. clipBoard.value = '';
  713. throw new Error('no tracks');
  714. }
  715. if (!tracks.every(it => it.discnumber > 0) && !tracks.every(it => !it.discnumber)) {
  716. addMessage('FATAL: inconsistent release (mix of tracks with and without disc number)', 'ua-critical', true);
  717. clipBoard.value = '';
  718. throw new Error('inconsistent disc numbering');
  719. }
  720.  
  721. var release = {};
  722. ['catalogs', 'bds', 'genres', 'srs', 'urls', 'comments', 'trackArtists', 'bitrates',
  723. 'drs', 'rgs', 'dirpaths', 'composers'].forEach(it => { release[it] = [] });
  724. function setUniqueProperty(propName, propNameLiteral) {
  725. let homogenous = new Set(tracks.map(it => it[propName]).filter(it => it != undefined && it != null));
  726. if (homogenous.size > 1) {
  727. var diverses = '', it = homogenous.values(), val;
  728. while (!(val = it.next()).done) diverses += '<br>\t' + val.value;
  729. addMessage('FATAL: mixed releases not accepted (' + propNameLiteral + ') - supposedly user compilation' + diverses, 'ua-critical', true);
  730. clipBoard.value = '';
  731. throw new Error('mixed release (' + propNameLiteral + ')');
  732. }
  733. release[propName] = homogenous.values().next().value;
  734. }
  735. setUniqueProperty('artist', 'album artist', true);
  736. setUniqueProperty('album', 'album title', true);
  737. setUniqueProperty('album_year', 'album year');
  738. setUniqueProperty('release_date', 'release date');
  739. setUniqueProperty('encoding', 'encoding');
  740. setUniqueProperty('codec', 'codec');
  741. setUniqueProperty('codec_profile', 'codec profile');
  742. setUniqueProperty('vendor', 'vendor');
  743. setUniqueProperty('media', 'media');
  744. setUniqueProperty('channels', 'channels');
  745. setUniqueProperty('label', 'label');
  746. setUniqueProperty('country', 'country');
  747.  
  748. tracks.forEach(function(iter) {
  749. push_unique('trackArtists', 'track_artist');
  750. push_unique('composers', 'composer');
  751. push_unique('catalogs', 'catalog');
  752. push_unique('bitrates', 'bitrate');
  753. push_unique('bds', 'bd');
  754. push_unique('rgs', 'rg');
  755. push_unique('drs', 'dr');
  756. if (iter.sr) {
  757. if (typeof release.srs[iter.sr] != 'number') {
  758. release.srs[iter.sr] = iter.duration;
  759. } else {
  760. release.srs[iter.sr] += iter.duration;
  761. }
  762. }
  763. push_unique('dirpaths', 'dirpath');
  764. push_unique('comments', 'comment');
  765. push_unique('genres', 'genre');
  766. push_unique('urls', 'url');
  767.  
  768. function push_unique(relProp, prop) {
  769. if (iter[prop] !== undefined && iter[prop] !== null && (typeof iter[prop] != 'string'
  770. || iter[prop].length > 0) && !release[relProp].includes(iter[prop])) release[relProp].push(iter[prop]);
  771. }
  772. });
  773. function validatorFunc(arr, validator, str) {
  774. if (arr.length <= 0 || !arr.some(validator)) return true;
  775. addMessage('FATAL: disallowed ' + str + ' present (' + arr.filter(validator) + ')', 'ua-critical');
  776. clipBoard.value = '';
  777. throw new Error('disallowed ' + str);
  778. }
  779. validatorFunc(release.bds, bd => ![16, 24].includes(bd), 'bit depths');
  780. validatorFunc(Object.keys(release.srs),
  781. sr => sr < 44100 || sr > 192000 || sr % 44100 != 0 && sr % 48000 != 0, 'sample rates');
  782.  
  783. var composerEmphasis = false, isFromDSD = false, isClassical = false;
  784. var yadg_prefil = '', releaseType, editionTitle, isVA, iter, rx;
  785. var tags = new TagManager();
  786. albumBitrate /= totalTime;
  787. if (tracks.every(it => /^(?:single)$/i.test(it.identifiers.RELEASETYPE))
  788. || totalTime > 0 && totalTime <= prefs.single_threshold) {
  789. releaseType = getReleaseIndex('Single');
  790. } else if (tracks.every(it => it.identifiers.RELEASETYPE == 'EP')
  791. || totalTime > 0 && totalTime <= prefs.EP_threshold) {
  792. releaseType = getReleaseIndex('EP');
  793. } else if (tracks.every(it => /^soundtrack$/i.test(it.identifiers.RELEASETYPE))) {
  794. releaseType = getReleaseIndex('Soundtrack');
  795. tags.add('score');
  796. composerEmphasis = true;
  797. }
  798.  
  799. // Processing artists: recognition, splitting and dividing to categores
  800. var roleCollisions = [
  801. [4, 5], // main
  802. [0, 4], // guest
  803. [], // remixer
  804. [], // composer
  805. [], // conductor
  806. [], // DJ/compiler
  807. [], // producer
  808. ];
  809. isVA = vaParser.test(release.artist);
  810. var artists = [];
  811. for (i = 0; i < 7; ++i) artists[i] = [];
  812.  
  813. if (!isVA) addArtists(0, yadg_prefil = spliceGuests(release.artist));
  814.  
  815. featParsers.slice(3).forEach(function(rx, __a, ndx) {
  816. matches = rx.exec(release.album);
  817. if (matches != null && (ndx < 2 || splitArtists(matches[1]).every((artist) => looksLikeTrueName(artist, 1)))) {
  818. addArtists(1, matches[1]);
  819. addMessage('Warning: featured artist(s) in album title (' + release.album + ')', 'ua-warning');
  820. release.album = release.album.replace(rx, '');
  821. }
  822. });
  823. remixParsers.slice(3).forEach(function(rx) {
  824. if (rx.test(release.album)) addArtists(2, RegExp.$1);
  825. })
  826. if (isVA && (/\s+\(compiled\s+by\s+(.*?)\)\s*$/i.test(release.album)
  827. || /\s+compiled\s+by\s+(.*?)\s*$/i.test(release.album))) {
  828. addArtists(5, RegExp.$1);
  829. if (!releaseType) releaseType = getReleaseIndex('Compilation');
  830. }
  831.  
  832. for (iter of tracks) {
  833. addTrackPerformers(iter.track_artist);
  834. addTrackPerformers(iter.performer);
  835. addArtists(2, iter.remixer);
  836. addArtists(3, iter.composer);
  837. addArtists(4, iter.conductor);
  838. addArtists(5, iter.compiler);
  839. addArtists(6, iter.producer);
  840.  
  841. if (iter.title) {
  842. featParsers.slice(3).forEach(function(rx, __a, ndx) {
  843. matches = rx.exec(iter.title);
  844. if (matches != null && (ndx < 2 || splitArtists(matches[1]).every((artist) => looksLikeTrueName(artist, 1)))) {
  845. iter.track_artist = (!isVA && (!iter.track_artist || iter.track_artist.includes(matches[1])) ?
  846. iter.artist : iter.track_artist) + ' feat. ' + matches[1];
  847. addArtists(1, matches[1]);
  848. addMessage('Warning: featured artist(s) in track title (#' + iter.tracknumber + ': ' + iter.title + ')', 'ua-warning');
  849. iter.title = iter.title.replace(rx, '');
  850. }
  851. });
  852. remixParsers.slice(3).forEach(rx => { if (rx.test(iter.title)) addArtists(2, RegExp.$1) });
  853. }
  854. }
  855. for (i = 0; i < Math.round(tracks.length / 2); ++i) splitAmpersands();
  856.  
  857. function addArtists(ndx, str) {
  858. if (str) splitArtists(str).forEach(function(artist) {
  859. artist = ndx != 0 ? artist.replace(noAKAs, '') : guessOtherArtists(artist);
  860. if (artist.length > 0 && !pseudoArtistParsers.some(rx => rx.test(artist))
  861. && !artists[ndx].includesCaseless(artist)
  862. && !roleCollisions[ndx].some(n => artists[n].includesCaseless(artist))) artists[ndx].push(artist);
  863. });
  864. }
  865. function addTrackPerformers(str) {
  866. if (str) splitArtists(spliceGuests(str, 1)).forEach(function(artist) {
  867. artist = guessOtherArtists(artist);
  868. if (artist.length > 0 && !pseudoArtistParsers.some(rx => rx.test(artist))
  869. && !artists[0].includesCaseless(artist)
  870. && (isVA || !artists[1].includesCaseless(artist))) artists[isVA ? 0 : 1].push(artist);
  871. });
  872. }
  873. function splitArtists(str) {
  874. var result = [str];
  875. multiArtistParsers.forEach(function(multiArtistParser) {
  876. for (i = result.length; i > 0; --i) {
  877. var j = result[i - 1].split(multiArtistParser);
  878. if (j.length >= 2 && j.every(twoOrMore)
  879. && !j.some(artist => pseudoArtistParsers.some(rx => rx.test(artist)))
  880. && !getSiteArtist(result[i - 1])) result.splice(i - 1, 1, ...j);
  881. }
  882. });
  883. return result;
  884. }
  885. function splitAmpersands() {
  886. for (var ndx = 0; ndx < artists.length; ++ndx) {
  887. ampersandParsers.forEach(function(ampersandParser) {
  888. for (var i = artists[ndx].length; i > 0; --i) {
  889. var j = artists[ndx][i - 1].split(ampersandParser);
  890. if (j.length >= 2 && j.every(twoOrMore) && !getSiteArtist(artists[ndx][i - 1])
  891. && (j.some(it1 => artists.some(it2 => it2.includesCaseless(it1))) || j.every(looksLikeTrueName))) {
  892. artists[ndx].splice(i - 1, 1, ...j.filter(function(artist) {
  893. return !artists[ndx].includesCaseless(artist)
  894. && !pseudoArtistParsers.some(rx => rx.test(artist))
  895. && !roleCollisions[ndx].some(n => artists[n].includesCaseless(artist));
  896. }));
  897. }
  898. }
  899. });
  900. }
  901. }
  902. function spliceGuests(str, level = 1) {
  903. (level ? featParsers.slice(level) : featParsers).forEach(function(it) {
  904. if (it.test(str)) {
  905. addArtists(1, RegExp.$1);
  906. str = str.replace(it, '');
  907. }
  908. });
  909. return str;
  910. }
  911. function guessOtherArtists(name) {
  912. otherArtistsParsers.forEach(function(it) {
  913. if (!it[0].test(name)) return;
  914. addArtists(it[1], RegExp.$2);
  915. name = RegExp.$1;
  916. });
  917. return name.replace(noAKAs, '');
  918. }
  919. function getSiteArtist(artist) {
  920. if (!artist) return null;
  921. xhr.open('GET', 'https://' + document.domain + '/ajax.php?action=artist&artistname=' + encodeURIComponent(artist), false);
  922. xhr.send();
  923. if (xhr.readyState != 4 || xhr.status != 200) {
  924. console.log('getSiteArtist("' + artist + '"): XMLHttpRequest readyState:' + xhr.readyState + ' status:' + xhr.status);
  925. return undefined; // error
  926. }
  927. var response = JSON.parse(xhr.responseText);
  928. return response.status == 'success' ? response.response : null;
  929. }
  930. function twoOrMore(artist) { return artist.length >= 2 && !pseudoArtistParsers.some(rx => rx.test(artist)) };
  931. function looksLikeTrueName(artist, index = 0) {
  932. return (index == 0 || !/^(?:The|his|her|Friends)\s+/i.test(artist)) && artist.split(/\s+/).length >= 2
  933. && !pseudoArtistParsers.some(rx => rx.test(artist)) || getSiteArtist(artist);
  934. }
  935.  
  936. if (elementWritable(document.getElementById('artist'))) {
  937. let artistIndex = 0;
  938. catLoop: for (i = 0; i < 7; ++i) for (iter of artists[i]
  939. .filter(artist => !roleCollisions[i].some(n => artists[n].includesCaseless(artist)))
  940. .sort((a, b) => a.localeCompare(b))) {
  941. if (isUpload) {
  942. var id = 'artist';
  943. if (artistIndex > 0) id += '_' + artistIndex;
  944. while ((ref = document.getElementById(id)) == null) addArtistField();
  945. } else {
  946. while ((ref = document.querySelectorAll('input[name="artists[]"]')).length <= artistIndex) addArtistField();
  947. ref = ref[artistIndex];
  948. }
  949. if (ref == null) throw new Error('Failed to allocate artist fields');
  950. ref.value = iter;
  951. ref.nextElementSibling.value = i + 1;
  952. if (++artistIndex >= 200) break catLoop;
  953. }
  954. if (overwrite && artistIndex > 0) while (document.getElementById('artist_' + artistIndex) != null) {
  955. removeArtistField();
  956. }
  957. }
  958.  
  959. // Processing album title
  960. const remasterParsers = [
  961. /\s+\(((?:Remaster(?:ed)?|Reissu(?:ed)?|Deluxe|Enhanced|Expanded|Limited)\b[^\(\)]*|[^\(\)]*\b(?:Edition|Version|Promo|Release))\)$/i,
  962. /\s+\[((?:Remaster(?:ed)?|Reissu(?:ed)?|Deluxe|Enhanced|Expanded|Limited)\b[^\[\]]*|[^\[\]]*\b(?:Edition|Version|Promo|Release))\]$/i,
  963. /\s+-\s+([^\[\]\(\)\-\−\—\–]*\b(?:(?:Remaster(?:ed)?|Bonus\s+Track)\b[^\[\]\(\)\-\−\—\–]*|Reissue|Edition|Version|Promo|Enhanced|Release))$/i
  964. ];
  965. const mediaParsers = [
  966. [/\s+(?:\[(?:LP|Vinyl|12"|7")\]|\((?:LP|Vinyl|12"|7")\))$/, 'Vinyl'],
  967. [/\s+(?:\[SA-?CD\]|\(SA-?CD\))$/, 'SACD'],
  968. [/\s+(?:\[(?:Blu[\s\-\−\—\–]?Ray|BD|BRD?)\]|\((?:Blu[\s\-\−\—\–]?Ray|BD|BRD?)\))$/, 'Blu-Ray'],
  969. [/\s+(?:\[DVD(?:-?A)?\]|\(DVD(?:-?A)?\))$/, 'DVD'],
  970. ];
  971. const releaseTypeParsers = [
  972. [/\s+(?:-\s+Single|\[Single\]|\(Single\))$/i, 'Single', true, true],
  973. [/\s+(?:(?:-\s+)?EP|\[EP\]|\(EP\))$/, 'EP', true, true],
  974. [/\s+\((?:Live|En\s+directo?|Ao\s+Vivo)\b[^\(\)]*\)$/i, 'Live album', false, false],
  975. [/\s+\[(?:Live|En\s+directo?|Ao\s+Vivo)\b[^\[\]]*\]$/i, 'Live album', false, false],
  976. [/(?:^Live\s+(?:[aA]t|[Ii]n)\b|^Directo?\s+[Ee]n\b|\bUnplugged\b|\bAcoustic\s+Stage\b|\s+Live$)/, 'Live album', false, false],
  977. [/\b(?:(?:Best [Oo]f|Greatest\s+Hits|Complete\s+(.+?\s+)(?:Albums|Recordings))\b|Collection$)/, 'Anthology', false, false],
  978. ];
  979. var album = release.album;
  980. releaseTypeParsers.forEach(function(it) {
  981. if (it[0].test(album)) {
  982. if (it[2] || !releaseType) releaseType = getReleaseIndex(it[1]);
  983. if (it[3]) album = album.replace(it[0], '');
  984. }
  985. });
  986. rx = '\\b(?:Soundtrack|Score|Motion\\s+Picture|Series|Television|Original(?:\\s+\\w+)?\\s+Cast|Music\\s+from|(?:Musique|Bande)\\s+originale)\\b';
  987. if (reInParenthesis(rx).test(album) || reInBrackets(rx).test(album)) {
  988. if (!releaseType) releaseType = getReleaseIndex('Soundtrack');
  989. tags.add('score');
  990. composerEmphasis = true;
  991. }
  992. remixParsers.forEach(function(rx) {
  993. if (rx.test(album) && !releaseType) releaseType = getReleaseIndex('Remix');
  994. });
  995. remasterParsers.forEach(function(rx) {
  996. if (rx.test(album)) {
  997. album = album.replace(rx, '');
  998. editionTitle = RegExp.$1;
  999. }
  1000. });
  1001. mediaParsers.forEach(function(it) {
  1002. if (it[0].test(album)) {
  1003. album = album.replace(it[0], '');
  1004. media = it[1];
  1005. }
  1006. });
  1007. if (elementWritable(ref = document.getElementById('title') || document.querySelector('input[name="title"]'))) {
  1008. ref.value = album;
  1009. }
  1010.  
  1011. if (yadg_prefil) yadg_prefil += ' ';
  1012. yadg_prefil += album;
  1013. if (elementWritable(ref = document.getElementById('yadg_input'))) {
  1014. ref.value = yadg_prefil || '';
  1015. if (yadg_prefil && (ref = document.getElementById('yadg_submit')) != null && !ref.disabled) ref.click();
  1016. }
  1017.  
  1018. if (!release.album_year && tracks.every(function(tr) {
  1019. return tr.identifiers.PUBYEAR && tr.identifiers.PUBYEAR == tracks[0].identifiers.PUBYEAR;
  1020. })) release.album_year = parseInt(tracks[0].identifiers.PUBYEAR);
  1021. if (elementWritable(ref = document.getElementById('year'))) {
  1022. ref.value = release.album_year || '';
  1023. }
  1024. i = release.release_date && extractYear(release.release_date);
  1025. if (elementWritable(ref = document.getElementById('remaster_year'))
  1026. || !isUpload && i > 0 && (ref = document.querySelector('input[name="year"]')) != null && !ref.disabled) {
  1027. ref.value = i || '';
  1028. }
  1029. //if (tracks.every(it => it.identifiers.EXPLICIT == '0')) editionTitle = 'Clean' + (editionTitle ? ' / ' + editionTitle : '');
  1030. if (!editionTitle && (tracks.every(it => it.title.endsWith(' (Remastered)') || it.title.endsWith(' [Remastered]')))) {
  1031. editionTitle = 'Remastered';
  1032. }
  1033. if (elementWritable(ref = document.getElementById('remaster_title'))) {
  1034. ref.value = editionTitle || '';
  1035. }
  1036. rx = /\s*[\,\;]\s*/g;
  1037. if (elementWritable(ref = document.getElementById('remaster_record_label') || document.querySelector('input[name="recordlabel"]'))) {
  1038. ref.value = release.label && release.label.replace(rx, ' / ') || '';
  1039. }
  1040. if (elementWritable(ref = document.getElementById('remaster_catalogue_number') || document.querySelector('input[name="cataloguenumber"]'))) {
  1041. let barcode = tracks.every(function(it, ndx, arr) {
  1042. return it.identifiers.BARCODE && it.identifiers.BARCODE == arr[0].identifiers.BARCODE;
  1043. }) && tracks[0].identifiers.BARCODE;
  1044. ref.value = release.catalogs.length >= 1 && release.catalogs.map(k => k.replace(rx, ' / ')).join(' / ')
  1045. || barcode || '';
  1046. }
  1047. var br_isSet = (ref = document.getElementById('bitrate')) != null && ref.value;
  1048. if (elementWritable(ref = document.getElementById('format'))) {
  1049. ref.value = release.codec || '';
  1050. ref.onchange(); //exec(function() { Format() });
  1051. }
  1052. if (isRequestNew) {
  1053. if (prefs.always_request_perfect_flac) reqSelectFormats('FLAC');
  1054. else if (release.codec) reqSelectFormats(release.codec);
  1055. }
  1056. var sel;
  1057. if (release.encoding == 'lossless') {
  1058. sel = release.bds.includes(24) ? '24bit Lossless' : 'Lossless';
  1059. } else if (release.bitrates.length >= 1) {
  1060. let lame_version = release.codec == 'MP3' && /^LAME(\d+)\.(\d+)/i.test(release.vendor) ?
  1061. parseInt(RegExp.$1) * 1000 + parseInt(RegExp.$2) : undefined;
  1062. if (release.codec == 'MP3' && release.codec_profile == 'VBR V0') {
  1063. sel = lame_version >= 3094 ? 'V0 (VBR)' : 'APX (VBR)'
  1064. } else if (release.codec == 'MP3' && release.codec_profile == 'VBR V1') {
  1065. sel = 'V1 (VBR)'
  1066. } else if (release.codec == 'MP3' && release.codec_profile == 'VBR V2') {
  1067. sel = lame_version >= 3094 ? sel = 'V2 (VBR)' : 'APS (VBR)'
  1068. } else if (release.bitrates.length == 1 && [192, 256, 320].includes(Math.round(release.bitrates[0]))) {
  1069. sel = Math.round(release.bitrates[0]);
  1070. } else {
  1071. sel = 'Other';
  1072. }
  1073. }
  1074. if ((ref = document.getElementById('bitrate')) != null && !ref.disabled && (overwrite || !br_isSet)) {
  1075. ref.value = sel || '';
  1076. ref.onchange(); //exec(function() { Bitrate() });
  1077. if (sel == 'Other' && (ref = document.getElementById('other_bitrate')) != null) {
  1078. ref.value = Math.round(release.bitrates.length == 1 ? release.bitrates[0] : albumBitrate);
  1079. if ((ref = document.getElementById('vbr')) != null) ref.checked = release.bitrates.length > 1;
  1080. }
  1081. }
  1082. if (isRequestNew) {
  1083. if (prefs.always_request_perfect_flac) {
  1084. reqSelectBitrates('Lossless', '24bit Lossless');
  1085. } else if (sel) reqSelectBitrates(sel);
  1086. }
  1087. if (release.media) {
  1088. sel = undefined;
  1089. [
  1090. [/\b(?:WEB|File|Download|digital\s+media)\b/i, 'WEB'],
  1091. [/\bCD\b/, 'CD'],
  1092. [/\b(?:SA-?CD|[Hh]ybrid)\b/, 'SACD'],
  1093. [/\b(?:[Bb]lu[\-\−\—\–\s]?[Rr]ay|BRD?|BD)\b/, 'Blu-Ray'],
  1094. [/\bDVD(?:-?A)?\b/, 'DVD'],
  1095. [/\b(?:[Vv]inyl\b|LP\b|12"|7")/, 'Vinyl'],
  1096. ].forEach(k => { if (k[0].test(release.media)) sel = k[1] });
  1097. media = sel || media;
  1098. }
  1099. if (!media) {
  1100. if (tracks.every(isRedBook)) {
  1101. addMessage('Info: media not determined - CD estimated', 'ua-info');
  1102. media = 'CD';
  1103. } else if (tracks.some(t => t.bd > 16 || (t.sr > 0 && t.sr != 44100) || t.samples > 0 && t.samples % 588 != 0)) {
  1104. addMessage('Info: media not determined - NOT CD', 'ua-info');
  1105. }
  1106. } else if (media != 'CD' && tracks.every(isRedBook)) {
  1107. addMessage('Info: CD as source media is estimated (' + media + ')', 'ua-info');
  1108. }
  1109. if (elementWritable(ref = document.getElementById('media'))) ref.value = media || '';
  1110. if (isRequestNew) {
  1111. if (prefs.always_request_perfect_flac) reqSelectMedias('WEB', 'CD', 'Blu-Ray', 'DVD', 'SACD')
  1112. else if (media) reqSelectMedias(media);
  1113. }
  1114. function isRedBook(t) {
  1115. return t.bd == 16 && t.sr == 44100 && t.channels == 2 && t.samples > 0 && t.samples % 588 == 0;
  1116. }
  1117. if (media == 'WEB') for (iter of tracks) {
  1118. if (iter.duration > 29.5 && iter.duration < 30.5) {
  1119. addMessage('Warning: track ' + iter.tracknumber + ' possible preview', 'ua-warning');
  1120. }
  1121. }
  1122. if (tracks.every(it => it.identifiers.ORIGINALFORMAT && it.identifiers.ORIGINALFORMAT.includes('DSD'))) {
  1123. isFromDSD = true;
  1124. }
  1125. // Release type
  1126. if (!releaseType) {
  1127. if (tracks.every(it => it.title.endsWith(' (Live)') || it.title.endsWith(' [Live]'))) {
  1128. releaseType = getReleaseIndex('Live album');
  1129. } else if (tracks.every(function(it) {
  1130. const p = /^([^\(\)\[\]]+?)(?:\s+(?:\([^\(\)]*\)|\[[^\[\]]*\]))?$/;
  1131. try { return p.exec(it.title)[1] == p.exec(tracks[0].title)[1] } catch(e) { return false }
  1132. })) {
  1133. releaseType = getReleaseIndex('Single');
  1134. } else if (/\b(?:Mixtape)\b/i.test(release.album)) {
  1135. releaseType = getReleaseIndex('Mixtape');
  1136. } else if (isVA) {
  1137. releaseType = getReleaseIndex('Compilation');
  1138. } else if (tracks.every(it => it.identifiers.COMPILATION == 1)) {
  1139. releaseType = getReleaseIndex('Anthology');
  1140. }
  1141. }
  1142. if ((ref = document.getElementById('releasetype')) != null && !ref.disabled && (overwrite || ref.value == 0)) {
  1143. ref.value = releaseType || getReleaseIndex('Album');
  1144. }
  1145. // Tags
  1146. if (release.genres.length > 0) {
  1147. const classicalGenreParsers = [
  1148. /\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,
  1149. ];
  1150. release.genres.forEach(function(genre) {
  1151. classicalGenreParsers.forEach(function(classicalGenreParser) {
  1152. if (classicalGenreParser.test(genre) && !/\b(?:metal|rock|pop)\b/i.test(genre)) {
  1153. composerEmphasis = true;
  1154. isClassical = true
  1155. }
  1156. });
  1157. if (/\b(?:Jazz|Vocal)\b/i.test(genre) && !/\b(?:Nu|Future|Acid)[\s\-\−\—\–]*Jazz\b/i.test(genre)
  1158. && !/\bElectr(?:o|ic)[\s\-\−\—\–]?Swing\b/i.test(genre)) {
  1159. composerEmphasis = true;
  1160. }
  1161. if (/\b(?:Soundtracks?|Score|Films?|Games?|Video|Series?|Theatre|Musical)\b/i.test(genre)) {
  1162. if (!releaseType) releaseType = getReleaseIndex('Soundtrack');
  1163. composerEmphasis = true;
  1164. }
  1165. if (/\b(?:Christmas\s+Music)\b/i.test(genre)) {
  1166. composerEmphasis = true;
  1167. }
  1168. tags.add(genre);
  1169. });
  1170. if (release.genres.length > 1) {
  1171. addMessage('Warning: inconsistent genre accross album: ' + release.genres, 'ua-warning');
  1172. }
  1173. }
  1174. if (prefs.estimate_decade_tag && (isNaN(totalTime) || totalTime < 2 * 60 * 60)
  1175. && release.album_year > 1900 && [1, 3, 5, 9, 13, undefined].includes(releaseType)
  1176. && !/\b(?:Remaster(?:ed)?|Reissue|Anniversary|Collector(?:'?s)?)\b/i.test(editionTitle))
  1177. tags.add(Math.floor(release.album_year/10) * 10 + 's'); // experimental
  1178. if (release.country) {
  1179. if (!excludedCountries.some(it => it.test(release.country))) tags.add(release.country);
  1180. }
  1181. if (elementWritable(ref = document.getElementById('tags'))) {
  1182. ref.value = tags.toString();
  1183. if (artists[0].length == 1 && prefs.fetch_tags_from_artist > 0) setTimeout(function() {
  1184. var artist = getSiteArtist(artists[0][0]);
  1185. if (!artist) return;
  1186. tags.add(...artist.tags.sort((a, b) => b.count - a.count).map(it => it.name).slice(0, prefs.fetch_tags_from_artist));
  1187. var ref = document.getElementById('tags');
  1188. ref.value = tags.toString();
  1189. }, 3000);
  1190. }
  1191.  
  1192. if (isClassical && !tracks.every(it => it.composer)) {
  1193. addMessage('Warning: all tracks composers must be defined for clasical music' + ruleLink('2.3.17'), 'ua-warning', true);
  1194. //return false;
  1195. }
  1196. if (!composerEmphasis && !prefs.keep_meaningles_composers) {
  1197. document.querySelectorAll('input[name="artists[]"]').forEach(function(i) {
  1198. if (['4', '5'].includes(i.nextElementSibling.value)) i.value = '';
  1199. });
  1200. }
  1201. const doubleParsParsers = [
  1202. /\(+(\([^\(\)]*\))\)+/,
  1203. /\[+(\[[^\[\]]*\])\]+/,
  1204. /\{+(\{[^\{\}]*\})\}+/,
  1205. ];
  1206. for (iter of tracks) {
  1207. doubleParsParsers.forEach(function(rx) {
  1208. if (rx.test(iter.title)) {
  1209. addMessage('Warning: doubled parentheses in track #' + iter.tracknumber +
  1210. ' title ("' + iter.title + '")', 'ua-warning');
  1211. //iter.title.replace(rx, RegExp.$1);
  1212. }
  1213. });
  1214. }
  1215. if (tracks.length > 1 && array_homogenous(tracks.map(k => k.title))) {
  1216. addMessage('Warning: all tracks having same title: ' + tracks[0].title, 'ua-warning');
  1217. }
  1218. if (isUpload) findPreviousUploads();
  1219. // Album description
  1220. url = release.urls.length == 1 && release.urls[0];
  1221. function makeUrlFromId(identifier, urlBase) {
  1222. if (!url && tracks.every(track => track.identifiers[identifier]
  1223. && track.identifiers[identifier] == tracks[0].identifiers[identifier])) {
  1224. url = urlBase + tracks[0].identifiers[identifier];
  1225. }
  1226. }
  1227. makeUrlFromId('DISCOGS_ID', 'https://www.discogs.com/release/');
  1228. makeUrlFromId('ITUNES_ID', 'https://music.apple.com/album/');
  1229. makeUrlFromId('APPLE_ID', 'https://music.apple.com/album/');
  1230. makeUrlFromId('SPOTIFY_ID', 'https://open.spotify.com/album/');
  1231. makeUrlFromId('DEEZER_ID', 'https://www.deezer.com/album/');
  1232. makeUrlFromId('PROSTUDIOMASTERS_ID', 'https://www.prostudiomasters.com/album/page/');
  1233. const vinylTest = /^((?:Vinyl|LP) rip by\s+)(.*)$/im;
  1234. const vinyltrackParser = /^([A-Z])[\-\.\s]?((\d+)(?:\.\d+)?)$/;
  1235. const classicalWorkParsers = [
  1236. /^(.*\S):\s+(.*)$/,
  1237. /^(.+?):\s+([IVXC]+\.\s+.*)$/,
  1238. ];
  1239. var description;
  1240. if (isRequestNew || isRequestEdit) { // request
  1241. description = []
  1242. if (release.release_date) {
  1243. i = new Date(release.release_date);
  1244. let today = new Date(new Date().toDateString());
  1245. description.push((isNaN(i) || i < today ? 'Released' : 'Releasing') + ' ' +
  1246. (isNaN(i) ? release.release_date : i.toDateString()));
  1247. if ((ref = document.getElementById('tags')) != null && !ref.disabled) {
  1248. let tags = new TagManager(ref.value);
  1249. if (prefs.upcoming_tags && i >= today) tags.add(prefs.upcoming_tags);
  1250. ref.value = tags.toString();
  1251. }
  1252. }
  1253. let summary = '';
  1254. if (totalDiscs > 1) summary += totalDiscs + 'discs, ';
  1255. summary += tracks.length + ' track(s)';
  1256. if (totalTime > 0) summary += ', ' + makeTimeString(totalTime);
  1257. description.push(summary);
  1258. if (url) description.push('[url]' + url + '[/url]');
  1259. if (release.catalogs.length == 1 && /^\d{10,}$/.test(release.catalogs[0])
  1260. || tracks.every(it => it.identifiers.BARCODE && it.identifiers.BARCODE == tracks[0].identifiers.BARCODE)
  1261. && /^\d{10,}$/.test(tracks[0].identifiers.BARCODE)) {
  1262. description.push('[url=https://www.google.com/search?q=' + RegExp.lastMatch + ']Find more stores...[/url]');
  1263. }
  1264. if (release.comments.length == 1) description.push(release.comments[0]);
  1265. description = genAlbumHeader().concat(description.join('\n\n'));
  1266. if (description.length > 0) {
  1267. ref = document.getElementById('description');
  1268. if (elementWritable(ref)) {
  1269. ref.value = description;
  1270. } else if (isRequestEdit && ref != null && !ref.disabled) {
  1271. ref.value = ref.textLength > 0 ? ref.value.concat('\n\n', description) : ref.value = description;
  1272. preview(0);
  1273. }
  1274. }
  1275. } else { // upload
  1276. description = '';
  1277. let vinylRipInfo;
  1278. if (release.comments.length == 1 && release.comments[0]) {
  1279. description = '\n\n';
  1280. if ((matches = vinylTest.exec(release.comments[0])) != null) {
  1281. vinylRipInfo = release.comments[0].slice(matches.index).trim().split(/(?:[ \t]*\r?\n)+/);
  1282. description += release.comments[0].slice(0, matches.index).trim();
  1283. } else description += release.comments[0];
  1284. }
  1285. if (elementWritable(ref = document.getElementById('album_desc'))) {
  1286. ref.value = genPlaylist().concat(description);
  1287. preview(0);
  1288. }
  1289. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  1290. if (ref.textLength == 0) ref.value = genPlaylist().concat(description); else {
  1291. let editioninfo = '';
  1292. if (editionTitle) {
  1293. editioninfo = '[size=5][b]' + editionTitle;
  1294. if (release.release_date && (i = extractYear(release.release_date)) > 0) editioninfo += ' (' + i + ')';
  1295. editioninfo += '[/b][/size]\n\n';
  1296. }
  1297. ref.value = ref.value.concat('\n\n', editioninfo, genPlaylist(false, false), description);
  1298. }
  1299. preview(0);
  1300. }
  1301. // Release description
  1302. var lineage = '', comment = '', drinfo, srcinfo;
  1303. if (elementWritable(ref = document.getElementById('release_samplerate'))) {
  1304. ref.value = Object.keys(release.srs).length == 1 ? Math.floor(Object.keys(release.srs)[0] / 1000) :
  1305. Object.keys(release.srs).length > 1 ? '999' : null;
  1306. }
  1307. if (Object.keys(release.srs).length > 0) {
  1308. let kHz = Object.keys(release.srs).sort((a, b) => release.srs[b] - release.srs[a])
  1309. .map(f => f / 1000).join('/').concat('kHz');
  1310. if (release.bds.some(bd => bd > 16)) {
  1311. drinfo = '[hide=DR' + (release.drs.length == 1 ? release.drs[0] : '') + '][pre][/pre]';
  1312. if (media == 'Vinyl') {
  1313. let hassr = ref == null || Object.keys(release.srs).length > 1;
  1314. lineage = hassr ? kHz + ' ' : '';
  1315. if (vinylRipInfo) {
  1316. vinylRipInfo[0] = vinylRipInfo[0].replace(vinylTest, '$1[color=blue]$2[/color]');
  1317. if (hassr) { vinylRipInfo[0] = vinylRipInfo[0].replace(/^Vinyl\b/, 'vinyl') }
  1318. lineage += vinylRipInfo[0] + '\n\n[u]Lineage:[/u]' +
  1319. vinylRipInfo.slice(1).map(function(l) {
  1320. return '\n' + l
  1321. // russian translation
  1322. .replace('Код класса состояния винила:', 'Vinyl condition class:')
  1323. .replace('Устройство воспроизведения:', 'Turntable:')
  1324. .replace('Головка звукоснимателя:', 'Cartridge:')
  1325. .replace('Предварительный усилитель:', 'Preamplifier:')
  1326. .replace('АЦП:', 'ADC:')
  1327. .replace('Программа-оцифровщик:', 'Software:')
  1328. .replace('Обработка:', 'Post-processing:');
  1329. }).join('');
  1330. } else {
  1331. lineage += (hassr ? 'Vinyl' : ' vinyl') + ' rip by [color=blue][/color]\n\n[u]Lineage:[/u]\n';
  1332. }
  1333. drinfo += '\n\n[img][/img]\n[img][/img]\n[img][/img][/hide]';
  1334. } else if (['Blu-Ray', 'DVD', 'SACD'].includes(media)) {
  1335. lineage = ref ? '' : kHz;
  1336. if (release.channels) add_channel_info();
  1337. if (media == 'SACD' || isFromDSD) {
  1338. lineage += ' from DSD64 using foobar2000\'s SACD decoder (direct-fp64)';
  1339. lineage += '\nOutput gain +0dB';
  1340. }
  1341. drinfo += '[/hide]';
  1342. //add_rg_info();
  1343. } else { // WEB Hi-Res
  1344. if (ref == null || Object.keys(release.srs).length > 1) lineage = kHz;
  1345. if (release.channels && release.channels != 2) add_channel_info();
  1346. if (isFromDSD) {
  1347. lineage += ' from DSD64 using foobar2000\'s SACD decoder (direct-fp64)';
  1348. lineage += '\nOutput gain +0dB';
  1349. } else {
  1350. add_dr_info();
  1351. }
  1352. //if (lineage.length > 0) add_rg_info();
  1353. if (release.bds.length > 1) release.bds.filter(bd => bd != 24).forEach(function(bd) {
  1354. let hybrid_tracks = tracks.filter(it => it.bd == bd).sort(trackComparer).map(function(it) {
  1355. return (totalDiscs > 1 && it.discnumber ? it.discnumber + '-' : '').concat(it.tracknumber);
  1356. });
  1357. if (hybrid_tracks.length < 1) return;
  1358. if (lineage) lineage += '\n';
  1359. lineage += 'Note: track';
  1360. if (hybrid_tracks.length > 1) lineage += 's';
  1361. lineage += ' #' + hybrid_tracks.join(', ') +
  1362. (hybrid_tracks.length > 1 ? ' are' : ' is') + ' ' + bd + 'bit lossless';
  1363. });
  1364. if (Object.keys(release.srs).length == 1 && Object.keys(release.srs)[0] == 88200 || isFromDSD) {
  1365. drinfo += '[/hide]';
  1366. } else {
  1367. drinfo = null;
  1368. }
  1369. }
  1370. } else { // 16bit or lossy
  1371. if (Object.keys(release.srs).some(f => f != 44100)) lineage = kHz;
  1372. if (release.channels && release.channels != 2) add_channel_info();
  1373. //add_dr_info();
  1374. //if (lineage.length > 0) add_rg_info();
  1375. if (['AAC', 'Opus', 'Vorbis'].includes(release.codec) && release.vendor) {
  1376. let _encoder_settings = release.vendor;
  1377. if (release.codec == 'AAC' && /^qaac\s+[\d\.]+/i.test(release.vendor)) {
  1378. let enc = [];
  1379. if (matches = release.vendor.match(/\bqaac\s+([\d\.]+)\b/i)) enc[0] = matches[1];
  1380. if (matches = release.vendor.match(/\bCoreAudioToolbox\s+([\d\.]+)\b/i)) enc[1] = matches[1];
  1381. if (matches = release.vendor.match(/\b(AAC-\S+)\s+Encoder\b/i)) enc[2] = matches[1];
  1382. if (matches = release.vendor.match(/\b([TC]VBR|ABR|CBR)\s+(\S+)\b/)) { enc[3] = matches[1]; enc[4] = matches[2]; }
  1383. if (matches = release.vendor.match(/\bQuality\s+(\d+)\b/i)) enc[5] = matches[1];
  1384. _encoder_settings = 'Converted by Apple\'s ' + enc[2] + ' encoder (' + enc[3] + '-' + enc[4] + ')';
  1385. }
  1386. if (lineage) lineage += '\n\n';
  1387. lineage += _encoder_settings;
  1388. }
  1389. }
  1390. }
  1391. function add_dr_info() {
  1392. if (release.drs.length != 1 || document.getElementById('release_dynamicrange') != null) return false;
  1393. if (lineage.length > 0) lineage += ' | ';
  1394. if (release.drs[0] < 4) lineage += '[color=red]';
  1395. lineage += 'DR' + release.drs[0];
  1396. if (release.drs[0] < 4) lineage += '[/color]';
  1397. return true;
  1398. }
  1399. function add_rg_info() {
  1400. if (release.rgs.length != 1) return false;
  1401. if (lineage.length > 0) lineage += ' | ';
  1402. lineage += 'RG'; //lineage += 'RG ' + rgs[0];
  1403. return true;
  1404. }
  1405. function add_channel_info() {
  1406. if (!release.channels) return false;
  1407. let chi = getChanString(release.channels);
  1408. if (lineage.length > 0 && chi.length > 0) lineage += ', ';
  1409. lineage += chi;
  1410. return chi.length > 0;
  1411. }
  1412. if (url) srcinfo = '[url]' + url + '[/url]';
  1413. if ((ref = document.getElementById('release_lineage')) != null) {
  1414. if (elementWritable(ref)) {
  1415. if (drinfo) comment = drinfo;
  1416. if (lineage && srcinfo) lineage += '\n\n';
  1417. if (srcinfo) lineage += srcinfo;
  1418. ref.value = lineage;
  1419. preview(1);
  1420. }
  1421. } else {
  1422. comment = lineage;
  1423. if (comment && drinfo) comment += '\n\n';
  1424. if (drinfo) comment += drinfo;
  1425. if (comment && srcinfo) comment += '\n\n';
  1426. if (srcinfo) comment += srcinfo;
  1427. }
  1428. if (elementWritable(ref = document.getElementById('release_desc'))) {
  1429. ref.value = comment;
  1430. if (comment.length > 0) preview(isNWCD ? 2 : 1);
  1431. }
  1432. if (release.encoding == 'lossless' && release.codec == 'FLAC'
  1433. && release.bds.includes(24) && release.dirpaths.length == 1) {
  1434. var uri = new URL(release.dirpaths[0] + '\\foo_dr.txt');
  1435. GM_xmlhttpRequest({
  1436. method: 'GET',
  1437. url: uri.href,
  1438. responseType: 'blob',
  1439. onload: function(response) {
  1440. if (response.readyState != 4 || !response.responseText) return;
  1441. var rlsDesc = document.getElementById('release_lineage') || document.getElementById('release_desc');
  1442. if (rlsDesc == null) return;
  1443. var value = rlsDesc.value;
  1444. matches = value.match(/(^\[hide=DR\d*\]\[pre\])\[\/pre\]/im);
  1445. if (matches == null) return;
  1446. var index = matches.index + matches[1].length;
  1447. rlsDesc.value = value.slice(0, index).concat(response.responseText, value.slice(index));
  1448. }
  1449. });
  1450. }
  1451. }
  1452. if (elementWritable(document.getElementById('image') || document.querySelector('input[name="image"]'))) {
  1453. if (tracks.every(track => track.identifiers.IMGURL && track.identifiers.IMGURL == tracks[0].identifiers.IMGURL)) {
  1454. setImage(tracks[0].identifiers.IMGURL);
  1455. } else {
  1456. if (/^https?:\/\/(\w+\.)?discogs\.com\/release\/[\w\-]+\/?$/i.test(url)) url += '/images';
  1457. getCoverOnline(url);
  1458. }
  1459. }
  1460. // } else if (elementWritable(document.getElementById('image') || document.querySelector('input[name="image"]'))
  1461. // && ((ref = document.getElementById('album_desc')) != null || (ref = document.getElementById('body')) != null)
  1462. // && ref.textLength > 0 && (matches = ref.value.matchAll(/\b(https?\/\/[\w\-\&\_\?\=]+)/i)) != null) {
  1463.  
  1464. if (elementWritable(ref = document.getElementById('release_dynamicrange'))) {
  1465. ref.value = release.drs.length == 1 ? release.drs[0] : '';
  1466. }
  1467. if (isRequestNew && prefs.request_default_bounty > 0) {
  1468. let amount = prefs.request_default_bounty < 1024 ? prefs.request_default_bounty : prefs.request_default_bounty / 1024;
  1469. if ((ref = document.getElementById('amount_box')) != null && !ref.disabled) ref.value = amount;
  1470. if ((ref = document.getElementById('unit')) != null && !ref.disabled) {
  1471. ref.value = prefs.request_default_bounty < 1024 ? 'mb' : 'gb';
  1472. }
  1473. exec(function() { Calculate() });
  1474. }
  1475. if (prefs.clean_on_apply) clipBoard.value = '';
  1476. prefs.save();
  1477. return true;
  1478.  
  1479. function genPlaylist(pad = true, header = true) {
  1480. var playlist = '';
  1481. if (tracks.length > 1) {
  1482. if (pad && isRED) playlist += '[pad=5|0|0|0]';
  1483. if (header) playlist += genAlbumHeader();
  1484. playlist += '[size=4][color=' + prefs.tracklist_head_color + '][b]Tracklisting[/b][/color][/size]';
  1485. if (pad && isRED) playlist += '[/pad]';
  1486. playlist += '\n'; //'[hr]';
  1487. let lastDisc, lastSubtitle, lastWork, lastSide, vinylTrackWidth;
  1488. let block = 0, classicalWorks = new Map();
  1489. if (composerEmphasis /*isClassical*/ && !tracks.some(it => it.discsubtitle)) {
  1490. tracks.forEach(function(track) {
  1491. (isClassical ? classicalWorkParsers : classicalWorkParsers.slice(1)).forEach(function(classicalWorkParser) {
  1492. if (track.classical_work || !classicalWorkParser.test(track.title)) return;
  1493. classicalWorks.set(track.classical_work = RegExp.$1, {});
  1494. track.classical_title = RegExp.$2;
  1495. });
  1496. });
  1497. for (iter of classicalWorks.keys()) {
  1498. let work = tracks.filter(track => track.classical_work == iter);
  1499. if (array_homogenous(work.map(it => it.track_artist))) {
  1500. classicalWorks.get(iter).performer = work[0].track_artist;
  1501. }
  1502. if (array_homogenous(work.map(it => it.composer))) {
  1503. classicalWorks.get(iter).composer = work[0].composer;
  1504. }
  1505. }
  1506. }
  1507. let duration, volumes = new Map(tracks.map(it => [it.discnumber, undefined]));
  1508. volumes.forEach(function(val, key) {
  1509. volumes.set(key, new Set(tracks.filter(it => it.discnumber == key).map(it => it.discsubtitle)).size)
  1510. });
  1511. if (!tracks.every(it => !isNaN(parseInt(it.tracknumber)))
  1512. && !tracks.every(it => vinyltrackParser.test(it.tracknumber.toUpperCase()))) {
  1513. addMessage('Warning: inconsistent tracks numbering (' + tracks.map(it => it.tracknumber) + ')', 'ua-warning');
  1514. }
  1515. vinylTrackWidth = tracks.reduce(function(acc, it) {
  1516. return Math.max(vinyltrackParser.test(it.tracknumber.toUpperCase()) && parseInt(RegExp.$3), acc);
  1517. }, 0);
  1518. if (vinylTrackWidth) {
  1519. vinylTrackWidth = vinylTrackWidth.toString().length;
  1520. tracks.forEach(function(it) {
  1521. if (vinyltrackParser.test(it.tracknumber.toUpperCase()) != null)
  1522. it.tracknumber = RegExp.$1 + RegExp.$3.padStart(vinylTrackWidth, '0');
  1523. });
  1524. ++vinylTrackWidth;
  1525. }
  1526. const padStart = '[pad=0|0|5|0]';
  1527. function prologue(prefix, postfix) {
  1528. function block1() {
  1529. if (block == 3) playlist += postfix;
  1530. playlist += '\n';
  1531. if (isRED && ![1, 2].includes(block)) playlist += padStart;
  1532. block = 1;
  1533. }
  1534. function block2() {
  1535. if (block == 3) playlist += postfix;
  1536. playlist += '\n';
  1537. if (isRED && ![1, 2].includes(block)) playlist += padStart;
  1538. block = 2;
  1539. }
  1540. function block3() {
  1541. if (block == 2) playlist += '[hr]';
  1542. if (isRED && [1, 2].includes(block)) playlist += '[/pad]';
  1543. playlist += '\n';
  1544. if (block != 3) playlist += prefix;
  1545. block = 3;
  1546. }
  1547. if (totalDiscs > 1 && iter.discnumber != lastDisc) {
  1548. block1();
  1549. lastDisc = iter.discnumber;
  1550. lastSubtitle = lastWork = undefined;
  1551. playlist += '[color=' + prefs.tracklist_disctitle_color + '][size=3][b]';
  1552. if (iter.identifiers.VOL_MEDIA && tracks.filter(it => it.discnumber == iter.discnumber)
  1553. .every(it => it.identifiers.VOL_MEDIA == iter.identifiers.VOL_MEDIA)) {
  1554. playlist += iter.identifiers.VOL_MEDIA.toUpperCase() + ' ';
  1555. }
  1556. playlist += 'Disc ' + iter.discnumber;
  1557. if (iter.discsubtitle && (volumes.get(iter.discnumber) || 0) == 1) {
  1558. playlist += ' – ' + iter.discsubtitle;
  1559. lastSubtitle = iter.discsubtitle;
  1560. }
  1561. playlist += '[/b][/size]';
  1562. duration = tracks.filter(it => it.discnumber == iter.discnumber)
  1563. .reduce((acc, it) => acc + it.duration, 0);
  1564. if (duration > 0) playlist += ' [size=2][i][' + makeTimeString(duration) + '][/i][/size]';
  1565. playlist += '[/color]';
  1566. }
  1567. if (iter.discsubtitle != lastSubtitle) {
  1568. if (block != 1 || iter.discsubtitle) block1();
  1569. if (iter.discsubtitle) {
  1570. playlist += '[color=' + prefs.tracklist_work_color + '][size=2][b]' + iter.discsubtitle + '[/b][/size]';
  1571. duration = tracks.filter(it => it.discsubtitle == iter.discsubtitle)
  1572. .reduce((acc, it) => acc + it.duration, 0);
  1573. if (duration > 0) playlist += ' [size=1][i][' + makeTimeString(duration) + '][/i][/size]';
  1574. playlist += '[/color]';
  1575. }
  1576. lastSubtitle = iter.discsubtitle;
  1577. }
  1578. if (iter.classical_work != lastWork) {
  1579. if (iter.classical_work) {
  1580. block2();
  1581. playlist += '[color=' + prefs.tracklist_work_color + '][size=2][b]';
  1582. if (release.composers.length != 1 && classicalWorks.get(iter.classical_work).composer) {
  1583. playlist += classicalWorks.get(iter.classical_work).composer + ': ';
  1584. }
  1585. playlist += iter.classical_work;
  1586. playlist += '[/b]';
  1587. if (classicalWorks.get(iter.classical_work).performer
  1588. && classicalWorks.get(iter.classical_work).performer != release.artist) {
  1589. playlist += ' (' + classicalWorks.get(iter.classical_work).performer + ')';
  1590. }
  1591. playlist += '[/size]';
  1592. duration = tracks.filter(it => it.classical_work == iter.classical_work)
  1593. .reduce((acc, it) => acc + it.duration, 0);
  1594. if (duration > 0) playlist += ' [size=1][i][' + makeTimeString(duration) + '][/i][/size]';
  1595. playlist += '[/color]';
  1596. } else {
  1597. if (block > 2) block1();
  1598. }
  1599. lastWork = iter.classical_work;
  1600. }
  1601. if (vinyltrackParser.test(iter.tracknumber)) {
  1602. if (block == 3 && lastSide && RegExp.$1 != lastSide) playlist += '\n';
  1603. lastSide = RegExp.$1;
  1604. }
  1605. block3();
  1606. } // prologue
  1607.  
  1608. for (iter of tracks.sort(trackComparer)) {
  1609. let title = '', ttwidth = vinylTrackWidth || (totalDiscs > 1 && iter.discnumber ?
  1610. tracks.filter(it => it.discnumber == iter.discnumber) : tracks)
  1611. .reduce((accumulator, it) => Math.max(accumulator, it.tracknumber.toString().length), 2);
  1612. if (prefs.tracklist_style == 1) { // STYLE 1 ----------------------------------------
  1613. prologue('[size=2]', '[/size]\n');
  1614. track = '[b][color=' + prefs.tracklist_tracknumber_color + ']';
  1615. track += isNaN(parseInt(iter.tracknumber)) ? iter.tracknumber : iter.tracknumber.padStart(ttwidth, '0');
  1616. track += '[/color][/b]' + prefs.title_separator;
  1617. if (iter.track_artist && iter.track_artist != release.artist
  1618. && (!iter.classical_work || !classicalWorks.get(iter.classical_work).performer)) {
  1619. title = '[color=' + prefs.tracklist_artist_color + ']' + iter.track_artist + '[/color] - ';
  1620. }
  1621. title += iter.classical_title || iter.title;
  1622. if (iter.composer && composerEmphasis && release.composers.length != 1
  1623. && (!iter.classical_work || !classicalWorks.get(iter.classical_work).composer)) {
  1624. title = title.concat(' [color=', prefs.tracklist_composer_color, '](', iter.composer, ')[/color]');
  1625. }
  1626. playlist += track + title;
  1627. if (iter.duration) playlist += ' [i][color=' + prefs.tracklist_duration_color +'][' +
  1628. makeTimeString(iter.duration) + '][/color][/i]';
  1629. } else if (prefs.tracklist_style == 2) { // STYLE 2 ----------------------------------------
  1630. prologue('[size=2][pre]', '[/pre][/size]');
  1631. track = isNaN(parseInt(iter.tracknumber)) ? iter.tracknumber : iter.tracknumber.padStart(ttwidth, '0');
  1632. track += prefs.title_separator;
  1633. if (iter.track_artist && iter.track_artist != release.artist
  1634. && (!iter.classical_work || !classicalWorks.get(iter.classical_work).performer)) {
  1635. title = iter.track_artist + ' - ';
  1636. }
  1637. title += iter.classical_title || iter.title;
  1638. if (composerEmphasis && iter.composer && release.composers.length != 1
  1639. && (!iter.classical_work || !classicalWorks.get(iter.classical_work).composer)) {
  1640. title = title.concat(' (', iter.composer, ')');
  1641. }
  1642. let l = 0, j, left, padding, spc;
  1643. duration = iter.duration ? '[' + makeTimeString(iter.duration) + ']' : null;
  1644. let width = prefs.max_tracklist_width - track.length;
  1645. if (duration) width -= duration.length + 1;
  1646. while (title.trueLength() > 0) {
  1647. j = width;
  1648. if (title.trueLength() > width) {
  1649. while (j > 0 && title[j] != ' ') { --j }
  1650. if (j <= 0) j = width;
  1651. }
  1652. left = title.slice(0, j).trim();
  1653. if (++l <= 1) {
  1654. playlist += track + left;
  1655. if (duration) {
  1656. spc = width - left.trueLength();
  1657. padding = (spc < 2 ? ' '.repeat(spc) : ' ' + prefs.pad_leader.repeat(spc - 1)) + ' ';
  1658. playlist += padding + duration;
  1659. }
  1660. width = prefs.max_tracklist_width - track.length - 2;
  1661. } else {
  1662. playlist += '\n' + ' '.repeat(track.length) + left;
  1663. }
  1664. title = title.slice(j).trim();
  1665. }
  1666. }
  1667. }
  1668. if (prefs.tracklist_style == 1 && totalTime > 0) {
  1669. playlist += '\n\n' + divs[0].repeat(10) + '\n[color=' + prefs.tracklist_duration_color +
  1670. ']Total time: [i]' + makeTimeString(totalTime) + '[/i][/color][/size]';
  1671. } else if (prefs.tracklist_style == 2) {
  1672. if (totalTime > 0) {
  1673. duration = '[' + makeTimeString(totalTime) + ']';
  1674. playlist += '\n\n' + divs[0].repeat(32).padStart(prefs.max_tracklist_width);
  1675. playlist += '\n' + 'Total time:'.padEnd(prefs.max_tracklist_width - duration.length) + duration;
  1676. }
  1677. playlist += '[/pre][/size]';
  1678. }
  1679. } else { // single
  1680. playlist += '[align=center]';
  1681. playlist += isRED ? '[pad=20|20|20|20]' : '';
  1682. playlist += '[size=4][b][color=' + prefs.tracklist_artist_color + ']' + release.artist + '[/color][hr]';
  1683. //playlist += '[color=' + prefs.tracklist_single_color + ']';
  1684. playlist += tracks[0].title;
  1685. //playlist += '[/color]'
  1686. playlist += '[/b]';
  1687. if (tracks[0].composer) {
  1688. playlist += '\n[i][color=' + prefs.tracklist_composer_color + '](' + tracks[0].composer + ')[/color][/i]';
  1689. }
  1690. playlist += '\n\n[color=' + prefs.tracklist_duration_color +'][' + makeTimeString(tracks[0].duration) + '][/color][/size]';
  1691. if (isRED) playlist += '[/pad]';
  1692. playlist += '[/align]';
  1693. }
  1694. return playlist;
  1695. }
  1696.  
  1697. function genAlbumHeader() {
  1698. return !isVA && artists[0].length >= 3 ? '[size=4]' +
  1699. joinArtists(artists[0], artist => '[artist]' + artist + '[/artist]') + ' – ' + release.album + '[/size]\n\n' : '';
  1700. }
  1701.  
  1702. function findPreviousUploads() {
  1703. let search = new URLSearchParams(document.location.search);
  1704. if (search.get('groupid')) GM_xmlhttpRequest({
  1705. method: 'GET',
  1706. url: document.location.origin + '/torrents.php?action=grouplog&groupid=' + search.get('groupid'),
  1707. responseType: 'document',
  1708. onload: function(response) {
  1709. if (response.readyState != 4 || response.status != 200) return;
  1710. var dom = domParser.parseFromString(response.responseText, "text/html");
  1711. dom.querySelectorAll('table > tbody > tr.rowa').forEach(function(tr) {
  1712. if (/^\s*deleted\b/i.test(tr.children[3].textContent))
  1713. scanLog('Torrent ' + tr.children[1].firstChild.textContent);
  1714. });
  1715. },
  1716. }); else {
  1717. let query = '';
  1718. if (!isVA && artists[0].length >= 1 && artists[0].length <= 3) query = artists[0].join(', ') + ' - ';
  1719. query += release.album;
  1720. scanLog(query);
  1721. }
  1722.  
  1723. function scanLog(query) {
  1724. GM_xmlhttpRequest({
  1725. method: 'GET',
  1726. url: document.location.origin + '/log.php?search=' + encodeURIComponent(query),
  1727. responseType: 'document',
  1728. onload: function (response) {
  1729. if (response.readyState != 4 || response.status != 200) return;
  1730. var dom = domParser.parseFromString(response.responseText, "text/html");
  1731. dom.querySelectorAll('table > tbody > tr.rowb').forEach(function(tr) {
  1732. var size, msg = tr.children[1].textContent.trim();
  1733. if (/\b[\d\s]+(?:\.\d+)?\s*(?:([KMGT])I?)?B\b/.test(msg)) size = get_size_from_string(RegExp.lastMatch);
  1734. if (!msg.includes('deleted') || (/\[(.*)\/(.*)\/(.*)\]/.test(msg) ?
  1735. !release.codec || release.codec != RegExp.$1
  1736. //|| !release.encoding || release.encoding != RegExp.$2
  1737. || !media || media != RegExp.$3 :
  1738. !size || !albumSize || Math.abs(albumSize / size - 1) >= 0.1)) return;
  1739. addMessage('Warning: possibly same release previously uploaded and deleted: ' + msg, 'ua-warning');
  1740. });
  1741. },
  1742. });
  1743. }
  1744.  
  1745. function get_size_from_string(str) {
  1746. var matches = /\b([\d\s]+(?:\.\d+)?)\s*(?:([KMGT])I?)?B\b/.exec(str.replace(',', '.').toUpperCase());
  1747. if (!matches) return null;
  1748. var size = parseFloat(matches[1].replace(/\s+/g, ''));
  1749. if (matches[2] == 'K') { size *= Math.pow(1024, 1) }
  1750. else if (matches[2] == 'M') { size *= Math.pow(1024, 2) }
  1751. else if (matches[2] == 'G') { size *= Math.pow(1024, 3) }
  1752. else if (matches[2] == 'T') { size *= Math.pow(1024, 4) }
  1753. return Math.round(size);
  1754. }
  1755. }
  1756.  
  1757. function init_from_url_music(url, weak = false) {
  1758. if (!/^https?:\/\//i.test(url)) return false;
  1759. var artist, album, albumYear, releaseDate, channels, label, composer, bd, sr = 44.1,
  1760. description, compiler, producer, totalTracks, discSubtitle, discNumber, trackNumber,
  1761. title, trackArtist, catalogue, encoding, format, bitrate, duration, country;
  1762. if (url.toLowerCase().includes('qobuz.com')) {
  1763. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1764. if (response.readyState != 4 || response.status != 200) return;
  1765. dom = domParser.parseFromString(response.responseText, 'text/html');
  1766. var error = new Error('Error parsing Qobus release page'), mainArtist;
  1767. if ((ref = dom.querySelector('div.album-meta > h2.album-meta__artist')) == null) throw error;
  1768. artist = ref.title || ref.textContent.trim();
  1769. if ((ref = dom.querySelector('div.album-meta > h1.album-meta__title')) == null) throw error;
  1770. album = ref.title || ref.textContent.trim();
  1771. ref = dom.querySelector('div.album-meta > ul > li:first-of-type');
  1772. if (ref != null) releaseDate = normalizeDate(ref.textContent);
  1773. ref = dom.querySelector('div.album-meta > ul > li:nth-of-type(2) > a');
  1774. if (ref != null) mainArtist = ref.title || ref.textContent.trim();
  1775. ref = dom.querySelector('p.album-about__copyright');
  1776. albumYear = ref != null && extractYear(ref.textContent) || extractYear(releaseDate);
  1777. let genres = [];
  1778. dom.querySelectorAll('section#about > ul > li').forEach(function(it) {
  1779. function matchLabel(lbl) { return it.textContent.trimLeft().startsWith(lbl) }
  1780. if (/\b(\d+)\s*(?:dis[ck]|disco|disque)/i.test(it.textContent)) totalDiscs = parseInt(RegExp.$1);
  1781. if (/\b(\d+)\s*(?:track|pist[ae]|tracce)/i.test(it.textContent)) totalTracks = parseInt(RegExp.$1);
  1782. if (it.textContent.trimLeft().startsWith('Label')) label = it.children[0].textContent.trim()
  1783. else if (['Composer', 'Compositeur', 'Komponist'].some(matchLabel)) {
  1784. composer = it.children[0].textContent.trim();
  1785. if (/\bVarious\b/i.test(composer)) composer = null;
  1786. } else if (it.textContent.startsWith('Genre') && it.children.length > 0) {
  1787. it.querySelectorAll('a').forEach(it => { genres.push(it.textContent.trim()) });
  1788. /*
  1789. if (genres.length >= 1 && ['Pop/Rock'].includes(genres[0])) genres.shift();
  1790. if (genres.length >= 2 && ['Alternative & Indie'].includes(genres[genres.length - 1])) genres.shift();
  1791. if (genres.length >= 1 && ['Metal', 'Heavy Metal'].some(genre => genres.includes(genre))) {
  1792. while (genres.length > 1) genres.shift();
  1793. }
  1794. */
  1795. while (genres.length > 1) genres.shift();
  1796. }
  1797. });
  1798. bd = 16; channels = 2;
  1799. dom.querySelectorAll('span.album-quality__info').forEach(function(k) {
  1800. if (/\b([\d\.\,]+)\s*kHz\b/i.test(k.textContent) != null) sr = parseFloat(RegExp.$1.replace(',', '.'));
  1801. if (/\b(\d+)[\-\s]*Bits?\b/i.test(k.textContent) != null) bd = parseInt(RegExp.$1);
  1802. if (/\b(?:Stereo)\b/i.test(k.textContent)) channels = 2;
  1803. if (/\b(\d)\.(\d)\b/.test(k.textContent)) channels = parseInt(RegExp.$1) + parseInt(RegExp.$2);
  1804. });
  1805. getDescFromNode('section#description > p', response.finalUrl, true);
  1806. if ((ref = dom.querySelector('a[title="Qobuzissime"]')) != null) {
  1807. description += '\x1C[align=center][url=https://www.qobuz.com' + ref.pathname +
  1808. '][img]https://ptpimg.me/4z35uj.png[/img][/url][/align]';
  1809. }
  1810. ref = dom.querySelectorAll('div.player__tracks > div.track > div.track__items');
  1811. let works = dom.querySelectorAll('div.player__tracks > p.player__work');
  1812. if (!totalTracks) totalTracks = ref.length;
  1813. ref.forEach(function(k) {
  1814. discSubtitle = null;
  1815. works.forEach(function(j) {
  1816. if (j.compareDocumentPosition(k) == Node.DOCUMENT_POSITION_FOLLOWING) discSubtitle = j
  1817. });
  1818. discSubtitle = discSubtitle != null ? discSubtitle.textContent.trim() : undefined;
  1819. if (/^\s*(?:dis[ck]|disco|disque)\s+(\d+)\s*$/i.test(discSubtitle)) {
  1820. discNumber = parseInt(RegExp.$1);
  1821. discSubtitle = undefined;
  1822. } else discNumber = undefined;
  1823. if (discNumber > totalDiscs) totalDiscs = discNumber;
  1824. trackNumber = parseInt(k.querySelector('span[itemprop="position"]').textContent.trim());
  1825. title = k.querySelector('span.track__item--name').textContent.trim().replace(/\s+/g, ' ');
  1826. duration = timeStringToTime(k.querySelector('span.track__item--duration').textContent);
  1827. trackArtist = undefined;
  1828. track = [
  1829. artist,
  1830. album,
  1831. albumYear,
  1832. releaseDate,
  1833. label,
  1834. undefined, // catalogue
  1835. undefined, // country
  1836. 'lossless',
  1837. 'FLAC',
  1838. undefined,
  1839. undefined,
  1840. bd,
  1841. sr * 1000,
  1842. channels,
  1843. 'WEB',
  1844. genres.join('; '),
  1845. discNumber,
  1846. totalDiscs,
  1847. discSubtitle,
  1848. trackNumber,
  1849. totalTracks,
  1850. title,
  1851. trackArtist,
  1852. undefined,
  1853. composer,
  1854. undefined,
  1855. undefined,
  1856. compiler,
  1857. producer,
  1858. duration,
  1859. undefined,
  1860. undefined,
  1861. undefined,
  1862. undefined,
  1863. undefined,
  1864. response.finalUrl,
  1865. undefined,
  1866. description,
  1867. undefined,
  1868. ];
  1869. tracks.push(track.join('\x1E'));
  1870. });
  1871. clipBoard.value = tracks.join('\n');
  1872. fill_from_text_music();
  1873. } });
  1874. return true;
  1875. } else if (url.toLowerCase().includes('highresaudio.com')) {
  1876. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1877. if (response.readyState != 4 || response.status != 200) return;
  1878. dom = domParser.parseFromString(response.responseText, 'text/html');
  1879. ref = dom.querySelector('h1 > span.artist');
  1880. if (ref != null) artist = ref.textContent.trim();
  1881. ref = dom.getElementById('h1-album-title');
  1882. if (ref != null) album = ref.firstChild.textContent.trim();
  1883. let genres = [], format;
  1884. dom.querySelectorAll('div.album-col-info-data > div > p').forEach(function(k) {
  1885. if (/\b(?:Genre|Subgenre)\b/i.test(k.firstChild.textContent)) genres.push(k.lastChild.textContent.trim());
  1886. if (/\b(?:Label)\b/i.test(k.firstChild.textContent)) label = k.lastChild.textContent.trim();
  1887. if (/\b(?:Album[\s\-]Release)\b/i.test(k.firstChild.textContent)) {
  1888. albumYear = normalizeDate(k.lastChild.textContent);
  1889. }
  1890. if (/\b(?:HRA[\s\-]Release)\b/i.test(k.firstChild.textContent)) {
  1891. releaseDate = normalizeDate(k.lastChild.textContent);
  1892. }
  1893. });
  1894. i = 0;
  1895. dom.querySelectorAll('tbody > tr > td.col-format').forEach(function(k) {
  1896. if (/^(FLAC)\s*([\d\.\,]+)\b/.exec(k.textContent) != null) {
  1897. format = RegExp.$1;
  1898. sr = parseFloat(RegExp.$2.replace(/,/g, '.'));
  1899. ++i;
  1900. }
  1901. });
  1902. if (i > 1) sr = undefined; // ambiguous
  1903. getDescFromNode('div#albumtab-info > p', response.finalUrl);
  1904. ref = dom.querySelectorAll('ul.playlist > li.pltrack');
  1905. totalTracks = ref.length;
  1906. ref.forEach(function(k) {
  1907. discSubtitle = k;
  1908. while ((discSubtitle = discSubtitle.previousElementSibling) != null) {
  1909. if (discSubtitle.nodeName == 'LI' && discSubtitle.className == 'plinfo') {
  1910. discSubtitle = discSubtitle.textContent.replace(/\s*:$/, '').trim();
  1911. if (/\b(?:DIS[CK]|Volume|CD)\s*(\d+)\b/i.exec(discSubtitle)) discNumber = parseInt(RegExp.$1);
  1912. break;
  1913. }
  1914. }
  1915. //if (discnumber > totalDiscs) totalDiscs = discnumber;
  1916. trackNumber = parseInt(k.querySelector('span.track').textContent.trim());
  1917. title = k.querySelector('span.title').textContent.trim().replace(/\s+/g, ' ');
  1918. duration = timeStringToTime(k.querySelector('span.time').textContent);
  1919. trackArtist = undefined;
  1920. track = [
  1921. artist,
  1922. album,
  1923. albumYear,
  1924. releaseDate,
  1925. label,
  1926. undefined, // catalogue
  1927. undefined, // country
  1928. 'lossless',
  1929. 'FLAC', //format,
  1930. undefined,
  1931. undefined,
  1932. 24,
  1933. sr * 1000,
  1934. 2,
  1935. 'WEB',
  1936. genres.join('; '),
  1937. discNumber,
  1938. totalDiscs,
  1939. discSubtitle,
  1940. trackNumber,
  1941. totalTracks,
  1942. title,
  1943. trackArtist,
  1944. undefined,
  1945. composer,
  1946. undefined,
  1947. undefined,
  1948. compiler,
  1949. producer,
  1950. duration,
  1951. undefined,
  1952. undefined,
  1953. undefined,
  1954. undefined,
  1955. undefined,
  1956. response.finalUrl,
  1957. undefined,
  1958. description,
  1959. undefined,
  1960. ];
  1961. tracks.push(track.join('\x1E'));
  1962. });
  1963. clipBoard.value = tracks.join('\n');
  1964. fill_from_text_music();
  1965. } });
  1966. return true;
  1967. } else if (url.toLowerCase().includes('bandcamp.com')) {
  1968. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1969. if (response.readyState != 4 || response.status != 200) return;
  1970. dom = domParser.parseFromString(response.responseText, 'text/html');
  1971. ref = dom.querySelector('span[itemprop="byArtist"] > a');
  1972. if (ref != null) artist = ref.textContent.trim();
  1973. ref = dom.querySelector('h2[itemprop="name"]');
  1974. if (ref != null) album = ref.textContent.trim();
  1975. ref = dom.querySelector('div.tralbum-credits');
  1976. if (ref != null && /\breleased\s+(.*?\b\d{4})\b/i.test(ref.textContent)) {
  1977. releaseDate = RegExp.$1;
  1978. albumYear = releaseDate;
  1979. }
  1980. ref = dom.querySelector('p#band-name-location > span.title');
  1981. if (ref != null) label = ref.textContent.trim();
  1982. let tags = new TagManager;
  1983. dom.querySelectorAll('div.tralbum-tags > a.tag').forEach(k => { tags.add(k.textContent.trim()) });
  1984. description = [];
  1985. dom.querySelectorAll('div.tralbumData').forEach(function(k) {
  1986. if (!k.classList.contains('tralbum-tags')) description.push(html2php(k, response.finalUrl))
  1987. });
  1988. description = description.join('\n\n').replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  1989. ref = dom.querySelectorAll('table.track_list > tbody > tr[itemprop="tracks"]');
  1990. totalTracks = ref.length;
  1991. ref.forEach(function(k) {
  1992. trackNumber = parseInt(k.querySelector('div.track_number').textContent);
  1993. title = k.querySelector('span.track-title').textContent.trim().replace(/\s+/g, ' ');
  1994. duration = timeStringToTime(k.querySelector('span.time').textContent);
  1995. trackArtist = undefined;
  1996. track = [
  1997. artist,
  1998. album,
  1999. albumYear,
  2000. releaseDate,
  2001. label,
  2002. undefined, // catalogue
  2003. undefined, // country
  2004. undefined, //'lossless',
  2005. undefined, //'FLAC',
  2006. undefined,
  2007. undefined,
  2008. undefined,
  2009. undefined,
  2010. 2,
  2011. 'WEB',
  2012. tags.toString(),
  2013. discNumber,
  2014. totalDiscs,
  2015. undefined,
  2016. trackNumber,
  2017. totalTracks,
  2018. title,
  2019. trackArtist,
  2020. undefined,
  2021. composer,
  2022. undefined,
  2023. undefined,
  2024. compiler,
  2025. producer,
  2026. duration,
  2027. undefined,
  2028. undefined,
  2029. undefined,
  2030. undefined,
  2031. undefined,
  2032. response.finalUrl,
  2033. undefined,
  2034. description,
  2035. undefined,
  2036. ];
  2037. tracks.push(track.join('\x1E'));
  2038. });
  2039. clipBoard.value = tracks.join('\n');
  2040. fill_from_text_music();
  2041. } });
  2042. return true;
  2043. } else if (url.toLowerCase().includes('prestomusic.com')) {
  2044. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2045. if (response.readyState != 4 || response.status != 200) return;
  2046. dom = domParser.parseFromString(response.responseText, 'text/html');
  2047. artist = getArtists(dom.querySelectorAll('div.c-product-block__contributors > p'));
  2048. ref = dom.querySelector('h1.c-product-block__title');
  2049. if (ref != null) album = ref.lastChild.textContent.trim();
  2050. dom.querySelectorAll('div.c-product-block__metadata > ul > li').forEach(function(k) {
  2051. if (k.firstChild.textContent.includes('Release Date')) {
  2052. releaseDate = extractYear(k.lastChild.textContent);
  2053. } else if (k.firstChild.textContent.includes('Label')) {
  2054. label = k.lastChild.textContent.trim();
  2055. } else if (k.firstChild.textContent.includes('Catalogue No')) {
  2056. catalogue = k.lastChild.textContent.trim();
  2057. }
  2058. });
  2059. albumYear = releaseDate;
  2060. var genre;
  2061. if (/\/jazz\//i.test(response.finalUrl)) genre = 'Jazz';
  2062. if (/\/classical\//i.test(response.finalUrl)) genre = 'Classical';
  2063. getDescFromNode('div#about > div > p', response.finalUrl, true);
  2064. ref = dom.querySelectorAll('div#related > div > ul > li');
  2065. composer = [];
  2066. ref.forEach(function(k) {
  2067. if (k.parentNode.previousElementSibling.textContent.includes('Composers')) {
  2068. composer.push(k.firstChild.textContent.trim().replace(/^(.*?)\s*,\s+(.*)$/, '$2 $1'));
  2069. }
  2070. });
  2071. composer = composer.join(', ') || undefined;
  2072. ref = dom.querySelectorAll('div.has--sample');
  2073. totalTracks = ref.length;
  2074. trackNumber = 0;
  2075. ref.forEach(function(it) {
  2076. trackNumber = ++trackNumber;
  2077. title = it.querySelector('p.c-track__title').textContent.trim().replace(/\s+/g, ' ');
  2078. duration = timeStringToTime(it.querySelector('div.c-track__duration').textContent);
  2079. let parent = it;
  2080. if (it.classList.contains('c-track')) {
  2081. parent = it.parentNode.parentNode;
  2082. if (parent.classList.contains('c-expander')) parent = parent.parentNode;
  2083. discSubtitle = parent.querySelector(':scope > div > div > div > p.c-track__title');
  2084. discSubtitle = discSubtitle != null ? discSubtitle.textContent.trim().replace(/\s+/g, ' ') : undefined;
  2085. } else {
  2086. discSubtitle = null;
  2087. }
  2088. trackArtist = getArtists(parent.querySelectorAll(':scope > div.c-track__details > ul > li'));
  2089. if (trackArtist.equalTo(artist)) trackArtist = [];
  2090. track = [
  2091. artist.join('; '),
  2092. album,
  2093. albumYear,
  2094. releaseDate,
  2095. label,
  2096. catalogue,
  2097. undefined, // country
  2098. undefined, // encoding
  2099. undefined, // format
  2100. undefined,
  2101. undefined, // bitrate
  2102. undefined, // BD
  2103. undefined, // SR
  2104. 2,
  2105. 'WEB',
  2106. genre,
  2107. discNumber,
  2108. totalDiscs,
  2109. discSubtitle,
  2110. trackNumber,
  2111. totalTracks,
  2112. title,
  2113. trackArtist.join(', '),
  2114. undefined,
  2115. composer,
  2116. undefined,
  2117. undefined,
  2118. compiler,
  2119. producer,
  2120. duration,
  2121. undefined,
  2122. undefined,
  2123. undefined,
  2124. undefined,
  2125. undefined,
  2126. response.finalUrl,
  2127. undefined,
  2128. description,
  2129. undefined,
  2130. ];
  2131. tracks.push(track.join('\x1E'));
  2132. });
  2133. clipBoard.value = tracks.join('\n');
  2134. fill_from_text_music();
  2135.  
  2136. function getArtists(nodeList) {
  2137. var artists = [];
  2138. nodeList.forEach(function(it) {
  2139. if (it.textContent.startsWith('Record')) return;
  2140. splitArtists(it.textContent.trim()).forEach(function(it) {
  2141. artists.push(it.replace(/\s*\([^\(\)]*\)$/, ''));
  2142. });
  2143. });
  2144. return artists;
  2145. }
  2146. } });
  2147. return true;
  2148. } else if (url.toLowerCase().includes('discogs.com/') && /\/releases?\/(\d+)\b/i.test(url)) {
  2149. GM_xmlhttpRequest({
  2150. method: 'GET',
  2151. url: 'https://api.discogs.com/releases/' + RegExp.$1,
  2152. responseType: 'json',
  2153. onload: function(response) {
  2154. if (response.readyState != 4 || response.status != 200) return;
  2155. var json = response.response;
  2156. const removeArtistNdx = /\s*\(\d+\)$/;
  2157. function getArtists(root) {
  2158. function filterArtists(rx, anv = true) {
  2159. return root.extraartists instanceof Array && rx instanceof RegExp ?
  2160. root.extraartists.filter(it => rx.test(it.role))
  2161. .map(it => (anv && it.anv || it.name || '').replace(removeArtistNdx, '')) : [];
  2162. }
  2163. var artists = [];
  2164. for (var ndx = 0; ndx < 7; ++ndx) artists[ndx] = [];
  2165. ndx = 0;
  2166. if (root.artists) root.artists.forEach(function(it) {
  2167. artists[ndx].push((it.anv || it.name).replace(removeArtistNdx, ''));
  2168. if (/^feat/i.test(it.join)) ndx = 1;
  2169. });
  2170. return [
  2171. artists[0],
  2172. artists[1].concat(filterArtists(/^(?:featuring)$/i)),
  2173. artists[2].concat(filterArtists(/\b(?:Remixed[\s\-]By|Remixer)\b/i)),
  2174. artists[3].concat(filterArtists(/\b(?:(?:Written|Composed)[\s\-]By|Composer)\b/i, false)),
  2175. artists[4].concat(filterArtists(/\b(?:Conducted[\s\-]By|Conductor)\b/i)),
  2176. artists[5].concat(filterArtists(/\b(?:Compiled[\s\-]By|Compiler)\b/i)),
  2177. artists[6].concat(filterArtists(/\b(?:Produced[\s\-]By|Producer)\b/i)),
  2178. // filter off from performers
  2179. filterArtists(/\b(?:(?:Mixed)[\s\-]By|Mixer)\b/i),
  2180. filterArtists(/\b(?:(?:Written|Composed)[\s\-]By|Composer)\b/i, true),
  2181. ];
  2182. }
  2183. var albumArtists = getArtists(json);
  2184. if (albumArtists[0].length > 0) {
  2185. artist = albumArtists[0].join('; ');
  2186. if (albumArtists[1].length > 0) artist += ' feat. ' + albumArtists[1].join('; ');
  2187. }
  2188. album = json.title;
  2189. var editions = [];
  2190. if (editions.length > 0) album += ' (' + editions.join(' / ') + ')';
  2191. label = [];
  2192. catalogue = [];
  2193. json.labels.forEach(function(it) {
  2194. //if (it.entity_type_name != 'Label') return;
  2195. if (!/^Not On Label\b/i.test(it.name)) label.pushUniqueCaseless(it.name.replace(removeArtistNdx, ''));
  2196. catalogue.pushUniqueCaseless(it.catno);
  2197. });
  2198. description = '';
  2199. if (json.companies && json.companies.length > 0) {
  2200. description = '[b]Companies, etc.[/b]\n';
  2201. let type_names = new Set(json.companies.map(it => it.entity_type_name));
  2202. type_names.forEach(function(type_name) {
  2203. description += '\n' + type_name + ' – ' + json.companies
  2204. .filter(it => it.entity_type_name == type_name)
  2205. .map(function(it) {
  2206. var result = '[url=https://www.discogs.com/label/' + it.id + ']' +
  2207. it.name.replace(removeArtistNdx, '') + '[/url]';
  2208. if (it.catno) result += ' – ' + it.catno;
  2209. return result;
  2210. })
  2211. .join(', ');
  2212. });
  2213. }
  2214. if (json.extraartists && json.extraartists.length > 0) {
  2215. if (description) description += '\n\n';
  2216. description += '[b]Credits[/b]\n';
  2217. let roles = new Set(json.extraartists.map(it => it.role));
  2218. roles.forEach(function(role) {
  2219. description += '\n' + role + ' – ' + json.extraartists
  2220. .filter(it => it.role == role)
  2221. .map(function(it) {
  2222. var result = '[url=https://www.discogs.com/artist/' + it.id + ']' +
  2223. (it.anv || it.name).replace(removeArtistNdx, '') + '[/url]';
  2224. if (it.tracks) result += ' (tracks: ' + it.tracks + ')';
  2225. return result;
  2226. })
  2227. .join(', ');
  2228. });
  2229. }
  2230. if (json.notes) {
  2231. if (description) description += '\n\n';
  2232. description += '[b]Notes[/b]\n\n' + json.notes.trim();
  2233. }
  2234. if (json.identifiers && json.identifiers.length > 0) {
  2235. if (description) description += '\n\n';
  2236. description += '[b]Barcode and Other Identifiers[/b]\n';
  2237. json.identifiers.forEach(function(it) {
  2238. description += '\n' + it.type;
  2239. if (it.description) description += ' (' + it.description + ')';
  2240. description += ': ' + it.value;
  2241. });
  2242. }
  2243. var identifiers = ['DISCOGS_ID=' + json.id];
  2244. [
  2245. ['Single', 'Single'],
  2246. ['EP', 'EP'],
  2247. ['Compilation', 'Compilation'],
  2248. ['Soundtrack', 'Soundtrack'],
  2249. ].forEach(function(k) {
  2250. if (json.formats.every(it => it.descriptions && it.descriptions.includesCaseless(k[0]))) {
  2251. identifiers.push('RELEASETYPE=' + k[1]);
  2252. }
  2253. });
  2254. json.identifiers.forEach(function(it) {
  2255. identifiers.push(it.type.replace(/\W+/g, '_').toUpperCase() + '=' + it.value.replace(/\s/g, '\x1B'));
  2256. });
  2257. json.formats.forEach(function(it) {
  2258. if (it.descriptions) it.descriptions.forEach(function(it) {
  2259. if (/^(?:.+?\s+Edition|Remaster(?:ed)|Reissue|.+?\s+Release|Enhanced|Promo)$/.test(it)) {
  2260. editions.push(it);
  2261. }
  2262. });
  2263. if (media) return;
  2264. if (it.name.includes('File')) {
  2265. if (['FLAC', 'WAV', 'AIF', 'AIFF', 'PCM'].some(k => it.descriptions.includes(k))) {
  2266. media = 'WEB'; encoding = 'lossless'; format = 'FLAC';
  2267. } else if (it.descriptions.includes('AAC')) {
  2268. media = 'WEB'; encoding = 'lossy'; format = 'AAC'; bd = undefined;
  2269. if (/(\d+)\s*kbps\b/i.test(it.text)) bitrate = parseInt(RegExp.$1);
  2270. } else if (it.descriptions.includes('MP3')) {
  2271. media = 'WEB'; encoding = 'lossy'; format = 'MP3'; bd = undefined;
  2272. if (/(\d+)\s*kbps\b/i.test(it.text)) bitrate = parseInt(RegExp.$1);
  2273. }
  2274. } else if (['CD', 'DVD', 'Vinyl', 'LP', '7"', '12"', '10"', '5"', 'SACD', 'Hybrid', 'Blu',
  2275. 'Cassette','Cartridge', 'Laserdisc', 'VCD'].some(k => it.name.includes(k))) media = it.name;
  2276. });
  2277. if (json.master_url) {
  2278. var yearWritable = elementWritable(document.getElementById('year'));
  2279. var tagsWritable = elementWritable(document.getElementById('tags'));
  2280. if (yearWritable || tagsWritable) GM_xmlhttpRequest({
  2281. method: 'GET',
  2282. url: json.master_url,
  2283. responseType: 'json',
  2284. onload: function(response) {
  2285. if (response.readyState != 4 || response.status != 200) return;
  2286. if (yearWritable && (albumYear = response.response.year) > 0) {
  2287. document.getElementById('year').value = albumYear;
  2288. }
  2289. if (tagsWritable) {
  2290. var tags = new TagManager();
  2291. if (json.genres) tags.add(...json.genres);
  2292. if (json.styles) tags.add(...json.styles);
  2293. if (response.response.genres) tags.add(...response.response.genres);
  2294. if (response.response.styles) tags.add(...response.response.styles);
  2295. if (tags.length > 0) document.getElementById('tags').value = tags.toString();
  2296. }
  2297. },
  2298. });
  2299. }
  2300. json.tracklist.forEach(function(track) {
  2301. if (track.type_.toLowerCase() == 'heading') {
  2302. discSubtitle = track.title;
  2303. } else if (track.type_.toLowerCase() == 'track') {
  2304. if (/^([a-zA-Z]+)?(\d+)-(\w+)$/.test(track.position)) {
  2305. if (RegExp.$1) identifiers.push('VOL_MEDIA=' + RegExp.$1.replace(/\s/g, '\x1B'));
  2306. discNumber = RegExp.$2;
  2307. trackNumber = RegExp.$3;
  2308. } else {
  2309. discNumber = undefined;
  2310. trackNumber = track.position;
  2311. }
  2312. let trackArtists = getArtists(track);
  2313. if (trackArtists[0].length > 0 && !trackArtists[0].equalTo(albumArtists[0])
  2314. || trackArtists[1].length > 0 && !trackArtists[1].equalTo(albumArtists[1])) {
  2315. trackArtist = (trackArtists[0].length > 0 ? trackArtists : albumArtists)[0].join('; ');
  2316. if (trackArtists[1].length > 0) trackArtist += ' feat. ' + trackArtists[1].join('; ');
  2317. } else {
  2318. trackArtist = null;
  2319. }
  2320. let performer = track.extraartists instanceof Array && track.extraartists
  2321. .map(artist => (artist.anv || artist.name).replace(removeArtistNdx, ''))
  2322. .filter(function(artist) {
  2323. return !albumArtists.slice(2).some(it => it instanceof Array && it.includes(artist))
  2324. && !trackArtists.slice(2).some(it => it instanceof Array && it.includes(artist))
  2325. });
  2326. track = [
  2327. artist,
  2328. album,
  2329. undefined, //json.year,
  2330. json.released,
  2331. label.join(' / '),
  2332. catalogue.join(' / '),
  2333. json.country,
  2334. encoding,
  2335. format,
  2336. undefined,
  2337. bitrate,
  2338. bd,
  2339. undefined, // samplerate
  2340. undefined, // channels
  2341. media,
  2342. (json.genres ? json.genres.join('; ') : '') + (json.styles ? ' | ' + json.styles.join('; ') : ''),
  2343. discNumber,
  2344. json.format_quantity,
  2345. discSubtitle,
  2346. trackNumber,
  2347. json.tracklist.length,
  2348. track.title,
  2349. trackArtist,
  2350. performer instanceof Array && performer.join('; ') || undefined,
  2351. stringyfyRole(3), // composers
  2352. stringyfyRole(4), // conductors
  2353. stringyfyRole(2), // remixers
  2354. stringyfyRole(5), // DJs/compilers
  2355. stringyfyRole(6), // producers
  2356. timeStringToTime(track.duration),
  2357. undefined,
  2358. undefined,
  2359. undefined,
  2360. undefined,
  2361. undefined,
  2362. undefined, //'https://www.discogs.com/release/' + json.id,
  2363. undefined,
  2364. description.replace(/\n/g, '\x1C').replace(/\r/g, '\x1D'),
  2365. identifiers.join(' '),
  2366. ];
  2367. tracks.push(track.join('\x1E'));
  2368.  
  2369. function stringyfyRole(ndx) {
  2370. return (trackArtists[ndx] instanceof Array && trackArtists[ndx].length > 0 ?
  2371. trackArtists : albumArtists)[ndx].join('; ');
  2372. }
  2373. }
  2374. });
  2375. clipBoard.value = tracks.join('\n');
  2376. fill_from_text_music();
  2377. },
  2378. });
  2379. return true;
  2380. } else if (url.toLowerCase().includes('supraphonline.cz')) {
  2381. GM_xmlhttpRequest({ method: 'GET', url: url.replace(/\?.*$/, ''), onload: function(response) {
  2382. if (response.readyState != 4 || response.status != 200)
  2383. throw new Error('Response error ' + response.status + ' (' + response.statusText + ')');
  2384. dom = domParser.parseFromString(response.responseText, 'text/html');
  2385. const copyrightParser = /^(?:\([PC]\)|℗|©)$/i;
  2386. var genre, ndx, conductor = [], origin = new URL(response.finalUrl).origin;
  2387. artist = [];
  2388. dom.querySelectorAll('h2.album-artist > a').forEach(function(it) {
  2389. artist.pushUnique(it.title);
  2390. });
  2391. isVA = false;
  2392. if (artist.length == 0 && (ref = dom.querySelector('h2.album-artist[title]')) != null) {
  2393. if (vaParser.test(ref.title)) isVA = true;
  2394. }
  2395. ref = dom.querySelector('span[itemprop="byArtist"] > meta[itemprop="name"]');
  2396. if (ref != null && vaParser.test(ref.content)) isVA = true;
  2397. if (isVA) artist = [];
  2398. if ((ref = dom.querySelector('h1[itemprop="name"]')) != null) album = ref.firstChild.data.trim();
  2399. if ((ref = dom.querySelector('meta[itemprop="numTracks"]')) != null) totalTracks = parseInt(ref.content);
  2400. if ((ref = dom.querySelector('meta[itemprop="genre"]')) != null) genre = ref.content;
  2401. if ((ref = dom.querySelector('li.album-version > div.selected > div')) != null) {
  2402. if (/\b(?:MP3)\b/.test(ref.textContent)) { media = 'WEB'; encoding = 'lossy'; format = 'MP3'; }
  2403. if (/\b(?:FLAC)\b/.test(ref.textContent)) { media = 'WEB'; encoding = 'lossless'; format = 'FLAC'; bd = 16; }
  2404. if (/\b(?:Hi[\s\-]*Res)\b/.test(ref.textContent)) { media = 'WEB'; encoding = 'lossless'; format = 'FLAC'; bd = 24; }
  2405. if (/\b(?:CD)\b/.test(ref.textContent)) { media = 'CD'; }
  2406. if (/\b(?:LP)\b/.test(ref.textContent)) { media = 'Vinyl'; }
  2407. }
  2408. dom.querySelectorAll('ul.summary > li').forEach(function(it) {
  2409. if (it.children.length < 1) return;
  2410. if (it.children[0].textContent.includes('Nosič')) media = it.lastChild.textContent.trim();
  2411. if (it.children[0].textContent.includes('Datum vydání')) releaseDate = normalizeDate(it.lastChild.textContent);
  2412. if (it.children[0].textContent.includes('První vydání')) albumYear = extractYear(it.lastChild.data);
  2413. //if (it.children[0].textContent.includes('Žánr')) genre = it.lastChild.textContent.trim();
  2414. if (it.children[0].textContent.includes('Vydavatel')) label = it.lastChild.textContent.trim();
  2415. if (it.children[0].textContent.includes('Katalogové číslo')) catalogue = it.lastChild.textContent.trim();
  2416. if (it.children[0].textContent.includes('Formát')) {
  2417. if (/\b(?:FLAC|WAV|AIFF?)\b/.test(it.lastChild.textContent)) { encoding = 'lossless'; format = 'FLAC'; }
  2418. if (/\b(\d+)[\-\s]?bits?\b/i.test(it.lastChild.textContent)) bd = parseInt(RegExp.$1);
  2419. if (/\b([\d\.\,]+)[\-\s]?kHz\b/.test(it.lastChild.textContent)) sr = parseFloat(RegExp.$1.replace(',', '.'));
  2420. }
  2421. if (it.children[0].textContent.includes('Celková stopáž')) totalTime = timeStringToTime(it.lastChild.textContent.trim());
  2422. if (copyrightParser.test(it.children[0].textContent) && !albumYear) albumYear = extractYear(it.lastChild.data);
  2423. });
  2424. const creators = ['autoři', 'interpreti', 'tělesa', 'digitalizace'];
  2425. artists = [];
  2426. for (i = 0; i < 4; ++i) artists[i] = {};
  2427. dom.querySelectorAll('ul.sidebar-artist > li').forEach(function(it) {
  2428. if ((ref = it.querySelector('h3')) != null) {
  2429. ndx = undefined;
  2430. creators.forEach((it, _ndx) => { if (ref.textContent.includes(it)) ndx = _ndx });
  2431. } else {
  2432. if (typeof ndx != 'number') return;
  2433. let role;
  2434. if (ndx == 2) role = 'ensemble';
  2435. else if ((ref = it.querySelector('span')) != null) role = translateRole(ref);
  2436. if ((ref = it.querySelector('a')) != null) {
  2437. if (!(artists[ndx][role] instanceof Array)) artists[ndx][role] = [];
  2438. var href = new URL(ref.href);
  2439. artists[ndx][role].pushUnique([ref.textContent.trim(), origin + href.pathname]);
  2440. }
  2441. }
  2442. });
  2443. getDescFromNode('div[itemprop="description"] p', response.finalUrl, true);
  2444. composer = [];
  2445. var performers = [], DJs = [];
  2446. function dumpArtist(ndx, role) {
  2447. if (!role || role == 'undefined') return;
  2448. if (description.length > 0) description += '\x1C' ;
  2449. description += '[color=#9576b1]' + role + '[/color] – ';
  2450. //description += artists[ndx][role].map(artist => '[artist]' + artist[0] + '[/artist]').join(', ');
  2451. description += artists[ndx][role].map(artist => '[url=' + artist[1] + ']' + artist[0] + '[/url]').join(', ');
  2452. }
  2453. for (i = 1; i < 3; ++i) Object.keys(artists[i]).forEach(function(role) { // performers
  2454. var a = artists[i][role].map(a => a[0]);
  2455. artist.pushUnique(...a);
  2456. (['conductor', 'choirmaster'].includes(role) ? conductor : role == 'DJ' ? DJs : performers).pushUnique(...a);
  2457. if (i != 2) dumpArtist(i, role);
  2458. });
  2459. Object.keys(artists[0]).forEach(function(role) { // composers
  2460. composer.pushUnique(...artists[0][role].map(it => it[0])
  2461. .filter(it => !pseudoArtistParsers.some(rx => rx.test(it))));
  2462. dumpArtist(0, role);
  2463. });
  2464. Object.keys(artists[3]).forEach(role => { dumpArtist(3, role) }); // ADC & mastering
  2465. var promises = [];
  2466. dom.querySelectorAll('table.table-tracklist > tbody > tr').forEach(function(row) {
  2467. promises.push(row.id && (ref = row.querySelector('td > a.trackdetail')) != null ? new Promise(function(resolve, reject) {
  2468. var id = parseInt(row.id.replace(/^track-/i, ''));
  2469. GM_xmlhttpRequest({
  2470. method: 'GET',
  2471. url: origin + ref.pathname + ref.search,
  2472. context: id,
  2473. onload: function(response) {
  2474. if (response.readyState == 4 || response.status == 200) {
  2475. var domDetail = domParser.parseFromString(response.responseText, 'text/html');
  2476. var track = domDetail.getElementById('track-' + response.context);
  2477. if (track != null) {
  2478. resolve([track, domDetail.querySelector('div[data-swap="trackdetail-' + response.context + '"] > div > div.row')]);
  2479. } else reject('Track detail not located');
  2480. } else {
  2481. reject('Response error ' + response.status + ' (' + response.statusText + ')');
  2482. }
  2483. },
  2484. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  2485. ontimeout: function() { reject('Timeout') },
  2486. });
  2487. }) : Promise.resolve([row, null]));
  2488. });
  2489. Promise.all(promises).then(function(rows) {
  2490. rows.forEach(function(tr) {
  2491. if (!(tr[0] instanceof HTMLElement)) throw new Error('Assertion failed: tr[0] != HTMLElement');
  2492. if (tr[0].id && tr[0].classList.contains('track')) {
  2493. tr[2] = [];
  2494. for (i = 0; i < 8; ++i) tr[2][i] = [];
  2495. if (!(tr[1] instanceof HTMLElement)) return;
  2496. tr[1].querySelectorAll('div[class]:nth-of-type(2) > ul > li > span').forEach(function(li) {
  2497. function oneOf(...arr) { return arr.some(role => key == role) }
  2498. var key = translateRole(li);
  2499. var val = li.nextElementSibling.textContent.trim();
  2500. if (pseudoArtistParsers.some(rx => rx.test(val))) return;
  2501. if (key.startsWith('remix')) {
  2502. tr[2][2].pushUnique(val);
  2503. } else if (oneOf('music', 'lyrics', 'music+lyrics', 'original lyrics', 'czech lyrics', 'libreto', 'music improvisation', 'author')) {
  2504. tr[2][3].pushUnique(val);
  2505. } else if (oneOf('conductor', 'choirmaster')) {
  2506. tr[2][4].pushUnique(val);
  2507. } else if (key == 'DJ') {
  2508. tr[2][5].pushUnique(val);
  2509. } else if (key == 'produced by') {
  2510. tr[2][6].pushUnique(val);
  2511. } else if (key == 'recorded by') {
  2512. } else {
  2513. tr[2][7].pushUnique(val);
  2514. }
  2515. });
  2516. }
  2517. });
  2518. var guests = rows.filter(tr => tr.length >= 3).map(it => it[2][7])
  2519. .reduce((acc, trpf) => trpf.filter(trpf => acc.includes(trpf)))
  2520. .filter(it => !artist.includes(it));
  2521. rows.forEach(function(tr) {
  2522. if (tr[0].classList.contains('cd-header')) {
  2523. discNumber = /\b\d+\b/.test(tr[0].querySelector('h3').firstChild.data.trim())
  2524. && parseInt(RegExp.lastMatch) || undefined;
  2525. }
  2526. if (tr[0].classList.contains('song-header')) {
  2527. discSubtitle = tr[0].children[0].title.trim() || undefined;
  2528. }
  2529. if (tr[0].id && tr[0].classList.contains('track')) {
  2530. var copyright, trackGenre, trackYear, recordPlace, recordDate, identifiers = '';
  2531. if (/^track-(\d+)$/i.test(tr[0].id)) identifiers = 'TRACK_ID=' + RegExp.$1;
  2532. trackNumber = /^\s*(\d+)\.?\s*$/.test(tr[0].children[0].firstChild.textContent) ?
  2533. parseInt(RegExp.$1) : undefined;
  2534. title = tr[0].querySelector('meta[itemprop="name"]').content;
  2535. duration = (ref = tr[0].querySelector('meta[itemprop="duration"]')) != null
  2536. && /^PT(\d+)H(\d+)M(\d+)S$/i.test(ref.content) ?
  2537. parseInt(RegExp.$1 || 0) * 60**2 + parseInt(RegExp.$2 || 0) * 60 + parseInt(RegExp.$3 || 0) : undefined;
  2538. if (tr[1] instanceof HTMLElement) {
  2539. tr[1].querySelectorAll('div[class]:nth-of-type(1) > ul > li > span').forEach(function(li) {
  2540. if (li.textContent.startsWith('Nahrávka dokončena')) {
  2541. identifiers += ' RECYEAR=' + extractYear(recordDate = li.nextSibling.data.trim());
  2542. }
  2543. if (li.textContent.startsWith('Místo nahrání')) {
  2544. recordPlace = li.nextSibling.data.trim();
  2545. }
  2546. if (li.textContent.startsWith('Rok prvního vydání')) {
  2547. identifiers += ' PUBYEAR=' + (trackYear = parseInt(li.nextSibling.data));
  2548. }
  2549. //if (copyrightParser.test(li.textContent)) copyright = li.nextSibling.data.trim();
  2550. if (li.textContent.startsWith('Žánr')) trackGenre = li.nextSibling.data.trim();
  2551. });
  2552. }
  2553. if (!isVA && tr[2][0].equalTo(artist)) tr[2][0] = [];
  2554. track = [
  2555. isVA ? 'Various Artists' : artist.join('; '),
  2556. album,
  2557. /*trackYear || */albumYear || undefined,
  2558. releaseDate,
  2559. label,
  2560. catalogue,
  2561. undefined, // country
  2562. encoding,
  2563. format,
  2564. undefined,
  2565. undefined,
  2566. bd,
  2567. sr * 1000,
  2568. 2,
  2569. media,
  2570. translateGenre(genre) + ' | ' + translateGenre(trackGenre),
  2571. discNumber,
  2572. totalDiscs,
  2573. discSubtitle,
  2574. trackNumber,
  2575. totalTracks,
  2576. title,
  2577. joinArtists(tr[2][0]),
  2578. tr[2][7].join('; ') || performers.join('; '),
  2579. tr[2][3].join(', ') || composer.join(', '),
  2580. tr[2][4].join('; ') || conductor.join('; '),
  2581. tr[2][2].join('; '),
  2582. tr[2][5].join('; ') || DJs.join('; '),
  2583. tr[2][6].join('; '),
  2584. duration,
  2585. undefined,
  2586. undefined,
  2587. undefined,
  2588. undefined,
  2589. undefined,
  2590. response.finalUrl,
  2591. undefined,
  2592. description,
  2593. identifiers,
  2594. ];
  2595. tracks.push(track.join('\x1E'));
  2596. }
  2597. });
  2598. clipBoard.value = tracks.join('\n');
  2599. fill_from_text_music();
  2600. }).catch(e => { alert(e) });
  2601.  
  2602. function translateGenre(genre) {
  2603. if (!genre || typeof genre != 'string') return undefined;
  2604. [
  2605. ['Orchestrální hudba', 'Orchestral Music'],
  2606. ['Komorní hudba', 'Chamber Music'],
  2607. ['Vokální', 'Classical, Vocal'],
  2608. ['Klasická hudba', 'Classical'],
  2609. ['Melodram', 'Classical, Melodram'],
  2610. ['Symfonie', 'Symphony'],
  2611. ['Vánoční hudba', 'Christmas Music'],
  2612. [/^(?:Alternativ(?:ní|a))$/i, 'Alternative'],
  2613. ['Dechová hudba', 'Brass Music'],
  2614. ['Elektronika', 'Electronic'],
  2615. ['Folklor', 'Folclore, World Music'],
  2616. ['Instrumentální hudba', 'Instrumental'],
  2617. ['Latinské rytmy', 'Latin'],
  2618. ['Meditační hudba', 'Meditative'],
  2619. ['Pro děti', 'Children'],
  2620. ['Pro dospělé', 'Adult'],
  2621. ['Mluvené slovo', 'Spoken Word'],
  2622. ['Audiokniha', 'audiobook'],
  2623. ['Humor', 'humour'],
  2624. ['Pohádka', 'Fairy-Tale'],
  2625. ].forEach(function(subst) {
  2626. if (typeof subst[0] == 'string' && genre.toLowerCase() == subst[0].toLowerCase()
  2627. || subst[0] instanceof RegExp && subst[0].test(genre)) genre = subst[1];
  2628. });
  2629. return genre;
  2630. }
  2631. function translateRole(elem) {
  2632. if (!(elem instanceof HTMLElement)) return undefined;
  2633. var role = elem.textContent.trim().toLowerCase().replace(/\s*:.*$/, '');
  2634. [
  2635. [/\b(?:klavír)\b/, 'piano'],
  2636. [/\b(?:housle)\b/, 'violin'],
  2637. [/\b(?:varhany)\b/, 'organ'],
  2638. [/\b(?:cembalo)\b/, 'harpsichord'],
  2639. [/\b(?:trubka)\b/, 'trumpet'],
  2640. [/\b(?:soprán)\b/, 'soprano'],
  2641. [/\b(?:alt)\b/, 'alto'],
  2642. [/\b(?:baryton)\b/, 'baritone'],
  2643. [/\b(?:bas)\b/, 'basso'],
  2644. [/\b(?:syntezátor)\b/, 'synthesizer'],
  2645. [/\b(?:zpěv)\b/, 'vocals'],
  2646. [/^(?:čte|četba)$/, 'narration'],
  2647. ['vypravuje', 'narration'],
  2648. ['komentář', 'commentary'],
  2649. ['hovoří', 'spoken by'],
  2650. ['hovoří a zpívá', 'speaks and sings'],
  2651. ['improvizace', 'improvisation'],
  2652. ['hudební těleso', 'ensemble'],
  2653. ['hudba', 'music'],
  2654. ['text', 'lyrics'],
  2655. ['hudba+text', 'music+lyrics'],
  2656. ['původní text', 'original lyrics'],
  2657. ['český text', 'czech lyrics'],
  2658. ['hudební improvizace', 'music improvisation'],
  2659. ['autor', 'author'],
  2660. ['účinkuje', 'participating'],
  2661. ['řídí', 'conductor'],
  2662. ['dirigent', 'conductor'],
  2663. ['sbormistr', 'choirmaster'],
  2664. ['produkce', 'produced by'],
  2665. ['nahrál', 'recorded by'],
  2666. ['digitální přepis', 'A/D transfer'],
  2667. ].forEach(function(subst) {
  2668. if (typeof subst[0] == 'string' && role.toLowerCase() == subst[0].toLowerCase()
  2669. || subst[0] instanceof RegExp && subst[0].test(role)) role = role.replace(subst[0], subst[1]);
  2670. });
  2671. return role;
  2672. }
  2673. } });
  2674. return true;
  2675. } else if (url.toLowerCase().includes('bontonland.cz')) {
  2676. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2677. if (response.readyState != 4 || response.status != 200) return;
  2678. dom = domParser.parseFromString(response.responseText, 'text/html');
  2679. ref = dom.querySelector('div#detailheader > h1');
  2680. if (ref != null && /^(.*?)\s*:\s*(.*)$/.test(ref.textContent.trim())) {
  2681. artist = RegExp.$1;
  2682. album = RegExp.$2;
  2683. }
  2684. var EAN;
  2685. dom.querySelectorAll('table > tbody > tr > td.nazevparametru').forEach(function(it) {
  2686. if (it.textContent.includes('Datum vydání')) {
  2687. releaseDate = normalizeDate(it.nextElementSibling.textContent);
  2688. albumYear = extractYear(it.nextElementSibling.textContent);
  2689. } else if (it.textContent.includes('Nosič / počet')) {
  2690. if (/^(.*?)\s*\/\s*(.*)$/.test(it.nextElementSibling.textContent)) {
  2691. media = RegExp.$1;
  2692. totalDiscs = RegExp.$2;
  2693. }
  2694. } else if (it.textContent.includes('Interpret')) {
  2695. artist = it.nextElementSibling.textContent.trim();
  2696. } else if (it.textContent.includes('EAN')) {
  2697. EAN = 'BARCODE=' + it.nextElementSibling.textContent.trim();
  2698. }
  2699. });
  2700. getDescFromNode('div#detailtabpopis > div[class^="pravy"] > div > p:not(:last-of-type)', response.finalUrl, true);
  2701. const plParser = /^(\d+)(?:\s*[\/\.\-\:\)])?\s+(.*?)(?:\s+((?:(?:\d+:)?\d+:)?\d+))?$/;
  2702. ref = dom.querySelector('div#detailtabpopis > div[class^="pravy"] > div > p:last-of-type');
  2703. if (ref == null) throw new Error('Playlist not located');
  2704. var trackList = html2php(ref).split(/[\r\n]+/);
  2705. trackList = trackList.filter(it => plParser.test(it.trim())).map(it => plParser.exec(it.trim()));
  2706. totalTracks = trackList.length;
  2707. if (!totalTracks) throw new Error('Playlist empty');
  2708. trackList.forEach(function(it) {
  2709. trackNumber = it[1];
  2710. title = it[2];
  2711. duration = timeStringToTime(it[3]);
  2712. trackArtist = undefined;
  2713. track = [
  2714. artist,
  2715. album,
  2716. albumYear,
  2717. releaseDate,
  2718. label,
  2719. undefined, // catalogue
  2720. undefined, // country
  2721. undefined, // encoding
  2722. undefined, // format
  2723. undefined,
  2724. undefined,
  2725. undefined,
  2726. undefined,
  2727. undefined,
  2728. 'CD', // media
  2729. undefined, // genre
  2730. discNumber,
  2731. totalDiscs,
  2732. discSubtitle,
  2733. trackNumber,
  2734. totalTracks,
  2735. title,
  2736. trackArtist,
  2737. undefined,
  2738. undefined, // composer
  2739. undefined,
  2740. undefined,
  2741. undefined, // compiler
  2742. undefined, // producer
  2743. duration,
  2744. undefined,
  2745. undefined,
  2746. undefined,
  2747. undefined,
  2748. undefined,
  2749. response.finalUrl,
  2750. undefined,
  2751. description,
  2752. EAN,
  2753. ];
  2754. tracks.push(track.join('\x1E'));
  2755. });
  2756. clipBoard.value = tracks.join('\n');
  2757. fill_from_text_music();
  2758. } });
  2759. return true;
  2760. } else if (url.toLowerCase().includes('nativedsd.com')) {
  2761. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2762. if (response.readyState != 4 || response.status != 200) return;
  2763. dom = domParser.parseFromString(response.responseText, 'text/html');
  2764. var NDSD_ID = 'ORIGINALFORMAT=DSD', genre;
  2765. ref = dom.querySelector('div.the-content > header > h2');
  2766. if (ref != null) artist = ref.firstChild.data.trim();
  2767. ref = dom.querySelector('div.the-content > header > h1');
  2768. if (ref != null) album = ref.firstChild.data.trim();
  2769. ref = dom.querySelector('div.the-content > header > h3');
  2770. if (ref != null) composer = ref.firstChild.data.trim();
  2771. ref = dom.querySelector('div.the-content > header > h1 > small');
  2772. if (ref != null) albumYear = extractYear(ref.firstChild.data);
  2773. releaseDate = albumYear; // weak
  2774. ref = dom.querySelector('div#breadcrumbs > div[class] > a:nth-of-type(2)');
  2775. if (ref != null) label = ref.firstChild.data.trim();
  2776. ref = dom.querySelector('h2#sku');
  2777. if (ref != null) {
  2778. if (/^Catalog Number: (.*)$/m.test(ref.firstChild.textContent)) catalogue = RegExp.$1;
  2779. if (/^ID: (.*)$/m.test(ref.lastChild.textContent)) NDSD_ID += ' NATIVEDSD_ID=' + RegExp.$1;
  2780. }
  2781. getDescFromNode('div.the-content > div.entry > p', response.finalUrl, false);
  2782. ref = dom.querySelector('div#repertoire > div > p');
  2783. if (ref != null) {
  2784. let repertoire = html2php(ref, url).trim();
  2785. let ndx = repertoire.indexOf('\n[b]Track');
  2786. if (description) description += '\x1C\x1C';
  2787. description += (ndx >= 0 ? repertoire.slice(0, ndx).trim() : repertoire)
  2788. .replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  2789. }
  2790. ref = dom.querySelectorAll('div#techspecs > table > tbody > tr');
  2791. if (ref.length > 0) {
  2792. if (description) description += '\x1C\x1C';
  2793. description += '[b][u]Tech specs[/u][/b]';
  2794. ref.forEach(function(it) {
  2795. description += '\n[b]'.concat(it.children[0].textContent.trim(), '[/b] ',
  2796. it.children[1].textContent.trim()).replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  2797. });
  2798. }
  2799. ref = dom.querySelectorAll('div#track-list > table > tbody > tr[id^="track"]');
  2800. totalTracks = ref.length;
  2801. ref.forEach(function(it) {
  2802. ref = it.children[0].children[0];
  2803. if (ref != null) trackNumber = parseInt(ref.firstChild.data.trim().replace(/\..*$/, ''));
  2804. let trackComposer;
  2805. ref = it.children[1];
  2806. if (ref != null) {
  2807. title = ref.firstChild.textContent.trim();
  2808. trackComposer = ref.childNodes[2] && ref.childNodes[2].textContent.trim() || undefined;
  2809. }
  2810. ref = it.children[2];
  2811. if (ref != null) duration = timeStringToTime(ref.firstChild.data);
  2812. track = [
  2813. artist,
  2814. album,
  2815. albumYear,
  2816. releaseDate,
  2817. label,
  2818. catalogue,
  2819. undefined, // country
  2820. 'lossless', // encoding
  2821. 'FLAC', // format
  2822. undefined,
  2823. undefined, // bitrate
  2824. 24, //bd,
  2825. 88200,
  2826. 2,
  2827. 'WEB',
  2828. genre, // 'Jazz'
  2829. discNumber,
  2830. totalDiscs,
  2831. discSubtitle,
  2832. trackNumber,
  2833. totalTracks,
  2834. title,
  2835. trackArtist,
  2836. undefined,
  2837. trackComposer || composer,
  2838. undefined,
  2839. undefined,
  2840. compiler,
  2841. producer,
  2842. duration,
  2843. undefined,
  2844. undefined,
  2845. undefined,
  2846. undefined,
  2847. undefined,
  2848. response.finalUrl,
  2849. undefined,
  2850. description,
  2851. NDSD_ID + ' TRACK_ID=' + it.id.replace(/^track-/i, ''),
  2852. ];
  2853. tracks.push(track.join('\x1E'));
  2854. });
  2855. clipBoard.value = tracks.join('\n');
  2856. fill_from_text_music();
  2857.  
  2858. function getArtists(elem) {
  2859. if (elem == null) return undefined;
  2860. var artists = [];
  2861. splitArtists(elem.textContent.trim()).forEach(function(it) {
  2862. artists.push(it.replace(/\s*\([^\(\)]*\)$/, ''));
  2863. });
  2864. return artists.join(', ');
  2865. }
  2866. } });
  2867. return true;
  2868. } else if (url.toLowerCase().includes('junodownload.com')) {
  2869. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2870. if (response.readyState != 4 || response.status != 200) return;
  2871. dom = domParser.parseFromString(response.responseText, 'text/html');
  2872. ref = dom.querySelector('h2.product-artist > a');
  2873. if (ref != null) artist = titleCase(ref.firstChild.data.trim());
  2874. ref = dom.querySelector('meta[itemprop="name"]');
  2875. if (ref != null) album = ref.content;
  2876. ref = dom.querySelector('meta[itemprop="author"]');
  2877. if (ref != null) label = ref.content;
  2878. ref = dom.querySelector('span[itemprop="datePublished"]');
  2879. if (ref != null) releaseDate = ref.firstChild.data.trim();
  2880. var genres = [];
  2881. dom.querySelectorAll('div.mb-3 > strong').forEach(function(it) {
  2882. if (it.textContent.startsWith('Genre')) {
  2883. ref = it;
  2884. while ((ref = ref.nextElementSibling) != null && ref.nodeName == 'A') {
  2885. genres.push(ref.textContent.trim());
  2886. }
  2887. } else if (it.textContent.startsWith('Cat')) {
  2888. if ((ref = it.nextSibling) != null && ref.nodeType == 3) catalogue = ref.data;
  2889. }
  2890. });
  2891.  
  2892. ref = dom.querySelectorAll('div.product-tracklist > div[itemprop="track"]');
  2893. totalTracks = ref.length;
  2894. ref.forEach(function(it) {
  2895. trackNumber = it.querySelector('div.track-title').firstChild.data.trim();
  2896. if (/^(\d+)\./.test(trackNumber)) trackNumber = parseInt(RegExp.$1);
  2897. title = it.querySelector('span[itemprop="name"]').textContent.trim();
  2898. i = it.querySelector('meta[itemprop="duration"]');
  2899. duration = i != null && /^P(\d+)H(\d+)M(\d+)S$/i.test(i.content) ?
  2900. (parseInt(RegExp.$1) || 0) * 60**2 + (parseInt(RegExp.$2) || 0) * 60 + (parseInt(RegExp.$3) || 0) : undefined;
  2901. track = [
  2902. artist,
  2903. album,
  2904. albumYear,
  2905. releaseDate,
  2906. label,
  2907. catalogue,
  2908. undefined, // country
  2909. undefined, // encoding
  2910. undefined, // format
  2911. undefined,
  2912. undefined, // bitrate
  2913. undefined, //bd,
  2914. undefined, // SR
  2915. 2,
  2916. 'WEB',
  2917. genres.join('; '),
  2918. discNumber,
  2919. totalDiscs,
  2920. discSubtitle,
  2921. trackNumber,
  2922. totalTracks,
  2923. title,
  2924. trackArtist,
  2925. undefined,
  2926. composer,
  2927. undefined,
  2928. undefined,
  2929. compiler,
  2930. producer,
  2931. duration,
  2932. undefined,
  2933. undefined,
  2934. undefined,
  2935. undefined,
  2936. undefined,
  2937. response.finalUrl,
  2938. undefined,
  2939. undefined, // description
  2940. 'BPM=' + it.children[2].textContent.trim(),
  2941. ];
  2942. tracks.push(track.join('\x1E'));
  2943. });
  2944. clipBoard.value = tracks.join('\n');
  2945. fill_from_text_music();
  2946.  
  2947. function getArtists(elem) {
  2948. if (elem == null) return undefined;
  2949. var artists = [];
  2950. splitArtists(elem.textContent.trim()).forEach(function(it) {
  2951. artists.push(it.replace(/\s*\([^\(\)]*\)$/, ''));
  2952. });
  2953. return artists.join(', ');
  2954. }
  2955. } });
  2956. return true;
  2957. } else if (url.toLowerCase().includes('hdtracks.com')) {
  2958. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2959. if (response.readyState != 4 || response.status != 200) return;
  2960. dom = domParser.parseFromString(response.responseText, 'text/html');
  2961. var genres = [];
  2962. dom.querySelectorAll('div.album-main-details > ul > li > span').forEach(function(it) {
  2963. if (it.textContent.startsWith('Title')) album = it.nextSibling.data.trim();
  2964. if (it.textContent.startsWith('Artist')) artist = it.nextElementSibling.textContent.trim();
  2965. if (it.textContent.startsWith('Genre')) {
  2966. ref = it;
  2967. while ((ref = ref.nextElementSibling) != null) genres.push(ref.textContent.trim());
  2968. }
  2969. if (it.textContent.startsWith('Label')) label = it.nextElementSibling.textContent.trim();
  2970. if (it.textContent.startsWith('Release Date')) releaseDate = normalizeDate(it.nextSibling.data.trim());
  2971. });
  2972. if (!albumYear) albumYear = extractYear(releaseDate);
  2973. ref = dom.querySelectorAll('table#track-table > tbody > tr[id^="track"]');
  2974. totalTracks = ref.length;
  2975. ref.forEach(function(it) {
  2976. trackNumber = parseInt(it.querySelector('td:first-of-type').textContent.trim());
  2977. title = it.querySelector('td.track-name').textContent.trim();
  2978. duration = timeStringToTime(it.querySelector('td:nth-of-type(3)').textContent.trim());
  2979. format = it.querySelector('td:nth-of-type(4) > span').textContent.trim();
  2980. sr = it.querySelector('td:nth-of-type(5)').textContent.trim().replace(/\/.*/, '');
  2981. if (/^([\d\.\,]+)\s*\/\s*(\d+)$/.test(sr)) {
  2982. sr = Math.round(parseFloat(RegExp.$1.replace(',', '.')) * 1000);
  2983. bd = parseInt(RegExp.$2);
  2984. } else sr = Math.round(parseFloat(sr) * 1000);
  2985. track = [
  2986. artist,
  2987. album,
  2988. albumYear,
  2989. releaseDate,
  2990. label,
  2991. catalogue,
  2992. undefined, // country
  2993. 'lossless',
  2994. undefined, // format
  2995. undefined,
  2996. undefined, // bitrate
  2997. bd || 24,
  2998. sr || undefined,
  2999. 2,
  3000. 'WEB',
  3001. genres.join('; '),
  3002. discNumber,
  3003. totalDiscs,
  3004. discSubtitle,
  3005. trackNumber,
  3006. totalTracks,
  3007. title,
  3008. trackArtist,
  3009. undefined,
  3010. composer,
  3011. undefined,
  3012. undefined,
  3013. compiler,
  3014. producer,
  3015. duration,
  3016. undefined,
  3017. undefined,
  3018. undefined,
  3019. undefined,
  3020. undefined,
  3021. response.finalUrl,
  3022. undefined,
  3023. undefined, // description
  3024. undefined,
  3025. ];
  3026. tracks.push(track.join('\x1E'));
  3027. });
  3028. clipBoard.value = tracks.join('\n');
  3029. fill_from_text_music();
  3030. } });
  3031. return true;
  3032. } else if (/^https?:\/\/(?:\w+\.)?deezer\.com\/(?:\w+\/)*album\/(\d+)/i.test(url)) {
  3033. GM_xmlhttpRequest({
  3034. method: 'GET',
  3035. url: 'https://api.deezer.com/album/' + RegExp.$1,
  3036. responseType: 'json',
  3037. onload: function(response) {
  3038. if (response.readyState != 4 || response.status != 200) throw new Error('Ready state ' + response.readyState + ', Response error ' + response.status + ' (' + response.statusText + ')');
  3039. var json = response.response;
  3040. isVA = vaParser.test(json.artist.name);
  3041. var identifiers = 'DEEZER_ID=' + json.id + ' RELEASETYPE=' + json.record_type;
  3042. json.tracks.data.forEach(function(track, ndx) {
  3043. trackArtist = track.artist.name;
  3044. if (!isVA && trackArtist && trackArtist == json.artist.name) trackArtist = undefined;
  3045. track = [
  3046. isVA ? 'Various Artists' : json.artist.name,
  3047. json.title,
  3048. undefined, //extractYear(json.release_date),
  3049. json.release_date,
  3050. json.label,
  3051. json.upc,
  3052. undefined, // country
  3053. undefined, // encoding
  3054. undefined, // format
  3055. undefined,
  3056. undefined, // bitrate
  3057. undefined, //bd,
  3058. undefined, // SR
  3059. 2,
  3060. 'WEB',
  3061. json.genres.data.map(it => it.name).join('; '),
  3062. discNumber,
  3063. totalDiscs,
  3064. discSubtitle,
  3065. ndx + 1,
  3066. json.nb_tracks,
  3067. track.title,
  3068. trackArtist,
  3069. undefined,
  3070. composer,
  3071. undefined,
  3072. undefined,
  3073. compiler,
  3074. producer,
  3075. track.duration,
  3076. undefined,
  3077. undefined,
  3078. undefined,
  3079. undefined,
  3080. undefined,
  3081. undefined, //'https://www.deezer.com/album/' + json.id,
  3082. undefined,
  3083. undefined, // description
  3084. identifiers + ' TRACK_ID=' + track.id,
  3085. ];
  3086. tracks.push(track.join('\x1E'));
  3087. });
  3088. clipBoard.value = tracks.join('\n');
  3089. fill_from_text_music();
  3090. },
  3091. });
  3092. return true;
  3093. } else if (/^https?:\/\/(?:\w+\.)?spotify\.com\/(?:\w+\/)*albums?\/(\w+)/i.test(url)) {
  3094. querySpotifyAPI('https://api.spotify.com/v1/albums/' + RegExp.$1).then(function(json) {
  3095. isVA = json.artists.length == 1 && vaParser.test(json.artists[0].name);
  3096. artist = json.artists.map(artist => artist.name);
  3097. totalDiscs = json.tracks.items.reduce((acc, track) => Math.max(acc, track.disc_number), 0);
  3098. var identifiers = 'RELEASETYPE=' + json.album_type + ' SPOTIFY_ID=' + json.id;
  3099. var image = json.images.reduce((acc, image) => image.width * image.height > acc.width * acc.height ? image : acc);
  3100. //if (image) identifiers += ' IMGURL=' + image.url;
  3101. json.tracks.items.forEach(function(track, ndx) {
  3102. trackArtist = track.artists.map(artist => artist.name);
  3103. if (!isVA && json.artists.length > 0 && trackArtist.equalTo(artist)) trackArtist = [];
  3104. track = [
  3105. isVA ? 'Various Artists' : joinArtists(artist),
  3106. json.name,
  3107. undefined, //extractYear(json.release_date),
  3108. json.release_date,
  3109. json.label,
  3110. json.external_ids.upc,
  3111. undefined, // country
  3112. undefined, // encoding
  3113. undefined, // format
  3114. undefined,
  3115. undefined, // bitrate
  3116. undefined, // BD
  3117. undefined, // SR
  3118. 2,
  3119. 'WEB',
  3120. json.genres.join('; '),
  3121. totalDiscs > 1 ? track.disc_number : undefined,
  3122. totalDiscs > 1 ? totalDiscs : undefined,
  3123. undefined, // discSubtitle
  3124. track.track_number,
  3125. json.total_tracks,
  3126. track.name,
  3127. joinArtists(trackArtist),
  3128. undefined,
  3129. composer,
  3130. undefined,
  3131. undefined,
  3132. compiler,
  3133. producer,
  3134. track.duration_ms / 1000,
  3135. undefined,
  3136. undefined,
  3137. undefined,
  3138. undefined,
  3139. undefined,
  3140. undefined, //'https://open.spotify.com/album/' + json.id,
  3141. undefined,
  3142. undefined, // description
  3143. identifiers +
  3144. ' EXPLICIT=' + Number(track.explicit) +
  3145. ' TRACK_ID=' + track.id,
  3146. ];
  3147. tracks.push(track.join('\x1E'));
  3148. });
  3149. clipBoard.value = tracks.join('\n');
  3150. fill_from_text_music();
  3151. }).catch(e => { alert(e) });
  3152. return true;
  3153.  
  3154. function querySpotifyAPI(api_url) {
  3155. if (!api_url) return Promise.reject('No API URL');
  3156. return setToken().then(function(credentials) {
  3157. return new Promise(function(resolve, reject) {
  3158. GM_xmlhttpRequest({
  3159. method: 'GET',
  3160. url: api_url,
  3161. headers: {
  3162. 'Accept': 'application/json',
  3163. 'Authorization': credentials.token_type + ' ' + credentials.access_token,
  3164. },
  3165. responseType: 'json',
  3166. onload: function(response) {
  3167. if (response.readyState == 4 && response.status == 200) resolve(response.response);
  3168. else reject('Response error ' + response.status + ' (' + response.statusText + ')');
  3169. },
  3170. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  3171. ontimeout: function() { reject('Timeout') },
  3172. });
  3173. });
  3174. });
  3175. }
  3176. function setToken() {
  3177. if (isTokenValid()) return Promise.resolve(spotifyCredentials);
  3178. if (!prefs.spotify_clientid || !prefs.spotify_clientsecret) return Promise.reject('Spotify credentials not set');
  3179. return new Promise(function(resolve, reject) {
  3180. const data = new URLSearchParams({
  3181. grant_type: 'client_credentials',
  3182. });
  3183. GM_xmlhttpRequest({
  3184. method: 'POST',
  3185. url: 'https://accounts.spotify.com/api/token',
  3186. headers: {
  3187. 'Content-Type': 'application/x-www-form-urlencoded',
  3188. 'Content-Length': data.toString().length,
  3189. 'Authorization': 'Basic ' + btoa(prefs.spotify_clientid + ':' + prefs.spotify_clientsecret),
  3190. },
  3191. responseType: 'json',
  3192. data: data.toString(),
  3193. onload: function(response) {
  3194. if (response.readyState == 4 && response.status == 200) {
  3195. spotifyCredentials = response.response;
  3196. spotifyCredentials.expires = new Date().getTime() + spotifyCredentials.expires_in;
  3197. if (isTokenValid()) resolve(spotifyCredentials); else reject('Invalid token');
  3198. } else reject('Response error ' + response.status + ' (' + JSON.parse(response.response).error + ')');
  3199. },
  3200. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  3201. ontimeout: function() { reject('Timeout') },
  3202. });
  3203. });
  3204. }
  3205. function isTokenValid() {
  3206. return spotifyCredentials.token_type && spotifyCredentials.token_type.toLowerCase() == 'bearer'
  3207. && spotifyCredentials.access_token && spotifyCredentials.expires >= new Date().getTime() + 30;
  3208. }
  3209. } else if (url.toLowerCase().includes('prostudiomasters.com')) {
  3210. GM_xmlhttpRequest({ method: 'GET', url: url, responseType: 'document', onload: function(response) {
  3211. if (response.readyState != 4 || response.status != 200) return;
  3212. dom = domParser.parseFromString(response.responseText, 'text/html');
  3213. var ID = '';
  3214. if (/\/page\/(\d+)$/i.test(response.finalUrl)) ID = 'PROSTUDIOMASTERS_ID=' + RegExp.$1 + ' ';
  3215. artist = Array.from(dom.querySelectorAll('h2.ArtistName > a')).map(node => node.textContent.trim());
  3216. if ((ref = dom.querySelector('h3.AlbumName')) != null) album = ref.textContent.trim();
  3217. if ((ref = dom.querySelector('div.pline')) != null
  3218. && /^(?:[℗©]\s*)+(\d{4})\s+(.+)/.test(ref.textContent.trim())) {
  3219. releaseDate = RegExp.$1;
  3220. label = RegExp.$2;
  3221. }
  3222. getDescFromNode('div.album-info', response.finalUrl, false);
  3223. //albumYear = extractYear(releaseDate);
  3224. var trs = dom.querySelectorAll('div.album-tracks > div > table > tbody > tr.track-playable');
  3225. totalTracks = trs.length;
  3226. trs.forEach(function(tr) {
  3227. trackArtist = undefined; sr = undefined; bd = undefined; format = undefined;
  3228. title = undefined; trackNumber = undefined; duration = undefined;
  3229. var trackId = tr.getAttribute('data-track-id');
  3230. if (trackId) trackId = 'TRACK_ID=' + trackId;
  3231. if ((ref = tr.querySelector('div.num')) != null) trackNumber = parseInt(ref.firstChild.textContent.trim());
  3232. if ((ref = tr.querySelector('td.track-name > div.name')) != null) {
  3233. title = ref.firstChild.textContent.trim();
  3234. if ((ref = ref.querySelector(':scope small')) != null) {
  3235. trackArtist = splitArtists(ref.firstChild.textContent);
  3236. trackArtist = trackArtist.equalTo(artist) ? undefined : joinArtists(trackArtist);
  3237. }
  3238. }
  3239. if ((ref = tr.querySelector('td:last-of-type')) != null) duration = timeStringToTime(ref.firstChild.data);
  3240. if ((ref = tr.querySelector('span.track-format')) != null && /^(\d+(?:[,\.]\d+)?)\s*([kM]Hz)(?:\s+(\d+)-bit)?\s*\|\s*(\S+)$/i.test(ref.textContent.trim())) {
  3241. sr = parseFloat(RegExp.$1);
  3242. if (RegExp.$2 == 'kHz') sr *= 1024;
  3243. if (RegExp.$2 == 'MHz') sr *= 1024**2;
  3244. sr = Math.round(sr);
  3245. bd = parseInt(RegExp.$3) || undefined;
  3246. format = RegExp.$4;
  3247. }
  3248. track = [
  3249. artist.join('; '),
  3250. album,
  3251. albumYear,
  3252. releaseDate,
  3253. label,
  3254. catalogue,
  3255. undefined, // country
  3256. undefined, //'lossless', // encoding
  3257. format,
  3258. undefined,
  3259. undefined, // bitrate
  3260. bd,
  3261. sr,
  3262. 2, // channels
  3263. 'WEB',
  3264. undefined, // genre
  3265. discNumber,
  3266. totalDiscs,
  3267. discSubtitle,
  3268. trackNumber,
  3269. totalTracks,
  3270. title,
  3271. trackArtist,
  3272. undefined,
  3273. composer,
  3274. undefined,
  3275. undefined,
  3276. compiler,
  3277. producer,
  3278. duration,
  3279. undefined,
  3280. undefined,
  3281. undefined,
  3282. undefined,
  3283. undefined,
  3284. ID ? undefined : response.finalUrl,
  3285. undefined,
  3286. description,
  3287. ID.concat(trackId).trim(),
  3288. ];
  3289. tracks.push(track.join('\x1E'));
  3290. });
  3291. clipBoard.value = tracks.join('\n');
  3292. fill_from_text_music();
  3293. } });
  3294. return true;
  3295. } else if (url.toLowerCase().includes('soundcloud.com') && prefs.soundcloud_clientid) {
  3296. // SC.initialize({
  3297. // client_id: prefs.soundcloud_clientid,
  3298. // redirect_uri: 'https://dont.spam.me/',
  3299. // });
  3300. SC.connect().then(function() { return SC.resolve(url) }).then(function(json) {
  3301. isVA = vaParser.test(json.artist.name);
  3302. var identifiers = 'SOUNDCLOUD_ID=' + json.id + ' RELEASETYPE=' + json.record_type;
  3303. json.tracks.data.forEach(function(track, ndx) {
  3304. trackArtist = track.artist.name;
  3305. if (!isVA && trackArtist && trackArtist == json.artist.name) trackArtist = undefined;
  3306. track = [
  3307. isVA ? 'Various Artists' : json.artist.name,
  3308. json.title,
  3309. undefined, //extractYear(json.release_date),
  3310. json.release_date,
  3311. json.label,
  3312. json.upc,
  3313. undefined, // country
  3314. undefined, // encoding
  3315. undefined, // format
  3316. undefined,
  3317. undefined, // bitrate
  3318. undefined, //bd,
  3319. undefined, // SR
  3320. 2,
  3321. 'WEB',
  3322. json.genres.data.map(it => it.name).join('; '),
  3323. discNumber,
  3324. totalDiscs,
  3325. discSubtitle,
  3326. ndx + 1,
  3327. json.nb_tracks,
  3328. track.title,
  3329. trackArtist,
  3330. undefined,
  3331. composer,
  3332. undefined,
  3333. undefined,
  3334. compiler,
  3335. producer,
  3336. track.duration,
  3337. undefined,
  3338. undefined,
  3339. undefined,
  3340. undefined,
  3341. undefined,
  3342. undefined, //'https://www.deezer.com/album/' + json.id,
  3343. undefined,
  3344. undefined, // description
  3345. identifiers + ' TRACK_ID=' + track.id,
  3346. ];
  3347. tracks.push(track.join('\x1E'));
  3348. });
  3349. clipBoard.value = tracks.join('\n');
  3350. fill_from_text_music();
  3351. });
  3352. return true;
  3353. }
  3354. if (!weak) {
  3355. addMessage('This domain not supported', 'ua-critical');
  3356. clipBoard.value = '';
  3357. }
  3358. return false;
  3359.  
  3360. function getDescFromNode(selector, url, quote = false) {
  3361. description = [];
  3362. dom.querySelectorAll(selector).forEach(k => { description.push(html2php(k, url).trim()) });
  3363. description = description.join('\n\n').trim().replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  3364. if (quote && description.length > 0) description = '[quote]' + description + '[/quote]';
  3365. }
  3366. } // init_from_url_music
  3367.  
  3368. function trackComparer(a, b) {
  3369. var cmp = a.discnumber - b.discnumber;
  3370. if (!isNaN(cmp) && cmp != 0) return cmp;
  3371. cmp = parseInt(a.tracknumber) - parseInt(b.tracknumber);
  3372. if (!isNaN(cmp)) return cmp;
  3373. var m1 = vinyltrackParser.exec(a.tracknumber.toUpperCase());
  3374. var m2 = vinyltrackParser.exec(b.tracknumber.toUpperCase());
  3375. return m1 != null && m2 != null ?
  3376. m1[1].localeCompare(m2[1]) || parseFloat(m1[2]) - parseFloat(m2[2]) :
  3377. a.tracknumber.toUpperCase().localeCompare(b.tracknumber.toUpperCase());
  3378. }
  3379.  
  3380. function normalizeDate(str) {
  3381. if (typeof str != 'string') return null;
  3382. if (/\b(d{4}-\d+-\d+|\d{1,2}\/\d{1,2}\/\d{2})\b/.test(str)) return RegExp.$1;
  3383. if (/\b(\d{1,2})\/(\d{1,2})\/(\d{4})\b/.test(str)) return RegExp.$2 + '/' + RegExp.$1 + '/' + RegExp.$3;
  3384. if (/\b(\d{1,2})\.\s?(\d{1,2})\.\s?(\d{2}|\d{4})\b/.test(str)) return RegExp.$2 + '/' + RegExp.$1 + '/' + RegExp.$3;
  3385. return extractYear(str);
  3386. }
  3387.  
  3388. function getCoverOnline(url) {
  3389. GM_xmlhttpRequest({
  3390. method: 'GET',
  3391. url: url,
  3392. onload: function(response) {
  3393. if (response.readyState != 4 || response.status != 200) return;
  3394. var ref, dom = domParser.parseFromString(response.responseText, 'text/html');
  3395. function testDomain(url, selector) {
  3396. return typeof url == 'string' && response.finalUrl.toLowerCase().includes(url.toLowerCase()) ?
  3397. dom.querySelector(selector) : null;
  3398. }
  3399. if ((ref = testDomain('qobuz.com', 'div.album-cover > img')) != null) {
  3400. setImage(ref.src);
  3401. } else if ((ref = testDomain('highresaudio.com', 'div.albumbody > img.cover[data-pin-media]')) != null) {
  3402. setImage(ref.dataset.pinMedia);
  3403. } else if ((ref = testDomain('bandcamp.com', 'div#tralbumArt > a.popupImage')) != null) {
  3404. setImage(ref.href);
  3405. } else if ((ref = testDomain('7digital.com', 'span.release-packshot-image > img[itemprop="image"]')) != null) {
  3406. setImage(ref.src);
  3407. } else if ((ref = testDomain('hdtracks.com', 'p.product-image > img')) != null) {
  3408. setImage(ref.src);
  3409. } else if ((ref = testDomain('discogs.com', 'div#view_images > p:first-of-type > span > img')) != null) {
  3410. setImage(ref.src);
  3411. } else if ((ref = testDomain('junodownload.com', 'a.productimage')) != null) {
  3412. setImage(ref.href);
  3413. } else if ((ref = testDomain('supraphonline.cz', 'meta[itemprop="image"]')) != null) {
  3414. setImage(ref.content.replace(/\?.*$/, ''));
  3415. } else if ((ref = testDomain('prestomusic.com', 'div.c-product-block__aside > a')) != null) {
  3416. setImage(ref.href.replace(/\?\d+$/, ''));
  3417. } else if ((ref = testDomain('bontonland.cz', 'a.detailzoom')) != null) {
  3418. setImage(ref.href);
  3419. } else if ((ref = testDomain('nativedsd.com', 'a#album-cover')) != null) {
  3420. setImage(ref.href);
  3421. } else if ((ref = testDomain('deezer.com', 'meta[property="og:image"]')) != null) {
  3422. setImage(ref.content);
  3423. } else if ((ref = testDomain('spotify.com', 'meta[property="og:image"]')) != null) {
  3424. setImage(ref.content);
  3425. } else if ((ref = testDomain('prostudiomasters.com', 'img.album-art')) != null) {
  3426. setImage(ref.currentSrc || ref.src);
  3427. }
  3428. },
  3429. //onerror: response => { throw new Error('Response error ' + response.status + ' (' + response.statusText + ')') },
  3430. //ontimeout: function() { throw new Error('Timeout') },
  3431. });
  3432. }
  3433.  
  3434. function reqSelectFormats(...vals) {
  3435. vals.forEach(function(val) {
  3436. [
  3437. ['MP3', 0],
  3438. ['FLAC', 1],
  3439. ['AAC', 2],
  3440. ['AC3', 3],
  3441. ['DTS', 4],
  3442. ].forEach(function(fmt) {
  3443. if (val.toLowerCase() == fmt[0].toLowerCase()
  3444. && (ref = document.getElementById('format_' + fmt[1])) != null) {
  3445. ref.checked = true;
  3446. ref.onchange();
  3447. }
  3448. });
  3449. });
  3450. }
  3451.  
  3452. function reqSelectBitrates(...vals) {
  3453. vals.forEach(function(val) {
  3454. var ndx = 10;
  3455. [
  3456. [192, 0],
  3457. ['APS (VBR)', 1],
  3458. ['V2 (VBR)', 2],
  3459. ['V1 (VBR)', 3],
  3460. [256, 4],
  3461. ['APX (VBR)', 5],
  3462. ['V0 (VBR)', 6],
  3463. [320, 7],
  3464. ['Lossless', 8],
  3465. ['24bit Lossless', 9],
  3466. ['Other', 10],
  3467. ].forEach(function(it) {
  3468. if ((typeof val == 'string' ? val.toLowerCase() : val)
  3469. == (typeof it[0] == 'string' ? it[0].toLowerCase() : it[0])) ndx = it[1]
  3470. });
  3471. if ((ref = document.getElementById('bitrate_' + ndx)) != null) {
  3472. ref.checked = true;
  3473. ref.onchange();
  3474. }
  3475. });
  3476. }
  3477.  
  3478. function reqSelectMedias(...vals) {
  3479. vals.forEach(function(val) {
  3480. [
  3481. ['CD', 0],
  3482. ['DVD', 1],
  3483. ['Vinyl', 2],
  3484. ['Soundboard', 3],
  3485. ['SACD', 4],
  3486. ['DAT', 5],
  3487. ['Cassette', 6],
  3488. ['WEB', 7],
  3489. ['Blu-Ray', 8],
  3490. ].forEach(function(med) {
  3491. if (val == med[0] && (ref = document.getElementById('media_' + med[1])) != null) {
  3492. ref.checked = true;
  3493. ref.onchange();
  3494. }
  3495. });
  3496. if (val == 'CD') {
  3497. if ((ref = document.getElementById('needlog')) != null) {
  3498. ref.checked = true;
  3499. ref.onchange();
  3500. if ((ref = document.getElementById('minlogscore')) != null) ref.value = 100;
  3501. }
  3502. if ((ref = document.getElementById('needcue')) != null) ref.checked = true;
  3503. //if ((ref = document.getElementById('needchecksum')) != null) ref.checked = true;
  3504. }
  3505. });
  3506. }
  3507.  
  3508. function getReleaseIndex(str) {
  3509. var ndx;
  3510. [
  3511. ['Album', 1],
  3512. ['Soundtrack', 3],
  3513. ['EP', 5],
  3514. ['Anthology', 6],
  3515. ['Compilation', 7],
  3516. ['Single', 9],
  3517. ['Live album', 11],
  3518. ['Remix', 13],
  3519. ['Bootleg', 14],
  3520. ['Interview', 15],
  3521. ['Mixtape', 16],
  3522. ['Demo', 17],
  3523. ['Concert Recording', 18],
  3524. ['DJ Mix', 19],
  3525. ['Unknown', 21],
  3526. ].forEach(k => { if (str.toLowerCase() == k[0].toLowerCase()) ndx = k[1] });
  3527. return ndx || 21;
  3528. }
  3529.  
  3530. function getChanString(n) {
  3531. if (!n) return null;
  3532. const chanmap = [
  3533. 'mono',
  3534. 'stereo',
  3535. '2.1',
  3536. '4.0 surround sound',
  3537. '5.0 surround sound',
  3538. '5.1 surround sound',
  3539. '7.0 surround sound',
  3540. '7.1 surround sound',
  3541. ];
  3542. return n >= 1 && n <= 8 ? chanmap[n - 1] : n + 'chn surround sound';
  3543. }
  3544.  
  3545. function joinArtists(arr, decorator = artist => artist) {
  3546. if (!(arr instanceof Array)) return null;
  3547. if (arr.some(artist => artist.includes('&'))) return arr.map(decorator).join(', ');
  3548. if (arr.length < 3) return arr.map(decorator).join(' & ');
  3549. return arr.slice(0, -1).map(decorator).join(', ') + ' & ' + decorator(arr.slice(-1).pop());
  3550. }
  3551. } // fill_from_text_music
  3552.  
  3553. function fill_from_text_apps(weak = false) {
  3554. if (messages != null) messages.parentNode.removeChild(messages);
  3555. if (!urlParser.test(clipBoard.value)) {
  3556. addMessage('Only URL accepted for this category', 'ua-critical');
  3557. return false;
  3558. }
  3559. url = RegExp.$1;
  3560. var description, tags = new TagManager();
  3561. if (url.toLowerCase().includes('://sanet')) {
  3562. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  3563. if (response.readyState != 4 || response.status != 200)
  3564. throw new Error('GM_xmlhttpRequest readyState=' + response.status + ', status=' + response.status);
  3565. dom = domParser.parseFromString(response.responseText, 'text/html');
  3566. i = dom.querySelector('h1.item_title > span');
  3567. if (elementWritable(ref = document.getElementById('title'))) {
  3568. ref.value = i != null ? i.textContent.
  3569. replace(/\(x64\)$/i, '(64-bit)').
  3570. replace(/\b(?:Build)\s+(\d+)/, 'build $1').
  3571. replace(/\b(?:Multilingual|Multilanguage)\b/, 'multilingual') : null;
  3572. }
  3573. description = html2php(dom.querySelector('section.descr'), response.finalUrl);
  3574. if (/\s*^(?:\[i\]\[\/i\])?Homepage$.*/m.test(description)) description = RegExp.leftContext;
  3575. description = description.trim().split(/\n/).slice(5)
  3576. .map(k => k.trimRight()).join('\n').replace(/(?:[ \t]*\r?\n){3,}/, '\n\n').trim();
  3577. ref = dom.querySelector('section.descr > div.release-info');
  3578. var releaseInfo = ref != null && ref.textContent.trim();
  3579. if (/\b(?:Languages?)\s*:\s*(.*?)\s*(?:$|\|)/i.exec(releaseInfo) != null) {
  3580. description += '\n\n[b]Languages:[/b]\n' + RegExp.$1;
  3581. }
  3582. ref = dom.querySelector('div.txtleft > a');
  3583. if (ref != null) description += '\n\n[b]Product page:[/b]\n[url]' + deAnonymize(ref.href) + '[/url]';
  3584. writeDescription(description);
  3585. if ((ref = dom.querySelector('section.descr > div.center > a.mfp-image')) != null) {
  3586. setImage(ref.href);
  3587. } else {
  3588. ref = dom.querySelector('section.descr > div.center > img[data-src]');
  3589. if (ref != null) setImage(ref.dataset.src);
  3590. }
  3591. var cat = dom.querySelector('a.cat:last-of-type > span');
  3592. if (cat != null) {
  3593. if (cat.textContent.toLowerCase() == 'windows') {
  3594. tags.add('apps.windows');
  3595. if (/\b(?:x64)\b/i.test(releaseInfo)) tags.add('win64');
  3596. if (/\b(?:x86)\b/i.test(releaseInfo)) tags.add('win32');
  3597. }
  3598. if (cat.textContent.toLowerCase() == 'macos') tags.add('apps.mac');
  3599. if (cat.textContent.toLowerCase() == 'linux' || cat.textContent.toLowerCase() == 'unix') tags.add('apps.linux');
  3600. if (cat.textContent.toLowerCase() == 'android') tags.add('apps.android');
  3601. if (cat.textContent.toLowerCase() == 'ios') tags.add('apps.ios');
  3602. }
  3603. if (tags.length > 0 && elementWritable(ref = document.getElementById('tags'))) {
  3604. ref.value = tags.toString();
  3605. }
  3606. }, });
  3607. return true;
  3608. }
  3609. if (!weak) {
  3610. addMessage('This domain not supported', 'ua-critical');
  3611. clipBoard.value = '';
  3612. }
  3613. return false;
  3614. }
  3615.  
  3616. function fill_from_text_books(weak = false) {
  3617. if (messages != null) messages.parentNode.removeChild(messages);
  3618. if (!urlParser.test(clipBoard.value)) {
  3619. addMessage('Only URL accepted for this category', 'ua-critical');
  3620. return false;
  3621. }
  3622. url = RegExp.$1;
  3623. var description, tags = new TagManager();
  3624. if (url.toLowerCase().includes('martinus.cz') || url.toLowerCase().includes('martinus.sk')) {
  3625. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  3626. if (response.readyState != 4 || response.status != 200) throw new Error('GM_xmlhttpRequest readyState=' + response.status + ', status=' + response.status);
  3627. dom = domParser.parseFromString(response.responseText, 'text/html');
  3628. function get_detail(x, y) {
  3629. var ref = dom.querySelector('section#details > div > div > div:first-of-type > div:nth-child(' +
  3630. x + ') > dl:nth-child(' + y + ') > dd');
  3631. return ref != null ? ref.textContent.trim() : null;
  3632. }
  3633.  
  3634. i = dom.querySelectorAll('article > ul > li > a');
  3635. if (i.length > 0 && elementWritable(ref = document.getElementById('title') || document.querySelector('input[name="title"]'))) {
  3636. description = joinAuthors(i);
  3637. if ((i = dom.querySelector('article > h1')) != null) description += ' – ' + i.textContent.trim();
  3638. i = dom.querySelector('div.bar.mb-medium > div:nth-child(1) > dl > dd > span');
  3639. if (i != null && (i = extractYear(i.textContent))) description += ' (' + i + ')';
  3640. ref.value = description;
  3641. }
  3642.  
  3643. description = '[quote]' + html2php(dom.querySelector('section#description > div')).
  3644. replace(/^\s*\[img\].*?\[\/img\]\s*/i, '') + '[/quote]';
  3645. const translation_map = [
  3646. [/\b(?:originál)/i, 'Original title'],
  3647. [/\b(?:datum|dátum|rok)\b/i, 'Release date'],
  3648. [/\b(?:katalog|katalóg)/i, 'Catalogue #'],
  3649. [/\b(?:stran|strán)\b/i, 'Page count'],
  3650. [/\bjazyk/i, 'Language'],
  3651. [/\b(?:nakladatel|vydavatel)/i, 'Publisher'],
  3652. [/\b(?:doporuč|ODPORÚČ)/i, 'Age rating'],
  3653. ];
  3654. dom.querySelectorAll('section#details > div > div > div:first-of-type > div > dl').forEach(function(detail) {
  3655. var lbl = detail.children[0].textContent.trim();
  3656. var val = detail.children[1].textContent.trim();
  3657. if (/\b(?:rozm)/i.test(lbl) || /\b(?:vazba|vázba)\b/i.test(lbl)) return;
  3658. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  3659. if (/\b(?:ISBN)\b/i.test(lbl)) {
  3660. url = new URL('https://www.worldcat.org/isbn/' + detail.children[1].textContent.trim());
  3661. val = '[url=' + url.href + ']' + detail.children[1].textContent.trim() + '[/url]';
  3662. findOCLC(url);
  3663. // } else if (/\b(?:ISBN)\b/i.test(lbl)) {
  3664. // val = '[url=https://www.goodreads.com/search/search?q=' + detail.children[1].textContent.trim() +
  3665. // '&search_type=books]' + detail.children[1].textContent.trim() + '[/url]';
  3666. }
  3667. description += '\n[b]' + lbl + ':[/b] ' + val;
  3668. });
  3669. url = new URL(response.finalUrl);
  3670. description += '\n\n[b]More info:[/b]\n[url]' + url.href + '[/url]';
  3671. writeDescription(description);
  3672.  
  3673. if ((i = dom.querySelector('a.mj-product-preview > img')) != null) {
  3674. setImage(i.src.replace(/\?.*/, ''));
  3675. } else if ((i = dom.querySelector('head > meta[property="og:image"]')) != null) {
  3676. setImage(i.content.replace(/\?.*/, ''));
  3677. }
  3678.  
  3679. dom.querySelectorAll('dd > ul > li > a').forEach(x => { tags.add(x.textContent) });
  3680. if (tags.length > 0 && elementWritable(ref = document.getElementById('tags'))) {
  3681. ref.value = tags.toString();
  3682. }
  3683. }, });
  3684. return true;
  3685. } else if (url.toLowerCase().includes('goodreads.com')) {
  3686. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  3687. if (response.readyState != 4 || response.status != 200) throw new Error('GM_xmlhttpRequest readyState=' + response.status + ', status=' + response.status);
  3688. dom = domParser.parseFromString(response.responseText, 'text/html');
  3689. i = dom.querySelectorAll('a.authorName > span');
  3690. if (i.length > 0 && elementWritable(ref = document.getElementById('title') || document.querySelector('input[name="title"]'))) {
  3691. description = joinAuthors(i);
  3692. if ((i = dom.querySelector('h1#bookTitle')) != null) description += ' – ' + i.textContent.trim();
  3693. if ((i = dom.querySelector('div#details > div.row:nth-of-type(2)')) != null
  3694. && (i = extractYear(i.textContent))) description += ' (' + i + ')';
  3695. ref.value = description;
  3696. }
  3697.  
  3698. var description = [];
  3699. dom.querySelectorAll('div#description span:last-of-type').forEach(function(it) {
  3700. description = html2php(it, response.finalUrl);
  3701. });
  3702. description = '[quote]' + description.trim() + '[/quote]';
  3703.  
  3704. function strip(str) {
  3705. return typeof str == 'string' ?
  3706. str.replace(/\s{2,}/g, ' ').replace(/[\n\r]+/, '').replace(/\s*\.{3}(?:less|more)\b/g, '').trim() : null;
  3707. }
  3708.  
  3709. dom.querySelectorAll('div#details > div.row').forEach(k => { description += '\n' + strip(k.innerText) });
  3710. description += '\n';
  3711.  
  3712. dom.querySelectorAll('div#bookDataBox > div.clearFloats').forEach(function(detail) {
  3713. var lbl = detail.children[0].textContent.trim();
  3714. var val = strip(detail.children[1].textContent);
  3715. if (/\b(?:ISBN)\b/i.test(lbl) && (/\b(\d{13})\b/.test(val) || /\b(\d{10})\b/.test(val))) {
  3716. url = new URL('https://www.worldcat.org/isbn/' + RegExp.$1);
  3717. val = '[url=' + url.href + ']' + strip(detail.children[1].textContent) + '[/url]';
  3718. findOCLC(url);
  3719. }
  3720. description += '\n[b]' + lbl + ':[/b] ' + val;
  3721. });
  3722. if ((ref = dom.querySelector('span[itemprop="ratingValue"]')) != null) {
  3723. description += '\n[b]Rating:[/b] ' + Math.round(parseFloat(ref.firstChild.textContent) * 20) + '%';
  3724. }
  3725. url = new URL(response.finalUrl);
  3726. // if ((ref = dom.querySelector('div#buyButtonContainer > ul > li > a.buttonBar')) != null) {
  3727. // let u = new URL(ref.href);
  3728. // description += '\n[url=' + url.origin + u.pathname + '?' + u.search + ']Libraries[/url]';
  3729. // }
  3730. description += '\n\n[b]More info and reviews:[/b]\n[url]' + url.origin + url.pathname + '[/url]';
  3731. dom.querySelectorAll('div.clearFloats.bigBox').forEach(function(bigBox) {
  3732. if (bigBox.id == 'aboutAuthor' && (ref = bigBox.querySelector('h2 > a')) != null) {
  3733. description += '\n\n[b][url=' + ref.href + ']' + ref.textContent.trim() + '[/url][/b]';
  3734. if ((ref = bigBox.querySelector('div.bigBoxBody a > div[style*="background-image"]')) != null) {
  3735. }
  3736. if ((ref = bigBox.querySelector('div.bookAuthorProfile__about > span[id]:last-of-type')) != null) {
  3737. description += '\n' + html2php(ref, response.finalUrl).replace(/^\[i\]Librarian\s+Note:.*?\[\/i\]\s+/i, '');
  3738. }
  3739. } else if ((ref = bigBox.querySelector('h2 > a[href^="/trivia/"]')) != null) {
  3740. description += '\n\n[b][url=' + ref.href + ']' + ref.textContent.trim() + '[/url][/b]';
  3741. if ((ref = bigBox.querySelector('div.bigBoxContent > div.mediumText')) != null) {
  3742. description += '\n' + ref.firstChild.textContent.trim();
  3743. }
  3744. // } else if ((ref = bigBox.querySelector('h2 > a[href^="/work/quotes/"]')) != null) {
  3745. // description += '\n\n[b][url=' + ref.href + ']' + ref.textContent.trim() + '[/url][/b]';
  3746. // bigBox.querySelectorAll('div.bigBoxContent > div.stacked > span.readable').forEach(function(quote) {
  3747. // description += '\n' + ref.firstChild.textContent.trim();
  3748. // });
  3749. }
  3750. });
  3751. writeDescription(description);
  3752. if ((ref = dom.querySelector('div.editionCover > img')) != null) setImage(ref.src.replace(/\?.*/, ''));
  3753. dom.querySelectorAll('div.elementList > div.left').forEach(tag => { tags.add(tag.textContent.trim()) });
  3754. if (tags.length > 0 && elementWritable(ref = document.getElementById('tags'))) ref.value = tags.toString();
  3755. }, });
  3756. return true;
  3757. } else if (url.toLowerCase().includes('databazeknih.cz')) {
  3758. if (!url.toLowerCase().includes('show=alldesc')) {
  3759. if (!url.includes('?')) { url += '?show=alldesc' } else { url += '&show=alldesc' }
  3760. }
  3761. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  3762. if (response.readyState != 4 || response.status != 200) throw new Error('GM_xmlhttpRequest readyState=' + response.status + ', status=' + response.status);
  3763. dom = domParser.parseFromString(response.responseText, 'text/html');
  3764. i = dom.querySelectorAll('span[itemprop="author"] > a');
  3765. if (i != null && elementWritable(ref = document.getElementById('title') || document.querySelector('input[name="title"]'))) {
  3766. description = joinAuthors(i);
  3767. if ((i = dom.querySelector('h1[itemprop="name"]')) != null) description += ' – ' + i.textContent.trim();
  3768. i = dom.querySelector('span[itemprop="datePublished"]');
  3769. if (i != null && (i = extractYear(i.textContent))) description += ' (' + i + ')';
  3770. ref.value = description;
  3771. }
  3772.  
  3773. description = '[quote]' + html2php(dom.querySelector('p[itemprop="description"]'), response.finalUrl) + '[/quote]';
  3774. const translation_map = [
  3775. [/\b(?:orig)/i, 'Original title'],
  3776. [/\b(?:série)\b/i, 'Series'],
  3777. [/\b(?:vydáno)\b/i, 'Released'],
  3778. [/\b(?:stran)\b/i, 'Page count'],
  3779. [/\b(?:jazyk)\b/i, 'Language'],
  3780. [/\b(?:překlad)/i, 'Translation'],
  3781. [/\b(?:autor obálky)\b/i, 'Cover author'],
  3782. ];
  3783. dom.querySelectorAll('table.bdetail tr').forEach(function(detail) {
  3784. var lbl = detail.children[0].textContent.trim();
  3785. var val = detail.children[1].textContent.trim();
  3786. if (/(?:žánr|\bvazba)\b/i.test(lbl)) return;
  3787. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  3788. if (/\b(?:ISBN)\b/i.test(lbl) && /\b(\d+(?:-\d+)*)\b/.exec(val) != null) {
  3789. url = new URL('https://www.worldcat.org/isbn/' + RegExp.$1.replace(/-/g, ''));
  3790. val = '[url=' + url.href + ']' + detail.children[1].textContent.trim() + '[/url]';
  3791. findOCLC(url);
  3792. }
  3793. description += '\n[b]' + lbl + '[/b] ' + val;
  3794. });
  3795.  
  3796. url = new URL(response.finalUrl);
  3797. description += '\n\n[b]More info:[/b]\n[url]' + url.origin + url.pathname + '[/url]';
  3798. writeDescription(description);
  3799.  
  3800. if ((ref = dom.querySelector('div#icover_mid > a')) != null) setImage(ref.href.replace(/\?.*/, ''));
  3801. if ((ref = dom.querySelector('div#lbImage')) != null && /\burl\("(.*)"\)/i.test(i.style.backgroundImage)) {
  3802. setImage(RegExp.$1.replace(/\?.*/, ''));
  3803. }
  3804.  
  3805. dom.querySelectorAll('h5[itemprop="genre"] > a').forEach(tag => { tags.add(tag.textContent.trim()) });
  3806. dom.querySelectorAll('a.tag').forEach(tag => { tags.add(tag.textContent.trim()) });
  3807. if (tags.length > 0 && elementWritable(ref = document.getElementById('tags'))) ref.value = tags.toString();
  3808. }, });
  3809. return true;
  3810. }
  3811. if (!weak) {
  3812. addMessage('This domain not supported', 'ua-critical');
  3813. clipBoard.value = '';
  3814. }
  3815. return false;
  3816.  
  3817. function joinAuthors(nodeList) {
  3818. if (typeof nodeList != 'object') return null;
  3819. return Array.from(nodeList).map(it => it.textContent.trim()).join(' & ');
  3820. }
  3821.  
  3822. function findOCLC(url) {
  3823. if (!url) return false;
  3824. var oclc = document.querySelector('input[name="oclc"]');
  3825. if (!elementWritable(oclc)) return false;
  3826. GM_xmlhttpRequest({
  3827. method: 'GET',
  3828. url: url,
  3829. onload: function(response) {
  3830. if (response.readyState != 4 || response.status != 200) return;
  3831. var dom = domParser.parseFromString(response.responseText, 'text/html');
  3832. var ref = dom.querySelector('tr#details-oclcno > td:last-of-type');
  3833. if (ref != null) oclc.value = ref.textContent.trim();
  3834. },
  3835. });
  3836. return true;
  3837. }
  3838. }
  3839.  
  3840. function preview(n) {
  3841. if (!prefs.auto_preview) return;
  3842. var btn = document.querySelector('input.button_preview_' + n + '[type="button"][value="Preview"]');
  3843. if (btn != null) btn.click();
  3844. }
  3845.  
  3846. function html2php(node, url) {
  3847. var php = '';
  3848. if (node instanceof HTMLElement) node.childNodes.forEach(function(ch) {
  3849. if (ch.nodeType == 3) {
  3850. php += ch.data.replace(/\s+/g, ' ');
  3851. } else if (ch.nodeName == 'P') {
  3852. php += '\n' + html2php(ch, url);
  3853. } else if (ch.nodeName == 'DIV') {
  3854. php += '\n\n' + html2php(ch, url) + '\n\n';
  3855. } else if (ch.nodeName == 'LABEL') {
  3856. php += '\n\n[b]' + html2php(ch, url) + '[/b]';
  3857. } else if (ch.nodeName == 'SPAN') {
  3858. php += html2php(ch, url);
  3859. } else if (ch.nodeName == 'BR' || ch.nodeName == 'HR') {
  3860. php += '\n';
  3861. } else if (ch.nodeName == 'B' || ch.nodeName == 'STRONG') {
  3862. php += '[b]' + html2php(ch, url) + '[/b]';
  3863. } else if (ch.nodeName == 'I' || ch.nodeName == 'EM') {
  3864. php += '[i]' + html2php(ch, url) + '[/i]';
  3865. } else if (ch.nodeName == 'U') {
  3866. php += '[u]' + html2php(ch, url) + '[/u]';
  3867. } else if (ch.nodeName == 'CODE') {
  3868. php += '[pre]' + ch.textContent + '[/pre]';
  3869. } else if (ch.nodeName == 'A') {
  3870. php += ch.childNodes.length > 0 ?
  3871. '[url=' + deAnonymize(ch.href) + ']' + html2php(ch, url) + '[/url]' :
  3872. '[url]' + deAnonymize(ch.href) + '[/url]';
  3873. } else if (ch.nodeName == 'IMG') {
  3874. php += '[img]' + (ch.dataset.src || ch.src) + '[/img]';
  3875. }
  3876. });
  3877. return php;
  3878. }
  3879.  
  3880. function deAnonymize(uri) {
  3881. return typeof uri == 'string' ? uri.replace(/^https?:\/\/(?:www\.)?anonymz\.com\/\?/i, '') : null;
  3882. }
  3883.  
  3884. function writeDescription(desc) {
  3885. if (typeof desc != 'string') return;
  3886. if (elementWritable(ref = document.querySelector('textarea#desc')
  3887. || document.querySelector('textarea#description'))) ref.value = desc;
  3888. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  3889. if (ref.textLength > 0) ref.value += '\n\n';
  3890. ref.value += desc;
  3891. }
  3892. }
  3893.  
  3894. function setImage(url) {
  3895. var image = document.getElementById('image') || document.querySelector('input[name="image"]');
  3896. if (!elementWritable(image)) return false;
  3897. image.value = url;
  3898.  
  3899. if (prefs.auto_preview_cover && image.id) {
  3900. if ((child = document.getElementById('cover preview')) == null) {
  3901. elem = document.createElement('div');
  3902. elem.style.paddingTop = '10px';
  3903. child = document.createElement('img');
  3904. child.id = 'cover preview';
  3905. child.style.width = '90%';
  3906. elem.append(child);
  3907. image.parentNode.previousElementSibling.append(elem);
  3908. }
  3909. child.src = url;
  3910. }
  3911. if (prefs.auto_rehost_cover) {
  3912. if (rehostItBtn != null) {
  3913. rehostItBtn.click();
  3914. } else {
  3915. rehost2PTPIMG([url]).then(urls => { if (urls.length > 0) image.value = urls[0] }).catch(e => { alert(e) });
  3916. }
  3917. }
  3918. }
  3919.  
  3920. function elementWritable(elem) { return elem != null && !elem.disabled && (overwrite || !elem.value) }
  3921. }
  3922.  
  3923. function addArtistField() { exec(function() { AddArtistField() }) }
  3924. function removeArtistField() { exec(function() { RemoveArtistField() }) }
  3925.  
  3926. function array_homogenous(arr) { return arr.every(k => k === arr[0]) }
  3927.  
  3928. function titleCase(str) {
  3929. return str.toLowerCase().split(' ').map(x => x[0].toUpperCase() + x.slice(1)).join(' ');
  3930. }
  3931.  
  3932. function exec(fn) {
  3933. let script = document.createElement('script');
  3934. script.type = 'application/javascript';
  3935. script.textContent = '(' + fn + ')();';
  3936. document.body.appendChild(script); // run the script
  3937. document.body.removeChild(script); // clean up
  3938. }
  3939.  
  3940. function makeTimeString(duration) {
  3941. let t = Math.abs(Math.round(duration));
  3942. let H = Math.floor(t / 60 ** 2);
  3943. let M = Math.floor(t / 60 % 60);
  3944. let S = t % 60;
  3945. return (duration < 0 ? '-' : '') + (H > 0 ? H + ':' + M.toString().padStart(2, '0') : M.toString()) +
  3946. ':' + S.toString().padStart(2, '0');
  3947. }
  3948.  
  3949. function timeStringToTime(str) {
  3950. if (!/(-\s*)?\b(\d+(?::\d{2})*(?:\.\d+)?)\b/.test(str)) return null;
  3951. var t = 0, a = RegExp.$2.split(':');
  3952. while (a.length > 0) t = t * 60 + parseFloat(a.shift());
  3953. return RegExp.$1 ? -t : t;
  3954. }
  3955.  
  3956. function extractYear(expr) {
  3957. if (typeof expr == 'number') return Math.round(expr);
  3958. if (typeof expr != 'string') return null;
  3959. if (/\b(\d{4})\b/.test(expr)) return parseInt(RegExp.$1);
  3960. var d = new Date(expr);
  3961. return parseInt(isNaN(d) ? expr : d.getFullYear());
  3962. }
  3963.  
  3964. function reInParenthesis(expr) { return new RegExp('\\s+\\([^\\(\\)]*'.concat(expr, '[^\\(\\)]*\\)$'), 'i') }
  3965. function reInBrackets(expr) { return new RegExp('\\s+\\[[^\\[\\]]*'.concat(expr, '[^\\[\\]]*\\]$'), 'i') }
  3966.  
  3967. function addMessage(text, cls, html = false) {
  3968. messages = document.getElementById('UA messages');
  3969. if (messages == null) {
  3970. var ua = document.getElementById('upload assistant');
  3971. if (ua == null) return null;
  3972. messages = document.createElement('TR');
  3973. if (messages == null) return null;
  3974. messages.id = 'UA messages';
  3975. ua.children[0].append(messages);
  3976.  
  3977. elem = document.createElement('TD');
  3978. if (elem == null) return null;
  3979. elem.colSpan = 2;
  3980. elem.className = 'ua-messages-bg';
  3981. messages.append(elem);
  3982. } else {
  3983. elem = messages.children[0]; // tbody
  3984. if (elem == null) return null;
  3985. }
  3986. var div = document.createElement('DIV');
  3987. div.classList.add('ua-messages', cls);
  3988. div[html ? 'innerHTML' : 'textContent'] = text;
  3989. return elem.appendChild(div);
  3990. }
  3991.  
  3992. function imageDropHandler(evt) {
  3993. evt.preventDefault();
  3994. if (evt.dataTransfer.files.length <= 0) return;
  3995. var image = document.getElementById('image') || document.querySelector('input[name="image"]');
  3996. if (image == null) return;
  3997. if (evt.currentTarget.busy) throw new Error('Wait till current upload finishes');
  3998. evt.currentTarget.busy = true;
  3999. if (evt.currentTarget.hTimer) {
  4000. clearTimeout(evt.currentTarget.hTimer);
  4001. delete evt.currentTarget.hTimer;
  4002. }
  4003. var origlabel = evt.currentTarget.value;
  4004. evt.currentTarget.value = 'Uploading...';
  4005. evt.currentTarget.style.backgroundColor = '#A00000';
  4006. var evtSrc = evt.currentTarget;
  4007. upload2PTPIMG(evt.dataTransfer.files[0]).then(function(result) {
  4008. if (result.length > 0) {
  4009. image.value = result[0];
  4010. evtSrc.style.backgroundColor = '#00A000';
  4011. evtSrc.hTimer = setTimeout(function() {
  4012. evtSrc.style.backgroundColor = null;
  4013. delete evtSrc.hTimer;
  4014. }, 10000);
  4015. } else evtSrc.style.backgroundColor = null;
  4016. }).catch(function(e) {
  4017. alert(e);
  4018. evtSrc.style.backgroundColor = null;
  4019. }).then(function() {
  4020. evtSrc.busy = false;
  4021. evtSrc.value = origlabel;
  4022. });
  4023. }
  4024.  
  4025. function voidDragHandler(evt) { evt.preventDefault() }
  4026.  
  4027. function upload2PTPIMG(file, elem) {
  4028. if (!(file instanceof File)) return Promise.reject('Bad parameter (file)');
  4029. var config = JSON.parse(window.localStorage.ptpimg_it);
  4030. if (!prefs.ptpimg_api_key && !config.api_key) return Promise.reject('API key not set');
  4031. return new Promise(function(resolve, reject) {
  4032. var reader = new FileReader();
  4033. var fr = new Promise(function(resolve, reject) {
  4034. reader.onload = function() { resolve(reader.result) }
  4035. reader.readAsBinaryString(file); //readAsArrayBuffer(file);
  4036. });
  4037. fr.then(function(result) {
  4038. const boundary = '----NN-GGn-PTPIMG';
  4039. var data = '--' + boundary + '\r\n';
  4040. data += 'Content-Disposition: form-data; name="file-upload[0]"; filename="' + file.name.toASCII() + '"\r\n';
  4041. data += 'Content-Type: ' + file.type + '\r\n\r\n';
  4042. data += result + '\r\n';
  4043. data += '--' + boundary + '\r\n';
  4044. data += 'Content-Disposition: form-data; name="api_key"\r\n\r\n';
  4045. data += (prefs.ptpimg_api_key || config.api_key) + '\r\n';
  4046. data += '--' + boundary + '--\r\n';
  4047. GM_xmlhttpRequest({
  4048. method: 'POST',
  4049. url: 'https://ptpimg.me/upload.php',
  4050. responseType: 'json',
  4051. headers: {
  4052. 'Content-Type': 'multipart/form-data; boundary=' + boundary,
  4053. 'Content-Length': data.length,
  4054. },
  4055. data: data,
  4056. binary: true,
  4057. onload: function(response) {
  4058. if (response.readyState == 4 && response.status == 200) {
  4059. resolve(response.response.map(item => 'https://ptpimg.me/' + item.code + '.' + item.ext));
  4060. } else reject('Response error ' + response.status + ' (' + response.statusText + ')');
  4061. },
  4062. onprogress: elem instanceof HTMLInputElement ?
  4063. arg => { elem.value = 'Uploading... (' + arg.position + '%)' } : undefined,
  4064. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  4065. ontimeout: function() { reject('Timeout') },
  4066. });
  4067. });
  4068. });
  4069. }
  4070.  
  4071. function rehost2PTPIMG(urls) {
  4072. if (!Array.isArray(urls)) return Promise.reject('Bad parameter (urls)');
  4073. var config = JSON.parse(window.localStorage.ptpimg_it);
  4074. if (!prefs.ptpimg_api_key && !config.api_key) return Promise.reject('API key not set');
  4075. return new Promise(function(resolve, reject) {
  4076. const boundary = 'NN-GGn-PTPIMG';
  4077. const dcTest = /^https?:\/\/(?:\w+\.)?discogs\.com\//i;
  4078. var data = '--' + boundary + "\n";
  4079. data += 'Content-Disposition: form-data; name="link-upload"\n\n';
  4080. data += urls.map(url => dcTest.test(url) ? 'https://reho.st/' + url : url).join('\n') + '\n';
  4081. data += '--' + boundary + '\n';
  4082. data += 'Content-Disposition: form-data; name="api_key"\n\n';
  4083. data += (prefs.ptpimg_api_key || config.api_key) + '\n';
  4084. data += '--' + boundary + '--';
  4085. GM_xmlhttpRequest({
  4086. method: 'POST',
  4087. url: 'https://ptpimg.me/upload.php',
  4088. responseType: 'json',
  4089. headers: {
  4090. 'Content-type': 'multipart/form-data; boundary=' + boundary,
  4091. 'Content-Length': data.length,
  4092. },
  4093. data: data,
  4094. onload: function(response) {
  4095. if (response.readyState == 4 && response.status == 200) {
  4096. resolve(response.response.map(item => 'https://ptpimg.me/' + item.code + '.' + item.ext));
  4097. } else reject('Response error ' + response.status + ' (' + response.statusText + ')');
  4098. },
  4099. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  4100. ontimeout: function() { reject('Timeout') },
  4101. });
  4102. });
  4103. }