RED (+ NWCD, Orpheus) Upload Assistant

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

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

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