stats.html 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 class="ui small input">
  9. <input type="text" id="statsRangeStart" placeholder="From date">
  10. </div>
  11. To
  12. <div class="ui small input">
  13. <input type="text" id="statsRangeEnd" placeholder="End date">
  14. </div>
  15. <button class="ui basic button"><i class="search icon"></i> Search</button><br>
  16. <small>Leave end range as empty for showing starting day only statistic</small>
  17. </div>
  18. <div class="ui divider"></div>
  19. <div class="ui basic segment">
  20. <!-- Client Geolocation Analysis-->
  21. <h3>Visitors Countries</h3>
  22. <p>Distributions of visitors by country code. Access origin are estimated using open source GeoIP database and might not be accurate.</p>
  23. <div style="min-height: 400px;">
  24. <canvas id="stats_visitors"></canvas>
  25. </div>
  26. <div class="ui divider"></div>
  27. <!-- Client IP Analysis -->
  28. <div class="ui stackable grid">
  29. <div class="eight wide column">
  30. <h3>Requests IP Version</h3>
  31. <p>The version of Internet Protocol that the client is using. If the request client is pass through a DNS proxy like CloudFlare,
  32. the CloudFlare proxy server address will be filtered and only the first value in the RemoteAddress field will be analysised.</p>
  33. <div>
  34. <canvas id="stats_ipver"></canvas>
  35. </div>
  36. </div>
  37. <div class="eight wide column">
  38. <h3>Request Origins</h3>
  39. <p>Top 25 request origin sorted by request count</p>
  40. <div style="height: 500px; overflow-y: auto;">
  41. <table class="ui unstackable striped celled table">
  42. <thead>
  43. <tr>
  44. <th>Request Origin</th>
  45. <th>No of Requests</th>
  46. </tr></thead>
  47. <tbody id="stats_requestCountlist">
  48. </tbody>
  49. </table>
  50. </div>
  51. </div>
  52. </div>
  53. <div class="ui divider"></div>
  54. <!-- Client Device Analysis -->
  55. <div class="ui stackable grid">
  56. <div class="eight wide column">
  57. <h3>Client Devices</h3>
  58. <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>
  59. <div>
  60. <canvas id="stats_device"></canvas>
  61. </div>
  62. </div>
  63. <div class="eight wide column">
  64. <h3>Client Browsers</h3>
  65. <p>The browsers where your client is using to visit your site</p>
  66. <div>
  67. <canvas id="stats_browsers"></canvas>
  68. </div>
  69. </div>
  70. </div>
  71. <div class="ui stackable grid">
  72. <div class="eight wide column">
  73. <h3>Client OS</h3>
  74. <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>
  75. <div>
  76. <canvas id="stats_OS"></canvas>
  77. </div>
  78. </div>
  79. <div class="eight wide column">
  80. <h3>OS Versions</h3>
  81. <p>The OS versions most commonly used by your site's visitors.</p>
  82. <div style="height: 500px; overflow-y: auto;">
  83. <table class="ui unstackable striped celled table">
  84. <thead>
  85. <tr>
  86. <th>OS Version</th>
  87. <th>Request Counts</th>
  88. <th>Percentage</th>
  89. </tr></thead>
  90. <tbody id="stats_OSVersionList">
  91. </tbody>
  92. </table>
  93. </div>
  94. </div>
  95. </div>
  96. </div>
  97. <button class="ui icon right floated basic button" onclick="initStatisticSummery();"><i class="green refresh icon"></i> Refresh</button>
  98. <br><br>
  99. </div>
  100. <script>
  101. function initStatisticSummery(startdate="", enddate=""){
  102. if (startdate == "" && enddate == "" ){
  103. let todaykey = getTodayStatisticKey();
  104. $.getJSON("/api/analytic/load?id=" + todaykey, function(data){
  105. console.log(data, todaykey);
  106. //Render visitor data
  107. renderVisitorChart(data.RequestOrigin);
  108. //Render IP versions
  109. renderIPVersionChart(data.RequestClientIp);
  110. //Render user agent analysis
  111. renderUserAgentCharts(data.UserAgent);
  112. });
  113. }
  114. }
  115. initStatisticSummery();
  116. picker.attach({ target: document.getElementById("statsRangeStart") });
  117. picker.attach({ target: document.getElementById("statsRangeEnd") });
  118. function getTodayStatisticKey(){
  119. var today = new Date();
  120. var year = today.getFullYear();
  121. var month = String(today.getMonth() + 1).padStart(2, '0');
  122. var day = String(today.getDate()).padStart(2, '0');
  123. var formattedDate = year + '_' + month + '_' + day;
  124. return formattedDate
  125. }
  126. function renderUserAgentCharts(userAgentsEntries){
  127. let userAgents = Object.keys(userAgentsEntries);
  128. let requestCounts = Object.values(userAgentsEntries);
  129. let mobileUser = 0;
  130. let desktopUser = 0;
  131. let osTypes = {};
  132. let osVersion = {};
  133. let browserTypes = {};
  134. let totalRequestCounts = 0;
  135. requestCounts.forEach(function(rc){
  136. totalRequestCounts += rc;
  137. })
  138. //Building a statistic summary
  139. userAgents.forEach(function(thisUA){
  140. var uaInfo = parseUserAgent(thisUA);
  141. if (uaInfo.isMobile){
  142. mobileUser+=userAgentsEntries[thisUA];
  143. }else{
  144. desktopUser+=userAgentsEntries[thisUA];
  145. }
  146. let currentNo = osTypes[uaInfo.os];
  147. let osVersionKey = uaInfo.os + " " + uaInfo.version.split("_").join(".");
  148. if (currentNo == undefined){
  149. osTypes[uaInfo.os] = userAgentsEntries[thisUA];
  150. }else{
  151. osTypes[uaInfo.os] = currentNo + userAgentsEntries[thisUA];
  152. }
  153. let p = osVersion[osVersionKey];
  154. if (p == undefined){
  155. osVersion[osVersionKey] = userAgentsEntries[thisUA];
  156. }else{
  157. osVersion[osVersionKey] = p + userAgentsEntries[thisUA];
  158. }
  159. let browserTypeKey = uaInfo.browser;
  160. if (browserTypeKey.indexOf("//") >= 0){
  161. //This is a uncatergorize browser, mostly a bot
  162. browserTypeKey = "Bots";
  163. }else if (browserTypeKey == ""){
  164. //No information
  165. browserTypeKey = "Unknown";
  166. }
  167. let b = browserTypes[browserTypeKey];
  168. if (b == undefined){
  169. browserTypes[browserTypeKey] = userAgentsEntries[thisUA];
  170. }else{
  171. browserTypes[browserTypeKey] = b + userAgentsEntries[thisUA];
  172. }
  173. });
  174. //Create the device chart
  175. let deviceTypeChart = new Chart(document.getElementById("stats_device"), {
  176. type: 'pie',
  177. data: {
  178. labels: ['Desktop', 'Mobile'],
  179. datasets: [{
  180. data: [desktopUser, mobileUser],
  181. backgroundColor: ['#e56b5e', '#6eb9c1'],
  182. hoverBackgroundColor: ['#e56b5e', '#6eb9c1']
  183. }]
  184. },
  185. options: {
  186. responsive: true,
  187. maintainAspectRatio: false,
  188. }
  189. });
  190. //Create the OS chart
  191. let OSnames = [];
  192. let OSCounts = [];
  193. let OSColors = [];
  194. for (const [key, value] of Object.entries(osTypes)) {
  195. OSnames.push(key);
  196. OSCounts.push(value);
  197. OSColors.push(getOSColorCode(key));
  198. }
  199. let osTypeChart = new Chart(document.getElementById("stats_OS"), {
  200. type: 'pie',
  201. data: {
  202. labels: OSnames,
  203. datasets: [{
  204. data: OSCounts,
  205. backgroundColor: OSColors,
  206. hoverBackgroundColor: OSColors
  207. }]
  208. },
  209. options: {
  210. responsive: true,
  211. maintainAspectRatio: false,
  212. }
  213. });
  214. //Populate the OS version table
  215. let sortedOSVersion = Object.entries(osVersion).sort((a, b) => b[1] - a[1]);
  216. // Loop through the sorted data and populate the table
  217. for (let i = 0; i < sortedOSVersion.length; i++) {
  218. let osVersion = sortedOSVersion[i][0];
  219. let requestcount = abbreviateNumber(sortedOSVersion[i][1]);
  220. let percentage = (sortedOSVersion[i][1] / totalRequestCounts * 100).toFixed(3);
  221. // Create a new row in the table
  222. let row = $("<tr>");
  223. // Add the OS version and percentage as columns in the row
  224. $("<td>").text(osVersion).appendTo(row);
  225. $("<td>").text(requestcount).appendTo(row);
  226. $("<td>").text(percentage + "%").appendTo(row);
  227. // Add the row to the table body
  228. $("#stats_OSVersionList").append(row);
  229. }
  230. //Create the browser charts
  231. let browserNames = [];
  232. let broserCounts = [];
  233. let browserColors = [];
  234. let sortedBrowserTypes = Object.entries(browserTypes).sort((a, b) => b[1] - a[1]);
  235. console.log(sortedBrowserTypes);
  236. sortedBrowserTypes.forEach(function(entry){
  237. browserNames.push(entry[0]);
  238. broserCounts.push(entry[1]);
  239. browserColors.push(generateColorFromHash(entry[0]));
  240. });
  241. let browserTypeChart = new Chart(document.getElementById("stats_browsers"), {
  242. type: 'pie',
  243. data: {
  244. labels: browserNames,
  245. datasets: [{
  246. data: broserCounts,
  247. backgroundColor: browserColors,
  248. hoverBackgroundColor: browserColors
  249. }]
  250. },
  251. options: {
  252. responsive: true,
  253. maintainAspectRatio: false,
  254. }
  255. });
  256. console.log(browserTypes);
  257. }
  258. //Generate the IPversion pie chart
  259. function renderIPVersionChart(RequestClientIp){
  260. let ipv4Count = Object.keys(RequestClientIp).filter(ip => ip.includes('.')).length;
  261. let ipv6Count = Object.keys(RequestClientIp).filter(ip => ip.includes(':')).length;
  262. let totalCount = ipv4Count + ipv6Count;
  263. let ipv4Percent = ((ipv4Count / totalCount) * 100).toFixed(2);
  264. let ipv6Percent = ((ipv6Count / totalCount) * 100).toFixed(2);
  265. // Create the chart data object
  266. let chartData = {
  267. labels: ['IPv4', 'IPv6'],
  268. datasets: [{
  269. data: [ipv4Percent, ipv6Percent],
  270. backgroundColor: ['#9295f0', '#bff092'],
  271. hoverBackgroundColor: ['#9295f0', '#bff092']
  272. }]
  273. };
  274. // Create the chart options object
  275. let ipvChartOption = {
  276. responsive: true,
  277. maintainAspectRatio: false,
  278. };
  279. // Create the pie chart
  280. let ipTypeChart = new Chart(document.getElementById("stats_ipver"), {
  281. type: 'pie',
  282. data: chartData,
  283. options: ipvChartOption
  284. });
  285. //Populate the request count table
  286. let requestCounts = Object.entries(RequestClientIp);
  287. // Sort the array by the value (count)
  288. requestCounts.sort((a, b) => b[1] - a[1]);
  289. // Select the table body and empty it
  290. let tableBody = $('#stats_requestCountlist');
  291. tableBody.empty();
  292. // Loop through the sorted array and add the top 25 requested IPs to the table
  293. for (let i = 0; i < 25 && i < requestCounts.length; i++) {
  294. let [ip, count] = requestCounts[i];
  295. let row = $('<tr>').appendTo(tableBody);
  296. $('<td style="word-break: break-all;">').text(ip).appendTo(row);
  297. $('<td>').text(count).appendTo(row);
  298. }
  299. }
  300. //Generate a fixed color code from string hash
  301. function generateColorFromHash(stringToHash){
  302. let hash = 0;
  303. for (let i = 0; i < stringToHash.length; i++) {
  304. hash = stringToHash.charCodeAt(i) + ((hash << 5) - hash);
  305. }
  306. const hue = hash % 300;
  307. const saturation = Math.floor(Math.random() * 20) + 70;
  308. const lightness = Math.floor(Math.random() * 20) + 60;
  309. return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
  310. }
  311. //Generate the visitor country pie chart
  312. function renderVisitorChart(visitorData){
  313. // Extract the labels and data from the visitor data object
  314. let labels = [];
  315. let data = Object.values(visitorData);
  316. Object.keys(visitorData).forEach(function(cc){
  317. if (cc == ""){
  318. labels.push("Local / Unknown")
  319. }else{
  320. labels.push(`${getCountryName(cc)} [${cc.toUpperCase()}]` );
  321. }
  322. });
  323. // Define the colors to be used in the pie chart
  324. let colors = [];
  325. labels.forEach(function(cc){
  326. colors.push(generateColorFromHash(cc));
  327. });
  328. // Create the chart data object
  329. let CCchartData = {
  330. labels: labels,
  331. datasets: [{
  332. data: data,
  333. backgroundColor: colors
  334. }]
  335. };
  336. // Create the chart options object
  337. let CCchartOptions = {
  338. responsive: true,
  339. maintainAspectRatio: false,
  340. };
  341. // Create the pie chart
  342. const visitorsChart = new Chart(document.getElementById("stats_visitors"), {
  343. type: 'pie',
  344. data: CCchartData,
  345. options: CCchartOptions
  346. });
  347. }
  348. </script>