RED (+ NWCD, Orpheus) Upload Assistant

Script fills in as much accurately the upload and group edit forms based on foobar2000's playlist selection via pasted output of copy command, release consistency check, two tracklist layouts, basic colours customization, featured artists extraction, image URl fetching from store and more...

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

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