TGBotReffBook
184 строки · 8.7 Кб
1import json
2import datetime
3import itertools
4from aiohttp import request
5
6from async_lru import alru_cache
7
8from app.data.keyspace import LessonsKeyWords
9from app.data.keyspace import Separators
10from app.data.urls import SCHEDULE_API_URL
11
12
13class ScheduleParser:
14"""Парсер сайта СПбПУ с расписание с помощью API"""
15
16@staticmethod
17@alru_cache
18async def getInstitutes() -> dict:
19"""API запрос для получения списка всех институтов"""
20url = SCHEDULE_API_URL + f"/faculties"
21async with request("GET", url) as html_page:
22answer = await html_page.json()
23institutes_dict = dict()
24for inst in answer["faculties"]:
25institutes_dict[inst["id"]] = inst["name"]
26return institutes_dict
27
28@staticmethod
29@alru_cache
30async def getCourses(faculty: int, ed_form: str, degree: int) -> list:
31"""API запрос для получения количечества курсов при заданных параметрах"""
32json_pack = await ScheduleParser.getGroups(faculty)
33levels = set()
34for group in json_pack["groups"]:
35if group["type"] == ed_form and group["kind"] == degree:
36levels.add(group['level'])
37return list(levels)
38
39@staticmethod
40@alru_cache
41async def getGroupsByParameters(faculty: int, ed_form: str, degree: int, level: int) -> dict:
42"""API запрос для получения всех групп по парамтерам: институт, форма обучения, степень обучения, курс"""
43json_pack = await ScheduleParser.getGroups(faculty)
44groups = dict()
45for group in json_pack["groups"]:
46if group["type"] == ed_form and group["kind"] == degree and group["level"] == level:
47groups[group["name"] + Separators.DATA_META + str(group["id"])] = group["name"]
48return {i: groups[i] for i in sorted(groups)}
49
50@staticmethod
51async def getGroupsByText(group: str) -> dict:
52"""API запрос для получения подходящих групп по тексту"""
53url = SCHEDULE_API_URL + f"/search/groups?q={group}"
54async with request("GET", url) as html_page:
55answer = await html_page.json()
56if answer["groups"] is None:
57return dict()
58
59groups_dict = dict()
60for gr in answer["groups"]:
61groups_dict[gr["name"] + Separators.DATA_META + str(gr["id"])] = gr["name"]
62return groups_dict
63
64@staticmethod
65@alru_cache
66async def getTeacherNameByID(id: int) -> str:
67"""API запрос для получения подходящих преподавателей по тексту"""
68url = SCHEDULE_API_URL + f"/teachers/{id}"
69async with request("GET", url) as html_page:
70answer = await html_page.json()
71if answer.get("error"):
72return str()
73return answer["full_name"]
74
75@staticmethod
76async def getTeacherByText(teacher: str) -> dict:
77"""API запрос для получения подходящих преподавателей по тексту"""
78url = SCHEDULE_API_URL + f"/search/teachers?q={teacher}"
79async with request("GET", url) as html_page:
80answer = await html_page.json()
81if answer["teachers"] is None:
82return dict()
83
84teachers_dict = dict()
85for tcr in answer["teachers"]:
86teachers_dict[str(tcr["id"])] = tcr["full_name"]
87return {i[0]: i[1] for i in sorted(teachers_dict.items(), key=lambda t: t[1])}
88
89@staticmethod
90async def getPlacesByText(place: str) -> dict:
91"""API запрос для получения подходящих групп по тексту"""
92url = SCHEDULE_API_URL + f"/search/rooms?q={place}"
93async with request("GET", url) as html_page:
94answer = await html_page.json()
95if answer["rooms"] is None:
96return dict()
97
98groups_dict = dict()
99for gr in answer["rooms"]:
100groups_dict[str(gr["building"]["id"]) + Separators.DATA_META + str(gr["id"])] = gr["building"]["name"] \
101+ ", " + gr["name"]
102return groups_dict
103
104@staticmethod
105@alru_cache
106async def getLessons(group: int, date: datetime.date) -> list:
107"""API запрос для получения занятий группы на неделю, где присутсвуте дата = date"""
108url = SCHEDULE_API_URL + '/scheduler/' + str(group) + '?date=' + date.isoformat()
109async with request("GET", url) as html_page:
110answer = await html_page.json()
111return ScheduleParser.parseLessons(answer)
112
113@staticmethod
114@alru_cache
115async def getTeacherLessons(teacher: int, date: datetime.date) -> list:
116"""API запрос для получения занятий преподавателя на неделю, где присутсвуте дата = date"""
117url = SCHEDULE_API_URL + '/teachers/' + str(teacher) + "/scheduler?date=" + date.isoformat()
118async with request("GET", url) as html_page:
119answer = await html_page.json()
120return ScheduleParser.parseLessons(answer)
121
122@staticmethod
123@alru_cache
124async def getPlaceLessons(building: int, place: int, date: datetime.date) -> list:
125"""API запрос для получения занятий преподавателя на неделю, где присутсвуте дата = date"""
126url = SCHEDULE_API_URL + '/buildings/' + str(building) + '/rooms/' + str(place) + "/scheduler?date=" + date.isoformat()
127async with request("GET", url) as html_page:
128answer = await html_page.json()
129return ScheduleParser.parseLessons(answer)
130
131@staticmethod
132def parseLessons(answer: json) -> list:
133"""Парсит json расписания"""
134lessons_result = []
135for day in answer["days"]:
136day_dict = dict()
137day_dict[LessonsKeyWords.DAY] = day["date"]
138lessons_at_day = []
139for lesson in day["lessons"]:
140lesson_dict = dict()
141lesson_dict[LessonsKeyWords.START_TIME] = lesson["time_start"]
142lesson_dict[LessonsKeyWords.END_TIME] = lesson["time_end"]
143lesson_dict[LessonsKeyWords.NAME] = lesson["subject_short"]
144# Type
145if lesson.get("typeObj") is not None:
146lesson_dict[LessonsKeyWords.TYPE] = lesson.get("typeObj")["name"]
147
148# Type
149if lesson.get("additional_info") is not None:
150lesson_dict[LessonsKeyWords.ADD_INFO] = lesson.get("additional_info")
151
152# Groups
153if lesson.get("groups") is not None:
154lesson_dict[LessonsKeyWords.GROUPS_NAME] = [group["name"] for group in lesson["groups"]]
155lesson_dict[LessonsKeyWords.GROUPS_LINK] = [
156f"/faculty/{group['faculty']['id']}/groups/{group['id']}" for group in lesson["groups"]]
157
158# Teacher
159if lesson.get("teachers") is not None:
160lesson_dict[LessonsKeyWords.TEACHER_NAME] = lesson["teachers"][0]["full_name"]
161lesson_dict[LessonsKeyWords.TEACHER_LINK] = f"/teachers/{lesson['teachers'][0]['id']}"
162
163# Place
164if lesson.get("auditories") is not None:
165auditori = lesson["auditories"][0]
166lesson_dict[LessonsKeyWords.PLACE_NAME] = auditori["building"]["name"] + ", " + auditori["name"]
167lesson_dict[LessonsKeyWords.PLACE_LINK] = f"/places/{auditori['building']['id']}/{auditori['id']}"
168
169# Resource
170if lesson.get("lms_url") is not None and lesson.get("lms_url") != "":
171lesson_dict[LessonsKeyWords.RESOURCE_NAME] = "СДО"
172lesson_dict[LessonsKeyWords.RESOURCE_LINK] = lesson["lms_url"]
173lessons_at_day.append(lesson_dict)
174day_dict[LessonsKeyWords.LESSONS] = lessons_at_day
175lessons_result.append(day_dict)
176return lessons_result
177
178@staticmethod
179@alru_cache
180async def getGroups(faculty):
181"""API запрос для получения всех групп в институте"""
182group_url = SCHEDULE_API_URL + "faculties/" + str(faculty) + "/groups"
183async with request("GET", group_url) as html_page:
184return await html_page.json()
185