-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add PE lessons to the generated calendar
This is based on @FEgor04's work in PR #2. - add PE lessons gathering and mapping - refactor project structure to separate responsibilities - switch to asyncio for io ops parallelization - make logging more detailed - improve type hints - implement error handling
- Loading branch information
Showing
9 changed files
with
574 additions
and
139 deletions.
There are no files selected for viewing
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,69 +1,21 @@ | ||
from __future__ import annotations | ||
|
||
from datetime import datetime, timedelta | ||
import logging | ||
from typing import Iterable | ||
|
||
from dateutil.parser import isoparse | ||
from ics import Calendar, Event | ||
|
||
_event_type_to_tag_map = { | ||
"Лекции": "Лек", | ||
"Практические занятия": "Прак", | ||
"Зачет": "Зачет", | ||
} | ||
logger = logging.getLogger(__name__) | ||
|
||
_raw_event_key_names = { | ||
"group": "Группа", | ||
"teacher_name": "Преподаватель", | ||
"zoom_url": "Ссылка на Zoom", | ||
"zoom_password": "Пароль Zoom", | ||
"zoom_info": "Доп. информация для Zoom", | ||
"note": "Примечание", | ||
} | ||
|
||
|
||
def _event_type_to_tag(t: str): | ||
return _event_type_to_tag_map.get(t, t) | ||
|
||
|
||
def _raw_event_to_description(re: dict): | ||
lines = [] | ||
for key, name in _raw_event_key_names.items(): | ||
if re[key]: | ||
lines.append(f"{name}: {re[key]}") | ||
|
||
_msk_formatted_datetime = (datetime.utcnow() + timedelta(hours=3)).strftime("%Y-%m-%d %H:%M") | ||
lines.append(f"Обновлено: {_msk_formatted_datetime} MSK") | ||
return "\n".join(lines) | ||
|
||
|
||
def _raw_event_to_location(re: dict): | ||
elements = [] | ||
for key in "room", "building": | ||
if re[key]: | ||
elements.append(re[key]) | ||
|
||
result = ", ".join(elements) | ||
|
||
if re["zoom_url"]: | ||
result = f"Zoom / {result}" if result else "Zoom" | ||
|
||
return result if result else None | ||
|
||
|
||
def raw_events_to_calendar(raw_events: list[dict]): | ||
def build_calendar(events: Iterable[Event]): | ||
calendar = Calendar() | ||
calendar.creator = "my-itmo-ru-to-ical" | ||
for raw_event in raw_events: | ||
event = Event( | ||
name=f"[{_event_type_to_tag(raw_event['type'])}] {raw_event['subject']}", | ||
begin=isoparse(f"{raw_event['date']}T{raw_event['time_start']}:00+03:00"), | ||
end=isoparse(f"{raw_event['date']}T{raw_event['time_end']}:00+03:00"), | ||
description=_raw_event_to_description(raw_event), | ||
location=_raw_event_to_location(raw_event), | ||
) | ||
if raw_event["zoom_url"]: | ||
event.url = raw_event["zoom_url"] | ||
|
||
for event in events: | ||
calendar.events.add(event) | ||
|
||
logger.info(f"Built a calendar with {len(calendar.events)} events") | ||
return calendar | ||
|
||
|
||
def calendar_to_ics_text(calendar: Calendar) -> str: | ||
return "\n".join(map(str.strip, calendar)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,73 @@ | ||
from datetime import datetime, timedelta | ||
|
||
from dateutil.parser import isoparse | ||
from ics import Event | ||
|
||
_lesson_type_to_tag_map = { | ||
"Лекции": "Лек", | ||
"Практические занятия": "Прак", | ||
"Зачет": "Зачет", | ||
} | ||
|
||
_raw_lesson_key_names = { | ||
"group": "Группа", | ||
"teacher_name": "Преподаватель", | ||
"teacher_fio": "Преподаватель", | ||
"zoom_url": "Ссылка на Zoom", | ||
"zoom_password": "Пароль Zoom", | ||
"zoom_info": "Доп. информация для Zoom", | ||
"note": "Примечание", | ||
} | ||
|
||
|
||
def _lesson_type_to_tag(t: str): | ||
return _lesson_type_to_tag_map.get(t, t) | ||
|
||
|
||
def _raw_lesson_to_description(raw_lesson: dict): | ||
lines = [] | ||
for key, name in _raw_lesson_key_names.items(): | ||
if raw_lesson.get(key): | ||
lines.append(f"{name}: {raw_lesson[key]}") | ||
|
||
_msk_formatted_datetime = (datetime.utcnow() + timedelta(hours=3)).strftime("%Y-%m-%d %H:%M") | ||
lines.append(f"Обновлено: {_msk_formatted_datetime} MSK") | ||
return "\n".join(lines) | ||
|
||
|
||
def _raw_lesson_to_location(raw_lesson: dict): | ||
elements = [] | ||
for key in "room", "building": | ||
if raw_lesson.get(key): | ||
elements.append(raw_lesson[key]) | ||
|
||
result = ", ".join(elements) | ||
|
||
if raw_lesson.get("zoom_url"): | ||
result = f"Zoom / {result}" if result else "Zoom" | ||
|
||
return result if result else None | ||
|
||
|
||
def raw_lesson_to_event(raw_lesson: dict) -> Event: | ||
event = Event( | ||
name=f"[{_lesson_type_to_tag(raw_lesson['type'])}] {raw_lesson['subject']}", | ||
begin=isoparse(f"{raw_lesson['date']}T{raw_lesson['time_start']}:00+03:00"), | ||
end=isoparse(f"{raw_lesson['date']}T{raw_lesson['time_end']}:00+03:00"), | ||
description=_raw_lesson_to_description(raw_lesson), | ||
location=_raw_lesson_to_location(raw_lesson), | ||
) | ||
if raw_lesson["zoom_url"]: | ||
event.url = raw_lesson["zoom_url"] | ||
|
||
return event | ||
|
||
|
||
def raw_pe_lesson_to_event(raw_pe_lesson: dict) -> Event: | ||
return Event( | ||
name=f"[Физра] {raw_pe_lesson['section_name']}", | ||
begin=isoparse(f"{raw_pe_lesson['date']}"), | ||
end=isoparse(f"{raw_pe_lesson['date_end']}"), | ||
description=_raw_lesson_to_description(raw_pe_lesson), | ||
location=raw_pe_lesson["room_name"], | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,17 @@ | ||
import logging | ||
from typing import Awaitable, Callable, Iterable, ParamSpec | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
P = ParamSpec("P") | ||
|
||
|
||
def catch_errors_to_empty_iter(func: Callable[P, Awaitable[Iterable]]) -> Callable[P, Awaitable[Iterable]]: | ||
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> Iterable: | ||
try: | ||
return await func(*args, **kwargs) | ||
except Exception: | ||
logger.exception(f"Failed to call {func.__name__}") | ||
return () | ||
|
||
return wrapper |
Oops, something went wrong.