aboutsummaryrefslogtreecommitdiff
path: root/management/parsers/ups2019.py
blob: c7ab7c96ca3a97139c6d7815b589d80650a0f04f (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
#    Copyright (C) 2019  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 date, datetime, timedelta
from html import unescape

from django.utils import timezone

import requests

from ...models import Course, Group, Module, Room
from ...utils import get_current_week, get_week
from .abstractparser import AbstractParser
from .ups2018 import GROUP_PREFIXES


class Parser(AbstractParser):
    def __get_name(self, raw_name):
        return raw_name.split('[')[1][:-1]

    def __get_event(self, event, year, week):
        if event["allDay"]:
            return

        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 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 = [unescape(st.strip())
                for st in event["description"].split("<br />")]
        groups = []
        rooms = []

        course = Course.objects.create(
            source=self.source, begin=begin, end=end,
            celcat_id=event["id"]
        )

        i = 0
        if event.get("eventCategory") is not None and \
           len(event.get("eventCategory", "")) > 0:
            course.type = event["eventCategory"]
            i = 1

        if event.get("module", "") is not None and \
           len(event.get("module", "")) > 0:
            module, _ = Module.objects.get_or_create(name=event["module"])
            course.module = module

        if '[' in data[i]:
            course.name = self.__get_name(data[i])
            i += 1

        while '[' in data[i]:
            course.name += ", " + self.__get_name(data[i])
            i += 1

        while i < len(data) and not data[i].startswith(GROUP_PREFIXES):
            rooms.append(data[i])
            i += 1
        course.rooms.add(*Room.objects.filter(name__in=rooms))

        while i < len(data) and data[i].startswith(GROUP_PREFIXES):
            groups.append(Group.objects.get_or_create(
                source=self.source, celcat_name=data[i]
            )[0])
            i += 1
        course.groups.add(*groups)

        if i < len(data):
            course.notes = "\n".join(data[i:]).strip()
            if "other" in course.notes:
                print("Warning: 'other' in course.notes")

        return course

    def get_events(self, today, year=None, week=None):
        for event in self.events:
            course = self.__get_event(event, year, week)
            if course is not None:
                yield course

    def get_update_date(self):
        return

    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 get_source(self):
        start = date.today()
        end = start + timedelta(days=365)

        req = requests.post(self.source.url,
                            headers={"User-Agent": self.user_agent},
                            data={"calView": "month",
                                  "resType": 103,
                                  "federationIds[]": self.source.metadata,
                                  "start": start.strftime("%Y-%m-%d"),
                                  "end": end.strftime("%Y-%m-%d")})
        req.encoding = "uft8"
        req.raise_for_status()

        self.events = req.json()
        return self.events