Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refaktoriranje + koledar učiteljev #2

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions .github/workflows/python-app.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# This workflow will install Python dependencies, run tests and lint with a single version of Python
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python

name: eAUrnik

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

permissions:
contents: read

jobs:
build:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v4
- name: Set up Python 3.12
uses: actions/setup-python@v3
with:
python-version: "3.12"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
- name: Test with unittest
run: |
python -m unittest
37 changes: 28 additions & 9 deletions API.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,45 @@
#

import Timetable
from flask import Flask, request, make_response
from flask_restful import Api, Resource, reqparse
from flask import Flask, make_response
from flask_restful import Api
from flask_cors import CORS

app = Flask(__name__)
api = Api(app)

CORS(app)

@app.errorhandler(404)
def page_not_found(e):
response = make_response("This request could not be processed. Check the provided information and try again.", 400)
response.headers["content-type"] = "application/json"
return response

class handle(Resource):
def get(self, school, class_, student):
timetable = Timetable.get(school, class_, student)
response = make_response(timetable, 200)
response.headers["content-type"] = "text/calendar"
return response
@app.route("/urniki/<string:school>/razredi/<int:class_>/dijak/<int:student>")
def get_student(school, class_, student):
"""Parse a student's calendar."""
timetable = Timetable.get_student(school, class_, student)
response = make_response(timetable, 200)
response.headers["content-type"] = "text/calendar"
return response

api.add_resource(handle, "/urniki/<string:school>/razredi/<int:class_>/dijak/<int:student>")
@app.route("/urniki/<string:school>/razredi/<int:class_>")
def get_class(school, class_):
"""Parse a class's calendar."""
timetable = Timetable.get_class(school, class_)
response = make_response(timetable, 200)
response.headers["content-type"] = "text/calendar"
return response

@app.route("/urniki/<string:school>/ucitelj/<int:teacher>")
@app.route("/urniki/<string:school>/ucitelj/<int:teacher>/tednov/<int:weeks>")
def get_teacher_weeks(school, teacher, weeks=1):
"""Parse a teacher's calender for multiple weeks ahead. If number of weeks isn't specified, defaults to 1."""
timetable = Timetable.get_teacher(school, teacher, weeks)
response = make_response(timetable, 200)
response.headers["content-type"] = "text/calendar"
return response

if __name__ == "__main__":
app.run(host = "::")
45 changes: 0 additions & 45 deletions Calendar.py

This file was deleted.

45 changes: 45 additions & 0 deletions CalendarGenerator.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
#
# Calendar.py
# eAUrnik
#

from ics import Calendar, Event
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo

class CalendarGenerator:
def __init__(self):
self.calendar = Calendar()
self.calendar.creator = "eAUrnik - Fork me on GitHub: https://git.io/JO5Za"

def append_week(self, parsed, monday):
durations = []
for duration in parsed[0]:
start, end = duration.split(" - ")
start_hours, start_minutes = map(int, start.split(":"))
end_hours, end_minutes = map(int, end.split(":"))
durations.append(((start_hours, start_minutes), (end_hours, end_minutes)))

data = parsed[1]
for day_index in range(0, len(data)):
day = monday + timedelta(days = day_index)
lessons = data[day_index]
for lesson_index in range(0, len(lessons)):
for lesson in lessons[lesson_index]:
title = lesson[0]
subtitle = lesson[1]

duration = durations[lesson_index]
timezone = ZoneInfo("Europe/Ljubljana")
start = datetime(day.year, day.month, day.day, duration[0][0], duration[0][1], tzinfo = timezone)
end = datetime(day.year, day.month, day.day, duration[1][0], duration[1][1], tzinfo = timezone)

event = Event()
event.name = title
event.location = subtitle
event.begin = start
event.end = end
self.calendar.events.add(event)

def get_string(self):
return "".join(self.calendar)
19 changes: 8 additions & 11 deletions Parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,15 @@ def parse_block(block):
class_attribute = block.get("class")
if "ednevnik-seznam_ur_teden-td-odpadlo" in class_attribute:
return
# if "ednevnik-seznam_ur_teden-td-nadomescanje" in class_attribute:
# title += " (N)"
if "ednevnik-seznam_ur_teden-td-nadomescanje" in class_attribute:
title += " (N)"
if "ednevnik-seznam_ur_teden-td-zaposlitev" in class_attribute:
title += " (Z)"
icon = block.xpath("table/tr/td[2]/img")
if icon and icon[0].get("title") in ["JV", "PB"]:
return
if block.xpath("div"):
subtitle_unformatted = block.xpath("div")[0].text.strip()
subtitle_components = subtitle_unformatted.split(", ")
subtitle = subtitle_components[1] + ", " + subtitle_components[0]
subtitle= block.xpath("div")[0].text.strip()
else:
subtitle = ""
return (title, subtitle)
Expand All @@ -46,16 +44,15 @@ def lessons(page):
rows = []
for j in range(1, len(coloumns)):
cell = coloumns[j]
blocks = cell.xpath("div")

blocks = cell.xpath(".//div[contains(@class, 'ednevnik-seznam_ur_teden-urnik')]")

if not blocks:
rows.append([])
continue

