-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
executable file
·1723 lines (1580 loc) · 68.5 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
#!/usr/bin/env python3
version = "GTM.1.3.8"
#region ASCII ART
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# _ _ _ __ _ _ #
# | | | | (_) / / | | | | #
# __ _ ___| |_| |_ _ _ __ ___ ___ / /__ ___ __| |___ ___| |__ ___ _ __ ___ __ _ #
# / _` |/ _ \ __| __| | '_ ` _ \ / _ \ / / __|/ _ \ / _` / __|/ __| '_ \ / _ \ '_ ` _ \ / _` | #
# | (_| | __/ |_| |_| | | | | | | __// /\__ \ (_) | (_| \__ \ (__| | | | __/ | | | | | (_| | #
# \__, |\___|\__|\__|_|_| |_| |_|\___/_/ |___/\___/ \__,_|___/\___|_| |_|\___|_| |_| |_|\__,_| #
# __/ | #
# |___/ #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# #
# Original Idea by PierreLeFevre (https://github.com/PierreLeFevre) #
# Sodschema Sourcecode by PierreLeFevre (https://github.com/PierreLeFevre/sodschema) #
# GetTime Classic was made by TayIsAsleep (https://github.com/TayIsAsleep) #
# Sodschema reboot made possible by Koala (https://github.com/KoalaV2) #
# #
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#endregion
#region IMPORT
import os
import time
import json
import base64
import logging
import hashlib
import datetime
import requests
import traceback
import threading
import feedparser
import tinynumpy as np
from functools import lru_cache
from urllib.parse import urlencode
from operator import attrgetter
from flask import Flask
from flask import Markup
from flask import jsonify
from flask import request
from flask import redirect
from flask import render_template
from flask import send_from_directory
from flask_cors import CORS
from flask_minify import minify
from flask_mobility import Mobility
from werkzeug.routing import Rule
from werkzeug.exceptions import NotFound
from waitress import serve
from bs4 import BeautifulSoup
#endregion
#region FUNCTIONS
def searchInDict(listInput, keyInput, valueInput):
#Code from https://stackoverflow.com/a/8653568
a = enumerate(listInput)
for x, y in a:
if y[keyInput] == valueInput:
return x
return None
# @lru_cache(maxsize=32)
# def getSchoolByID(schoolID):
# """
# Returns `True, {school data}` if `schoolID` was an int\n
# Returns `False, {school data}` if `schoolID` was an string, and if it existed in the school list\n
# Returns `None, None` if `schoolID` was not in the school list at all.
# """
# global allSchools, allSchoolsList
# try:
# b = searchInDict(allSchoolsList,'id',int(schoolID))
# try:
# return True, allSchools[allSchoolsList[b]['unitId']]
# except Exception as e:
# return None,None,-1,str(e)
# except Exception as e:
# try:
# # Tests if schoolID was just the school name
# return False, allSchools[schoolID]
# except:
# return None,None,-2,str(e)
def SetLogging(path="", filename="log.log", format=None): # '%(asctime)s %(levelname)s %(name)s %(threadName)s : %(message)s'
"""
Changes logging settings.
"""
if format == None:
format = configfile['loggingFormat']
try:os.mkdir(path)
except:pass
open(path+filename, 'w').close() # Clear Logfile
log = logging.getLogger() # root logger
for hdlr in log.handlers[:]: # remove all old handlers
log.removeHandler(hdlr)
a = logging.FileHandler(path+filename, 'r+', encoding="utf-8")
a.setFormatter(logging.Formatter(format))
log.addHandler(a)
def CurrentTime():
"""
Returns a dictionary with the current time in many different formats.
Returns:
dict: (secound, minute, hour, day, week, week2, month, year, weekday, weekday2, datestamp, dayNames)\n
'weekday2' returns 1-5, but 0 if its Saturday or Sunday.\n
'week2' returns the current week, but if its Saturday or Sunday, it returns the next week.\n
"""
now = datetime.datetime.now()
a = {
'secound':now.second,
'minute':now.minute,
'hour':now.hour,
'day':now.day,
'month':now.month,
'year':now.year,
'week':datetime.date.today().isocalendar()[1],
'weekday':now.isoweekday(),
'datestamp':datetime.datetime.today().strftime('%Y-%m-%d-%H-%M-%S'),
'dayNames':("måndag", "tisdag", "onsdag", "torsdag", "fredag", "lördag", "söndag")
}
isSundayOrSaturday = True if a['weekday'] in (6,7) else False
a['weekday2'] = 0 if isSundayOrSaturday else a['weekday']
a['weekday3'] = 1 if isSundayOrSaturday else a['weekday']
a['week2'] = a['week'] + (1 if isSundayOrSaturday else 0)
a['timeScore'] = (a['hour'] * 60) + a['minute']
return a
def TinyUrlShortener(url, alias="") -> str:
return requests.get(f"https://www.tinyurl.com/api-create.php?{urlencode({'url':url,'alias':alias})}").text
@lru_cache(maxsize=32)
def EncodeString(key, clear):
# Code from https://stackoverflow.com/a/16321853
enc = []
for i in range(len(clear)):
key_c = key[i % len(key)]
enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc).encode()).decode()
@lru_cache(maxsize=32)
def DecodeString(key, enc):
# Code from https://stackoverflow.com/a/16321853
dec = []
enc = base64.urlsafe_b64decode(enc).decode()
for i in range(len(enc)):
key_c = key[i % len(key)]
dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
dec.append(dec_c)
return "".join(dec)
@lru_cache(maxsize=32)
def GenerateHiddenURL(key, idInput, schoolInput, mainLink):
a = EncodeString(key,idInput + "½" + str(schoolInput))
return mainLink + f"?a={a}",a
@lru_cache(maxsize=32)
def sha256(hash_string):
# Code from https://tinyurl.com/2k3ds62p
return hashlib.sha256(hash_string.encode()).hexdigest()
def arg01_to_bool(args, argName):
"""
This function takes {request.args} and check if the argName is 1 or 0.\n
If argName is "1", it returns True.\n
If argname is "0", it returns False.\n
And if it is anything else, or if it does not exist, it returns False aswell.
"""
if str(argName) in args:
if str(args[str(argName)]) == "1":
return True
if str(args[str(argName)]) == "0":
return False
return False
def getFood(allowCache=True, week=None):
t = CurrentTime()
week = week if week != None else t['week']
myHash = sha256(f"{week}{t['week']}")
if allowCache and myHash in dataCache and time.time() - dataCache[myHash]['age'] < dataCache[myHash]['maxage']:
toReturn = dataCache[myHash]['data']
else:
NewsFeed = feedparser.parse("https://skolmaten.se/nti-gymnasiet-sodertorn/rss/weeks/?offset=" + str(week - t['week']))
toReturn = {"data":{"food":[],"week":week if week != None else t['week']}}
for x in range(5):
try:
post = NewsFeed.entries[x]
temp = post.summary.split("<br />") # This might break in the future
toReturn['data']['food'].append({'regular':temp[0],'veg':temp[1]})
toReturn['data']['week'] = int(post.title.split(" ")[3]) # This might break in the future
except:pass
if allowCache:
dataCache[myHash] = {'maxage':configfile['getFoodMaxAge'],'age':time.time(),'data':toReturn}
return toReturn
@lru_cache(maxsize=32)
def color_convert(color, reverse=False):
if reverse:
if color[1] == "hex":
return '#%02x%02x%02x' % color[0] # Code from https://stackoverflow.com/a/3380739
if color[1] == "rgb":
return color[0]
if color[1] == "rgb_L":
return list(color[0])
if type(color) == str: # Assuming its HEX
typeToReturn = "hex"
if color.startswith("#"):
color = color.lstrip('#')
color = tuple(int(color[i:i+2], 16) for i in (0, 2, 4)) # Code from https://stackoverflow.com/a/29643643
elif type(color) == list and len(color) == 3: # Assuming its RGB, but as a list
typeToReturn = "rgb_L"
color = tuple(color)
elif type(color) == tuple and len(color) == 3: # Assuming its RGB in the right format
typeToReturn = "rgb"
return color,typeToReturn
@lru_cache(maxsize=32)
def fadeColor(color, percent):
"""
if `0 > percent >= -1` then it fades to black.\n
if `1 > percent >= 0` then it fades to white.
"""
color,typeToReturn = color_convert(color)
# Code from https://stackoverflow.com/a/28033054
color = np.array(color)
x = color + (np.array([0,0,0] if percent < 0 else [255,255,255]) - color) * (percent if percent > 1 else percent * -1)
x = (round(x[0]) if x[0] > 0 else 0 ,round(x[1]) if x[1] > 0 else 0 ,round(x[2]) if x[2] > 0 else 0 )
return color_convert((color,typeToReturn),reverse=True)
@lru_cache(maxsize=32)
def grayscale(color):
color,typeToReturn = color_convert(color)
x = int(sum(color) / 3)
color = (x,x,x)
return color_convert((color,typeToReturn),reverse=True)
@lru_cache(maxsize=32)
def invertColor(color):
color,typeToReturn = color_convert(color)
color = (255-color[0],255-color[1],255-color[2])
return color_convert((color,typeToReturn),reverse=True)
def global_time_argument_handler(request, handle_overflow=True):
"""
Handles all time related arguments.
This function handles date overflow (if week is 53, it sets the
week to 1 and adds one year instead)
It also handles offset operators (`<` and `>`)
Takes:
`request` object
Returns:
`dict` object with `initDayMode`, `initWeek`, `initYear` and `initDay`
"""
t = CurrentTime()
initDayMode = None
initDayModeWasForced = False
initWeek = t['week2']
initYear = t['year']
initDay = t['weekday3']
initDateWasSet = False
initDateActualWeekday = None
if 'day' in request.args:
if request.args['day'].startswith(">"):
try:
initDay = t['weekday3'] + int(request.args['day'][1:])
initDayMode = True
except:pass
elif request.args['day'].startswith("<"):
try:
initDay = t['weekday3'] - int(request.args['day'][1:])
initDayMode = True
except:pass
else:
try:
initDay = int(request.args['day'])
initDayMode = True
except:pass
if 'week' in request.args:
if request.args['week'].startswith(">"):
try:initWeek = t['week'] + int(request.args['week'][1:])
except:pass
elif request.args['week'].startswith("<"):
try:initWeek = t['week'] - int(request.args['week'][1:])
except:pass
else:
try:initWeek = int(request.args['week'])
except:pass
if 'year' in request.args:
if request.args['year'].startswith(">"):
try:initYear = t['year'] + int(request.args['year'][1:])
except:pass
elif request.args['year'].startswith("<"):
try:initYear = t['year'] - int(request.args['year'][1:])
except:pass
else:
try:initYear = int(request.args['year'])
except:pass
if 'date' in request.args:
initDateWasSet = True
try:
if request.args['date'].count("-") == 0:
d = datetime.datetime.strptime(f"{request.args['date']}-{t['month']}-{t['year']}", '%d-%m-%Y')
elif request.args['date'].count("-") == 1:
d = datetime.datetime.strptime(f"{request.args['date']}-{t['year']}", '%d-%m-%Y')
elif request.args['date'].count("-") == 2:
d = datetime.datetime.strptime(request.args['date'], '%d-%m-%Y')
initDayMode = True
initDay = d.weekday() + 1
initDateActualWeekday = d.weekday() + 1
except:
d = datetime.datetime.strptime(request.args['date'], '%Y-%m')
initYear = d.year
initWeek = d.isocalendar()[1]
if 'daymode' in request.args:
initDayMode = arg01_to_bool(request.args,"daymode")
initDayModeWasForced = True
# Fix values
if handle_overflow:
while initDay > 5:
initDay -= 5
initWeek += 1
while initDay < 0:
initDay += 5
initWeek -= 1
while initWeek < 0:
initYear -= 1
initWeek += 52
while initWeek > 52:
initYear += 1
initWeek -= 52
return{
"initDayMode": initDayMode,
"initDayModeWasForced":initDayModeWasForced, # Is true if 'daymode' was specified in the URL (gets prio over everything)
"initWeek": initWeek,
"initYear": initYear,
"initDay": initDay,
"initDateWasSet":initDateWasSet, # Is true if a date was specified
"initDateActualWeekday":initDateActualWeekday
}
#endregion
#region CLASSES
class HTMLObject:
def __init__(self, tag, arguments):
self.tag = tag
self.arguments = arguments
def render(self):
a = ' '.join((f'{key}="{str(self.arguments[key])}"' if key != 'innerHTML' else "") for key in self.arguments)
b = "" if not 'innerHTML' in self.arguments else self.arguments['innerHTML']
return f"<{self.tag} {a}>{b}</{self.tag}>"
class Lesson:
def __init__(self, lessonName=None, teacherName=None, classroomName=None, timeStart=None, timeEnd=None, insertDict=None) -> None:
if insertDict != None:
self.lessonName = insertDict['lessonName']
self.teacherName = insertDict['teacherName']
self.classroomName = insertDict['classroomName']
self.timeStart = insertDict['timeStart']
self.timeEnd = insertDict['timeEnd']
else:
self.lessonName = lessonName
self.teacherName = teacherName
self.classroomName = classroomName
self.timeStart = timeStart
self.timeEnd = timeEnd
@lru_cache(maxsize=32)
def GetTimeScore(self, start=True, end=False):
if end == True:start = False
#KNOWN ISSUE:
#If time is 23:00, and you try and get timescore for a lesson that starts 01:00 the next day, it will not return 2 hours
#This is because timescore does not care about dates, only hours and minutes
secounds = sum(x * int(t) for x, t in zip([1, 60, 3600], reversed((self.timeStart if start else self.timeEnd).split(":"))))
return int(secounds / 60)
class GetTime:
"""
GetTime Request object.
Once created, it can generate alot of information. (HTML schedule, Text schedule, Food, ect)
"""
t = CurrentTime()
def __init__(self, _id=None, _week=t['week2'], _day=t['weekday2'], _year=t['year'], _resolution=(1280,720), _school='IT-Gymnasiet Södertörn') -> None:
self._id = _id
self._week = _week
self._day = _day
self._year = _year
self._resolution = _resolution
self._s = requests.Session()
self._s.headers.update({
"X-Scope": "8a22163c-8662-4535-9050-bc5e1923df48",
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "application/json",
})
# try:
# If user has entered the school ID instead, then this converts it back to the name
# (SHOULD BE THE OTHER WAY AROUND BUT THAT WILL TAKE SOME MORE TIME TO FIX)
# int(_school)
# self._school = getSchoolByID(_school)[1]['unitId']
# except:
self._school = _school
def getHash(self) -> str:
"""
Generates a sha256 hash of all the settings of this object.
Usefull to figure out if we can use cache or not (If getHash() is the same, then the data inside is the same aswell)
Returns:
str: SHA256 hash
"""
return sha256("".join([str(x) for x in (self._id,self._week,self._day,self._year,self._resolution,self._school)]))
def getData(self, allowCache=True) -> dict:
"""
This function makes a request to Skola24's servers and returns the schedule data
\n
Takes:
None
Returns:
<JSON> object with the data inside
"""
if self._id == None:
logging.info("Returning None because _id was None")
return {"status":-7,"message":"_id was None (No ID specified)","data":None} # If ID is not set then it returns None by default
# Default values
response1 = ""
response2 = ""
response3 = ""
myHash = self.getHash()
if allowCache and myHash in dataCache and time.time() - dataCache[myHash]['age'] < dataCache[myHash]['maxage']:
logging.info("Using cache!")
toReturn = dataCache[myHash]['data']
else:
try:
#region Request 1
logging.info("Request 1")
url1 = 'https://web.skola24.se/api/encrypt/signature'
try:
response1 = self._s.post(url1, data=json.dumps({"signature":self._id}))
except TimeoutError:
return {"status":-9,"message":"Response 1 Error (TimeoutError)","data":""}
except Exception:
return {"status":-10,"message":"Response 1 Error (Other)","data":traceback.format_exc()}
try:
response1 = json.loads(response1.text)['data']['signature']
except Exception as e:
logging.info(f"Response 1 Error : {str(e)}")
if "Our service is down for maintenance. We apologize for any inconvenience this may cause." in response1.text or "The service is unavailable." in response1.text:
return {"status":-69.1,"message":f"Skola24 is currently down for maintenance (Request 1)","data":response1.text}
return {"status":-2,"message":f"Response 1 Error : {str(e)}","data":str(response1)}
#endregion
#region Request 2
logging.info("Request 2")
url2 = 'https://web.skola24.se/api/get/timetable/render/key'
response2 = self._s.post(url2, data="null")
try:
response2 = json.loads(response2.text)['data']['key']
except TimeoutError:
return {"status":-11,"message":"Response 2 Error (TimeoutError)","data":""}
except Exception as e:
logging.info(f"Response 2 Error : {str(e)}")
if "The service is unavailable." in response2.text:
return {"status":-69.2,"message":f"Skola24 is currently down for maintenance (Request 2)","data":response2.text}
return {"status":-3,"message":f"Response 2 Error : {str(e)}","data":str(response2)}
#endregion
#region Request 3
logging.info("Request 3")
url3 = 'https://web.skola24.se/api/render/timetable'
payload3 = {
"renderKey":response2,
"host": allSchools[self._school]['hostName'],
"unitGuid": allSchools[self._school]['unitGuid'],
"scheduleDay":int(self._day),
"width":int(self._resolution[0]),
"height":int(self._resolution[1]),
"selectionType":4,
"selection":response1,
"week":int(self._week),
"year":int(self._year),
}
response3 = self._s.post(url3, data=json.dumps(payload3))
try:response3 = json.loads(response3.text)
except TimeoutError:
return {"status":-12,"message":"Response 3 Error (TimeoutError)","data":""}
except Exception as e:
logging.info(f"Response 3 Error : {str(e)}")
return {"status":-4,"message":f"Response 3 Error : {str(e)}","data":str(response3)}
#endregion
toReturn = {"status":0,"message":"OK","data":response3}
except Exception as e:
toReturn = {"status":-99,"message":"GENERAL ERROR","data":traceback.format_exc()}
logging.info(str(toReturn))
return toReturn
logging.info("Request 3 is finished. Will now check for errors")
#Error Checking
if response1 == "":
return {"status":-30.1,"message":"response1 was empty","data":None}
if response2 == "":
return {"status":-30.2,"message":"response2 was empty","data":None}
if response3 == "":
return {"status":-30.3,"message":"response3 was empty","data":None}
try:
if response3['error'] != None:
return {'status':-5,'message':"error was not None","data":response3}
if len(response3['validation']) > 0:
return {'status':-6,'message':','.join([x['message'] for x in response3['validation']]),"data":response3,"validation":response3['validation']}
except:
return {'status':-8,'message':f"An error occured when trying to check for other errors! (Yes, really.) Here is the traceback : {traceback.format_exc()}","data":response3}
if allowCache:
dataCache[myHash] = {'maxage':configfile['getDataMaxAge'],'age':time.time(),'data':toReturn}
return toReturn
def getMoreData(self, allowCache=True) -> dict:
# myHash = self.getHash()
# if allowCache and myHash in dataCache and time.time() - dataCache[myHash]['age'] < dataCache[myHash]['maxage']:
# logging.info("Using cache!")
# toReturn = dataCache[myHash]['data']
# else:
# pass
toReturn = {
"data": {
"classes": [],
"courses": [],
"groups": [],
"periods": [],
"rooms": [],
"students": [],
"subjects": [],
"teachers": []
},
"error": None,
"exception": None,
"validation": []
}
if self._school in allSchools:
try:
headers = {
'X-Scope': '8a22163c-8662-4535-9050-bc5e1923df48',
'X-Requested-With': 'XMLHttpRequest',
}
data = '''{
"hostName":"%s",
"unitGuid":"%s",
"filters":{
"class":true,
"course":true,
"group":true,
"period":true,
"room":true,
"student":true,
"subject":true,
"teacher":true
}
}''' % (
allSchools[self._school]['hostName'],
allSchools[self._school]['unitGuid']
)
response = self._s.post('https://web.skola24.se/api/get/timetable/selection', headers=headers, data=data)
try:
toReturn = response.json()
except:
toReturn['error'] = 'BAD DATA'
toReturn['traceback'] = traceback.format_exc()
toReturn['BAD_DATA'] = response.text
except:
toReturn['error'] = 'Other Error'
toReturn['traceback'] = traceback.format_exc()
else:
toReturn['error'] = f'"{self._school}" is not a valid school ID'
if "overwriteOtherData" in allSchools[self._school]:
overwriteData = allSchools[self._school]["overwriteOtherData"]['data']
for key in overwriteData:
for x in overwriteData[key]:
toReturn["data"][key].append(x)
return toReturn
def fetch(self, allowCache=True) -> list:
"""
Fetches and formats data into <lesson> objects.
\n
Takes:
None
Returns:
List with <lesson> objects
"""
toReturn = []
response = self.getData(allowCache=allowCache)
if response['status'] < 0:
logging.info('ERROR!',response)
return response
try:
if response['data']['data']['lessonInfo'] == None:
return [] # No lessions this day
except Exception as e:
logging.info(f"Before i die! : {str(response)}")
raise e
for x in response['data']['data']['lessonInfo']:
try:
currentLesson = Lesson()
try:currentLesson.lessonName=x['texts'][0]
except:pass
try:currentLesson.teacherName=x['texts'][1]
except:pass
try:currentLesson.timeStart=x['timeStart']
except:pass
try:currentLesson.timeEnd=x['timeEnd']
except:pass
#Sometimes the classroomName is absent
try:currentLesson.classroomName = x['texts'][2]
except:currentLesson.classroomName = ""
if currentLesson.classroomName == "":
currentLesson.classroomName = None
toReturn.append(currentLesson)
except:pass
toReturn.sort(key=attrgetter('timeStart'))
return toReturn
def handleHTML(self, classes="", privateID=False, allowCache=True, darkMode=False, darkModeSetting=1, isMobile=False) -> dict:
"""
Fetches and converts the <JSON> data into a SVG (for sending to HTML)
\n
Takes:
classes (optional) (add custom classes to the SVG)
Returns:
{'html':(SVG HTML CODE),'timestamp':timeStamp}
"""
#region init
toReturn = []
timeTakenToFetchData = time.time()
j = self.getData(allowCache=allowCache)
if j['status'] < 0:
try:
return {'html':"""<!-- ERROR --> <div id="schedule" style="all: initial;*{all:unset;}">""" + f"""<p style="color:white">{j['message']}</p>""" + j['data'].text + "</div>",'data':j}
except AttributeError:
return {'html':"""<!-- ERROR --> <div id="schedule" style="all: initial;*{all:unset;}">""" + f"""<p style="color:white">{j['message']}</p>{j['data']}</div>""",'data':j}
timeTakenToFetchData = time.time()-timeTakenToFetchData
timeTakenToHandleData = time.time()
#endregion
#region Start of the SVG
toReturn.append(f"""<svg id="schedule" class="{classes}" style="width:{self._resolution[0]}px; height:{self._resolution[1]}px;" viewBox="0 0 {self._resolution[0]} {self._resolution[1]}" shape-rendering="crispEdges">""")
#region boxList
logging.info("Looping through boxList...")
toReturn_boxList = []
colors = []
for current in j['data']['data']['boxList']:
# Saves the color in a seperate variable so that we can modify it
bColor = current['bColor']
if current['type'] == "Lesson":
# Add bodycolor to dictionary and leaave fColor empty to store the bodycolor.
colors.append({ "bColor": bColor, "fColor": []})
if darkModeSetting == 2:
bColor = "#525252"
elif darkModeSetting == 3:
bColor = grayscale(bColor)
elif darkModeSetting == 4:
bColor = invertColor(bColor)
else:
if darkMode:
if bColor == "#FFFFFF":
bColor = "#282828"
if bColor == "#CCCCCC":
bColor = "#373737"
toReturn_boxList.append(
HTMLObject(
tag='rect',
arguments={
'id':current['id'],
'x':current['x'],
'y':current['y'],
'width':current['width'],
'height':current['height'],
'class':f"rect-{current['type'].replace(' ','-')}",
'style':f'fill:{bColor};'
}
)
)
#endregion
#region textList
scriptBuilder = {}
logging.info("Looping through textList...")
toReturn_textList = []
numlist = []
for i,current in enumerate(j['data']['data']['textList']):
# Saves the color in a seperate variable so that we can modify it
fColor = current['fColor']
if current['type'] == "Lesson":
# Add current lesson number to numlist.
numlist.append(i)
# Turn the existing 32,33,34 etc dictionary into 1,2,3,4.
newi = numlist[-1]-numlist[0]
# Store fontcolor in dictionary and divide newi by 3 since there is 3 fonts per lesson.
try:
colors[newi//3]["fColor"].append(fColor)
newbColor = colors[newi//3]["bColor"]
newFcolor = colors[newi//3]["fColor"][0]
# Calculate the color luminance: https://stackoverflow.com/questions/9780632/how-do-i-determine-if-a-color-is-closer-to-white-or-black
FY = (tuple(int(newFcolor[i:i + 2], 16) / 255. for i in (1, 3, 5)))
BY = (tuple(int(newbColor[i:i + 2], 16) / 255. for i in (1, 3, 5)))
whitescalefont = 0.2126*FY[0]+0.7152*FY[1]+0.0722*FY[2]
whitescalebody = 0.2126*BY[0]+0.7152*BY[1]+0.0722*BY[2]
# # If lesson body is bright and font is bright change font to dark.
if whitescalebody > 0.5 and whitescalefont == 1.0:
fColor = "#000000"
# # If lesson body is dark and font is dark change font to bright.
# if whitescalebody < 0.5 and whitescalefont == 0.0:
# fColor = "#FFFFFF"
except:
pass
if darkModeSetting == 2:
fColor = "#FFFFFF"
elif darkModeSetting == 4:
fColor = invertColor(fColor)
else:
if darkMode:
if fColor == "#000000":
fColor = "#FFFFFF"
if current['text'] != "":
# If the text is of a Lession type, that means that it sits ontop of a block that the user should be able to click to set a URL.
# This only happens if privateID is false, because if the ID is private, it doesnt add the scripts anyways, so why bother generating them in the first place?
if privateID == False and current['type'] == "Lesson":
# If the key does not exist yet, it creates an empty list for it
if not current['parentId'] in scriptBuilder:
scriptBuilder[current['parentId']] = []
# Only takes the first 2 arguments (skips the 3rd, aka classroom name)
if len(scriptBuilder[current['parentId']]) <= 1:
scriptBuilder[current['parentId']].append(str(current['text']))
y_offset = 12
if current['type'] in ('HeadingDay','ClockAxisBox'):
y_offset += 5
if isMobile and current['type'] in ('ClockFrameStart','ClockFrameEnd'):
y_offset -= 3
size_offset = -2
if current['type'] == "Lesson":
size_offset += -1
if current['type'] in ('ClockFrameStart','ClockFrameEnd'):
size_offset += 1
toReturn_textList.append(
HTMLObject(
tag='text',
arguments={
'x':current['x'],
'y':current['y'] + y_offset,
'class':f"text-{current['type'].replace(' ','-')}",
'style':f'font-size:{int(current["fontsize"])+size_offset}px;fill:{fColor};',
'innerHTML':current['text']
}
)
)
#endregion
#region lineList
logging.info("Looping through lineList...")
toReturn_lineList = []
for current in j['data']['data']['lineList']:
color = current['color']
if darkMode:
if color == "#000000":
color = "#525252"
x1,x2=current['p1x'],current['p2x']
# Checks delta lenght and skips those smalled then 10px
if int(x1-x2 if x1>x2 else x2-x1) > 10:
toReturn_lineList.append(
HTMLObject(
tag='line',
arguments={
'x1':current['p1x'],
'y1':current['p1y'],
'x2':current['p2x'],
'y2':current['p2y'],
'stroke':color,
'class':f"line-{current['type'].replace(' ','-')}"
}
)
)
#endregion
#region Scripts
if privateID == False:
a = [x.arguments for x in toReturn_boxList]
for key in scriptBuilder:
toReturn_boxList[searchInDict(a,'id',key)].arguments['onclick'] = f"""iWasClicked('{key}','{"_".join(scriptBuilder[key])}');"""
for x in toReturn_boxList + toReturn_textList + toReturn_lineList:
toReturn.append(x.render())
timeTakenToHandleData = time.time() - timeTakenToHandleData
#endregion
#region Comments
toReturn.append("<!-- THIS SCHEDULE WAS MADE POSSIBLE BY https://github.com/KoalaV2 -->")
toReturn.append(f"<!-- SETTINGS USED: id: {'[HIDDEN]' if privateID else self._id}, week: {self._week}, day: {self._day}, resolution: {self._resolution}, class: {classes} -->")
toReturn.append(f"<!-- Time taken (Requesting data): {timeTakenToFetchData} secounds -->")
toReturn.append(f"<!-- Time taken (Schedule generation): {timeTakenToHandleData} secounds -->")
toReturn.append(f"<!-- Time taken (TOTAL): {(timeTakenToFetchData + timeTakenToHandleData)} secounds -->")
#endregion
toReturn.append("</svg>")
# End of the SVG
#endregion
return {'html':"\n".join(toReturn)}
def GenerateTextSummary(self, mode="normal", lessons=None, allowCache=True):
if lessons == None:lessons = self.fetch(allowCache=allowCache)
try:
if lessons[0]<0:return str(lessons[1])
except:pass
if mode == "normal":
return "\n".join([(f"{x.lessonName} börjar kl {x.timeStart[:-3]} och slutar kl {x.timeEnd[:-3]}" + f" i sal {x.classroomName}" if x.classroomName != None else "") for x in lessons])
if mode == "discord":
return "\n".join([(f"**`{x.lessonName}`** börjar kl {x.timeStart[:-3]} och slutar kl {x.timeEnd[:-3]}" + f" i sal {x.classroomName}" if x.classroomName != None else "") for x in lessons])
def GenerateLessonJSON(self, lessons=None, allowCache=True):
"""
Generates a dict used to create the SIMPLE_JSON API.
Takes:
<List> lessons (optional) (If you have allready runned .fetch() then you can simply convert that data to SIMPLE_JSON)
Returns:
<Dict> SIMPLE_JSON format
"""
if lessons == None:lessons = self.fetch(allowCache=allowCache)
try:
if lessons['status'] < 0:return lessons
except:pass
lessons.sort(key=attrgetter('timeStart'))
return{
'id':self._id,
'week':self._week,
'day':self._day,
'year':self._year,
'lessons':[
{'lessonName':x.lessonName,
'teacherName':x.teacherName,
'classroomName':x.classroomName,
'timeStart':x.timeStart,
'timeEnd':x.timeEnd
}for x in lessons
]
}
def GetFood(self, allowCache=True):
"""
Runs `getFood()` on this object (using `self._week`)
Args:
allowCache (bool, optional): If set to `False` then it skips any existing cache. Defaults to True.
Returns:
dict: dictionary with all the food information.
"""
return getFood(allowCache=allowCache,week=self._week)
class DropDown_Button:
def __init__(self, button_text={'short':'','long':''}, button_icon="", button_type="link", button_arguments={}, button_id="") -> None:
self.button_text = button_text #Max : 17 characters long
self.button_icon = button_icon
self.button_type = button_type
self.button_arguments = button_arguments
self.button_id = button_id
def checkVariables(self):
if type(self.button_text) == str:
self.button_text = {'short':self.button_text,'long':self.button_text}
def render(self):
self.checkVariables()
arguments = " ".join([f'{key}="{self.button_arguments[key]}"' for key in self.button_arguments])
types = {
'link':f"""
<a {arguments} class="control control-container">
<span id="{self.button_id}" class="menu-option-text" shortText="{self.button_text['short']} " longText="{self.button_text['long']} ">{self.button_text['long']} </span>
<i class="{self.button_icon} control-right"></i>
</a>
""",
'switch':f"""
<label class="toggleBox control-container" for="{self.button_id}">
<span id="{self.button_id}-text" class="menu-option-text" shortText="{self.button_text['short']} " longText="{self.button_text['long']} ">{self.button_text['long']} </span>
<label class="switch">
<input type="checkbox" {arguments} class="input-switch" name="{self.button_id}" id="{self.button_id}"/>
<span class="slider round control control-right"></span>
</label>
</label>
"""
}
return Markup(types[self.button_type])
#endregion
#region Load data
def init_Load():
"""
This function loads in all of the external files (such as .json files)
"""
toLogLater = [] #Contains things to log after all the logging and such has been configured, to make sure it shows up in the logfile
# Set working dir to path of main.py
os.chdir(os.path.dirname(os.path.realpath(__file__)))
# Load config file
default_template = { # Default template. Uses values from here when it cant be found in settings.json
"DEBUGMODE": False,
"limpMode": True,
"ip": "0.0.0.0",
"port": "5000",
"logToFile": True,
"logToSameFile": True,
"logFileLocation": "logs/",
"loggingFormat": "%(asctime)s %(levelname)10s %(funcName)15s() : %(message)s",
"mainLink": "http://0.0.0.0:5000/",
"key": "Default template",
"enableErrorHandler": True,
"discordKey": "Default template",
"discordPrefix": "!gt",
"discordRGB": [138,194,241],
"getDataMaxAge": 300,
"getFoodMaxAge": 3600
}
configWasFine = True
try:
with open("settings.json", encoding="utf-8") as f:
configfile = json.load(f)
for key in default_template:
if not key in configfile:
toLogLater.append(("critical",f"THE KEY \"{key}\" IS MISSING FROM \"settings.json\"! USING DEFAULT VALUE ({default_template[key]})! ALL FEATURES MIGHT NOT BE WORKING AS INTENDED!"))
configfile[key] = default_template[key]
configWasFine = False
except Exception:
toLogLater.append(("critical","UNABLE TO LOAD FROM \"settings.json\"! USING DEFAULT TEMPLATE! ALL FEATURES MIGHT NOT BE WORKING AS INTENDED!"))
configfile = default_template
configWasFine = False
if configWasFine:
toLogLater.append(("info","\"settings.json\" loaded without issues."))
# Load contacts
try:
with open("contacts.json", encoding="utf-8") as f:
contacts = json.load(f)
toLogLater.append(("info","\"contacts.json\" loaded without issues."))
except:
toLogLater.append(("critical","\"contacts.json\" did not load successfully. Please make sure the file exists."))
contacts = {}
# Load menus
try:
with open("menus.json", encoding="utf-8") as f:
menus = json.load(f)
toLogLater.append(("info","\"menus.json\" loaded without issues."))
except:
toLogLater.append(("critical","\"menus.json\" did not load successfully. Please make sure the file exists."))
menus = {}
# Load schools file
unitssession = requests.Session()
lunchid = dict()
headers = {'Client': configfile["foodKey"]}
print("Getting all lunches.")
lunchsession = requests.Session()
lunchsession.headers.update(headers)
r = lunchsession.get("https://skolmaten.se/api/3/provinces").json()
def getlunchid(k):
params = {'province': k["id"]}
r = lunchsession.get("https://skolmaten.se/api/3/districts",params=params).json()
for districts in r["districts"]:
params = {'district': districts["id"]}