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