RED (+ NWCD, Orpheus) Upload Assistant

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