Greasy Fork 还支持 简体中文。

RED/NWCD 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, classical works formatting, coverart 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-10-23 提交的版本,檢視 最新版本

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