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

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