-
Notifications
You must be signed in to change notification settings - Fork 0
/
correction.py
163 lines (128 loc) · 5.67 KB
/
correction.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
"""This script will notify you when a new slot is available for correction on the 42 intra."""
import json
import os
import platform
from datetime import date, datetime, timedelta
from string import Template
from time import sleep
from typing import Dict, List, Optional
import requests
from notifypy import Notify
from rich.console import Console
from rich.prompt import IntPrompt, Prompt
SLEEP_TIME = 10
URL = Template("https://projects.intra.42.fr/projects/$project_name/slots.json?team_id=$team_id&start=$start&end=$end")
DIR = os.path.dirname(os.path.realpath(__file__))
class SlotException(Exception):
"""Exception raised when a slot could not be retrieved."""
class Slot:
"""A slot is a time interval where a project can be corrected."""
def __init__(self, data: Dict[str, str]) -> None:
self.id = data["id"]
self.start = datetime.strptime(data["start"][:19], "%Y-%m-%dT%H:%M:%S")
self.end = datetime.strptime(data["end"][:19], "%Y-%m-%dT%H:%M:%S")
def __eq__(self, __value: object) -> bool:
if not isinstance(__value, Slot):
raise NotImplementedError()
return self.id == __value.id
def __str__(self) -> str:
if self.start.date() == self.end.date() and self.start.date() == date.today():
return f"{self.start.time():%H:%M} - {self.end.time():%H:%M}"
return f"{self.start:%d/%m/%Y %H:%M} - {self.end:%d/%m/%Y %H:%M}"
def get_config_path(console: Console) -> Optional[str]:
"""Get the path to the config file."""
if platform.system() == "Windows":
config_folder = os.getenv("APPDATA")
if config_folder is None:
console.print("Could not find APPDATA environment variable. No config will be saved.", style="bold red")
else:
config_folder = os.getenv("HOME")
if config_folder is None:
console.print("Could not find HOME environment variable. No config will be saved.", style="bold red")
if config_folder is None:
return None
return os.path.join(config_folder, "42-correction-tracker.json")
def load_config(console: Console, config_path: Optional[str]) -> dict:
"""Load the config file."""
if config_path is None or not os.path.exists(config_path):
return {}
try:
with open(config_path, "r", encoding="utf-8") as file:
config = json.load(file)
except (OSError, json.JSONDecodeError) as error:
console.print(f"Could not load config file at {config_path} ({error})", style="bold red")
config = {}
return config
def ask_config(config: dict) -> None:
"""Ask the user for the config values."""
project_name_raw = Prompt.ask("Project name", default=config.get("project_name"))
config["project_name"] = project_name_raw.replace(" ", "-").lower()
config["team_id"] = Prompt.ask("Team ID", default=config.get("team_id"))
config["session_token"] = Prompt.ask("Session token", default=config.get("session_token"))
config["nb_days"] = IntPrompt.ask("Number of days", default=config.get("nb_days"))
def save_config(console: Console, config: dict, config_path: Optional[str]) -> None:
"""Save the config file."""
if config_path is None:
return
try:
with open(config_path, "w", encoding="utf-8") as file:
json.dump(config, file)
except OSError:
console.print(f"Could not save config file at {config_path}", style="bold red")
def get_slots(config: dict) -> List[Slot]:
"""Get the slots for the given config."""
response = requests.get(
URL.substitute(config, start=date.today(), end=date.today() + timedelta(days=config["nb_days"])),
headers={
"host": "projects.intra.42.fr",
"Cookie": f"_intra_42_session_production={config['session_token']}"
},
timeout=10
)
content = response.json()
if response.status_code == 200:
return [Slot(slot) for slot in content]
if response.status_code == 404:
raise SlotException("Could not get slots (Project not found)")
if response.status_code == 401:
raise SlotException("Could not get slots (Invalid session token)")
raise SlotException("Could not get slots (Unknown error)")
def send_new_slot_notification(slot: Slot) -> None:
"""Send a notification for a new slot."""
notification = Notify()
notification.title = "New slot"
notification.message = str(slot)
notification.icon = DIR + "/icon.png"
notification.send()
def main() -> None:
console = Console()
console.print("Welcome to the 42 correction tracker!", style="bold green", highlight=False)
config_path = get_config_path(console)
config = load_config(console, config_path)
ask_config(config)
save_config(console, config, config_path)
print()
with console.status("Searching for slots..."):
slots = []
while True:
try:
new_slots = get_slots(config)
except SlotException as error:
console.print(error, style="bold red", highlight=False)
sleep(SLEEP_TIME)
continue
for new_slot in new_slots:
if new_slot not in slots:
console.print(f"{datetime.now()} - New slot: {new_slot}", style="bold green")
send_new_slot_notification(new_slot)
slots.append(new_slot)
for old_slot in slots.copy():
if old_slot not in new_slots:
console.print(f"{datetime.now()} - Slot removed: {old_slot}", style="bold red")
slots.remove(old_slot)
sleep(SLEEP_TIME)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
pass