Skip to content

Instantly share code, notes, and snippets.

@c0d3r111
Last active July 11, 2020 07:41
Show Gist options
  • Save c0d3r111/96baee9ba1692b601bfb61187684af1e to your computer and use it in GitHub Desktop.
Save c0d3r111/96baee9ba1692b601bfb61187684af1e to your computer and use it in GitHub Desktop.
For BLW espressox
window.addEventListener('load', function() {
fetch('/hit-counter')
.then(response => response.text())
.then(response => {
window.TOTAL_HITS = repsonse << 0;
})
.catch(() => {
window.TOTAL_HITS = 0;
});
});
/*
if (window.TOTAL_HITS) {
// do something
}
*/
"use strict";
const fs = require('fs').promises;
const metrohash = require('metrohash').metrohash64;
class Counter {
constructor (divisor) {
this.datapath = __dirname + '/counter.data';
this.divisor = divisor << 0 || 10;
this.tracker = {
look(fingerprint) {
if (!(fingerprint in this.collection)) {
this.collection[fingerprint] = 0;
}
return (this.collection[fingerprint] += 1);
},
collection: {},
};
void this.load();
}
exists (location) {
return new Promise(function(resolve) {
void fs
.access(location)
.then(() => resolve(true))
.catch(() => resolve(false));
});
}
hash (string) {
return metrohash(string, 31);
}
hit (ip, useragent) {
if (ip && useragent) {
const fingerprint = this.hash(String(ip) + String(useragent));
if (this.tracker.look(fingerprint) % this.divisor === 0) {
return 1;
}
}
return 0;
}
async dump () {
await this.ensure(this.datapath);
const prints = Object.keys(this.tracker.collection);
const blob = [];
for (const print of prints) {
void blob.push(print + ':' + this.tracker.collection[print]);
}
await fs.writeFile(this.datapath, blob.join('|'));
return;
}
async ensure (location) {
const exists = await this.exists(location);
if (!exists) {
await fs.mkdir(location, {recursive: true});
}
return;
}
async load () {
const hasdata = await this.exists(this.datapath);
if (hasdata) {
const data = await fs.readFile(this.datapath, 'utf8');
const format = data.split('|');
for (const entry of format) {
const [fingerprint, hits] = entry.split(':');
if (fingerprint && hits) {
this.tracker.collection[fingerprint] = hits << 0;
}
}
}
this.loaded = true;
return;
}
}
"use strict";
/*
Reverse proxy nginx desired route to port 8000;
*/
const http = require('http');
const Counter = require('./counter');
const counter = new Counter(10); // divisor;
void http.createServer(function(request, response) {
const ip = request.headers['x-forwarded-for'];
const ua = request.headers['user-agent'];
return void response.end(counter.hit(ip, ua));
}).listen(8000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment