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

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