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 // add 571 v._pageViews.forEach( pv => { 572 me.addToRefererList(pv._ref); 573 }); 574 } 575 576 }); 577 578 BotMon.live.gui.status.hideBusy('Done.'); 579 }, 580 581 // Referer List: 582 _refererList: [], 583 _refererListCount: 0, 584 585 addToRefererList: function(ref) { 586 //console.log('BotMon.live.data.analytics.addToRefererList',ref); 587 588 const me = BotMon.live.data.analytics; 589 590 // ignore internal references: 591 if (ref && ref.host == 'denkfehler.online') { 592 return; 593 } 594 595 // find the referer ID: 596 let refId = 'null'; 597 if (ref && ref.host) { 598 const hArr = ref.host.split('.'); 599 const tld = hArr[hArr.length-1]; 600 refId = ( tld == 'localhost' ? tld : hArr[hArr.length-2] + ( tld.length > 3 ? '.' + tld : '' ) ); 601 } 602 603 // already exists? 604 let refObj = null; 605 for (let i = 0; i < me._refererList.length; i++) { 606 if (me._refererList[i].id == refId) { 607 refObj = me._refererList[i]; 608 break; 609 } 610 } 611 612 // if not exists, create it: 613 if (!refObj) { 614 refObj = { 615 id: refId, 616 count: 0 617 }; 618 me._refererList.push(refObj); 619 } else { 620 refObj.count += 1; 621 } 622 // add to total count: 623 me._refererListCount += 1; 624 }, 625 626 getTopReferers: function(max) { 627 //console.info(('BotMon.live.data.analytics.getTopReferers(' + max + ')')); 628 629 const me = BotMon.live.data.analytics; 630 631 const rList = []; // return array 632 633 // sort the list: 634 me._refererList.sort( (a,b) => { 635 return b.count - a.count; 636 }); 637 638 // get the top: 639 for (let i = 0; i < max; i++) { 640 const it = me._refererList[i]; 641 const rIt = { 642 id: it.id, 643 count: it.count, 644 pct: (it.count / me._refererListCount * 100).toFixed(0) 645 } 646 rList.push(rIt); 647 } 648 649 return rList; 650 }, 651 652 /* countries of visits */ 653 _countries: { 654 'user': [], 655 'human': [], 656 'likelyBot': [], 657 'known_bot': [] 658 659 }, 660 /** 661 * Adds a country code to the statistics. 662 * 663 * @param {string} iso The ISO 3166-1 alpha-2 country code. 664 */ 665 addToCountries: function(iso, name, type) { 666 667 const me = BotMon.live.data.analytics; 668 669 // find the correct array: 670 let arr = null; 671 switch (type) { 672 673 case BM_USERTYPE.KNOWN_USER: 674 arr = me._countries.user; 675 break; 676 case BM_USERTYPE.HUMAN: 677 arr = me._countries.human; 678 break; 679 case BM_USERTYPE.LIKELY_BOT: 680 arr = me._countries.likelyBot; 681 break; 682 case BM_USERTYPE.KNOWN_BOT: 683 arr = me._countries.known_bot; 684 break; 685 default: 686 console.warn(`Unknown user type ${type} in function addToCountries.`); 687 } 688 689 if (arr) { 690 let cRec = arr.find( it => it.iso == iso); 691 if (!cRec) { 692 cRec = { 693 'iso': iso, 694 'name': name, 695 'count': 1 696 }; 697 arr.push(cRec); 698 } else { 699 cRec.count += 1; 700 } 701 } 702 }, 703 704 /** 705 * Returns a list of countries with visit counts, sorted by visit count in descending order. 706 * 707 * @param {BM_USERTYPE} type The type of visitors to return. 708 * @param {number} max The maximum number of entries to return. 709 * @return {Array} A list of objects with properties 'iso' (ISO 3166-1 alpha-2 country code) and 'count' (visit count). 710 */ 711 getCountryList: function(type, max) { 712 713 const me = BotMon.live.data.analytics; 714 715 // find the correct array: 716 let arr = null; 717 switch (type) { 718 719 case BM_USERTYPE.KNOWN_USER: 720 arr = me._countries.user; 721 break; 722 case BM_USERTYPE.HUMAN: 723 arr = me._countries.human; 724 break; 725 case BM_USERTYPE.LIKELY_BOT: 726 arr = me._countries.likelyBot; 727 break; 728 case BM_USERTYPE.KNOWN_BOT: 729 arr = me._countries.known_bot; 730 break; 731 default: 732 console.warn(`Unknown user type ${type} in function getCountryList.`); 733 } 734 735 if (arr) { 736 // sort by visit count: 737 arr.sort( (a,b) => b.count - a.count); 738 739 // reduce to only the top (max) items and create the target format: 740 let rList = []; 741 for (let i=0; Math.min(max, arr.length) > i; i++) { 742 const cRec = arr[i]; 743 rList.push({ 744 'iso': cRec.iso, 745 'name': cRec.name, 746 'count': cRec.count 747 }); 748 } 749 return rList; 750 } 751 return []; 752 }, 753 754 /* browser and platform of human visitors */ 755 _browsers: [], 756 _platforms: [], 757 758 addBrowserPlatform: function(visitor) { 759 //console.info('addBrowserPlatform', visitor); 760 761 const me = BotMon.live.data.analytics; 762 763 // add to browsers list: 764 let browserRec = ( visitor._client ? visitor._client : {'id': 'unknown'}); 765 if (visitor._client) { 766 let bRec = me._browsers.find( it => it.id == browserRec.id); 767 if (!bRec) { 768 bRec = { 769 'id': browserRec.id, 770 'count': 1 771 }; 772 me._browsers.push(bRec); 773 } else { 774 bRec.count += 1; 775 } 776 } 777 778 // add to platforms list: 779 let platformRec = ( visitor._platform ? visitor._platform : {'id': 'unknown'}); 780 if (visitor._platform) { 781 let pRec = me._platforms.find( it => it.id == platformRec.id); 782 if (!pRec) { 783 pRec = { 784 'id': platformRec.id, 785 'count': 1 786 }; 787 me._platforms.push(pRec); 788 } else { 789 pRec.count += 1; 790 } 791 } 792 793 }, 794 795 getTopBrowsers: function(max) { 796 797 const me = BotMon.live.data.analytics; 798 799 me._browsers.sort( (a,b) => b.count - a.count); 800 801 // how many browsers to show: 802 const max2 = ( me._browsers.length >= max ? max-1 : max ); 803 804 const rArr = []; // return array 805 let total = 0; 806 const others = { 807 'id': 'other', 808 'name': "Others", 809 'count': 0 810 }; 811 for (let i=0; i < me._browsers.length; i++) { 812 if (i < max2) { 813 rArr.push({ 814 'id': me._browsers[i].id, 815 'name': BotMon.live.data.clients.getName(me._browsers[i].id), 816 'count': me._browsers[i].count 817 }); 818 total += me._browsers[i].count; 819 } else { 820 others.count += me._browsers[i].count; 821 total += me._browsers[i].count; 822 } 823 }; 824 825 if (me._browsers.length > (max-1)) { 826 rArr.push(others); 827 }; 828 829 // update percentages: 830 rArr.forEach( it => { 831 it.pct = Math.round(it.count * 100 / total); 832 }); 833 834 return rArr; 835 }, 836 837 getTopPlatforms: function(max) { 838 839 const me = BotMon.live.data.analytics; 840 841 me._platforms.sort( (a,b) => b.count - a.count); 842 // how many browsers to show: 843 const max2 = ( me._platforms.length >= max ? max-1 : max ); 844 845 const rArr = []; // return array 846 let total = 0; 847 const others = { 848 'id': 'other', 849 'name': "Others", 850 'count': 0 851 }; 852 for (let i=0; i < me._platforms.length; i++) { 853 if (i < max2) { 854 rArr.push({ 855 'id': me._platforms[i].id, 856 'name': BotMon.live.data.platforms.getName(me._platforms[i].id), 857 'count': me._platforms[i].count 858 }); 859 total += me._platforms[i].count; 860 } else { 861 others.count += me._platforms[i].count; 862 total += me._platforms[i].count; 863 } 864 }; 865 866 if (me._platforms.length > (max-1)) { 867 rArr.push(others); 868 }; 869 870 // update percentages: 871 rArr.forEach( it => { 872 it.pct = Math.round(it.count * 100 / total); 873 }); 874 875 return rArr; 876 } 877 }, 878 879 bots: { 880 // loads the list of known bots from a JSON file: 881 init: async function() { 882 //console.info('BotMon.live.data.bots.init()'); 883 884 // Load the list of known bots: 885 BotMon.live.gui.status.showBusy("Loading known bots …"); 886 const url = BotMon._baseDir + 'config/known-bots.json'; 887 try { 888 const response = await fetch(url); 889 if (!response.ok) { 890 throw new Error(`${response.status} ${response.statusText}`); 891 } 892 893 this._list = await response.json(); 894 this._ready = true; 895 896 } catch (error) { 897 BotMon.live.gui.status.setError("Error while loading the known bots file:", error.message); 898 } finally { 899 BotMon.live.gui.status.hideBusy("Status: Done."); 900 BotMon.live.data._dispatch('bots') 901 } 902 }, 903 904 // returns bot info if the clientId matches a known bot, null otherwise: 905 match: function(agent) { 906 //console.info('BotMon.live.data.bots.match(',agent,')'); 907 908 const BotList = BotMon.live.data.bots._list; 909 910 // default is: not found! 911 let botInfo = null; 912 913 if (!agent) return null; 914 915 // check for known bots: 916 BotList.find(bot => { 917 let r = false; 918 for (let j=0; j<bot.rx.length; j++) { 919 const rxr = agent.match(new RegExp(bot.rx[j])); 920 if (rxr) { 921 botInfo = { 922 n : bot.n, 923 id: bot.id, 924 geo: (bot.geo ? bot.geo : null), 925 url: bot.url, 926 v: (rxr.length > 1 ? rxr[1] : -1) 927 }; 928 r = true; 929 break; 930 }; 931 }; 932 return r; 933 }); 934 935 // check for unknown bots: 936 if (!botInfo) { 937 const botmatch = agent.match(/([\s\d\w]*bot|[\s\d\w]*crawler|[\s\d\w]*spider)[\/\s;\),\\.$]/i); 938 if(botmatch) { 939 botInfo = {'id': ( botmatch[1] || "other_" ), 'n': "Other" + ( botmatch[1] ? " (" + botmatch[1] + ")" : "" ) , "bot": botmatch[1] }; 940 } 941 } 942 943 //console.log("botInfo:", botInfo); 944 return botInfo; 945 }, 946 947 948 // indicates if the list is loaded and ready to use: 949 _ready: false, 950 951 // the actual bot list is stored here: 952 _list: [] 953 }, 954 955 clients: { 956 // loads the list of known clients from a JSON file: 957 init: async function() { 958 //console.info('BotMon.live.data.clients.init()'); 959 960 // Load the list of known bots: 961 BotMon.live.gui.status.showBusy("Loading known clients"); 962 const url = BotMon._baseDir + 'config/known-clients.json'; 963 try { 964 const response = await fetch(url); 965 if (!response.ok) { 966 throw new Error(`${response.status} ${response.statusText}`); 967 } 968 969 BotMon.live.data.clients._list = await response.json(); 970 BotMon.live.data.clients._ready = true; 971 972 } catch (error) { 973 BotMon.live.gui.status.setError("Error while loading the known clients file: " + error.message); 974 } finally { 975 BotMon.live.gui.status.hideBusy("Status: Done."); 976 BotMon.live.data._dispatch('clients') 977 } 978 }, 979 980 // returns bot info if the user-agent matches a known bot, null otherwise: 981 match: function(agent) { 982 //console.info('BotMon.live.data.clients.match(',agent,')'); 983 984 let match = {"n": "Unknown", "v": -1, "id": 'null'}; 985 986 if (agent) { 987 BotMon.live.data.clients._list.find(client => { 988 let r = false; 989 for (let j=0; j<client.rx.length; j++) { 990 const rxr = agent.match(new RegExp(client.rx[j])); 991 if (rxr) { 992 match.n = client.n; 993 match.v = (rxr.length > 1 ? rxr[1] : -1); 994 match.id = client.id || null; 995 r = true; 996 break; 997 } 998 } 999 return r; 1000 }); 1001 } 1002 1003 //console.log(match) 1004 return match; 1005 }, 1006 1007 // return the browser name for a browser ID: 1008 getName: function(id) { 1009 const it = BotMon.live.data.clients._list.find(client => client.id == id); 1010 return ( it && it.n ? it.n : "Unknown"); //it.n; 1011 }, 1012 1013 // indicates if the list is loaded and ready to use: 1014 _ready: false, 1015 1016 // the actual bot list is stored here: 1017 _list: [] 1018 1019 }, 1020 1021 platforms: { 1022 // loads the list of known platforms from a JSON file: 1023 init: async function() { 1024 //console.info('BotMon.live.data.platforms.init()'); 1025 1026 // Load the list of known bots: 1027 BotMon.live.gui.status.showBusy("Loading known platforms"); 1028 const url = BotMon._baseDir + 'config/known-platforms.json'; 1029 try { 1030 const response = await fetch(url); 1031 if (!response.ok) { 1032 throw new Error(`${response.status} ${response.statusText}`); 1033 } 1034 1035 BotMon.live.data.platforms._list = await response.json(); 1036 BotMon.live.data.platforms._ready = true; 1037 1038 } catch (error) { 1039 BotMon.live.gui.status.setError("Error while loading the known platforms file: " + error.message); 1040 } finally { 1041 BotMon.live.gui.status.hideBusy("Status: Done."); 1042 BotMon.live.data._dispatch('platforms') 1043 } 1044 }, 1045 1046 // returns bot info if the browser id matches a known platform: 1047 match: function(cid) { 1048 //console.info('BotMon.live.data.platforms.match(',cid,')'); 1049 1050 let match = {"n": "Unknown", "id": 'null'}; 1051 1052 if (cid) { 1053 BotMon.live.data.platforms._list.find(platform => { 1054 let r = false; 1055 for (let j=0; j<platform.rx.length; j++) { 1056 const rxr = cid.match(new RegExp(platform.rx[j])); 1057 if (rxr) { 1058 match.n = platform.n; 1059 match.v = (rxr.length > 1 ? rxr[1] : -1); 1060 match.id = platform.id || null; 1061 r = true; 1062 break; 1063 } 1064 } 1065 return r; 1066 }); 1067 } 1068 1069 return match; 1070 }, 1071 1072 // return the platform name for a given ID: 1073 getName: function(id) { 1074 const it = BotMon.live.data.platforms._list.find( pf => pf.id == id); 1075 return ( it ? it.n : 'Unknown' ); 1076 }, 1077 1078 1079 // indicates if the list is loaded and ready to use: 1080 _ready: false, 1081 1082 // the actual bot list is stored here: 1083 _list: [] 1084 1085 }, 1086 1087 rules: { 1088 // loads the list of rules and settings from a JSON file: 1089 init: async function() { 1090 //console.info('BotMon.live.data.rules.init()'); 1091 1092 // Load the list of known bots: 1093 BotMon.live.gui.status.showBusy("Loading list of rules …"); 1094 1095 // relative file path to the rules file: 1096 const filePath = 'config/default-config.json'; 1097 1098 // load the rules file: 1099 this._loadrulesFile(BotMon._baseDir + filePath); 1100 }, 1101 1102 /** 1103 * Loads the list of rules and settings from a JSON file. 1104 * @param {String} url - the URL from which to load the rules file. 1105 */ 1106 1107 _loadrulesFile: async function(url) { 1108 //console.info('BotMon.live.data.rules._loadrulesFile(',url,')');} 1109 1110 const me = BotMon.live.data.rules; 1111 try { 1112 const response = await fetch(url); 1113 if (!response.ok) { 1114 throw new Error(`${response.status} ${response.statusText}`); 1115 } 1116 1117 const json = await response.json(); 1118 1119 if (json.rules) { 1120 me._rulesList = json.rules; 1121 } 1122 1123 // override the threshold? 1124 if (json.threshold) me._threshold = json.threshold; 1125 1126 if (json.ipRanges) { 1127 // clean up the IPs first: 1128 let list = []; 1129 json.ipRanges.forEach( it => { 1130 let item = { 1131 'from': BotMon.t._ip2Num(it.from), 1132 'to': BotMon.t._ip2Num(it.to), 1133 'label': it.label 1134 }; 1135 list.push(item); 1136 }); 1137 1138 me._botIPs = list; 1139 } 1140 1141 me._ready = true; 1142 1143 } catch (error) { 1144 BotMon.live.gui.status.setError("Error while loading the config file: " + error.message); 1145 } finally { 1146 BotMon.live.gui.status.hideBusy("Status: Done."); 1147 BotMon.live.data._dispatch('rules') 1148 } 1149 }, 1150 1151 _rulesList: [], // list of rules to find out if a visitor is a bot 1152 _threshold: 100, // above this, it is considered a bot. 1153 1154 // returns a descriptive text for a rule id 1155 getRuleInfo: function(ruleId) { 1156 // console.info('getRuleInfo', ruleId); 1157 1158 // shortcut for neater code: 1159 const me = BotMon.live.data.rules; 1160 1161 for (let i=0; i<me._rulesList.length; i++) { 1162 const rule = me._rulesList[i]; 1163 if (rule.id == ruleId) { 1164 return rule; 1165 } 1166 } 1167 return null; 1168 1169 }, 1170 1171 // evaluate a visitor for lkikelihood of being a bot 1172 evaluate: function(visitor) { 1173 1174 // shortcut for neater code: 1175 const me = BotMon.live.data.rules; 1176 1177 let r = { // evaluation result 1178 'val': 0, 1179 'rules': [], 1180 'isBot': false 1181 }; 1182 1183 for (let i=0; i<me._rulesList.length; i++) { 1184 const rule = me._rulesList[i]; 1185 const params = ( rule.params ? rule.params : [] ); 1186 1187 if (rule.func) { // rule is calling a function 1188 if (me.func[rule.func]) { 1189 if(me.func[rule.func](visitor, ...params)) { 1190 r.val += rule.bot; 1191 r.rules.push(rule.id) 1192 } 1193 } else { 1194 //console.warn("Unknown rule function: “${rule.func}”. Ignoring rule.") 1195 } 1196 } 1197 } 1198 1199 // is a bot? 1200 r.isBot = (r.val >= me._threshold); 1201 1202 return r; 1203 }, 1204 1205 // list of functions that can be called by the rules list to evaluate a visitor: 1206 func: { 1207 1208 // check if client is on the list passed as parameter: 1209 matchesClient: function(visitor, ...clients) { 1210 1211 const clientId = ( visitor._client ? visitor._client.id : ''); 1212 return clients.includes(clientId); 1213 }, 1214 1215 // check if OS/Platform is one of the obsolete ones: 1216 matchesPlatform: function(visitor, ...platforms) { 1217 1218 const pId = ( visitor._platform ? visitor._platform.id : ''); 1219 1220 if (visitor._platform.id == null) console.log(visitor._platform); 1221 1222 return platforms.includes(pId); 1223 }, 1224 1225 // are there at lest num pages loaded? 1226 smallPageCount: function(visitor, num) { 1227 return (visitor._pageViews.length <= Number(num)); 1228 }, 1229 1230 // There was no entry in a specific log file for this visitor: 1231 // note that this will also trigger the "noJavaScript" rule: 1232 noRecord: function(visitor, type) { 1233 return !visitor._seenBy.includes(type); 1234 }, 1235 1236 // there are no referrers in any of the page visits: 1237 noReferrer: function(visitor) { 1238 1239 let r = false; // return value 1240 for (let i = 0; i < visitor._pageViews.length; i++) { 1241 if (!visitor._pageViews[i]._ref) { 1242 r = true; 1243 break; 1244 } 1245 } 1246 return r; 1247 }, 1248 1249 // test for specific client identifiers: 1250 /*matchesClients: function(visitor, ...list) { 1251 1252 for (let i=0; i<list.length; i++) { 1253 if (visitor._client.id == list[i]) { 1254 return true 1255 } 1256 }; 1257 return false; 1258 },*/ 1259 1260 // unusual combinations of Platform and Client: 1261 combinationTest: function(visitor, ...combinations) { 1262 1263 for (let i=0; i<combinations.length; i++) { 1264 1265 if (visitor._platform.id == combinations[i][0] 1266 && visitor._client.id == combinations[i][1]) { 1267 return true 1268 } 1269 }; 1270 1271 return false; 1272 }, 1273 1274 // is the IP address from a known bot network? 1275 fromKnownBotIP: function(visitor) { 1276 1277 const ipInfo = BotMon.live.data.rules.getBotIPInfo(visitor.ip); 1278 1279 if (ipInfo) { 1280 visitor._ipInKnownBotRange = true; 1281 } 1282 1283 return (ipInfo !== null); 1284 }, 1285 1286 // is the page language mentioned in the client's accepted languages? 1287 // the parameter holds an array of exceptions, i.e. page languages that should be ignored. 1288 matchLang: function(visitor, ...exceptions) { 1289 1290 if (visitor.lang && visitor.accept && exceptions.indexOf(visitor.lang) < 0) { 1291 return (visitor.accept.split(',').indexOf(visitor.lang) < 0); 1292 } 1293 return false; 1294 }, 1295 1296 // the "Accept language" header contains certain entries: 1297 clientAccepts: function(visitor, ...languages) { 1298 //console.info('clientAccepts', visitor.accept, languages); 1299 1300 if (visitor.accept && languages) {; 1301 return ( visitor.accept.split(',').filter(lang => languages.includes(lang)).length > 0 ); 1302 } 1303 return false; 1304 }, 1305 1306 // Is there an accept-language field defined at all? 1307 noAcceptLang: function(visitor) { 1308 1309 if (!visitor.accept || visitor.accept.length <= 0) { // no accept-languages header 1310 return true; 1311 } 1312 // TODO: parametrize this! 1313 return false; 1314 }, 1315 // At least x page views were recorded, but they come within less than y seconds 1316 loadSpeed: function(visitor, minItems, maxTime) { 1317 1318 if (visitor._pageViews.length >= minItems) { 1319 //console.log('loadSpeed', visitor._pageViews.length, minItems, maxTime); 1320 1321 const pvArr = visitor._pageViews.map(pv => pv._lastSeen).sort(); 1322 1323 let totalTime = 0; 1324 for (let i=1; i < pvArr.length; i++) { 1325 totalTime += (pvArr[i] - pvArr[i-1]); 1326 } 1327 1328 //console.log(' ', totalTime , Math.round(totalTime / (pvArr.length * 1000)), (( totalTime / pvArr.length ) <= maxTime * 1000), visitor.ip); 1329 1330 return (( totalTime / pvArr.length ) <= maxTime * 1000); 1331 } 1332 }, 1333 1334 // Country code matches one of those in the list: 1335 matchesCountry: function(visitor, ...countries) { 1336 1337 // ingore if geoloc is not set or unknown: 1338 if (visitor.geo) { 1339 return (countries.indexOf(visitor.geo) >= 0); 1340 } 1341 return false; 1342 }, 1343 1344 // Country does not match one of the given codes. 1345 notFromCountry: function(visitor, ...countries) { 1346 1347 // ingore if geoloc is not set or unknown: 1348 if (visitor.geo && visitor.geo !== 'ZZ') { 1349 return (countries.indexOf(visitor.geo) < 0); 1350 } 1351 return false; 1352 } 1353 }, 1354 1355 /* known bot IP ranges: */ 1356 _botIPs: [], 1357 1358 // return information on a bot IP range: 1359 getBotIPInfo: function(ip) { 1360 1361 // shortcut to make code more readable: 1362 const me = BotMon.live.data.rules; 1363 1364 // convert IP address to easier comparable form: 1365 const ipNum = BotMon.t._ip2Num(ip); 1366 1367 for (let i=0; i < me._botIPs.length; i++) { 1368 const ipRange = me._botIPs[i]; 1369 1370 if (ipNum >= ipRange.from && ipNum <= ipRange.to) { 1371 return ipRange; 1372 } 1373 1374 }; 1375 return null; 1376 1377 } 1378 1379 }, 1380 1381 /** 1382 * Loads a log file (server, page load, or ticker) and parses it. 1383 * @param {String} type - the type of the log file to load (srv, log, or tck) 1384 * @param {Function} [onLoaded] - an optional callback function to call after loading is finished. 1385 */ 1386 loadLogFile: async function(type, onLoaded = undefined) { 1387 //console.info('BotMon.live.data.loadLogFile(',type,')'); 1388 1389 let typeName = ''; 1390 let columns = []; 1391 1392 switch (type) { 1393 case "srv": 1394 typeName = "Server"; 1395 columns = ['ts','ip','pg','id','typ','usr','agent','ref','lang','accept','geo']; 1396 break; 1397 case "log": 1398 typeName = "Page load"; 1399 columns = ['ts','ip','pg','id','usr','lt','ref','agent']; 1400 break; 1401 case "tck": 1402 typeName = "Ticker"; 1403 columns = ['ts','ip','pg','id','agent']; 1404 break; 1405 default: 1406 console.warn(`Unknown log type ${type}.`); 1407 return; 1408 } 1409 1410 // Show the busy indicator and set the visible status: 1411 BotMon.live.gui.status.showBusy(`Loading ${typeName} log file …`); 1412 1413 // compose the URL from which to load: 1414 const url = BotMon._baseDir + `logs/${BotMon._today}.${type}.txt`; 1415 //console.log("Loading:",url); 1416 1417 // fetch the data: 1418 try { 1419 const response = await fetch(url); 1420 if (!response.ok) { 1421 1422 throw new Error(`${response.status} ${response.statusText}`); 1423 1424 } else { 1425 1426 // parse the data: 1427 const logtxt = await response.text(); 1428 if (logtxt.length <= 0) { 1429 throw new Error(`Empty log file ${url}.`); 1430 } 1431 1432 logtxt.split('\n').forEach((line) => { 1433 if (line.trim() === '') return; // skip empty lines 1434 const cols = line.split('\t'); 1435 1436 // assign the columns to an object: 1437 const data = {}; 1438 cols.forEach( (colVal,i) => { 1439 colName = columns[i] || `col${i}`; 1440 const colValue = (colName == 'ts' ? new Date(colVal) : colVal.trim()); 1441 data[colName] = colValue; 1442 }); 1443 1444 // register the visit in the model: 1445 switch(type) { 1446 case 'srv': 1447 BotMon.live.data.model.registerVisit(data, type); 1448 break; 1449 case 'log': 1450 data.typ = 'js'; 1451 BotMon.live.data.model.updateVisit(data); 1452 break; 1453 case 'tck': 1454 data.typ = 'js'; 1455 BotMon.live.data.model.updateTicks(data); 1456 break; 1457 default: 1458 console.warn(`Unknown log type ${type}.`); 1459 return; 1460 } 1461 }); 1462 } 1463 1464 } catch (error) { 1465 BotMon.live.gui.status.setError(`Error while loading the ${typeName} log file: ${error.message} – data may be incomplete.`); 1466 } finally { 1467 BotMon.live.gui.status.hideBusy("Status: Done."); 1468 if (onLoaded) { 1469 onLoaded(); // callback after loading is finished. 1470 } 1471 } 1472 } 1473 }, 1474 1475 gui: { 1476 init: function() { 1477 // init the lists view: 1478 this.lists.init(); 1479 }, 1480 1481 /* The Overview / web metrics section of the live tab */ 1482 overview: { 1483 /** 1484 * Populates the overview part of the today tab with the analytics data. 1485 * 1486 * @method make 1487 * @memberof BotMon.live.gui.overview 1488 */ 1489 make: function() { 1490 1491 const data = BotMon.live.data.analytics.data; 1492 1493 // shortcut for neater code: 1494 const makeElement = BotMon.t._makeElement; 1495 1496 const botsVsHumans = document.getElementById('botmon__today__botsvshumans'); 1497 if (botsVsHumans) { 1498 botsVsHumans.appendChild(makeElement('dt', {}, "Bots vs. Humans")); 1499 1500 for (let i = 3; i >= 0; i--) { 1501 const dd = makeElement('dd'); 1502 let title = ''; 1503 let value = ''; 1504 switch(i) { 1505 case 0: 1506 title = "Registered users:"; 1507 value = data.bots.users; 1508 break; 1509 case 1: 1510 title = "Probably humans:"; 1511 value = data.bots.human; 1512 break; 1513 case 2: 1514 title = "Suspected bots:"; 1515 value = data.bots.suspected; 1516 break; 1517 case 3: 1518 title = "Known bots:"; 1519 value = data.bots.known; 1520 break; 1521 default: 1522 console.warn(`Unknown list type ${i}.`); 1523 } 1524 dd.appendChild(makeElement('span', {}, title)); 1525 dd.appendChild(makeElement('strong', {}, value)); 1526 botsVsHumans.appendChild(dd); 1527 } 1528 } 1529 1530 // update known bots list: 1531 const botlist = document.getElementById('botmon__botslist'); /* Known bots */ 1532 botlist.innerHTML = "<dt>Known bots (top 5)</dt>"; 1533 1534 let bots = BotMon.live.data.analytics.groups.knownBots.toSorted( (a, b) => { 1535 return b._pageViews.length - a._pageViews.length; 1536 }); 1537 1538 for (let i=0; i < Math.min(bots.length, 5); i++) { 1539 const dd = makeElement('dd'); 1540 dd.appendChild(makeElement('span', {'class': 'has_icon bot bot_' + bots[i]._bot.id }, bots[i]._bot.n)); 1541 dd.appendChild(makeElement('span', undefined, bots[i]._pageViews.length)); 1542 botlist.appendChild(dd); 1543 } 1544 1545 // update the suspected bot IP ranges list: 1546 /*const botIps = document.getElementById('botmon__today__botips'); 1547 if (botIps) { 1548 botIps.appendChild(makeElement('dt', {}, "Bot IP ranges (top 5)")); 1549 1550 const ipList = BotMon.live.data.analytics.getTopBotIPRanges(5); 1551 ipList.forEach( (ipInfo) => { 1552 const li = makeElement('dd'); 1553 li.appendChild(makeElement('span', {'class': 'has_icon ipaddr ip' + ipInfo.typ }, ipInfo.ip)); 1554 li.appendChild(makeElement('span', {'class': 'count' }, ipInfo.num)); 1555 botIps.append(li) 1556 }); 1557 }*/ 1558 1559 // update the top bot countries list: 1560 const botCountries = document.getElementById('botmon__today__countries'); 1561 if (botCountries) { 1562 botCountries.appendChild(makeElement('dt', {}, "Bot Countries (top 5)")); 1563 const countryList = BotMon.live.data.analytics.getCountryList('likely_bot', 5); 1564 countryList.forEach( (cInfo) => { 1565 const cLi = makeElement('dd'); 1566 cLi.appendChild(makeElement('span', {'class': 'has_icon country ctry_' + cInfo.iso.toLowerCase() }, cInfo.name)); 1567 cLi.appendChild(makeElement('span', {'class': 'count' }, cInfo.count)); 1568 botCountries.appendChild(cLi); 1569 }); 1570 } 1571 1572 // update the webmetrics overview: 1573 const wmoverview = document.getElementById('botmon__today__wm_overview'); 1574 if (wmoverview) { 1575 const bounceRate = Math.round(data.totalVisits / data.totalPageViews * 100); 1576 1577 wmoverview.appendChild(makeElement('dt', {}, "Overview")); 1578 for (let i = 0; i < 3; i++) { 1579 const dd = makeElement('dd'); 1580 let title = ''; 1581 let value = ''; 1582 switch(i) { 1583 case 0: 1584 title = "Total page views:"; 1585 value = data.totalPageViews; 1586 break; 1587 case 1: 1588 title = "Total visitors (est.):"; 1589 value = data.totalVisits; 1590 break; 1591 case 2: 1592 title = "Bounce rate (est.):"; 1593 value = bounceRate + '%'; 1594 break; 1595 default: 1596 console.warn(`Unknown list type ${i}.`); 1597 } 1598 dd.appendChild(makeElement('span', {}, title)); 1599 dd.appendChild(makeElement('strong', {}, value)); 1600 wmoverview.appendChild(dd); 1601 } 1602 } 1603 1604 // update the webmetrics clients list: 1605 const wmclients = document.getElementById('botmon__today__wm_clients'); 1606 if (wmclients) { 1607 1608 wmclients.appendChild(makeElement('dt', {}, "Top browsers")); 1609 1610 const clientList = BotMon.live.data.analytics.getTopBrowsers(5); 1611 if (clientList) { 1612 clientList.forEach( (cInfo) => { 1613 const cDd = makeElement('dd'); 1614 cDd.appendChild(makeElement('span', {'class': 'has_icon client cl_' + cInfo.id }, ( cInfo.name ? cInfo.name : cInfo.id))); 1615 cDd.appendChild(makeElement('span', { 1616 'class': 'count', 1617 'title': cInfo.count + " page views" 1618 }, Math.round(cInfo.pct) + '%')); 1619 wmclients.appendChild(cDd); 1620 }); 1621 } 1622 } 1623 1624 // update the webmetrics platforms list: 1625 const wmplatforms = document.getElementById('botmon__today__wm_platforms'); 1626 if (wmplatforms) { 1627 1628 wmplatforms.appendChild(makeElement('dt', {}, "Top platforms")); 1629 1630 const pfList = BotMon.live.data.analytics.getTopPlatforms(5); 1631 if (pfList) { 1632 pfList.forEach( (pInfo) => { 1633 const pDd = makeElement('dd'); 1634 pDd.appendChild(makeElement('span', {'class': 'has_icon platform pf_' + pInfo.id }, ( pInfo.name ? pInfo.name : pInfo.id))); 1635 pDd.appendChild(makeElement('span', { 1636 'class': 'count', 1637 'title': pInfo.count + " page views" 1638 }, Math.round(pInfo.pct) + '%')); 1639 wmplatforms.appendChild(pDd); 1640 }); 1641 } 1642 } 1643 1644 // update the top referrers; 1645 const wmreferers = document.getElementById('botmon__today__wm_referers'); 1646 if (wmreferers) { 1647 1648 wmreferers.appendChild(makeElement('dt', {}, "Top Referers")); 1649 1650 const refList = BotMon.live.data.analytics.getTopReferers(5); 1651 if (refList) { 1652 refList.forEach( (rInfo) => { 1653 const rDd = makeElement('dd'); 1654 rDd.appendChild(makeElement('span', {'class': 'has_icon referer ref_' + rInfo.id }, rInfo.id)); 1655 rDd.appendChild(makeElement('span', { 1656 'class': 'count', 1657 'title': rInfo.count + " references" 1658 }, Math.round(rInfo.pct) + '%')); 1659 wmreferers.appendChild(rDd); 1660 }); 1661 } 1662 } 1663 } 1664 }, 1665 1666 status: { 1667 setText: function(txt) { 1668 const el = document.getElementById('botmon__today__status'); 1669 if (el && BotMon.live.gui.status._errorCount <= 0) { 1670 el.innerText = txt; 1671 } 1672 }, 1673 1674 setTitle: function(html) { 1675 const el = document.getElementById('botmon__today__title'); 1676 if (el) { 1677 el.innerHTML = html; 1678 } 1679 }, 1680 1681 setError: function(txt) { 1682 console.error(txt); 1683 BotMon.live.gui.status._errorCount += 1; 1684 const el = document.getElementById('botmon__today__status'); 1685 if (el) { 1686 el.innerText = "Data may be incomplete."; 1687 el.classList.add('error'); 1688 } 1689 }, 1690 _errorCount: 0, 1691 1692 showBusy: function(txt = null) { 1693 BotMon.live.gui.status._busyCount += 1; 1694 const el = document.getElementById('botmon__today__busy'); 1695 if (el) { 1696 el.style.display = 'inline-block'; 1697 } 1698 if (txt) BotMon.live.gui.status.setText(txt); 1699 }, 1700 _busyCount: 0, 1701 1702 hideBusy: function(txt = null) { 1703 const el = document.getElementById('botmon__today__busy'); 1704 BotMon.live.gui.status._busyCount -= 1; 1705 if (BotMon.live.gui.status._busyCount <= 0) { 1706 if (el) el.style.display = 'none'; 1707 if (txt) BotMon.live.gui.status.setText(txt); 1708 } 1709 } 1710 }, 1711 1712 lists: { 1713 init: function() { 1714 1715 // function shortcut: 1716 const makeElement = BotMon.t._makeElement; 1717 1718 const parent = document.getElementById('botmon__today__visitorlists'); 1719 if (parent) { 1720 1721 for (let i=0; i < 4; i++) { 1722 1723 // change the id and title by number: 1724 let listTitle = ''; 1725 let listId = ''; 1726 switch (i) { 1727 case 0: 1728 listTitle = "Registered users"; 1729 listId = 'users'; 1730 break; 1731 case 1: 1732 listTitle = "Probably humans"; 1733 listId = 'humans'; 1734 break; 1735 case 2: 1736 listTitle = "Suspected bots"; 1737 listId = 'suspectedBots'; 1738 break; 1739 case 3: 1740 listTitle = "Known bots"; 1741 listId = 'knownBots'; 1742 break; 1743 default: 1744 console.warn('Unknown list number.'); 1745 } 1746 1747 const details = makeElement('details', { 1748 'data-group': listId, 1749 'data-loaded': false 1750 }); 1751 const title = details.appendChild(makeElement('summary')); 1752 title.appendChild(makeElement('span', {'class': 'title'}, listTitle)); 1753 title.appendChild(makeElement('span', {'class': 'counter'})); 1754 details.addEventListener("toggle", this._onDetailsToggle); 1755 1756 parent.appendChild(details); 1757 1758 } 1759 } 1760 }, 1761 1762 _onDetailsToggle: function(e) { 1763 //console.info('BotMon.live.gui.lists._onDetailsToggle()'); 1764 1765 const target = e.target; 1766 1767 if (target.getAttribute('data-loaded') == 'false') { // only if not loaded yet 1768 target.setAttribute('data-loaded', 'loading'); 1769 1770 const fillType = target.getAttribute('data-group'); 1771 const fillList = BotMon.live.data.analytics.groups[fillType]; 1772 if (fillList && fillList.length > 0) { 1773 1774 const ul = BotMon.t._makeElement('ul'); 1775 1776 fillList.forEach( (it) => { 1777 ul.appendChild(BotMon.live.gui.lists._makeVisitorItem(it, fillType)); 1778 }); 1779 1780 target.appendChild(ul); 1781 target.setAttribute('data-loaded', 'true'); 1782 } else { 1783 target.setAttribute('data-loaded', 'false'); 1784 } 1785 1786 } 1787 }, 1788 1789 _makeVisitorItem: function(data, type) { 1790 1791 // shortcut for neater code: 1792 const make = BotMon.t._makeElement; 1793 1794 let ipType = ( data.ip.indexOf(':') >= 0 ? '6' : '4' ); 1795 if (data.ip == '127.0.0.1' || data.ip == '::1' ) ipType = '0'; 1796 1797 const platformName = (data._platform ? data._platform.n : 'Unknown'); 1798 const clientName = (data._client ? data._client.n: 'Unknown'); 1799 1800 const sumClass = ( data._seenBy.indexOf('srv') < 0 ? 'noServer' : 'hasServer'); 1801 1802 const li = make('li'); // root list item 1803 const details = make('details'); 1804 const summary = make('summary', { 1805 'class': sumClass 1806 }); 1807 details.appendChild(summary); 1808 1809 const span1 = make('span'); /* left-hand group */ 1810 1811 if (data._type !== BM_USERTYPE.KNOWN_BOT) { /* No platform/client for bots */ 1812 span1.appendChild(make('span', { /* Platform */ 1813 'class': 'icon_only platform pf_' + (data._platform ? data._platform.id : 'unknown'), 1814 'title': "Platform: " + platformName 1815 }, platformName)); 1816 1817 span1.appendChild(make('span', { /* Client */ 1818 'class': 'icon_only client client cl_' + (data._client ? data._client.id : 'unknown'), 1819 'title': "Client: " + clientName 1820 }, clientName)); 1821 } 1822 1823 // identifier: 1824 if (data._type == BM_USERTYPE.KNOWN_BOT) { /* Bot only */ 1825 1826 const botName = ( data._bot && data._bot.n ? data._bot.n : "Unknown"); 1827 span1.appendChild(make('span', { /* Bot */ 1828 'class': 'has_icon bot bot_' + (data._bot ? data._bot.id : 'unknown'), 1829 'title': "Bot: " + botName 1830 }, botName)); 1831 1832 } else if (data._type == BM_USERTYPE.KNOWN_USER) { /* User only */ 1833 1834 span1.appendChild(make('span', { /* User */ 1835 'class': 'has_icon user_known', 1836 'title': "User: " + data.usr 1837 }, data.usr)); 1838 1839 } else { /* others */ 1840 1841 1842 /*span1.appendChild(make('span', { // IP-Address 1843 'class': 'has_icon ipaddr ip' + ipType, 1844 'title': "IP-Address: " + data.ip 1845 }, data.ip));*/ 1846 1847 span1.appendChild(make('span', { /* Internal ID */ 1848 'class': 'has_icon session typ_' + data.typ, 1849 'title': "ID: " + data.id 1850 }, data.id)); 1851 } 1852 1853 // country flag: 1854 if (data.geo && data.geo !== 'ZZ') { 1855 span1.appendChild(make('span', { 1856 'class': 'icon_only country ctry_' + data.geo.toLowerCase(), 1857 'data-ctry': data.geo, 1858 'title': "Country: " + ( data._country || "Unknown") 1859 }, ( data._country || "Unknown") )); 1860 } 1861 1862 summary.appendChild(span1); 1863 const span2 = make('span'); /* right-hand group */ 1864 1865 span2.appendChild(make('span', { /* first-seen */ 1866 'class': 'has_iconfirst-seen', 1867 'title': "First seen: " + data._firstSeen.toLocaleString() + " UTC" 1868 }, BotMon.t._formatTime(data._firstSeen))); 1869 1870 span2.appendChild(make('span', { /* page views */ 1871 'class': 'has_icon pageviews', 1872 'title': data._pageViews.length + " page view(s)" 1873 }, data._pageViews.length)); 1874 1875 summary.appendChild(span2); 1876 1877 // add details expandable section: 1878 details.appendChild(BotMon.live.gui.lists._makeVisitorDetails(data, type)); 1879 1880 li.appendChild(details); 1881 return li; 1882 }, 1883 1884 _makeVisitorDetails: function(data, type) { 1885 1886 // shortcut for neater code: 1887 const make = BotMon.t._makeElement; 1888 1889 let ipType = ( data.ip.indexOf(':') >= 0 ? '6' : '4' ); 1890 if (data.ip == '127.0.0.1' || data.ip == '::1' ) ipType = '0'; 1891 const platformName = (data._platform ? data._platform.n : 'Unknown'); 1892 const clientName = (data._client ? data._client.n: 'Unknown'); 1893 1894 const dl = make('dl', {'class': 'visitor_details'}); 1895 1896 if (data._type == BM_USERTYPE.KNOWN_BOT) { 1897 1898 dl.appendChild(make('dt', {}, "Bot name:")); /* bot info */ 1899 dl.appendChild(make('dd', {'class': 'icon_only bot bot_' + (data._bot ? data._bot.id : 'unknown')}, 1900 (data._bot ? data._bot.n : 'Unknown'))); 1901 1902 if (data._bot && data._bot.url) { 1903 dl.appendChild(make('dt', {}, "Bot info:")); /* bot info */ 1904 const botInfoDd = dl.appendChild(make('dd')); 1905 botInfoDd.appendChild(make('a', { 1906 'href': data._bot.url, 1907 'target': '_blank' 1908 }, data._bot.url)); /* bot info link*/ 1909 1910 } 1911 1912 } else { /* not for bots */ 1913 1914 dl.appendChild(make('dt', {}, "Client:")); /* client */ 1915 dl.appendChild(make('dd', {'class': 'has_icon client cl_' + (data._client ? data._client.id : 'unknown')}, 1916 clientName + ( data._client.v > 0 ? ' (' + data._client.v + ')' : '' ) )); 1917 1918 dl.appendChild(make('dt', {}, "Platform:")); /* platform */ 1919 dl.appendChild(make('dd', {'class': 'has_icon platform pf_' + (data._platform ? data._platform.id : 'unknown')}, 1920 platformName + ( data._platform.v > 0 ? ' (' + data._platform.v + ')' : '' ) )); 1921 1922 dl.appendChild(make('dt', {}, "IP-Address:")); 1923 const ipItem = make('dd', {'class': 'has_icon ipaddr ip' + ipType}); 1924 ipItem.appendChild(make('span', {'class': 'address'} , data.ip)); 1925 ipItem.appendChild(make('a', { 1926 'class': 'icon_only extlink dnscheck', 1927 'href': `https://dnschecker.org/ip-location.php?ip=${encodeURIComponent(data.ip)}`, 1928 'target': 'dnscheck', 1929 'title': "View this address on DNSChecker.org" 1930 } , "Check Address")); 1931 ipItem.appendChild(make('a', { 1932 'class': 'icon_only extlink ipinfo', 1933 'href': `https://ipinfo.io/${encodeURIComponent(data.ip)}`, 1934 'target': 'ipinfo', 1935 'title': "View this address on IPInfo.io" 1936 } , "DNS Info")); 1937 dl.appendChild(ipItem); 1938 1939 /*dl.appendChild(make('dt', {}, "ID:")); 1940 dl.appendChild(make('dd', {'class': 'has_icon ip' + data.typ}, data.id));*/ 1941 } 1942 1943 if (Math.abs(data._lastSeen - data._firstSeen) < 100) { 1944 dl.appendChild(make('dt', {}, "Seen:")); 1945 dl.appendChild(make('dd', {'class': 'seen'}, data._firstSeen.toLocaleString())); 1946 } else { 1947 dl.appendChild(make('dt', {}, "First seen:")); 1948 dl.appendChild(make('dd', {'class': 'firstSeen'}, data._firstSeen.toLocaleString())); 1949 dl.appendChild(make('dt', {}, "Last seen:")); 1950 dl.appendChild(make('dd', {'class': 'lastSeen'}, data._lastSeen.toLocaleString())); 1951 } 1952 1953 dl.appendChild(make('dt', {}, "User-Agent:")); 1954 dl.appendChild(make('dd', {'class': 'agent'}, data.agent)); 1955 1956 dl.appendChild(make('dt', {}, "Languages:")); 1957 dl.appendChild(make('dd', {'class': 'langs'}, ` [${data.accept}]`)); 1958 1959 if (data.geo && data.geo !=='') { 1960 dl.appendChild(make('dt', {}, "Location:")); 1961 dl.appendChild(make('dd', { 1962 'class': 'has_icon country ctry_' + data.geo.toLowerCase(), 1963 'data-ctry': data.geo, 1964 'title': "Country: " + data._country 1965 }, data._country + ' (' + data.geo + ')')); 1966 } 1967 1968 /*dl.appendChild(make('dt', {}, "Visitor Type:")); 1969 dl.appendChild(make('dd', undefined, data._type ));*/ 1970 1971 dl.appendChild(make('dt', {}, "Session ID:")); 1972 dl.appendChild(make('dd', {'class': 'has_icon session typ_' + data.typ}, data.id)); 1973 1974 dl.appendChild(make('dt', {}, "Seen by:")); 1975 dl.appendChild(make('dd', undefined, data._seenBy.join(', ') )); 1976 1977 dl.appendChild(make('dt', {}, "Visited pages:")); 1978 const pagesDd = make('dd', {'class': 'pages'}); 1979 const pageList = make('ul'); 1980 1981 /* list all page views */ 1982 data._pageViews.sort( (a, b) => a._firstSeen - b._firstSeen ); 1983 data._pageViews.forEach( (page) => { 1984 pageList.appendChild(BotMon.live.gui.lists._makePageViewItem(page)); 1985 }); 1986 pagesDd.appendChild(pageList); 1987 dl.appendChild(pagesDd); 1988 1989 /* bot evaluation rating */ 1990 if (data._type !== BM_USERTYPE.KNOWN_BOT && data._type !== BM_USERTYPE.KNOWN_USER) { 1991 dl.appendChild(make('dt', undefined, "Bot rating:")); 1992 dl.appendChild(make('dd', {'class': 'bot-rating'}, ( data._botVal ? data._botVal : '–' ) + ' (of ' + BotMon.live.data.rules._threshold + ')')); 1993 1994 /* add bot evaluation details: */ 1995 if (data._eval) { 1996 dl.appendChild(make('dt', {}, "Bot evaluation:")); 1997 const evalDd = make('dd'); 1998 const testList = make('ul',{ 1999 'class': 'eval' 2000 }); 2001 data._eval.forEach( test => { 2002 2003 const tObj = BotMon.live.data.rules.getRuleInfo(test); 2004 let tDesc = tObj ? tObj.desc : test; 2005 2006 // special case for Bot IP range test: 2007 if (tObj.func == 'fromKnownBotIP') { 2008 const rangeInfo = BotMon.live.data.rules.getBotIPInfo(data.ip); 2009 if (rangeInfo) { 2010 tDesc += ' (' + (rangeInfo.label ? rangeInfo.label : 'Unknown') + ')'; 2011 } 2012 } 2013 2014 // create the entry field 2015 const tstLi = make('li'); 2016 tstLi.appendChild(make('span', { 2017 'data-testid': test 2018 }, tDesc)); 2019 tstLi.appendChild(make('span', {}, ( tObj ? tObj.bot : '—') )); 2020 testList.appendChild(tstLi); 2021 }); 2022 2023 // add total row 2024 const tst2Li = make('li', { 2025 'class': 'total' 2026 }); 2027 /*tst2Li.appendChild(make('span', {}, "Total:")); 2028 tst2Li.appendChild(make('span', {}, data._botVal)); 2029 testList.appendChild(tst2Li);*/ 2030 2031 evalDd.appendChild(testList); 2032 dl.appendChild(evalDd); 2033 } 2034 } 2035 // return the element to add to the UI: 2036 return dl; 2037 }, 2038 2039 // make a page view item: 2040 _makePageViewItem: function(page) { 2041 //console.log("makePageViewItem:",page); 2042 2043 // shortcut for neater code: 2044 const make = BotMon.t._makeElement; 2045 2046 // the actual list item: 2047 const pgLi = make('li'); 2048 2049 const row1 = make('div', {'class': 'row'}); 2050 2051 row1.appendChild(make('span', { // page id is the left group 2052 'data-lang': page.lang, 2053 'title': "PageID: " + page.pg 2054 }, page.pg)); /* DW Page ID */ 2055 2056 // get the time difference: 2057 row1.appendChild(make('span', { 2058 'class': 'first-seen', 2059 'title': "First visited: " + page._firstSeen.toLocaleString() + " UTC" 2060 }, BotMon.t._formatTime(page._firstSeen))); 2061 2062 pgLi.appendChild(row1); 2063 2064 /* LINE 2 */ 2065 2066 const row2 = make('div', {'class': 'row'}); 2067 2068 // page referrer: 2069 if (page._ref) { 2070 row2.appendChild(make('span', { 2071 'class': 'referer', 2072 'title': "Referrer: " + page._ref.href 2073 }, page._ref.hostname)); 2074 } else { 2075 row2.appendChild(make('span', { 2076 'class': 'referer' 2077 }, "No referer")); 2078 } 2079 2080 // visit duration: 2081 let visitTimeStr = "Bounce"; 2082 const visitDuration = page._lastSeen.getTime() - page._firstSeen.getTime(); 2083 if (visitDuration > 0) { 2084 visitTimeStr = Math.floor(visitDuration / 1000) + "s"; 2085 } 2086 const tDiff = BotMon.t._formatTimeDiff(page._firstSeen, page._lastSeen); 2087 if (tDiff) { 2088 row2.appendChild(make('span', {'class': 'visit-length', 'title': 'Last seen: ' + page._lastSeen.toLocaleString()}, tDiff)); 2089 } else { 2090 row2.appendChild(make('span', { 2091 'class': 'bounce', 2092 'title': "Visitor bounced"}, "Bounce")); 2093 } 2094 2095 pgLi.appendChild(row2); 2096 2097 return pgLi; 2098 } 2099 } 2100 } 2101}; 2102 2103/* launch only if the BotMon admin panel is open: */ 2104if (document.getElementById('botmon__admin')) { 2105 BotMon.init(); 2106}