Greasy Fork 还支持 简体中文。

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-15 提交的版本,檢視 最新版本

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