-
Notifications
You must be signed in to change notification settings - Fork 0
/
setup.py
1139 lines (826 loc) · 45.3 KB
/
setup.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import customtkinter as ctk
from customtkinter import *
from CTkMessagebox import CTkMessagebox
import pronotepy
import requests
from geopy.geocoders import Nominatim
from dotenv import set_key
import re
import sys
import time
import json
from hPyT import *
import importlib
import os
import webbrowser
import configparser
import base64
from win11toast import notify
import shutil
import subprocess
import winsound
import datetime
# Create a ConfigParser object
config = configparser.ConfigParser()
default_title_font = "Roboto", 15
default_subtitle_font = "Roboto", 12
default_text_font = "Roboto", 13
default_credit_font = "Roboto", 10
default_font_name = "Roboto"
geolocator = Nominatim(user_agent="Geocoder")
script_directory = os.path.dirname(os.path.abspath(__file__))
config_file_path = f"{script_directory}/Data/config.ini"
config_file_name = "config.ini"
cancel_icon_path = f"{script_directory}/Icons/cancel_icon.png"
ok_icon_path = f"{script_directory}/Icons/ok_icon.png"
question_icon_path = f"{script_directory}/Icons/question_icon.png"
warning_icon_path = f"{script_directory}/Icons/warning_icon.png"
info_icon_path = f"{script_directory}/Icons/info_icon.png"
github_repo_name = "TGA25dev/Pronote-Class-Notifier"
local_paths = {
"config": os.path.join(script_directory, "Data", "config.ini"),
"ico": os.path.join(script_directory, "Data", "pronote_butterfly.ico"),
"ent_data": os.path.join(script_directory, "Data", "ent_data.json"),
"env_p": os.path.join(script_directory, "Data", "pronote_password.env"),
"env_u": os.path.join(script_directory, "Data", "pronote_username.env")
}
github_paths = {
"config": "Data/config.ini",
"ico": "Data/pronote_butterfly.ico",
"ent_data": "Data/ent_data.json",
"env_p": "Data/pronote_password.env",
"env_u": "Data/pronote_username.env"
}
#wanted file type can be : ico, config, ent_data, pronote_password or pronote_username
def check_important_file_existence(wanted_file_type):
github_file_path = None
file_path = None
file_path = local_paths.get(wanted_file_type)
github_file_path = github_paths.get(wanted_file_type)
# Check if the file exists
while not os.path.isfile(file_path):
if github_file_path is not None:
print(f"File ({wanted_file_type}) does not exist. Downloading from the GitHub repo...")
notify('Fichier manquant !', 'Un fichier nécéssaire au fonctionement du logiciel semble avoir été supprimé !\n\nTéléchargement en cours...', icon="https://i.postimg.cc/FRKD3Jgc/warning.png")
# Construct the API URL
api_url = f"https://api.github.com/repos/{github_repo_name}/contents/{github_file_path}"
# Send a GET request to the API URL
response = requests.get(api_url)
# If the request was successful, get the download URL
if response.status_code == 200:
# The content is in the 'content' key of the JSON response
content = response.json()['content']
# Decode the content from Base64
content = base64.b64decode(content)
# Write the content to the file
with open(file_path, 'wb') as f:
f.write(content)
print(f"File ({wanted_file_type}) has been saved succesfully !")
notify("Téléchargement terminé !","Merci d'avoir patienté ! 🚀", icon="https://i.postimg.cc/PJWpqSpM/ok-icon.png")
else:
print(f"Failed to download file ({wanted_file_type}). Status code: {response.status_code}")
else:
# Create empty .env file for env_u or env_p if they don't exist
with open(file_path, 'w') as f:
if wanted_file_type == "env_p":
f.write("Password=")
elif wanted_file_type == "env_u":
f.write("User=")
print(f"File ({wanted_file_type}) has been created successfully!")
notify("Téléchargement terminé !","Merci d'avoir patienté ! 😉", icon="https://i.postimg.cc/PJWpqSpM/ok-icon.png")
else:
print(f"File ({wanted_file_type}) exists. No action taken.")
countdown_seconds = 20 # Define the countdown_seconds variable outside the function
def update_countdown():
global countdown_seconds # Declare that you're using the global variable
if countdown_seconds > 0:
closing_countdown_label.configure(text=f"Fermeture dans {countdown_seconds}s...")
countdown_seconds -= 1
root.after(1000, update_countdown) # Schedule the update_countdown function to run after 1 second
else:
root.destroy() # Close the window or take any other action when the countdown reaches 0
def find_export_dir():
box = CTkMessagebox(title="Ziper le dossier ?", message=f"Souhaitez-vous ziper le dossier du bot pour alléger son poid ?", icon=question_icon_path, option_1="Oui", option_2="Non",cancel_button=None ,cancel_button_color="light grey", justify="center", master=root, width=350, height=10, corner_radius=20)
box.info._text_label.configure(wraplength=450)
response = box.get()
if response == "Non":
subprocess.Popen(f'explorer {os.path.realpath(f"{script_directory}/Bot Files")}')
else:
print("Ziping folder...")
shutil.make_archive(f"{script_directory}/Bot Files", 'zip', f"{script_directory}/Bot Files")
print("Folder has been ziped succesfully !")
shutil.rmtree(f"{script_directory}/Bot Files")
subprocess.Popen(f'explorer {os.path.realpath(f"{script_directory}")}')
find_dir_button.configure(state="disabled", text_color="grey")
global closing_countdown_label
closing_countdown_label = CTkLabel(root, text="Fermeture...")
closing_countdown_label.place(relx=0.2, rely=0.95, anchor="center")
close_button.place_forget()
winsound.PlaySound("SystemExclamation", winsound.SND_ALIAS)
window_flash.flash(root, 5, 500)
# Start the countdown
update_countdown()
def final_step():
print("All steps have been succesfully completed !")
tabview.pack_forget()
main_text.place(relx=0.5, rely=0.3, anchor="center")
main_text.configure(text="Vous avez terminé la configuration de Pronote Class Notifier !\n\nCliquez sur le boutton ci-dessous pour trouver le dossier\nde votre bot.")
global find_dir_button
find_dir_button = CTkButton(root, text="Trouver", command=find_export_dir)
find_dir_button.place(relx=0.5, rely=0.65, anchor="center")
bot_files_folder = os.path.exists(f"{script_directory}/Bot Files")
bot_files_zip_folder = os.path.isfile(f"{script_directory}/Bot Files.zip")
if bot_files_folder:
shutil.rmtree(f"{script_directory}/Bot Files")
elif bot_files_zip_folder:
os.remove(f"{script_directory}/Bot Files.zip")
os.mkdir(f"{script_directory}/Bot Files")
os.mkdir(f"{script_directory}/Bot Files/Data")
shutil.copy(f"{script_directory}/requirements.txt", f"{script_directory}/Bot Files/requirements.txt")
shutil.copy(f"{script_directory}/pronote_main_code.py", f"{script_directory}/Bot Files/pronote_main_code.py")
shutil.copy(f"{script_directory}/Data/{config_file_name}", f"{script_directory}/Bot Files/Data/{config_file_name}")
shutil.copy(f"{script_directory}/Data/ent_data.json", f"{script_directory}/Bot Files/Data/ent_data.json")
shutil.copy(f"{script_directory}/Data/pronote_password.env", f"{script_directory}/Bot Files/Data/pronote_password.env")
shutil.copy(f"{script_directory}/Data/pronote_username.env", f"{script_directory}/Bot Files/Data/pronote_username.env")
steps = ['config_tab1_approved', 'config_tab2_approved', 'config_tab3_approved', 'config_tab4_approved']
for step in steps:
if step not in globals():
globals()[step] = False
# Function to check if all steps are completed
def check_all_steps_completed():
if all(globals().get(step, False) for step in steps):
final_step()
def get_ntfy_topic():
ntfy_entered_topic_name = ntfy_topic_name_entry.get()
box = CTkMessagebox(title="Valider ?", message=f"Est-ce bien le nom de votre topic ?\n{ntfy_entered_topic_name}", icon=question_icon_path, option_1="Oui", option_2="Annuler",cancel_button=None ,cancel_button_color="light grey", justify="center", master=root, width=350, height=10, corner_radius=20)
box.info._text_label.configure(wraplength=450)
response = box.get()
if response == "Oui":
defined_ntfy_topic_name = ntfy_entered_topic_name
print(f"ntfy topic name has been defined on: {defined_ntfy_topic_name}")
ntfy_topic_name_button.configure(state="disabled")
ntfy_topic_name_entry.configure(state="disabled", text_color="grey")
config_tab_step1_text.configure(text="Parfait !\nVous pouvez passer au deuxième onglet.")
check_important_file_existence(wanted_file_type="config")
# Read the INI file with the appropriate encoding
with open(config_file_path, 'r', encoding='utf-8') as configfile:
config.read_file(configfile)
# Modify a key in the INI file
config['Global']['topic_name'] = defined_ntfy_topic_name
# Write the changes back to the INI file
with open(config_file_path, 'w', encoding='utf-8') as configfile:
config.write(configfile)
globals()['config_tab1_approved'] = True
check_all_steps_completed()
elif response == "Annuler":
pass
def config_steps():
mid_canvas.place_forget()
school_name_text.place_forget()
check_important_file_existence(wanted_file_type="config")
# Read the INI file with the appropriate encoding
with open(config_file_path, 'r', encoding='utf-8') as configfile:
config.read_file(configfile)
# Modify a key in the INI file
config['Global']['student_fullname'] = nom_utilisateur
config['Global']['student_firstname'] = user_first_name
config['Global']['student_class'] = student_class_name
# Write the changes back to the INI file
with open(config_file_path, 'w', encoding='utf-8') as configfile:
config.write(configfile)
#right_text_label = ctk.CTkLabel(root, text="Vous pouvez désormais personaliser Pronote Class Notifier (certains parametres son obligatoires)") # Adjust width as needed
#right_text_label.place(relx=0.75, rely=0.4, anchor="center")
global tabview
tabview = ctk.CTkTabview(master=root, height=195, width=450)
tabview.pack(padx=20, pady=0)
tabview.add("1. ntfy") # add tab at the end
tabview.add("2. Repas") # add tab at the end
tabview.add("3. Emojis")
tabview.add("4. Avancé")
tabview.set("1. ntfy") # set currently visible tab
close_button.tkraise()
author_name_label.tkraise()
global config_tab_step1_text
config_tab_step1_text = ctk.CTkLabel(master=tabview.tab("1. ntfy"), text= f"Bonjour {user_first_name} !\nEnregistrez ici le nom de votre topic ntfy.")
config_tab_step1_text.place(relx=0.5, rely=0.2, anchor="center")
global ntfy_topic_name_entry
ntfy_topic_name_entry = ctk.CTkEntry(master=tabview.tab("1. ntfy"), width=200)
ntfy_topic_name_entry.place(relx=0.5, rely=0.5, anchor="center")
ntfy_topic_name_entry.bind("<Return>", lambda event: get_ntfy_topic())
# Function to enable the button if entry is not empty
def enable_button(event):
if ntfy_topic_name_entry.get() and ntfy_topic_name_entry.get() != "mon-topic-ntfy":
ntfy_topic_name_button.configure(state="normal", text_color="white")
else:
ntfy_topic_name_button.configure(state="disabled", text_color="grey")
ntfy_topic_name_entry.insert(0, "mon-topic-ntfy")
ntfy_topic_name_entry.bind("<FocusIn>", lambda event: ntfy_topic_name_entry.delete(0, ctk.END) if ntfy_topic_name_entry.get() == "mon-topic-ntfy" else None)
ntfy_topic_name_entry.bind("<FocusOut>", lambda event: ntfy_topic_name_entry.insert(0, "mon-topic-ntfy") if not ntfy_topic_name_entry.get() else None)
ntfy_topic_name_entry.bind("<KeyRelease>", enable_button)
global ntfy_topic_name_button
ntfy_topic_name_button = ctk.CTkButton(master=tabview.tab("1. ntfy"), text="Valider",command=get_ntfy_topic, state="disabled", text_color="grey")
ntfy_topic_name_button.place(relx=0.5, rely=0.75, anchor="center")
#TAB 2 LUNCH TIMES
if not menus_found:
config_tab_step2_text = ctk.CTkLabel(master=tabview.tab("2. Repas"), text="Votre établissement ne semble pas avoir défini\nle menu de la cantine dans Pronote...\n\nPassez cette étape.")
config_tab_step2_text.place(relx=0.5, rely=0.5, anchor="center")
globals()['config_tab2_approved'] = True
check_all_steps_completed()
# Handling the case when a menu is found
else:
config_tab_step2_text = ctk.CTkLabel(master=tabview.tab("2. Repas"), text="Déplacez le curseur bleu pour définir vos horaires\nde déjeuner.")
config_tab_step2_text.place(relx=0.5, rely=0.15, anchor="center")
# Create labels and Scale widgets for each day
days = ["Lundi", "Mardi", "Mercredi", "Jeudi", "Vendredi"]
labels = {}
scales = {}
lunch_times = {}
global current_day_index
current_day_index = 0 # Initialize current_day_index here
def time_to_minutes(time):
"""Convert time in HH:MM format to minutes since 00:00."""
hours, minutes = map(int, time.split(":"))
return hours * 60 + minutes
def minutes_to_time(minutes):
"""Convert minutes since 00:00 to time in HH:MM format."""
hours = minutes // 60
minutes = minutes % 60
return f"{hours:02d}:{minutes:02d}"
def submit_lunch_time():
global current_day_index
global day
day = days[current_day_index]
selected_minutes = int(scales[day].get())
lunch_times[day] = minutes_to_time(selected_minutes)
if current_day_index < len(days) - 1:
# Hide the current day and move to the next day
labels[day].place_forget()
scales[day].place_forget()
current_day_index += 1
next_day = days[current_day_index]
labels[next_day].place(relx=0.35, rely=0.3)
scales[next_day].place(relx=0.5, rely=0.5, anchor="center")
else:
# Final submission
scales[day].configure(state="disabled", progress_color="grey")
submit_button.configure(state="disabled", text_color="grey")
label.place_forget()
config_tab_step2_text.configure(text="Vos paramètres ont étés enregistrés !\nPassez à la prochaine étape.")
print(f"Lunch times submitted:\n{lunch_times}")
french_to_english = {
'lundi': 'Monday',
'mardi': 'Tuesday',
'mercredi': 'Wednesday',
'jeudi': 'Thursday',
'vendredi': 'Friday'
}
check_important_file_existence(wanted_file_type="config")
# Read the INI file with the appropriate encoding
with open(config_file_path, 'r', encoding='utf-8') as configfile:
config.read_file(configfile)
for french_day, time in lunch_times.items():
english_day = french_to_english.get(french_day.lower()) # Translate French day to English
if english_day:
config['LunchTimes'][english_day] = time
# Write the changes back to the INI file
with open(config_file_path, 'w', encoding='utf-8') as configfile:
config.write(configfile)
globals()['config_tab2_approved'] = True
check_all_steps_completed()
# Define the time range for lunch times (e.g., from 10:30 to 14:30 in 5-minute intervals)
start_time = time_to_minutes("10:30")
end_time = time_to_minutes("14:30")
increment = 5 # 5 minutes increment
for day in days:
label = ctk.CTkLabel(master=tabview.tab("2. Repas"), text=f"{day} 12h30 (par défaut)")
labels[day] = label
scale = ctk.CTkSlider(master=tabview.tab("2. Repas"), from_=start_time, to=end_time, number_of_steps=(end_time - start_time) // increment)
scales[day] = scale
# Add a label to show the selected time
def update_label(value, scale=scale, label=label, day=day):
time = minutes_to_time(int(float(value)))
label.configure(text=f"{day}: {time}h")
scale.configure(command=lambda value, scale=scale, label=label, day=day: update_label(value, scale, label, day))
# Show the Scale for the first day only
labels[days[current_day_index]].place(relx=0.35, rely=0.3)
scales[days[current_day_index]].place(relx=0.5, rely=0.5, anchor="center")
# Create the submit button
submit_button = ctk.CTkButton(master=tabview.tab("2. Repas"), text="Enregistrer", command=submit_lunch_time)
submit_button.place(relx=0.5, rely=0.8, anchor="center")
#TAB 3 EMOJIS
config_tab_step3_text = ctk.CTkLabel(master=tabview.tab("3. Emojis"), text="La configuration des emojis arrivera dans une\nprochaine version.\n\n(Vous pouvez toujours le faire manuellement dans le\nfichier de configuration)")
config_tab_step3_text.place(relx=0.5, rely=0.5, anchor="center")
globals()['config_tab3_approved'] = True
check_all_steps_completed()
#TAB 4 ADVANCED
def set_config_file_advanced():
save_button.configure(state="disabled", text_color="grey")
switch.configure(state="disabled", text_color="grey", button_color="grey")
combo_menu.configure(state="disabled", button_color="grey")
check_important_file_existence(wanted_file_type="config")
config_tab_step4_text.configure(text="Votre fuseau horaire à bien été enregistré !")
# Read the INI file with the appropriate encoding
with open(config_file_path, 'r', encoding='utf-8') as configfile:
config.read_file(configfile)
# Modify a key in the INI file
config['Advanced']['timezone'] = selected_timezone
# Write the changes back to the INI file
with open(config_file_path, 'w', encoding='utf-8') as configfile:
config.write(configfile)
globals()['config_tab4_approved'] = True
check_all_steps_completed()
def switch_toggled():
if switch_var.get() == "on":
combo_menu.place_forget()
else:
combo_menu.place(relx=0.5, rely=0.55, anchor="center")
def save_selection():
global selected_timezone
if switch_var.get() == "off":
selected_option = combo_menu.get()
if selected_option == "":
print("Value cannot be None !")
box = CTkMessagebox(title="Erreur !", message="Vous devez choisir une valeur du menu avant de valider !", icon=warning_icon_path, option_1="Réessayer",master=root, width=350, height=10, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
else:
if selected_option == "UTC":
selected_timezone = "UTC"
else:
sign = selected_option[3]
offset = selected_option[4:]
# Invert the sign for the Etc/GMT format
if sign == '+':
etc_gmt_offset = f"-{offset}"
elif sign == '-':
etc_gmt_offset = f"+{offset}"
selected_timezone = f"Etc/GMT{etc_gmt_offset}"
print(f"New timezone has been selected : {selected_timezone}")
set_config_file_advanced()
else:
selected_timezone = "Europe/Paris"
print("Default timezone has been selected !")
set_config_file_advanced()
config_tab_step4_text = ctk.CTkLabel(master=tabview.tab("4. Avancé"), text="Au besoin changez le fuseau horaire utilisé.")
config_tab_step4_text.place(relx=0.5, rely=0.15, anchor="center")
# Add a switch (CTkSwitch)
switch_var = ctk.StringVar(value="on") # Set the switch to be enabled by default
switch = ctk.CTkSwitch(master=tabview.tab("4. Avancé"), text="France (par défaut)", variable=switch_var, onvalue="on", offvalue="off", command=switch_toggled)
switch.place(relx=0.5, rely=0.35, anchor="center")
# Add a combobox
options = ["UTC", "UTC+1", "UTC+2", "UTC+3", "UTC+4", "UTC+5", "UTC+6", "UTC+7", "UTC+8", "UTC+9", "UTC+10", "UTC+11", "UTC+12", "UTC-1", "UTC-2", "UTC-3", "UTC-4", "UTC-5", "UTC-6", "UTC-7", "UTC-8", "UTC-9", "UTC-10", "UTC-11", "UTC-12", "UTC-13", "UTC-14"]
combo_menu = ctk.CTkComboBox(master=tabview.tab("4. Avancé"), values=options, state="readonly")
combo_menu.place_forget() # Initially hidden
# Add a save button
save_button = ctk.CTkButton(master=tabview.tab("4. Avancé"), text="Valider", command=save_selection)
save_button.place(relx=0.5, rely=0.8, anchor="center")
def save_credentials():
username = username_entry.get()
password = password_entry.get()
if not username or not password:
print("Missing Entrys")
box = CTkMessagebox(title="Erreur !", message="Vous devez renseigner un mot de passe et un identifiant...", icon=warning_icon_path, option_1="Réessayer",master=root, width=350, height=10, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
else:
root.config(cursor="watch")
try:
check_important_file_existence(wanted_file_type="config")
# Read the INI file with the appropriate encoding
with open(config_file_path, 'r', encoding='utf-8') as configfile:
config.read_file(configfile)
if ent_connexion:
module = importlib.import_module("pronotepy.ent")
used_ent = getattr(module, used_ent_name, None)
client = pronotepy.Client(pronote_url, username=username, password=password, ent=used_ent)
# Modify a key in the INI file
config['Global']['ent_used'] = "True"
config['Global']['ent_name'] = used_ent_name
else:
client = pronotepy.Client(pronote_url, username=username, password=password)
# Modify a key in the INI file
config['Global']['ent_used'] = "False"
config['Global']['ent_name'] = "None"
# Write the changes back to the INI file
with open(config_file_path, 'w', encoding='utf-8') as configfile:
config.write(configfile)
if client.logged_in:
box = CTkMessagebox(title="Succès !", message="Connexion effectuée !", icon=ok_icon_path, option_1="Parfait", master=root, width=300, height=10, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
today = datetime.date.today()
fallback_dates = [
datetime.date(2024, 5, 27),
datetime.date(2024, 5, 28),
datetime.date(2024, 5, 29),
datetime.date(2024, 5, 30),
datetime.date(2024, 5, 31)
]
global menus
dates_to_check = [today] + fallback_dates
global menus_found
menus_found = False
for date in dates_to_check:
try:
menus = client.menus(date_from=date)
if menus: # If a menu is found, break out of the loop
menus_found = True
break
except KeyError:
menus_found = False
global nom_utilisateur
global student_class_name
nom_utilisateur = client.info.name
student_class_name = client.info.class_name
print(f'Logged in as {nom_utilisateur}')
# Enregistrer le nom d'utilisateur et le mot de passe dans deux fichiers .env différents
set_key(f"{script_directory}/Data/pronote_username.env", 'User', username)
set_key(f"{script_directory}/Data/pronote_password.env", 'Password', password)
# Separate uppercase letters (high caps) and other characters
#user_last_name = ' '.join(re.findall(r'\b[A-Z]+\b', nom_utilisateur))
#user_first_name = re.sub(r'\b[A-Z]+\b', '', nom_utilisateur)
#user_first_name = re.sub(r'[^a-zA-Z\s]', '', user_first_name)
pattern = r'\b(?:\S+\s*)+\S+\b'
match = re.search(pattern, nom_utilisateur)
global user_first_name
user_first_name = match.group().split()[-1] if match else None
root.config(cursor="arrow")
# Effacer les champs après enregistrement
username_entry.delete(0, 'end')
password_entry.delete(0, 'end')
username_label.place_forget()
username_entry.place_forget()
password_entry.place_forget()
password_label.place_forget()
save_button.place_forget()
title_label.configure(text="")
main_text.configure(text= "")
config_steps()
else:
print("Unknow error !")
box = CTkMessagebox(title="Erreur !", message="Une erreur inconnue est survenue...\nVeuillez réessayer plus tard.", icon=cancel_icon_path, option_1="Ok",master=root, width=300, height=10, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
root.config(cursor="arrow")
except (pronotepy.CryptoError, pronotepy.ENTLoginError):
print("Wrong credentials !")
box = CTkMessagebox(title="Erreur !", message="Vos identifiants de connexion semblent incorrects...", icon=warning_icon_path, option_1="Réessayer",master=root, width=300, height=10, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
password_entry.delete(0, 'end')
root.config(cursor="arrow")
def search_school():
root.config(cursor="watch")
city = city_entry.get()
print(city)
try:
true_city_geocode = geolocator.geocode(city)
except:
box = CTkMessagebox(title="Erreur !", message="Une erreur inconnue est survenue...", icon=warning_icon_path, option_1="Réessayer",master=root, width=300, height=10, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
root.config(cursor="arrow")
if not true_city_geocode:
print("Unknow city !")
box = CTkMessagebox(title="Erreur !", message="Cette ville ne semble pas exister...", icon=warning_icon_path, option_1="Réessayer",master=root, width=300, height=10, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
root.config(cursor="arrow")
city_entry.delete(0, "end")
elif true_city_geocode:
true_city_name = true_city_geocode.raw["name"]
print(true_city_name)
display_name = true_city_geocode.raw["display_name"]
# Split the display name by comma
display_name_parts = display_name.split(", ")
# Get the last part which should be the country name
country_name = display_name_parts[-1]
print(country_name)
if country_name != "France":
city_entry.delete(0, "end")
box = CTkMessagebox(title="Info", message=f"Pronote Class Notifier ne peut être utilisé que dans un établissement situé en France !", icon=info_icon_path, option_1="Ok",master=root, width=350, height=10, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
root.config(cursor="arrow")
else:
city_entry.delete(0, "end")
if ("Marseille" in true_city_name) and "Arrondissement" not in true_city_name:
box = CTkMessagebox(title="Info", message=f"Pour Marseille merci de spécifier l'arrondissement en entier !\nExemple : Marseille 1er Arrondissement, Marseille 2e Arrondissement,", icon=info_icon_path, option_1="Réessayer",master=root, width=350, height=15, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
root.config(cursor="arrow")
elif ("Paris" in true_city_name or "Lyon" in true_city_name) and "Arrondissement" not in true_city_name:
box = CTkMessagebox(title="Info", message=f"Pour {true_city_name} merci de spécifier l'arrondissement !\nExemple : {true_city_name} 19e, {true_city_name} 20e, {true_city_name} 1er", icon=info_icon_path, option_1="Réessayer",master=root, width=350, height=10, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
root.config(cursor="arrow")
else:
search_button.configure(state="disabled", text_color="grey")
if "Arrondissement" in true_city_name:
# Define the pattern to match
pattern = r'(\d+e)\s+(Arrondissement)' or r'(\d+er)\s+(Arrondissement)'
# Replace the matched pattern with a space between the number and "Arrondissement"
true_city_name = re.sub(pattern, r'\1 \2', true_city_name)
url = "https://data.education.gouv.fr/api/explore/v2.1/catalog/datasets/fr-en-adresse-et-geolocalisation-etablissements-premier-et-second-degre/records"
# Define query parameters
limit = 30
params = {
"limit": 30,
"refine": [
f"libelle_commune:{true_city_name}",
"nature_uai_libe:COLLEGE",
"nature_uai_libe:LYCEE ENSEIGNT GENERAL ET TECHNOLOGIQUE",
"nature_uai_libe:LYCEE POLYVALENT",
"nature_uai_libe:LYCEE PROFESSIONNEL"
]
}
# Make the GET request
response = requests.get(url, params=params)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Parse the JSON response
data = response.json()
results_number = data["total_count"]
if results_number == 0:
print("No results for the city !")
box = CTkMessagebox(title="Aucun résultat", message="Il ne semble pas y avoir de collèges ou lycées dans cette ville...", icon=warning_icon_path, option_1="Réessayer",master=root, width=350, height=10, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
else:
results_count = data["total_count"]
# Print the data
appellation_officielle_values = []
for record in data['results']:
appellation_officielle = record['appellation_officielle']
appellation_officielle_values.append(appellation_officielle)
print(f"{results_count} results have been returned for {true_city_name} ! (limit is {limit})")
def optionmenu_callback(choice):
root.config(cursor="watch")
url = "https://data.education.gouv.fr/api/explore/v2.1/catalog/datasets/fr-en-adresse-et-geolocalisation-etablissements-premier-et-second-degre/records"
# Define query parameters
params = {
"limit": 10,
"refine": [
f"appellation_officielle:{choice}",
f"libelle_commune:{true_city_name}",
]
}
# Make the GET request
response = requests.get(url, params=params)
# Check if the request was successful (status code 200)
if response.status_code == 200:
# Parse the JSON response
data = response.json()
# Print the data
uai_number = data["results"][0]["numero_uai"]
global departement_code
global region_name
global school_type
departement_code = data["results"][0]["code_departement"]
region_name = data["results"][0]["libelle_region"]
school_type = data["results"][0]["nature_uai_libe"]
global pronote_url
pronote_url = f"https://{uai_number}.index-education.net/pronote/eleve.html"
print(pronote_url)
check_important_file_existence(wanted_file_type="config")
# Read the INI file with the appropriate encoding
with open(config_file_path, 'r', encoding='utf-8') as configfile:
config.read_file(configfile)
config["Global"]["login_page_link"] = pronote_url
# Write the changes back to the INI file
with open(config_file_path, 'w', encoding='utf-8') as configfile:
config.write(configfile)
pronote_use = True
pronote_use_msg = None
try:
response = requests.get(pronote_url, allow_redirects=False)
except requests.exceptions.ConnectionError:
pronote_use = False
pronote_use_msg = "DNS Error"
except Exception as e:
pronote_use_msg = str(e)
pronote_use = False
# Handle any other unexpected errors
if pronote_use and not pronote_use_msg and response.status_code == 200:
print(f"{choice} ({true_city_name}) uses Pronote !")
global used_ent_name
used_ent_name = None
global ent_connexion
ent_connexion = False
choice_menu.place_forget()
root.config(cursor="arrow")
title_label.configure(text="Etape 3/4")
main_text.configure(text=f"Connectez vous à Pronote\nà l'aide de vos indentifiants.")
def adjust_text_size(event=None):
# Get the current text of the label
text = school_name_text.cget("text")
# Calculate the length of the text
text_length = len(text)
# Adjust font size based on text length
font_size = max(10, 12 - text_length // 10) # Adjust the formula as needed
# Update the font size of the label
school_name_text.configure(font=("Roboto", font_size))
global school_name_text
school_name_text = ctk.CTkLabel(root, text=f"{choice}", font=(default_subtitle_font))
school_name_text.place(relx=0.23, rely=0.65, anchor="center")
# Bind the label to the adjust_text_size function
school_name_text.bind("<Configure>", adjust_text_size)
# Création des labels
global username_label
username_label = ctk.CTkLabel(root, text="Identifiant", font=(default_subtitle_font))
username_label.place(relx=0.75, rely=0.23, anchor="center")
global password_label
password_label = ctk.CTkLabel(root, text="Mot de passe", font=(default_subtitle_font))
password_label.place(relx=0.75, rely=0.53, anchor="center")
# Création des champs de saisie
global username_entry
username_entry = ctk.CTkEntry(root, width=150)
username_entry.place(relx=0.75, rely=0.35, anchor="center")
global password_entry
password_entry = ctk.CTkEntry(root, width=150, show="*")
password_entry.place(relx=0.75, rely=0.65, anchor="center")
password_entry.bind("<Return>", lambda event: save_credentials())
# Création du bouton d'enregistrement
global save_button
save_button = ctk.CTkButton(root, text="Connexion", command=save_credentials)
save_button.place(relx=0.75, rely=0.83, anchor="center")
else:
if pronote_use_msg == "DNS Error":
print(f"{choice} ({true_city_name}) doesn't seem to use Pronote... See below\nWebsite {pronote_url} does not exists. {pronote_use_msg}")
box = CTkMessagebox(title="Aucun résultat", message="Votre établissement ne semble pas utiliser Pronote.", icon=warning_icon_path, option_1="Ok",master=root, width=350, height=10, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
root.config(cursor="arrow")
elif response != 202 and not pronote_use_msg:
api_response = {
"region": f"{region_name}",
"departement": f"{departement_code}",
"type": f"{school_type}"
}
check_important_file_existence(wanted_file_type="ent_data")
# Load the JSON file
with open(f"{script_directory}/Data/ent_data.json", 'r') as file:
data = json.load(file)
# Count the number of correspondences between the API response and each option except variable_name
correspondence_counts = {}
for option_key, option_value in data.items():
# Count correspondences for all options except variable_name
count = sum(api_response[arg] == option_value[arg] for arg in api_response.keys())
# Check if any of the departments match
option_departements = option_value["departement"]
if isinstance(option_departements, list):
departement_count = any(dept in api_response["departement"] for dept in option_departements)
else:
# Split the department string into individual codes
option_departements = option_departements.split(", ")
# Check if any of the individual departments match
departement_count = any(dept in api_response["departement"] for dept in option_departements)
type_match_lycee = False
if api_response["type"].startswith("LYCEE") and option_value["type"] == "LYCEE":
type_match_lycee = True
type_match_clg = False
if api_response["type"].startswith("COLLEGE"):
type_match_clg = True
correspondence_counts[option_key] = count + departement_count + type_match_lycee + type_match_clg
# Choose the option with the highest correspondence
chosen_option = max(correspondence_counts, key=correspondence_counts.get)
# Print the chosen option key and its associated variable_name
used_ent_name = data[chosen_option]["variable_name"]
# ENT Connexion
print(f"{choice} ({true_city_name}) uses Pronote (ENT Conexion: {used_ent_name}) !")
ent_connexion = True
choice_menu.place_forget()
root.config(cursor="arrow")
title_label.configure(text="Etape 3/4")
main_text.configure(text=f"Connectez vous à Pronote\nà l'aide de vos indentifiants.")
def adjust_text_size(event=None):
# Get the current text of the label
text = school_name_text.cget("text")
# Calculate the length of the text
text_length = len(text)
# Adjust font size based on text length
font_size = max(10, 12 - text_length // 10) # Adjust the formula as needed
# Update the font size of the label
school_name_text.configure(font=("Roboto", font_size))
school_name_text = ctk.CTkLabel(root, text=f"{choice}", font=(default_subtitle_font))
school_name_text.place(relx=0.23, rely=0.65, anchor="center")
# Bind the label to the adjust_text_size function
school_name_text.bind("<Configure>", adjust_text_size)
# Création des labels
username_label = ctk.CTkLabel(root, text="Identifiant", font=(default_subtitle_font)) #CHANGE ALL FONTS TO ROBOTO (BOLD)
username_label.place(relx=0.75, rely=0.23, anchor="center")
password_label = ctk.CTkLabel(root, text="Mot de passe", font=(default_subtitle_font))
password_label.place(relx=0.75, rely=0.53, anchor="center")
# Création des champs de saisie
username_entry = ctk.CTkEntry(root, width=150)
username_entry.place(relx=0.75, rely=0.35, anchor="center")
password_entry = ctk.CTkEntry(root, width=150, show="*")
password_entry.place(relx=0.75, rely=0.65, anchor="center")
# Création du bouton d'enregistrement
save_button = ctk.CTkButton(root, text="Connexion", command=save_credentials)
save_button.place(relx=0.75, rely=0.83, anchor="center")
else:
print(response)
print(f"Unknown error for {pronote_url}\nError detail : {pronote_use_msg}")
box = CTkMessagebox(title="Erreur", message="Une erreur inconnue est survenue.\nMerci de réessayer plus tard.", icon=cancel_icon_path, option_1="Ok",master=root, width=350, height=10, corner_radius=20,sound=True)
box.info._text_label.configure(wraplength=450)
title_label.configure(text="Etape 2/4")
main_text.configure(text="Selectionnez \nvotre établissement.")
# Create a StringVar to store the selected option
default_choice_menu_var = ctk.StringVar(value="Selectionnez votre établissement")
# Create the OptionMenu with dynamic width
choice_menu = ctk.CTkOptionMenu(root, width=175, dynamic_resizing=False, values=appellation_officielle_values, variable=default_choice_menu_var, command=optionmenu_callback)
choice_menu.place(relx=0.75, rely=0.4, anchor="center")
search_button.place_forget()
city_entry.place_forget()
root.config(cursor="arrow")
else:
# If the request was not successful, print an error message
print("Error:", response.status_code)
return []
# Create the main window