RED (+ NWCD, Orpheus) Upload Assistant

Accurate filling the upload and group edit forms based on foobar2000's playlist selection via pasted output of copy command, release consistency check, two tracklist layouts, basic colours customization, featured artists extraction, image URl fetching from store and more. As alternative to copied playlist, URL to product in supported webstore can be used -- see below for the list.

当前为 2019-09-15 提交的版本,查看 最新版本

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