Mon Jun 26 15:25:26 CEST 2023

This commit is contained in:
mnjx
2023-06-26 16:33:38 +02:00
parent 8168ff3cd4
commit 8b1a6643b5
7 changed files with 297 additions and 249 deletions
+1 -1
View File
@@ -2,4 +2,4 @@
src/lib/data/*.csv
src/lib/shadow
TODO.md
*.swp
+14 -5
View File
@@ -49,9 +49,13 @@ def encrypt_and_write_to_file(password: str, strdata: str, file_path: str) -> bo
f = Fernet(key)
encrypted = f.encrypt(strdata.encode())
with open(file_path, "wb") as ef:
ef.write(encrypted)
if os.path.exists(file_path):
with open(file_path, "wb") as ef:
ef.write(encrypted)
else:
os.system(f"touch {file_path}")
with open(file_path, "wb") as ef:
ef.write(encrypted)
return 0
except:
@@ -68,8 +72,13 @@ def read_from_file_and_decrypt(password: str, file_path: str) -> str:
f = Fernet(key)
with open(file_path, "rb") as ef:
decrypted = f.decrypt(ef.read())
if os.path.exists(file_path):
with open(file_path, "rb") as ef:
decrypted = f.decrypt(ef.read())
else:
os.system(f"touch {file_path}")
with open(file_path, "rb") as ef:
decrypted = f.decrypt(ef.read())
return decrypted.decode()
except:
+2 -6
View File
@@ -106,10 +106,7 @@ def show_grades(password, username, local=False):
if grades == []:
print("N/A\n")
import os
if os.path.exists(f"{os.environ['HOME']}/.local/lib/solendata/{nw.get_user_hash(username)}-encrypted_grades"):
os.remove(f"{os.environ['HOME']}/.local/lib/solendata/{nw.get_user_hash(username)}-encrypted_grades")
return
for i in range(len(grades)):
@@ -131,7 +128,6 @@ def grades_to_file(password, username, grades=None):
for later use and extraction.
"""
import csv
if grades is None:
try:
grades = get_grades(password, username, "/SOL/App/Hodnoceni/KZH001_HodnVypisStud.aspx")
@@ -168,7 +164,7 @@ def grades_to_file(password, username, grades=None):
strdata = "".join(lstrdata)
cr.encrypt_and_write_to_file(password, strdata, f"{os.environ['HOME']}/.local/lib/solendata/{nw.get_user_hash(username)}-encrypted_grades")
cr.encrypt_and_write_to_file(password, strdata, f"{os.environ['HOME']}/.local/lib/solendata/{nw.get_user_hash(username)}-grades")
def grades_from_file(password, username) -> list:
"""
@@ -179,7 +175,7 @@ def grades_from_file(password, username) -> list:
import csv
from io import StringIO
try:
strdata = cr.read_from_file_and_decrypt(password, f"{os.environ['HOME']}/.local/lib/solendata/{nw.get_user_hash(username)}-encrypted_grades")
strdata = cr.read_from_file_and_decrypt(password, f"{os.environ['HOME']}/.local/lib/solendata/{nw.get_user_hash(username)}-grades")
except:
print("Could not read the file")
return
+14 -7
View File
@@ -18,9 +18,15 @@ def _read_shadow() -> str:
"""
result = ""
with open(f"{os.environ['HOME']}/.local/lib/solendata/shadow", "r") as f:
for row in f:
result += row+";"
try:
with open(f"{os.environ['HOME']}/.local/lib/solendata/shadow", "r") as f:
for row in f:
result += row+";"
except FileNotFoundError:
os.system(f"touch {os.environ['HOME']}/.local/lib/solendata/shadow")
with open(f"{os.environ['HOME']}/.local/lib/solendata/shadow", "r") as f:
for row in f:
result += row+";"
return result
@@ -30,14 +36,17 @@ def _save_creds(user: str, pwd: str):
by appending them.
"""
creds = _get_creds_hash(user, pwd)
creds = ";" + _get_creds_hash(user, pwd)
try:
with open(f"{os.environ['HOME']}/.local/lib/solendata/shadow", "a+") as f:
if not creds in _read_shadow():
f.write(creds)
except FileNotFoundError:
print("No shadow file found")
os.system(f"touch {os.environ['HOME']}/.local/lib/solendata/shadow")
with open(f"{os.environ['HOME']}/.local/lib/solendata/shadow", "a+") as f:
if not creds in _read_shadow():
f.write(creds)
def _eval_creds(creds: str) -> bool:
"""
@@ -132,8 +141,6 @@ def get_html_from(params=None) -> str:
response = session.get(base)
if response.status_code == 200:
#print("Download successful")
return response
else:
print("Download unsuccessful")
return ""
+100 -106
View File
@@ -4,12 +4,13 @@
"""
from solenlib import networking as nw
from solenlib import crypto as cr
from bs4 import BeautifulSoup
import os
not_login = 0
def fetch_locally() -> list:
def fetch_locally(password, username) -> list:
"""
Helper function for exctracting
data from a local file.
@@ -20,10 +21,10 @@ def fetch_locally() -> list:
if not_login == 1:
not_login = 0
schedule = schedule_from_file()
schedule = schedule_from_file(password, username)
return schedule
def get_schedule(url: str) -> list:
def get_schedule(password, url: str) -> list:
"""
Filters & extracts the schedule from
the HTML soup.
@@ -134,9 +135,9 @@ def get_schedule(url: str) -> list:
global not_login
not_login = 1
return fetch_locally()
return fetch_locally(password, username)
def schedule_from_file_to_list():
def schedule_from_file_to_list(password, username, strdata):
"""
Extracts the schedule from
a local file and returns
@@ -147,40 +148,38 @@ def schedule_from_file_to_list():
schedule = []
schedule_ = []
try:
with open(f"{os.environ['HOME']}/.local/lib/solendata/schedule_tdy_tmr.csv") as f:
import csv
reader = csv.reader(f)
for row in reader:
temp = []
for col in row:
temp.append(col.strip())
schedule_.append(temp)
import csv
from io import StringIO
f = StringIO(strdata)
reader = csv.reader(f, delimiter=",")
for row in reader:
temp = []
for col in row:
temp.append(col.strip())
schedule_.append(temp)
for i in range(0, len(schedule_), 2):
del schedule_[i][0]
for i in range(0, len(schedule_), 2):
del schedule_[i][0]
temp = []
for i in range(1, len(schedule_), 2):
temp.append(schedule_[i][0])
del schedule_[i][0]
schedule.append(temp)
temp = []
for i in range(1, len(schedule_), 2):
temp.append(schedule_[i][0])
del schedule_[i][0]
schedule.append(temp)
for i in range(10):
temp = []
for j in range(10):
try:
temp.append(schedule_[j][0])
del schedule_[j][0]
except IndexError:
pass
schedule.append(temp)
except FileNotFoundError:
print("No schedule_tdy_tmr.csv file found\n")
for i in range(10):
temp = []
for j in range(10):
try:
temp.append(schedule_[j][0])
del schedule_[j][0]
except IndexError:
pass
schedule.append(temp)
return schedule
def get_whitespace(key: str, idx=0) -> int:
def get_whitespace(password, username, strdata, key: str, idx=0) -> int:
"""
Helper function that calculates
how much whitespaces are needed
@@ -188,7 +187,7 @@ def get_whitespace(key: str, idx=0) -> int:
correctly.
"""
schedule = schedule_from_file_to_list()
schedule = schedule_from_file_to_list(password, username, strdata)
max_len = 0
if key == "DATE":
@@ -204,22 +203,28 @@ def get_whitespace(key: str, idx=0) -> int:
return max_len
def show_schedule(local=False):
def show_schedule(password, username, local=False):
"""
Shows the schedule on the
terminal in a pretty way.
"""
try:
strdata = cr.read_from_file_and_decrypt(password, f"{os.environ['HOME']}/.local/lib/solendata/{nw.get_user_hash(username)}-schedule_tdy_tmr")
except:
print("Could not read the file")
return
if local == False:
# if there is internet access, load stuff from the web
# if not, load the schedule.csv file
if nw.is_connected() == True:
schedule = get_schedule("/SOL/App/Spolecne/KZZ010_RychlyPrehled.aspx")
schedule_to_file(schedule)
schedule = get_schedule(password, "/SOL/App/Spolecne/KZZ010_RychlyPrehled.aspx")
schedule_to_file(password, username, schedule)
else:
schedule = schedule_from_file()
schedule = schedule_from_file(password, username)
else:
schedule = schedule_from_file()
schedule = schedule_from_file(password, username)
print("")
@@ -229,123 +234,112 @@ def show_schedule(local=False):
if schedule == []:
print("N/A\n")
import os
if os.path.exists(f"{os.environ['HOME']}/.local/lib/solendata/schedule_tdy_tmr.csv"):
os.remove(f"{os.environ['HOME']}/.local/lib/solendata/schedule_tdy_tmr.csv")
return
for i in range(len(schedule)):
max_len = get_whitespace("DATE")
max_len = get_whitespace(password, username, strdata, "DATE")
whitespace = " " * (max_len - len(schedule[i]["DAY"]))
print(schedule[i]["DAY"] + whitespace, end=" ")
for j in range(len(schedule[i]["SUBJECTS"])):
max_len = get_whitespace("WHERES", j+1)
max_len = get_whitespace(password, username, strdata, "WHERES", j+1)
whitespace = " " * (max_len - len(schedule[i]["SUBJECTS"][j]))
print("| " + schedule[i]["SUBJECTS"][j] + whitespace, end=" ")
print("")
max_len = get_whitespace("DATE")
max_len = get_whitespace(password, username, strdata, "DATE")
whitespace = " " * (max_len - len(schedule[i]["DATE"]))
print(schedule[i]["DATE"] + whitespace, end=" ")
for j in range(len(schedule[i]["WHERES"])):
max_len = get_whitespace("WHERES", j+1)
max_len = get_whitespace(password, username, strdata, "WHERES", j+1)
whitespace = " " * (max_len - len(schedule[i]["WHERES"][j]))
print("| " + schedule[i]["WHERES"][j] + whitespace, end=" ")
print("")
def schedule_to_file(schedule=None):
def schedule_to_file(password, username, schedule=None):
"""
Writes the schedule to
a local file for later
use.
"""
import csv
if schedule is None:
try:
schedule = get_schedule("/SOL/App/Spolecne/KZZ010_RychlyPrehled.aspx")
except Exception:
schedule = get_schedule(password, "/SOL/App/Spolecne/KZZ010_RychlyPrehled.aspx")
except:
print("An error occured, you probably can't access the internet right now")
return
with open(f"{os.environ['HOME']}/.local/lib/solendata/schedule_tdy_tmr.csv", mode="w", newline="") as f:
data = []
lstrdata = []
for i in range(len(schedule)):
temp = []
try:
temp.append(schedule[i]["DAY"])
except KeyError:
temp.append("N/A")
for j in range(len(schedule[i]["SUBJECTS"])):
try:
temp.append(schedule[i]["SUBJECTS"][j])
except KeyError:
temp.append("N/A")
data.append(temp)
for row in schedule:
lstrdata.append(row["DAY"])
lstrdata.append(",")
for i in row["SUBJECTS"]:
lstrdata.append(i)
lstrdata.append(",")
del lstrdata[-1]
lstrdata.append("\n")
temp = []
try:
temp.append(schedule[i]["DATE"])
except KeyError:
temp.append("N/A")
for j in range(len(schedule[i]["WHERES"])):
try:
temp.append(schedule[i]["WHERES"][j])
except KeyError:
temp.append("N/A")
data.append(temp)
lstrdata.append(row["DATE"])
for i in row["WHERES"]:
lstrdata.append(i)
lstrdata.append(",")
del lstrdata[-1]
lstrdata.append("\n")
writer = csv.writer(f)
for row in data:
writer.writerow(row)
strdata = "".join(lstrdata)
def schedule_from_file() -> list:
cr.encrypt_and_write_to_file(password, strdata, f"{os.environ['HOME']}/.local/lib/solendata/{nw.get_user_hash(username)}-schedule_tdy_tmr")
def schedule_from_file(password, username) -> list:
"""
Fetches schedule data from a file.
"""
import csv
from io import StringIO
schedule = []
try:
with open(f"{os.environ['HOME']}/.local/lib/solendata/schedule_tdy_tmr.csv", mode="r") as f:
reader = csv.reader(f)
rows = []
for row in reader:
rows.append(row)
strdata = cr.read_from_file_and_decrypt(password, f"{os.environ['HOME']}/.local/lib/solendata/{nw.get_user_hash(username)}-schedule_tdy_tmr")
except:
print("Could not read the file")
return
f = StringIO(strdata)
reader = csv.reader(f, delimiter=",")
rows = []
for row in reader:
rows.append(row)
for row in range(0, len(rows), 2):
temp = {}
for row in range(0, len(rows), 2):
temp = {}
temp["DAY"] = rows[row][0]
temp["DAY"] = rows[row][0]
try:
temp["DATE"] = rows[row+1][0]
except IndexError:
pass
try:
temp["DATE"] = rows[row+1][0]
except IndexError:
pass
subjects = []
for i in range(1, len(rows[row])):
subjects.append(rows[row][i])
temp["SUBJECTS"] = subjects
subjects = []
for i in range(1, len(rows[row])):
subjects.append(rows[row][i])
temp["SUBJECTS"] = subjects
wheres = []
try:
for i in range(1, len(rows[row+1])):
wheres.append(rows[row+1][i])
except IndexError:
pass
temp["WHERES"] = wheres
wheres = []
try:
for i in range(1, len(rows[row+1])):
wheres.append(rows[row+1][i])
except IndexError:
pass
temp["WHERES"] = wheres
schedule.append(temp)
except FileNotFoundError:
print("No schedule_tdy_tmr.csv file found\n")
schedule.append(temp)
return schedule
+148 -106
View File
@@ -1,21 +1,36 @@
"""
Functions related to this
week's schedule.
"""
from solenlib import networking as nw
from solenlib import crypto as cr
from bs4 import BeautifulSoup
import os
not_login = 0
def fetch_locally() -> list:
def fetch_locally(password, username) -> list:
"""
Helper function for extracting
data from a local file.
"""
global not_login
if not_login == 1:
not_login = 0
#print("Could not sign in (you may have entered invalid login credentials)")
#print("Fetching the schedule for this week locally\n")
schedule = schedule_from_file()
schedule = schedule_from_file(password, username)
return schedule
def sort_schedule(schedule: list[dict]) -> list[dict]:
"""
Helper function for sorting
the schedule correctly.
"""
sorted_schedule: list[dict] = [{}, {}, {}, {}, {}]
for i in range(len(schedule)):
@@ -32,7 +47,12 @@ def sort_schedule(schedule: list[dict]) -> list[dict]:
return sorted_schedule
def get_schedule(url: str):
def get_schedule(password, url: str) -> list:
"""
Filters & extracts the schedule from
the HTML soup.
"""
try:
html = nw.get_html_from(url)
@@ -146,45 +166,57 @@ def get_schedule(url: str):
schedule = fetch_locally()
return schedule
def schedule_from_file_to_list():
def schedule_from_file_to_list(password, username, strdata):
"""
Extracts the schedule from
a local file and returns
it in a list, which is better
for the get_whitespace() function.
"""
schedule = []
schedule_ = []
try:
with open(f"{os.environ['HOME']}/.local/lib/solendata/schedule_week.csv") as f:
import csv
reader = csv.reader(f)
for row in reader:
temp = []
for col in row:
temp.append(col.strip())
schedule_.append(temp)
import csv
from io import StringIO
f = StringIO(strdata)
reader = csv.reader(f, delimiter=",")
for row in reader:
temp = []
for col in row:
temp.append(col.strip())
schedule_.append(temp)
for i in range(0, len(schedule_), 2):
del schedule_[i][0]
for i in range(0, len(schedule_), 2):
del schedule_[i][0]
temp = []
for i in range(1, len(schedule_), 2):
temp.append(schedule_[i][0])
del schedule_[i][0]
schedule.append(temp)
temp = []
for i in range(1, len(schedule_), 2):
temp.append(schedule_[i][0])
del schedule_[i][0]
schedule.append(temp)
for i in range(10):
temp = []
for j in range(10):
try:
temp.append(schedule_[j][0])
del schedule_[j][0]
except IndexError:
pass
schedule.append(temp)
except FileNotFoundError:
print("No schedule_week.csv file found\n")
for i in range(10):
temp = []
for j in range(10):
try:
temp.append(schedule_[j][0])
del schedule_[j][0]
except IndexError:
pass
schedule.append(temp)
return schedule
def get_whitespace(key: str, idx=0) -> int:
schedule = schedule_from_file_to_list()
def get_whitespace(password, username, strdata, key: str, idx=0) -> int:
"""
Helper function that calculates
how much whitespaces are needed
in order to display the table grid
correctly.
"""
schedule = schedule_from_file_to_list(password, username, strdata)
max_len = 0
if key == "DATE":
@@ -200,17 +232,28 @@ def get_whitespace(key: str, idx=0) -> int:
return max_len
def show_schedule(local=False):
def show_schedule(password, username, local=False):
"""
Shows the schedule on the
terminal in a pretty way.
"""
try:
strdata = cr.read_from_file_and_decrypt(password, f"{os.environ['HOME']}/.local/lib/solendata/{nw.get_user_hash(username)}-schedule_week")
except:
print("Could not read the file")
return
if local == False:
# if there is internet access, load stuff from the web
# if not, load the schedule.csv file
if nw.is_connected() == True:
schedule = get_schedule("/SOL/App/Kalendar/KZK001_KalendarTyden.aspx")
schedule_to_file(schedule)
schedule = get_schedule(password, "/SOL/App/Kalendar/KZK001_KalendarTyden.aspx")
schedule_to_file(password, username, schedule)
else:
schedule = schedule_from_file()
schedule = schedule_from_file(password, username)
else:
schedule = schedule_from_file()
schedule = schedule_from_file(password, username)
print("")
@@ -220,113 +263,112 @@ def show_schedule(local=False):
if schedule == []:
print("N/A\n")
import os
if os.path.exists(f"{os.environ['HOME']}/.local/lib/solendata/schedule_week.csv"):
os.remove(f"{os.environ['HOME']}/.local/lib/solendata/schedule_week.csv")
return
for i in range(len(schedule)):
max_len = get_whitespace("DATE")
max_len = get_whitespace(password, username, strdata, "DATE")
whitespace = " " * (max_len - len(schedule[i]["DAY"]))
print(schedule[i]["DAY"] + whitespace, end=" ")
for j in range(len(schedule[i]["SUBJECTS"])):
max_len = get_whitespace("WHERES", j+1)
max_len = get_whitespace(password, username, strdata, "WHERES", j+1)
whitespace = " " * (max_len - len(schedule[i]["SUBJECTS"][j]))
print("| " + schedule[i]["SUBJECTS"][j] + whitespace, end=" ")
print("")
max_len = get_whitespace("DATE")
max_len = get_whitespace(password, username, strdata, "DATE")
whitespace = " " * (max_len - len(schedule[i]["DATE"]))
print(schedule[i]["DATE"] + whitespace, end=" ")
for j in range(len(schedule[i]["WHERES"])):
max_len = get_whitespace("WHERES", j+1)
max_len = get_whitespace(password, username, strdata, "WHERES", j+1)
whitespace = " " * (max_len - len(schedule[i]["WHERES"][j]))
print("| " + schedule[i]["WHERES"][j] + whitespace, end=" ")
print("")
def schedule_to_file(schedule=None):
import csv
def schedule_to_file(password, username, schedule=None):
"""
Writes the schedule to
a local file for later
use.
"""
if schedule is None:
try:
schedule = get_schedule("/SOL/App/Kalendar/KZK001_KalendarTyden.aspx")
except Exception:
schedule = get_schedule(password, "/SOL/App/Kalendar/KZK001_KalendarTyden.aspx")
except:
print("An error occured, you probably can't access the internet right now")
return
with open(f"{os.environ['HOME']}/.local/lib/solendata/schedule_week.csv", mode="w", newline="") as f:
data = []
lstrdata = []
for i in range(len(schedule)):
temp = []
try:
temp.append(schedule[i]["DAY"])
except KeyError:
temp.append("N/A")
for j in range(len(schedule[i]["SUBJECTS"])):
try:
temp.append(schedule[i]["SUBJECTS"][j])
except KeyError:
temp.append("N/A")
data.append(temp)
for row in schedule:
lstrdata.append(row["DAY"])
lstrdata.append(",")
for i in row["SUBJECTS"]:
lstrdata.append(i)
lstrdata.append(",")
del lstrdata[-1]
lstrdata.append("\n")
temp = []
try:
temp.append(schedule[i]["DATE"])
except KeyError:
temp.append("N/A")
for j in range(len(schedule[i]["WHERES"])):
try:
temp.append(schedule[i]["WHERES"][j])
except KeyError:
temp.append("N/A")
data.append(temp)
lstrdata.append(row["DATE"])
for i in row["WHERES"]:
lstrdata.append(i)
lstrdata.append(",")
del lstrdata[-1]
lstrdata.append("\n")
writer = csv.writer(f)
for row in data:
writer.writerow(row)
strdata = "".join(lstrdata)
cr.encrypt_and_write_to_file(password, strdata, f"{os.environ['HOME']}/.local/lib/solendata/{nw.get_user_hash(username)}-schedule_week")
def schedule_from_file(password, username) -> list:
"""
Fetches schedule data from a file.
"""
def schedule_from_file() -> list:
import csv
from io import StringIO
schedule = []
try:
with open(f"{os.environ['HOME']}/.local/lib/solendata/schedule_week.csv", mode="r") as f:
reader = csv.reader(f)
rows = []
for row in reader:
rows.append(row)
strdata = cr.read_from_file_and_decrypt(password, f"{os.environ['HOME']}/.local/lib/solendata/{nw.get_user_hash(username)}-schedule_week")
except:
print("Could not read the file")
return
f = StringIO(strdata)
reader = csv.reader(f)
rows = []
for row in reader:
rows.append(row)
for row in range(0, len(rows), 2):
temp = {}
for row in range(0, len(rows), 2):
temp = {}
temp["DAY"] = rows[row][0]
temp["DAY"] = rows[row][0]
try:
temp["DATE"] = rows[row+1][0]
except IndexError:
pass
try:
temp["DATE"] = rows[row+1][0]
except IndexError:
pass
subjects = []
for i in range(1, len(rows[row])):
subjects.append(rows[row][i])
temp["SUBJECTS"] = subjects
subjects = []
for i in range(1, len(rows[row])):
subjects.append(rows[row][i])
temp["SUBJECTS"] = subjects
wheres = []
try:
for i in range(1, len(rows[row+1])):
wheres.append(rows[row+1][i])
except IndexError:
pass
temp["WHERES"] = wheres
wheres = []
try:
for i in range(1, len(rows[row+1])):
wheres.append(rows[row+1][i])
except IndexError:
pass
temp["WHERES"] = wheres
schedule.append(temp)
except FileNotFoundError:
print("No schedule_week.csv file found\n")
schedule.append(temp)
return schedule
+8 -8
View File
@@ -95,14 +95,14 @@ if __name__ == "__main__":
try:
if args.week:
if args.local:
sw.show_schedule(local=True)
sw.show_schedule(pwd, user, local=True)
else:
sw.show_schedule()
sw.show_schedule(pwd, user)
if args.today_tomorrow:
if args.local:
st.show_schedule(local=True)
st.show_schedule(pwd, user, local=True)
else:
st.show_schedule()
st.show_schedule(pwd, user)
if args.grades:
if args.local:
gr.show_grades(pwd, user, local=True)
@@ -111,12 +111,12 @@ if __name__ == "__main__":
if not args.grades and not args.today_tomorrow and not args.week:
if args.local:
sw.show_schedule(local=True)
st.show_schedule(local=True)
sw.show_schedule(pwd, user, local=True)
st.show_schedule(pwd, user, local=True)
gr.show_grades(pwd, user, local=True)
else:
sw.show_schedule()
st.show_schedule()
sw.show_schedule(pwd, user)
st.show_schedule(pwd, user)
gr.show_grades(pwd, user)
except Exception as e:
raise e