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

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