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.117
  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. 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. 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. if (Object.keys(srs).length == 1 && Object.keys(srs)[0] == 88200) {
  969. drinfo += '[/hide]';
  970. } else {
  971. drinfo = null;
  972. }
  973. }
  974. } else { // 16bit or lossy
  975. if (Object.keys(srs).some(f => f != 44100)) lineage = kHz;
  976. if (channels.length == 1 && channels[0] != 2) add_channel_info();
  977. //add_dr_info();
  978. //if (lineage.length > 0) add_rg_info();
  979. if (['AAC', 'Opus', 'Vorbis'].includes(codecs[0]) && vendors[0]) {
  980. let _encoder_settings = vendors[0];
  981. if (codecs[0] == 'AAC' && /^qaac\s+[\d\.]+/i.test(vendors[0])) {
  982. let enc = [];
  983. if (matches = vendors[0].match(/\bqaac\s+([\d\.]+)\b/i)) enc[0] = matches[1];
  984. if (matches = vendors[0].match(/\bCoreAudioToolbox\s+([\d\.]+)\b/i)) enc[1] = matches[1];
  985. if (matches = vendors[0].match(/\b(AAC-\S+)\s+Encoder\b/i)) enc[2] = matches[1];
  986. if (matches = vendors[0].match(/\b([TC]VBR|ABR|CBR)\s+(\S+)\b/)) { enc[3] = matches[1]; enc[4] = matches[2]; }
  987. if (matches = vendors[0].match(/\bQuality\s+(\d+)\b/i)) enc[5] = matches[1];
  988. _encoder_settings = 'Converted by Apple\'s ' + enc[2] + ' encoder (' + enc[3] + '-' + enc[4] + ')';
  989. }
  990. if (lineage) lineage += '\n\n';
  991. lineage += _encoder_settings;
  992. }
  993. }
  994. }
  995. function add_dr_info() {
  996. if (drs.length != 1 || document.getElementById('release_dynamicrange') != null) return false;
  997. if (lineage.length > 0) lineage += ' | ';
  998. if (drs[0] < 4) lineage += '[color=red]';
  999. lineage += 'DR' + drs[0];
  1000. if (drs[0] < 4) lineage += '[/color]';
  1001. return true;
  1002. }
  1003. function add_rg_info() {
  1004. if (rgs.length != 1) return false;
  1005. if (lineage.length > 0) lineage += ' | ';
  1006. lineage += 'RG'; //lineage += 'RG ' + rgs[0];
  1007. return true;
  1008. }
  1009. function add_channel_info() {
  1010. if (channels.length != 1) return false;
  1011. let chi = getChanString(channels[0]);
  1012. if (lineage.length > 0 && chi.length > 0) lineage += ', ';
  1013. lineage += chi;
  1014. return chi.length > 0;
  1015. }
  1016. if (url) srcinfo = '[url]' + url + '[/url]';
  1017. if ((ref = document.getElementById('release_lineage')) != null) {
  1018. if (element_writable(ref)) {
  1019. if (drinfo) comment = drinfo;
  1020. if (lineage && srcinfo) lineage += '\n\n';
  1021. if (srcinfo) lineage += srcinfo;
  1022. ref.value = lineage;
  1023. preview(1);
  1024. }
  1025. } else {
  1026. comment = lineage;
  1027. if (comment && drinfo) comment += '\n\n';
  1028. if (drinfo) comment += drinfo;
  1029. if (comment && srcinfo) comment += '\n\n';
  1030. if (srcinfo) comment += srcinfo;
  1031. }
  1032. if (element_writable(ref = document.getElementById('release_desc'))) {
  1033. ref.value = comment;
  1034. if (comment.length > 0) preview(isNWCD() ? 2 : 1);
  1035. }
  1036. if (encodings[0] == 'lossless' && codecs[0] == 'FLAC' && bds.includes(24) && dirpaths.length == 1) {
  1037. var uri = new URL(dirpaths[0] + '\\foo_dr.txt');
  1038. GM_xmlhttpRequest({
  1039. method: 'GET',
  1040. url: uri.href,
  1041. responseType: 'blob',
  1042. onload: function(response) {
  1043. if (response.readyState != 4 || !response.responseText) return;
  1044. var rlsDesc = document.getElementById('release_lineage') || document.getElementById('release_desc');
  1045. if (rlsDesc == null) return;
  1046. var value = rlsDesc.value;
  1047. matches = value.match(/(^\[hide=DR\d*\]\[pre\])\[\/pre\]/im);
  1048. if (matches == null) return;
  1049. var index = matches.index + matches[1].length;
  1050. rlsDesc.value = value.slice(0, index).concat(response.responseText, value.slice(index));
  1051. }
  1052. });
  1053. }
  1054. } else { // isRequest
  1055. description = []
  1056. if (release_dates.length == 1) {
  1057. i = new Date(release_dates[0]);
  1058. description.push('Releasing ' + (isNaN(i) ? release_dates[0] : i.toString().replace(/\s+\d+:.*/, '')));
  1059. }
  1060. if (url) description.push('[url]' + url + '[/url]');
  1061. if (catalogs.length == 1 && /^\d{10,}$/.test(catalogs[0])) {
  1062. description.push('[url=https://www.google.com/search?q=' + catalogs[0] + ']Find more stores...[/url]');
  1063. }
  1064. if (comments.length == 1) description.push(comments[0]);
  1065. description = description.join('\n\n');
  1066. if (description.length > 0 && element_writable(ref = document.getElementById('description'))) ref.value = description;
  1067. }
  1068. if (element_writable(document.getElementById('image') || document.querySelector('input[name="image"]'))) {
  1069. let u = url;
  1070. if (/^https?:\/\/(\w+\.)?discogs\.com\/release\/[\w\-]+\/?$/i.test(u)) u += '/images';
  1071. GM_xmlhttpRequest({ method: 'GET', url: u, onload: fetch_image_from_store });
  1072. }
  1073. // } else if (element_writable(document.getElementById('image') || document.querySelector('input[name="image"]'))
  1074. // && ((ref = document.getElementById('album_desc')) != null || (ref = document.getElementById('body')) != null)
  1075. // && ref.textLength > 0 && (matches = ref.value.matchAll(/\b(https?\/\/[\w\-\&\_\?\=]+)/i)) != null) {
  1076.  
  1077. if (element_writable(ref = document.getElementById('release_dynamicrange'))) {
  1078. ref.value = drs.length == 1 ? drs[0] : null;
  1079. }
  1080. if (isRequest && prefs.request_default_bounty > 0) {
  1081. let amount = prefs.request_default_bounty < 1024 ? prefs.request_default_bounty : prefs.request_default_bounty / 1024;
  1082. if ((ref = document.getElementById('amount_box')) != null && !ref.disabled) ref.value = amount;
  1083. if ((ref = document.getElementById('unit')) != null && !ref.disabled) {
  1084. ref.value = prefs.request_default_bounty < 1024 ? 'mb' : 'gb';
  1085. }
  1086. exec(function() { Calculate() });
  1087. }
  1088. if (prefs.clean_on_apply) clipBoard.value = null;
  1089. prefs.save();
  1090. return true;
  1091.  
  1092. function gen_full_tracklist() { // ========================= TACKLIST =========================
  1093. description = isRED() ? '[pad=5|0|0|0]' : '';
  1094. description += '[size=4][color=' + prefs.tracklist_head_color + '][b]Tracklisting[/b][/color][/size]';
  1095. if (isRED()) '[/pad]';
  1096. let classical_units = new Set();
  1097. if (isClassical && !tracks.some(k => k.discsubtitle)) {
  1098. for (track of tracks) {
  1099. if (matches = track.title.match(/^(.+?)\s*:\s+(.*)$/)) {
  1100. classical_units.add(track.classical_unit_title = matches[1]);
  1101. track.classical_title = matches[2];
  1102. } else {
  1103. track.classical_unit_title = null;
  1104. }
  1105. }
  1106. for (let unit of classical_units.keys()) {
  1107. let group_performer = array_homogenous(tracks.filter(k => k.classical_unit_title === unit).map(k => k.track_artist));
  1108. let group_composer = array_homogenous(tracks.filter(k => k.classical_unit_title === unit).map(k => k.composer));
  1109. for (track of tracks) {
  1110. if (track.classical_unit_title !== unit) continue;
  1111. if (group_composer) track.classical_unit_composer = track.composer;
  1112. if (group_performer) track.classical_unit_performer = track.track_artist;
  1113. }
  1114. }
  1115. }
  1116. let block = 1, lastdisc, lastsubtitle, lastside, vinyl_trackwidth;
  1117. let lastwork = classical_units.size > 0 ? null : undefined;
  1118. description += '\n';
  1119. let volumes = new Map(tracks.map(k => [k.discnumber, undefined]));
  1120. volumes.forEach(function(val, key) {
  1121. volumes.set(key, array_homogenous(tracks.filter(k => k.discnumber == key).map(k => k.discsubtitle)));
  1122. });
  1123. if (media == 'Vinyl') {
  1124. let max_side_track = undefined;
  1125. rx = /^([A-Z])(\d+)?(\.(\d+))?/i;
  1126. for (iter of tracks) {
  1127. if (matches = iter.tracknumber.match(rx)) {
  1128. max_side_track = Math.max(parseInt(matches[2]) || 1, max_side_track || 0);
  1129. }
  1130. }
  1131. if (typeof max_side_track == 'number') {
  1132. max_side_track = max_side_track.toString().length;
  1133. vinyl_trackwidth = 1 + max_side_track;
  1134. for (iter of tracks) {
  1135. if (matches = iter.tracknumber.match(rx)) {
  1136. iter.tracknumber = matches[1].toUpperCase();
  1137. if (matches[2]) iter.tracknumber += matches[2].padStart(max_side_track, '0');
  1138. }
  1139. }
  1140. }
  1141. }
  1142. function prologue(prefix, postfix) {
  1143. function block1() {
  1144. if (block == 3) description += postfix;
  1145. description += '\n';
  1146. block = 1;
  1147. }
  1148. function block2() {
  1149. if (block == 3) description += postfix;
  1150. description += '\n';
  1151. block = 2;
  1152. }
  1153. function block3() {
  1154. if (block == 2) { description += '[hr]' } else { description += '\n' }
  1155. if (block != 3) description += prefix;
  1156. block = 3;
  1157. }
  1158. if (totaldiscs > 1 && iter.discnumber != lastdisc) {
  1159. block1();
  1160. description += '[size=3][color=' + prefs.tracklist_discsubtitle_color + '][b]Disc ' + iter.discnumber;
  1161. if (iter.discsubtitle && (!volumes.has(iter.discnumber) || volumes.get(iter.discnumber))) {
  1162. description += ' - ' + iter.discsubtitle;
  1163. lastsubtitle = iter.discsubtitle;
  1164. }
  1165. description += '[/b][/color][/size]';
  1166. lastdisc = iter.discnumber;
  1167. }
  1168. if (iter.discsubtitle != lastsubtitle) {
  1169. block1();
  1170. if (iter.discsubtitle) {
  1171. description += '[size=2][color=' + prefs.tracklist_discsubtitle_color + '][b]' +
  1172. iter.discsubtitle + '[/b][/color][/size]';
  1173. }
  1174. lastsubtitle = iter.discsubtitle;
  1175. }
  1176. if (iter.classical_unit_title !== lastwork) {
  1177. if (iter.classical_unit_composer || iter.classical_unit_title || iter.classical_unit_performer) {
  1178. block2();
  1179. description += '[size=2][color=' + prefs.tracklist_classicalblock_color + '][b]';
  1180. if (iter.classical_unit_composer) description += iter.classical_unit_composer + ': ';
  1181. if (iter.classical_unit_title) description += iter.classical_unit_title;
  1182. description += '[/b]';
  1183. if (iter.classical_unit_performer) description += ' (' + iter.classical_unit_performer + ')';
  1184. description += '[/color][/size]';
  1185. } else {
  1186. if (block != 2) block1();
  1187. }
  1188. lastwork = iter.classical_unit_title;
  1189. }
  1190. block3();
  1191. if (media == 'Vinyl') {
  1192. let c = iter.tracknumber[0].toUpperCase();
  1193. if (lastside != undefined && c != lastside) description += '\n';
  1194. lastside = c;
  1195. }
  1196. }
  1197. var varying_composer = !array_homogenous(tracks.map(k => k.composer));
  1198. for (iter of tracks.sort(function(a, b) {
  1199. var d = a.discnumber - b.discnumber;
  1200. var t = a.tracknumber - b.tracknumber;
  1201. return isNaN(d) || d == 0 ? isNaN(t) ? a.tracknumber.localeCompare(b.tracknumber) : t : d;
  1202. })) {
  1203. let title = '';
  1204. let ttwidth = vinyl_trackwidth || Math.max((iter.totaltracks || tracks.length).toString().length, 2);
  1205. if (prefs.tracklist_style == 1) {
  1206. // STYLE 1 ----------------------------------------
  1207. prologue('[size=2]', '[/size]\n');
  1208. track = '[b][color=' + prefs.tracklist_tracknumber_color + ']';
  1209. track += isNaN(parseInt(iter.tracknumber)) ? iter.tracknumber : iter.tracknumber.padStart(ttwidth, '0');
  1210. track += '[/color][/b]' + prefs.title_separator;
  1211. if (iter.track_artist && !iter.classical_unit_performer) {
  1212. title = '[color=' + prefs.tracklist_artist_color + ']' + iter.track_artist + '[/color] - ';
  1213. }
  1214. title += iter.classical_title || iter.title;
  1215. if (iter.composer && composer_emphasis && varying_composer && !iter.classical_unit_composer) {
  1216. title = title.concat(' [color=', prefs.tracklist_composer_color, '](', iter.composer, ')[/color]');
  1217. }
  1218. description += track + title;
  1219. if (iter.duration) description += ' [i][color=' + prefs.tracklist_duration_color +'][' +
  1220. makeTimeString(iter.duration) + '][/color][/i]';
  1221. } else if (prefs.tracklist_style == 2) {
  1222. // STYLE 2 ----------------------------------------
  1223. prologue('[size=2][pre]', '[/pre][/size]');
  1224. track = isNaN(parseInt(iter.tracknumber)) ? iter.tracknumber : iter.tracknumber.padStart(ttwidth, '0');
  1225. track += prefs.title_separator;
  1226. if (iter.track_artist && !iter.classical_unit_performer) title = iter.track_artist + ' - ';
  1227. title += iter.classical_title || iter.title;
  1228. if (iter.composer && composer_emphasis && varying_composer && !iter.classical_unit_composer) {
  1229. title = title.concat(' (', iter.composer, ')');
  1230. }
  1231. dur = iter.duration ? '[' + makeTimeString(iter.duration) + ']' : null;
  1232. let l = 0, j, left, padding, spc;
  1233. let width = prefs.max_tracklist_width - track.length;
  1234. if (dur) width -= dur.length + 1;
  1235. while (title.length > 0) {
  1236. j = width;
  1237. if (title.length > width) {
  1238. while (j > 0 && title[j] != ' ') { --j }
  1239. if (j <= 0) j = width;
  1240. }
  1241. left = title.slice(0, j).trim();
  1242. if (++l <= 1) {
  1243. description += track + left;
  1244. if (dur) {
  1245. spc = width - left.length;
  1246. padding = (spc < 2 ? ' '.repeat(spc) : ' ' + prefs.pad_leader.repeat(spc - 1)) + ' ';
  1247. description += padding + dur;
  1248. }
  1249. width = prefs.max_tracklist_width - track.length - 2;
  1250. } else {
  1251. description += '\n' + ' '.repeat(track.length) + left;
  1252. }
  1253. title = title.slice(j).trim();
  1254. }
  1255. }
  1256. }
  1257. if (prefs.tracklist_style == 1 && total_time > 0) {
  1258. description += '\n\n' + divs[0].repeat(10) + '\n[color=' + prefs.tracklist_duration_color +
  1259. ']Total time: [i]' + makeTimeString(total_time) + '[/i][/color][/size]';
  1260. } else if (prefs.tracklist_style == 2) {
  1261. if (total_time > 0) {
  1262. dur = '[' + makeTimeString(total_time) + ']';
  1263. description = description.concat('\n\n', divs[0].repeat(32).padStart(prefs.max_tracklist_width));
  1264. description = description.concat('\n', 'Total time:'.padEnd(prefs.max_tracklist_width - dur.length), dur);
  1265. }
  1266. description = description.concat('[/pre][/size]');
  1267. }
  1268. }
  1269.  
  1270. function getChanString(n) {
  1271. if (!n) return null;
  1272. const chanmap = [
  1273. 'mono',
  1274. 'stereo',
  1275. '2.1',
  1276. '4.0 surround sound',
  1277. '5.0 surround sound',
  1278. '5.1 surround sound',
  1279. '7.0 surround sound',
  1280. '7.1 surround sound',
  1281. ];
  1282. return n >= 1 && n <= 8 ? chanmap[n - 1] : n + 'chn surround sound';
  1283. }
  1284.  
  1285. function init_from_url_music(url) {
  1286. if (typeof url != 'string') return false;
  1287. var artist, album, albumYear, remasterYear, channels, label, composer, bd, sr = 44.1,
  1288. description, compiler, producer, totaltracks, totaldiscs, discsubtitle, discnumber,
  1289. tracknumber, title, track_artist, duration, catalogue, encoding, format, bitrate;
  1290. if (url.toLowerCase().indexOf('qobuz.com') >= 0) {
  1291. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1292. if (response.readyState != 4 || response.status != 200) return;
  1293. dom = domparser.parseFromString(response.responseText, "text/html");
  1294. if (dom == null) return;
  1295.  
  1296. if ((ref = dom.querySelector('h2.album-meta__artist')) != null) artist = ref.textContent.trim();
  1297. if ((ref = dom.querySelector('h1.album-meta__title')) != null) album = ref.textContent.trim();
  1298. ref = dom.querySelector('div.album-meta > ul > li:first-of-type');
  1299. if (ref != null) remasterYear = normalizeDate(ref.textContent);
  1300. ref = dom.querySelector('p.album-about__copyright');
  1301. albumYear = ref != null && extract_year(ref.textContent) || extract_year(remasterYear);
  1302. let genres = [];
  1303. dom.querySelectorAll('section#about > ul > li').forEach(function(k) {
  1304. if (/\b(\d+)\s*(?:dis[ck]|disco|disque)(?:s?\b|\(s\))/i.test(k.textContent)) {
  1305. totaldiscs = parseInt(RegExp.$1);
  1306. }
  1307. if (/\b(\d+)\s*(?:track|pist[ae]|tracce)(?:s?\b|\(s\))/i.test(k.textContent)) {
  1308. totaltracks = parseInt(RegExp.$1);
  1309. }
  1310. if (k.textContent.includes('Label')) label = k.children[0].textContent.trim()
  1311. else if (k.textContent.includes('Composer')) {
  1312. composer = k.children[0].textContent.trim();
  1313. if (/\bVarious\b/i.test(composer)) composer = null;
  1314. } else if (k.textContent.includes('Genre') && k.children.length > 0) {
  1315. k.querySelectorAll('a').forEach(k => { genres.push(k.textContent.trim()) });
  1316. if (genres.length > 0 && ['Pop/Rock'].includes(genres[0])) genres.shift();
  1317. if (genres.length > 0 && ['Metal', 'Heavy Metal'].some(genre => genres.includes(genre))) {
  1318. while (genres.length > 1) genres.shift();
  1319. }
  1320. }
  1321. });
  1322. bd = 16; channels = 2;
  1323. dom.querySelectorAll('span.album-quality__info').forEach(function(k) {
  1324. if (/\b([\d\.\,]+)\s*kHz\b/i.test(k.textContent) != null) sr = parseFloat(RegExp.$1.replace(/,/g, '.'));
  1325. if (/\b(\d+)[\-\s]*Bits?\b/i.test(k.textContent) != null) bd = parseInt(RegExp.$1);
  1326. if (/\b(?:Stereo)\b/i.test(k.textContent)) channels = 2;
  1327. if (/\b(\d)\.(\d)\b/.test(k.textContent)) channels = parseInt(RegExp.$1) + parseInt(RegExp.$2);
  1328. });
  1329. get_desc_from_node('section#description > p', response.finalUrl, true);
  1330. if ((ref = dom.querySelector('a[title="Qobuzissime"]')) != null) {
  1331. description += '\x1C[align=center][url=https://www.qobuz.com' + ref.pathname +
  1332. '][img]https://ptpimg.me/4z35uj.png[/img][/url][/align]';
  1333. }
  1334. ref = dom.querySelectorAll('div.player__tracks > div.track > div.track__items');
  1335. let works = dom.querySelectorAll('div.player__tracks > p.player__work');
  1336. if (!totaltracks) totaltracks = ref.length;
  1337. ref.forEach(function(k) {
  1338. discsubtitle = null;
  1339. works.forEach(function(j) {
  1340. if (j.compareDocumentPosition(k) == Node.DOCUMENT_POSITION_FOLLOWING) discsubtitle = j
  1341. });
  1342. discsubtitle = discsubtitle != null ? discsubtitle.textContent.trim() : undefined;
  1343. if (/^\s*(?:dis[ck]|disco|disque)\s+(\d+)\s*$/i.test(discsubtitle)) {
  1344. discnumber = parseInt(RegExp.$1);
  1345. discsubtitle = undefined;
  1346. } else discnumber = undefined;
  1347. if (discnumber > totaldiscs) totaldiscs = discnumber;
  1348. tracknumber = parseInt(k.querySelector('span[itemprop="position"]').textContent.trim());
  1349. title = k.querySelector('span.track__item--name').textContent.trim().replace(/\s+/g, ' ');
  1350. duration = timestrToTime(k.querySelector('span.track__item--duration').textContent);
  1351. track_artist = undefined;
  1352. track = [
  1353. artist,
  1354. album,
  1355. albumYear,
  1356. remasterYear,
  1357. label,
  1358. undefined,
  1359. 'lossless',
  1360. 'FLAC',
  1361. undefined,
  1362. undefined,
  1363. bd,
  1364. sr * 1000,
  1365. channels,
  1366. 'WEB',
  1367. genres.join(', '),
  1368. discnumber,
  1369. totaldiscs,
  1370. discsubtitle,
  1371. tracknumber,
  1372. totaltracks,
  1373. title,
  1374. track_artist,
  1375. undefined,
  1376. composer,
  1377. undefined,
  1378. undefined,
  1379. compiler,
  1380. producer,
  1381. duration,
  1382. undefined,
  1383. undefined,
  1384. undefined,
  1385. undefined,
  1386. response.finalUrl,
  1387. undefined,
  1388. description,
  1389. undefined,
  1390. ];
  1391. tracks.push(track.join('\x1E'));
  1392. });
  1393. clipBoard.value = tracks.join('\n');
  1394. fill_from_text_music();
  1395. } });
  1396. } else if (url.toLowerCase().indexOf('highresaudio.com') >= 0) {
  1397. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1398. if (response.readyState != 4 || response.status != 200) return;
  1399. dom = domparser.parseFromString(response.responseText, "text/html");
  1400. if (dom == null) return;
  1401.  
  1402. ref = dom.querySelector('h1 > span.artist');
  1403. if (ref != null) artist = ref.textContent.trim();
  1404. ref = dom.getElementById('h1-album-title');
  1405. if (ref != null) album = ref.firstChild.textContent.trim();
  1406. let genres = [], format;
  1407. dom.querySelectorAll('div.album-col-info-data > div > p').forEach(function(k) {
  1408. if (/\b(?:Genre|Subgenre)\b/i.test(k.firstChild.textContent)) genres.push(k.lastChild.textContent.trim());
  1409. if (/\b(?:Label)\b/i.test(k.firstChild.textContent)) label = k.lastChild.textContent.trim();
  1410. if (/\b(?:Album[\s\-]Release)\b/i.test(k.firstChild.textContent)) {
  1411. albumYear = normalizeDate(k.lastChild.textContent);
  1412. }
  1413. if (/\b(?:HRA[\s\-]Release)\b/i.test(k.firstChild.textContent)) {
  1414. remasterYear = normalizeDate(k.lastChild.textContent);
  1415. }
  1416. });
  1417. i = 0;
  1418. dom.querySelectorAll('tbody > tr > td.col-format').forEach(function(k) {
  1419. if (/^(FLAC)\s*([\d\.\,]+)\b/.exec(k.textContent) != null) {
  1420. format = RegExp.$1;
  1421. sr = parseFloat(RegExp.$2.replace(/,/g, '.'));
  1422. ++i;
  1423. }
  1424. });
  1425. if (i > 1) sr = undefined; // ambiguous
  1426. get_desc_from_node('div#albumtab-info > p', response.finalUrl);
  1427. ref = dom.querySelectorAll('ul.playlist > li.pltrack');
  1428. totaltracks = ref.length;
  1429. ref.forEach(function(k) {
  1430. discsubtitle = k;
  1431. while ((discsubtitle = discsubtitle.previousElementSibling) != null) {
  1432. if (discsubtitle.nodeName == 'LI' && discsubtitle.className == 'plinfo') {
  1433. discsubtitle = discsubtitle.textContent.replace(/\s*:$/, '').trim();
  1434. if (/\b(?:DIS[CK]|Volume|CD)\s*(\d+)\b/i.exec(discsubtitle)) discnumber = parseInt(RegExp.$1);
  1435. break;
  1436. }
  1437. }
  1438. //if (discnumber > totaldiscs) totaldiscs = discnumber;
  1439. tracknumber = parseInt(k.querySelector('span.track').textContent.trim());
  1440. title = k.querySelector('span.title').textContent.trim().replace(/\s+/g, ' ');
  1441. duration = timestrToTime(k.querySelector('span.time').textContent);
  1442. track_artist = undefined;
  1443. track = [
  1444. artist,
  1445. album,
  1446. albumYear,
  1447. remasterYear,
  1448. label,
  1449. undefined,
  1450. 'lossless',
  1451. 'FLAC', //format,
  1452. undefined,
  1453. undefined,
  1454. 24,
  1455. sr * 1000,
  1456. 2,
  1457. 'WEB',
  1458. genres.join(', '),
  1459. discnumber,
  1460. totaldiscs,
  1461. discsubtitle,
  1462. tracknumber,
  1463. totaltracks,
  1464. title,
  1465. track_artist,
  1466. undefined,
  1467. composer,
  1468. undefined,
  1469. undefined,
  1470. compiler,
  1471. producer,
  1472. duration,
  1473. undefined,
  1474. undefined,
  1475. undefined,
  1476. undefined,
  1477. response.finalUrl,
  1478. undefined,
  1479. description,
  1480. undefined,
  1481. ];
  1482. tracks.push(track.join('\x1E'));
  1483. });
  1484. clipBoard.value = tracks.join('\n');
  1485. fill_from_text_music();
  1486. } });
  1487. } else if (url.toLowerCase().indexOf('bandcamp.com') >= 0) {
  1488. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1489. if (response.readyState != 4 || response.status != 200) return;
  1490. dom = domparser.parseFromString(response.responseText, "text/html");
  1491. if (dom == null) return;
  1492.  
  1493. ref = dom.querySelector('span[itemprop="byArtist"] > a');
  1494. if (ref != null) artist = ref.textContent.trim();
  1495. ref = dom.querySelector('h2[itemprop="name"]');
  1496. if (ref != null) album = ref.textContent.trim();
  1497. ref = dom.querySelector('div.tralbum-credits');
  1498. if (ref != null && /\breleased\s+(.*?\b\d{4})\b/i.test(ref.textContent)) {
  1499. remasterYear = RegExp.$1;
  1500. albumYear = remasterYear;
  1501. }
  1502. ref = dom.querySelector('p#band-name-location > span.title');
  1503. if (ref != null) label = ref.textContent.trim();
  1504. let tags = new TagManager;
  1505. dom.querySelectorAll('div.tralbum-tags > a.tag').forEach(k => { tags.add(k.textContent.trim()) });
  1506. description = [];
  1507. dom.querySelectorAll('div.tralbumData').forEach(function(k) {
  1508. if (!k.classList.contains('tralbum-tags')) description.push(html2php(k, response.finalUrl))
  1509. });
  1510. description = description.join('\n\n').replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  1511. ref = dom.querySelectorAll('table.track_list > tbody > tr[itemprop="tracks"]');
  1512. totaltracks = ref.length;
  1513. ref.forEach(function(k) {
  1514. tracknumber = parseInt(k.querySelector('div.track_number').textContent);
  1515. title = k.querySelector('span.track-title').textContent.trim().replace(/\s+/g, ' ');
  1516. duration = timestrToTime(k.querySelector('span.time').textContent);
  1517. track_artist = undefined;
  1518. track = [
  1519. artist,
  1520. album,
  1521. albumYear,
  1522. remasterYear,
  1523. label,
  1524. undefined,
  1525. undefined, //'lossless',
  1526. undefined, //'FLAC',
  1527. undefined,
  1528. undefined,
  1529. undefined,
  1530. undefined,
  1531. 2,
  1532. 'WEB',
  1533. tags.toString(),
  1534. discnumber,
  1535. totaldiscs,
  1536. undefined,
  1537. tracknumber,
  1538. totaltracks,
  1539. title,
  1540. track_artist,
  1541. undefined,
  1542. composer,
  1543. undefined,
  1544. undefined,
  1545. compiler,
  1546. producer,
  1547. duration,
  1548. undefined,
  1549. undefined,
  1550. undefined,
  1551. undefined,
  1552. response.finalUrl,
  1553. undefined,
  1554. description,
  1555. undefined,
  1556. ];
  1557. tracks.push(track.join('\x1E'));
  1558. });
  1559. clipBoard.value = tracks.join('\n');
  1560. fill_from_text_music();
  1561. } });
  1562. } else if (url.toLowerCase().indexOf('prestomusic.com') >= 0) {
  1563. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1564. if (response.readyState != 4 || response.status != 200) return;
  1565. dom = domparser.parseFromString(response.responseText, "text/html");
  1566. if (dom == null) return;
  1567.  
  1568. artist = getArtists(dom.querySelectorAll('div.c-product-block__contributors > p'));
  1569. ref = dom.querySelector('h1.c-product-block__title');
  1570. if (ref != null) album = ref.lastChild.textContent.trim();
  1571. dom.querySelectorAll('div.c-product-block__metadata > ul > li').forEach(function(k) {
  1572. if (k.firstChild.textContent.indexOf('Release Date') >= 0) {
  1573. remasterYear = extract_year(k.lastChild.textContent);
  1574. } else if (k.firstChild.textContent.indexOf('Label') >= 0) {
  1575. label = k.lastChild.textContent.trim();
  1576. } else if (k.firstChild.textContent.indexOf('Catalogue No') >= 0) {
  1577. catalogue = k.lastChild.textContent.trim();
  1578. }
  1579. });
  1580. albumYear = remasterYear;
  1581. let genre;
  1582. if (/\/jazz\//i.test(response.finalUrl)) genre = 'Jazz';
  1583. if (/\/classical\//i.test(response.finalUrl)) genre = 'Classical';
  1584. get_desc_from_node('div#about > div > p', response.finalUrl, true);
  1585. ref = dom.querySelectorAll('div#related > div > ul > li');
  1586. composer = [];
  1587. ref.forEach(function(k) {
  1588. if (k.parentNode.previousElementSibling.textContent.indexOf('Composers') >= 0) {
  1589. composer.push(k.firstChild.textContent.trim().replace(/^(.*?)\s*,\s+(.*)$/, '$2 $1'));
  1590. }
  1591. });
  1592. composer = composer.join(', ') || undefined;
  1593. ref = dom.querySelectorAll('div.has--sample');
  1594. totaltracks = ref.length;
  1595. let tracknumber = 0;
  1596. ref.forEach(function(k) {
  1597. tracknumber = ++tracknumber;
  1598. title = k.querySelector('p.c-track__title').textContent.trim().replace(/\s+/g, ' ');
  1599. duration = timestrToTime(k.querySelector('div.c-track__duration').textContent);
  1600. if (k.classList.contains('c-track')) {
  1601. track_artist = getArtists(k.parentNode.parentNode.querySelectorAll(':scope > div.c-track__details > ul > li'));
  1602. discsubtitle = k.parentNode.parentNode.querySelector(':scope > div > div > div > p.c-track__title');
  1603. discsubtitle = discsubtitle != null ? discsubtitle.textContent.trim() : undefined;
  1604. } else {
  1605. track_artist = getArtists(k.querySelectorAll(':scope > div.c-track__details > ul > li'));
  1606. discsubtitle = undefined;
  1607. }
  1608. if (track_artist == artist) track_artist = undefined;
  1609. track = [
  1610. artist,
  1611. album,
  1612. albumYear,
  1613. remasterYear,
  1614. label,
  1615. catalogue,
  1616. undefined, //encoding,
  1617. undefined, //format,
  1618. undefined,
  1619. undefined, //bitrate,
  1620. undefined, //bd,
  1621. undefined, //sr * 1000,
  1622. 2,
  1623. 'WEB',
  1624. genre,
  1625. discnumber,
  1626. totaldiscs,
  1627. discsubtitle,
  1628. tracknumber,
  1629. totaltracks,
  1630. title,
  1631. track_artist,
  1632. undefined,
  1633. composer,
  1634. undefined,
  1635. undefined,
  1636. compiler,
  1637. producer,
  1638. duration,
  1639. undefined,
  1640. undefined,
  1641. undefined,
  1642. undefined,
  1643. response.finalUrl,
  1644. undefined,
  1645. description,
  1646. undefined,
  1647. ];
  1648. tracks.push(track.join('\x1E'));
  1649. });
  1650. clipBoard.value = tracks.join('\n');
  1651. fill_from_text_music();
  1652.  
  1653. function getArtists(elems) {
  1654. if (elems == null) return undefined;
  1655. var artists = [];
  1656. elems.forEach(k => { artists.push(k.textContent.trim()) });
  1657. return artists.join(artists.length > 3 ? ', ' : ' & ');
  1658. }
  1659. } });
  1660. }
  1661.  
  1662. function get_desc_from_node(selector, url, quote = false) {
  1663. description = [];
  1664. dom.querySelectorAll(selector).forEach(k => { description.push(html2php(k, url).trim()) });
  1665. description = description.join('\n\n').trim().replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  1666. if (quote && description.length > 0) description = '[quote]' + description + '[/quote]';
  1667. }
  1668. } // init_from_url_music
  1669.  
  1670. function normalizeDate(str) {
  1671. if (typeof str != 'string') return null;
  1672. return /\b(d{4}-\d+-\d+|\d{1,2}\/\d{1,2}\/\d{2})\b/.test(str) ? RegExp.$1 :
  1673. /\b(\d{1,2})\/(\d{1,2})\/(\d{4})\b/.test(str) ? RegExp.$2 + '/' + RegExp.$1 + '/' + RegExp.$3 :
  1674. /\b(\d{1,2})\.\s?(\d{1,2})\.\s?(\d{2}|\d{4})\b/.test(str) ? RegExp.$2 + '/' + RegExp.$1 + '/' + RegExp.$3 :
  1675. extract_year(str);
  1676. }
  1677.  
  1678. function fetch_image_from_store(response) {
  1679. if (response.readyState != 4 || !response.responseText) return;
  1680. dom = domparser.parseFromString(response.responseText, "text/html");
  1681. if (dom == null) return;
  1682. function testDomain(str) {
  1683. return typeof str == 'string' && response.finalUrl.toLowerCase().includes(str.toLowerCase());
  1684. }
  1685. if (testDomain('qobuz.com') && (ref = dom.querySelector('div.album-cover > img')) != null) {
  1686. setImage(ref.src);
  1687. } else if (testDomain('highresaudio.com') && (ref = dom.querySelector('div.albumbody > img.cover[data-pin-media]')) != null) {
  1688. setImage(ref.dataset.pinMedia);
  1689. } else if (testDomain('bandcamp.com') && (ref = dom.querySelector('div#tralbumArt > a.popupImage')) != null) {
  1690. setImage(ref.href);
  1691. } else if (testDomain('7digital.com') && (ref = dom.querySelector('span.release-packshot-image > img[itemprop="image"]')) != null) {
  1692. setImage(ref.src);
  1693. } else if (testDomain('hdtracks.com') && (ref = dom.querySelector('p.product-image > img')) != null) {
  1694. setImage(ref.src);
  1695. } else if (testDomain('discogs.com') && (ref = dom.querySelector('div#view_images > p:first-of-type > span > img')) != null) {
  1696. setImage(ref.src);
  1697. } else if (testDomain('junodownload.com') && (ref = dom.querySelector('a.productimage')) != null) {
  1698. setImage(ref.href);
  1699. } else if (testDomain('supraphonline.cz') && (ref = dom.querySelector('div.sexycover > img')) != null) {
  1700. setImage(ref.src.replace(/\?\d+$/, ''));
  1701. } else if (testDomain('prestomusic.com') && (ref = dom.querySelector('div.c-product-block__aside > a')) != null) {
  1702. setImage(ref.href.replace(/\?\d+$/, ''));
  1703. }
  1704. }
  1705.  
  1706. function reqSelectFormats(...vals) {
  1707. vals.forEach(function(val) {
  1708. [
  1709. ['MP3', 0],
  1710. ['FLAC', 1],
  1711. ['AAC', 2],
  1712. ['AC3', 3],
  1713. ['DTS', 4],
  1714. ].forEach(function(fmt) {
  1715. if (val == fmt[0] && (ref = document.getElementById('format_' + fmt[1])) != null) {
  1716. ref.checked = true;
  1717. ref.onchange();
  1718. }
  1719. });
  1720. });
  1721. }
  1722.  
  1723. function reqSelectBitrates(...vals) {
  1724. vals.forEach(function(val) {
  1725. var ndx = 10;
  1726. [
  1727. [192, 0],
  1728. ['APS (VBR)', 1],
  1729. ['V2 (VBR)', 2],
  1730. ['V1 (VBR)', 3],
  1731. [256, 4],
  1732. ['APX (VBR)', 5],
  1733. ['V0 (VBR)', 6],
  1734. [320, 7],
  1735. ['Lossless', 8],
  1736. ['24bit Lossless', 9],
  1737. ['Other', 10],
  1738. ].forEach(k => { if (val == k[0]) ndx = k[1] });
  1739. if ((ref = document.getElementById('bitrate_' + ndx)) != null) {
  1740. ref.checked = true;
  1741. ref.onchange();
  1742. }
  1743. });
  1744. }
  1745.  
  1746. function reqSelectMedias(...vals) {
  1747. vals.forEach(function(val) {
  1748. [
  1749. ['CD', 0],
  1750. ['DVD', 1],
  1751. ['Vinyl', 2],
  1752. ['Soundboard', 3],
  1753. ['SACD', 4],
  1754. ['DAT', 5],
  1755. ['Cassette', 6],
  1756. ['WEB', 7],
  1757. ['Blu-Ray', 8],
  1758. ].forEach(function(med) {
  1759. if (val == med[0] && (ref = document.getElementById('media_' + med[1])) != null) {
  1760. ref.checked = true;
  1761. ref.onchange();
  1762. }
  1763. });
  1764. if (val == 'CD') {
  1765. if ((ref = document.getElementById('needlog')) != null) {
  1766. ref.checked = true;
  1767. ref.onchange();
  1768. if ((ref = document.getElementById('minlogscore')) != null) ref.value = 100;
  1769. }
  1770. if ((ref = document.getElementById('needcue')) != null) ref.checked = true;
  1771. //if ((ref = document.getElementById('needchecksum')) != null) ref.checked = true;
  1772. }
  1773. });
  1774. }
  1775.  
  1776. function getReleaseIndex(str) {
  1777. var ndx;
  1778. [
  1779. ['Album', 1],
  1780. ['Soundtrack', 3],
  1781. ['EP', 5],
  1782. ['Anthology', 6],
  1783. ['Compilation', 7],
  1784. ['Single', 9],
  1785. ['Live album', 11],
  1786. ['Remix', 13],
  1787. ['Bootleg', 14],
  1788. ['Interview', 15],
  1789. ['Mixtape', 16],
  1790. ['Demo', 17],
  1791. ['Concert Recording', 18],
  1792. ['DJ Mix', 19],
  1793. ['Unknown', 21],
  1794. ].forEach(k => { if (str.toLowerCase() == k[0].toLowerCase()) ndx = k[1] });
  1795. return ndx || 21;
  1796. }
  1797. }
  1798.  
  1799. function fill_from_text_apps() {
  1800. if (!/^https?:\/\//i.test(clipBoard.value)) return false;
  1801. var description, tags = new TagManager();
  1802. if (clipBoard.value.toLowerCase().indexOf('//sanet') >= 0) {
  1803. GM_xmlhttpRequest({ method: 'GET', url: clipBoard.value, onload: function(response) {
  1804. if (response.readyState != 4 || response.status != 200) return;
  1805. dom = domparser.parseFromString(response.responseText, "text/html");
  1806.  
  1807. i = dom.querySelector('h1.item_title > span');
  1808. if (element_writable(ref = document.getElementById('title'))) {
  1809. ref.value = i != null ? i.textContent.
  1810. replace(/\(x64\)$/i, '(64-bit)').
  1811. replace(/\b(?:Build)\s+(\d+)/, 'build $1').
  1812. replace(/\b(?:Multilingual|Multilanguage)\b/, 'multilingual') : null;
  1813. }
  1814. description = html2php(dom.querySelector('section.descr'), response.finalUrl);
  1815. if (/\s*^(?:\[i\]\[\/i\])?Homepage$.*/m.test(description)) description = RegExp.leftContext;
  1816. description = description.trim().split(/\n/).slice(5).map(k => k.trimRight()).join('\n').trim();
  1817. ref = dom.querySelector('section.descr > div.release-info');
  1818. var releaseInfo = ref != null && ref.textContent.trim();
  1819. if (/\b(?:Languages?)\s*:\s*(.*?)\s*(?:$|\|)/i.exec(releaseInfo) != null) {
  1820. description += '\n\n[b]Languages:[/b]\n' + RegExp.$1;
  1821. }
  1822. ref = dom.querySelector('div.txtleft > a');
  1823. if (ref != null) description += '\n\n[b]Product page:[/b]\n[url]' + de_anonymize(ref.href) + '[/url]';
  1824. write_description(description);
  1825. if ((ref = dom.querySelector('section.descr > div.center > a.mfp-image')) != null) {
  1826. setImage(ref.href);
  1827. } else {
  1828. ref = dom.querySelector('section.descr > div.center > img[data-src]');
  1829. if (ref != null) setImage(ref.dataset.src);
  1830. }
  1831. var cat = dom.querySelector('a.cat:last-of-type > span');
  1832. if (cat != null) {
  1833. if (cat.textContent.toLowerCase() == 'windows') {
  1834. tags.add('apps.windows');
  1835. if (/\b(?:x64)\b/i.test(releaseInfo)) tags.add('win64');
  1836. if (/\b(?:x86)\b/i.test(releaseInfo)) tags.add('win32');
  1837. }
  1838. if (cat.textContent.toLowerCase() == 'macos') tags.add('apps.mac');
  1839. if (cat.textContent.toLowerCase() == 'linux' || cat.textContent.toLowerCase() == 'unix') tags.add('apps.linux');
  1840. if (cat.textContent.toLowerCase() == 'android') tags.add('apps.android');
  1841. if (cat.textContent.toLowerCase() == 'ios') tags.add('apps.ios');
  1842. }
  1843. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  1844. ref.value = tags.toString();
  1845. }
  1846. }, });
  1847. return true;
  1848. }
  1849. return false;
  1850. }
  1851.  
  1852. function fill_from_text_books() {
  1853. if (!/^https?:\/\//i.test(clipBoard.value)) return false;
  1854. var description, tags = new TagManager();
  1855. if (clipBoard.value.toLowerCase().indexOf('martinus.cz') >= 0 || clipBoard.value.toLowerCase().indexOf('martinus.sk') >= 0) {
  1856. GM_xmlhttpRequest({ method: 'GET', url: clipBoard.value, onload: function(response) {
  1857. if (response.readyState != 4 || response.status != 200) return;
  1858. dom = domparser.parseFromString(response.responseText, "text/html");
  1859.  
  1860. function get_detail(x, y) {
  1861. var ref = dom.querySelector('section#details > div > div > div:first-of-type > div:nth-child(' +
  1862. x + ') > dl:nth-child(' + y + ') > dd');
  1863. return ref != null ? ref.textContent.trim() : null;
  1864. }
  1865.  
  1866. i = dom.querySelectorAll('article > ul > li > a');
  1867. if (i.length > 0 && element_writable(ref = document.getElementById('title'))) {
  1868. description = join_authors(i);
  1869. if ((i = dom.querySelector('article > h1')) != null) description += ' - ' + i.textContent.trim();
  1870. i = dom.querySelector('div.bar.mb-medium > div:nth-child(1) > dl > dd > span');
  1871. if (i != null && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  1872. ref.value = description;
  1873. }
  1874.  
  1875. description = '[quote]' + html2php(dom.querySelector('section#description > div')).
  1876. replace(/^\s*\[img\].*?\[\/img\]\s*/i, '') + '[/quote]';
  1877. const translation_map = [
  1878. [/\b(?:originál)/i, 'Original title'],
  1879. [/\b(?:datum|dátum|rok)\b/i, 'Release date'],
  1880. [/\b(?:katalog|katalóg)/i, 'Catalogue #'],
  1881. [/\b(?:stran|strán)\b/i, 'Page count'],
  1882. [/\bjazyk/i, 'Language'],
  1883. [/\b(?:nakladatel|vydavatel)/i, 'Publisher'],
  1884. [/\b(?:doporuč|ODPORÚČ)/i, 'Age rating'],
  1885. ];
  1886. dom.querySelectorAll('section#details > div > div > div:first-of-type > div > dl').forEach(function(detail) {
  1887. var lbl = detail.children[0].textContent.trim();
  1888. var val = detail.children[1].textContent.trim();
  1889. if (/\b(?:rozm)/i.test(lbl) || /\b(?:vazba|vázba)\b/i.test(lbl)) return;
  1890. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  1891. if (/\b(?:ISBN)\b/i.test(lbl)) {
  1892. val = '[url=https://www.worldcat.org/isbn/' + detail.children[1].textContent.trim() +
  1893. ']' + detail.children[1].textContent.trim() + '[/url]';
  1894. // } else if (/\b(?:ISBN)\b/i.test(lbl)) {
  1895. // val = '[url=https://www.goodreads.com/search/search?q=' + detail.children[1].textContent.trim() +
  1896. // '&search_type=books]' + detail.children[1].textContent.trim() + '[/url]';
  1897. }
  1898. description += '\n[b]' + lbl + ':[/b] ' + val;
  1899. });
  1900. description += '\n[b]More info:[/b] ' + response.finalUrl;
  1901. write_description(description);
  1902.  
  1903. if ((i = dom.querySelector('a.mj-product-preview > img')) != null) {
  1904. setImage(i.src.replace(/\?.*/, ''));
  1905. } else if ((i = dom.querySelector('head > meta[property="og:image"]')) != null) {
  1906. setImage(i.content.replace(/\?.*/, ''));
  1907. }
  1908.  
  1909. dom.querySelectorAll('dd > ul > li > a').forEach(x => { tags.add(x.textContent) });
  1910. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  1911. ref.value = tags.toString();
  1912. }
  1913. }, });
  1914. return true;
  1915. } else if (clipBoard.value.toLowerCase().indexOf('goodreads.com') >= 0) {
  1916. GM_xmlhttpRequest({ method: 'GET', url: clipBoard.value, onload: function(response) {
  1917. if (response.readyState != 4 || response.status != 200) return;
  1918. dom = domparser.parseFromString(response.responseText, "text/html");
  1919.  
  1920. i = dom.querySelectorAll('a.authorName > span');
  1921. if (i.length > 0 && element_writable(ref = document.getElementById('title'))) {
  1922. description = join_authors(i);
  1923. if ((i = dom.querySelector('h1#bookTitle')) != null) description += ' - ' + i.textContent.trim();
  1924. if ((i = dom.querySelector('div#details > div.row:nth-of-type(2)')) != null
  1925. && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  1926. ref.value = description;
  1927. }
  1928.  
  1929. description = '[quote]' + html2php(dom.querySelector('div#description > span:last-of-type'), response.finalUrl) + '[/quote]';
  1930.  
  1931. function strip(str) {
  1932. return typeof str == 'string' ?
  1933. str.replace(/\s{2,}/g, ' ').replace(/[\n\r]+/, '').replace(/\s*\.{3}(?:less|more)\b/g, '').trim() : null;
  1934. }
  1935.  
  1936. dom.querySelectorAll('div#details > div.row').forEach(k => { description += '\n' + strip(k.innerText) });
  1937. description += '\n';
  1938.  
  1939. dom.querySelectorAll('div#bookDataBox > div.clearFloats').forEach(function(detail) {
  1940. var lbl = detail.children[0].textContent.trim();
  1941. var val = strip(detail.children[1].textContent);
  1942. if (/\b(?:ISBN)\b/i.test(lbl) && ((matches = val.match(/\b(\d{13})\b/)) != null
  1943. || (matches = val.match(/\b(\d{10})\b/)) != null)) {
  1944. val = '[url=https://www.worldcat.org/isbn/' + matches[1] + ']' + strip(detail.children[1].textContent) + '[/url]';
  1945. }
  1946. description += '\n[b]' + lbl + ':[/b] ' + val;
  1947. });
  1948. description += '\n[b]More info:[/b] ' + response.finalUrl;
  1949. write_description(description);
  1950.  
  1951. if ((i = dom.querySelector('div.editionCover > img')) != null) {
  1952. setImage(i.src.replace(/\?.*/, ''));
  1953. }
  1954.  
  1955. dom.querySelectorAll('div.elementList > div.left').forEach(x => { tags.add(x.textContent.trim()) });
  1956. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  1957. ref.value = tags.toString();
  1958. }
  1959. }, });
  1960. return true;
  1961. } else if (clipBoard.value.toLowerCase().indexOf('databazeknih.cz') >= 0) {
  1962. let url = clipBoard.value;
  1963. if (url.toLowerCase().indexOf('show=alldesc') < 0) {
  1964. if (!url.includes('?')) { url += '?show=alldesc' } else { url += '&show=alldesc' }
  1965. }
  1966. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1967. if (response.readyState != 4 || response.status != 200) return;
  1968. dom = domparser.parseFromString(response.responseText, "text/html");
  1969.  
  1970. i = dom.querySelectorAll('span[itemprop="author"] > a');
  1971. if (i != null && element_writable(ref = document.getElementById('title'))) {
  1972. description = join_authors(i);
  1973. if ((i = dom.querySelector('h1[itemprop="name"]')) != null) description += ' - ' + i.textContent.trim();
  1974. i = dom.querySelector('span[itemprop="datePublished"]');
  1975. if (i != null && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  1976. ref.value = description;
  1977. }
  1978.  
  1979. description = '[quote]' + html2php(dom.querySelector('p[itemprop="description"]'), response.finalUrl) + '[/quote]';
  1980. const translation_map = [
  1981. [/\b(?:orig)/i, 'Original title'],
  1982. [/\b(?:série)\b/i, 'Series'],
  1983. [/\b(?:vydáno)\b/i, 'Released'],
  1984. [/\b(?:stran)\b/i, 'Page count'],
  1985. [/\b(?:jazyk)\b/i, 'Language'],
  1986. [/\b(?:překlad)/i, 'Translation'],
  1987. [/\b(?:autor obálky)\b/i, 'Cover author'],
  1988. ];
  1989. dom.querySelectorAll('table.bdetail tr').forEach(function(detail) {
  1990. var lbl = detail.children[0].textContent.trim();
  1991. var val = detail.children[1].textContent.trim();
  1992. if (/(?:žánr|\bvazba)\b/i.test(lbl)) return;
  1993. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  1994. if (/\b(?:ISBN)\b/i.test(lbl) && /\b(\d+(?:-\d+)*)\b/.exec(val) != null) {
  1995. val = '[url=https://www.worldcat.org/isbn/' + RegExp.$1.replace(/-/g, '') +
  1996. ']' + detail.children[1].textContent.trim() + '[/url]';
  1997. }
  1998. description += '\n[b]' + lbl + '[/b] ' + val;
  1999. });
  2000. description += '\n[b]More info:[/b] ' + response.finalUrl.replace(/\?.*/, '');
  2001. write_description(description);
  2002.  
  2003. if ((i = dom.querySelector('div#icover_mid > a')) != null) setImage(i.href.replace(/\?.*/, ''));
  2004. if ((i = dom.querySelector('div#lbImage')) != null
  2005. && (matches = i.style.backgroundImage.match(/\burl\("(.*)"\)/i)) != null) {
  2006. setImage(matches[1].replace(/\?.*/, ''));
  2007. }
  2008.  
  2009. dom.querySelectorAll('h5[itemprop="genre"] > a').forEach(x => { tags.add(x.textContent.trim()) });
  2010. dom.querySelectorAll('a.tag').forEach(x => { tags.add(x.textContent.trim()) });
  2011. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  2012. ref.value = tags.toString();
  2013. }
  2014. }, });
  2015. return true;
  2016. }
  2017. return false;
  2018.  
  2019. function join_authors(nodeList) {
  2020. if (typeof nodeList != 'object') return null;
  2021. var authors = [];
  2022. nodeList.forEach(k => { authors.push(k.textContent.trim()) });
  2023. return authors.join(' & ');
  2024. }
  2025. }
  2026.  
  2027. function preview(n) {
  2028. if (!prefs.auto_preview) return;
  2029. var btn = document.querySelector('input.button_preview_' + n + '[type="button"][value="Preview"]');
  2030. if (btn != null) btn.click();
  2031. }
  2032.  
  2033. function html2php(node, url) {
  2034. var text = '';
  2035. if (node instanceof HTMLElement) node.childNodes.forEach(function(ch) {
  2036. if (ch.nodeType == 3) {
  2037. text += ch.data.replace(/\s+/g, ' ');
  2038. } else if (ch.nodeName == 'P') {
  2039. text += '\n' + html2php(ch, url);
  2040. } else if (ch.nodeName == 'DIV') {
  2041. text += '\n' + html2php(ch, url) + '\n\n';
  2042. } else if (ch.nodeName == 'LABEL') {
  2043. text += '\n\n[b]' + html2php(ch, url) + '[/b]';
  2044. } else if (ch.nodeName == 'SPAN') {
  2045. text += html2php(ch, url);
  2046. } else if (ch.nodeName == 'BR' || ch.nodeName == 'HR') {
  2047. text += '\n';
  2048. } else if (ch.nodeName == 'B' || ch.nodeName == 'STRONG') {
  2049. text += '[b]' + html2php(ch, url) + '[/b]';
  2050. } else if (ch.nodeName == 'I' || ch.nodeName == 'EM') {
  2051. text += '[i]' + html2php(ch, url) + '[/i]';
  2052. } else if (ch.nodeName == 'U') {
  2053. text += '[u]' + html2php(ch, url) + '[/u]';
  2054. } else if (ch.nodeName == 'CODE') {
  2055. text += '[pre]' + ch.textContent + '[/pre]';
  2056. } else if (ch.nodeName == 'A') {
  2057. text += ch.textContent.trim() ?
  2058. '[url=' + de_anonymize(ch.href) + ']' + ch.textContent.replace(/\s+/g, ' ') + '[/url]' :
  2059. '[url]' + de_anonymize(ch.href) + '[/url]';
  2060. } else if (ch.nodeName == 'IMG') {
  2061. text += '[img]' + (ch.dataset.src || ch.src) + '[/img]';
  2062. }
  2063. });
  2064. return text; //.replace(/\n{3,}/, '\n\n');
  2065. }
  2066.  
  2067. function de_anonymize(uri) {
  2068. return typeof uri == 'string' ? uri.replace(/^https?:\/\/(?:www\.)?anonymz\.com\/\?/i, '') : null;
  2069. }
  2070.  
  2071. function write_description(desc) {
  2072. if (typeof desc != 'string') return;
  2073. if (element_writable(ref = document.getElementById('desc'))) ref.value = desc;
  2074. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  2075. if (ref.textLength > 0) ref.value += '\n\n';
  2076. ref.value += desc;
  2077. }
  2078. }
  2079.  
  2080. function setImage(url) {
  2081. var image = document.getElementById('image') || document.querySelector('input[name="image"]');
  2082. if (!element_writable(image)) return false;
  2083. image.value = url;
  2084.  
  2085. if (prefs.auto_preview_cover) {
  2086. if ((child = document.getElementById('cover preview')) == null) {
  2087. elem = document.createElement('div');
  2088. elem.style.paddingTop = '10px';
  2089. child = document.createElement('img');
  2090. child.id = 'cover preview';
  2091. child.style.width = '90%';
  2092. elem.append(child);
  2093. image.parentNode.previousElementSibling.append(elem);
  2094. }
  2095. child.src = url;
  2096. }
  2097. // Re-Host to PTPIMG
  2098. if (prefs.auto_rehost_cover) {
  2099. var rehost_btn = document.querySelector('input.rehost_it_cover[type="button"]');
  2100. if (rehost_btn != null) {
  2101. rehost_btn.click();
  2102. } else {
  2103. var pr = rehostImgs([url]);
  2104. if (pr != null) pr.then(new_urls => { image.value = new_urls[0] });
  2105. }
  2106. }
  2107. }
  2108.  
  2109. // PTPIMG rehoster taken from `PTH PTPImg It`
  2110. function rehostImgs(urls) {
  2111. if (!Array.isArray(urls)) return null;
  2112. var config = JSON.parse(window.localStorage.ptpimg_it);
  2113. return config.api_key ? new Promise(ptpimg_upload_urls).catch(m => { alert(m) }) : null;
  2114.  
  2115. function ptpimg_upload_urls(resolve, reject) {
  2116. const boundary = 'NN-GGn-PTPIMG';
  2117. var data = '--' + boundary + "\n";
  2118. data += 'Content-Disposition: form-data; name="link-upload"\n\n';
  2119. data += urls.map(function(url) {
  2120. return url.toLowerCase().indexOf('://reho.st/') < 0 && url.toLowerCase().indexOf('discogs.com') >= 0 ?
  2121. 'https://reho.st/' + url : url;
  2122. }).join('\n') + '\n';
  2123. data += '--' + boundary + '\n';
  2124. data += 'Content-Disposition: form-data; name="api_key"\n\n';
  2125. data += config.api_key + '\n';
  2126. data += '--' + boundary + '--';
  2127. GM_xmlhttpRequest({
  2128. method: 'POST',
  2129. url: 'https://ptpimg.me/upload.php',
  2130. responseType: 'json',
  2131. headers: {
  2132. 'Content-type': 'multipart/form-data; boundary=' + boundary,
  2133. },
  2134. data: data,
  2135. onload: response => {
  2136. if (response.status != 200) reject('Response error ' + response.status);
  2137. resolve(response.response.map(item => 'https://ptpimg.me/' + item.code + '.' + item.ext));
  2138. },
  2139. });
  2140. }
  2141. }
  2142.  
  2143. function element_writable(elem) { return elem != null && !elem.disabled && (overwrite || !elem.value) }
  2144. }
  2145.  
  2146. function add_artist() { exec(function() { AddArtistField() }) }
  2147.  
  2148. function array_homogenous(arr) { return arr.every(k => k === arr[0]) }
  2149.  
  2150. function exec(fn) {
  2151. let script = document.createElement('script');
  2152. script.type = 'application/javascript';
  2153. script.textContent = '(' + fn + ')();';
  2154. document.body.appendChild(script); // run the script
  2155. document.body.removeChild(script); // clean up
  2156. }
  2157.  
  2158. function makeTimeString(duration) {
  2159. let t = Math.abs(Math.round(duration));
  2160. let H = Math.floor(t / 60 ** 2);
  2161. let M = Math.floor(t / 60 % 60);
  2162. let S = t % 60;
  2163. return (duration < 0 ? '-' : '') + (H > 0 ? H + ':' + M.toString().padStart(2, '0') : M.toString()) +
  2164. ':' + S.toString().padStart(2, '0');
  2165. }
  2166.  
  2167. function timestrToTime(str) {
  2168. if (!/(-\s*)?\b(\d+(?::\d{2})*(?:\.\d+)?)\b/.test(str)) return null;
  2169. var t = 0, a = RegExp.$2.split(':');
  2170. while (a.length > 0) t = t * 60 + parseFloat(a.shift());
  2171. return RegExp.$1 ? -t : t;
  2172. }
  2173.  
  2174. function extract_year(expr) {
  2175. if (typeof expr != 'string') return null;
  2176. if (/\b(\d{4})\b/.test(expr)) return parseInt(RegExp.$1);
  2177. var d = new Date(expr);
  2178. return parseInt(isNaN(d) ? expr : d.getFullYear());
  2179. }
  2180.  
  2181. function isRED() { return document.domain.toLowerCase().endsWith('redacted.ch') }
  2182. function isNWCD() { return document.domain.toLowerCase().endsWith('notwhat.cd') }
  2183. function isOrpheus() { return document.domain.toLowerCase().endsWith('orpheus.network') }
  2184.  
  2185. function reInParenthesis(expr) { return new RegExp('\\s+\\([^\\(\\)]*'.concat(expr, '[^\\(\\)]*\\)$'), 'i') }
  2186. function reInBrackets(expr) { return new RegExp('\\s+\\[[^\\[\\]]*'.concat(expr, '[^\\[\\]]*\\]$'), 'i') }
  2187.  
  2188. function matchCaseless(str) { return str.toLowerCase() == this.toLowerCase() }
  2189.  
  2190. Array.prototype.includesCaseless = function(str) { return this.find(matchCaseless, str) != undefined };
  2191.  
  2192. function addMessage(text, cls, html = false) {
  2193. messages = document.getElementById('UA messages');
  2194. if (messages == null) {
  2195. var ua = document.getElementById('upload assistant');
  2196. if (ua == null) return null;
  2197. messages = document.createElement('TR');
  2198. if (messages == null) return null;
  2199. messages.id = 'UA messages';
  2200. ua.children[0].append(messages);
  2201.  
  2202. elem = document.createElement('TD');
  2203. if (elem == null) return null;
  2204. elem.colSpan = 2;
  2205. elem.style.padding = '15px';
  2206. elem.style.textAlign = 'left';
  2207. messages.append(elem);
  2208. } else {
  2209. elem = messages.children[0]; // tbody
  2210. if (elem == null) return null;
  2211. }
  2212. var div = document.createElement('DIV');
  2213. div.classList.add('ua-messages', cls);
  2214. div[html ? 'innerHTML' : 'textContent'] = text;
  2215. return elem.appendChild(div);
  2216. }