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

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