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

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