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