stats.html 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781
  1. <script src="./script/useragent.js"></script>
  2. <link href="./script/datepicker/dp-light.css" rel="stylesheet">
  3. <script defer src="./script/datepicker/datepicker.js"></script>
  4. <div class="standardContainer">
  5. <div class="ui basic segment">
  6. <h2>Statistical Analysis</h2>
  7. <p>Statistic of your server in every aspects</p>
  8. <div style="margin-bottom: 0.4em;">
  9. <div class="ui small input">
  10. <input type="text" id="statsRangeStart" placeholder="From date">
  11. </div>
  12. <span style="padding-left: 0.6em; padding-right: 0.6em;"> <i class="ui right arrow icon"></i> </span>
  13. <div class="ui small input">
  14. <input type="text" id="statsRangeEnd" placeholder="End date">
  15. </div>
  16. </div>
  17. <button onclick="handleLoadStatisticButtonPress();" class="ui basic button"><i class="blue search icon"></i> Search</button>
  18. <button onclick="clearStatisticDateRange();" class="ui yellow basic button"><i class="eraser icon"></i> Clear Range</button>
  19. <br>
  20. <small>Leave end range as empty for showing starting day only statistic</small>
  21. </div>
  22. <div class="ui divider"></div>
  23. <div id="statisticRenderNotEnoughData" class="ui segment" style="padding: 2em;" align="center">
  24. <h4 class="ui icon header">
  25. <i class="medium icons" style="color: #dbdbdb !important;">
  26. <i class="chart pie icon"></i>
  27. <i class="small corner remove icon" style="
  28. font-size: 1.4em;
  29. margin-right: -0.2em;
  30. margin-bottom: -0em;
  31. "></i>
  32. </i>
  33. <div class="content" style="margin-top: 1em; color: #7c7c7c !important;">
  34. No Data
  35. <div class="sub header" style="color: #adadad !important;">The selected period contains too little or no request data collected. <br>
  36. Please select a larger range or make sure there are enough traffic routing through this site.</div>
  37. </div>
  38. </h4>
  39. </div>
  40. <div id="statisticRenderElement" class="ui basic segment">
  41. <!-- View Counts Statistics -->
  42. <div class="ui three small statistics">
  43. <div class="statistic">
  44. <div class="value totalViewCount">
  45. </div>
  46. <div class="label">
  47. Total Requests
  48. </div>
  49. </div>
  50. <div class="statistic">
  51. <div class="value">
  52. <i class="ui green check circle icon"></i> <span class="totalSuccCount"></span>
  53. </div>
  54. <div class="label">
  55. Success Requests
  56. </div>
  57. </div>
  58. <div class="statistic">
  59. <div class="value">
  60. <i class="ui red times circle icon"></i> <span class="totalErrorCount"></span>
  61. </div>
  62. <div class="label">
  63. Error Requests
  64. </div>
  65. </div>
  66. </div>
  67. <!-- Forward Type Data -->
  68. <h3>Forward Traffic Types</h3>
  69. <p>Traffic forwarding type classified by their protocols and proxy rules.</p>
  70. <table class="ui celled unstackable table">
  71. <thead>
  72. <tr><th>Forward Type</th>
  73. <th>Counts</th>
  74. <th>Percentage</th>
  75. </tr></thead>
  76. <tbody class="forwardTypeCounts">
  77. </tbody>
  78. </table>
  79. <!-- Client Geolocation Analysis-->
  80. <h3>Visitors Countries</h3>
  81. <p>Distributions of visitors by country code. Access origin are estimated using open source GeoIP database and might not be accurate.</p>
  82. <div style="min-height: 400px;">
  83. <canvas id="stats_visitors"></canvas>
  84. </div>
  85. <div class="ui divider"></div>
  86. <!-- Client IP Analysis -->
  87. <div class="ui stackable grid">
  88. <div class="eight wide column">
  89. <h3>Requests IP Version</h3>
  90. <p>The version of Internet Protocol that the client is using. If the request client is pass through a DNS proxy like CloudFlare,
  91. the CloudFlare proxy server address will be filtered and only the first value in the RemoteAddress field will be analysised.</p>
  92. <div>
  93. <canvas id="stats_ipver"></canvas>
  94. </div>
  95. </div>
  96. <div class="eight wide column">
  97. <h3>Request Origins</h3>
  98. <p>Top 25 request origin sorted by request count</p>
  99. <div style="height: 500px; overflow-y: auto;">
  100. <table class="ui unstackable striped celled table">
  101. <thead>
  102. <tr>
  103. <th class="no-sort">Request Origin</th>
  104. <th class="no-sort">No of Requests</th>
  105. </tr></thead>
  106. <tbody id="stats_requestCountlist">
  107. </tbody>
  108. </table>
  109. </div>
  110. </div>
  111. </div>
  112. <div class="ui divider"></div>
  113. <!-- Client Device Analysis -->
  114. <div class="ui stackable grid">
  115. <div class="eight wide column">
  116. <h3>Client Devices</h3>
  117. <p>Device type analysis by its request interactions.The number of iteration count does not means the number unique device, as no cookie is used to track the devices identify.</p>
  118. <div>
  119. <canvas id="stats_device"></canvas>
  120. </div>
  121. </div>
  122. <div class="eight wide column">
  123. <h3>Client Browsers</h3>
  124. <p>The browsers where your client is using to visit your site</p>
  125. <div>
  126. <canvas id="stats_browsers"></canvas>
  127. </div>
  128. </div>
  129. </div>
  130. <div class="ui stackable grid">
  131. <div class="eight wide column">
  132. <h3>Client OS</h3>
  133. <p>The OS where your client is using. Estimated using the UserAgent header sent by the client browser while requesting a resources from one of your host.</p>
  134. <div>
  135. <canvas id="stats_OS"></canvas>
  136. </div>
  137. </div>
  138. <div class="eight wide column">
  139. <h3>OS Versions</h3>
  140. <p>The OS versions most commonly used by your site's visitors.</p>
  141. <div style="height: 500px; overflow-y: auto;">
  142. <table class="ui unstackable striped celled table">
  143. <thead>
  144. <tr>
  145. <th>OS Version</th>
  146. <th>Request Counts</th>
  147. <th>Percentage</th>
  148. </tr></thead>
  149. <tbody id="stats_OSVersionList">
  150. </tbody>
  151. </table>
  152. </div>
  153. </div>
  154. </div>
  155. <div class="ui divider"></div>
  156. <div class="ui stackable grid">
  157. <div class="eight wide column">
  158. <h3>Request File Types</h3>
  159. <p>The file types being served by this proxy</p>
  160. <div>
  161. <canvas id="stats_filetype"></canvas>
  162. </div>
  163. </div>
  164. <div class="eight wide column">
  165. <h3>Referring Sites</h3>
  166. <p>The Top 100 sources of traffic according to referer header</p>
  167. <div>
  168. <div style="height: 500px; overflow-y: auto;">
  169. <table class="ui unstackable striped celled table">
  170. <thead>
  171. <tr>
  172. <th class="no-sort">Referer</th>
  173. <th class="no-sort">Requests</th>
  174. </tr></thead>
  175. <tbody id="stats_RefererTable">
  176. </tbody>
  177. </table>
  178. </div>
  179. </div>
  180. </div>
  181. </div>
  182. <div class="ui divider"></div>
  183. <div class="ui basic segment" id="trendGraphs">
  184. <h3>Visitor Trend Analysis</h3>
  185. <p>Request trends in the selected time range</p>
  186. <div>
  187. <canvas id="requestTrends"></canvas>
  188. </div>
  189. </div>
  190. </div>
  191. <!-- <button class="ui icon right floated basic button" onclick="initStatisticSummery();"><i class="green refresh icon"></i> Refresh</button> -->
  192. <br><br>
  193. </div>
  194. <script>
  195. var statisticCharts = [];
  196. //Start day must be earlier than end date
  197. function initStatisticSummery(startdate="", enddate=""){
  198. if (startdate == "" && enddate == "" ){
  199. let todaykey = getTodayStatisticKey();
  200. loadStatisticByDate(todaykey);
  201. }else if ((startdate != "" && enddate == "") || startdate == enddate){
  202. //Load the target date
  203. let targetDate = startdate.trim();
  204. loadStatisticByDate(targetDate);
  205. }else{
  206. //Two dates are given and they are not identical
  207. loadStatisticByRange(startdate, enddate);
  208. //console.log(startdate, enddate);
  209. }
  210. }
  211. function loadStatisticByDate(dateid){
  212. $.getJSON("/api/analytic/load?id=" + dateid, function(data){
  213. if (data.error != undefined){
  214. msgbox(data.error, false, 6000);
  215. return;
  216. }
  217. //Destroy all the previous charts
  218. statisticCharts.forEach(function(thisChart){
  219. thisChart.destroy();
  220. })
  221. if (data.TotalRequest == 0){
  222. //No data to analysis
  223. $("#statisticRenderElement").hide()
  224. $("#statisticRenderNotEnoughData").show();
  225. return;
  226. }else{
  227. $("#statisticRenderElement").show();
  228. $("#statisticRenderNotEnoughData").hide();
  229. }
  230. //Render the text values
  231. $("#statisticRenderElement").find(".totalViewCount").text(abbreviateNumber(data.TotalRequest));
  232. $("#statisticRenderElement").find(".totalSuccCount").text(abbreviateNumber(data.ValidRequest));
  233. $("#statisticRenderElement").find(".totalErrorCount").text(abbreviateNumber(data.ErrorRequest));
  234. //Render forward type data
  235. renderForwardTypeCounts(data.ForwardTypes);
  236. //Render visitor data
  237. renderVisitorChart(data.RequestOrigin);
  238. //Render IP versions
  239. renderIPVersionChart(data.RequestClientIp);
  240. //Render user agent analysis
  241. renderUserAgentCharts(data.UserAgent);
  242. //Render file type by analysising request URL paths
  243. renderFileTypeGraph(data.RequestURL);
  244. //Render Referer header
  245. renderRefererTable(data.Referer);
  246. //Hide the trend graphs
  247. $("#trendGraphs").hide();
  248. });
  249. }
  250. initStatisticSummery();
  251. $("#statsRangeStart").val(getTodayStatisticKey().split("_").join("-"));
  252. function loadStatisticByRange(startdate, endDate){
  253. $.getJSON("/api/analytic/loadRange?start=" + startdate + "&end=" + endDate, function(data){
  254. //console.log(data);
  255. //Destroy all the previous charts
  256. statisticCharts.forEach(function(thisChart){
  257. thisChart.destroy();
  258. })
  259. if (data.Summary.TotalRequest == 0){
  260. //No data to analysis
  261. $("#statisticRenderElement").hide()
  262. $("#statisticRenderNotEnoughData").show();
  263. return;
  264. }else{
  265. $("#statisticRenderElement").show();
  266. $("#statisticRenderNotEnoughData").hide();
  267. }
  268. //Render the text values
  269. $("#statisticRenderElement").find(".totalViewCount").text(abbreviateNumber(data.Summary.TotalRequest));
  270. $("#statisticRenderElement").find(".totalSuccCount").text(abbreviateNumber(data.Summary.ValidRequest));
  271. $("#statisticRenderElement").find(".totalErrorCount").text(abbreviateNumber(data.Summary.ErrorRequest));
  272. //Render forward type data
  273. renderForwardTypeCounts(data.Summary.ForwardTypes);
  274. //Render visitor data
  275. renderVisitorChart(data.Summary.RequestOrigin);
  276. //Render IP versions
  277. renderIPVersionChart(data.Summary.RequestClientIp);
  278. //Render user agent analysis
  279. renderUserAgentCharts(data.Summary.UserAgent);
  280. //Render file type by analysising request URL paths
  281. renderFileTypeGraph(data.Summary.RequestURL);
  282. //Render Referer header
  283. renderRefererTable(data.Summary.Referer);
  284. //Render the trend graph
  285. $("#trendGraphs").show();
  286. renderTrendGraph(data.Records);
  287. });
  288. }
  289. picker.attach({ target: document.getElementById("statsRangeStart") });
  290. picker.attach({ target: document.getElementById("statsRangeEnd") });
  291. function renderForwardTypeCounts(forwardTypes){
  292. let tablBody = $("#statisticRenderElement").find(".forwardTypeCounts");
  293. tablBody.empty();
  294. let totalForwardCounts = 0;
  295. for (let [key, value] of Object.entries(forwardTypes)) {
  296. totalForwardCounts += value;
  297. }
  298. for (let [key, value] of Object.entries(forwardTypes)) {
  299. tablBody.append(`<tr>
  300. <td>${key}</td>
  301. <td>${abbreviateNumber(value)} (${value})</td>
  302. <td>${((value/totalForwardCounts)*100).toFixed(3)}%</td>
  303. </tr>
  304. `);
  305. }
  306. }
  307. function getTodayStatisticKey(){
  308. var today = new Date();
  309. var year = today.getFullYear();
  310. var month = String(today.getMonth() + 1).padStart(2, '0');
  311. var day = String(today.getDate()).padStart(2, '0');
  312. var formattedDate = year + '_' + month + '_' + day;
  313. return formattedDate
  314. }
  315. function handleLoadStatisticButtonPress(){
  316. var sd = $("#statsRangeStart").val();
  317. var ed = $("#statsRangeEnd").val();
  318. //Swap them if sd is later than ed
  319. if (sd != "" && ed != "" && sd > ed) {
  320. ed = [sd, sd = ed][0];
  321. $("#statsRangeStart").val(sd);
  322. $("#statsRangeEnd").val(ed);
  323. }
  324. initStatisticSummery(sd, ed);
  325. }
  326. function clearStatisticDateRange(){
  327. $("#statsRangeStart").val("");
  328. $("#statsRangeEnd").val("");
  329. }
  330. function renderRefererTable(refererList){
  331. const sortedEntries = Object.entries(refererList).sort(([, valueA], [, valueB]) => valueB - valueA);
  332. $("#stats_RefererTable").html("");
  333. let endStop = 100;
  334. if (sortedEntries.length < 100){
  335. endStop = sortedEntries.length;
  336. }
  337. for (var i = 0; i < endStop; i++) {
  338. let referer = (decodeURIComponent(sortedEntries[i][0])).replace(/(<([^>]+)>)/ig,"");
  339. if (sortedEntries[i][0] == ""){
  340. //Root
  341. referer = `<span style="color: #b5b5b5;">(<i class="eye slash outline icon"></i> Unknown or Hidden)</span>`;
  342. }
  343. $("#stats_RefererTable").append(`<tr>
  344. <td>${referer}</td>
  345. <td>${sortedEntries[i][1]}</td>
  346. </tr>`);
  347. }
  348. }
  349. function renderFileTypeGraph(requestURLs){
  350. //Create the device chart
  351. let fileExtensions = {};
  352. for (const [url, count] of Object.entries(requestURLs)) {
  353. let filename = url.split("/").pop();
  354. let ext = "";
  355. if (filename == ""){
  356. //Loading from a folder
  357. ext = "Folder path"
  358. }else{
  359. if (filename.includes(".")){
  360. ext = filename.split(".").pop();
  361. }else{
  362. ext = "API call"
  363. }
  364. }
  365. if (fileExtensions[ext] != undefined){
  366. fileExtensions[ext] = fileExtensions[ext] + count;
  367. }else{
  368. //First time this ext show up
  369. fileExtensions[ext] = count;
  370. }
  371. }
  372. //Convert the key-value pairs to array for graph render
  373. let fileTypes = [];
  374. let fileCounts = [];
  375. let colors = [];
  376. for (const [ftype, count] of Object.entries(fileExtensions)) {
  377. fileTypes.push(ftype);
  378. fileCounts.push(count);
  379. colors.push(generateColorFromHash(ftype));
  380. }
  381. let filetypeChart = new Chart(document.getElementById("stats_filetype"), {
  382. type: 'pie',
  383. data: {
  384. labels: fileTypes,
  385. datasets: [{
  386. data: fileCounts,
  387. backgroundColor: colors,
  388. hoverBackgroundColor: colors,
  389. }]
  390. },
  391. options: {
  392. responsive: true,
  393. maintainAspectRatio: false,
  394. }
  395. });
  396. statisticCharts.push(filetypeChart);
  397. }
  398. function renderTrendGraph(dailySummary){
  399. // Get the canvas element
  400. const canvas = document.getElementById('requestTrends');
  401. //Generate the X axis labels
  402. let datesLabel = [];
  403. let succData = [];
  404. let errorData = [];
  405. let totalData = [];
  406. for (var i = 0; i < dailySummary.length; i++){
  407. let thisDayData = dailySummary[i];
  408. datesLabel.push("Day " + i);
  409. succData.push(thisDayData.ValidRequest);
  410. errorData.push(thisDayData.ErrorRequest);
  411. totalData.push(thisDayData.TotalRequest);
  412. }
  413. // Create the chart
  414. let TrendChart = new Chart(canvas, {
  415. type: 'line',
  416. data: {
  417. labels: datesLabel,
  418. datasets: [
  419. {
  420. label: 'All Requests',
  421. data: totalData,
  422. borderColor: '#7d99f7',
  423. backgroundColor: 'rgba(125, 153, 247, 0.4)',
  424. fill: false
  425. },
  426. {
  427. label: 'Success Requests',
  428. data: succData,
  429. borderColor: '#6dad7c',
  430. backgroundColor: "rgba(109, 173, 124, 0.4)",
  431. fill: true
  432. },
  433. {
  434. label: 'Error Requests',
  435. data: errorData,
  436. borderColor: '#de7373',
  437. backgroundColor: "rgba(222, 115, 115, 0.4)",
  438. fill: true
  439. },
  440. ]
  441. },
  442. options: {
  443. responsive: true,
  444. maintainAspectRatio: true,
  445. title: {
  446. display: true,
  447. //text: 'Line Chart Example'
  448. },
  449. scales: {
  450. x: {
  451. display: true,
  452. title: {
  453. display: false,
  454. text: 'Time'
  455. }
  456. },
  457. y: {
  458. display: true,
  459. title: {
  460. display: true,
  461. text: 'Request Counts'
  462. }
  463. }
  464. }
  465. }
  466. });
  467. statisticCharts.push(TrendChart);
  468. }
  469. function renderUserAgentCharts(userAgentsEntries){
  470. let userAgents = Object.keys(userAgentsEntries);
  471. let requestCounts = Object.values(userAgentsEntries);
  472. let mobileUser = 0;
  473. let desktopUser = 0;
  474. let osTypes = {};
  475. let osVersion = {};
  476. let browserTypes = {};
  477. let totalRequestCounts = 0;
  478. requestCounts.forEach(function(rc){
  479. totalRequestCounts += rc;
  480. })
  481. //Building a statistic summary
  482. userAgents.forEach(function(thisUA){
  483. var uaInfo = parseUserAgent(thisUA);
  484. if (uaInfo.isMobile){
  485. mobileUser+=userAgentsEntries[thisUA];
  486. }else{
  487. desktopUser+=userAgentsEntries[thisUA];
  488. }
  489. let currentNo = osTypes[uaInfo.os];
  490. let osVersionKey = uaInfo.os + " " + uaInfo.version.split("_").join(".");
  491. if (currentNo == undefined){
  492. osTypes[uaInfo.os] = userAgentsEntries[thisUA];
  493. }else{
  494. osTypes[uaInfo.os] = currentNo + userAgentsEntries[thisUA];
  495. }
  496. let p = osVersion[osVersionKey];
  497. if (p == undefined){
  498. osVersion[osVersionKey] = userAgentsEntries[thisUA];
  499. }else{
  500. osVersion[osVersionKey] = p + userAgentsEntries[thisUA];
  501. }
  502. let browserTypeKey = uaInfo.browser;
  503. if (browserTypeKey.indexOf("//") >= 0){
  504. //This is a uncatergorize browser, mostly a bot
  505. browserTypeKey = "Bots";
  506. }else if (browserTypeKey == ""){
  507. //No information
  508. browserTypeKey = "Unknown";
  509. }
  510. let b = browserTypes[browserTypeKey];
  511. if (b == undefined){
  512. browserTypes[browserTypeKey] = userAgentsEntries[thisUA];
  513. }else{
  514. browserTypes[browserTypeKey] = b + userAgentsEntries[thisUA];
  515. }
  516. });
  517. //Create the device chart
  518. let deviceTypeChart = new Chart(document.getElementById("stats_device"), {
  519. type: 'pie',
  520. data: {
  521. labels: ['Desktop', 'Mobile'],
  522. datasets: [{
  523. data: [desktopUser, mobileUser],
  524. backgroundColor: ['#e56b5e', '#6eb9c1'],
  525. hoverBackgroundColor: ['#e56b5e', '#6eb9c1']
  526. }]
  527. },
  528. options: {
  529. responsive: true,
  530. maintainAspectRatio: false,
  531. }
  532. });
  533. statisticCharts.push(deviceTypeChart);
  534. //Create the OS chart
  535. let OSnames = [];
  536. let OSCounts = [];
  537. let OSColors = [];
  538. for (const [key, value] of Object.entries(osTypes)) {
  539. OSnames.push(key);
  540. OSCounts.push(value);
  541. OSColors.push(getOSColorCode(key));
  542. }
  543. let osTypeChart = new Chart(document.getElementById("stats_OS"), {
  544. type: 'pie',
  545. data: {
  546. labels: OSnames,
  547. datasets: [{
  548. data: OSCounts,
  549. backgroundColor: OSColors,
  550. hoverBackgroundColor: OSColors
  551. }]
  552. },
  553. options: {
  554. responsive: true,
  555. maintainAspectRatio: false,
  556. }
  557. });
  558. statisticCharts.push(osTypeChart);
  559. //Populate the OS version table
  560. let sortedOSVersion = Object.entries(osVersion).sort((a, b) => b[1] - a[1]);
  561. $("#stats_OSVersionList").html("");
  562. // Loop through the sorted data and populate the table
  563. for (let i = 0; i < sortedOSVersion.length; i++) {
  564. let osVersion = sortedOSVersion[i][0];
  565. let requestcount = abbreviateNumber(sortedOSVersion[i][1]);
  566. let percentage = (sortedOSVersion[i][1] / totalRequestCounts * 100).toFixed(3);
  567. // Create a new row in the table
  568. let row = $("<tr>");
  569. // Add the OS version and percentage as columns in the row
  570. $("<td>").text(osVersion).appendTo(row);
  571. $("<td>").text(requestcount).appendTo(row);
  572. $("<td>").text(percentage + "%").appendTo(row);
  573. // Add the row to the table body
  574. $("#stats_OSVersionList").append(row);
  575. }
  576. //Create the browser charts
  577. let browserNames = [];
  578. let broserCounts = [];
  579. let browserColors = [];
  580. let sortedBrowserTypes = Object.entries(browserTypes).sort((a, b) => b[1] - a[1]);
  581. console.log(sortedBrowserTypes);
  582. sortedBrowserTypes.forEach(function(entry){
  583. browserNames.push(entry[0]);
  584. broserCounts.push(entry[1]);
  585. browserColors.push(generateColorFromHash(entry[0]));
  586. });
  587. let browserTypeChart = new Chart(document.getElementById("stats_browsers"), {
  588. type: 'pie',
  589. data: {
  590. labels: browserNames,
  591. datasets: [{
  592. data: broserCounts,
  593. backgroundColor: browserColors,
  594. hoverBackgroundColor: browserColors
  595. }]
  596. },
  597. options: {
  598. responsive: true,
  599. maintainAspectRatio: false,
  600. }
  601. });
  602. statisticCharts.push(browserTypeChart);
  603. }
  604. //Generate the IPversion pie chart
  605. function renderIPVersionChart(RequestClientIp){
  606. let ipv4Count = Object.keys(RequestClientIp).filter(ip => ip.includes('.')).length;
  607. let ipv6Count = Object.keys(RequestClientIp).filter(ip => ip.includes(':')).length;
  608. let totalCount = ipv4Count + ipv6Count;
  609. let ipv4Percent = ((ipv4Count / totalCount) * 100).toFixed(2);
  610. let ipv6Percent = ((ipv6Count / totalCount) * 100).toFixed(2);
  611. // Create the chart data object
  612. let chartData = {
  613. labels: ['IPv4', 'IPv6'],
  614. datasets: [{
  615. data: [ipv4Percent, ipv6Percent],
  616. backgroundColor: ['#9295f0', '#bff092'],
  617. hoverBackgroundColor: ['#9295f0', '#bff092']
  618. }]
  619. };
  620. // Create the chart options object
  621. let ipvChartOption = {
  622. responsive: true,
  623. maintainAspectRatio: false,
  624. };
  625. // Create the pie chart
  626. let ipTypeChart = new Chart(document.getElementById("stats_ipver"), {
  627. type: 'pie',
  628. data: chartData,
  629. options: ipvChartOption
  630. });
  631. statisticCharts.push(ipTypeChart);
  632. //Populate the request count table
  633. let requestCounts = Object.entries(RequestClientIp);
  634. // Sort the array by the value (count)
  635. requestCounts.sort((a, b) => b[1] - a[1]);
  636. // Select the table body and empty it
  637. let tableBody = $('#stats_requestCountlist');
  638. tableBody.empty();
  639. // Loop through the sorted array and add the top 25 requested IPs to the table
  640. for (let i = 0; i < 25 && i < requestCounts.length; i++) {
  641. let [ip, count] = requestCounts[i];
  642. let row = $('<tr>').appendTo(tableBody);
  643. $('<td style="word-break: break-all;">').text(ip).appendTo(row);
  644. $('<td>').text(count).appendTo(row);
  645. }
  646. }
  647. //Generate a fixed color code from string hash
  648. function generateColorFromHash(stringToHash){
  649. let hash = 0;
  650. for (let i = 0; i < stringToHash.length; i++) {
  651. hash = stringToHash.charCodeAt(i) + ((hash << 5) - hash);
  652. }
  653. const hue = hash % 300;
  654. const saturation = Math.floor(Math.random() * 20) + 70;
  655. const lightness = Math.floor(Math.random() * 20) + 60;
  656. return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
  657. }
  658. //Generate the visitor country pie chart
  659. function renderVisitorChart(visitorData){
  660. // Extract the labels and data from the visitor data object
  661. let labels = [];
  662. let data = Object.values(visitorData);
  663. Object.keys(visitorData).forEach(function(cc){
  664. if (cc == ""){
  665. labels.push("Local / Unknown")
  666. }else{
  667. labels.push(`${getCountryName(cc)} [${cc.toUpperCase()}]` );
  668. }
  669. });
  670. // Define the colors to be used in the pie chart
  671. let colors = [];
  672. labels.forEach(function(cc){
  673. colors.push(generateColorFromHash(cc));
  674. });
  675. // Create the chart data object
  676. let CCchartData = {
  677. labels: labels,
  678. datasets: [{
  679. data: data,
  680. backgroundColor: colors
  681. }]
  682. };
  683. // Create the chart options object
  684. let CCchartOptions = {
  685. responsive: true,
  686. maintainAspectRatio: false,
  687. };
  688. // Create the pie chart
  689. const visitorsChart = new Chart(document.getElementById("stats_visitors"), {
  690. type: 'pie',
  691. data: CCchartData,
  692. options: CCchartOptions
  693. });
  694. statisticCharts.push(visitorsChart);
  695. }
  696. </script>