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

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