RED (+ NWCD, Orpheus) Upload Assistant

Accurate filling of new upload/request and group/request edit forms based on foobar2000's playlist selection (via pasted output of copy command), release integrity check, two tracklist layouts, colours customization, featured artists extraction, image fetching from store and more. As alternative to pasted playlist, e.g. for requests creation, valid URL to product page on supported web can be used -- see below for list of supported sites.

当前为 2019-09-26 提交的版本,查看 最新版本

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