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

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