-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamlit_app_advanced.py
More file actions
4755 lines (4034 loc) · 181 KB
/
Copy pathstreamlit_app_advanced.py
File metadata and controls
4755 lines (4034 loc) · 181 KB
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 streamlit as st
import json
import time
from datetime import datetime, timedelta
from itertools import combinations
import random
from openpyxl import Workbook
from openpyxl.styles import PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
import os
from icalendar import Calendar, Event
import pytz
import re
import requests
from typing import List, Dict
from parse_headers import parse_request_headers, format_for_banner_api
# Initialize session state for browser-based storage (stateless)
if "classes_data" not in st.session_state:
st.session_state.classes_data = {}
# Initialize color mapping in session state to prevent regeneration
if "class_colors" not in st.session_state:
st.session_state.class_colors = {}
def get_term_name(term_code: str) -> str:
"""
Convert term code to human-readable name
Format: YYYYSS where YYYY is year and SS is semester
30 = Winter, 40 = Spring/Summer, 50 = Fall
Examples:
202530 -> Winter 2025
202540 -> Spring/Summer 2025
202550 -> Fall 2025
"""
if not term_code or len(term_code) != 6:
return term_code
try:
year = term_code[:4]
semester_code = term_code[4:6]
semester_map = {"30": "Winter", "40": "Spring/Summer", "50": "Fall"}
semester = semester_map.get(semester_code, f"Semester {semester_code}")
return f"{semester} {year}"
except:
return term_code
# BANNER API FUNCTIONS
def get_banner_credentials():
"""Get cookies and synchronizer token from session state"""
creds = st.session_state.get("banner_credentials", {})
cookies = creds.get("cookies", {})
sync_token = creds.get("sync_token", "")
unique_session_id = creds.get("unique_session_id", "")
return cookies, sync_token, unique_session_id
def get_banner_credentials():
"""Get Banner API credentials from Streamlit secrets or session state"""
if "banner_cookies" not in st.session_state:
# Try to get from secrets first
try:
st.session_state.banner_cookies = {
"JSESSIONID": st.secrets["BANNER"]["JSESSIONID"],
"NLB": st.secrets["BANNER"]["NLB"],
"NSC_ESNS": st.secrets["BANNER"]["NSC_ESNS"],
}
st.session_state.banner_token = st.secrets["BANNER"]["SYNC_TOKEN"]
st.session_state.banner_session_id = st.secrets["BANNER"].get(
"UNIQUE_SESSION_ID", ""
)
except:
# No credentials available - user needs to authenticate
return None, None, ""
return (
st.session_state.banner_cookies,
st.session_state.banner_token,
st.session_state.get("banner_session_id", ""),
)
def fetch_available_terms() -> List[Dict]:
"""
Fetch available terms from Banner API
Returns:
List of term dictionaries with 'code' and 'description'
"""
import time
cookies, sync_token, _ = get_banner_credentials()
if not cookies or not sync_token:
st.error("❌ No authentication credentials found.")
return []
terms_url = "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classRegistration/getTerms"
params = {"searchTerm": "", "offset": 1, "max": 10, "_": int(time.time() * 1000)}
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"Referer": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/term/termSelection?mode=registration",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"X-Requested-With": "XMLHttpRequest",
"X-Synchronizer-Token": sync_token,
"sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
try:
response = requests.get(
terms_url, params=params, headers=headers, cookies=cookies, timeout=15
)
if response.status_code == 200:
terms = response.json()
return terms if isinstance(terms, list) else []
else:
st.error(f"Failed to fetch terms: HTTP {response.status_code}")
return []
except Exception as e:
st.error(f"Error fetching terms: {e}")
return []
def search_courses(search_term: str, term: str = "202530") -> List[Dict]:
"""
Search for courses using the Banner API autocomplete
Args:
search_term: The search term (e.g., "abdy", "itsc", "cprg")
term: Term code (e.g., "202530")
Returns:
List of course dictionaries with 'code' and 'description'
"""
import time
cookies, sync_token, _ = get_banner_credentials()
# Check if credentials are available
if not cookies or not sync_token:
st.error("❌ No authentication credentials found. Please authenticate first.")
return []
search_url = "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classSearch/get_subjectcoursecombo"
search_params = {
"searchTerm": search_term,
"term": term,
"offset": 1,
"max": 500, # Get more results
}
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"Referer": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classRegistration/classRegistration",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
"X-Synchronizer-Token": sync_token,
"sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
try:
response = requests.get(
search_url,
params=search_params,
headers=headers,
cookies=cookies,
timeout=15,
)
if response.status_code == 200:
data = response.json()
# Return list of course objects
return data if isinstance(data, list) else []
else:
st.error(f"Search failed: HTTP {response.status_code}")
return []
except Exception as e:
st.error(f"Error searching courses: {e}")
return []
def reset_banner_search(term: str = "202530") -> bool:
"""Reset the Banner search state"""
cookies, sync_token, _ = get_banner_credentials()
# Check if credentials are available
if not cookies or not sync_token:
return False
reset_url = "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classSearch/resetDataForm"
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"Referer": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classRegistration/classRegistration",
"X-Synchronizer-Token": sync_token,
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
}
try:
response = requests.post(
reset_url, headers=headers, cookies=cookies, data={"term": term}, timeout=10
)
return response.status_code == 200
except:
return False
def fetch_banner_api(
term: str, course_code: str, session_id: str = None, open_only: bool = True
) -> Dict:
"""
Fetch course data from SAIT Banner API (with authentication)
Args:
term: Term code (e.g., "202530" for Winter 2026)
course_code: Course code (e.g., "ITSC320", "CPSY300")
session_id: Optional unique session ID (will generate if not provided)
open_only: If True, only fetch classes with available seats
Returns:
Dictionary with API response
"""
import time
cookies, sync_token, _ = get_banner_credentials()
# Check if credentials are available
if not cookies or not sync_token:
st.error("❌ No authentication credentials found. Please authenticate first.")
return {"success": False, "error": "No credentials"}
# Generate unique session ID if not provided
if not session_id:
session_id = f"streamlit{int(time.time() * 1000)}"
# Step 1: Search endpoint to set up what we're searching for
search_url = "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classSearch/get_subjectcoursecombo"
search_params = {"searchTerm": course_code, "term": term, "offset": 1, "max": 10}
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"Referer": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classRegistration/classRegistration",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
"X-Synchronizer-Token": sync_token,
"sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
try:
# Step 1: Search
search_response = requests.get(
search_url,
params=search_params,
headers=headers,
cookies=cookies,
timeout=15,
)
if search_response.status_code != 200:
st.error(
f"Search failed for {course_code}: HTTP {search_response.status_code}"
)
return None
search_data = search_response.json()
if not search_data or len(search_data) == 0:
st.warning(f"No course found matching {course_code}")
return None
# Get the actual course code from search results
actual_code = search_data[0]["code"]
# Step 2: Get results
results_url = "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/searchResults/searchResults"
results_params = {
"txt_subjectcoursecombo": actual_code,
"txt_term": term,
"startDatepicker": "",
"endDatepicker": "",
"uniqueSessionId": session_id,
"pageOffset": 0,
"pageMaxSize": 50,
"sortColumn": "subjectDescription",
"sortDirection": "asc",
}
# Only add chk_open_only if filtering by available seats
if open_only:
results_params["chk_open_only"] = "true"
results_response = requests.get(
results_url,
params=results_params,
headers=headers,
cookies=cookies,
timeout=15,
)
results_response.raise_for_status()
data = results_response.json()
return data
except requests.exceptions.RequestException as e:
st.error(f"Error fetching {course_code} from Banner API: {e}")
return None
except json.JSONDecodeError as e:
st.error(f"Failed to parse JSON response for {course_code}: {e}")
return None
def parse_banner_response(api_response: Dict, open_only: bool = True) -> List[Dict]:
"""
Parse Banner API response and convert to app's class format
Args:
api_response: API response dictionary
open_only: If True, only include classes with available seats
Returns:
List of class dictionaries in app format
"""
if not api_response:
st.warning("No response received from API")
return []
if not isinstance(api_response, dict):
st.error(f"Invalid API response format: {type(api_response)}")
return []
if not api_response.get("success"):
st.error(f"API returned error: {api_response.get('message', 'Unknown error')}")
return []
classes = []
data_items = api_response.get("data", [])
# Additional safety check - ensure data_items is not None
if data_items is None:
st.warning("No data returned from API")
return []
for course_data in data_items:
seats_available = course_data.get("seatsAvailable", 0)
# Only include courses with available seats if open_only is True
if open_only and seats_available <= 0:
continue
# Parse meeting times
schedule = []
for meeting in course_data.get("meetingsFaculty", []):
meeting_time = meeting.get("meetingTime", {})
# Skip if no meeting time data
if not meeting_time:
continue
# Get times
begin_time = meeting_time.get("beginTime")
end_time = meeting_time.get("endTime")
if not begin_time or not end_time:
continue
# Convert military time (e.g., "0800") to HH:MM format
start_time = f"{begin_time[:2]}:{begin_time[2:]}"
end_time_str = f"{end_time[:2]}:{end_time[2:]}"
# Get location
building = meeting_time.get("building", "")
room = meeting_time.get("room", "")
building_room = f"{building}{room}" if building or room else "TBA"
# Map day booleans to day names
day_mapping = {
"monday": "Monday",
"tuesday": "Tuesday",
"wednesday": "Wednesday",
"thursday": "Thursday",
"friday": "Friday",
"saturday": "Saturday",
"sunday": "Sunday",
}
# Add schedule entry for each day that is True
for day_key, day_name in day_mapping.items():
if meeting_time.get(day_key, False):
schedule.append(
{
"day": day_name,
"start_time": start_time,
"end_time": end_time_str,
"class_room": building_room,
}
)
if schedule: # Only add if there's a valid schedule
# Get instructor name
instructor = "TBA"
if course_data.get("faculty"):
instructor = course_data["faculty"][0].get("displayName", "TBA")
class_obj = {
"name": f"{course_data['subject']} {course_data['courseNumber']}",
"group": course_data.get("sequenceNumber", "A"),
"schedule": schedule,
"seats_available": course_data.get("seatsAvailable", 0),
"max_enrollment": course_data.get("maximumEnrollment", 0),
"instructor": instructor,
"crn": course_data.get("courseReferenceNumber", ""),
}
classes.append(class_obj)
else:
# No valid schedule found - skip this class
pass
return classes
def fetch_all_available_courses(
term: str, course_codes: List[str], open_only: bool = True
) -> List[Dict]:
"""
Fetch all available courses for given course codes
Args:
term: Term code (e.g., "202530")
course_codes: List of course codes (e.g., ["ITSC320", "CPSY300", "INTP302"])
open_only: If True, only fetch classes with available seats
Returns:
List of all available classes
"""
import time
all_classes = []
session_id = f"streamlit{int(time.time() * 1000)}"
progress_bar = st.progress(0)
status_text = st.empty()
for idx, course_code in enumerate(course_codes):
# Reset search state before each course
reset_banner_search(term)
time.sleep(0.5)
status_text.text(
f"Fetching {course_code} courses... ({idx+1}/{len(course_codes)})"
)
api_response = fetch_banner_api(term, course_code, session_id, open_only)
if api_response:
classes = parse_banner_response(api_response, open_only=open_only)
all_classes.extend(classes)
st.success(
f"✅ Found {len(classes)} available section(s) for {course_code}"
)
else:
st.warning(f"⚠️ No data returned for {course_code}")
# Update progress
progress_bar.progress((idx + 1) / len(course_codes))
# Small delay to avoid overwhelming the server
time.sleep(1)
progress_bar.empty()
status_text.empty()
return all_classes
# REGISTRATION API FUNCTIONS
def get_current_registrations(term: str, unique_session_id: str = "") -> List[Dict]:
"""
Get user's current registered classes for a term with meeting time information
Args:
term: Term code (e.g., "202530")
unique_session_id: Unique session ID from save_term_to_banner (optional)
Returns:
List of calendar event objects with day/time information
"""
cookies, sync_token, _ = get_banner_credentials()
if not cookies or not sync_token:
st.error("❌ No authentication credentials found.")
return []
# Use the getMeetingInformationForRegistrations endpoint which returns meetingTimes
url = "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classRegistration/getMeetingInformationForRegistrations"
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"Referer": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classRegistration/classRegistration",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"X-Requested-With": "XMLHttpRequest",
"X-Synchronizer-Token": sync_token,
"sec-ch-ua": '"Chromium";v="140", "Not?A_Brand";v="24", "Google Chrome";v="140"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
try:
response = requests.get(url, headers=headers, cookies=cookies, timeout=15)
if response.status_code == 200:
try:
data = response.json()
if isinstance(data, list):
# Convert the meetingTimes format to individual events
converted_events = []
for course in data:
crn = course.get("courseReferenceNumber", "")
subject = course.get("subject", "")
course_number = course.get("courseNumber", "")
course_title = course.get("courseTitle", "")
section = course.get("sequenceNumber", "A")
# Process each meeting time
meeting_times = course.get("meetingTimes", [])
for meeting in meeting_times:
# Get day of week
days = []
if meeting.get("monday"):
days.append("Monday")
if meeting.get("tuesday"):
days.append("Tuesday")
if meeting.get("wednesday"):
days.append("Wednesday")
if meeting.get("thursday"):
days.append("Thursday")
if meeting.get("friday"):
days.append("Friday")
# Get times
begin_time = meeting.get("beginTime", "")
end_time = meeting.get("endTime", "")
start_date = meeting.get("startDate", "")
end_date = meeting.get("endDate", "")
# For each day this meeting occurs
for day in days:
converted_events.append(
{
"crn": crn,
"subject": subject,
"courseNumber": course_number,
"title": f"{subject} {course_number}",
"courseTitle": course_title,
"section": section,
"term": term,
"day": day,
"beginTime": begin_time,
"endTime": end_time,
"startDate": start_date,
"endDate": end_date,
"building": meeting.get(
"buildingDescription", ""
),
"room": meeting.get("room", ""),
}
)
return converted_events
else:
st.error(f"❌ Unexpected data type: {type(data)}")
return []
except json.JSONDecodeError as e:
st.error(f"❌ Failed to parse JSON response: {e}")
return []
else:
st.error(f"❌ API returned status code {response.status_code}")
return []
except requests.exceptions.RequestException as e:
st.error(f"❌ Error fetching registrations: {e}")
return []
return []
except Exception as e:
st.error(f"❌ Request failed: {str(e)}")
return []
def save_term_to_banner(term: str, mode: str = "registration") -> tuple[bool, str]:
"""
Save the selected term to Banner session
Args:
term: Term code (e.g., "202520")
mode: Mode (default "registration")
Returns:
Tuple of (success: bool, unique_session_id: str)
"""
cookies, sync_token, unique_session_id = get_banner_credentials()
if not cookies or not sync_token:
return False, ""
# Use the existing session ID from authentication, or generate if not available
if not unique_session_id:
import random
import string
unique_session_id = "".join(
random.choices(string.ascii_lowercase + string.digits, k=5)
) + str(int(time.time() * 1000))
try:
# Step 0: Fetch usage tracking BEFORE term selection (as shown in PowerShell)
tracking_url_before = "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/userPreference/fetchUsageTracking"
tracking_headers_before = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"Referer": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/term/termSelection?mode=registration",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
response0 = requests.get(
tracking_url_before,
headers=tracking_headers_before,
cookies=cookies,
timeout=10,
)
if response0.status_code != 200:
return False, ""
# Step 1: Save the term
save_url = f"https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/term/saveTerm?mode={mode}&term={term}&uniqueSessionId={unique_session_id}"
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"Referer": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/term/termSelection?mode=registration",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"X-Requested-With": "XMLHttpRequest",
"X-Synchronizer-Token": sync_token,
"sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
# Step 1: Save term
response1 = requests.get(save_url, headers=headers, cookies=cookies, timeout=10)
if response1.status_code != 200:
return False, ""
# Step 2: POST to term search
search_url = f"https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/term/search?mode={mode}"
search_headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Origin": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca",
"Pragma": "no-cache",
"Referer": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/term/termSelection?mode=registration",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"X-Requested-With": "XMLHttpRequest",
"X-Synchronizer-Token": sync_token,
"sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
}
search_data = f"term={term}&studyPath=&studyPathText=&startDatepicker=&endDatepicker=&uniqueSessionId={unique_session_id}"
response2 = requests.post(
search_url,
headers=search_headers,
cookies=cookies,
data=search_data,
timeout=10,
)
if response2.status_code != 200:
return False, ""
# Step 3: Fetch usage tracking AFTER term selection (final step)
tracking_url = "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/userPreference/fetchUsageTracking"
tracking_headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"Referer": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classRegistration/classRegistration",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
response3 = requests.get(
tracking_url, headers=tracking_headers, cookies=cookies, timeout=10
)
return response3.status_code == 200, unique_session_id
except Exception as e:
return False, ""
def get_registration_models_for_term(
term: str, unique_session_id: str = ""
) -> Dict[str, Dict]:
"""
Extract full registration model objects from the Banner registration page HTML.
The models are embedded in window.bootstraps.summaryModels in the JavaScript.
These models contain all the required fields that Banner expects for drop operations.
Args:
term: Term code
unique_session_id: Unique session ID from save_term_to_banner (optional)
Returns:
Dictionary of {crn: model_object}
"""
cookies, sync_token, _ = get_banner_credentials()
if not cookies or not sync_token:
return {}
# Fetch the registration page HTML which contains the models
url = "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classRegistration/classRegistration"
if unique_session_id:
url += f"?uniqueSessionId={unique_session_id}"
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"Referer": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/term/termSelection?mode=registration",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "same-origin",
"Upgrade-Insecure-Requests": "1",
"sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
try:
response = requests.get(url, headers=headers, cookies=cookies, timeout=15)
if response.status_code == 200:
html = response.text
# Extract the summaryModels from the JavaScript in the HTML
# Look for: summaryModels: [...] in window.bootstraps
import re
import json
# Find the start of summaryModels array
start_pattern = r"summaryModels:\s*\["
match = re.search(start_pattern, html)
if match:
start_pos = match.end() - 1 # Position of the opening '['
# Now manually find the matching closing bracket by counting
bracket_count = 0
end_pos = start_pos
in_string = False
escape_next = False
for i in range(start_pos, len(html)):
char = html[i]
# Handle string escaping
if escape_next:
escape_next = False
continue
if char == "\\":
escape_next = True
continue
# Track if we're inside a string
if char == '"' and not escape_next:
in_string = not in_string
continue
# Only count brackets outside of strings
if not in_string:
if char == "[":
bracket_count += 1
elif char == "]":
bracket_count -= 1
if bracket_count == 0:
end_pos = i + 1
break
if bracket_count == 0:
models_json = html[start_pos:end_pos]
# Parse the JSON array
try:
models = json.loads(models_json)
# Build dictionary of CRN -> model
models_by_crn = {}
for model in models:
if (
isinstance(model, dict)
and "courseReferenceNumber" in model
):
crn = str(model["courseReferenceNumber"])
models_by_crn[crn] = model
return models_by_crn
except json.JSONDecodeError as e:
return {}
return {}
return {}
except Exception as e:
return {}
def add_class_to_cart(term: str, crn: str) -> Dict:
"""
Add a class to registration cart
Args:
term: Term code (e.g., "202530")
crn: Course Reference Number
Returns:
Dict with 'success' boolean and 'data' or 'error' message
"""
cookies, sync_token, _ = get_banner_credentials()
if not cookies or not sync_token:
return {"success": False, "error": "No authentication credentials"}
url = f"https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classRegistration/addRegistrationItem?term={term}&courseReferenceNumber={crn}&olr=false"
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Pragma": "no-cache",
"Referer": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classRegistration/classRegistration",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"X-Requested-With": "XMLHttpRequest",
"X-Synchronizer-Token": sync_token,
"sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
try:
response = requests.get(url, headers=headers, cookies=cookies, timeout=15)
if response.status_code == 200:
data = response.json()
if data.get("success", False):
return {"success": True, "data": data}
else:
# Get error message from response
error_msg = data.get("message", "Unknown error")
return {"success": False, "error": error_msg}
else:
return {"success": False, "error": f"HTTP {response.status_code}"}
except Exception as e:
return {"success": False, "error": str(e)}
def submit_registration(term: str, registration_items: List[Dict]) -> Dict:
"""
Submit registration changes (add/drop classes)
Args:
term: Term code
registration_items: List of registration item objects to update
Returns:
Response dictionary
"""
cookies, sync_token, _ = get_banner_credentials()
if not cookies or not sync_token:
return {"success": False, "error": "No credentials"}
url = "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classRegistration/submitRegistration/batch"
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate, br, zstd",
"Accept-Language": "en-US,en;q=0.9",
"Cache-Control": "no-cache",
"Origin": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca",
"Pragma": "no-cache",
"Referer": "https://sait-sust-prd-prd1-ban-ss-ssag6.sait.ca/StudentRegistrationSsb/ssb/classRegistration/classRegistration",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"X-Requested-With": "XMLHttpRequest",
"X-Synchronizer-Token": sync_token,
"sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"Windows"',
}
unique_session_id = f"streamlit{int(time.time() * 1000)}"
payload = {
"create": [],
"update": registration_items,
"destroy": [],
"uniqueSessionId": unique_session_id,
}
try:
response = requests.post(
url, headers=headers, cookies=cookies, json=payload, timeout=15