aboutsummaryrefslogtreecommitdiff
path: root/src/server/lib/getMeetingpointData.js
blob: 0272398b67cb6d242c2a405eaf57ac5263daeeb2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const Promise = require('bluebird');
const cheerio = require('cheerio');
const _ = require('lodash');
const request = Promise.promisify(require('request'));

let meetingpointData;
let lastUpdate;

function getUsers(page) {
  const script = page('script').eq(1).text();

  const regexs = [/var classes = \[(.+)\];/, /var teachers = \[(.+)\];/, /var rooms = \[(.+)\];/, /var students = \[(.+)\];/];
  const items = regexs.map(regex => script.match(regex)[1].split(',').map(item => item.replace(/"/g, '')));

  const classes = items[0].map((item, index) => ({
    type: 'c',
    value: item,
    index,
  }));

  const teachers = items[1].map((item, index) => ({
    type: 't',
    value: item,
    index,
  }));

  const rooms = items[2].map((item, index) => ({
    type: 'r',
    value: item,
    index,
  }));

  const students = items[3].map((item, index) => ({
    type: 's',
    value: item,
    index,
  }));

  return _.flatten([classes, teachers, rooms, students]);
}

function getWeeks(page) {
  const weekSelector = page('select[name="week"]');
  const weeks = _.map(weekSelector.children(), option => ({
    id: cheerio(option).attr('value'),
    text: cheerio(option).text(),
  }));

  return weeks;
}

function requestData() {
  lastUpdate = new Date();

  const requests = [
    request('http://www.meetingpointmco.nl/Roosters-AL/doc/dagroosters/frames/navbar.htm', { timeout: 5000 }),
    request('http://www.meetingpointmco.nl/Roosters-AL/doc/basisroosters/frames/navbar.htm', { timeout: 5000 }),
  ];

  return Promise.all(requests).then(([dailyScheduleResponse, basisScheduleResponse]) => {
    const dailySchedulePage = cheerio.load(dailyScheduleResponse.body);
    const basisSchedulePage = cheerio.load(basisScheduleResponse.body);
    const users = getUsers(dailySchedulePage);
    const dailyScheduleWeeks = getWeeks(dailySchedulePage);
    const basisScheduleWeeks = getWeeks(basisSchedulePage);

    meetingpointData = { users, dailyScheduleWeeks, basisScheduleWeeks };

    console.log(meetingpointData);

    return meetingpointData;
  });
}

function getMeetingpointData() {
  if (lastUpdate == null || new Date() - lastUpdate > 10 * 60 * 1000) { // 10 minutes
    return requestData();
  } else if (!meetingpointData) {
    return Promise.reject();
  }
  return Promise.resolve(meetingpointData);
}

module.exports = getMeetingpointData;