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

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