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

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