tongji-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (76) hide show
  1. tongji_cli/__init__.py +0 -0
  2. tongji_cli/__main__.py +3 -0
  3. tongji_cli/auth.py +167 -0
  4. tongji_cli/browser_session.py +15 -0
  5. tongji_cli/campus/__init__.py +0 -0
  6. tongji_cli/campus/bus.py +349 -0
  7. tongji_cli/campus/card_transactions.py +111 -0
  8. tongji_cli/campus/commands.py +92 -0
  9. tongji_cli/campus/dorm_energy.py +241 -0
  10. tongji_cli/campus/guides.py +132 -0
  11. tongji_cli/campus/notices.py +329 -0
  12. tongji_cli/campus/rooms_public.py +84 -0
  13. tongji_cli/campus/school_calendar.py +119 -0
  14. tongji_cli/campus/stadium.py +111 -0
  15. tongji_cli/campus/stadium_orders.py +80 -0
  16. tongji_cli/canvas/__init__.py +0 -0
  17. tongji_cli/canvas/api.py +492 -0
  18. tongji_cli/canvas/assignments.py +46 -0
  19. tongji_cli/canvas/commands.py +238 -0
  20. tongji_cli/canvas/compose.py +64 -0
  21. tongji_cli/canvas/discussion.py +159 -0
  22. tongji_cli/canvas/grades.py +74 -0
  23. tongji_cli/canvas/inbox.py +49 -0
  24. tongji_cli/canvas/navigation.py +56 -0
  25. tongji_cli/canvas/notifications.py +77 -0
  26. tongji_cli/canvas/quizzes.py +128 -0
  27. tongji_cli/canvas/submit.py +153 -0
  28. tongji_cli/canvas/thread_actions.py +157 -0
  29. tongji_cli/cli.py +102 -0
  30. tongji_cli/common.py +13 -0
  31. tongji_cli/display.py +106 -0
  32. tongji_cli/jw/__init__.py +0 -0
  33. tongji_cli/jw/announcements.py +91 -0
  34. tongji_cli/jw/applications.py +50 -0
  35. tongji_cli/jw/commands.py +177 -0
  36. tongji_cli/jw/competitions.py +66 -0
  37. tongji_cli/jw/forms.py +53 -0
  38. tongji_cli/jw/graduation.py +95 -0
  39. tongji_cli/jw/help.py +67 -0
  40. tongji_cli/jw/major_timetable.py +44 -0
  41. tongji_cli/jw/mentors.py +58 -0
  42. tongji_cli/jw/menu.py +58 -0
  43. tongji_cli/jw/personal_changes.py +121 -0
  44. tongji_cli/jw/progress.py +104 -0
  45. tongji_cli/jw/records.py +344 -0
  46. tongji_cli/jw/retake.py +202 -0
  47. tongji_cli/jw/schemes.py +121 -0
  48. tongji_cli/jw/syllabus.py +128 -0
  49. tongji_cli/jw/timetable.py +147 -0
  50. tongji_cli/library/__init__.py +0 -0
  51. tongji_cli/library/commands.py +110 -0
  52. tongji_cli/library/holdings.py +85 -0
  53. tongji_cli/library/loans.py +247 -0
  54. tongji_cli/library/room_booking.py +273 -0
  55. tongji_cli/library/rooms.py +45 -0
  56. tongji_cli/library/services.py +112 -0
  57. tongji_cli/library/space.py +257 -0
  58. tongji_cli/library/study.py +105 -0
  59. tongji_cli/media/__init__.py +0 -0
  60. tongji_cli/media/commands.py +35 -0
  61. tongji_cli/media/courses.py +65 -0
  62. tongji_cli/media/export.py +133 -0
  63. tongji_cli/media/sessions.py +69 -0
  64. tongji_cli/media/tasks.py +106 -0
  65. tongji_cli/portal/__init__.py +0 -0
  66. tongji_cli/portal/apply.py +139 -0
  67. tongji_cli/portal/certificate_download.py +107 -0
  68. tongji_cli/portal/commands.py +58 -0
  69. tongji_cli/portal/guides.py +214 -0
  70. tongji_cli/portal/legacy.py +273 -0
  71. tongji_cli/portal/records.py +158 -0
  72. tongji_cli/schedule.py +28 -0
  73. tongji_cli-0.1.0.dist-info/METADATA +248 -0
  74. tongji_cli-0.1.0.dist-info/RECORD +76 -0
  75. tongji_cli-0.1.0.dist-info/WHEEL +4 -0
  76. tongji_cli-0.1.0.dist-info/entry_points.txt +2 -0
