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

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