RED (+ NWCD, Orpheus) Upload Assistant

Script fills in as much accurately the upload and group edit forms based on foobar2000's playlist selection via pasted output of copy command, release consistency check, two tracklist layouts, basic colours customization, featured artists extraction, image URl fetching from store and more...

当前为 2019-09-04 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name RED (+ NWCD, Orpheus) Upload Assistant
  3. // @namespace https://greasyfork.org/cs/users/321857-anakunda
  4. // @version 1.80
  5. // @description Script fills in as much accurately the upload and group edit forms based on foobar2000's playlist selection via pasted output of copy command, release consistency check, two tracklist layouts, basic colours customization, featured artists extraction, image URl fetching from store and more...
  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://notwhat.cd/upload.php*
  11. // @match https://notwhat.cd/torrents.php?action=editgroup*
  12. // @match https://orpheus.network/upload.php*
  13. // @match https://orpheus.network/torrents.php?action=editgroup*
  14. // @connect file://*
  15. // @connect *
  16. // @grant GM_xmlhttpRequest
  17. // @grant GM_getValue
  18. // @grant GM_setValue
  19. // @grant GM_deleteValue
  20. // @grant GM_log
  21. // ==/UserScript==
  22.  
  23. // The pattern for built-in copy command or custom Text Tools quick copy command, which is handled by this helper is:
  24. // $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($if2(%label%,%publisher%),)]$char(30)[$fix_eol($if3(%catalog%,%CATALOGNUMBER%,%catalog #%,%barcode%,%UPC%,%EAN%),)]$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%,%discogs_format%,%source%)]$char(30)[$fix_eol(%genre%,)]['; '$fix_eol(%style%,)]$char(30)[$num(%discnumber%,0)]$char(30)[$num(%totaldiscs%,0)]$char(30)[$fix_eol(%discsubtitle%,)]$char(30)[%track number%]$char(30)[$num(%totaltracks%,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(%composer%,)]$char(30)[$fix_eol(%conductor%,)]$char(30)[$fix_eol(%remixer%,)]$char(30)[$fix_eol(%compiler%,)]$char(30)[$fix_eol($if2(%producer%,%producedby%),)]$char(30)%length_seconds_fp%$char(30)[%replaygain_album_gain%]$char(30)[%album dynamic range%]$char(30)[%__tool%][ | %ENCODER%][ | %ENCODER_OPTIONS%]$char(30)[$fix_eol($if2(%url%,'https://www.discogs.com/release/'%discogs_release_id%),)]$char(30)$directory_path(%path%)$char(30)[$replace($replace(%comment%,$char(13),$char(29)),$char(10),$char(28))]
  25.  
  26. 'use strict';
  27.  
  28. var prefs = {
  29. set: function(prop, def) { this[prop] = GM_getValue(prop, def) },
  30. save: function() {
  31. for (var iter in this) { if (typeof this[iter] != 'function') GM_setValue(iter, this[iter]) }
  32. },
  33. };
  34. prefs.set('remap_texttools_newlines', 0); // convert underscores to linebreaks (ambiguous)
  35. prefs.set('clean_on_apply', 0); // clean the input box on successfull fill
  36. prefs.set('keep_meaningles_composers', 0); // keep composers from file tags also for non-composer emphasis works
  37. prefs.set('always_hide_dnu_list', 0); // risky!
  38. prefs.set('single_threshold', 8 * 60); // Max length of single in s
  39. prefs.set('EP_threshold', 28 * 60); // Max time of EP in s
  40. prefs.set('auto_preview_cover', 1);
  41. prefs.set('auto_rehost_cover', 1);
  42. // tracklist specific
  43. prefs.set('tracklist_style', 1); // 1: classical, 2: propertional right aligned
  44. prefs.set('max_tracklist_width', 80); // right margin of the right aligned tracklist. should not exceed the group description width on any device
  45. prefs.set('title_separator', '. '); // divisor of track# and title
  46. prefs.set('tracklist_head_color', '#4682B4');
  47. prefs.set('tracklist_single_color', '#708080');
  48. // classical tracklist only components colouring
  49. prefs.set('tracklist_discsubtitle_color', '#008B8B');
  50. prefs.set('tracklist_classicalblock_color', 'Olive');
  51. prefs.set('tracklist_tracknumber_color', '#8899AA');
  52. prefs.set('tracklist_artist_color', '#889B2F');
  53. prefs.set('tracklist_composer_color', '#556B2F');
  54. prefs.set('tracklist_duration_color', '#4682B4');
  55.  
  56. var iter, ref, tbl, elem, child, tb, warnings;
  57. if (/\/upload\.php\b/.test(document.URL)) {
  58. ref = document.querySelector('form#upload_table > div#dynamic_form');
  59. if (ref == null) return;
  60. common1();
  61. let x = [];
  62. x.push(document.createElement('tr'));
  63. x[0].style.verticalAlign = 'middle';
  64. x[0].style.backgroundColor = 'transparent';
  65. child = document.createElement('input');
  66. child.id = 'fill-from-text';
  67. child.value = 'Fill from text (overwrite)';
  68. child.type = 'button';
  69. child.style.width = '13em';
  70. child.onclick = fill_from_text;
  71. x[0].append(child);
  72. elem.append(x[0]);
  73. x.push(document.createElement('tr'));
  74. x[1].style.verticalAlign = 'middle';
  75. x[1].style.backgroundColor = 'transparent';
  76. child = document.createElement('input');
  77. child.id = 'fill-from-text-weak';
  78. child.value = 'Fill from text (keep values)';
  79. child.type = 'button';
  80. child.style.width = '13em';
  81. child.onclick = fill_from_text;
  82. x[1].append(child);
  83. elem.append(x[1]);
  84. common2();
  85. } else if (document.URL.indexOf('/torrents.php?action=editgroup') >= 0) {
  86. ref = document.querySelector('form.edit_form > div > div > input[type="submit"]');
  87. if (ref == null) return;
  88. ref = ref.parentNode;
  89. ref.parentNode.insertBefore(document.createElement('br'), ref);
  90. common1();
  91. child = document.createElement('input');
  92. child.id = 'append-from-text';
  93. child.value = 'Fill from text (append)';
  94. child.type = 'button';
  95. child.onclick = fill_from_text;
  96. elem.append(child);
  97. common2();
  98. tbl.style.marginBottom = '10px';
  99. }
  100. if ((ref = document.getElementById('image')) != null) {
  101. ref.ondblclick = ondblclick;
  102. ref.onmousedown = onmousedown;
  103. ref.ondrop = ondblclick;
  104. }
  105.  
  106. function ondblclick() { this.value = null }
  107. function onmousedown(e) { if (e.button == 1) this.value = null }
  108.  
  109. function common1() {
  110. tbl = document.createElement('tr');
  111. tbl.style.backgroundColor = 'darkgoldenrod';
  112. elem = document.createElement('td');
  113. child = document.createElement('textarea');
  114. child.id = 'import_data';
  115. child.name = 'import_data';
  116. child.cols = 50;
  117. child.rows = 3;
  118. child.style.width = '610px';
  119. child.style.height = '3em';
  120. child.style.backgroundColor = 'antiquewhite'; //'darkgoldenrod';
  121. //child.style.color = 'white';
  122. child.style.fontSize = 'small';
  123. child.className = ' wbbarea';
  124. child.spellcheck = false;
  125. child.setAttribute('data-wbb', '');
  126. //child.ondblclick = ondblclick;
  127. child.onmousedown = onmousedown;
  128. //child.onpaste = fill_from_text;
  129. elem.append(child);
  130. tbl.append(elem);
  131. elem = document.createElement('td');
  132. elem.align = 'right';
  133. }
  134. function common2() {
  135. tbl.append(elem);
  136. tb = document.createElement('tbody');
  137. tb.append(tbl);
  138. tbl = document.createElement('table');
  139. tbl.id = 'upload assistant';
  140. tbl.cellPadding = 0;
  141. tbl.cellSpacing = 0;
  142. tbl.className = 'layout border';
  143. tbl.border = 0;
  144. tbl.width = '100%';
  145. tbl.append(tb);
  146. ref.parentNode.insertBefore(tbl, ref);
  147. }
  148.  
  149. if (prefs.always_hide_dnu_list && (ref = document.querySelector('div#content > div:first-of-type')) != null) {
  150. ref.style.display = 'none'; // Hide DNU list (warning - risky!)
  151. }
  152.  
  153. class TagManager extends Array {
  154. constructor() {
  155. super();
  156. this.substitutions = [
  157. [/^Alternative(?:\s+and\s+|\s*[&+]\s*)Indie$/i, 'alternative', 'indie'],
  158. [/^Pop(?:\s+and\s+|\s*[&+]\s*)Rock$/i, 'pop', 'rock'],
  159. [/^Pop\s*(?:[\-\−\—\–\/]\s*)?Rock$/i, 'pop.rock'],
  160. [/^Rock(?:\s+and\s+|\s*[&+]\s*)Pop$/i, 'pop', 'rock'],
  161. [/^Rock\s*(?:[\-\−\—\–\/]\s*)?Pop$/i, 'pop.rock'],
  162. [/^Soul(?:\s+and\s+|\s*[&+]\s*)Funk$/i, 'soul', 'funk'],
  163. [/^Funk(?:\s+and\s+|\s*[&+]\s*)Soul$/i, 'soul', 'funk'],
  164. [/^World(?:\s+and\s+|\s*[&+]\s*)Country$/i, 'world.music', 'country'],
  165. [/^Jazz Fusion\s*&\s*Jazz Rock$/i, 'jazz.fusion', 'jazz.rock'],
  166. [/^(?:Singer(?:\s+and\s+|\s*[&+]\s*))?Songwriter$/i, 'singer.songwriter'],
  167. [/^(?:R\s*(?:[\'\’\`][Nn](?:\s+|[\'\’\`]\s*)|&\s*)B)$/i, 'rhytm.and.blues'],
  168. [/\b(?:soundtracks?)$/i, 'score'],
  169. [/^(?:Electro)$/i, 'electronic'],
  170. [/^(?:Metal)$/i, 'heavy.metal'],
  171. [/^(?:Nonfiction)$/i, 'non.fiction'],
  172. [/^(?:Neo[\s\-\−\—\–]+Classical)$/i, 'neoclassical'],
  173. [/^(?:Bluesy[\s\-\−\—\–]+Rock)$/i, 'blues.rock'],
  174. [/^(?:Be[\s\-\−\—\–]+Bop)$/i, 'bebop'],
  175. [/^(?:Rap)$/i, 'hip.hop'],
  176. ];
  177. this.additions = [
  178. [/^(?:(?:(?:Be|Post|Neo)[\s\-\−\—\–]*)?Bop|Modal|Fusion|Free[\s\-\−\—\–]+Improvisation|Jazz[\s\-\−\—\–]+Fusion|Big[\s\-\−\—\–]*Band)$/i, 'jazz'],
  179. [/^(?:(?:Free|Cool|Avant[\s\-\−\—\–]*Garde|Contemporary|Vocal|Modal|Soul|Smooth|Piano|Latin|Afro[\s\-\−\—\–]*Cuban)[\s\-\−\—\–]+Jazz)$/i, 'jazz'],
  180. [/^(?:Opera)$/i, 'classical'],
  181. [/\b(?:Chamber[\s\-\−\—\–]+Music)\b/i, 'classical'],
  182. ];
  183. this.removals = [
  184. ];
  185. }
  186.  
  187. add(...tags) {
  188. var added = 0;
  189. for (var tag of tags) {
  190. if (typeof tag != 'string') continue;
  191. tag.split(/\s*[\,\/\;\>\|]+\s*/).forEach(function(tag) {
  192. tag = tag.normalize("NFD").
  193. replace(/[\u0300-\u036f]/g, '').
  194. replace(/\(.*?\)|\[.*?\]|\{.*?\}/g, '').
  195. trim();
  196. if (tag.length <= 0 || tag == '?') return null;
  197. for (var k of this.substitutions) {
  198. if (k[0].test(tag)) { added += this.add(...k.slice(1)); return; }
  199. }
  200. for (k of this.additions) {
  201. if (k[0].test(tag)) { added += this.add(...k.slice(1)); }
  202. }
  203. for (k of this.removals) { if (k[0].test(tag)) return }
  204. tag = tag.
  205. replace(/\s*(?:[\'\’\`][Nn](?:\s+|[\'\’\`]\s*)|[\&\+]\s*)/, ' and ').
  206. replace(/[\!\@\#\$\%\^\*\?\<\"\[\{\]\}\=]+/g, '').
  207. replace(/[\s\-\−\—\–\_\.\'\`\~]+/g, '.').
  208. toLowerCase();
  209. if (tag.length >= 2 && !this.includes(tag)) {
  210. this.push(tag);
  211. ++added;
  212. }
  213. }.bind(this));
  214. }
  215. return added;
  216. }
  217. toString() {
  218. return this.length > 0 ? this.sort().join(', ') : null;
  219. }
  220. };
  221.  
  222. function fill_from_text(e) {
  223. var overwrite = this.id == 'fill-from-text';
  224. var clipBoard = document.getElementById('import_data');
  225. if (clipBoard == null) return false;
  226. //let promise = clientInformation.clipboard.readText().then(text => clipBoard = text);
  227. //if (typeof clipBoard != 'string') return false;
  228. var category = document.getElementById('categories');
  229. var ref, iter, i, matches, rx;
  230. if ((warnings = document.getElementById('UA warnings')) != null) warnings.parentNode.removeChild(warnings);
  231. if (category == null && document.getElementById('releasetype') != null
  232. || category != null && category.value == 0) return fill_from_text_music();
  233. if (category != null && category.value == 1) return fill_from_text_apps();
  234. if (category != null && (category.value == 2 || category.value == 3)) return fill_from_text_books();
  235. return category == null ? fill_from_text_apps() || fill_from_text_books() : false;
  236.  
  237. function fill_from_text_music() {
  238. const div = ['—', '⸺', '⸻'];
  239. var lines = clipBoard.value.split(/[\r\n]+/);
  240. var track, tracks = [];
  241.  
  242. if (lines.length == 1 && /^https?:\/\//i.test(lines[0])) {
  243. init_from_url_music(lines[0]);
  244. return;
  245. } else for (iter of lines) {
  246. if (!iter.trim()) continue; // skip empty lines
  247. let metaData = iter.split('\x1E');
  248. track = {
  249. artist: metaData.shift().trim() || null,
  250. album: metaData.shift().trim() || null,
  251. album_year: extract_year(metaData.shift().trim()),
  252. release_year: extract_year(metaData.shift().trim()),
  253. label: metaData.shift().trim() || null,
  254. catalog: metaData.shift().trim() || null,
  255. encoding: metaData.shift().trim() || null,
  256. codec: metaData.shift().trim() || null,
  257. codec_profile: metaData.shift().trim() || null,
  258. bitrate: parseFloat(metaData.shift().trim()) || null,
  259. bd: parseInt(metaData.shift().trim()) || null,
  260. sr: parseInt(metaData.shift().trim()) || null,
  261. channels: parseInt(metaData.shift().trim()) || null,
  262. media: metaData.shift().trim() || null,
  263. genre: metaData.shift().trim() || null,
  264. discnumber: parseInt(metaData.shift().trim()) || null,
  265. totaldiscs: parseInt(metaData.shift().trim()) || null,
  266. discsubtitle: metaData.shift().trim() || null,
  267. tracknumber: metaData.shift().trim() || null,
  268. totaltracks: parseInt(metaData.shift().trim()) || null,
  269. title: metaData.shift().trim() || null,
  270. track_artist: metaData.shift().trim() || null,
  271. performer: metaData.shift().trim() || null,
  272. composer: metaData.shift().trim() || null,
  273. conductor: metaData.shift().trim() || null,
  274. remixer: metaData.shift().trim() || null,
  275. compiler: metaData.shift().trim() || null,
  276. producer: metaData.shift().trim() || null,
  277. duration: parseFloat(metaData.shift().trim()) || null,
  278. rg: metaData.shift().trim() || null,
  279. dr: metaData.shift().trim() || null,
  280. vendor: metaData.shift().trim() || null,
  281. url: metaData.shift().trim() || null,
  282. dirpath: metaData.shift() || null,
  283. comment: metaData.shift().trim() || null,
  284. };
  285. if (track.comment == '.') track.comment = undefined;
  286. if (track.comment) {
  287. track.comment = track.comment.replace(/\x1D/g, '\r').replace(/\x1C/g, '\n');
  288. if (prefs.remap_texttools_newlines) track.comment = track.comment.replace(/__/g, '\r\n').replace(/_/g, '\n') // ambiguous
  289. }
  290. if (track.dr != null) track.dr = parseInt(track.dr); // DR0
  291. tracks.push(track);
  292. }
  293. var album_artists = [], albums = [], album_years = [], release_years = [], labels = [], catalogs = [];
  294. var codecs = [], bds = [], medias = [], genres = [], srs = {}, urls = [], comments = [], track_artists = [];
  295. var encodings = [], bitrates = [], codec_profiles = [], drs = [], channels = [], rgs = [], dirpaths = [];
  296. var vendors = [];
  297. let is_va = false, composer_emphasis = false, is_from_dsd = false, is_classical = false;
  298. var total_time = 0, release_type = 1, album_bitrate = 0, totaldiscs = 1, artist_counter = 0;
  299. var edition_title, media, yadg_prefil = '';
  300. const featParser1 = /\(feat(?:\.|uring)\s+([^\(\)]+?)\s*\)$/i;
  301. const featParser2 = /\[feat(?:\.|uring)\s+([^\[\]]+?)\s*\]$/i;
  302. for (iter of tracks) {
  303. push_unique(album_artists, 'artist');
  304. push_unique(track_artists, 'track_artist');
  305. push_unique(albums, 'album');
  306. push_unique(album_years, 'album_year');
  307. push_unique(release_years, 'release_year');
  308. push_unique(labels, 'label');
  309. push_unique(catalogs, 'catalog');
  310. push_unique(encodings, 'encoding');
  311. push_unique(codecs, 'codec');
  312. push_unique(codec_profiles, 'codec_profile');
  313. push_unique(bitrates, 'bitrate');
  314. push_unique(bds, 'bd');
  315. push_unique(channels, 'channels');
  316. push_unique(medias, 'media');
  317. if (iter.sr) {
  318. if (typeof srs[iter.sr] != 'number') {
  319. srs[iter.sr] = iter.duration;
  320. } else {
  321. srs[iter.sr] += iter.duration;
  322. }
  323. }
  324. push_unique(genres, 'genre');
  325. push_unique(urls, 'url');
  326. push_unique(comments, 'comment');
  327. push_unique(rgs, 'rg');
  328. push_unique(drs, 'dr');
  329. push_unique(vendors, 'vendor');
  330. push_unique(dirpaths, 'dirpath');
  331.  
  332. if (iter.discnumber > totaldiscs) totaldiscs = iter.discnumber;
  333. total_time += iter.duration;
  334. album_bitrate += iter.duration * iter.bitrate;
  335. }
  336. function push_unique(array, prop) {
  337. if (iter[prop] !== undefined && iter[prop] !== null && (typeof iter[prop] != 'string' || iter[prop].length > 0)
  338. && !array.includes(iter[prop])) array.push(iter[prop]);
  339. }
  340. // inconsistent releases not allowed - die
  341. const requisites = [
  342. [encodings, 'encoding'],
  343. [codecs, 'codec'],
  344. [codec_profiles, 'codec profile'],
  345. [vendors, 'vendor'],
  346. [medias, 'media'],
  347. [channels, 'channel'],
  348. [album_artists, 'album artists'],
  349. [albums, 'album'],
  350. ];
  351. for (iter of requisites) {
  352. if (iter[0].length > 1) {
  353. addWarning('FATAL: fuzzy releases aren\'t allowed (' + iter[1] + '): ' + iter[0]);
  354. clipBoard.value = null;
  355. return false;
  356. }
  357. }
  358. function validatorFunc(arr, validator, str) {
  359. if (arr.length <= 0 || !arr.some(validator)) return true;
  360. addWarning('FATAL: disallowed ' + str + ' present (' + arr.filter(validator) + ')');
  361. clipBoard.value = null;
  362. return false;
  363. }
  364. if (!validatorFunc(bds, (bd) => ![16, 24].includes(bd), 'bit depths')
  365. || !validatorFunc(Object.keys(srs), (sr) => sr < 44100 || sr > 192000
  366. || sr % 44100 != 0 && sr % 48000 != 0, 'sample rates')) return false;
  367. var tags = new TagManager();
  368. album_bitrate /= total_time;
  369. if (total_time <= prefs.single_threshold) {
  370. release_type = 9; // single
  371. } else if (total_time <= prefs.EP_threshold) {
  372. release_type = 5; // EP
  373. }
  374. if (album_artists.length == 1 && (ref = document.getElementById('artist')) != null) {
  375. const guest_parser = /^(.*?)(?:\s+(?:feat(?:\.|uring)|with)\s+(.*))?$/;
  376. if (matches = album_artists[0].match(guest_parser)) {
  377. let artists = [];
  378. for (iter = 0; iter < 7; ++iter) artists.push([]);
  379. const artist_parser = /\s*(?:[\,\;\/\|]|(?:&)\s+(?!(?:The|His|Friends)\b))+\s*/i;
  380. const weak_artist_parser = /\s*[\,\;\/\|]+\s*/;
  381. const other_artists_parsers = [
  382. [/^(.*?)\s+(?:under|(?:conducted) by)\s+(.*)$/, artists[4]],
  383. [/^()(.*?)\s+\(conductor\)$/i, artists[4]],
  384. //[/^()(.*?)\s+\(.*\)$/i, guests],
  385. ];
  386. const invalid_artist = /^#?N\/?A$/i;
  387. const noakas = /\s+aka\s+(.*)/;
  388. let j;
  389. if (/^(?:Various(?: Artists?)?|VA)$/.test(matches[1])) {
  390. is_va = true;
  391. } else {
  392. j = matches[1].split(artist_parser);
  393. (j.every(twoOrMore) ? j : [ matches[0] ]).forEach(function(i) {
  394. i = guess_other_artists(i);
  395. if (i.length > 0 && !invalid_artist.test(i) && !artists[0].includesCaseless(i)) artists[0].push(i);
  396. });
  397. yadg_prefil = matches[1];
  398. }
  399. if (!is_va && matches[2]) {
  400. artists[1] = matches[2].split(weak_artist_parser);
  401. if (!artists[1].every(twoOrMore)) artists[1] = matches[2];
  402. }
  403. for (iter of tracks) {
  404. add_track_artists('track_artist');
  405. add_track_artists('performer');
  406. add_other_artists(artists[2], 'remixer');
  407. add_other_artists(artists[3], 'composer');
  408. add_other_artists(artists[4], 'conductor');
  409. add_other_artists(artists[5], 'compiler');
  410. add_other_artists(artists[6], 'producer');
  411.  
  412. if (iter.title) {
  413. if ((matches = iter.title.match(/\(remix(?:ed)? by ([^\(\)]+)\)/i)) != null
  414. || (matches = iter.title.match(/\(([^\(\)]+?)(?:[\'\’\`]s)? remix\)/i)) != null
  415. || (matches = iter.title.match(/\[remix(?:ed)? by ([^\[\]]+)\]/i)) != null
  416. || (matches = iter.title.match(/\[([^\[\]]+?)(?:[\'\’\`]s)? remix\]/i)) != null) {
  417. j = matches[1].split(weak_artist_parser);
  418. (j.every(twoOrMore) ? j : [ matches[1] ]).forEach(function(k) {
  419. if (!artists[2].includesCaseless(k)) artists[2].push(k);
  420. });
  421. }
  422. if ((matches = iter.title.match(featParser1)) != null || (matches = iter.title.match(featParser2)) != null) {
  423. j = matches[1].split(weak_artist_parser);
  424. (j.every(twoOrMore) ? j : [ matches[1] ]).forEach(k => { if (!notInGuestSMain(k)) artists[1].push(k) });
  425. addWarning('Warning: featured artist(s) in track name (#' +
  426. iter.tracknumber + ': ' + iter.title + ')', false, '#C00000');
  427. }
  428. }
  429. } // iterate tracks
  430. for (iter = 0; iter < Math.round(tracks.length / 2); ++iter) split_ampersands();
  431.  
  432. function notInGuestSMain(k) { return !artists[0].includesCaseless(k) && !artists[1].includesCaseless(k) }
  433. function twoOrMore(k) { return k.length >= 2 && !invalid_artist.test(k) };
  434. function add_track_artists(prop) {
  435. if (iter[prop] && (matches = iter[prop].match(guest_parser))) {
  436. j = matches[1].split(weak_artist_parser);
  437. for (i of j.every(twoOrMore) ? j : [ matches[1] ]) {
  438. i = guess_other_artists(i);
  439. if (i.length > 0 && !invalid_artist.test(i) && !artists[0].includesCaseless(i)
  440. && (is_va || !artists[1].includesCaseless(i))) (is_va ? artists[0] : artists[1]).push(i);
  441. }
  442. if (matches[2]) {
  443. j = matches[2].split(weak_artist_parser);
  444. for (i of j.every(twoOrMore) ? j : [ matches[2] ]) {
  445. i = i.replace(noakas, '');
  446. if (!invalid_artist.test(i) && notInGuestSMain(i)) artists[1].push(i);
  447. }
  448. }
  449. }
  450. }
  451. function add_other_artists(list, prop) {
  452. if (!iter[prop]) return;
  453. j = iter[prop].split(weak_artist_parser);
  454. for (i of j.every(twoOrMore) ? j : [ iter[prop] ]) {
  455. i = i.replace(noakas, '');
  456. if (!invalid_artist.test(i) && !list.includesCaseless(i)) list.push(i);
  457. }
  458. }
  459. function guess_other_artists(name) {
  460. other_artists_parsers.forEach(function(it) {
  461. if (it[0].exec(name) == null) return;
  462. name = RegExp.$2.replace(noakas, '');
  463. if (name.length > 0 && !invalid_artist.test(name) && !it[1].includesCaseless(name)) it[1].push(RegExp.$2);
  464. name = RegExp.$1;
  465. });
  466. return name.replace(noakas, '');
  467. }
  468. function split_ampersands() {
  469. for (i = artists[0].length; i > 0; --i) {
  470. j = artists[0][i - 1].split('\s+&\s+');
  471. if (j.length >= 2 && j.every(twoOrMore) && !j.every(notInGuestSMain)) {
  472. artists[0].splice(i - 1, 1, ...j.filter(k => !artists[0].includesCaseless(k)));
  473. }
  474. }
  475. for (i = artists[1].length; i > 0; --i) {
  476. j = artists[1][i - 1].split('\s+&\s+');
  477. if (j.length >= 2 && j.every(twoOrMore) && !j.every(notInGuestSMain)) {
  478. artists[1].splice(i - 1, 1, ...j.filter(notInGuestSMain));
  479. }
  480. }
  481. }
  482.  
  483. if (!ref.disabled) {
  484. let artist_index = 0;
  485. feed_artist_category(artists[0].filter(k => !artists[4].includesCaseless(k)), 1);
  486. feed_artist_category(artists[1].filter(k => !artists[0].includesCaseless(k) && !artists[4].includesCaseless(k)), 2);
  487. for (iter = 2; iter < 7; ++iter) feed_artist_category(artists[iter], iter + 1);
  488. if (overwrite) while (document.getElementById('artist_' + artist_index) != null) {
  489. exec(function() { RemoveArtistField() });
  490. }
  491.  
  492. function feed_artist_category(list, type) {
  493. for (iter of list.sort()) {
  494. let id = 'artist';
  495. if (artist_index > 0) {
  496. id += '_' + artist_index;
  497. if (document.getElementById(id) == null) add_artist();
  498. }
  499. ref = document.getElementById(id);
  500. if (ref != null && (overwrite || !ref.value)) {
  501. ref.value = iter;
  502. ref.nextElementSibling.value = type;
  503. }
  504. ++artist_index;
  505. }
  506. }
  507. }
  508. }
  509. }
  510. if (is_va && release_type == 1) release_type = 7; // compilation
  511. if (albums.length == 1) {
  512. let album = albums[0];
  513. rx = /\s+(?:-\s+Single|\[Single\]|\(Single\))$/i;
  514. if (rx.test(album)) {
  515. album = album.replace(rx, '');
  516. release_type = 9; // single
  517. }
  518. rx = /\s+(?:(?:-\s+)?EP|\[EP\]|\(EP\))$/;
  519. if (rx.test(album)) {
  520. album = album.replace(rx, '')
  521. release_type = 5; // EP
  522. }
  523. rx = /\s+\((?:Live|En\s+directo?|Ao\s+Vivo)\b[^\(\)]*\)$/i;
  524. if (rx.test(album)) {
  525. //album = album.replace(rx, '')
  526. if (release_type == 1 || release_type == 7) release_type = 11; // live album
  527. }
  528. rx = /\s+\[(?:Live|En\s+directo?|Ao\s+Vivo)\b[^\[\]]*\]$/i;
  529. if (rx.test(album)) {
  530. //album = album.replace(rx, '')
  531. if (release_type == 1 || release_type == 7) release_type = 11; // live album
  532. }
  533. if (/(?:^Live\s+[aA]t\b|^Directo?\s+[Ee]n\b|\bUnplugged\b|\bAcoustic\s+Stage\b|\s+Live$)/.test(album)
  534. && (release_type == 1 || release_type == 7)) release_type = 11; // live album
  535. rx = /\b(?:Best [Oo]f|Greatest Hits|Complete\s+(.+?\s+)(?:Albums|Recordings))\b/;
  536. if (rx.test(album) && release_type == 1) release_type = 6; // Anthology
  537. rx = '\\b(?:Soundtrack|Score|Motion\\s+Picture|Series|Television|Original(?:\\s+\\w+)?\\s+Cast|Music\\s+from|(?:Musique|Bande)\\s+originale)\\b';
  538. if (reInParenthesis(rx).test(album) || reInBrackets(rx).test(album)) {
  539. //album = album.replace(rx, '')
  540. release_type = 3; // soundtrack
  541. tags.add('score');
  542. composer_emphasis = true;
  543. }
  544. rx = /\s+(?:\([^\(\)]*\bRemix(?:e[ds])?\b[^\(\)]*\)|Remix(?:e[ds])?)$/i;
  545. if (rx.test(album)) {
  546. //album = album.replace(rx, '')
  547. if (release_type == 1) release_type = 13; // remix
  548. }
  549. rx = /\s+\[[^\[\]]*\bRemix(?:e[ds])?\b[^\[\]]*\]$/i;
  550. if (rx.test(album)) {
  551. //album = album.replace(rx, '')
  552. if (release_type == 1) release_type = 13; // remix
  553. }
  554. rx = /\s+\(([^\(\)]*\b(?:Remaster(?:ed)?\b[^\(\)]*|Reissue|Edition|Version))\)$/i;
  555. if (matches = rx.exec(album)) {
  556. album = album.replace(rx, '');
  557. edition_title = matches[1];
  558. }
  559. rx = /\s+\[([^\[\]]*\b(?:Remaster(?:ed)?\b[^\[\]]*|Reissue|Edition|Version))\]$/i;
  560. if (matches = rx.exec(album)) {
  561. album = album.replace(rx, '');
  562. edition_title = matches[1];
  563. }
  564. rx = /\s+-\s+([^\[\]\(\)\-\−\—\–]*\b(?:(?:Remaster(?:ed)?|Bonus\s+Track)\b[^\[\]\(\)\-\−\—\–]*|Reissue|Edition|Version))$/i;
  565. if (matches = rx.exec(album)) {
  566. album = album.replace(rx, '');
  567. edition_title = matches[1];
  568. }
  569. if (featParser1.test(album)) album = album.replace(featParser1, '');
  570. if (featParser2.test(album)) album = album.replace(featParser1, '');
  571. rx = /\s+(?:\[LP|Vinyl|12"|7"\]|\(LP|Vinyl|12"|7"\))$/;
  572. if (matches = rx.exec(album)) { album = album.replace(rx, ''); media = 'Vinyl'; }
  573. rx = /\s+(?:\[SA-?CD\]|\(SA-?CD\))$/;
  574. if (matches = rx.exec(album)) { album = album.replace(rx, ''); media = 'SACD'; }
  575. rx = /\s+(?:\[(?:Blu[\s\-\−\—\–]?Ray|B[DR])\]|\((?:Blu[\s\-\−\—\–]?Ray|B[DR])\))$/;
  576. if (matches = rx.exec(album)) { album = album.replace(rx, ''); media = 'Blu-Ray'; }
  577. rx = /\s+(?:\[DVD(?:-?A)?\]|\(DVD(?:-?A)?\))$/;
  578. if (matches = rx.exec(album)) { album = album.replace(rx, ''); media = 'DVD'; }
  579. if (element_writable(ref = document.getElementById('title'))) ref.value = album;
  580. if (yadg_prefil) yadg_prefil += ' ';
  581. yadg_prefil += album;
  582. }
  583. if (yadg_prefil && (ref = document.getElementById('yadg_input')) != null) {
  584. ref.value = yadg_prefil;
  585. ref = document.getElementById('yadg_submit');
  586. if (ref != null && !ref.disabled) ref.click();
  587. }
  588. if (album_years.length == 1) {
  589. if (element_writable(ref = document.getElementById('year'))) ref.value = album_years[0];
  590. } else if (album_years.length > 1) {
  591. addWarning('Warning: inconsistent album year accross album: ' + album_years, false, '#C00000');
  592. }
  593. if (release_years.length == 1) {
  594. if (element_writable(ref = document.getElementById('remaster_year'))) ref.value = release_years[0];
  595. } else if (release_years.length > 1) {
  596. addWarning('Warning: inconsistent release year accross album: ' + release_years, false, '#C00000');
  597. }
  598. if (edition_title) {
  599. if (element_writable(ref = document.getElementById('remaster_title'))) ref.value = edition_title;
  600. }
  601. rx = /\s*[\,\;]\s*/g;
  602. if (labels.length == 1 && element_writable(ref = document.getElementById('remaster_record_label'))) {
  603. ref.value = labels[0].replace(rx, ' / ');
  604. } else if (labels.length > 1) {
  605. addWarning('Warning: inconsistent label accross album: ' + labels, false, '#C00000');
  606. }
  607. if (catalogs.length >= 1 && element_writable(ref = document.getElementById('remaster_catalogue_number'))) {
  608. ref.value = catalogs.map(k => k.replace(rx, ' / ')).join(' / ');
  609. }
  610. var br_isSet = (ref = document.getElementById('bitrate')) != null && ref.value;
  611. if (codecs.length == 1 && element_writable(ref = document.getElementById('format'))) {
  612. ref.value = codecs[0];
  613. exec(function() { Format() });
  614. }
  615. var sel;
  616. if (encodings[0] == 'lossless') {
  617. sel = bds.includes(24) ? '24bit Lossless' : 'Lossless';
  618. } else if (bitrates.length >= 1) {
  619. let lame_version = vendors.length > 0 && (matches = vendors[0].match(/^LAME(\d+)\.(\d+)/i)) ?
  620. parseInt(matches[1]) * 1000 + parseInt(matches[2]) : undefined;
  621. if (codec_profiles.length == 1 && codec_profiles[0] == 'VBR V0') {
  622. sel = lame_version >= 3094 ? 'V0 (VBR)' : 'APX (VBR)'
  623. } else if (codec_profiles.length == 1 && codec_profiles[0] == 'VBR V1') {
  624. sel = 'V1 (VBR)'
  625. } else if (codec_profiles.length == 1 && codec_profiles[0] == 'VBR V2') {
  626. sel = lame_version >= 3094 ? sel = 'V2 (VBR)' : 'APS (VBR)'
  627. } else if (bitrates.length == 1 && [192, 256, 320].includes(Math.round(bitrates[0]))) {
  628. sel = Math.round(bitrates[0]);
  629. } else {
  630. if (element_writable(ref = document.getElementById('bitrate')) && ref.value != 'Other') {
  631. ref.value = 'Other';
  632. exec(function() { Bitrate() });
  633. }
  634. if (element_writable(ref = document.getElementById('other_bitrate'))) {
  635. ref.value = Math.round(bitrates.length == 1 ? bitrates[0] : album_bitrate);
  636. if ((ref = document.getElementById('vbr')) != null && !ref.disabled) ref.checked = bitrates.length > 1;
  637. }
  638. }
  639. }
  640. if (sel && (ref = document.getElementById('bitrate')) != null && !ref.disabled && (overwrite || !br_isSet)) {
  641. ref.value = sel;
  642. }
  643. if (medias.length >= 1) {
  644. sel = undefined;
  645. if (/\b(?:WEB|File|Download)\b/i.test(medias[0])) sel = 'WEB';
  646. if (/\bCD\b/.test(medias[0])) sel = 'CD';
  647. if (/\b(?:SA-?CD|Hybrid)\b/i.test(medias[0])) sel = 'SACD';
  648. if (/\b(?:Blu[\-\−\—\–\s]?Ray|BR|BD)\b/i.test(medias[0])) sel = 'Blu-Ray';
  649. if (/\bDVD(?:-?A)?\b/.test(medias[0])) sel = 'DVD';
  650. if (/\b(?:Vinyl\b|LP\b|12"|7")/i.test(medias[0])) sel = 'Vinyl';
  651. media = sel || media;
  652. if (media && element_writable(ref = document.getElementById('media'))) ref.value = media;
  653. }
  654. if (genres.length >= 1) {
  655. genres.forEach(function(genre) {
  656. if (/\b(?:Classical|Symphony|Symphonic(?:al)?$|Chamber|Choral|Etude|Opera|Duets|Klassik)\b/i.test(genre)
  657. && !/\b(?:metal|rock|pop)\b/i.test(genre)) {
  658. composer_emphasis = true;
  659. is_classical = true
  660. }
  661. if (/\b(?:Jazz|Vocal)\b/i.test(genre) && !/\b(?:Nu|Future|Acid)[\s\-\−\—\–]*Jazz\b/i.test(genre)
  662. && !/\bElectr(?:o|ic)[\s\-\−\—\–]?Swing\b/i.test(genre)) {
  663. composer_emphasis = true;
  664. }
  665. if (/\b(?:Soundtracks?|Score|Films?|Games?|Video|Series?|Theatre|Musical)\b/i.test(genre)) {
  666. composer_emphasis = true;
  667. if (release_type == 1) release_type = 3;
  668. }
  669. tags.add(genre);
  670. });
  671. if (genres.length > 1) addWarning('Warning: inconsistent genre accross album: ' + genres, false, '#C00000');
  672. }
  673. if (tags.length >= 1 && element_writable(ref = document.getElementById('tags'))) ref.value = tags.toString();
  674. if (element_writable(ref = document.getElementById('releasetype'))) ref.value = release_type;
  675.  
  676. if (!composer_emphasis && !prefs.keep_meaningles_composers) {
  677. ref = document.querySelectorAll('input[name="artists[]"]');
  678. if (ref != null) ref.forEach(i => { if (['4', '5'].includes(i.nextElementSibling.value)) i.value = null });
  679. }
  680. // ============================================= The Playlist =============================================
  681. var description, ripinfo, dur;
  682. const vinyl_test = /^((?:Vinyl|LP) rip by\s+)(.*)$/im;
  683. if (tracks.length > 1) {
  684. gen_full_tracklist();
  685. } else { // single
  686. description = '[align=center]';
  687. description += isRED() ? '[pad=20|20|20|20]' : '';
  688. description += '[size=4][b][color=' + prefs.tracklist_artist_color + ']' + album_artists[0] + '[/color][hr]';
  689. //description += '[color=' + prefs.tracklist_single_color + ']';
  690. description += tracks[0].title;
  691. //description += '[/color]'
  692. description += '[/b]';
  693. if (tracks[0].composer) {
  694. description += '\n[i][color=' + prefs.tracklist_composer_color + '](' + tracks[0].composer + ')[/color][/i]';
  695. }
  696. description += '\n\n[color=' + prefs.tracklist_duration_color +'][' +
  697. make_time_string(tracks[0].duration) + '][/color][/size]';
  698. if (isRED()) description += '[/pad]';
  699. description += '[/align]';
  700. }
  701. if (comments.length == 1 && comments[0]) {
  702. let cmt = comments[0];
  703. if (matches = cmt.match(vinyl_test)) {
  704. ripinfo = cmt.slice(matches.index).trim().split(/[\r\n]+/);
  705. description = description.concat('\n\n', cmt.slice(0, matches.index).trim());
  706. } else {
  707. description = description.concat('\n\n', cmt);
  708. }
  709. }
  710. if (element_writable(ref = document.getElementById('album_desc'))) {
  711. ref.value = description;
  712. preview(0);
  713. }
  714. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  715. let editioninfo;
  716. if (edition_title) {
  717. editioninfo = '[size=5][b]' + edition_title;
  718. if (release_years.length >= 1) { editioninfo = editioninfo.concat(' (', release_years[0] + ')') }
  719. editioninfo = editioninfo.concat('[/b][/size]\n\n');
  720. } else { editioninfo = '' }
  721. if (ref.textLength > 0) {
  722. ref.value = ref.value.concat('\n\n', editioninfo, description);
  723. } else {
  724. ref.value = editioninfo + description;
  725. }
  726. preview(0);
  727. }
  728. var lineage = '', comment = '', drinfo, srcinfo;
  729. if (Object.keys(srs).length > 0) {
  730. let kHz = Object.keys(srs).sort((a, b) => srs[b] - srs[a]).map(f => f / 1000).join('/').concat('kHz');
  731. if (element_writable(ref = document.getElementById('release_samplerate'))) {
  732. ref.value = Object.keys(srs).length > 1 ? '999' : Math.floor(Object.keys(srs)[0] / 1000);
  733. }
  734. if (bds.some(bd => bd > 16)) {
  735. if (drs.length >= 1) drinfo = '[hide=DR' + (drs.length == 1 ? drs[0] : '') + '][pre][/pre]';
  736. if (media == 'Vinyl') {
  737. let hassr = ref == null || Object.keys(srs).length > 1;
  738. lineage = hassr ? kHz + ' ' : '';
  739. if (ripinfo) {
  740. ripinfo[0] = ripinfo[0].replace(vinyl_test, '$1[color=blue]$2[/color]');
  741. if (hassr) { ripinfo[0] = ripinfo[0].replace(/^Vinyl\b/, 'vinyl') }
  742. lineage += ripinfo[0] + '\n\n[u]Lineage:[/u]' + ripinfo.slice(1).map(k => '\n' + k).join('');
  743. } else {
  744. lineage += (hassr ? 'Vinyl' : ' vinyl') + ' rip by [color=blue][/color]\n\n[u]Lineage:[/u]';
  745. }
  746. if (drs.length >= 1) drinfo += '\n\n[img][/img]\n[img][/img]\n[img][/img][/hide]';
  747. } else if (['Blu-Ray', 'DVD', 'SACD'].includes(media)) {
  748. lineage = ref ? '' : kHz;
  749. if (channels.length == 1) add_channel_info();
  750. if (media == 'SACD' || is_from_dsd) {
  751. lineage += ' from DSD64 using foobar2000\'s SACD decoder (direct-fp64)';
  752. lineage += '\nOutput gain +0dB';
  753. }
  754. drinfo += '[/hide]';
  755. //add_rg_info();
  756. } else { // WEB Hi-Res
  757. if (ref == null || Object.keys(srs).length > 1) lineage = kHz;
  758. if (channels.length == 1 && channels[0] != 2) add_channel_info();
  759. add_dr_info();
  760. //if (lineage.length > 0) add_rg_info();
  761. if (bds.length >= 2) bds.filter(bd => bd != 24).forEach(function(bd) {
  762. let hybrid_tracks = tracks.filter(k => k.bd == bd).map(k => k.tracknumber);
  763. if (hybrid_tracks.length < 1) return;
  764. if (lineage) lineage += '\n';
  765. lineage += 'Note: track';
  766. if (hybrid_tracks.length > 1) lineage += 's';
  767. lineage += ' #' + hybrid_tracks.sort().join(', ') +
  768. (hybrid_tracks.length > 1 ? ' are' : ' is') + ' ' + bd + 'bit lossless';
  769. });
  770. drinfo = Object.keys(srs).includes(88200) ? drinfo.concat('[/hide]') : null;
  771. }
  772. } else { // 16bit or lossy
  773. if (Object.keys(srs).some(f => f != 44100)) lineage = kHz;
  774. if (channels.length == 1 && channels[0] != 2) add_channel_info();
  775. //add_dr_info();
  776. //if (lineage.length > 0) add_rg_info();
  777. if (['AAC', 'Opus', 'Vorbis'].includes(codecs[0]) && vendors[0]) {
  778. let _encoder_settings = vendors[0];
  779. if (codecs[0] == 'AAC' && /^qaac\s+[\d\.]+/i.test(vendors[0])) {
  780. let enc = [];
  781. if (matches = vendors[0].match(/\bqaac\s+([\d\.]+)\b/i)) enc[0] = matches[1];
  782. if (matches = vendors[0].match(/\bCoreAudioToolbox\s+([\d\.]+)\b/i)) enc[1] = matches[1];
  783. if (matches = vendors[0].match(/\b(AAC-\S+)\s+Encoder\b/i)) enc[2] = matches[1];
  784. if (matches = vendors[0].match(/\b([TC]VBR|ABR|CBR)\s+(\S+)\b/)) { enc[3] = matches[1]; enc[4] = matches[2]; }
  785. if (matches = vendors[0].match(/\bQuality\s+(\d+)\b/i)) enc[5] = matches[1];
  786. _encoder_settings = 'Converted by Apple\'s ' + enc[2] + ' encoder (' + enc[3] + '-' + enc[4] + ')';
  787. }
  788. if (lineage) lineage += '\n\n';
  789. lineage += _encoder_settings;
  790. }
  791. }
  792. }
  793. function add_dr_info() {
  794. if (drs.length != 1 || document.getElementById('release_dynamicrange') != null) return false;
  795. if (lineage.length > 0) lineage += ' | ';
  796. if (drs[0] < 4) lineage += '[color=red]';
  797. lineage += 'DR' + drs[0];
  798. if (drs[0] < 4) lineage += '[/color]';
  799. return true;
  800. }
  801. function add_rg_info() {
  802. if (rgs.length != 1) return false;
  803. if (lineage.length > 0) lineage += ' | ';
  804. lineage += 'RG'; //lineage += 'RG ' + rgs[0];
  805. return true;
  806. }
  807. function add_channel_info() {
  808. if (channels.length != 1) return false;
  809. let chi = getChanString(channels[0]);
  810. if (lineage.length > 0 && chi.length > 0) lineage += ', ';
  811. lineage += chi;
  812. return chi.length > 0;
  813. }
  814. if (urls.length == 1 && urls[0]) {
  815. srcinfo = '[url]' + urls[0] + '[/url]';
  816. if (element_writable(document.getElementById('image'))) {
  817. let u = urls[0];
  818. if (/^https?:\/\/(\w+\.)?discogs\.com\/release\/[\w\-]+\/?$/i.test(u)) u += '/images';
  819. GM_xmlhttpRequest({ method: 'GET', url: u, onload: fetch_image_from_store });
  820. }
  821. // } else if (element_writable(document.getElementById('image'))
  822. // && ((ref = document.getElementById('album_desc')) != null || (ref = document.getElementById('body')) != null)
  823. // && ref.textLength > 0 && (matches = ref.value.matchAll(/\b(https?\/\/[\w\-\&\_\?\=]+)/i)) != null) {
  824. }
  825. ref = document.getElementById('release_lineage');
  826. if (ref != null) {
  827. if (element_writable(ref)) {
  828. if (drinfo) comment = drinfo;
  829. if (lineage && srcinfo) lineage += '\n\n';
  830. if (srcinfo) lineage += srcinfo;
  831. ref.value = lineage;
  832. preview(1);
  833. }
  834. } else {
  835. comment = lineage;
  836. if (comment && drinfo) comment += '\n\n';
  837. if (drinfo) comment += drinfo;
  838. if (comment && srcinfo) comment += '\n\n';
  839. if (srcinfo) comment += srcinfo;
  840. }
  841. if (comment.length > 0) {
  842. if (element_writable(ref = document.getElementById('release_desc'))) {
  843. ref.value = comment;
  844. preview(isNWCD() ? 2 : 1);
  845. }
  846. }
  847. if (encodings[0] == 'lossless' && codecs[0] == 'FLAC' && bds.includes(24) && dirpaths.length == 1) {
  848. var uri = new URL(dirpaths[0] + '\\foo_dr.txt');
  849. GM_xmlhttpRequest({
  850. method: 'GET',
  851. url: uri.href,
  852. responseType: 'blob',
  853. onload: function(response) {
  854. if (response.readyState != 4 || !response.responseText) return;
  855. var rlsDesc = document.getElementById('release_lineage') || document.getElementById('release_desc');
  856. if (rlsDesc == null) return;
  857. var value = rlsDesc.value;
  858. matches = value.match(/(^\[hide=DR\d*\]\[pre\])\[\/pre\]/im);
  859. if (matches == null) return;
  860. var index = matches.index + matches[1].length;
  861. rlsDesc.value = value.slice(0, index).concat(response.responseText, value.slice(index));
  862. }
  863. });
  864. }
  865. if (drs.length == 1) {
  866. if (element_writable(ref = document.getElementById('release_dynamicrange'))) ref.value = drs[0];
  867. }
  868. if (prefs.clean_on_apply) clipBoard.value = null;
  869. prefs.save();
  870. return true;
  871.  
  872. function gen_full_tracklist() { // ========================= TACKLIST =========================
  873. description = isRED() ? '[pad=5|0|0|0]' : '';
  874. description += '[size=4][color=' + prefs.tracklist_head_color + '][b]Tracklisting[/b][/color][/size]';
  875. if (isRED()) '[/pad]';
  876. let classical_units = new Set();
  877. if (is_classical) {
  878. for (track of tracks) {
  879. if (matches = track.title.match(/^(.+?)\s*:\s+(.*)$/)) {
  880. classical_units.add(track.classical_unit_title = matches[1]);
  881. track.classical_title = matches[2];
  882. } else {
  883. track.classical_unit_title = null;
  884. }
  885. }
  886. for (let unit of classical_units.keys()) {
  887. let group_performer = array_homogenous(tracks.filter(k => k.classical_unit_title === unit).map(k => k.track_artist));
  888. let group_composer = array_homogenous(tracks.filter(k => k.classical_unit_title === unit).map(k => k.composer));
  889. for (track of tracks) {
  890. if (track.classical_unit_title !== unit) continue;
  891. if (group_composer) track.classical_unit_composer = track.composer;
  892. if (group_performer) track.classical_unit_performer = track.track_artist;
  893. }
  894. }
  895. }
  896. let block = 1, lastdisc, lastsubtitle, lastside, vinyl_trackwidth;
  897. let lastwork = classical_units.size > 0 ? null : undefined;
  898. description += '\n';
  899. let volumes = new Map(tracks.map(k => [k.discnumber, undefined]));
  900. volumes.forEach(function(val, key) {
  901. volumes.set(key, array_homogenous(tracks.filter(k => k.discnumber == key).map(k => k.discsubtitle)));
  902. });
  903. if (media == 'Vinyl') {
  904. let max_side_track = undefined;
  905. rx = /^([A-Z])(\d+)?(\.(\d+))?/i;
  906. for (iter of tracks) {
  907. if (matches = iter.tracknumber.match(rx)) {
  908. max_side_track = Math.max(parseInt(matches[2]) || 1, max_side_track || 0);
  909. }
  910. }
  911. if (typeof max_side_track == 'number') {
  912. max_side_track = max_side_track.toString().length;
  913. vinyl_trackwidth = 1 + max_side_track;
  914. for (iter of tracks) {
  915. if (matches = iter.tracknumber.match(rx)) {
  916. iter.tracknumber = matches[1].toUpperCase();
  917. if (matches[2]) iter.tracknumber += matches[2].padStart(max_side_track, '0');
  918. }
  919. }
  920. }
  921. }
  922. function prologue(prefix, postfix) {
  923. function block1() {
  924. if (block == 3) description += postfix;
  925. description += '\n';
  926. block = 1;
  927. }
  928. function block2() {
  929. if (block == 3) description += postfix;
  930. description += '\n';
  931. block = 2;
  932. }
  933. function block3() {
  934. if (block == 2) { description += '[hr]' } else { description += '\n' }
  935. if (block != 3) description += prefix;
  936. block = 3;
  937. }
  938. if (totaldiscs > 1 && iter.discnumber != lastdisc) {
  939. block1();
  940. description += '[size=3][color=' + prefs.tracklist_discsubtitle_color + '][b]Disc ' + iter.discnumber;
  941. if (iter.discsubtitle && (!volumes.has(iter.discnumber) || volumes.get(iter.discnumber))) {
  942. description += ' - ' + iter.discsubtitle;
  943. lastsubtitle = iter.discsubtitle;
  944. }
  945. description += '[/b][/color][/size]';
  946. lastdisc = iter.discnumber;
  947. }
  948. if (iter.discsubtitle != lastsubtitle) {
  949. block1();
  950. if (iter.discsubtitle) {
  951. description += '[size=2][color=' + prefs.tracklist_discsubtitle_color + '][b]' +
  952. iter.discsubtitle + '[/b][/color][/size]';
  953. }
  954. lastsubtitle = iter.discsubtitle;
  955. }
  956. if (iter.classical_unit_title !== lastwork) {
  957. if (iter.classical_unit_composer || iter.classical_unit_title || iter.classical_unit_performer) {
  958. block2();
  959. description += '[size=2][color=' + prefs.tracklist_classicalblock_color + '][b]';
  960. if (iter.classical_unit_composer) description += iter.classical_unit_composer + ': ';
  961. if (iter.classical_unit_title) description += iter.classical_unit_title;
  962. description += '[/b]';
  963. if (iter.classical_unit_performer) description += ' (' + iter.classical_unit_performer + ')';
  964. description += '[/color][/size]';
  965. } else {
  966. if (block != 2) block1();
  967. }
  968. lastwork = iter.classical_unit_title;
  969. }
  970. block3();
  971. if (media == 'Vinyl') {
  972. let c = iter.tracknumber[0].toUpperCase();
  973. if (lastside != undefined && c != lastside) description += '\n';
  974. lastside = c;
  975. }
  976. }
  977. for (iter of tracks.sort(function(a, b) {
  978. var d = a.discnumber - b.discnumber;
  979. var t = a.tracknumber - b.tracknumber;
  980. return isNaN(d) || d == 0 ? isNaN(t) ? a.tracknumber.localeCompare(b.tracknumber) : t : d;
  981. })) {
  982. let title = '';
  983. let ttwidth = vinyl_trackwidth || Math.max((iter.totaltracks || tracks.length).toString().length, 2);
  984. if (prefs.tracklist_style == 1) {
  985. // STYLE 1 ----------------------------------------
  986. prologue('[size=2]', '[/size]\n');
  987. track = '[b][color=' + prefs.tracklist_tracknumber_color + ']';
  988. track += isNaN(parseInt(iter.tracknumber)) ? iter.tracknumber : iter.tracknumber.padStart(ttwidth, '0');
  989. track += '[/color][/b]' + prefs.title_separator;
  990. if (iter.track_artist && !iter.classical_unit_performer) {
  991. title = '[color=' + prefs.tracklist_artist_color + ']' + iter.track_artist + '[/color] - ';
  992. }
  993. title += iter.classical_title || iter.title;
  994. if (iter.composer && composer_emphasis && !iter.classical_unit_composer) {
  995. title = title.concat(' [color=', prefs.tracklist_composer_color, '](', iter.composer, ')[/color]');
  996. }
  997. description += track + title + ' [i][color=' + prefs.tracklist_duration_color +'][' +
  998. make_time_string(iter.duration) + '][/color][/i]';
  999. } else if (prefs.tracklist_style == 2) {
  1000. // STYLE 2 ----------------------------------------
  1001. prologue('[size=2][pre]', '[/pre][/size]');
  1002. track = isNaN(parseInt(iter.tracknumber)) ? iter.tracknumber : iter.tracknumber.padStart(ttwidth, '0');
  1003. track += prefs.title_separator;
  1004. if (iter.track_artist && !iter.classical_unit_performer) title = iter.track_artist + ' - ';
  1005. title += iter.classical_title || iter.title;
  1006. if (iter.composer && composer_emphasis && !iter.classical_unit_composer) {
  1007. title = title.concat(' (', iter.composer, ')');
  1008. }
  1009. dur = '[' + make_time_string(iter.duration) + ']';
  1010. let l = 0, width = prefs.max_tracklist_width - track.length - dur.length - 1;
  1011. while (title.length > 0) {
  1012. let j = width;
  1013. if (title.length > width) {
  1014. while (j > 0 && title[j] != ' ') { --j }
  1015. if (j <= 0) { j = width }
  1016. }
  1017. let left = title.slice(0, j).trim();
  1018. if (++l <= 1) {
  1019. description = description.concat(track, left.padEnd(width, ' '), ' ', dur);
  1020. width = prefs.max_tracklist_width - track.length - 2;
  1021. } else {
  1022. description = description.concat('\n', ' '.repeat(track.length), left);
  1023. }
  1024. title = title.slice(j).trim();
  1025. }
  1026. }
  1027. }
  1028. if (prefs.tracklist_style == 1) {
  1029. description += '\n\n' + div[0].repeat(10) + '\n[color=' + prefs.tracklist_duration_color +
  1030. ']Total time: [i]' + make_time_string(total_time) + '[/i][/color][/size]';
  1031. } else if (prefs.tracklist_style == 2) {
  1032. dur = '[' + make_time_string(total_time) + ']';
  1033. description = description.concat('\n\n', div[0].repeat(32).padStart(prefs.max_tracklist_width));
  1034. description = description.concat('\n', 'Total time:'.padEnd(prefs.max_tracklist_width - dur.length), dur);
  1035. description = description.concat('[/pre][/size]');
  1036. }
  1037. }
  1038.  
  1039. function getChanString(n) {
  1040. const chanmap = [
  1041. 'mono',
  1042. 'stereo',
  1043. '2.1',
  1044. '4.0 surround sound',
  1045. '5.0 surround sound',
  1046. '5.1 surround sound',
  1047. '7.0 surround sound',
  1048. '7.1 surround sound',
  1049. ];
  1050. return n >= 1 && n <= 8 ? chanmap[n - 1] : n + 'chn surround sound';
  1051. }
  1052.  
  1053. function init_from_url_music(url) {
  1054. if (typeof url != 'string') return false;
  1055. var parser, html, remasterYear, channels = 2, label, composer, sr = 44.1, description = '',
  1056. compiler, producer, totaltracks, totaldiscs = null;
  1057. const yearMatch = /\b(\d{4})\b/;
  1058. if (url.toLowerCase().indexOf('qobuz.com') >= 0) {
  1059. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1060. if (response.readyState != 4 || response.status != 200) return;
  1061. parser = new DOMParser();
  1062. html = parser.parseFromString(response.responseText, "text/html");
  1063. if (html == null) return;
  1064.  
  1065. let artist = html.querySelector('h2.album-meta__artist').textContent.trim();
  1066. let album = html.querySelector('h1.album-meta__title').textContent.trim();
  1067. let genre;
  1068. ref = html.querySelectorAll('div.album-meta > ul > li');
  1069. if (ref != null) ref.forEach(function(k) {
  1070. if (/\bGenre\b/.test(k.textContent)) genre = k.children[k.children.length - 1].textContent.trim();
  1071. });
  1072. ref = html.querySelector('div.album-meta > ul > li:first-of-type');
  1073. if (ref != null && (matches = ref.textContent.match(yearMatch)) != null) remasterYear = parseInt(matches[1]);
  1074. ref = html.querySelector('p.album-about__copyright');
  1075. let albumYear = ref != null && yearMatch.exec(ref.textContent) != null ? parseInt(RegExp.$1) : remasterYear;
  1076. ref = html.querySelectorAll('ul.album-about__items > li');
  1077. if (ref != null) ref.forEach(function(k) {
  1078. if (/^(?:Label)\b/.test(k.textContent)) label = k.children[0].textContent.trim()
  1079. else if (/^(?:Composer|Compositeur)\b/.test(k.textContent)) composer = k.children[0].textContent.trim()
  1080. if (/\b(\d+)\s*(?:dis[ck](?:s\b|\(s\))?|disco(?:s\b|\(s\))?|disque(?:s\|\(s\))?)/i.exec(k.textContent) != null) {
  1081. totaldiscs = parseInt(RegExp.$1);
  1082. }
  1083. if (/\b(\d+)\s*(?:track(?:s\b|\(s\))?|pist[ae](?:s\b|\(s\))?|tracce)/i.exec(k.textContent) != null) {
  1084. totaltracks = parseInt(RegExp.$1);
  1085. }
  1086. });
  1087. if (/\bVarious\b/.test(composer)) composer = null;
  1088. let bd = 16;
  1089. ref = html.querySelectorAll('span.album-quality__info');
  1090. if (ref != null) ref.forEach(function(k) {
  1091. if (/\b([\d\.,]+)\s*kHz\b/.exec(k.textContent) != null) sr = parseFloat(RegExp.$1.replace(/,/g, '.'));
  1092. if (/\b(\d+)[\-\s]?Bits?\b/i.exec(k.textContent) != null) bd = parseInt(RegExp.$1);
  1093. });
  1094. ref = html.querySelectorAll('section#description > p');
  1095. if (ref != null) ref.forEach(k => { desc_extract(k) });
  1096. function desc_extract(node) {
  1097. if (!node.textContent.trim()) return;
  1098. for (var i of node.childNodes) {
  1099. if (i.nodeType == 3 || i.nodeName == 'P') {
  1100. //if (i.length < 10) continue;
  1101. description += i.textContent.replace(/[\n\r]+/g, '');
  1102. } else if (i.nodeName == 'BR' || i.nodeName == 'HR') {
  1103. description += '\n';
  1104. } else if (i.nodeName == 'B' || i.nodeName == 'STRONG') {
  1105. description += '[b]' + i.textContent + '[/b]';
  1106. } else if (i.nodeName == 'I' || i.nodeName == 'EM') {
  1107. description += '[i]' + i.textContent + '[/i]';
  1108. } else if (i.nodeName == 'A') {
  1109. description += '[url=' + i.href + ']' + i.textContent.trim() + '[/url]';
  1110. }
  1111. }
  1112. description += '\n';
  1113. }
  1114. if (description) description = '[quote]' + description.trim().replace(/\n/g, '\x1C').replace(/\r/g, '\x1D') + '[/quote]';
  1115. ref = html.querySelectorAll('div.track > div.track__items');
  1116. if (ref != null) ref.forEach(function(k) {
  1117. let discsubtitle = null, track_artist = null;
  1118. let discnumber = k.parentNode.parentNode.parentNode.querySelector('p.player__work');
  1119. discnumber = discnumber != null && /^DIS[CK]\s*(\d+)$/i.exec(discnumber.textContent) != null ?
  1120. parseInt(RegExp.$1) : null;
  1121. if (discnumber > totaldiscs) totaldisc = discnumber;
  1122. let tracknumber = parseInt(k.querySelector('span[itemprop="position"]').textContent.trim());
  1123. let title = k.querySelector('span.track__item--name').textContent.trim();
  1124. let duration = k.querySelector('span.track__item--duration').textContent;
  1125. if (/\b(?:(\d+):)?(\d{1,2}):(\d{2})\b/.exec(duration)) {
  1126. duration = RegExp.$1 * 60 ** 2 + parseInt(RegExp.$2) * 60 + parseInt(RegExp.$3);
  1127. }
  1128. track = [
  1129. artist,
  1130. album,
  1131. albumYear,
  1132. remasterYear,
  1133. label,
  1134. null,
  1135. 'lossless',
  1136. 'FLAC',
  1137. null,
  1138. null,
  1139. bd,
  1140. sr * 1000,
  1141. channels,
  1142. 'WEB',
  1143. genre,
  1144. discnumber,
  1145. totaldiscs,
  1146. discsubtitle,
  1147. tracknumber,
  1148. totaltracks,
  1149. title,
  1150. track_artist,
  1151. null,
  1152. composer,
  1153. null,
  1154. null,
  1155. compiler,
  1156. producer,
  1157. duration,
  1158. null,
  1159. null,
  1160. null,
  1161. response.finalUrl,
  1162. null,
  1163. description,
  1164. ];
  1165. tracks.push(track.join('\x1E'));
  1166. });
  1167. clipBoard.value = tracks.join('\n');
  1168. fill_from_text_music();
  1169. } });
  1170. } else if (url.toLowerCase().indexOf('highresaudio.com') >= 0) {
  1171. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1172. if (response.readyState != 4 || response.status != 200) return;
  1173. parser = new DOMParser();
  1174. html = parser.parseFromString(response.responseText, "text/html");
  1175. if (html == null) return;
  1176.  
  1177. let artist = html.querySelector('h1 > span.artist').textContent.trim();
  1178. let album = html.getElementById('h1-album-title').firstChild.textContent.trim();
  1179. let albumYear, genres = [];
  1180. ref = html.querySelectorAll('div.album-col-info-data > div > p');
  1181. if (ref != null) ref.forEach(function(k) {
  1182. if (/\b(?:Genre|Subgenre)\b/i.test(k.firstChild.textContent)) genres.push(k.lastChild.textContent.trim());
  1183. if (/\b(?:Label)\b/i.test(k.firstChild.textContent)) label = k.lastChild.textContent.trim();
  1184. if (/\b(?:Album[\s\-]Release)\b/i.test(k.firstChild.textContent) && yearMatch.exec(k.lastChild.textContent) != null) {
  1185. albumYear = parseInt(RegExp.$1);
  1186. }
  1187. if (/\b(?:HRA[\s\-]Release)\b/i.test(k.firstChild.textContent) && yearMatch.exec(k.lastChild.textContent) != null) {
  1188. remasterYear = parseInt(RegExp.$1);
  1189. }
  1190. });
  1191. ref = html.querySelectorAll('td.col-format');
  1192. if (ref != null) ref.forEach(function(k) {
  1193. if (/^FLAC\s*(\d+)\b/.exec(k.textContent) != null) sr = parseFloat(RegExp.$1.replace(/,/g, '.'));
  1194. });
  1195. ref = html.querySelectorAll('div#albumtab-info > p');
  1196. if (ref != null) ref.forEach(k => { desc_extract(k) });
  1197. function desc_extract(node) {
  1198. if (!node.textContent.trim()) return;
  1199. for (var i of node.childNodes) {
  1200. if (i.nodeType == 3 || i.nodeName == 'P') {
  1201. //if (i.length < 10) continue;
  1202. description += i.textContent.replace(/[\n\r]+/g, '');
  1203. } else if (i.nodeName == 'BR' || i.nodeName == 'HR') {
  1204. description += '\n';
  1205. } else if (i.nodeName == 'B' || i.nodeName == 'STRONG') {
  1206. description += '[b]' + i.textContent + '[/b]';
  1207. } else if (i.nodeName == 'I' || i.nodeName == 'EM') {
  1208. description += '[i]' + i.textContent + '[/i]';
  1209. } else if (i.nodeName == 'A') {
  1210. description += '[url=' + i.href + ']' + i.textContent.trim() + '[/url]';
  1211. }
  1212. }
  1213. description += '\n';
  1214. }
  1215. if (description) description = description.trim().replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  1216. ref = html.querySelectorAll('ul.playlist > li.pltrack');
  1217. totaltracks = ref != null && ref.length;
  1218. if (ref != null) ref.forEach(function(k) {
  1219. let discsubtitle = k, track_artist, discnumber = null;
  1220. while ((discsubtitle = discsubtitle.previousElementSibling) != null) {
  1221. if (discsubtitle.nodeName == 'LI' && discsubtitle.className == 'plinfo') {
  1222. discsubtitle = discsubtitle.textContent.replace(/\s*:$/, '').trim();
  1223. if (/\b(?:DIS[CK]|Volume|CD)\s*(\d+)\b/i.exec(discsubtitle)) discnumber = parseInt(RegExp.$1);
  1224. break;
  1225. }
  1226. }
  1227. if (discnumber > totaldiscs) totaldisc = discnumber;
  1228. let tracknumber = parseInt(k.querySelector('span.track').textContent.trim());
  1229. let title = k.querySelector('span.title').textContent.trim();
  1230. let duration = k.querySelector('span.time').textContent;
  1231. if (/\b(?:(\d+):)?(\d{1,2}):(\d{2})\b/.exec(duration)) {
  1232. duration = RegExp.$1 * 60 ** 2 + parseInt(RegExp.$2) * 60 + parseInt(RegExp.$3);
  1233. }
  1234. track = [
  1235. artist,
  1236. album,
  1237. albumYear,
  1238. remasterYear,
  1239. label,
  1240. null,
  1241. 'lossless',
  1242. 'FLAC',
  1243. null,
  1244. null,
  1245. 24,
  1246. sr * 1000,
  1247. channels,
  1248. 'WEB',
  1249. genres.join(', '),
  1250. discnumber,
  1251. totaldiscs,
  1252. null, //discsubtitle,
  1253. tracknumber,
  1254. totaltracks,
  1255. title,
  1256. track_artist,
  1257. null,
  1258. composer,
  1259. null,
  1260. null,
  1261. compiler,
  1262. producer,
  1263. duration,
  1264. null,
  1265. null,
  1266. null,
  1267. response.finalUrl,
  1268. null,
  1269. description,
  1270. ];
  1271. tracks.push(track.join('\x1E'));
  1272. });
  1273. clipBoard.value = tracks.join('\n');
  1274. fill_from_text_music();
  1275. } });
  1276. }
  1277. }
  1278.  
  1279. function fetch_image_from_store(response) {
  1280. if (response.readyState != 4 || !response.responseText) return;
  1281. ref = document.getElementById('image');
  1282. var parser = new DOMParser();
  1283. var html = parser.parseFromString(response.responseText, "text/html");
  1284. if (html == null) return;
  1285. if (response.finalUrl.toLowerCase().indexOf('qobuz.com') >= 0
  1286. && (ref = html.querySelector('div.album-cover > img')) != null) set_image(ref.src);
  1287. if (response.finalUrl.toLowerCase().indexOf('highresaudio.com') >= 0
  1288. && (ref = html.querySelector('div.albumbody > img.cover[data-pin-media]')) != null) {
  1289. set_image(ref.dataset.pinMedia);
  1290. }
  1291. if (response.finalUrl.toLowerCase().indexOf('bandcamp.com') >= 0
  1292. && (ref = html.querySelector('div#tralbumArt > a.popupImage')) != null) set_image(ref.href);
  1293. if (response.finalUrl.toLowerCase().indexOf('7digital.com') >= 0
  1294. && (ref = html.querySelector('span.release-packshot-image > img[itemprop="image"]')) != null) {
  1295. set_image(ref.src);
  1296. }
  1297. if (response.finalUrl.toLowerCase().indexOf('hdtracks.com') >= 0
  1298. && (ref = html.querySelector('p.product-image > img')) != null) set_image(ref.src);
  1299. if (response.finalUrl.toLowerCase().indexOf('discogs.com') >= 0
  1300. && (ref = html.querySelector('div#view_images > p:first-of-type > span > img')) != null) set_image(ref.src);
  1301. if (response.finalUrl.toLowerCase().indexOf('junodownload.com') >= 0
  1302. && (ref = html.querySelector('a.productimage')) != null) set_image(ref.href);
  1303. if (response.finalUrl.toLowerCase().indexOf('supraphonline.cz') >= 0
  1304. && (ref = html.querySelector('div.sexycover > img')) != null) set_image(ref.src.replace(/\?\d+$/, ''));
  1305. }
  1306. }
  1307.  
  1308. function fill_from_text_apps() {
  1309. if (/^https?:\/\//i.test(clipBoard.value)) return false;
  1310. var parser, html, description, tags = new TagManager();
  1311. if (clipBoard.value.toLowerCase().indexOf('//sanet') >= 0) {
  1312. GM_xmlhttpRequest({ method: 'GET', url: clipBoard.value, onload: function(response) {
  1313. if (response.readyState != 4 || response.status != 200) return;
  1314. parser = new DOMParser();
  1315. html = parser.parseFromString(response.responseText, "text/html");
  1316.  
  1317. i = html.querySelector('h1.item_title > span');
  1318. if (i != null && element_writable(ref = document.getElementById('title'))) {
  1319. ref.value = i.textContent.replace(/\(x64\)$/i, '(64-bit)').replace(/\bBuild\s+(\d+)/, 'build $1').
  1320. replace(/\bMultilingual\b/, 'multilingual').replace(/\bMultilanguage\b/, 'multilanguage');
  1321. }
  1322.  
  1323. i = html.querySelector('section.descr');
  1324. if (i != null) {
  1325. description = '';
  1326. ref = html.querySelector('section.descr > div.release-info');
  1327. if (ref != null) var releaseInfo = ref.textContent.trim();
  1328. desc_extract(i);
  1329. ref = html.querySelector('div.txtleft > a');
  1330. if (ref != null) description += '\n\n[b]Product page:[/b]\n[url]' + de_anonymize(ref.href) + '[/url]';
  1331. write_description(description);
  1332.  
  1333. function desc_extract(node) {
  1334. for (var i of node.childNodes) {
  1335. if (i.nodeType == 3) {
  1336. if (i.length < 5) continue;
  1337. description += i.textContent.trim();
  1338. } else if (i.nodeName == 'BR' || i.nodeName == 'HR') {
  1339. description += '\n';
  1340. } else if (i.nodeName == 'LABEL') {
  1341. description += '\n\n[b]' + i.textContent.trim() + '[/b]\n';
  1342. } else if (i.nodeName == 'A') {
  1343. if (i.classList.contains('mfp-image')) {
  1344. //rehost_imgs([de_anonymize(i.href)]).then(new_url => {
  1345. // description += '\n\n[img]' + new_url + '[/img]'
  1346. //}).catch(function() {
  1347. // description += '\n\n[img]' + de_anonymize(i.href) + '[/img]'
  1348. //});
  1349. description += '\n\n[img]' + de_anonymize(i.href) + '[/img]'
  1350. } else {
  1351. description += '[url=' + de_anonymize(i.href) + ']' + i.textContent.trim() + '[/url]';
  1352. }
  1353. } else if (i.nodeName == 'B' || i.nodeName == 'STRONG') {
  1354. description += '[b]' + i.textContent + '[/b]';
  1355. } else if (i.nodeName == 'I') {
  1356. description += '[i]' + i.textContent + '[/i]';
  1357. } else if (i.nodeName == 'DIV') {
  1358. if (i.classList.contains('scrpad') || i.classList.contains('aleft')) {
  1359. desc_extract(i);
  1360. description += '\n';
  1361. }
  1362. }
  1363. }
  1364. }
  1365. }
  1366.  
  1367. i = html.querySelector('section.descr > div.center > a.mfp-image');
  1368. if (i != null) {
  1369. set_image(i.href);
  1370. } else {
  1371. i = html.querySelector('section.descr > div.center > img[data-src]');
  1372. if (i != null) set_image(i.dataset.src);
  1373. }
  1374.  
  1375. var cat = html.querySelector('a.cat:last-of-type > span');
  1376. if (cat != null) {
  1377. if (cat.textContent.toLowerCase() == 'windows') {
  1378. tags.add('apps.windows');
  1379. if (releaseInfo && /\bx64\b/i.test(releaseInfo)) tags.add('win64');
  1380. if (releaseInfo && /\bx86\b/i.test(releaseInfo)) tags.add('win32');
  1381. }
  1382. if (cat.textContent.toLowerCase() == 'macos') tags.add('apps.mac');
  1383. if (cat.textContent.toLowerCase() == 'linux' || cat.textContent.toLowerCase() == 'unix') tags.add('apps.linux');
  1384. if (cat.textContent.toLowerCase() == 'android') tags.add('apps.android');
  1385. if (cat.textContent.toLowerCase() == 'ios') tags.add('apps.ios');
  1386. }
  1387. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  1388. ref.value = tags.toString();
  1389. }
  1390. }, });
  1391. return true;
  1392. }
  1393. return false;
  1394.  
  1395. function de_anonymize(uri) {
  1396. return uri ? uri.replace('http://anonymz.com/?', '').replace('https://anonymz.com/?', '') : null;
  1397. }
  1398.  
  1399. function html2php(str) {
  1400. return str ? str.replace(/\<b\>/ig, '[b]').replace(/\<\/b\>/ig, '[/b]').
  1401. replace(/\<i\>/ig, '[i]').replace(/\<\/i\>/ig, '[/i]') : null;
  1402. }
  1403. }
  1404.  
  1405. function fill_from_text_books() {
  1406. if (/^https?:\/\//i.test(clipBoard.value)) return false;
  1407. var parser, html, description, tags = new TagManager();
  1408. if (clipBoard.value.toLowerCase().indexOf('martinus.cz') >= 0 || clipBoard.value.toLowerCase().indexOf('martinus.sk') >= 0) {
  1409. GM_xmlhttpRequest({ method: 'GET', url: clipBoard.value, onload: function(response) {
  1410. if (response.readyState != 4 || response.status != 200) return;
  1411. parser = new DOMParser();
  1412. html = parser.parseFromString(response.responseText, "text/html");
  1413.  
  1414. function get_detail(x, y) {
  1415. var ref = html.querySelector('section#details > div > div > div:first-of-type > div:nth-child(' +
  1416. x + ') > dl:nth-child(' + y + ') > dd');
  1417. return ref != null ? ref.textContent.trim() : null;
  1418. }
  1419.  
  1420. i = html.querySelectorAll('article > ul > li > a');
  1421. if (i != null && element_writable(ref = document.getElementById('title'))) {
  1422. description = join_authors(i);
  1423. i = html.querySelector('article > h1');
  1424. if (i != null) description += ' - ' + i.textContent.trim();
  1425. i = html.querySelector('div.bar.mb-medium > div:nth-child(1) > dl > dd > span');
  1426. if (i != null && (matches = i.textContent.match(/\b(\d{4})\b/)) != null) description += ' (' + matches[1] + ')';
  1427. ref.value = description;
  1428. }
  1429.  
  1430. description = '[quote]';
  1431. i = html.querySelector('section#description > div');
  1432. if (i != null) {
  1433. desc_extract(i);
  1434.  
  1435. function desc_extract(node) {
  1436. for (var i of node.childNodes) {
  1437. if (i.nodeType == 3 || i.nodeName == 'P') {
  1438. //if (i.length < 10) continue;
  1439. description += i.textContent;
  1440. } else if (i.nodeName == 'BR' || i.nodeName == 'HR') {
  1441. description += '\n';
  1442. } else if (i.nodeName == 'B' || i.nodeName == 'STRONG') {
  1443. description += '[b]' + i.textContent + '[/b]';
  1444. } else if (i.nodeName == 'I') {
  1445. description += '[i]' + i.textContent + '[/i]';
  1446. } else if (i.nodeName == 'DIV') {
  1447. //desc_extract(i);
  1448. //description += '\n';
  1449. }
  1450. }
  1451. }
  1452. }
  1453.  
  1454. description += '[/quote]';
  1455. let details = html.querySelectorAll('section#details > div > div > div:first-of-type > div > dl');
  1456. const translation_map = [
  1457. [/\b(?:originál)/i, 'Original title'],
  1458. [/\b(?:datum|dátum|rok)\b/i, 'Release date'],
  1459. [/\b(?:katalog|katalóg)/i, 'Catalogue #'],
  1460. [/\b(?:stran|strán)\b/i, 'Page count'],
  1461. [/\bjazyk/i, 'Language'],
  1462. [/\b(?:nakladatel|vydavatel)/i, 'Publisher'],
  1463. [/\b(?:doporuč|ODPORÚČ)/i, 'Age rating'],
  1464. ];
  1465. if (details != null) details.forEach(function(detail) {
  1466. var lbl = detail.children[0].textContent.trim();
  1467. var val = detail.children[1].textContent.trim();
  1468. if (/\b(?:rozm)/i.test(lbl) || /\b(?:vazba|vázba)\b/i.test(lbl)) return;
  1469. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  1470. if (/\b(?:ISBN)\b/i.test(lbl)) {
  1471. val = '[url=https://www.worldcat.org/isbn/' + detail.children[1].textContent.trim() +
  1472. ']' + detail.children[1].textContent.trim() + '[/url]';
  1473. // } else if (/\b(?:ISBN)\b/i.test(lbl)) {
  1474. // val = '[url=https://www.goodreads.com/search/search?q=' + detail.children[1].textContent.trim() +
  1475. // '&search_type=books]' + detail.children[1].textContent.trim() + '[/url]';
  1476. }
  1477. description += '\n[b]' + lbl + ':[/b] ' + val;
  1478. });
  1479. description += '\n[b]More info:[/b] ' + response.finalUrl;
  1480. write_description(description);
  1481.  
  1482. if ((i = html.querySelector('a.mj-product-preview > img')) != null) {
  1483. set_image(i.src.replace(/\?.*/, ''));
  1484. } else if ((i = html.querySelector('head > meta[property="og:image"]')) != null) {
  1485. set_image(i.content.replace(/\?.*/, ''));
  1486. }
  1487.  
  1488. var cat = html.querySelectorAll('dd > ul > li > a');
  1489. if (cat != null) cat.forEach(x => { tags.add(x.textContent) });
  1490. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  1491. ref.value = tags.toString();
  1492. }
  1493. }, });
  1494. return true;
  1495. } else if (clipBoard.value.toLowerCase().indexOf('goodreads.com') >= 0) {
  1496. GM_xmlhttpRequest({ method: 'GET', url: clipBoard.value, onload: function(response) {
  1497. if (response.readyState != 4 || response.status != 200) return;
  1498. parser = new DOMParser();
  1499. html = parser.parseFromString(response.responseText, "text/html");
  1500.  
  1501. i = html.querySelectorAll('a.authorName > span');
  1502. if (i != null && element_writable(ref = document.getElementById('title'))) {
  1503. description = join_authors(i);
  1504. i = html.querySelector('h1#bookTitle');
  1505. if (i != null) description += ' - ' + i.textContent.trim();
  1506. i = html.querySelector('div#details > div#row:nth-child(2)');
  1507. if (i != null && (matches = i.textContent.match(/\b(\d{4})\b/)) != null) description += ' (' + matches[1] + ')';
  1508. ref.value = description;
  1509. }
  1510.  
  1511. description = '[quote]';
  1512. i = html.querySelector('div#description > span:last-of-type');
  1513. if (i != null) {
  1514. desc_extract(i);
  1515.  
  1516. function desc_extract(node) {
  1517. for (var i of node.childNodes) {
  1518. if (i.nodeType == 3 || i.nodeName == 'P') {
  1519. //if (i.length < 10) continue;
  1520. description += i.textContent;
  1521. } else if (i.nodeName == 'BR' || i.nodeName == 'HR') {
  1522. description += '\n';
  1523. } else if (i.nodeName == 'B' || i.nodeName == 'STRONG') {
  1524. description += '[b]' + i.textContent + '[/b]';
  1525. } else if (i.nodeName == 'I') {
  1526. description += '[i]' + i.textContent + '[/i]';
  1527. } else if (i.nodeName == 'DIV') {
  1528. //desc_extract(i);
  1529. //description += '\n';
  1530. }
  1531. }
  1532. }
  1533. }
  1534. description += '[/quote]';
  1535.  
  1536. function strip(str) {
  1537. return typeof str == 'string' ?
  1538. str.replace(/\s{2,}/g, ' ').replace(/[\n\r]+/, '').replace(/\s*\.{3}(?:less|more)\b/g, '').trim() : null;
  1539. }
  1540.  
  1541. i = html.querySelectorAll('div#details > div.row');
  1542. if (i != null) i.forEach(k => { description += '\n' + strip(k.innerText) });
  1543. description += '\n';
  1544.  
  1545. let details = html.querySelectorAll('div#bookDataBox > div.clearFloats');
  1546. for (var detail of details) {
  1547. var lbl = detail.children[0].textContent.trim();
  1548. var val = strip(detail.children[1].textContent);
  1549. if (/\b(?:ISBN)\b/i.test(lbl) && ((matches = val.match(/\b(\d{13})\b/)) != null
  1550. || (matches = val.match(/\b(\d{10})\b/)) != null)) {
  1551. val = '[url=https://www.worldcat.org/isbn/' + matches[1] + ']' + strip(detail.children[1].textContent) + '[/url]';
  1552. }
  1553. description += '\n[b]' + lbl + ':[/b] ' + val;
  1554. }
  1555. description += '\n[b]More info:[/b] ' + response.finalUrl;
  1556. write_description(description);
  1557.  
  1558. if ((i = html.querySelector('div.editionCover > img')) != null) {
  1559. set_image(i.src.replace(/\?.*/, ''));
  1560. }
  1561.  
  1562. var cat = html.querySelectorAll('div.elementList > div.left');
  1563. if (cat != null) cat.forEach(x => { tags.add(x.textContent.trim()) });
  1564. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  1565. ref.value = tags.toString();
  1566. }
  1567. }, });
  1568. return true;
  1569. } else if (clipBoard.value.toLowerCase().indexOf('databazeknih.cz') >= 0) {
  1570. let url = clipBoard.value;
  1571. if (url.toLowerCase().indexOf('show=alldesc') < 0) {
  1572. if (!url.includes('?')) { url += '?show=alldesc' } else { url += '&show=alldesc' }
  1573. }
  1574. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1575. if (response.readyState != 4 || response.status != 200) return;
  1576. parser = new DOMParser();
  1577. html = parser.parseFromString(response.responseText, "text/html");
  1578.  
  1579. i = html.querySelectorAll('span[itemprop="author"] > a');
  1580. if (i != null && element_writable(ref = document.getElementById('title'))) {
  1581. description = join_authors(i);
  1582. i = html.querySelector('h1[itemprop="name"]');
  1583. if (i != null) description += ' - ' + i.textContent.trim();
  1584. i = html.querySelector('span[itemprop="datePublished"]');
  1585. if (i != null && (matches = i.textContent.match(/\b(\d{4})\b/)) != null) description += ' (' + matches[1] + ')';
  1586. ref.value = description;
  1587. }
  1588.  
  1589. description = '[quote]';
  1590. i = html.querySelector('p[itemprop="description"]');
  1591. if (i != null) desc_extract(i);
  1592.  
  1593. function desc_extract(node) {
  1594. for (var i of node.childNodes) {
  1595. if (i.nodeType == 3 || i.nodeName == 'P') {
  1596. //if (i.length < 10) continue;
  1597. description += i.textContent.trim();
  1598. } else if (i.nodeName == 'BR' || i.nodeName == 'HR') {
  1599. description += '\n';
  1600. } else if (i.nodeName == 'B' || i.nodeName == 'STRONG') {
  1601. description += '[b]' + i.textContent + '[/b]';
  1602. } else if (i.nodeName == 'I') {
  1603. description += '[i]' + i.textContent + '[/i]';
  1604. } else if (i.nodeName == 'DIV') {
  1605. //desc_extract(i);
  1606. //description += '\n';
  1607. }
  1608. }
  1609. }
  1610. description += '[/quote]';
  1611.  
  1612. let details = html.querySelectorAll('table.bdetail tr');
  1613. const translation_map = [
  1614. [/\b(?:orig)/i, 'Original title'],
  1615. [/\b(?:série)\b/i, 'Series'],
  1616. [/\b(?:vydáno)\b/i, 'Released'],
  1617. [/\b(?:stran)\b/i, 'Page count'],
  1618. [/\b(?:jazyk)\b/i, 'Language'],
  1619. [/\b(?:překlad)/i, 'Translation'],
  1620. [/\b(?:autor obálky)\b/i, 'Cover author'],
  1621. ];
  1622. if (details != null) details.forEach(function(detail) {
  1623. var lbl = detail.children[0].textContent.trim();
  1624. var val = detail.children[1].textContent.trim();
  1625. if (/(?:žánr|\bvazba)\b/i.test(lbl)) return;
  1626. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  1627. if (/\b(?:ISBN)\b/i.test(lbl) && /\b(\d+(?:-\d+)*)\b/.exec(val) != null) {
  1628. val = '[url=https://www.worldcat.org/isbn/' + RegExp.$1.replace(/-/g, '') +
  1629. ']' + detail.children[1].textContent.trim() + '[/url]';
  1630. }
  1631. description += '\n[b]' + lbl + '[/b] ' + val;
  1632. });
  1633. description += '\n[b]More info:[/b] ' + response.finalUrl.replace(/\?.*/, '');
  1634. write_description(description);
  1635.  
  1636. if ((i = html.querySelector('div#icover_mid > a')) != null) set_image(i.href.replace(/\?.*/, ''));
  1637. if ((i = html.querySelector('div#lbImage')) != null
  1638. && (matches = i.style.backgroundImage.match(/\burl\("(.*)"\)/i)) != null) {
  1639. set_image(matches[1].replace(/\?.*/, ''));
  1640. }
  1641.  
  1642. var cat = html.querySelectorAll('h5[itemprop="genre"] > a');
  1643. if (cat != null) cat.forEach(x => { tags.add(x.textContent.trim()) });
  1644. cat = html.querySelectorAll('a.tag');
  1645. if (cat != null) cat.forEach(x => { tags.add(x.textContent.trim()) });
  1646. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  1647. ref.value = tags.toString();
  1648. }
  1649. }, });
  1650. return true;
  1651. }
  1652. return false;
  1653.  
  1654. function join_authors(nodeList) {
  1655. if (typeof nodeList != 'object') return null;
  1656. var authors = [];
  1657. nodeList.forEach(k => { authors.push(k.textContent.trim()) });
  1658. return authors.join(' & ');
  1659. }
  1660. }
  1661.  
  1662. function preview(n) {
  1663. if (!prefs.auto_preview) return;
  1664. var btn = document.querySelector('input.button_preview_' + n + '[type="button"][value="Preview"]');
  1665. if (btn != null) btn.click();
  1666. }
  1667.  
  1668. function write_description(desc) {
  1669. if (typeof desc != 'string') return;
  1670. if (element_writable(ref = document.getElementById('desc'))) ref.value = desc;
  1671. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  1672. if (ref.textLength > 0) ref.value += '\n\n';
  1673. ref.value += desc;
  1674. }
  1675. }
  1676.  
  1677. function set_image(url) {
  1678. var image = document.getElementById('image');
  1679. if (!element_writable(image)) return false;
  1680. image.value = url;
  1681.  
  1682. if (prefs.auto_preview_cover) {
  1683. child = document.getElementById('cover preview');
  1684. if (child == null) {
  1685. elem = document.createElement('div');
  1686. elem.style.paddingTop = '10px';
  1687. child = document.createElement('img');
  1688. child.id = 'cover preview';
  1689. child.style.width = '90%';
  1690. elem.append(child);
  1691. image.parentNode.previousElementSibling.append(elem);
  1692. }
  1693. child.src = url;
  1694. }
  1695. // Re-Host to PTPIMG
  1696. if (prefs.auto_rehost_cover) {
  1697. var rehost_btn = document.querySelector('input.rehost_it_cover[type="button"]');
  1698. if (rehost_btn != null) {
  1699. rehost_btn.click();
  1700. } else {
  1701. var pr = rehost_imgs([url]);
  1702. if (pr != null) pr.then(new_urls => { image.value = new_urls[0] });
  1703. }
  1704. }
  1705. }
  1706.  
  1707. // PTPIMG rehoster taken from `PTH PTPImg It`
  1708. function rehost_imgs(urls) {
  1709. if (!Array.isArray(urls)) return null;;
  1710. var config = JSON.parse(window.localStorage.ptpimg_it);
  1711. return config.api_key ? new Promise(ptpimg_upload_urls).catch(m => { alert(m) }) : null;
  1712.  
  1713. function ptpimg_upload_urls(resolve, reject) {
  1714. const boundary = 'NN-GGn-PTPIMG';
  1715. var data = '--' + boundary + "\n";
  1716. data += 'Content-Disposition: form-data; name="link-upload"\n\n';
  1717. data += urls.map(function(url) {
  1718. return url.toLowerCase().indexOf('://reho.st/') < 0 && url.toLowerCase().indexOf('discogs.com') >= 0 ?
  1719. 'https://reho.st/' + url : url;
  1720. }).join('\n') + '\n';
  1721. data += '--' + boundary + '\n';
  1722. data += 'Content-Disposition: form-data; name="api_key"\n\n';
  1723. data += config.api_key + '\n';
  1724. data += '--' + boundary + '--';
  1725. GM_xmlhttpRequest({
  1726. method: 'POST',
  1727. url: 'https://ptpimg.me/upload.php',
  1728. responseType: 'json',
  1729. headers: {
  1730. 'Content-type': 'multipart/form-data; boundary=' + boundary,
  1731. },
  1732. data: data,
  1733. onload: response => {
  1734. if (response.status != 200) reject('Response error ' + response.status);
  1735. resolve(response.response.map(item => 'https://ptpimg.me/' + item.code + '.' + item.ext));
  1736. },
  1737. });
  1738. }
  1739. }
  1740.  
  1741. function element_writable(elem) { return elem != null && !elem.disabled && (overwrite || !elem.value) }
  1742. }
  1743.  
  1744. function add_artist() { exec(function() { AddArtistField() }) }
  1745.  
  1746. function array_homogenous(arr) { return arr.every(k => k === arr[0]) }
  1747.  
  1748. function exec(fn) {
  1749. let script = document.createElement('script');
  1750. script.type = 'application/javascript';
  1751. script.textContent = '(' + fn + ')();';
  1752. document.body.appendChild(script); // run the script
  1753. document.body.removeChild(script); // clean up
  1754. }
  1755.  
  1756. function make_time_string(duration) {
  1757. let t = Math.round(duration);
  1758. t = Math.abs(t);
  1759. let x = Math.floor(t / 60 ** 2);
  1760. let res;
  1761. if (x > 0) {
  1762. res = x + ':' + Math.floor(t / 60 % 60).toString().padStart(2, '0');
  1763. } else {
  1764. res = Math.floor(t / 60 % 60).toString();
  1765. }
  1766. return res + ':' + (t % 60).toString().padStart(2, '0');
  1767. }
  1768.  
  1769. function extract_year(expr) {
  1770. if (typeof expr != 'string') return null;
  1771. var year, m = expr.match(/\b(\d{4})\b/);
  1772. return m != null && parseInt(m[1]) || parseInt(expr) || null;
  1773. }
  1774.  
  1775. function isRED() { return document.domain.toLowerCase().endsWith('redacted.ch') }
  1776. function isNWCD() { return document.domain.toLowerCase().endsWith('notwhat.cd') }
  1777. function isOrpheus() { return document.domain.toLowerCase().endsWith('orpheus.network') }
  1778.  
  1779. function reInParenthesis(expr) { return new RegExp('\\s+\\([^\\(\\)]*'.concat(expr, '[^\\(\\)]*\\)$'), 'i') }
  1780. function reInBrackets(expr) { return new RegExp('\\s+\\[[^\\[\\]]*'.concat(expr, '[^\\[\\]]*\\]$'), 'i') }
  1781.  
  1782. function matchCaseless(str) { return str.toLowerCase() == this.toLowerCase() }
  1783.  
  1784. Array.prototype.includesCaseless = function(str) { return this.find(matchCaseless, str) != undefined };
  1785.  
  1786. function addWarning(text, bold = true, color = 'red') {
  1787. warnings = document.getElementById('UA warnings');
  1788. if (warnings == null) {
  1789. var ua = document.getElementById('upload assistant');
  1790. if (ua == null) return null;
  1791. warnings = document.createElement('TR');
  1792. if (warnings == null) return null;
  1793. warnings.id = 'UA warnings';
  1794. ua.children[0].append(warnings);
  1795.  
  1796. elem = document.createElement('TD');
  1797. if (elem == null) return null;
  1798. elem.colSpan = 2;
  1799. elem.style.paddingLeft = '15px';
  1800. elem.style.paddingRight = '15px';
  1801. elem.style.textAlign = 'left';
  1802. warnings.append(elem);
  1803. } else {
  1804. elem = warnings.children[0];
  1805. if (elem == null) return null;
  1806. }
  1807. var div = document.createElement('DIV');
  1808. if (color) div.style.color = color;
  1809. if (bold) {
  1810. div.appendChild(document.createElement('B')).textContent = text;
  1811. } else {
  1812. div.textContent = text;
  1813. }
  1814. return elem.appendChild(div);
  1815. }