Skip to content

Commit 66edff0

Browse files
authored
Fix the scripts (#13)
1 parent de824c8 commit 66edff0

File tree

9 files changed

+95
-122
lines changed

9 files changed

+95
-122
lines changed

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ requests_mock_case_sensitive = true
6969
line-length = 160
7070
fix = true
7171
unsafe-fixes = true
72+
include = ["*.py", "*.pyi", "scripts/*"]
7273

7374
[tool.ruff.lint]
7475
select = [

scripts/list_all_courses

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
#!/usr/bin/env python
22
from logprise import logger
33

4-
from smartschool import Smartschool, PathCredentials, Courses
4+
from smartschool import Courses, PathCredentials, Smartschool
55

6-
Smartschool.start(PathCredentials())
7-
for course in Courses():
6+
session = Smartschool(PathCredentials())
7+
for course in Courses(session):
88
logger.info(course.name)
Lines changed: 35 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,71 +1,52 @@
11
#!/usr/bin/env python
2+
from __future__ import annotations
3+
24
from collections import defaultdict
3-
from datetime import date, datetime, timedelta
5+
from typing import TYPE_CHECKING
6+
7+
from _common_tasks_stuff import _next_weekday
48

5-
from smartschool import Courses, FutureTasks, PathCredentials, Periods, Smartschool, SmartschoolHours, SmartschoolLessons, SmartschoolMomentInfos
9+
from smartschool import FutureTasks, PathCredentials, Smartschool, SmartschoolHours
610
from smartschool.common import IsSaved, save, send_email
7-
from smartschool.objects import AgendaHour, FutureTaskOneTask
8-
from smartschool.session import session
11+
12+
if TYPE_CHECKING:
13+
from datetime import date
14+
15+
from smartschool.objects import AgendaHour, FutureTaskOneTask
916

1017

1118
def _is_equal_task(a: FutureTaskOneTask, b: FutureTaskOneTask) -> bool:
12-
return (a.course, a.hourID, a.label, a.description, a.date) ==(b.course, b.hourID, b.label, b.description, b.date)
19+
return (a.course, a.hourID, a.label, a.description, a.date) == (b.course, b.hourID, b.label, b.description, b.date)
1320

1421

15-
def _email_text(task: FutureTaskOneTask) -> str:
16-
hour: AgendaHour = SmartschoolHours().search_by_hourId(task.hourID)
22+
def _email_text(session: Smartschool, task: FutureTaskOneTask) -> str:
23+
hour: AgendaHour = SmartschoolHours(session).search_by_hourId(task.hourID)
1724

18-
return (
19-
f"date: {task.date}\n"
20-
f"lesuur: {hour.title}e lesuur\n"
21-
f"time: {hour.start} -> {hour.end}\n"
22-
f"les: {task.course}\n"
23-
"\n"
24-
f"{task.label}:\n"
25-
f" {task.description}\n"
26-
)
25+
return f"date: {task.date}\nlesuur: {hour.title}e lesuur\ntime: {hour.start} -> {hour.end}\nles: {task.course}\n\n{task.label}:\n {task.description}\n"
2726

2827

29-
def process_task(task: FutureTaskOneTask, all_tasks: dict) -> None:
28+
def process_task(session: Smartschool, task: FutureTaskOneTask, all_tasks: dict) -> None:
3029
"""Stores in an array + report if it's a new/updated task."""
31-
3230
course_name = task.course
33-
hour: AgendaHour = SmartschoolHours().search_by_hourId(task.hourID)
31+
hour: AgendaHour = SmartschoolHours(session).search_by_hourId(task.hourID)
3432
when = task.date
3533

3634
all_tasks[when][hour.title].append(task)
3735

38-
status = save(type_="todo", course_name=course_name, id_=task.assignmentID, data=task, is_eq=_is_equal_task)
36+
status = save(session, type_="todo", course_name=course_name, id_=task.assignmentID, data=task, is_eq=_is_equal_task)
3937
if status == IsSaved.SAME:
4038
return
4139

4240
subject = f"📑 [{when} {hour.title}e lesuur] {course_name} ({task.label})"
4341
if status != IsSaved.NEW:
4442
subject = f"⚠⚠ {subject}" # There is an update...
4543

46-
text = _email_text(task)
47-
48-
send_email(subject=subject, text=text, email_from=session.creds.other_info['email_from'], email_to=session.creds.other_info['email_to'])
44+
text = _email_text(session, task)
4945

46+
send_email(subject=subject, text=text, email_from=session.creds.other_info["email_from"], email_to=session.creds.other_info["email_to"])
5047

51-
def _next_weekday() -> date | None:
52-
now = datetime.now()
5348

54-
if now.hour in [12, 20] and now.isoweekday() == 3: # Wednesday
55-
... # Ok
56-
elif now.hour in [17, 20] and now.isoweekday() != 3: # !Wednesday
57-
... # Ok
58-
else:
59-
return None
60-
61-
next_weekday = now + timedelta(days=1)
62-
while next_weekday.isoweekday() in [6, 7]: # Saturday, Sunday
63-
next_weekday += timedelta(days=1)
64-
65-
return next_weekday.date()
66-
67-
68-
def report_tasks_for_next_day(all_tasks: dict):
49+
def report_tasks_for_next_day(session: Smartschool, all_tasks: dict):
6950
next_weekday = _next_weekday()
7051
if not next_weekday:
7152
return
@@ -76,40 +57,38 @@ def report_tasks_for_next_day(all_tasks: dict):
7657
tasks = all_tasks[next_weekday]
7758

7859
text = []
79-
for uur, tasks in sorted(tasks.items(), key=lambda x: x[0]): # type: str, list[FutureTaskOneTask]
80-
for task in tasks:
81-
text.append(_email_text(task))
60+
for _uur, subtasks in sorted(tasks.items(), key=lambda x: x[0]): # type: str, list[FutureTaskOneTask]
61+
for task in subtasks:
62+
text.append(_email_text(session, task))
8263

8364
text = "\n---------------------------------------\n\n".join(text)
8465

85-
status = save('todo', '.email', str(next_weekday), data=text, extension='txt')
66+
status = save(session, "todo", ".email", str(next_weekday), data=text, extension="txt")
8667
if status == IsSaved.SAME:
8768
return # Don't re-send if nothing changed
8869

89-
subject=f"🍕 Todo list {next_weekday}"
70+
subject = f"🍕 Todo list {next_weekday}"
9071
if status != IsSaved.NEW:
9172
subject = f"⚠⚠ {subject}" # There is an update...
92-
send_email(
93-
subject=subject,
94-
text=text, email_from=session.creds.other_info['email_from'], email_to=session.creds.other_info['email_to'])
73+
send_email(subject=subject, text=text, email_from=session.creds.other_info["email_from"], email_to=session.creds.other_info["email_to"])
9574

9675

9776
def main():
9877
all_tasks: dict[date, dict[str, list]] = defaultdict(lambda: defaultdict(list))
9978

100-
Smartschool.start(PathCredentials())
101-
assert 'email_from' in session.creds.other_info
102-
assert 'email_to' in session.creds.other_info
79+
session = Smartschool(PathCredentials())
80+
assert "email_from" in session.creds.other_info
81+
assert "email_to" in session.creds.other_info
10382

104-
for day in FutureTasks().days:
83+
for day in FutureTasks(session):
10584
for course in day.courses:
10685
assert not course.items.materials, "Please correct the model to include this information."
10786

10887
for task in course.items.tasks:
109-
process_task(task, all_tasks)
110-
111-
report_tasks_for_next_day(all_tasks)
88+
process_task(session, task, all_tasks)
89+
90+
report_tasks_for_next_day(session, all_tasks)
11291

11392

114-
if __name__ == '__main__':
93+
if __name__ == "__main__":
11594
main()
Lines changed: 22 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,29 @@
11
#!/usr/bin/env python
22
from collections import defaultdict
3-
from datetime import date
3+
from typing import TYPE_CHECKING
4+
5+
from _common_tasks_stuff import _email_text, _next_weekday
46

5-
from _common_tasks_stuff import _next_weekday, _email_text
67
from smartschool import PathCredentials, Smartschool
78
from smartschool.common import IsSaved, save, send_email
8-
from smartschool.objects import FutureTaskOneTask, PlannedElement
9+
from smartschool.objects import PlannedElement
910
from smartschool.planner import PlannedElements
10-
from smartschool.session import session
11+
12+
if TYPE_CHECKING:
13+
from datetime import date
1114

1215

1316
def _is_equal_task(a: PlannedElement, b: PlannedElement) -> bool:
14-
return (
15-
[c.name for c in a.courses],
16-
a.period.dateTimeFrom,
17-
a.period.dateTimeTo,
18-
a.assignmentType.name,
19-
a.name
20-
) == (
17+
return ([c.name for c in a.courses], a.period.dateTimeFrom, a.period.dateTimeTo, a.assignmentType.name, a.name) == (
2118
[c.name for c in b.courses],
2219
b.period.dateTimeFrom,
2320
b.period.dateTimeTo,
2421
b.assignmentType.name,
25-
b.name
22+
b.name,
2623
)
2724

2825

29-
def process_task(task: PlannedElement, all_tasks: dict) -> None:
26+
def process_task(session: Smartschool, task: PlannedElement, all_tasks: dict) -> None:
3027
"""Stores in an array + report if it's a new/updated task."""
3128
next_weekday = _next_weekday()
3229
is_for_next_day = next_weekday < task.period.dateTimeFrom.date() or next_weekday > task.period.dateTimeTo.date()
@@ -46,19 +43,18 @@ def process_task(task: PlannedElement, all_tasks: dict) -> None:
4643
if is_for_next_day:
4744
all_tasks[when][hour].append(text)
4845

49-
status = save(type_="todo", course_name=course_name, id_=task.assignmentType.id, data=task, is_eq=_is_equal_task)
46+
status = save(session, type_="todo", course_name=course_name, id_=task.assignmentType.id, data=task, is_eq=_is_equal_task)
5047
if status == IsSaved.SAME:
5148
return
5249

5350
subject = f"📑 [{when} {hour}] {course_name} ({task.name})"
5451
if status != IsSaved.NEW:
5552
subject = f"⚠⚠ {subject}" # There is an update...
5653

57-
send_email(subject=subject, text=text, email_from=session.creds.other_info['email_from'],
58-
email_to=session.creds.other_info['email_to'])
54+
send_email(subject=subject, text=text, email_from=session.creds.other_info["email_from"], email_to=session.creds.other_info["email_to"])
5955

6056

61-
def report_tasks_for_next_day(all_tasks: dict):
57+
def report_tasks_for_next_day(session: Smartschool, all_tasks: dict):
6258
for dag, rest in all_tasks.items():
6359
text = []
6460

@@ -68,31 +64,29 @@ def report_tasks_for_next_day(all_tasks: dict):
6864

6965
text = "\n---------------------------------------\n\n".join(text)
7066

71-
status = save('todo', '.email', dag, data=text, extension='txt')
67+
status = save(session, "todo", ".email", dag, data=text, extension="txt")
7268
if status == IsSaved.SAME:
7369
continue # Don't re-send if nothing changed
7470

7571
subject = f"🍕 Todo list {dag}"
7672
if status != IsSaved.NEW:
7773
subject = f"⚠⚠ {subject}" # There is an update...
7874

79-
send_email(
80-
subject=subject,
81-
text=text, email_from=session.creds.other_info['email_from'], email_to=session.creds.other_info['email_to'])
75+
send_email(subject=subject, text=text, email_from=session.creds.other_info["email_from"], email_to=session.creds.other_info["email_to"])
8276

8377

8478
def main():
8579
all_tasks: dict[date, dict[str, list]] = defaultdict(lambda: defaultdict(list))
8680

87-
Smartschool.start(PathCredentials())
88-
assert 'email_from' in session.creds.other_info
89-
assert 'email_to' in session.creds.other_info
81+
session = Smartschool(PathCredentials())
82+
assert "email_from" in session.creds.other_info
83+
assert "email_to" in session.creds.other_info
9084

91-
for element in PlannedElements():
92-
process_task(element, all_tasks)
85+
for element in PlannedElements(session):
86+
process_task(session, element, all_tasks)
9387

94-
report_tasks_for_next_day(all_tasks)
88+
report_tasks_for_next_day(session, all_tasks)
9589

9690

97-
if __name__ == '__main__':
91+
if __name__ == "__main__":
9892
main()

scripts/smartschool_report_on_results

Lines changed: 23 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,15 @@
11
#!/usr/bin/env python
2+
from __future__ import annotations
3+
4+
from typing import TYPE_CHECKING
25

36
from logprise import logger
4-
from smartschool import PathCredentials, Results, Smartschool, DownloadError
7+
8+
from smartschool import PathCredentials, Results, Smartschool, SmartSchoolDownloadError
59
from smartschool.common import IsSaved, save, send_email
6-
from smartschool.objects import ResultWithoutDetails
7-
from smartschool.session import session
10+
11+
if TYPE_CHECKING:
12+
from smartschool.objects import ResultWithoutDetails
813

914

1015
def is_punten_json_the_same(previous: ResultWithoutDetails, current: ResultWithoutDetails) -> bool:
@@ -67,26 +72,20 @@ def is_punten_json_the_same(previous: ResultWithoutDetails, current: ResultWitho
6772

6873

6974
def build_text(
70-
is_update: bool,
75+
is_update: bool, # noqa: FBT001
7176
result: ResultWithoutDetails,
7277
) -> tuple[str, str]:
7378
course_name = result.courses[0].name
7479
teacher_names = [teacher.name.startingWithFirstName for teacher in result.courses[0].teachers]
7580
test_name = result.name
7681

77-
achieved = f"{result.graphic.achieved_points:.2f}".rstrip('0').rstrip('.')
78-
total = f"{result.graphic.total_points:.2f}".rstrip('0').rstrip('.')
79-
pct = f"{100 * result.graphic.percentage:.2f}".rstrip('0').rstrip('.')
82+
achieved = f"{result.graphic.achieved_points:.2f}".rstrip("0").rstrip(".")
83+
total = f"{result.graphic.total_points:.2f}".rstrip("0").rstrip(".")
84+
pct = f"{100 * result.graphic.percentage:.2f}".rstrip("0").rstrip(".")
8085

8186
my_points = f"{achieved}/{total} ({pct}%)"
8287

83-
text = (
84-
f"Course: {course_name}\n"
85-
f"Test: {test_name}\n"
86-
"\n"
87-
f"Points: {my_points}\n"
88-
"\n"
89-
)
88+
text = f"Course: {course_name}\nTest: {test_name}\n\nPoints: {my_points}\n\n"
9089
for teacher_name in teacher_names:
9190
text += f"Teacher: {teacher_name}\n"
9291
text += "\n"
@@ -121,35 +120,35 @@ def build_text(
121120
return text, email_subject
122121

123122

124-
def process_result(result: ResultWithoutDetails) -> None:
123+
def process_result(session: Smartschool, result: ResultWithoutDetails) -> None:
125124
assert len(result.courses) == 1, f"Multiple courses? {result.courses}"
126125

127126
logger.info("[{}] Processing '{}'", result.courses[0].name, result.name)
128127

129128
course_name = result.courses[0].name # FE: 'Frans'
130129
id_ = result.identifier
131130

132-
status = save("punten", course_name, id_, result, is_punten_json_the_same)
131+
status = save(session, "punten", course_name, id_, result, is_punten_json_the_same)
133132

134133
if status == IsSaved.SAME:
135134
logger.debug(" => Already processed")
136135
return
137136

138137
text, subject = build_text(result=result, is_update=status != IsSaved.NEW)
139-
send_email(subject=subject, text=text, email_from=session.creds.other_info['email_from'], email_to=session.creds.other_info['email_to'])
138+
send_email(subject=subject, text=text, email_from=session.creds.other_info["email_from"], email_to=session.creds.other_info["email_to"])
140139

141140

142141
def main():
143142
try:
144-
Smartschool.start(PathCredentials())
145-
assert 'email_from' in session.creds.other_info
146-
assert 'email_to' in session.creds.other_info
143+
session = Smartschool(PathCredentials())
144+
assert "email_from" in session.creds.other_info
145+
assert "email_to" in session.creds.other_info
147146

148-
for result in Results():
149-
process_result(result)
150-
except DownloadError:
147+
for result in Results(session):
148+
process_result(session, result)
149+
except SmartSchoolDownloadError:
151150
...
152151

153152

154-
if __name__ == '__main__':
153+
if __name__ == "__main__":
155154
main()

src/smartschool/__init__.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
from .agenda import SmartschoolHours, SmartschoolLessons, SmartschoolMomentInfos
22
from .courses import Courses, TopNavCourses
33
from .credentials import EnvCredentials, PathCredentials
4-
from .exceptions import DownloadError, SmartSchoolAuthenticationError, SmartSchoolException
4+
from .exceptions import SmartSchoolAuthenticationError, SmartSchoolDownloadError, SmartSchoolException
55
from .future_tasks import FutureTasks
66
from .messages import (
77
AdjustMessageLabel,
@@ -26,7 +26,6 @@
2626
"Attachments",
2727
"BoxType",
2828
"Courses",
29-
"DownloadError",
3029
"EnvCredentials",
3130
"FutureTasks",
3231
"MarkMessageUnread",
@@ -40,6 +39,7 @@
4039
"ResultDetail",
4140
"Results",
4241
"SmartSchoolAuthenticationError",
42+
"SmartSchoolDownloadError",
4343
"SmartSchoolException",
4444
"Smartschool",
4545
"SmartschoolHours",

0 commit comments

Comments
 (0)