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

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