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

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