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

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