aboutsummaryrefslogtreecommitdiff
path: root/management/commands/timetables.py
blob: 99742ae7e6ecee227411f9c5c9eb6d312b246844 (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
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from edt.models import Timetable, Group, Room, Course

from bs4 import BeautifulSoup

from ._private import delete_courses_in_week, get_events, get_weeks, get_xml, Week

import datetime
import requests


class Command(BaseCommand):
    help = "Fetches registered celcat timetables"

    def add_arguments(self, parser):
        parser.add_argument("--week", type=int, choices=range(1, 54), nargs="+")

    def __get_weeks(self, weeks):
        if weeks is None:
            year, week, day = timezone.now().isocalendar()
            if day >= 6:
                year, week, _ = (timezone.now() + datetime.timedelta(weeks=1)).isocalendar()

            yield year, week
        else:
            year = timezone.now().year
            for week in weeks:
                yield year, week

    def handle(self, *args, **options):
        for year, week in self.__get_weeks(options["week"]):
            delete_courses_in_week(year, week)

            for timetable in Timetable.objects.all():
                self.stdout.write("Processing {0}, week {1}".format(timetable, week))

                soup = get_xml(timetable.url)
                weeks = get_weeks(soup)

                for name, type_, groups, rooms, notes, begin, end in get_events(soup, weeks, week, timetable):
                    course = Course.objects.create(name=name, notes=notes, timetable=timetable, begin=begin, end=end)

                    course.groups.add(*groups)
                    if rooms is not None:
                        course.rooms.add(*rooms)

                    course.save()

        self.stdout.write(self.style.SUCCESS("Done."))