-
Notifications
You must be signed in to change notification settings - Fork 2
/
analytic.mjs
1 lines (1 loc) · 1.37 KB
/
analytic.mjs
1
import url from"url";import qs from"querystring";import*as fs from"fs";try{fs.readFileSync("./stats.json")}catch(s){console.log("Installing Analytics API"),fs.writeFileSync("./stats.json",JSON.stringify({users:0,top:0,visits:0,id:[]}))}export default function(s,t){if(!s.url.startsWith("/analytics."))return!0;var i=JSON.parse(fs.readFileSync("./stats.json"));s.query=qs.parse(url.parse(s.url).query);var e=s.query.id;if(s.url.startsWith("/analytics.start")){if(i.id.find(s=>s.id==e))return t.end("Exists");var r=i.id.push({pinged:(new Date).getTime(),id:e})-1;i.visits++,i.users=i.id.length,i.top<i.users&&(i.top=i.users),t.end("Done");var n=setInterval(function(){if(!i.id[r])return clearInterval(n);(new Date).getTime()-i.id[r].pinged>29999&&(i.id.splice(r,1),i.users=i.id.length),fs.writeFileSync("./stats.json",JSON.stringify(i))},3e4)}if(s.url.startsWith("/analytics.ping")){if(!i.id.find(s=>s.id==e))return t.end("Failed");if(!e)return t.end("Failed");i.top<i.users&&(i.top=i.users);var a=i.id.find(s=>s.id==e),d=a;a.pinged=(new Date).getTime(),i.id[i.id.indexOf(d)]=a,t.end("Success")}return s.url.startsWith("/analytics.users")?(i.top<i.users&&(i.top=i.users),t.end(JSON.stringify(i))):s.url.startsWith("/analytics.client.js")?t.end(fs.readFileSync("./client.js")):s.url.startsWith("/analytics.worker.js")?t.end(fs.readFileSync("./worker.js")):fs.writeFileSync("./stats.json",JSON.stringify(i))}