const WebSocket = require('ws');
const URL = 'wss://myktis.com/socket.io/?EIO=3&transport=websocket';
// given the data-array response/message from KTIS, parse out the current song and return it.
const parseSongPayload = (dataArray) => {
if (!Array.isArray(dataArray)) {
throw Error("The dataArray isn't an array.");
}
const pastSongsArray = dataArray.filter(entry => entry.hasOwnProperty('past'));
if (pastSongsArray.length === 0) {
throw Error("The array of past songs is empty.");
}
const pastArrayInArray = JSON.parse(pastSongsArray[0].past);
if (!Array.isArray(pastArrayInArray)) {
throw Error("Past/previous song entry isn't an array");
}
return pastArrayInArray[0];
};
// I dunno what the "2" means, but the site replies with the current song info.
const askForCurrentSong = () => {
ws.send('2');
};
exports.endpoint = function(request, response) {
const ws = new WebSocket(URL);
ws.on('open', function open() {
ws.send('42["blog","2"]');
});
ws.on('message', function incoming(data) {
if (data.startsWith('42[')) {
try {
const songInfo = parseSongPayload(JSON.parse(data.substring(2)));
response.end(JSON.stringify(songInfo));
} catch (e) {
response.end("ERROR: " + e.message);
}
} else {
// response.end("WTF? " + JSON.stringify(data));
}
});
}