-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
2094 lines (1821 loc) · 99.1 KB
/
main.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
import threading
import time
import requests.exceptions
import google.auth.exceptions
import urllib3.exceptions
import re
from PIL import Image
import _tkinter
import os
import atexit
from tkinter import messagebox
import json
import darkdetect
import gspread
import sys
import webbrowser
import pyasn1.error
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import smtplib
from tkcalendar import Calendar
from datetime import datetime
from multiprocessing import Process
import subprocess
path = os.path.dirname(os.path.realpath(__file__))
with open(f"{path}/data.json", "r") as f:
data = json.load(f)
appearence_mode = data["appearence_mode"]
color_theme = data["color_theme"]
ctk.set_appearance_mode(appearence_mode)
ctk.set_default_color_theme(color_theme)
database = None
assetsPath = os.path.join(os.path.dirname(os.path.realpath(__file__)), "Assets")
current_version = "1.0"
class Sound:
def __init__(self, s):
self.s = s
def __str__(self):
return self.s
Default = Sound("ms-winsoundevent:Notification.Default")
Silent = Sound("silent")
def _run_ps(*, file='', command=''):
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
cmd = ["powershell.exe", "-ExecutionPolicy", "Bypass"]
if file and command:
raise ValueError
elif file:
cmd.extend(["-file", file])
elif command:
cmd.extend(['-Command', command])
else:
raise ValueError
subprocess.Popen(
cmd,
# stdin, stdout, and stderr have to be defined here, because windows tries to duplicate these if not null
stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, # set to null because we don't need the output :)
stderr=subprocess.DEVNULL,
startupinfo=si
)
TEMPLATE = r"""
[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] > $null
[Windows.UI.Notifications.ToastNotification, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null
[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null
$Template = @"
<toast {launch} duration="{duration}">
<visual>
<binding template="ToastImageAndText02">
<image id="1" src="{icon}" />
<text id="1"><![CDATA[{title}]]></text>
<text id="2"><![CDATA[{msg}]]></text>
</binding>
</visual>
<actions>
{actions}
</actions>
{audio}
</toast>
"@
$SerializedXml = New-Object Windows.Data.Xml.Dom.XmlDocument
$SerializedXml.LoadXml($Template)
$Toast = [Windows.UI.Notifications.ToastNotification]::new($SerializedXml)
$Toast.Tag = "{tag}"
$Toast.Group = "{group}"
$Notifier = [Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier("{app_id}")
$Notifier.Show($Toast);
"""
class Notification(object):
def __init__(self,
app_id: str,
title: str,
msg: str = "",
icon: str = "",
duration: str = 'short',
launch: str = ''):
"""
Construct a new notification
Args:
app_id: your app name, make it readable to your user. It can contain spaces, however special characters
(eg. é) are not supported.
title: The heading of the toast.
msg: The content/message of the toast.
icon: An optional path to an image to display on the left of the title & message.
Make sure the path is absolute.
duration: How long the toast should show up for (short/long), default is short.
launch: The url or callback to launch (invoked when the user clicks the notification)
Notes:
If you want to pass a callback to `launch` parameter,
please use `create_notification` from `Notifier` object
Raises:
ValueError: If the duration specified is not short or long
"""
self.app_id = app_id
self.title = title
self.msg = msg
self.icon = icon
self.duration = duration
self.launch = launch
self.audio = Silent
self.tag = self.title
self.group = self.app_id
self.actions = []
self.script = ""
if duration not in ("short", "long"):
raise ValueError("Duration is not 'short' or 'long'")
def set_audio(self, sound: Sound, loop: bool):
"""
Set the audio for the notification
Args:
sound: The audio to play when the notification is showing. Choose one from `winotify.audio` module,
(eg. audio.Default). The default for all notification is silent.
loop: If True, the audio will play indefinitely until user click or dismis the notification.
"""
self.audio = '<audio src="{}" loop="{}" />'.format(sound, str(loop).lower())
def show(self):
"""
Show the toast
"""
if self.actions:
self.actions = '\n'.join(self.actions)
else:
self.actions = ''
if self.audio == Silent:
self.audio = '<audio silent="true" />'
if self.launch:
self.launch = 'activationType="protocol" launch="{}"'.format(self.launch)
self.script = TEMPLATE.format(**self.__dict__)
_run_ps(command=self.script)
def edit_data(key, value):
with open(f"{path}/data.json", 'r') as f:
data = json.load(f)
data[key] = value
with open(f"{path}/data.json", 'w') as f:
json.dump(data, f, indent=4)
def get_creds() -> dict:
with open("creds.txt", 'r') as f:
content = f.read()
creds = ""
for c in content:
creds += chr(ord(c) - 2)
return json.loads(creds)
def create_spreadsheet() -> None:
scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
gc = gspread.service_account_from_dict(
get_creds(),
scopes=scopes
)
spreadsheet = gc.create("Rotary School Student Data")
spreadsheet.share('mr.pluto012@gmail.com', perm_type='user', role='writer')
sheet = spreadsheet.sheet1
sheet.resize(380000)
sheet.insert_row(["$Class$", "\"\""], 1)
sheet.insert_row(["$Pin$", "6789:"], 2)
sheet.insert_row(["Student ID", "Class-Roll", "Name", "Date of Birth", "Father's Name", "Father's Phone", "Mother's Name", "Mother's Phone", "Present Address", "Permanent Address"], 3)
def create_worksheet() -> None:
scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
gc = gspread.service_account_from_dict(
get_creds(),
scopes=scopes
)
spreadsheet = gc.open("Rotary School Student Data")
spreadsheet.add_worksheet("sheet1", 380000)
sheet = spreadsheet.sheet1
sheet.insert_row(["$Class$", "\"\""], 1)
sheet.insert_row(["$Pin$", "6789:"], 2)
sheet.insert_row(["Student ID", "Class-Roll", "Name", "Date of Birth", "Father's Name", "Father's Phone", "Mother's Name", "Mother's Phone", "Present Address", "Permanent Address"], 3)
def error_handler(func):
def wrapper(*args, **kwargs):
try:
result = func(*args, **kwargs)
return result
except requests.exceptions.ConnectionError:
if messagebox.showerror("Connection Lost!", "Connection was lost! Please check your Internet Connection and try again!"):
exit(0)
return wrapper
class Database():
def __init__(self) -> None:
scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
self.gc = gspread.service_account_from_dict(
get_creds(),
scopes=scopes
)
self.spreadsheet = self.gc.open("Rotary School Student Data")
self.sheet = self.spreadsheet.sheet1
@error_handler
def get_all(self) -> list:
return self.sheet.get()
@error_handler
def get_classes(self) -> str:
try:
f = self.sheet.find("$Class$")
except requests.exceptions.ConnectionError:
if messagebox.showerror("Connection Lost!", "Connection was lost! Please check your Internet Connection and try again!"):
exit(0)
value = self.sheet.cell(f.row, f.col + 1).value
value = value.replace("\"", "")
if value != '':
value = value.split(", ")
else:
value = []
return value
@error_handler
def get_all_sections(self, class_str: str) -> list:
try:
data = self.sheet.col_values(2)
except requests.exceptions.ConnectionError:
if messagebox.showerror("Connection Lost!", "Connection was lost! Please check your Internet Connection and try again!"):
exit(0)
data = data[data.index("Class-Roll") + 1:]
data = [i for i in data if i]
sections = []
for d in data:
if str(d).split("-")[0] == class_str:
if str(d).split("-")[1] not in sections:
sections.append(str(d).split("-")[1])
sections.sort()
return sections
@error_handler
def get_student_amount_by_class(self) -> dict:
try:
data = self.sheet.col_values(2)
except requests.exceptions.ConnectionError:
if messagebox.showerror("Connection Lost!", "Connection was lost! Please check your Internet Connection and try again!"):
exit(0)
data = data[data.index("Class-Roll") + 1:]
data = [i for i in data if i]
student_dict = {}
for d in data:
_class = str(d).split("-")[0]
if _class in student_dict:
student_dict[_class] += 1
else:
student_dict[_class] = 1
return student_dict
@error_handler
def get_student_amount_by_section(self, class_str: str) -> dict:
try:
data = self.sheet.col_values(2)
except requests.exceptions.ConnectionError:
if messagebox.showerror("Connection Lost!", "Connection was lost! Please check your Internet Connection and try again!"):
exit(0)
data = data[data.index("Class-Roll") + 1:]
data = [i for i in data if i]
filtered_data = []
for d in data:
if str(d).split("-")[0] == class_str:
filtered_data.append(d)
student_dict = {}
for d in filtered_data:
_section = str(d).split("-")[1]
if _section in student_dict:
student_dict[_section] += 1
else:
student_dict[_section] = 1
return student_dict
@error_handler
def get_all_students_amount(self) -> int:
try:
data = self.sheet.col_values(2)
except requests.exceptions.ConnectionError:
if messagebox.showerror("Connection Lost!", "Connection was lost! Please check your Internet Connection and try again!"):
exit(0)
data = data[data.index("Class-Roll") + 1:]
data = [i for i in data if i]
return len(data)
@error_handler
def add_class(self, class_str: str) -> None:
try:
f = self.sheet.find("$Class$")
except requests.exceptions.ConnectionError:
if messagebox.showerror("Connection Lost!", "Connection was lost! Please check your Internet Connection and try again!"):
exit(0)
value = self.sheet.cell(f.row, f.col + 1).value
value = value.replace("\"", "")
if value != '':
value = value.split(", ")
else:
value = []
value.append(class_str)
value = [int(val) for val in value]
value.sort()
value = [str(val) for val in value]
value = ", ".join(value)
self.sheet.update_cell(f.row, f.col + 1, f"\"{value}\"")
@error_handler
def get_all_student_data_by_class_and_section(self, class_str: str) -> dict:
_class = class_str.split("-")[0]
_section = class_str.split("-")[1]
try:
all_data = self.get_all()
except requests.exceptions.ConnectionError:
if messagebox.showerror("Connection Lost!", "Connection was lost! Please check your Internet Connection and try again!"):
exit(0)
all_data = all_data[3:]
all_data = [i for i in all_data if i]
all_class_students = []
for data in all_data:
if str(data[1]).split("-")[0] == _class and str(data[1]).split("-")[1] == _section:
all_class_students.append(data)
all_student_data = {}
for student in all_class_students:
student_data = {}
student_data['studentID'] = student[0]
student_data['name'] = student[2]
all_student_data[str(student[1]).split("-")[2]] = student_data
return all_student_data
@error_handler
def get_all_student_data(self) -> dict:
try:
all_data = self.get_all()
except requests.exceptions.ConnectionError:
if messagebox.showerror("Connection Lost!", "Connection was lost! Please check your Internet Connection and try again!"):
exit(0)
all_data = all_data[3:]
all_data = [i for i in all_data if i]
all_student_data = {}
for student in all_data:
student_data = {}
student_data['studentID'] = student[0]
student_data['name'] = student[2]
student_data["position"] = student[1]
all_student_data[str(student[1]).split("-")[2]] = student_data
return all_student_data
@error_handler
def get_student_data(self, position: str) -> dict:
try:
f = self.sheet.find(position)
except requests.exceptions.ConnectionError:
if messagebox.showerror("Connection Lost!", "Connection was lost! Please check your Internet Connection and try again!"):
exit(0)
data = self.sheet.row_values(f.row)
if len(data) < 10:
data.extend([''] * (10 - len(data)))
student_data = {}
student_data['studentID'] = data[0]
student_data['class'] = str(data[1]).split("-")[0]
student_data['roll'] = str(data[1]).split("-")[1]
student_data['name'] = data[2]
student_data['dob'] = data[3]
student_data['fathersName'] = data[4]
student_data['fathersPhone'] = str(data[5]).replace("\"", '')
student_data['mothersName'] = data[6]
student_data['mothersPhone'] = str(data[7]).replace("\"", '')
student_data['presentAddress'] = data[8]
student_data['permanentAddress'] = data[9]
student_data['paymentTimeline'] = data[10].replace("\"", "")
return data, student_data
@error_handler
def delete_class(self, class_str: str) -> None:
try:
f = self.sheet.find("$Class$")
except requests.exceptions.ConnectionError:
if messagebox.showerror("Connection Lost!", "Connection was lost! Please check your Internet Connection and try again!"):
exit(0)
value = self.sheet.cell(f.row, f.col + 1).value
value = value.replace("\"", "")
if value != None:
value = value.split(", ")
value.remove(class_str)
value = [int(val) for val in value]
value.sort()
value = [str(val) for val in value]
value = ", ".join(value)
self.sheet.update_cell(f.row, f.col + 1, f"\"{value}\"")
all_values = self.sheet.col_values(2)
all_values = all_values[all_values.index("Class-Roll") + 1:]
all_values = [i for i in all_values if i]
for value in all_values:
if str(value).split("-")[0] == class_str:
_find = self.sheet.find(value)
self.sheet.delete_rows(_find.row)
@error_handler
def delete_section(self, section_with_class: str) -> None:
class_str, section_str = section_with_class.split("-")[0], section_with_class.split("-")[1].lower()
all_values = self.sheet.col_values(2)
all_values = all_values[all_values.index("Class-Roll") + 1:]
all_values = [i for i in all_values if i]
for value in all_values:
if str(value).split("-")[0] == class_str and str(value).split("-")[1] == section_str:
_find = self.sheet.find(value)
self.sheet.delete_rows(_find.row)
@error_handler
def delete_student(self, class_position: str) -> None:
_find = self.sheet.find(class_position)
_class, _section, _roll = class_position.split("-")
rolls = self.get_rolls(_class, _section)
self.sheet.delete_rows(_find.row)
_last_roll_find = self.sheet.find(f"{_class}-{_section}-{str(rolls[-1])}")
correction_range = f"{_find.address}:{_last_roll_find.address}"
corrected_rolls = [[f"{_class}-{_section}-{roll}"] for roll in range(rolls[rolls.index(int(_roll))], rolls[-1])]
self.sheet.update(corrected_rolls, correction_range)
@error_handler
def get_pin(self) -> str:
_find = self.sheet.find("$Pin$")
return (self.sheet.cell(_find.row, _find.col + 1).value).replace("\"", '')
@error_handler
def get_rolls(self, class_str: str, section_str: str) -> list:
all_values = self.sheet.col_values(2)
all_values = all_values[all_values.index("Class-Roll") + 1:]
all_values = [i for i in all_values if i]
rolls = []
for data in all_values:
_class, _section, _roll = str(data).split("-")
if _class.lower() == class_str.lower() and _section.lower() == section_str.lower():
rolls.append(int(_roll))
rolls.sort()
return rolls
@error_handler
def get_all_student_ids(self) -> list:
all_ids = self.sheet.col_values(1)
all_ids = all_ids[all_ids.index("Student ID") + 1:]
all_ids = [int(i) for i in all_ids if i]
all_ids.sort()
return all_ids
@error_handler
def get_classes_have_data(self) -> list:
all_values = self.sheet.col_values(2)
all_values = all_values[all_values.index("Class-Roll") + 1:]
all_values = [i for i in all_values if i]
classes = []
for data in all_values:
_class, _, _ = str(data).split("-")
if int(_class) not in classes:
classes.append(int(_class))
classes.sort()
return classes
@error_handler
def add_student(self, student_id: str, class_section_roll: str, name: str, DoB: str, fathersname: str, fatherscontact: str, mothersname: str, motherscontact: str, presentaddress: str, permanentaddress: str) -> None:
data = [student_id, class_section_roll, name, DoB, fathersname, fatherscontact, mothersname, motherscontact, presentaddress, permanentaddress]
gclass, gsection, groll = str(class_section_roll).split("-")
classes_have_data = self.get_classes_have_data()
if classes_have_data:
if int(gclass) in classes_have_data:
sections = self.get_all_sections(gclass)
if str(gsection).lower() in sections:
rolls = self.get_rolls(gclass, str(gsection).lower())
last_roll = 0
for roll in rolls:
if roll < int(groll):
last_roll = roll
if last_roll == 0:
_rolls = rolls.copy()
_rolls.append(int(groll))
_rolls.sort()
next_roll = _rolls[_rolls.index(int(groll)) + 1]
_find = self.sheet.find(f"{gclass}-{gsection}-{next_roll}")
self.sheet.insert_row(data, _find.row)
else:
_find = self.sheet.find(f"{gclass}-{gsection}-{last_roll}")
self.sheet.insert_row(data, _find.row + 1)
else:
sections.append(gsection)
sections.sort()
last_section = ""
if sections.index(gsection) != 0:
last_section = sections[sections.index(gsection) - 1]
last_roll = self.get_rolls(gclass, last_section)[-1]
_find = self.sheet.find(f"{gclass}-{last_section}-{last_roll}")
self.sheet.insert_row(data, _find.row + 1)
else:
next_section = sections[sections.index(gsection)+1]
first_roll = self.get_rolls(gclass, next_section)[0]
_find = self.sheet.find(f"{gclass}-{next_section}-{first_roll}")
self.sheet.insert_row(data, _find.row)
else:
classes_have_data.append(int(gclass))
classes_have_data.sort()
if classes_have_data.index(int(gclass)) != 0:
last_class = classes_have_data[classes_have_data.index(int(gclass)) - 1]
last_section = self.get_all_sections(str(last_class))[-1]
last_roll = self.get_rolls(str(last_class), str(last_section))[-1]
_find = self.sheet.find(f"{last_class}-{last_section}-{last_roll}")
self.sheet.insert_row(data, _find.row + 1)
else:
next_class = classes_have_data[classes_have_data.index(int(gclass)) + 1]
first_section = self.get_all_sections(str(next_class))[0]
first_roll = self.get_rolls(str(next_class), first_section)[0]
_find = self.sheet.find(f"{next_class}-{first_section}-{first_roll}")
self.sheet.insert_row(data, _find.row)
else:
self.sheet.append_row(data)
@error_handler
def update_student(self, data) -> None:
class_section_roll = data[1]
_find = self.sheet.find(class_section_roll)
self.sheet.delete_rows(_find.row)
self.sheet.insert_row(data, _find.row)
@error_handler
def change_pin(self, new_pin) -> None:
pE = ""
for c in new_pin:
pE += chr(ord(c) + 5)
_find = self.sheet.find("$Pin$")
self.sheet.update_cell(_find.row, _find.col + 1, pE)
def splash():
global istypewrite
istypewrite = True
def typewrite(obj: ctk.CTkLabel):
global istypewrite
while istypewrite:
currentText = obj.cget("text")
if "Getting things ready" in currentText:
if "..." in currentText:
obj.configure(text=currentText.replace("...", ""))
else:
obj.configure(text=f"{currentText}.")
time.sleep(1)
win = ctk.CTk()
win.wm_overrideredirect(True)
win.wm_iconbitmap(f"{assetsPath}/Icon.ico")
win.title("Rotary School Student Manager")
positionRight = int(win.winfo_screenwidth()/2 - 650/2)
positionDown = int(win.winfo_screenheight()/2 - 400/2)
win.geometry(f"650x400+{positionRight}+{positionDown-50}")
pinFrame = ctk.CTkFrame(win, height=100, width=400, border_width=0, fg_color="transparent")
pinFrame.pack(anchor="center", side="bottom", pady=40)
pinFrame.pack_propagate(False)
loadingLabel = ctk.CTkLabel(pinFrame, text="Getting things ready", font=("Segoe UI", 15, "bold", "italic"))
loadingLabel.pack(anchor="center", side="bottom", pady=0)
mainLabel = ctk.CTkLabel(win, text="Rotary School Student Manager", font=("Segoe UI", 25, "bold"), justify="left")
mainLabel.pack(anchor="center", side="bottom")
logo = ctk.CTkLabel(win, text="", image=ctk.CTkImage(Image.open(os.path.join(assetsPath, "Logo Dark.png")), Image.open(os.path.join(assetsPath, "Logo Light.png")), (150, 150)))
logo.place(x=245, y=30)
threading.Thread(target=typewrite, args=(loadingLabel, ), daemon=True).start()
win.after(1500, lambda: dbloadWin(win))
win.after(150, win.focus_force)
win.mainloop()
def ReportErrorSequence(win: ctk.CTk, subject: str, type: str, filename: str, linenumber: str, message: str):
if messagebox.askyesno("Unexpected Error Raised!", "Rotary School Student Manager Software just hit an unexected error!\nWould you like to report it to the Developer, so that it can be solved as quickly as possible?"):
maildialog = ctk.CTkInputDialog(text="Enter your Email Address:", title="Error Report Sequence")
replymail = maildialog.get_input()
if replymail == "":
win.destroy()
return
email_data = MIMEMultipart('alternative')
email_data['From'] = "mr.pluto012@gmail.com"
email_data['To'] = "tahsin.ict@outlook.com"
email_data["Subject"] = subject
html_code = f"""\
<html><head>
</head>
<body>
<table width="100%" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:600px" align="center">
<tbody>
<tr>
<td role="modules-container" style="padding:0px 0px 0px 0px;color:#353740;text-align:left" bgcolor="#FFFFFF" width="100%" align="left">
<table class="m_6462241684133058065preheader" role="module" border="0" cellpadding="0" cellspacing="0" width="100%" style="display:none!important;opacity:0;color:transparent;height:0;width:0">
<tbody>
<tr>
<td role="module-content">
<p>Error on Rotary School Student Manager Software!</p>
</td>
</tr>
</tbody>
</table>
<center>
<img alt="Logo" src="https://github.com/Sayad-Uddin-Tahsin/Rotary-School-Student-Manager/blob/main/Assets/Logo%20Dark.png?raw=true" height="100" width="100" style="margin: 0; padding: 0;">
<p style="font-family:'Arial Black'; font-size: 20px;">Rotary School Student Manager</p>
</center>
<table role="module" border="0" cellpadding="0" cellspacing="0" width="100%" style="table-layout:fixed">
<tbody>
<tr>
<td style="padding:0px 24px 0px 24px" role="module-content" height="100%" valign="top" bgcolor="">
<table border="0" cellpadding="0" cellspacing="0" align="center" width="100%" height="1px" style="line-height:0px;font-size:0px">
<tbody>
<tr>
<td style="padding:0px 0px 0px 0px" bgcolor="#ECECF1"></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table role="module" border="0" cellpadding="0" cellspacing="0" width="100%" style="table-layout:fixed">
<tbody>
<tr>
<td style="padding:10px 24px 14px 24px;line-height:24px;text-align:inherit" height="100%" valign="top" bgcolor="" role="module-content">
<div>
<div style="font-family:inherit;text-align:inherit">
<span style="font-size:16px"><p><b>Error Type:</b> <code>{type}</code></p><p><b>Filename:</b> <code>{filename}</code></p><p><b>Line Number:</b> <code>{linenumber}</code></p><p><b>Error Message</b><br><code>{message}</code></p></span>
</div>
</div>
</td>
</tr>
</tbody>
</table>
<table role="module" border="0" cellpadding="0" cellspacing="0" width="100%" style="table-layout:fixed">
<tbody>
<tr>
<td bgcolor="" valign="top" height="100%" role="module-content" style="padding:0px 24px 15px 24px">
<table border="0" cellpadding="0" cellspacing="0" align="center" width="100%" height="1px" style="line-height:1px;font-size:1px">
<tbody>
<tr>
<td style="padding:0px 0px 1px 0px" bgcolor="#ECECF1"></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<div role="module" style="color:#8e8ea0;font-size:12px;line-height:20px;padding:0px 16px 0px 16px;text-align:center; font-family:'Courier New'">
<div>
<p style="font-family:inherit;font-size:12px;line-height:20px">From Rotary School Student Management Software</p>
</div>
</div>
<table role="module" border="0" cellpadding="0" cellspacing="0" width="100%" style="table-layout:fixed">
<tbody>
<tr>
<td style="padding:0px 0px 32px 0px" role="module-content" bgcolor=""></td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</body></html>
"""
html = MIMEText(html_code, 'html')
email_data.attach(html)
email_data.add_header('reply-to', replymail)
mail = smtplib.SMTP('smtp.gmail.com', 587)
mail.ehlo()
mail.starttls()
mail.login('mr.pluto012@gmail.com', 'gsuatadfkrflyjgh')
mail.sendmail(email_data['From'], "tahsin.ict@outlook.com", email_data.as_string())
mail.quit()
win.destroy()
def dbloadWin(window):
window.destroy()
global istypewrite
istypewrite = True
def move_to_main():
global istypewrite
istypewrite = False
win.overrideredirect(False)
win.after(0, lambda: main(win))
def typewrite(obj: ctk.CTkLabel):
global istypewrite
while istypewrite:
currentText = obj.cget("text")
if "Loading Database" in currentText:
if "..." in currentText:
obj.configure(text=currentText.replace("...", ""))
else:
obj.configure(text=f"{currentText}.")
elif "Retrying in" in currentText:
sec = int(re.search(r'\d+', currentText).group())
if sec != 1:
obj.configure(text=currentText.replace(str(sec), str(sec - 1)))
else:
obj.configure(text="Retrying to load Database...")
load_database()
time.sleep(1)
def move_to_pin():
win.attributes("-topmost", 1)
win.focus_force()
global istypewrite
def validate_entry(text, obj):
if text == "" or text.isdigit():
if len(text) > 1:
return False
else:
currentIndex = pin_entries.index(obj)
if text != "":
if currentIndex == len(pin_entries) - 1:
threading.Thread(target=is_pin_match(str(text)), daemon=True).start()
win.focus_force()
return True
else:
pin_entries[currentIndex + 1].configure(state="normal")
pin_entries[currentIndex + 1].focus_force()
else:
if currentIndex != 0:
pin_entries[currentIndex].configure(state="disabled")
pin_entries[currentIndex - 1].focus_force()
return True
else:
return False
def gen_pin_entries(bcolor: tuple = ("#979DA2", "#565B5E")):
pin_entries.clear()
last_x_pos = 0
for i in range(1, 6):
e = ctk.CTkEntry(pinFrame, width=30, height=35, font=("Consolas", 18), border_width=2, justify="center", border_color=bcolor)
if i != 1:
e.configure(state="disabled")
if i == 1:
e.focus_force()
e.configure(validate="key", validatecommand=(win.register(lambda text, obj=e: validate_entry(text, obj)), "%P"))
last_x_pos = i * 25
e.place(x=last_x_pos + i * 45, y=25)
pin_entries.append(e)
def is_pin_match(last_int: str):
pO = database.get_pin()
pE = [e.get() for e in pinFrame.winfo_children()]
pE.insert(-1, last_int)
pE = ''.join([e for e in pE if e])
pEE = ""
for c in pE:
pEE += chr(ord(c) + 5)
if pO == pEE:
for e in pinFrame.winfo_children():
e.configure(border_color=("#90ee90", "#154734"))
move_to_main()
else:
for e in pinFrame.winfo_children():
e.destroy()
win.bell()
threading.Thread(target=gen_pin_entries, args=(("#FF0000", "#8B0000"), ), daemon=True).start()
istypewrite = False
win.resizable(0, 0)
win.overrideredirect(False)
loadingLabel.configure(text="")
loadingLabel.destroy()
pin_entries = []
threading.Thread(target=gen_pin_entries, daemon=True).start()
def load_database():
global database, istypewrite
done = False
try:
database = Database()
done = True
except (google.auth.exceptions.TransportError, requests.exceptions.ConnectionError, urllib3.exceptions.MaxRetryError, urllib3.exceptions.NewConnectionError) as e:
loadingLabel.configure(text=f"Loading Failed, No Internet Connection! Retrying in 5")
except google.auth.exceptions.RefreshError as e:
loadingLabel.configure(text=f"Loading Failed, Computer time is incorrect! Retrying in 5")
except gspread.exceptions.SpreadsheetNotFound:
create_spreadsheet()
load_database()
except gspread.exceptions.WorksheetNotFound:
create_worksheet()
load_database()
except gspread.exceptions.GSpreadException as e:
istypewrite = False
win.bell()
e_type, e_object, e_traceback = sys.exc_info()
e_filename = os.path.split(
e_traceback.tb_frame.f_code.co_filename
)[1]
e_message = str(e)
e_line_number = e_traceback.tb_lineno
ReportErrorSequence(win, "Unexpected Error on Rotary School Student Manager", e_type, e_filename, e_line_number, e_message)
except pyasn1.error.PyAsn1Error:
loadingLabel.configure(text=f"Database Credentials Error!")
if messagebox.askyesno("Credentials Error", "Credentials error usually raised when the Database credentials are not correct! Please contact with the Developer!\nDo you want to send him Mail?"):
webbrowser.open("mailto:tahsin.ict@outlook.com?subject=Credendials Error on Rotary School Student Manager&body=%0A%0ARedirected from Rotary School Student Manager Software")
except FileNotFoundError as e:
if str(e) == "[Errno 2] No such file or directory: 'creds.txt'":
loadingLabel.configure(text=f"Database Credentials Not Found!")
loadingLabel.configure(text=f"Database Credentials Not Found!")
loadingLabel.configure(text=f"Database Credentials Not Found!")
except Exception as e:
istypewrite = False
win.bell()
e_type, e_object, e_traceback = sys.exc_info()
e_filename = os.path.split(
e_traceback.tb_frame.f_code.co_filename
)[1]
e_message = str(e)
e_line_number = e_traceback.tb_lineno
ReportErrorSequence(win, "Unexpected Error on Rotary School Student Manager", e_type, e_filename, e_line_number, e_message)
if done:
move_to_pin()
win = ctk.CTk()
win.wm_iconbitmap(f"{assetsPath}/Icon.ico")
win.title("Rotary School Student Manager")
positionRight = int(win.winfo_screenwidth()/2 - 650/2)
positionDown = int(win.winfo_screenheight()/2 - 400/2)
win.geometry(f"650x400+{positionRight}+{positionDown-50}")
win.resizable(0, 0)
aboutLabel = ctk.CTkLabel(win, text="Developer", font=("Consolas", 12))
aboutLabel.pack(anchor="e", side="bottom", padx=10)
aboutLabel.bind("<Enter>", lambda e: aboutLabel.configure(cursor="hand2", font=("Consolas", 12, 'underline')))
aboutLabel.bind("<Leave>", lambda e: aboutLabel.configure(cursor="", font=("Consolas", 12)))
aboutLabel.bind("<Button-1>", lambda e: about())
pinFrame = ctk.CTkFrame(win, height=100, width=450, border_width=0, fg_color="transparent")
pinFrame.pack(anchor="center", side="bottom", pady=25)
pinFrame.pack_propagate(False)
loadingLabel = ctk.CTkLabel(pinFrame, text="Loading Database", font=("Segoe UI", 15, "bold", "italic"))
loadingLabel.pack(anchor="center", side="bottom", pady=0)
mainLabel = ctk.CTkLabel(win, text="Rotary School Student Manager", font=("Segoe UI", 25, "bold"), justify="left")
mainLabel.pack(anchor="center", side="bottom")
logo = ctk.CTkLabel(win, text="", image=ctk.CTkImage(Image.open(os.path.join(assetsPath, "Logo Dark.png")), Image.open(os.path.join(assetsPath, "Logo Light.png")), (150, 150)))
logo.place(x=245, y=30)
threading.Thread(target=typewrite, args=(loadingLabel, ), daemon=True).start()
threading.Thread(target=load_database, daemon=True).start()
win.focus_force()
win.mainloop()
def about():
root = ctk.CTkToplevel()
root.geometry(f"650x400")
root.title("Rotary School Student Manager")
root.resizable(0, 0)
root.wm_iconbitmap(f"{assetsPath}/Icon.ico")
aboutLabel = ctk.CTkLabel(root, text=f"About", font=("Segoe UI", 30, 'bold'))
aboutLabel.place(x=10, y=10)
descriptionLabel = ctk.CTkLabel(root, text="Rotary School Student Manager is a Software made for Rotary School Khulna for organizing the Student Information in a Digital Way!", font=("Segoe UI", 13), wraplength=600, justify="left")
descriptionLabel.place(x=10, y=60)
sourceLabel = ctk.CTkLabel(root, text=f"Software Source Code is available at: ", font=("Seoge UI", 12, "bold"))
sourceLabel.place(x=10, y=100)
sourceHyperLabel = ctk.CTkLabel(root, text="GitHub: Sayad-Uddin-Tahsin/Rotary-School-Student-Manager", font=("Seoge UI", 12, "underline"), text_color="#0078D7")
sourceHyperLabel.place(x=225, y=100)
sourceHyperLabel.bind("<Enter>", lambda e: sourceHyperLabel.configure(cursor="hand2"))
sourceHyperLabel.bind("<Leave>", lambda e: sourceHyperLabel.configure(cursor=""))
sourceHyperLabel.bind("<Button-1>", lambda e: webbrowser.open("https://github.com/Sayad-Uddin-Tahsin/Rotary-School-Student-Manager"))
devFrame = ctk.CTkFrame(root, width=450, height=200, corner_radius=6, border_width=1, fg_color="transparent")
devFrame.place(x=100, y=140)
imageLabel = ctk.CTkLabel(devFrame, text="", image=ctk.CTkImage(Image.open(os.path.join(assetsPath, "Tahsin.png")), Image.open(os.path.join(assetsPath, "Tahsin.png")), (50, 50)))
imageLabel.place(x=30, y=10)
ctk.CTkLabel(devFrame, text="Mohammad Sayad Uddin Tahsin", font=("Arial Black", 18, "bold")).place(x=90, y=10)
ctk.CTkLabel(devFrame, text="Developer of Rotary School Student Manager", font=("Segoe UI", 14, 'bold')).place(x=90, y=35)
text = """
This is Sayad Uddin Tahsin, a student of class 8 (2023) of Rotary School, Khulna. I have a passion for software development and technology. This software is a product of my dedication and interest in creating solutions through code. \nI hope you find it useful and enjoy using it.
"""
ctk.CTkLabel(devFrame, text=text, font=("Segoe UI", 13), wraplength=450, justify="left").place(x=10, y=60)
ctk.CTkLabel(devFrame, text="For any query, please reach me at:", font=("Segoe UI", 13)).place(x=10, y=165)
mailLabel = ctk.CTkLabel(devFrame, text="Email: tahsin.ict@outlook.com", font=("Segoe UI", 13, 'underline'), text_color="#0078D7")
mailLabel.place(x=215, y=165)
mailLabel.bind("<Enter>", lambda e: mailLabel.configure(cursor="hand2"))
mailLabel.bind("<Leave>", lambda e: mailLabel.configure(cursor=""))
mailLabel.bind("<Button-1>", lambda e: webbrowser.open("mailto:tahsin.ict@outlook.com?subject=Query about Rotary School Student Manager&body=\n\n\nRedirected from Rotary School Student Manager Software"))
versionLabel = ctk.CTkLabel(root, text=f"Rotary School Student Manager v{current_version} is running on your computer.", font=("Seoge UI", 15, "bold"))
versionLabel.place(x=10, y=360)
root.after(100, root.lift)
root.mainloop()
def searcher(win: ctk.CTk, text: str = None):
global all_student_data
win.destroy()
root = ctk.CTk()
positionRight = int(root.winfo_screenwidth()/2 - 650/2)
positionDown = int(root.winfo_screenheight()/2 - 400/2)
root.geometry(f"650x400+{positionRight}+{positionDown-50}")
root.title("Rotary School Student Manager")
root.resizable(0, 0)
root.wm_iconbitmap(f"{assetsPath}/Icon.ico")
aboutLabel = ctk.CTkLabel(root, text="Rotary School Student Manager", font=("Consolas", 12))
aboutLabel.pack(anchor="se", side="bottom", padx=10)
aboutLabel.bind("<Enter>", lambda e: aboutLabel.configure(cursor="hand2", font=("Consolas", 12, 'underline')))
aboutLabel.bind("<Leave>", lambda e: aboutLabel.configure(cursor="", font=("Consolas", 12)))
aboutLabel.bind("<Button-1>", lambda e: about())
Title = ctk.CTkLabel(root, text=f"Find Student", font=("Segoe UI", 30, 'bold'))
Title.pack(padx=10, pady=22, anchor="nw", side="left")
def search():
global all_student_data
text = searchEntry.get()
matched = []
if searchFilter.get() == "Name":
for d in all_student_data:
if text.lower() in all_student_data[d]['name'].lower():
matched.append(d)
elif searchFilter.get() == "Student ID":
for d in all_student_data: