RED (+ NWCD, Orpheus) Upload Assistant

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