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

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