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

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