Skip to content

Instantly share code, notes, and snippets.

@ForbesLindesay
Created May 21, 2013 05:20
Show Gist options
  • Select an option

  • Save ForbesLindesay/5617622 to your computer and use it in GitHub Desktop.

Select an option

Save ForbesLindesay/5617622 to your computer and use it in GitHub Desktop.
This script monitors my internet usage and prints out the results to the console every time it changes. You can get a session token by going to check your usage in the browser and looking for `?session=<SESSION TOKEN>` in the address bar
var Q = require('q')
var sprom = require('sprom')
var hyperquest = require('hyperquest')
var format = require('format-number')({truncate: 2})
var session = '<Session Token>'
//Limits in MB
var dailyLimit = 5000
var weeklyLimit = 15000
function request(period) {
return Q.promise(function (resolve, reject) {
hyperquest('https://register.robinson.cam.ac.uk/stats.html?session=' + session + '&period=' + period,
function (err, res) {
if (err) reject(err)
else if (res.statusCode >= 400) reject(new Error('Server responded with status code ' + res.statusCode))
else resolve(sprom(res))
})
})
.then(function (body) {
body = body.toString()
body = body.split(/<h4>/i)
.slice(1)
.map(function (computer) {
computer = computer.split(/<\/h4>/i)
return {
name: computer[0].trim(),
table: parseTable(computer[1])
}
})
return body
})
}
function parseTable(str) {
return str.split(/<tr[^>]*>/i)
.slice(1)
.map(function (row) {
return row.split(/<t(?:d|h)[^>]*>/i)
.slice(1)
.map(function (cell) {
return cell.split(/<\/t(?:d|h)>/i)[0].trim()
})
})
}
function extractValues(computers) {
var tables = computers.map(function (c) { return c.table })
return tables.map(function (t) { return Number(t[1][3].replace(/\,/g, '')) })
}
function get(period) {
return request(period)
.then(extractValues)
.then(function (values) {
return values.reduce(function (a, b) { return a > b ? a : b })
})
}
var last = [0,0]
function update() {
return Q.all([get('daily'), get('weekly')])
.spread(function (daily, weekly) {
if (daily != last[0] || weekly != last[1]) {
last = [daily, weekly]
console.log()
console.log('Daily: ' + format(daily) + '/' + format(dailyLimit) + ' => ' + format(daily/5000 * 100) + '%')
console.log('Weekly: ' + format(weekly) + '/' + format(weeklyLimit) + ' => ' + format(weekly/15000 * 100) + '%')
}
})
.then(null, function (err) {
console.error(err.stack)
})
}
function run() {
update()
.fin(function () {
Q.delay(20000).done(run)
})
.done()
}
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment