123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391 |
- <script src="./script/useragent.js"></script>
- <link href="./script/datepicker/dp-light.css" rel="stylesheet">
- <script defer src="./script/datepicker/datepicker.js"></script>
- <div class="standardContainer">
- <div class="ui basic segment">
- <h2>Statistical Analysis</h2>
- <p>Statistic of your server in every aspects</p>
- <div class="ui small input">
- <input type="text" id="statsRangeStart" placeholder="From date">
- </div>
- To
- <div class="ui small input">
- <input type="text" id="statsRangeEnd" placeholder="End date">
- </div>
- <button class="ui basic button"><i class="search icon"></i> Search</button><br>
- <small>Leave end range as empty for showing starting day only statistic</small>
- </div>
- <div class="ui divider"></div>
- <div class="ui basic segment">
- <!-- Client Geolocation Analysis-->
- <h3>Visitors Countries</h3>
- <p>Distributions of visitors by country code. Access origin are estimated using open source GeoIP database and might not be accurate.</p>
- <div style="min-height: 400px;">
- <canvas id="stats_visitors"></canvas>
- </div>
- <div class="ui divider"></div>
- <!-- Client IP Analysis -->
- <div class="ui stackable grid">
- <div class="eight wide column">
- <h3>Requests IP Version</h3>
- <p>The version of Internet Protocol that the client is using. If the request client is pass through a DNS proxy like CloudFlare,
- the CloudFlare proxy server address will be filtered and only the first value in the RemoteAddress field will be analysised.</p>
- <div>
- <canvas id="stats_ipver"></canvas>
- </div>
- </div>
- <div class="eight wide column">
- <h3>Request Origins</h3>
- <p>Top 25 request origin sorted by request count</p>
- <div style="height: 500px; overflow-y: auto;">
- <table class="ui unstackable striped celled table">
- <thead>
- <tr>
- <th>Request Origin</th>
- <th>No of Requests</th>
- </tr></thead>
- <tbody id="stats_requestCountlist">
-
- </tbody>
- </table>
- </div>
- </div>
- </div>
- <div class="ui divider"></div>
- <!-- Client Device Analysis -->
- <div class="ui stackable grid">
- <div class="eight wide column">
- <h3>Client Devices</h3>
- <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>
- <div>
- <canvas id="stats_device"></canvas>
- </div>
- </div>
- <div class="eight wide column">
- <h3>Client Browsers</h3>
- <p>The browsers where your client is using to visit your site</p>
- <div>
- <canvas id="stats_browsers"></canvas>
- </div>
- </div>
- </div>
- <div class="ui stackable grid">
- <div class="eight wide column">
- <h3>Client OS</h3>
- <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>
- <div>
- <canvas id="stats_OS"></canvas>
- </div>
- </div>
- <div class="eight wide column">
- <h3>OS Versions</h3>
- <p>The OS versions most commonly used by your site's visitors.</p>
- <div style="height: 500px; overflow-y: auto;">
- <table class="ui unstackable striped celled table">
- <thead>
- <tr>
- <th>OS Version</th>
- <th>Request Counts</th>
- <th>Percentage</th>
- </tr></thead>
- <tbody id="stats_OSVersionList">
-
- </tbody>
- </table>
- </div>
- </div>
- </div>
- </div>
- <button class="ui icon right floated basic button" onclick="initStatisticSummery();"><i class="green refresh icon"></i> Refresh</button>
- <br><br>
- </div>
- <script>
- function initStatisticSummery(startdate="", enddate=""){
- if (startdate == "" && enddate == "" ){
- let todaykey = getTodayStatisticKey();
- $.getJSON("/api/analytic/load?id=" + todaykey, function(data){
- console.log(data, todaykey);
- //Render visitor data
- renderVisitorChart(data.RequestOrigin);
- //Render IP versions
- renderIPVersionChart(data.RequestClientIp);
- //Render user agent analysis
- renderUserAgentCharts(data.UserAgent);
- });
- }
- }
- initStatisticSummery();
- picker.attach({ target: document.getElementById("statsRangeStart") });
- picker.attach({ target: document.getElementById("statsRangeEnd") });
-
- function getTodayStatisticKey(){
- var today = new Date();
- var year = today.getFullYear();
- var month = String(today.getMonth() + 1).padStart(2, '0');
- var day = String(today.getDate()).padStart(2, '0');
- var formattedDate = year + '_' + month + '_' + day;
- return formattedDate
- }
- function renderUserAgentCharts(userAgentsEntries){
- let userAgents = Object.keys(userAgentsEntries);
- let requestCounts = Object.values(userAgentsEntries);
- let mobileUser = 0;
- let desktopUser = 0;
- let osTypes = {};
- let osVersion = {};
- let browserTypes = {};
- let totalRequestCounts = 0;
-
- requestCounts.forEach(function(rc){
- totalRequestCounts += rc;
- })
- //Building a statistic summary
- userAgents.forEach(function(thisUA){
- var uaInfo = parseUserAgent(thisUA);
- if (uaInfo.isMobile){
- mobileUser+=userAgentsEntries[thisUA];
- }else{
- desktopUser+=userAgentsEntries[thisUA];
- }
- let currentNo = osTypes[uaInfo.os];
- let osVersionKey = uaInfo.os + " " + uaInfo.version.split("_").join(".");
- if (currentNo == undefined){
- osTypes[uaInfo.os] = userAgentsEntries[thisUA];
- }else{
- osTypes[uaInfo.os] = currentNo + userAgentsEntries[thisUA];
- }
- let p = osVersion[osVersionKey];
- if (p == undefined){
- osVersion[osVersionKey] = userAgentsEntries[thisUA];
- }else{
- osVersion[osVersionKey] = p + userAgentsEntries[thisUA];
- }
- let browserTypeKey = uaInfo.browser;
- if (browserTypeKey.indexOf("//") >= 0){
- //This is a uncatergorize browser, mostly a bot
- browserTypeKey = "Bots";
- }else if (browserTypeKey == ""){
- //No information
- browserTypeKey = "Unknown";
- }
- let b = browserTypes[browserTypeKey];
- if (b == undefined){
- browserTypes[browserTypeKey] = userAgentsEntries[thisUA];
- }else{
- browserTypes[browserTypeKey] = b + userAgentsEntries[thisUA];
- }
-
- });
- //Create the device chart
- let deviceTypeChart = new Chart(document.getElementById("stats_device"), {
- type: 'pie',
- data: {
- labels: ['Desktop', 'Mobile'],
- datasets: [{
- data: [desktopUser, mobileUser],
- backgroundColor: ['#e56b5e', '#6eb9c1'],
- hoverBackgroundColor: ['#e56b5e', '#6eb9c1']
- }]
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- }
- });
- //Create the OS chart
- let OSnames = [];
- let OSCounts = [];
- let OSColors = [];
- for (const [key, value] of Object.entries(osTypes)) {
- OSnames.push(key);
- OSCounts.push(value);
- OSColors.push(getOSColorCode(key));
- }
-
- let osTypeChart = new Chart(document.getElementById("stats_OS"), {
- type: 'pie',
- data: {
- labels: OSnames,
- datasets: [{
- data: OSCounts,
- backgroundColor: OSColors,
- hoverBackgroundColor: OSColors
- }]
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- }
- });
- //Populate the OS version table
- let sortedOSVersion = Object.entries(osVersion).sort((a, b) => b[1] - a[1]);
-
- // Loop through the sorted data and populate the table
- for (let i = 0; i < sortedOSVersion.length; i++) {
- let osVersion = sortedOSVersion[i][0];
- let requestcount = abbreviateNumber(sortedOSVersion[i][1]);
- let percentage = (sortedOSVersion[i][1] / totalRequestCounts * 100).toFixed(3);
-
- // Create a new row in the table
- let row = $("<tr>");
-
- // Add the OS version and percentage as columns in the row
- $("<td>").text(osVersion).appendTo(row);
- $("<td>").text(requestcount).appendTo(row);
- $("<td>").text(percentage + "%").appendTo(row);
-
- // Add the row to the table body
- $("#stats_OSVersionList").append(row);
- }
- //Create the browser charts
- let browserNames = [];
- let broserCounts = [];
- let browserColors = [];
- let sortedBrowserTypes = Object.entries(browserTypes).sort((a, b) => b[1] - a[1]);
- console.log(sortedBrowserTypes);
- sortedBrowserTypes.forEach(function(entry){
- browserNames.push(entry[0]);
- broserCounts.push(entry[1]);
- browserColors.push(generateColorFromHash(entry[0]));
- });
-
- let browserTypeChart = new Chart(document.getElementById("stats_browsers"), {
- type: 'pie',
- data: {
- labels: browserNames,
- datasets: [{
- data: broserCounts,
- backgroundColor: browserColors,
- hoverBackgroundColor: browserColors
- }]
- },
- options: {
- responsive: true,
- maintainAspectRatio: false,
- }
- });
- console.log(browserTypes);
- }
- //Generate the IPversion pie chart
- function renderIPVersionChart(RequestClientIp){
- let ipv4Count = Object.keys(RequestClientIp).filter(ip => ip.includes('.')).length;
- let ipv6Count = Object.keys(RequestClientIp).filter(ip => ip.includes(':')).length;
- let totalCount = ipv4Count + ipv6Count;
- let ipv4Percent = ((ipv4Count / totalCount) * 100).toFixed(2);
- let ipv6Percent = ((ipv6Count / totalCount) * 100).toFixed(2);
- // Create the chart data object
- let chartData = {
- labels: ['IPv4', 'IPv6'],
- datasets: [{
- data: [ipv4Percent, ipv6Percent],
- backgroundColor: ['#9295f0', '#bff092'],
- hoverBackgroundColor: ['#9295f0', '#bff092']
- }]
- };
- // Create the chart options object
- let ipvChartOption = {
- responsive: true,
- maintainAspectRatio: false,
- };
- // Create the pie chart
- let ipTypeChart = new Chart(document.getElementById("stats_ipver"), {
- type: 'pie',
- data: chartData,
- options: ipvChartOption
- });
- //Populate the request count table
- let requestCounts = Object.entries(RequestClientIp);
- // Sort the array by the value (count)
- requestCounts.sort((a, b) => b[1] - a[1]);
- // Select the table body and empty it
- let tableBody = $('#stats_requestCountlist');
- tableBody.empty();
- // Loop through the sorted array and add the top 25 requested IPs to the table
- for (let i = 0; i < 25 && i < requestCounts.length; i++) {
- let [ip, count] = requestCounts[i];
- let row = $('<tr>').appendTo(tableBody);
- $('<td style="word-break: break-all;">').text(ip).appendTo(row);
- $('<td>').text(count).appendTo(row);
- }
- }
- //Generate a fixed color code from string hash
- function generateColorFromHash(stringToHash){
- let hash = 0;
- for (let i = 0; i < stringToHash.length; i++) {
- hash = stringToHash.charCodeAt(i) + ((hash << 5) - hash);
- }
- const hue = hash % 300;
- const saturation = Math.floor(Math.random() * 20) + 70;
- const lightness = Math.floor(Math.random() * 20) + 60;
- return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
- }
- //Generate the visitor country pie chart
- function renderVisitorChart(visitorData){
- // Extract the labels and data from the visitor data object
- let labels = [];
- let data = Object.values(visitorData);
- Object.keys(visitorData).forEach(function(cc){
- if (cc == ""){
- labels.push("Local / Unknown")
- }else{
- labels.push(`${getCountryName(cc)} [${cc.toUpperCase()}]` );
- }
- });
- // Define the colors to be used in the pie chart
- let colors = [];
- labels.forEach(function(cc){
- colors.push(generateColorFromHash(cc));
- });
- // Create the chart data object
- let CCchartData = {
- labels: labels,
- datasets: [{
- data: data,
- backgroundColor: colors
- }]
- };
- // Create the chart options object
- let CCchartOptions = {
- responsive: true,
- maintainAspectRatio: false,
- };
- // Create the pie chart
- const visitorsChart = new Chart(document.getElementById("stats_visitors"), {
- type: 'pie',
- data: CCchartData,
- options: CCchartOptions
- });
- }
- </script>
|