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

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