-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathmain.py
More file actions
513 lines (429 loc) · 21 KB
/
main.py
File metadata and controls
513 lines (429 loc) · 21 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
import json
import os
import sys
import time
import base64
import random
import re
import urllib3
from hashlib import md5
from io import BytesIO
import select
import datetime
import ddddocr
import requests
from PIL import Image
from rich.console import Console
from rich.progress import Progress
from rich.prompt import Prompt, Confirm
from rich.table import Table
from rich.panel import Panel
from seu_auth import seu_login # 确保该模块存在
# JSON 解析工具:跳过前导垃圾字节
_JSON_START_RE = re.compile(r'[\[\{]')
def _parse_json(res):
"""尝试从响应中解析 JSON,自动跳过前导不可见字节。"""
try:
return res.json()
except (json.JSONDecodeError, Exception):
text = res.text
m = _JSON_START_RE.search(text)
if m:
try:
return json.loads(text[m.start():])
except (json.JSONDecodeError, Exception):
return None
return None
# 初始化 rich 组件
console = Console()
error_console = Console(stderr=True, style="bold red")
# 是否保存验证码
save_code = False
def resource_path(relative_path):
if getattr(sys, 'frozen', False): # 判断是否处于打包环境
base_path = getattr(sys, '_MEIPASS', '') # 临时解压路径
else:
# 以脚本所在目录为基准,确保无论从哪启动都能找到资源
base_path = os.path.dirname(os.path.abspath(__file__))
return str(os.path.join(base_path, relative_path))
import ssl
from requests.adapters import HTTPAdapter
from urllib3.exceptions import InsecureRequestWarning
urllib3.disable_warnings(InsecureRequestWarning)
class TLSAdapter(HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
ctx = ssl.create_default_context()
ctx.set_ciphers("DEFAULT@SECLEVEL=1")
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
ctx.options |= 0x4
kwargs["ssl_context"] = ctx
return super().init_poolmanager(*args, **kwargs)
# 生成浏览器指纹
def generate_fingerprint():
# 仿照984ba064c2399f4b5c379df8aaeb995a生成,同样字符数,随机生成
fingerprint = md5(str(time.time()).encode()).hexdigest()
return fingerprint
def fetch_lecture(hd_wid: str, ss, ver_code):
"""
发送抢课(预约)请求,模拟类似 AJAX 的异步数据提交。
不再根据返回结果判断成功,仅返回状态信息。
"""
url = "https://ehall.seu.edu.cn/gsapp/sys/jzxxtjapp/hdyy/yySave.do"
if not ver_code:
return 500, "验证码识别失败", False
# 模拟前端通过 POST 发送一个包含 JSON 字符串的 'paramJson' 字段
data_payload = {"HD_WID": hd_wid, "vcode": ver_code}
form_data = {"paramJson": json.dumps(data_payload)}
# 设置 HTTP Headers,模拟浏览器发送 AJAX 请求
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Dest": "empty",
"Referer": getattr(ss, "ehall_referer",
"https://ehall.seu.edu.cn/gsapp/sys/jzxxtjapp/*default/index.do"),
"X-Requested-With": "XMLHttpRequest",
}
try:
r = ss.post(url, data=form_data, headers=headers, verify=False)
# 调试输出
if not r.text.strip():
return 500, "服务器繁忙,无响应内容", False
if r.headers.get("Content-Type", "").startswith("text/html"):
return 500, "服务器繁忙,返回异常页面", False
result = _parse_json(r)
if result is None:
return 500, "服务器繁忙,响应非JSON", False
code = result.get("code", -1)
msg = result.get("msg", "未知错误")
success = result.get("success", False)
return code, msg, success
except requests.exceptions.RequestException as e:
return 500, f"服务器繁忙,请求异常: {str(e)[:80]}", False
def check_booking_success(ss, target_wid: str, max_page: int = 5) -> bool:
"""
通过查询已预约讲座列表,判断指定讲座是否预约成功。
遍历多页结果以确保找到目标讲座。
"""
url = "https://ehall.seu.edu.cn/gsapp/sys/jzxxtjapp/hdyy/queryMyActivityList.do"
for page in range(1, max_page + 1):
try:
res = ss.post(
f"{url}?_={int(time.time() * 1000)}",
data={"pageIndex": page, "pageSize": 10, "sortField": "", "sortOrder": ""},
verify=False
)
result = _parse_json(res)
if result is None:
break
datas = result.get("datas", [])
for item in datas:
if item.get("HD_WID") == target_wid:
return True
# 如果返回的数据少于 pageSize,说明没有更多数据了
if len(datas) < 10:
break
except Exception as e:
# 服务器繁忙,查询失败,返回 False 继续抢
break
return False
def get_code(ss, captcha_hash_table=None):
c_url = f"https://ehall.seu.edu.cn/gsapp/sys/jzxxtjapp/hdyy/vcode.do?_={int(time.time() * 1000)}"
c_headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
"Sec-Fetch-Site": "same-origin",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Dest": "empty",
"Referer": getattr(ss, "ehall_referer",
"https://ehall.seu.edu.cn/gsapp/sys/jzxxtjapp/*default/index.do"),
"X-Requested-With": "XMLHttpRequest",
}
c = ss.post(c_url, headers=c_headers)
try:
c_r = _parse_json(c)
if c_r is None or "result" not in c_r:
raise RuntimeError("验证码接口繁忙")
except (json.JSONDecodeError, RuntimeError):
raise RuntimeError("验证码接口繁忙")
c_img = base64.b64decode(c_r["result"].split(",")[1])
result = ""
if captcha_hash_table:
img = Image.open(BytesIO(c_img))
with BytesIO() as output:
img.save(output, format="JPEG")
hash_val = md5(output.getvalue()).hexdigest()
if hash_val in captcha_hash_table:
result = captcha_hash_table[hash_val]
if not result:
result = ocr.classification(c_img)
return result, c_img
def get_mobile_verify_code(ss, username: str):
url = "https://auth.seu.edu.cn/auth/casback/sendStage2Code"
data = {"userId": username}
res = ss.post(url, data=json.dumps(data))
if res.json()["success"] != True:
raise Exception(f"发送手机验证码失败[{res.status_code}, {res.json()}]")
else:
console.print(Panel.fit(f"[bold yellow]⚠ {res.json()['info']}[/]", title="提示"))
def login(username: str, password: str, fingerprint=None):
try:
service_url = "http://ehall.seu.edu.cn/gsapp/sys/jzxxtjapp/*default/index.do"
session, redirect_url, error_type = seu_login(username, password, service_url, fingerprint)
if error_type == 'non_trusted_device':
console.print(Panel.fit(f"[bold yellow]⚠ 非可信设备登录,需要输入手机验证码[/]", title="提示"))
get_mobile_verify_code(session, username)
phone_code = Prompt.ask("请输入手机验证码")
session, redirect_url, error_type = seu_login(username, password, service_url, fingerprint, phone_code)
if not session:
raise Exception("统一身份认证平台登录失败")
if not redirect_url:
raise Exception("获取重定向url失败")
# 在访问 ehall 前先挂 TLSAdapter,并清掉统一认证阶段遗留的 JSON Content-Type,
# 否则后续表单接口会带错请求头,导致列表接口返回异常。
session.mount("https://", TLSAdapter())
session.mount("http://", TLSAdapter())
session.headers.pop("Content-Type", None)
res = session.get(redirect_url, verify=False, allow_redirects=True)
if res.status_code != 200:
raise Exception(f"访问研究生素质讲座系统失败[{res.status_code}, {res.reason}]")
# 保存 ehall 首页完整 URL(含 gid_ 等安全参数),供后续请求作为 Referer
session.ehall_referer = res.url
return session
except Exception as e:
error_console.print(Panel.fit(f"[bold red]✗ 登录失败: {str(e)}[/]", title="错误"))
return None
def get_lecture_list(session):
try:
res = session.post(
f"https://ehall.seu.edu.cn/gsapp/sys/jzxxtjapp/hdyy/queryActivityList.do?_={int(time.time() * 1000)}",
data={"pageIndex": 1, "pageSize": 100},
headers={"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"},
verify=False # 禁用SSL证书验证
)
data = _parse_json(res)
if data is None or "datas" not in data:
# 服务器繁忙,JSON解析失败,返回空让抢课继续
return session, None, None
lecture_list = data["datas"]
stu_cnt_arr = [[int(l["HDZRS"]), int(l["YYRS"])] for l in lecture_list]
console.print("[bold green]✓ 获取讲座列表成功[/]")
return session, lecture_list, stu_cnt_arr
except Exception as e:
# 网络异常等,返回空让抢课继续
return session, None, None
def login_and_get_lecture_list(username: str, password: str, fingerprint=None):
session = login(username, password, fingerprint)
if session is None:
return None, None, None
return get_lecture_list(session)
def print_lecture_list(lecture_list: list):
try:
table = Table(title="研究生素质讲座列表", show_header=True, header_style="bold magenta")
table.add_column("序号", style="cyan")
# table.add_column("WID", style="blue", width=20)
table.add_column("讲座名称")
table.add_column("预约时间")
table.add_column("活动时间")
for idx, lecture in enumerate(lecture_list):
table.add_row(
str(idx),
# lecture["WID"],
lecture["JZMC"],
f"{lecture['YYKSSJ']}至{lecture['YYJSSJ']}",
lecture["JZSJ"]
)
console.print(table)
except Exception as e:
error_console.print(f"打印讲座列表失败: {str(e)}")
if __name__ == "__main__":
# 初始化验证码组件(自定义模型已不兼容新验证码,改用默认内置模型)
captcha_hash_table_path = resource_path("captcha_hash_table.csv")
ocr = ddddocr.DdddOcr(show_ad=False)
captcha_hash_table = {}
if os.path.exists(captcha_hash_table_path):
with open(captcha_hash_table_path) as f:
for line in f:
if line.strip():
hash_val, label = line.strip().split(",")
captcha_hash_table[hash_val] = label
# 用户认证
with console.status("[bold green]正在读取配置文件...") as status:
try:
with open("config.txt") as f:
stu_info = [line.strip() for line in f if line.strip()]
user_name, password, fingerprint = stu_info[0], stu_info[1], stu_info[2]
except Exception:
status.stop() # 关键:停止状态动画
console.print(Panel.fit("[yellow]⚠ 将在当前目录创建 config.txt 文件[/]", title="提示"))
user_name = Prompt.ask("请输入学号", console=console)
password = Prompt.ask("请输入密码", password=True, console=console)
fingerprint = generate_fingerprint()
with open("config.txt", "w") as f:
f.write(f"{user_name}\n{password}\n{fingerprint}\n")
# 第一次登录:获取讲座列表和初始Session
console.print(Panel.fit(f"[bold]🕒 {time.ctime()} 首次尝试登录系统并获取讲座列表...[/]", title="状态"))
s, lecture_list, stu_cnt_arr = login_and_get_lecture_list(user_name, password, fingerprint)
if lecture_list is None:
error_console.print("[bold red]✗ 登录或获取讲座列表失败,退出程序[/]")
sys.exit(1)
print_lecture_list(lecture_list)
# 选择讲座 (保持不变)
target_index = Prompt.ask("请输入课程序号", console=console, default="0")
try:
lecture_info = lecture_list[int(target_index)]
except (ValueError, IndexError, TypeError):
error_console.print("[bold red]✗ 输入的课程序号无效,请输入有效的序号[/]")
sys.exit(1)
wid = lecture_info["WID"]
if not Confirm.ask(f"确认选择讲座 [cyan]{lecture_info['JZMC']}[/]", default=True, console=console):
sys.exit(0)
# 等待抢课 - 使用本地时间
target_time = datetime.datetime.strptime(lecture_info["YYKSSJ"], "%Y-%m-%d %H:%M:%S")
# 提前重新登录的时间(秒)。目标时间前 10 秒重新登录,确保 session 最新
# RELOGIN_BEFORE_SECONDS = 10
RELOGIN_BEFORE_SECONDS = Prompt.ask("请输入提前重新登录的时间(秒)", console=console, default=10)
RELOGIN_BEFORE_SECONDS = float(RELOGIN_BEFORE_SECONDS)
# 倒计时延迟(秒)。目标时间结束后再延迟 0.5 秒开始抢课循环
# START_DELAY_SECONDS = 0.5
START_DELAY_SECONDS = Prompt.ask("请输入倒计时延迟(秒),可为负数", console=console, default=0.5)
START_DELAY_SECONDS = float(START_DELAY_SECONDS)
with Progress() as progress:
start_time = datetime.datetime.now()
total_seconds = (target_time - start_time).total_seconds()
# total_seconds 可能为负,确保总数合理
task = progress.add_task(
f"[red]等待抢课 | 目标时间: {target_time.strftime('%H:%M:%S')}",
total=max(total_seconds, 1) # 至少是 1
)
relogin_done = False
while True:
current_time = datetime.datetime.now()
remaining = (target_time - current_time).total_seconds()
# 检查是否需要提前重新登录
if not relogin_done and 0 < remaining <= RELOGIN_BEFORE_SECONDS:
console.rule(f"[bold yellow]🕒 目标时间前 {RELOGIN_BEFORE_SECONDS} 秒,进行二次登录...[/]")
s = login(user_name, password, fingerprint)
if s is None:
error_console.print("[bold red]✗ 提前二次登录失败,退出程序[/]")
sys.exit(1)
console.print("[bold green]✓ 二次登录成功![/]")
relogin_done = True
if remaining <= -START_DELAY_SECONDS:
# 倒计时结束且延迟时间已过
progress.update(task, completed=max(total_seconds, 1))
break
if remaining <= 0:
# 已经到达目标时间,开始延迟计时
progress.update(
task,
completed=total_seconds,
description=f"[bold red]⏰ 目标已到,延迟 {abs(remaining):.2f} / {START_DELAY_SECONDS:.2f} 秒开始抢课...[/]"
)
time.sleep(0.01) # 微小延迟,保持 CPU 占用合理
continue
# 正常倒计时更新
progress.update(
task,
completed=total_seconds - remaining, # 计算已完成的进度
description=f"[bold cyan]⏳ 剩余时间: {str(datetime.timedelta(seconds=int(remaining)))}.{int((remaining % 1) * 10):<1} 秒[/] | 目标时间: {target_time.strftime('%H:%M:%S')}"
)
# 根据剩余时间调整休眠,越接近目标时间越频繁
if remaining > 60:
time.sleep(1)
elif remaining > 10:
time.sleep(0.5)
elif remaining > 2:
time.sleep(0.1)
else:
time.sleep(0.01) # 接近 0 时采用更精细的等待
# 抢课循环开始
console.rule(f"[bold red]🚀 延迟 {START_DELAY_SECONDS} 秒结束,开始抢课![/]")
# 确保在开始抢课时 s 是最新的(如果在倒计时期间没有触发二次登录,这里相当于补一个)
if not relogin_done:
console.rule("[bold yellow]🕒 未触发二次登录,进行最终登录检查...[/]")
s = login(user_name, password, fingerprint)
if s is None:
error_console.print("[bold red]✗ 最终登录失败,退出程序[/]")
sys.exit(1)
console.print("[bold green]✓ 最终登录检查成功,开始抢课![/]")
# 创建验证码保存目录 (保持不变)
if save_code:
os.makedirs("code_img/true", exist_ok=True)
os.makedirs("code_img/false", exist_ok=True)
# 第一次获取验证码
v_code, v_img = get_code(ss=s, captcha_hash_table=captcha_hash_table)
attempt = 1
check_interval = 5 # 每抢 N 次查询一次已预约列表
success_confirmed = False
while True:
# 获取最新讲座列表(失败时跳过余量检查,继续抢)
s, lecture_list_refresh, stu_cnt_arr = get_lecture_list(s)
try:
with console.status(
f"[bold][yellow]{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}[/yellow] - 第 {attempt} 次尝试..."
):
if stu_cnt_arr and stu_cnt_arr[int(target_index)][0] <= stu_cnt_arr[int(target_index)][1]: # pyright: ignore[reportOptionalSubscript]
console.print("[yellow]当前人数已满,等待下次尝试...[/]")
attempt += 1
time.sleep(1)
continue
elif not stu_cnt_arr:
# 获取列表失败,跳过余量检查
pass
code, msg, success = fetch_lecture(wid, s, v_code)
style = "green" if success else "yellow" if "繁忙" in msg else "red" if "频繁" in msg else "yellow"
console.print(f"[{style}]» 状态码: {code}\n 消息: {msg}\n 成功: {success}[/]")
if not v_code:
# 验证码为空,立即重新获取
v_code, v_img = get_code(ss=s, captcha_hash_table=captcha_hash_table)
continue
if "验证码错误" in msg:
# 保存验证码
if save_code:
with open(f"code_img/false/captcha_{attempt}_code{v_code}.jpg", "wb") as f:
f.write(v_img)
# 验证码错误后随机延迟 0.1-0.5 秒
random_delay = random.uniform(0.1, 0.5)
time.sleep(random_delay)
v_code, v_img = get_code(ss=s, captcha_hash_table=captcha_hash_table)
continue
else:
# 保存验证码
if save_code:
with open(f"code_img/true/captcha_{attempt}_code{v_code}.jpg", "wb") as f:
f.write(v_img)
if success:
console.print("[bold green]✓ 服务器返回预约成功,正在通过已预约列表确认...[/]")
# 定期查询已预约列表确认是否成功(每 check_interval 次或服务器返回成功时)
if attempt % check_interval == 0 or success:
with console.status("[bold cyan]正在查询已预约讲座列表确认结果...[/]"):
if check_booking_success(s, wid):
console.print(Panel.fit(
f"[bold green]🎉 抢课成功确认![/]\n讲座WID: {wid}\n讲座名称: {lecture_info['JZMC']}\n于第 {attempt} 次尝试确认成功",
title="✓ 成功"
))
success_confirmed = True
break
elif success:
console.print("[yellow]⚠ 服务器返回成功但已预约列表中未找到,可能存在延迟,继续尝试...[/]")
if "频繁" in msg:
console.print("[yellow]请求过于频繁,等待 10 秒后重试...[/]")
time.sleep(10)
attempt += 1
time.sleep(0.5)
except Exception as e:
console.print(f"[yellow]⚠ 异常(继续重试): {str(e)}[/]")
time.sleep(1)
# 退出处理
if success_confirmed:
console.print(Panel.fit("[bold]按任意键退出...[/]", title="完成"))
while True:
if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
sys.stdin.read(1)
console.print("[italic]退出程序[/]")
sys.exit(0)
time.sleep(0.1)