RED/NWCD Upload Assistant

Accurate filling of new upload/request and group/request edit forms based on foobar2000's playlist selection (via pasted output of copy command), release integrity check, two tracklist layouts, colours customization, featured artists extraction, classical works formatting, coverart fetching from store and more. As alternative to pasted playlist, e.g. for requests creation, valid URL to product page on supported web can be used -- see below for list of supported sites.

当前为 2019-10-23 提交的版本,查看 最新版本

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