From 4cf43c8787d7c47afd179ceefb7b668f2801b763 Mon Sep 17 00:00:00 2001 From: gfdfdxc <29912959+gfdfdxc@users.noreply.github.com> Date: Tue, 3 Nov 2026 03:48:48 +0800 Subject: [PATCH 1/8] feat(schedule): add graduate timetable support --- lib/models/campus_identity.dart | 75 ++ lib/models/graduate_schedule.dart | 383 ++++++++++ lib/pages/schedule_page.dart | 223 +++++- lib/services/assignment_service.dart | 9 + lib/services/graduate_schedule_client.dart | 257 +++++++ lib/services/http_client.dart | 92 +++ lib/services/schedule_service.dart | 273 ++++++- lib/services/storage_service.dart | 58 ++ test/campus_identity_test.dart | 163 +++++ test/graduate_schedule_test.dart | 781 +++++++++++++++++++++ test/schedule_fetch_coalescing_test.dart | 25 +- 11 files changed, 2331 insertions(+), 8 deletions(-) create mode 100644 lib/models/campus_identity.dart create mode 100644 lib/models/graduate_schedule.dart create mode 100644 lib/services/graduate_schedule_client.dart create mode 100644 test/campus_identity_test.dart create mode 100644 test/graduate_schedule_test.dart diff --git a/lib/models/campus_identity.dart b/lib/models/campus_identity.dart new file mode 100644 index 00000000..bf768bfe --- /dev/null +++ b/lib/models/campus_identity.dart @@ -0,0 +1,75 @@ +enum CampusStudentKind { undergraduate, graduate, unknown } + +enum CampusScheduleSource { automatic, undergraduate, graduate } + +/// An authoritative response that cannot safely reuse a previous classification. +class CampusIdentityConflict extends FormatException { + const CampusIdentityConflict(super.message); +} + +/// A classification of the current IDS principal, never a guess from a student +/// number or from whether another school's application happens to open. +class CampusIdentity { + const CampusIdentity(this.kind, this.categoryName); + + final CampusStudentKind kind; + final String categoryName; + + factory CampusIdentity.fromIds( + Map profile, + String expectedSid, { + Map? associatedAccounts, + }) { + final data = profile['datas']; + if (profile['code']?.toString() != '0' || data is! Map) { + throw const FormatException('IDS 用户信息读取失败,请检查学校登录会话'); + } + final uid = data['uid']?.toString().trim() ?? ''; + if (uid.isEmpty) { + throw const FormatException('IDS 当前账号信息缺少 uid,无法识别身份'); + } + // A phone/email login or an older CpDaily binding may not include a school + // number. In that case the authenticated CASTGC principal remains the + // authority; never compare its uid with an empty string or an internal UUID. + if (expectedSid.trim().isNotEmpty && uid != expectedSid.trim()) { + throw const CampusIdentityConflict('IDS 当前账号与学校绑定学号不一致,请检查 CpDaily / IDS 绑定'); + } + var category = data['categoryName']?.toString().trim() ?? ''; + if (category.isEmpty && associatedAccounts != null) { + final rows = associatedAccounts['bindingUserList']; + if (rows is List) { + final matches = rows + .whereType>() + .where((r) => r['userId']?.toString() == uid && r['accountStatus'] == '账号正常') + .toList(); + if (matches.length == 1) category = matches.single['categoryName']?.toString().trim() ?? ''; + } + } + return CampusIdentity.fromCategory(category); + } + + factory CampusIdentity.fromCategory(String category) { + final label = category.replaceAll(RegExp(r'\s+'), ''); + if (RegExp('校友|离校|毕业|教职工|教师|退休').hasMatch(label)) { + return CampusIdentity(CampusStudentKind.unknown, category); + } + final undergraduate = label.contains('本科'); + final graduate = RegExp('研究生|硕士|博士').hasMatch(label); + return CampusIdentity( + undergraduate == graduate + ? CampusStudentKind.unknown + : undergraduate + ? CampusStudentKind.undergraduate + : CampusStudentKind.graduate, + category, + ); + } + + Map toJson() => {'kind': kind.name, 'categoryName': categoryName}; + + factory CampusIdentity.fromJson(Map json) { + final identity = CampusIdentity.fromCategory(json['categoryName'] as String? ?? ''); + if (json['kind'] != identity.kind.name) throw const FormatException('学生身份缓存无效'); + return identity; + } +} diff --git a/lib/models/graduate_schedule.dart b/lib/models/graduate_schedule.dart new file mode 100644 index 00000000..e39ca674 --- /dev/null +++ b/lib/models/graduate_schedule.dart @@ -0,0 +1,383 @@ +import 'dart:convert'; + +import 'course_table.dart'; + +const graduateTableId = 'graduate'; +const graduateSemesterPrefix = 'graduate:'; + +/// The read-only loadKbxx response, reduced to course/calendar fields. It never +/// contains the student profile, login initialization, CSRF tokens or cookies. +class GraduateSchedule { + GraduateSchedule._(this.data); + final Map data; + + factory GraduateSchedule.fromJson(Map raw) { + for (final key in ['results', 'xkjgList', 'ntkmdList']) { + if (raw[key] is! List) throw FormatException('研究生课表缺少 $key 列表'); + } + final periods = + raw['skjcList'] is String ? jsonDecode(raw['skjcList'] as String) : raw['skjcList']; + if (periods is! List) throw const FormatException('研究生课表节次格式变化'); + const fields = [ + 'XNXQDM', + 'XNXQMC', + 'KCDM', + 'KCMC', + 'BJDM', + 'BJMC', + 'JSXM', + 'RKJS', + 'JASMC', + 'PKSJDD', + 'PKSJDDMS', + 'XQ', + 'KSJCDM', + 'JSJCDM', + 'ZCMC', + 'RQ', + 'rqs', + 'JCFADM', + 'JCFAMC', + 'BYBZ', + ]; + Map select(Map row, List keys) => { + for (final key in keys) + if (row.containsKey(key)) key: row[key], + }; + return GraduateSchedule._({ + for (final key in ['results', 'xkjgList', 'ntkmdList']) + key: (raw[key] as List).map((r) => select(r as Map, fields)).toList(), + 'skjcList': + periods.map((r) => select(r as Map, ['DM', 'MC', 'KSSJ', 'JSSJ', 'JCFADM'])).toList(), + 'mrjcfadm': raw['mrjcfadm'], + 'currentTerm': raw['currentTerm'], + 'currentTermName': raw['currentTermName'], + 'rqpkjgallList': (raw['rqpkjgallList'] as List? ?? const []) + .map((r) => select(r as Map, ['bjdm', 'kssj', 'jssj', 'rq', 'rqs'])) + .toList(), + }); + } + + Map toJson() => data; + List> _rows(String key) => (data[key] as List).cast>(); + List> get rows => _rows('results'); + String _text(dynamic value) => value?.toString().trim() ?? ''; + String rawTerm(String semesterId) => semesterId.substring(graduateSemesterPrefix.length); + bool _inTerm(Map row, String term) => _text(row['XNXQDM']) == term; + + SemesterInfo get semesterInfo { + final labels = {}; + for (final row in [...rows, ..._rows('xkjgList'), ..._rows('ntkmdList')]) { + final id = _text(row['XNXQDM']); + if (id.isNotEmpty) { + final name = _text(row['XNXQMC']); + labels[id] = name.isEmpty ? (labels[id] ?? id) : name; + } + } + final current = _text(data['currentTerm']); + if (current.isNotEmpty) { + labels[current] = + _text(data['currentTermName']).isEmpty ? current : _text(data['currentTermName']); + } + if (labels.isEmpty) throw const FormatException('学校没有返回可识别的研究生学期'); + final semesters = >{}; + for (final entry in labels.entries) { + final match = RegExp(r'(\d{4})\s*[-—–~~]\s*(\d{4})').firstMatch(entry.value); + final year = match == null ? entry.value : '${match[1]}-${match[2]}'; + final term = ['秋', '春', '暑'].where(entry.value.contains).firstOrNull ?? entry.value; + // Keep unknown official labels instead of guessing numeric term codes. + semesters.putIfAbsent(year, () => {})[term] = '$graduateSemesterPrefix${entry.key}'; + } + final defaultId = labels.containsKey(current) ? current : (labels.keys.toList()..sort()).last; + return SemesterInfo( + semesters: semesters, + defaultSemester: '$graduateSemesterPrefix$defaultId', + tableId: graduateTableId, + ); + } + + Map schemesFor(String semesterId) { + final result = {}; + for (final row in rows.where((r) => _inTerm(r, rawTerm(semesterId)))) { + final id = _text(row['JCFADM']); + if (id.isNotEmpty) { + result[id] = _text(row['JCFAMC']).isEmpty ? '节次方案 $id' : _text(row['JCFAMC']); + } + } + if (result.isEmpty) { + final id = _text(data['mrjcfadm']); + result[id] = '默认节次方案'; + } + return result; + } + + String defaultScheme(String semesterId) { + final schemes = schemesFor(semesterId); + final preferred = _text(data['mrjcfadm']); + return schemes.containsKey(preferred) ? preferred : schemes.keys.first; + } + + List> unarrangedFor(String semesterId) { + final term = rawTerm(semesterId); + final arranged = rows.where((r) => _inTerm(r, term)).map((r) => _text(r['BJDM'])).toSet(); + final cancelled = cancelledFor(semesterId).map((r) => _text(r['BJDM'])).toSet(); + return _rows('xkjgList') + .where( + (r) => + _inTerm(r, term) && + !arranged.contains(_text(r['BJDM'])) && + !cancelled.contains(_text(r['BJDM'])), + ) + .toList(); + } + + List> cancelledFor(String semesterId) => _rows('ntkmdList') + .where((r) => _text(r['XNXQDM']).isEmpty || _inTerm(r, rawTerm(semesterId))) + .toList(); + + CourseTable tableFor(String semesterId, String scheme, {DateTime? firstMonday}) { + final periods = []; + for (final p in _rows('skjcList')) { + if (_text(p['JCFADM']) != scheme) continue; + final index = int.tryParse(_text(p['DM'])); + if (index == null || index < 1) throw const FormatException('无法识别研究生节次编号'); + periods.add( + CoursePeriod( + index: index, + timeRange: '${graduateTime(p['KSSJ'])}-${graduateTime(p['JSSJ'])}', + ), + ); + } + periods.sort((a, b) => a.index.compareTo(b.index)); + final cancelled = + cancelledFor(semesterId).map((r) => _text(r['BJDM'])).where((id) => id.isNotEmpty).toSet(); + final courses = []; + final anchor = firstMonday ?? firstMondayFor(semesterId); + for (final row in rows.where((r) => _inTerm(r, rawTerm(semesterId)))) { + if (_text(row['JCFADM']).isNotEmpty && _text(row['JCFADM']) != scheme) continue; + if (cancelled.contains(_text(row['BJDM']))) continue; + final day = int.tryParse(_text(row['XQ'])); + final first = int.tryParse(_text(row['KSJCDM'])); + final last = int.tryParse(_text(row['JSJCDM'])); + if (day == null || + day < 1 || + day > 7 || + first == null || + last == null || + first < 1 || + last < first || + last > 100) { + throw const FormatException('研究生课表的星期或节次无法识别'); + } + final units = [for (var unit = first; unit <= last; unit++) unit]; + if (units.any((n) => !periods.any((p) => p.index == n))) { + throw const FormatException('研究生课表的排课与节次方案不匹配'); + } + final dates = _datesFor(row, semesterId); + final weeksByDay = >{}; + if (anchor != null && dates.isNotEmpty) { + final monday = DateTime.utc(anchor.year, anchor.month, anchor.day); + for (final date in dates) { + final offset = date.difference(monday).inDays; + if (offset < 0 || offset >= 60 * 7) { + throw const FormatException('课程日期超出学期范围,请核对第 1 周周一'); + } + weeksByDay.putIfAbsent(date.weekday, () => {}).add(offset ~/ 7 + 1); + } + } else if (_text(row['ZCMC']).isNotEmpty) { + weeksByDay[day] = graduateWeeks(_text(row['ZCMC'])).toSet(); + } else if (dates.isEmpty) { + throw const FormatException('研究生课程缺少可识别的周次和日期'); + } + // Date-only records wait for a confirmed first Monday; they must not be + // invented as weekly recurring courses. The page exposes the date control. + for (final entry in weeksByDay.entries) { + final weeks = entry.value.toList()..sort(); + final bits = List.filled(weeks.last + 1, '0'); + for (final week in weeks) { + bits[week] = '1'; + } + courses.add( + EamsCourse( + name: _text(row['KCMC']), + classroom: _text(row['JASMC']), + teachers: _text(row['JSXM']).isEmpty ? _text(row['RKJS']) : _text(row['JSXM']), + weeks: bits.join(), + times: {entry.key: units}, + ), + ); + } + } + return CourseTable(periods: periods, courses: courses); + } + + List _datesFor(Map row, String semesterId) { + var values = []; + if (_text(row['RQ']).isNotEmpty) { + values = [row['RQ']]; + } else if (row['rqs'] is List && (row['rqs'] as List).isNotEmpty) { + values = row['rqs'] as List; + } else if (_text(row['BJDM']).isNotEmpty && + rows + .where( + (r) => + _inTerm(r, rawTerm(semesterId)) && + r['BJDM'] == row['BJDM'] && + _text(r['KSJCDM']) == _text(row['KSJCDM']) && + _text(r['JSJCDM']) == _text(row['JSJCDM']), + ) + .length == + 1) { + final scheme = + _text(row['JCFADM']).isEmpty ? defaultScheme(semesterId) : _text(row['JCFADM']); + final periods = _rows('skjcList').where((p) => _text(p['JCFADM']) == scheme); + final first = periods.where((p) => _text(p['DM']) == _text(row['KSJCDM'])).firstOrNull; + final last = periods.where((p) => _text(p['DM']) == _text(row['JSJCDM'])).firstOrNull; + if (first != null && last != null) { + for (final record in _rows('rqpkjgallList')) { + if (record['bjdm'] == row['BJDM'] && + graduateTime(record['kssj']) == graduateTime(first['KSSJ']) && + graduateTime(record['jssj']) == graduateTime(last['JSSJ'])) { + if (_text(record['rq']).isNotEmpty) values.add(record['rq']); + if (record['rqs'] is List) values.addAll(record['rqs'] as List); + } + } + } + } + return _parseDates(values); + } + + List _parseDates(List values) => values + .map((value) { + final text = _text(value).replaceAll('/', '-').replaceAllMapped( + RegExp(r'^(\d{4})(\d{2})(\d{2})$'), + (m) => '${m[1]}-${m[2]}-${m[3]}', + ); + final match = RegExp(r'^(\d{4})-(\d{1,2})-(\d{1,2})$').firstMatch(text); + if (match == null) throw const FormatException('研究生课程日期无法识别'); + final year = int.parse(match[1]!); + final month = int.parse(match[2]!); + final day = int.parse(match[3]!); + final date = DateTime.utc(year, month, day); + if (date.year != year || date.month != month || date.day != day) { + throw const FormatException('研究生课程日期无效'); + } + return date; + }) + .toSet() + .toList() + ..sort(); + + /// Infer a Monday from consistent dated sessions and their teaching weeks. + /// Ambiguous or conflicting dates keep the local date picker as a fallback. + DateTime? firstMondayFor(String semesterId) { + if (_rows('rqpkjgallList').any((r) => _text(r['rq']).isNotEmpty)) { + return _firstMondayFromCalendarRecords(semesterId); + } + final anchors = {}; + for (final row in rows.where((r) => _inTerm(r, rawTerm(semesterId)))) { + if (_text(row['ZCMC']).isEmpty) continue; + final dates = _datesFor(row, semesterId); + final weeks = graduateWeeks(_text(row['ZCMC'])); + if (dates.isEmpty || dates.length != weeks.length) continue; + final day = int.tryParse(_text(row['XQ'])); + for (var i = 0; i < dates.length; i++) { + final date = dates[i]; + if (date.weekday != day) return null; + anchors.add(date.subtract(Duration(days: (weeks[i] - 1) * 7 + date.weekday - 1))); + } + } + if (anchors.length != 1) return null; + final date = anchors.single; + return DateTime(date.year, date.month, date.day); + } + + /// Match all dated class/clock groups against their possible teaching weeks. + /// Missing holiday sessions are allowed; a partial date range that fits more + /// than one Monday stays unknown. At least two independent classes must agree. + DateTime? _firstMondayFromCalendarRecords(String semesterId) { + final cancelled = cancelledFor(semesterId).map((r) => _text(r['BJDM'])).toSet(); + final groups = >>{}; + String clockKey(String id, dynamic first, dynamic last) => + '$id|${graduateTime(first)}|${graduateTime(last)}'; + for (final row in rows.where((r) => _inTerm(r, rawTerm(semesterId)))) { + final id = _text(row['BJDM']); + if (id.isEmpty || cancelled.contains(id) || _text(row['ZCMC']).isEmpty) continue; + final scheme = + _text(row['JCFADM']).isEmpty ? defaultScheme(semesterId) : _text(row['JCFADM']); + final periods = _rows('skjcList').where((p) => _text(p['JCFADM']) == scheme); + final first = periods.where((p) => _text(p['DM']) == _text(row['KSJCDM'])).firstOrNull; + final last = periods.where((p) => _text(p['DM']) == _text(row['JSJCDM'])).firstOrNull; + if (first == null || last == null) continue; + groups.putIfAbsent(clockKey(id, first['KSSJ'], last['JSSJ']), () => []).add(row); + } + final dates = >{}; + for (final record in _rows('rqpkjgallList')) { + final id = _text(record['bjdm']); + if (id.isEmpty || cancelled.contains(id)) continue; + final key = clockKey(id, record['kssj'], record['jssj']); + if (!groups.containsKey(key)) continue; + dates.putIfAbsent(key, () => []).addAll(_parseDates([ + if (_text(record['rq']).isNotEmpty) record['rq'], + if (record['rqs'] is List) ...(record['rqs'] as List), + ]),); + } + Set? candidates; + final supportingClasses = {}; + for (final entry in dates.entries) { + Set? groupCandidates; + for (final date in entry.value.toSet()) { + final possible = {}; + for (final row in groups[entry.key]!) { + // A shifted weekday cannot identify its original teaching week. + if (int.tryParse(_text(row['XQ'])) != date.weekday) continue; + for (final week in graduateWeeks(_text(row['ZCMC']))) { + possible.add(date.subtract(Duration(days: (week - 1) * 7 + date.weekday - 1))); + } + } + if (possible.isEmpty) continue; + groupCandidates = + groupCandidates == null ? possible : groupCandidates.intersection(possible); + if (groupCandidates.isEmpty) return null; + } + if (groupCandidates == null) continue; + supportingClasses.add(_text(groups[entry.key]!.first['BJDM'])); + candidates = candidates == null ? groupCandidates : candidates.intersection(groupCandidates); + if (candidates.isEmpty) return null; + } + if (supportingClasses.length < 2 || candidates?.length != 1) return null; + final monday = candidates!.single; + return DateTime(monday.year, monday.month, monday.day); + } +} + +String graduateTime(dynamic raw) { + final value = raw.toString().trim(); + final compact = value.contains(':') ? value.replaceAll(':', '') : value.padLeft(4, '0'); + if (!RegExp(r'^\d{4}$').hasMatch(compact)) throw const FormatException('研究生节次时间无法识别'); + final hour = int.parse(compact.substring(0, 2)); + final minute = int.parse(compact.substring(2)); + if (hour > 23 || minute > 59) throw const FormatException('研究生节次时间无效'); + return '${compact.substring(0, 2)}:${compact.substring(2)}'; +} + +List graduateWeeks(String raw) { + final normalized = raw + .replaceAll(RegExp(r'[\s第]'), '') + .replaceAll(RegExp('[,、]'), ',') + .replaceAll(RegExp('[~~—–]'), '-') + .replaceAllMapped(RegExp(r'[((](单|双)周?[))]'), (m) => m[1]!); + final result = {}; + for (final piece in normalized.split(',')) { + final match = RegExp(r'^(\d+)(?:-(\d+))?(?:周)?(单|双)?(?:周)?$').firstMatch(piece); + if (match == null) throw FormatException('无法识别研究生课表周次:$raw'); + final first = int.parse(match[1]!); + final last = int.parse(match[2] ?? match[1]!); + if (first < 1 || last < first || last > 60) throw const FormatException('研究生课表周次范围无效'); + for (var week = first; week <= last; week++) { + if (match[3] == null || (match[3] == '单' ? week.isOdd : week.isEven)) result.add(week); + } + } + if (result.isEmpty) throw const FormatException('研究生课表周次为空'); + return result.toList()..sort(); +} diff --git a/lib/pages/schedule_page.dart b/lib/pages/schedule_page.dart index 6f32c499..4c4bee1f 100644 --- a/lib/pages/schedule_page.dart +++ b/lib/pages/schedule_page.dart @@ -7,6 +7,7 @@ import 'package:open_filex/open_filex.dart'; import 'package:url_launcher/url_launcher.dart'; import '../models/assignment.dart'; +import '../models/campus_identity.dart'; import '../models/course.dart'; import '../models/course_table.dart'; import '../models/custom_course.dart'; @@ -576,6 +577,10 @@ class _SchedulePageState extends State { title: '切换学期', sfSymbol: 'calendar', ), + const IosNativeNavigationBarMenuItem( + value: 'source', + title: '课表来源', + ), IosNativeNavigationBarMenuItem( value: 'saturday', title: '显示周六', @@ -708,6 +713,7 @@ class _SchedulePageState extends State { value: 'semester', child: Text('切换学期'), ), + const PopupMenuItem(value: 'source', child: Text('课表来源')), CheckedPopupMenuItem( value: 'saturday', checked: _showSaturday, @@ -830,8 +836,8 @@ class _SchedulePageState extends State { return ListView( key: ValueKey('empty-$week'), children: [ - SizedBox( - height: 300, + ConstrainedBox( + constraints: const BoxConstraints(minHeight: 300), child: Center( child: Column( mainAxisSize: MainAxisSize.min, @@ -858,6 +864,35 @@ class _SchedulePageState extends State { color: theme.colorScheme.onSurfaceVariant, ), ), + if (state == EmptyWeekState.failed) ...[ + Padding( + padding: const EdgeInsets.fromLTRB(24, 12, 24, 0), + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 600), + child: SelectableText( + (_schedule.error ?? '').replaceFirst(RegExp(r'^FormatException:\s*'), ''), + textAlign: TextAlign.center, + style: theme.textTheme.bodyMedium, + ), + ), + ), + const SizedBox(height: 12), + Wrap( + spacing: 12, + children: [ + TextButton.icon( + onPressed: _schedule.loading ? null : _refresh, + icon: const Icon(Icons.refresh), + label: const Text('重试'), + ), + TextButton.icon( + onPressed: _schedule.loading ? null : _showScheduleSource, + icon: const Icon(Icons.school_outlined), + label: const Text('课表来源'), + ), + ], + ), + ], ], ), ), @@ -892,6 +927,13 @@ class _SchedulePageState extends State { return Column( children: [ + if (_schedule.isGraduate) _buildGraduateControls(theme), + if (_schedule.error != null && visibleCourses.isNotEmpty) + TextButton.icon( + icon: const Icon(Icons.info_outline, size: 18), + label: const Text('刷新失败,正在显示上次课表 · 查看原因'), + onPressed: _showScheduleError, + ), _DayHeader( weekStart: _weekStartForWeek(week), today: today, @@ -915,12 +957,181 @@ class _SchedulePageState extends State { ); } + Widget _buildGraduateControls(ThemeData theme) { + final schemes = _schedule.graduateSchemes; + final extraCount = _schedule.graduateUnarranged.length + _schedule.graduateCancelled.length; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + child: Wrap( + spacing: 12, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text('研究生课表', style: theme.textTheme.labelLarge), + if (_schedule.identityWarning != null) Text(_schedule.identityWarning!), + if (schemes.length > 1) + DropdownButton( + value: _schedule.graduateScheme, + items: schemes.entries + .map((e) => DropdownMenuItem(value: e.key, child: Text(e.value))) + .toList(), + onChanged: (value) async { + if (value == null) return; + try { + await _schedule.selectGraduateScheme(value); + } catch (e) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$e'))); + } + } + }, + ), + TextButton.icon( + icon: const Icon(Icons.event_outlined, size: 18), + label: Text( + _schedule.termBegin == null + ? '设置第 1 周周一' + : '第 1 周周一 · ${_schedule.termBegin!.month}/${_schedule.termBegin!.day}', + ), + onPressed: _setGraduateFirstMonday, + ), + if (_schedule.termBegin == null) const Text('设置后可显示日期、当前周和导出日历'), + if (extraCount > 0) + TextButton( + onPressed: _showGraduateExtraCourses, + child: Text( + '未排课 ${_schedule.graduateUnarranged.length} · 停开 ${_schedule.graduateCancelled.length}', + ), + ), + ], + ), + ); + } + + Future _showScheduleSource() async { + final source = await showDialog( + context: context, + builder: (context) => SimpleDialog( + title: const Text('课表来源'), + children: [ + for (final option in [ + (CampusScheduleSource.automatic, '自动识别(IDS 身份)'), + (CampusScheduleSource.undergraduate, '本科教务课表'), + (CampusScheduleSource.graduate, '研究生课表'), + ]) + SimpleDialogOption( + onPressed: () => Navigator.pop(context, option.$1), + child: Row( + children: [ + Icon( + _schedule.scheduleSource == option.$1 + ? Icons.check_circle_outline + : Icons.circle_outlined, + size: 20, + ), + const SizedBox(width: 12), + Flexible(child: Text(option.$2)), + ], + ), + ), + if (_schedule.identityLabel != null) + Padding(padding: const EdgeInsets.all(24), child: Text(_schedule.identityLabel!)), + if (_schedule.identityWarning != null) + Padding(padding: const EdgeInsets.all(24), child: Text(_schedule.identityWarning!)), + ], + ), + ); + if (source == null || !mounted) return; + try { + await _schedule.selectScheduleSource(source); + } catch (error) { + if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$error'))); + } + } + + Future _showScheduleError() => showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('课表刷新失败'), + content: SelectableText( + (_schedule.error ?? '').replaceFirst(RegExp(r'^FormatException:\s*'), ''), + ), + actions: [TextButton(onPressed: () => Navigator.pop(context), child: const Text('关闭'))], + ), + ); + + Future _setGraduateFirstMonday() async { + final now = DateTime.now(); + final date = await showDatePicker( + context: context, + helpText: '选择本学期第 1 周的周一(仅保存在本机)', + initialDate: _schedule.termBegin ?? now.subtract(Duration(days: now.weekday - 1)), + firstDate: DateTime(2000), + lastDate: DateTime(2100), + selectableDayPredicate: (date) => date.weekday == DateTime.monday, + ); + if (date != null && mounted) { + try { + await _schedule.setGraduateFirstMonday(date); + } catch (error) { + if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$error'))); + } + } + } + + Future _showGraduateExtraCourses() async { + await showDialog( + context: context, + builder: (context) => AlertDialog( + title: const Text('研究生课程信息'), + content: SizedBox( + width: 480, + child: SingleChildScrollView( + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final section in [ + ('已选但未排课', _schedule.graduateUnarranged), + ('已停开', _schedule.graduateCancelled), + ]) ...[ + Text(section.$1, style: Theme.of(context).textTheme.titleSmall), + for (final course in section.$2) + ListTile( + contentPadding: EdgeInsets.zero, + title: Text('${course['KCMC'] ?? ''}'), + subtitle: Text( + [ + course['BJMC'], + course['RKJS'] ?? course['JSXM'], + course['PKSJDDMS'] ?? course['PKSJDD'], + ] + .whereType() + .map((v) => '$v'.replaceAll(RegExp(r'<[^>]*>'), '')) + .where((v) => v.isNotEmpty) + .join(' · '), + ), + ), + const SizedBox(height: 12), + ], + ], + ), + ), + ), + actions: [ + TextButton(onPressed: () => Navigator.pop(context), child: const Text('关闭')), + ], + ), + ); + } + void _onMenuSelected(String value) { switch (value) { case 'currentWeek': _goToCurrentWeek(); case 'semester': _showSemesterPicker(); + case 'source': + unawaited(_showScheduleSource()); case 'saturday': setState(() => _showSaturday = !_showSaturday); case 'sunday': @@ -1058,6 +1269,14 @@ class _SchedulePageState extends State { _showDesktopSemesterWheelPopover(); }, ), + DesktopMenuRow( + leading: const Icon(Icons.school_outlined, size: 20), + title: Text('课表来源', style: theme.textTheme.bodyMedium), + onTap: () { + close(); + unawaited(_showScheduleSource()); + }, + ), const Divider(height: 1), DesktopMenuRow( leading: Icon( diff --git a/lib/services/assignment_service.dart b/lib/services/assignment_service.dart index 18f4e390..24966e6a 100644 --- a/lib/services/assignment_service.dart +++ b/lib/services/assignment_service.dart @@ -7,6 +7,7 @@ import 'package:http/http.dart' as http; import '../models/assignment.dart'; import '../models/assignment_overrides.dart'; +import '../models/graduate_schedule.dart'; import '../models/third_party_account.dart'; import 'api_base_url.dart'; import 'auth_service.dart'; @@ -362,6 +363,14 @@ class AssignmentService extends ChangeNotifier { Future?> _fetchExamTable() async { final semesterId = _selectedSemesterId(); + // Graduate term ids belong to a different school system. Sending one to + // EAMS would query the wrong term and can disturb its stateful session. + if (_schedule.hasGraduateIdentity || + _schedule.isGraduate || + semesterId?.startsWith(graduateSemesterPrefix) == true) { + _platformErrors.remove('exam'); + return null; + } final node = _tpAuth.eamsNode; if (!_tpAuth.hasCpdailyBinding || semesterId == null || diff --git a/lib/services/graduate_schedule_client.dart b/lib/services/graduate_schedule_client.dart new file mode 100644 index 00000000..d7efdc3b --- /dev/null +++ b/lib/services/graduate_schedule_client.dart @@ -0,0 +1,257 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:http/http.dart' as http_package; + +import '../models/campus_identity.dart'; +import 'http_client.dart'; + +/// A read-only school client. Identity comes from IDS, independently of access +/// to the graduate application. CASTGC is sent only to IDS. +class GraduateScheduleClient { + GraduateScheduleClient(this.http, this.tgc); + + final LoggingHttpClient http; + final String tgc; + final List<_SchoolCookie> _cookies = []; + Future? _graduateSession; + static const host = 'graduate-course.shanghaitech.edu.cn'; + static const idsHost = 'ids.shanghaitech.edu.cn'; + static const base = '/yjsxkapp/sys/xsxkapp/'; + + // GET_USER_INFO in the official frontend. queryUserData is the editable + // profile/form model and is not the authenticated principal. + static final _idsProfile = Uri.https(idsHost, '/personalInfo/common/getUserConf'); + static final _idsAccounts = Uri.https(idsHost, '/personalInfo/accountRelation/bindingUserList'); + static final _idsPage = Uri.https(idsHost, '/personalInfo/personCenter/index.html'); + static final _graduatePage = Uri.https(host, '${base}course.html'); + // The university's student manual links this protected application entry. + // Static .html pages and public configuration do not establish a CAS session. + static final _graduateEntry = Uri.https(host, '$base*default/index.do'); + + Future identity(String expectedSid) async { + // Follow the same personal-center entry as the official frontend so IDS can + // establish its own session and reference-token cookie before its API call. + final (pageUri, pageResponse) = await _get(_idsPage); + if (pageUri.host == idsHost && pageUri.path == '/authserver/login') { + throw const FormatException('IDS 登录会话已失效,请更新 CpDaily / IDS 绑定'); + } + if (pageResponse.statusCode != 200) { + throw FormatException('IDS 个人中心返回 HTTP ${pageResponse.statusCode}'); + } + final profile = await _jsonUri(_idsProfile, idsQuery: true); + var identity = CampusIdentity.fromIds(profile, expectedSid); + if (identity.categoryName.isEmpty) { + final (uri, response) = await _get(_idsAccounts, idsQuery: true); + final value = _decodeJson(uri, response, 'IDS 身份分类'); + identity = CampusIdentity.fromIds(profile, expectedSid, associatedAccounts: value); + } + return identity; + } + + Future> publicInfo() => _json('xsxkHome/loadPublicInfo_course.do'); + Future> timetable() => _json('xsxkCourse/loadKbxx.do'); + + Future> _json(String path) async { + // Share both success and failure within a refresh. A broken entry must not + // be requested again when optional metadata fails before the timetable read. + await (_graduateSession ??= _openGraduateSession()); + return _jsonUri( + Uri.https(host, '$base$path', { + '_': DateTime.now().millisecondsSinceEpoch.toString(), + }), + ); + } + + Future _openGraduateSession() async { + final (entryUri, entryResponse) = await _get(_graduateEntry); + if (entryUri.host == idsHost && entryUri.path == '/authserver/login') { + throw const FormatException('研究生系统的 IDS 登录会话已失效,请更新 CpDaily / IDS 绑定'); + } + if (entryResponse.statusCode != 200) { + throw FormatException('研究生系统认证入口返回 HTTP ${entryResponse.statusCode}'); + } + } + + Future> _jsonUri(Uri uri, {bool idsQuery = false}) async { + final label = uri.host == idsHost + ? 'IDS 用户信息' + : uri.path.endsWith('loadKbxx.do') + ? '研究生课表(loadKbxx.do)' + : '研究生学期配置(loadPublicInfo_course.do)'; + for (var attempt = 0; attempt < 2; attempt++) { + final (lastUri, response) = await _get(uri, idsQuery: idsQuery); + if (attempt == 0 && + uri.host == host && + response.statusCode == 200 && + lastUri.host == host && + lastUri.path.endsWith('.html') && + lastUri.path != uri.path) { + // An actual SSO redirect can finish on the application's HTML landing + // page. Read the requested API once with the newly established cookies. + continue; + } + // EMAP can return its CAS entry in JSON rather than an HTTP redirect. + // Follow only that explicit login signal, once; never retry a 404. + String? loginUrl; + if (uri.host == host && [200, 401, 403].contains(response.statusCode)) { + try { + final value = jsonDecode(response.body); + if (value is Map && value['loginURL'] is String) { + loginUrl = value['loginURL'] as String; + } + } on FormatException { + // _decodeJson below reports a non-JSON response with its stage. + } + } + if (loginUrl != null && loginUrl.isNotEmpty && attempt == 0) { + final (loginUri, loginResponse) = await _get(uri.resolve(loginUrl)); + if (loginUri.host == idsHost && loginUri.path == '/authserver/login') { + throw FormatException('$label的学校登录会话已失效'); + } + if (loginResponse.statusCode != 200) { + throw FormatException('$label登录入口返回 HTTP ${loginResponse.statusCode}'); + } + continue; + } + if (loginUrl != null && loginUrl.isNotEmpty) { + throw FormatException('$label登录后仍返回登录入口,学校会话未建立'); + } + return _decodeJson(lastUri, response, label); + } + throw FormatException('$label登录后仍未取得数据'); + } + + Map _decodeJson(Uri lastUri, http_package.Response response, String label) { + if (lastUri.host == idsHost && lastUri.path == '/authserver/login') { + throw FormatException('$label被重定向到登录页,学校会话已失效'); + } + if (response.statusCode != 200) { + if (response.statusCode == 401 || response.statusCode == 403) { + throw FormatException('$label返回 HTTP ${response.statusCode},学校会话未认证或没有访问权限'); + } + throw FormatException('$label返回 HTTP ${response.statusCode};请稍后重试,不会自动反复访问'); + } + try { + final value = jsonDecode(response.body); + if (value is Map) return value; + } on FormatException { + throw FormatException('$label返回 HTTP 200,但内容是网页而非 JSON(可能登录已过期)'); + } + throw FormatException('$label返回数据格式变化'); + } + + Future<(Uri, http_package.Response)> _get(Uri uri, {bool idsQuery = false}) async { + if (tgc.isEmpty || tgc.contains(RegExp(r'[\r\n;]'))) { + throw const FormatException('学校绑定缺少有效的 CASTGC,请更新 CpDaily / IDS 绑定'); + } + for (var hop = 0; hop < 12; hop++) { + if (!_allowed(uri)) throw const FormatException('学校登录跳转地址不受支持'); + final applicable = _cookies + .where((c) => c.matches(uri) && (c.cookie.name != 'CASTGC' || uri.host == idsHost)); + final cookies = [ + ...applicable.map((c) => '${c.cookie.name}=${c.cookie.value}'), + if (uri.host == idsHost && !applicable.any((c) => c.cookie.name == 'CASTGC')) 'CASTGC=$tgc', + ].join('; '); + final headers = { + if (cookies.isNotEmpty) 'Cookie': cookies, + 'Accept': 'application/json, text/html;q=0.9', + if (uri.host == host && uri.path.endsWith('.do')) ...{ + // The official initial public-info request uses plain XMLHttpRequest; + // only the later jQuery timetable request marks itself as AJAX. + if (uri.path.endsWith('loadKbxx.do')) 'X-Requested-With': 'XMLHttpRequest', + 'Referer': _graduatePage.toString(), + 'Cache-Control': 'no-cache', + }, + if (uri.host == idsHost && uri.path.startsWith('/personalInfo/')) ...{ + 'X-Requested-With': 'XMLHttpRequest', + 'Referer': _idsPage.toString(), + for (final c in applicable) + if (c.cookie.name == 'REFERERCE_TOKEN') 'refererToken': c.cookie.value, + for (final c in applicable) + if (c.cookie.name == 'XSRF-TOKEN') 'X-XSRF-TOKEN': Uri.decodeComponent(c.cookie.value), + }, + }; + final response = idsQuery && (uri == _idsAccounts || uri == _idsProfile) + ? await http.readIdsQuery(uri, headers: headers) + : await http.readOnlyGet(uri, headers: headers); + for (final raw + in (response.headers['set-cookie'] ?? '').split(RegExp(r',(?=\s*[^\s;,=]+=)'))) { + if (raw.trim().isEmpty) continue; + try { + final cookie = Cookie.fromSetCookieValue(raw.trim()); + if (cookie.name == 'CASTGC' && uri.host != idsHost) continue; + final domain = (cookie.domain ?? uri.host).replaceFirst(RegExp(r'^\.'), '').toLowerCase(); + // Never accept a cookie for a sibling or unrelated host. + if (domain != uri.host && !uri.host.endsWith('.$domain')) continue; + final directory = uri.path.substring(0, uri.path.lastIndexOf('/')); + final defaultPath = directory.isEmpty ? '/' : directory; + final stored = _SchoolCookie( + cookie, + domain, + cookie.domain == null, + cookie.path?.startsWith('/') == true ? cookie.path! : defaultPath, + ); + _cookies.removeWhere( + (c) => c.cookie.name == cookie.name && c.domain == domain && c.path == stored.path, + ); + if (cookie.maxAge != 0 && + (cookie.expires == null || cookie.expires!.isAfter(DateTime.now()))) { + _cookies.add(stored); + } + } on HttpException { + // Ignore malformed optional cookie headers. + } on FormatException { + // Empty Set-Cookie or an unrelated malformed cookie. + } + } + if ([301, 302, 303, 307, 308].contains(response.statusCode)) { + final location = response.headers['location']; + if (location == null) break; + uri = uri.resolve(location); + continue; + } + return (uri, response); + } + throw const FormatException('学校登录跳转次数过多,请更新 CpDaily / IDS 绑定'); + } + + bool _allowed(Uri uri) { + if (uri.scheme != 'https' || uri.userInfo.isNotEmpty || uri.port != 443) return false; + if (uri.host == idsHost) { + return { + '/authserver/login', + _idsProfile.path, + _idsAccounts.path, + _idsPage.path, + '/personalInfo/', + }.contains(uri.path); + } + if (uri.host != host) return false; + return { + '${base}index.html', + _graduateEntry.path, + _graduatePage.path, + '${base}xsxkHome/loadPublicInfo_course.do', + '${base}xsxkCourse/loadKbxx.do', + '/yjsxkapp/login', + '/yjsxkapp/login/', + '/yjsxkapp/', + }.contains(uri.path); + } +} + +class _SchoolCookie { + const _SchoolCookie(this.cookie, this.domain, this.hostOnly, this.path); + final Cookie cookie; + final String domain; + final bool hostOnly; + final String path; + + bool matches(Uri uri) => + (uri.host == domain || (!hostOnly && uri.host.endsWith('.$domain'))) && + (uri.path == path || + (uri.path.startsWith(path) && + (path.endsWith('/') || uri.path.substring(path.length).startsWith('/')))) && + (cookie.expires == null || cookie.expires!.isAfter(DateTime.now())); +} diff --git a/lib/services/http_client.dart b/lib/services/http_client.dart index 72799b95..1c55bbd4 100644 --- a/lib/services/http_client.dart +++ b/lib/services/http_client.dart @@ -11,6 +11,98 @@ class LoggingHttpClient { LoggingHttpClient(this._logger, {http.Client? inner}) : _inner = inner ?? http.Client(); + /// School SSO redirects can carry tickets and personal records. Log only + /// the origin/path, status and structural summary, never credentials or raw bodies. + Future readOnlyGet(Uri uri, {Map? headers}) async { + final request = http.Request('GET', uri) + ..followRedirects = false + ..headers.addAll(headers ?? const {}); + return _readSchoolRequest(request); + } + + /// The official IDS client uses POST for these two identity reads. This exact + /// allowlist deliberately excludes editing, binding and account switching. + Future readIdsQuery(Uri uri, {Map? headers}) { + if (uri.scheme != 'https' || + uri.host != 'ids.shanghaitech.edu.cn' || + uri.port != 443 || + uri.userInfo.isNotEmpty || + uri.hasQuery || + uri.hasFragment || + !const { + '/personalInfo/common/getUserConf', + '/personalInfo/accountRelation/bindingUserList', + }.contains(uri.path)) { + throw const FormatException('不支持的 IDS 查询接口'); + } + final request = http.Request('POST', uri) + ..followRedirects = false + ..headers.addAll(headers ?? const {}) + ..headers['Content-Type'] = 'application/json' + ..body = '{}'; + return _readSchoolRequest(request); + } + + Future _readSchoolRequest(http.Request request) async { + final uri = request.url; + final http.Response response; + try { + response = await http.Response.fromStream( + await _inner.send(request).timeout(const Duration(seconds: 15)), + ).timeout(const Duration(seconds: 15)); + } catch (error) { + _logger.log( + method: request.method, + url: '${uri.scheme}://${uri.host}${uri.path}', + error: '网络请求未完成(${error.runtimeType})', + tag: 'schoolSchedule:readOnly', + ); + rethrow; + } + final summary = { + 'contentType': response.headers['content-type']?.split(';').first ?? 'unknown', + 'bytes': response.bodyBytes.length, + }; + try { + final value = jsonDecode(response.body); + summary['format'] = 'JSON'; + if (value is Map) { + final code = value['code']; + if ((code is String || code is num) && RegExp(r'^-?\d{1,8}$').hasMatch('$code')) { + summary['code'] = code; + } + if (value['success'] is bool) summary['success'] = value['success']; + for (final key in ['results', 'bindingUserList', 'xkjgList', 'ntkmdList', 'rqpkjgallList']) { + if (value[key] is List) summary['${key}Count'] = (value[key] as List).length; + } + final data = value['datas']; + summary['datasType'] = data == null + ? 'null' + : data is Map + ? 'object' + : data is List + ? 'list' + : 'other'; + if (data is Map) { + summary['currentUidPresent'] = data['uid']?.toString().trim().isNotEmpty == true; + summary['categoryPresent'] = data['categoryName']?.toString().trim().isNotEmpty == true; + } + } + } on FormatException { + summary['format'] = RegExp(r'^\s*<', caseSensitive: false).hasMatch(response.body) + ? 'HTML(可能为登录页面)' + : '非 JSON'; + } + _logger.log( + method: request.method, + url: '${uri.scheme}://${uri.host}${uri.path}', + statusCode: response.statusCode, + responseBody: jsonEncode(summary), + tag: 'schoolSchedule:readOnly', + ); + return response; + } + Future get( Uri url, { Map? headers, diff --git a/lib/services/schedule_service.dart b/lib/services/schedule_service.dart index 3bc8910d..a97134d0 100644 --- a/lib/services/schedule_service.dart +++ b/lib/services/schedule_service.dart @@ -5,10 +5,13 @@ import 'dart:math' as math; import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; +import '../models/campus_identity.dart'; import '../models/course_table.dart'; import '../models/custom_course.dart'; +import '../models/graduate_schedule.dart'; import 'api_base_url.dart'; import 'auth_service.dart'; +import 'graduate_schedule_client.dart'; import 'http_client.dart'; import 'session/cookie_provider.dart'; import 'session/session_tree.dart'; @@ -26,6 +29,42 @@ class ScheduleService extends ChangeNotifier { String? _selectedSemesterId; bool _loading = false; String? _error; + GraduateSchedule? _graduateSchedule; + String? _graduateScheme; + String? _identityForAccount; + bool _graduateIdentity = false; + String? _identityLabel; + String? _identityWarning; + String? _observedAccount; + int _accountRevision = 0; + + bool get isGraduate => _semesterInfo?.tableId == graduateTableId; + bool get hasGraduateIdentity => _graduateIdentity; + String? get identityLabel => _identityLabel; + String? get identityWarning => _identityWarning; + CampusScheduleSource get scheduleSource => _storage.scheduleSourceFor(_campusAccount()); + + Future selectScheduleSource(CampusScheduleSource source) async { + if (_loading) throw const FormatException('课表加载中,请稍后切换来源'); + final owner = _campusAccount(); + if (owner == null) throw const FormatException('请先绑定 CpDaily / IDS'); + await _storage.setScheduleSource(owner, source); + _identityForAccount = null; + _identityLabel = null; + _identityWarning = null; + await fetchAll(); + } + + Map get graduateSchemes => _selectedSemesterId == null + ? const {} + : _graduateSchedule?.schemesFor(_selectedSemesterId!) ?? const {}; + String? get graduateScheme => _graduateScheme; + List> get graduateUnarranged => _selectedSemesterId == null + ? const [] + : _graduateSchedule?.unarrangedFor(_selectedSemesterId!) ?? const []; + List> get graduateCancelled => _selectedSemesterId == null + ? const [] + : _graduateSchedule?.cancelledFor(_selectedSemesterId!) ?? const []; // While true, AssignmentService should NOT refetch on our notifies — // selectSemester sets this during its own network fetch to avoid a // concurrent exam_table + course_table race on EAMS's stateful session. @@ -49,7 +88,13 @@ class ScheduleService extends ChangeNotifier { /// teaching ends. Falls back to a generous default until the calendar loads. int get totalWeeks { final calendar = _termCalendar; - if (calendar == null) return _fallbackTotalWeeks; + if (calendar == null) { + if (isGraduate && _courseTable != null) { + return _courseTable!.courses + .fold(_fallbackTotalWeeks, (max, c) => math.max(max, c.weeks.length - 1)); + } + return _fallbackTotalWeeks; + } final weeks = math.max(calendar.allTeachWeeks, calendar.allTermWeeks); return weeks > 0 ? weeks : _fallbackTotalWeeks; } @@ -59,7 +104,31 @@ class ScheduleService extends ChangeNotifier { // elearning, egateApp) or a cloud-sync merge that replaced the account can // each turn a fetch that was failing into one that works. They all go through // requestFetch, which decides whether they amount to anything. - _tpAuth.addListener(requestFetch); + _observedAccount = _campusAccount(); + _tpAuth.addListener(_onCampusChanged); + } + + void _onCampusChanged() { + final account = _campusAccount(); + if (account != _observedAccount) { + _observedAccount = account; + _accountRevision++; + _identityForAccount = null; + _graduateIdentity = false; + _identityLabel = null; + _identityWarning = null; + _graduateSchedule = null; + _graduateScheme = null; + _fetchedForAccount = null; + if (isGraduate) { + _semesterInfo = null; + _selectedSemesterId = null; + _courseTable = null; + _termCalendar = null; + notifyListeners(); + } + } + requestFetch(); } /// The campus account the timetable currently in hand was fetched for. @@ -113,7 +182,7 @@ class ScheduleService extends ChangeNotifier { await fetchAll(); // Only a success counts as "fetched for": a failed attempt has to be able to // try again on the next trigger. - if (account != null && _error == null) { + if (account != null && account == _campusAccount() && _error == null) { _fetchedForAccount = account; } } @@ -209,11 +278,31 @@ class ScheduleService extends ChangeNotifier { Future loadCachedData() async { _semesterInfo = _storage.loadSemesters(); + if (_semesterInfo?.tableId == graduateTableId) { + if (_storage.graduateScheduleOwner != _campusAccount()) { + _semesterInfo = null; + notifyListeners(); + return; + } + _graduateSchedule = _storage.loadGraduateSchedule(); + } _selectedSemesterId = _storage.selectedSemester ?? _semesterInfo?.defaultSemester; + if (isGraduate && + !_semesterInfo!.semesters.values.any((terms) => terms.containsValue(_selectedSemesterId))) { + _selectedSemesterId = _semesterInfo!.defaultSemester; + } if (_selectedSemesterId != null) { _courseTable = _storage.loadCourseTable(_selectedSemesterId!); } _termCalendar = _storage.loadTermCalendar(_selectedSemesterId ?? ''); + if (isGraduate && _graduateSchedule != null && _selectedSemesterId != null) { + _graduateScheme = _schemeFor(_graduateSchedule!, _selectedSemesterId!); + try { + _courseTable = _graduateTable(_graduateSchedule!, _selectedSemesterId!, _graduateScheme!); + } on FormatException { + _error = '研究生课表缓存需要刷新,请核对学期起始日'; + } + } notifyListeners(); } @@ -222,11 +311,16 @@ class ScheduleService extends ChangeNotifier { if (!_hasCpdailyBinding) return; _loading = true; _error = null; + _identityWarning = null; notifyListeners(); try { + if (await _fetchGraduateIfEligible()) return; await fetchSemesters(); - _selectedSemesterId ??= _semesterInfo?.defaultSemester; + if (!_semesterInfo!.semesters.values + .any((terms) => terms.containsValue(_selectedSemesterId))) { + _selectedSemesterId = _semesterInfo?.defaultSemester; + } if (_selectedSemesterId != null) { await Future.wait([ fetchCourseTable(_selectedSemesterId!), @@ -241,6 +335,156 @@ class ScheduleService extends ChangeNotifier { } } + /// Resolve the current IDS principal before touching either academic system. + /// A failed graduate application is never evidence of undergraduate identity. + Future _fetchGraduateIfEligible() async { + final account = _campusAccount(); + if (account == null) return false; + final revision = _accountRevision; + final client = + GraduateScheduleClient(_http, _tpAuth.cpdailyNode.rawFields['tgc'] as String? ?? ''); + if (_identityForAccount != account) { + final source = scheduleSource; + if (source != CampusScheduleSource.automatic) { + _graduateIdentity = source == CampusScheduleSource.graduate; + _identityLabel = _graduateIdentity ? '手动选择研究生课表' : '手动选择本科课表'; + _identityForAccount = account; + } else { + try { + final identity = await client.identity(_tpAuth.cpdailyStudentId); + if (revision != _accountRevision) return true; + if (identity.kind == CampusStudentKind.unknown) { + throw const CampusIdentityConflict('IDS 未返回可识别的本研身份,请手动选择课表来源'); + } + _graduateIdentity = identity.kind == CampusStudentKind.graduate; + _identityLabel = 'IDS:${identity.categoryName}'; + _identityWarning = null; + _identityForAccount = account; + await _storage.saveCampusIdentity(account, identity); + } catch (error) { + if (revision != _accountRevision) return true; + final cached = _storage.loadCampusIdentity(account); + if (error is CampusIdentityConflict || + cached == null || + cached.kind == CampusStudentKind.unknown) { + throw FormatException('身份识别失败:${_schoolError(error)};可手动选择课表来源'); + } + _graduateIdentity = cached.kind == CampusStudentKind.graduate; + _identityLabel = 'IDS 已缓存身份:${cached.categoryName}'; + _identityWarning = 'IDS 身份暂时无法刷新,沿用此账号已确认的身份'; + } + } + } + if (!_graduateIdentity) return false; + // Public info supplies the official current term, including empty terms. + // A broken optional configuration endpoint must not discard an otherwise valid + // timetable. Prefer its term labels only when the metadata is available. + Map public = const {}; + try { + public = await client.publicInfo(); + } catch (error) { + final warning = '学期配置暂时不可用:${_schoolError(error)};按课表中的学期显示'; + _identityWarning = [_identityWarning, warning].whereType().join(';'); + } + if (revision != _accountRevision) return true; + final Map raw; + try { + raw = await client.timetable(); + } catch (error) { + throw FormatException('研究生课表获取失败:${_schoolError(error)}'); + } + if (revision != _accountRevision) return true; + final current = public['lcxxMap']; + final snapshot = GraduateSchedule.fromJson({ + ...raw, + if (current is Map) 'currentTerm': current['XNXQDM'], + if (current is Map) 'currentTermName': current['XNXQMC'], + }); + final info = snapshot.semesterInfo; + final ids = info.semesters.values.expand((terms) => terms.values); + final semester = + ids.contains(_selectedSemesterId) ? _selectedSemesterId! : info.defaultSemester; + final scheme = _schemeFor(snapshot, semester); + final table = _graduateTable(snapshot, semester, scheme); + // Parse before committing anything, so malformed responses retain the last + // good timetable rather than caching an empty success. + _graduateSchedule = snapshot; + _graduateScheme = scheme; + _semesterInfo = info; + _selectedSemesterId = semester; + _courseTable = table; + await _storage.saveGraduateSchedule(account, snapshot); + await _storage.saveSemesters(info); + await _storage.setSelectedSemester(semester); + await _storage.saveCourseTable(semester, table); + if (revision != _accountRevision) return true; + await _loadGraduateCalendar(semester); + return true; + } + + String _schoolError(Object error) { + if (error is FormatException) return error.message; + if (error is TimeoutException) return '查询超时,请检查网络或稍后重试'; + return '网络请求失败(${error.runtimeType}),请检查学校会话和连接'; + } + + Future _loadGraduateCalendar(String semesterId) async { + _termCalendar = _storage.loadTermCalendar(semesterId); + final inferred = _graduateSchedule?.firstMondayFor(semesterId); + if (_termCalendar == null && inferred != null) { + await setGraduateFirstMonday(inferred); + } + } + + String _schemeFor(GraduateSchedule snapshot, String semesterId) { + final saved = _storage.graduateSchemeFor(semesterId); + return saved != null && snapshot.schemesFor(semesterId).containsKey(saved) + ? saved + : snapshot.defaultScheme(semesterId); + } + + CourseTable _graduateTable(GraduateSchedule snapshot, String semester, String scheme) => snapshot + .tableFor(semester, scheme, firstMonday: _storage.loadTermCalendar(semester)?.termBegin); + + Future setGraduateFirstMonday(DateTime date) async { + if (!isGraduate || _selectedSemesterId == null || date.weekday != DateTime.monday) { + throw const FormatException('请选择研究生学期第 1 周的周一'); + } + final table = + _graduateSchedule!.tableFor(_selectedSemesterId!, _graduateScheme!, firstMonday: date); + final weeks = + table.courses.fold(_fallbackTotalWeeks, (n, c) => math.max(n, c.weeks.length - 1)); + _termCalendar = TermCalendar( + code: 200, + schoolYearTerm: _selectedSemesterId!, + termBegin: DateTime(date.year, date.month, date.day), + snapshotDate: null, + snapshotWeekOfTerm: null, + allTeachWeeks: weeks, + allTermWeeks: weeks, + amClasses: 0, + pmClasses: 0, + eveClasses: 0, + ); + await _storage.saveTermCalendar(_selectedSemesterId!, _termCalendar!); + _courseTable = table; + await _storage.saveCourseTable(_selectedSemesterId!, table); + notifyListeners(); + } + + Future selectGraduateScheme(String scheme) async { + final semester = _selectedSemesterId; + if (_graduateSchedule == null || semester == null || !graduateSchemes.containsKey(scheme)) { + return; + } + final table = _graduateTable(_graduateSchedule!, semester, scheme); + _graduateScheme = scheme; + _courseTable = table; + await _storage.setGraduateScheme(semester, scheme); + await _storage.saveCourseTable(semester, table); + notifyListeners(); + } + Future fetchSemesters() async { final resp = await _postWithRetry( '$_baseUrl/schedule/semesters', @@ -258,6 +502,16 @@ class ScheduleService extends ChangeNotifier { } Future fetchCourseTable(String semesterId) async { + if (semesterId.startsWith(graduateSemesterPrefix)) { + if (_graduateSchedule == null) throw const FormatException('请先刷新研究生课表'); + final scheme = _schemeFor(_graduateSchedule!, semesterId); + final table = _graduateTable(_graduateSchedule!, semesterId, scheme); + _graduateScheme = scheme; + _courseTable = table; + await _storage.saveCourseTable(semesterId, table); + notifyListeners(); + return; + } final extra = { 'semester_id': semesterId, if (_semesterInfo?.tableId.isNotEmpty == true) 'table_id': _semesterInfo!.tableId, @@ -283,6 +537,10 @@ class ScheduleService extends ChangeNotifier { } Future _fetchTermBeginForSemester(String semesterId) async { + if (semesterId.startsWith(graduateSemesterPrefix)) { + await _loadGraduateCalendar(semesterId); + return; + } // Try to find the year and semester number from semesterInfo if (_semesterInfo == null) return; @@ -411,4 +669,11 @@ class ScheduleService extends ChangeNotifier { } return resp; } + + @override + void dispose() { + _pendingFetch?.cancel(); + _tpAuth.removeListener(_onCampusChanged); + super.dispose(); + } } diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index b42ed5c3..10aa197d 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -12,8 +12,10 @@ import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../models/assignment_overrides.dart'; +import '../models/campus_identity.dart'; import '../models/course_table.dart'; import '../models/custom_course.dart'; +import '../models/graduate_schedule.dart'; import '../models/oa_gym.dart'; import '../models/renew_status.dart'; import '../models/third_party_account.dart'; @@ -243,6 +245,62 @@ class StorageService { static const _termBeginPrefix = 'schedule_term_begin_'; static const _selectedSemesterKey = 'schedule_selected_semester'; + CampusIdentity? loadCampusIdentity(String owner) { + final raw = _prefs.getString('schedule_campus_identity'); + if (raw == null) return null; + try { + final data = jsonDecode(raw) as Map; + return data['owner'] == owner ? CampusIdentity.fromJson(data) : null; + } catch (_) { + return null; + } + } + + Future saveCampusIdentity(String owner, CampusIdentity identity) => _prefs.setString( + 'schedule_campus_identity', + jsonEncode({'owner': owner, ...identity.toJson()}), + ); + + CampusScheduleSource scheduleSourceFor(String? owner) { + final raw = _prefs.getString('schedule_source_preference'); + if (raw == null || owner == null) return CampusScheduleSource.automatic; + try { + final data = jsonDecode(raw) as Map; + return data['owner'] == owner + ? CampusScheduleSource.values.firstWhere((v) => v.name == data['source']) + : CampusScheduleSource.automatic; + } catch (_) { + return CampusScheduleSource.automatic; + } + } + + Future setScheduleSource(String owner, CampusScheduleSource source) => _prefs.setString( + 'schedule_source_preference', + jsonEncode({'owner': owner, 'source': source.name}), + ); + + String? get graduateScheduleOwner => _prefs.getString('graduate_schedule_owner'); + + String? graduateSchemeFor(String semesterId) => _prefs.getString('graduate_scheme_$semesterId'); + + Future setGraduateScheme(String semesterId, String scheme) => + _prefs.setString('graduate_scheme_$semesterId', scheme); + + GraduateSchedule? loadGraduateSchedule() { + final raw = _prefs.getString('graduate_schedule'); + if (raw == null) return null; + try { + return GraduateSchedule.fromJson(jsonDecode(raw) as Map); + } catch (_) { + return null; + } + } + + Future saveGraduateSchedule(String owner, GraduateSchedule schedule) async { + await _prefs.setString('graduate_schedule', jsonEncode(schedule.toJson())); + await _prefs.setString('graduate_schedule_owner', owner); + } + Future saveSemesters(SemesterInfo info) => _prefs.setString(_semestersKey, jsonEncode(info.toJson())); diff --git a/test/campus_identity_test.dart b/test/campus_identity_test.dart new file mode 100644 index 00000000..fae20b04 --- /dev/null +++ b/test/campus_identity_test.dart @@ -0,0 +1,163 @@ +import 'dart:convert'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:techpie/models/campus_identity.dart'; +import 'package:techpie/services/debug_logger.dart'; +import 'package:techpie/services/graduate_schedule_client.dart'; +import 'package:techpie/services/http_client.dart'; + +void main() { + test('IDS categories distinguish current students and reject ambiguous or former identities', () { + for (final role in ['学生/硕士生', '学生/博士生', '学生/研究生']) { + expect(CampusIdentity.fromCategory(role).kind, CampusStudentKind.graduate); + } + expect(CampusIdentity.fromCategory('学生/本科生').kind, CampusStudentKind.undergraduate); + for (final role in ['', '学生', '本科/硕士', '硕士校友', '毕业研究生', '教职工/博士']) { + expect(CampusIdentity.fromCategory(role).kind, CampusStudentKind.unknown); + } + }); + + test('associated-account roles never identify a different or disabled principal', () { + const profile = { + 'code': '0', + 'datas': {'uid': '20260001'}, + }; + final identity = CampusIdentity.fromIds( + profile, + '20260001', + associatedAccounts: { + 'bindingUserList': [ + {'userId': '20260002', 'categoryName': '学生/硕士生', 'accountStatus': '账号正常'}, + {'userId': '20260001', 'categoryName': '学生/本科生', 'accountStatus': '账号正常'}, + ], + }, + ); + expect(identity.kind, CampusStudentKind.undergraduate); + final disabled = CampusIdentity.fromIds( + profile, + '20260001', + associatedAccounts: { + 'bindingUserList': [ + {'userId': '20260001', 'categoryName': '学生/硕士生', 'accountStatus': '已禁用'}, + ], + }, + ); + expect(disabled.kind, CampusStudentKind.unknown); + expect( + () => CampusIdentity.fromIds(profile, '20260002'), + throwsA(isA()), + ); + }); + + test('editable profile data without uid is a schema failure, not an account mismatch', () { + expect( + () => CampusIdentity.fromIds( + { + 'code': '0', + 'datas': {'nickName': 'example', 'userAttributes': []}, + }, + '20260001', + ), + throwsA(isA().having((e) => e.message, 'message', contains('缺少 uid'))), + ); + expect( + CampusIdentity.fromIds( + { + 'code': '0', + 'datas': {'uid': '20260001', 'categoryName': '学生/硕士生'}, + }, + '', + ).kind, + CampusStudentKind.graduate, + ); + }); + + test('IDS uses its official read-only POST list with reference cookies and redacted diagnostics', + () async { + final requests = []; + final logger = DebugLogger()..enabled = true; + final client = GraduateScheduleClient( + LoggingHttpClient( + logger, + inner: MockClient((request) async { + requests.add(request); + expect(request.url.host, GraduateScheduleClient.idsHost); + expect(request.headers['cookie'], contains('CASTGC=private-tgc')); + if (request.url.path.endsWith('index.html')) { + return http.Response( + 'IDS', + 200, + headers: { + 'set-cookie': 'REFERERCE_TOKEN=private-reference; Path=/personalInfo; Secure, ' + 'XSRF-TOKEN=private%3Acsrf; Path=/personalInfo; Secure', + }, + ); + } + expect(request.headers['refererToken'], 'private-reference'); + expect(request.headers['X-XSRF-TOKEN'], 'private:csrf'); + expect(request.headers['X-Requested-With'], 'XMLHttpRequest'); + if (request.url.path.endsWith('getUserConf')) { + expect(request.method, 'POST'); + return http.Response( + jsonEncode({ + 'code': '0', + 'datas': {'uid': '20260001', 'cn': 'PRIVATE-NAME'}, + }), + 200, + ); + } + expect(request.url.path, '/personalInfo/accountRelation/bindingUserList'); + expect(request.method, 'POST'); + expect(jsonDecode(request.body), isEmpty); + return http.Response( + jsonEncode({ + 'bindingUserList': [ + {'userId': '20260002', 'categoryName': '学生/本科生', 'accountStatus': '账号正常'}, + {'userId': '20260001', 'categoryName': '学生/硕士生', 'accountStatus': '账号正常'}, + ], + }), + 200, + headers: {'content-type': 'application/json; charset=utf-8'}, + ); + }), + ), + 'private-tgc', + ); + expect((await client.identity('20260001')).kind, CampusStudentKind.graduate); + expect(requests, hasLength(3)); + expect(jsonDecode(logger.entries.last.responseBody!)['bindingUserListCount'], 2); + final logs = + logger.entries.map((e) => '${e.url} ${e.requestBody} ${e.responseBody} ${e.error}').join(); + for (final private in [ + '20260001', + '20260002', + 'PRIVATE-NAME', + 'private-tgc', + 'private-reference', + 'private:csrf', + ]) { + expect(logs, isNot(contains(private))); + } + }); + + test('the IDS POST entry rejects settings endpoints before any request is sent', () async { + var sent = 0; + final client = LoggingHttpClient( + DebugLogger(), + inner: MockClient((request) async { + sent++; + return http.Response('', 200); + }), + ); + for (final target in [ + 'https://ids.shanghaitech.edu.cn/personalInfo/accountRelation/setDefaultAccount', + 'https://ids.shanghaitech.edu.cn:444/personalInfo/accountRelation/bindingUserList', + 'https://unrelated.example/personalInfo/accountRelation/bindingUserList', + ]) { + expect(() => client.readIdsQuery(Uri.parse(target)), throwsFormatException); + } + expect(sent, 0); + }); +} diff --git a/test/graduate_schedule_test.dart b/test/graduate_schedule_test.dart new file mode 100644 index 00000000..21d86a64 --- /dev/null +++ b/test/graduate_schedule_test.dart @@ -0,0 +1,781 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:techpie/models/campus_identity.dart'; +import 'package:techpie/models/graduate_schedule.dart'; +import 'package:techpie/models/third_party_account.dart'; +import 'package:techpie/services/assignment_service.dart'; +import 'package:techpie/services/auth_service.dart'; +import 'package:techpie/services/debug_logger.dart'; +import 'package:techpie/services/graduate_schedule_client.dart'; +import 'package:techpie/services/http_client.dart'; +import 'package:techpie/services/schedule_service.dart'; +import 'package:techpie/services/storage_service.dart'; +import 'package:techpie/services/third_party_auth_service.dart'; +import 'package:techpie/services/uni_auth_service.dart'; + +Map fixture() => { + 'currentTerm': '20261', + 'currentTermName': '2026-2027学年秋季学期', + 'results': [ + { + 'XNXQDM': '20261', + 'XNXQMC': '2026-2027学年秋季学期', + 'BJDM': 'g1', + 'KCMC': '合成研究生课程', + 'XQ': 1, + 'KSJCDM': 1, + 'JSJCDM': 2, + 'ZCMC': '1-16周(单)', + 'JSXM': '示例教师', + 'JASMC': '示例教室', + 'JCFADM': 'A', + }, + { + 'XNXQDM': '20261', + 'BJDM': 'g2', + 'KCMC': '合成研选本课程', + 'BYBZ': 0, + 'XQ': 3, + 'KSJCDM': 1, + 'JSJCDM': 2, + 'ZCMC': '2-16双周', + 'JCFADM': 'B', + }, + { + 'XNXQDM': '20261', + 'BJDM': 'cancelled', + 'KCMC': '合成停开课程', + 'XQ': 2, + 'KSJCDM': 1, + 'JSJCDM': 2, + 'ZCMC': '1-16周', + 'JCFADM': 'A', + }, + ], + 'skjcList': jsonEncode([ + for (final scheme in ['A', 'B']) ...[ + { + 'DM': 1, + 'MC': '第一节', + 'KSSJ': scheme == 'A' ? 815 : 900, + 'JSSJ': scheme == 'A' ? 900 : 945, + 'JCFADM': scheme, + }, + { + 'DM': 2, + 'MC': '第二节', + 'KSSJ': scheme == 'A' ? 910 : 955, + 'JSSJ': scheme == 'A' ? 955 : 1040, + 'JCFADM': scheme, + }, + ], + ]), + 'xkjgList': [ + {'XNXQDM': '20261', 'BJDM': 'g1', 'KCMC': '合成研究生课程'}, + {'XNXQDM': '20261', 'BJDM': 'unarranged', 'KCMC': '合成未排课课程'}, + ], + 'ntkmdList': [ + {'XNXQDM': '20261', 'BJDM': 'cancelled', 'KCMC': '合成停开课程'}, + ], + 'mrjcfadm': 'A', + }; + +const semester = 'graduate:20261'; + +Map datedFixture() { + final raw = fixture(); + final original = raw['results'] as List; + raw['results'] = [ + {...original[0] as Map, 'ZCMC': '1-4周'}, + {...original[1] as Map, 'JCFADM': 'A', 'ZCMC': '1-4周'}, + ]; + raw['ntkmdList'] = []; + raw['rqpkjgallList'] = [ + for (final date in ['2026-09-14', '2026-10-05']) + {'bjdm': 'g1', 'kssj': '0815', 'jssj': '0955', 'rq': date}, + for (final date in ['2026-09-16', '2026-10-07']) + {'bjdm': 'g2', 'kssj': '0815', 'jssj': '0955', 'rq': date}, + ]; + return raw; +} + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('graduate terms are namespaced; schemes retain their actual clock times', () { + final schedule = GraduateSchedule.fromJson(fixture()); + expect(schedule.semesterInfo.defaultSemester, semester); + expect(schedule.semesterInfo.semesters['2026-2027']!['秋'], semester); + final a = schedule.tableFor(semester, 'A'); + final b = schedule.tableFor(semester, 'B'); + expect(a.periods.first.timeRange, '08:15-09:00'); + expect(b.periods.first.timeRange, '09:00-09:45'); + expect(a.courses.single.name, '合成研究生课程'); + expect(a.courses.single.isActiveInWeek(1), isTrue); + expect(a.courses.single.isActiveInWeek(2), isFalse); + expect(b.courses.single.name, '合成研选本课程'); + expect(b.courses.single.isActiveInWeek(2), isTrue); + expect(schedule.unarrangedFor(semester).single['BJDM'], 'unarranged'); + expect(schedule.cancelledFor(semester).single['BJDM'], 'cancelled'); + }); + + test('week parser handles Chinese separators and rejects partial parses', () { + expect(graduateWeeks('第1~8周(单),10、12周'), [1, 3, 5, 7, 10, 12]); + for (final value in ['', '1-16周,未知', '0-3周', '1-100周']) { + expect(() => graduateWeeks(value), throwsFormatException); + } + }); + + test('malformed responses and mismatched periods cannot become empty success', () { + expect(() => GraduateSchedule.fromJson({'results': []}), throwsFormatException); + final raw = fixture(); + (raw['results'] as List).first['JSJCDM'] = 9; + expect(() => GraduateSchedule.fromJson(raw).tableFor(semester, 'A'), throwsFormatException); + }); + + test('a current empty semester is retained and credentials are never cached', () { + final raw = fixture() + ..['results'] = [] + ..['xkjgList'] = [] + ..['ntkmdList'] = []; + raw['csrfToken'] = 'must-not-persist'; + raw['xs'] = {'XH': 'private'}; + final snapshot = GraduateSchedule.fromJson(raw); + expect(snapshot.semesterInfo.defaultSemester, semester); + expect(snapshot.tableFor(semester, 'A').courses, isEmpty); + expect(jsonEncode(snapshot.toJson()), isNot(contains('must-not-persist'))); + expect(snapshot.toJson().containsKey('xs'), isFalse); + }); + + test('term Monday is inferred only from unambiguous server dates', () { + final raw = fixture(); + final row = (raw['results'] as List).first as Map; + row['RQ'] = '2026-09-07'; + expect(GraduateSchedule.fromJson(raw).firstMondayFor(semester), isNull); + row['ZCMC'] = '1周'; + expect(GraduateSchedule.fromJson(raw).firstMondayFor(semester), DateTime(2026, 9, 7)); + }); + + test('explicit server dates override recurring weeks and preserve rescheduling', () { + final raw = fixture(); + final row = (raw['results'] as List).first as Map; + row['rqs'] = ['2026-09-07', '2026-09-22']; + final schedule = GraduateSchedule.fromJson(raw); + expect(schedule.firstMondayFor(semester), isNull); + final table = schedule.tableFor(semester, 'A', firstMonday: DateTime(2026, 9, 7)); + expect(table.courses.length, 2); + final monday = table.courses.singleWhere((c) => c.times.containsKey(1)); + final tuesday = table.courses.singleWhere((c) => c.times.containsKey(2)); + expect(monday.isActiveInWeek(1), isTrue); + expect(monday.isActiveInWeek(3), isFalse); + expect(tuesday.isActiveInWeek(3), isTrue); + expect( + () => schedule.tableFor(semester, 'A', firstMonday: DateTime(2026, 10, 5)), + throwsFormatException, + ); + }); + + test('date-level records match only an unambiguous class and clock interval', () { + final raw = fixture(); + raw['rqpkjgallList'] = [ + { + 'bjdm': 'g1', + 'kssj': '08:15', + 'jssj': '09:55', + 'rqs': ['2026-09-07', '2026-09-21'], + }, + ]; + final table = + GraduateSchedule.fromJson(raw).tableFor(semester, 'A', firstMonday: DateTime(2026, 9, 7)); + expect(table.courses.single.isActiveInWeek(1), isTrue); + expect(table.courses.single.isActiveInWeek(3), isTrue); + expect(table.courses.single.isActiveInWeek(5), isFalse); + }); + + test('real rq records establish one Monday despite missing holiday sessions', () { + final snapshot = GraduateSchedule.fromJson(datedFixture()); + expect(snapshot.firstMondayFor(semester), DateTime(2026, 9, 14)); + final restored = GraduateSchedule.fromJson(snapshot.toJson()); + expect(restored.firstMondayFor(semester), DateTime(2026, 9, 14)); + final table = restored.tableFor(semester, 'A'); + expect(table.courses, hasLength(2)); + for (final course in table.courses) { + expect(course.isActiveInWeek(1), isTrue); + expect(course.isActiveInWeek(2), isFalse); + expect(course.isActiveInWeek(3), isFalse); + expect(course.isActiveInWeek(4), isTrue); + } + }); + + test('partial, conflicting or single-class rq dates cannot silently set a Monday', () { + final partial = datedFixture(); + partial['rqpkjgallList'] = [ + for (final date in ['2026-09-21', '2026-09-28']) + {'bjdm': 'g1', 'kssj': '0815', 'jssj': '0955', 'rq': date}, + for (final date in ['2026-09-23', '2026-09-30']) + {'bjdm': 'g2', 'kssj': '0815', 'jssj': '0955', 'rq': date}, + ]; + expect(GraduateSchedule.fromJson(partial).firstMondayFor(semester), isNull); + final conflicting = datedFixture(); + (conflicting['rqpkjgallList'] as List)[3]['rq'] = '2026-10-14'; + expect(GraduateSchedule.fromJson(conflicting).firstMondayFor(semester), isNull); + final single = datedFixture(); + (single['rqpkjgallList'] as List).removeWhere((r) => r['bjdm'] == 'g2'); + expect(GraduateSchedule.fromJson(single).firstMondayFor(semester), isNull); + }); + + test('split rows share date constraints and shifted weekdays do not shift the term', () { + final raw = datedFixture(); + final rows = raw['results'] as List; + final split = {...rows[0] as Map, 'ZCMC': '3-4周', 'JASMC': '后半学期教室'}; + rows[0]['ZCMC'] = '1-2周'; + rows.add(split); + (raw['rqpkjgallList'] as List).add({ + 'bjdm': 'g1', + 'kssj': '0815', + 'jssj': '0955', + 'rq': '2026-09-22', + }); + expect(GraduateSchedule.fromJson(raw).firstMondayFor(semester), DateTime(2026, 9, 14)); + }); + + test('graduate refresh automatically stores the inferred start without an EAMS request', + () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + h.overrides['loadKbxx.do'] = http.Response(jsonEncode(datedFixture()), 200, + headers: {'content-type': 'application/json; charset=utf-8'},); + await h.schedule.fetchAll(); + expect(h.schedule.error, isNull); + expect(h.schedule.termBegin, DateTime(2026, 9, 14)); + expect(h.storage.loadTermCalendar(semester)!.termBegin, DateTime(2026, 9, 14)); + expect(h.requests.any((r) => r.url.path.contains('/api/')), isFalse); + expect(h.requests.any((r) => r.url.host == 'eams.shanghaitech.edu.cn'), isFalse); + await h.schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)); + await h.schedule.fetchAll(); + expect(h.schedule.termBegin, DateTime(2026, 9, 7)); + }); + + test('the official protected entry establishes graduate cookies before API reads', () async { + final requests = []; + var authenticated = false; + final logger = DebugLogger()..enabled = true; + final client = GraduateScheduleClient( + LoggingHttpClient( + logger, + inner: MockClient((request) async { + requests.add(request); + expect(request.method, 'GET'); + expect(request.followRedirects, isFalse); + if (request.url.host == GraduateScheduleClient.idsHost) { + expect(request.headers['cookie'], contains('CASTGC=test-tgc')); + return http.Response( + '', + 302, + headers: { + 'set-cookie': 'CASTGC=rotated-tgc; Domain=shanghaitech.edu.cn; Path=/; Secure', + 'location': + 'https://${GraduateScheduleClient.host}${GraduateScheduleClient.base}*default/index.do?ticket=private-ticket', + }, + ); + } + expect(request.headers['cookie'] ?? '', isNot(contains('CASTGC'))); + if (request.url.path.endsWith('*default/index.do') && + request.url.queryParameters.containsKey('ticket')) { + authenticated = true; + return http.Response( + '', + 302, + headers: { + 'set-cookie': 'GS_SESSIONID=private-session; Path=/yjsxkapp; Secure', + 'location': '${GraduateScheduleClient.base}*default/index.do', + }, + ); + } + if (request.url.path.endsWith('*default/index.do') && !authenticated) { + return http.Response( + '', + 302, + headers: { + 'location': + 'https://${GraduateScheduleClient.idsHost}/authserver/login?service=test', + }, + ); + } + if (request.url.path.endsWith('*default/index.do')) { + expect(request.headers['cookie'], contains('GS_SESSIONID=private-session')); + return http.Response( + '', + 200, + headers: { + 'set-cookie': '_WEU=private-weu; Path=/yjsxkapp; Secure', + }, + ); + } + expect(request.headers['cookie'], contains('GS_SESSIONID=private-session')); + expect(request.headers['cookie'], contains('_WEU=private-weu')); + expect(request.url.path, endsWith('loadKbxx.do')); + expect(request.url.queryParameters, contains('_')); + expect(request.headers['X-Requested-With'], 'XMLHttpRequest'); + return http.Response( + jsonEncode({ + 'code': '1', + 'xs': {'XH': 'TEST'}, + }), + 200, + ); + }), + ), + 'test-tgc', + ); + expect((await client.timetable())['code'], '1'); + expect(requests.length, 5); + expect(logger.entries.map((e) => e.url).join(), isNot(contains('private-ticket'))); + final logs = logger.entries.map((e) => '${e.url} ${e.responseBody} ${e.error}').join(); + for (final private in [ + 'private-ticket', + 'test-tgc', + 'rotated-tgc', + 'private-session', + 'private-weu', + 'TEST', + 'XH', + ]) { + expect(logs, isNot(contains(private))); + } + expect(jsonDecode(logger.entries.last.responseBody!)['format'], 'JSON'); + }); + + test('redirects to write endpoints or other hosts are rejected before sending', () async { + for (final target in [ + 'https://unrelated.example/collect', + 'https://${GraduateScheduleClient.host}${GraduateScheduleClient.base}xsxkCourse/choiceCourse.do', + 'http://${GraduateScheduleClient.idsHost}/authserver/login', + ]) { + var sent = 0; + final client = GraduateScheduleClient( + LoggingHttpClient( + DebugLogger(), + inner: MockClient((request) async { + sent++; + return http.Response('', 302, headers: {'location': target}); + }), + ), + 'test-tgc', + ); + await expectLater(client.timetable(), throwsFormatException); + expect(sent, 1); + } + }); + + test('a matching graduate profile fetches no undergraduate schedule endpoints', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + await h.schedule.fetchAll(); + expect(h.schedule.error, isNull); + expect(h.schedule.isGraduate, isTrue); + expect(h.schedule.courseTable!.courses.single.name, '合成研究生课程'); + expect( + h.requests + .where((r) => r.url.host == GraduateScheduleClient.host) + .every((r) => r.method == 'GET'), + isTrue, + ); + expect(h.requests.any((r) => r.url.path.contains('/api/')), isFalse); + await h.schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)); + expect(h.schedule.termBegin, DateTime(2026, 9, 7)); + expect(h.schedule.totalWeeks, greaterThanOrEqualTo(16)); + await h.schedule.selectGraduateScheme('B'); + expect(h.schedule.courseTable!.courses.single.name, '合成研选本课程'); + // A failed refresh must leave a usable previous result in hand. + h.fail = true; + await h.schedule.fetchAll(); + expect(h.schedule.error, isNotNull); + expect(h.schedule.isGraduate, isTrue); + expect(h.schedule.courseTable!.courses.single.name, '合成研选本课程'); + expect(h.requests.any((r) => r.url.path.contains('/api/')), isFalse); + }); + + test('an EMAP JSON loginURL is followed once before reading data, without writes', () async { + var infoCalls = 0; + var casCalls = 0; + final client = GraduateScheduleClient( + LoggingHttpClient( + DebugLogger(), + inner: MockClient((request) async { + expect(request.method, 'GET'); + if (request.url.path.endsWith('*default/index.do')) { + return http.Response('entry', 200); + } + if (request.url.host == GraduateScheduleClient.idsHost) { + casCalls++; + return http.Response( + '', + 302, + headers: { + 'location': 'https://${GraduateScheduleClient.host}/yjsxkapp/login?ticket=private', + }, + ); + } + if (request.url.path == '/yjsxkapp/login') { + return http.Response( + 'entry', + 200, + headers: { + if (request.url.queryParameters.containsKey('ticket')) + 'set-cookie': 'session=valid; Path=/yjsxkapp; Secure', + }, + ); + } + expect(request.url.path, endsWith('loadPublicInfo_course.do')); + infoCalls++; + return http.Response( + jsonEncode( + infoCalls == 1 + ? { + 'loginURL': + 'https://${GraduateScheduleClient.idsHost}/authserver/login?service=graduate', + } + : { + 'lcxxMap': {'XNXQDM': '20261'}, + }, + ), + 200, + ); + }), + ), + 'test-tgc', + ); + expect((await client.publicInfo())['lcxxMap'], {'XNXQDM': '20261'}); + expect(infoCalls, 2); + expect(casCalls, 1); + }); + + test('a plain timetable 401 is not retried as though it were an API redirect', () async { + var apiCalls = 0; + final client = GraduateScheduleClient( + LoggingHttpClient( + DebugLogger(), + inner: MockClient((request) async { + if (request.url.path.endsWith('*default/index.do')) { + return http.Response('entry', 200); + } + apiCalls++; + return http.Response('{}', 401); + }), + ), + 'test-tgc', + ); + await expectLater( + client.timetable(), + throwsA(isA().having((e) => e.message, 'message', contains('未认证'))), + ); + expect(apiCalls, 1); + }); + + test('a failed authentication entry is shared across metadata and timetable reads', () async { + var entryCalls = 0; + final client = GraduateScheduleClient( + LoggingHttpClient( + DebugLogger(), + inner: MockClient((request) async { + expect(request.url.path, endsWith('*default/index.do')); + entryCalls++; + return http.Response('unavailable', 404); + }), + ), + 'test-tgc', + ); + await expectLater(client.publicInfo(), throwsFormatException); + await expectLater(client.timetable(), throwsFormatException); + expect(entryCalls, 1); + }); + + test('IDS undergraduate identity uses original requests without opening the graduate system', + () async { + final h = await harness(graduate: false); + addTearDown(h.schedule.dispose); + await h.schedule.fetchAll(); + expect(h.schedule.error, isNull); + expect(h.schedule.isGraduate, isFalse); + expect(h.schedule.selectedSemesterId, 'undergrad-term'); + expect(h.requests.any((r) => r.url.host == GraduateScheduleClient.host), isFalse); + expect( + h.requests.where((r) => r.url.path.contains('/schedule/')).map((r) => r.url.path).toList(), + [ + '/api/schedule/semesters', + '/api/schedule/course_table', + '/api/schedule/term_begin', + ]); + }); + + test('a profile with a different student id never opts this account in', () async { + final h = await harness(profileSid: 'OTHER'); + addTearDown(h.schedule.dispose); + await h.schedule.fetchAll(); + expect(h.schedule.error, contains('IDS 当前账号与学校绑定学号不一致')); + expect(h.schedule.isGraduate, isFalse); + expect(h.requests.any((r) => r.url.path.endsWith('loadKbxx.do')), isFalse); + expect(h.requests.any((r) => r.url.path.contains('/schedule/')), isFalse); + }); + + test('IDS failure never silently falls back to undergraduate requests', () async { + for (final response in [ + http.Response('missing', 404), + http.Response('login', 200), + ]) { + final h = await harness(); + addTearDown(h.schedule.dispose); + h.overrides['getUserConf'] = response; + await h.schedule.fetchAll(); + expect(h.schedule.error, contains('身份识别失败')); + expect(h.requests.every((r) => r.url.host == GraduateScheduleClient.idsHost), isTrue); + expect(h.requests.where((r) => r.url.path.endsWith('getUserConf')), hasLength(1)); + } + }); + + test('unknown IDS categories require a source choice, not a guess', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + h.category = '教职工/教师'; + await h.schedule.fetchAll(); + expect(h.schedule.error, contains('手动选择课表来源')); + expect(h.requests.every((r) => r.url.host == GraduateScheduleClient.idsHost), isTrue); + }); + + test('a broken optional semester endpoint does not discard a valid timetable', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + h.overrides['loadPublicInfo_course.do'] = http.Response('missing', 404); + await h.schedule.fetchAll(); + expect(h.schedule.error, isNull); + expect(h.schedule.courseTable!.courses.single.name, '合成研究生课程'); + expect(h.schedule.identityWarning, contains('loadPublicInfo_course.do')); + expect(h.schedule.identityWarning, contains('404')); + expect(h.requests.where((r) => r.url.path.endsWith('loadPublicInfo_course.do')), hasLength(1)); + h.overrides.remove('loadPublicInfo_course.do'); + await h.schedule.fetchAll(); + expect(h.schedule.error, isNull); + expect(h.schedule.identityWarning, isNull); + }); + + test('a timetable 404 is reported once and preserves the last usable table', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + await h.schedule.fetchAll(); + h.requests.clear(); + h.overrides['loadKbxx.do'] = http.Response('not found', 404); + await h.schedule.fetchAll(); + expect(h.schedule.error, contains('loadKbxx.do')); + expect(h.schedule.error, contains('404')); + expect(h.schedule.courseTable!.courses.single.name, '合成研究生课程'); + expect(h.requests.where((r) => r.url.path.endsWith('loadKbxx.do')), hasLength(1)); + expect(h.requests.any((r) => r.url.path.contains('/schedule/')), isFalse); + expect(h.requests.any((r) => r.url.path.endsWith('loadStdInfo.do')), isFalse); + }); + + test('local manual source choices bypass IDS and keep undergraduate routing intact', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + h.overrides['getUserConf'] = http.Response('missing', 404); + await h.schedule.selectScheduleSource(CampusScheduleSource.graduate); + expect(h.schedule.error, isNull); + expect(h.schedule.isGraduate, isTrue); + expect(h.requests.every((r) => r.url.host == GraduateScheduleClient.host), isTrue); + h.requests.clear(); + await h.schedule.selectScheduleSource(CampusScheduleSource.undergraduate); + expect(h.schedule.error, isNull); + expect(h.schedule.isGraduate, isFalse); + expect(h.schedule.selectedSemesterId, 'undergrad-term'); + expect( + h.requests.any( + (r) => [GraduateScheduleClient.idsHost, GraduateScheduleClient.host].contains(r.url.host), + ), + isFalse, + ); + expect(h.storage.scheduleSourceFor('different-account'), CampusScheduleSource.automatic); + }); + + test('cached IDS identity belongs to one account and survives only availability failures', + () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + await h.schedule.fetchAll(); + expect(h.storage.loadCampusIdentity('different-account'), isNull); + h.overrides['getUserConf'] = http.Response('missing', 404); + final restored = ScheduleService(h.storage, h.httpClient, h.auth, h.tp); + addTearDown(restored.dispose); + await restored.fetchAll(); + expect(restored.error, isNull); + expect(restored.isGraduate, isTrue); + expect(restored.identityWarning, contains('沿用此账号已确认的身份')); + h.overrides['getUserConf'] = http.Response( + jsonEncode({ + 'code': '0', + 'datas': {'uid': '20260002', 'categoryName': '学生/硕士生'}, + }), + 200, + headers: {'content-type': 'application/json; charset=utf-8'}, + ); + final mismatched = ScheduleService(h.storage, h.httpClient, h.auth, h.tp); + addTearDown(mismatched.dispose); + h.requests.clear(); + await mismatched.fetchAll(); + expect(mismatched.error, contains('学号不一致')); + expect(h.requests.every((r) => r.url.host == GraduateScheduleClient.idsHost), isTrue); + }); + + test('selected scheme and local start date survive a cached restart', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + await h.schedule.fetchAll(); + await h.schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)); + await h.schedule.selectGraduateScheme('B'); + final restored = ScheduleService(h.storage, h.httpClient, h.auth, h.tp); + addTearDown(restored.dispose); + final before = h.requests.length; + await restored.loadCachedData(); + expect(h.requests.length, before); + expect(restored.graduateScheme, 'B'); + expect(restored.termBegin, DateTime(2026, 9, 7)); + expect(restored.courseTable!.courses.single.name, '合成研选本课程'); + }); + + test('a cached graduate term never reaches EAMS even before identity hydration', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + await h.storage.setSelectedSemester(semester); + final assignments = AssignmentService(h.storage, h.httpClient, h.auth, h.tp, h.schedule); + addTearDown(assignments.dispose); + await assignments.fetchPlatform('exam'); + expect(h.requests, isEmpty); + }); + + test('a confirmed graduate never queries EAMS exams even when its first timetable fails', + () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + await h.storage.setSelectedSemester('undergrad-term'); + h.overrides['loadKbxx.do'] = http.Response('missing', 404); + await h.schedule.fetchAll(); + expect(h.schedule.hasGraduateIdentity, isTrue); + final assignments = AssignmentService(h.storage, h.httpClient, h.auth, h.tp, h.schedule); + addTearDown(assignments.dispose); + h.requests.clear(); + await assignments.fetchPlatform('exam'); + expect(h.requests, isEmpty); + }); + + test('an unbind discards a late graduate response instead of caching it', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + h.tableGate = Completer(); + final pending = h.schedule.fetchAll(); + await h.tableEntered.future; + await h.tp.unbind(ThirdPartyPlatform.cpdaily); + h.tableGate!.complete(); + await pending; + expect(h.schedule.courseTable, isNull); + expect(h.schedule.semesterInfo, isNull); + expect(h.storage.graduateScheduleOwner, isNull); + }); +} + +class Harness { + late ScheduleService schedule; + late StorageService storage; + late LoggingHttpClient httpClient; + late AuthService auth; + late ThirdPartyAuthService tp; + Completer? tableGate; + final tableEntered = Completer(); + final requests = []; + final overrides = {}; + String category = ''; + bool fail = false; +} + +Future harness({bool graduate = true, String profileSid = '20260001'}) async { + SharedPreferences.setMockInitialValues({}); + FlutterSecureStorage.setMockInitialValues({}); + final storage = StorageService(await SharedPreferences.getInstance()); + await storage.saveThirdPartyAccount( + ThirdPartyAccount( + platform: ThirdPartyPlatform.cpdaily, + account: '20260001', + sid: '20260001', + token: 'session', + raw: const {'tgc': 'test-tgc'}, + boundAt: DateTime(2026), + ), + ); + final h = Harness()..category = graduate ? '学生/硕士生' : '学生/本科生'; + final client = LoggingHttpClient( + DebugLogger(), + inner: MockClient((request) async { + h.requests.add(request); + final override = h.overrides[request.url.path.split('/').last]; + if (override != null) return override; + if (request.url.path.endsWith('loadKbxx.do') && h.tableGate != null) { + h.tableEntered.complete(); + await h.tableGate!.future; + } + if (h.fail) throw const FormatException('synthetic offline'); + final Object data = switch (request.url.path.split('/').last) { + 'index.html' || 'course.html' || 'login' || 'index.do' => 'synthetic entry', + 'getUserConf' => { + 'code': '0', + 'datas': {'uid': profileSid, 'categoryName': h.category}, + }, + 'loadKbxx.do' => fixture(), + 'loadPublicInfo_course.do' => { + 'lcxxMap': {'XNXQDM': '20261', 'XNXQMC': '2026-2027学年秋季学期'}, + }, + 'eams' => { + 'success': true, + 'data': {'token': 'school-session'}, + }, + 'stdDetail.action' => '姓名: TEST', + 'semesters' => { + 'success': true, + 'data': { + 'semesters': { + '2026-2027': {'秋': 'undergrad-term'}, + }, + 'defaultSemester': 'undergrad-term', + 'tableId': 't1', + }, + }, + 'course_table' => { + 'success': true, + 'data': {'periods': [], 'courses': []}, + }, + 'term_begin' => { + 'success': true, + 'data': {'termBegin': '2026-09-07', 'allTeachWeeks': 16, 'allTermWeeks': 20}, + }, + _ => throw StateError('Unexpected request ${request.url.path}'), + }; + return http.Response( + data is String ? data : jsonEncode(data), + 200, + headers: {'content-type': 'application/json; charset=utf-8'}, + ); + }), + ); + final auth = AuthService(storage, client, UniAuthService()); + final tp = ThirdPartyAuthService(storage, client); + await tp.initialize(); + h.storage = storage; + h.httpClient = client; + h.auth = auth; + h.tp = tp; + h.schedule = ScheduleService(storage, client, auth, tp); + return h; +} diff --git a/test/schedule_fetch_coalescing_test.dart b/test/schedule_fetch_coalescing_test.dart index 2456b5ca..2bfcfbb0 100644 --- a/test/schedule_fetch_coalescing_test.dart +++ b/test/schedule_fetch_coalescing_test.dart @@ -46,6 +46,7 @@ void main() { await tpAuth.initialize(); final schedule = ScheduleService(storage, http, auth, tpAuth); + addTearDown(schedule.dispose); expect(schedule.semesterInfo, isNull, reason: 'nothing in hand yet'); // The burst: every one of these notifies the schedule through the same @@ -61,9 +62,10 @@ void main() { await Future.delayed(const Duration(milliseconds: 900)); expect( - requests.length, + requests.where((uri) => uri.host == 'techpie.geekpie.club').length, 1, - reason: 'the burst is one round; the client fails on the first request, ' + reason: 'the burst is one backend round after the read-only identity probe; ' + 'the client fails on the first backend request, ' 'so a second round would show up as a second request', ); }); @@ -98,6 +100,7 @@ void main() { await tpAuth.initialize(); final schedule = ScheduleService(storage, http, auth, tpAuth); + addTearDown(schedule.dispose); schedule.requestFetch(force: true); await Future.delayed(const Duration(milliseconds: 900)); expect( @@ -133,6 +136,11 @@ class _AnsweringClient extends http.BaseClient { Future send(http.BaseRequest request) async { requests.add(request.url); final body = switch (request.url.path) { + '/personalInfo/personCenter/index.html' => 'IDS', + '/personalInfo/common/getUserConf' => jsonEncode({ + 'code': '0', + 'datas': {'uid': '20240001', 'categoryName': '学生/本科生'}, + }), // The eams cookie is minted from the parent tgc before a timetable fetch // can carry one. '/api/auth/third-party/eams' => jsonEncode({ @@ -185,6 +193,19 @@ class _RecordingClient extends http.BaseClient { @override Future send(http.BaseRequest request) async { requests.add(request.url); + if (request.url.host == 'ids.shanghaitech.edu.cn') { + final body = request.url.path.endsWith('index.html') + ? 'IDS' + : jsonEncode({ + 'code': '0', + 'datas': {'uid': '20240001', 'categoryName': '学生/本科生'}, + }); + return http.StreamedResponse( + Stream.value(utf8.encode(body)), + 200, + headers: const {'content-type': 'application/json; charset=utf-8'}, + ); + } throw const _Refused(); } } From ebb521aded8f791d6dbced55f92eb50a8f04ccbd Mon Sep 17 00:00:00 2001 From: gfdfdxc <29912959+gfdfdxc@users.noreply.github.com> Date: Tue, 3 Nov 2026 04:29:14 +0800 Subject: [PATCH 2/8] chore(schedule): move term start setting into view settings --- lib/pages/schedule_page.dart | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/lib/pages/schedule_page.dart b/lib/pages/schedule_page.dart index 4c4bee1f..08ae1092 100644 --- a/lib/pages/schedule_page.dart +++ b/lib/pages/schedule_page.dart @@ -581,6 +581,12 @@ class _SchedulePageState extends State { value: 'source', title: '课表来源', ), + if (_schedule.isGraduate) + const IosNativeNavigationBarMenuItem( + value: 'termStart', + title: '设置学期起始日', + sfSymbol: 'calendar', + ), IosNativeNavigationBarMenuItem( value: 'saturday', title: '显示周六', @@ -714,6 +720,8 @@ class _SchedulePageState extends State { child: Text('切换学期'), ), const PopupMenuItem(value: 'source', child: Text('课表来源')), + if (_schedule.isGraduate) + const PopupMenuItem(value: 'termStart', child: Text('设置学期起始日')), CheckedPopupMenuItem( value: 'saturday', checked: _showSaturday, @@ -985,16 +993,6 @@ class _SchedulePageState extends State { } }, ), - TextButton.icon( - icon: const Icon(Icons.event_outlined, size: 18), - label: Text( - _schedule.termBegin == null - ? '设置第 1 周周一' - : '第 1 周周一 · ${_schedule.termBegin!.month}/${_schedule.termBegin!.day}', - ), - onPressed: _setGraduateFirstMonday, - ), - if (_schedule.termBegin == null) const Text('设置后可显示日期、当前周和导出日历'), if (extraCount > 0) TextButton( onPressed: _showGraduateExtraCourses, @@ -1132,6 +1130,8 @@ class _SchedulePageState extends State { _showSemesterPicker(); case 'source': unawaited(_showScheduleSource()); + case 'termStart': + unawaited(_setGraduateFirstMonday()); case 'saturday': setState(() => _showSaturday = !_showSaturday); case 'sunday': @@ -1277,6 +1277,15 @@ class _SchedulePageState extends State { unawaited(_showScheduleSource()); }, ), + if (_schedule.isGraduate) + DesktopMenuRow( + leading: const Icon(Icons.event_outlined, size: 20), + title: Text('设置学期起始日', style: theme.textTheme.bodyMedium), + onTap: () { + close(); + unawaited(_setGraduateFirstMonday()); + }, + ), const Divider(height: 1), DesktopMenuRow( leading: Icon( From 5813b6d70417bbff537ebaa2dacabbbab3148b85 Mon Sep 17 00:00:00 2001 From: gfdfdxc <29912959+gfdfdxc@users.noreply.github.com> Date: Wed, 11 Nov 2026 02:11:01 +0800 Subject: [PATCH 3/8] fix(schedule): correct graduate timetable parsing and switching --- lib/models/graduate_schedule.dart | 163 +++++++++++++++-------- lib/services/schedule_service.dart | 157 ++++++++++++++-------- lib/services/storage_service.dart | 22 +-- test/graduate_schedule_history_test.dart | 69 ++++++++++ test/graduate_schedule_test.dart | 103 +++++++++++++- 5 files changed, 394 insertions(+), 120 deletions(-) create mode 100644 test/graduate_schedule_history_test.dart diff --git a/lib/models/graduate_schedule.dart b/lib/models/graduate_schedule.dart index e39ca674..32b9183d 100644 --- a/lib/models/graduate_schedule.dart +++ b/lib/models/graduate_schedule.dart @@ -60,11 +60,41 @@ class GraduateSchedule { Map toJson() => data; List> _rows(String key) => (data[key] as List).cast>(); - List> get rows => _rows('results'); + late final List> rows = _scheduleRows(); String _text(dynamic value) => value?.toString().trim() ?? ''; + String _classId(Map row) => + _text(row['BJDM']).isEmpty ? _text(row['KCDM']) : _text(row['BJDM']); String rawTerm(String semesterId) => semesterId.substring(graduateSemesterPrefix.length); bool _inTerm(Map row, String term) => _text(row['XNXQDM']) == term; + // Historical enrollments can carry their entire timetable as display text. + // Expand only classes missing from the structured timetable for that term. + List> _scheduleRows() { + final result = [..._rows('results')]; + final structuredClasses = {for (final row in result) (row['XNXQDM'], _classId(row))}; + final separator = RegExp(r'[;;\n]|', caseSensitive: false); + final session = RegExp(r'^(.+?)\s*星期([一二三四五六日天])\s*\[(\d+)(?:-(\d+))?节\]\s*(.*)$'); + for (final course in _rows('xkjgList')) { + if (structuredClasses.contains((course['XNXQDM'], _classId(course)))) continue; + final plain = _text(course['PKSJDD']); + final schedule = plain.isEmpty ? _text(course['PKSJDDMS']) : plain; + for (final part in schedule.split(separator)) { + final match = session.firstMatch(part.trim()); + if (match == null) continue; + result.add({ + ...course, + 'ZCMC': match[1]!.trim(), + 'XQ': match[2] == '天' ? 7 : '一二三四五六日'.indexOf(match[2]!) + 1, + 'KSJCDM': match[3], + 'JSJCDM': match[4] ?? match[3], + 'JASMC': match[5]!.trim(), + if (_text(course['JCFADM']).isEmpty) 'JCFADM': data['mrjcfadm'], + }); + } + } + return result; + } + SemesterInfo get semesterInfo { final labels = {}; for (final row in [...rows, ..._rows('xkjgList'), ..._rows('ntkmdList')]) { @@ -76,16 +106,17 @@ class GraduateSchedule { } final current = _text(data['currentTerm']); if (current.isNotEmpty) { - labels[current] = - _text(data['currentTermName']).isEmpty ? current : _text(data['currentTermName']); + final name = _text(data['currentTermName']); + labels[current] = name.isEmpty ? (labels[current] ?? current) : name; } if (labels.isEmpty) throw const FormatException('学校没有返回可识别的研究生学期'); final semesters = >{}; for (final entry in labels.entries) { - final match = RegExp(r'(\d{4})\s*[-—–~~]\s*(\d{4})').firstMatch(entry.value); - final year = match == null ? entry.value : '${match[1]}-${match[2]}'; - final term = ['秋', '春', '暑'].where(entry.value.contains).firstOrNull ?? entry.value; - // Keep unknown official labels instead of guessing numeric term codes. + final match = RegExp(r'(\d{4})\s*[-—–~~]\s*(\d{4})(?:\s*学年)?').firstMatch(entry.value); + final year = match == null ? entry.key : '${match[1]}-${match[2]}'; + final name = match == null ? entry.value : entry.value.replaceRange(match.start, match.end, ''); + final termName = name.trim().replaceFirst(RegExp(r'学期$'), '').trim(); + final term = kSemesterTermNames.where(termName.contains).firstOrNull ?? termName; semesters.putIfAbsent(year, () => {})[term] = '$graduateSemesterPrefix${entry.key}'; } final defaultId = labels.containsKey(current) ? current : (labels.keys.toList()..sort()).last; @@ -119,14 +150,14 @@ class GraduateSchedule { List> unarrangedFor(String semesterId) { final term = rawTerm(semesterId); - final arranged = rows.where((r) => _inTerm(r, term)).map((r) => _text(r['BJDM'])).toSet(); - final cancelled = cancelledFor(semesterId).map((r) => _text(r['BJDM'])).toSet(); + final arranged = rows.where((r) => _inTerm(r, term)).map(_classId).toSet(); + final cancelled = cancelledFor(semesterId).map(_classId).toSet(); return _rows('xkjgList') .where( (r) => _inTerm(r, term) && - !arranged.contains(_text(r['BJDM'])) && - !cancelled.contains(_text(r['BJDM'])), + !arranged.contains(_classId(r)) && + !cancelled.contains(_classId(r)), ) .toList(); } @@ -150,12 +181,12 @@ class GraduateSchedule { } periods.sort((a, b) => a.index.compareTo(b.index)); final cancelled = - cancelledFor(semesterId).map((r) => _text(r['BJDM'])).where((id) => id.isNotEmpty).toSet(); + cancelledFor(semesterId).map(_classId).where((id) => id.isNotEmpty).toSet(); final courses = []; final anchor = firstMonday ?? firstMondayFor(semesterId); for (final row in rows.where((r) => _inTerm(r, rawTerm(semesterId)))) { if (_text(row['JCFADM']).isNotEmpty && _text(row['JCFADM']) != scheme) continue; - if (cancelled.contains(_text(row['BJDM']))) continue; + if (cancelled.contains(_classId(row))) continue; final day = int.tryParse(_text(row['XQ'])); final first = int.tryParse(_text(row['KSJCDM'])); final last = int.tryParse(_text(row['JSJCDM'])); @@ -173,9 +204,9 @@ class GraduateSchedule { if (units.any((n) => !periods.any((p) => p.index == n))) { throw const FormatException('研究生课表的排课与节次方案不匹配'); } - final dates = _datesFor(row, semesterId); + final dates = _datesFor(row, semesterId, firstMonday: anchor); final weeksByDay = >{}; - if (anchor != null && dates.isNotEmpty) { + if (anchor != null && dates != null) { final monday = DateTime.utc(anchor.year, anchor.month, anchor.day); for (final date in dates) { final offset = date.difference(monday).inDays; @@ -186,7 +217,7 @@ class GraduateSchedule { } } else if (_text(row['ZCMC']).isNotEmpty) { weeksByDay[day] = graduateWeeks(_text(row['ZCMC'])).toSet(); - } else if (dates.isEmpty) { + } else if (dates == null) { throw const FormatException('研究生课程缺少可识别的周次和日期'); } // Date-only records wait for a confirmed first Monday; they must not be @@ -211,40 +242,61 @@ class GraduateSchedule { return CourseTable(periods: periods, courses: courses); } - List _datesFor(Map row, String semesterId) { - var values = []; + /// Null means use the recurring schedule. An empty list means the dated + /// calendar covers this group but has no sessions for this segment. + List? _datesFor(Map row, String semesterId, {DateTime? firstMonday}) { if (_text(row['RQ']).isNotEmpty) { - values = [row['RQ']]; - } else if (row['rqs'] is List && (row['rqs'] as List).isNotEmpty) { - values = row['rqs'] as List; - } else if (_text(row['BJDM']).isNotEmpty && - rows - .where( - (r) => - _inTerm(r, rawTerm(semesterId)) && - r['BJDM'] == row['BJDM'] && - _text(r['KSJCDM']) == _text(row['KSJCDM']) && - _text(r['JSJCDM']) == _text(row['JSJCDM']), - ) - .length == - 1) { - final scheme = - _text(row['JCFADM']).isEmpty ? defaultScheme(semesterId) : _text(row['JCFADM']); - final periods = _rows('skjcList').where((p) => _text(p['JCFADM']) == scheme); - final first = periods.where((p) => _text(p['DM']) == _text(row['KSJCDM'])).firstOrNull; - final last = periods.where((p) => _text(p['DM']) == _text(row['JSJCDM'])).firstOrNull; - if (first != null && last != null) { - for (final record in _rows('rqpkjgallList')) { - if (record['bjdm'] == row['BJDM'] && - graduateTime(record['kssj']) == graduateTime(first['KSSJ']) && - graduateTime(record['jssj']) == graduateTime(last['JSSJ'])) { - if (_text(record['rq']).isNotEmpty) values.add(record['rq']); - if (record['rqs'] is List) values.addAll(record['rqs'] as List); - } - } - } + return _parseDates([row['RQ']]); + } + if (row['rqs'] is List && (row['rqs'] as List).isNotEmpty) { + return _parseDates(row['rqs'] as List); + } + final records = _rows('rqpkjgallList'); + if (records.isEmpty) return null; + final key = _rowClockKey(row, semesterId); + if (key == null) return null; + final dates = _parseDates([ + for (final r in records) + if (r['bjdm'] == row['BJDM'] && _clockKey(_text(r['bjdm']), r['kssj'], r['jssj']) == key) ...[ + if (_text(r['rq']).isNotEmpty) r['rq'], + if (r['rqs'] is List) ...(r['rqs'] as List), + ], + ]); + if (dates.isEmpty) return null; + final segments = rows.where( + (r) => _inTerm(r, rawTerm(semesterId)) && + r['BJDM'] == row['BJDM'] && + _rowClockKey(r, semesterId) == key, + ).toList(); + if (segments.length == 1) return dates; + if (firstMonday == null || segments.any((r) => _text(r['ZCMC']).isEmpty)) return null; + + final monday = DateTime.utc(firstMonday.year, firstMonday.month, firstMonday.day); + final weeks = {for (final segment in segments) segment: graduateWeeks(_text(segment['ZCMC']))}; + final assigned = []; + for (final date in dates) { + final offset = date.difference(monday).inDays; + final candidates = segments.where((s) => offset >= 0 && weeks[s]!.contains(offset ~/ 7 + 1)); + // A shifted weekday is attributable when just one segment teaches that week. + final owner = candidates.singleOrNull ?? + candidates.where((s) => _text(s['XQ']) == date.weekday.toString()).singleOrNull; + if (owner == null) return null; + if (identical(owner, row)) assigned.add(date); } - return _parseDates(values); + return assigned; + } + + String _clockKey(String id, dynamic first, dynamic last) => + '$id|${graduateTime(first)}|${graduateTime(last)}'; + + String? _rowClockKey(Map row, String semesterId) { + final id = _text(row['BJDM']); + if (id.isEmpty) return null; + final scheme = _text(row['JCFADM']).isEmpty ? defaultScheme(semesterId) : _text(row['JCFADM']); + final periods = _rows('skjcList').where((p) => _text(p['JCFADM']) == scheme); + final first = periods.where((p) => _text(p['DM']) == _text(row['KSJCDM'])).firstOrNull; + final last = periods.where((p) => _text(p['DM']) == _text(row['JSJCDM'])).firstOrNull; + return first == null || last == null ? null : _clockKey(id, first['KSSJ'], last['JSSJ']); } List _parseDates(List values) => values @@ -279,7 +331,7 @@ class GraduateSchedule { if (_text(row['ZCMC']).isEmpty) continue; final dates = _datesFor(row, semesterId); final weeks = graduateWeeks(_text(row['ZCMC'])); - if (dates.isEmpty || dates.length != weeks.length) continue; + if (dates == null || dates.length != weeks.length) continue; final day = int.tryParse(_text(row['XQ'])); for (var i = 0; i < dates.length; i++) { final date = dates[i]; @@ -298,24 +350,17 @@ class GraduateSchedule { DateTime? _firstMondayFromCalendarRecords(String semesterId) { final cancelled = cancelledFor(semesterId).map((r) => _text(r['BJDM'])).toSet(); final groups = >>{}; - String clockKey(String id, dynamic first, dynamic last) => - '$id|${graduateTime(first)}|${graduateTime(last)}'; for (final row in rows.where((r) => _inTerm(r, rawTerm(semesterId)))) { final id = _text(row['BJDM']); if (id.isEmpty || cancelled.contains(id) || _text(row['ZCMC']).isEmpty) continue; - final scheme = - _text(row['JCFADM']).isEmpty ? defaultScheme(semesterId) : _text(row['JCFADM']); - final periods = _rows('skjcList').where((p) => _text(p['JCFADM']) == scheme); - final first = periods.where((p) => _text(p['DM']) == _text(row['KSJCDM'])).firstOrNull; - final last = periods.where((p) => _text(p['DM']) == _text(row['JSJCDM'])).firstOrNull; - if (first == null || last == null) continue; - groups.putIfAbsent(clockKey(id, first['KSSJ'], last['JSSJ']), () => []).add(row); + final key = _rowClockKey(row, semesterId); + if (key != null) groups.putIfAbsent(key, () => []).add(row); } final dates = >{}; for (final record in _rows('rqpkjgallList')) { final id = _text(record['bjdm']); if (id.isEmpty || cancelled.contains(id)) continue; - final key = clockKey(id, record['kssj'], record['jssj']); + final key = _clockKey(id, record['kssj'], record['jssj']); if (!groups.containsKey(key)) continue; dates.putIfAbsent(key, () => []).addAll(_parseDates([ if (_text(record['rq']).isNotEmpty) record['rq'], diff --git a/lib/services/schedule_service.dart b/lib/services/schedule_service.dart index a97134d0..3937d1d1 100644 --- a/lib/services/schedule_service.dart +++ b/lib/services/schedule_service.dart @@ -48,11 +48,15 @@ class ScheduleService extends ChangeNotifier { if (_loading) throw const FormatException('课表加载中,请稍后切换来源'); final owner = _campusAccount(); if (owner == null) throw const FormatException('请先绑定 CpDaily / IDS'); - await _storage.setScheduleSource(owner, source); + final saved = _storage.setScheduleSource(owner, source); _identityForAccount = null; + _graduateIdentity = source == CampusScheduleSource.graduate; _identityLabel = null; _identityWarning = null; - await fetchAll(); + _restoreCachedSchedule(source); + notifyListeners(); + await saved; + if (owner == _campusAccount()) await fetchAll(); } Map get graduateSchemes => _selectedSemesterId == null @@ -117,16 +121,9 @@ class ScheduleService extends ChangeNotifier { _graduateIdentity = false; _identityLabel = null; _identityWarning = null; - _graduateSchedule = null; - _graduateScheme = null; _fetchedForAccount = null; - if (isGraduate) { - _semesterInfo = null; - _selectedSemesterId = null; - _courseTable = null; - _termCalendar = null; - notifyListeners(); - } + _clearSchedule(); + notifyListeners(); } requestFetch(); } @@ -173,20 +170,10 @@ class ScheduleService extends ChangeNotifier { final current = _campusAccount(); final changed = current != null && current != _fetchedForAccount; if (_fetchedForAccount != null && !changed && _error == null) return; - unawaited(_fetchAndStamp()); + unawaited(fetchAll()); }); } - Future _fetchAndStamp() async { - final account = _campusAccount(); - await fetchAll(); - // Only a success counts as "fetched for": a failed attempt has to be able to - // try again on the next trigger. - if (account != null && account == _campusAccount() && _error == null) { - _fetchedForAccount = account; - } - } - int currentWeek() { final begin = termBegin; if (begin == null) return 1; @@ -231,7 +218,9 @@ class ScheduleService extends ChangeNotifier { CourseTable? courseTableFor(String? semesterId) { if (semesterId == null) return null; - return semesterId == _selectedSemesterId ? _courseTable : _storage.loadCourseTable(semesterId); + return semesterId == _selectedSemesterId + ? _courseTable + : _storage.loadCourseTable(semesterId, owner: _campusAccount()); } TermCalendar? termCalendarFor(String? semesterId) { @@ -277,60 +266,109 @@ class ScheduleService extends ChangeNotifier { ); Future loadCachedData() async { - _semesterInfo = _storage.loadSemesters(); - if (_semesterInfo?.tableId == graduateTableId) { - if (_storage.graduateScheduleOwner != _campusAccount()) { - _semesterInfo = null; - notifyListeners(); + _restoreCachedSchedule(scheduleSource, onStartup: true); + final selected = _selectedSemesterId; + if (selected != null && _storage.selectedSemester != selected) { + await _storage.setSelectedSemester(selected); + } + notifyListeners(); + } + + void _clearSchedule() { + _semesterInfo = null; + _selectedSemesterId = null; + _courseTable = null; + _termCalendar = null; + _graduateSchedule = null; + _graduateScheme = null; + _error = null; + } + + void _restoreCachedSchedule(CampusScheduleSource source, {bool onStartup = false}) { + _clearSchedule(); + final owner = _campusAccount(); + final saved = _storage.loadSemesters(); + final kind = switch (source) { + CampusScheduleSource.graduate => CampusStudentKind.graduate, + CampusScheduleSource.undergraduate => CampusStudentKind.undergraduate, + CampusScheduleSource.automatic => owner == null ? null : _storage.loadCampusIdentity(owner)?.kind, + }; + // A fresh switch to automatic must wait for IDS when no identity is cached. + // On boot, older installations can still display their last timetable. + if (!onStartup && kind == null) return; + final graduate = kind == null ? saved?.info.tableId == graduateTableId : kind == CampusStudentKind.graduate; + if (graduate) { + if (owner == null || _storage.graduateScheduleOwner != owner) return; + _graduateSchedule = _storage.loadGraduateSchedule(); + _semesterInfo = _graduateSchedule?.semesterInfo; + if (_semesterInfo == null) return; + } else { + if (saved != null && + (saved.info.tableId == graduateTableId || (saved.owner != null && saved.owner != owner))) { return; } - _graduateSchedule = _storage.loadGraduateSchedule(); - } - _selectedSemesterId = _storage.selectedSemester ?? _semesterInfo?.defaultSemester; - if (isGraduate && - !_semesterInfo!.semesters.values.any((terms) => terms.containsValue(_selectedSemesterId))) { - _selectedSemesterId = _semesterInfo!.defaultSemester; + _semesterInfo = saved?.info; } - if (_selectedSemesterId != null) { - _courseTable = _storage.loadCourseTable(_selectedSemesterId!); + final cachedId = _storage.selectedSemester; + // Older undergraduate caches may contain just a selected term and its calendar. + if (_semesterInfo == null && (!onStartup || cachedId?.startsWith(graduateSemesterPrefix) != false)) { + return; } - _termCalendar = _storage.loadTermCalendar(_selectedSemesterId ?? ''); - if (isGraduate && _graduateSchedule != null && _selectedSemesterId != null) { - _graduateScheme = _schemeFor(_graduateSchedule!, _selectedSemesterId!); + final id = _validSemester(cachedId)!; + _selectedSemesterId = id; + _courseTable = _storage.loadCourseTable(id, owner: owner); + _termCalendar = _storage.loadTermCalendar(id); + if (_graduateSchedule != null) { + _graduateScheme = _schemeFor(_graduateSchedule!, id); try { - _courseTable = _graduateTable(_graduateSchedule!, _selectedSemesterId!, _graduateScheme!); + _courseTable = _graduateTable(_graduateSchedule!, id, _graduateScheme!); } on FormatException { _error = '研究生课表缓存需要刷新,请核对学期起始日'; } } - notifyListeners(); + } + + String? _validSemester(String? selected) { + final info = _semesterInfo; + if (info == null || info.semesters.values.any((terms) => terms.containsValue(selected))) { + return selected; + } + return info.defaultSemester; } Future fetchAll() async { if (_loading) return; // 避免启动时并发重复调用 if (!_hasCpdailyBinding) return; + final revision = _accountRevision; _loading = true; _error = null; _identityWarning = null; notifyListeners(); try { - if (await _fetchGraduateIfEligible()) return; + if (await _fetchGraduateIfEligible() || revision != _accountRevision) return; await fetchSemesters(); - if (!_semesterInfo!.semesters.values - .any((terms) => terms.containsValue(_selectedSemesterId))) { - _selectedSemesterId = _semesterInfo?.defaultSemester; - } + if (revision != _accountRevision) return; + _selectedSemesterId = _validSemester(_selectedSemesterId); if (_selectedSemesterId != null) { + if (_storage.selectedSemester != _selectedSemesterId) { + await _storage.setSelectedSemester(_selectedSemesterId!); + if (revision != _accountRevision) return; + } await Future.wait([ fetchCourseTable(_selectedSemesterId!), _fetchTermBeginForSemester(_selectedSemesterId!), ]); } } catch (e) { - _error = e.toString(); + if (revision == _accountRevision) _error = e.toString(); } finally { _loading = false; + if (revision == _accountRevision) { + if (_error == null) _fetchedForAccount = _campusAccount(); + } else if (_hasCpdailyBinding) { + requestFetch(force: true); + } notifyListeners(); } } @@ -375,6 +413,13 @@ class ScheduleService extends ChangeNotifier { } } } + if (revision != _accountRevision) return true; + if (_semesterInfo == null || isGraduate != _graduateIdentity) { + _restoreCachedSchedule( + _graduateIdentity ? CampusScheduleSource.graduate : CampusScheduleSource.undergraduate, + ); + notifyListeners(); + } if (!_graduateIdentity) return false; // Public info supplies the official current term, including empty terms. // A broken optional configuration endpoint must not discard an otherwise valid @@ -383,6 +428,7 @@ class ScheduleService extends ChangeNotifier { try { public = await client.publicInfo(); } catch (error) { + if (revision != _accountRevision) return true; final warning = '学期配置暂时不可用:${_schoolError(error)};按课表中的学期显示'; _identityWarning = [_identityWarning, warning].whereType().join(';'); } @@ -414,7 +460,6 @@ class ScheduleService extends ChangeNotifier { _selectedSemesterId = semester; _courseTable = table; await _storage.saveGraduateSchedule(account, snapshot); - await _storage.saveSemesters(info); await _storage.setSelectedSemester(semester); await _storage.saveCourseTable(semester, table); if (revision != _accountRevision) return true; @@ -486,6 +531,7 @@ class ScheduleService extends ChangeNotifier { } Future fetchSemesters() async { + final owner = _campusAccount(); final resp = await _postWithRetry( '$_baseUrl/schedule/semesters', const {}, @@ -497,7 +543,7 @@ class ScheduleService extends ChangeNotifier { } _semesterInfo = SemesterInfo.fromJson(data['data'] as Map); - await _storage.saveSemesters(_semesterInfo!); + await _storage.saveSemesters(_semesterInfo!, owner: owner); notifyListeners(); } @@ -512,6 +558,7 @@ class ScheduleService extends ChangeNotifier { notifyListeners(); return; } + final owner = _campusAccount(); final extra = { 'semester_id': semesterId, if (_semesterInfo?.tableId.isNotEmpty == true) 'table_id': _semesterInfo!.tableId, @@ -532,7 +579,7 @@ class ScheduleService extends ChangeNotifier { _courseTable = CourseTable.fromApiResponse( data['data'] as Map, ); - await _storage.saveCourseTable(semesterId, _courseTable!); + await _storage.saveCourseTable(semesterId, _courseTable!, owner: owner); notifyListeners(); } @@ -590,11 +637,13 @@ class ScheduleService extends ChangeNotifier { Future selectSemester(String semesterId) async { // No-op if the semester is already selected. if (_selectedSemesterId == semesterId) return; + final revision = _accountRevision; _selectedSemesterId = semesterId; await _storage.setSelectedSemester(semesterId); + if (revision != _accountRevision) return; // Load cached data for the new semester so the UI updates instantly. - _courseTable = _storage.loadCourseTable(semesterId); + _courseTable = _storage.loadCourseTable(semesterId, owner: _campusAccount()); _termCalendar = _storage.loadTermCalendar(semesterId); // Notify the cached-swap UI update. AssignmentService._onScheduleChanged // sees the semester changed and would fire fetchAssignments here — but @@ -621,10 +670,11 @@ class ScheduleService extends ChangeNotifier { _fetchTermBeginForSemester(semesterId), ]); } catch (e) { - _error = e.toString(); + if (revision == _accountRevision) _error = e.toString(); } finally { _loading = false; _suppressAssignmentRefetch = false; + if (revision != _accountRevision && _hasCpdailyBinding) requestFetch(force: true); // This final notify fires _onScheduleChanged again. Because // _suppressAssignmentRefetch is now false, AssignmentService will // refetch (the EAMS session is primed by our fetchCourseTable above, @@ -644,10 +694,12 @@ class ScheduleService extends ChangeNotifier { Map extra, String tag, ) async { + final revision = _accountRevision; final node = _tpAuth.eamsNode; final resp = await _tpAuth.sessionTree.withCookie( node, (cp) async { + if (revision != _accountRevision) throw StateError('学校账号已切换'); final body = {..._authBody(cp), ...extra}; final r = await _http.post( Uri.parse(url), @@ -661,6 +713,7 @@ class ScheduleService extends ChangeNotifier { ); }, ); + if (revision != _accountRevision) throw StateError('学校账号已切换'); if (resp == null) { throw Exception('cpdaily session unavailable'); } diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index 10aa197d..33ee06a6 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -301,22 +301,28 @@ class StorageService { await _prefs.setString('graduate_schedule_owner', owner); } - Future saveSemesters(SemesterInfo info) => - _prefs.setString(_semestersKey, jsonEncode(info.toJson())); + Future saveSemesters(SemesterInfo info, {String? owner}) => + _prefs.setString(_semestersKey, jsonEncode({...info.toJson(), 'owner': owner})); - SemesterInfo? loadSemesters() { + ({SemesterInfo info, String? owner})? loadSemesters() { final raw = _prefs.getString(_semestersKey); if (raw == null) return null; - return SemesterInfo.fromJson(jsonDecode(raw) as Map); + final json = jsonDecode(raw) as Map; + return (info: SemesterInfo.fromJson(json), owner: json['owner'] as String?); } - Future saveCourseTable(String semesterId, CourseTable table) => - _prefs.setString('$_courseTablePrefix$semesterId', jsonEncode(table.toJson())); + Future saveCourseTable(String semesterId, CourseTable table, {String? owner}) => + _prefs.setString( + '$_courseTablePrefix$semesterId', + jsonEncode({...table.toJson(), if (owner != null) 'owner': owner}), + ); - CourseTable? loadCourseTable(String semesterId) { + CourseTable? loadCourseTable(String semesterId, {String? owner}) { final raw = _prefs.getString('$_courseTablePrefix$semesterId'); if (raw == null) return null; - return CourseTable.fromJson(jsonDecode(raw) as Map); + final json = jsonDecode(raw) as Map; + if (json['owner'] != null && json['owner'] != owner) return null; + return CourseTable.fromJson(json); } Future saveTermCalendar(String key, TermCalendar info) => diff --git a/test/graduate_schedule_history_test.dart b/test/graduate_schedule_history_test.dart new file mode 100644 index 00000000..057852f9 --- /dev/null +++ b/test/graduate_schedule_history_test.dart @@ -0,0 +1,69 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/models/graduate_schedule.dart'; + +void main() { + final course = { + 'KCMC': '历史课程', + 'BJDM': 'class-1', + 'XNXQDM': '20251', + 'XNXQMC': '2025-2026学年 第一学期', + }; + final raw = { + 'results': >[], + 'xkjgList': [ + { + ...course, + 'PKSJDD': '1-3,5-12周 星期五[1-2节]甲教室;13-16周 星期五[1-2节]乙教室', + }, + { + ...course, + 'BJDM': null, + 'KCDM': 'H2', + 'PKSJDDMS': '3周 星期五[2节]丙教室
4周 星期日[1节]丁教室', + }, + {...course, 'BJDM': null, 'KCDM': 'H3'}, + {...course, 'BJDM': 'later', 'XNXQDM': '20252', 'XNXQMC': '2025-2026学年 第二学期'}, + ], + 'ntkmdList': >[], + 'mrjcfadm': 'A', + 'skjcList': [ + {'DM': 1, 'KSSJ': 815, 'JSSJ': 900, 'JCFADM': 'A'}, + {'DM': 2, 'KSSJ': 910, 'JSSJ': 955, 'JCFADM': 'A'}, + ], + }; + const semester = 'graduate:20251'; + + test('text-only enrollments preserve split rooms, sparse weeks and single meetings', () { + final schedule = GraduateSchedule.fromJson(raw); + final courses = schedule.tableFor(semester, schedule.defaultScheme(semester)).courses; + expect(courses, hasLength(4)); + final early = courses.singleWhere((c) => c.classroom == '甲教室'); + expect(early.times, {5: [1, 2]}); + expect(early.isActiveInWeek(3), isTrue); + expect(early.isActiveInWeek(4), isFalse); + expect(early.isActiveInWeek(5), isTrue); + expect(early.isActiveInWeek(13), isFalse); + expect(courses.singleWhere((c) => c.classroom == '乙教室').weeksText, '13-16周'); + final sunday = courses.singleWhere((c) => c.classroom == '丁教室'); + expect(sunday.times, {7: [1]}); + expect(sunday.weeksText, '4周'); + expect(schedule.unarrangedFor(semester).single['KCDM'], 'H3'); + }); + + test('existing structured meetings take precedence over enrollment descriptions', () { + final schedule = GraduateSchedule.fromJson({ + ...raw, + 'results': [ + {...course, 'XQ': 1, 'KSJCDM': 1, 'JSJCDM': 2, 'ZCMC': '2周', 'JASMC': '结构化教室'}, + ], + }); + final rooms = schedule.tableFor(semester, 'A').courses.map((c) => c.classroom); + expect(rooms, unorderedEquals(['结构化教室', '丙教室', '丁教室'])); + }); + + test('the common semester label adds the year and ordinal suffix exactly once', () { + final info = GraduateSchedule.fromJson({...raw, 'currentTerm': '20251'}).semesterInfo; + expect(info.findSemesterLabel(semester), '2025-2026 第一学期'); + expect(info.findSemesterLabel('graduate:20252'), '2025-2026 第二学期'); + }); +} diff --git a/test/graduate_schedule_test.dart b/test/graduate_schedule_test.dart index 21d86a64..0bd817b6 100644 --- a/test/graduate_schedule_test.dart +++ b/test/graduate_schedule_test.dart @@ -242,7 +242,22 @@ void main() { 'jssj': '0955', 'rq': '2026-09-22', }); - expect(GraduateSchedule.fromJson(raw).firstMondayFor(semester), DateTime(2026, 9, 14)); + final snapshot = GraduateSchedule.fromJson(raw); + expect(snapshot.firstMondayFor(semester), DateTime(2026, 9, 14)); + final table = snapshot.tableFor(semester, 'A'); + final meetings = [ + for (final course in table.courses.where((c) => c.name == '合成研究生课程')) + for (var week = 1; week <= 4; week++) + if (course.isActiveInWeek(week)) (week, course.times.keys.single, course.classroom), + ]; + expect(meetings, unorderedEquals([(1, 1, '示例教室'), (2, 2, '示例教室'), (4, 1, '后半学期教室')])); + + // All sessions of the second segment were cancelled in the dated calendar. + (raw['rqpkjgallList'] as List) + .removeWhere((r) => r['bjdm'] == 'g1' && r['rq'] == '2026-10-05'); + final partial = GraduateSchedule.fromJson(raw) + .tableFor(semester, 'A', firstMonday: DateTime(2026, 9, 14)); + expect(partial.courses.map((course) => course.classroom), isNot(contains('后半学期教室'))); }); test('graduate refresh automatically stores the inferred start without an EAMS request', @@ -600,6 +615,55 @@ void main() { isFalse, ); expect(h.storage.scheduleSourceFor('different-account'), CampusScheduleSource.automatic); + expect(h.storage.selectedSemester, 'undergrad-term'); + final restarted = ScheduleService(h.storage, h.httpClient, h.auth, h.tp); + addTearDown(restarted.dispose); + await restarted.loadCachedData(); + expect(restarted.selectedSemesterId, 'undergrad-term'); + expect(restarted.courseTable!.courses, isEmpty); + + // Repair stale selections written by an older version at cache hydration. + await h.storage.setSelectedSemester(semester); + await restarted.loadCachedData(); + expect(restarted.isGraduate, isFalse); + expect(restarted.selectedSemesterId, 'undergrad-term'); + expect(h.storage.selectedSemester, 'undergrad-term'); + expect(restarted.courseTable!.courses, isEmpty); + }); + + test('a failed source switch shows only the target timetable during and after refresh', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + await h.schedule.selectScheduleSource(CampusScheduleSource.graduate); + h.overrides['semesters'] = http.Response('offline', 503); + final switching = h.schedule.selectScheduleSource(CampusScheduleSource.undergraduate); + expect(h.schedule.semesterInfo, isNull); + expect(h.schedule.courseTable, isNull); + expect(h.schedule.termCalendar, isNull); + await switching; + expect(h.schedule.error, isNotNull); + expect(h.schedule.courseTable, isNull); + final restarted = ScheduleService(h.storage, h.httpClient, h.auth, h.tp); + addTearDown(restarted.dispose); + await restarted.loadCachedData(); + expect(restarted.courseTable, isNull); + + h.overrides.remove('semesters'); + await h.schedule.fetchAll(); + await h.schedule.selectScheduleSource(CampusScheduleSource.graduate); + h.overrides['semesters'] = http.Response('offline', 503); + final cachedSwitch = h.schedule.selectScheduleSource(CampusScheduleSource.undergraduate); + expect(h.schedule.selectedSemesterId, 'undergrad-term'); + expect(h.schedule.courseTable!.courses, isEmpty); + await cachedSwitch; + expect(h.schedule.error, isNotNull); + expect(h.schedule.selectedSemesterId, 'undergrad-term'); + expect(h.schedule.courseTable!.courses, isEmpty); + + // A semester ID can be shared by two undergraduate accounts. + await h.storage.saveCourseTable('undergrad-term', h.schedule.courseTable!, owner: 'other-user'); + await restarted.loadCachedData(); + expect(restarted.courseTable, isNull); }); test('cached IDS identity belongs to one account and survives only availability failures', @@ -672,6 +736,43 @@ void main() { expect(h.requests, isEmpty); }); + test('a new campus account fetches once after the previous account finishes', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + h.tableGate = Completer(); + final oldFetch = h.schedule.fetchAll(); + await h.tableEntered.future; + + const owner = '20260002|20260002'; + await h.storage.setScheduleSource(owner, CampusScheduleSource.graduate); + await h.tp.replaceAll([ + ThirdPartyAccount( + platform: ThirdPartyPlatform.cpdaily, + account: '20260002', + sid: '20260002', + token: 'session-b', + raw: const {'tgc': 'test-tgc-b'}, + boundAt: DateTime(2026), + ), + ]); + // Let B's debounce expire while A is still waiting for the timetable. + await Future.delayed(const Duration(milliseconds: 700)); + final refreshed = Completer(); + h.schedule.addListener(() { + if (!h.schedule.loading && h.storage.graduateScheduleOwner == owner && !refreshed.isCompleted) { + refreshed.complete(); + } + }); + h.tableGate!.complete(); + h.tableGate = null; + await oldFetch; + await refreshed.future.timeout(const Duration(seconds: 3)); + h.schedule.requestFetch(force: true); + await Future.delayed(const Duration(milliseconds: 700)); + expect(h.requests.where((r) => r.url.path.endsWith('/loadKbxx.do')), hasLength(2)); + expect(h.schedule.error, isNull); + }); + test('an unbind discards a late graduate response instead of caching it', () async { final h = await harness(); addTearDown(h.schedule.dispose); From 6c76f143149356b3ac27a7855e2a904428a31e2e Mon Sep 17 00:00:00 2001 From: gfdfdxc <29912959+gfdfdxc@users.noreply.github.com> Date: Fri, 13 Nov 2026 04:30:20 +0800 Subject: [PATCH 4/8] fix(schedule): isolate graduate caches and clear stale exams --- lib/services/assignment_service.dart | 2 +- lib/services/schedule_service.dart | 29 ++++++++++++---- lib/services/storage_service.dart | 39 +++++++++++++++++++--- lib/services/third_party_auth_service.dart | 16 +++++++++ 4 files changed, 73 insertions(+), 13 deletions(-) diff --git a/lib/services/assignment_service.dart b/lib/services/assignment_service.dart index 24966e6a..a599c45a 100644 --- a/lib/services/assignment_service.dart +++ b/lib/services/assignment_service.dart @@ -369,7 +369,7 @@ class AssignmentService extends ChangeNotifier { _schedule.isGraduate || semesterId?.startsWith(graduateSemesterPrefix) == true) { _platformErrors.remove('exam'); - return null; + return []; } final node = _tpAuth.eamsNode; if (!_tpAuth.hasCpdailyBinding || diff --git a/lib/services/schedule_service.dart b/lib/services/schedule_service.dart index 3937d1d1..be4f75bf 100644 --- a/lib/services/schedule_service.dart +++ b/lib/services/schedule_service.dart @@ -266,6 +266,7 @@ class ScheduleService extends ChangeNotifier { ); Future loadCachedData() async { + if (_campusAccount() == null) await _storage.clearGraduateScheduleCache(); _restoreCachedSchedule(scheduleSource, onStartup: true); final selected = _selectedSemesterId; if (selected != null && _storage.selectedSemester != selected) { @@ -460,8 +461,10 @@ class ScheduleService extends ChangeNotifier { _selectedSemesterId = semester; _courseTable = table; await _storage.saveGraduateSchedule(account, snapshot); + if (revision != _accountRevision) return true; await _storage.setSelectedSemester(semester); - await _storage.saveCourseTable(semester, table); + if (revision != _accountRevision) return true; + await _storage.saveCourseTable(semester, table, owner: account); if (revision != _accountRevision) return true; await _loadGraduateCalendar(semester); return true; @@ -495,13 +498,16 @@ class ScheduleService extends ChangeNotifier { if (!isGraduate || _selectedSemesterId == null || date.weekday != DateTime.monday) { throw const FormatException('请选择研究生学期第 1 周的周一'); } + final semester = _selectedSemesterId!; + final revision = _accountRevision; + final owner = _campusAccount(); final table = - _graduateSchedule!.tableFor(_selectedSemesterId!, _graduateScheme!, firstMonday: date); + _graduateSchedule!.tableFor(semester, _graduateScheme!, firstMonday: date); final weeks = table.courses.fold(_fallbackTotalWeeks, (n, c) => math.max(n, c.weeks.length - 1)); _termCalendar = TermCalendar( code: 200, - schoolYearTerm: _selectedSemesterId!, + schoolYearTerm: semester, termBegin: DateTime(date.year, date.month, date.day), snapshotDate: null, snapshotWeekOfTerm: null, @@ -511,9 +517,11 @@ class ScheduleService extends ChangeNotifier { pmClasses: 0, eveClasses: 0, ); - await _storage.saveTermCalendar(_selectedSemesterId!, _termCalendar!); + await _storage.saveTermCalendar(semester, _termCalendar!); + if (revision != _accountRevision) return; _courseTable = table; - await _storage.saveCourseTable(_selectedSemesterId!, table); + await _storage.saveCourseTable(semester, table, owner: owner); + if (revision != _accountRevision) return; notifyListeners(); } @@ -522,11 +530,15 @@ class ScheduleService extends ChangeNotifier { if (_graduateSchedule == null || semester == null || !graduateSchemes.containsKey(scheme)) { return; } + final revision = _accountRevision; + final owner = _campusAccount(); final table = _graduateTable(_graduateSchedule!, semester, scheme); _graduateScheme = scheme; _courseTable = table; await _storage.setGraduateScheme(semester, scheme); - await _storage.saveCourseTable(semester, table); + if (revision != _accountRevision) return; + await _storage.saveCourseTable(semester, table, owner: owner); + if (revision != _accountRevision) return; notifyListeners(); } @@ -550,11 +562,14 @@ class ScheduleService extends ChangeNotifier { Future fetchCourseTable(String semesterId) async { if (semesterId.startsWith(graduateSemesterPrefix)) { if (_graduateSchedule == null) throw const FormatException('请先刷新研究生课表'); + final revision = _accountRevision; + final owner = _campusAccount(); final scheme = _schemeFor(_graduateSchedule!, semesterId); final table = _graduateTable(_graduateSchedule!, semesterId, scheme); _graduateScheme = scheme; _courseTable = table; - await _storage.saveCourseTable(semesterId, table); + await _storage.saveCourseTable(semesterId, table, owner: owner); + if (revision != _accountRevision) return; notifyListeners(); return; } diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index 33ee06a6..ff6ad5fc 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -279,7 +279,17 @@ class StorageService { jsonEncode({'owner': owner, 'source': source.name}), ); - String? get graduateScheduleOwner => _prefs.getString('graduate_schedule_owner'); + String? get graduateScheduleOwner { + final current = _prefs.getString('graduate_schedule_v2'); + final raw = current ?? _prefs.getString('graduate_schedule'); + if (raw == null) return null; + try { + final data = jsonDecode(raw) as Map; + return current == null ? _prefs.getString('graduate_schedule_owner') : data['owner'] as String?; + } catch (_) { + return null; + } + } String? graduateSchemeFor(String semesterId) => _prefs.getString('graduate_scheme_$semesterId'); @@ -287,7 +297,7 @@ class StorageService { _prefs.setString('graduate_scheme_$semesterId', scheme); GraduateSchedule? loadGraduateSchedule() { - final raw = _prefs.getString('graduate_schedule'); + final raw = _prefs.getString('graduate_schedule_v2') ?? _prefs.getString('graduate_schedule'); if (raw == null) return null; try { return GraduateSchedule.fromJson(jsonDecode(raw) as Map); @@ -296,9 +306,25 @@ class StorageService { } } - Future saveGraduateSchedule(String owner, GraduateSchedule schedule) async { - await _prefs.setString('graduate_schedule', jsonEncode(schedule.toJson())); - await _prefs.setString('graduate_schedule_owner', owner); + Future saveGraduateSchedule(String owner, GraduateSchedule schedule) => + // Keep the owner and response in one preference write. + _prefs.setString('graduate_schedule_v2', jsonEncode({...schedule.toJson(), 'owner': owner})); + + Future clearGraduateScheduleCache() async { + final keys = _prefs.getKeys().where( + (key) => + key == 'graduate_schedule' || + key == 'graduate_schedule_v2' || + key == 'graduate_schedule_owner' || + key.startsWith('$_courseTablePrefix$graduateSemesterPrefix') || + key.startsWith('$_termBeginPrefix$graduateSemesterPrefix') || + key.startsWith('graduate_scheme_'), + ).toList(); + if (loadSemesters()?.info.tableId == graduateTableId) keys.add(_semestersKey); + if (selectedSemester?.startsWith(graduateSemesterPrefix) == true) { + keys.add(_selectedSemesterKey); + } + await Future.wait(keys.map(_prefs.remove)); } Future saveSemesters(SemesterInfo info, {String? owner}) => @@ -321,6 +347,9 @@ class StorageService { final raw = _prefs.getString('$_courseTablePrefix$semesterId'); if (raw == null) return null; final json = jsonDecode(raw) as Map; + if (semesterId.startsWith(graduateSemesterPrefix) && (owner == null || json['owner'] != owner)) { + return null; + } if (json['owner'] != null && json['owner'] != owner) return null; return CourseTable.fromJson(json); } diff --git a/lib/services/third_party_auth_service.dart b/lib/services/third_party_auth_service.dart index d570ac11..099aed84 100644 --- a/lib/services/third_party_auth_service.dart +++ b/lib/services/third_party_auth_service.dart @@ -417,6 +417,7 @@ class ThirdPartyAuthService extends ChangeNotifier { Future unbind(ThirdPartyPlatform platform) async { _tree.setAccount(platform, null); + if (platform == ThirdPartyPlatform.cpdaily) await _storage.clearGraduateScheduleCache(); await _storage.clearThirdPartyAccount(platform); // Unbinding cpdaily invalidates all downstream derived cookies. if (platform == ThirdPartyPlatform.cpdaily) { @@ -441,6 +442,13 @@ class ThirdPartyAuthService extends ChangeNotifier { /// existing platform binding, writes each entry in [next] to secure storage, /// and rebuilds the in-memory map. Fires a single notification. Future replaceAll(List next) async { + final currentCampus = _tree.cpdaily.account; + final nextCampus = next.where((a) => a.platform == ThirdPartyPlatform.cpdaily).firstOrNull; + if (currentCampus != null && + (nextCampus?.sid != currentCampus.sid || nextCampus?.account != currentCampus.account)) { + _tree.setAccount(ThirdPartyPlatform.cpdaily, null); + await _storage.clearGraduateScheduleCache(); + } // Clear storage for every platform first. for (final p in ThirdPartyPlatform.values) { await _storage.clearThirdPartyAccount(p); @@ -485,6 +493,12 @@ class ThirdPartyAuthService extends ChangeNotifier { if (next != null && cur != null && _accountEqual(cur, next)) continue; if (next == null && cur == null) continue; if (next != null) { + if (p == ThirdPartyPlatform.cpdaily && + cur != null && + (next.sid != cur.sid || next.account != cur.account)) { + _tree.setAccount(p, null); + await _storage.clearGraduateScheduleCache(); + } await _storage.saveThirdPartyAccount(next); _tree.setAccount(p, next); } else { @@ -496,6 +510,7 @@ class ThirdPartyAuthService extends ChangeNotifier { } } _tree.setAccount(p, null); + if (p == ThirdPartyPlatform.cpdaily) await _storage.clearGraduateScheduleCache(); await _storage.clearThirdPartyAccount(p); } } @@ -657,6 +672,7 @@ class ThirdPartyAuthService extends ChangeNotifier { } _tree.setAccount(p, null); } + await _storage.clearGraduateScheduleCache(); await _storage.clearAllThirdPartyAccounts(); await _storage.clearAllDerivedCookies(); _onTreeChanged(force: true); From 6b68cd108be86fdaae5b7380cb4ec8655b9127af Mon Sep 17 00:00:00 2001 From: gfdfdxc <29912959+gfdfdxc@users.noreply.github.com> Date: Mon, 16 Nov 2026 03:37:14 +0800 Subject: [PATCH 5/8] fix(schedule): wait for identity before fetching exams --- lib/services/assignment_service.dart | 13 +++-- lib/services/schedule_service.dart | 22 +++++++- test/assignment_service_test.dart | 3 ++ test/graduate_schedule_test.dart | 76 ++++++++++++++++++++++++++++ 4 files changed, 109 insertions(+), 5 deletions(-) diff --git a/lib/services/assignment_service.dart b/lib/services/assignment_service.dart index a599c45a..363f367c 100644 --- a/lib/services/assignment_service.dart +++ b/lib/services/assignment_service.dart @@ -361,16 +361,21 @@ class AssignmentService extends ChangeNotifier { } } + bool get _graduateExamsUnsupported => _schedule.hasGraduateIdentity || + _schedule.isGraduate || + _selectedSemesterId()?.startsWith(graduateSemesterPrefix) == true; + Future?> _fetchExamTable() async { - final semesterId = _selectedSemesterId(); + final undergraduate = + !_graduateExamsUnsupported && await _schedule.canFetchUndergraduateExams(); // Graduate term ids belong to a different school system. Sending one to // EAMS would query the wrong term and can disturb its stateful session. - if (_schedule.hasGraduateIdentity || - _schedule.isGraduate || - semesterId?.startsWith(graduateSemesterPrefix) == true) { + if (_graduateExamsUnsupported) { _platformErrors.remove('exam'); return []; } + if (!undergraduate) return null; + final semesterId = _selectedSemesterId(); final node = _tpAuth.eamsNode; if (!_tpAuth.hasCpdailyBinding || semesterId == null || diff --git a/lib/services/schedule_service.dart b/lib/services/schedule_service.dart index be4f75bf..761d45c2 100644 --- a/lib/services/schedule_service.dart +++ b/lib/services/schedule_service.dart @@ -32,6 +32,8 @@ class ScheduleService extends ChangeNotifier { GraduateSchedule? _graduateSchedule; String? _graduateScheme; String? _identityForAccount; + bool _identityResolved = false; + Completer? _fetchCompletion; bool _graduateIdentity = false; String? _identityLabel; String? _identityWarning; @@ -50,6 +52,7 @@ class ScheduleService extends ChangeNotifier { if (owner == null) throw const FormatException('请先绑定 CpDaily / IDS'); final saved = _storage.setScheduleSource(owner, source); _identityForAccount = null; + _identityResolved = false; _graduateIdentity = source == CampusScheduleSource.graduate; _identityLabel = null; _identityWarning = null; @@ -118,6 +121,7 @@ class ScheduleService extends ChangeNotifier { _observedAccount = account; _accountRevision++; _identityForAccount = null; + _identityResolved = false; _graduateIdentity = false; _identityLabel = null; _identityWarning = null; @@ -337,9 +341,21 @@ class ScheduleService extends ChangeNotifier { return info.defaultSemester; } + Future canFetchUndergraduateExams() async { + if (!_hasCpdailyBinding) return false; + if (scheduleSource == CampusScheduleSource.undergraduate) return true; + final revision = _accountRevision; + if (!_identityResolved || _loading) await fetchAll(); + return revision == _accountRevision && _identityResolved && !_graduateIdentity; + } + Future fetchAll() async { - if (_loading) return; // 避免启动时并发重复调用 + if (_loading) { + await _fetchCompletion?.future; + return; + } if (!_hasCpdailyBinding) return; + final completion = _fetchCompletion = Completer(); final revision = _accountRevision; _loading = true; _error = null; @@ -370,6 +386,8 @@ class ScheduleService extends ChangeNotifier { } else if (_hasCpdailyBinding) { requestFetch(force: true); } + _fetchCompletion = null; + completion.complete(); notifyListeners(); } } @@ -383,6 +401,7 @@ class ScheduleService extends ChangeNotifier { final client = GraduateScheduleClient(_http, _tpAuth.cpdailyNode.rawFields['tgc'] as String? ?? ''); if (_identityForAccount != account) { + _identityResolved = false; final source = scheduleSource; if (source != CampusScheduleSource.automatic) { _graduateIdentity = source == CampusScheduleSource.graduate; @@ -415,6 +434,7 @@ class ScheduleService extends ChangeNotifier { } } if (revision != _accountRevision) return true; + _identityResolved = true; if (_semesterInfo == null || isGraduate != _graduateIdentity) { _restoreCachedSchedule( _graduateIdentity ? CampusScheduleSource.graduate : CampusScheduleSource.undergraduate, diff --git a/test/assignment_service_test.dart b/test/assignment_service_test.dart index 23b38860..43e1259c 100644 --- a/test/assignment_service_test.dart +++ b/test/assignment_service_test.dart @@ -5,6 +5,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; import 'package:techpie/models/assignment.dart'; +import 'package:techpie/models/campus_identity.dart'; import 'package:techpie/models/third_party_account.dart'; import 'package:techpie/models/user_session.dart'; import 'package:techpie/services/assignment_service.dart'; @@ -24,6 +25,7 @@ void main() { FlutterSecureStorage.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); final storage = StorageService(prefs); + await storage.setScheduleSource('student|student', CampusScheduleSource.undergraduate); final oldBlackboard = _assignmentJson( id: 'blackboard-old', @@ -138,6 +140,7 @@ void main() { FlutterSecureStorage.setMockInitialValues({}); final prefs = await SharedPreferences.getInstance(); final storage = StorageService(prefs); + await storage.setScheduleSource('student|student', CampusScheduleSource.undergraduate); await storage.setSelectedSemester('263'); await storage.saveSession( UserSession( diff --git a/test/graduate_schedule_test.dart b/test/graduate_schedule_test.dart index 0bd817b6..1970627b 100644 --- a/test/graduate_schedule_test.dart +++ b/test/graduate_schedule_test.dart @@ -736,6 +736,76 @@ void main() { expect(h.requests, isEmpty); }); + for (final graduate in [true, false]) { + test('startup exam fetching waits for IDS classification (graduate=$graduate)', () async { + final h = await harness(graduate: graduate); + addTearDown(h.schedule.dispose); + await h.storage.setSelectedSemester('undergrad-term'); + h.identityGate = Completer(); + h.overrides['exam_table'] = http.Response( + jsonEncode({'success': true, 'data': {'exams': []}}), + 200, + ); + final assignments = AssignmentService(h.storage, h.httpClient, h.auth, h.tp, h.schedule); + addTearDown(assignments.dispose); + h.schedule.requestFetch(force: true); + final exams = assignments.fetchPlatform('exam'); + await h.identityEntered.future.timeout(const Duration(seconds: 3)); + final earlyExams = h.requests.where((r) => r.url.path.endsWith('/exam_table')).toList(); + final scheduleDone = Completer(); + h.schedule.addListener(() { + if (!h.schedule.loading && !scheduleDone.isCompleted) scheduleDone.complete(); + }); + h.identityGate!.complete(); + await Future.wait([exams, scheduleDone.future]); + expect(earlyExams, isEmpty); + expect( + h.requests.where((r) => r.url.path.endsWith('/exam_table')), + hasLength(graduate ? 0 : 1), + ); + expect(h.requests.where((r) => r.url.path.endsWith('/getUserConf')), hasLength(1)); + expect(assignments.platformErrors, isEmpty); + }); + } + + test('an unresolved identity never sends a cached undergraduate semester to EAMS', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + await h.storage.setSelectedSemester('undergrad-term'); + h.overrides['getUserConf'] = http.Response('offline', 503); + final assignments = AssignmentService(h.storage, h.httpClient, h.auth, h.tp, h.schedule); + addTearDown(assignments.dispose); + await assignments.fetchPlatform('exam'); + expect(h.requests.any((r) => r.url.path.endsWith('/exam_table')), isFalse); + expect(h.requests.any((r) => r.url.path.endsWith('/eams')), isFalse); + }); + + test('confirmed cached undergraduate identity permits exams when IDS is unavailable', () async { + final h = await harness(graduate: false); + addTearDown(h.schedule.dispose); + await h.storage.saveCampusIdentity( + '20260001|20260001', CampusIdentity.fromCategory('学生/本科生'), + ); + h.overrides['getUserConf'] = http.Response('offline', 503); + h.overrides['exam_table'] = http.Response( + jsonEncode({'success': true, 'data': {'exams': []}}), 200, + ); + final assignments = AssignmentService(h.storage, h.httpClient, h.auth, h.tp, h.schedule); + addTearDown(assignments.dispose); + await assignments.fetchPlatform('exam'); + expect(h.requests.where((r) => r.url.path.endsWith('/exam_table')), hasLength(1)); + expect(assignments.platformErrors, isEmpty); + h.overrides['getUserConf'] = http.Response( + jsonEncode({'code': '0', 'datas': {'uid': 'different-account', 'categoryName': '学生/本科生'}}), + 200, + headers: {'content-type': 'application/json; charset=utf-8'}, + ); + await h.schedule.fetchAll(); + h.requests.clear(); + await assignments.fetchPlatform('exam'); + expect(h.requests.any((r) => r.url.path.endsWith('/exam_table')), isFalse); + }); + test('a new campus account fetches once after the previous account finishes', () async { final h = await harness(); addTearDown(h.schedule.dispose); @@ -795,6 +865,8 @@ class Harness { late AuthService auth; late ThirdPartyAuthService tp; Completer? tableGate; + Completer? identityGate; + final identityEntered = Completer(); final tableEntered = Completer(); final requests = []; final overrides = {}; @@ -823,6 +895,10 @@ Future harness({bool graduate = true, String profileSid = '20260001'}) h.requests.add(request); final override = h.overrides[request.url.path.split('/').last]; if (override != null) return override; + if (request.url.path.endsWith('getUserConf') && h.identityGate != null) { + h.identityEntered.complete(); + await h.identityGate!.future; + } if (request.url.path.endsWith('loadKbxx.do') && h.tableGate != null) { h.tableEntered.complete(); await h.tableGate!.future; From d26259d82af7833b5463e8af02afcda9754f8f26 Mon Sep 17 00:00:00 2001 From: gfdfdxc <29912959+gfdfdxc@users.noreply.github.com> Date: Mon, 16 Nov 2026 04:21:05 +0800 Subject: [PATCH 6/8] Merge graduate schedule test --- test/graduate_review_followup_test.dart | 390 ------------------------ test/graduate_schedule_test.dart | 366 ++++++++++++++++++++++ 2 files changed, 366 insertions(+), 390 deletions(-) delete mode 100644 test/graduate_review_followup_test.dart diff --git a/test/graduate_review_followup_test.dart b/test/graduate_review_followup_test.dart deleted file mode 100644 index 32edc1a8..00000000 --- a/test/graduate_review_followup_test.dart +++ /dev/null @@ -1,390 +0,0 @@ -import 'dart:async'; -import 'dart:convert'; - -import 'package:flutter_test/flutter_test.dart'; -import 'package:http/http.dart' as http; -import 'package:http/testing.dart'; -import 'package:shared_preferences/shared_preferences.dart'; -import 'package:techpie/models/assignment.dart'; -import 'package:techpie/models/course_table.dart'; -import 'package:techpie/models/graduate_schedule.dart'; -import 'package:techpie/models/ids_passkey.dart'; -import 'package:techpie/models/third_party_account.dart'; -import 'package:techpie/services/assignment_service.dart'; -import 'package:techpie/services/debug_logger.dart'; -import 'package:techpie/services/graduate_schedule_client.dart'; -import 'package:techpie/services/http_client.dart'; -import 'package:techpie/services/schedule_service.dart'; -import 'package:techpie/services/storage_service.dart'; -import 'package:techpie/services/third_party_auth_service.dart'; - -import 'graduate_schedule_test.dart' as fixtures; -import 'support/fake_ids_client.dart'; - -void main() { - TestWidgetsFlutterBinding.ensureInitialized(); - const owner = '20260001|20260001'; - const semester = fixtures.semester; - - test('IDS response cookies rotate within the client and stay off the graduate host', () async { - const ids = GraduateScheduleClient.idsHost; - const graduate = GraduateScheduleClient.host; - var idsVisits = 0; - final log = LoggingHttpClient( - DebugLogger(), - inner: MockClient((request) async { - final uri = request.url; - if (uri.host == ids) { - expect( - request.headers['cookie'], - contains('CASTGC=${idsVisits == 0 ? 'bound' : 'rotated'}'), - ); - idsVisits++; - if (uri.path.endsWith('index.html')) { - return http.Response( - 'IDS', - 200, - headers: {'set-cookie': 'CASTGC=rotated; Path=/; Secure'}, - ); - } - if (uri.path.endsWith('getUserConf')) { - return http.Response( - jsonEncode({ - 'code': '0', - 'datas': {'uid': '20260001', 'categoryName': '学生/硕士生'}, - }), - 200, - headers: {'content-type': 'application/json; charset=utf-8'}, - ); - } - return http.Response( - '', - 302, - headers: { - 'location': - 'https://$graduate${GraduateScheduleClient.base}*default/index.do?ticket=test', - }, - ); - } - expect(uri.host, graduate); - expect(request.headers['cookie'] ?? '', isNot(contains('CASTGC'))); - if (uri.path.endsWith('loadKbxx.do')) { - return http.Response( - jsonEncode(fixtures.fixture()), - 200, - headers: {'content-type': 'application/json; charset=utf-8'}, - ); - } - if (uri.hasQuery) { - return http.Response( - 'course', - 200, - headers: {'set-cookie': 'CASTGC=foreign; Path=/; Secure'}, - ); - } - return http.Response('', 302, headers: {'location': 'https://$ids/authserver/login'}); - }), - ); - addTearDown(log.close); - final client = GraduateScheduleClient(log, 'bound'); - await client.identity('20260001'); - await client.timetable(); - expect(idsVisits, 3); - expect(client.tgc, 'bound'); - }); - - for (final removal in [ - 'unbind', - 'clearAll', - 'replaceAll', - 'syncRemove', - 'replaceAccount', - 'syncAccount', - 'rebindSameAccount', - ]) { - test('$removal removes graduate caches before the same account is rebound', () async { - final h = await fixtures.harness(); - addTearDown(h.schedule.dispose); - await h.schedule.fetchAll(); - await h.schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)); - await h.schedule.selectGraduateScheme('B'); - final prefs = await SharedPreferences.getInstance(); - final snapshot = GraduateSchedule.fromJson(fixtures.fixture()); - await prefs.setString('graduate_schedule', jsonEncode(snapshot.toJson())); - await prefs.setString('graduate_schedule_owner', owner); - await h.storage.saveSemesters(snapshot.semesterInfo, owner: owner); - await h.storage - .saveCourseTable('undergrad-term', const CourseTable(periods: [], courses: [])); - switch (removal) { - case 'unbind': - await h.tp.unbind(ThirdPartyPlatform.ids); - case 'clearAll': - await h.tp.clearAll(); - case 'replaceAll': - await h.tp.replaceAll([]); - case 'syncRemove': - await h.tp.applyIdsSyncBinding( - IdsSyncBinding(credential: null, updatedAt: DateTime.now(), deviceId: 'fixture'), - ); - case 'replaceAccount': - await h.tp.bindIds( - account: '20260002', - password: 'synthetic', - promptCaptcha: (_, __, {required refresh}) async => null, - ); - case 'syncAccount': - await h.tp.applyIdsSyncBinding( - IdsSyncBinding( - credential: FakeIdsClient.key('20260002'), - updatedAt: DateTime.now(), - deviceId: 'fixture', - ), - ); - case 'rebindSameAccount': - await h.tp.bindIds( - account: '20260001', - password: 'synthetic', - promptCaptcha: (_, __, {required refresh}) async => null, - ); - } - await h.schedule.loadCachedData(); - expect(h.schedule.courseTable, isNull); - expect(h.schedule.courseTableFor(semester), isNull); - expect(h.storage.graduateScheduleOwner, isNull); - expect(h.storage.loadGraduateSchedule(), isNull); - expect(prefs.getString('graduate_schedule_owner'), isNull); - expect(h.storage.loadCourseTable(semester, owner: owner), isNull); - expect(h.storage.loadTermCalendar(semester), isNull); - expect(h.storage.graduateSchemeFor(semester), isNull); - expect(h.storage.selectedSemester, isNull); - expect(h.storage.loadSemesters(), isNull); - expect(h.storage.loadCourseTable('undergrad-term'), isNotNull); - await h.tp.bindIds( - account: '20260001', - password: 'synthetic', - promptCaptcha: (_, __, {required refresh}) async => null, - ); - await h.schedule.loadCachedData(); - expect(h.schedule.courseTable, isNull); - h.requests.clear(); - await h.schedule.fetchAll(); - expect(h.schedule.courseTable!.courses, isNotEmpty); - expect(h.requests.any((r) => r.url.path.endsWith('loadKbxx.do')), isTrue); - }); - } - - test('startup clears graduate caches left by an older unbound installation', () async { - final h = await fixtures.harness(); - await h.schedule.fetchAll(); - h.schedule.dispose(); - await h.storage.clearThirdPartyAccount(ThirdPartyPlatform.ids); - final tp = ThirdPartyAuthService(h.storage, h.httpClient); - await tp.initialize(); - addTearDown(tp.dispose); - final schedule = ScheduleService(h.storage, h.httpClient, h.auth, tp); - addTearDown(schedule.dispose); - await schedule.loadCachedData(); - expect(h.storage.loadGraduateSchedule(), isNull); - expect(h.storage.loadCourseTable(semester, owner: owner), isNull); - expect(h.storage.selectedSemester, isNull); - expect(schedule.courseTable, isNull); - }); - - test('all graduate table writes carry ownership, including non-selected semesters', () async { - final h = await fixtures.harness(); - addTearDown(h.schedule.dispose); - await h.schedule.fetchAll(); - void checkOwner() { - expect(h.storage.loadCourseTable(semester, owner: owner), isNotNull); - expect(h.storage.loadCourseTable(semester, owner: 'another-account'), isNull); - } - - checkOwner(); - await h.tp.unbind(ThirdPartyPlatform.gradescope); - checkOwner(); - await h.schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)); - checkOwner(); - await h.schedule.selectGraduateScheme('B'); - checkOwner(); - await h.schedule.fetchCourseTable(semester); - checkOwner(); - const otherSemester = 'graduate:20262'; - await h.storage.saveCourseTable(otherSemester, h.schedule.courseTable!, owner: owner); - expect(h.schedule.courseTableFor(otherSemester), isNotNull); - await h.tp.unbind(ThirdPartyPlatform.ids); - expect(h.schedule.courseTableFor(semester), isNull); - expect(h.schedule.courseTableFor(otherSemester), isNull); - final prefs = await SharedPreferences.getInstance(); - await prefs.setString( - 'schedule_course_table_$semester', - jsonEncode( - const CourseTable( - periods: [], - courses: [], - ).toJson(), - ), - ); - expect(h.storage.loadCourseTable(semester, owner: owner), isNull); - await prefs.setString( - 'schedule_course_table_legacy-undergrad', - jsonEncode(const CourseTable(periods: [], courses: []).toJson()), - ); - expect(h.storage.loadCourseTable('legacy-undergrad', owner: owner), isNotNull); - }); - - test('graduate snapshots read legacy owners and save owner and response together', () async { - final h = await fixtures.harness(); - addTearDown(h.schedule.dispose); - final prefs = await SharedPreferences.getInstance(); - final snapshot = GraduateSchedule.fromJson(fixtures.fixture()); - await prefs.setString('graduate_schedule', jsonEncode(snapshot.toJson())); - await prefs.setString('graduate_schedule_owner', owner); - expect(h.storage.graduateScheduleOwner, owner); - await h.storage.saveGraduateSchedule('new-owner', snapshot); - expect(jsonDecode(prefs.getString('graduate_schedule_v2')!)['owner'], 'new-owner'); - expect(prefs.getString('graduate_schedule_owner'), owner); - expect(jsonDecode(prefs.getString('graduate_schedule')!), snapshot.toJson()); - expect(h.storage.graduateScheduleOwner, 'new-owner'); - expect(h.storage.loadGraduateSchedule()!.rows, isNotEmpty); - }); - - for (final phase in ['snapshot', 'selection', 'calendar', 'scheme']) { - test('an unbind during $phase persistence stops the remaining graduate writes', () async { - final h = await fixtures.harness(); - h.schedule.dispose(); - final storage = _PausedStorage(await SharedPreferences.getInstance()); - final schedule = ScheduleService(storage, h.httpClient, h.auth, h.tp); - addTearDown(schedule.dispose); - if (phase == 'calendar' || phase == 'scheme') await schedule.fetchAll(); - storage.phase = phase; - storage.writes.clear(); - final pending = switch (phase) { - 'calendar' => schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)), - 'scheme' => schedule.selectGraduateScheme('B'), - _ => schedule.fetchAll(), - }; - await storage.entered.future; - await h.tp.unbind(ThirdPartyPlatform.ids); - storage.release.complete(); - await pending; - expect(schedule.courseTable, isNull); - expect(storage.loadGraduateSchedule(), isNull); - expect(storage.loadCourseTable(semester, owner: owner), isNull); - expect(storage.writes, isNot(contains('table'))); - if (phase == 'snapshot') expect(storage.writes, isNot(contains('selection'))); - }); - } - - for (final nextAccount in ['20260002', '20260001']) { - test('rebinding $nextAccount during snapshot save discards the old response', () async { - final h = await fixtures.harness(); - h.schedule.dispose(); - final storage = _PausedStorage(await SharedPreferences.getInstance())..phase = 'snapshot'; - final schedule = ScheduleService(storage, h.httpClient, h.auth, h.tp); - addTearDown(schedule.dispose); - final pending = schedule.fetchAll(); - await storage.entered.future; - await h.tp.bindIds( - account: nextAccount, - password: 'synthetic', - promptCaptcha: (_, __, {required refresh}) async => null, - ); - expect(schedule.courseTable, isNull); - expect(storage.loadGraduateSchedule(), isNull); - storage.release.complete(); - await pending; - expect(schedule.courseTable, isNull); - expect(storage.loadGraduateSchedule(), isNull); - expect(storage.selectedSemester, isNull); - await h.tp.bindIds( - account: '20260001', - password: 'synthetic', - promptCaptcha: (_, __, {required refresh}) async => null, - ); - await schedule.loadCachedData(); - expect(schedule.courseTable, isNull); - expect(storage.graduateScheduleOwner, isNull); - }); - } - - test('unsupported graduate exams remove old exams while retaining assignments', () async { - final h = await fixtures.harness(); - addTearDown(h.schedule.dispose); - await h.schedule.fetchAll(); - await h.storage.saveCachedAssignments([ - ExamAssignment( - id: 'old-exam', - title: '本科考试', - course: '旧课程', - due: DateTime(2026), - semesterId: 'undergrad-term', - location: '', - batchName: '', - ).toJson(), - Assignment( - id: 'homework', - platform: 'blackboard', - title: '作业', - course: '课程', - due: DateTime(2026), - ).toJson(), - ]); - final assignments = AssignmentService(h.storage, h.httpClient, h.auth, h.tp, h.schedule); - addTearDown(assignments.dispose); - assignments.loadCached(); - h.requests.clear(); - await assignments.fetchPlatform('exam'); - expect(assignments.assignments.map((a) => a.id), ['homework']); - expect(h.storage.loadCachedAssignments().map((a) => a['id']), ['homework']); - expect(assignments.platformErrors, isEmpty); - expect(h.requests, isEmpty); - }); -} - -class _PausedStorage extends StorageService { - _PausedStorage(super.prefs); - - String? phase; - final entered = Completer(); - final release = Completer(); - final writes = []; - - Future _pause(String name) async { - writes.add(name); - if (name == phase) { - entered.complete(); - await release.future; - } - } - - @override - Future saveGraduateSchedule(String owner, GraduateSchedule schedule) async { - final pending = super.saveGraduateSchedule(owner, schedule); - await _pause('snapshot'); - await pending; - } - - @override - Future setSelectedSemester(String id) async { - await super.setSelectedSemester(id); - await _pause('selection'); - } - - @override - Future saveTermCalendar(String key, TermCalendar info) async { - await super.saveTermCalendar(key, info); - await _pause('calendar'); - } - - @override - Future setGraduateScheme(String semesterId, String scheme) async { - await super.setGraduateScheme(semesterId, scheme); - await _pause('scheme'); - } - - @override - Future saveCourseTable(String semesterId, CourseTable table, {String? owner}) async { - await super.saveCourseTable(semesterId, table, owner: owner); - await _pause('table'); - } -} diff --git a/test/graduate_schedule_test.dart b/test/graduate_schedule_test.dart index c97476e8..77e88e27 100644 --- a/test/graduate_schedule_test.dart +++ b/test/graduate_schedule_test.dart @@ -6,8 +6,11 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:http/testing.dart'; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:techpie/models/assignment.dart'; import 'package:techpie/models/campus_identity.dart'; +import 'package:techpie/models/course_table.dart'; import 'package:techpie/models/graduate_schedule.dart'; +import 'package:techpie/models/ids_passkey.dart'; import 'package:techpie/models/third_party_account.dart'; import 'package:techpie/services/assignment_service.dart'; import 'package:techpie/services/auth_service.dart'; @@ -109,6 +112,7 @@ Map datedFixture() { void main() { TestWidgetsFlutterBinding.ensureInitialized(); + const owner = '20260001|20260001'; test('graduate terms are namespaced; schemes retain their actual clock times', () { final schedule = GraduateSchedule.fromJson(fixture()); @@ -865,6 +869,320 @@ void main() { expect(h.schedule.semesterInfo, isNull); expect(h.storage.graduateScheduleOwner, isNull); }); + + test('IDS response cookies rotate within the client and stay off the graduate host', () async { + const ids = GraduateScheduleClient.idsHost; + const graduate = GraduateScheduleClient.host; + var idsVisits = 0; + final log = LoggingHttpClient( + DebugLogger(), + inner: MockClient((request) async { + final uri = request.url; + if (uri.host == ids) { + expect( + request.headers['cookie'], + contains('CASTGC=${idsVisits == 0 ? 'bound' : 'rotated'}'), + ); + idsVisits++; + if (uri.path.endsWith('index.html')) { + return http.Response( + 'IDS', + 200, + headers: {'set-cookie': 'CASTGC=rotated; Path=/; Secure'}, + ); + } + if (uri.path.endsWith('getUserConf')) { + return http.Response( + jsonEncode({ + 'code': '0', + 'datas': {'uid': '20260001', 'categoryName': '学生/硕士生'}, + }), + 200, + headers: {'content-type': 'application/json; charset=utf-8'}, + ); + } + return http.Response( + '', + 302, + headers: { + 'location': + 'https://$graduate${GraduateScheduleClient.base}*default/index.do?ticket=test', + }, + ); + } + expect(uri.host, graduate); + expect(request.headers['cookie'] ?? '', isNot(contains('CASTGC'))); + if (uri.path.endsWith('loadKbxx.do')) { + return http.Response( + jsonEncode(fixture()), + 200, + headers: {'content-type': 'application/json; charset=utf-8'}, + ); + } + if (uri.hasQuery) { + return http.Response( + 'course', + 200, + headers: {'set-cookie': 'CASTGC=foreign; Path=/; Secure'}, + ); + } + return http.Response('', 302, headers: {'location': 'https://$ids/authserver/login'}); + }), + ); + addTearDown(log.close); + final client = GraduateScheduleClient(log, 'bound'); + await client.identity('20260001'); + await client.timetable(); + expect(idsVisits, 3); + expect(client.tgc, 'bound'); + }); + + for (final removal in [ + 'unbind', + 'clearAll', + 'replaceAll', + 'syncRemove', + 'replaceAccount', + 'syncAccount', + 'rebindSameAccount', + ]) { + test('$removal removes graduate caches before the same account is rebound', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + await h.schedule.fetchAll(); + await h.schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)); + await h.schedule.selectGraduateScheme('B'); + final prefs = await SharedPreferences.getInstance(); + final snapshot = GraduateSchedule.fromJson(fixture()); + await prefs.setString('graduate_schedule', jsonEncode(snapshot.toJson())); + await prefs.setString('graduate_schedule_owner', owner); + await h.storage.saveSemesters(snapshot.semesterInfo, owner: owner); + await h.storage + .saveCourseTable('undergrad-term', const CourseTable(periods: [], courses: [])); + switch (removal) { + case 'unbind': + await h.tp.unbind(ThirdPartyPlatform.ids); + case 'clearAll': + await h.tp.clearAll(); + case 'replaceAll': + await h.tp.replaceAll([]); + case 'syncRemove': + await h.tp.applyIdsSyncBinding( + IdsSyncBinding(credential: null, updatedAt: DateTime.now(), deviceId: 'fixture'), + ); + case 'replaceAccount': + await h.tp.bindIds( + account: '20260002', + password: 'synthetic', + promptCaptcha: (_, __, {required refresh}) async => null, + ); + case 'syncAccount': + await h.tp.applyIdsSyncBinding( + IdsSyncBinding( + credential: FakeIdsClient.key('20260002'), + updatedAt: DateTime.now(), + deviceId: 'fixture', + ), + ); + case 'rebindSameAccount': + await h.tp.bindIds( + account: '20260001', + password: 'synthetic', + promptCaptcha: (_, __, {required refresh}) async => null, + ); + } + await h.schedule.loadCachedData(); + expect(h.schedule.courseTable, isNull); + expect(h.schedule.courseTableFor(semester), isNull); + expect(h.storage.graduateScheduleOwner, isNull); + expect(h.storage.loadGraduateSchedule(), isNull); + expect(prefs.getString('graduate_schedule_owner'), isNull); + expect(h.storage.loadCourseTable(semester, owner: owner), isNull); + expect(h.storage.loadTermCalendar(semester), isNull); + expect(h.storage.graduateSchemeFor(semester), isNull); + expect(h.storage.selectedSemester, isNull); + expect(h.storage.loadSemesters(), isNull); + expect(h.storage.loadCourseTable('undergrad-term'), isNotNull); + await h.tp.bindIds( + account: '20260001', + password: 'synthetic', + promptCaptcha: (_, __, {required refresh}) async => null, + ); + await h.schedule.loadCachedData(); + expect(h.schedule.courseTable, isNull); + h.requests.clear(); + await h.schedule.fetchAll(); + expect(h.schedule.courseTable!.courses, isNotEmpty); + expect(h.requests.any((r) => r.url.path.endsWith('loadKbxx.do')), isTrue); + }); + } + + test('startup clears graduate caches left by an older unbound installation', () async { + final h = await harness(); + await h.schedule.fetchAll(); + h.schedule.dispose(); + await h.storage.clearThirdPartyAccount(ThirdPartyPlatform.ids); + final tp = ThirdPartyAuthService(h.storage, h.httpClient); + await tp.initialize(); + addTearDown(tp.dispose); + final schedule = ScheduleService(h.storage, h.httpClient, h.auth, tp); + addTearDown(schedule.dispose); + await schedule.loadCachedData(); + expect(h.storage.loadGraduateSchedule(), isNull); + expect(h.storage.loadCourseTable(semester, owner: owner), isNull); + expect(h.storage.selectedSemester, isNull); + expect(schedule.courseTable, isNull); + }); + + test('all graduate table writes carry ownership, including non-selected semesters', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + await h.schedule.fetchAll(); + void checkOwner() { + expect(h.storage.loadCourseTable(semester, owner: owner), isNotNull); + expect(h.storage.loadCourseTable(semester, owner: 'another-account'), isNull); + } + + checkOwner(); + await h.tp.unbind(ThirdPartyPlatform.gradescope); + checkOwner(); + await h.schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)); + checkOwner(); + await h.schedule.selectGraduateScheme('B'); + checkOwner(); + await h.schedule.fetchCourseTable(semester); + checkOwner(); + const otherSemester = 'graduate:20262'; + await h.storage.saveCourseTable(otherSemester, h.schedule.courseTable!, owner: owner); + expect(h.schedule.courseTableFor(otherSemester), isNotNull); + await h.tp.unbind(ThirdPartyPlatform.ids); + expect(h.schedule.courseTableFor(semester), isNull); + expect(h.schedule.courseTableFor(otherSemester), isNull); + final prefs = await SharedPreferences.getInstance(); + await prefs.setString( + 'schedule_course_table_$semester', + jsonEncode( + const CourseTable( + periods: [], + courses: [], + ).toJson(), + ), + ); + expect(h.storage.loadCourseTable(semester, owner: owner), isNull); + await prefs.setString( + 'schedule_course_table_legacy-undergrad', + jsonEncode(const CourseTable(periods: [], courses: []).toJson()), + ); + expect(h.storage.loadCourseTable('legacy-undergrad', owner: owner), isNotNull); + }); + + test('graduate snapshots read legacy owners and save owner and response together', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + final prefs = await SharedPreferences.getInstance(); + final snapshot = GraduateSchedule.fromJson(fixture()); + await prefs.setString('graduate_schedule', jsonEncode(snapshot.toJson())); + await prefs.setString('graduate_schedule_owner', owner); + expect(h.storage.graduateScheduleOwner, owner); + await h.storage.saveGraduateSchedule('new-owner', snapshot); + expect(jsonDecode(prefs.getString('graduate_schedule_v2')!)['owner'], 'new-owner'); + expect(prefs.getString('graduate_schedule_owner'), owner); + expect(jsonDecode(prefs.getString('graduate_schedule')!), snapshot.toJson()); + expect(h.storage.graduateScheduleOwner, 'new-owner'); + expect(h.storage.loadGraduateSchedule()!.rows, isNotEmpty); + }); + + for (final phase in ['snapshot', 'selection', 'calendar', 'scheme']) { + test('an unbind during $phase persistence stops the remaining graduate writes', () async { + final h = await harness(); + h.schedule.dispose(); + final storage = _PausedStorage(await SharedPreferences.getInstance()); + final schedule = ScheduleService(storage, h.httpClient, h.auth, h.tp); + addTearDown(schedule.dispose); + if (phase == 'calendar' || phase == 'scheme') await schedule.fetchAll(); + storage.phase = phase; + storage.writes.clear(); + final pending = switch (phase) { + 'calendar' => schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)), + 'scheme' => schedule.selectGraduateScheme('B'), + _ => schedule.fetchAll(), + }; + await storage.entered.future; + await h.tp.unbind(ThirdPartyPlatform.ids); + storage.release.complete(); + await pending; + expect(schedule.courseTable, isNull); + expect(storage.loadGraduateSchedule(), isNull); + expect(storage.loadCourseTable(semester, owner: owner), isNull); + expect(storage.writes, isNot(contains('table'))); + if (phase == 'snapshot') expect(storage.writes, isNot(contains('selection'))); + }); + } + + for (final nextAccount in ['20260002', '20260001']) { + test('rebinding $nextAccount during snapshot save discards the old response', () async { + final h = await harness(); + h.schedule.dispose(); + final storage = _PausedStorage(await SharedPreferences.getInstance())..phase = 'snapshot'; + final schedule = ScheduleService(storage, h.httpClient, h.auth, h.tp); + addTearDown(schedule.dispose); + final pending = schedule.fetchAll(); + await storage.entered.future; + await h.tp.bindIds( + account: nextAccount, + password: 'synthetic', + promptCaptcha: (_, __, {required refresh}) async => null, + ); + expect(schedule.courseTable, isNull); + expect(storage.loadGraduateSchedule(), isNull); + storage.release.complete(); + await pending; + expect(schedule.courseTable, isNull); + expect(storage.loadGraduateSchedule(), isNull); + expect(storage.selectedSemester, isNull); + await h.tp.bindIds( + account: '20260001', + password: 'synthetic', + promptCaptcha: (_, __, {required refresh}) async => null, + ); + await schedule.loadCachedData(); + expect(schedule.courseTable, isNull); + expect(storage.graduateScheduleOwner, isNull); + }); + } + + test('unsupported graduate exams remove old exams while retaining assignments', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + await h.schedule.fetchAll(); + await h.storage.saveCachedAssignments([ + ExamAssignment( + id: 'old-exam', + title: '本科考试', + course: '旧课程', + due: DateTime(2026), + semesterId: 'undergrad-term', + location: '', + batchName: '', + ).toJson(), + Assignment( + id: 'homework', + platform: 'blackboard', + title: '作业', + course: '课程', + due: DateTime(2026), + ).toJson(), + ]); + final assignments = AssignmentService(h.storage, h.httpClient, h.auth, h.tp, h.schedule); + addTearDown(assignments.dispose); + assignments.loadCached(); + h.requests.clear(); + await assignments.fetchPlatform('exam'); + expect(assignments.assignments.map((a) => a.id), ['homework']); + expect(h.storage.loadCachedAssignments().map((a) => a['id']), ['homework']); + expect(assignments.platformErrors, isEmpty); + expect(h.requests, isEmpty); + }); } class Harness { @@ -958,3 +1276,51 @@ Future harness({bool graduate = true, String profileSid = '20260001'}) h.schedule = ScheduleService(storage, client, auth, tp); return h; } + +class _PausedStorage extends StorageService { + _PausedStorage(super.prefs); + + String? phase; + final entered = Completer(); + final release = Completer(); + final writes = []; + + Future _pause(String name) async { + writes.add(name); + if (name == phase) { + entered.complete(); + await release.future; + } + } + + @override + Future saveGraduateSchedule(String owner, GraduateSchedule schedule) async { + final pending = super.saveGraduateSchedule(owner, schedule); + await _pause('snapshot'); + await pending; + } + + @override + Future setSelectedSemester(String id) async { + await super.setSelectedSemester(id); + await _pause('selection'); + } + + @override + Future saveTermCalendar(String key, TermCalendar info) async { + await super.saveTermCalendar(key, info); + await _pause('calendar'); + } + + @override + Future setGraduateScheme(String semesterId, String scheme) async { + await super.setGraduateScheme(semesterId, scheme); + await _pause('scheme'); + } + + @override + Future saveCourseTable(String semesterId, CourseTable table, {String? owner}) async { + await super.saveCourseTable(semesterId, table, owner: owner); + await _pause('table'); + } +} From 1496231ecb48707d2a94ade7dcc0e034404b432b Mon Sep 17 00:00:00 2001 From: gfdfdxc <29912959+gfdfdxc@users.noreply.github.com> Date: Mon, 16 Nov 2026 04:34:04 +0800 Subject: [PATCH 7/8] refactor(schedule): remove manual term start setting --- lib/models/graduate_schedule.dart | 4 +-- lib/pages/schedule_page.dart | 38 ----------------------- lib/services/schedule_service.dart | 21 +++++++------ test/graduate_schedule_test.dart | 50 +++++++++++++++++++----------- 4 files changed, 45 insertions(+), 68 deletions(-) diff --git a/lib/models/graduate_schedule.dart b/lib/models/graduate_schedule.dart index 32b9183d..07680db3 100644 --- a/lib/models/graduate_schedule.dart +++ b/lib/models/graduate_schedule.dart @@ -211,7 +211,7 @@ class GraduateSchedule { for (final date in dates) { final offset = date.difference(monday).inDays; if (offset < 0 || offset >= 60 * 7) { - throw const FormatException('课程日期超出学期范围,请核对第 1 周周一'); + throw const FormatException('研究生课程日期与学期范围不一致,请刷新课表'); } weeksByDay.putIfAbsent(date.weekday, () => {}).add(offset ~/ 7 + 1); } @@ -221,7 +221,7 @@ class GraduateSchedule { throw const FormatException('研究生课程缺少可识别的周次和日期'); } // Date-only records wait for a confirmed first Monday; they must not be - // invented as weekly recurring courses. The page exposes the date control. + // invented as weekly recurring courses. for (final entry in weeksByDay.entries) { final weeks = entry.value.toList()..sort(); final bits = List.filled(weeks.last + 1, '0'); diff --git a/lib/pages/schedule_page.dart b/lib/pages/schedule_page.dart index ca572b4a..d4653b95 100644 --- a/lib/pages/schedule_page.dart +++ b/lib/pages/schedule_page.dart @@ -606,12 +606,6 @@ class _SchedulePageState extends State { value: 'source', title: '课表来源', ), - if (_schedule.isGraduate) - const IosNativeNavigationBarMenuItem( - value: 'termStart', - title: '设置学期起始日', - sfSymbol: 'calendar', - ), IosNativeNavigationBarMenuItem( value: 'saturday', title: '显示周六', @@ -745,8 +739,6 @@ class _SchedulePageState extends State { child: Text('切换学期'), ), const PopupMenuItem(value: 'source', child: Text('课表来源')), - if (_schedule.isGraduate) - const PopupMenuItem(value: 'termStart', child: Text('设置学期起始日')), CheckedPopupMenuItem( value: 'saturday', checked: _showSaturday, @@ -1080,25 +1072,6 @@ class _SchedulePageState extends State { ), ); - Future _setGraduateFirstMonday() async { - final now = DateTime.now(); - final date = await showDatePicker( - context: context, - helpText: '选择本学期第 1 周的周一(仅保存在本机)', - initialDate: _schedule.termBegin ?? now.subtract(Duration(days: now.weekday - 1)), - firstDate: DateTime(2000), - lastDate: DateTime(2100), - selectableDayPredicate: (date) => date.weekday == DateTime.monday, - ); - if (date != null && mounted) { - try { - await _schedule.setGraduateFirstMonday(date); - } catch (error) { - if (mounted) ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$error'))); - } - } - } - Future _showGraduateExtraCourses() async { await showDialog( context: context, @@ -1153,8 +1126,6 @@ class _SchedulePageState extends State { _showSemesterPicker(); case 'source': unawaited(_showScheduleSource()); - case 'termStart': - unawaited(_setGraduateFirstMonday()); case 'saturday': setState(() => _showSaturday = !_showSaturday); case 'sunday': @@ -1300,15 +1271,6 @@ class _SchedulePageState extends State { unawaited(_showScheduleSource()); }, ), - if (_schedule.isGraduate) - DesktopMenuRow( - leading: const Icon(Icons.event_outlined, size: 20), - title: Text('设置学期起始日', style: theme.textTheme.bodyMedium), - onTap: () { - close(); - unawaited(_setGraduateFirstMonday()); - }, - ), const Divider(height: 1), DesktopMenuRow( leading: Icon( diff --git a/lib/services/schedule_service.dart b/lib/services/schedule_service.dart index b880a1de..22a7d7a0 100644 --- a/lib/services/schedule_service.dart +++ b/lib/services/schedule_service.dart @@ -330,7 +330,7 @@ class ScheduleService extends ChangeNotifier { try { _courseTable = _graduateTable(_graduateSchedule!, id, _graduateScheme!); } on FormatException { - _error = '研究生课表缓存需要刷新,请核对学期起始日'; + _error = '研究生课表日期缓存需要刷新'; } } } @@ -506,8 +506,8 @@ class ScheduleService extends ChangeNotifier { Future _loadGraduateCalendar(String semesterId) async { _termCalendar = _storage.loadTermCalendar(semesterId); final inferred = _graduateSchedule?.firstMondayFor(semesterId); - if (_termCalendar == null && inferred != null) { - await setGraduateFirstMonday(inferred); + if (inferred != null && _termCalendar?.termBegin != inferred) { + await _saveGraduateCalendar(semesterId, inferred); } } @@ -518,14 +518,15 @@ class ScheduleService extends ChangeNotifier { : snapshot.defaultScheme(semesterId); } - CourseTable _graduateTable(GraduateSchedule snapshot, String semester, String scheme) => snapshot - .tableFor(semester, scheme, firstMonday: _storage.loadTermCalendar(semester)?.termBegin); + CourseTable _graduateTable(GraduateSchedule snapshot, String semester, String scheme) => + snapshot.tableFor( + semester, + scheme, + firstMonday: + snapshot.firstMondayFor(semester) ?? _storage.loadTermCalendar(semester)?.termBegin, + ); - Future setGraduateFirstMonday(DateTime date) async { - if (!isGraduate || _selectedSemesterId == null || date.weekday != DateTime.monday) { - throw const FormatException('请选择研究生学期第 1 周的周一'); - } - final semester = _selectedSemesterId!; + Future _saveGraduateCalendar(String semester, DateTime date) async { final revision = _accountRevision; final owner = _campusAccount(); final table = diff --git a/test/graduate_schedule_test.dart b/test/graduate_schedule_test.dart index 77e88e27..606e03f5 100644 --- a/test/graduate_schedule_test.dart +++ b/test/graduate_schedule_test.dart @@ -93,6 +93,14 @@ Map fixture() => { const semester = 'graduate:20261'; +Map fixtureWithStart() { + final raw = fixture(); + final row = (raw['results'] as List).first as Map; + row['ZCMC'] = '1周'; + row['RQ'] = '2026-09-07'; + return raw; +} + Map datedFixture() { final raw = fixture(); final original = raw['results'] as List; @@ -278,9 +286,17 @@ void main() { expect(h.storage.loadTermCalendar(semester)!.termBegin, DateTime(2026, 9, 14)); expect(h.requests.any((r) => r.url.path.contains('/api/')), isFalse); expect(h.requests.any((r) => r.url.host == 'eams.shanghaitech.edu.cn'), isFalse); - await h.schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)); + await h.storage.saveTermCalendar( + semester, + TermCalendar.fromJson({ + ...h.storage.loadTermCalendar(semester)!.toJson(), + 'termBegin': '2026-11-02', + }), + ); await h.schedule.fetchAll(); - expect(h.schedule.termBegin, DateTime(2026, 9, 7)); + expect(h.schedule.error, isNull); + expect(h.schedule.termBegin, DateTime(2026, 9, 14)); + expect(h.storage.loadTermCalendar(semester)!.termBegin, DateTime(2026, 9, 14)); }); test('the official protected entry establishes graduate cookies before API reads', () async { @@ -409,8 +425,6 @@ void main() { isTrue, ); expect(h.requests.any((r) => r.url.path.contains('/api/')), isFalse); - await h.schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)); - expect(h.schedule.termBegin, DateTime(2026, 9, 7)); expect(h.schedule.totalWeeks, greaterThanOrEqualTo(16)); await h.schedule.selectGraduateScheme('B'); expect(h.schedule.courseTable!.courses.single.name, '合成研选本课程'); @@ -701,11 +715,10 @@ void main() { expect(h.requests.every((r) => r.url.host == GraduateScheduleClient.idsHost), isTrue); }); - test('selected scheme and local start date survive a cached restart', () async { - final h = await harness(); + test('selected scheme and inferred start date survive a cached restart', () async { + final h = await harness(timetable: fixtureWithStart()); addTearDown(h.schedule.dispose); await h.schedule.fetchAll(); - await h.schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)); await h.schedule.selectGraduateScheme('B'); final restored = ScheduleService(h.storage, h.httpClient, h.auth, h.tp); addTearDown(restored.dispose); @@ -947,10 +960,9 @@ void main() { 'rebindSameAccount', ]) { test('$removal removes graduate caches before the same account is rebound', () async { - final h = await harness(); + final h = await harness(timetable: fixtureWithStart()); addTearDown(h.schedule.dispose); await h.schedule.fetchAll(); - await h.schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)); await h.schedule.selectGraduateScheme('B'); final prefs = await SharedPreferences.getInstance(); final snapshot = GraduateSchedule.fromJson(fixture()); @@ -1035,7 +1047,7 @@ void main() { }); test('all graduate table writes carry ownership, including non-selected semesters', () async { - final h = await harness(); + final h = await harness(timetable: fixtureWithStart()); addTearDown(h.schedule.dispose); await h.schedule.fetchAll(); void checkOwner() { @@ -1046,8 +1058,6 @@ void main() { checkOwner(); await h.tp.unbind(ThirdPartyPlatform.gradescope); checkOwner(); - await h.schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)); - checkOwner(); await h.schedule.selectGraduateScheme('B'); checkOwner(); await h.schedule.fetchCourseTable(semester); @@ -1094,27 +1104,27 @@ void main() { for (final phase in ['snapshot', 'selection', 'calendar', 'scheme']) { test('an unbind during $phase persistence stops the remaining graduate writes', () async { - final h = await harness(); + final h = await harness(timetable: fixtureWithStart()); h.schedule.dispose(); final storage = _PausedStorage(await SharedPreferences.getInstance()); final schedule = ScheduleService(storage, h.httpClient, h.auth, h.tp); addTearDown(schedule.dispose); - if (phase == 'calendar' || phase == 'scheme') await schedule.fetchAll(); + if (phase == 'scheme') await schedule.fetchAll(); storage.phase = phase; storage.writes.clear(); final pending = switch (phase) { - 'calendar' => schedule.setGraduateFirstMonday(DateTime(2026, 9, 7)), 'scheme' => schedule.selectGraduateScheme('B'), _ => schedule.fetchAll(), }; await storage.entered.future; + final tableWrites = storage.writes.where((name) => name == 'table').length; await h.tp.unbind(ThirdPartyPlatform.ids); storage.release.complete(); await pending; expect(schedule.courseTable, isNull); expect(storage.loadGraduateSchedule(), isNull); expect(storage.loadCourseTable(semester, owner: owner), isNull); - expect(storage.writes, isNot(contains('table'))); + expect(storage.writes.where((name) => name == 'table'), hasLength(tableWrites)); if (phase == 'snapshot') expect(storage.writes, isNot(contains('selection'))); }); } @@ -1201,7 +1211,11 @@ class Harness { bool fail = false; } -Future harness({bool graduate = true, String profileSid = '20260001'}) async { +Future harness({ + bool graduate = true, + String profileSid = '20260001', + Map? timetable, +}) async { SharedPreferences.setMockInitialValues({}); FlutterSecureStorage.setMockInitialValues({}); final storage = StorageService(await SharedPreferences.getInstance()); @@ -1230,7 +1244,7 @@ Future harness({bool graduate = true, String profileSid = '20260001'}) 'code': '0', 'datas': {'uid': profileSid, 'categoryName': h.category}, }, - 'loadKbxx.do' => fixture(), + 'loadKbxx.do' => timetable ?? fixture(), 'loadPublicInfo_course.do' => { 'lcxxMap': {'XNXQDM': '20261', 'XNXQMC': '2026-2027学年秋季学期'}, }, From f34ec2de7bbd53d24473dd9b24f56bcbdd956c52 Mon Sep 17 00:00:00 2001 From: gfdfdxc <29912959+gfdfdxc@users.noreply.github.com> Date: Tue, 17 Nov 2026 13:56:33 +0800 Subject: [PATCH 8/8] fix(schedule): isolate cookies and revalidate IDS sessions --- lib/services/assignment_service.dart | 14 +- lib/services/graduate_schedule_client.dart | 9 +- lib/services/schedule_service.dart | 100 +++++++++------ lib/services/storage_service.dart | 2 + test/graduate_schedule_test.dart | 142 +++++++++++++++++++++ 5 files changed, 224 insertions(+), 43 deletions(-) diff --git a/lib/services/assignment_service.dart b/lib/services/assignment_service.dart index f377860f..deb04f0c 100644 --- a/lib/services/assignment_service.dart +++ b/lib/services/assignment_service.dart @@ -475,11 +475,19 @@ class AssignmentService extends ChangeNotifier { final resp = await _tpAuth.sessionTree.withCookie( node, (cp) async { + // Minting EAMS cookies can renew IDS after the initial identity check. + if (!await _schedule.canFetchUndergraduateExams()) { + throw const FormatException('学校身份尚未确认'); + } + final currentSemester = _selectedSemesterId(); + if (currentSemester == null || currentSemester.isEmpty) { + throw const FormatException('本科课表学期尚未确认'); + } final r = await _http.post( Uri.parse('$_baseUrl/schedule/exam_table'), headers: _jsonHeaders(), body: jsonEncode({ - 'semester_id': semesterId, + 'semester_id': currentSemester, 'cookies': cp.cookies, }), tag: 'schedule:exam_table', @@ -490,6 +498,10 @@ class AssignmentService extends ChangeNotifier { if (resp == null) return null; return _parseExamTableResponse(resp); } catch (e) { + if (_graduateExamsUnsupported) { + _platformErrors.remove('exam'); + return []; + } _platformErrors['exam'] = '同步失败,请检查网络或稍后重试'; return null; } diff --git a/lib/services/graduate_schedule_client.dart b/lib/services/graduate_schedule_client.dart index d7efdc3b..da4525ff 100644 --- a/lib/services/graduate_schedule_client.dart +++ b/lib/services/graduate_schedule_client.dart @@ -13,7 +13,7 @@ class GraduateScheduleClient { final LoggingHttpClient http; final String tgc; - final List<_SchoolCookie> _cookies = []; + final Map> _cookieJars = {}; Future? _graduateSession; static const host = 'graduate-course.shanghaitech.edu.cn'; static const idsHost = 'ids.shanghaitech.edu.cn'; @@ -147,7 +147,8 @@ class GraduateScheduleClient { } for (var hop = 0; hop < 12; hop++) { if (!_allowed(uri)) throw const FormatException('学校登录跳转地址不受支持'); - final applicable = _cookies + final jar = _cookieJars.putIfAbsent(uri.origin, () => []); + final applicable = jar .where((c) => c.matches(uri) && (c.cookie.name != 'CASTGC' || uri.host == idsHost)); final cookies = [ ...applicable.map((c) => '${c.cookie.name}=${c.cookie.value}'), @@ -192,12 +193,12 @@ class GraduateScheduleClient { cookie.domain == null, cookie.path?.startsWith('/') == true ? cookie.path! : defaultPath, ); - _cookies.removeWhere( + jar.removeWhere( (c) => c.cookie.name == cookie.name && c.domain == domain && c.path == stored.path, ); if (cookie.maxAge != 0 && (cookie.expires == null || cookie.expires!.isAfter(DateTime.now()))) { - _cookies.add(stored); + jar.add(stored); } } on HttpException { // Ignore malformed optional cookie headers. diff --git a/lib/services/schedule_service.dart b/lib/services/schedule_service.dart index 22a7d7a0..5cd43f4a 100644 --- a/lib/services/schedule_service.dart +++ b/lib/services/schedule_service.dart @@ -32,6 +32,7 @@ class ScheduleService extends ChangeNotifier { GraduateSchedule? _graduateSchedule; String? _graduateScheme; String? _identityForAccount; + String? _identityForSession; bool _identityResolved = false; Completer? _fetchCompletion; bool _graduateIdentity = false; @@ -45,6 +46,9 @@ class ScheduleService extends ChangeNotifier { String? get identityLabel => _identityLabel; String? get identityWarning => _identityWarning; CampusScheduleSource get scheduleSource => _storage.scheduleSourceFor(_campusAccount()); + String? get _idsSession => _tpAuth.idsNode.cookieProvider?.cookies; + bool get _identityIsCurrent => _identityResolved && + (scheduleSource != CampusScheduleSource.automatic || _identityForSession == _idsSession); Future selectScheduleSource(CampusScheduleSource source) async { if (_loading) throw const FormatException('课表加载中,请稍后切换来源'); @@ -52,6 +56,7 @@ class ScheduleService extends ChangeNotifier { if (owner == null) throw const FormatException('请先绑定 CpDaily / IDS'); final saved = _storage.setScheduleSource(owner, source); _identityForAccount = null; + _identityForSession = null; _identityResolved = false; _graduateIdentity = source == CampusScheduleSource.graduate; _identityLabel = null; @@ -123,6 +128,7 @@ class ScheduleService extends ChangeNotifier { _observedAccount = account; _accountRevision++; _identityForAccount = null; + _identityForSession = null; _identityResolved = false; _graduateIdentity = false; _identityLabel = null; @@ -161,7 +167,7 @@ class ScheduleService extends ChangeNotifier { void requestFetch({bool force = false}) { final account = _campusAccount(); final accountChanged = account != null && account != _fetchedForAccount; - final usable = _semesterInfo != null && _error == null; + final usable = _semesterInfo != null && _error == null && _identityIsCurrent; if (!force && !accountChanged && usable) return; _pendingFetch?.cancel(); @@ -175,7 +181,7 @@ class ScheduleService extends ChangeNotifier { // a round already fetched in this process for this account is the answer. final current = _campusAccount(); final changed = current != null && current != _fetchedForAccount; - if (_fetchedForAccount != null && !changed && _error == null) return; + if (_fetchedForAccount != null && !changed && _error == null && _identityIsCurrent) return; unawaited(fetchAll()); }); } @@ -347,8 +353,8 @@ class ScheduleService extends ChangeNotifier { if (!_hasIdsBinding) return false; if (scheduleSource == CampusScheduleSource.undergraduate) return true; final revision = _accountRevision; - if (!_identityResolved || _loading) await fetchAll(); - return revision == _accountRevision && _identityResolved && !_graduateIdentity; + if (!_identityIsCurrent || _loading) await fetchAll(); + return revision == _accountRevision && _identityIsCurrent && !_graduateIdentity; } Future fetchAll() async { @@ -384,7 +390,7 @@ class ScheduleService extends ChangeNotifier { } finally { _loading = false; if (revision == _accountRevision) { - if (_error == null) _fetchedForAccount = _campusAccount(); + if (_error == null && _identityIsCurrent) _fetchedForAccount = _campusAccount(); } else if (_hasIdsBinding) { requestFetch(force: true); } @@ -394,10 +400,12 @@ class ScheduleService extends ChangeNotifier { } } - Future _graduateClient() async { + Future<({GraduateScheduleClient client, String session})> _graduateClient() async { final cookie = await _tpAuth.sessionTree.freshCookie(_tpAuth.idsNode); if (cookie == null) throw const FormatException('IDS 学校会话暂时不可用,请刷新 IDS 绑定'); - return GraduateScheduleClient(_http, _tpAuth.idsNode.rawFields['tgc'] as String? ?? ''); + final tgc = RegExp(r'(?:^|;)\s*CASTGC=([^;]*)').firstMatch(cookie.cookies)?.group(1) ?? + _tpAuth.idsNode.rawFields['tgc'] as String? ?? ''; + return (client: GraduateScheduleClient(_http, tgc), session: cookie.cookies); } /// Resolve the current IDS principal before touching either academic system. @@ -407,17 +415,22 @@ class ScheduleService extends ChangeNotifier { if (account == null) return false; final revision = _accountRevision; late final client = _graduateClient(); - if (_identityForAccount != account) { - _identityResolved = false; - final source = scheduleSource; - if (source != CampusScheduleSource.automatic) { - _graduateIdentity = source == CampusScheduleSource.graduate; - _identityLabel = _graduateIdentity ? '手动选择研究生课表' : '手动选择本科课表'; - _identityForAccount = account; - } else { - try { - final identity = await (await client).identity(_tpAuth.idsStudentId); - if (revision != _accountRevision) return true; + final source = scheduleSource; + if (source != CampusScheduleSource.automatic) { + _graduateIdentity = source == CampusScheduleSource.graduate; + _identityLabel = _graduateIdentity ? '手动选择研究生课表' : '手动选择本科课表'; + _identityForAccount = account; + _identityForSession = _idsSession; + } else { + var session = _idsSession; + try { + final school = await client; + session = school.session; + if (revision != _accountRevision || session != _idsSession) return true; + if (_identityForAccount != account || !_identityIsCurrent) { + _identityResolved = false; + final identity = await school.client.identity(_tpAuth.idsStudentId); + if (revision != _accountRevision || session != _idsSession) return true; if (identity.kind == CampusStudentKind.unknown) { throw const CampusIdentityConflict('IDS 未返回可识别的本研身份,请手动选择课表来源'); } @@ -425,22 +438,33 @@ class ScheduleService extends ChangeNotifier { _identityLabel = 'IDS:${identity.categoryName}'; _identityWarning = null; _identityForAccount = account; + _identityForSession = session; await _storage.saveCampusIdentity(account, identity); - } catch (error) { - if (revision != _accountRevision) return true; - final cached = _storage.loadCampusIdentity(account); - if (error is CampusIdentityConflict || - cached == null || - cached.kind == CampusStudentKind.unknown) { - throw FormatException('身份识别失败:${_schoolError(error)};可手动选择课表来源'); - } - _graduateIdentity = cached.kind == CampusStudentKind.graduate; - _identityLabel = 'IDS 已缓存身份:${cached.categoryName}'; - _identityWarning = 'IDS 身份暂时无法刷新,沿用此账号已确认的身份'; } + } catch (error) { + if (revision != _accountRevision || session != _idsSession) return true; + _identityResolved = false; + _identityForAccount = null; + if (error is CampusIdentityConflict) { + await _storage.clearCampusIdentity(); + if (revision != _accountRevision || session != _idsSession) return true; + } + final cached = _storage.loadCampusIdentity(account); + if (error is CampusIdentityConflict || + cached == null || + cached.kind == CampusStudentKind.unknown) { + throw FormatException('身份识别失败:${_schoolError(error)};可手动选择课表来源'); + } + _graduateIdentity = cached.kind == CampusStudentKind.graduate; + _identityLabel = 'IDS 已缓存身份:${cached.categoryName}'; + _identityWarning = 'IDS 身份暂时无法刷新,沿用此账号已确认的身份'; + _identityForSession = session; } } - if (revision != _accountRevision) return true; + if (revision != _accountRevision || + (source == CampusScheduleSource.automatic && _identityForSession != _idsSession)) { + return true; + } _identityResolved = true; if (_semesterInfo == null || isGraduate != _graduateIdentity) { _restoreCachedSchedule( @@ -454,20 +478,20 @@ class ScheduleService extends ChangeNotifier { // timetable. Prefer its term labels only when the metadata is available. Map public = const {}; try { - public = await (await client).publicInfo(); + public = await (await client).client.publicInfo(); } catch (error) { - if (revision != _accountRevision) return true; + if (revision != _accountRevision || !_identityIsCurrent) return true; final warning = '学期配置暂时不可用:${_schoolError(error)};按课表中的学期显示'; _identityWarning = [_identityWarning, warning].whereType().join(';'); } - if (revision != _accountRevision) return true; + if (revision != _accountRevision || !_identityIsCurrent) return true; final Map raw; try { - raw = await (await client).timetable(); + raw = await (await client).client.timetable(); } catch (error) { throw FormatException('研究生课表获取失败:${_schoolError(error)}'); } - if (revision != _accountRevision) return true; + if (revision != _accountRevision || !_identityIsCurrent) return true; final current = public['lcxxMap']; final snapshot = GraduateSchedule.fromJson({ ...raw, @@ -488,11 +512,11 @@ class ScheduleService extends ChangeNotifier { _selectedSemesterId = semester; _courseTable = table; await _storage.saveGraduateSchedule(account, snapshot); - if (revision != _accountRevision) return true; + if (revision != _accountRevision || !_identityIsCurrent) return true; await _storage.setSelectedSemester(semester); - if (revision != _accountRevision) return true; + if (revision != _accountRevision || !_identityIsCurrent) return true; await _storage.saveCourseTable(semester, table, owner: account); - if (revision != _accountRevision) return true; + if (revision != _accountRevision || !_identityIsCurrent) return true; await _loadGraduateCalendar(semester); return true; } diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index bddb3cc5..742da009 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -304,6 +304,8 @@ class StorageService { jsonEncode({'owner': owner, ...identity.toJson()}), ); + Future clearCampusIdentity() => _prefs.remove('schedule_campus_identity'); + CampusScheduleSource scheduleSourceFor(String? owner) { final raw = _prefs.getString('schedule_source_preference'); if (raw == null || owner == null) return CampusScheduleSource.automatic; diff --git a/test/graduate_schedule_test.dart b/test/graduate_schedule_test.dart index 606e03f5..95219794 100644 --- a/test/graduate_schedule_test.dart +++ b/test/graduate_schedule_test.dart @@ -883,6 +883,148 @@ void main() { expect(h.storage.graduateScheduleOwner, isNull); }); + test('parent-domain cookies stay within the origin that issued them', () async { + final log = LoggingHttpClient( + DebugLogger(), + inner: MockClient((request) async { + final cookie = request.headers['cookie'] ?? ''; + if (request.url.host == GraduateScheduleClient.idsHost) { + expect(cookie, isNot(contains('graduate-secret'))); + if (request.url.path.endsWith('index.html')) { + return http.Response( + 'IDS', + 200, + headers: { + 'set-cookie': 'SESSION=ids-secret; Domain=shanghaitech.edu.cn; Path=/; Secure', + }, + ); + } + expect(cookie, contains('SESSION=ids-secret')); + return http.Response( + jsonEncode({ + 'code': '0', + 'datas': {'uid': '20260001', 'categoryName': '学生/硕士生'}, + }), + 200, + headers: {'content-type': 'application/json; charset=utf-8'}, + ); + } + expect(cookie, isNot(contains('ids-secret'))); + if (request.url.path.endsWith('loadKbxx.do')) { + expect(cookie, contains('SESSION=graduate-secret')); + return http.Response(jsonEncode(fixture()), 200, + headers: {'content-type': 'application/json; charset=utf-8'},); + } + return http.Response( + 'graduate', + 200, + headers: { + 'set-cookie': 'SESSION=graduate-secret; Domain=shanghaitech.edu.cn; Path=/; Secure', + }, + ); + }), + ); + addTearDown(log.close); + final client = GraduateScheduleClient(log, 'bound'); + await client.identity('20260001'); + await client.timetable(); + await client.identity('20260001'); + }); + + for (final rawTgc in [null, 'stale-raw']) { + test('the authoritative IDS cookie supplies CASTGC when raw tgc is $rawTgc', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + await h.tp.updateRaw(ThirdPartyPlatform.ids, { + 'cookies': 'SESSION=reference; CASTGC=header-session', + if (rawTgc != null) 'tgc': rawTgc, + }); + await h.schedule.fetchAll(); + expect(h.schedule.error, isNull); + expect(h.schedule.isGraduate, isTrue); + final requests = h.requests.where((r) => r.url.host == GraduateScheduleClient.idsHost); + expect(requests, isNotEmpty); + for (final request in requests) { + expect(request.headers['cookie'], contains('CASTGC=header-session')); + expect(request.headers['cookie'], isNot(contains('stale-raw'))); + } + }); + } + + for (final graduate in [false, true]) { + test('a changed IDS session revalidates the principal (graduate=$graduate)', () async { + final h = await harness(graduate: graduate); + addTearDown(h.schedule.dispose); + await h.schedule.fetchAll(); + final previous = h.schedule.courseTable; + h.overrides['getUserConf'] = http.Response( + jsonEncode({'code': '0', 'datas': {'uid': '20260002', 'categoryName': '学生/硕士生'}}), + 200, + headers: {'content-type': 'application/json; charset=utf-8'}, + ); + h.overrides['exam_table'] = http.Response( + jsonEncode({'success': true, 'data': {'exams': []}}), 200, + ); + await h.tp.updateRaw(ThirdPartyPlatform.ids, {'tgc': 'rotated-session'}); + expect(h.schedule.courseTable, same(previous)); + h.requests.clear(); + final assignments = AssignmentService(h.storage, h.httpClient, h.auth, h.tp, h.schedule); + addTearDown(assignments.dispose); + if (graduate) { + await h.schedule.fetchAll(); + } else { + await assignments.fetchPlatform('exam'); + } + expect(h.schedule.error, contains('学号不一致')); + expect(h.requests.where((r) => r.url.path.endsWith('getUserConf')), hasLength(1)); + expect(h.requests.any((r) => r.url.path.endsWith('exam_table')), isFalse); + expect(h.requests.any((r) => r.url.host == GraduateScheduleClient.host), isFalse); + expect(h.storage.loadCampusIdentity(owner), isNull); + h.overrides['getUserConf'] = http.Response('offline', 503); + h.requests.clear(); + await assignments.fetchPlatform('exam'); + expect(h.requests.any((r) => r.url.path.endsWith('exam_table')), isFalse); + }); + } + + test('a renewed IDS session is revalidated before the EAMS exam request', () async { + final h = await harness(graduate: false); + addTearDown(h.schedule.dispose); + await h.tp.updateRaw(ThirdPartyPlatform.ids, {'tgc': 'old-session'}); + await h.schedule.fetchAll(); + h.overrides['getUserConf'] = http.Response( + jsonEncode({'code': '0', 'datas': {'uid': '20260002', 'categoryName': '学生/硕士生'}}), + 200, + headers: {'content-type': 'application/json; charset=utf-8'}, + ); + h.overrides['exam_table'] = http.Response( + jsonEncode({'success': true, 'data': {'exams': []}}), 200, + ); + h.tp.idsNode.seedNextRenewTimestamp(DateTime(2020)); + h.requests.clear(); + final assignments = AssignmentService(h.storage, h.httpClient, h.auth, h.tp, h.schedule); + addTearDown(assignments.dispose); + await assignments.fetchPlatform('exam'); + expect(h.tp.idsNode.rawFields['tgc'], 'tgc-value'); + expect(h.schedule.error, contains('学号不一致')); + expect(h.requests.any((r) => r.url.path.endsWith('exam_table')), isFalse); + }); + + test('a changed IDS session discards an in-flight identity response', () async { + final h = await harness(); + addTearDown(h.schedule.dispose); + h.identityGate = Completer(); + final pending = h.schedule.fetchAll(); + await h.identityEntered.future; + await h.tp.updateRaw(ThirdPartyPlatform.ids, {'tgc': 'rotated-session'}); + h.identityGate!.complete(); + await pending; + expect(h.schedule.courseTable, isNull); + expect(h.storage.loadGraduateSchedule(), isNull); + expect(h.storage.loadCampusIdentity(owner), isNull); + expect(h.requests.any((r) => r.url.host == GraduateScheduleClient.host), isFalse); + }); + test('IDS response cookies rotate within the client and stay off the graduate host', () async { const ids = GraduateScheduleClient.idsHost; const graduate = GraduateScheduleClient.host;