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

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