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

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