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