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

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