RED (+ NWCD, Orpheus) Upload Assistant

Accurate filling the upload and group edit forms based on foobar2000's playlist selection via pasted output of copy command, release consistency check, two tracklist layouts, basic colours customization, featured artists extraction, image URl fetching from store and more. As alternative to copied playlist, URL to product in supported webstore can be used -- see below for the list.

当前为 2019-09-23 提交的版本,查看 最新版本

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