stats.html 22 KB

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