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.94
  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($if2(%comment%,%description%),$char(13),$char(29)),$char(10),$char(28))]
  25. //
  26. // Fetch release description from webstore URL, supported
  27. //
  28. // Supported sites for music:
  29. // - qobuz.com
  30. // - highresaudio.com
  31. // - bandcamp.com
  32. // - prestomusic.com
  33. //
  34. // Supported sites for ebooks:
  35. // - martinus.cz, martinus.sk
  36. // - goodreads.com
  37. // - databazeknih.cz
  38. //
  39. // Supported sites for applications:
  40. // - sanet.st
  41.  
  42. 'use strict';
  43.  
  44. var prefs = {
  45. set: function(prop, def) { this[prop] = GM_getValue(prop, def) },
  46. save: function() {
  47. for (var iter in this) { if (typeof this[iter] != 'function') GM_setValue(iter, this[iter]) }
  48. },
  49. };
  50. prefs.set('remap_texttools_newlines', 0); // convert underscores to linebreaks (ambiguous)
  51. prefs.set('clean_on_apply', 0); // clean the input box on successfull fill
  52. prefs.set('keep_meaningles_composers', 0); // keep composers from file tags also for non-composer emphasis works
  53. prefs.set('always_hide_dnu_list', 0); // risky!
  54. prefs.set('single_threshold', 8 * 60); // Max length of single in s
  55. prefs.set('EP_threshold', 28 * 60); // Max time of EP in s
  56. prefs.set('auto_preview_cover', 1);
  57. prefs.set('auto_rehost_cover', 1);
  58. // tracklist specific
  59. prefs.set('tracklist_style', 1); // 1: classical, 2: propertional right aligned
  60. prefs.set('max_tracklist_width', 80); // right margin of the right aligned tracklist. should not exceed the group description width on any device
  61. prefs.set('title_separator', '. '); // divisor of track# and title
  62. prefs.set('pad_leader', ' ');
  63. prefs.set('tracklist_head_color', '#4682B4');
  64. prefs.set('tracklist_single_color', '#708080');
  65. // classical tracklist only components colouring
  66. prefs.set('tracklist_discsubtitle_color', '#008B8B');
  67. prefs.set('tracklist_classicalblock_color', 'Olive');
  68. prefs.set('tracklist_tracknumber_color', '#8899AA');
  69. prefs.set('tracklist_artist_color', '#889B2F');
  70. prefs.set('tracklist_composer_color', '#556B2F');
  71. prefs.set('tracklist_duration_color', '#4682B4');
  72.  
  73. 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 { color: red; font-weight: bold; }
  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. document.querySelectorAll('input[name="artists[]"]').forEach(function(i) {
  762. if (['4', '5'].includes(i.nextElementSibling.value)) i.value = null
  763. });
  764. }
  765. for (iter of tracks) {
  766. doubleParsParsers.forEach(function(rx) {
  767. if (rx.test(iter.title)) {
  768. addWarning('Warning: doubled parentheses in track #' + iter.tracknumber +
  769. ' title ("' + iter.title + '")', 'uaw-info');
  770. //iter.title.replace(rx, RegExp.$1);
  771. }
  772. });
  773. }
  774. if (tracks.length > 1 && array_homogenous(tracks.map(k => k.title))) {
  775. addWarning('Warning: all tracks having same title: ' + tracks[0].title, 'uaw-info');
  776. }
  777. // ============================================= The Playlist =============================================
  778. var description, ripinfo, dur;
  779. const vinyl_test = /^((?:Vinyl|LP) rip by\s+)(.*)$/im;
  780. if (tracks.length > 1) {
  781. gen_full_tracklist();
  782. } else { // single
  783. description = '[align=center]';
  784. description += isRED() ? '[pad=20|20|20|20]' : '';
  785. description += '[size=4][b][color=' + prefs.tracklist_artist_color + ']' + album_artists[0] + '[/color][hr]';
  786. //description += '[color=' + prefs.tracklist_single_color + ']';
  787. description += tracks[0].title;
  788. //description += '[/color]'
  789. description += '[/b]';
  790. if (tracks[0].composer) {
  791. description += '\n[i][color=' + prefs.tracklist_composer_color + '](' + tracks[0].composer + ')[/color][/i]';
  792. }
  793. description += '\n\n[color=' + prefs.tracklist_duration_color +'][' +
  794. makeTimeString(tracks[0].duration) + '][/color][/size]';
  795. if (isRED()) description += '[/pad]';
  796. description += '[/align]';
  797. }
  798. if (comments.length == 1 && comments[0]) {
  799. let cmt = comments[0];
  800. if (matches = cmt.match(vinyl_test)) {
  801. ripinfo = cmt.slice(matches.index).trim().split(/[\r\n]+/);
  802. description = description.concat('\n\n', cmt.slice(0, matches.index).trim());
  803. } else {
  804. description = description.concat('\n\n', cmt);
  805. }
  806. }
  807. if (element_writable(ref = document.getElementById('album_desc'))) {
  808. ref.value = description;
  809. preview(0);
  810. }
  811. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  812. let editioninfo;
  813. if (edition_title) {
  814. editioninfo = '[size=5][b]' + edition_title;
  815. if (release_years.length >= 1) { editioninfo = editioninfo.concat(' (', release_years[0] + ')') }
  816. editioninfo = editioninfo.concat('[/b][/size]\n\n');
  817. } else { editioninfo = '' }
  818. if (ref.textLength > 0) {
  819. ref.value = ref.value.concat('\n\n', editioninfo, description);
  820. } else {
  821. ref.value = editioninfo + description;
  822. }
  823. preview(0);
  824. }
  825. var lineage = '', comment = '', drinfo, srcinfo;
  826. if (Object.keys(srs).length > 0) {
  827. let kHz = Object.keys(srs).sort((a, b) => srs[b] - srs[a]).map(f => f / 1000).join('/').concat('kHz');
  828. if (element_writable(ref = document.getElementById('release_samplerate'))) {
  829. ref.value = Object.keys(srs).length > 1 ? '999' : Math.floor(Object.keys(srs)[0] / 1000);
  830. }
  831. if (bds.some(bd => bd > 16)) {
  832. if (drs.length >= 1) drinfo = '[hide=DR' + (drs.length == 1 ? drs[0] : '') + '][pre][/pre]';
  833. if (media == 'Vinyl') {
  834. let hassr = ref == null || Object.keys(srs).length > 1;
  835. lineage = hassr ? kHz + ' ' : '';
  836. if (ripinfo) {
  837. ripinfo[0] = ripinfo[0].replace(vinyl_test, '$1[color=blue]$2[/color]');
  838. if (hassr) { ripinfo[0] = ripinfo[0].replace(/^Vinyl\b/, 'vinyl') }
  839. lineage += ripinfo[0] + '\n\n[u]Lineage:[/u]' + ripinfo.slice(1).map(k => '\n' + k).join('');
  840. } else {
  841. lineage += (hassr ? 'Vinyl' : ' vinyl') + ' rip by [color=blue][/color]\n\n[u]Lineage:[/u]';
  842. }
  843. if (drs.length >= 1) drinfo += '\n\n[img][/img]\n[img][/img]\n[img][/img][/hide]';
  844. } else if (['Blu-Ray', 'DVD', 'SACD'].includes(media)) {
  845. lineage = ref ? '' : kHz;
  846. if (channels.length == 1) add_channel_info();
  847. if (media == 'SACD' || is_from_dsd) {
  848. lineage += ' from DSD64 using foobar2000\'s SACD decoder (direct-fp64)';
  849. lineage += '\nOutput gain +0dB';
  850. }
  851. drinfo += '[/hide]';
  852. //add_rg_info();
  853. } else { // WEB Hi-Res
  854. if (ref == null || Object.keys(srs).length > 1) lineage = kHz;
  855. if (channels.length == 1 && channels[0] != 2) add_channel_info();
  856. add_dr_info();
  857. //if (lineage.length > 0) add_rg_info();
  858. if (bds.length >= 2) bds.filter(bd => bd != 24).forEach(function(bd) {
  859. let hybrid_tracks = tracks.filter(k => k.bd == bd).map(k => k.tracknumber);
  860. if (hybrid_tracks.length < 1) return;
  861. if (lineage) lineage += '\n';
  862. lineage += 'Note: track';
  863. if (hybrid_tracks.length > 1) lineage += 's';
  864. lineage += ' #' + hybrid_tracks.sort().join(', ') +
  865. (hybrid_tracks.length > 1 ? ' are' : ' is') + ' ' + bd + 'bit lossless';
  866. });
  867. drinfo = Object.keys(srs).includes(88200) ? drinfo.concat('[/hide]') : null;
  868. }
  869. } else { // 16bit or lossy
  870. if (Object.keys(srs).some(f => f != 44100)) lineage = kHz;
  871. if (channels.length == 1 && channels[0] != 2) add_channel_info();
  872. //add_dr_info();
  873. //if (lineage.length > 0) add_rg_info();
  874. if (['AAC', 'Opus', 'Vorbis'].includes(codecs[0]) && vendors[0]) {
  875. let _encoder_settings = vendors[0];
  876. if (codecs[0] == 'AAC' && /^qaac\s+[\d\.]+/i.test(vendors[0])) {
  877. let enc = [];
  878. if (matches = vendors[0].match(/\bqaac\s+([\d\.]+)\b/i)) enc[0] = matches[1];
  879. if (matches = vendors[0].match(/\bCoreAudioToolbox\s+([\d\.]+)\b/i)) enc[1] = matches[1];
  880. if (matches = vendors[0].match(/\b(AAC-\S+)\s+Encoder\b/i)) enc[2] = matches[1];
  881. if (matches = vendors[0].match(/\b([TC]VBR|ABR|CBR)\s+(\S+)\b/)) { enc[3] = matches[1]; enc[4] = matches[2]; }
  882. if (matches = vendors[0].match(/\bQuality\s+(\d+)\b/i)) enc[5] = matches[1];
  883. _encoder_settings = 'Converted by Apple\'s ' + enc[2] + ' encoder (' + enc[3] + '-' + enc[4] + ')';
  884. }
  885. if (lineage) lineage += '\n\n';
  886. lineage += _encoder_settings;
  887. }
  888. }
  889. }
  890. function add_dr_info() {
  891. if (drs.length != 1 || document.getElementById('release_dynamicrange') != null) return false;
  892. if (lineage.length > 0) lineage += ' | ';
  893. if (drs[0] < 4) lineage += '[color=red]';
  894. lineage += 'DR' + drs[0];
  895. if (drs[0] < 4) lineage += '[/color]';
  896. return true;
  897. }
  898. function add_rg_info() {
  899. if (rgs.length != 1) return false;
  900. if (lineage.length > 0) lineage += ' | ';
  901. lineage += 'RG'; //lineage += 'RG ' + rgs[0];
  902. return true;
  903. }
  904. function add_channel_info() {
  905. if (channels.length != 1) return false;
  906. let chi = getChanString(channels[0]);
  907. if (lineage.length > 0 && chi.length > 0) lineage += ', ';
  908. lineage += chi;
  909. return chi.length > 0;
  910. }
  911. if (urls.length == 1 && urls[0]) {
  912. srcinfo = '[url]' + urls[0] + '[/url]';
  913. if (element_writable(document.getElementById('image'))) {
  914. let u = urls[0];
  915. if (/^https?:\/\/(\w+\.)?discogs\.com\/release\/[\w\-]+\/?$/i.test(u)) u += '/images';
  916. GM_xmlhttpRequest({ method: 'GET', url: u, onload: fetch_image_from_store });
  917. }
  918. // } else if (element_writable(document.getElementById('image'))
  919. // && ((ref = document.getElementById('album_desc')) != null || (ref = document.getElementById('body')) != null)
  920. // && ref.textLength > 0 && (matches = ref.value.matchAll(/\b(https?\/\/[\w\-\&\_\?\=]+)/i)) != null) {
  921. }
  922. ref = document.getElementById('release_lineage');
  923. if (ref != null) {
  924. if (element_writable(ref)) {
  925. if (drinfo) comment = drinfo;
  926. if (lineage && srcinfo) lineage += '\n\n';
  927. if (srcinfo) lineage += srcinfo;
  928. ref.value = lineage;
  929. preview(1);
  930. }
  931. } else {
  932. comment = lineage;
  933. if (comment && drinfo) comment += '\n\n';
  934. if (drinfo) comment += drinfo;
  935. if (comment && srcinfo) comment += '\n\n';
  936. if (srcinfo) comment += srcinfo;
  937. }
  938. if (comment.length > 0) {
  939. if (element_writable(ref = document.getElementById('release_desc'))) {
  940. ref.value = comment;
  941. preview(isNWCD() ? 2 : 1);
  942. }
  943. }
  944. if (encodings[0] == 'lossless' && codecs[0] == 'FLAC' && bds.includes(24) && dirpaths.length == 1) {
  945. var uri = new URL(dirpaths[0] + '\\foo_dr.txt');
  946. GM_xmlhttpRequest({
  947. method: 'GET',
  948. url: uri.href,
  949. responseType: 'blob',
  950. onload: function(response) {
  951. if (response.readyState != 4 || !response.responseText) return;
  952. var rlsDesc = document.getElementById('release_lineage') || document.getElementById('release_desc');
  953. if (rlsDesc == null) return;
  954. var value = rlsDesc.value;
  955. matches = value.match(/(^\[hide=DR\d*\]\[pre\])\[\/pre\]/im);
  956. if (matches == null) return;
  957. var index = matches.index + matches[1].length;
  958. rlsDesc.value = value.slice(0, index).concat(response.responseText, value.slice(index));
  959. }
  960. });
  961. }
  962. if (drs.length == 1) {
  963. if (element_writable(ref = document.getElementById('release_dynamicrange'))) ref.value = drs[0];
  964. }
  965. if (prefs.clean_on_apply) clipBoard.value = null;
  966. prefs.save();
  967. return true;
  968.  
  969. function gen_full_tracklist() { // ========================= TACKLIST =========================
  970. description = isRED() ? '[pad=5|0|0|0]' : '';
  971. description += '[size=4][color=' + prefs.tracklist_head_color + '][b]Tracklisting[/b][/color][/size]';
  972. if (isRED()) '[/pad]';
  973. let classical_units = new Set();
  974. if (is_classical && !tracks.some(k => k.discsubtitle)) {
  975. for (track of tracks) {
  976. if (matches = track.title.match(/^(.+?)\s*:\s+(.*)$/)) {
  977. classical_units.add(track.classical_unit_title = matches[1]);
  978. track.classical_title = matches[2];
  979. } else {
  980. track.classical_unit_title = null;
  981. }
  982. }
  983. for (let unit of classical_units.keys()) {
  984. let group_performer = array_homogenous(tracks.filter(k => k.classical_unit_title === unit).map(k => k.track_artist));
  985. let group_composer = array_homogenous(tracks.filter(k => k.classical_unit_title === unit).map(k => k.composer));
  986. for (track of tracks) {
  987. if (track.classical_unit_title !== unit) continue;
  988. if (group_composer) track.classical_unit_composer = track.composer;
  989. if (group_performer) track.classical_unit_performer = track.track_artist;
  990. }
  991. }
  992. }
  993. let block = 1, lastdisc, lastsubtitle, lastside, vinyl_trackwidth;
  994. let lastwork = classical_units.size > 0 ? null : undefined;
  995. description += '\n';
  996. let volumes = new Map(tracks.map(k => [k.discnumber, undefined]));
  997. volumes.forEach(function(val, key) {
  998. volumes.set(key, array_homogenous(tracks.filter(k => k.discnumber == key).map(k => k.discsubtitle)));
  999. });
  1000. if (media == 'Vinyl') {
  1001. let max_side_track = undefined;
  1002. rx = /^([A-Z])(\d+)?(\.(\d+))?/i;
  1003. for (iter of tracks) {
  1004. if (matches = iter.tracknumber.match(rx)) {
  1005. max_side_track = Math.max(parseInt(matches[2]) || 1, max_side_track || 0);
  1006. }
  1007. }
  1008. if (typeof max_side_track == 'number') {
  1009. max_side_track = max_side_track.toString().length;
  1010. vinyl_trackwidth = 1 + max_side_track;
  1011. for (iter of tracks) {
  1012. if (matches = iter.tracknumber.match(rx)) {
  1013. iter.tracknumber = matches[1].toUpperCase();
  1014. if (matches[2]) iter.tracknumber += matches[2].padStart(max_side_track, '0');
  1015. }
  1016. }
  1017. }
  1018. }
  1019. function prologue(prefix, postfix) {
  1020. function block1() {
  1021. if (block == 3) description += postfix;
  1022. description += '\n';
  1023. block = 1;
  1024. }
  1025. function block2() {
  1026. if (block == 3) description += postfix;
  1027. description += '\n';
  1028. block = 2;
  1029. }
  1030. function block3() {
  1031. if (block == 2) { description += '[hr]' } else { description += '\n' }
  1032. if (block != 3) description += prefix;
  1033. block = 3;
  1034. }
  1035. if (totaldiscs > 1 && iter.discnumber != lastdisc) {
  1036. block1();
  1037. description += '[size=3][color=' + prefs.tracklist_discsubtitle_color + '][b]Disc ' + iter.discnumber;
  1038. if (iter.discsubtitle && (!volumes.has(iter.discnumber) || volumes.get(iter.discnumber))) {
  1039. description += ' - ' + iter.discsubtitle;
  1040. lastsubtitle = iter.discsubtitle;
  1041. }
  1042. description += '[/b][/color][/size]';
  1043. lastdisc = iter.discnumber;
  1044. }
  1045. if (iter.discsubtitle != lastsubtitle) {
  1046. block1();
  1047. if (iter.discsubtitle) {
  1048. description += '[size=2][color=' + prefs.tracklist_discsubtitle_color + '][b]' +
  1049. iter.discsubtitle + '[/b][/color][/size]';
  1050. }
  1051. lastsubtitle = iter.discsubtitle;
  1052. }
  1053. if (iter.classical_unit_title !== lastwork) {
  1054. if (iter.classical_unit_composer || iter.classical_unit_title || iter.classical_unit_performer) {
  1055. block2();
  1056. description += '[size=2][color=' + prefs.tracklist_classicalblock_color + '][b]';
  1057. if (iter.classical_unit_composer) description += iter.classical_unit_composer + ': ';
  1058. if (iter.classical_unit_title) description += iter.classical_unit_title;
  1059. description += '[/b]';
  1060. if (iter.classical_unit_performer) description += ' (' + iter.classical_unit_performer + ')';
  1061. description += '[/color][/size]';
  1062. } else {
  1063. if (block != 2) block1();
  1064. }
  1065. lastwork = iter.classical_unit_title;
  1066. }
  1067. block3();
  1068. if (media == 'Vinyl') {
  1069. let c = iter.tracknumber[0].toUpperCase();
  1070. if (lastside != undefined && c != lastside) description += '\n';
  1071. lastside = c;
  1072. }
  1073. }
  1074. var varying_composer = !array_homogenous(tracks.map(k => k.composer));
  1075. for (iter of tracks.sort(function(a, b) {
  1076. var d = a.discnumber - b.discnumber;
  1077. var t = a.tracknumber - b.tracknumber;
  1078. return isNaN(d) || d == 0 ? isNaN(t) ? a.tracknumber.localeCompare(b.tracknumber) : t : d;
  1079. })) {
  1080. let title = '';
  1081. let ttwidth = vinyl_trackwidth || Math.max((iter.totaltracks || tracks.length).toString().length, 2);
  1082. if (prefs.tracklist_style == 1) {
  1083. // STYLE 1 ----------------------------------------
  1084. prologue('[size=2]', '[/size]\n');
  1085. track = '[b][color=' + prefs.tracklist_tracknumber_color + ']';
  1086. track += isNaN(parseInt(iter.tracknumber)) ? iter.tracknumber : iter.tracknumber.padStart(ttwidth, '0');
  1087. track += '[/color][/b]' + prefs.title_separator;
  1088. if (iter.track_artist && !iter.classical_unit_performer) {
  1089. title = '[color=' + prefs.tracklist_artist_color + ']' + iter.track_artist + '[/color] - ';
  1090. }
  1091. title += iter.classical_title || iter.title;
  1092. if (iter.composer && composer_emphasis && varying_composer && !iter.classical_unit_composer) {
  1093. title = title.concat(' [color=', prefs.tracklist_composer_color, '](', iter.composer, ')[/color]');
  1094. }
  1095. description += track + title;
  1096. if (iter.duration) description += ' [i][color=' + prefs.tracklist_duration_color +'][' +
  1097. makeTimeString(iter.duration) + '][/color][/i]';
  1098. } else if (prefs.tracklist_style == 2) {
  1099. // STYLE 2 ----------------------------------------
  1100. prologue('[size=2][pre]', '[/pre][/size]');
  1101. track = isNaN(parseInt(iter.tracknumber)) ? iter.tracknumber : iter.tracknumber.padStart(ttwidth, '0');
  1102. track += prefs.title_separator;
  1103. if (iter.track_artist && !iter.classical_unit_performer) title = iter.track_artist + ' - ';
  1104. title += iter.classical_title || iter.title;
  1105. if (iter.composer && composer_emphasis && varying_composer && !iter.classical_unit_composer) {
  1106. title = title.concat(' (', iter.composer, ')');
  1107. }
  1108. dur = iter.duration ? '[' + makeTimeString(iter.duration) + ']' : null;
  1109. let l = 0, j, left, padding, spc;
  1110. let width = prefs.max_tracklist_width - track.length;
  1111. if (dur) width -= dur.length + 1;
  1112. while (title.length > 0) {
  1113. j = width;
  1114. if (title.length > width) {
  1115. while (j > 0 && title[j] != ' ') { --j }
  1116. if (j <= 0) j = width;
  1117. }
  1118. left = title.slice(0, j).trim();
  1119. if (++l <= 1) {
  1120. description += track + left;
  1121. if (dur) {
  1122. spc = width - left.length;
  1123. padding = (spc < 2 ? ' '.repeat(spc) : ' ' + prefs.pad_leader.repeat(spc - 1)) + ' ';
  1124. description += padding + dur;
  1125. }
  1126. width = prefs.max_tracklist_width - track.length - 2;
  1127. } else {
  1128. description += '\n' + ' '.repeat(track.length) + left;
  1129. }
  1130. title = title.slice(j).trim();
  1131. }
  1132. }
  1133. }
  1134. if (prefs.tracklist_style == 1) {
  1135. description += '\n\n' + div[0].repeat(10) + '\n[color=' + prefs.tracklist_duration_color +
  1136. ']Total time: [i]' + makeTimeString(total_time) + '[/i][/color][/size]';
  1137. } else if (prefs.tracklist_style == 2) {
  1138. dur = '[' + makeTimeString(total_time) + ']';
  1139. description = description.concat('\n\n', div[0].repeat(32).padStart(prefs.max_tracklist_width));
  1140. description = description.concat('\n', 'Total time:'.padEnd(prefs.max_tracklist_width - dur.length), dur);
  1141. description = description.concat('[/pre][/size]');
  1142. }
  1143. }
  1144.  
  1145. function getChanString(n) {
  1146. const chanmap = [
  1147. 'mono',
  1148. 'stereo',
  1149. '2.1',
  1150. '4.0 surround sound',
  1151. '5.0 surround sound',
  1152. '5.1 surround sound',
  1153. '7.0 surround sound',
  1154. '7.1 surround sound',
  1155. ];
  1156. return n >= 1 && n <= 8 ? chanmap[n - 1] : n + 'chn surround sound';
  1157. }
  1158.  
  1159. function init_from_url_music(url) {
  1160. if (typeof url != 'string') return false;
  1161. var artist, album, albumYear, remasterYear, channels, label, composer, bd, sr = 44.1,
  1162. description, compiler, producer, totaltracks, totaldiscs = null, discsubtitle,
  1163. discnumber, tracknumber, title, track_artist, duration, catalogue, encoding, format, bitrate;
  1164. if (url.toLowerCase().indexOf('qobuz.com') >= 0) {
  1165. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1166. if (response.readyState != 4 || response.status != 200) return;
  1167. dom = htmlparser.parseFromString(response.responseText, "text/html");
  1168. if (dom == null) return;
  1169.  
  1170. ref = dom.querySelector('h2.album-meta__artist');
  1171. if (ref != null) artist = ref.textContent.trim();
  1172. ref = dom.querySelector('h1.album-meta__title');
  1173. album = ref.textContent.trim();
  1174. ref = dom.querySelector('div.album-meta > ul > li:first-of-type');
  1175. if (ref != null) remasterYear = extract_year(ref.textContent);
  1176. ref = dom.querySelector('p.album-about__copyright');
  1177. albumYear = ref != null && extract_year(ref.textContent) || remasterYear;
  1178. let genre;
  1179. dom.querySelectorAll('section#about > ul > li').forEach(function(k) {
  1180. if (/\b(\d+)\s*(?:dis[ck](?:s\b|\(s\))?|disco(?:s\b|\(s\))?|disque(?:s\|\(s\))?)/i.exec(k.textContent) != null) {
  1181. totaldiscs = parseInt(RegExp.$1);
  1182. }
  1183. if (/\b(\d+)\s*(?:track(?:s\b|\(s\))?|pist[ae](?:s\b|\(s\))?|tracce)/i.exec(k.textContent) != null) {
  1184. totaltracks = parseInt(RegExp.$1);
  1185. }
  1186. if (k.textContent.indexOf('Label') >= 0) label = k.children[0].textContent.trim()
  1187. else if (k.textContent.indexOf('Composer') >= 0) {
  1188. composer = k.children[0].textContent.trim();
  1189. if (/\bVarious\b/i.test(composer)) composer = null;
  1190. } else if (k.textContent.indexOf('Genre') >= 0 && k.children.length > 0) {
  1191. genre = k.querySelector('a:last-child');
  1192. genre = genre != null ? genre = genre.textContent.trim() : undefined;
  1193. }
  1194. });
  1195. bd = 16; channels = 2;
  1196. dom.querySelectorAll('span.album-quality__info').forEach(function(k) {
  1197. if (/\b([\d\.\,]+)\s*kHz\b/i.exec(k.textContent) != null) sr = parseFloat(RegExp.$1.replace(/,/g, '.'));
  1198. if (/\b(\d+)[\-\s]*Bits?\b/i.exec(k.textContent) != null) bd = parseInt(RegExp.$1);
  1199. if (/\b(?:Stereo)b/i.test(k.textContent)) channels = 2;
  1200. if (/\b(?:4\.0)b/.test(k.textContent)) channels = 4;
  1201. if (/\b(?:5\.0)b/.test(k.textContent)) channels = 5;
  1202. if (/\b(?:5\.1)b/.test(k.textContent)) channels = 6;
  1203. if (/\b(?:7\.0)b/.test(k.textContent)) channels = 7;
  1204. if (/\b(?:7\.1)b/.test(k.textContent)) channels = 8;
  1205. });
  1206. get_desc_from_node('section#description > p', response.finalUrl, true);
  1207. if ((ref = dom.querySelector('a[title="Qobuzissime"]')) != null) {
  1208. description += '\x1C[align=center][url=https://www.qobuz.com' + ref.pathname +
  1209. '][img]https://ptpimg.me/4z35uj.png[/img][/url][/align]';
  1210. }
  1211. ref = dom.querySelectorAll('div.track > div.track__items');
  1212. if (!totaltracks) totaltracks = ref.length;
  1213. ref.forEach(function(k) {
  1214. discnumber = k.parentNode.parentNode.parentNode.querySelector('p.player__work');
  1215. discnumber = discnumber != null && /^DIS[CK]\s*(\d+)$/i.exec(discnumber.textContent) != null ?
  1216. parseInt(RegExp.$1) : undefined;
  1217. if (discnumber > totaldiscs) totaldiscs = discnumber;
  1218. tracknumber = parseInt(k.querySelector('span[itemprop="position"]').textContent.trim());
  1219. title = k.querySelector('span.track__item--name').textContent.trim().replace(/\s+/g, ' ');
  1220. duration = timestrToTime(k.querySelector('span.track__item--duration').textContent);
  1221. track_artist = undefined;
  1222. track = [
  1223. artist,
  1224. album,
  1225. albumYear,
  1226. remasterYear,
  1227. label,
  1228. undefined,
  1229. 'lossless',
  1230. 'FLAC',
  1231. undefined,
  1232. undefined,
  1233. bd,
  1234. sr * 1000,
  1235. channels,
  1236. 'WEB',
  1237. genre,
  1238. discnumber,
  1239. totaldiscs,
  1240. discsubtitle,
  1241. tracknumber,
  1242. totaltracks,
  1243. title,
  1244. track_artist,
  1245. undefined,
  1246. composer,
  1247. undefined,
  1248. undefined,
  1249. compiler,
  1250. producer,
  1251. duration,
  1252. undefined,
  1253. undefined,
  1254. undefined,
  1255. response.finalUrl,
  1256. undefined,
  1257. description,
  1258. ];
  1259. tracks.push(track.join('\x1E'));
  1260. });
  1261. clipBoard.value = tracks.join('\n');
  1262. fill_from_text_music();
  1263. } });
  1264. } else if (url.toLowerCase().indexOf('highresaudio.com') >= 0) {
  1265. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1266. if (response.readyState != 4 || response.status != 200) return;
  1267. dom = htmlparser.parseFromString(response.responseText, "text/html");
  1268. if (dom == null) return;
  1269.  
  1270. ref = dom.querySelector('h1 > span.artist');
  1271. if (ref != null) artist = ref.textContent.trim();
  1272. ref = dom.getElementById('h1-album-title');
  1273. if (ref != null) album = ref.firstChild.textContent.trim();
  1274. let genres = [], format;
  1275. dom.querySelectorAll('div.album-col-info-data > div > p').forEach(function(k) {
  1276. if (/\b(?:Genre|Subgenre)\b/i.test(k.firstChild.textContent)) genres.push(k.lastChild.textContent.trim());
  1277. if (/\b(?:Label)\b/i.test(k.firstChild.textContent)) label = k.lastChild.textContent.trim();
  1278. if (/\b(?:Album[\s\-]Release)\b/i.test(k.firstChild.textContent)) albumYear = extract_year(k.lastChild.textContent);
  1279. if (/\b(?:HRA[\s\-]Release)\b/i.test(k.firstChild.textContent)) remasterYear = extract_year(k.lastChild.textContent);
  1280. });
  1281. i = 0;
  1282. dom.querySelectorAll('tbody > tr > td.col-format').forEach(function(k) {
  1283. if (/^(FLAC)\s*([\d\.\,]+)\b/.exec(k.textContent) != null) {
  1284. format = RegExp.$1;
  1285. sr = parseFloat(RegExp.$2.replace(/,/g, '.'));
  1286. ++i;
  1287. }
  1288. });
  1289. if (i > 1) sr = undefined; // ambiguous
  1290. get_desc_from_node('div#albumtab-info > p', response.finalUrl);
  1291. ref = dom.querySelectorAll('ul.playlist > li.pltrack');
  1292. totaltracks = ref.length;
  1293. ref.forEach(function(k) {
  1294. discsubtitle = k;
  1295. while ((discsubtitle = discsubtitle.previousElementSibling) != null) {
  1296. if (discsubtitle.nodeName == 'LI' && discsubtitle.className == 'plinfo') {
  1297. discsubtitle = discsubtitle.textContent.replace(/\s*:$/, '').trim();
  1298. if (/\b(?:DIS[CK]|Volume|CD)\s*(\d+)\b/i.exec(discsubtitle)) discnumber = parseInt(RegExp.$1);
  1299. break;
  1300. }
  1301. }
  1302. //if (discnumber > totaldiscs) totaldiscs = discnumber;
  1303. tracknumber = parseInt(k.querySelector('span.track').textContent.trim());
  1304. title = k.querySelector('span.title').textContent.trim().replace(/\s+/g, ' ');
  1305. duration = timestrToTime(k.querySelector('span.time').textContent);
  1306. track_artist = undefined;
  1307. track = [
  1308. artist,
  1309. album,
  1310. albumYear,
  1311. remasterYear,
  1312. label,
  1313. undefined,
  1314. 'lossless',
  1315. 'FLAC', //format,
  1316. undefined,
  1317. undefined,
  1318. 24,
  1319. sr * 1000,
  1320. 2,
  1321. 'WEB',
  1322. genres.join(', '),
  1323. discnumber,
  1324. totaldiscs,
  1325. discsubtitle,
  1326. tracknumber,
  1327. totaltracks,
  1328. title,
  1329. track_artist,
  1330. undefined,
  1331. composer,
  1332. undefined,
  1333. undefined,
  1334. compiler,
  1335. producer,
  1336. duration,
  1337. undefined,
  1338. undefined,
  1339. undefined,
  1340. response.finalUrl,
  1341. undefined,
  1342. description,
  1343. ];
  1344. tracks.push(track.join('\x1E'));
  1345. });
  1346. clipBoard.value = tracks.join('\n');
  1347. fill_from_text_music();
  1348. } });
  1349. } else if (url.toLowerCase().indexOf('bandcamp.com') >= 0) {
  1350. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1351. if (response.readyState != 4 || response.status != 200) return;
  1352. dom = htmlparser.parseFromString(response.responseText, "text/html");
  1353. if (dom == null) return;
  1354.  
  1355. ref = dom.querySelector('span[itemprop="byArtist"] > a');
  1356. if (ref != null) artist = ref.textContent.trim();
  1357. ref = dom.querySelector('h2[itemprop="name"]');
  1358. if (ref != null) album = ref.textContent.trim();
  1359. ref = dom.querySelector('div.tralbum-credits');
  1360. if (ref != null && /\breleased\s+.*?\b(\d{4})\b/i.exec(ref.textContent)) {
  1361. remasterYear = parseInt(RegExp.$1);
  1362. albumYear = remasterYear;
  1363. }
  1364. ref = dom.querySelector('p#band-name-location > span.title');
  1365. if (ref != null) label = ref.textContent.trim();
  1366. let tags = new TagManager;
  1367. dom.querySelectorAll('div.tralbum-tags > a.tag').forEach(k => { tags.add(k.textContent.trim()) });
  1368. description = [];
  1369. dom.querySelectorAll('div.tralbumData').forEach(function(k) {
  1370. if (!k.classList.contains('tralbum-tags')) description.push(html2php(k, response.finalUrl))
  1371. });
  1372. description = description.join('\n\n').replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  1373. ref = dom.querySelectorAll('table.track_list > tbody > tr[itemprop="tracks"]');
  1374. totaltracks = ref.length;
  1375. ref.forEach(function(k) {
  1376. tracknumber = parseInt(k.querySelector('div.track_number').textContent);
  1377. title = k.querySelector('span.track-title').textContent.trim().replace(/\s+/g, ' ');
  1378. duration = timestrToTime(k.querySelector('span.time').textContent);
  1379. track_artist = undefined;
  1380. track = [
  1381. artist,
  1382. album,
  1383. albumYear,
  1384. remasterYear,
  1385. label,
  1386. undefined,
  1387. undefined, //'lossless',
  1388. undefined, //'FLAC',
  1389. undefined,
  1390. undefined,
  1391. undefined,
  1392. undefined,
  1393. 2,
  1394. 'WEB',
  1395. tags.toString(),
  1396. discnumber,
  1397. totaldiscs,
  1398. undefined,
  1399. tracknumber,
  1400. totaltracks,
  1401. title,
  1402. track_artist,
  1403. undefined,
  1404. composer,
  1405. undefined,
  1406. undefined,
  1407. compiler,
  1408. producer,
  1409. duration,
  1410. undefined,
  1411. undefined,
  1412. undefined,
  1413. response.finalUrl,
  1414. undefined,
  1415. description,
  1416. ];
  1417. tracks.push(track.join('\x1E'));
  1418. });
  1419. clipBoard.value = tracks.join('\n');
  1420. fill_from_text_music();
  1421. } });
  1422. } else if (url.toLowerCase().indexOf('prestomusic.com') >= 0) {
  1423. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1424. if (response.readyState != 4 || response.status != 200) return;
  1425. dom = htmlparser.parseFromString(response.responseText, "text/html");
  1426. if (dom == null) return;
  1427.  
  1428. artist = getArtists(dom.querySelectorAll('div.c-product-block__contributors > p'));
  1429. ref = dom.querySelector('h1.c-product-block__title');
  1430. if (ref != null) album = ref.lastChild.textContent.trim();
  1431. dom.querySelectorAll('div.c-product-block__metadata > ul > li').forEach(function(k) {
  1432. if (k.firstChild.textContent.indexOf('Release Date') >= 0) {
  1433. remasterYear = extract_year(k.lastChild.textContent.trim());
  1434. } else if (k.firstChild.textContent.indexOf('Label') >= 0) {
  1435. label = k.lastChild.textContent.trim();
  1436. } else if (k.firstChild.textContent.indexOf('Catalogue No') >= 0) {
  1437. catalogue = k.lastChild.textContent.trim();
  1438. }
  1439. });
  1440. albumYear = remasterYear;
  1441. let genre;
  1442. if (/\/jazz\//i.test(response.finalUrl)) genre = 'Jazz';
  1443. if (/\/classical\//i.test(response.finalUrl)) genre = 'Classical';
  1444. get_desc_from_node('div#about > div > p', response.finalUrl, true);
  1445. ref = dom.querySelectorAll('div#related > div > ul > li');
  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.join(', ') || undefined;
  1453. ref = dom.querySelectorAll('div.has--sample');
  1454. totaltracks = ref.length;
  1455. let tracknumber = 0;
  1456. ref.forEach(function(k) {
  1457. tracknumber = ++tracknumber;
  1458. title = k.querySelector('p.c-track__title').textContent.trim().replace(/\s+/g, ' ');
  1459. duration = timestrToTime(k.querySelector('div.c-track__duration').textContent);
  1460. if (k.classList.contains('c-track')) {
  1461. track_artist = getArtists(k.parentNode.parentNode.querySelectorAll(':scope > div.c-track__details > ul > li'));
  1462. discsubtitle = k.parentNode.parentNode.querySelector(':scope > div > div > div > p.c-track__title');
  1463. discsubtitle = discsubtitle != null ? discsubtitle.textContent.trim() : undefined;
  1464. } else {
  1465. track_artist = getArtists(k.querySelectorAll(':scope > div.c-track__details > ul > li'));
  1466. discsubtitle = undefined;
  1467. }
  1468. if (track_artist == artist) track_artist = undefined;
  1469. track = [
  1470. artist,
  1471. album,
  1472. albumYear,
  1473. remasterYear,
  1474. label,
  1475. catalogue,
  1476. undefined, //encoding,
  1477. undefined, //format,
  1478. undefined,
  1479. undefined, //bitrate,
  1480. undefined, //bd,
  1481. undefined, //sr * 1000,
  1482. 2,
  1483. 'WEB',
  1484. genre,
  1485. discnumber,
  1486. totaldiscs,
  1487. discsubtitle,
  1488. tracknumber,
  1489. totaltracks,
  1490. title,
  1491. track_artist,
  1492. undefined,
  1493. composer,
  1494. undefined,
  1495. undefined,
  1496. compiler,
  1497. producer,
  1498. duration,
  1499. undefined,
  1500. undefined,
  1501. undefined,
  1502. response.finalUrl,
  1503. undefined,
  1504. description,
  1505. ];
  1506. tracks.push(track.join('\x1E'));
  1507. });
  1508. clipBoard.value = tracks.join('\n');
  1509. fill_from_text_music();
  1510.  
  1511. function getArtists(elems) {
  1512. if (elems == null) return undefined;
  1513. var artists = [];
  1514. elems.forEach(k => { artists.push(k.textContent.trim()) });
  1515. return artists.join(artists.length > 3 ? ', ' : ' & ');
  1516. }
  1517. } });
  1518. }
  1519.  
  1520. function get_desc_from_node(selector, url, quote = false) {
  1521. description = [];
  1522. dom.querySelectorAll(selector).forEach(k => { description.push(html2php(k, url).trim()) });
  1523. description = description.join('\n\n').trim().replace(/\n/g, '\x1C').replace(/\r/g, '\x1D');
  1524. if (quote && description.length > 0) description = '[quote]' + description + '[/quote]';
  1525. }
  1526. } // init_from_url_music
  1527.  
  1528. function fetch_image_from_store(response) {
  1529. if (response.readyState != 4 || !response.responseText) return;
  1530. ref = document.getElementById('image');
  1531. dom = htmlparser.parseFromString(response.responseText, "text/html");
  1532. if (dom == null) return;
  1533. if (response.finalUrl.toLowerCase().indexOf('qobuz.com') >= 0
  1534. && (ref = dom.querySelector('div.album-cover > img')) != null) set_image(ref.src);
  1535. if (response.finalUrl.toLowerCase().indexOf('highresaudio.com') >= 0
  1536. && (ref = dom.querySelector('div.albumbody > img.cover[data-pin-media]')) != null) {
  1537. set_image(ref.dataset.pinMedia);
  1538. }
  1539. if (response.finalUrl.toLowerCase().indexOf('bandcamp.com') >= 0
  1540. && (ref = dom.querySelector('div#tralbumArt > a.popupImage')) != null) set_image(ref.href);
  1541. if (response.finalUrl.toLowerCase().indexOf('7digital.com') >= 0
  1542. && (ref = dom.querySelector('span.release-packshot-image > img[itemprop="image"]')) != null) {
  1543. set_image(ref.src);
  1544. }
  1545. if (response.finalUrl.toLowerCase().indexOf('hdtracks.com') >= 0
  1546. && (ref = dom.querySelector('p.product-image > img')) != null) set_image(ref.src);
  1547. if (response.finalUrl.toLowerCase().indexOf('discogs.com') >= 0
  1548. && (ref = dom.querySelector('div#view_images > p:first-of-type > span > img')) != null) set_image(ref.src);
  1549. if (response.finalUrl.toLowerCase().indexOf('junodownload.com') >= 0
  1550. && (ref = dom.querySelector('a.productimage')) != null) set_image(ref.href);
  1551. if (response.finalUrl.toLowerCase().indexOf('supraphonline.cz') >= 0
  1552. && (ref = dom.querySelector('div.sexycover > img')) != null) set_image(ref.src.replace(/\?\d+$/, ''));
  1553. if (response.finalUrl.toLowerCase().indexOf('prestomusic.com') >= 0
  1554. && (ref = dom.querySelector('div.c-product-block__aside > a')) != null) set_image(ref.href.replace(/\?\d+$/, ''));
  1555. }
  1556. }
  1557.  
  1558. function fill_from_text_apps() {
  1559. if (!/^https?:\/\//i.test(clipBoard.value)) return false;
  1560. var description, tags = new TagManager();
  1561. if (clipBoard.value.toLowerCase().indexOf('//sanet') >= 0) {
  1562. GM_xmlhttpRequest({ method: 'GET', url: clipBoard.value, onload: function(response) {
  1563. if (response.readyState != 4 || response.status != 200) return;
  1564. dom = htmlparser.parseFromString(response.responseText, "text/html");
  1565.  
  1566. i = dom.querySelector('h1.item_title > span');
  1567. if (i != null && element_writable(ref = document.getElementById('title'))) {
  1568. ref.value = i.textContent.
  1569. replace(/\(x64\)$/i, '(64-bit)').
  1570. replace(/\bBuild\s+(\d+)/, 'build $1').
  1571. replace(/\b(?:Multilingual|Multilanguage)\b/, 'multilingual');
  1572. }
  1573. description = html2php(dom.querySelector('section.descr'), response.finalUrl);
  1574. var index = description.search(/^(?:\[i\]\[\/i\])?Homepage$.*/m);
  1575. if (index >= 0) description = description.slice(0, index);
  1576. description = description.trim().split(/\n/).slice(5).map(k => k.trimRight()).join('\n').trim();
  1577. ref = dom.querySelector('section.descr > div.release-info');
  1578. var releaseInfo = ref != null && ref.textContent.trim();
  1579. if (/\bLanguages?\s*:\s*(.*?)\s*(?:$|\|)/i.exec(releaseInfo) != null) {
  1580. description += '\n\n[b]Languages:[/b]\n' + RegExp.$1;
  1581. }
  1582. ref = dom.querySelector('div.txtleft > a');
  1583. if (ref != null) description += '\n\n[b]Product page:[/b]\n[url]' + de_anonymize(ref.href) + '[/url]';
  1584. write_description(description);
  1585. if ((ref = dom.querySelector('section.descr > div.center > a.mfp-image')) != null) {
  1586. set_image(ref.href);
  1587. } else {
  1588. ref = dom.querySelector('section.descr > div.center > img[data-src]');
  1589. if (ref != null) set_image(ref.dataset.src);
  1590. }
  1591. var cat = dom.querySelector('a.cat:last-of-type > span');
  1592. if (cat != null) {
  1593. if (cat.textContent.toLowerCase() == 'windows') {
  1594. tags.add('apps.windows');
  1595. if (/\bx64\b/i.test(releaseInfo)) tags.add('win64');
  1596. if (/\bx86\b/i.test(releaseInfo)) tags.add('win32');
  1597. }
  1598. if (cat.textContent.toLowerCase() == 'macos') tags.add('apps.mac');
  1599. if (cat.textContent.toLowerCase() == 'linux' || cat.textContent.toLowerCase() == 'unix') tags.add('apps.linux');
  1600. if (cat.textContent.toLowerCase() == 'android') tags.add('apps.android');
  1601. if (cat.textContent.toLowerCase() == 'ios') tags.add('apps.ios');
  1602. }
  1603. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  1604. ref.value = tags.toString();
  1605. }
  1606. }, });
  1607. return true;
  1608. }
  1609. return false;
  1610.  
  1611. function de_anonymize(uri) {
  1612. return typeof uri == 'string' ? uri.replace(/^https?:\/\/(?:www\.)?anonymz\.com\/\?/, '') : null;
  1613. }
  1614. }
  1615.  
  1616. function fill_from_text_books() {
  1617. if (!/^https?:\/\//i.test(clipBoard.value)) return false;
  1618. var description, tags = new TagManager();
  1619. if (clipBoard.value.toLowerCase().indexOf('martinus.cz') >= 0 || clipBoard.value.toLowerCase().indexOf('martinus.sk') >= 0) {
  1620. GM_xmlhttpRequest({ method: 'GET', url: clipBoard.value, onload: function(response) {
  1621. if (response.readyState != 4 || response.status != 200) return;
  1622. dom = htmlparser.parseFromString(response.responseText, "text/html");
  1623.  
  1624. function get_detail(x, y) {
  1625. var ref = dom.querySelector('section#details > div > div > div:first-of-type > div:nth-child(' +
  1626. x + ') > dl:nth-child(' + y + ') > dd');
  1627. return ref != null ? ref.textContent.trim() : null;
  1628. }
  1629.  
  1630. i = dom.querySelectorAll('article > ul > li > a');
  1631. if (i.length > 0 && element_writable(ref = document.getElementById('title'))) {
  1632. description = join_authors(i);
  1633. if ((i = dom.querySelector('article > h1')) != null) description += ' - ' + i.textContent.trim();
  1634. i = dom.querySelector('div.bar.mb-medium > div:nth-child(1) > dl > dd > span');
  1635. if (i != null && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  1636. ref.value = description;
  1637. }
  1638.  
  1639. description = '[quote]' + html2php(dom.querySelector('section#description > div')).
  1640. split(/\n/).slice(2).join('\n').trim() + '[/quote]';
  1641. const translation_map = [
  1642. [/\b(?:originál)/i, 'Original title'],
  1643. [/\b(?:datum|dátum|rok)\b/i, 'Release date'],
  1644. [/\b(?:katalog|katalóg)/i, 'Catalogue #'],
  1645. [/\b(?:stran|strán)\b/i, 'Page count'],
  1646. [/\bjazyk/i, 'Language'],
  1647. [/\b(?:nakladatel|vydavatel)/i, 'Publisher'],
  1648. [/\b(?:doporuč|ODPORÚČ)/i, 'Age rating'],
  1649. ];
  1650. dom.querySelectorAll('section#details > div > div > div:first-of-type > div > dl').forEach(function(detail) {
  1651. var lbl = detail.children[0].textContent.trim();
  1652. var val = detail.children[1].textContent.trim();
  1653. if (/\b(?:rozm)/i.test(lbl) || /\b(?:vazba|vázba)\b/i.test(lbl)) return;
  1654. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  1655. if (/\b(?:ISBN)\b/i.test(lbl)) {
  1656. val = '[url=https://www.worldcat.org/isbn/' + detail.children[1].textContent.trim() +
  1657. ']' + detail.children[1].textContent.trim() + '[/url]';
  1658. // } else if (/\b(?:ISBN)\b/i.test(lbl)) {
  1659. // val = '[url=https://www.goodreads.com/search/search?q=' + detail.children[1].textContent.trim() +
  1660. // '&search_type=books]' + detail.children[1].textContent.trim() + '[/url]';
  1661. }
  1662. description += '\n[b]' + lbl + ':[/b] ' + val;
  1663. });
  1664. description += '\n[b]More info:[/b] ' + response.finalUrl;
  1665. write_description(description);
  1666.  
  1667. if ((i = dom.querySelector('a.mj-product-preview > img')) != null) {
  1668. set_image(i.src.replace(/\?.*/, ''));
  1669. } else if ((i = dom.querySelector('head > meta[property="og:image"]')) != null) {
  1670. set_image(i.content.replace(/\?.*/, ''));
  1671. }
  1672.  
  1673. dom.querySelectorAll('dd > ul > li > a').forEach(x => { tags.add(x.textContent) });
  1674. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  1675. ref.value = tags.toString();
  1676. }
  1677. }, });
  1678. return true;
  1679. } else if (clipBoard.value.toLowerCase().indexOf('goodreads.com') >= 0) {
  1680. GM_xmlhttpRequest({ method: 'GET', url: clipBoard.value, onload: function(response) {
  1681. if (response.readyState != 4 || response.status != 200) return;
  1682. dom = htmlparser.parseFromString(response.responseText, "text/html");
  1683.  
  1684. i = dom.querySelectorAll('a.authorName > span');
  1685. if (i.length > 0 && element_writable(ref = document.getElementById('title'))) {
  1686. description = join_authors(i);
  1687. if ((i = dom.querySelector('h1#bookTitle')) != null) description += ' - ' + i.textContent.trim();
  1688. if ((i = dom.querySelector('div#details > div#row:nth-child(2)')) != null
  1689. && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  1690. ref.value = description;
  1691. }
  1692.  
  1693. description = '[quote]' + html2php(dom.querySelector('div#description > span:last-of-type'), response.finalUrl) + '[/quote]';
  1694.  
  1695. function strip(str) {
  1696. return typeof str == 'string' ?
  1697. str.replace(/\s{2,}/g, ' ').replace(/[\n\r]+/, '').replace(/\s*\.{3}(?:less|more)\b/g, '').trim() : null;
  1698. }
  1699.  
  1700. dom.querySelectorAll('div#details > div.row').forEach(k => { description += '\n' + strip(k.innerText) });
  1701. description += '\n';
  1702.  
  1703. dom.querySelectorAll('div#bookDataBox > div.clearFloats').forEach(function(detail) {
  1704. var lbl = detail.children[0].textContent.trim();
  1705. var val = strip(detail.children[1].textContent);
  1706. if (/\b(?:ISBN)\b/i.test(lbl) && ((matches = val.match(/\b(\d{13})\b/)) != null
  1707. || (matches = val.match(/\b(\d{10})\b/)) != null)) {
  1708. val = '[url=https://www.worldcat.org/isbn/' + matches[1] + ']' + strip(detail.children[1].textContent) + '[/url]';
  1709. }
  1710. description += '\n[b]' + lbl + ':[/b] ' + val;
  1711. });
  1712. description += '\n[b]More info:[/b] ' + response.finalUrl;
  1713. write_description(description);
  1714.  
  1715. if ((i = dom.querySelector('div.editionCover > img')) != null) {
  1716. set_image(i.src.replace(/\?.*/, ''));
  1717. }
  1718.  
  1719. dom.querySelectorAll('div.elementList > div.left').forEach(x => { tags.add(x.textContent.trim()) });
  1720. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  1721. ref.value = tags.toString();
  1722. }
  1723. }, });
  1724. return true;
  1725. } else if (clipBoard.value.toLowerCase().indexOf('databazeknih.cz') >= 0) {
  1726. let url = clipBoard.value;
  1727. if (url.toLowerCase().indexOf('show=alldesc') < 0) {
  1728. if (!url.includes('?')) { url += '?show=alldesc' } else { url += '&show=alldesc' }
  1729. }
  1730. GM_xmlhttpRequest({ method: 'GET', url: url, onload: function(response) {
  1731. if (response.readyState != 4 || response.status != 200) return;
  1732. dom = htmlparser.parseFromString(response.responseText, "text/html");
  1733.  
  1734. i = dom.querySelectorAll('span[itemprop="author"] > a');
  1735. if (i != null && element_writable(ref = document.getElementById('title'))) {
  1736. description = join_authors(i);
  1737. if ((i = dom.querySelector('h1[itemprop="name"]')) != null) description += ' - ' + i.textContent.trim();
  1738. i = dom.querySelector('span[itemprop="datePublished"]');
  1739. if (i != null && (i = extract_year(i.textContent))) description += ' (' + i + ')';
  1740. ref.value = description;
  1741. }
  1742.  
  1743. description = '[quote]' + html2php(dom.querySelector('p[itemprop="description"]'), response.finalUrl) + '[/quote]';
  1744.  
  1745. const translation_map = [
  1746. [/\b(?:orig)/i, 'Original title'],
  1747. [/\b(?:série)\b/i, 'Series'],
  1748. [/\b(?:vydáno)\b/i, 'Released'],
  1749. [/\b(?:stran)\b/i, 'Page count'],
  1750. [/\b(?:jazyk)\b/i, 'Language'],
  1751. [/\b(?:překlad)/i, 'Translation'],
  1752. [/\b(?:autor obálky)\b/i, 'Cover author'],
  1753. ];
  1754. dom.querySelectorAll('table.bdetail tr').forEach(function(detail) {
  1755. var lbl = detail.children[0].textContent.trim();
  1756. var val = detail.children[1].textContent.trim();
  1757. if (/(?:žánr|\bvazba)\b/i.test(lbl)) return;
  1758. translation_map.forEach(k => { if (k[0].test(lbl)) lbl = k[1] });
  1759. if (/\b(?:ISBN)\b/i.test(lbl) && /\b(\d+(?:-\d+)*)\b/.exec(val) != null) {
  1760. val = '[url=https://www.worldcat.org/isbn/' + RegExp.$1.replace(/-/g, '') +
  1761. ']' + detail.children[1].textContent.trim() + '[/url]';
  1762. }
  1763. description += '\n[b]' + lbl + '[/b] ' + val;
  1764. });
  1765. description += '\n[b]More info:[/b] ' + response.finalUrl.replace(/\?.*/, '');
  1766. write_description(description);
  1767.  
  1768. if ((i = dom.querySelector('div#icover_mid > a')) != null) set_image(i.href.replace(/\?.*/, ''));
  1769. if ((i = dom.querySelector('div#lbImage')) != null
  1770. && (matches = i.style.backgroundImage.match(/\burl\("(.*)"\)/i)) != null) {
  1771. set_image(matches[1].replace(/\?.*/, ''));
  1772. }
  1773.  
  1774. dom.querySelectorAll('h5[itemprop="genre"] > a').forEach(x => { tags.add(x.textContent.trim()) });
  1775. dom.querySelectorAll('a.tag').forEach(x => { tags.add(x.textContent.trim()) });
  1776. if (tags.length > 0 && element_writable(ref = document.getElementById('tags'))) {
  1777. ref.value = tags.toString();
  1778. }
  1779. }, });
  1780. return true;
  1781. }
  1782. return false;
  1783.  
  1784. function join_authors(nodeList) {
  1785. if (typeof nodeList != 'object') return null;
  1786. var authors = [];
  1787. nodeList.forEach(k => { authors.push(k.textContent.trim()) });
  1788. return authors.join(' & ');
  1789. }
  1790. }
  1791.  
  1792. function preview(n) {
  1793. if (!prefs.auto_preview) return;
  1794. var btn = document.querySelector('input.button_preview_' + n + '[type="button"][value="Preview"]');
  1795. if (btn != null) btn.click();
  1796. }
  1797.  
  1798. function html2php(node, url) {
  1799. var text = '';
  1800. if (node instanceof HTMLElement) node.childNodes.forEach(function(ch) {
  1801. if (ch.nodeType == 3) {
  1802. text += ch.data.replace(/\s+/g, ' ');
  1803. } else if (ch.nodeName == 'P') {
  1804. text += '\n' + html2php(ch, url);
  1805. } else if (ch.nodeName == 'DIV') {
  1806. text += '\n' + html2php(ch, url) + '\n\n';
  1807. } else if (ch.nodeName == 'LABEL') {
  1808. text += '\n\n[b]' + html2php(ch, url) + '[/b]';
  1809. } else if (ch.nodeName == 'SPAN') {
  1810. text += html2php(ch, url);
  1811. } else if (ch.nodeName == 'BR' || ch.nodeName == 'HR') {
  1812. text += '\n';
  1813. } else if (ch.nodeName == 'B' || ch.nodeName == 'STRONG') {
  1814. text += '[b]' + html2php(ch, url) + '[/b]';
  1815. } else if (ch.nodeName == 'I' || ch.nodeName == 'EM') {
  1816. text += '[i]' + html2php(ch, url) + '[/i]';
  1817. } else if (ch.nodeName == 'U') {
  1818. text += '[u]' + html2php(ch, url) + '[/u]';
  1819. } else if (ch.nodeName == 'CODE') {
  1820. text += '[pre]' + ch.textContent + '[/pre]';
  1821. } else if (ch.nodeName == 'A') {
  1822. text += ch.textContent.trim() ?
  1823. '[url=' + ch.href + ']' + ch.textContent.replace(/\s+/g, ' ') + '[/url]' :
  1824. '[url]' + ch.href + '[/url]';
  1825. } else if (ch.nodeName == 'IMG') {
  1826. text += '[img]' + (ch.dataset.src || ch.src) + '[/img]';
  1827. }
  1828. });
  1829. return text;
  1830. }
  1831.  
  1832. function write_description(desc) {
  1833. if (typeof desc != 'string') return;
  1834. if (element_writable(ref = document.getElementById('desc'))) ref.value = desc;
  1835. if ((ref = document.getElementById('body')) != null && !ref.disabled) {
  1836. if (ref.textLength > 0) ref.value += '\n\n';
  1837. ref.value += desc;
  1838. }
  1839. }
  1840.  
  1841. function set_image(url) {
  1842. var image = document.getElementById('image');
  1843. if (!element_writable(image)) return false;
  1844. image.value = url;
  1845.  
  1846. if (prefs.auto_preview_cover) {
  1847. if ((child = document.getElementById('cover preview')) == null) {
  1848. elem = document.createElement('div');
  1849. elem.style.paddingTop = '10px';
  1850. child = document.createElement('img');
  1851. child.id = 'cover preview';
  1852. child.style.width = '90%';
  1853. elem.append(child);
  1854. image.parentNode.previousElementSibling.append(elem);
  1855. }
  1856. child.src = url;
  1857. }
  1858. // Re-Host to PTPIMG
  1859. if (prefs.auto_rehost_cover) {
  1860. var rehost_btn = document.querySelector('input.rehost_it_cover[type="button"]');
  1861. if (rehost_btn != null) {
  1862. rehost_btn.click();
  1863. } else {
  1864. var pr = rehost_imgs([url]);
  1865. if (pr != null) pr.then(new_urls => { image.value = new_urls[0] });
  1866. }
  1867. }
  1868. }
  1869.  
  1870. // PTPIMG rehoster taken from `PTH PTPImg It`
  1871. function rehost_imgs(urls) {
  1872. if (!Array.isArray(urls)) return null;
  1873. var config = JSON.parse(window.localStorage.ptpimg_it);
  1874. return config.api_key ? new Promise(ptpimg_upload_urls).catch(m => { alert(m) }) : null;
  1875.  
  1876. function ptpimg_upload_urls(resolve, reject) {
  1877. const boundary = 'NN-GGn-PTPIMG';
  1878. var data = '--' + boundary + "\n";
  1879. data += 'Content-Disposition: form-data; name="link-upload"\n\n';
  1880. data += urls.map(function(url) {
  1881. return url.toLowerCase().indexOf('://reho.st/') < 0 && url.toLowerCase().indexOf('discogs.com') >= 0 ?
  1882. 'https://reho.st/' + url : url;
  1883. }).join('\n') + '\n';
  1884. data += '--' + boundary + '\n';
  1885. data += 'Content-Disposition: form-data; name="api_key"\n\n';
  1886. data += config.api_key + '\n';
  1887. data += '--' + boundary + '--';
  1888. GM_xmlhttpRequest({
  1889. method: 'POST',
  1890. url: 'https://ptpimg.me/upload.php',
  1891. responseType: 'json',
  1892. headers: {
  1893. 'Content-type': 'multipart/form-data; boundary=' + boundary,
  1894. },
  1895. data: data,
  1896. onload: response => {
  1897. if (response.status != 200) reject('Response error ' + response.status);
  1898. resolve(response.response.map(item => 'https://ptpimg.me/' + item.code + '.' + item.ext));
  1899. },
  1900. });
  1901. }
  1902. }
  1903.  
  1904. function element_writable(elem) { return elem != null && !elem.disabled && (overwrite || !elem.value) }
  1905. }
  1906.  
  1907. function add_artist() { exec(function() { AddArtistField() }) }
  1908.  
  1909. function array_homogenous(arr) { return arr.every(k => k === arr[0]) }
  1910.  
  1911. function exec(fn) {
  1912. let script = document.createElement('script');
  1913. script.type = 'application/javascript';
  1914. script.textContent = '(' + fn + ')();';
  1915. document.body.appendChild(script); // run the script
  1916. document.body.removeChild(script); // clean up
  1917. }
  1918.  
  1919. function makeTimeString(duration) {
  1920. let t = Math.abs(Math.round(duration));
  1921. let H = Math.floor(t / 60 ** 2);
  1922. let M = Math.floor(t / 60 % 60);
  1923. let S = t % 60;
  1924. return (duration < 0 ? '-' : '') +
  1925. (H > 0 ? H + ':' + M.toString().padStart(2, '0') : M.toString()) +
  1926. ':' + S.toString().padStart(2, '0');
  1927. }
  1928.  
  1929. function timestrToTime(str) {
  1930. return /\b(?:(?:(\d+):)?(\d+):)?(\d+)\b/.exec(str) != null ?
  1931. parseInt(RegExp.$1 || 0) * 60 ** 2 + parseInt(RegExp.$2 || 0) * 60 + parseInt(RegExp.$3 || 0) : 0;
  1932. }
  1933.  
  1934. function extract_year(expr) {
  1935. if (typeof expr != 'string') return null;
  1936. var year, m = expr.match(/\b(\d{4})\b/);
  1937. return m != null && parseInt(m[1]) || parseInt(expr) || null;
  1938. }
  1939.  
  1940. function isRED() { return document.domain.toLowerCase().endsWith('redacted.ch') }
  1941. function isNWCD() { return document.domain.toLowerCase().endsWith('notwhat.cd') }
  1942. function isOrpheus() { return document.domain.toLowerCase().endsWith('orpheus.network') }
  1943.  
  1944. function reInParenthesis(expr) { return new RegExp('\\s+\\([^\\(\\)]*'.concat(expr, '[^\\(\\)]*\\)$'), 'i') }
  1945. function reInBrackets(expr) { return new RegExp('\\s+\\[[^\\[\\]]*'.concat(expr, '[^\\[\\]]*\\]$'), 'i') }
  1946.  
  1947. function matchCaseless(str) { return str.toLowerCase() == this.toLowerCase() }
  1948.  
  1949. Array.prototype.includesCaseless = function(str) { return this.find(matchCaseless, str) != undefined };
  1950.  
  1951. function addWarning(text, cls) {
  1952. warnings = document.getElementById('UA warnings');
  1953. if (warnings == null) {
  1954. var ua = document.getElementById('upload assistant');
  1955. if (ua == null) return null;
  1956. warnings = document.createElement('TR');
  1957. if (warnings == null) return null;
  1958. warnings.id = 'UA warnings';
  1959. ua.children[0].append(warnings);
  1960.  
  1961. elem = document.createElement('TD');
  1962. if (elem == null) return null;
  1963. elem.colSpan = 2;
  1964. elem.style.padding = '15px';
  1965. elem.style.textAlign = 'left';
  1966. warnings.append(elem);
  1967. } else {
  1968. elem = warnings.children[0];
  1969. if (elem == null) return null;
  1970. }
  1971. var div = document.createElement('DIV');
  1972. div.classList.add('ua-warning', cls);
  1973. div.textContent = text;
  1974. return elem.appendChild(div);
  1975. }