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

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