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

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