aboutsummaryrefslogtreecommitdiff
path: root/lib/getMeetingpointData.js
blob: ea0f4de45cf7c4450aa3ddaa6993170fd7957289 (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
85
86
87
88
89
90
91
92
93
94
95
96
97
'use strict'

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(function (regex) {
    const match = script.match(regex)

    if (!match) {
      return []
    }

    return match[1].split(',').map(function (item) {
      return item.replace(/"/g, '')
    })
  })

  return []
  .concat(items[0].map(function (item, index) {
    return {
      type: 'c',
      value: item,
      index: index
    }
  }))
  .concat(items[1].map(function (item, index) {
    return {
      type: 't',
      value: item,
      index: index
    }
  }))
  .concat(items[2].map(function (item, index) {
    return {
      type: 'r',
      value: item,
      index: index
    }
  }))
  .concat(items[3].map(function (item, index) {
    return {
      type: 's',
      value: item,
      index: index
    }
  }))
}

function getValidWeekNumbers(page) {
  const weekSelector = page('select[name="week"]');
  const weekNumbers = _.map(weekSelector.children(), option => parseInt(option.attribs.value))

  return weekNumbers;
}

function requestData() {
  lastUpdate = new Date()

  const url = process.env.SCHOOL_LEVEL === 'mavo'
    ? 'http://www.meetingpointmco.nl/Roosters-AL/TOSweb/dagroosters/frames/navbar.htm'
    : 'http://www.meetingpointmco.nl/Roosters-AL/doc/dagroosters/frames/navbar.htm';

  console.log(url);

  return request(url, { timeout: 5000 }).then((response) => {
    const page = cheerio.load(response.body)
    console.log('hey')
    const users = getUsers(page)
    console.log(users);
    const validWeekNumbers = getValidWeekNumbers(page)

    meetingpointData = { users, validWeekNumbers }

    return meetingpointData
  })
}

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

module.exports = getMeetingpointData