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

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