stats.html 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  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. console.log(sortedEntries);
  333. $("#stats_RefererTable").html("");
  334. let endStop = 100;
  335. if (sortedEntries.length < 100){
  336. endStop = sortedEntries.length;
  337. }
  338. for (var i = 0; i < endStop; i++) {
  339. let referer = (decodeURIComponent(sortedEntries[i][0])).replace(/(<([^>]+)>)/ig,"");
  340. if (sortedEntries[i][0] == ""){
  341. //Root
  342. referer = `<span style="color: #b5b5b5;">(<i class="eye slash outline icon"></i> Unknown or Hidden)</span>`;
  343. }
  344. $("#stats_RefererTable").append(`<tr>
  345. <td>${referer}</td>
  346. <td>${sortedEntries[i][1]}</td>
  347. </tr>`);
  348. }
  349. }
  350. function renderFileTypeGraph(requestURLs){
  351. //Create the device chart
  352. let fileExtensions = {};
  353. for (const [url, count] of Object.entries(requestURLs)) {
  354. let filename = url.split("/").pop();
  355. let ext = "";
  356. if (filename == ""){
  357. //Loading from a folder
  358. ext = "Folder path"
  359. }else{
  360. if (filename.includes(".")){
  361. ext = filename.split(".").pop();
  362. }else{
  363. ext = "API call"
  364. }
  365. }
  366. if (fileExtensions[ext] != undefined){
  367. fileExtensions[ext] = fileExtensions[ext] + count;
  368. }else{
  369. //First time this ext show up
  370. fileExtensions[ext] = count;
  371. }
  372. }
  373. //Convert the key-value pairs to array for graph render
  374. let fileTypes = [];
  375. let fileCounts = [];
  376. let colors = [];
  377. for (const [ftype, count] of Object.entries(fileExtensions)) {
  378. fileTypes.push(ftype);
  379. fileCounts.push(count);
  380. colors.push(generateColorFromHash(ftype));
  381. }
  382. let filetypeChart = new Chart(document.getElementById("stats_filetype"), {
  383. type: 'pie',
  384. data: {
  385. labels: fileTypes,
  386. datasets: [{
  387. data: fileCounts,
  388. backgroundColor: colors,
  389. hoverBackgroundColor: colors,
  390. }]
  391. },
  392. options: {
  393. responsive: true,
  394. maintainAspectRatio: false,
  395. }
  396. });
  397. statisticCharts.push(filetypeChart);
  398. }
  399. function renderTrendGraph(dailySummary){
  400. // Get the canvas element
  401. const canvas = document.getElementById('requestTrends');
  402. //Generate the X axis labels
  403. let datesLabel = [];
  404. let succData = [];
  405. let errorData = [];
  406. let totalData = [];
  407. for (var i = 0; i < dailySummary.length; i++){
  408. let thisDayData = dailySummary[i];
  409. datesLabel.push("Day " + i);
  410. succData.push(thisDayData.ValidRequest);
  411. errorData.push(thisDayData.ErrorRequest);
  412. totalData.push(thisDayData.TotalRequest);
  413. }
  414. // Create the chart
  415. let TrendChart = new Chart(canvas, {
  416. type: 'line',
  417. data: {
  418. labels: datesLabel,
  419. datasets: [
  420. {
  421. label: 'All Requests',
  422. data: totalData,
  423. borderColor: '#7d99f7',
  424. backgroundColor: 'rgba(125, 153, 247, 0.4)',
  425. fill: false
  426. },
  427. {
  428. label: 'Success Requests',
  429. data: succData,
  430. borderColor: '#6dad7c',
  431. backgroundColor: "rgba(109, 173, 124, 0.4)",
  432. fill: true
  433. },
  434. {
  435. label: 'Error Requests',
  436. data: errorData,
  437. borderColor: '#de7373',
  438. backgroundColor: "rgba(222, 115, 115, 0.4)",
  439. fill: true
  440. },
  441. ]
  442. },
  443. options: {
  444. responsive: true,
  445. maintainAspectRatio: true,
  446. title: {
  447. display: true,
  448. //text: 'Line Chart Example'
  449. },
  450. scales: {
  451. x: {
  452. display: true,
  453. title: {
  454. display: false,
  455. text: 'Time'
  456. }
  457. },
  458. y: {
  459. display: true,
  460. title: {
  461. display: true,
  462. text: 'Request Counts'
  463. }
  464. }
  465. }
  466. }
  467. });
  468. statisticCharts.push(TrendChart);
  469. }
  470. function renderUserAgentCharts(userAgentsEntries){
  471. let userAgents = Object.keys(userAgentsEntries);
  472. let requestCounts = Object.values(userAgentsEntries);
  473. let mobileUser = 0;
  474. let desktopUser = 0;
  475. let osTypes = {};
  476. let osVersion = {};
  477. let browserTypes = {};
  478. let totalRequestCounts = 0;
  479. requestCounts.forEach(function(rc){
  480. totalRequestCounts += rc;
  481. })
  482. //Building a statistic summary
  483. userAgents.forEach(function(thisUA){
  484. var uaInfo = parseUserAgent(thisUA);
  485. if (uaInfo.isMobile){
  486. mobileUser+=userAgentsEntries[thisUA];
  487. }else{
  488. desktopUser+=userAgentsEntries[thisUA];
  489. }
  490. let currentNo = osTypes[uaInfo.os];
  491. let osVersionKey = uaInfo.os + " " + uaInfo.version.split("_").join(".");
  492. if (currentNo == undefined){
  493. osTypes[uaInfo.os] = userAgentsEntries[thisUA];
  494. }else{
  495. osTypes[uaInfo.os] = currentNo + userAgentsEntries[thisUA];
  496. }
  497. let p = osVersion[osVersionKey];
  498. if (p == undefined){
  499. osVersion[osVersionKey] = userAgentsEntries[thisUA];
  500. }else{
  501. osVersion[osVersionKey] = p + userAgentsEntries[thisUA];
  502. }
  503. let browserTypeKey = uaInfo.browser;
  504. if (browserTypeKey.indexOf("//") >= 0){
  505. //This is a uncatergorize browser, mostly a bot
  506. browserTypeKey = "Bots";
  507. }else if (browserTypeKey == ""){
  508. //No information
  509. browserTypeKey = "Unknown";
  510. }
  511. let b = browserTypes[browserTypeKey];
  512. if (b == undefined){
  513. browserTypes[browserTypeKey] = userAgentsEntries[thisUA];
  514. }else{
  515. browserTypes[browserTypeKey] = b + userAgentsEntries[thisUA];
  516. }
  517. });
  518. //Create the device chart
  519. let deviceTypeChart = new Chart(document.getElementById("stats_device"), {
  520. type: 'pie',
  521. data: {
  522. labels: ['Desktop', 'Mobile'],
  523. datasets: [{
  524. data: [desktopUser, mobileUser],
  525. backgroundColor: ['#e56b5e', '#6eb9c1'],
  526. hoverBackgroundColor: ['#e56b5e', '#6eb9c1']
  527. }]
  528. },
  529. options: {
  530. responsive: true,
  531. maintainAspectRatio: false,
  532. }
  533. });
  534. statisticCharts.push(deviceTypeChart);
  535. //Create the OS chart
  536. let OSnames = [];
  537. let OSCounts = [];
  538. let OSColors = [];
  539. for (const [key, value] of Object.entries(osTypes)) {
  540. OSnames.push(key);
  541. OSCounts.push(value);
  542. OSColors.push(getOSColorCode(key));
  543. }
  544. let osTypeChart = new Chart(document.getElementById("stats_OS"), {
  545. type: 'pie',
  546. data: {
  547. labels: OSnames,
  548. datasets: [{
  549. data: OSCounts,
  550. backgroundColor: OSColors,
  551. hoverBackgroundColor: OSColors
  552. }]
  553. },
  554. options: {
  555. responsive: true,
  556. maintainAspectRatio: false,
  557. }
  558. });
  559. statisticCharts.push(osTypeChart);
  560. //Populate the OS version table
  561. let sortedOSVersion = Object.entries(osVersion).sort((a, b) => b[1] - a[1]);
  562. $("#stats_OSVersionList").html("");
  563. // Loop through the sorted data and populate the table
  564. for (let i = 0; i < sortedOSVersion.length; i++) {
  565. let osVersion = sortedOSVersion[i][0];
  566. let requestcount = abbreviateNumber(sortedOSVersion[i][1]);
  567. let percentage = (sortedOSVersion[i][1] / totalRequestCounts * 100).toFixed(3);
  568. // Create a new row in the table
  569. let row = $("<tr>");
  570. // Add the OS version and percentage as columns in the row
  571. $("<td>").text(osVersion).appendTo(row);
  572. $("<td>").text(requestcount).appendTo(row);
  573. $("<td>").text(percentage + "%").appendTo(row);
  574. // Add the row to the table body
  575. $("#stats_OSVersionList").append(row);
  576. }
  577. //Create the browser charts
  578. let browserNames = [];
  579. let broserCounts = [];
  580. let browserColors = [];
  581. let sortedBrowserTypes = Object.entries(browserTypes).sort((a, b) => b[1] - a[1]);
  582. console.log(sortedBrowserTypes);
  583. sortedBrowserTypes.forEach(function(entry){
  584. browserNames.push(entry[0]);
  585. broserCounts.push(entry[1]);
  586. browserColors.push(generateColorFromHash(entry[0]));
  587. });
  588. let browserTypeChart = new Chart(document.getElementById("stats_browsers"), {
  589. type: 'pie',
  590. data: {
  591. labels: browserNames,
  592. datasets: [{
  593. data: broserCounts,
  594. backgroundColor: browserColors,
  595. hoverBackgroundColor: browserColors
  596. }]
  597. },
  598. options: {
  599. responsive: true,
  600. maintainAspectRatio: false,
  601. }
  602. });
  603. statisticCharts.push(browserTypeChart);
  604. }
  605. //Generate the IPversion pie chart
  606. function renderIPVersionChart(RequestClientIp){
  607. let ipv4Count = Object.keys(RequestClientIp).filter(ip => ip.includes('.')).length;
  608. let ipv6Count = Object.keys(RequestClientIp).filter(ip => ip.includes(':')).length;
  609. let totalCount = ipv4Count + ipv6Count;
  610. let ipv4Percent = ((ipv4Count / totalCount) * 100).toFixed(2);
  611. let ipv6Percent = ((ipv6Count / totalCount) * 100).toFixed(2);
  612. // Create the chart data object
  613. let chartData = {
  614. labels: ['IPv4', 'IPv6'],
  615. datasets: [{
  616. data: [ipv4Percent, ipv6Percent],
  617. backgroundColor: ['#9295f0', '#bff092'],
  618. hoverBackgroundColor: ['#9295f0', '#bff092']
  619. }]
  620. };
  621. // Create the chart options object
  622. let ipvChartOption = {
  623. responsive: true,
  624. maintainAspectRatio: false,
  625. };
  626. // Create the pie chart
  627. let ipTypeChart = new Chart(document.getElementById("stats_ipver"), {
  628. type: 'pie',
  629. data: chartData,
  630. options: ipvChartOption
  631. });
  632. statisticCharts.push(ipTypeChart);
  633. //Populate the request count table
  634. let requestCounts = Object.entries(RequestClientIp);
  635. // Sort the array by the value (count)
  636. requestCounts.sort((a, b) => b[1] - a[1]);
  637. // Select the table body and empty it
  638. let tableBody = $('#stats_requestCountlist');
  639. tableBody.empty();
  640. // Loop through the sorted array and add the top 25 requested IPs to the table
  641. for (let i = 0; i < 25 && i < requestCounts.length; i++) {
  642. let [ip, count] = requestCounts[i];
  643. let row = $('<tr>').appendTo(tableBody);
  644. $('<td style="word-break: break-all;">').text(ip).appendTo(row);
  645. $('<td>').text(count).appendTo(row);
  646. }
  647. }
  648. //Generate a fixed color code from string hash
  649. function generateColorFromHash(stringToHash){
  650. let hash = 0;
  651. for (let i = 0; i < stringToHash.length; i++) {
  652. hash = stringToHash.charCodeAt(i) + ((hash << 5) - hash);
  653. }
  654. const hue = hash % 300;
  655. const saturation = Math.floor(Math.random() * 20) + 70;
  656. const lightness = Math.floor(Math.random() * 20) + 60;
  657. return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
  658. }
  659. //Generate the visitor country pie chart
  660. function renderVisitorChart(visitorData){
  661. // Extract the labels and data from the visitor data object
  662. let labels = [];
  663. let data = Object.values(visitorData);
  664. Object.keys(visitorData).forEach(function(cc){
  665. if (cc == ""){
  666. labels.push("Local / Unknown")
  667. }else{
  668. labels.push(`${getCountryName(cc)} [${cc.toUpperCase()}]` );
  669. }
  670. });
  671. // Define the colors to be used in the pie chart
  672. let colors = [];
  673. labels.forEach(function(cc){
  674. colors.push(generateColorFromHash(cc));
  675. });
  676. // Create the chart data object
  677. let CCchartData = {
  678. labels: labels,
  679. datasets: [{
  680. data: data,
  681. backgroundColor: colors
  682. }]
  683. };
  684. // Create the chart options object
  685. let CCchartOptions = {
  686. responsive: true,
  687. maintainAspectRatio: false,
  688. };
  689. // Create the pie chart
  690. const visitorsChart = new Chart(document.getElementById("stats_visitors"), {
  691. type: 'pie',
  692. data: CCchartData,
  693. options: CCchartOptions
  694. });
  695. statisticCharts.push(visitorsChart);
  696. }
  697. </script>