Greasy Fork 还支持 简体中文。

RED (+ NWCD, Orpheus) Upload Assistant

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

目前為 2019-09-21 提交的版本,檢視 最新版本

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