coloumn_lessons = []
parsed = parse_block(blocks[0])
if parsed:
coloumn_lessons = [parsed]
for k in range(1, len(blocks)):
block = blocks[k].xpath("div")[0]
for block in blocks:
parsed = parse_block(block)
if parsed:
coloumn_lessons.append(parsed)
Expand Down
120 changes: 93 additions & 27 deletions Timetable.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,42 @@
#

import Parser
import Calendar
import CalendarGenerator
import requests
import datetime

def get(school, class_, student):
today = datetime.date.today()
monday = today + datetime.timedelta(days = -today.weekday())
if today.weekday() == 5 or today.weekday() == 6: # Saturday or Sunday
monday += datetime.timedelta(weeks = 1)

schoolyear = today.year
if today.month < 8:
schoolyear -= 1
schoolyearStart = datetime.date(schoolyear, 9, 1)
while schoolyearStart.weekday() == 5 or schoolyearStart.weekday() == 6:
schoolyearStart += datetime.timedelta(days = 1)

week = 1
for i in range((monday - schoolyearStart).days):
if (schoolyearStart + datetime.timedelta(days = i + 1)).weekday() == 0:
week += 1

from datetime import date, timedelta

def get_monday(today):
"""Returns the upcoming Monday. If today is Saturday or Sunday, return next Monday."""
monday = today - timedelta(days=today.weekday()) # Get current week's Monday

# If it's the weekend, take next week.
if today.weekday() >= 5:
monday += timedelta(weeks=1)

return monday

def get_schoolyear_start(schoolyear):
"""Returns the start of the school year, adjusting if it starts on a weekend."""
schoolyear_start = date(schoolyear, 9, 1)
# If it falls on a weekend, move to the next Monday
while schoolyear_start.weekday() >= 5:
schoolyear_start += timedelta(days=1)
return schoolyear_start

def calculate_week(today):
"""Calculates the week number in the school year."""
monday = get_monday(today)

# Determine the school year based on the current date
schoolyear = today.year - 1 if today.month < 9 else today.year # If the month is before September, take previous year.
schoolyear_start = get_schoolyear_start(schoolyear)

# Calculate the number of Mondays between the school year start and current Monday
delta_days = (monday - schoolyear_start).days
return delta_days // 7 + 1


def get_session():
session = requests.Session()
session.get("https://www.easistent.com")

Expand All @@ -34,11 +48,63 @@ def get(school, class_, student):
name = cookie.name
if name != "vxcaccess":
session.cookies.pop(name)

URL = "https://www.easistent.com/urniki/izpis/" + school + "/" + str(class_) + "/0/0/0/" + str(week) + "/" + str(student)

return session

def get_lessons(session, schoolId, classId=0, professorId=0, classroomId=0, week=0, studentId=0):
# The IDs used in the API call are in the following order:
# 1. School
# 2. Class
# 3. Professor/teacher
# 4. Classroom
# 5. Not sure
# 6. Week
# 7. Student
#
# Setting any of these IDs (except the school) to 0 returns all.
URL = f"https://www.easistent.com/urniki/izpis/{schoolId}/{classId}/{professorId}/{classroomId}/0/{week}/{studentId}"
response = session.get(URL)

lessons = Parser.lessons(response.content)
timetable = Calendar.make(lessons, monday)

return timetable
return Parser.lessons(response.content)

def get_student(school, class_, student):
today = date.today()
monday = get_monday(today)
week = calculate_week(today)

session = get_session()

lessons = get_lessons(session, schoolId=school, classId=class_, week=week, studentId=student)

calendar = CalendarGenerator.CalendarGenerator()
calendar.append_week(lessons, monday)
return calendar.get_string()

def get_class(school, class_):
today = date.today()
monday = get_monday(today)
week = calculate_week(today)

session = get_session()

lessons = get_lessons(session, schoolId=school, classId=class_, week=week)

calendar = CalendarGenerator.CalendarGenerator()
calendar.append_week(lessons, monday)
return calendar.get_string()

def get_teacher(school, teacher, weeks = 1):
today = date.today()
monday = get_monday(today)
current_week = calculate_week(today)

session = get_session()

calendar = CalendarGenerator.CalendarGenerator()

for i in range(weeks):
lessons_week = current_week + i - 1
lessons = get_lessons(session, schoolId=school, professorId=teacher, week=lessons_week)
calendar.append_week(lessons, monday + timedelta(weeks=i-1))

return calendar.get_string()
24 changes: 24 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
aniso8601==9.0.1
arrow==1.3.0
attrs==24.2.0
blinker==1.8.2
certifi==2024.8.30
charset-normalizer==3.3.2
click==8.1.7
Flask==3.0.3
Flask-Cors==5.0.0
Flask-RESTful==0.3.10
ics==0.7.2
idna==3.8
itsdangerous==2.2.0
Jinja2==3.1.4
lxml==5.3.0
MarkupSafe==2.1.5
python-dateutil==2.9.0.post0
pytz==2024.2
requests==2.32.3
six==1.16.0
TatSu==5.12.1
types-python-dateutil==2.9.0.20240906
urllib3==2.2.3
Werkzeug==3.0.4
Loading