stats.html 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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>
  156. <!-- <button class="ui icon right floated basic button" onclick="initStatisticSummery();"><i class="green refresh icon"></i> Refresh</button> -->
  157. <br><br>
  158. </div>
  159. <script>
  160. var statisticCharts = [];
  161. //Start day must be earlier than end date
  162. function initStatisticSummery(startdate="", enddate=""){
  163. if (startdate == "" && enddate == "" ){
  164. let todaykey = getTodayStatisticKey();
  165. loadStatisticByDate(todaykey);
  166. }else if ((startdate != "" && enddate == "") || startdate == enddate){
  167. //Load the target date
  168. let targetDate = startdate.trim();
  169. loadStatisticByDate(targetDate);
  170. }else{
  171. //Two dates are given and they are not identical
  172. loadStatisticByRange(startdate, enddate);
  173. console.log(startdate, enddate);
  174. }
  175. }
  176. function loadStatisticByDate(dateid){
  177. $.getJSON("/api/analytic/load?id=" + dateid, function(data){
  178. //Destroy all the previous charts
  179. statisticCharts.forEach(function(thisChart){
  180. thisChart.destroy();
  181. })
  182. if (data.TotalRequest == 0){
  183. //No data to analysis
  184. $("#statisticRenderElement").hide()
  185. $("#statisticRenderNotEnoughData").show();
  186. return;
  187. }else{
  188. $("#statisticRenderElement").show();
  189. $("#statisticRenderNotEnoughData").hide();
  190. }
  191. //Render the text values
  192. $("#statisticRenderElement").find(".totalViewCount").text(abbreviateNumber(data.TotalRequest));
  193. $("#statisticRenderElement").find(".totalSuccCount").text(abbreviateNumber(data.ValidRequest));
  194. $("#statisticRenderElement").find(".totalErrorCount").text(abbreviateNumber(data.ErrorRequest));
  195. //Render forward type data
  196. renderForwardTypeCounts(data.ForwardTypes);
  197. //Render visitor data
  198. renderVisitorChart(data.RequestOrigin);
  199. //Render IP versions
  200. renderIPVersionChart(data.RequestClientIp);
  201. //Render user agent analysis
  202. renderUserAgentCharts(data.UserAgent);
  203. });
  204. }
  205. initStatisticSummery();
  206. $("#statsRangeStart").val(getTodayStatisticKey().split("_").join("-"));
  207. function loadStatisticByRange(startdate, endDate){
  208. $.getJSON("/api/analytic/loadRange?start=" + startdate + "&end=" + endDate, function(data){
  209. console.log(data);
  210. //Destroy all the previous charts
  211. statisticCharts.forEach(function(thisChart){
  212. thisChart.destroy();
  213. })
  214. if (data.Summary.TotalRequest == 0){
  215. //No data to analysis
  216. $("#statisticRenderElement").hide()
  217. $("#statisticRenderNotEnoughData").show();
  218. return;
  219. }else{
  220. $("#statisticRenderElement").show();
  221. $("#statisticRenderNotEnoughData").hide();
  222. }
  223. //Render the text values
  224. $("#statisticRenderElement").find(".totalViewCount").text(abbreviateNumber(data.Summary.TotalRequest));
  225. $("#statisticRenderElement").find(".totalSuccCount").text(abbreviateNumber(data.Summary.ValidRequest));
  226. $("#statisticRenderElement").find(".totalErrorCount").text(abbreviateNumber(data.Summary.ErrorRequest));
  227. //Render forward type data
  228. renderForwardTypeCounts(data.Summary.ForwardTypes);
  229. //Render visitor data
  230. renderVisitorChart(data.Summary.RequestOrigin);
  231. //Render IP versions
  232. renderIPVersionChart(data.Summary.RequestClientIp);
  233. //Render user agent analysis
  234. renderUserAgentCharts(data.Summary.UserAgent);
  235. });
  236. }
  237. picker.attach({ target: document.getElementById("statsRangeStart") });
  238. picker.attach({ target: document.getElementById("statsRangeEnd") });
  239. function renderForwardTypeCounts(forwardTypes){
  240. let tablBody = $("#statisticRenderElement").find(".forwardTypeCounts");
  241. tablBody.empty();
  242. let totalForwardCounts = 0;
  243. for (let [key, value] of Object.entries(forwardTypes)) {
  244. totalForwardCounts += value;
  245. }
  246. for (let [key, value] of Object.entries(forwardTypes)) {
  247. tablBody.append(`<tr>
  248. <td>${key}</td>
  249. <td>${abbreviateNumber(value)} (${value})</td>
  250. <td>${((value/totalForwardCounts)*100).toFixed(3)}%</td>
  251. </tr>
  252. `);
  253. }
  254. }
  255. function getTodayStatisticKey(){
  256. var today = new Date();
  257. var year = today.getFullYear();
  258. var month = String(today.getMonth() + 1).padStart(2, '0');
  259. var day = String(today.getDate()).padStart(2, '0');
  260. var formattedDate = year + '_' + month + '_' + day;
  261. return formattedDate
  262. }
  263. function handleLoadStatisticButtonPress(){
  264. var sd = $("#statsRangeStart").val();
  265. var ed = $("#statsRangeEnd").val();
  266. //Swap them if sd is later than ed
  267. if (sd != "" && ed != "" && sd > ed) {
  268. ed = [sd, sd = ed][0];
  269. $("#statsRangeStart").val(sd);
  270. $("#statsRangeEnd").val(ed);
  271. }
  272. initStatisticSummery(sd, ed);
  273. }
  274. function clearStatisticDateRange(){
  275. $("#statsRangeStart").val("");
  276. $("#statsRangeEnd").val("");
  277. }
  278. function renderUserAgentCharts(userAgentsEntries){
  279. let userAgents = Object.keys(userAgentsEntries);
  280. let requestCounts = Object.values(userAgentsEntries);
  281. let mobileUser = 0;
  282. let desktopUser = 0;
  283. let osTypes = {};
  284. let osVersion = {};
  285. let browserTypes = {};
  286. let totalRequestCounts = 0;
  287. requestCounts.forEach(function(rc){
  288. totalRequestCounts += rc;
  289. })
  290. //Building a statistic summary
  291. userAgents.forEach(function(thisUA){
  292. var uaInfo = parseUserAgent(thisUA);
  293. if (uaInfo.isMobile){
  294. mobileUser+=userAgentsEntries[thisUA];
  295. }else{
  296. desktopUser+=userAgentsEntries[thisUA];
  297. }
  298. let currentNo = osTypes[uaInfo.os];
  299. let osVersionKey = uaInfo.os + " " + uaInfo.version.split("_").join(".");
  300. if (currentNo == undefined){
  301. osTypes[uaInfo.os] = userAgentsEntries[thisUA];
  302. }else{
  303. osTypes[uaInfo.os] = currentNo + userAgentsEntries[thisUA];
  304. }
  305. let p = osVersion[osVersionKey];
  306. if (p == undefined){
  307. osVersion[osVersionKey] = userAgentsEntries[thisUA];
  308. }else{
  309. osVersion[osVersionKey] = p + userAgentsEntries[thisUA];
  310. }
  311. let browserTypeKey = uaInfo.browser;
  312. if (browserTypeKey.indexOf("//") >= 0){
  313. //This is a uncatergorize browser, mostly a bot
  314. browserTypeKey = "Bots";
  315. }else if (browserTypeKey == ""){
  316. //No information
  317. browserTypeKey = "Unknown";
  318. }
  319. let b = browserTypes[browserTypeKey];
  320. if (b == undefined){
  321. browserTypes[browserTypeKey] = userAgentsEntries[thisUA];
  322. }else{
  323. browserTypes[browserTypeKey] = b + userAgentsEntries[thisUA];
  324. }
  325. });
  326. //Create the device chart
  327. let deviceTypeChart = new Chart(document.getElementById("stats_device"), {
  328. type: 'pie',
  329. data: {
  330. labels: ['Desktop', 'Mobile'],
  331. datasets: [{
  332. data: [desktopUser, mobileUser],
  333. backgroundColor: ['#e56b5e', '#6eb9c1'],
  334. hoverBackgroundColor: ['#e56b5e', '#6eb9c1']
  335. }]
  336. },
  337. options: {
  338. responsive: true,
  339. maintainAspectRatio: false,
  340. }
  341. });
  342. statisticCharts.push(deviceTypeChart);
  343. //Create the OS chart
  344. let OSnames = [];
  345. let OSCounts = [];
  346. let OSColors = [];
  347. for (const [key, value] of Object.entries(osTypes)) {
  348. OSnames.push(key);
  349. OSCounts.push(value);
  350. OSColors.push(getOSColorCode(key));
  351. }
  352. let osTypeChart = new Chart(document.getElementById("stats_OS"), {
  353. type: 'pie',
  354. data: {
  355. labels: OSnames,
  356. datasets: [{
  357. data: OSCounts,
  358. backgroundColor: OSColors,
  359. hoverBackgroundColor: OSColors
  360. }]
  361. },
  362. options: {
  363. responsive: true,
  364. maintainAspectRatio: false,
  365. }
  366. });
  367. statisticCharts.push(osTypeChart);
  368. //Populate the OS version table
  369. let sortedOSVersion = Object.entries(osVersion).sort((a, b) => b[1] - a[1]);
  370. $("#stats_OSVersionList").html("");
  371. // Loop through the sorted data and populate the table
  372. for (let i = 0; i < sortedOSVersion.length; i++) {
  373. let osVersion = sortedOSVersion[i][0];
  374. let requestcount = abbreviateNumber(sortedOSVersion[i][1]);
  375. let percentage = (sortedOSVersion[i][1] / totalRequestCounts * 100).toFixed(3);
  376. // Create a new row in the table
  377. let row = $("<tr>");
  378. // Add the OS version and percentage as columns in the row
  379. $("<td>").text(osVersion).appendTo(row);
  380. $("<td>").text(requestcount).appendTo(row);
  381. $("<td>").text(percentage + "%").appendTo(row);
  382. // Add the row to the table body
  383. $("#stats_OSVersionList").append(row);
  384. }
  385. //Create the browser charts
  386. let browserNames = [];
  387. let broserCounts = [];
  388. let browserColors = [];
  389. let sortedBrowserTypes = Object.entries(browserTypes).sort((a, b) => b[1] - a[1]);
  390. console.log(sortedBrowserTypes);
  391. sortedBrowserTypes.forEach(function(entry){
  392. browserNames.push(entry[0]);
  393. broserCounts.push(entry[1]);
  394. browserColors.push(generateColorFromHash(entry[0]));
  395. });
  396. let browserTypeChart = new Chart(document.getElementById("stats_browsers"), {
  397. type: 'pie',
  398. data: {
  399. labels: browserNames,
  400. datasets: [{
  401. data: broserCounts,
  402. backgroundColor: browserColors,
  403. hoverBackgroundColor: browserColors
  404. }]
  405. },
  406. options: {
  407. responsive: true,
  408. maintainAspectRatio: false,
  409. }
  410. });
  411. statisticCharts.push(browserTypeChart);
  412. }
  413. //Generate the IPversion pie chart
  414. function renderIPVersionChart(RequestClientIp){
  415. let ipv4Count = Object.keys(RequestClientIp).filter(ip => ip.includes('.')).length;
  416. let ipv6Count = Object.keys(RequestClientIp).filter(ip => ip.includes(':')).length;
  417. let totalCount = ipv4Count + ipv6Count;
  418. let ipv4Percent = ((ipv4Count / totalCount) * 100).toFixed(2);
  419. let ipv6Percent = ((ipv6Count / totalCount) * 100).toFixed(2);
  420. // Create the chart data object
  421. let chartData = {
  422. labels: ['IPv4', 'IPv6'],
  423. datasets: [{
  424. data: [ipv4Percent, ipv6Percent],
  425. backgroundColor: ['#9295f0', '#bff092'],
  426. hoverBackgroundColor: ['#9295f0', '#bff092']
  427. }]
  428. };
  429. // Create the chart options object
  430. let ipvChartOption = {
  431. responsive: true,
  432. maintainAspectRatio: false,
  433. };
  434. // Create the pie chart
  435. let ipTypeChart = new Chart(document.getElementById("stats_ipver"), {
  436. type: 'pie',
  437. data: chartData,
  438. options: ipvChartOption
  439. });
  440. statisticCharts.push(ipTypeChart);
  441. //Populate the request count table
  442. let requestCounts = Object.entries(RequestClientIp);
  443. // Sort the array by the value (count)
  444. requestCounts.sort((a, b) => b[1] - a[1]);
  445. // Select the table body and empty it
  446. let tableBody = $('#stats_requestCountlist');
  447. tableBody.empty();
  448. // Loop through the sorted array and add the top 25 requested IPs to the table
  449. for (let i = 0; i < 25 && i < requestCounts.length; i++) {
  450. let [ip, count] = requestCounts[i];
  451. let row = $('<tr>').appendTo(tableBody);
  452. $('<td style="word-break: break-all;">').text(ip).appendTo(row);
  453. $('<td>').text(count).appendTo(row);
  454. }
  455. }
  456. //Generate a fixed color code from string hash
  457. function generateColorFromHash(stringToHash){
  458. let hash = 0;
  459. for (let i = 0; i < stringToHash.length; i++) {
  460. hash = stringToHash.charCodeAt(i) + ((hash << 5) - hash);
  461. }
  462. const hue = hash % 300;
  463. const saturation = Math.floor(Math.random() * 20) + 70;
  464. const lightness = Math.floor(Math.random() * 20) + 60;
  465. return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
  466. }
  467. //Generate the visitor country pie chart
  468. function renderVisitorChart(visitorData){
  469. // Extract the labels and data from the visitor data object
  470. let labels = [];
  471. let data = Object.values(visitorData);
  472. Object.keys(visitorData).forEach(function(cc){
  473. if (cc == ""){
  474. labels.push("Local / Unknown")
  475. }else{
  476. labels.push(`${getCountryName(cc)} [${cc.toUpperCase()}]` );
  477. }
  478. });
  479. // Define the colors to be used in the pie chart
  480. let colors = [];
  481. labels.forEach(function(cc){
  482. colors.push(generateColorFromHash(cc));
  483. });
  484. // Create the chart data object
  485. let CCchartData = {
  486. labels: labels,
  487. datasets: [{
  488. data: data,
  489. backgroundColor: colors
  490. }]
  491. };
  492. // Create the chart options object
  493. let CCchartOptions = {
  494. responsive: true,
  495. maintainAspectRatio: false,
  496. };
  497. // Create the pie chart
  498. const visitorsChart = new Chart(document.getElementById("stats_visitors"), {
  499. type: 'pie',
  500. data: CCchartData,
  501. options: CCchartOptions
  502. });
  503. statisticCharts.push(visitorsChart);
  504. }
  505. </script>