RED (+ NWCD, Orpheus) Upload Assistant

Accurate filling 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. As alternative to copied playlist, URL to product in supported webstore can be used -- see below for the list.

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

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