tongji_cli/__init__.py ADDED
File without changes
tongji_cli/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from tongji_cli.cli import main
2
+
3
+ raise SystemExit(main())
tongji_cli/auth.py ADDED
@@ -0,0 +1,167 @@
1
+ import json
2
+ import os
3
+ import re
4
+ import subprocess
5
+ import sys
6
+ import time
7
+ from urllib.parse import urlsplit
8
+
9
+ from playwright.sync_api import Error, TimeoutError as BrowserTimeout, sync_playwright
10
+
11
+ from tongji_cli.media import courses as media_courses
12
+ from tongji_cli.browser_session import PROFILE, open_session
13
+ from tongji_cli.common import QueryUnavailable, failure
14
+ from tongji_cli.jw.commands import personal_change_command
15
+
16
+
17
+ SITES = {
18
+ "canvas": "https://canvas.tongji.edu.cn/courses",
19
+ "jw": "https://1.tongji.edu.cn/workbench",
20
+ "service": "https://all.tongji.edu.cn/",
21
+ "library": "https://www.lib.tongji.edu.cn/my/home/dashboard",
22
+ "space": "https://space.tongji.edu.cn/",
23
+ "card": "https://yikatong.tongji.edu.cn/",
24
+ "stadium": "https://stadium.tongji.edu.cn/pc/#/Venue/1",
25
+ "media": media_courses.ENTRY,
26
+ }
27
+
28
+
29
+ def observe(page, site):
30
+ host = urlsplit(page.url).hostname
31
+ if host == "iam.tongji.edu.cn":
32
+ return "login_required"
33
+ if host != urlsplit(SITES[site]).hostname:
34
+ return "unverified"
35
+ if site == "media":
36
+ return "authenticated" if page.get_by_text("我的课程", exact=True).first.is_visible() else "unverified"
37
+ if site == "service":
38
+ portal = page.frame_locator('iframe[src*="CUS_TEMPLATE_TONGJI"]')
39
+ return "authenticated" if portal.locator('#stepThree input[placeholder*="事项"]').is_visible() else "unverified"
40
+ if site == "stadium":
41
+ if page.get_by_text("退出", exact=True).filter(visible=True).count():
42
+ return "authenticated"
43
+ return "login_required" if page.get_by_text(re.compile(r"^\s*登\s*录\s*$")).filter(visible=True).count() else "unverified"
44
+ if site == "card":
45
+ if page.get_by_role("link", name="个人中心", exact=True).is_visible():
46
+ return "authenticated"
47
+ return "login_required" if page.get_by_role("link", name="统一认证登陆").is_visible() else "unverified"
48
+ if site == "space":
49
+ return "authenticated" if page.get_by_text("我的中心", exact=True).first.is_visible() else "unverified"
50
+ if site == "library":
51
+ if page.get_by_text("登录统一身份认证", exact=True).first.is_visible():
52
+ return "login_required"
53
+ return "authenticated" if page.get_by_role("link", name="图书借阅", exact=True).is_visible() else "unverified"
54
+ if site == "canvas":
55
+ if page.locator("#global_nav_profile_link").is_visible() and page.locator("#content").is_visible():
56
+ return "authenticated"
57
+ else:
58
+ if page.get_by_text(re.compile(r"^(退出登录|安全退出|个人课表|我的课表|我的选课)$")).filter(visible=True).count():
59
+ return "authenticated"
60
+ if page.get_by_text(re.compile(r"^(统一身份认证登录|统一身份认证|登录)$")).first.is_visible():
61
+ return "login_required"
62
+ return "unverified"
63
+
64
+
65
+ def visit(page, site, interactive):
66
+ if site == "space" and not interactive:
67
+ page.set_viewport_size({"width": 1280, "height": 720})
68
+ try:
69
+ page.goto(SITES[site], wait_until="commit", timeout=30000)
70
+ except Error:
71
+ if observe(page, site) != "login_required":
72
+ return "unreachable"
73
+ deadline = time.monotonic() + (600 if interactive else 12)
74
+ login_seen = None
75
+ opened_sso = False
76
+ stadium_menu_open = False
77
+ while time.monotonic() < deadline:
78
+ state = observe(page, site)
79
+ if state == "login_required":
80
+ if (interactive and site == "library" and not opened_sso
81
+ and urlsplit(page.url).hostname == urlsplit(SITES["library"]).hostname):
82
+ page.get_by_text("登录统一身份认证", exact=True).first.click()
83
+ opened_sso = True
84
+ elif site == "stadium" and not opened_sso and urlsplit(page.url).hostname == urlsplit(SITES[site]).hostname:
85
+ login = re.compile(r"^\s*登\s*录\s*$")
86
+ dialog = page.locator('[role=dialog]:visible').get_by_text(login)
87
+ if dialog.filter(visible=True).count():
88
+ dialog.filter(visible=True).last.click()
89
+ opened_sso = True
90
+ login_seen = None
91
+ continue
92
+ if not stadium_menu_open:
93
+ try:
94
+ page.get_by_text(login).filter(visible=True).first.click(timeout=1200)
95
+ except BrowserTimeout:
96
+ if observe(page, site) == "login_required":
97
+ raise
98
+ continue
99
+ stadium_menu_open = True
100
+ continue
101
+ elif site == "card" and not opened_sso and urlsplit(page.url).hostname == urlsplit(SITES["card"]).hostname:
102
+ page.get_by_role("link", name="统一认证登陆").click()
103
+ opened_sso = True
104
+ login_seen = None
105
+ continue
106
+ if login_seen is None:
107
+ login_seen = time.monotonic()
108
+ else:
109
+ login_seen = None
110
+ if state == "authenticated" or (not interactive and login_seen is not None and time.monotonic() - login_seen >= 3):
111
+ return state
112
+ page.wait_for_timeout(500)
113
+ return observe(page, site)
114
+
115
+
116
+ def signed_in_queries(args, now, site_items):
117
+ interactive = args.command == "login"
118
+ site_filter = getattr(args, "site", args.command)
119
+ if args.command in {"login", "status"} and site_filter == "all":
120
+ sites = list(SITES)
121
+ elif site_filter in SITES:
122
+ sites = [site_filter]
123
+ else:
124
+ sites = ["canvas", "jw"]
125
+ os.umask(0o077)
126
+ PROFILE.mkdir(parents=True, exist_ok=True, mode=0o700)
127
+ results = {}
128
+ with sync_playwright() as engine:
129
+ checkout_window = args.command == "sports" and args.operation == "reserve" and not args.preview
130
+ library_window = args.command == "library" and args.operation in {"study", "rooms"} and args.action == "reserve" and not args.preview
131
+ handoff = checkout_window or library_window or (personal_change_command(args) and not args.preview)
132
+ context = open_session(engine, PROFILE, interactive=interactive or bool(handoff), no_viewport=True)
133
+ try:
134
+ page = context.pages[0] if context.pages else context.new_page()
135
+ if interactive:
136
+ page.bring_to_front()
137
+ for site in sites:
138
+ if interactive:
139
+ print(f"正在打开 {site} 的学校页面,请在浏览器内完成认证。", file=sys.stderr, flush=True)
140
+ try:
141
+ state = visit(page, site, interactive)
142
+ entry = {"status": state}
143
+ if state == "authenticated" and args.command not in {"login", "status"}:
144
+ output = site_items(args, site, context, page, now)
145
+ if isinstance(output, dict):
146
+ entry.update(output)
147
+ else:
148
+ entry["items"] = output
149
+ results[site] = entry
150
+ except (Error, AssertionError, QueryUnavailable, OSError, ValueError, KeyError, TypeError) as error:
151
+ if page.is_closed():
152
+ raise
153
+ results[site] = failure(error)
154
+ finally:
155
+ context.close()
156
+ if interactive and any(entry["status"] == "authenticated" for entry in results.values()):
157
+ check = subprocess.run(
158
+ [sys.executable, "-m", "tongji_cli", "status", *(["--site", site_filter] if site_filter else []), "--json"],
159
+ capture_output=True, text=True,
160
+ )
161
+ if check.stdout.strip():
162
+ restarted = json.loads(check.stdout)
163
+ else:
164
+ restarted = {}
165
+ for site, entry in results.items():
166
+ entry["after_restart"] = restarted.get(site, {}).get("status", "unverified")
167
+ return results
@@ -0,0 +1,15 @@
1
+ import os
2
+ from pathlib import Path
3
+
4
+
5
+ CHANNEL = os.environ.get("TONGJI_BROWSER") or "chrome"
6
+ if CHANNEL not in {"chrome", "chromium"}:
7
+ raise SystemExit("TONGJI_BROWSER 支持 chrome 或 chromium")
8
+ PROFILE = Path.home() / ".local" / "share" / "tongji-cli" / CHANNEL
9
+
10
+
11
+ def open_session(engine, profile, *, interactive=False, no_viewport=False):
12
+ return engine.chromium.launch_persistent_context(
13
+ profile, channel=CHANNEL, headless=not interactive, no_viewport=no_viewport,
14
+ args=["--restore-last-session"], ignore_default_args=["about:blank"],
15
+ )
File without changes
@@ -0,0 +1,349 @@
1
+ import argparse
2
+ import hashlib
3
+ import re
4
+ from datetime import date, datetime, time, timedelta
5
+ from html import unescape
6
+ from urllib.parse import urljoin
7
+ from urllib.request import urlopen
8
+
9
+ from tongji_cli.common import QueryUnavailable, SHANGHAI
10
+ from tongji_cli.campus.school_calendar import open_data
11
+
12
+ BASE = "https://jiading.tongji.edu.cn"
13
+ INDEX = BASE + "/rctz/list.htm"
14
+ SERVICES = BASE + "/5916/list.htm"
15
+ CALENDAR_PATH = "/v1/rt/onetongji/calendar"
16
+ # The student timetable is a poster, signed May 2026. Only use this transcription
17
+ # while the student-services listing still points to the verified poster.
18
+ POSTER_SHA = "006c28d5c0e931340669e43af6cd5d62e9087e3afafd768e71dce5935dd46ce5"
19
+ REGULAR = {
20
+ "平日": {"嘉定": ["06:30", "12:15", "16:30"], "四平": ["08:45", "14:00", "20:30"]},
21
+ "周六": {"嘉定": ["06:30", "12:15"], "四平": ["11:00", "15:30", "17:30"]},
22
+ "周日": {"嘉定": ["06:30", "12:15"], "四平": ["11:00", "17:30"]},
23
+ }
24
+ STOPS = {"嘉定": "广楼南侧", "四平": "四平校区西南门停车场"}
25
+ SHUTTLE_STOPS = {"嘉定": "嘉三路近七号楼入口处", "上海汽车城": "曹安公路安谐路822路公交站点(靠地铁站一侧)"}
26
+ DZ1_STOPS = {"嘉定": SHUTTLE_STOPS["嘉定"], "封浜": "封浜公交站(位于出轨交14号线封浜站5号口后的翔封路对面)"}
27
+ DZ1_TIMES = [
28
+ ("06:50", "07:25"), ("08:10", "08:45"), ("09:50", "10:25"),
29
+ ("16:10", "16:45"), ("17:35", "18:10"), ("19:10", "19:45"),
30
+ ]
31
+ SHUTTLE_TIMES = [
32
+ ("06:25", "06:40"), ("06:40", "06:55"), ("06:55", "07:10"), ("07:10", "07:25"),
33
+ ("07:30", "07:45"), ("07:50", "08:05"), ("08:20", "08:35"), ("08:55", "09:10"),
34
+ ("09:30", "09:45"), ("10:10", "10:25"), ("10:45", "11:00"), ("11:45", "12:00"),
35
+ ("12:20", "12:35"), ("12:55", "13:10"), ("13:30", "13:45"), ("14:05", "14:20"),
36
+ ("14:40", "14:55"), ("15:15", "15:30"), ("16:00", "16:15"), ("16:40", "16:55"),
37
+ ("17:35", "17:50"), ("18:15", "18:30"), ("18:45", "19:00"), ("19:15", "19:30"),
38
+ ("19:45", "20:00"), ("20:15", "20:30"), ("20:45", "21:00"), ("21:15", "21:30"),
39
+ ("21:45", "22:20"),
40
+ ]
41
+ WEEKDAY_ONLY = {"06:25", "07:10", "12:55", "15:15"}
42
+ MD = r"(\d{1,2})月(\d{1,2})日"
43
+ WEEKDAY = r"(?:[((](?:星期|周)[一二三四五六日天][))])?"
44
+ SPAN = re.compile(MD + WEEKDAY + r"[至到—--](?:(\d{1,2})月)?(\d{1,2})日")
45
+
46
+
47
+ def configure(commands):
48
+ parser = commands.add_parser("bus", help="校区定班车与地铁短驳车")
49
+ operations = parser.add_subparsers(dest="operation", required=True)
50
+ sub = operations.add_parser("next", help="嘉定与四平校区之间的下一班学生定班车")
51
+ sub.add_argument("--from", dest="origin", required=True, choices=STOPS)
52
+ sub.add_argument("--to", dest="destination", required=True, choices=STOPS)
53
+ sub.add_argument("--at", type=parse_time, help="上海出发时间,如 2026-11-27T12:00")
54
+ shuttle = operations.add_parser("shuttle", help="嘉定校区往返11号线上海汽车城站、14号线封浜站的时刻与候车点")
55
+ shuttle.add_argument("--line", choices=("11", "14"), default="11", help="地铁线路,默认 11")
56
+ shuttle.add_argument("--date", type=date.fromisoformat, metavar="YYYY-MM-DD", help="默认上海今天")
57
+ shuttle.add_argument("--from", dest="origin", choices=("嘉定", "上海汽车城", "封浜"), help="默认查询双向")
58
+
59
+
60
+ def parse_time(value):
61
+ try:
62
+ instant = datetime.fromisoformat(value)
63
+ except ValueError:
64
+ raise argparse.ArgumentTypeError("请输入 ISO 日期或日期时间") from None
65
+ return instant.astimezone(SHANGHAI) if instant.tzinfo else instant.replace(tzinfo=SHANGHAI)
66
+
67
+
68
+ def run(args):
69
+ if args.operation == "shuttle":
70
+ return shuttle_timetable(args.date or datetime.now(SHANGHAI).date(), args.origin, args.line)
71
+ if args.origin == args.destination:
72
+ raise QueryUnavailable("嘉定与四平之间的定班车需要不同的起终点")
73
+ now = args.at or datetime.now(SHANGHAI)
74
+ if now.date() < date(2026, 6, 1):
75
+ raise QueryUnavailable("目前核对的时刻表署于 2026 年 5 月,更早班次未核实")
76
+ regular_source = regular_timetable_url()
77
+ tomorrow = now.date() + timedelta(days=1)
78
+ calendar = None
79
+ notices = [(published, url, title, article(url))
80
+ for published, url, title in student_notices(tomorrow)]
81
+ for day in (now.date(), tomorrow):
82
+ schedule = None
83
+ for published, url, title, body in notices:
84
+ if day < published:
85
+ continue
86
+ schedule = notice_schedule(body, title, published, day, args.origin, url)
87
+ if schedule is not None:
88
+ departures, label = schedule
89
+ source = url
90
+ break
91
+ if schedule is None:
92
+ if calendar is None:
93
+ calendar = open_data(CALENDAR_PATH, {"fromDate": now.date(), "endDate": tomorrow})
94
+ kind = str(calendar.get(day.isoformat()))
95
+ label = {"2": "平日", "3": "周六" if day.weekday() == 5 else "周日"}.get(kind)
96
+ if not label or (kind == "3" and day.weekday() < 5):
97
+ raise QueryUnavailable(f"{day} 校历或假期班车安排待核实。{INDEX}")
98
+ departures, source = REGULAR[label][args.origin], regular_source
99
+ for clock in departures:
100
+ departure = datetime.combine(day, time.fromisoformat(clock), SHANGHAI)
101
+ if departure >= now:
102
+ return [{"from": args.origin, "to": args.destination, "line": "学生定班车",
103
+ "departure": departure.isoformat(), "stop": STOPS[args.origin],
104
+ "schedule": label, "source": source, "regular_source": regular_source}]
105
+ raise QueryUnavailable(f"今日和次日均无可确认的后续班次。{INDEX}")
106
+
107
+
108
+ def fetch(url):
109
+ try:
110
+ with urlopen(url, timeout=12) as response:
111
+ return response.read()
112
+ except OSError:
113
+ raise QueryUnavailable(f"未能读取校方班车来源。{url}") from None
114
+
115
+
116
+ def article(url):
117
+ html = fetch(url).decode()
118
+ body = re.search(r"""<div\s+class=["']wp_articlecontent["']>(.*?)</div>""", html, re.S)
119
+ if not body:
120
+ raise QueryUnavailable(f"校方公告格式待核对。{url}")
121
+ return body[1]
122
+
123
+
124
+ def regular_timetable_url():
125
+ html = fetch(SERVICES).decode()
126
+ link = re.search(r"""<a href=['"]([^'"]+)['"][^>]*title=['"]学生班车时刻表['"]""", html)
127
+ if not link:
128
+ raise QueryUnavailable(f"未找到学生班车时刻表。{SERVICES}")
129
+ url = urljoin(BASE, link[1])
130
+ poster = re.search(r"""<img\b[^>]*?\ssrc=["']([^"']+)""", article(url))
131
+ if not poster or hashlib.sha256(fetch(urljoin(url, poster[1]))).hexdigest() != POSTER_SHA:
132
+ raise QueryUnavailable(f"学生班车时刻表图片已变动,原文时刻待重新核对。{url}")
133
+ return url
134
+
135
+
136
+ def student_notices(until, title_pattern="班车|定班车", since=date(2026, 5, 1)):
137
+ result = []
138
+ url = INDEX
139
+ while url:
140
+ html = fetch(url).decode()
141
+ links = re.findall(r"""<span>([\d-]{10})</span>\s*<a[^>]*>\s*<a href=['"]([^'"]+)['"][^>]*title=['"]([^'"]+)""", html)
142
+ if not links:
143
+ raise QueryUnavailable(f"班车通知目录格式待核对。{url}")
144
+ for stamp, href, title in links:
145
+ published = date.fromisoformat(stamp)
146
+ if published < since:
147
+ return result
148
+ if published > until or not re.search(title_pattern, title):
149
+ continue
150
+ if "教师班车" in title and not re.search("学生班车|定班车", title):
151
+ continue
152
+ if "三门路同济北苑" in title and "嘉定" not in title:
153
+ continue
154
+ result.append((published, urljoin(BASE, href), title))
155
+ next_page = re.search(r'<a class="next" href="([^"]+)"', html)
156
+ url = urljoin(url, next_page[1]) if next_page else None
157
+ return result
158
+
159
+
160
+ def plain(fragment):
161
+ return re.sub(r"\s+", "", unescape(re.sub(r"<[^>]+>", "", fragment)))
162
+
163
+
164
+ def shuttle_timetable(day, origin, line="11"):
165
+ stops = DZ1_STOPS if line == "14" else SHUTTLE_STOPS
166
+ if origin and origin not in stops:
167
+ raise QueryUnavailable(f"{line}号线接驳的出发站可选{'、'.join(stops)}。")
168
+ if day < date(2026, 6, 1):
169
+ raise QueryUnavailable(f"目前核对的短驳车时刻表署于 2026 年 5 月,更早班次未核实。{SERVICES}")
170
+ poster = regular_timetable_url()
171
+ schedule, changes = shuttle_overrides(day, line)
172
+ if schedule is None:
173
+ params = {"fromDate": day.isoformat(), "endDate": day.isoformat()}
174
+ kind = str(open_data(CALENDAR_PATH, params).get(day.isoformat()))
175
+ day_types = {"2": "工作日", "3": "双休日"} if line == "14" else {"1": "双休日", "2": "工作日", "3": "双休日"}
176
+ label = day_types.get(kind)
177
+ if not label:
178
+ raise QueryUnavailable(f"{day} 短驳车校历或假期安排待核实。{INDEX}")
179
+ schedule = label, None, poster
180
+ label, pairs, source = schedule
181
+ if pairs is None and line == "14":
182
+ pairs = DZ1_TIMES
183
+ elif pairs is None:
184
+ weekend = label == "双休日" or (label == "公告指定正常运行" and day.weekday() >= 5)
185
+ pairs = [pair for pair in SHUTTLE_TIMES if not (weekend and pair[0] in WEEKDAY_ONLY)
186
+ and (pair[0] != "16:00" or (not weekend and day.weekday() == 4))]
187
+ result = []
188
+ stations = list(stops)
189
+ for column, (station, stop) in enumerate(stops.items()):
190
+ if origin and station != origin:
191
+ continue
192
+ departures = {}
193
+ for pair in pairs:
194
+ pickup = changes.get((station, pair[column]), (stop, source))
195
+ departures.setdefault(pickup, []).append(pair[column])
196
+ for (pickup_stop, pickup_source), times in departures.items():
197
+ row = {"date": day.isoformat(), "line": "14号线嘉定DZ1线" if line == "14" else "11号线短驳车", "from": station,
198
+ "to": stations[1 - column], "stop": pickup_stop,
199
+ "departures": times, "schedule": label, "source": source, "regular_source": poster}
200
+ if station == "封浜":
201
+ row["notes"] = "封浜站具体发车时间以公交车到站时间为准"
202
+ if pickup_source != source:
203
+ row["stop_source"] = pickup_source
204
+ result.append(row)
205
+ return result
206
+
207
+
208
+ def shuttle_overrides(day, line):
209
+ schedule = None
210
+ changes = {}
211
+ # The verified poster image was published May 26, after the May 21 DZ1 adjustment.
212
+ if line == "14":
213
+ notices = student_notices(day, "学生班车|短驳车|14号线|DZ1|封浜|定制公交", since=date(2026, 5, 27))
214
+ else:
215
+ notices = student_notices(day, "学生班车|短驳车|上海汽车城")
216
+ other = "11" if line == "14" else "14"
217
+ for published, url, title in notices:
218
+ if other + "号线" in title and line + "号线" not in title:
219
+ continue
220
+ body = article(url)
221
+ if re.fullmatch(r"关于\d{1,2}月\d{1,2}日短驳车发车点临时调整的通知", title):
222
+ month, number = map(int, re.search(MD, title).groups())
223
+ if day == date(published.year, month, number):
224
+ changes.update(shuttle_stop_changes(body, url))
225
+ else:
226
+ override = shuttle_notice(body, published, day, url, line)
227
+ if schedule is None and override:
228
+ schedule = override
229
+ return schedule, changes
230
+
231
+
232
+ def table_rows(table):
233
+ return [[plain(cell) for cell in re.findall(r"<td\b[^>]*>(.*?)</td>", row, re.S)]
234
+ for row in re.findall(r"<tr\b[^>]*>(.*?)</tr>", table, re.S)]
235
+
236
+
237
+ def shuttle_stop_changes(body, url):
238
+ rows = table_rows(body)
239
+ if not rows or rows[0] != ["涉及出发时刻", "原发车点", "临时调整发车点"] or len(rows) < 2:
240
+ raise QueryUnavailable(f"短驳车临时发车点待核实。{url}")
241
+ changes = {}
242
+ for row in rows[1:]:
243
+ if len(row) != 3 or row[1] != SHUTTLE_STOPS["嘉定"] or not row[2]:
244
+ raise QueryUnavailable(f"短驳车临时发车点待核实。{url}")
245
+ clocks = re.findall(r"\d{1,2}:\d{2}", row[0])
246
+ if not clocks or "".join(clocks) != row[0]:
247
+ raise QueryUnavailable(f"临时调整发车点的班次待核实。{url}")
248
+ changes.update({("嘉定", clock.zfill(5)): (row[2], url) for clock in clocks})
249
+ return changes
250
+
251
+
252
+ def notice_period(text, published):
253
+ intro = text.split("学生班车安排如下")[0]
254
+ stated_year = re.search(r"(20\d{2})年", intro)
255
+ year = int(stated_year[1]) if stated_year else published.year
256
+ return year, SPAN.search(intro)
257
+
258
+
259
+ def is_makeup_day(text, year, day):
260
+ makeup = re.search(r"((?:" + MD + WEEKDAY + r"[、,,]?)+)(?:上课、上班|上班、上课)[,,]学生班车按工作日", text)
261
+ return makeup and any(day == date(year, int(m), int(d)) for m, d in re.findall(MD, makeup[1]))
262
+
263
+
264
+ def shuttle_notice(body, published, day, url, line):
265
+ text = plain(body)
266
+ year, period = notice_period(text, published)
267
+ if not period:
268
+ raise QueryUnavailable(f"短驳车变更公告适用日期待核实。{url}")
269
+ if is_makeup_day(text, year, day):
270
+ return "工作日", None, url
271
+ if not in_span(period, year, day):
272
+ return None
273
+ if line == "14":
274
+ section = re.search(r"(?:三|3)[、..]轨道交通14号线(?:短驳车|定制公交(?:嘉定)?DZ1线)[((][^))]+[))](.*?)(?:注[::]|特此通知|$)", text)
275
+ if section and re.fullmatch(r"(?:端午节|暑假|中秋节|国庆节)期间(?:按时刻表)?正常运行[。.]?", section[1]):
276
+ return "公告指定正常运行", None, url
277
+ raise QueryUnavailable(f"14号线嘉定DZ1线临时安排待核实。{url}")
278
+ section = re.search(r"(?:二|2)[、..]轨道交通11号线短驳车[((][^))]+[))](.*?)(?:三|3)[、..]", text)
279
+ if section:
280
+ arrangement = section[1]
281
+ if re.fullmatch(r"[^。]*期间按双休日时刻表运行[。.]?", arrangement):
282
+ return "双休日", None, url
283
+ if re.search("停开|停运|取消|调整发车点", arrangement):
284
+ raise QueryUnavailable(f"短驳车临时安排请见校方原文。{url}")
285
+ normal = re.search(r"正常运行至" + MD, arrangement)
286
+ if normal and day <= date(year, *map(int, normal.groups())):
287
+ return "公告指定正常运行", None, url
288
+ bounds = SPAN.search(arrangement)
289
+ if not bounds or in_span(bounds, year, day):
290
+ for table in re.findall(r"<table\b[^>]*>.*?</table>", body, re.S):
291
+ rows = table_rows(table)
292
+ if rows and rows[0] == ["嘉定校区发车时间", "上海汽车城站返回时间"]:
293
+ if len(rows) > 1 and all(len(row) == 2 and all(re.fullmatch(r"\d{1,2}:\d{2}", t)
294
+ for t in row) for row in rows[1:]):
295
+ return "校方临时时刻表", [(a.zfill(5), b.zfill(5)) for a, b in rows[1:]], url
296
+ raise QueryUnavailable(f"短驳车临时安排请见校方原文。{url}")
297
+
298
+
299
+ def in_span(match, year, day):
300
+ month1, day1, month2, day2 = (int(v) if v else None for v in match.groups())
301
+ end_month = month2 or month1
302
+ return date(year, month1, day1) <= day <= date(year + int(end_month < month1), end_month, day2)
303
+
304
+
305
+ def notice_schedule(body, title, published, day, origin, url):
306
+ text = plain(body)
307
+ year, period = notice_period(text, published)
308
+ if is_makeup_day(text, year, day):
309
+ return REGULAR["平日"][origin], "公告指定工作日"
310
+ if not period:
311
+ dates = re.findall(MD, title)
312
+ if len(dates) == 1 and not re.search("起|开始|恢复", title) and ("当天" in text or "当日" in text):
313
+ month, day_of_month = map(int, dates[0])
314
+ if day != date(year, month, day_of_month):
315
+ return None
316
+ raise QueryUnavailable(f"班车变更公告的适用日期或新安排待核实。{url}")
317
+ if not in_span(period, year, day):
318
+ return None
319
+ section = re.search(r"一[、..]定班车(.*?)(?:二[、..]|$)", text)
320
+ if not section:
321
+ raise QueryUnavailable(f"假期定班车安排待核实。{url}")
322
+ if re.search(r"发车点.{0,8}(?:调整|改为|迁)|(?:调整|变更).{0,5}发车点", section[1]):
323
+ raise QueryUnavailable(f"定班车发车地点变更待核实。{url}")
324
+ tables = re.findall(r"<table\b[^>]*>.*?</table>", body, re.S)
325
+ cursor = 0
326
+ for table in tables:
327
+ position = body.index(table, cursor)
328
+ preceding = plain(body[cursor:position])
329
+ cursor = position + len(table)
330
+ rows = table_rows(table)
331
+ if not rows or rows[0][-2:] != ["嘉定校区", "四平路校区"]:
332
+ continue
333
+ bounds = list(SPAN.finditer(preceding))
334
+ if bounds and not in_span(bounds[-1], year, day):
335
+ continue
336
+ clocks = []
337
+ applies = True
338
+ for row in rows[1:]:
339
+ if "双休日" in row:
340
+ applies = day.weekday() >= 5
341
+ elif "周一至周五" in row:
342
+ applies = day.weekday() < 5
343
+ if applies:
344
+ if len(row) < 2 or not all(re.fullmatch(r"\d{1,2}:\d{2}", t) for t in row[-2:]):
345
+ raise QueryUnavailable(f"临时班车时刻待核实。{url}")
346
+ clocks.append(row[-2 if origin == "嘉定" else -1].zfill(5))
347
+ if clocks:
348
+ return sorted(clocks), "校方临时安排"
349
+ raise QueryUnavailable(f"公告未列出可确认的定班车时刻。{url}")
@@ -0,0 +1,111 @@
1
+ from urllib.parse import urlsplit
2
+
3
+ from playwright.sync_api import TimeoutError as BrowserTimeout, expect
4
+
5
+ from tongji_cli.common import QueryUnavailable
6
+
7
+
8
+ def transactions(page, start, end):
9
+ if start > end:
10
+ raise QueryUnavailable("起始日期不能晚于截止日期")
11
+ page.get_by_role("link", name="个人中心", exact=True).click()
12
+ frame = page.frame_locator('iframe[name="comepage"]')
13
+ menu = page.locator(".side-menu-box h2").filter(has_text="我的校园卡").first
14
+ menu.hover(position={"x": 25, "y": 12})
15
+ link = menu.get_by_text("流水信息", exact=True).filter(visible=True).last
16
+ with report_response(page):
17
+ link.click()
18
+ dates = frame.locator("input.textbox-text:visible")
19
+ choose_date(frame, dates.nth(0), start)
20
+ choose_date(frame, dates.nth(1), end)
21
+ with report_response(page) as first:
22
+ frame.get_by_text("查询", exact=True).filter(visible=True).click()
23
+ return read_pages(page, frame, first.value)
24
+
25
+
26
+ def choose_date(frame, field, day):
27
+ field.click()
28
+ calendar = frame.locator(".calendar:visible")
29
+ cell = calendar.locator(f'td.calendar-day[abbr="{day.year},{day.month},{day.day}"]')
30
+ if not cell.count() or "calendar-other-month" in (cell.get_attribute("class") or ""):
31
+ calendar.locator(".calendar-title").click()
32
+ calendar.locator(".calendar-menu-year").fill(str(day.year))
33
+ calendar.locator(f'.calendar-menu-month[abbr="{day.month}"]').click()
34
+ cell.click(timeout=5000)
35
+ if field.input_value() != day.isoformat():
36
+ raise QueryUnavailable("日期选择器未选中指定日期")
37
+
38
+
39
+ def report_response(page):
40
+ return page.expect_response(lambda r: r.request.frame.name == "comepage" and
41
+ urlsplit(r.url).path == "/Report/GetPersonTrjn", timeout=20000)
42
+
43
+
44
+ def read_pages(page, frame, response):
45
+ grid = frame.locator(".datagrid-view2:visible")
46
+ headers = grid.locator(".datagrid-header td[field]:visible")
47
+ headers.first.wait_for(timeout=10000)
48
+ columns = headers.evaluate_all("es=>es.map(e=>[e.getAttribute('field'),e.innerText.trim()])")
49
+ labels = [label for _, label in columns]
50
+ fields = [key for key, _ in columns]
51
+ if not {"OCCTIME", "TRANAMT", "TRANNAME"}.issubset(fields):
52
+ raise QueryUnavailable("一卡通流水表头待核实")
53
+ items = []
54
+ total = None
55
+ number = 1
56
+ while True:
57
+ if not response.ok:
58
+ raise QueryUnavailable(f"一卡通查询返回 HTTP {response.status}")
59
+ # 校方正常返回流水时也会给出 issucceed=false,按页码、总数和实际显示的记录核对。
60
+ data = response.json()
61
+ if total is None:
62
+ total = data["total"]
63
+ if total != data["total"] or not isinstance(total, int) or not isinstance(data["rows"], list):
64
+ raise QueryUnavailable("一卡通流水总数或分页数据待核实")
65
+ expected = [[row[key] for key in fields] for row in data["rows"]]
66
+ try:
67
+ expect(frame.locator("input.pagination-num")).to_have_value(str(number if total else 0))
68
+ values = rendered_rows(page.frame(name="comepage"), fields, expected)
69
+ except (AssertionError, BrowserTimeout):
70
+ raise QueryUnavailable("页面显示的流水记录与一卡通本次查询结果不一致") from None
71
+ items.extend(dict(zip(labels, (value or None for value in row))) for row in values)
72
+ if len(items) == total:
73
+ return items
74
+ next_page = frame.locator("a:visible").filter(has=frame.locator(".pagination-next"))
75
+ if not expected or len(items) > total or not next_page.count() or "l-btn-disabled" in (next_page.get_attribute("class") or ""):
76
+ raise QueryUnavailable("已加载流水记录数与一卡通总数不一致")
77
+ with report_response(page) as following:
78
+ next_page.click()
79
+ response = following.value
80
+ number += 1
81
+
82
+
83
+ def rendered_rows(frame, fields, expected):
84
+ snapshot = frame.wait_for_function("""({fields, expected}) => {
85
+ const grid = [...document.querySelectorAll('.datagrid-view2')].find(e => e.getClientRects().length);
86
+ if (!grid) return false;
87
+ const rows = [...grid.querySelectorAll('.datagrid-body tr.datagrid-row')].filter(r => r.getClientRects().length);
88
+ if (rows.length !== expected.length) return false;
89
+ const values = [];
90
+ for (const [i, row] of rows.entries()) {
91
+ const cells = [...row.querySelectorAll('td[field]')].filter(c => c.getClientRects().length);
92
+ if (cells.length !== fields.length) return false;
93
+ const display = [];
94
+ for (const [j, cell] of cells.entries()) {
95
+ if (cell.getAttribute('field') !== fields[j]) return false;
96
+ const text = cell.innerText.trim();
97
+ const raw = expected[i][j];
98
+ if (text !== String(raw ?? '').trim()) {
99
+ if (raw == null || raw === '' || !text || !['TRANAMT', 'CARDBAL'].includes(fields[j]) ||
100
+ Number(text) !== Number(raw)) return false;
101
+ }
102
+ display.push(text);
103
+ }
104
+ values.push(display);
105
+ }
106
+ return values;
107
+ }""", arg={"fields": fields, "expected": expected}, timeout=10000)
108
+ try:
109
+ return snapshot.json_value()
110
+ finally:
111
+ snapshot.dispose()