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-25 提交的版本,檢視 最新版本

  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, xhr = new XMLHttpRequest();
  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 = [];
  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 (elementWritable(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 (elementWritable(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 (elementWritable(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 (elementWritable(ref = document.getElementById('year'))) {
  910. ref.value = release.album_year || '';
  911. }
  912. i = release.release_date && extract_year(release.release_date);
  913. if (elementWritable(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 (elementWritable(ref = document.getElementById('remaster_title'))) {
  922. ref.value = editionTitle || '';
  923. }
  924. rx = /\s*[\,\;]\s*/g;
  925. if (elementWritable(ref = document.getElementById('remaster_record_label') || document.querySelector('input[name="recordlabel"]'))) {
  926. ref.value = release.label && release.label.replace(rx, ' / ') || '';
  927. }
  928. if (elementWritable(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 (elementWritable(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 (elementWritable(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 (elementWritable(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. } else if (/\b(?:Mixtape)\b/i.test(release.album)) {
  1065. releaseType = getReleaseIndex('Mixtape');
  1066. } else if (isVA) {
  1067. releaseType = getReleaseIndex('Compilation');
  1068. } else if (tracks.every(it => it.identifiers.COMPILATION == 1)) {
  1069. releaseType = getReleaseIndex('Anthology');
  1070. }
  1071. }
  1072. if ((ref = document.getElementById('releasetype')) != null && !ref.disabled && (overwrite || ref.value == 0)) {
  1073. ref.value = releaseType || getReleaseIndex('Album');
  1074. }
  1075. if (!composerEmphasis && !prefs.keep_meaningles_composers) {
  1076. document.querySelectorAll('input[name="artists[]"]').forEach(function(i) {
  1077. if (['4', '5'].includes(i.nextElementSibling.value)) i.value = '';
  1078. });
  1079. }
  1080. const doubleParsParsers = [
  1081. /\(+(\([^\(\)]*\))\)+/,
  1082. /\[+(\[[^\[\]]*\])\]+/,
  1083. /\{+(\{[^\{\}]*\})\}+/,
  1084. ];
  1085. for (iter of tracks) {
  1086. doubleParsParsers.forEach(function(rx) {
  1087. if (rx.test(iter.title)) {
  1088. addMessage('Warning: doubled parentheses in track #' + iter.tracknumber +
  1089. ' title ("' + iter.title + '")', 'ua-warning');
  1090. //iter.title.replace(rx, RegExp.$1);
  1091. }
  1092. });
  1093. }
  1094. if (tracks.length > 1 && array_homogenous(tracks.map(k => k.title))) {
  1095. addMessage('Warning: all tracks having same title: ' + tracks[0].title, 'ua-warning');
  1096. }
  1097. // Album description
  1098. var description;
  1099. url = release.urls.length == 1 && release.urls[0];
  1100. if (!url && tracks.every(it => it.identifiers.DISCOGS_ID && it.identifiers.DISCOGS_ID == tracks[0].identifiers.DISCOGS_ID)) {
  1101. url = 'https://www.discogs.com/release/' + tracks[0].identifiers.DISCOGS_ID;
  1102. }
  1103. const vinylTest = /^((?:Vinyl|LP) rip by\s+)(.*)$/im;
  1104. const vinyltrackParser = /^([A-Z])[\-\.\s]?((\d+)(?:\.\d+)?)$/;
  1105. const classicalWorkParsers = [
  1106. /^(.+?):\s+([IVXC]+\.\s+.*)$/,
  1107. /^(.*\S):\s+(.*)$/,
  1108. ];
  1109. if (isRequestNew || isRequestEdit) { // isRequestNew
  1110. description = []
  1111. if (release.release_date) {
  1112. i = new Date(release.release_date);
  1113. description.push((i < new Date() ? 'Released' : 'Releasing') + ' ' +
  1114. (isNaN(i) ? release.release_date : i.toDateString()));
  1115. }
  1116. let summary = '';
  1117. if (totalDiscs > 1) summary += totalDiscs + 'discs, ';
  1118. summary += tracks.length + ' track(s)';
  1119. if (totalTime > 0) summary += ', ' + makeTimeString(totalTime);
  1120. description.push(summary);
  1121. if (url) description.push('[url]' + url + '[/url]');
  1122. if (release.catalogs.length == 1 && /^\d{10,}$/.test(release.catalogs[0])
  1123. || tracks.every(it => it.identifiers.BARCODE && it.identifiers.BARCODE == tracks[0].identifiers.BARCODE)
  1124. && /^\d{10,}$/.test(tracks[0].identifiers.BARCODE)) {
  1125. description.push('[url=https://www.google.com/search?q=' + RegExp.lastMatch + ']Find more stores...[/url]');
  1126. }
  1127. if (release.comments.length == 1) description.push(release.comments[0]);
  1128. description = description.join('\n\n');
  1129. if (description.length > 0) {
  1130. ref = document.getElementById('description');
  1131. if (elementWritable(ref)) {
  1132. ref.value = description;
  1133. } else if (isRequestEdit && ref != null && !ref.disabled) {
  1134. ref.value = ref.textLength > 0 ? ref.value.concat('\n\n', description) : ref.value = description;
  1135. preview(0);
  1136. }
  1137. }
  1138. } else { // upload
  1139. let ripinfo, dur;
  1140. description = !isVA && artists[0].length >= 3 ?
  1141. '[size=4]' + joinArtists(artists[0], artist => '[artist]' + artist + '[/artist]') + ' – ' +
  1142. release.album + '[/size]\n\n' : '';
  1143. // ============================================= The Playlist =============================================
  1144. if (tracks.length > 1) {
  1145. description += isRED ? '[pad=5|0|0|0]' : '';
  1146. description += '[size=4][color=' + prefs.tracklist_head_color + '][b]Tracklisting[/b][/color][/size]';
  1147. if (isRED) description += '[/pad]';
  1148. description += '\n'; //'[hr]';
  1149. let lastDisc, lastSubtitle, lastWork, lastSide, vinylTrackWidth;
  1150. let block = 0, classicalWorks = new Map();
  1151. if (isClassical && !tracks.some(it => it.discsubtitle)) {
  1152. tracks.forEach(function(track) {
  1153. classicalWorkParsers.forEach(function(classicalWorkParser) {
  1154. if (track.classical_work || !classicalWorkParser.test(track.title)) return;
  1155. classicalWorks.set(track.classical_work = RegExp.$1, {});
  1156. track.classical_title = RegExp.$2;
  1157. });
  1158. });
  1159. for (iter of classicalWorks.keys()) {
  1160. let work = tracks.filter(track => track.classical_work == iter);
  1161. if (array_homogenous(work.map(it => it.track_artist))) {
  1162. classicalWorks.get(iter).performer = work[0].track_artist;
  1163. }
  1164. if (array_homogenous(work.map(it => it.composer))) {
  1165. classicalWorks.get(iter).composer = work[0].composer;
  1166. }
  1167. }
  1168. }
  1169. let volumes = new Map(tracks.map(it => [it.discnumber, undefined]));
  1170. volumes.forEach(function(val, key) {
  1171. volumes.set(key, new Set(tracks.filter(it => it.discnumber == key).map(it => it.discsubtitle)).size)
  1172. });
  1173. if (!tracks.every(it => !isNaN(parseInt(it.tracknumber)))
  1174. && !tracks.every(it => vinyltrackParser.test(it.tracknumber.toUpperCase()))) {
  1175. addMessage('Warning: inconsistent tracks numbering (' + tracks.map(it => it.tracknumber) + ')', 'ua-warning');
  1176. }
  1177. vinylTrackWidth = tracks.reduce(function(acc, it) {
  1178. return Math.max(vinyltrackParser.test(it.tracknumber.toUpperCase()) && parseInt(RegExp.$3), acc);
  1179. }, 0);
  1180. if (vinylTrackWidth) {
  1181. vinylTrackWidth = vinylTrackWidth.toString().length;
  1182. tracks.forEach(function(it) {
  1183. if (vinyltrackParser.test(it.tracknumber.toUpperCase()) != null)
  1184. it.tracknumber = RegExp.$1 + RegExp.$3.padStart(vinylTrackWidth, '0');
  1185. });
  1186. ++vinylTrackWidth;
  1187. }
  1188.  
  1189. const padStart = '[pad=0|0|5|0]';
  1190. function prologue(prefix, postfix) {
  1191. function block1() {
  1192. if (block == 3) description += postfix;
  1193. description += '\n';
  1194. if (isRED && ![1, 2].includes(block)) description += padStart;
  1195. block = 1;
  1196. }
  1197. function block2() {
  1198. if (block == 3) description += postfix;
  1199. description += '\n';
  1200. if (isRED && ![1, 2].includes(block)) description += padStart;
  1201. block = 2;
  1202. }
  1203. function block3() {
  1204. if (block == 2) description += '[hr]';
  1205. if (isRED && [1, 2].includes(block)) description += '[/pad]';
  1206. description += '\n';
  1207. if (block != 3) description += prefix;
  1208. block = 3;
  1209. }
  1210. var blockDuration;
  1211. if (totalDiscs > 1 && iter.discnumber != lastDisc) {
  1212. block1();
  1213. description += '[color=' + prefs.tracklist_disctitle_color + '][size=3][b]';
  1214. if (iter.identifiers.VOL_MEDIA && tracks.filter(it => it.discnumber == iter.discnumber)
  1215. .every(it => it.identifiers.VOL_MEDIA == iter.identifiers.VOL_MEDIA)) {
  1216. description += iter.identifiers.VOL_MEDIA.toUpperCase() + ' ';
  1217. }
  1218. description += 'Disc ' + iter.discnumber;
  1219. if (iter.discsubtitle && (volumes.get(iter.discnumber) || 0) == 1) {
  1220. description += ' – ' + iter.discsubtitle;
  1221. lastSubtitle = iter.discsubtitle;
  1222. }
  1223. description += '[/b][/size]';
  1224. blockDuration = tracks.filter(it => it.discnumber == iter.discnumber)
  1225. .reduce((acc, it) => acc + it.duration, 0);
  1226. if (blockDuration > 0) description += ' [size=2][i][' + makeTimeString(blockDuration) + '][/i][/size]';
  1227. description += '[/color]';
  1228. lastDisc = iter.discnumber;
  1229. lastWork = undefined;
  1230. }
  1231. if (iter.discsubtitle != lastSubtitle) {
  1232. if (block != 1 || iter.discsubtitle) block1();
  1233. if (iter.discsubtitle) {
  1234. description += '[color=' + prefs.tracklist_disctitle_color + '][size=2][b]' + iter.discsubtitle + '[/b][/size]';
  1235. blockDuration = tracks.filter(it => it.discsubtitle == iter.discsubtitle)
  1236. .reduce((acc, it) => acc + it.duration, 0);
  1237. if (blockDuration > 0) description += ' [size=1][i][' + makeTimeString(blockDuration) + '][/i][/size]';
  1238. description += '[/color]';
  1239. }
  1240. lastSubtitle = iter.discsubtitle;
  1241. }
  1242. if (iter.classical_work != lastWork) {
  1243. if (iter.classical_work) {
  1244. block2();
  1245. description += '[color=' + prefs.tracklist_classicalblock_color + '][size=2][b]';
  1246. if (release.composers.length != 1 && classicalWorks.get(iter.classical_work).composer) {
  1247. description += classicalWorks.get(iter.classical_work).composer + ': ';
  1248. }
  1249. description += iter.classical_work;
  1250. description += '[/b]';
  1251. if (classicalWorks.get(iter.classical_work).performer
  1252. && classicalWorks.get(iter.classical_work).performer != release.artist) {
  1253. description += ' (' + classicalWorks.get(iter.classical_work).performer + ')';
  1254. }
  1255. description += '[/size]';
  1256. blockDuration = tracks.filter(it => it.classical_work == iter.classical_work)
  1257. .reduce((acc, it) => acc + it.duration, 0);
  1258. if (blockDuration > 0) description += ' [size=1][i][' + makeTimeString(blockDuration) + '][/i][/size]';
  1259. description += '[/color]';
  1260. } else {
  1261. if (block > 2) block1();
  1262. }
  1263. lastWork = iter.classical_work;
  1264. }
  1265. if (vinyltrackParser.test(iter.tracknumber)) {
  1266. if (block == 3 && lastSide && RegExp.$1 != lastSide) description += '\n';
  1267. lastSide = RegExp.$1;
  1268. }
  1269. block3();
  1270. } // prologue
  1271.  
  1272. for (iter of tracks.sort(trackComparer)) {
  1273. let title = '';
  1274. let ttwidth = vinylTrackWidth || (totalDiscs > 1 && iter.discnumber ?
  1275. tracks.filter(it => it.discnumber == iter.discnumber) : tracks)
  1276. .reduce((accumulator, it) => Math.max(accumulator, iter.tracknumber.toString().length), 2);
  1277. if (prefs.tracklist_style == 1) { // STYLE 1 ----------------------------------------
  1278. prologue('[size=2]', '[/size]\n');
  1279. track = '[b][color=' + prefs.tracklist_tracknumber_color + ']';
  1280. track += isNaN(parseInt(iter.tracknumber)) ? iter.tracknumber : iter.tracknumber.padStart(ttwidth, '0');
  1281. track += '[/color][/b]' + prefs.title_separator;
  1282. if (iter.track_artist && iter.track_artist != release.artist
  1283. && (!iter.classical_work || !classicalWorks.get(iter.classical_work).performer)) {
  1284. title = '[color=' + prefs.tracklist_artist_color + ']' + iter.track_artist + '[/color] - ';
  1285. }
  1286. title += iter.classical_title || iter.title;
  1287. if (iter.composer && composerEmphasis && release.composers.length != 1
  1288. && (!iter.classical_work || !classicalWorks.get(iter.classical_work).composer)) {
  1289. title = title.concat(' [color=', prefs.tracklist_composer_color, '](', iter.composer, ')[/color]');
  1290. }
  1291. description += track + title;
  1292. if (iter.duration) description += ' [i][color=' + prefs.tracklist_duration_color +'][' +
  1293. makeTimeString(iter.duration) + '][/color][/i]';
  1294. } else if (prefs.tracklist_style == 2) { // STYLE 2 ----------------------------------------
  1295. prologue('[size=2][pre]', '[/pre][/size]');
  1296. track = isNaN(parseInt(iter.tracknumber)) ? iter.tracknumber : iter.tracknumber.padStart(ttwidth, '0');
  1297. track += prefs.title_separator;
  1298. if (iter.track_artist && iter.track_artist != release.artist
  1299. && (!iter.classical_work || !classicalWorks.get(iter.classical_work).performer)) {
  1300. title = iter.track_artist + ' - ';
  1301. }
  1302. title += iter.classical_title || iter.title;
  1303. if (composerEmphasis && iter.composer && release.composers.length != 1
  1304. && (!iter.classical_work || !classicalWorks.get(iter.classical_work).composer)) {
  1305. title = title.concat(' (', iter.composer, ')');
  1306. }
  1307. dur = iter.duration ? '[' + makeTimeString(iter.duration) + ']' : null;
  1308. let l = 0, j, left, padding, spc;
  1309. let width = prefs.max_tracklist_width - track.length;
  1310. if (dur) width -= dur.length + 1;
  1311. while (title.length > 0) {
  1312. j = width;
  1313. if (title.length > width) {
  1314. while (j > 0 && title[j] != ' ') { --j }
  1315. if (j <= 0) j = width;
  1316. }
  1317. left = title.slice(0, j).trim();
  1318. if (++l <= 1) {
  1319. description += track + left;
  1320. if (dur) {
  1321. spc = width - left.length;
  1322. padding = (spc < 2 ? ' '.repeat(spc) : ' ' + prefs.pad_leader.repeat(spc - 1)) + ' ';
  1323. description += padding + dur;
  1324. }
  1325. width = prefs.max_tracklist_width - track.length - 2;
  1326. } else {
  1327. description += '\n' + ' '.repeat(track.length) + left;
  1328. }
  1329. title = title.slice(j).trim();
  1330. }
  1331. }
  1332. }
  1333. if (prefs.tracklist_style == 1 && totalTime > 0) {
  1334. description += '\n\n' + divs[0].repeat(10) + '\n[color=' + prefs.tracklist_duration_color +
  1335. ']Total time: [i]' + makeTimeString(totalTime) + '[/i][/color][/size]';
  1336. } else if (prefs.tracklist_style == 2) {
  1337. if (totalTime > 0) {
  1338. dur = '[' + makeTimeString(totalTime) + ']';
  1339. description = description.concat('\n\n', divs[0].repeat(32).padStart(prefs.max_tracklist_width));
  1340. description = description.concat('\n', 'Total time:'.padEnd(prefs.max_tracklist_width - dur.length), dur);
  1341. }
  1342. description = description.concat('[/pre][/size]');
  1343. }
  1344. } else { // single
  1345. description += '[align=center]';
  1346. description += isRED ? '[pad=20|20|20|20]' : '';
  1347. description += '[size=4][b][color=' + prefs.tracklist_artist_color + ']' + release.artist + '[/color][hr]';
  1348. //description += '[color=' + prefs.tracklist_single_color + ']';
  1349. description += tracks[0].title;
  1350. //description += '[/color]'
  1351. description += '[/b]';
  1352. if (tracks[0].composer) {
  1353. description += '\n[i][color=' + prefs.tracklist_composer_color + '](' + tracks[0].composer + ')[/color][/i]';
  1354. }
  1355. description += '\n\n[color=' + prefs.tracklist_duration_color +'][' +
  1356. makeTimeString(tracks[0].duration) + '][/color][/size]';
  1357. if (isRED) description += '[/pad]';
  1358. description += '[/align]';
  1359. }
  1360. if (release.comments.length == 1 && release.comments[0]) {
  1361. if (matches = release.comments[0].match(vinylTest)) {
  1362. ripinfo = release.comments[0].slice(matches.index).trim().split(/[\r\n]+/);
  1363. description = description.concat('\n\n', release.comments[0].slice(0, matches.index).trim());
  1364. } else {
  1365. description += '\n\n' + release.comments[0];
  1366. }
  1367. }
  1368. if (elementWritable(ref = document.getElementById('album_desc'))) {
  1369. ref.value = description;
  1370. preview(0);
  1371. }
  1372. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  1373. let editioninfo;
  1374. if (editionTitle) {
  1375. editioninfo = '[size=5][b]' + editionTitle;
  1376. if (release.release_date && (i = extract_year(release.release_date)) > 0) editioninfo += ' (' + i + ')';
  1377. editioninfo = editioninfo.concat('[/b][/size]\n\n');
  1378. } else editioninfo = '';
  1379. ref.value = ref.textLength > 0 ?
  1380. ref.value.concat('\n\n', editioninfo, description) : editioninfo + description;
  1381. preview(0);
  1382. }
  1383. // Release description
  1384. var lineage = '', comment = '', drinfo, srcinfo;
  1385. if (elementWritable(ref = document.getElementById('release_samplerate'))) {
  1386. ref.value = Object.keys(release.srs).length == 1 ? Math.floor(Object.keys(release.srs)[0] / 1000) :
  1387. Object.keys(release.srs).length > 1 ? '999' : null;
  1388. }
  1389. if (Object.keys(release.srs).length > 0) {
  1390. let kHz = Object.keys(release.srs).sort((a, b) => release.srs[b] - release.srs[a])
  1391. .map(f => f / 1000).join('/').concat('kHz');
  1392. if (release.bds.some(bd => bd > 16)) {
  1393. drinfo = '[hide=DR' + (release.drs.length == 1 ? release.drs[0] : '') + '][pre][/pre]';
  1394. if (media == 'Vinyl') {
  1395. let hassr = ref == null || Object.keys(release.srs).length > 1;
  1396. lineage = hassr ? kHz + ' ' : '';
  1397. if (ripinfo) {
  1398. ripinfo[0] = ripinfo[0].replace(vinylTest, '$1[color=blue]$2[/color]');
  1399. if (hassr) { ripinfo[0] = ripinfo[0].replace(/^Vinyl\b/, 'vinyl') }
  1400. lineage += ripinfo[0] + '\n\n[u]Lineage:[/u]' + ripinfo.slice(1).map(k => '\n' + k).join('');
  1401. } else {
  1402. lineage += (hassr ? 'Vinyl' : ' vinyl') + ' rip by [color=blue][/color]\n\n[u]Lineage:[/u]';
  1403. }
  1404. drinfo += '\n\n[img][/img]\n[img][/img]\n[img][/img][/hide]';
  1405. } else if (['Blu-Ray', 'DVD', 'SACD'].includes(media)) {
  1406. lineage = ref ? '' : kHz;
  1407. if (release.channels) add_channel_info();
  1408. if (media == 'SACD' || isFromDSD) {
  1409. lineage += ' from DSD64 using foobar2000\'s SACD decoder (direct-fp64)';
  1410. lineage += '\nOutput gain +0dB';
  1411. }
  1412. drinfo += '[/hide]';
  1413. //add_rg_info();
  1414. } else { // WEB Hi-Res
  1415. if (ref == null || Object.keys(release.srs).length > 1) lineage = kHz;
  1416. if (release.channels && release.channels != 2) add_channel_info();
  1417. if (isFromDSD) {
  1418. lineage += ' from DSD64 using foobar2000\'s SACD decoder (direct-fp64)';
  1419. lineage += '\nOutput gain +0dB';
  1420. } else {
  1421. add_dr_info();
  1422. }
  1423. //if (lineage.length > 0) add_rg_info();
  1424. if (release.bds.length > 1) release.bds.filter(bd => bd != 24).forEach(function(bd) {
  1425. let hybrid_tracks = tracks.filter(it => it.bd == bd).sort(trackComparer).map(function(it) {
  1426. return (totalDiscs > 1 && it.discnumber ? it.discnumber + '-' : '').concat(it.tracknumber);
  1427. });
  1428. if (hybrid_tracks.length < 1) return;
  1429. if (lineage) lineage += '\n';
  1430. lineage += 'Note: track';
  1431. if (hybrid_tracks.length > 1) lineage += 's';
  1432. lineage += ' #' + hybrid_tracks.join(', ') +
  1433. (hybrid_tracks.length > 1 ? ' are' : ' is') + ' ' + bd + 'bit lossless';
  1434. });
  1435. if (Object.keys(release.srs).length == 1 && Object.keys(release.srs)[0] == 88200 || isFromDSD) {
  1436. drinfo += '[/hide]';
  1437. } else {
  1438. drinfo = null;
  1439. }
  1440. }
  1441. } else { // 16bit or lossy
  1442. if (Object.keys(release.srs).some(f => f != 44100)) lineage = kHz;
  1443. if (release.channels && release.channels != 2) add_channel_info();
  1444. //add_dr_info();
  1445. //if (lineage.length > 0) add_rg_info();
  1446. if (['AAC', 'Opus', 'Vorbis'].includes(release.codec) && release.vendor) {
  1447. let _encoder_settings = release.vendor;
  1448. if (release.codec == 'AAC' && /^qaac\s+[\d\.]+/i.test(release.vendor)) {
  1449. let enc = [];
  1450. if (matches = release.vendor.match(/\bqaac\s+([\d\.]+)\b/i)) enc[0] = matches[1];
  1451. if (matches = release.vendor.match(/\bCoreAudioToolbox\s+([\d\.]+)\b/i)) enc[1] = matches[1];
  1452. if (matches = release.vendor.match(/\b(AAC-\S+)\s+Encoder\b/i)) enc[2] = matches[1];
  1453. if (matches = release.vendor.match(/\b([TC]VBR|ABR|CBR)\s+(\S+)\b/)) { enc[3] = matches[1]; enc[4] = matches[2]; }
  1454. if (matches = release.vendor.match(/\bQuality\s+(\d+)\b/i)) enc[5] = matches[1];
  1455. _encoder_settings = 'Converted by Apple\'s ' + enc[2] + ' encoder (' + enc[3] + '-' + enc[4] + ')';
  1456. }
  1457. if (lineage) lineage += '\n\n';
  1458. lineage += _encoder_settings;
  1459. }
  1460. }
  1461. }
  1462. function add_dr_info() {
  1463. if (release.drs.length != 1 || document.getElementById('release_dynamicrange') != null) return false;
  1464. if (lineage.length > 0) lineage += ' | ';
  1465. if (release.drs[0] < 4) lineage += '[color=red]';
  1466. lineage += 'DR' + release.drs[0];
  1467. if (release.drs[0] < 4) lineage += '[/color]';
  1468. return true;
  1469. }
  1470. function add_rg_info() {
  1471. if (release.rgs.length != 1) return false;
  1472. if (lineage.length > 0) lineage += ' | ';
  1473. lineage += 'RG'; //lineage += 'RG ' + rgs[0];
  1474. return true;
  1475. }
  1476. function add_channel_info() {
  1477. if (!release.channels) return false;
  1478. let chi = getChanString(release.channels);
  1479. if (lineage.length > 0 && chi.length > 0) lineage += ', ';
  1480. lineage += chi;
  1481. return chi.length > 0;
  1482. }
  1483. if (url) srcinfo = '[url]' + url + '[/url]';
  1484. if ((ref = document.getElementById('release_lineage')) != null) {
  1485. if (elementWritable(ref)) {
  1486. if (drinfo) comment = drinfo;
  1487. if (lineage && srcinfo) lineage += '\n\n';
  1488. if (srcinfo) lineage += srcinfo;
  1489. ref.value = lineage;
  1490. preview(1);
  1491. }
  1492. } else {
  1493. comment = lineage;
  1494. if (comment && drinfo) comment += '\n\n';
  1495. if (drinfo) comment += drinfo;
  1496. if (comment && srcinfo) comment += '\n\n';
  1497. if (srcinfo) comment += srcinfo;
  1498. }
  1499. if (elementWritable(ref = document.getElementById('release_desc'))) {
  1500. ref.value = comment;
  1501. if (comment.length > 0) preview(isNWCD ? 2 : 1);
  1502. }
  1503. if (release.encoding == 'lossless' && release.codec == 'FLAC'
  1504. && release.bds.includes(24) && release.dirpaths.length == 1) {
  1505. var uri = new URL(release.dirpaths[0] + '\\foo_dr.txt');
  1506. GM_xmlhttpRequest({
  1507. method: 'GET',
  1508. url: uri.href,
  1509. responseType: 'blob',
  1510. onload: function(response) {
  1511. if (response.readyState != 4 || !response.responseText) return;
  1512. var rlsDesc = document.getElementById('release_lineage') || document.getElementById('release_desc');
  1513. if (rlsDesc == null) return;
  1514. var value = rlsDesc.value;
  1515. matches = value.match(/(^\[hide=DR\d*\]\[pre\])\[\/pre\]/im);
  1516. if (matches == null) return;
  1517. var index = matches.index + matches[1].length;
  1518. rlsDesc.value = value.slice(0, index).concat(response.responseText, value.slice(index));
  1519. }
  1520. });
  1521. }
  1522. }
  1523. if (elementWritable(document.getElementById('image') || document.querySelector('input[name="image"]'))) {
  1524. if (tracks.every(track => track.identifiers.IMGURL && track.identifiers.IMGURL == tracks[0].identifiers.IMGURL)) {
  1525. setImage(tracks[0].identifiers.IMGURL);
  1526. } else {
  1527. if (/^https?:\/\/(\w+\.)?discogs\.com\/release\/[\w\-]+\/?$/i.test(url)) url += '/images';
  1528. getCoverOnline(url);
  1529. }
  1530. }
  1531. // } else if (elementWritable(document.getElementById('image') || document.querySelector('input[name="image"]'))
  1532. // && ((ref = document.getElementById('album_desc')) != null || (ref = document.getElementById('body')) != null)
  1533. // && ref.textLength > 0 && (matches = ref.value.matchAll(/\b(https?\/\/[\w\-\&\_\?\=]+)/i)) != null) {
  1534.  
  1535. if (elementWritable(ref = document.getElementById('release_dynamicrange'))) {
  1536. ref.value = release.drs.length == 1 ? release.drs[0] : '';
  1537. }
  1538. if (isRequestNew && prefs.request_default_bounty > 0) {
  1539. let amount = prefs.request_default_bounty < 1024 ? prefs.request_default_bounty : prefs.request_default_bounty / 1024;
  1540. if ((ref = document.getElementById('amount_box')) != null && !ref.disabled) ref.value = amount;
  1541. if ((ref = document.getElementById('unit')) != null && !ref.disabled) {
  1542. ref.value = prefs.request_default_bounty < 1024 ? 'mb' : 'gb';
  1543. }
  1544. exec(function() { Calculate() });
  1545. }
  1546. if (prefs.clean_on_apply) clipBoard.value = '';
  1547. prefs.save();
  1548. return true;
  1549.  
  1550. function getChanString(n) {
  1551. if (!n) return null;
  1552. const chanmap = [
  1553. 'mono',
  1554. 'stereo',
  1555. '2.1',
  1556. '4.0 surround sound',
  1557. '5.0 surround sound',
  1558. '5.1 surround sound',
  1559. '7.0 surround sound',
  1560. '7.1 surround sound',
  1561. ];
  1562. return n >= 1 && n <= 8 ? chanmap[n - 1] : n + 'chn surround sound';
  1563. }
  1564.  
  1565. function init_from_url_music(url, weak = false) {
  1566. if (!/^https?:\/\//i.test(url)) return false;
  1567. var artist, album, albumYear, releaseDate, channels, label, composer, bd, sr = 44.1,
  1568. description, compiler, producer, totalTracks, discSubtitle, discNumber, trackNumber,
  1569. title, trackArtist, catalogue, encoding, format, bitrate, duration, country;
  1570. if (url.toLowerCase().includes('qobuz.com')) {
  1571. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1572. if (response.readyState != 4 || response.status != 200) return;
  1573. dom = domParser.parseFromString(response.responseText, "text/html");
  1574. if (dom == null) return;
  1575.  
  1576. var error = new Error('Error parsing Qobus release page');
  1577. var mainArtist;
  1578. if ((ref = dom.querySelector('div.album-meta > h2.album-meta__artist')) == null) throw error;
  1579. artist = ref.title || ref.textContent.trim();
  1580. if ((ref = dom.querySelector('div.album-meta > h1.album-meta__title')) == null) throw error;
  1581. album = ref.title || ref.textContent.trim();
  1582. ref = dom.querySelector('div.album-meta > ul > li:first-of-type');
  1583. if (ref != null) releaseDate = normalizeDate(ref.textContent);
  1584. ref = dom.querySelector('div.album-meta > ul > li:nth-of-type(2) > a');
  1585. if (ref != null) mainArtist = ref.title || ref.textContent.trim();
  1586. ref = dom.querySelector('p.album-about__copyright');
  1587. albumYear = ref != null && extract_year(ref.textContent) || extract_year(releaseDate);
  1588. let genres = [];
  1589. dom.querySelectorAll('section#about > ul > li').forEach(function(it) {
  1590. function matchLabel(lbl) { return it.textContent.trimLeft().startsWith(lbl) }
  1591. if (/\b(\d+)\s*(?:dis[ck]|disco|disque)/i.test(it.textContent)) {
  1592. totalDiscs = parseInt(RegExp.$1);
  1593. }
  1594. if (/\b(\d+)\s*(?:track|pist[ae]|tracce)/i.test(it.textContent)) {
  1595. totalTracks = parseInt(RegExp.$1);
  1596. }
  1597. if (it.textContent.trimLeft().startsWith('Label')) label = it.children[0].textContent.trim()
  1598. else if (['Composer', 'Compositeur', 'Komponist'].some(matchLabel)) {
  1599. composer = it.children[0].textContent.trim();
  1600. if (/\bVarious\b/i.test(composer)) composer = null;
  1601. } else if (it.textContent.startsWith('Genre') && it.children.length > 0) {
  1602. it.querySelectorAll('a').forEach(it => { genres.push(it.textContent.trim()) });
  1603. if (genres.length > 0 && ['Pop/Rock'].includes(genres[0])) genres.shift();
  1604. if (genres.length > 0 && ['Metal', 'Heavy Metal'].some(genre => genres.includes(genre))) {
  1605. while (genres.length > 1) genres.shift();
  1606. }
  1607. }
  1608. });
  1609. bd = 16; channels = 2;
  1610. dom.querySelectorAll('span.album-quality__info').forEach(function(k) {
  1611. if (/\b([\d\.\,]+)\s*kHz\b/i.test(k.textContent) != null) sr = parseFloat(RegExp.$1.replace(',', '.'));
  1612. if (/\b(\d+)[\-\s]*Bits?\b/i.test(k.textContent) != null) bd = parseInt(RegExp.$1);
  1613. if (/\b(?:Stereo)\b/i.test(k.textContent)) channels = 2;
  1614. if (/\b(\d)\.(\d)\b/.test(k.textContent)) channels = parseInt(RegExp.$1) + parseInt(RegExp.$2);
  1615. });
  1616. get_desc_from_node('section#description > p', response.finalUrl, true);
  1617. if ((ref = dom.querySelector('a[title="Qobuzissime"]')) != null) {
  1618. description += '\x1C[align=center][url=https://www.qobuz.com' + ref.pathname +
  1619. '][img]https://ptpimg.me/4z35uj.png[/img][/url][/align]';
  1620. }
  1621. ref = dom.querySelectorAll('div.player__tracks > div.track > div.track__items');
  1622. let works = dom.querySelectorAll('div.player__tracks > p.player__work');
  1623. if (!totalTracks) totalTracks = ref.length;
  1624. ref.forEach(function(k) {
  1625. discSubtitle = null;
  1626. works.forEach(function(j) {
  1627. if (j.compareDocumentPosition(k) == Node.DOCUMENT_POSITION_FOLLOWING) discSubtitle = j
  1628. });
  1629. discSubtitle = discSubtitle != null ? discSubtitle.textContent.trim() : undefined;
  1630. if (/^\s*(?:dis[ck]|disco|disque)\s+(\d+)\s*$/i.test(discSubtitle)) {
  1631. discNumber = parseInt(RegExp.$1);
  1632. discSubtitle = undefined;
  1633. } else discNumber = undefined;
  1634. if (discNumber > totalDiscs) totalDiscs = discNumber;
  1635. trackNumber = parseInt(k.querySelector('span[itemprop="position"]').textContent.trim());
  1636. title = k.querySelector('span.track__item--name').textContent.trim().replace(/\s+/g, ' ');
  1637. duration = timeStringToTime(k.querySelector('span.track__item--duration').textContent);
  1638. trackArtist = undefined;
  1639. track = [
  1640. artist,
  1641. album,
  1642. albumYear,
  1643. releaseDate,
  1644. label,
  1645. undefined, // catalogue
  1646. undefined, // country
  1647. 'lossless',
  1648. 'FLAC',
  1649. undefined,
  1650. undefined,
  1651. bd,
  1652. sr * 1000,
  1653. channels,
  1654. 'WEB',
  1655. genres.join('; '),
  1656. discNumber,
  1657. totalDiscs,
  1658. discSubtitle,
  1659. trackNumber,
  1660. totalTracks,
  1661. title,
  1662. trackArtist,
  1663. undefined,
  1664. composer,
  1665. undefined,
  1666. undefined,
  1667. compiler,
  1668. producer,
  1669. duration,
  1670. undefined,
  1671. undefined,
  1672. undefined,
  1673. undefined,
  1674. response.finalUrl,
  1675. undefined,
  1676. description,
  1677. undefined,
  1678. ];
  1679. tracks.push(track.join('\x1E'));
  1680. });
  1681. clipBoard.value = tracks.join('\n');
  1682. fill_from_text_music();
  1683. } });
  1684. return true;
  1685. } else if (url.toLowerCase().includes('highresaudio.com')) {
  1686. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1687. if (response.readyState != 4 || response.status != 200) return;
  1688. dom = domParser.parseFromString(response.responseText, "text/html");
  1689. if (dom == null) return;
  1690.  
  1691. ref = dom.querySelector('h1 > span.artist');
  1692. if (ref != null) artist = ref.textContent.trim();
  1693. ref = dom.getElementById('h1-album-title');
  1694. if (ref != null) album = ref.firstChild.textContent.trim();
  1695. let genres = [], format;
  1696. dom.querySelectorAll('div.album-col-info-data > div > p').forEach(function(k) {
  1697. if (/\b(?:Genre|Subgenre)\b/i.test(k.firstChild.textContent)) genres.push(k.lastChild.textContent.trim());
  1698. if (/\b(?:Label)\b/i.test(k.firstChild.textContent)) label = k.lastChild.textContent.trim();
  1699. if (/\b(?:Album[\s\-]Release)\b/i.test(k.firstChild.textContent)) {
  1700. albumYear = normalizeDate(k.lastChild.textContent);
  1701. }
  1702. if (/\b(?:HRA[\s\-]Release)\b/i.test(k.firstChild.textContent)) {
  1703. releaseDate = normalizeDate(k.lastChild.textContent);
  1704. }
  1705. });
  1706. i = 0;
  1707. dom.querySelectorAll('tbody > tr > td.col-format').forEach(function(k) {
  1708. if (/^(FLAC)\s*([\d\.\,]+)\b/.exec(k.textContent) != null) {
  1709. format = RegExp.$1;
  1710. sr = parseFloat(RegExp.$2.replace(/,/g, '.'));
  1711. ++i;
  1712. }
  1713. });
  1714. if (i > 1) sr = undefined; // ambiguous
  1715. get_desc_from_node('div#albumtab-info > p', response.finalUrl);
  1716. ref = dom.querySelectorAll('ul.playlist > li.pltrack');
  1717. totalTracks = ref.length;
  1718. ref.forEach(function(k) {
  1719. discSubtitle = k;
  1720. while ((discSubtitle = discSubtitle.previousElementSibling) != null) {
  1721. if (discSubtitle.nodeName == 'LI' && discSubtitle.className == 'plinfo') {
  1722. discSubtitle = discSubtitle.textContent.replace(/\s*:$/, '').trim();
  1723. if (/\b(?:DIS[CK]|Volume|CD)\s*(\d+)\b/i.exec(discSubtitle)) discNumber = parseInt(RegExp.$1);
  1724. break;
  1725. }
  1726. }
  1727. //if (discnumber > totalDiscs) totalDiscs = discnumber;
  1728. trackNumber = parseInt(k.querySelector('span.track').textContent.trim());
  1729. title = k.querySelector('span.title').textContent.trim().replace(/\s+/g, ' ');
  1730. duration = timeStringToTime(k.querySelector('span.time').textContent);
  1731. trackArtist = undefined;
  1732. track = [
  1733. artist,
  1734. album,
  1735. albumYear,
  1736. releaseDate,
  1737. label,
  1738. undefined, // catalogue
  1739. undefined, // country
  1740. 'lossless',
  1741. 'FLAC', //format,
  1742. undefined,
  1743. undefined,
  1744. 24,
  1745. sr * 1000,
  1746. 2,
  1747. 'WEB',
  1748. genres.join('; '),
  1749. discNumber,
  1750. totalDiscs,
  1751. discSubtitle,
  1752. trackNumber,
  1753. totalTracks,
  1754. title,
  1755. trackArtist,
  1756. undefined,
  1757. composer,
  1758. undefined,
  1759. undefined,
  1760. compiler,
  1761. producer,
  1762. duration,
  1763. undefined,
  1764. undefined,
  1765. undefined,
  1766. undefined,
  1767. response.finalUrl,
  1768. undefined,
  1769. description,
  1770. undefined,
  1771. ];
  1772. tracks.push(track.join('\x1E'));
  1773. });
  1774. clipBoard.value = tracks.join('\n');
  1775. fill_from_text_music();
  1776. } });
  1777. return true;
  1778. } else if (url.toLowerCase().includes('bandcamp.com')) {
  1779. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1780. if (response.readyState != 4 || response.status != 200) return;
  1781. dom = domParser.parseFromString(response.responseText, "text/html");
  1782. if (dom == null) return;
  1783.  
  1784. ref = dom.querySelector('span[itemprop="byArtist"] > a');
  1785. if (ref != null) artist = ref.textContent.trim();
  1786. ref = dom.querySelector('h2[itemprop="name"]');
  1787. if (ref != null) album = ref.textContent.trim();
  1788. ref = dom.querySelector('div.tralbum-credits');
  1789. if (ref != null && /\breleased\s+(.*?\b\d{4})\b/i.test(ref.textContent)) {
  1790. releaseDate = RegExp.$1;
  1791. albumYear = releaseDate;
  1792. }
  1793. ref = dom.querySelector('p#band-name-location > span.title');
  1794. if (ref != null) label = ref.textContent.trim();
  1795. let tags = new TagManager;
  1796. dom.querySelectorAll('div.tralbum-tags > a.tag').forEach(k => { tags.add(k.textContent.trim()) });
  1797. description = [];
  1798. dom.querySelectorAll('div.tralbumData').forEach(function(k) {
  1799. if (!k.classList.contains('tralbum-tags')) description.push(html2php(k, response.finalUrl))
  1800. });
  1801. description = description.join('\n\n').replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  1802. ref = dom.querySelectorAll('table.track_list > tbody > tr[itemprop="tracks"]');
  1803. totalTracks = ref.length;
  1804. ref.forEach(function(k) {
  1805. trackNumber = parseInt(k.querySelector('div.track_number').textContent);
  1806. title = k.querySelector('span.track-title').textContent.trim().replace(/\s+/g, ' ');
  1807. duration = timeStringToTime(k.querySelector('span.time').textContent);
  1808. trackArtist = undefined;
  1809. track = [
  1810. artist,
  1811. album,
  1812. albumYear,
  1813. releaseDate,
  1814. label,
  1815. undefined, // catalogue
  1816. undefined, // country
  1817. undefined, //'lossless',
  1818. undefined, //'FLAC',
  1819. undefined,
  1820. undefined,
  1821. undefined,
  1822. undefined,
  1823. 2,
  1824. 'WEB',
  1825. tags.toString(),
  1826. discNumber,
  1827. totalDiscs,
  1828. undefined,
  1829. trackNumber,
  1830. totalTracks,
  1831. title,
  1832. trackArtist,
  1833. undefined,
  1834. composer,
  1835. undefined,
  1836. undefined,
  1837. compiler,
  1838. producer,
  1839. duration,
  1840. undefined,
  1841. undefined,
  1842. undefined,
  1843. undefined,
  1844. response.finalUrl,
  1845. undefined,
  1846. description,
  1847. undefined,
  1848. ];
  1849. tracks.push(track.join('\x1E'));
  1850. });
  1851. clipBoard.value = tracks.join('\n');
  1852. fill_from_text_music();
  1853. } });
  1854. return true;
  1855. } else if (url.toLowerCase().includes('prestomusic.com')) {
  1856. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1857. if (response.readyState != 4 || response.status != 200) return;
  1858. dom = domParser.parseFromString(response.responseText, "text/html");
  1859. if (dom == null) return;
  1860.  
  1861. artist = getArtists(dom.querySelectorAll('div.c-product-block__contributors > p'));
  1862. ref = dom.querySelector('h1.c-product-block__title');
  1863. if (ref != null) album = ref.lastChild.textContent.trim();
  1864. dom.querySelectorAll('div.c-product-block__metadata > ul > li').forEach(function(k) {
  1865. if (k.firstChild.textContent.includes('Release Date')) {
  1866. releaseDate = extract_year(k.lastChild.textContent);
  1867. } else if (k.firstChild.textContent.includes('Label')) {
  1868. label = k.lastChild.textContent.trim();
  1869. } else if (k.firstChild.textContent.includes('Catalogue No')) {
  1870. catalogue = k.lastChild.textContent.trim();
  1871. }
  1872. });
  1873. albumYear = releaseDate;
  1874. var genre;
  1875. if (/\/jazz\//i.test(response.finalUrl)) genre = 'Jazz';
  1876. if (/\/classical\//i.test(response.finalUrl)) genre = 'Classical';
  1877. get_desc_from_node('div#about > div > p', response.finalUrl, true);
  1878. ref = dom.querySelectorAll('div#related > div > ul > li');
  1879. composer = [];
  1880. ref.forEach(function(k) {
  1881. if (k.parentNode.previousElementSibling.textContent.includes('Composers')) {
  1882. composer.push(k.firstChild.textContent.trim().replace(/^(.*?)\s*,\s+(.*)$/, '$2 $1'));
  1883. }
  1884. });
  1885. composer = composer.join(', ') || undefined;
  1886. ref = dom.querySelectorAll('div.has--sample');
  1887. totalTracks = ref.length;
  1888. trackNumber = 0;
  1889. ref.forEach(function(it) {
  1890. trackNumber = ++trackNumber;
  1891. title = it.querySelector('p.c-track__title').textContent.trim().replace(/\s+/g, ' ');
  1892. duration = timeStringToTime(it.querySelector('div.c-track__duration').textContent);
  1893. let parent = it;
  1894. if (it.classList.contains('c-track')) {
  1895. parent = it.parentNode.parentNode;
  1896. if (parent.classList.contains('c-expander')) parent = parent.parentNode;
  1897. discSubtitle = parent.querySelector(':scope > div > div > div > p.c-track__title');
  1898. discSubtitle = discSubtitle != null ? discSubtitle.textContent.trim().replace(/\s+/g, ' ') : undefined;
  1899. } else {
  1900. discSubtitle = null;
  1901. }
  1902. trackArtist = getArtists(parent.querySelectorAll(':scope > div.c-track__details > ul > li'));
  1903. if (trackArtist.equalTo(artist)) trackArtist = [];
  1904. track = [
  1905. artist.join('; '),
  1906. album,
  1907. albumYear,
  1908. releaseDate,
  1909. label,
  1910. catalogue,
  1911. undefined, // country
  1912. undefined, // encoding
  1913. undefined, // format
  1914. undefined,
  1915. undefined, // bitrate
  1916. undefined, // BD
  1917. undefined, // SR
  1918. 2,
  1919. 'WEB',
  1920. genre,
  1921. discNumber,
  1922. totalDiscs,
  1923. discSubtitle,
  1924. trackNumber,
  1925. totalTracks,
  1926. title,
  1927. trackArtist.join(', '),
  1928. undefined,
  1929. composer,
  1930. undefined,
  1931. undefined,
  1932. compiler,
  1933. producer,
  1934. duration,
  1935. undefined,
  1936. undefined,
  1937. undefined,
  1938. undefined,
  1939. response.finalUrl,
  1940. undefined,
  1941. description,
  1942. undefined,
  1943. ];
  1944. tracks.push(track.join('\x1E'));
  1945. });
  1946. clipBoard.value = tracks.join('\n');
  1947. fill_from_text_music();
  1948.  
  1949. function getArtists(nodeList) {
  1950. var artists = [];
  1951. nodeList.forEach(function(it) {
  1952. if (it.textContent.startsWith('Record')) return;
  1953. splitArtists(it.textContent.trim()).forEach(function(it) {
  1954. artists.push(it.replace(/\s*\([^\(\)]*\)$/, ''));
  1955. });
  1956. });
  1957. return artists;
  1958. }
  1959. } });
  1960. return true;
  1961. } else if (url.toLowerCase().includes('discogs.com/') && /\/releases?\/(\d+)\b/i.test(url)) {
  1962. GM_xmlhttpRequest({ method: 'GET', url: 'https://api.discogs.com/releases/' + RegExp.$1, onload: function(response) {
  1963. if (response.readyState != 4 || response.status != 200) return;
  1964. var json = JSON.parse(response.responseText);
  1965. if (json == null) return;
  1966.  
  1967. const removeArtistNdx = /\s*\(\d+\)$/;
  1968. function getArtists(root) {
  1969. function filterArtists(rx, anv = true) {
  1970. return root.extraartists instanceof Array && rx instanceof RegExp ?
  1971. root.extraartists
  1972. .filter(it => rx.test(it.role))
  1973. .map(it => (anv && it.anv || it.name || '').replace(removeArtistNdx, '')) : [];
  1974. }
  1975. var artists = [];
  1976. for (var ndx = 0; ndx < 7; ++ndx) artists[ndx] = [];
  1977. ndx = 0;
  1978. if (root.artists) root.artists.forEach(function(it) {
  1979. artists[ndx].push((it.anv || it.name).replace(removeArtistNdx, ''));
  1980. if (/^feat/i.test(it.join)) ndx = 1;
  1981. });
  1982. return [
  1983. artists[0],
  1984. artists[1].concat(filterArtists(/^(?:featuring)$/i)),
  1985. artists[2].concat(filterArtists(/\b(?:Remixed[\s\-]By|Remixer)\b/i)),
  1986. artists[3].concat(filterArtists(/\b(?:(?:Written|Composed)[\s\-]By|Composer)\b/i, false)),
  1987. artists[4].concat(filterArtists(/\b(?:Conducted[\s\-]By|Conductor)\b/i)),
  1988. artists[5].concat(filterArtists(/\b(?:Compiled[\s\-]By|Compiler)\b/i)),
  1989. artists[6].concat(filterArtists(/\b(?:Produced[\s\-]By|Producer)\b/i)),
  1990. // filter off from performers
  1991. filterArtists(/\b(?:(?:Mixed)[\s\-]By|Mixer)\b/i),
  1992. filterArtists(/\b(?:(?:Written|Composed)[\s\-]By|Composer)\b/i, true),
  1993. ];
  1994. }
  1995. var albumArtists = getArtists(json);
  1996. if (albumArtists[0].length > 0) {
  1997. artist = albumArtists[0].join('; ');
  1998. if (albumArtists[1].length > 0) artist += ' feat. ' + albumArtists[1].join('; ');
  1999. }
  2000. album = json.title;
  2001. var editions = [];
  2002. if (editions.length > 0) album += ' (' + editions.join(' / ') + ')';
  2003. releaseDate = json.released;
  2004. albumYear = json.year;
  2005. label = [];
  2006. catalogue = [];
  2007. json.labels.forEach(function(it) {
  2008. //if (it.entity_type_name != 'Label') return;
  2009. if (!/^Not On Label\b/i.test(it.name)) label.pushUniqueCaseless(it.name.replace(removeArtistNdx, ''));
  2010. catalogue.pushUniqueCaseless(it.catno);
  2011. });
  2012. description = '';
  2013. if (json.companies && json.companies.length > 0) {
  2014. description = '[b]Companies, etc.[/b]\n';
  2015. let type_names = new Set(json.companies.map(it => it.entity_type_name));
  2016. type_names.forEach(function(type_name) {
  2017. description += '\n' + type_name + ' – ' + json.companies
  2018. .filter(it => it.entity_type_name == type_name)
  2019. .map(function(it) {
  2020. var result = '[url=https://www.discogs.com/label/' + it.id + ']' +
  2021. it.name.replace(removeArtistNdx, '') + '[/url]';
  2022. if (it.catno) result += ' – ' + it.catno;
  2023. return result;
  2024. })
  2025. .join(', ');
  2026. });
  2027. }
  2028. if (json.extraartists && json.extraartists.length > 0) {
  2029. if (description) description += '\n\n';
  2030. description += '[b]Credits[/b]\n';
  2031. let roles = new Set(json.extraartists.map(it => it.role));
  2032. roles.forEach(function(role) {
  2033. description += '\n' + role + ' – ' + json.extraartists
  2034. .filter(it => it.role == role)
  2035. .map(function(it) {
  2036. var result = '[url=https://www.discogs.com/artist/' + it.id + ']' +
  2037. (it.anv || it.name).replace(removeArtistNdx, '') + '[/url]';
  2038. if (it.tracks) result += ' (tracks: ' + it.tracks + ')';
  2039. return result;
  2040. })
  2041. .join(', ');
  2042. });
  2043. }
  2044. if (json.notes) {
  2045. if (description) description += '\n\n';
  2046. description += '[b]Notes[/b]\n\n' + json.notes.trim();
  2047. }
  2048. if (json.identifiers && json.identifiers.length > 0) {
  2049. if (description) description += '\n\n';
  2050. description += '[b]Barcode and Other Identifiers[/b]\n';
  2051. json.identifiers.forEach(function(it) {
  2052. description += '\n' + it.type;
  2053. if (it.description) description += ' (' + it.description + ')';
  2054. description += ': ' + it.value;
  2055. });
  2056. }
  2057. country = json.country;
  2058. totalTracks = json.tracklist.length;
  2059. totalDiscs = json.format_quantity;
  2060. var identifiers = ['DISCOGS_ID=' + json.id];
  2061. [
  2062. ['Single', 'Single'],
  2063. ['EP', 'EP'],
  2064. ['Compilation', 'Compilation'],
  2065. ['Soundtrack', 'Soundtrack'],
  2066. ].forEach(function(k) {
  2067. if (json.formats.every(it => it.descriptions && it.descriptions.includesCaseless(k[0]))) {
  2068. identifiers.push('RELEASETYPE=' + k[1]);
  2069. }
  2070. });
  2071. json.identifiers.forEach(function(it) {
  2072. identifiers.push(it.type.replace(/\W+/g, '_').toUpperCase() + '=' + it.value.replace(/\s/g, '\x1B'));
  2073. });
  2074. json.formats.forEach(function(it) {
  2075. if (it.descriptions) it.descriptions.forEach(function(it) {
  2076. if (/^(?:.+?\s+Edition|Remaster(?:ed)|Reissue|.+?\s+Release|Enhanced|Promo)$/.test(it)) {
  2077. editions.push(it);
  2078. }
  2079. });
  2080. if (media) return;
  2081. if (it.name.includes('File')) {
  2082. if (['FLAC', 'WAV', 'AIF', 'AIFF', 'PCM'].some(k => it.descriptions.includes(k))) {
  2083. media = 'WEB'; encoding = 'lossless'; format = 'FLAC';
  2084. } else if (it.descriptions.includes('AAC')) {
  2085. media = 'WEB'; encoding = 'lossy'; format = 'AAC'; bd = undefined;
  2086. if (/(\d+)\s*kbps\b/i.test(it.text)) bitrate = parseInt(RegExp.$1);
  2087. } else if (it.descriptions.includes('MP3')) {
  2088. media = 'WEB'; encoding = 'lossy'; format = 'MP3'; bd = undefined;
  2089. if (/(\d+)\s*kbps\b/i.test(it.text)) bitrate = parseInt(RegExp.$1);
  2090. }
  2091. } else if (['CD', 'DVD', 'Vinyl', 'LP', '7"', '12"', '10"', '5"', 'SACD', 'Hybrid', 'Blu',
  2092. 'Cassette','Cartridge', 'Laserdisc', 'VCD'].some(k => it.name.includes(k))) media = it.name;
  2093. });
  2094. json.tracklist.forEach(function(it) {
  2095. if (it.type_.toLowerCase() == 'heading') {
  2096. discSubtitle = it.title;
  2097. } else if (it.type_.toLowerCase() == 'track') {
  2098. if (/^([a-zA-Z]+)?(\d+)-(\w+)$/.test(it.position)) {
  2099. if (RegExp.$1) identifiers.push('VOL_MEDIA=' + RegExp.$1.replace(/\s/g, '\x1B'));
  2100. discNumber = RegExp.$2;
  2101. trackNumber = RegExp.$3;
  2102. } else {
  2103. discNumber = undefined;
  2104. trackNumber = it.position;
  2105. }
  2106. let trackArtists = getArtists(it);
  2107. if (trackArtists[0].length > 0 && !trackArtists[0].equalTo(albumArtists[0])
  2108. || trackArtists[1].length > 0 && !trackArtists[1].equalTo(albumArtists[1])) {
  2109. trackArtist = (trackArtists[0].length > 0 ? trackArtists : albumArtists)[0].join('; ');
  2110. if (trackArtists[1].length > 0) trackArtist += ' feat. ' + trackArtists[1].join('; ');
  2111. } else {
  2112. trackArtist = null;
  2113. }
  2114. title = it.title;
  2115. duration = timeStringToTime(it.duration);
  2116. let performer = it.extraartists instanceof Array && it.extraartists
  2117. .map(it => (it.anv || it.name).replace(removeArtistNdx, ''))
  2118. .filter(function(artist) {
  2119. return !albumArtists.slice(2).some(it => it instanceof Array && it.includes(artist))
  2120. && !trackArtists.slice(2).some(it => it instanceof Array && it.includes(artist))
  2121. });
  2122. track = [
  2123. artist,
  2124. album,
  2125. albumYear,
  2126. releaseDate,
  2127. label.join(' / '),
  2128. catalogue.join(' / '),
  2129. country,
  2130. encoding,
  2131. format,
  2132. undefined,
  2133. bitrate,
  2134. bd,
  2135. undefined, // samplerate
  2136. undefined, // channels
  2137. media,
  2138. (json.genres ? json.genres.join('; ') : '') + (json.styles ? ' | ' + json.styles.join('; ') : ''),
  2139. discNumber,
  2140. totalDiscs,
  2141. discSubtitle,
  2142. trackNumber,
  2143. totalTracks,
  2144. title,
  2145. trackArtist,
  2146. performer instanceof Array && performer.join('; ') || undefined,
  2147. stringyfyRole(3), // composers
  2148. stringyfyRole(4), // conductors
  2149. stringyfyRole(2), // remixers
  2150. stringyfyRole(5), // DJs/compilers
  2151. stringyfyRole(6), // producers
  2152. duration,
  2153. undefined,
  2154. undefined,
  2155. undefined,
  2156. undefined,
  2157. undefined, // URL
  2158. undefined,
  2159. description.replace(/\n/g, '\x1C').replace(/\r/g, '\x1D'),
  2160. identifiers.join(' '),
  2161. ];
  2162. tracks.push(track.join('\x1E'));
  2163.  
  2164. function stringyfyRole(ndx) {
  2165. return (trackArtists[ndx] instanceof Array && trackArtists[ndx].length > 0 ?
  2166. trackArtists : albumArtists)[ndx].join('; ');
  2167. }
  2168. }
  2169. });
  2170. clipBoard.value = tracks.join('\n');
  2171. fill_from_text_music();
  2172. } });
  2173. return true;
  2174. } else if (url.toLowerCase().includes('supraphonline.cz')) {
  2175. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2176. if (response.readyState != 4 || response.status != 200) return;
  2177. dom = domParser.parseFromString(response.responseText, "text/html");
  2178. if (dom == null) return;
  2179.  
  2180. var genre, conductor = [];
  2181. artist = [];
  2182. dom.querySelectorAll('h2.album-artist > a').forEach(function(it) {
  2183. artist.pushUnique(it.title);
  2184. });
  2185. isVA = false;
  2186. if (artist.length == 0 && (ref = dom.querySelector('h2.album-artist[title]')) != null) {
  2187. if (vaParser.test(ref.title)) isVA = true;
  2188. if (isVA) artist = ['Various Artists']; //else artist = [ref.title];
  2189. }
  2190. ref = dom.querySelector('span[itemprop="byArtist"] > meta[itemprop="name"]');
  2191. if (ref != null && /^(?:Různí\s+interpreti)$/i.test(ref.content)) isVA = true;
  2192. if ((ref = dom.querySelector('h1[itemprop="name"]')) != null) album = ref.firstChild.data.trim();
  2193. if ((ref = dom.querySelector('meta[itemprop="numTracks"]')) != null) totalTracks = parseInt(ref.content);
  2194. if ((ref = dom.querySelector('meta[itemprop="genre"]')) != null) genre = ref.content;
  2195. if ((ref = dom.querySelector('li.album-version > div.selected > div')) != null) {
  2196. if (/\b(?:CD)\b/.test(ref.textContent)) { media = 'CD'; }
  2197. if (/\b(?:LP)\b/.test(ref.textContent)) { media = 'Vinyl'; }
  2198. if (/\b(?:MP3)\b/.test(ref.textContent)) { media = 'WEB'; encoding = 'lossy'; format = 'MP3'; }
  2199. if (/\b(?:FLAC)\b/.test(ref.textContent)) { media = 'WEB'; encoding = 'lossless'; format = 'FLAC'; bd = 16; }
  2200. if (/\b(?:Hi[\s\-]*Res)\b/.test(ref.textContent)) { media = 'WEB'; encoding = 'lossless'; format = 'FLAC'; bd = 24; }
  2201. }
  2202. dom.querySelectorAll('ul.summary > li').forEach(function(it) {
  2203. if (it.children.length < 1) return;
  2204. if (it.children[0].textContent.includes('Nosič')) media = it.lastChild.textContent.trim();
  2205. if (it.children[0].textContent.includes('Datum vydání')) releaseDate = normalizeDate(it.lastChild.textContent);
  2206. //if (it.children[0].textContent.includes('Žánr')) genre = it.lastChild.textContent.trim();
  2207. if (it.children[0].textContent.includes('Vydavatel')) label = it.lastChild.textContent.trim();
  2208. if (it.children[0].textContent.includes('Katalogové číslo')) catalogue = it.lastChild.textContent.trim();
  2209. if (it.children[0].textContent.includes('Formát')) {
  2210. if (/\b(?:FLAC|WAV|AIFF?)\b/.test(it.lastChild.textContent)) { encoding = 'lossless'; format = 'FLAC'; }
  2211. if (/\b(\d+)[\-\s]?bits?\b/i.test(it.lastChild.textContent)) bd = parseInt(RegExp.$1);
  2212. if (/\b([\d\.\,]+)[\-\s]?kHz\b/.test(it.lastChild.textContent)) sr = parseFloat(RegExp.$1.replace(',', '.'));
  2213. }
  2214. if (it.children[0].textContent.includes('Celková stopáž')) totalTime = timeStringToTime(it.lastChild.textContent.trim());
  2215. if (/^(?:\([PC]\)|℗|©)$/i.test(it.children[0].textContent)) albumYear = extract_year(it.lastChild.data);
  2216. });
  2217. [
  2218. [/^(?:Orchestrální\s+hudba)$/i, 'Orchestral Music'],
  2219. [/^(?:Komorní\s+hudba)$/i, 'Chamber Music'],
  2220. [/^(?:Vokální)$/i, 'Classical, Vocal'],
  2221. [/^(?:Klasická\s+hudba)$/i, 'Classical'],
  2222. [/^(?:Melodram)$/i, 'Classical, Melodram'],
  2223. [/^(?:Symfonie)$/i, 'Symphony'],
  2224. [/^(?:Vánoční\s+hudba)$/i, 'Christmas Music'],
  2225. [/^(?:Alternativní)$/i, 'Alternative'],
  2226. [/^(?:Dechová\s+hudba)$/i, 'Brass Music'],
  2227. [/^(?:Elektronika)$/i, 'Electronic'],
  2228. [/^(?:Folklor)$/i, 'Folclore, World Music'],
  2229. [/^(?:Instrumentální\s+hudba)$/i, 'Instrumental'],
  2230. [/^(?:Latinské\s+rytmy)$/i, 'Latin'],
  2231. [/^(?:Meditační\s+hudba)$/i, 'Meditative'],
  2232. [/^(?:Pro\s+děti)$/i, 'Children'],
  2233. ].forEach(it => { if (it[0].test(genre)) genre = it[1] });
  2234. const creators = [
  2235. 'autoři',
  2236. 'interpreti',
  2237. 'tělesa',
  2238. 'digitalizace',
  2239. ];
  2240. var ndx;
  2241. artists = [];
  2242. for (i = 0; i < 4; ++i) artists[i] = {};
  2243. dom.querySelectorAll('ul.sidebar-artist > li').forEach(function(it) {
  2244. if ((ref = it.querySelector('h3')) != null) {
  2245. ndx = undefined;
  2246. creators.forEach((it, _ndx) => { if (ref.textContent.includes(it)) ndx = _ndx });
  2247. } else {
  2248. if (typeof ndx != 'number') return;
  2249. ref = it.querySelector('span');
  2250. let key = ref != null ? ref.textContent.replace(/\s*:.*$/, '').toLowerCase() : undefined;
  2251. [
  2252. [/^(?:zpěv)$/, 'vocals'],
  2253. [/^(?:hudba)$/, 'music'],
  2254. [/^(?:původní\s+text)$/, 'original lyrics'],
  2255. [/^(?:text)$/, 'lyrics'],
  2256. [/^(?:autor)$/, 'author'],
  2257. [/^(?:účinkuje)$/, 'participating'],
  2258. [/^(?:nahrál)$/, 'recorded'],
  2259. [/^(?:sbormistr)$/, 'choirmaster'],
  2260. [/^(?:řídí|dirigent)$/, 'conductor'],
  2261. ].forEach(it => { if (it[0].test(key)) key = it[1] });
  2262. if (!(artists[ndx][key] instanceof Array)) artists[ndx][key] = [];
  2263. artists[ndx][key].pushUnique(it.querySelector('a').textContent.trim());
  2264. }
  2265. });
  2266. get_desc_from_node('div[itemprop="description"] p', response.finalUrl, true);
  2267. composer = [];
  2268. var performers = [];
  2269. function dumpArtist(ndx, role, title) {
  2270. if (!role || role == 'undefined') return;
  2271. if (description.length > 0) description += '\x1C' ;
  2272. description += role + ' – ';
  2273. description += artists[ndx][role].join(', ');
  2274. }
  2275. for (iter = 1; iter < 3; ++iter) Object.keys(artists[iter]).forEach(function(it) {
  2276. (it == 'conductor' ? conductor : performers).pushUnique(...artists[iter][it]);
  2277. dumpArtist(iter, it);
  2278. });
  2279. Object.keys(artists[0]).forEach(it => {
  2280. composer.pushUnique(...artists[0][it])
  2281. dumpArtist(0, it);
  2282. });
  2283. Object.keys(artists[3]).forEach(function(it) {
  2284. dumpArtist(3, it);
  2285. });
  2286. if (artist.length == 0 && !isVA) artist = performers;
  2287. dom.querySelectorAll('table.table-tracklist > tbody > tr').forEach(function(it) {
  2288. if (it.classList.contains('cd-header')) {
  2289. discNumber = /\b\d+\b/.test(it.querySelector('h3').firstChild.data.trim())
  2290. && parseInt(RegExp.lastMatch) || undefined;
  2291. }
  2292. if (it.classList.contains('song-header')) {
  2293. discSubtitle = it.children[0].title.trim() || undefined;
  2294. }
  2295. if (it.classList.contains('track') && it.id) {
  2296. if (/^\s*(\d+)\.?\s*$/.test(it.children[0].firstChild.textContent)) {
  2297. trackNumber = parseInt(RegExp.$1);
  2298. }
  2299. ref = it.querySelectorAll('meta[itemprop="name"]');
  2300. if (ref.length > 0) title = ref[0].content;
  2301. if (/^PT(\d+)H(\d+)M(\d+)S$/i.test(it.querySelector('meta[itemprop="duration"]').content)) {
  2302. duration = parseInt(RegExp.$1 || 0) * 60**2 + parseInt(RegExp.$2 || 0) * 60 + parseInt(RegExp.$3 || 0);
  2303. }
  2304. track = [
  2305. isVA ? 'Various Artists' : artist.join('; '),
  2306. album,
  2307. albumYear,
  2308. releaseDate,
  2309. label,
  2310. catalogue,
  2311. undefined, // country
  2312. encoding,
  2313. format,
  2314. undefined,
  2315. undefined,
  2316. bd,
  2317. sr * 1000,
  2318. 2,
  2319. media,
  2320. genre,
  2321. discNumber,
  2322. totalDiscs,
  2323. discSubtitle,
  2324. trackNumber,
  2325. totalTracks,
  2326. title,
  2327. trackArtist,
  2328. performers.join(', '),
  2329. composer.join(', '),
  2330. conductor.join(', '),
  2331. undefined,
  2332. undefined, // compiler
  2333. undefined, // producer
  2334. duration,
  2335. undefined,
  2336. undefined,
  2337. undefined,
  2338. undefined,
  2339. response.finalUrl,
  2340. undefined,
  2341. description,
  2342. /^track-(\d+)$/i.test(it.id) ? 'TRACK_ID=' + RegExp.$1 : undefined,
  2343. ];
  2344. tracks.push(track.join('\x1E'));
  2345. }
  2346. });
  2347. clipBoard.value = tracks.join('\n');
  2348. fill_from_text_music();
  2349. } });
  2350. return true;
  2351. } else if (url.toLowerCase().includes('bontonland.cz')) {
  2352. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2353. if (response.readyState != 4 || response.status != 200) return;
  2354. dom = domParser.parseFromString(response.responseText, "text/html");
  2355. if (dom == null) return;
  2356.  
  2357. ref = dom.querySelector('div#detailheader > h1');
  2358. if (ref != null && /^(.*?)\s*:\s*(.*)$/.test(ref.textContent.trim())) {
  2359. artist = RegExp.$1;
  2360. album = RegExp.$2;
  2361. }
  2362. var EAN;
  2363. dom.querySelectorAll('table > tbody > tr > td.nazevparametru').forEach(function(it) {
  2364. if (it.textContent.includes('Datum vydání')) {
  2365. releaseDate = normalizeDate(it.nextElementSibling.textContent);
  2366. albumYear = extract_year(it.nextElementSibling.textContent);
  2367. } else if (it.textContent.includes('Nosič / počet')) {
  2368. if (/^(.*?)\s*\/\s*(.*)$/.test(it.nextElementSibling.textContent)) {
  2369. media = RegExp.$1;
  2370. totalDiscs = RegExp.$2;
  2371. }
  2372. } else if (it.textContent.includes('Interpret')) {
  2373. artist = it.nextElementSibling.textContent.trim();
  2374. } else if (it.textContent.includes('EAN')) {
  2375. EAN = 'BARCODE=' + it.nextElementSibling.textContent.trim();
  2376. }
  2377. });
  2378. get_desc_from_node('div#detailtabpopis > div[class^="pravy"] > div > p:not(:last-of-type)', response.finalUrl, true);
  2379. const plParser = /^(\d+)(?:\s*[\/\.\-\:\)])?\s+(.*?)(?:\s+((?:(?:\d+:)?\d+:)?\d+))?$/;
  2380. ref = dom.querySelector('div#detailtabpopis > div[class^="pravy"] > div > p:last-of-type');
  2381. if (ref == null) throw new Error('Playlist not located');
  2382. var trackList = html2php(ref).split(/[\r\n]+/);
  2383. trackList = trackList.filter(it => plParser.test(it.trim())).map(it => plParser.exec(it.trim()));
  2384. totalTracks = trackList.length;
  2385. if (!totalTracks) throw new Error('Playlist empty');
  2386. trackList.forEach(function(it) {
  2387. trackNumber = it[1];
  2388. title = it[2];
  2389. duration = timeStringToTime(it[3]);
  2390. trackArtist = undefined;
  2391. track = [
  2392. artist,
  2393. album,
  2394. albumYear,
  2395. releaseDate,
  2396. label,
  2397. undefined, // catalogue
  2398. undefined, // country
  2399. undefined, // encoding
  2400. undefined, // format
  2401. undefined,
  2402. undefined,
  2403. undefined,
  2404. undefined,
  2405. undefined,
  2406. 'CD', // media
  2407. undefined, // genre
  2408. discNumber,
  2409. totalDiscs,
  2410. discSubtitle,
  2411. trackNumber,
  2412. totalTracks,
  2413. title,
  2414. trackArtist,
  2415. undefined,
  2416. undefined, // composer
  2417. undefined,
  2418. undefined,
  2419. undefined, // compiler
  2420. undefined, // producer
  2421. duration,
  2422. undefined,
  2423. undefined,
  2424. undefined,
  2425. undefined,
  2426. response.finalUrl,
  2427. undefined,
  2428. description,
  2429. EAN,
  2430. ];
  2431. tracks.push(track.join('\x1E'));
  2432. });
  2433. clipBoard.value = tracks.join('\n');
  2434. fill_from_text_music();
  2435. } });
  2436. return true;
  2437. } else if (url.toLowerCase().includes('nativedsd.com')) {
  2438. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2439. if (response.readyState != 4 || response.status != 200) return;
  2440. dom = domParser.parseFromString(response.responseText, "text/html");
  2441. if (dom == null) return;
  2442.  
  2443. var NDSD_ID = 'ORIGINALFORMAT=DSD', genre;
  2444. ref = dom.querySelector('div.the-content > header > h2');
  2445. if (ref != null) artist = ref.firstChild.data.trim();
  2446. ref = dom.querySelector('div.the-content > header > h1');
  2447. if (ref != null) album = ref.firstChild.data.trim();
  2448. ref = dom.querySelector('div.the-content > header > h3');
  2449. if (ref != null) composer = ref.firstChild.data.trim();
  2450. ref = dom.querySelector('div.the-content > header > h1 > small');
  2451. if (ref != null) albumYear = extract_year(ref.firstChild.data);
  2452. releaseDate = albumYear; // weak
  2453. ref = dom.querySelector('div#breadcrumbs > div[class] > a:nth-of-type(2)');
  2454. if (ref != null) label = ref.firstChild.data.trim();
  2455. ref = dom.querySelector('h2#sku');
  2456. if (ref != null) {
  2457. if (/^Catalog Number: (.*)$/m.test(ref.firstChild.textContent)) catalogue = RegExp.$1;
  2458. if (/^ID: (.*)$/m.test(ref.lastChild.textContent)) NDSD_ID += ' NATIVEDSD_ID=' + RegExp.$1;
  2459. }
  2460. get_desc_from_node('div.the-content > div.entry > p', response.finalUrl, false);
  2461. ref = dom.querySelector('div#repertoire > div > p');
  2462. if (ref != null) {
  2463. let repertoire = html2php(ref, url).trim();
  2464. let ndx = repertoire.indexOf('\n[b]Track');
  2465. if (description) description += '\x1C\x1C';
  2466. description += (ndx >= 0 ? repertoire.slice(0, ndx).trim() : repertoire)
  2467. .replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  2468. }
  2469. ref = dom.querySelectorAll('div#techspecs > table > tbody > tr');
  2470. if (ref.length > 0) {
  2471. if (description) description += '\x1C\x1C';
  2472. description += '[b][u]Tech specs[/u][/b]';
  2473. ref.forEach(function(it) {
  2474. description += '\n[b]'.concat(it.children[0].textContent.trim(), '[/b] ',
  2475. it.children[1].textContent.trim()).replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  2476. });
  2477. }
  2478. ref = dom.querySelectorAll('div#track-list > table > tbody > tr[id^="track"]');
  2479. totalTracks = ref.length;
  2480. ref.forEach(function(it) {
  2481. ref = it.children[0].children[0];
  2482. if (ref != null) trackNumber = parseInt(ref.firstChild.data.trim().replace(/\..*$/, ''));
  2483. let trackComposer;
  2484. ref = it.children[1];
  2485. if (ref != null) {
  2486. title = ref.firstChild.textContent.trim();
  2487. trackComposer = ref.childNodes[2] && ref.childNodes[2].textContent.trim() || undefined;
  2488. }
  2489. ref = it.children[2];
  2490. if (ref != null) duration = timeStringToTime(ref.firstChild.data);
  2491. track = [
  2492. artist,
  2493. album,
  2494. albumYear,
  2495. releaseDate,
  2496. label,
  2497. catalogue,
  2498. undefined, // country
  2499. 'lossless', // encoding
  2500. 'FLAC', // format
  2501. undefined,
  2502. undefined, // bitrate
  2503. 24, //bd,
  2504. 88200,
  2505. 2,
  2506. 'WEB',
  2507. genre, // 'Jazz'
  2508. discNumber,
  2509. totalDiscs,
  2510. discSubtitle,
  2511. trackNumber,
  2512. totalTracks,
  2513. title,
  2514. trackArtist,
  2515. undefined,
  2516. trackComposer || composer,
  2517. undefined,
  2518. undefined,
  2519. compiler,
  2520. producer,
  2521. duration,
  2522. undefined,
  2523. undefined,
  2524. undefined,
  2525. undefined,
  2526. response.finalUrl,
  2527. undefined,
  2528. description,
  2529. NDSD_ID + ' TRACK_ID=' + it.id.replace(/^track-/i, ''),
  2530. ];
  2531. tracks.push(track.join('\x1E'));
  2532. });
  2533. clipBoard.value = tracks.join('\n');
  2534. fill_from_text_music();
  2535.  
  2536. function getArtists(elem) {
  2537. if (elem == null) return undefined;
  2538. var artists = [];
  2539. splitArtists(elem.textContent.trim()).forEach(function(it) {
  2540. artists.push(it.replace(/\s*\([^\(\)]*\)$/, ''));
  2541. });
  2542. return artists.join(', ');
  2543. }
  2544. } });
  2545. return true;
  2546. } else if (url.toLowerCase().includes('junodownload.com')) {
  2547. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2548. if (response.readyState != 4 || response.status != 200) return;
  2549. dom = domParser.parseFromString(response.responseText, "text/html");
  2550. if (dom == null) return;
  2551.  
  2552. ref = dom.querySelector('h2.product-artist > a');
  2553. if (ref != null) artist = titleCase(ref.firstChild.data.trim());
  2554. ref = dom.querySelector('meta[itemprop="name"]');
  2555. if (ref != null) album = ref.content;
  2556. ref = dom.querySelector('meta[itemprop="author"]');
  2557. if (ref != null) label = ref.content;
  2558. ref = dom.querySelector('span[itemprop="datePublished"]');
  2559. if (ref != null) releaseDate = ref.firstChild.data.trim();
  2560. var genres = [];
  2561. dom.querySelectorAll('div.mb-3 > strong').forEach(function(it) {
  2562. if (it.textContent.startsWith('Genre')) {
  2563. ref = it;
  2564. while ((ref = ref.nextElementSibling) != null && ref.nodeName == 'A') {
  2565. genres.push(ref.textContent.trim());
  2566. }
  2567. } else if (it.textContent.startsWith('Cat')) {
  2568. if ((ref = it.nextSibling) != null && ref.nodeType == 3) catalogue = ref.data;
  2569. }
  2570. });
  2571.  
  2572. ref = dom.querySelectorAll('div.product-tracklist > div[itemprop="track"]');
  2573. totalTracks = ref.length;
  2574. ref.forEach(function(it) {
  2575. trackNumber = it.querySelector('div.track-title').firstChild.data.trim();
  2576. if (/^(\d+)\./.test(trackNumber)) trackNumber = parseInt(RegExp.$1);
  2577. title = it.querySelector('span[itemprop="name"]').textContent.trim();
  2578. i = it.querySelector('meta[itemprop="duration"]');
  2579. duration = i != null && /^P(\d+)H(\d+)M(\d+)S$/i.test(i.content) ?
  2580. (parseInt(RegExp.$1) || 0) * 60**2 + (parseInt(RegExp.$2) || 0) * 60 + (parseInt(RegExp.$3) || 0) : undefined;
  2581. track = [
  2582. artist,
  2583. album,
  2584. albumYear,
  2585. releaseDate,
  2586. label,
  2587. catalogue,
  2588. undefined, // country
  2589. undefined, // encoding
  2590. undefined, // format
  2591. undefined,
  2592. undefined, // bitrate
  2593. undefined, //bd,
  2594. undefined, // SR
  2595. 2,
  2596. 'WEB',
  2597. genres.join('; '),
  2598. discNumber,
  2599. totalDiscs,
  2600. discSubtitle,
  2601. trackNumber,
  2602. totalTracks,
  2603. title,
  2604. trackArtist,
  2605. undefined,
  2606. composer,
  2607. undefined,
  2608. undefined,
  2609. compiler,
  2610. producer,
  2611. duration,
  2612. undefined,
  2613. undefined,
  2614. undefined,
  2615. undefined,
  2616. response.finalUrl,
  2617. undefined,
  2618. undefined, // description
  2619. 'BPM=' + it.children[2].textContent.trim(),
  2620. ];
  2621. tracks.push(track.join('\x1E'));
  2622. });
  2623. clipBoard.value = tracks.join('\n');
  2624. fill_from_text_music();
  2625.  
  2626. function getArtists(elem) {
  2627. if (elem == null) return undefined;
  2628. var artists = [];
  2629. splitArtists(elem.textContent.trim()).forEach(function(it) {
  2630. artists.push(it.replace(/\s*\([^\(\)]*\)$/, ''));
  2631. });
  2632. return artists.join(', ');
  2633. }
  2634. } });
  2635. return true;
  2636. } else if (url.toLowerCase().includes('hdtracks.com')) {
  2637. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  2638. if (response.readyState != 4 || response.status != 200) return;
  2639. dom = domParser.parseFromString(response.responseText, "text/html");
  2640. if (dom == null) return;
  2641.  
  2642. var genres = [];
  2643. dom.querySelectorAll('div.album-main-details > ul > li > span').forEach(function(it) {
  2644. if (it.textContent.startsWith('Title')) album = it.nextSibling.data.trim();
  2645. if (it.textContent.startsWith('Artist')) artist = it.nextElementSibling.textContent.trim();
  2646. if (it.textContent.startsWith('Genre')) {
  2647. ref = it;
  2648. while ((ref = ref.nextElementSibling) != null) genres.push(ref.textContent.trim());
  2649. }
  2650. if (it.textContent.startsWith('Label')) label = it.nextElementSibling.textContent.trim();
  2651. if (it.textContent.startsWith('Release Date')) releaseDate = normalizeDate(it.nextSibling.data.trim());
  2652. });
  2653. if (!albumYear) albumYear = extract_year(releaseDate);
  2654. ref = dom.querySelectorAll('table#track-table > tbody > tr[id^="track"]');
  2655. totalTracks = ref.length;
  2656. ref.forEach(function(it) {
  2657. trackNumber = parseInt(it.querySelector('td:first-of-type').textContent.trim());
  2658. title = it.querySelector('td.track-name').textContent.trim();
  2659. duration = timeStringToTime(it.querySelector('td:nth-of-type(3)').textContent.trim());
  2660. format = it.querySelector('td:nth-of-type(4) > span').textContent.trim();
  2661. sr = it.querySelector('td:nth-of-type(5)').textContent.trim().replace(/\/.*/, '');
  2662. if (/^([\d\.\,]+)\s*\/\s*(\d+)$/.test(sr)) {
  2663. sr = Math.round(parseFloat(RegExp.$1.replace(',', '.')) * 1000);
  2664. bd = parseInt(RegExp.$2);
  2665. } else sr = Math.round(parseFloat(sr) * 1000);
  2666. track = [
  2667. artist,
  2668. album,
  2669. albumYear,
  2670. releaseDate,
  2671. label,
  2672. catalogue,
  2673. undefined, // country
  2674. 'lossless',
  2675. undefined, // format
  2676. undefined,
  2677. undefined, // bitrate
  2678. bd || 24,
  2679. sr || undefined,
  2680. 2,
  2681. 'WEB',
  2682. genres.join('; '),
  2683. discNumber,
  2684. totalDiscs,
  2685. discSubtitle,
  2686. trackNumber,
  2687. totalTracks,
  2688. title,
  2689. trackArtist,
  2690. undefined,
  2691. composer,
  2692. undefined,
  2693. undefined,
  2694. compiler,
  2695. producer,
  2696. duration,
  2697. undefined,
  2698. undefined,
  2699. undefined,
  2700. undefined,
  2701. response.finalUrl,
  2702. undefined,
  2703. undefined, // description
  2704. undefined,
  2705. ];
  2706. tracks.push(track.join('\x1E'));
  2707. });
  2708. clipBoard.value = tracks.join('\n');
  2709. fill_from_text_music();
  2710. } });
  2711. return true;
  2712. } else if (/^https?:\/\/(?:\w+\.)?deezer\.com\/(?:\w+\/)*album\/(\d+)/i.test(url)) {
  2713. GM_xmlhttpRequest({ method: 'GET', url: 'https://api.deezer.com/album/' + RegExp.$1, onload: function(response) {
  2714. if (response.readyState != 4 || response.status != 200) throw new Error('Ready state ' + response.readyState + ', Response error ' + response.status + ' (' + response.statusText + ')');
  2715. var json = JSON.parse(response.responseText);
  2716. if (json == null) return;
  2717.  
  2718. isVA = vaParser.test(json.artist.name);
  2719. var identifiers = 'DEEZER_ID=' + json.id + ' RELEASETYPE=' + json.record_type;
  2720. json.tracks.data.forEach(function(track, ndx) {
  2721. trackArtist = track.artist.name;
  2722. if (!isVA && trackArtist && trackArtist == json.artist.name) trackArtist = undefined;
  2723. track = [
  2724. isVA ? 'Various Artists' : json.artist.name,
  2725. json.title,
  2726. undefined, //extract_year(json.release_date),
  2727. json.release_date,
  2728. json.label,
  2729. json.upc,
  2730. undefined, // country
  2731. undefined, // encoding
  2732. undefined, // format
  2733. undefined,
  2734. undefined, // bitrate
  2735. undefined, //bd,
  2736. undefined, // SR
  2737. 2,
  2738. 'WEB',
  2739. json.genres.data.map(it => it.name).join('; '),
  2740. discNumber,
  2741. totalDiscs,
  2742. discSubtitle,
  2743. ndx + 1,
  2744. json.nb_tracks,
  2745. track.title,
  2746. trackArtist,
  2747. undefined,
  2748. composer,
  2749. undefined,
  2750. undefined,
  2751. compiler,
  2752. producer,
  2753. track.duration,
  2754. undefined,
  2755. undefined,
  2756. undefined,
  2757. undefined,
  2758. 'https://www.deezer.com/album/' + json.id,
  2759. undefined,
  2760. undefined, // description
  2761. identifiers + ' TRACK_ID=' + track.id,
  2762. ];
  2763. tracks.push(track.join('\x1E'));
  2764. });
  2765. clipBoard.value = tracks.join('\n');
  2766. fill_from_text_music();
  2767. } });
  2768. return true;
  2769. } else if (/^https?:\/\/(?:\w+\.)?spotify\.com\/(?:\w+\/)*albums?\/(\w+)/i.test(url)) {
  2770. querySpotifyAPI('https://api.spotify.com/v1/albums/' + RegExp.$1).then(function(json) {
  2771. isVA = json.artists.length == 1 && vaParser.test(json.artists[0].name);
  2772. artist = json.artists.map(artist => artist.name);
  2773. totalDiscs = json.tracks.items.reduce((acc, track) => Math.max(acc, track.disc_number), 0);
  2774. var identifiers = 'RELEASETYPE=' + json.album_type + ' SPOTIFY_ID=' + json.id;
  2775. var image = json.images.reduce((acc, image) => image.width * image.height > acc.width * acc.height ? image : acc);
  2776. //if (image) identifiers += ' IMGURL=' + image.url;
  2777. json.tracks.items.forEach(function(track, ndx) {
  2778. trackArtist = track.artists.map(artist => artist.name);
  2779. if (!isVA && json.artists.length > 0 && trackArtist.equalTo(artist)) trackArtist = [];
  2780. track = [
  2781. isVA ? 'Various Artists' : joinArtists(artist),
  2782. json.name,
  2783. undefined, //extract_year(json.release_date),
  2784. json.release_date,
  2785. json.label,
  2786. json.external_ids.upc,
  2787. undefined, // country
  2788. undefined, // encoding
  2789. undefined, // format
  2790. undefined,
  2791. undefined, // bitrate
  2792. undefined, // BD
  2793. undefined, // SR
  2794. 2,
  2795. 'WEB',
  2796. json.genres.join('; '),
  2797. totalDiscs > 1 ? track.disc_number : undefined,
  2798. totalDiscs > 1 ? totalDiscs : undefined,
  2799. undefined, // discSubtitle
  2800. track.track_number,
  2801. json.total_tracks,
  2802. track.name,
  2803. joinArtists(trackArtist),
  2804. undefined,
  2805. composer,
  2806. undefined,
  2807. undefined,
  2808. compiler,
  2809. producer,
  2810. track.duration_ms / 1000,
  2811. undefined,
  2812. undefined,
  2813. undefined,
  2814. undefined,
  2815. 'https://open.spotify.com/album/' + json.id,
  2816. undefined,
  2817. undefined, // description
  2818. identifiers +
  2819. ' EXPLICIT=' + Number(track.explicit) +
  2820. ' TRACK_ID=' + track.id,
  2821. ];
  2822. tracks.push(track.join('\x1E'));
  2823. });
  2824. clipBoard.value = tracks.join('\n');
  2825. fill_from_text_music();
  2826. }).catch(e => { alert(e) });
  2827. return true;
  2828.  
  2829. function querySpotifyAPI(api_url) {
  2830. if (!api_url) return Promise.reject('No API URL');
  2831. return setToken().then(function(credentials) {
  2832. return new Promise(function(resolve, reject) {
  2833. GM_xmlhttpRequest({
  2834. method: 'GET',
  2835. url: api_url,
  2836. responseType: 'application/json',
  2837. headers: {
  2838. 'Accept': 'application/json',
  2839. 'Content-Type': 'application/json',
  2840. 'Authorization': credentials.token_type + ' ' + credentials.access_token,
  2841. },
  2842. onload: function(response) {
  2843. if (response.readyState == 4 && response.status == 200) {
  2844. resolve(JSON.parse(response.response));
  2845. } else {
  2846. reject('Response error ' + response.status + ' (' + response.statusText + ')');
  2847. }
  2848. },
  2849. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  2850. ontimeout: function() { reject('Timeout') },
  2851. });
  2852. });
  2853. });
  2854. }
  2855. function setToken() {
  2856. if (isTokenValid()) return Promise.resolve(spotifyCredentials);
  2857. if (!prefs.spotify_clientid || !prefs.spotify_clientsecret) return Promise.reject('Spotify credentials not set');
  2858. return new Promise(function(resolve, reject) {
  2859. const data = new URLSearchParams({
  2860. grant_type: 'client_credentials',
  2861. });
  2862. GM_xmlhttpRequest({
  2863. method: 'POST',
  2864. url: 'https://accounts.spotify.com/api/token',
  2865. headers: {
  2866. 'Content-Type': 'application/x-www-form-urlencoded',
  2867. 'Content-Length': data.toString().length,
  2868. 'Authorization': 'Basic ' + btoa(prefs.spotify_clientid + ':' + prefs.spotify_clientsecret),
  2869. },
  2870. data: data.toString(),
  2871. onload: function(response) {
  2872. if (response.readyState == 4 && response.status == 200) {
  2873. spotifyCredentials = JSON.parse(response.response);
  2874. spotifyCredentials.expires = new Date().getTime() + spotifyCredentials.expires_in;
  2875. if (isTokenValid()) { resolve(spotifyCredentials) } else { reject('Invalid token') }
  2876. } else {
  2877. reject('Response error ' + response.status + ' (' + JSON.parse(response.response).error + ')');
  2878. }
  2879. },
  2880. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  2881. ontimeout: function() { reject('Timeout') },
  2882. });
  2883. });
  2884. }
  2885. function isTokenValid() {
  2886. return spotifyCredentials.token_type && spotifyCredentials.token_type.toLowerCase() == 'bearer'
  2887. && spotifyCredentials.access_token && spotifyCredentials.expires >= new Date().getTime() + 30;
  2888. }
  2889. }
  2890. if (!weak) {
  2891. addMessage('This domain not supported', 'ua-critical');
  2892. clipBoard.value = '';
  2893. }
  2894. return false;
  2895.  
  2896. function get_desc_from_node(selector, url, quote = false) {
  2897. description = [];
  2898. dom.querySelectorAll(selector).forEach(k => { description.push(html2php(k, url).trim()) });
  2899. description = description.join('\n\n').trim().replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  2900. if (quote && description.length > 0) description = '[quote]' + description + '[/quote]';
  2901. }
  2902. } // init_from_url_music
  2903.  
  2904. function trackComparer(a, b) {
  2905. var cmp = a.discnumber - b.discnumber;
  2906. if (!isNaN(cmp) && cmp != 0) return cmp;
  2907. cmp = parseInt(a.tracknumber) - parseInt(b.tracknumber);
  2908. if (!isNaN(cmp)) return cmp;
  2909. var m1 = vinyltrackParser.exec(a.tracknumber.toUpperCase());
  2910. var m2 = vinyltrackParser.exec(b.tracknumber.toUpperCase());
  2911. return m1 != null && m2 != null ?
  2912. m1[1].localeCompare(m2[1]) || parseFloat(m1[2]) - parseFloat(m2[2]) :
  2913. a.tracknumber.toUpperCase().localeCompare(b.tracknumber.toUpperCase());
  2914. }
  2915.  
  2916. function normalizeDate(str) {
  2917. if (typeof str != 'string') return null;
  2918. if (/\b(d{4}-\d+-\d+|\d{1,2}\/\d{1,2}\/\d{2})\b/.test(str)) return RegExp.$1;
  2919. if (/\b(\d{1,2})\/(\d{1,2})\/(\d{4})\b/.test(str)) return RegExp.$2 + '/' + RegExp.$1 + '/' + RegExp.$3;
  2920. if (/\b(\d{1,2})\.\s?(\d{1,2})\.\s?(\d{2}|\d{4})\b/.test(str)) return RegExp.$2 + '/' + RegExp.$1 + '/' + RegExp.$3;
  2921. return extract_year(str);
  2922. }
  2923.  
  2924. function getCoverOnline(url) {
  2925. GM_xmlhttpRequest({
  2926. method: 'GET',
  2927. url: url,
  2928. onload: function(response) {
  2929. if (response.readyState != 4 || response.status != 200) return;
  2930. var ref, dom = domParser.parseFromString(response.responseText, "text/html");
  2931. if (dom == null) return;
  2932. function testDomain(url, selector) {
  2933. return typeof url == 'string' && response.finalUrl.toLowerCase().includes(url.toLowerCase()) ?
  2934. dom.querySelector(selector) : null;
  2935. }
  2936. if ((ref = testDomain('qobuz.com', 'div.album-cover > img')) != null) {
  2937. setImage(ref.src);
  2938. } else if ((ref = testDomain('highresaudio.com', 'div.albumbody > img.cover[data-pin-media]')) != null) {
  2939. setImage(ref.dataset.pinMedia);
  2940. } else if ((ref = testDomain('bandcamp.com', 'div#tralbumArt > a.popupImage')) != null) {
  2941. setImage(ref.href);
  2942. } else if ((ref = testDomain('7digital.com', 'span.release-packshot-image > img[itemprop="image"]')) != null) {
  2943. setImage(ref.src);
  2944. } else if ((ref = testDomain('hdtracks.com', 'p.product-image > img')) != null) {
  2945. setImage(ref.src);
  2946. } else if ((ref = testDomain('discogs.com', 'div#view_images > p:first-of-type > span > img')) != null) {
  2947. setImage(ref.src);
  2948. } else if ((ref = testDomain('junodownload.com', 'a.productimage')) != null) {
  2949. setImage(ref.href);
  2950. } else if ((ref = testDomain('supraphonline.cz', 'meta[itemprop="image"]')) != null) {
  2951. setImage(ref.content.replace(/\?.*$/, ''));
  2952. } else if ((ref = testDomain('prestomusic.com', 'div.c-product-block__aside > a')) != null) {
  2953. setImage(ref.href.replace(/\?\d+$/, ''));
  2954. } else if ((ref = testDomain('bontonland.cz', 'a.detailzoom')) != null) {
  2955. setImage(ref.href);
  2956. } else if ((ref = testDomain('nativedsd.com', 'a#album-cover')) != null) {
  2957. setImage(ref.href);
  2958. } else if ((ref = testDomain('deezer.com', 'meta[property="og:image"]')) != null) {
  2959. setImage(ref.content);
  2960. } else if ((ref = testDomain('spotify.com', 'meta[property="og:image"]')) != null) {
  2961. setImage(ref.content);
  2962. }
  2963. },
  2964. //onerror: response => { throw new Error('Response error ' + response.status + ' (' + response.statusText + ')') },
  2965. //ontimeout: function() { throw new Error('Timeout') },
  2966. });
  2967. }
  2968.  
  2969. function reqSelectFormats(...vals) {
  2970. vals.forEach(function(val) {
  2971. [
  2972. ['MP3', 0],
  2973. ['FLAC', 1],
  2974. ['AAC', 2],
  2975. ['AC3', 3],
  2976. ['DTS', 4],
  2977. ].forEach(function(fmt) {
  2978. if (val.toLowerCase() == fmt[0].toLowerCase()
  2979. && (ref = document.getElementById('format_' + fmt[1])) != null) {
  2980. ref.checked = true;
  2981. ref.onchange();
  2982. }
  2983. });
  2984. });
  2985. }
  2986.  
  2987. function reqSelectBitrates(...vals) {
  2988. vals.forEach(function(val) {
  2989. var ndx = 10;
  2990. [
  2991. [192, 0],
  2992. ['APS (VBR)', 1],
  2993. ['V2 (VBR)', 2],
  2994. ['V1 (VBR)', 3],
  2995. [256, 4],
  2996. ['APX (VBR)', 5],
  2997. ['V0 (VBR)', 6],
  2998. [320, 7],
  2999. ['Lossless', 8],
  3000. ['24bit Lossless', 9],
  3001. ['Other', 10],
  3002. ].forEach(function(it) {
  3003. if ((typeof val == 'string' ? val.toLowerCase() : val)
  3004. == (typeof it[0] == 'string' ? it[0].toLowerCase() : it[0])) ndx = it[1]
  3005. });
  3006. if ((ref = document.getElementById('bitrate_' + ndx)) != null) {
  3007. ref.checked = true;
  3008. ref.onchange();
  3009. }
  3010. });
  3011. }
  3012.  
  3013. function reqSelectMedias(...vals) {
  3014. vals.forEach(function(val) {
  3015. [
  3016. ['CD', 0],
  3017. ['DVD', 1],
  3018. ['Vinyl', 2],
  3019. ['Soundboard', 3],
  3020. ['SACD', 4],
  3021. ['DAT', 5],
  3022. ['Cassette', 6],
  3023. ['WEB', 7],
  3024. ['Blu-Ray', 8],
  3025. ].forEach(function(med) {
  3026. if (val == med[0] && (ref = document.getElementById('media_' + med[1])) != null) {
  3027. ref.checked = true;
  3028. ref.onchange();
  3029. }
  3030. });
  3031. if (val == 'CD') {
  3032. if ((ref = document.getElementById('needlog')) != null) {
  3033. ref.checked = true;
  3034. ref.onchange();
  3035. if ((ref = document.getElementById('minlogscore')) != null) ref.value = 100;
  3036. }
  3037. if ((ref = document.getElementById('needcue')) != null) ref.checked = true;
  3038. //if ((ref = document.getElementById('needchecksum')) != null) ref.checked = true;
  3039. }
  3040. });
  3041. }
  3042.  
  3043. function getReleaseIndex(str) {
  3044. var ndx;
  3045. [
  3046. ['Album', 1],
  3047. ['Soundtrack', 3],
  3048. ['EP', 5],
  3049. ['Anthology', 6],
  3050. ['Compilation', 7],
  3051. ['Single', 9],
  3052. ['Live album', 11],
  3053. ['Remix', 13],
  3054. ['Bootleg', 14],
  3055. ['Interview', 15],
  3056. ['Mixtape', 16],
  3057. ['Demo', 17],
  3058. ['Concert Recording', 18],
  3059. ['DJ Mix', 19],
  3060. ['Unknown', 21],
  3061. ].forEach(k => { if (str.toLowerCase() == k[0].toLowerCase()) ndx = k[1] });
  3062. return ndx || 21;
  3063. }
  3064.  
  3065. function joinArtists(arr, decorator = artist => artist) {
  3066. if (!(arr instanceof Array)) return null;
  3067. if (arr.some(artist => artist.includes('&'))) return arr.map(decorator).join(', ');
  3068. if (arr.length < 3) return arr.map(decorator).join(' & ');
  3069. return arr.slice(0, -1).map(decorator).join(', ') + ' & ' + decorator(arr.slice(-1).pop());
  3070. }
  3071. } // fill_from_text_music
  3072.  
  3073. function fill_from_text_apps(weak = false) {
  3074. if (messages != null) messages.parentNode.removeChild(messages);
  3075. if (!urlParser.test(clipBoard.value)) {
  3076. addMessage('Only URL accepted for this category', 'ua-critical');
  3077. return false;
  3078. }
  3079. url = RegExp.$1;
  3080. var description, tags = new TagManager();
  3081. if (url.toLowerCase().includes('//sanet')) {
  3082. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  3083. if (response.readyState != 4 || response.status != 200) throw new Error('GM_xmlhttpRequest readyState=' + response.status + ', status=' + response.status);
  3084. dom = domParser.parseFromString(response.responseText, "text/html");
  3085.  
  3086. i = dom.querySelector('h1.item_title > span');
  3087. if (elementWritable(ref = document.getElementById('title'))) {
  3088. ref.value = i != null ? i.textContent.
  3089. replace(/\(x64\)$/i, '(64-bit)').
  3090. replace(/\b(?:Build)\s+(\d+)/, 'build $1').
  3091. replace(/\b(?:Multilingual|Multilanguage)\b/, 'multilingual') : null;
  3092. }
  3093. description = html2php(dom.querySelector('section.descr'), response.finalUrl);
  3094. if (/\s*^(?:\[i\]\[\/i\])?Homepage$.*/m.test(description)) description = RegExp.leftContext;
  3095. description = description.trim().split(/\n/).slice(5).map(k => k.trimRight()).join('\n').trim();
  3096. ref = dom.querySelector('section.descr > div.release-info');
  3097. var releaseInfo = ref != null && ref.textContent.trim();
  3098. if (/\b(?:Languages?)\s*:\s*(.*?)\s*(?:$|\|)/i.exec(releaseInfo) != null) {
  3099. description += '\n\n[b]Languages:[/b]\n' + RegExp.$1;
  3100. }
  3101. ref = dom.querySelector('div.txtleft > a');
  3102. if (ref != null) description += '\n\n[b]Product page:[/b]\n[url]' + deAnonymize(ref.href) + '[/url]';
  3103. writeDescription(description);
  3104. if ((ref = dom.querySelector('section.descr > div.center > a.mfp-image')) != null) {
  3105. setImage(ref.href);
  3106. } else {
  3107. ref = dom.querySelector('section.descr > div.center > img[data-src]');
  3108. if (ref != null) setImage(ref.dataset.src);
  3109. }
  3110. var cat = dom.querySelector('a.cat:last-of-type > span');
  3111. if (cat != null) {
  3112. if (cat.textContent.toLowerCase() == 'windows') {
  3113. tags.add('apps.windows');
  3114. if (/\b(?:x64)\b/i.test(releaseInfo)) tags.add('win64');
  3115. if (/\b(?:x86)\b/i.test(releaseInfo)) tags.add('win32');
  3116. }
  3117. if (cat.textContent.toLowerCase() == 'macos') tags.add('apps.mac');
  3118. if (cat.textContent.toLowerCase() == 'linux' || cat.textContent.toLowerCase() == 'unix') tags.add('apps.linux');
  3119. if (cat.textContent.toLowerCase() == 'android') tags.add('apps.android');
  3120. if (cat.textContent.toLowerCase() == 'ios') tags.add('apps.ios');
  3121. }
  3122. if (tags.length > 0 && elementWritable(ref = document.getElementById('tags'))) {
  3123. ref.value = tags.toString();
  3124. }
  3125. }, });
  3126. return true;
  3127. }
  3128. if (!weak) {
  3129. addMessage('This domain not supported', 'ua-critical');
  3130. clipBoard.value = '';
  3131. }
  3132. return false;
  3133. }
  3134.  
  3135. function fill_from_text_books(weak = false) {
  3136. if (messages != null) messages.parentNode.removeChild(messages);
  3137. if (!urlParser.test(clipBoard.value)) {
  3138. addMessage('Only URL accepted for this category', 'ua-critical');
  3139. return false;
  3140. }
  3141. url = RegExp.$1;
  3142. var description, tags = new TagManager();
  3143. if (url.toLowerCase().includes('martinus.cz') || url.toLowerCase().includes('martinus.sk')) {
  3144. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  3145. if (response.readyState != 4 || response.status != 200) throw new Error('GM_xmlhttpRequest readyState=' + response.status + ', status=' + response.status);
  3146. dom = domParser.parseFromString(response.responseText, "text/html");
  3147.  
  3148. function get_detail(x, y) {
  3149. var ref = dom.querySelector('section#details > div > div > div:first-of-type > div:nth-child(' +
  3150. x + ') > dl:nth-child(' + y + ') > dd');
  3151. return ref != null ? ref.textContent.trim() : null;
  3152. }
  3153.  
  3154. i = dom.querySelectorAll('article > ul > li > a');
  3155. if (i.length > 0 && elementWritable(ref = document.getElementById('title') || document.querySelector('input[name="title"]'))) {
  3156. description = joinAuthors(i);
  3157. if ((i = dom.querySelector('article > h1')) != null) description += ' – ' + i.textContent.trim();
  3158. i = dom.querySelector('div.bar.mb-medium > div:nth-child(1) > dl > dd > span');
  3159. if (i != null && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  3160. ref.value = description;
  3161. }
  3162.  
  3163. description = '[quote]' + html2php(dom.querySelector('section#description > div')).
  3164. replace(/^\s*\[img\].*?\[\/img\]\s*/i, '') + '[/quote]';
  3165. const translation_map = [
  3166. [/\b(?:originál)/i, 'Original title'],
  3167. [/\b(?:datum|dátum|rok)\b/i, 'Release date'],
  3168. [/\b(?:katalog|katalóg)/i, 'Catalogue #'],
  3169. [/\b(?:stran|strán)\b/i, 'Page count'],
  3170. [/\bjazyk/i, 'Language'],
  3171. [/\b(?:nakladatel|vydavatel)/i, 'Publisher'],
  3172. [/\b(?:doporuč|ODPORÚČ)/i, 'Age rating'],
  3173. ];
  3174. dom.querySelectorAll('section#details > div > div > div:first-of-type > div > dl').forEach(function(detail) {
  3175. var lbl = detail.children[0].textContent.trim();
  3176. var val = detail.children[1].textContent.trim();
  3177. if (/\b(?:rozm)/i.test(lbl) || /\b(?:vazba|vázba)\b/i.test(lbl)) return;
  3178. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  3179. if (/\b(?:ISBN)\b/i.test(lbl)) {
  3180. url = new URL('https://www.worldcat.org/isbn/' + detail.children[1].textContent.trim());
  3181. val = '[url=' + url.href + ']' + detail.children[1].textContent.trim() + '[/url]';
  3182. findOCLC(url);
  3183. // } else if (/\b(?:ISBN)\b/i.test(lbl)) {
  3184. // val = '[url=https://www.goodreads.com/search/search?q=' + detail.children[1].textContent.trim() +
  3185. // '&search_type=books]' + detail.children[1].textContent.trim() + '[/url]';
  3186. }
  3187. description += '\n[b]' + lbl + ':[/b] ' + val;
  3188. });
  3189. url = new URL(response.finalUrl);
  3190. description += '\n\n[b]More info:[/b]\n[url]' + url.href + '[/url]';
  3191. writeDescription(description);
  3192.  
  3193. if ((i = dom.querySelector('a.mj-product-preview > img')) != null) {
  3194. setImage(i.src.replace(/\?.*/, ''));
  3195. } else if ((i = dom.querySelector('head > meta[property="og:image"]')) != null) {
  3196. setImage(i.content.replace(/\?.*/, ''));
  3197. }
  3198.  
  3199. dom.querySelectorAll('dd > ul > li > a').forEach(x => { tags.add(x.textContent) });
  3200. if (tags.length > 0 && elementWritable(ref = document.getElementById('tags'))) {
  3201. ref.value = tags.toString();
  3202. }
  3203. }, });
  3204. return true;
  3205. } else if (url.toLowerCase().includes('goodreads.com')) {
  3206. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  3207. if (response.readyState != 4 || response.status != 200) throw new Error('GM_xmlhttpRequest readyState=' + response.status + ', status=' + response.status);
  3208. dom = domParser.parseFromString(response.responseText, "text/html");
  3209.  
  3210. i = dom.querySelectorAll('a.authorName > span');
  3211. if (i.length > 0 && elementWritable(ref = document.getElementById('title') || document.querySelector('input[name="title"]'))) {
  3212. description = joinAuthors(i);
  3213. if ((i = dom.querySelector('h1#bookTitle')) != null) description += ' – ' + i.textContent.trim();
  3214. if ((i = dom.querySelector('div#details > div.row:nth-of-type(2)')) != null
  3215. && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  3216. ref.value = description;
  3217. }
  3218.  
  3219. var description = [];
  3220. dom.querySelectorAll('div#description span:last-of-type').forEach(function(it) {
  3221. description = html2php(it, response.finalUrl);
  3222. });
  3223. description = '[quote]' + description.trim() + '[/quote]';
  3224.  
  3225. function strip(str) {
  3226. return typeof str == 'string' ?
  3227. str.replace(/\s{2,}/g, ' ').replace(/[\n\r]+/, '').replace(/\s*\.{3}(?:less|more)\b/g, '').trim() : null;
  3228. }
  3229.  
  3230. dom.querySelectorAll('div#details > div.row').forEach(k => { description += '\n' + strip(k.innerText) });
  3231. description += '\n';
  3232.  
  3233. dom.querySelectorAll('div#bookDataBox > div.clearFloats').forEach(function(detail) {
  3234. var lbl = detail.children[0].textContent.trim();
  3235. var val = strip(detail.children[1].textContent);
  3236. if (/\b(?:ISBN)\b/i.test(lbl) && (/\b(\d{13})\b/.test(val) || /\b(\d{10})\b/.test(val))) {
  3237. url = new URL('https://www.worldcat.org/isbn/' + RegExp.$1);
  3238. val = '[url=' + url.href + ']' + strip(detail.children[1].textContent) + '[/url]';
  3239. findOCLC(url);
  3240. }
  3241. description += '\n[b]' + lbl + ':[/b] ' + val;
  3242. });
  3243. if ((ref = dom.querySelector('span[itemprop="ratingValue"]')) != null) {
  3244. description += '\n[b]Rating:[/b] ' + Math.round(parseFloat(ref.firstChild.textContent) * 20) + '%';
  3245. }
  3246. url = new URL(response.finalUrl);
  3247. // if ((ref = dom.querySelector('div#buyButtonContainer > ul > li > a.buttonBar')) != null) {
  3248. // let u = new URL(ref.href);
  3249. // description += '\n[url=' + url.origin + u.pathname + '?' + u.search + ']Libraries[/url]';
  3250. // }
  3251. description += '\n\n[b]More info and reviews:[/b]\n[url]' + url.origin + url.pathname + '[/url]';
  3252. dom.querySelectorAll('div.clearFloats.bigBox').forEach(function(bigBox) {
  3253. if (bigBox.id == 'aboutAuthor' && (ref = bigBox.querySelector('h2 > a')) != null) {
  3254. description += '\n\n[b][url=' + ref.href + ']' + ref.textContent.trim() + '[/url][/b]';
  3255. if ((ref = bigBox.querySelector('div.bigBoxBody a > div[style*="background-image"]')) != null) {
  3256. }
  3257. if ((ref = bigBox.querySelector('div.bookAuthorProfile__about > span[id]:last-of-type')) != null) {
  3258. description += '\n' + html2php(ref, response.finalUrl).replace(/^\[i\]Librarian\s+Note:.*?\[\/i\]\s+/i, '');
  3259. }
  3260. } else if ((ref = bigBox.querySelector('h2 > a[href^="/trivia/"]')) != null) {
  3261. description += '\n\n[b][url=' + ref.href + ']' + ref.textContent.trim() + '[/url][/b]';
  3262. if ((ref = bigBox.querySelector('div.bigBoxContent > div.mediumText')) != null) {
  3263. description += '\n' + ref.firstChild.textContent.trim();
  3264. }
  3265. // } else if ((ref = bigBox.querySelector('h2 > a[href^="/work/quotes/"]')) != null) {
  3266. // description += '\n\n[b][url=' + ref.href + ']' + ref.textContent.trim() + '[/url][/b]';
  3267. // bigBox.querySelectorAll('div.bigBoxContent > div.stacked > span.readable').forEach(function(quote) {
  3268. // description += '\n' + ref.firstChild.textContent.trim();
  3269. // });
  3270. }
  3271. });
  3272. writeDescription(description);
  3273. if ((ref = dom.querySelector('div.editionCover > img')) != null) setImage(ref.src.replace(/\?.*/, ''));
  3274. dom.querySelectorAll('div.elementList > div.left').forEach(tag => { tags.add(tag.textContent.trim()) });
  3275. if (tags.length > 0 && elementWritable(ref = document.getElementById('tags'))) ref.value = tags.toString();
  3276. }, });
  3277. return true;
  3278. } else if (url.toLowerCase().includes('databazeknih.cz')) {
  3279. if (!url.toLowerCase().includes('show=alldesc')) {
  3280. if (!url.includes('?')) { url += '?show=alldesc' } else { url += '&show=alldesc' }
  3281. }
  3282. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  3283. if (response.readyState != 4 || response.status != 200) throw new Error('GM_xmlhttpRequest readyState=' + response.status + ', status=' + response.status);
  3284. dom = domParser.parseFromString(response.responseText, "text/html");
  3285.  
  3286. i = dom.querySelectorAll('span[itemprop="author"] > a');
  3287. if (i != null && elementWritable(ref = document.getElementById('title') || document.querySelector('input[name="title"]'))) {
  3288. description = joinAuthors(i);
  3289. if ((i = dom.querySelector('h1[itemprop="name"]')) != null) description += ' – ' + i.textContent.trim();
  3290. i = dom.querySelector('span[itemprop="datePublished"]');
  3291. if (i != null && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  3292. ref.value = description;
  3293. }
  3294.  
  3295. description = '[quote]' + html2php(dom.querySelector('p[itemprop="description"]'), response.finalUrl) + '[/quote]';
  3296. const translation_map = [
  3297. [/\b(?:orig)/i, 'Original title'],
  3298. [/\b(?:série)\b/i, 'Series'],
  3299. [/\b(?:vydáno)\b/i, 'Released'],
  3300. [/\b(?:stran)\b/i, 'Page count'],
  3301. [/\b(?:jazyk)\b/i, 'Language'],
  3302. [/\b(?:překlad)/i, 'Translation'],
  3303. [/\b(?:autor obálky)\b/i, 'Cover author'],
  3304. ];
  3305. dom.querySelectorAll('table.bdetail tr').forEach(function(detail) {
  3306. var lbl = detail.children[0].textContent.trim();
  3307. var val = detail.children[1].textContent.trim();
  3308. if (/(?:žánr|\bvazba)\b/i.test(lbl)) return;
  3309. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  3310. if (/\b(?:ISBN)\b/i.test(lbl) && /\b(\d+(?:-\d+)*)\b/.exec(val) != null) {
  3311. url = new URL('https://www.worldcat.org/isbn/' + RegExp.$1.replace(/-/g, ''));
  3312. val = '[url=' + url.href + ']' + detail.children[1].textContent.trim() + '[/url]';
  3313. findOCLC(url);
  3314. }
  3315. description += '\n[b]' + lbl + '[/b] ' + val;
  3316. });
  3317.  
  3318. url = new URL(response.finalUrl);
  3319. description += '\n\n[b]More info:[/b]\n[url]' + url.origin + url.pathname + '[/url]';
  3320. writeDescription(description);
  3321.  
  3322. if ((ref = dom.querySelector('div#icover_mid > a')) != null) setImage(ref.href.replace(/\?.*/, ''));
  3323. if ((ref = dom.querySelector('div#lbImage')) != null && /\burl\("(.*)"\)/i.test(i.style.backgroundImage)) {
  3324. setImage(RegExp.$1.replace(/\?.*/, ''));
  3325. }
  3326.  
  3327. dom.querySelectorAll('h5[itemprop="genre"] > a').forEach(tag => { tags.add(tag.textContent.trim()) });
  3328. dom.querySelectorAll('a.tag').forEach(tag => { tags.add(tag.textContent.trim()) });
  3329. if (tags.length > 0 && elementWritable(ref = document.getElementById('tags'))) ref.value = tags.toString();
  3330. }, });
  3331. return true;
  3332. }
  3333. if (!weak) {
  3334. addMessage('This domain not supported', 'ua-critical');
  3335. clipBoard.value = '';
  3336. }
  3337. return false;
  3338.  
  3339. function joinAuthors(nodeList) {
  3340. if (typeof nodeList != 'object') return null;
  3341. return Array.from(nodeList).map(it => it.textContent.trim()).join(' & ');
  3342. }
  3343.  
  3344. function findOCLC(url) {
  3345. if (!url) return false;
  3346. var oclc = document.querySelector('input[name="oclc"]');
  3347. if (!elementWritable(oclc)) return false;
  3348. GM_xmlhttpRequest({
  3349. method: 'GET',
  3350. url: url,
  3351. onload: function(response) {
  3352. if (response.readyState != 4 || response.status != 200) return;
  3353. var dom = domParser.parseFromString(response.responseText, "text/html");
  3354. if (dom == null) return;
  3355. var ref = dom.querySelector('tr#details-oclcno > td:last-of-type');
  3356. if (ref != null) oclc.value = ref.textContent.trim();
  3357. },
  3358. });
  3359. return true;
  3360. }
  3361. }
  3362.  
  3363. function preview(n) {
  3364. if (!prefs.auto_preview) return;
  3365. var btn = document.querySelector('input.button_preview_' + n + '[type="button"][value="Preview"]');
  3366. if (btn != null) btn.click();
  3367. }
  3368.  
  3369. function html2php(node, url) {
  3370. var php = '';
  3371. if (node instanceof HTMLElement) node.childNodes.forEach(function(ch) {
  3372. if (ch.nodeType == 3) {
  3373. php += ch.data.replace(/\s+/g, ' ');
  3374. } else if (ch.nodeName == 'P') {
  3375. php += '\n' + html2php(ch, url);
  3376. } else if (ch.nodeName == 'DIV') {
  3377. php += '\n\n' + html2php(ch, url) + '\n\n';
  3378. } else if (ch.nodeName == 'LABEL') {
  3379. php += '\n\n[b]' + html2php(ch, url) + '[/b]';
  3380. } else if (ch.nodeName == 'SPAN') {
  3381. php += html2php(ch, url);
  3382. } else if (ch.nodeName == 'BR' || ch.nodeName == 'HR') {
  3383. php += '\n';
  3384. } else if (ch.nodeName == 'B' || ch.nodeName == 'STRONG') {
  3385. php += '[b]' + html2php(ch, url) + '[/b]';
  3386. } else if (ch.nodeName == 'I' || ch.nodeName == 'EM') {
  3387. php += '[i]' + html2php(ch, url) + '[/i]';
  3388. } else if (ch.nodeName == 'U') {
  3389. php += '[u]' + html2php(ch, url) + '[/u]';
  3390. } else if (ch.nodeName == 'CODE') {
  3391. php += '[pre]' + ch.textContent + '[/pre]';
  3392. } else if (ch.nodeName == 'A') {
  3393. php += ch.childNodes.length > 0 ?
  3394. '[url=' + deAnonymize(ch.href) + ']' + html2php(ch, url) + '[/url]' :
  3395. '[url]' + deAnonymize(ch.href) + '[/url]';
  3396. } else if (ch.nodeName == 'IMG') {
  3397. php += '[img]' + (ch.dataset.src || ch.src) + '[/img]';
  3398. }
  3399. });
  3400. return php;
  3401. }
  3402.  
  3403. function deAnonymize(uri) {
  3404. return typeof uri == 'string' ? uri.replace(/^https?:\/\/(?:www\.)?anonymz\.com\/\?/i, '') : null;
  3405. }
  3406.  
  3407. function writeDescription(desc) {
  3408. if (typeof desc != 'string') return;
  3409. if (elementWritable(ref = document.querySelector('textarea#desc')
  3410. || document.querySelector('textarea#description'))) ref.value = desc;
  3411. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  3412. if (ref.textLength > 0) ref.value += '\n\n';
  3413. ref.value += desc;
  3414. }
  3415. }
  3416.  
  3417. function setImage(url) {
  3418. var image = document.getElementById('image') || document.querySelector('input[name="image"]');
  3419. if (!elementWritable(image)) return false;
  3420. image.value = url;
  3421.  
  3422. if (prefs.auto_preview_cover && image.id) {
  3423. if ((child = document.getElementById('cover preview')) == null) {
  3424. elem = document.createElement('div');
  3425. elem.style.paddingTop = '10px';
  3426. child = document.createElement('img');
  3427. child.id = 'cover preview';
  3428. child.style.width = '90%';
  3429. elem.append(child);
  3430. image.parentNode.previousElementSibling.append(elem);
  3431. }
  3432. child.src = url;
  3433. }
  3434. if (prefs.auto_rehost_cover) {
  3435. if (rehostItBtn != null) {
  3436. rehostItBtn.click();
  3437. } else {
  3438. rehost2PTPIMG([url]).then(urls => { if (urls.length > 0) image.value = urls[0] }).catch(e => { alert(e) });
  3439. }
  3440. }
  3441. }
  3442.  
  3443. function elementWritable(elem) { return elem != null && !elem.disabled && (overwrite || !elem.value) }
  3444. }
  3445.  
  3446. function addArtistField() { exec(function() { AddArtistField() }) }
  3447. function removeArtistField() { exec(function() { RemoveArtistField() }) }
  3448.  
  3449. function array_homogenous(arr) { return arr.every(k => k === arr[0]) }
  3450.  
  3451. function titleCase(str) {
  3452. return str.toLowerCase().split(' ').map(x => x[0].toUpperCase() + x.slice(1)).join(' ');
  3453. }
  3454.  
  3455. function exec(fn) {
  3456. let script = document.createElement('script');
  3457. script.type = 'application/javascript';
  3458. script.textContent = '(' + fn + ')();';
  3459. document.body.appendChild(script); // run the script
  3460. document.body.removeChild(script); // clean up
  3461. }
  3462.  
  3463. function makeTimeString(duration) {
  3464. let t = Math.abs(Math.round(duration));
  3465. let H = Math.floor(t / 60 ** 2);
  3466. let M = Math.floor(t / 60 % 60);
  3467. let S = t % 60;
  3468. return (duration < 0 ? '-' : '') + (H > 0 ? H + ':' + M.toString().padStart(2, '0') : M.toString()) +
  3469. ':' + S.toString().padStart(2, '0');
  3470. }
  3471.  
  3472. function timeStringToTime(str) {
  3473. if (!/(-\s*)?\b(\d+(?::\d{2})*(?:\.\d+)?)\b/.test(str)) return null;
  3474. var t = 0, a = RegExp.$2.split(':');
  3475. while (a.length > 0) t = t * 60 + parseFloat(a.shift());
  3476. return RegExp.$1 ? -t : t;
  3477. }
  3478.  
  3479. function extract_year(expr) {
  3480. if (typeof expr == 'number') return Math.round(expr);
  3481. if (typeof expr != 'string') return null;
  3482. if (/\b(\d{4})\b/.test(expr)) return parseInt(RegExp.$1);
  3483. var d = new Date(expr);
  3484. return parseInt(isNaN(d) ? expr : d.getFullYear());
  3485. }
  3486.  
  3487. function reInParenthesis(expr) { return new RegExp('\\s+\\([^\\(\\)]*'.concat(expr, '[^\\(\\)]*\\)$'), 'i') }
  3488. function reInBrackets(expr) { return new RegExp('\\s+\\[[^\\[\\]]*'.concat(expr, '[^\\[\\]]*\\]$'), 'i') }
  3489.  
  3490. function addMessage(text, cls, html = false) {
  3491. messages = document.getElementById('UA messages');
  3492. if (messages == null) {
  3493. var ua = document.getElementById('upload assistant');
  3494. if (ua == null) return null;
  3495. messages = document.createElement('TR');
  3496. if (messages == null) return null;
  3497. messages.id = 'UA messages';
  3498. ua.children[0].append(messages);
  3499.  
  3500. elem = document.createElement('TD');
  3501. if (elem == null) return null;
  3502. elem.colSpan = 2;
  3503. elem.className = 'ua-messages-bg';
  3504. messages.append(elem);
  3505. } else {
  3506. elem = messages.children[0]; // tbody
  3507. if (elem == null) return null;
  3508. }
  3509. var div = document.createElement('DIV');
  3510. div.classList.add('ua-messages', cls);
  3511. div[html ? 'innerHTML' : 'textContent'] = text;
  3512. return elem.appendChild(div);
  3513. }
  3514.  
  3515. function imageDropHandler(evt) {
  3516. evt.preventDefault();
  3517. if (evt.dataTransfer.files.length <= 0) return;
  3518. var image = document.getElementById('image') || document.querySelector('input[name="image"]');
  3519. if (image == null) return;
  3520. if (evt.currentTarget.busy) throw new Error('Wait till current upload finishes');
  3521. evt.currentTarget.busy = true;
  3522. if (evt.currentTarget.hTimer) {
  3523. clearTimeout(evt.currentTarget.hTimer);
  3524. delete evt.currentTarget.hTimer;
  3525. }
  3526. var origlabel = evt.currentTarget.value;
  3527. evt.currentTarget.value = 'Uploading...';
  3528. evt.currentTarget.style.backgroundColor = '#A00000';
  3529. var evtSrc = evt.currentTarget;
  3530. upload2PTPIMG(evt.dataTransfer.files[0]).then(function(result) {
  3531. if (result.length > 0) {
  3532. image.value = result[0];
  3533. evtSrc.style.backgroundColor = '#00A000';
  3534. evtSrc.hTimer = setTimeout(function() {
  3535. evtSrc.style.backgroundColor = null;
  3536. delete evtSrc.hTimer;
  3537. }, 3000);
  3538. } else evtSrc.style.backgroundColor = null;
  3539. }).catch(function(e) {
  3540. alert(e);
  3541. evtSrc.style.backgroundColor = null;
  3542. }).then(function() {
  3543. evtSrc.busy = false;
  3544. evtSrc.value = origlabel;
  3545. });
  3546. }
  3547.  
  3548. function voidDragHandler(evt) { evt.preventDefault() }
  3549.  
  3550. function upload2PTPIMG(file, elem) {
  3551. if (!(file instanceof File)) return Promise.reject('Bad parameter (file)');
  3552. var config = JSON.parse(window.localStorage.ptpimg_it);
  3553. if (!prefs.ptpimg_api_key && !config.api_key) return Promise.reject('API key not set');
  3554. return new Promise(function(resolve, reject) {
  3555. var reader = new FileReader();
  3556. var fr = new Promise(function(resolve, reject) {
  3557. reader.onload = function() { resolve(reader.result) }
  3558. reader.readAsBinaryString(file); //readAsArrayBuffer(file);
  3559. });
  3560. fr.then(function(result) {
  3561. const boundary = '----NN-GGn-PTPIMG';
  3562. var data = '--' + boundary + '\r\n';
  3563. data += 'Content-Disposition: form-data; name="file-upload[0]"; filename="' + file.name.toASCII() + '"\r\n';
  3564. data += 'Content-Type: ' + file.type + '\r\n\r\n';
  3565. data += result + '\r\n';
  3566. data += '--' + boundary + '\r\n';
  3567. data += 'Content-Disposition: form-data; name="api_key"\r\n\r\n';
  3568. data += (prefs.ptpimg_api_key || config.api_key) + '\r\n';
  3569. data += '--' + boundary + '--\r\n';
  3570. GM_xmlhttpRequest({
  3571. method: 'POST',
  3572. url: 'https://ptpimg.me/upload.php',
  3573. responseType: 'json',
  3574. headers: {
  3575. 'Content-Type': 'multipart/form-data; boundary=' + boundary,
  3576. 'Content-Length': data.length,
  3577. },
  3578. data: data,
  3579. binary: true,
  3580. onload: function(response) {
  3581. if (response.status != 200) reject('Response error ' + response.status + ' (' + response.statusText + ')');
  3582. resolve(response.response.map(item => 'https://ptpimg.me/' + item.code + '.' + item.ext));
  3583. },
  3584. onprogress: elem instanceof HTMLInputElement ?
  3585. arg => { elem.value = 'Uploading... (' + arg.position + '%)' } : undefined,
  3586. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  3587. ontimeout: function() { reject('Timeout') },
  3588. });
  3589. });
  3590. });
  3591. }
  3592.  
  3593. function rehost2PTPIMG(urls) {
  3594. if (!Array.isArray(urls)) return Promise.reject('Bad parameter (urls)');
  3595. var config = JSON.parse(window.localStorage.ptpimg_it);
  3596. if (!prefs.ptpimg_api_key && !config.api_key) return Promise.reject('API key not set');
  3597. return new Promise(function(resolve, reject) {
  3598. const boundary = 'NN-GGn-PTPIMG';
  3599. const dcTest = /^https?:\/\/(?:\w+\.)?discogs\.com\//i;
  3600. var data = '--' + boundary + "\n";
  3601. data += 'Content-Disposition: form-data; name="link-upload"\n\n';
  3602. data += urls.map(url => dcTest.test(url) ? 'https://reho.st/' + url : url).join('\n') + '\n';
  3603. data += '--' + boundary + '\n';
  3604. data += 'Content-Disposition: form-data; name="api_key"\n\n';
  3605. data += (prefs.ptpimg_api_key || config.api_key) + '\n';
  3606. data += '--' + boundary + '--';
  3607. GM_xmlhttpRequest({
  3608. method: 'POST',
  3609. url: 'https://ptpimg.me/upload.php',
  3610. responseType: 'json',
  3611. headers: {
  3612. 'Content-type': 'multipart/form-data; boundary=' + boundary,
  3613. 'Content-Length': data.length,
  3614. },
  3615. data: data,
  3616. onload: function(response) {
  3617. if (response.status != 200) reject('Response error ' + response.status + ' (' + response.statusText + ')');
  3618. resolve(response.response.map(item => 'https://ptpimg.me/' + item.code + '.' + item.ext));
  3619. },
  3620. onerror: response => { reject('Response error ' + response.status + ' (' + response.statusText + ')') },
  3621. ontimeout: function() { reject('Timeout') },
  3622. });
  3623. });
  3624. }