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