xref: /plugin/botmon/script.js (revision 25d766a156aaad87f126d68b662608b64cfa87c9)
1"use strict";
2/* DokuWiki BotMon Plugin Script file */
3/* 12.09.2025 - 0.3.0 - beta */
4/* Author: Sascha Leib <ad@hominem.info> */
5
6// enumeration of user types:
7const BM_USERTYPE = Object.freeze({
8	'UNKNOWN': 'unknown',
9	'KNOWN_USER': 'user',
10	'HUMAN': 'human',
11	'LIKELY_BOT': 'likely_bot',
12	'KNOWN_BOT': 'known_bot'
13});
14
15/* BotMon root object */
16const BotMon = {
17
18	init: function() {
19		//console.info('BotMon.init()');
20
21		// find the plugin basedir:
22		this._baseDir = document.currentScript.src.substring(0, document.currentScript.src.indexOf('/exe/'))
23			+ '/plugins/botmon/';
24
25		// read the page language from the DOM:
26		this._lang = document.getRootNode().documentElement.lang || this._lang;
27
28		// get the time offset:
29		this._timeDiff = BotMon.t._getTimeOffset();
30
31		// init the sub-objects:
32		BotMon.t._callInit(this);
33	},
34
35	_baseDir: null,
36	_lang: 'en',
37	_today: (new Date()).toISOString().slice(0, 10),
38	_timeDiff: '',
39
40	/* internal tools */
41	t: {
42		/* helper function to call inits of sub-objects */
43		_callInit: function(obj) {
44			//console.info('BotMon.t._callInit(obj=',obj,')');
45
46			/* call init / _init on each sub-object: */
47			Object.keys(obj).forEach( (key,i) => {
48				const sub = obj[key];
49				let init = null;
50				if (typeof sub === 'object' && sub.init) {
51					init = sub.init;
52				}
53
54				// bind to object
55				if (typeof init == 'function') {
56					const init2 = init.bind(sub);
57					init2(obj);
58				}
59			});
60		},
61
62		/* helper function to calculate the time difference to UTC: */
63		_getTimeOffset: function() {
64			const now = new Date();
65			let offset = now.getTimezoneOffset(); // in minutes
66			const sign = Math.sign(offset); // +1 or -1
67			offset = Math.abs(offset); // always positive
68
69			let hours = 0;
70			while (offset >= 60) {
71				hours += 1;
72				offset -= 60;
73			}
74			return ( hours > 0 ? sign * hours + ' h' : '') + (offset > 0 ? ` ${offset} min` : '');
75		},
76
77		/* helper function to create a new element with all attributes and text content */
78		_makeElement: function(name, atlist = undefined, text = undefined) {
79			var r = null;
80			try {
81				r = document.createElement(name);
82				if (atlist) {
83					for (let attr in atlist) {
84						r.setAttribute(attr, atlist[attr]);
85					}
86				}
87				if (text) {
88					r.textContent = text.toString();
89				}
90			} catch(e) {
91				console.error(e);
92			}
93			return r;
94		},
95
96		/* helper to convert an ip address string to a normalised format: */
97		_ip2Num: function(ip) {
98			if (!ip) {
99				return 'null';
100			} else if (ip.indexOf(':') > 0) { /* IP6 */
101				return (ip.split(':').map(d => ('0000'+d).slice(-4) ).join(''));
102			} else { /* IP4 */
103				return Number(ip.split('.').map(d => ('000'+d).slice(-3) ).join(''));
104			}
105		},
106
107		/* helper function to format a Date object to show only the time. */
108		/* returns String */
109		_formatTime: function(date) {
110
111			if (date) {
112				return date.getHours() + ':' + ('0'+date.getMinutes()).slice(-2) + ':' + ('0'+date.getSeconds()).slice(-2);
113			} else {
114				return null;
115			}
116
117		},
118
119		/* helper function to show a time difference in seconds or minutes */
120		/* returns String */
121		_formatTimeDiff: function(dateA, dateB) {
122
123			// if the second date is ealier, swap them:
124			if (dateA > dateB) dateB = [dateA, dateA = dateB][0];
125
126			// get the difference in milliseconds:
127			let ms = dateB - dateA;
128
129			if (ms > 50) { /* ignore small time spans */
130				const h = Math.floor((ms / (1000 * 60 * 60)) % 24);
131				const m = Math.floor((ms / (1000 * 60)) % 60);
132				const s = Math.floor((ms / 1000) % 60);
133
134				return ( h>0 ? h + 'h ': '') + ( m>0 ? m + 'm ': '') + ( s>0 ? s + 's': '');
135			}
136
137			return null;
138
139		}
140	}
141};
142
143/* everything specific to the "Today" tab is self-contained in the "live" object: */
144BotMon.live = {
145	init: function() {
146		//console.info('BotMon.live.init()');
147
148		// set the title:
149		const tDiff = '(<abbr title="Coordinated Universal Time">UTC</abbr>' + (BotMon._timeDiff != '' ? `, ${BotMon._timeDiff}` : '' ) + ')';
150		BotMon.live.gui.status.setTitle(`Data for <time datetime=${BotMon._today}>${BotMon._today}</time> ${tDiff}`);
151
152		// init sub-objects:
153		BotMon.t._callInit(this);
154	},
155
156	data: {
157		init: function() {
158			//console.info('BotMon.live.data.init()');
159
160			// call sub-inits:
161			BotMon.t._callInit(this);
162		},
163
164		// this will be called when the known json files are done loading:
165		_dispatch: function(file) {
166			//console.info('BotMon.live.data._dispatch(,',file,')');
167
168			// shortcut to make code more readable:
169			const data = BotMon.live.data;
170
171			// set the flags:
172			switch(file) {
173				case 'rules':
174					data._dispatchRulesLoaded = true;
175					break;
176				case 'bots':
177					data._dispatchBotsLoaded = true;
178					break;
179				case 'clients':
180					data._dispatchClientsLoaded = true;
181					break;
182				case 'platforms':
183					data._dispatchPlatformsLoaded = true;
184					break;
185				default:
186					// ignore
187			}
188
189			// are all the flags set?
190			if (data._dispatchBotsLoaded && data._dispatchClientsLoaded && data._dispatchPlatformsLoaded && data._dispatchRulesLoaded) {
191				// chain the log files loading:
192				BotMon.live.data.loadLogFile('srv', BotMon.live.data._onServerLogLoaded);
193			}
194		},
195		// flags to track which data files have been loaded:
196		_dispatchBotsLoaded: false,
197		_dispatchClientsLoaded: false,
198		_dispatchPlatformsLoaded: false,
199		_dispatchRulesLoaded: false,
200
201		// event callback, after the server log has been loaded:
202		_onServerLogLoaded: function() {
203			//console.info('BotMon.live.data._onServerLogLoaded()');
204
205			// chain the client log file to load:
206			BotMon.live.data.loadLogFile('log', BotMon.live.data._onClientLogLoaded);
207		},
208
209		// event callback, after the client log has been loaded:
210		_onClientLogLoaded: function() {
211			//console.info('BotMon.live.data._onClientLogLoaded()');
212
213			// chain the ticks file to load:
214			BotMon.live.data.loadLogFile('tck', BotMon.live.data._onTicksLogLoaded);
215
216		},
217
218		// event callback, after the tiker log has been loaded:
219		_onTicksLogLoaded: function() {
220			//console.info('BotMon.live.data._onTicksLogLoaded()');
221
222			// analyse the data:
223			BotMon.live.data.analytics.analyseAll();
224
225			// sort the data:
226			// #TODO
227
228			// display the data:
229			BotMon.live.gui.overview.make();
230
231			//console.log(BotMon.live.data.model._visitors);
232
233		},
234
235		model: {
236			// visitors storage:
237			_visitors: [],
238
239			// find an already existing visitor record:
240			findVisitor: function(visitor) {
241				//console.info('BotMon.live.data.model.findVisitor()');
242				//console.log(visitor);
243
244				// shortcut to make code more readable:
245				const model = BotMon.live.data.model;
246
247				const timeout = 60 * 60 * 1000; // session timeout: One hour
248
249				// loop over all visitors already registered:
250				for (let i=0; i<model._visitors.length; i++) {
251					const v = model._visitors[i];
252
253					if (visitor._type == BM_USERTYPE.KNOWN_BOT) { // known bots
254
255						// bots match when their ID matches:
256						if (v._bot && v._bot.id == visitor._bot.id) {
257							return v;
258						}
259
260					} else { /*if (visitor._type == BM_USERTYPE.KNOWN_USER) { // registered users
261
262						// visitors match when their names match:
263						if ( v.usr == visitor.usr
264						&& v.ip == visitor.ip
265						&& v.agent == visitor.agent) {
266							return v;
267						}
268					} else { // any other visitor
269
270						if (Math.abs(v._lastSeen - visitor.ts) < timeout) { // ignore timed out visits */
271							if ( v.id == visitor.id) { // match the DW/PHP IDs
272								return v;
273							}
274						/*}*/
275					}
276				}
277				return null; // nothing found
278			},
279
280			/* if there is already this visit registered, return the page view item */
281			_getPageView: function(visit, view) {
282
283				// shortcut to make code more readable:
284				const model = BotMon.live.data.model;
285
286				for (let i=0; i<visit._pageViews.length; i++) {
287					const pv = visit._pageViews[i];
288					if (pv.pg == view.pg) {
289						return pv;
290					}
291				}
292				return null; // not found
293			},
294
295			// register a new visitor (or update if already exists)
296			registerVisit: function(nv, type) {
297				//console.info('registerVisit', nv, type);
298
299				// shortcut to make code more readable:
300				const model = BotMon.live.data.model;
301
302				// is it a known bot?
303				const bot = BotMon.live.data.bots.match(nv.agent);
304
305				// enrich new visitor with relevant data:
306				if (!nv._bot) nv._bot = bot ?? null; // bot info
307				nv._type = ( bot ? BM_USERTYPE.KNOWN_BOT : ( nv.usr && nv.usr !== '' ? BM_USERTYPE.KNOWN_USER : BM_USERTYPE.UNKNOWN ) ); // user type
308				if (bot && bot.geo) {
309					if (!nv.geo || nv.geo == '' || nv.geo == 'ZZ') nv.geo = bot.geo;
310				} else if (!nv.geo ||nv.geo == '') {
311					nv.geo = 'ZZ';
312				}
313
314				// update first and last seen:
315				if (!nv._firstSeen) nv._firstSeen = nv.ts; // first-seen
316				nv._lastSeen = nv.ts; // last-seen
317
318				// country name:
319				try {
320					nv._country = ( nv.geo == 'local' ? "localhost" : "Unknown" );
321					if (nv.geo && nv.geo !== '' && nv.geo !== 'ZZ' && nv.geo !== 'local') {
322						const countryName = new Intl.DisplayNames(['en', BotMon._lang], {type: 'region'});
323						nv._country = countryName.of(nv.geo.substring(0,2)) ?? nv.geo;
324					}
325				} catch (err) {
326					console.error(err);
327					nv._country = 'Error';
328				}
329
330				// check if it already exists:
331				let visitor = model.findVisitor(nv);
332				if (!visitor) {
333					visitor = nv;
334					visitor._seenBy = [type];
335					visitor._pageViews = []; // array of page views
336					visitor._hasReferrer = false; // has at least one referrer
337					visitor._jsClient = false; // visitor has been seen logged by client js as well
338					visitor._client = BotMon.live.data.clients.match(nv.agent) ?? null; // client info
339					visitor._platform = BotMon.live.data.platforms.match(nv.agent); // platform info
340					model._visitors.push(visitor);
341				} else { // update existing
342					if (visitor._firstSeen > nv.ts) {
343						visitor._firstSeen = nv.ts;
344					}
345				}
346
347				// find browser
348
349				// is this visit already registered?
350				let prereg = model._getPageView(visitor, nv);
351				if (!prereg) {
352					// add new page view:
353					prereg = model._makePageView(nv, type);
354					visitor._pageViews.push(prereg);
355				} else {
356					// update last seen date
357					prereg._lastSeen = nv.ts;
358					// increase view count:
359					prereg._viewCount += 1;
360					prereg._tickCount += 1;
361				}
362
363				// update referrer state:
364				visitor._hasReferrer = visitor._hasReferrer ||
365					(prereg.ref !== undefined && prereg.ref !== '');
366
367				// update time stamp for last-seen:
368				if (visitor._lastSeen < nv.ts) {
369					visitor._lastSeen = nv.ts;
370				}
371
372				// if needed:
373				return visitor;
374			},
375
376			// updating visit data from the client-side log:
377			updateVisit: function(dat) {
378				//console.info('updateVisit', dat);
379
380				// shortcut to make code more readable:
381				const model = BotMon.live.data.model;
382
383				const type = 'log';
384
385				let visitor = BotMon.live.data.model.findVisitor(dat);
386				if (!visitor) {
387					visitor = model.registerVisit(dat, type);
388				}
389				if (visitor) {
390
391					if (visitor._lastSeen < dat.ts) {
392						visitor._lastSeen = dat.ts;
393					}
394					if (!visitor._seenBy.includes(type)) {
395						visitor._seenBy.push(type);
396					}
397					visitor._jsClient = true; // seen by client js
398				}
399
400				// find the page view:
401				let prereg = BotMon.live.data.model._getPageView(visitor, dat);
402				if (prereg) {
403					// update the page view:
404					prereg._lastSeen = dat.ts;
405					if (!prereg._seenBy.includes(type)) prereg._seenBy.push(type);
406					prereg._jsClient = true; // seen by client js
407				} else {
408					// add the page view to the visitor:
409					prereg = model._makePageView(dat, type);
410					visitor._pageViews.push(prereg);
411				}
412				prereg._tickCount += 1;
413			},
414
415			// updating visit data from the ticker log:
416			updateTicks: function(dat) {
417				//console.info('updateTicks', dat);
418
419				// shortcut to make code more readable:
420				const model = BotMon.live.data.model;
421
422				const type = 'tck';
423
424				// find the visit info:
425				let visitor = model.findVisitor(dat);
426				if (!visitor) {
427					console.info(`No visitor with ID “${dat.id}” found, registering as a new one.`);
428					visitor = model.registerVisit(dat, type);
429				}
430				if (visitor) {
431					// update visitor:
432					if (visitor._lastSeen < dat.ts) visitor._lastSeen = dat.ts;
433					if (!visitor._seenBy.includes(type)) visitor._seenBy.push(type);
434
435					// get the page view info:
436					let pv = model._getPageView(visitor, dat);
437					if (!pv) {
438						console.info(`No page view for visit ID “${dat.id}”, page “${dat.pg}”, registering a new one.`);
439						pv = model._makePageView(dat, type);
440						visitor._pageViews.push(pv);
441					}
442
443					// update the page view info:
444					if (!pv._seenBy.includes(type)) pv._seenBy.push(type);
445					if (pv._lastSeen.getTime() < dat.ts.getTime()) pv._lastSeen = dat.ts;
446					pv._tickCount += 1;
447
448				}
449			},
450
451			// helper function to create a new "page view" item:
452			_makePageView: function(data, type) {
453				// console.info('_makePageView', data);
454
455				// try to parse the referrer:
456				let rUrl = null;
457				try {
458					rUrl = ( data.ref && data.ref !== '' ? new URL(data.ref) : null );
459				} catch (e) {
460					console.warn(`Invalid referer: “${data.ref}”.`);
461				}
462
463				return {
464					_by: type,
465					ip: data.ip,
466					pg: data.pg,
467					lang: data.lang || '??',
468					_ref: rUrl,
469					_firstSeen: data.ts,
470					_lastSeen: data.ts,
471					_seenBy: [type],
472					_jsClient: ( type !== 'srv'),
473					_viewCount: 1,
474					_tickCount: 0
475				};
476			}
477		},
478
479		analytics: {
480
481			init: function() {
482				//console.info('BotMon.live.data.analytics.init()');
483			},
484
485			// data storage:
486			data: {
487				totalVisits: 0,
488				totalPageViews: 0,
489				humanPageViews: 0,
490				bots: {
491					known: 0,
492					suspected: 0,
493					human: 0,
494					users: 0
495				}
496			},
497
498			// sort the visits by type:
499			groups: {
500				knownBots: [],
501				suspectedBots: [],
502				humans: [],
503				users: []
504			},
505
506			// all analytics
507			analyseAll: function() {
508				//console.info('BotMon.live.data.analytics.analyseAll()');
509
510				// shortcut to make code more readable:
511				const model = BotMon.live.data.model;
512				const me = BotMon.live.data.analytics;
513
514				BotMon.live.gui.status.showBusy("Analysing data …");
515
516				// loop over all visitors:
517				model._visitors.forEach( (v) => {
518
519					// count visits and page views:
520					this.data.totalVisits += 1;
521					this.data.totalPageViews += v._pageViews.length;
522
523					// check for typical bot aspects:
524					let botScore = 0;
525
526					if (v._type == BM_USERTYPE.KNOWN_BOT) { // known bots
527
528						this.data.bots.known += v._pageViews.length;
529						this.groups.knownBots.push(v);
530
531					} else if (v._type == BM_USERTYPE.KNOWN_USER) { // known users */
532
533						this.data.bots.users += v._pageViews.length;
534						this.groups.users.push(v);
535
536					} else {
537
538						// get evaluation:
539						const e = BotMon.live.data.rules.evaluate(v);
540						v._eval = e.rules;
541						v._botVal = e.val;
542
543						if (e.isBot) { // likely bots
544							v._type = BM_USERTYPE.LIKELY_BOT;
545							this.data.bots.suspected += v._pageViews.length;
546							this.groups.suspectedBots.push(v);
547						} else { // probably humans
548							v._type = BM_USERTYPE.HUMAN;
549							this.data.bots.human += v._pageViews.length;
550							this.groups.humans.push(v);
551						}
552					}
553
554					// perform actions depending on the visitor type:
555					if (v._type == BM_USERTYPE.KNOWN_BOT || v._type == BM_USERTYPE.LIKELY_BOT) { /* bots only */
556
557						// add bot views to IP range information:
558						/*v._pageViews.forEach( pv => {
559							me.addToIPRanges(pv.ip);
560						});*/
561
562						// add to the country lists:
563						me.addToCountries(v.geo, v._country, v._type);
564
565					} else { /* humans only */
566
567						// add browser and platform statistics:
568						me.addBrowserPlatform(v);
569					}
570
571				});
572
573				BotMon.live.gui.status.hideBusy('Done.');
574			},
575
576			// visits from IP ranges:
577			/*_ipRange: {
578				ip4: [],
579				ip6: []
580			},*/
581			/**
582			 * Adds a visit to the IP range statistics.
583			 *
584			 * This helps to identify IP ranges that are used by bots.
585			 *
586			 * @param {string} ip The IP address to add.
587			 */
588			/*addToIPRanges: function(ip) {
589
590				// #TODO: handle nestled ranges!
591				const me = BotMon.live.data.analytics;
592				const ipv = (ip.indexOf(':') > 0 ? 6 : 4);
593
594				const ipArr = ip.split( ipv == 6 ? ':' : '.');
595				const maxSegments = (ipv == 6 ? 4 : 3);
596
597				let arr = (ipv == 6 ? me._ipRange.ip6 : me._ipRange.ip4);
598
599				// find any existing segment entry:
600				it = null;
601				for (let i=0; i < arr.length; i++) {
602					const sig = arr[i];
603					if (sig.seg == ipArr[0]) {
604						it = sig;
605						break;
606					}
607				}
608
609				// create if not found:
610				if (!it) {
611					it = {seg: ipArr[0], count: 1};
612					//if (i<maxSegments) it.sub = [];
613					arr.push(it);
614
615				} else { // increase count:
616
617					it.count += 1;
618				}
619
620			},*/
621			/*getTopBotIPRanges: function(max) {
622
623				const me = BotMon.live.data.analytics;
624
625				const kMinHits = 2;
626
627				// combine the ip lists, removing all lower volume branches:
628				let ipTypes = [4,6];
629				const tmpList = [];
630				for (let i=0; i<ipTypes.length; i++) {
631					const ipType = ipTypes[i];
632					(ipType == 6 ? me._ipRange.ip6 : me._ipRange.ip4).forEach( it => {
633						if (it.count > kMinHits) {
634							it.type = ipType;
635							tmpList.push(it);
636						}
637						});
638					tmpList.sort( (a,b) => b.count - a.count);
639				}
640
641				// reduce to only the top (max) items and create the target format:
642				// #TODO: handle nestled ranges!
643				let rList = [];
644				for (let j=0; Math.min(max, tmpList.length) > j; j++) {
645					const rangeInfo = tmpList[j];
646					rList.push({
647						'ip': rangeInfo.seg + ( rangeInfo.type == 4 ? '.x.x.x' : '::x'),
648						'typ': rangeInfo.type,
649						'num': rangeInfo.count
650					});
651				}
652
653				return rList;
654			},*/
655
656			/* countries of visits */
657			_countries: {
658				'user': [],
659				'human': [],
660				'likelyBot': [],
661				'known_bot': []
662
663			},
664			/**
665			 * Adds a country code to the statistics.
666			 *
667			 * @param {string} iso The ISO 3166-1 alpha-2 country code.
668			 */
669			addToCountries: function(iso, name, type) {
670
671				const me = BotMon.live.data.analytics;
672
673				// find the correct array:
674				let arr = null;
675				switch (type) {
676
677					case BM_USERTYPE.KNOWN_USER:
678						arr = me._countries.user;
679						break;
680					case BM_USERTYPE.HUMAN:
681						arr = me._countries.human;
682						break;
683					case BM_USERTYPE.LIKELY_BOT:
684						arr = me._countries.likelyBot;
685						break;
686					case BM_USERTYPE.KNOWN_BOT:
687						arr = me._countries.known_bot;
688						break;
689					default:
690						console.warn(`Unknown user type ${type} in function addToCountries.`);
691				}
692
693				if (arr) {
694					let cRec = arr.find( it => it.iso == iso);
695					if (!cRec) {
696						cRec = {
697							'iso': iso,
698							'name': name,
699							'count': 1
700						};
701						arr.push(cRec);
702					} else {
703						cRec.count += 1;
704					}
705				}
706			},
707
708			/**
709			 * Returns a list of countries with visit counts, sorted by visit count in descending order.
710			 *
711			 * @param {BM_USERTYPE} type The type of visitors to return.
712			 * @param {number} max The maximum number of entries to return.
713			 * @return {Array} A list of objects with properties 'iso' (ISO 3166-1 alpha-2 country code) and 'count' (visit count).
714			 */
715			getCountryList: function(type, max) {
716
717				const me = BotMon.live.data.analytics;
718
719				// find the correct array:
720				let arr = null;
721				switch (type) {
722
723					case BM_USERTYPE.KNOWN_USER:
724						arr = me._countries.user;
725						break;
726					case BM_USERTYPE.HUMAN:
727						arr = me._countries.human;
728						break;
729					case BM_USERTYPE.LIKELY_BOT:
730						arr = me._countries.likelyBot;
731						break;
732					case BM_USERTYPE.KNOWN_BOT:
733						arr = me._countries.known_bot;
734						break;
735					default:
736						console.warn(`Unknown user type ${type} in function getCountryList.`);
737				}
738
739				if (arr) {
740					// sort by visit count:
741					arr.sort( (a,b) => b.count - a.count);
742
743					// reduce to only the top (max) items and create the target format:
744					let rList = [];
745					for (let i=0; Math.min(max, arr.length) > i; i++) {
746						const cRec = arr[i];
747						rList.push({
748							'iso': cRec.iso,
749							'name': cRec.name,
750							'count': cRec.count
751						});
752					}
753					return rList;
754				}
755				return [];
756			},
757
758			/* browser and platform of human visitors */
759			_browsers: [],
760			_platforms: [],
761
762			addBrowserPlatform: function(visitor) {
763				//console.info('addBrowserPlatform', visitor);
764
765				const me = BotMon.live.data.analytics;
766
767				// add to browsers list:
768				let browserRec = ( visitor._client ? visitor._client : {'id': 'unknown'});
769				if (visitor._client) {
770					let bRec = me._browsers.find( it => it.id == browserRec.id);
771					if (!bRec) {
772						bRec = {
773							'id': browserRec.id,
774							'count': 1
775						};
776						me._browsers.push(bRec);
777					} else {
778						bRec.count += 1;
779					}
780				}
781
782				// add to platforms list:
783				let platformRec = ( visitor._platform ? visitor._platform : {'id': 'unknown'});
784				if (visitor._platform) {
785					let pRec = me._platforms.find( it => it.id == platformRec.id);
786					if (!pRec) {
787						pRec = {
788							'id': platformRec.id,
789							'count': 1
790						};
791						me._platforms.push(pRec);
792					} else {
793						pRec.count += 1;
794					}
795				}
796
797			},
798
799			getTopBrowsers: function(max) {
800
801				const me = BotMon.live.data.analytics;
802
803				me._browsers.sort( (a,b) => b.count - a.count);
804
805				// how many browsers to show:
806				const max2 = ( me._browsers.length >= max ? max-1 : max );
807
808				const rArr = []; // return array
809				let total = 0;
810				const others = {
811					'id': 'other',
812					'name': "Others",
813					'count': 0
814				};
815				for (let i=0; i < me._browsers.length; i++) {
816					if (i < max2) {
817						rArr.push({
818							'id': me._browsers[i].id,
819							'name': BotMon.live.data.clients.getName(me._browsers[i].id),
820							'count': me._browsers[i].count
821						});
822						total += me._browsers[i].count;
823					} else {
824						others.count += me._browsers[i].count;
825						total += me._browsers[i].count;
826					}
827				};
828
829				if (me._browsers.length > (max-1)) {
830					rArr.push(others);
831				};
832
833				// update percentages:
834				rArr.forEach( it => {
835					it.pct = Math.round(it.count * 100 / total);
836				});
837
838				return rArr;
839			},
840
841			getTopPlatforms: function(max) {
842
843				const me = BotMon.live.data.analytics;
844
845				me._platforms.sort( (a,b) => b.count - a.count);
846				// how many browsers to show:
847				const max2 = ( me._platforms.length >= max ? max-1 : max );
848
849				const rArr = []; // return array
850				let total = 0;
851				const others = {
852					'id': 'other',
853					'name': "Others",
854					'count': 0
855				};
856				for (let i=0; i < me._platforms.length; i++) {
857					if (i < max2) {
858						rArr.push({
859							'id': me._platforms[i].id,
860							'name': BotMon.live.data.platforms.getName(me._platforms[i].id),
861							'count': me._platforms[i].count
862						});
863						total += me._platforms[i].count;
864					} else {
865						others.count += me._platforms[i].count;
866						total += me._platforms[i].count;
867					}
868				};
869
870				if (me._platforms.length > (max-1)) {
871					rArr.push(others);
872				};
873
874				// update percentages:
875				rArr.forEach( it => {
876					it.pct = Math.round(it.count * 100 / total);
877				});
878
879				return rArr;
880			}
881		},
882
883		bots: {
884			// loads the list of known bots from a JSON file:
885			init: async function() {
886				//console.info('BotMon.live.data.bots.init()');
887
888				// Load the list of known bots:
889				BotMon.live.gui.status.showBusy("Loading known bots …");
890				const url = BotMon._baseDir + 'config/known-bots.json';
891				try {
892					const response = await fetch(url);
893					if (!response.ok) {
894						throw new Error(`${response.status} ${response.statusText}`);
895					}
896
897					this._list = await response.json();
898					this._ready = true;
899
900				} catch (error) {
901					BotMon.live.gui.status.setError("Error while loading the known bots file:", error.message);
902				} finally {
903					BotMon.live.gui.status.hideBusy("Status: Done.");
904					BotMon.live.data._dispatch('bots')
905				}
906			},
907
908			// returns bot info if the clientId matches a known bot, null otherwise:
909			match: function(agent) {
910				//console.info('BotMon.live.data.bots.match(',agent,')');
911
912				const BotList = BotMon.live.data.bots._list;
913
914				// default is: not found!
915				let botInfo = null;
916
917				if (!agent) return null;
918
919				// check for known bots:
920				BotList.find(bot => {
921					let r = false;
922					for (let j=0; j<bot.rx.length; j++) {
923						const rxr = agent.match(new RegExp(bot.rx[j]));
924						if (rxr) {
925							botInfo = {
926								n : bot.n,
927								id: bot.id,
928								geo: (bot.geo ? bot.geo : null),
929								url: bot.url,
930								v: (rxr.length > 1 ? rxr[1] : -1)
931							};
932							r = true;
933							break;
934						};
935					};
936					return r;
937				});
938
939				// check for unknown bots:
940				if (!botInfo) {
941					const botmatch = agent.match(/([\s\d\w]*bot|[\s\d\w]*crawler|[\s\d\w]*spider)[\/\s;\),\\.$]/i);
942					if(botmatch) {
943						botInfo = {'id': ( botmatch[1] || "other_" ), 'n': "Other" + ( botmatch[1] ? " (" + botmatch[1] + ")" : "" ) , "bot": botmatch[1] };
944					}
945				}
946
947				//console.log("botInfo:", botInfo);
948				return botInfo;
949			},
950
951
952			// indicates if the list is loaded and ready to use:
953			_ready: false,
954
955			// the actual bot list is stored here:
956			_list: []
957		},
958
959		clients: {
960			// loads the list of known clients from a JSON file:
961			init: async function() {
962				//console.info('BotMon.live.data.clients.init()');
963
964				// Load the list of known bots:
965				BotMon.live.gui.status.showBusy("Loading known clients");
966				const url = BotMon._baseDir + 'config/known-clients.json';
967				try {
968					const response = await fetch(url);
969					if (!response.ok) {
970						throw new Error(`${response.status} ${response.statusText}`);
971					}
972
973					BotMon.live.data.clients._list = await response.json();
974					BotMon.live.data.clients._ready = true;
975
976				} catch (error) {
977					BotMon.live.gui.status.setError("Error while loading the known clients file: " + error.message);
978				} finally {
979					BotMon.live.gui.status.hideBusy("Status: Done.");
980					BotMon.live.data._dispatch('clients')
981				}
982			},
983
984			// returns bot info if the user-agent matches a known bot, null otherwise:
985			match: function(agent) {
986				//console.info('BotMon.live.data.clients.match(',agent,')');
987
988				let match = {"n": "Unknown", "v": -1, "id": 'null'};
989
990				if (agent) {
991					BotMon.live.data.clients._list.find(client => {
992						let r = false;
993						for (let j=0; j<client.rx.length; j++) {
994							const rxr = agent.match(new RegExp(client.rx[j]));
995							if (rxr) {
996								match.n = client.n;
997								match.v = (rxr.length > 1 ? rxr[1] : -1);
998								match.id = client.id || null;
999								r = true;
1000								break;
1001							}
1002						}
1003						return r;
1004					});
1005				}
1006
1007				//console.log(match)
1008				return match;
1009			},
1010
1011			// return the browser name for a browser ID:
1012			getName: function(id) {
1013				const it = BotMon.live.data.clients._list.find(client => client.id == id);
1014				return ( it && it.n ? it.n : "Unknown"); //it.n;
1015			},
1016
1017			// indicates if the list is loaded and ready to use:
1018			_ready: false,
1019
1020			// the actual bot list is stored here:
1021			_list: []
1022
1023		},
1024
1025		platforms: {
1026			// loads the list of known platforms from a JSON file:
1027			init: async function() {
1028				//console.info('BotMon.live.data.platforms.init()');
1029
1030				// Load the list of known bots:
1031				BotMon.live.gui.status.showBusy("Loading known platforms");
1032				const url = BotMon._baseDir + 'config/known-platforms.json';
1033				try {
1034					const response = await fetch(url);
1035					if (!response.ok) {
1036						throw new Error(`${response.status} ${response.statusText}`);
1037					}
1038
1039					BotMon.live.data.platforms._list = await response.json();
1040					BotMon.live.data.platforms._ready = true;
1041
1042				} catch (error) {
1043					BotMon.live.gui.status.setError("Error while loading the known platforms file: " + error.message);
1044				} finally {
1045					BotMon.live.gui.status.hideBusy("Status: Done.");
1046					BotMon.live.data._dispatch('platforms')
1047				}
1048			},
1049
1050			// returns bot info if the browser id matches a known platform:
1051			match: function(cid) {
1052				//console.info('BotMon.live.data.platforms.match(',cid,')');
1053
1054				let match = {"n": "Unknown", "id": 'null'};
1055
1056				if (cid) {
1057					BotMon.live.data.platforms._list.find(platform => {
1058						let r = false;
1059						for (let j=0; j<platform.rx.length; j++) {
1060							const rxr = cid.match(new RegExp(platform.rx[j]));
1061							if (rxr) {
1062								match.n = platform.n;
1063								match.v = (rxr.length > 1 ? rxr[1] : -1);
1064								match.id = platform.id || null;
1065								r = true;
1066								break;
1067							}
1068						}
1069						return r;
1070					});
1071				}
1072
1073				return match;
1074			},
1075
1076			// return the platform name for a given ID:
1077			getName: function(id) {
1078				const it = BotMon.live.data.platforms._list.find( pf => pf.id == id);
1079				return ( it ? it.n : 'Unknown' );
1080			},
1081
1082
1083			// indicates if the list is loaded and ready to use:
1084			_ready: false,
1085
1086			// the actual bot list is stored here:
1087			_list: []
1088
1089		},
1090
1091		rules: {
1092			// loads the list of rules and settings from a JSON file:
1093			init: async function() {
1094				//console.info('BotMon.live.data.rules.init()');
1095
1096				// Load the list of known bots:
1097				BotMon.live.gui.status.showBusy("Loading list of rules …");
1098
1099				// relative file path to the rules file:
1100				const filePath = 'config/default-config.json';
1101
1102				// load the rules file:
1103				this._loadrulesFile(BotMon._baseDir + filePath);
1104			},
1105
1106			/**
1107			 * Loads the list of rules and settings from a JSON file.
1108			 * @param {String} url - the URL from which to load the rules file.
1109			 */
1110
1111			_loadrulesFile: async function(url) {
1112				//console.info('BotMon.live.data.rules._loadrulesFile(',url,')');}
1113
1114				const me = BotMon.live.data.rules;
1115				try {
1116					const response = await fetch(url);
1117					if (!response.ok) {
1118						throw new Error(`${response.status} ${response.statusText}`);
1119					}
1120
1121					const json = await response.json();
1122
1123					if (json.rules) {
1124						me._rulesList = json.rules;
1125					}
1126
1127					// override the threshold?
1128					if (json.threshold) me._threshold = json.threshold;
1129
1130					if (json.ipRanges) {
1131						// clean up the IPs first:
1132						let list = [];
1133						json.ipRanges.forEach( it => {
1134							let item = {
1135								'from': BotMon.t._ip2Num(it.from),
1136								'to': BotMon.t._ip2Num(it.to),
1137								'label': it.label
1138							};
1139							list.push(item);
1140						});
1141
1142						me._botIPs = list;
1143					}
1144
1145					me._ready = true;
1146
1147				} catch (error) {
1148					BotMon.live.gui.status.setError("Error while loading the config file: " + error.message);
1149				} finally {
1150					BotMon.live.gui.status.hideBusy("Status: Done.");
1151					BotMon.live.data._dispatch('rules')
1152				}
1153			},
1154
1155			_rulesList: [], // list of rules to find out if a visitor is a bot
1156			_threshold: 100, // above this, it is considered a bot.
1157
1158			// returns a descriptive text for a rule id
1159			getRuleInfo: function(ruleId) {
1160				// console.info('getRuleInfo', ruleId);
1161
1162				// shortcut for neater code:
1163				const me = BotMon.live.data.rules;
1164
1165				for (let i=0; i<me._rulesList.length; i++) {
1166					const rule = me._rulesList[i];
1167					if (rule.id == ruleId) {
1168						return rule;
1169					}
1170				}
1171				return null;
1172
1173			},
1174
1175			// evaluate a visitor for lkikelihood of being a bot
1176			evaluate: function(visitor) {
1177
1178				// shortcut for neater code:
1179				const me = BotMon.live.data.rules;
1180
1181				let r =  {	// evaluation result
1182					'val': 0,
1183					'rules': [],
1184					'isBot': false
1185				};
1186
1187				for (let i=0; i<me._rulesList.length; i++) {
1188					const rule = me._rulesList[i];
1189					const params = ( rule.params ? rule.params : [] );
1190
1191					if (rule.func) { // rule is calling a function
1192						if (me.func[rule.func]) {
1193							if(me.func[rule.func](visitor, ...params)) {
1194								r.val += rule.bot;
1195								r.rules.push(rule.id)
1196							}
1197						} else {
1198							//console.warn("Unknown rule function: “${rule.func}”. Ignoring rule.")
1199						}
1200					}
1201				}
1202
1203				// is a bot?
1204				r.isBot = (r.val >= me._threshold);
1205
1206				return r;
1207			},
1208
1209			// list of functions that can be called by the rules list to evaluate a visitor:
1210			func: {
1211
1212				// check if client is on the list passed as parameter:
1213				matchesClient: function(visitor, ...clients) {
1214
1215					const clientId = ( visitor._client ? visitor._client.id : '');
1216					return clients.includes(clientId);
1217				},
1218
1219				// check if OS/Platform is one of the obsolete ones:
1220				matchesPlatform: function(visitor, ...platforms) {
1221
1222					const pId = ( visitor._platform ? visitor._platform.id : '');
1223
1224					if (visitor._platform.id == null) console.log(visitor._platform);
1225
1226					return platforms.includes(pId);
1227				},
1228
1229				// are there at lest num pages loaded?
1230				smallPageCount: function(visitor, num) {
1231					return (visitor._pageViews.length <= Number(num));
1232				},
1233
1234				// There was no entry in a specific log file for this visitor:
1235				// note that this will also trigger the "noJavaScript" rule:
1236				noRecord: function(visitor, type) {
1237					return !visitor._seenBy.includes(type);
1238				},
1239
1240				// there are no referrers in any of the page visits:
1241				noReferrer: function(visitor) {
1242
1243					let r = false; // return value
1244					for (let i = 0; i < visitor._pageViews.length; i++) {
1245						if (!visitor._pageViews[i]._ref) {
1246							r = true;
1247							break;
1248						}
1249					}
1250					return r;
1251				},
1252
1253				// test for specific client identifiers:
1254				/*matchesClients: function(visitor, ...list) {
1255
1256					for (let i=0; i<list.length; i++) {
1257						if (visitor._client.id == list[i]) {
1258								return true
1259						}
1260					};
1261					return false;
1262				},*/
1263
1264				// unusual combinations of Platform and Client:
1265				combinationTest: function(visitor, ...combinations) {
1266
1267					for (let i=0; i<combinations.length; i++) {
1268
1269						if (visitor._platform.id == combinations[i][0]
1270							&& visitor._client.id == combinations[i][1]) {
1271								return true
1272						}
1273					};
1274
1275					return false;
1276				},
1277
1278				// is the IP address from a known bot network?
1279				fromKnownBotIP: function(visitor) {
1280
1281					const ipInfo = BotMon.live.data.rules.getBotIPInfo(visitor.ip);
1282
1283					if (ipInfo) {
1284						visitor._ipInKnownBotRange = true;
1285					}
1286
1287					return (ipInfo !== null);
1288				},
1289
1290				// is the page language mentioned in the client's accepted languages?
1291				// the parameter holds an array of exceptions, i.e. page languages that should be ignored.
1292				matchLang: function(visitor, ...exceptions) {
1293
1294					if (visitor.lang && visitor.accept && exceptions.indexOf(visitor.lang) < 0) {
1295						return (visitor.accept.split(',').indexOf(visitor.lang) < 0);
1296					}
1297					return false;
1298				},
1299
1300				// the "Accept language" header contains certain entries:
1301				clientAccepts: function(visitor, ...languages) {
1302					//console.info('clientAccepts', visitor.accept, languages);
1303
1304					if (visitor.accept && languages) {;
1305						return ( visitor.accept.split(',').filter(lang => languages.includes(lang)).length > 0 );
1306					}
1307					return false;
1308				},
1309
1310				// Is there an accept-language field defined at all?
1311				noAcceptLang: function(visitor) {
1312
1313					if (!visitor.accept || visitor.accept.length <= 0) { // no accept-languages header
1314						return true;
1315					}
1316					// TODO: parametrize this!
1317					return false;
1318				},
1319				// At least x page views were recorded, but they come within less than y seconds
1320				loadSpeed: function(visitor, minItems, maxTime) {
1321
1322					if (visitor._pageViews.length >= minItems) {
1323						//console.log('loadSpeed', visitor._pageViews.length, minItems, maxTime);
1324
1325						const pvArr = visitor._pageViews.map(pv => pv._lastSeen).sort();
1326
1327						let totalTime = 0;
1328						for (let i=1; i < pvArr.length; i++) {
1329							totalTime += (pvArr[i] - pvArr[i-1]);
1330						}
1331
1332						//console.log('     ', totalTime , Math.round(totalTime / (pvArr.length * 1000)), (( totalTime / pvArr.length ) <= maxTime * 1000), visitor.ip);
1333
1334						return (( totalTime / pvArr.length ) <= maxTime * 1000);
1335					}
1336				},
1337
1338				// Country code matches one of those in the list:
1339				matchesCountry: function(visitor, ...countries) {
1340
1341					// ingore if geoloc is not set or unknown:
1342					if (visitor.geo) {
1343						return (countries.indexOf(visitor.geo) >= 0);
1344					}
1345					return false;
1346				},
1347
1348				// Country does not match one of the given codes.
1349				notFromCountry: function(visitor, ...countries) {
1350
1351					// ingore if geoloc is not set or unknown:
1352					if (visitor.geo && visitor.geo !== 'ZZ') {
1353						return (countries.indexOf(visitor.geo) < 0);
1354					}
1355					return false;
1356				}
1357			},
1358
1359			/* known bot IP ranges: */
1360			_botIPs: [],
1361
1362			// return information on a bot IP range:
1363			getBotIPInfo: function(ip) {
1364
1365				// shortcut to make code more readable:
1366				const me = BotMon.live.data.rules;
1367
1368				// convert IP address to easier comparable form:
1369				const ipNum = BotMon.t._ip2Num(ip);
1370
1371				for (let i=0; i < me._botIPs.length; i++) {
1372					const ipRange = me._botIPs[i];
1373
1374					if (ipNum >= ipRange.from && ipNum <= ipRange.to) {
1375						return ipRange;
1376					}
1377
1378				};
1379				return null;
1380
1381			}
1382
1383		},
1384
1385		/**
1386		 * Loads a log file (server, page load, or ticker) and parses it.
1387		 * @param {String} type - the type of the log file to load (srv, log, or tck)
1388		 * @param {Function} [onLoaded] - an optional callback function to call after loading is finished.
1389		 */
1390		loadLogFile: async function(type, onLoaded = undefined) {
1391			//console.info('BotMon.live.data.loadLogFile(',type,')');
1392
1393			let typeName = '';
1394			let columns = [];
1395
1396			switch (type) {
1397				case "srv":
1398					typeName = "Server";
1399					columns = ['ts','ip','pg','id','typ','usr','agent','ref','lang','accept','geo'];
1400					break;
1401				case "log":
1402					typeName = "Page load";
1403					columns = ['ts','ip','pg','id','usr','lt','ref','agent'];
1404					break;
1405				case "tck":
1406					typeName = "Ticker";
1407					columns = ['ts','ip','pg','id','agent'];
1408					break;
1409				default:
1410					console.warn(`Unknown log type ${type}.`);
1411					return;
1412			}
1413
1414			// Show the busy indicator and set the visible status:
1415			BotMon.live.gui.status.showBusy(`Loading ${typeName} log file …`);
1416
1417			// compose the URL from which to load:
1418			const url = BotMon._baseDir + `logs/${BotMon._today}.${type}.txt`;
1419			//console.log("Loading:",url);
1420
1421			// fetch the data:
1422			try {
1423				const response = await fetch(url);
1424				if (!response.ok) {
1425
1426					throw new Error(`${response.status} ${response.statusText}`);
1427
1428				} else {
1429
1430					// parse the data:
1431					const logtxt = await response.text();
1432					if (logtxt.length <= 0) {
1433						throw new Error(`Empty log file ${url}.`);
1434					}
1435
1436					logtxt.split('\n').forEach((line) => {
1437						if (line.trim() === '') return; // skip empty lines
1438						const cols = line.split('\t');
1439
1440						// assign the columns to an object:
1441						const data = {};
1442						cols.forEach( (colVal,i) => {
1443							colName = columns[i] || `col${i}`;
1444							const colValue = (colName == 'ts' ? new Date(colVal) : colVal.trim());
1445							data[colName] = colValue;
1446						});
1447
1448						// register the visit in the model:
1449						switch(type) {
1450							case 'srv':
1451								BotMon.live.data.model.registerVisit(data, type);
1452								break;
1453							case 'log':
1454								data.typ = 'js';
1455								BotMon.live.data.model.updateVisit(data);
1456								break;
1457							case 'tck':
1458								data.typ = 'js';
1459								BotMon.live.data.model.updateTicks(data);
1460								break;
1461							default:
1462								console.warn(`Unknown log type ${type}.`);
1463								return;
1464						}
1465					});
1466				}
1467
1468			} catch (error) {
1469				BotMon.live.gui.status.setError(`Error while loading the ${typeName} log file: ${error.message} – data may be incomplete.`);
1470			} finally {
1471				BotMon.live.gui.status.hideBusy("Status: Done.");
1472				if (onLoaded) {
1473					onLoaded(); // callback after loading is finished.
1474				}
1475			}
1476		}
1477	},
1478
1479	gui: {
1480		init: function() {
1481			// init the lists view:
1482			this.lists.init();
1483		},
1484
1485		/* The Overview / web metrics section of the live tab */
1486		overview: {
1487			/**
1488			 * Populates the overview part of the today tab with the analytics data.
1489			 *
1490			 * @method make
1491			 * @memberof BotMon.live.gui.overview
1492			 */
1493			make: function() {
1494
1495				const data = BotMon.live.data.analytics.data;
1496
1497				// shortcut for neater code:
1498				const makeElement = BotMon.t._makeElement;
1499
1500				const botsVsHumans = document.getElementById('botmon__today__botsvshumans');
1501				if (botsVsHumans) {
1502					botsVsHumans.appendChild(makeElement('dt', {}, "Bots vs. Humans"));
1503
1504					for (let i = 3; i >= 0; i--) {
1505						const dd = makeElement('dd');
1506						let title = '';
1507						let value = '';
1508						switch(i) {
1509							case 0:
1510								title = "Registered users:";
1511								value = data.bots.users;
1512								break;
1513							case 1:
1514								title = "Probably humans:";
1515								value = data.bots.human;
1516								break;
1517							case 2:
1518								title = "Suspected bots:";
1519								value = data.bots.suspected;
1520								break;
1521							case 3:
1522								title = "Known bots:";
1523								value = data.bots.known;
1524								break;
1525							default:
1526								console.warn(`Unknown list type ${i}.`);
1527						}
1528						dd.appendChild(makeElement('span', {}, title));
1529						dd.appendChild(makeElement('strong', {}, value));
1530						botsVsHumans.appendChild(dd);
1531					}
1532				}
1533
1534				// update known bots list:
1535				const botlist = document.getElementById('botmon__botslist'); /* Known bots */
1536				botlist.innerHTML = "<dt>Known bots (top 5)</dt>";
1537
1538				let bots = BotMon.live.data.analytics.groups.knownBots.toSorted( (a, b) => {
1539					return b._pageViews.length - a._pageViews.length;
1540				});
1541
1542				for (let i=0; i < Math.min(bots.length, 5); i++) {
1543					const dd = makeElement('dd');
1544					dd.appendChild(makeElement('span', {'class': 'has_icon bot bot_' + bots[i]._bot.id }, bots[i]._bot.n));
1545					dd.appendChild(makeElement('span', undefined, bots[i]._pageViews.length));
1546					botlist.appendChild(dd);
1547				}
1548
1549				// update the suspected bot IP ranges list:
1550				/*const botIps = document.getElementById('botmon__today__botips');
1551				if (botIps) {
1552					botIps.appendChild(makeElement('dt', {}, "Bot IP ranges (top 5)"));
1553
1554					const ipList = BotMon.live.data.analytics.getTopBotIPRanges(5);
1555					ipList.forEach( (ipInfo) => {
1556						const li = makeElement('dd');
1557						li.appendChild(makeElement('span', {'class': 'has_icon ipaddr ip' + ipInfo.typ }, ipInfo.ip));
1558						li.appendChild(makeElement('span', {'class': 'count' }, ipInfo.num));
1559						botIps.append(li)
1560					});
1561				}*/
1562
1563				// update the top bot countries list:
1564				const botCountries = document.getElementById('botmon__today__countries');
1565				if (botCountries) {
1566					botCountries.appendChild(makeElement('dt', {}, "Bot Countries (top 5)"));
1567					const countryList = BotMon.live.data.analytics.getCountryList('likely_bot', 5);
1568					countryList.forEach( (cInfo) => {
1569						const cLi = makeElement('dd');
1570						cLi.appendChild(makeElement('span', {'class': 'has_icon country ctry_' + cInfo.iso.toLowerCase() }, cInfo.name));
1571						cLi.appendChild(makeElement('span', {'class': 'count' }, cInfo.count));
1572						botCountries.appendChild(cLi);
1573					});
1574				}
1575
1576				// update the webmetrics overview:
1577				const wmoverview = document.getElementById('botmon__today__wm_overview');
1578				if (wmoverview) {
1579					const bounceRate = Math.round(data.totalVisits / data.totalPageViews * 100);
1580
1581					wmoverview.appendChild(makeElement('dt', {}, "Overview"));
1582					for (let i = 0; i < 3; i++) {
1583						const dd = makeElement('dd');
1584						let title = '';
1585						let value = '';
1586						switch(i) {
1587							case 0:
1588								title = "Total page views:";
1589								value = data.totalPageViews;
1590								break;
1591							case 1:
1592								title = "Total visitors (est.):";
1593								value = data.totalVisits;
1594								break;
1595							case 2:
1596								title = "Bounce rate (est.):";
1597								value = bounceRate + '%';
1598								break;
1599							default:
1600								console.warn(`Unknown list type ${i}.`);
1601						}
1602						dd.appendChild(makeElement('span', {}, title));
1603						dd.appendChild(makeElement('strong', {}, value));
1604						wmoverview.appendChild(dd);
1605					}
1606				}
1607
1608				// update the webmetrics clients list:
1609				const wmclients = document.getElementById('botmon__today__wm_clients');
1610				if (wmclients) {
1611
1612					wmclients.appendChild(makeElement('dt', {}, "Top browsers (humans only)"));
1613
1614					const clientList = BotMon.live.data.analytics.getTopBrowsers(5);
1615					if (clientList) {
1616						clientList.forEach( (cInfo) => {
1617							const cDd = makeElement('dd');
1618							cDd.appendChild(makeElement('span', {'class': 'has_icon client cl_' + cInfo.id }, ( cInfo.name ? cInfo.name : cInfo.id)));
1619							cDd.appendChild(makeElement('span', {
1620								'class': 'count',
1621								'title': cInfo.count + " page views"
1622							}, Math.round(cInfo.pct) + '%'));
1623							wmclients.appendChild(cDd);
1624						});
1625					}
1626				}
1627
1628				// update the webmetrics platforms list:
1629				const wmplatforms = document.getElementById('botmon__today__wm_platforms');
1630				if (wmplatforms) {
1631
1632					wmplatforms.appendChild(makeElement('dt', {}, "Top platforms (humans only)"));
1633
1634					const pfList = BotMon.live.data.analytics.getTopPlatforms(5);
1635					if (pfList) {
1636						pfList.forEach( (pInfo) => {
1637							const pDd = makeElement('dd');
1638							pDd.appendChild(makeElement('span', {'class': 'has_icon platform pf_' + pInfo.id }, ( pInfo.name ? pInfo.name : pInfo.id)));
1639							pDd.appendChild(makeElement('span', {
1640								'class': 'count',
1641								'title': pInfo.count + " page views"
1642							}, Math.round(pInfo.pct) + '%'));
1643							wmplatforms.appendChild(pDd);
1644						});
1645					}
1646				}
1647
1648			}
1649		},
1650
1651		status: {
1652			setText: function(txt) {
1653				const el = document.getElementById('botmon__today__status');
1654				if (el && BotMon.live.gui.status._errorCount <= 0) {
1655					el.innerText = txt;
1656				}
1657			},
1658
1659			setTitle: function(html) {
1660				const el = document.getElementById('botmon__today__title');
1661				if (el) {
1662					el.innerHTML = html;
1663				}
1664			},
1665
1666			setError: function(txt) {
1667				console.error(txt);
1668				BotMon.live.gui.status._errorCount += 1;
1669				const el = document.getElementById('botmon__today__status');
1670				if (el) {
1671					el.innerText = "Data may be incomplete.";
1672					el.classList.add('error');
1673				}
1674			},
1675			_errorCount: 0,
1676
1677			showBusy: function(txt = null) {
1678				BotMon.live.gui.status._busyCount += 1;
1679				const el = document.getElementById('botmon__today__busy');
1680				if (el) {
1681					el.style.display = 'inline-block';
1682				}
1683				if (txt) BotMon.live.gui.status.setText(txt);
1684			},
1685			_busyCount: 0,
1686
1687			hideBusy: function(txt = null) {
1688				const el = document.getElementById('botmon__today__busy');
1689				BotMon.live.gui.status._busyCount -= 1;
1690				if (BotMon.live.gui.status._busyCount <= 0) {
1691					if (el) el.style.display = 'none';
1692					if (txt) BotMon.live.gui.status.setText(txt);
1693				}
1694			}
1695		},
1696
1697		lists: {
1698			init: function() {
1699
1700				// function shortcut:
1701				const makeElement = BotMon.t._makeElement;
1702
1703				const parent = document.getElementById('botmon__today__visitorlists');
1704				if (parent) {
1705
1706					for (let i=0; i < 4; i++) {
1707
1708						// change the id and title by number:
1709						let listTitle = '';
1710						let listId = '';
1711						switch (i) {
1712							case 0:
1713								listTitle = "Registered users";
1714								listId = 'users';
1715								break;
1716							case 1:
1717								listTitle = "Probably humans";
1718								listId = 'humans';
1719								break;
1720							case 2:
1721								listTitle = "Suspected bots";
1722								listId = 'suspectedBots';
1723								break;
1724							case 3:
1725								listTitle = "Known bots";
1726								listId = 'knownBots';
1727								break;
1728							default:
1729								console.warn('Unknown list number.');
1730						}
1731
1732						const details = makeElement('details', {
1733							'data-group': listId,
1734							'data-loaded': false
1735						});
1736						const title = details.appendChild(makeElement('summary'));
1737						title.appendChild(makeElement('span', {'class': 'title'}, listTitle));
1738						title.appendChild(makeElement('span', {'class': 'counter'}));
1739						details.addEventListener("toggle", this._onDetailsToggle);
1740
1741						parent.appendChild(details);
1742
1743					}
1744				}
1745			},
1746
1747			_onDetailsToggle: function(e) {
1748				//console.info('BotMon.live.gui.lists._onDetailsToggle()');
1749
1750				const target = e.target;
1751
1752				if (target.getAttribute('data-loaded') == 'false') { // only if not loaded yet
1753					target.setAttribute('data-loaded', 'loading');
1754
1755					const fillType = target.getAttribute('data-group');
1756					const fillList = BotMon.live.data.analytics.groups[fillType];
1757					if (fillList && fillList.length > 0) {
1758
1759						const ul = BotMon.t._makeElement('ul');
1760
1761						fillList.forEach( (it) => {
1762							ul.appendChild(BotMon.live.gui.lists._makeVisitorItem(it, fillType));
1763						});
1764
1765						target.appendChild(ul);
1766						target.setAttribute('data-loaded', 'true');
1767					} else {
1768						target.setAttribute('data-loaded', 'false');
1769					}
1770
1771				}
1772			},
1773
1774			_makeVisitorItem: function(data, type) {
1775
1776				// shortcut for neater code:
1777				const make = BotMon.t._makeElement;
1778
1779				let ipType = ( data.ip.indexOf(':') >= 0 ? '6' : '4' );
1780				if (data.ip == '127.0.0.1' || data.ip == '::1' ) ipType = '0';
1781
1782				const platformName = (data._platform ? data._platform.n : 'Unknown');
1783				const clientName = (data._client ? data._client.n: 'Unknown');
1784
1785				const sumClass = ( data._seenBy.indexOf('srv') < 0 ? 'noServer' : 'hasServer');
1786
1787				const li = make('li'); // root list item
1788				const details = make('details');
1789				const summary = make('summary', {
1790					'class': sumClass
1791				});
1792				details.appendChild(summary);
1793
1794				const span1 = make('span'); /* left-hand group */
1795
1796				if (data._type !== BM_USERTYPE.KNOWN_BOT) { /* No platform/client for bots */
1797					span1.appendChild(make('span', { /* Platform */
1798						'class': 'icon_only platform pf_' + (data._platform ? data._platform.id : 'unknown'),
1799						'title': "Platform: " + platformName
1800					}, platformName));
1801
1802					span1.appendChild(make('span', { /* Client */
1803						'class': 'icon_only client client cl_' + (data._client ? data._client.id : 'unknown'),
1804						'title': "Client: " + clientName
1805					}, clientName));
1806				}
1807
1808				// identifier:
1809				if (data._type == BM_USERTYPE.KNOWN_BOT) { /* Bot only */
1810
1811					const botName = ( data._bot && data._bot.n ? data._bot.n : "Unknown");
1812					span1.appendChild(make('span', { /* Bot */
1813						'class': 'has_icon bot bot_' + (data._bot ? data._bot.id : 'unknown'),
1814						'title': "Bot: " + botName
1815					}, botName));
1816
1817				} else if (data._type == BM_USERTYPE.KNOWN_USER) { /* User only */
1818
1819					span1.appendChild(make('span', { /* User */
1820						'class': 'has_icon user_known',
1821						'title': "User: " + data.usr
1822					}, data.usr));
1823
1824				} else { /* others */
1825
1826
1827					/*span1.appendChild(make('span', { // IP-Address
1828						'class': 'has_icon ipaddr ip' + ipType,
1829						'title': "IP-Address: " + data.ip
1830					}, data.ip));*/
1831
1832					span1.appendChild(make('span', { /* Internal ID */
1833						'class': 'has_icon session typ_' + data.typ,
1834						'title': "ID: " + data.id
1835					}, data.id));
1836				}
1837
1838				// country flag:
1839				if (data.geo && data.geo !== 'ZZ') {
1840					span1.appendChild(make('span', {
1841						'class': 'icon_only country ctry_' + data.geo.toLowerCase(),
1842						'data-ctry': data.geo,
1843						'title': "Country: " + ( data._country || "Unknown")
1844					}, ( data._country || "Unknown") ));
1845				}
1846
1847				summary.appendChild(span1);
1848				const span2 = make('span'); /* right-hand group */
1849
1850					span2.appendChild(make('span', { /* first-seen */
1851						'class': 'has_iconfirst-seen',
1852						'title': "First seen: " + data._firstSeen.toLocaleString() + " UTC"
1853					}, BotMon.t._formatTime(data._firstSeen)));
1854
1855					span2.appendChild(make('span', { /* page views */
1856						'class': 'has_icon pageviews',
1857						'title': data._pageViews.length + " page view(s)"
1858					}, data._pageViews.length));
1859
1860				summary.appendChild(span2);
1861
1862				// add details expandable section:
1863				details.appendChild(BotMon.live.gui.lists._makeVisitorDetails(data, type));
1864
1865				li.appendChild(details);
1866				return li;
1867			},
1868
1869			_makeVisitorDetails: function(data, type) {
1870
1871				// shortcut for neater code:
1872				const make = BotMon.t._makeElement;
1873
1874				let ipType = ( data.ip.indexOf(':') >= 0 ? '6' : '4' );
1875				if (data.ip == '127.0.0.1' || data.ip == '::1' ) ipType = '0';
1876				const platformName = (data._platform ? data._platform.n : 'Unknown');
1877				const clientName = (data._client ? data._client.n: 'Unknown');
1878
1879				const dl = make('dl', {'class': 'visitor_details'});
1880
1881				if (data._type == BM_USERTYPE.KNOWN_BOT) {
1882
1883					dl.appendChild(make('dt', {}, "Bot name:")); /* bot info */
1884					dl.appendChild(make('dd', {'class': 'icon_only bot bot_' + (data._bot ? data._bot.id : 'unknown')},
1885						(data._bot ? data._bot.n : 'Unknown')));
1886
1887					if (data._bot && data._bot.url) {
1888						dl.appendChild(make('dt', {}, "Bot info:")); /* bot info */
1889						const botInfoDd = dl.appendChild(make('dd'));
1890						botInfoDd.appendChild(make('a', {
1891							'href': data._bot.url,
1892							'target': '_blank'
1893						}, data._bot.url)); /* bot info link*/
1894
1895					}
1896
1897				} else { /* not for bots */
1898
1899					dl.appendChild(make('dt', {}, "Client:")); /* client */
1900					dl.appendChild(make('dd', {'class': 'has_icon client cl_' + (data._client ? data._client.id : 'unknown')},
1901						clientName + ( data._client.v > 0 ? ' (' + data._client.v + ')' : '' ) ));
1902
1903					dl.appendChild(make('dt', {}, "Platform:")); /* platform */
1904					dl.appendChild(make('dd', {'class': 'has_icon platform pf_' + (data._platform ? data._platform.id : 'unknown')},
1905						platformName + ( data._platform.v > 0 ? ' (' + data._platform.v + ')' : '' ) ));
1906
1907					dl.appendChild(make('dt', {}, "IP-Address:"));
1908					const ipItem = make('dd', {'class': 'has_icon ipaddr ip' + ipType});
1909						ipItem.appendChild(make('span', {'class': 'address'} , data.ip));
1910						ipItem.appendChild(make('a', {
1911							'class': 'icon_only extlink dnscheck',
1912							'href': `https://dnschecker.org/ip-location.php?ip=${encodeURIComponent(data.ip)}`,
1913							'target': 'dnscheck',
1914							'title': "View this address on DNSChecker.org"
1915						} , "Check Address"));
1916						ipItem.appendChild(make('a', {
1917							'class': 'icon_only extlink ipinfo',
1918							'href': `https://ipinfo.io/${encodeURIComponent(data.ip)}`,
1919							'target': 'ipinfo',
1920							'title': "View this address on IPInfo.io"
1921						} , "DNS Info"));
1922					dl.appendChild(ipItem);
1923
1924					/*dl.appendChild(make('dt', {}, "ID:"));
1925					dl.appendChild(make('dd', {'class': 'has_icon ip' + data.typ}, data.id));*/
1926				}
1927
1928				if (Math.abs(data._lastSeen - data._firstSeen) < 100) {
1929					dl.appendChild(make('dt', {}, "Seen:"));
1930					dl.appendChild(make('dd', {'class': 'seen'}, data._firstSeen.toLocaleString()));
1931				} else {
1932					dl.appendChild(make('dt', {}, "First seen:"));
1933					dl.appendChild(make('dd', {'class': 'firstSeen'}, data._firstSeen.toLocaleString()));
1934					dl.appendChild(make('dt', {}, "Last seen:"));
1935					dl.appendChild(make('dd', {'class': 'lastSeen'}, data._lastSeen.toLocaleString()));
1936				}
1937
1938				dl.appendChild(make('dt', {}, "User-Agent:"));
1939				dl.appendChild(make('dd', {'class': 'agent'}, data.agent));
1940
1941				dl.appendChild(make('dt', {}, "Languages:"));
1942				dl.appendChild(make('dd', {'class': 'langs'}, ` [${data.accept}]`));
1943
1944				if (data.geo && data.geo !=='') {
1945					dl.appendChild(make('dt', {}, "Location:"));
1946					dl.appendChild(make('dd', {
1947						'class': 'has_icon country ctry_' + data.geo.toLowerCase(),
1948						'data-ctry': data.geo,
1949						'title': "Country: " + data._country
1950					}, data._country + ' (' + data.geo + ')'));
1951				}
1952
1953				/*dl.appendChild(make('dt', {}, "Visitor Type:"));
1954				dl.appendChild(make('dd', undefined, data._type ));*/
1955
1956				dl.appendChild(make('dt', {}, "Session ID:"));
1957				dl.appendChild(make('dd', {'class': 'has_icon session typ_' + data.typ}, data.id));
1958
1959				dl.appendChild(make('dt', {}, "Seen by:"));
1960				dl.appendChild(make('dd', undefined, data._seenBy.join(', ') ));
1961
1962				dl.appendChild(make('dt', {}, "Visited pages:"));
1963				const pagesDd = make('dd', {'class': 'pages'});
1964				const pageList = make('ul');
1965
1966				/* list all page views */
1967				data._pageViews.sort( (a, b) => a._firstSeen - b._firstSeen );
1968				data._pageViews.forEach( (page) => {
1969					pageList.appendChild(BotMon.live.gui.lists._makePageViewItem(page));
1970				});
1971				pagesDd.appendChild(pageList);
1972				dl.appendChild(pagesDd);
1973
1974				/* bot evaluation rating */
1975				if (data._type !== BM_USERTYPE.KNOWN_BOT && data._type !== BM_USERTYPE.KNOWN_USER) {
1976					dl.appendChild(make('dt', undefined, "Bot rating:"));
1977					dl.appendChild(make('dd', {'class': 'bot-rating'}, ( data._botVal ? data._botVal : '–' ) + ' (of ' + BotMon.live.data.rules._threshold + ')'));
1978
1979					/* add bot evaluation details: */
1980					if (data._eval) {
1981						dl.appendChild(make('dt', {}, "Bot evaluation details:"));
1982						const evalDd = make('dd');
1983						const testList = make('ul',{
1984							'class': 'eval'
1985						});
1986						data._eval.forEach( test => {
1987
1988							const tObj = BotMon.live.data.rules.getRuleInfo(test);
1989							let tDesc = tObj ? tObj.desc : test;
1990
1991							// special case for Bot IP range test:
1992							if (tObj.func == 'fromKnownBotIP') {
1993								const rangeInfo = BotMon.live.data.rules.getBotIPInfo(data.ip);
1994								if (rangeInfo) {
1995									tDesc += ' (' + (rangeInfo.label ? rangeInfo.label : 'Unknown') + ')';
1996								}
1997							}
1998
1999							// create the entry field
2000							const tstLi = make('li');
2001							tstLi.appendChild(make('span', {
2002								'data-testid': test
2003							}, tDesc));
2004							tstLi.appendChild(make('span', {}, ( tObj ? tObj.bot : '—') ));
2005							testList.appendChild(tstLi);
2006						});
2007
2008						// add total row
2009						const tst2Li = make('li', {
2010							'class': 'total'
2011						});
2012						/*tst2Li.appendChild(make('span', {}, "Total:"));
2013						tst2Li.appendChild(make('span', {}, data._botVal));
2014						testList.appendChild(tst2Li);*/
2015
2016						evalDd.appendChild(testList);
2017						dl.appendChild(evalDd);
2018					}
2019				}
2020				// return the element to add to the UI:
2021				return dl;
2022			},
2023
2024			// make a page view item:
2025			_makePageViewItem: function(page) {
2026				console.log("makePageViewItem:",page);
2027
2028				// shortcut for neater code:
2029				const make = BotMon.t._makeElement;
2030
2031				// the actual list item:
2032				const pgLi = make('li');
2033
2034				const row1 = make('div', {'class': 'row'});
2035
2036					row1.appendChild(make('span', { // page id is the left group
2037						'data-lang': page.lang,
2038						'title': "PageID: " + page.pg
2039					}, page.pg)); /* DW Page ID */
2040
2041					// get the time difference:
2042					row1.appendChild(make('span', {
2043						'class': 'first-seen',
2044						'title': "First visited: " + page._firstSeen.toLocaleString() + " UTC"
2045					}, BotMon.t._formatTime(page._firstSeen)));
2046
2047				pgLi.appendChild(row1);
2048
2049				/* LINE 2 */
2050
2051				const row2 = make('div', {'class': 'row'});
2052
2053					// page referrer:
2054					if (page._ref) {
2055						row2.appendChild(make('span', {
2056							'class': 'referer',
2057							'title': "Referrer: " + page._ref.href
2058						}, page._ref.hostname));
2059					} else {
2060						row2.appendChild(make('span', {
2061							'class': 'referer'
2062						}, "No referer"));
2063					}
2064
2065					// visit duration:
2066					let visitTimeStr = "Bounce";
2067					const visitDuration = page._lastSeen.getTime() - page._firstSeen.getTime();
2068					if (visitDuration > 0) {
2069						visitTimeStr = Math.floor(visitDuration / 1000) + "s";
2070					}
2071					const tDiff = BotMon.t._formatTimeDiff(page._firstSeen, page._lastSeen);
2072					if (tDiff) {
2073						row2.appendChild(make('span', {'class': 'visit-length', 'title': 'Last seen: ' + page._lastSeen.toLocaleString()}, tDiff));
2074					} else {
2075						row2.appendChild(make('span', {
2076							'class': 'bounce',
2077							'title': "Visitor bounced"}, "Bounce"));
2078					}
2079
2080				pgLi.appendChild(row2);
2081
2082				return pgLi;
2083			}
2084		}
2085	}
2086};
2087
2088/* launch only if the BotMon admin panel is open: */
2089if (document.getElementById('botmon__admin')) {
2090	BotMon.init();
2091}