Last active
December 28, 2015 02:49
-
-
Save lotas/7430753 to your computer and use it in GitHub Desktop.
Fetch & parse radio song details, save in mongodb database To generate some stats and remember which song played a while ago ;)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'), | |
xml2js = require('xml2js'), | |
MongoClient = require('mongodb').MongoClient; | |
var reqOptions = { | |
host: "streamdb4web.securenetsystems.net", | |
port: 80, | |
path: "/player_status_update/KMYZ.xml?randStr=", | |
method: "GET" | |
}; | |
MongoClient.connect('mongodb://127.0.0.1/radio', function(err, db){ | |
if (err) { | |
throw err; | |
} | |
var collection = db.collection('songs'); | |
var lastSong = '', lastArtist = ''; | |
var fetchPlaylist = function() { | |
fetchUrl(function(data) { | |
// check for change | |
if (lastSong != data.title || lastArtist != data.artist) { | |
data.dt = new Date(); | |
collection.insert(data, function(err, docs){ | |
if (err) throw err; | |
}); | |
lastSong = data.title; | |
lastArtist = data.artist; | |
console.log("Now playing: " + lastArtist + " - " + lastSong); | |
} | |
setTimeout(fetchPlaylist, 25000); | |
}); | |
}; | |
fetchPlaylist(); | |
}); | |
function fetchUrl(callback) { | |
var req = http.request(reqOptions, function(res){ | |
if (200 != res.statusCode) { | |
console.error("Server returned status: " + res.statusCode); | |
console.log('HEADERS: ' + JSON.stringify(res.headers)); | |
return false; | |
} | |
res.setEncoding('utf8'); | |
res.on('data', function (chunk) { | |
xml2js.parseString(chunk, function(err, result) { | |
if (err) { | |
console.warn(err); | |
return false; | |
} | |
var obj = result.playlist; | |
for (var k in obj) { | |
if (obj[k].length == 1) { | |
obj[k] = obj[k].pop(); | |
} | |
}; | |
callback(obj); | |
}); | |
}); | |
}); | |
req.on('error', function(e){ | |
console.warn('Error fetching: ' + e.message); | |
}); | |
req.end(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"name": "radio-updates", | |
"version": "0.0.1", | |
"author": "Yaraslau Kurmyza <lotask@gmail.com>", | |
"dependencies": { | |
"mongodb": "*", | |
"xml2js": "*" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment