aboutsummaryrefslogtreecommitdiff
path: root/management/parsers/ups2018.py
blob: f1da5bfcca9044177d8ac6c2eda5a484bf021b1c (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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
#    Copyright (C) 2018  Alban Gruin
#
#    celcatsanitizer is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published
#    by the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    celcatsanitizer is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with celcatsanitizer.  If not, see <http://www.gnu.org/licenses/>.

from datetime import datetime, timedelta
from collections import OrderedDict

import asyncio
import calendar
import json
import re

from django.utils import timezone

import lxml.html
import requests

from ...models import Course, Group, Room
from ...utils import get_current_week, get_week
from .abstractparser import AbstractParser, ParserError

VARNAME = "v.events.list = "


def find_events_list(soup):
    res = []
    found = False
    for script in soup.xpath("//script/text()"):
        if VARNAME in script:
            for var in script.split('\n'):
                if var.startswith(VARNAME):
                    res = json.loads(var[len(VARNAME):-2])
                    found = True

    return res, found


def get_next_month(dt):
    n = dt.replace(day=1) + timedelta(days=32)
    return n.replace(day=1)


class Parser(AbstractParser):
    def __init__(self, source):
        super(Parser, self).__init__(source)
        self.events = [self._make_request(source.url)]
        self.source = source

    def _make_request(self, url, date=None):
        events, found = [], False
        attempts = 0
        params = {}

        if date is not None:
            params["Date"] = date

        while not found:
            if attempts == 3:
                raise ParserError("Failed to retrieve {0}".format(url))
            attempts += 1

            # En-tête tiré de mon Firefox…
            req = super(Parser, self)._make_request(
                url, params=params,
                headers={"Accept-Language": "en-US,en;q=0.5"},
            )
            req.raise_for_status()

            parser = lxml.html.HTMLParser(encoding="utf8")
            soup = lxml.html.document_fromstring(req.content, parser=parser)
            events, found = find_events_list(soup)

        if date is None:
            self.months = []
            for option in soup.xpath("//option"):
                if option.get("selected") is not None or len(self.months) > 0:
                    self.months.append(option.text)

        return events

    def __get_event(self, event, today,
                    beginning_of_month, end_of_month,
                    year, week):
        begin = timezone.make_aware(
            datetime.strptime(event["start"], "%Y-%m-%dT%H:%M:%S")
        )
        end = timezone.make_aware(
            datetime.strptime(event["end"], "%Y-%m-%dT%H:%M:%S")
        )

        if begin < beginning_of_month or begin >= end_of_month or \
           (today is not None and begin < today):
            return

        if year is not None and week is not None:
            event_year, event_week, _ = begin.isocalendar()
            if event_year != year or event_week != week:
                return

        data = event["text"].split("<br>")
        rooms = None
        if data[0] == "Global Event":
            return

        course = Course.objects.create(
            source=self.source, begin=begin, end=end
        )

        min_i = 0
        if len(data) > 0 and re.match("^\(\d+:\d+-\d+:\d+\)$", data[0]):
            min_i = 1

        i = min_i
        while i < len(data) and not data[i].startswith(
                ("L1 ", "L2 ", "L3 ", "L3P ", "M1 ", "M2 ", "DEUST ", "MAG1 ",
                 "1ERE ANNEE ", "2EME ANNEE ", "3EME ANNEE ",
                 "MAT-Agreg Interne ")
        ):
            i += 1

        groups = data[i]
        if i - 1 >= min_i:
            # TODO: le jour où la version minimale supportée sera
            # Python 3.7, il sera possible de remplacer OrderedDict
            # par un dictionnaire classique.
            names = OrderedDict.fromkeys(data[i - 1].split(';'))
            course.name = ", ".join(names.keys())
        else:
            course.name = "Sans nom"
        if i - 2 >= min_i:
            course.type = data[i - 2]
        if len(data) >= i + 2:
            rooms = data[i + 1]
        if len(data) >= i + 3:
            course.notes = data[i + 2]

        groups = [
            Group.objects.get_or_create(
                source=self.source, celcat_name=name
            )[0]
            for name in groups.split(';')
        ]
        course.groups.add(*groups)

        if rooms is not None:
            rooms_objs = Room.objects.filter(name__in=rooms.split(';'))
            if rooms_objs.count() > 0:
                course.rooms.add(*rooms_objs)
            elif course.notes:
                course.notes = "{0}\n{1}".format(rooms, course.notes)
            else:
                course.notes = rooms

        if course.notes is not None:
            course.notes = course.notes.strip()

        return course

    def get_events(self, today, year=None, week=None):
        for i, month in enumerate(self.events):
            beginning_of_month = timezone.make_aware(
                datetime.strptime(self.months[i], "%B, %Y")
            )
            end_of_month = get_next_month(beginning_of_month)

            for event in month:
                course = self.__get_event(event, today,
                                          beginning_of_month, end_of_month,
                                          year, week)
                if course is not None:
                    yield course

    def get_update_date(self):
        return None  # Pas de date de mise à jour dans ce format

    def get_weeks(self):
        # FIXME: détection automatique à partir des événements présents
        beginning, _ = get_week(*get_current_week())
        self.weeks = {"1": beginning}

        return self.weeks

    def ajax_req(self, month):
        month = datetime.strptime(month, "%B, %Y")
        first_monday = min(
            week[calendar.MONDAY]
            for week in calendar.monthcalendar(month.year, month.month)
            if week[calendar.MONDAY] > 0
        )
        month_str = month.replace(day=first_monday).strftime("%Y%m%d")

        return self._make_request(self.source.url, month_str)

    @asyncio.coroutine
    def get_months_async(self):
        loop = asyncio.get_event_loop()
        futures = []

        for month in self.months[1:]:
            futures.append(loop.run_in_executor(None, self.ajax_req, month))

        responses = yield from asyncio.gather(*futures)
        return responses

    def get_source_from_months(self, async=True):
        events = []

        if async:
            loop = asyncio.get_event_loop()
            events = loop.run_until_complete(self.get_months_async())
        else:
            for month in self.months[1:]:
                events.append(self.ajax_req(month))

        return events

    def get_source(self):
        self.events += self.get_source_from_months()
        return self.events