rooster.io/schedule.js

68 lines
2.3 KiB
JavaScript
Raw Normal View History

//schedule.js
var http = require('http');
var cheerio = require('cheerio');
var config = require('./configuration');
2015-06-13 22:07:06 +02:00
//Wrapper function that is being called by express.
2015-06-13 22:36:18 +02:00
function schedule(req, res, next) {
get(req.match.url, function (json) {
req.match.json = json;
next();
});
}
2015-06-13 22:07:06 +02:00
//Function for getting the page via http.
function get(url, callback) {
http.get(url, function (res) {
var _download = '';
res.on('data', function (data) {
_download += data;
2015-06-13 22:36:18 +02:00
});
res.on('end', function () {
callback(to_json(_download));
});
});
}
2015-06-13 22:07:06 +02:00
//Function for converting the page into a json dataset.
function to_json(page) {
var result = cheerio('td:nth-child(3) table', page);
2015-06-16 15:22:34 +02:00
var is_teacher = cheerio(cheerio(page).find('tr.CoreDark').find('td')[3]).find('a').html() == null;
var amount_of_days = cheerio(result).find('tr.AccentDark').find('td').length - 1;
var amount_of_hours = config().amount_of_hours;
2015-06-13 22:07:06 +02:00
var schedule_data = [];
2015-06-16 15:22:34 +02:00
var offset = is_teacher ? 5 : 6;
//Looping for amount of days
for (day = 0; day < amount_of_days; day++) {
schedule_data[day] = [];
//Looping for amount of hours
for (hour = 0; hour < amount_of_hours; hour++) {
2015-06-16 15:22:34 +02:00
var schedule = cheerio('tr:nth-child('+ (offset + hour) +')', result);
//Looping for (optional) specialhours
var amount_of_special_hours = schedule.find('table').eq(day).children().length;
schedule_data[day][hour] = {teacher: [], chamber: [], course: [], changed: []};
for (special_hour = 0; special_hour < amount_of_special_hours; special_hour++) {
var selected_hour = schedule.find('table').eq(day).find('tr').eq(special_hour).find('td');
//Give the value of the schedule hour to the fitting array.
schedule_data[day][hour].teacher[special_hour] = selected_hour.eq(0).html();
schedule_data[day][hour].chamber[special_hour] = selected_hour.eq(2).html();
2015-06-16 15:22:34 +02:00
schedule_data[day][hour].course[special_hour] = selected_hour.eq(4).html();
//Check if the hour is 'changed' by the schedule authors, if so set to true.
schedule_data[day][hour].changed[special_hour] = selected_hour.eq(0).attr().class == 'tableCellNew' ? true : false;
}
}
}
return schedule_data;
}
2015-06-13 22:07:06 +02:00
//Exporting the schedule function.
module.exports = schedule;