Greasy Fork 还支持 简体中文。

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

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