Keeping track of maximum connected listeners on Icecast2 with node.js

I wrote a small node.js reverse proxy for icecast2 , which keeps track of maximum connected listeners.

Step1:
Make sure you have node.js installed on your machine

Step 2:
Install all the extra modules needed for the proxy
user:~$ npm install http-proxy
user:~$ npm install moment

Step 3:
Save the following code to a file (icecast_proxy.js) and change the following values:
ICECAST_HOST
ICECAST_PORT
PROXY_PORT

var httpProxy = require('http-proxy');
var fs = require('fs');
var moment = require('moment');

var count = 0;
var maxcount = 0;
var exists = fs.existsSync("icecast_stats.json");
if (exists) {
    data = fs.readFileSync("icecast_stats.json", 'utf8');
    var datafromfile = JSON.parse(data);
    maxcount = datafromfile.listeners;
} else {
    var filedata = {
        listeners: 0,
        date: moment().format('LLLL')
    }
    fs.writeFileSync("icecast_stats.json", JSON.stringify(filedata));
}
var server = httpProxy.createServer(function (req, res, proxy) {
    proxy.proxyRequest(req, res, {
        host: 'ICECAST_HOST',
        port: ICECAST_PORT,
    });
}).listen(PROXY_PORT);

server.proxy.on('proxyError', function (err, req, res) {
    count = 0;
    res.end();
});

server.proxy.on("start", function () {
    count += 1;
    if (count > maxcount) {
        maxcount = count;
        var filedata = {
            listeners: count,
            date: moment().format('LLLL')
        }
        fs.writeFile("icecast_stats.json", JSON.stringify(filedata), function (err) {
            if (err) {
                console.log(err);
            }
        });
    }
    console.log(count);
});

server.proxy.on("end", function () {
    count -= 1;
    console.log(count);
});

 

Step 4:
Run the file with node.js
user:~$ node icecast_proxy.js

EXAMPLE
Lets say we have an icecast server, with host: host1.example.com , port 8000 and mount point live.mp3
From here, we have to choose whether we want to run this proxy on the same server, or on a seperate one. If we choose to run it on the same server, he have to define a second port for our proxy to run on, other than 8000. Our proxy’s host will also be host1.example.com. If we choose to run it on a seperate server with with host: host2.example.com, we can still use port 8000 for the proxy. I’ll just go with the first example, where we run it from the same machine.
We set:

ICECAST_HOST -> host1.example.com
ICECAST_PORT -> 8000
PROXY_PORT -> 8001

and run it. Now our listeners can connect to http://host1.example.com:8001/live.mp3
The maximum listeners number is saved to a file called icecast_stats.json which is on the same path with our proxy script.

icecast_stat.json can be accessed with any text editor.

 

Share on FacebookTweet about this on TwitterShare on Google+Share on StumbleUponShare on RedditShare on TumblrShare on LinkedInEmail this to someone