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 = 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() + description;
  1283. preview(0);
  1284. }
  1285. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  1286. let editioninfo;
  1287. if (editionTitle) {
  1288. editioninfo = '[size=5][b]' + editionTitle;
  1289. if (release.release_date && (i = extract_year(release.release_date)) > 0) editioninfo += ' (' + i + ')';
  1290. editioninfo += '[/b][/size]\n\n';
  1291. } else editioninfo = '';
  1292. ref.value = ref.textLength > 0 ? ref.value.concat('\n\n', editioninfo, genPlaylist(false), description)
  1293. : editioninfo.concat(genPlaylist(!editioninfo), description);
  1294. preview(0);
  1295. }
  1296. // Release description
  1297. var lineage = '', comment = '', drinfo, srcinfo;
  1298. if (elementWritable(ref = document.getElementById('release_samplerate'))) {
  1299. ref.value = Object.keys(release.srs).length == 1 ? Math.floor(Object.keys(release.srs)[0] / 1000) :
  1300. Object.keys(release.srs).length > 1 ? '999' : null;
  1301. }
  1302. if (Object.keys(release.srs).length > 0) {
  1303. let kHz = Object.keys(release.srs).sort((a, b) => release.srs[b] - release.srs[a])
  1304. .map(f => f / 1000).join('/').concat('kHz');
  1305. if (release.bds.some(bd => bd > 16)) {
  1306. drinfo = '[hide=DR' + (release.drs.length == 1 ? release.drs[0] : '') + '][pre][/pre]';
  1307. if (media == 'Vinyl') {
  1308. let hassr = ref == null || Object.keys(release.srs).length > 1;
  1309. lineage = hassr ? kHz + ' ' : '';
  1310. if (vinylRipInfo) {
  1311. vinylRipInfo[0] = vinylRipInfo[0].replace(vinylTest, '$1[color=blue]$2[/color]');
  1312. if (hassr) { vinylRipInfo[0] = vinylRipInfo[0].replace(/^Vinyl\b/, 'vinyl') }
  1313. lineage += vinylRipInfo[0] + '\n\n[u]Lineage:[/u]' +
  1314. vinylRipInfo.slice(1).map(function(l) {
  1315. return '\n' + l
  1316. // russian translation
  1317. .replace('Код класса состояния винила:', 'Vinyl condition class:')
  1318. .replace('Устройство воспроизведения:', 'Playback device:')
  1319. .replace('Предварительный усилитель:', 'Pre-amplifier:')
  1320. .replace('АЦП:', 'ADC:')
  1321. .replace('Обработка:', 'Processing:')
  1322. }).join('');
  1323. } else {
  1324. lineage += (hassr ? 'Vinyl' : ' vinyl') + ' rip by [color=blue][/color]\n\n[u]Lineage:[/u]\n';
  1325. }
  1326. drinfo += '\n\n[img][/img]\n[img][/img]\n[img][/img][/hide]';
  1327. } else if (['Blu-Ray', 'DVD', 'SACD'].includes(media)) {
  1328. lineage = ref ? '' : kHz;
  1329. if (release.channels) add_channel_info();
  1330. if (media == 'SACD' || isFromDSD) {
  1331. lineage += ' from DSD64 using foobar2000\'s SACD decoder (direct-fp64)';
  1332. lineage += '\nOutput gain +0dB';
  1333. }
  1334. drinfo += '[/hide]';
  1335. //add_rg_info();
  1336. } else { // WEB Hi-Res
  1337. if (ref == null || Object.keys(release.srs).length > 1) lineage = kHz;
  1338. if (release.channels && release.channels != 2) add_channel_info();
  1339. if (isFromDSD) {
  1340. lineage += ' from DSD64 using foobar2000\'s SACD decoder (direct-fp64)';
  1341. lineage += '\nOutput gain +0dB';
  1342. } else {
  1343. add_dr_info();
  1344. }
  1345. //if (lineage.length > 0) add_rg_info();
  1346. if (release.bds.length > 1) release.bds.filter(bd => bd != 24).forEach(function(bd) {
  1347. let hybrid_tracks = tracks.filter(it => it.bd == bd).sort(trackComparer).map(function(it) {
  1348. return (totalDiscs > 1 && it.discnumber ? it.discnumber + '-' : '').concat(it.tracknumber);
  1349. });
  1350. if (hybrid_tracks.length < 1) return;
  1351. if (lineage) lineage += '\n';
  1352. lineage += 'Note: track';
  1353. if (hybrid_tracks.length > 1) lineage += 's';
  1354. lineage += ' #' + hybrid_tracks.join(', ') +
  1355. (hybrid_tracks.length > 1 ? ' are' : ' is') + ' ' + bd + 'bit lossless';
  1356. });
  1357. if (Object.keys(release.srs).length == 1 && Object.keys(release.srs)[0] == 88200 || isFromDSD) {
  1358. drinfo += '[/hide]';
  1359. } else {
  1360. drinfo = null;
  1361. }
  1362. }
  1363. } else { // 16bit or lossy
  1364. if (Object.keys(release.srs).some(f => f != 44100)) lineage = kHz;
  1365. if (release.channels && release.channels != 2) add_channel_info();
  1366. //add_dr_info();
  1367. //if (lineage.length > 0) add_rg_info();
  1368. if (['AAC', 'Opus', 'Vorbis'].includes(release.codec) && release.vendor) {
  1369. let _encoder_settings = release.vendor;
  1370. if (release.codec == 'AAC' && /^qaac\s+[\d\.]+/i.test(release.vendor)) {
  1371. let enc = [];
  1372. if (matches = release.vendor.match(/\bqaac\s+([\d\.]+)\b/i)) enc[0] = matches[1];
  1373. if (matches = release.vendor.match(/\bCoreAudioToolbox\s+([\d\.]+)\b/i)) enc[1] = matches[1];
  1374. if (matches = release.vendor.match(/\b(AAC-\S+)\s+Encoder\b/i)) enc[2] = matches[1];
  1375. if (matches = release.vendor.match(/\b([TC]VBR|ABR|CBR)\s+(\S+)\b/)) { enc[3] = matches[1]; enc[4] = matches[2]; }
  1376. if (matches = release.vendor.match(/\bQuality\s+(\d+)\b/i)) enc[5] = matches[1];
  1377. _encoder_settings = 'Converted by Apple\'s ' + enc[2] + ' encoder (' + enc[3] + '-' + enc[4] + ')';
  1378. }
  1379. if (lineage) lineage += '\n\n';
  1380. lineage += _encoder_settings;
  1381. }
  1382. }
  1383. }
  1384. function add_dr_info() {
  1385. if (release.drs.length != 1 || document.getElementById('release_dynamicrange') != null) return false;
  1386. if (lineage.length > 0) lineage += ' | ';
  1387. if (release.drs[0] < 4) lineage += '[color=red]';
  1388. lineage += 'DR' + release.drs[0];
  1389. if (release.drs[0] < 4) lineage += '[/color]';
  1390. return true;
  1391. }
  1392. function add_rg_info() {
  1393. if (release.rgs.length != 1) return false;
  1394. if (lineage.length > 0) lineage += ' | ';
  1395. lineage += 'RG'; //lineage += 'RG ' + rgs[0];
  1396. return true;
  1397. }
  1398. function add_channel_info() {
  1399. if (!release.channels) return false;
  1400. let chi = getChanString(release.channels);
  1401. if (lineage.length > 0 && chi.length > 0) lineage += ', ';
  1402. lineage += chi;
  1403. return chi.length > 0;
  1404. }
  1405. if (url) srcinfo = '[url]' + url + '[/url]';
  1406. if ((ref = document.getElementById('release_lineage')) != null) {
  1407. if (elementWritable(ref)) {
  1408. if (drinfo) comment = drinfo;
  1409. if (lineage && srcinfo) lineage += '\n\n';
  1410. if (srcinfo) lineage += srcinfo;
  1411. ref.value = lineage;
  1412. preview(1);
  1413. }
  1414. } else {
  1415. comment = lineage;
  1416. if (comment && drinfo) comment += '\n\n';
  1417. if (drinfo) comment += drinfo;
  1418. if (comment && srcinfo) comment += '\n\n';
  1419. if (srcinfo) comment += srcinfo;
  1420. }
  1421. if (elementWritable(ref = document.getElementById('release_desc'))) {
  1422. ref.value = comment;
  1423. if (comment.length > 0) preview(isNWCD ? 2 : 1);
  1424. }
  1425. if (release.encoding == 'lossless' && release.codec == 'FLAC'
  1426. && release.bds.includes(24) && release.dirpaths.length == 1) {
  1427. var uri = new URL(release.dirpaths[0] + '\\foo_dr.txt');
  1428. GM_xmlhttpRequest({
  1429. method: 'GET',
  1430. url: uri.href,
  1431. responseType: 'blob',
  1432. onload: function(response) {
  1433. if (response.readyState != 4 || !response.responseText) return;
  1434. var rlsDesc = document.getElementById('release_lineage') || document.getElementById('release_desc');
  1435. if (rlsDesc == null) return;
  1436. var value = rlsDesc.value;
  1437. matches = value.match(/(^\[hide=DR\d*\]\[pre\])\[\/pre\]/im);
  1438. if (matches == null) return;
  1439. var index = matches.index + matches[1].length;
  1440. rlsDesc.value = value.slice(0, index).concat(response.responseText, value.slice(index));
  1441. }
  1442. });
  1443. }
  1444. }
  1445. if (elementWritable(document.getElementById('image') || document.querySelector('input[name="image"]'))) {
  1446. if (tracks.every(track => track.identifiers.IMGURL && track.identifiers.IMGURL == tracks[0].identifiers.IMGURL)) {
  1447. setImage(tracks[0].identifiers.IMGURL);
  1448. } else {
  1449. if (/^https?:\/\/(\w+\.)?discogs\.com\/release\/[\w\-]+\/?$/i.test(url)) url += '/images';
  1450. getCoverOnline(url);
  1451. }
  1452. }
  1453. // } else if (elementWritable(document.getElementById('image') || document.querySelector('input[name="image"]'))
  1454. // && ((ref = document.getElementById('album_desc')) != null || (ref = document.getElementById('body')) != null)
  1455. // && ref.textLength > 0 && (matches = ref.value.matchAll(/\b(https?\/\/[\w\-\&\_\?\=]+)/i)) != null) {
  1456.  
  1457. if (elementWritable(ref = document.getElementById('release_dynamicrange'))) {
  1458. ref.value = release.drs.length == 1 ? release.drs[0] : '';
  1459. }
  1460. if (isRequestNew && prefs.request_default_bounty > 0) {
  1461. let amount = prefs.request_default_bounty < 1024 ? prefs.request_default_bounty : prefs.request_default_bounty / 1024;
  1462. if ((ref = document.getElementById('amount_box')) != null && !ref.disabled) ref.value = amount;
  1463. if ((ref = document.getElementById('unit')) != null && !ref.disabled) {
  1464. ref.value = prefs.request_default_bounty < 1024 ? 'mb' : 'gb';
  1465. }
  1466. exec(function() { Calculate() });
  1467. }
  1468. if (prefs.clean_on_apply) clipBoard.value = '';
  1469. prefs.save();
  1470. return true;
  1471.  
  1472. function genPlaylist(pad = true) { // ===================================== The Playlist =====================================
  1473. var playlist = '';
  1474. if (tracks.length > 1) {
  1475. if (pad && isRED) playlist += '[pad=5|0|0|0]';
  1476. if (!isVA && artists[0].length >= 3) playlist += '[size=4]' +
  1477. joinArtists(artists[0], artist => '[artist]' + artist + '[/artist]') + ' – ' + release.album + '[/size]\n\n';
  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 findPreviousUploads() {
  1692. let search = new URLSearchParams(document.location.search);
  1693. if (search.get('groupid')) GM_xmlhttpRequest({
  1694. method: 'GET',
  1695. url: document.location.origin + '/torrents.php?action=grouplog&groupid=' + search.get('groupid'),
  1696. responseType: 'document',
  1697. onload: function(response) {
  1698. if (response.readyState != 4 || response.status != 200) return;
  1699. var dom = domParser.parseFromString(response.responseText, "text/html");
  1700. dom.querySelectorAll('table > tbody > tr.rowa').forEach(function(tr) {
  1701. if (/^\s*deleted\b/i.test(tr.children[3].textContent))
  1702. scanLog('Torrent ' + tr.children[1].firstChild.textContent);
  1703. });
  1704. },
  1705. }); else {
  1706. let query = '';
  1707. if (!isVA && artists[0].length >= 1 && artists[0].length <= 3) query = artists[0].join(', ') + ' - ';
  1708. query += release.album;
  1709. scanLog(query);
  1710. }
  1711.  
  1712. function scanLog(query) {
  1713. GM_xmlhttpRequest({
  1714. method: 'GET',
  1715. url: document.location.origin + '/log.php?search=' + encodeURIComponent(query),
  1716. responseType: 'document',
  1717. onload: function (response) {
  1718. if (response.readyState != 4 || response.status != 200) return;
  1719. var dom = domParser.parseFromString(response.responseText, "text/html");
  1720. dom.querySelectorAll('table > tbody > tr.rowb').forEach(function(tr) {
  1721. var size, msg = tr.children[1].textContent.trim();
  1722. if (/\b[\d\s]+(?:\.\d+)?\s*(?:([KMGT])I?)?B\b/.test(msg)) size = get_size_from_string(RegExp.lastMatch);
  1723. if (!msg.includes('deleted') || (/\[(.*)\/(.*)\/(.*)\]/.test(msg) ?
  1724. !release.codec || release.codec != RegExp.$1
  1725. //|| !release.encoding || release.encoding != RegExp.$2
  1726. || !media || media != RegExp.$3 :
  1727. !size || !albumSize || Math.abs(albumSize / size - 1) >= 0.1)) return;
  1728. addMessage('Warning: possibly same release previously uploaded and deleted: ' + msg, 'ua-warning');
  1729. });
  1730. },
  1731. });
  1732. }
  1733.  
  1734. function get_size_from_string(str) {
  1735. var matches = /\b([\d\s]+(?:\.\d+)?)\s*(?:([KMGT])I?)?B\b/.exec(str.replace(',', '.').toUpperCase());
  1736. if (!matches) return null;
  1737. var size = parseFloat(matches[1].replace(/\s+/g, ''));
  1738. if (matches[2] == 'K') { size *= Math.pow(1024, 1) }
  1739. else if (matches[2] == 'M') { size *= Math.pow(1024, 2) }
  1740. else if (matches[2] == 'G') { size *= Math.pow(1024, 3) }
  1741. else if (matches[2] == 'T') { size *= Math.pow(1024, 4) }
  1742. return Math.round(size);
  1743. }
  1744. }
  1745.  
  1746. function init_from_url_music(url, weak = false) {
  1747. if (!/^https?:\/\//i.test(url)) return false;
  1748. var artist, album, albumYear, releaseDate, channels, label, composer, bd, sr = 44.1,
  1749. description, compiler, producer, totalTracks, discSubtitle, discNumber, trackNumber,
  1750. title, trackArtist, catalogue, encoding, format, bitrate, duration, country;
  1751. if (url.toLowerCase().includes('qobuz.com')) {
  1752. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1753. if (response.readyState != 4 || response.status != 200) return;
  1754. dom = domParser.parseFromString(response.responseText, 'text/html');
  1755. var error = new Error('Error parsing Qobus release page'), mainArtist;
  1756. if ((ref = dom.querySelector('div.album-meta > h2.album-meta__artist')) == null) throw error;
  1757. artist = ref.title || ref.textContent.trim();
  1758. if ((ref = dom.querySelector('div.album-meta > h1.album-meta__title')) == null) throw error;
  1759. album = ref.title || ref.textContent.trim();
  1760. ref = dom.querySelector('div.album-meta > ul > li:first-of-type');
  1761. if (ref != null) releaseDate = normalizeDate(ref.textContent);
  1762. ref = dom.querySelector('div.album-meta > ul > li:nth-of-type(2) > a');
  1763. if (ref != null) mainArtist = ref.title || ref.textContent.trim();
  1764. ref = dom.querySelector('p.album-about__copyright');
  1765. albumYear = ref != null && extract_year(ref.textContent) || extract_year(releaseDate);
  1766. let genres = [];
  1767. dom.querySelectorAll('section#about > ul > li').forEach(function(it) {
  1768. function matchLabel(lbl) { return it.textContent.trimLeft().startsWith(lbl) }
  1769. if (/\b(\d+)\s*(?:dis[ck]|disco|disque)/i.test(it.textContent)) totalDiscs = parseInt(RegExp.$1);
  1770. if (/\b(\d+)\s*(?:track|pist[ae]|tracce)/i.test(it.textContent)) totalTracks = parseInt(RegExp.$1);
  1771. if (it.textContent.trimLeft().startsWith('Label')) label = it.children[0].textContent.trim()
  1772. else if (['Composer', 'Compositeur', 'Komponist'].some(matchLabel)) {
  1773. composer = it.children[0].textContent.trim();
  1774. if (/\bVarious\b/i.test(composer)) composer = null;
  1775. } else if (it.textContent.startsWith('Genre') && it.children.length > 0) {
  1776. it.querySelectorAll('a').forEach(it => { genres.push(it.textContent.trim()) });
  1777. /*
  1778. if (genres.length >= 1 && ['Pop/Rock'].includes(genres[0])) genres.shift();
  1779. if (genres.length >= 2 && ['Alternative & Indie'].includes(genres[genres.length - 1])) genres.shift();
  1780. if (genres.length >= 1 && ['Metal', 'Heavy Metal'].some(genre => genres.includes(genre))) {
  1781. while (genres.length > 1) genres.shift();
  1782. }
  1783. */
  1784. while (genres.length > 1) genres.shift();
  1785. }
  1786. });
  1787. bd = 16; channels = 2;
  1788. dom.querySelectorAll('span.album-quality__info').forEach(function(k) {
  1789. if (/\b([\d\.\,]+)\s*kHz\b/i.test(k.textContent) != null) sr = parseFloat(RegExp.$1.replace(',', '.'));
  1790. if (/\b(\d+)[\-\s]*Bits?\b/i.test(k.textContent) != null) bd = parseInt(RegExp.$1);
  1791. if (/\b(?:Stereo)\b/i.test(k.textContent)) channels = 2;
  1792. if (/\b(\d)\.(\d)\b/.test(k.textContent)) channels = parseInt(RegExp.$1) + parseInt(RegExp.$2);
  1793. });
  1794. get_desc_from_node('section#description > p', response.finalUrl, true);
  1795. if ((ref = dom.querySelector('a[title="Qobuzissime"]')) != null) {
  1796. description += '\x1C[align=center][url=https://www.qobuz.com' + ref.pathname +
  1797. '][img]https://ptpimg.me/4z35uj.png[/img][/url][/align]';
  1798. }
  1799. ref = dom.querySelectorAll('div.player__tracks > div.track > div.track__items');
  1800. let works = dom.querySelectorAll('div.player__tracks > p.player__work');
  1801. if (!totalTracks) totalTracks = ref.length;
  1802. ref.forEach(function(k) {
  1803. discSubtitle = null;
  1804. works.forEach(function(j) {
  1805. if (j.compareDocumentPosition(k) == Node.DOCUMENT_POSITION_FOLLOWING) discSubtitle = j
  1806. });
  1807. discSubtitle = discSubtitle != null ? discSubtitle.textContent.trim() : undefined;
  1808. if (/^\s*(?:dis[ck]|disco|disque)\s+(\d+)\s*$/i.test(discSubtitle)) {
  1809. discNumber = parseInt(RegExp.$1);
  1810. discSubtitle = undefined;
  1811. } else discNumber = undefined;
  1812. if (discNumber > totalDiscs) totalDiscs = discNumber;
  1813. trackNumber = parseInt(k.querySelector('span[itemprop="position"]').textContent.trim());
  1814. title = k.querySelector('span.track__item--name').textContent.trim().replace(/\s+/g, ' ');
  1815. duration = timeStringToTime(k.querySelector('span.track__item--duration').textContent);
  1816. trackArtist = undefined;
  1817. track = [
  1818. artist,
  1819. album,
  1820. albumYear,
  1821. releaseDate,
  1822. label,
  1823. undefined, // catalogue
  1824. undefined, // country
  1825. 'lossless',
  1826. 'FLAC',
  1827. undefined,
  1828. undefined,
  1829. bd,
  1830. sr * 1000,
  1831. channels,
  1832. 'WEB',
  1833. genres.join('; '),
  1834. discNumber,
  1835. totalDiscs,
  1836. discSubtitle,
  1837. trackNumber,
  1838. totalTracks,
  1839. title,
  1840. trackArtist,
  1841. undefined,
  1842. composer,
  1843. undefined,
  1844. undefined,
  1845. compiler,
  1846. producer,
  1847. duration,
  1848. undefined,
  1849. undefined,
  1850. undefined,
  1851. undefined,
  1852. undefined,
  1853. response.finalUrl,
  1854. undefined,
  1855. description,
  1856. undefined,
  1857. ];
  1858. tracks.push(track.join('\x1E'));
  1859. });
  1860. clipBoard.value = tracks.join('\n');
  1861. fill_from_text_music();
  1862. } });
  1863. return true;
  1864. } else if (url.toLowerCase().includes('highresaudio.com')) {
  1865. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1866. if (response.readyState != 4 || response.status != 200) return;
  1867. dom = domParser.parseFromString(response.responseText, 'text/html');
  1868. ref = dom.querySelector('h1 > span.artist');
  1869. if (ref != null) artist = ref.textContent.trim();
  1870. ref = dom.getElementById('h1-album-title');
  1871. if (ref != null) album = ref.firstChild.textContent.trim();
  1872. let genres = [], format;
  1873. dom.querySelectorAll('div.album-col-info-data > div > p').forEach(function(k) {
  1874. if (/\b(?:Genre|Subgenre)\b/i.test(k.firstChild.textContent)) genres.push(k.lastChild.textContent.trim());
  1875. if (/\b(?:Label)\b/i.test(k.firstChild.textContent)) label = k.lastChild.textContent.trim();
  1876. if (/\b(?:Album[\s\-]Release)\b/i.test(k.firstChild.textContent)) {
  1877. albumYear = normalizeDate(k.lastChild.textContent);
  1878. }
  1879. if (/\b(?:HRA[\s\-]Release)\b/i.test(k.firstChild.textContent)) {
  1880. releaseDate = normalizeDate(k.lastChild.textContent);
  1881. }
  1882. });
  1883. i = 0;
  1884. dom.querySelectorAll('tbody > tr > td.col-format').forEach(function(k) {
  1885. if (/^(FLAC)\s*([\d\.\,]+)\b/.exec(k.textContent) != null) {
  1886. format = RegExp.$1;
  1887. sr = parseFloat(RegExp.$2.replace(/,/g, '.'));
  1888. ++i;
  1889. }
  1890. });
  1891. if (i > 1) sr = undefined; // ambiguous
  1892. get_desc_from_node('div#albumtab-info > p', response.finalUrl);
  1893. ref = dom.querySelectorAll('ul.playlist > li.pltrack');
  1894. totalTracks = ref.length;
  1895. ref.forEach(function(k) {
  1896. discSubtitle = k;
  1897. while ((discSubtitle = discSubtitle.previousElementSibling) != null) {
  1898. if (discSubtitle.nodeName == 'LI' && discSubtitle.className == 'plinfo') {
  1899. discSubtitle = discSubtitle.textContent.replace(/\s*:$/, '').trim();
  1900. if (/\b(?:DIS[CK]|Volume|CD)\s*(\d+)\b/i.exec(discSubtitle)) discNumber = parseInt(RegExp.$1);
  1901. break;
  1902. }
  1903. }
  1904. //if (discnumber > totalDiscs) totalDiscs = discnumber;
  1905. trackNumber = parseInt(k.querySelector('span.track').textContent.trim());
  1906. title = k.querySelector('span.title').textContent.trim().replace(/\s+/g, ' ');
  1907. duration = timeStringToTime(k.querySelector('span.time').textContent);
  1908. trackArtist = undefined;
  1909. track = [
  1910. artist,
  1911. album,
  1912. albumYear,
  1913. releaseDate,
  1914. label,
  1915. undefined, // catalogue
  1916. undefined, // country
  1917. 'lossless',
  1918. 'FLAC', //format,
  1919. undefined,
  1920. undefined,
  1921. 24,
  1922. sr * 1000,
  1923. 2,
  1924. 'WEB',
  1925. genres.join('; '),
  1926. discNumber,
  1927. totalDiscs,
  1928. discSubtitle,
  1929. trackNumber,
  1930. totalTracks,
  1931. title,
  1932. trackArtist,
  1933. undefined,
  1934. composer,
  1935. undefined,
  1936. undefined,
  1937. compiler,
  1938. producer,
  1939. duration,
  1940. undefined,
  1941. undefined,
  1942. undefined,
  1943. undefined,
  1944. undefined,
  1945. response.finalUrl,
  1946. undefined,
  1947. description,
  1948. undefined,
  1949. ];
  1950. tracks.push(track.join('\x1E'));
  1951. });
  1952. clipBoard.value = tracks.join('\n');
  1953. fill_from_text_music();
  1954. } });
  1955. return true;
  1956. } else if (url.toLowerCase().includes('bandcamp.com')) {
  1957. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1958. if (response.readyState != 4 || response.status != 200) return;
  1959. dom = domParser.parseFromString(response.responseText, 'text/html');
  1960. ref = dom.querySelector('span[itemprop="byArtist"] > a');
  1961. if (ref != null) artist = ref.textContent.trim();
  1962. ref = dom.querySelector('h2[itemprop="name"]');
  1963. if (ref != null) album = ref.textContent.trim();
  1964. ref = dom.querySelector('div.tralbum-credits');
  1965. if (ref != null && /\breleased\s+(.*?\b\d{4})\b/i.test(ref.textContent)) {
  1966. releaseDate = RegExp.$1;
  1967. albumYear = releaseDate;
  1968. }
  1969. ref = dom.querySelector('p#band-name-location > span.title');
  1970. if (ref != null) label = ref.textContent.trim();
  1971. let tags = new TagManager;
  1972. dom.querySelectorAll('div.tralbum-tags > a.tag').forEach(k => { tags.add(k.textContent.trim()) });
  1973. description = [];
  1974. dom.querySelectorAll('div.tralbumData').forEach(function(k) {
  1975. if (!k.classList.contains('tralbum-tags')) description.push(html2php(k, response.finalUrl))
  1976. });
  1977. description = description.join('\n\n').replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  1978. ref = dom.querySelectorAll('table.track_list > tbody > tr[itemprop="tracks"]');
  1979. totalTracks = ref.length;
  1980. ref.forEach(function(k) {
  1981. trackNumber = parseInt(k.querySelector('div.track_number').textContent);
  1982. title = k.querySelector('span.track-title').textContent.trim().replace(/\s+/g, ' ');
  1983. duration = timeStringToTime(k.querySelector('span.time').textContent);
  1984. trackArtist = undefined;
  1985. track = [
  1986. artist,
  1987. album,
  1988. albumYear,
  1989. releaseDate,
  1990. label,
  1991. undefined, // catalogue
  1992. undefined, // country
  1993. undefined, //'lossless',
  1994. undefined, //'FLAC',
  1995. undefined,
  1996. undefined,
  1997. undefined,
  1998. undefined,
  1999. 2,
  2000. 'WEB',
  2001. tags.toString(),
  2002. discNumber,
  2003. totalDiscs,
  2004. undefined,
  2005. trackNumber,
  2006. totalTracks,
  2007. title,
  2008. trackArtist,
  2009. undefined,
  2010. composer,
  2011. undefined,
  2012. undefined,
  2013. compiler,
  2014. producer,
  2015. duration,
  2016. undefined,
  2017. undefined,
  2018. undefined,
  2019. undefined,
  2020. undefined,
  2021. response.finalUrl,
  2022. undefined,
  2023. description,
  2024. undefined,
  2025. ];
  2026. tracks.push(track.join('\x1E'));
  2027. });
  2028. clipBoard.value = tracks.join('\n');
  2029. fill_from_text_music();
  2030. } });
  2031. return true;
  2032. } else if (url.toLowerCase().includes('prestomusic.com')) {
  2033. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2034. if (response.readyState != 4 || response.status != 200) return;
  2035. dom = domParser.parseFromString(response.responseText, 'text/html');
  2036. artist = getArtists(dom.querySelectorAll('div.c-product-block__contributors > p'));
  2037. ref = dom.querySelector('h1.c-product-block__title');
  2038. if (ref != null) album = ref.lastChild.textContent.trim();
  2039. dom.querySelectorAll('div.c-product-block__metadata > ul > li').forEach(function(k) {
  2040. if (k.firstChild.textContent.includes('Release Date')) {
  2041. releaseDate = extract_year(k.lastChild.textContent);
  2042. } else if (k.firstChild.textContent.includes('Label')) {
  2043. label = k.lastChild.textContent.trim();
  2044. } else if (k.firstChild.textContent.includes('Catalogue No')) {
  2045. catalogue = k.lastChild.textContent.trim();
  2046. }
  2047. });
  2048. albumYear = releaseDate;
  2049. var genre;
  2050. if (/\/jazz\//i.test(response.finalUrl)) genre = 'Jazz';
  2051. if (/\/classical\//i.test(response.finalUrl)) genre = 'Classical';
  2052. get_desc_from_node('div#about > div > p', response.finalUrl, true);
  2053. ref = dom.querySelectorAll('div#related > div > ul > li');
  2054. composer = [];
  2055. ref.forEach(function(k) {
  2056. if (k.parentNode.previousElementSibling.textContent.includes('Composers')) {
  2057. composer.push(k.firstChild.textContent.trim().replace(/^(.*?)\s*,\s+(.*)$/, '$2 $1'));
  2058. }
  2059. });
  2060. composer = composer.join(', ') || undefined;
  2061. ref = dom.querySelectorAll('div.has--sample');
  2062. totalTracks = ref.length;
  2063. trackNumber = 0;
  2064. ref.forEach(function(it) {
  2065. trackNumber = ++trackNumber;
  2066. title = it.querySelector('p.c-track__title').textContent.trim().replace(/\s+/g, ' ');
  2067. duration = timeStringToTime(it.querySelector('div.c-track__duration').textContent);
  2068. let parent = it;
  2069. if (it.classList.contains('c-track')) {
  2070. parent = it.parentNode.parentNode;
  2071. if (parent.classList.contains('c-expander')) parent = parent.parentNode;
  2072. discSubtitle = parent.querySelector(':scope > div > div > div > p.c-track__title');
  2073. discSubtitle = discSubtitle != null ? discSubtitle.textContent.trim().replace(/\s+/g, ' ') : undefined;
  2074. } else {
  2075. discSubtitle = null;
  2076. }
  2077. trackArtist = getArtists(parent.querySelectorAll(':scope > div.c-track__details > ul > li'));
  2078. if (trackArtist.equalTo(artist)) trackArtist = [];
  2079. track = [
  2080. artist.join('; '),
  2081. album,
  2082. albumYear,
  2083. releaseDate,
  2084. label,
  2085. catalogue,
  2086. undefined, // country
  2087. undefined, // encoding
  2088. undefined, // format
  2089. undefined,
  2090. undefined, // bitrate
  2091. undefined, // BD
  2092. undefined, // SR
  2093. 2,
  2094. 'WEB',
  2095. genre,
  2096. discNumber,
  2097. totalDiscs,
  2098. discSubtitle,
  2099. trackNumber,
  2100. totalTracks,
  2101. title,
  2102. trackArtist.join(', '),
  2103. undefined,
  2104. composer,
  2105. undefined,
  2106. undefined,
  2107. compiler,
  2108. producer,
  2109. duration,
  2110. undefined,
  2111. undefined,
  2112. undefined,
  2113. undefined,
  2114. undefined,
  2115. response.finalUrl,
  2116. undefined,
  2117. description,
  2118. undefined,
  2119. ];
  2120. tracks.push(track.join('\x1E'));
  2121. });
  2122. clipBoard.value = tracks.join('\n');
  2123. fill_from_text_music();
  2124.  
  2125. function getArtists(nodeList) {
  2126. var artists = [];
  2127. nodeList.forEach(function(it) {
  2128. if (it.textContent.startsWith('Record')) return;
  2129. splitArtists(it.textContent.trim()).forEach(function(it) {
  2130. artists.push(it.replace(/\s*\([^\(\)]*\)$/, ''));
  2131. });
  2132. });
  2133. return artists;
  2134. }
  2135. } });
  2136. return true;
  2137. } else if (url.toLowerCase().includes('discogs.com/') && /\/releases?\/(\d+)\b/i.test(url)) {
  2138. GM_xmlhttpRequest({
  2139. method: 'GET',
  2140. url: 'https://api.discogs.com/releases/' + RegExp.$1,
  2141. responseType: 'json',
  2142. onload: function(response) {
  2143. if (response.readyState != 4 || response.status != 200) return;
  2144. var json = response.response;
  2145. const removeArtistNdx = /\s*\(\d+\)$/;
  2146. function getArtists(root) {
  2147. function filterArtists(rx, anv = true) {
  2148. return root.extraartists instanceof Array && rx instanceof RegExp ?
  2149. root.extraartists.filter(it => rx.test(it.role))
  2150. .map(it => (anv && it.anv || it.name || '').replace(removeArtistNdx, '')) : [];
  2151. }
  2152. var artists = [];
  2153. for (var ndx = 0; ndx < 7; ++ndx) artists[ndx] = [];
  2154. ndx = 0;
  2155. if (root.artists) root.artists.forEach(function(it) {
  2156. artists[ndx].push((it.anv || it.name).replace(removeArtistNdx, ''));
  2157. if (/^feat/i.test(it.join)) ndx = 1;
  2158. });
  2159. return [
  2160. artists[0],
  2161. artists[1].concat(filterArtists(/^(?:featuring)$/i)),
  2162. artists[2].concat(filterArtists(/\b(?:Remixed[\s\-]By|Remixer)\b/i)),
  2163. artists[3].concat(filterArtists(/\b(?:(?:Written|Composed)[\s\-]By|Composer)\b/i, false)),
  2164. artists[4].concat(filterArtists(/\b(?:Conducted[\s\-]By|Conductor)\b/i)),
  2165. artists[5].concat(filterArtists(/\b(?:Compiled[\s\-]By|Compiler)\b/i)),
  2166. artists[6].concat(filterArtists(/\b(?:Produced[\s\-]By|Producer)\b/i)),
  2167. // filter off from performers
  2168. filterArtists(/\b(?:(?:Mixed)[\s\-]By|Mixer)\b/i),
  2169. filterArtists(/\b(?:(?:Written|Composed)[\s\-]By|Composer)\b/i, true),
  2170. ];
  2171. }
  2172. var albumArtists = getArtists(json);
  2173. if (albumArtists[0].length > 0) {
  2174. artist = albumArtists[0].join('; ');
  2175. if (albumArtists[1].length > 0) artist += ' feat. ' + albumArtists[1].join('; ');
  2176. }
  2177. album = json.title;
  2178. var editions = [];
  2179. if (editions.length > 0) album += ' (' + editions.join(' / ') + ')';
  2180. label = [];
  2181. catalogue = [];
  2182. json.labels.forEach(function(it) {
  2183. //if (it.entity_type_name != 'Label') return;
  2184. if (!/^Not On Label\b/i.test(it.name)) label.pushUniqueCaseless(it.name.replace(removeArtistNdx, ''));
  2185. catalogue.pushUniqueCaseless(it.catno);
  2186. });
  2187. description = '';
  2188. if (json.companies && json.companies.length > 0) {
  2189. description = '[b]Companies, etc.[/b]\n';
  2190. let type_names = new Set(json.companies.map(it => it.entity_type_name));
  2191. type_names.forEach(function(type_name) {
  2192. description += '\n' + type_name + ' – ' + json.companies
  2193. .filter(it => it.entity_type_name == type_name)
  2194. .map(function(it) {
  2195. var result = '[url=https://www.discogs.com/label/' + it.id + ']' +
  2196. it.name.replace(removeArtistNdx, '') + '[/url]';
  2197. if (it.catno) result += ' – ' + it.catno;
  2198. return result;
  2199. })
  2200. .join(', ');
  2201. });
  2202. }
  2203. if (json.extraartists && json.extraartists.length > 0) {
  2204. if (description) description += '\n\n';
  2205. description += '[b]Credits[/b]\n';
  2206. let roles = new Set(json.extraartists.map(it => it.role));
  2207. roles.forEach(function(role) {
  2208. description += '\n' + role + ' – ' + json.extraartists
  2209. .filter(it => it.role == role)
  2210. .map(function(it) {
  2211. var result = '[url=https://www.discogs.com/artist/' + it.id + ']' +
  2212. (it.anv || it.name).replace(removeArtistNdx, '') + '[/url]';
  2213. if (it.tracks) result += ' (tracks: ' + it.tracks + ')';
  2214. return result;
  2215. })
  2216. .join(', ');
  2217. });
  2218. }
  2219. if (json.notes) {
  2220. if (description) description += '\n\n';
  2221. description += '[b]Notes[/b]\n\n' + json.notes.trim();
  2222. }
  2223. if (json.identifiers && json.identifiers.length > 0) {
  2224. if (description) description += '\n\n';
  2225. description += '[b]Barcode and Other Identifiers[/b]\n';
  2226. json.identifiers.forEach(function(it) {
  2227. description += '\n' + it.type;
  2228. if (it.description) description += ' (' + it.description + ')';
  2229. description += ': ' + it.value;
  2230. });
  2231. }
  2232. var identifiers = ['DISCOGS_ID=' + json.id];
  2233. [
  2234. ['Single', 'Single'],
  2235. ['EP', 'EP'],
  2236. ['Compilation', 'Compilation'],
  2237. ['Soundtrack', 'Soundtrack'],
  2238. ].forEach(function(k) {
  2239. if (json.formats.every(it => it.descriptions && it.descriptions.includesCaseless(k[0]))) {
  2240. identifiers.push('RELEASETYPE=' + k[1]);
  2241. }
  2242. });
  2243. json.identifiers.forEach(function(it) {
  2244. identifiers.push(it.type.replace(/\W+/g, '_').toUpperCase() + '=' + it.value.replace(/\s/g, '\x1B'));
  2245. });
  2246. json.formats.forEach(function(it) {
  2247. if (it.descriptions) it.descriptions.forEach(function(it) {
  2248. if (/^(?:.+?\s+Edition|Remaster(?:ed)|Reissue|.+?\s+Release|Enhanced|Promo)$/.test(it)) {
  2249. editions.push(it);
  2250. }
  2251. });
  2252. if (media) return;
  2253. if (it.name.includes('File')) {
  2254. if (['FLAC', 'WAV', 'AIF', 'AIFF', 'PCM'].some(k => it.descriptions.includes(k))) {
  2255. media = 'WEB'; encoding = 'lossless'; format = 'FLAC';
  2256. } else if (it.descriptions.includes('AAC')) {
  2257. media = 'WEB'; encoding = 'lossy'; format = 'AAC'; bd = undefined;
  2258. if (/(\d+)\s*kbps\b/i.test(it.text)) bitrate = parseInt(RegExp.$1);
  2259. } else if (it.descriptions.includes('MP3')) {
  2260. media = 'WEB'; encoding = 'lossy'; format = 'MP3'; bd = undefined;
  2261. if (/(\d+)\s*kbps\b/i.test(it.text)) bitrate = parseInt(RegExp.$1);
  2262. }
  2263. } else if (['CD', 'DVD', 'Vinyl', 'LP', '7"', '12"', '10"', '5"', 'SACD', 'Hybrid', 'Blu',
  2264. 'Cassette','Cartridge', 'Laserdisc', 'VCD'].some(k => it.name.includes(k))) media = it.name;
  2265. });
  2266. if (json.master_url) {
  2267. var yearWritable = elementWritable(document.getElementById('year'));
  2268. var tagsWritable = elementWritable(document.getElementById('tags'));
  2269. if (yearWritable || tagsWritable) GM_xmlhttpRequest({
  2270. method: 'GET',
  2271. url: json.master_url,
  2272. responseType: 'json',
  2273. onload: function(response) {
  2274. if (response.readyState != 4 || response.status != 200) return;
  2275. if (yearWritable && (albumYear = response.response.year) > 0) {
  2276. document.getElementById('year').value = albumYear;
  2277. }
  2278. if (tagsWritable) {
  2279. var tags = new TagManager();
  2280. if (json.genres) tags.add(...json.genres);
  2281. if (json.styles) tags.add(...json.styles);
  2282. if (response.response.genres) tags.add(...response.response.genres);
  2283. if (response.response.styles) tags.add(...response.response.styles);
  2284. if (tags.length > 0) document.getElementById('tags').value = tags.toString();
  2285. }
  2286. },
  2287. });
  2288. }
  2289. json.tracklist.forEach(function(track) {
  2290. if (track.type_.toLowerCase() == 'heading') {
  2291. discSubtitle = track.title;
  2292. } else if (track.type_.toLowerCase() == 'track') {
  2293. if (/^([a-zA-Z]+)?(\d+)-(\w+)$/.test(track.position)) {
  2294. if (RegExp.$1) identifiers.push('VOL_MEDIA=' + RegExp.$1.replace(/\s/g, '\x1B'));
  2295. discNumber = RegExp.$2;
  2296. trackNumber = RegExp.$3;
  2297. } else {
  2298. discNumber = undefined;
  2299. trackNumber = track.position;
  2300. }
  2301. let trackArtists = getArtists(track);
  2302. if (trackArtists[0].length > 0 && !trackArtists[0].equalTo(albumArtists[0])
  2303. || trackArtists[1].length > 0 && !trackArtists[1].equalTo(albumArtists[1])) {
  2304. trackArtist = (trackArtists[0].length > 0 ? trackArtists : albumArtists)[0].join('; ');
  2305. if (trackArtists[1].length > 0) trackArtist += ' feat. ' + trackArtists[1].join('; ');
  2306. } else {
  2307. trackArtist = null;
  2308. }
  2309. let performer = track.extraartists instanceof Array && track.extraartists
  2310. .map(artist => (artist.anv || artist.name).replace(removeArtistNdx, ''))
  2311. .filter(function(artist) {
  2312. return !albumArtists.slice(2).some(it => it instanceof Array && it.includes(artist))
  2313. && !trackArtists.slice(2).some(it => it instanceof Array && it.includes(artist))
  2314. });
  2315. track = [
  2316. artist,
  2317. album,
  2318. undefined, //json.year,
  2319. json.released,
  2320. label.join(' / '),
  2321. catalogue.join(' / '),
  2322. json.country,
  2323. encoding,
  2324. format,
  2325. undefined,
  2326. bitrate,
  2327. bd,
  2328. undefined, // samplerate
  2329. undefined, // channels
  2330. media,
  2331. (json.genres ? json.genres.join('; ') : '') + (json.styles ? ' | ' + json.styles.join('; ') : ''),
  2332. discNumber,
  2333. json.format_quantity,
  2334. discSubtitle,
  2335. trackNumber,
  2336. json.tracklist.length,
  2337. track.title,
  2338. trackArtist,
  2339. performer instanceof Array && performer.join('; ') || undefined,
  2340. stringyfyRole(3), // composers
  2341. stringyfyRole(4), // conductors
  2342. stringyfyRole(2), // remixers
  2343. stringyfyRole(5), // DJs/compilers
  2344. stringyfyRole(6), // producers
  2345. timeStringToTime(track.duration),
  2346. undefined,
  2347. undefined,
  2348. undefined,
  2349. undefined,
  2350. undefined,
  2351. undefined, //'https://www.discogs.com/release/' + json.id,
  2352. undefined,
  2353. description.replace(/\n/g, '\x1C').replace(/\r/g, '\x1D'),
  2354. identifiers.join(' '),
  2355. ];
  2356. tracks.push(track.join('\x1E'));
  2357.  
  2358. function stringyfyRole(ndx) {
  2359. return (trackArtists[ndx] instanceof Array && trackArtists[ndx].length > 0 ?
  2360. trackArtists : albumArtists)[ndx].join('; ');
  2361. }
  2362. }
  2363. });
  2364. clipBoard.value = tracks.join('\n');
  2365. fill_from_text_music();
  2366. },
  2367. });
  2368. return true;
  2369. } else if (url.toLowerCase().includes('supraphonline.cz')) {
  2370. GM_xmlhttpRequest({ method: 'GET', url: url.replace(/\?.*$/, ''), onload: function(response) {
  2371. if (response.readyState != 4 || response.status != 200)
  2372. throw new Error('Response error ' + response.status + ' (' + response.statusText + ')');
  2373. dom = domParser.parseFromString(response.responseText, 'text/html');
  2374. const copyrightParser = /^(?:\([PC]\)|℗|©)$/i;
  2375. var genre, ndx, conductor = [], origin = new URL(response.finalUrl).origin;
  2376. artist = [];
  2377. dom.querySelectorAll('h2.album-artist > a').forEach(function(it) {
  2378. artist.pushUnique(it.title);
  2379. });
  2380. isVA = false;
  2381. if (artist.length == 0 && (ref = dom.querySelector('h2.album-artist[title]')) != null) {
  2382. if (vaParser.test(ref.title)) isVA = true;
  2383. }
  2384. ref = dom.querySelector('span[itemprop="byArtist"] > meta[itemprop="name"]');
  2385. if (ref != null && vaParser.test(ref.content)) isVA = true;
  2386. if (isVA) artist = [];
  2387. if ((ref = dom.querySelector('h1[itemprop="name"]')) != null) album = ref.firstChild.data.trim();
  2388. if ((ref = dom.querySelector('meta[itemprop="numTracks"]')) != null) totalTracks = parseInt(ref.content);
  2389. if ((ref = dom.querySelector('meta[itemprop="genre"]')) != null) genre = ref.content;
  2390. if ((ref = dom.querySelector('li.album-version > div.selected > div')) != null) {
  2391. if (/\b(?:MP3)\b/.test(ref.textContent)) { media = 'WEB'; encoding = 'lossy'; format = 'MP3'; }
  2392. if (/\b(?:FLAC)\b/.test(ref.textContent)) { media = 'WEB'; encoding = 'lossless'; format = 'FLAC'; bd = 16; }
  2393. if (/\b(?:Hi[\s\-]*Res)\b/.test(ref.textContent)) { media = 'WEB'; encoding = 'lossless'; format = 'FLAC'; bd = 24; }
  2394. if (/\b(?:CD)\b/.test(ref.textContent)) { media = 'CD'; }
  2395. if (/\b(?:LP)\b/.test(ref.textContent)) { media = 'Vinyl'; }
  2396. }
  2397. dom.querySelectorAll('ul.summary > li').forEach(function(it) {
  2398. if (it.children.length < 1) return;
  2399. if (it.children[0].textContent.includes('Nosič')) media = it.lastChild.textContent.trim();
  2400. if (it.children[0].textContent.includes('Datum vydání')) releaseDate = normalizeDate(it.lastChild.textContent);
  2401. if (it.children[0].textContent.includes('První vydání')) albumYear = extract_year(it.lastChild.data);
  2402. //if (it.children[0].textContent.includes('Žánr')) genre = it.lastChild.textContent.trim();
  2403. if (it.children[0].textContent.includes('Vydavatel')) label = it.lastChild.textContent.trim();
  2404. if (it.children[0].textContent.includes('Katalogové číslo')) catalogue = it.lastChild.textContent.trim();
  2405. if (it.children[0].textContent.includes('Formát')) {
  2406. if (/\b(?:FLAC|WAV|AIFF?)\b/.test(it.lastChild.textContent)) { encoding = 'lossless'; format = 'FLAC'; }
  2407. if (/\b(\d+)[\-\s]?bits?\b/i.test(it.lastChild.textContent)) bd = parseInt(RegExp.$1);
  2408. if (/\b([\d\.\,]+)[\-\s]?kHz\b/.test(it.lastChild.textContent)) sr = parseFloat(RegExp.$1.replace(',', '.'));
  2409. }
  2410. if (it.children[0].textContent.includes('Celková stopáž')) totalTime = timeStringToTime(it.lastChild.textContent.trim());
  2411. if (copyrightParser.test(it.children[0].textContent) && !albumYear) albumYear = extract_year(it.lastChild.data);
  2412. });
  2413. const creators = ['autoři', 'interpreti', 'tělesa', 'digitalizace'];
  2414. artists = [];
  2415. for (i = 0; i < 4; ++i) artists[i] = {};
  2416. dom.querySelectorAll('ul.sidebar-artist > li').forEach(function(it) {
  2417. if ((ref = it.querySelector('h3')) != null) {
  2418. ndx = undefined;
  2419. creators.forEach((it, _ndx) => { if (ref.textContent.includes(it)) ndx = _ndx });
  2420. } else {
  2421. if (typeof ndx != 'number') return;
  2422. let role;
  2423. if (ndx == 2) role = 'ensemble';
  2424. else if ((ref = it.querySelector('span')) != null) role = translateRole(ref);
  2425. if ((ref = it.querySelector('a')) != null) {
  2426. if (!(artists[ndx][role] instanceof Array)) artists[ndx][role] = [];
  2427. var href = new URL(ref.href);
  2428. artists[ndx][role].pushUnique([ref.textContent.trim(), origin + href.pathname]);
  2429. }
  2430. }
  2431. });
  2432. get_desc_from_node('div[itemprop="description"] p', response.finalUrl, true);
  2433. composer = [];
  2434. var performers = [], DJs = [];
  2435. function dumpArtist(ndx, role) {
  2436. if (!role || role == 'undefined') return;
  2437. if (description.length > 0) description += '\x1C' ;
  2438. description += '[color=#9576b1]' + role + '[/color] – ';
  2439. //description += artists[ndx][role].map(artist => '[artist]' + artist[0] + '[/artist]').join(', ');
  2440. description += artists[ndx][role].map(artist => '[url=' + artist[1] + ']' + artist[0] + '[/url]').join(', ');
  2441. }
  2442. for (i = 1; i < 3; ++i) Object.keys(artists[i]).forEach(function(role) { // performers
  2443. var a = artists[i][role].map(a => a[0]);
  2444. artist.pushUnique(...a);
  2445. (['conductor', 'choirmaster'].includes(role) ? conductor : role == 'DJ' ? DJs : performers).pushUnique(...a);
  2446. if (i != 2) dumpArtist(i, role);
  2447. });
  2448. Object.keys(artists[0]).forEach(function(role) { // composers
  2449. composer.pushUnique(...artists[0][role].map(it => it[0])
  2450. .filter(it => !pseudoArtistParsers.some(rx => rx.test(it))));
  2451. dumpArtist(0, role);
  2452. });
  2453. Object.keys(artists[3]).forEach(role => { dumpArtist(3, role) }); // ADC & mastering
  2454. var promises = [];
  2455. dom.querySelectorAll('table.table-tracklist > tbody > tr').forEach(function(row) {
  2456. promises.push(row.id && (ref = row.querySelector('td > a.trackdetail')) != null ? new Promise(function(resolve, reject) {
  2457. var id = parseInt(row.id.replace(/^track-/i, ''));
  2458. GM_xmlhttpRequest({
  2459. method: 'GET',
  2460. url: origin + ref.pathname + ref.search,
  2461. context: id,
  2462. onload: function(response) {
  2463. if (response.readyState == 4 || response.status == 200) {
  2464. var domDetail = domParser.parseFromString(response.responseText, 'text/html');
  2465. var track = domDetail.getElementById('track-' + response.context);
  2466. if (track != null) {
  2467. resolve([track, domDetail.querySelector('div[data-swap="trackdetail-' + response.context + '"] > div > div.row')]);
  2468. } else reject('Track detail not located');
  2469. } else {
  2470. reject('Response error ' + response.status + ' (' + response.statusText + ')');
  2471. }
  2472. },
  2473. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  2474. ontimeout: function() { reject('Timeout') },
  2475. });
  2476. }) : Promise.resolve([row, null]));
  2477. });
  2478. Promise.all(promises).then(function(rows) {
  2479. rows.forEach(function(tr) {
  2480. if (!(tr[0] instanceof HTMLElement)) throw new Error('Assertion failed: tr[0] != HTMLElement');
  2481. if (tr[0].id && tr[0].classList.contains('track')) {
  2482. tr[2] = [];
  2483. for (i = 0; i < 8; ++i) tr[2][i] = [];
  2484. if (!(tr[1] instanceof HTMLElement)) return;
  2485. tr[1].querySelectorAll('div[class]:nth-of-type(2) > ul > li > span').forEach(function(li) {
  2486. function oneOf(...arr) { return arr.some(role => key == role) }
  2487. var key = translateRole(li);
  2488. var val = li.nextElementSibling.textContent.trim();
  2489. if (pseudoArtistParsers.some(rx => rx.test(val))) return;
  2490. if (key.startsWith('remix')) {
  2491. tr[2][2].pushUnique(val);
  2492. } else if (oneOf('music', 'lyrics', 'music+lyrics', 'original lyrics', 'czech lyrics', 'libreto', 'music improvisation', 'author')) {
  2493. tr[2][3].pushUnique(val);
  2494. } else if (oneOf('conductor', 'choirmaster')) {
  2495. tr[2][4].pushUnique(val);
  2496. } else if (key == 'DJ') {
  2497. tr[2][5].pushUnique(val);
  2498. } else if (key == 'produced by') {
  2499. tr[2][6].pushUnique(val);
  2500. } else if (key == 'recorded by') {
  2501. } else {
  2502. tr[2][7].pushUnique(val);
  2503. }
  2504. });
  2505. }
  2506. });
  2507. var guests = rows.filter(tr => tr.length >= 3).map(it => it[2][7])
  2508. .reduce((acc, trpf) => trpf.filter(trpf => acc.includes(trpf)))
  2509. .filter(it => !artist.includes(it));
  2510. rows.forEach(function(tr) {
  2511. if (tr[0].classList.contains('cd-header')) {
  2512. discNumber = /\b\d+\b/.test(tr[0].querySelector('h3').firstChild.data.trim())
  2513. && parseInt(RegExp.lastMatch) || undefined;
  2514. }
  2515. if (tr[0].classList.contains('song-header')) {
  2516. discSubtitle = tr[0].children[0].title.trim() || undefined;
  2517. }
  2518. if (tr[0].id && tr[0].classList.contains('track')) {
  2519. var copyright, trackGenre, trackYear, recordPlace, recordDate, identifiers = '';
  2520. if (/^track-(\d+)$/i.test(tr[0].id)) identifiers = 'TRACK_ID=' + RegExp.$1;
  2521. trackNumber = /^\s*(\d+)\.?\s*$/.test(tr[0].children[0].firstChild.textContent) ?
  2522. parseInt(RegExp.$1) : undefined;
  2523. title = tr[0].querySelector('meta[itemprop="name"]').content;
  2524. duration = (ref = tr[0].querySelector('meta[itemprop="duration"]')) != null
  2525. && /^PT(\d+)H(\d+)M(\d+)S$/i.test(ref.content) ?
  2526. parseInt(RegExp.$1 || 0) * 60**2 + parseInt(RegExp.$2 || 0) * 60 + parseInt(RegExp.$3 || 0) : undefined;
  2527. if (tr[1] instanceof HTMLElement) {
  2528. tr[1].querySelectorAll('div[class]:nth-of-type(1) > ul > li > span').forEach(function(li) {
  2529. if (li.textContent.startsWith('Nahrávka dokončena')) {
  2530. identifiers += ' RECYEAR=' + extract_year(recordDate = li.nextSibling.data.trim());
  2531. }
  2532. if (li.textContent.startsWith('Místo nahrání')) {
  2533. recordPlace = li.nextSibling.data.trim();
  2534. }
  2535. if (li.textContent.startsWith('Rok prvního vydání')) {
  2536. identifiers += ' PUBYEAR=' + (trackYear = parseInt(li.nextSibling.data));
  2537. }
  2538. //if (copyrightParser.test(li.textContent)) copyright = li.nextSibling.data.trim();
  2539. if (li.textContent.startsWith('Žánr')) trackGenre = li.nextSibling.data.trim();
  2540. });
  2541. }
  2542. if (!isVA && tr[2][0].equalTo(artist)) tr[2][0] = [];
  2543. track = [
  2544. isVA ? 'Various Artists' : artist.join('; '),
  2545. album,
  2546. /*trackYear || */albumYear || undefined,
  2547. releaseDate,
  2548. label,
  2549. catalogue,
  2550. undefined, // country
  2551. encoding,
  2552. format,
  2553. undefined,
  2554. undefined,
  2555. bd,
  2556. sr * 1000,
  2557. 2,
  2558. media,
  2559. translateGenre(genre) + ' | ' + translateGenre(trackGenre),
  2560. discNumber,
  2561. totalDiscs,
  2562. discSubtitle,
  2563. trackNumber,
  2564. totalTracks,
  2565. title,
  2566. joinArtists(tr[2][0]),
  2567. tr[2][7].join('; ') || performers.join('; '),
  2568. tr[2][3].join(', ') || composer.join(', '),
  2569. tr[2][4].join('; ') || conductor.join('; '),
  2570. tr[2][2].join('; '),
  2571. tr[2][5].join('; ') || DJs.join('; '),
  2572. tr[2][6].join('; '),
  2573. duration,
  2574. undefined,
  2575. undefined,
  2576. undefined,
  2577. undefined,
  2578. undefined,
  2579. response.finalUrl,
  2580. undefined,
  2581. description,
  2582. identifiers,
  2583. ];
  2584. tracks.push(track.join('\x1E'));
  2585. }
  2586. });
  2587. clipBoard.value = tracks.join('\n');
  2588. fill_from_text_music();
  2589. }).catch(e => { alert(e) });
  2590.  
  2591. function translateGenre(genre) {
  2592. if (!genre || typeof genre != 'string') return undefined;
  2593. [
  2594. ['Orchestrální hudba', 'Orchestral Music'],
  2595. ['Komorní hudba', 'Chamber Music'],
  2596. ['Vokální', 'Classical, Vocal'],
  2597. ['Klasická hudba', 'Classical'],
  2598. ['Melodram', 'Classical, Melodram'],
  2599. ['Symfonie', 'Symphony'],
  2600. ['Vánoční hudba', 'Christmas Music'],
  2601. [/^(?:Alternativ(?:ní|a))$/i, 'Alternative'],
  2602. ['Dechová hudba', 'Brass Music'],
  2603. ['Elektronika', 'Electronic'],
  2604. ['Folklor', 'Folclore, World Music'],
  2605. ['Instrumentální hudba', 'Instrumental'],
  2606. ['Latinské rytmy', 'Latin'],
  2607. ['Meditační hudba', 'Meditative'],
  2608. ['Pro děti', 'Children'],
  2609. ['Pro dospělé', 'Adult'],
  2610. ['Mluvené slovo', 'Spoken Word'],
  2611. ['Audiokniha', 'audiobook'],
  2612. ['Humor', 'humour'],
  2613. ['Pohádka', 'Fairy-Tale'],
  2614. ].forEach(function(subst) {
  2615. if (typeof subst[0] == 'string' && genre.toLowerCase() == subst[0].toLowerCase()
  2616. || subst[0] instanceof RegExp && subst[0].test(genre)) genre = subst[1];
  2617. });
  2618. return genre;
  2619. }
  2620. function translateRole(elem) {
  2621. if (!(elem instanceof HTMLElement)) return undefined;
  2622. var role = elem.textContent.trim().toLowerCase().replace(/\s*:.*$/, '');
  2623. [
  2624. [/\b(?:klavír)\b/, 'piano'],
  2625. [/\b(?:housle)\b/, 'violin'],
  2626. [/\b(?:varhany)\b/, 'organ'],
  2627. [/\b(?:cembalo)\b/, 'harpsichord'],
  2628. [/\b(?:trubka)\b/, 'trumpet'],
  2629. [/\b(?:soprán)\b/, 'soprano'],
  2630. [/\b(?:alt)\b/, 'alto'],
  2631. [/\b(?:baryton)\b/, 'baritone'],
  2632. [/\b(?:bas)\b/, 'basso'],
  2633. [/\b(?:syntezátor)\b/, 'synthesizer'],
  2634. [/\b(?:zpěv)\b/, 'vocals'],
  2635. [/^(?:čte|četba)$/, 'narration'],
  2636. ['vypravuje', 'narration'],
  2637. ['komentář', 'commentary'],
  2638. ['hovoří', 'spoken by'],
  2639. ['hovoří a zpívá', 'speaks and sings'],
  2640. ['improvizace', 'improvisation'],
  2641. ['hudební těleso', 'ensemble'],
  2642. ['hudba', 'music'],
  2643. ['text', 'lyrics'],
  2644. ['hudba+text', 'music+lyrics'],
  2645. ['původní text', 'original lyrics'],
  2646. ['český text', 'czech lyrics'],
  2647. ['hudební improvizace', 'music improvisation'],
  2648. ['autor', 'author'],
  2649. ['účinkuje', 'participating'],
  2650. ['řídí', 'conductor'],
  2651. ['dirigent', 'conductor'],
  2652. ['sbormistr', 'choirmaster'],
  2653. ['produkce', 'produced by'],
  2654. ['nahrál', 'recorded by'],
  2655. ['digitální přepis', 'A/D transfer'],
  2656. ].forEach(function(subst) {
  2657. if (typeof subst[0] == 'string' && role.toLowerCase() == subst[0].toLowerCase()
  2658. || subst[0] instanceof RegExp && subst[0].test(role)) role = role.replace(subst[0], subst[1]);
  2659. });
  2660. return role;
  2661. }
  2662. } });
  2663. return true;
  2664. } else if (url.toLowerCase().includes('bontonland.cz')) {
  2665. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2666. if (response.readyState != 4 || response.status != 200) return;
  2667. dom = domParser.parseFromString(response.responseText, 'text/html');
  2668. ref = dom.querySelector('div#detailheader > h1');
  2669. if (ref != null && /^(.*?)\s*:\s*(.*)$/.test(ref.textContent.trim())) {
  2670. artist = RegExp.$1;
  2671. album = RegExp.$2;
  2672. }
  2673. var EAN;
  2674. dom.querySelectorAll('table > tbody > tr > td.nazevparametru').forEach(function(it) {
  2675. if (it.textContent.includes('Datum vydání')) {
  2676. releaseDate = normalizeDate(it.nextElementSibling.textContent);
  2677. albumYear = extract_year(it.nextElementSibling.textContent);
  2678. } else if (it.textContent.includes('Nosič / počet')) {
  2679. if (/^(.*?)\s*\/\s*(.*)$/.test(it.nextElementSibling.textContent)) {
  2680. media = RegExp.$1;
  2681. totalDiscs = RegExp.$2;
  2682. }
  2683. } else if (it.textContent.includes('Interpret')) {
  2684. artist = it.nextElementSibling.textContent.trim();
  2685. } else if (it.textContent.includes('EAN')) {
  2686. EAN = 'BARCODE=' + it.nextElementSibling.textContent.trim();
  2687. }
  2688. });
  2689. get_desc_from_node('div#detailtabpopis > div[class^="pravy"] > div > p:not(:last-of-type)', response.finalUrl, true);
  2690. const plParser = /^(\d+)(?:\s*[\/\.\-\:\)])?\s+(.*?)(?:\s+((?:(?:\d+:)?\d+:)?\d+))?$/;
  2691. ref = dom.querySelector('div#detailtabpopis > div[class^="pravy"] > div > p:last-of-type');
  2692. if (ref == null) throw new Error('Playlist not located');
  2693. var trackList = html2php(ref).split(/[\r\n]+/);
  2694. trackList = trackList.filter(it => plParser.test(it.trim())).map(it => plParser.exec(it.trim()));
  2695. totalTracks = trackList.length;
  2696. if (!totalTracks) throw new Error('Playlist empty');
  2697. trackList.forEach(function(it) {
  2698. trackNumber = it[1];
  2699. title = it[2];
  2700. duration = timeStringToTime(it[3]);
  2701. trackArtist = undefined;
  2702. track = [
  2703. artist,
  2704. album,
  2705. albumYear,
  2706. releaseDate,
  2707. label,
  2708. undefined, // catalogue
  2709. undefined, // country
  2710. undefined, // encoding
  2711. undefined, // format
  2712. undefined,
  2713. undefined,
  2714. undefined,
  2715. undefined,
  2716. undefined,
  2717. 'CD', // media
  2718. undefined, // genre
  2719. discNumber,
  2720. totalDiscs,
  2721. discSubtitle,
  2722. trackNumber,
  2723. totalTracks,
  2724. title,
  2725. trackArtist,
  2726. undefined,
  2727. undefined, // composer
  2728. undefined,
  2729. undefined,
  2730. undefined, // compiler
  2731. undefined, // producer
  2732. duration,
  2733. undefined,
  2734. undefined,
  2735. undefined,
  2736. undefined,
  2737. undefined,
  2738. response.finalUrl,
  2739. undefined,
  2740. description,
  2741. EAN,
  2742. ];
  2743. tracks.push(track.join('\x1E'));
  2744. });
  2745. clipBoard.value = tracks.join('\n');
  2746. fill_from_text_music();
  2747. } });
  2748. return true;
  2749. } else if (url.toLowerCase().includes('nativedsd.com')) {
  2750. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2751. if (response.readyState != 4 || response.status != 200) return;
  2752. dom = domParser.parseFromString(response.responseText, 'text/html');
  2753. var NDSD_ID = 'ORIGINALFORMAT=DSD', genre;
  2754. ref = dom.querySelector('div.the-content > header > h2');
  2755. if (ref != null) artist = ref.firstChild.data.trim();
  2756. ref = dom.querySelector('div.the-content > header > h1');
  2757. if (ref != null) album = ref.firstChild.data.trim();
  2758. ref = dom.querySelector('div.the-content > header > h3');
  2759. if (ref != null) composer = ref.firstChild.data.trim();
  2760. ref = dom.querySelector('div.the-content > header > h1 > small');
  2761. if (ref != null) albumYear = extract_year(ref.firstChild.data);
  2762. releaseDate = albumYear; // weak
  2763. ref = dom.querySelector('div#breadcrumbs > div[class] > a:nth-of-type(2)');
  2764. if (ref != null) label = ref.firstChild.data.trim();
  2765. ref = dom.querySelector('h2#sku');
  2766. if (ref != null) {
  2767. if (/^Catalog Number: (.*)$/m.test(ref.firstChild.textContent)) catalogue = RegExp.$1;
  2768. if (/^ID: (.*)$/m.test(ref.lastChild.textContent)) NDSD_ID += ' NATIVEDSD_ID=' + RegExp.$1;
  2769. }
  2770. get_desc_from_node('div.the-content > div.entry > p', response.finalUrl, false);
  2771. ref = dom.querySelector('div#repertoire > div > p');
  2772. if (ref != null) {
  2773. let repertoire = html2php(ref, url).trim();
  2774. let ndx = repertoire.indexOf('\n[b]Track');
  2775. if (description) description += '\x1C\x1C';
  2776. description += (ndx >= 0 ? repertoire.slice(0, ndx).trim() : repertoire)
  2777. .replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  2778. }
  2779. ref = dom.querySelectorAll('div#techspecs > table > tbody > tr');
  2780. if (ref.length > 0) {
  2781. if (description) description += '\x1C\x1C';
  2782. description += '[b][u]Tech specs[/u][/b]';
  2783. ref.forEach(function(it) {
  2784. description += '\n[b]'.concat(it.children[0].textContent.trim(), '[/b] ',
  2785. it.children[1].textContent.trim()).replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  2786. });
  2787. }
  2788. ref = dom.querySelectorAll('div#track-list > table > tbody > tr[id^="track"]');
  2789. totalTracks = ref.length;
  2790. ref.forEach(function(it) {
  2791. ref = it.children[0].children[0];
  2792. if (ref != null) trackNumber = parseInt(ref.firstChild.data.trim().replace(/\..*$/, ''));
  2793. let trackComposer;
  2794. ref = it.children[1];
  2795. if (ref != null) {
  2796. title = ref.firstChild.textContent.trim();
  2797. trackComposer = ref.childNodes[2] && ref.childNodes[2].textContent.trim() || undefined;
  2798. }
  2799. ref = it.children[2];
  2800. if (ref != null) duration = timeStringToTime(ref.firstChild.data);
  2801. track = [
  2802. artist,
  2803. album,
  2804. albumYear,
  2805. releaseDate,
  2806. label,
  2807. catalogue,
  2808. undefined, // country
  2809. 'lossless', // encoding
  2810. 'FLAC', // format
  2811. undefined,
  2812. undefined, // bitrate
  2813. 24, //bd,
  2814. 88200,
  2815. 2,
  2816. 'WEB',
  2817. genre, // 'Jazz'
  2818. discNumber,
  2819. totalDiscs,
  2820. discSubtitle,
  2821. trackNumber,
  2822. totalTracks,
  2823. title,
  2824. trackArtist,
  2825. undefined,
  2826. trackComposer || composer,
  2827. undefined,
  2828. undefined,
  2829. compiler,
  2830. producer,
  2831. duration,
  2832. undefined,
  2833. undefined,
  2834. undefined,
  2835. undefined,
  2836. undefined,
  2837. response.finalUrl,
  2838. undefined,
  2839. description,
  2840. NDSD_ID + ' TRACK_ID=' + it.id.replace(/^track-/i, ''),
  2841. ];
  2842. tracks.push(track.join('\x1E'));
  2843. });
  2844. clipBoard.value = tracks.join('\n');
  2845. fill_from_text_music();
  2846.  
  2847. function getArtists(elem) {
  2848. if (elem == null) return undefined;
  2849. var artists = [];
  2850. splitArtists(elem.textContent.trim()).forEach(function(it) {
  2851. artists.push(it.replace(/\s*\([^\(\)]*\)$/, ''));
  2852. });
  2853. return artists.join(', ');
  2854. }
  2855. } });
  2856. return true;
  2857. } else if (url.toLowerCase().includes('junodownload.com')) {
  2858. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2859. if (response.readyState != 4 || response.status != 200) return;
  2860. dom = domParser.parseFromString(response.responseText, 'text/html');
  2861. ref = dom.querySelector('h2.product-artist > a');
  2862. if (ref != null) artist = titleCase(ref.firstChild.data.trim());
  2863. ref = dom.querySelector('meta[itemprop="name"]');
  2864. if (ref != null) album = ref.content;
  2865. ref = dom.querySelector('meta[itemprop="author"]');
  2866. if (ref != null) label = ref.content;
  2867. ref = dom.querySelector('span[itemprop="datePublished"]');
  2868. if (ref != null) releaseDate = ref.firstChild.data.trim();
  2869. var genres = [];
  2870. dom.querySelectorAll('div.mb-3 > strong').forEach(function(it) {
  2871. if (it.textContent.startsWith('Genre')) {
  2872. ref = it;
  2873. while ((ref = ref.nextElementSibling) != null && ref.nodeName == 'A') {
  2874. genres.push(ref.textContent.trim());
  2875. }
  2876. } else if (it.textContent.startsWith('Cat')) {
  2877. if ((ref = it.nextSibling) != null && ref.nodeType == 3) catalogue = ref.data;
  2878. }
  2879. });
  2880.  
  2881. ref = dom.querySelectorAll('div.product-tracklist > div[itemprop="track"]');
  2882. totalTracks = ref.length;
  2883. ref.forEach(function(it) {
  2884. trackNumber = it.querySelector('div.track-title').firstChild.data.trim();
  2885. if (/^(\d+)\./.test(trackNumber)) trackNumber = parseInt(RegExp.$1);
  2886. title = it.querySelector('span[itemprop="name"]').textContent.trim();
  2887. i = it.querySelector('meta[itemprop="duration"]');
  2888. duration = i != null && /^P(\d+)H(\d+)M(\d+)S$/i.test(i.content) ?
  2889. (parseInt(RegExp.$1) || 0) * 60**2 + (parseInt(RegExp.$2) || 0) * 60 + (parseInt(RegExp.$3) || 0) : undefined;
  2890. track = [
  2891. artist,
  2892. album,
  2893. albumYear,
  2894. releaseDate,
  2895. label,
  2896. catalogue,
  2897. undefined, // country
  2898. undefined, // encoding
  2899. undefined, // format
  2900. undefined,
  2901. undefined, // bitrate
  2902. undefined, //bd,
  2903. undefined, // SR
  2904. 2,
  2905. 'WEB',
  2906. genres.join('; '),
  2907. discNumber,
  2908. totalDiscs,
  2909. discSubtitle,
  2910. trackNumber,
  2911. totalTracks,
  2912. title,
  2913. trackArtist,
  2914. undefined,
  2915. composer,
  2916. undefined,
  2917. undefined,
  2918. compiler,
  2919. producer,
  2920. duration,
  2921. undefined,
  2922. undefined,
  2923. undefined,
  2924. undefined,
  2925. undefined,
  2926. response.finalUrl,
  2927. undefined,
  2928. undefined, // description
  2929. 'BPM=' + it.children[2].textContent.trim(),
  2930. ];
  2931. tracks.push(track.join('\x1E'));
  2932. });
  2933. clipBoard.value = tracks.join('\n');
  2934. fill_from_text_music();
  2935.  
  2936. function getArtists(elem) {
  2937. if (elem == null) return undefined;
  2938. var artists = [];
  2939. splitArtists(elem.textContent.trim()).forEach(function(it) {
  2940. artists.push(it.replace(/\s*\([^\(\)]*\)$/, ''));
  2941. });
  2942. return artists.join(', ');
  2943. }
  2944. } });
  2945. return true;
  2946. } else if (url.toLowerCase().includes('hdtracks.com')) {
  2947. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2948. if (response.readyState != 4 || response.status != 200) return;
  2949. dom = domParser.parseFromString(response.responseText, 'text/html');
  2950. var genres = [];
  2951. dom.querySelectorAll('div.album-main-details > ul > li > span').forEach(function(it) {
  2952. if (it.textContent.startsWith('Title')) album = it.nextSibling.data.trim();
  2953. if (it.textContent.startsWith('Artist')) artist = it.nextElementSibling.textContent.trim();
  2954. if (it.textContent.startsWith('Genre')) {
  2955. ref = it;
  2956. while ((ref = ref.nextElementSibling) != null) genres.push(ref.textContent.trim());
  2957. }
  2958. if (it.textContent.startsWith('Label')) label = it.nextElementSibling.textContent.trim();
  2959. if (it.textContent.startsWith('Release Date')) releaseDate = normalizeDate(it.nextSibling.data.trim());
  2960. });
  2961. if (!albumYear) albumYear = extract_year(releaseDate);
  2962. ref = dom.querySelectorAll('table#track-table > tbody > tr[id^="track"]');
  2963. totalTracks = ref.length;
  2964. ref.forEach(function(it) {
  2965. trackNumber = parseInt(it.querySelector('td:first-of-type').textContent.trim());
  2966. title = it.querySelector('td.track-name').textContent.trim();
  2967. duration = timeStringToTime(it.querySelector('td:nth-of-type(3)').textContent.trim());
  2968. format = it.querySelector('td:nth-of-type(4) > span').textContent.trim();
  2969. sr = it.querySelector('td:nth-of-type(5)').textContent.trim().replace(/\/.*/, '');
  2970. if (/^([\d\.\,]+)\s*\/\s*(\d+)$/.test(sr)) {
  2971. sr = Math.round(parseFloat(RegExp.$1.replace(',', '.')) * 1000);
  2972. bd = parseInt(RegExp.$2);
  2973. } else sr = Math.round(parseFloat(sr) * 1000);
  2974. track = [
  2975. artist,
  2976. album,
  2977. albumYear,
  2978. releaseDate,
  2979. label,
  2980. catalogue,
  2981. undefined, // country
  2982. 'lossless',
  2983. undefined, // format
  2984. undefined,
  2985. undefined, // bitrate
  2986. bd || 24,
  2987. sr || undefined,
  2988. 2,
  2989. 'WEB',
  2990. genres.join('; '),
  2991. discNumber,
  2992. totalDiscs,
  2993. discSubtitle,
  2994. trackNumber,
  2995. totalTracks,
  2996. title,
  2997. trackArtist,
  2998. undefined,
  2999. composer,
  3000. undefined,
  3001. undefined,
  3002. compiler,
  3003. producer,
  3004. duration,
  3005. undefined,
  3006. undefined,
  3007. undefined,
  3008. undefined,
  3009. undefined,
  3010. response.finalUrl,
  3011. undefined,
  3012. undefined, // description
  3013. undefined,
  3014. ];
  3015. tracks.push(track.join('\x1E'));
  3016. });
  3017. clipBoard.value = tracks.join('\n');
  3018. fill_from_text_music();
  3019. } });
  3020. return true;
  3021. } else if (/^https?:\/\/(?:\w+\.)?deezer\.com\/(?:\w+\/)*album\/(\d+)/i.test(url)) {
  3022. GM_xmlhttpRequest({
  3023. method: 'GET',
  3024. url: 'https://api.deezer.com/album/' + RegExp.$1,
  3025. responseType: 'json',
  3026. onload: function(response) {
  3027. if (response.readyState != 4 || response.status != 200) throw new Error('Ready state ' + response.readyState + ', Response error ' + response.status + ' (' + response.statusText + ')');
  3028. var json = response.response;
  3029. isVA = vaParser.test(json.artist.name);
  3030. var identifiers = 'DEEZER_ID=' + json.id + ' RELEASETYPE=' + json.record_type;
  3031. json.tracks.data.forEach(function(track, ndx) {
  3032. trackArtist = track.artist.name;
  3033. if (!isVA && trackArtist && trackArtist == json.artist.name) trackArtist = undefined;
  3034. track = [
  3035. isVA ? 'Various Artists' : json.artist.name,
  3036. json.title,
  3037. undefined, //extract_year(json.release_date),
  3038. json.release_date,
  3039. json.label,
  3040. json.upc,
  3041. undefined, // country
  3042. undefined, // encoding
  3043. undefined, // format
  3044. undefined,
  3045. undefined, // bitrate
  3046. undefined, //bd,
  3047. undefined, // SR
  3048. 2,
  3049. 'WEB',
  3050. json.genres.data.map(it => it.name).join('; '),
  3051. discNumber,
  3052. totalDiscs,
  3053. discSubtitle,
  3054. ndx + 1,
  3055. json.nb_tracks,
  3056. track.title,
  3057. trackArtist,
  3058. undefined,
  3059. composer,
  3060. undefined,
  3061. undefined,
  3062. compiler,
  3063. producer,
  3064. track.duration,
  3065. undefined,
  3066. undefined,
  3067. undefined,
  3068. undefined,
  3069. undefined,
  3070. undefined, //'https://www.deezer.com/album/' + json.id,
  3071. undefined,
  3072. undefined, // description
  3073. identifiers + ' TRACK_ID=' + track.id,
  3074. ];
  3075. tracks.push(track.join('\x1E'));
  3076. });
  3077. clipBoard.value = tracks.join('\n');
  3078. fill_from_text_music();
  3079. },
  3080. });
  3081. return true;
  3082. } else if (/^https?:\/\/(?:\w+\.)?spotify\.com\/(?:\w+\/)*albums?\/(\w+)/i.test(url)) {
  3083. querySpotifyAPI('https://api.spotify.com/v1/albums/' + RegExp.$1).then(function(json) {
  3084. isVA = json.artists.length == 1 && vaParser.test(json.artists[0].name);
  3085. artist = json.artists.map(artist => artist.name);
  3086. totalDiscs = json.tracks.items.reduce((acc, track) => Math.max(acc, track.disc_number), 0);
  3087. var identifiers = 'RELEASETYPE=' + json.album_type + ' SPOTIFY_ID=' + json.id;
  3088. var image = json.images.reduce((acc, image) => image.width * image.height > acc.width * acc.height ? image : acc);
  3089. //if (image) identifiers += ' IMGURL=' + image.url;
  3090. json.tracks.items.forEach(function(track, ndx) {
  3091. trackArtist = track.artists.map(artist => artist.name);
  3092. if (!isVA && json.artists.length > 0 && trackArtist.equalTo(artist)) trackArtist = [];
  3093. track = [
  3094. isVA ? 'Various Artists' : joinArtists(artist),
  3095. json.name,
  3096. undefined, //extract_year(json.release_date),
  3097. json.release_date,
  3098. json.label,
  3099. json.external_ids.upc,
  3100. undefined, // country
  3101. undefined, // encoding
  3102. undefined, // format
  3103. undefined,
  3104. undefined, // bitrate
  3105. undefined, // BD
  3106. undefined, // SR
  3107. 2,
  3108. 'WEB',
  3109. json.genres.join('; '),
  3110. totalDiscs > 1 ? track.disc_number : undefined,
  3111. totalDiscs > 1 ? totalDiscs : undefined,
  3112. undefined, // discSubtitle
  3113. track.track_number,
  3114. json.total_tracks,
  3115. track.name,
  3116. joinArtists(trackArtist),
  3117. undefined,
  3118. composer,
  3119. undefined,
  3120. undefined,
  3121. compiler,
  3122. producer,
  3123. track.duration_ms / 1000,
  3124. undefined,
  3125. undefined,
  3126. undefined,
  3127. undefined,
  3128. undefined,
  3129. undefined, //'https://open.spotify.com/album/' + json.id,
  3130. undefined,
  3131. undefined, // description
  3132. identifiers +
  3133. ' EXPLICIT=' + Number(track.explicit) +
  3134. ' TRACK_ID=' + track.id,
  3135. ];
  3136. tracks.push(track.join('\x1E'));
  3137. });
  3138. clipBoard.value = tracks.join('\n');
  3139. fill_from_text_music();
  3140. }).catch(e => { alert(e) });
  3141. return true;
  3142.  
  3143. function querySpotifyAPI(api_url) {
  3144. if (!api_url) return Promise.reject('No API URL');
  3145. return setToken().then(function(credentials) {
  3146. return new Promise(function(resolve, reject) {
  3147. GM_xmlhttpRequest({
  3148. method: 'GET',
  3149. url: api_url,
  3150. headers: {
  3151. 'Accept': 'application/json',
  3152. 'Authorization': credentials.token_type + ' ' + credentials.access_token,
  3153. },
  3154. responseType: 'json',
  3155. onload: function(response) {
  3156. if (response.readyState == 4 && response.status == 200) resolve(response.response);
  3157. else reject('Response error ' + response.status + ' (' + response.statusText + ')');
  3158. },
  3159. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  3160. ontimeout: function() { reject('Timeout') },
  3161. });
  3162. });
  3163. });
  3164. }
  3165. function setToken() {
  3166. if (isTokenValid()) return Promise.resolve(spotifyCredentials);
  3167. if (!prefs.spotify_clientid || !prefs.spotify_clientsecret) return Promise.reject('Spotify credentials not set');
  3168. return new Promise(function(resolve, reject) {
  3169. const data = new URLSearchParams({
  3170. grant_type: 'client_credentials',
  3171. });
  3172. GM_xmlhttpRequest({
  3173. method: 'POST',
  3174. url: 'https://accounts.spotify.com/api/token',
  3175. headers: {
  3176. 'Content-Type': 'application/x-www-form-urlencoded',
  3177. 'Content-Length': data.toString().length,
  3178. 'Authorization': 'Basic ' + btoa(prefs.spotify_clientid + ':' + prefs.spotify_clientsecret),
  3179. },
  3180. responseType: 'json',
  3181. data: data.toString(),
  3182. onload: function(response) {
  3183. if (response.readyState == 4 && response.status == 200) {
  3184. spotifyCredentials = response.response;
  3185. spotifyCredentials.expires = new Date().getTime() + spotifyCredentials.expires_in;
  3186. if (isTokenValid()) resolve(spotifyCredentials); else reject('Invalid token');
  3187. } else reject('Response error ' + response.status + ' (' + JSON.parse(response.response).error + ')');
  3188. },
  3189. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  3190. ontimeout: function() { reject('Timeout') },
  3191. });
  3192. });
  3193. }
  3194. function isTokenValid() {
  3195. return spotifyCredentials.token_type && spotifyCredentials.token_type.toLowerCase() == 'bearer'
  3196. && spotifyCredentials.access_token && spotifyCredentials.expires >= new Date().getTime() + 30;
  3197. }
  3198. } else if (url.toLowerCase().includes('soundcloud.com') && prefs.soundcloud_clientid) {
  3199. // SC.initialize({
  3200. // client_id: prefs.soundcloud_clientid,
  3201. // redirect_uri: 'https://dont.spam.me/',
  3202. // });
  3203. SC.connect().then(function() { return SC.resolve(url) }).then(function(json) {
  3204. isVA = vaParser.test(json.artist.name);
  3205. var identifiers = 'SOUNDCLOUD_ID=' + json.id + ' RELEASETYPE=' + json.record_type;
  3206. json.tracks.data.forEach(function(track, ndx) {
  3207. trackArtist = track.artist.name;
  3208. if (!isVA && trackArtist && trackArtist == json.artist.name) trackArtist = undefined;
  3209. track = [
  3210. isVA ? 'Various Artists' : json.artist.name,
  3211. json.title,
  3212. undefined, //extract_year(json.release_date),
  3213. json.release_date,
  3214. json.label,
  3215. json.upc,
  3216. undefined, // country
  3217. undefined, // encoding
  3218. undefined, // format
  3219. undefined,
  3220. undefined, // bitrate
  3221. undefined, //bd,
  3222. undefined, // SR
  3223. 2,
  3224. 'WEB',
  3225. json.genres.data.map(it => it.name).join('; '),
  3226. discNumber,
  3227. totalDiscs,
  3228. discSubtitle,
  3229. ndx + 1,
  3230. json.nb_tracks,
  3231. track.title,
  3232. trackArtist,
  3233. undefined,
  3234. composer,
  3235. undefined,
  3236. undefined,
  3237. compiler,
  3238. producer,
  3239. track.duration,
  3240. undefined,
  3241. undefined,
  3242. undefined,
  3243. undefined,
  3244. undefined,
  3245. undefined, //'https://www.deezer.com/album/' + json.id,
  3246. undefined,
  3247. undefined, // description
  3248. identifiers + ' TRACK_ID=' + track.id,
  3249. ];
  3250. tracks.push(track.join('\x1E'));
  3251. });
  3252. clipBoard.value = tracks.join('\n');
  3253. fill_from_text_music();
  3254. });
  3255. return true;
  3256. }
  3257. if (!weak) {
  3258. addMessage('This domain not supported', 'ua-critical');
  3259. clipBoard.value = '';
  3260. }
  3261. return false;
  3262.  
  3263. function get_desc_from_node(selector, url, quote = false) {
  3264. description = [];
  3265. dom.querySelectorAll(selector).forEach(k => { description.push(html2php(k, url).trim()) });
  3266. description = description.join('\n\n').trim().replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  3267. if (quote && description.length > 0) description = '[quote]' + description + '[/quote]';
  3268. }
  3269. } // init_from_url_music
  3270.  
  3271. function trackComparer(a, b) {
  3272. var cmp = a.discnumber - b.discnumber;
  3273. if (!isNaN(cmp) && cmp != 0) return cmp;
  3274. cmp = parseInt(a.tracknumber) - parseInt(b.tracknumber);
  3275. if (!isNaN(cmp)) return cmp;
  3276. var m1 = vinyltrackParser.exec(a.tracknumber.toUpperCase());
  3277. var m2 = vinyltrackParser.exec(b.tracknumber.toUpperCase());
  3278. return m1 != null && m2 != null ?
  3279. m1[1].localeCompare(m2[1]) || parseFloat(m1[2]) - parseFloat(m2[2]) :
  3280. a.tracknumber.toUpperCase().localeCompare(b.tracknumber.toUpperCase());
  3281. }
  3282.  
  3283. function normalizeDate(str) {
  3284. if (typeof str != 'string') return null;
  3285. if (/\b(d{4}-\d+-\d+|\d{1,2}\/\d{1,2}\/\d{2})\b/.test(str)) return RegExp.$1;
  3286. if (/\b(\d{1,2})\/(\d{1,2})\/(\d{4})\b/.test(str)) return RegExp.$2 + '/' + RegExp.$1 + '/' + RegExp.$3;
  3287. if (/\b(\d{1,2})\.\s?(\d{1,2})\.\s?(\d{2}|\d{4})\b/.test(str)) return RegExp.$2 + '/' + RegExp.$1 + '/' + RegExp.$3;
  3288. return extract_year(str);
  3289. }
  3290.  
  3291. function getCoverOnline(url) {
  3292. GM_xmlhttpRequest({
  3293. method: 'GET',
  3294. url: url,
  3295. onload: function(response) {
  3296. if (response.readyState != 4 || response.status != 200) return;
  3297. var ref, dom = domParser.parseFromString(response.responseText, 'text/html');
  3298. function testDomain(url, selector) {
  3299. return typeof url == 'string' && response.finalUrl.toLowerCase().includes(url.toLowerCase()) ?
  3300. dom.querySelector(selector) : null;
  3301. }
  3302. if ((ref = testDomain('qobuz.com', 'div.album-cover > img')) != null) {
  3303. setImage(ref.src);
  3304. } else if ((ref = testDomain('highresaudio.com', 'div.albumbody > img.cover[data-pin-media]')) != null) {
  3305. setImage(ref.dataset.pinMedia);
  3306. } else if ((ref = testDomain('bandcamp.com', 'div#tralbumArt > a.popupImage')) != null) {
  3307. setImage(ref.href);
  3308. } else if ((ref = testDomain('7digital.com', 'span.release-packshot-image > img[itemprop="image"]')) != null) {
  3309. setImage(ref.src);
  3310. } else if ((ref = testDomain('hdtracks.com', 'p.product-image > img')) != null) {
  3311. setImage(ref.src);
  3312. } else if ((ref = testDomain('discogs.com', 'div#view_images > p:first-of-type > span > img')) != null) {
  3313. setImage(ref.src);
  3314. } else if ((ref = testDomain('junodownload.com', 'a.productimage')) != null) {
  3315. setImage(ref.href);
  3316. } else if ((ref = testDomain('supraphonline.cz', 'meta[itemprop="image"]')) != null) {
  3317. setImage(ref.content.replace(/\?.*$/, ''));
  3318. } else if ((ref = testDomain('prestomusic.com', 'div.c-product-block__aside > a')) != null) {
  3319. setImage(ref.href.replace(/\?\d+$/, ''));
  3320. } else if ((ref = testDomain('bontonland.cz', 'a.detailzoom')) != null) {
  3321. setImage(ref.href);
  3322. } else if ((ref = testDomain('nativedsd.com', 'a#album-cover')) != null) {
  3323. setImage(ref.href);
  3324. } else if ((ref = testDomain('deezer.com', 'meta[property="og:image"]')) != null) {
  3325. setImage(ref.content);
  3326. } else if ((ref = testDomain('spotify.com', 'meta[property="og:image"]')) != null) {
  3327. setImage(ref.content);
  3328. }
  3329. },
  3330. //onerror: response => { throw new Error('Response error ' + response.status + ' (' + response.statusText + ')') },
  3331. //ontimeout: function() { throw new Error('Timeout') },
  3332. });
  3333. }
  3334.  
  3335. function reqSelectFormats(...vals) {
  3336. vals.forEach(function(val) {
  3337. [
  3338. ['MP3', 0],
  3339. ['FLAC', 1],
  3340. ['AAC', 2],
  3341. ['AC3', 3],
  3342. ['DTS', 4],
  3343. ].forEach(function(fmt) {
  3344. if (val.toLowerCase() == fmt[0].toLowerCase()
  3345. && (ref = document.getElementById('format_' + fmt[1])) != null) {
  3346. ref.checked = true;
  3347. ref.onchange();
  3348. }
  3349. });
  3350. });
  3351. }
  3352.  
  3353. function reqSelectBitrates(...vals) {
  3354. vals.forEach(function(val) {
  3355. var ndx = 10;
  3356. [
  3357. [192, 0],
  3358. ['APS (VBR)', 1],
  3359. ['V2 (VBR)', 2],
  3360. ['V1 (VBR)', 3],
  3361. [256, 4],
  3362. ['APX (VBR)', 5],
  3363. ['V0 (VBR)', 6],
  3364. [320, 7],
  3365. ['Lossless', 8],
  3366. ['24bit Lossless', 9],
  3367. ['Other', 10],
  3368. ].forEach(function(it) {
  3369. if ((typeof val == 'string' ? val.toLowerCase() : val)
  3370. == (typeof it[0] == 'string' ? it[0].toLowerCase() : it[0])) ndx = it[1]
  3371. });
  3372. if ((ref = document.getElementById('bitrate_' + ndx)) != null) {
  3373. ref.checked = true;
  3374. ref.onchange();
  3375. }
  3376. });
  3377. }
  3378.  
  3379. function reqSelectMedias(...vals) {
  3380. vals.forEach(function(val) {
  3381. [
  3382. ['CD', 0],
  3383. ['DVD', 1],
  3384. ['Vinyl', 2],
  3385. ['Soundboard', 3],
  3386. ['SACD', 4],
  3387. ['DAT', 5],
  3388. ['Cassette', 6],
  3389. ['WEB', 7],
  3390. ['Blu-Ray', 8],
  3391. ].forEach(function(med) {
  3392. if (val == med[0] && (ref = document.getElementById('media_' + med[1])) != null) {
  3393. ref.checked = true;
  3394. ref.onchange();
  3395. }
  3396. });
  3397. if (val == 'CD') {
  3398. if ((ref = document.getElementById('needlog')) != null) {
  3399. ref.checked = true;
  3400. ref.onchange();
  3401. if ((ref = document.getElementById('minlogscore')) != null) ref.value = 100;
  3402. }
  3403. if ((ref = document.getElementById('needcue')) != null) ref.checked = true;
  3404. //if ((ref = document.getElementById('needchecksum')) != null) ref.checked = true;
  3405. }
  3406. });
  3407. }
  3408.  
  3409. function getReleaseIndex(str) {
  3410. var ndx;
  3411. [
  3412. ['Album', 1],
  3413. ['Soundtrack', 3],
  3414. ['EP', 5],
  3415. ['Anthology', 6],
  3416. ['Compilation', 7],
  3417. ['Single', 9],
  3418. ['Live album', 11],
  3419. ['Remix', 13],
  3420. ['Bootleg', 14],
  3421. ['Interview', 15],
  3422. ['Mixtape', 16],
  3423. ['Demo', 17],
  3424. ['Concert Recording', 18],
  3425. ['DJ Mix', 19],
  3426. ['Unknown', 21],
  3427. ].forEach(k => { if (str.toLowerCase() == k[0].toLowerCase()) ndx = k[1] });
  3428. return ndx || 21;
  3429. }
  3430.  
  3431. function getChanString(n) {
  3432. if (!n) return null;
  3433. const chanmap = [
  3434. 'mono',
  3435. 'stereo',
  3436. '2.1',
  3437. '4.0 surround sound',
  3438. '5.0 surround sound',
  3439. '5.1 surround sound',
  3440. '7.0 surround sound',
  3441. '7.1 surround sound',
  3442. ];
  3443. return n >= 1 && n <= 8 ? chanmap[n - 1] : n + 'chn surround sound';
  3444. }
  3445.  
  3446. function joinArtists(arr, decorator = artist => artist) {
  3447. if (!(arr instanceof Array)) return null;
  3448. if (arr.some(artist => artist.includes('&'))) return arr.map(decorator).join(', ');
  3449. if (arr.length < 3) return arr.map(decorator).join(' & ');
  3450. return arr.slice(0, -1).map(decorator).join(', ') + ' & ' + decorator(arr.slice(-1).pop());
  3451. }
  3452. } // fill_from_text_music
  3453.  
  3454. function fill_from_text_apps(weak = false) {
  3455. if (messages != null) messages.parentNode.removeChild(messages);
  3456. if (!urlParser.test(clipBoard.value)) {
  3457. addMessage('Only URL accepted for this category', 'ua-critical');
  3458. return false;
  3459. }
  3460. url = RegExp.$1;
  3461. var description, tags = new TagManager();
  3462. if (url.toLowerCase().includes('://sanet')) {
  3463. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  3464. if (response.readyState != 4 || response.status != 200)
  3465. throw new Error('GM_xmlhttpRequest readyState=' + response.status + ', status=' + response.status);
  3466. dom = domParser.parseFromString(response.responseText, 'text/html');
  3467. i = dom.querySelector('h1.item_title > span');
  3468. if (elementWritable(ref = document.getElementById('title'))) {
  3469. ref.value = i != null ? i.textContent.
  3470. replace(/\(x64\)$/i, '(64-bit)').
  3471. replace(/\b(?:Build)\s+(\d+)/, 'build $1').
  3472. replace(/\b(?:Multilingual|Multilanguage)\b/, 'multilingual') : null;
  3473. }
  3474. description = html2php(dom.querySelector('section.descr'), response.finalUrl);
  3475. if (/\s*^(?:\[i\]\[\/i\])?Homepage$.*/m.test(description)) description = RegExp.leftContext;
  3476. description = description.trim().split(/\n/).slice(5)
  3477. .map(k => k.trimRight()).join('\n').replace(/(?:[ \t]*\r?\n){3,}/, '\n\n').trim();
  3478. ref = dom.querySelector('section.descr > div.release-info');
  3479. var releaseInfo = ref != null && ref.textContent.trim();
  3480. if (/\b(?:Languages?)\s*:\s*(.*?)\s*(?:$|\|)/i.exec(releaseInfo) != null) {
  3481. description += '\n\n[b]Languages:[/b]\n' + RegExp.$1;
  3482. }
  3483. ref = dom.querySelector('div.txtleft > a');
  3484. if (ref != null) description += '\n\n[b]Product page:[/b]\n[url]' + deAnonymize(ref.href) + '[/url]';
  3485. writeDescription(description);
  3486. if ((ref = dom.querySelector('section.descr > div.center > a.mfp-image')) != null) {
  3487. setImage(ref.href);
  3488. } else {
  3489. ref = dom.querySelector('section.descr > div.center > img[data-src]');
  3490. if (ref != null) setImage(ref.dataset.src);
  3491. }
  3492. var cat = dom.querySelector('a.cat:last-of-type > span');
  3493. if (cat != null) {
  3494. if (cat.textContent.toLowerCase() == 'windows') {
  3495. tags.add('apps.windows');
  3496. if (/\b(?:x64)\b/i.test(releaseInfo)) tags.add('win64');
  3497. if (/\b(?:x86)\b/i.test(releaseInfo)) tags.add('win32');
  3498. }
  3499. if (cat.textContent.toLowerCase() == 'macos') tags.add('apps.mac');
  3500. if (cat.textContent.toLowerCase() == 'linux' || cat.textContent.toLowerCase() == 'unix') tags.add('apps.linux');
  3501. if (cat.textContent.toLowerCase() == 'android') tags.add('apps.android');
  3502. if (cat.textContent.toLowerCase() == 'ios') tags.add('apps.ios');
  3503. }
  3504. if (tags.length > 0 && elementWritable(ref = document.getElementById('tags'))) {
  3505. ref.value = tags.toString();
  3506. }
  3507. }, });
  3508. return true;
  3509. }
  3510. if (!weak) {
  3511. addMessage('This domain not supported', 'ua-critical');
  3512. clipBoard.value = '';
  3513. }
  3514. return false;
  3515. }
  3516.  
  3517. function fill_from_text_books(weak = false) {
  3518. if (messages != null) messages.parentNode.removeChild(messages);
  3519. if (!urlParser.test(clipBoard.value)) {
  3520. addMessage('Only URL accepted for this category', 'ua-critical');
  3521. return false;
  3522. }
  3523. url = RegExp.$1;
  3524. var description, tags = new TagManager();
  3525. if (url.toLowerCase().includes('martinus.cz') || url.toLowerCase().includes('martinus.sk')) {
  3526. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  3527. if (response.readyState != 4 || response.status != 200) throw new Error('GM_xmlhttpRequest readyState=' + response.status + ', status=' + response.status);
  3528. dom = domParser.parseFromString(response.responseText, 'text/html');
  3529. function get_detail(x, y) {
  3530. var ref = dom.querySelector('section#details > div > div > div:first-of-type > div:nth-child(' +
  3531. x + ') > dl:nth-child(' + y + ') > dd');
  3532. return ref != null ? ref.textContent.trim() : null;
  3533. }
  3534.  
  3535. i = dom.querySelectorAll('article > ul > li > a');
  3536. if (i.length > 0 && elementWritable(ref = document.getElementById('title') || document.querySelector('input[name="title"]'))) {
  3537. description = joinAuthors(i);
  3538. if ((i = dom.querySelector('article > h1')) != null) description += ' – ' + i.textContent.trim();
  3539. i = dom.querySelector('div.bar.mb-medium > div:nth-child(1) > dl > dd > span');
  3540. if (i != null && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  3541. ref.value = description;
  3542. }
  3543.  
  3544. description = '[quote]' + html2php(dom.querySelector('section#description > div')).
  3545. replace(/^\s*\[img\].*?\[\/img\]\s*/i, '') + '[/quote]';
  3546. const translation_map = [
  3547. [/\b(?:originál)/i, 'Original title'],
  3548. [/\b(?:datum|dátum|rok)\b/i, 'Release date'],
  3549. [/\b(?:katalog|katalóg)/i, 'Catalogue #'],
  3550. [/\b(?:stran|strán)\b/i, 'Page count'],
  3551. [/\bjazyk/i, 'Language'],
  3552. [/\b(?:nakladatel|vydavatel)/i, 'Publisher'],
  3553. [/\b(?:doporuč|ODPORÚČ)/i, 'Age rating'],
  3554. ];
  3555. dom.querySelectorAll('section#details > div > div > div:first-of-type > div > dl').forEach(function(detail) {
  3556. var lbl = detail.children[0].textContent.trim();
  3557. var val = detail.children[1].textContent.trim();
  3558. if (/\b(?:rozm)/i.test(lbl) || /\b(?:vazba|vázba)\b/i.test(lbl)) return;
  3559. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  3560. if (/\b(?:ISBN)\b/i.test(lbl)) {
  3561. url = new URL('https://www.worldcat.org/isbn/' + detail.children[1].textContent.trim());
  3562. val = '[url=' + url.href + ']' + detail.children[1].textContent.trim() + '[/url]';
  3563. findOCLC(url);
  3564. // } else if (/\b(?:ISBN)\b/i.test(lbl)) {
  3565. // val = '[url=https://www.goodreads.com/search/search?q=' + detail.children[1].textContent.trim() +
  3566. // '&search_type=books]' + detail.children[1].textContent.trim() + '[/url]';
  3567. }
  3568. description += '\n[b]' + lbl + ':[/b] ' + val;
  3569. });
  3570. url = new URL(response.finalUrl);
  3571. description += '\n\n[b]More info:[/b]\n[url]' + url.href + '[/url]';
  3572. writeDescription(description);
  3573.  
  3574. if ((i = dom.querySelector('a.mj-product-preview > img')) != null) {
  3575. setImage(i.src.replace(/\?.*/, ''));
  3576. } else if ((i = dom.querySelector('head > meta[property="og:image"]')) != null) {
  3577. setImage(i.content.replace(/\?.*/, ''));
  3578. }
  3579.  
  3580. dom.querySelectorAll('dd > ul > li > a').forEach(x => { tags.add(x.textContent) });
  3581. if (tags.length > 0 && elementWritable(ref = document.getElementById('tags'))) {
  3582. ref.value = tags.toString();
  3583. }
  3584. }, });
  3585. return true;
  3586. } else if (url.toLowerCase().includes('goodreads.com')) {
  3587. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  3588. if (response.readyState != 4 || response.status != 200) throw new Error('GM_xmlhttpRequest readyState=' + response.status + ', status=' + response.status);
  3589. dom = domParser.parseFromString(response.responseText, 'text/html');
  3590. i = dom.querySelectorAll('a.authorName > span');
  3591. if (i.length > 0 && elementWritable(ref = document.getElementById('title') || document.querySelector('input[name="title"]'))) {
  3592. description = joinAuthors(i);
  3593. if ((i = dom.querySelector('h1#bookTitle')) != null) description += ' – ' + i.textContent.trim();
  3594. if ((i = dom.querySelector('div#details > div.row:nth-of-type(2)')) != null
  3595. && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  3596. ref.value = description;
  3597. }
  3598.  
  3599. var description = [];
  3600. dom.querySelectorAll('div#description span:last-of-type').forEach(function(it) {
  3601. description = html2php(it, response.finalUrl);
  3602. });
  3603. description = '[quote]' + description.trim() + '[/quote]';
  3604.  
  3605. function strip(str) {
  3606. return typeof str == 'string' ?
  3607. str.replace(/\s{2,}/g, ' ').replace(/[\n\r]+/, '').replace(/\s*\.{3}(?:less|more)\b/g, '').trim() : null;
  3608. }
  3609.  
  3610. dom.querySelectorAll('div#details > div.row').forEach(k => { description += '\n' + strip(k.innerText) });
  3611. description += '\n';
  3612.  
  3613. dom.querySelectorAll('div#bookDataBox > div.clearFloats').forEach(function(detail) {
  3614. var lbl = detail.children[0].textContent.trim();
  3615. var val = strip(detail.children[1].textContent);
  3616. if (/\b(?:ISBN)\b/i.test(lbl) && (/\b(\d{13})\b/.test(val) || /\b(\d{10})\b/.test(val))) {
  3617. url = new URL('https://www.worldcat.org/isbn/' + RegExp.$1);
  3618. val = '[url=' + url.href + ']' + strip(detail.children[1].textContent) + '[/url]';
  3619. findOCLC(url);
  3620. }
  3621. description += '\n[b]' + lbl + ':[/b] ' + val;
  3622. });
  3623. if ((ref = dom.querySelector('span[itemprop="ratingValue"]')) != null) {
  3624. description += '\n[b]Rating:[/b] ' + Math.round(parseFloat(ref.firstChild.textContent) * 20) + '%';
  3625. }
  3626. url = new URL(response.finalUrl);
  3627. // if ((ref = dom.querySelector('div#buyButtonContainer > ul > li > a.buttonBar')) != null) {
  3628. // let u = new URL(ref.href);
  3629. // description += '\n[url=' + url.origin + u.pathname + '?' + u.search + ']Libraries[/url]';
  3630. // }
  3631. description += '\n\n[b]More info and reviews:[/b]\n[url]' + url.origin + url.pathname + '[/url]';
  3632. dom.querySelectorAll('div.clearFloats.bigBox').forEach(function(bigBox) {
  3633. if (bigBox.id == 'aboutAuthor' && (ref = bigBox.querySelector('h2 > a')) != null) {
  3634. description += '\n\n[b][url=' + ref.href + ']' + ref.textContent.trim() + '[/url][/b]';
  3635. if ((ref = bigBox.querySelector('div.bigBoxBody a > div[style*="background-image"]')) != null) {
  3636. }
  3637. if ((ref = bigBox.querySelector('div.bookAuthorProfile__about > span[id]:last-of-type')) != null) {
  3638. description += '\n' + html2php(ref, response.finalUrl).replace(/^\[i\]Librarian\s+Note:.*?\[\/i\]\s+/i, '');
  3639. }
  3640. } else if ((ref = bigBox.querySelector('h2 > a[href^="/trivia/"]')) != null) {
  3641. description += '\n\n[b][url=' + ref.href + ']' + ref.textContent.trim() + '[/url][/b]';
  3642. if ((ref = bigBox.querySelector('div.bigBoxContent > div.mediumText')) != null) {
  3643. description += '\n' + ref.firstChild.textContent.trim();
  3644. }
  3645. // } else if ((ref = bigBox.querySelector('h2 > a[href^="/work/quotes/"]')) != null) {
  3646. // description += '\n\n[b][url=' + ref.href + ']' + ref.textContent.trim() + '[/url][/b]';
  3647. // bigBox.querySelectorAll('div.bigBoxContent > div.stacked > span.readable').forEach(function(quote) {
  3648. // description += '\n' + ref.firstChild.textContent.trim();
  3649. // });
  3650. }
  3651. });
  3652. writeDescription(description);
  3653. if ((ref = dom.querySelector('div.editionCover > img')) != null) setImage(ref.src.replace(/\?.*/, ''));
  3654. dom.querySelectorAll('div.elementList > div.left').forEach(tag => { tags.add(tag.textContent.trim()) });
  3655. if (tags.length > 0 && elementWritable(ref = document.getElementById('tags'))) ref.value = tags.toString();
  3656. }, });
  3657. return true;
  3658. } else if (url.toLowerCase().includes('databazeknih.cz')) {
  3659. if (!url.toLowerCase().includes('show=alldesc')) {
  3660. if (!url.includes('?')) { url += '?show=alldesc' } else { url += '&show=alldesc' }
  3661. }
  3662. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  3663. if (response.readyState != 4 || response.status != 200) throw new Error('GM_xmlhttpRequest readyState=' + response.status + ', status=' + response.status);
  3664. dom = domParser.parseFromString(response.responseText, 'text/html');
  3665. i = dom.querySelectorAll('span[itemprop="author"] > a');
  3666. if (i != null && elementWritable(ref = document.getElementById('title') || document.querySelector('input[name="title"]'))) {
  3667. description = joinAuthors(i);
  3668. if ((i = dom.querySelector('h1[itemprop="name"]')) != null) description += ' – ' + i.textContent.trim();
  3669. i = dom.querySelector('span[itemprop="datePublished"]');
  3670. if (i != null && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  3671. ref.value = description;
  3672. }
  3673.  
  3674. description = '[quote]' + html2php(dom.querySelector('p[itemprop="description"]'), response.finalUrl) + '[/quote]';
  3675. const translation_map = [
  3676. [/\b(?:orig)/i, 'Original title'],
  3677. [/\b(?:série)\b/i, 'Series'],
  3678. [/\b(?:vydáno)\b/i, 'Released'],
  3679. [/\b(?:stran)\b/i, 'Page count'],
  3680. [/\b(?:jazyk)\b/i, 'Language'],
  3681. [/\b(?:překlad)/i, 'Translation'],
  3682. [/\b(?:autor obálky)\b/i, 'Cover author'],
  3683. ];
  3684. dom.querySelectorAll('table.bdetail tr').forEach(function(detail) {
  3685. var lbl = detail.children[0].textContent.trim();
  3686. var val = detail.children[1].textContent.trim();
  3687. if (/(?:žánr|\bvazba)\b/i.test(lbl)) return;
  3688. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  3689. if (/\b(?:ISBN)\b/i.test(lbl) && /\b(\d+(?:-\d+)*)\b/.exec(val) != null) {
  3690. url = new URL('https://www.worldcat.org/isbn/' + RegExp.$1.replace(/-/g, ''));
  3691. val = '[url=' + url.href + ']' + detail.children[1].textContent.trim() + '[/url]';
  3692. findOCLC(url);
  3693. }
  3694. description += '\n[b]' + lbl + '[/b] ' + val;
  3695. });
  3696.  
  3697. url = new URL(response.finalUrl);
  3698. description += '\n\n[b]More info:[/b]\n[url]' + url.origin + url.pathname + '[/url]';
  3699. writeDescription(description);
  3700.  
  3701. if ((ref = dom.querySelector('div#icover_mid > a')) != null) setImage(ref.href.replace(/\?.*/, ''));
  3702. if ((ref = dom.querySelector('div#lbImage')) != null && /\burl\("(.*)"\)/i.test(i.style.backgroundImage)) {
  3703. setImage(RegExp.$1.replace(/\?.*/, ''));
  3704. }
  3705.  
  3706. dom.querySelectorAll('h5[itemprop="genre"] > a').forEach(tag => { tags.add(tag.textContent.trim()) });
  3707. dom.querySelectorAll('a.tag').forEach(tag => { tags.add(tag.textContent.trim()) });
  3708. if (tags.length > 0 && elementWritable(ref = document.getElementById('tags'))) ref.value = tags.toString();
  3709. }, });
  3710. return true;
  3711. }
  3712. if (!weak) {
  3713. addMessage('This domain not supported', 'ua-critical');
  3714. clipBoard.value = '';
  3715. }
  3716. return false;
  3717.  
  3718. function joinAuthors(nodeList) {
  3719. if (typeof nodeList != 'object') return null;
  3720. return Array.from(nodeList).map(it => it.textContent.trim()).join(' & ');
  3721. }
  3722.  
  3723. function findOCLC(url) {
  3724. if (!url) return false;
  3725. var oclc = document.querySelector('input[name="oclc"]');
  3726. if (!elementWritable(oclc)) return false;
  3727. GM_xmlhttpRequest({
  3728. method: 'GET',
  3729. url: url,
  3730. onload: function(response) {
  3731. if (response.readyState != 4 || response.status != 200) return;
  3732. var dom = domParser.parseFromString(response.responseText, 'text/html');
  3733. var ref = dom.querySelector('tr#details-oclcno > td:last-of-type');
  3734. if (ref != null) oclc.value = ref.textContent.trim();
  3735. },
  3736. });
  3737. return true;
  3738. }
  3739. }
  3740.  
  3741. function preview(n) {
  3742. if (!prefs.auto_preview) return;
  3743. var btn = document.querySelector('input.button_preview_' + n + '[type="button"][value="Preview"]');
  3744. if (btn != null) btn.click();
  3745. }
  3746.  
  3747. function html2php(node, url) {
  3748. var php = '';
  3749. if (node instanceof HTMLElement) node.childNodes.forEach(function(ch) {
  3750. if (ch.nodeType == 3) {
  3751. php += ch.data.replace(/\s+/g, ' ');
  3752. } else if (ch.nodeName == 'P') {
  3753. php += '\n' + html2php(ch, url);
  3754. } else if (ch.nodeName == 'DIV') {
  3755. php += '\n\n' + html2php(ch, url) + '\n\n';
  3756. } else if (ch.nodeName == 'LABEL') {
  3757. php += '\n\n[b]' + html2php(ch, url) + '[/b]';
  3758. } else if (ch.nodeName == 'SPAN') {
  3759. php += html2php(ch, url);
  3760. } else if (ch.nodeName == 'BR' || ch.nodeName == 'HR') {
  3761. php += '\n';
  3762. } else if (ch.nodeName == 'B' || ch.nodeName == 'STRONG') {
  3763. php += '[b]' + html2php(ch, url) + '[/b]';
  3764. } else if (ch.nodeName == 'I' || ch.nodeName == 'EM') {
  3765. php += '[i]' + html2php(ch, url) + '[/i]';
  3766. } else if (ch.nodeName == 'U') {
  3767. php += '[u]' + html2php(ch, url) + '[/u]';
  3768. } else if (ch.nodeName == 'CODE') {
  3769. php += '[pre]' + ch.textContent + '[/pre]';
  3770. } else if (ch.nodeName == 'A') {
  3771. php += ch.childNodes.length > 0 ?
  3772. '[url=' + deAnonymize(ch.href) + ']' + html2php(ch, url) + '[/url]' :
  3773. '[url]' + deAnonymize(ch.href) + '[/url]';
  3774. } else if (ch.nodeName == 'IMG') {
  3775. php += '[img]' + (ch.dataset.src || ch.src) + '[/img]';
  3776. }
  3777. });
  3778. return php;
  3779. }
  3780.  
  3781. function deAnonymize(uri) {
  3782. return typeof uri == 'string' ? uri.replace(/^https?:\/\/(?:www\.)?anonymz\.com\/\?/i, '') : null;
  3783. }
  3784.  
  3785. function writeDescription(desc) {
  3786. if (typeof desc != 'string') return;
  3787. if (elementWritable(ref = document.querySelector('textarea#desc')
  3788. || document.querySelector('textarea#description'))) ref.value = desc;
  3789. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  3790. if (ref.textLength > 0) ref.value += '\n\n';
  3791. ref.value += desc;
  3792. }
  3793. }
  3794.  
  3795. function setImage(url) {
  3796. var image = document.getElementById('image') || document.querySelector('input[name="image"]');
  3797. if (!elementWritable(image)) return false;
  3798. image.value = url;
  3799.  
  3800. if (prefs.auto_preview_cover && image.id) {
  3801. if ((child = document.getElementById('cover preview')) == null) {
  3802. elem = document.createElement('div');
  3803. elem.style.paddingTop = '10px';
  3804. child = document.createElement('img');
  3805. child.id = 'cover preview';
  3806. child.style.width = '90%';
  3807. elem.append(child);
  3808. image.parentNode.previousElementSibling.append(elem);
  3809. }
  3810. child.src = url;
  3811. }
  3812. if (prefs.auto_rehost_cover) {
  3813. if (rehostItBtn != null) {
  3814. rehostItBtn.click();
  3815. } else {
  3816. rehost2PTPIMG([url]).then(urls => { if (urls.length > 0) image.value = urls[0] }).catch(e => { alert(e) });
  3817. }
  3818. }
  3819. }
  3820.  
  3821. function elementWritable(elem) { return elem != null && !elem.disabled && (overwrite || !elem.value) }
  3822. }
  3823.  
  3824. function addArtistField() { exec(function() { AddArtistField() }) }
  3825. function removeArtistField() { exec(function() { RemoveArtistField() }) }
  3826.  
  3827. function array_homogenous(arr) { return arr.every(k => k === arr[0]) }
  3828.  
  3829. function titleCase(str) {
  3830. return str.toLowerCase().split(' ').map(x => x[0].toUpperCase() + x.slice(1)).join(' ');
  3831. }
  3832.  
  3833. function exec(fn) {
  3834. let script = document.createElement('script');
  3835. script.type = 'application/javascript';
  3836. script.textContent = '(' + fn + ')();';
  3837. document.body.appendChild(script); // run the script
  3838. document.body.removeChild(script); // clean up
  3839. }
  3840.  
  3841. function makeTimeString(duration) {
  3842. let t = Math.abs(Math.round(duration));
  3843. let H = Math.floor(t / 60 ** 2);
  3844. let M = Math.floor(t / 60 % 60);
  3845. let S = t % 60;
  3846. return (duration < 0 ? '-' : '') + (H > 0 ? H + ':' + M.toString().padStart(2, '0') : M.toString()) +
  3847. ':' + S.toString().padStart(2, '0');
  3848. }
  3849.  
  3850. function timeStringToTime(str) {
  3851. if (!/(-\s*)?\b(\d+(?::\d{2})*(?:\.\d+)?)\b/.test(str)) return null;
  3852. var t = 0, a = RegExp.$2.split(':');
  3853. while (a.length > 0) t = t * 60 + parseFloat(a.shift());
  3854. return RegExp.$1 ? -t : t;
  3855. }
  3856.  
  3857. function extract_year(expr) {
  3858. if (typeof expr == 'number') return Math.round(expr);
  3859. if (typeof expr != 'string') return null;
  3860. if (/\b(\d{4})\b/.test(expr)) return parseInt(RegExp.$1);
  3861. var d = new Date(expr);
  3862. return parseInt(isNaN(d) ? expr : d.getFullYear());
  3863. }
  3864.  
  3865. function reInParenthesis(expr) { return new RegExp('\\s+\\([^\\(\\)]*'.concat(expr, '[^\\(\\)]*\\)$'), 'i') }
  3866. function reInBrackets(expr) { return new RegExp('\\s+\\[[^\\[\\]]*'.concat(expr, '[^\\[\\]]*\\]$'), 'i') }
  3867.  
  3868. function addMessage(text, cls, html = false) {
  3869. messages = document.getElementById('UA messages');
  3870. if (messages == null) {
  3871. var ua = document.getElementById('upload assistant');
  3872. if (ua == null) return null;
  3873. messages = document.createElement('TR');
  3874. if (messages == null) return null;
  3875. messages.id = 'UA messages';
  3876. ua.children[0].append(messages);
  3877.  
  3878. elem = document.createElement('TD');
  3879. if (elem == null) return null;
  3880. elem.colSpan = 2;
  3881. elem.className = 'ua-messages-bg';
  3882. messages.append(elem);
  3883. } else {
  3884. elem = messages.children[0]; // tbody
  3885. if (elem == null) return null;
  3886. }
  3887. var div = document.createElement('DIV');
  3888. div.classList.add('ua-messages', cls);
  3889. div[html ? 'innerHTML' : 'textContent'] = text;
  3890. return elem.appendChild(div);
  3891. }
  3892.  
  3893. function imageDropHandler(evt) {
  3894. evt.preventDefault();
  3895. if (evt.dataTransfer.files.length <= 0) return;
  3896. var image = document.getElementById('image') || document.querySelector('input[name="image"]');
  3897. if (image == null) return;
  3898. if (evt.currentTarget.busy) throw new Error('Wait till current upload finishes');
  3899. evt.currentTarget.busy = true;
  3900. if (evt.currentTarget.hTimer) {
  3901. clearTimeout(evt.currentTarget.hTimer);
  3902. delete evt.currentTarget.hTimer;
  3903. }
  3904. var origlabel = evt.currentTarget.value;
  3905. evt.currentTarget.value = 'Uploading...';
  3906. evt.currentTarget.style.backgroundColor = '#A00000';
  3907. var evtSrc = evt.currentTarget;
  3908. upload2PTPIMG(evt.dataTransfer.files[0]).then(function(result) {
  3909. if (result.length > 0) {
  3910. image.value = result[0];
  3911. evtSrc.style.backgroundColor = '#00A000';
  3912. evtSrc.hTimer = setTimeout(function() {
  3913. evtSrc.style.backgroundColor = null;
  3914. delete evtSrc.hTimer;
  3915. }, 10000);
  3916. } else evtSrc.style.backgroundColor = null;
  3917. }).catch(function(e) {
  3918. alert(e);
  3919. evtSrc.style.backgroundColor = null;
  3920. }).then(function() {
  3921. evtSrc.busy = false;
  3922. evtSrc.value = origlabel;
  3923. });
  3924. }
  3925.  
  3926. function voidDragHandler(evt) { evt.preventDefault() }
  3927.  
  3928. function upload2PTPIMG(file, elem) {
  3929. if (!(file instanceof File)) return Promise.reject('Bad parameter (file)');
  3930. var config = JSON.parse(window.localStorage.ptpimg_it);
  3931. if (!prefs.ptpimg_api_key && !config.api_key) return Promise.reject('API key not set');
  3932. return new Promise(function(resolve, reject) {
  3933. var reader = new FileReader();
  3934. var fr = new Promise(function(resolve, reject) {
  3935. reader.onload = function() { resolve(reader.result) }
  3936. reader.readAsBinaryString(file); //readAsArrayBuffer(file);
  3937. });
  3938. fr.then(function(result) {
  3939. const boundary = '----NN-GGn-PTPIMG';
  3940. var data = '--' + boundary + '\r\n';
  3941. data += 'Content-Disposition: form-data; name="file-upload[0]"; filename="' + file.name.toASCII() + '"\r\n';
  3942. data += 'Content-Type: ' + file.type + '\r\n\r\n';
  3943. data += result + '\r\n';
  3944. data += '--' + boundary + '\r\n';
  3945. data += 'Content-Disposition: form-data; name="api_key"\r\n\r\n';
  3946. data += (prefs.ptpimg_api_key || config.api_key) + '\r\n';
  3947. data += '--' + boundary + '--\r\n';
  3948. GM_xmlhttpRequest({
  3949. method: 'POST',
  3950. url: 'https://ptpimg.me/upload.php',
  3951. responseType: 'json',
  3952. headers: {
  3953. 'Content-Type': 'multipart/form-data; boundary=' + boundary,
  3954. 'Content-Length': data.length,
  3955. },
  3956. data: data,
  3957. binary: true,
  3958. onload: function(response) {
  3959. if (response.readyState == 4 && response.status == 200) {
  3960. resolve(response.response.map(item => 'https://ptpimg.me/' + item.code + '.' + item.ext));
  3961. } else reject('Response error ' + response.status + ' (' + response.statusText + ')');
  3962. },
  3963. onprogress: elem instanceof HTMLInputElement ?
  3964. arg => { elem.value = 'Uploading... (' + arg.position + '%)' } : undefined,
  3965. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  3966. ontimeout: function() { reject('Timeout') },
  3967. });
  3968. });
  3969. });
  3970. }
  3971.  
  3972. function rehost2PTPIMG(urls) {
  3973. if (!Array.isArray(urls)) return Promise.reject('Bad parameter (urls)');
  3974. var config = JSON.parse(window.localStorage.ptpimg_it);
  3975. if (!prefs.ptpimg_api_key && !config.api_key) return Promise.reject('API key not set');
  3976. return new Promise(function(resolve, reject) {
  3977. const boundary = 'NN-GGn-PTPIMG';
  3978. const dcTest = /^https?:\/\/(?:\w+\.)?discogs\.com\//i;
  3979. var data = '--' + boundary + "\n";
  3980. data += 'Content-Disposition: form-data; name="link-upload"\n\n';
  3981. data += urls.map(url => dcTest.test(url) ? 'https://reho.st/' + url : url).join('\n') + '\n';
  3982. data += '--' + boundary + '\n';
  3983. data += 'Content-Disposition: form-data; name="api_key"\n\n';
  3984. data += (prefs.ptpimg_api_key || config.api_key) + '\n';
  3985. data += '--' + boundary + '--';
  3986. GM_xmlhttpRequest({
  3987. method: 'POST',
  3988. url: 'https://ptpimg.me/upload.php',
  3989. responseType: 'json',
  3990. headers: {
  3991. 'Content-type': 'multipart/form-data; boundary=' + boundary,
  3992. 'Content-Length': data.length,
  3993. },
  3994. data: data,
  3995. onload: function(response) {
  3996. if (response.readyState == 4 && response.status == 200) {
  3997. resolve(response.response.map(item => 'https://ptpimg.me/' + item.code + '.' + item.ext));
  3998. } else reject('Response error ' + response.status + ' (' + response.statusText + ')');
  3999. },
  4000. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  4001. ontimeout: function() { reject('Timeout') },
  4002. });
  4003. });
  4004. }