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
|
# /var/www/seiue-backend/index.py (Final Production Version with Audit Log)
from flask import Flask, request, jsonify
from flask_cors import CORS
import json
import logging
from logging.handlers import RotatingFileHandler
import sys
import time
import functools
from datetime import datetime, timedelta, timezone
from collections import defaultdict
import pytz
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
# --- Flask App Initialization ---
app = Flask(__name__)
CORS(app)
# --- Audit Logging Configuration ---
audit_logger = logging.getLogger("audit")
audit_logger.setLevel(logging.INFO)
audit_logger.propagate = False
if not audit_logger.handlers:
audit_log_file = '/var/www/seiue-backend/audit.log'
file_handler = RotatingFileHandler(audit_log_file, maxBytes=5*1024*1024, backupCount=5, encoding='utf-8')
file_formatter = logging.Formatter("%(asctime)s | %(message)s")
file_handler.setFormatter(file_formatter)
audit_logger.addHandler(file_handler)
# Also log audit to stdout for journalctl
audit_logger.addHandler(logging.StreamHandler(sys.stdout))
# --- Audit Log Decorator ---
def log_request(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
start_time = time.time()
response = None
status_code = 500
payload = request.get_json(silent=True) or {}
try:
response = f(*args, **kwargs)
if isinstance(response, tuple):
status_code = response[1]
else:
status_code = response.status_code
return response
except Exception as e:
status_code = 500
app.logger.exception("Unhandled exception in handler")
response = jsonify({"error": "Internal Server Error", "detail": str(e)}), 500
return response
finally:
duration_ms = round((time.time() - start_time) * 1000)
audit_info = {
"timestamp": datetime.now(timezone.utc).isoformat(),
"client_ip": request.headers.get('CF-Connecting-IP', request.remote_addr),
"username": payload.get("username"),
"mode": payload.get("mode"),
"http_status": status_code,
"duration_ms": duration_ms,
}
if response and 200 <= status_code < 300:
try:
json_data = response.get_json()
audit_info["result_status"] = json_data.get("status")
except: pass
audit_logger.info(json.dumps(audit_info, ensure_ascii=False))
return decorated_function
# --- SeiueAPIClient and Business Logic ---
class SeiueAPIClient:
def __init__(self, username, password):
self.username, self.password = username, password
self.session = requests.Session()
self.BEIJING_TZ = pytz.timezone("Asia/Shanghai")
retries = Retry(total=3, backoff_factor=0.5, status_forcelist=[500, 502, 503, 504])
self.session.mount("https://", HTTPAdapter(max_retries=retries))
self.session.headers.update({"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36", "Accept": "application/json, text/plain, */*"})
self.login_url = "https://passport.seiue.com/login?school_id=3"
self.authorize_url = "https://passport.seiue.com/authorize"
self.events_url_template = "https://api.seiue.com/chalk/calendar/personals/{}/events"
self.students_url_template = "https://api.seiue.com/scms/class/classes/{}/group-members?expand=reflection&member_type=student"
self.attendance_submit_url_template = "https://api.seiue.com/sams/attendance/class/{}/records/sync"
self.verification_url = "https://api.seiue.com/sams/attendance/attendances-info"
self.bearer_token, self.reflection_id = None, None
def _auth_flow_with_username(self, uname: str) -> bool:
try: self.session.get(self.login_url, headers={"Accept": "text/html"}, timeout=20)
except requests.RequestException as e: app.logger.debug(f"Preflight GET failed (continuing): {e}")
try:
login_resp = self.session.post(self.login_url, headers={"Referer": self.login_url, "Origin": "https://passport.seiue.com"}, data={"email": uname, "password": self.password}, timeout=30, allow_redirects=True)
app.logger.info(f"Login POST for '{uname}' completed with status {login_resp.status_code}.")
auth_resp = self.session.post(self.authorize_url, headers={"Referer": "https://chalk-c3.seiue.com/", "Origin": "https://chalk-c3.seiue.com", "X-Requested-With": "XMLHttpRequest"}, data={'client_id': 'GpxvnjhVKt56qTmnPWH1sA', 'response_type': 'token'}, timeout=30)
if auth_resp.status_code not in (200, 201): app.logger.warning(f"Authorize step for '{uname}' failed with status {auth_resp.status_code}."); return False
auth_data = auth_resp.json()
self.bearer_token, self.reflection_id = auth_data.get("access_token"), auth_data.get("active_reflection_id")
if not (self.bearer_token and self.reflection_id): app.logger.error("Token/Reflection ID missing in auth response."); return False
self.session.headers.update({"Authorization": f"Bearer {self.bearer_token}", "x-school-id": "3", "x-role": "teacher", "x-reflection-id": str(self.reflection_id)})
app.logger.info(f"Authentication successful for '{uname}'."); return True
except (requests.RequestException, json.JSONDecodeError) as e: app.logger.error(f"Auth flow for '{uname}' failed with exception: {e}"); return False
def login_and_get_token(self) -> bool:
app.logger.info("--- Starting Authentication Flow ---")
for candidate in {self.username, self.username.upper(), self.username.lower()}:
if self._auth_flow_with_username(candidate): return True
app.logger.error("All authentication attempts failed."); return False
def _with_refresh(self, request_fn):
resp = request_fn()
if getattr(resp, "status_code", None) in (401, 403):
if self.login_and_get_token(): return request_fn()
return resp
def get_scheduled_lessons(self, target_date):
start = target_date.astimezone(self.BEIJING_TZ).strftime('%Y-%m-%d 00:00:00'); end = target_date.astimezone(self.BEIJING_TZ).strftime('%Y-%m-%d 23:59:59')
resp = self._with_refresh(lambda: self.session.get(self.events_url_template.format(self.reflection_id), params={"start_time": start, "end_time": end, "expand": "address,initiators"}, timeout=30))
resp.raise_for_status(); lessons = [e for e in (resp.json() or []) if e.get('type') == 'lesson']
app.logger.info(f"Found {len(lessons)} lessons for {target_date.strftime('%Y-%m-%d')}."); return lessons
def get_checked_attendance_time_ids(self, lessons):
if not lessons: return set()
time_ids, biz_ids = set(), set(); [ (time_ids.add(str(int(l["custom"]["id"]))), biz_ids.add(str(int(l["subject"]["id"])))) for l in lessons if l.get("custom", {}).get("id") and l.get("subject", {}).get("id") ]
if not time_ids or not biz_ids: return set()
params = {"attendance_time_id_in": ",".join(sorted(time_ids)), "biz_id_in": ",".join(sorted(biz_ids)), "biz_type_in": "class", "expand": "checked_attendance_time_ids", "paginated": "0"}
resp = self._with_refresh(lambda: self.session.get(self.verification_url, params=params, timeout=30)); resp.raise_for_status()
checked = {int(i) for item in (resp.json() or []) for i in item.get("checked_attendance_time_ids", [])}
app.logger.info(f"Found {len(checked)} already checked IDs."); return checked
def submit_attendance_for_lesson_group(self, lesson_group):
if not lesson_group: return True
course, class_id = lesson_group[0].get('title'), lesson_group[0].get("subject", {}).get("id")
if not class_id: app.logger.error(f"Missing class_id for '{course}'"); return False
resp_s = self._with_refresh(lambda: self.session.get(self.students_url_template.format(class_id), timeout=20)); resp_s.raise_for_status()
students = resp_s.json() or []
if not students: app.logger.warning(f"No students for class {class_id}"); return True
records, seen = [], set()
for l in lesson_group:
tid = int(l['custom']['id'])
for s in students:
oid = int(s['reflection']['id']); key = (tid, oid)
if key not in seen: records.append({"tag": "正常", "attendance_time_id": tid, "owner_id": oid, "source": "web"}); seen.add(key)
if not records: app.logger.error(f"No records generated for '{course}'"); return False
resp_sub = self._with_refresh(lambda: self.session.put(self.attendance_submit_url_template.format(class_id), json={"abnormal_notice_roles": [], "attendance_records": records}, timeout=40))
if resp_sub.status_code in (409, 422): app.logger.warning(f"Submission for '{course}' rejected ({resp_sub.status_code})"); return "WINDOW_CLOSED"
resp_sub.raise_for_status(); app.logger.info(f"Submitted {len(records)} records for '{course}'."); return True
def process_day(client, current_date):
lessons = client.get_scheduled_lessons(current_date)
if lessons is None: return "API_ERROR", "Failed to fetch lessons"
if not lessons: return "NO_CLASS", "No classes scheduled"
checked = client.get_checked_attendance_time_ids(lessons)
to_submit = [l for l in lessons if l.get("custom", {}).get("id") and int(l["custom"]["id"]) not in checked]
if not to_submit: return "NO_ACTION_NEEDED", "All classes already checked"
groups = defaultdict(list); [groups[l.get("subject",{}).get("id")].append(l) for l in to_submit]
attempted_ids = {int(l['custom']['id']) for grp in groups.values() for l in grp}
for grp in groups.values(): client.submit_attendance_for_lesson_group(grp)
final_checked = set()
for _ in range(3):
time.sleep(5)
current_checked = client.get_checked_attendance_time_ids(lessons)
if all(tid in current_checked for tid in attempted_ids): final_checked = current_checked; break
if all(tid in (final_checked or current_checked) for tid in attempted_ids): return "SUCCESS", "Successfully submitted and verified."
else: pending = len([tid for tid in attempted_ids if tid not in (final_checked or current_checked)]); return "VERIFY_FAILED", f"{pending} lessons failed final verification."
# --- Flask Routes ---
@app.route('/', defaults={'path': ''}, methods=['GET', 'POST'])
@app.route('/<path:path>', methods=['GET', 'POST'])
@log_request
def handler(path):
if request.method == 'POST':
payload = request.get_json();
username, password, mode = payload.get("username"), payload.get("password"), payload.get("mode")
if not (username and password and mode): return jsonify({"error": "Missing parameters"}), 400
client = SeiueAPIClient(username, password)
if not client.login_and_get_token(): return jsonify({"error": "Login failed"}), 401
BEIJING_TZ = pytz.timezone("Asia/Shanghai")
if mode == "today":
target_date = datetime.now(BEIJING_TZ)
status, msg = process_day(client, target_date)
elif mode == "specific_date":
target_date = BEIJING_TZ.localize(datetime.strptime(payload.get("date"), "%Y%m%d"))
status, msg = process_day(client, target_date)
elif mode == "range":
sd = BEIJING_TZ.localize(datetime.strptime(payload.get("start_date"), "%Y%m%d"))
ed = BEIJING_TZ.localize(datetime.strptime(payload.get("end_date"), "%Y%m%d"))
all_results = []; cur = sd
while cur <= ed:
s, m = process_day(client, cur)
all_results.append(f"{cur.strftime('%Y-%m-%d')}: {s} - {m}")
cur += timedelta(days=1)
if cur <= ed: time.sleep(1)
status, msg = "COMPLETED", "\n".join(all_results)
else:
return jsonify({"error": "Invalid mode"}), 400
return jsonify({"status": status, "message": msg}), 200
return jsonify({"status": "ok"})
|