From 9517b8834293a5ff732d07dec94f00dcc174f3c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AshGrey=F0=9F=A5=95?= Date: Sun, 27 Sep 2026 15:47:58 +0800 Subject: [PATCH 01/26] feat(cli): add learning platform course export (#5) Add `learn-courses --semester` to fetch course data and print a YAML summary. Extract the learning platform session handling into the campus package, add course formatting and tests, and document the command. --- README.md | 6 + packages/campus/lib/src/course_schedule.dart | 25 +- packages/campus/lib/src/learn_courses.dart | 120 ++++++++ packages/campus/lib/thulium_campus.dart | 1 + packages/campus/test/learn_courses_test.dart | 160 ++++++++++ packages/cli/bin/thulium.dart | 32 +- packages/cli/lib/learn_course_formatter.dart | 76 +++++ packages/cli/pubspec.lock | 280 ++++++++++++++++++ packages/cli/pubspec.yaml | 1 + .../cli/test/learn_course_formatter_test.dart | 53 ++++ 10 files changed, 728 insertions(+), 26 deletions(-) create mode 100644 packages/campus/lib/src/learn_courses.dart create mode 100644 packages/campus/test/learn_courses_test.dart create mode 100644 packages/cli/lib/learn_course_formatter.dart create mode 100644 packages/cli/test/learn_course_formatter_test.dart diff --git a/README.md b/README.md index cf34b58..d75d8da 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ dart run bin/thulium.dart login --verbose dart run bin/thulium.dart status dart run bin/thulium.dart schedule dart run bin/thulium.dart schedule --refresh +dart run bin/thulium.dart learn-courses --semester 2026-2027-1 dart run bin/thulium.dart logout ``` @@ -62,6 +63,11 @@ copy can be shown if the portal is temporarily unavailable. Manual refresh and `schedule --refresh` request a new copy instead of silently using stale data. Logging out removes the saved calendar. +`learn-courses` fetches the learning platform's course list for the requested +semester and prints an English-keyed YAML view of the useful course fields. +The output contains student-specific information, so avoid redirecting it to a +shared log. + Interactive login attempts can be retried after credential, verification-code, or network errors. Each retry starts a fresh authentication flow. diff --git a/packages/campus/lib/src/course_schedule.dart b/packages/campus/lib/src/course_schedule.dart index 2ec0b68..f0ac1a0 100644 --- a/packages/campus/lib/src/course_schedule.dart +++ b/packages/campus/lib/src/course_schedule.dart @@ -1,6 +1,5 @@ part of '../thulium_campus.dart'; -const _LEARN_ROAMING_ID = '3E401364BDD7AEA7EBF1EDE3F15ED4B7'; const _UNDERGRADUATE_ACADEMIC_CALENDAR_ROAMING_ID = '287C0C6D90ABB364CD5FDF1495199962'; const _GRADUATE_ACADEMIC_CALENDAR_ROAMING_ID = @@ -231,15 +230,7 @@ final class CourseScheduleService { var stage = 'roaming to the learning platform'; try { trace?.call('Calendar stage=$stage'); - final landingPage = await _authClient.roamToPortalApp(_LEARN_ROAMING_ID); - late final String csrf; - try { - _ensurePortalResponse(landingPage.body, landingPage.statusCode); - csrf = _readCsrf(landingPage.body); - } catch (_) { - _authClient.traceUnexpectedResponse('learning-landing', landingPage); - rethrow; - } + final csrf = await LearnPlatformSession(_authClient).open(); stage = 'fetching the current academic term'; trace?.call('Calendar stage=$stage'); final semesterResponse = await _authClient.getAuthenticated( @@ -604,20 +595,6 @@ final class CourseScheduleService { } } - String _readCsrf(String body) { - final match = RegExp( - r"""_csrf=([\w-]+)|name=["']_csrf["'][^>]*value=["']([\w-]+)""", - caseSensitive: false, - ).firstMatch(body); - final token = match?.group(1) ?? match?.group(2); - if (token == null || token.isEmpty) { - throw const FormatException( - 'The campus service did not return a CSRF token.', - ); - } - return token; - } - String _formatDate(DateTime date) => '${date.year.toString().padLeft(4, '0')}' '${date.month.toString().padLeft(2, '0')}' diff --git a/packages/campus/lib/src/learn_courses.dart b/packages/campus/lib/src/learn_courses.dart new file mode 100644 index 0000000..4e4f7e8 --- /dev/null +++ b/packages/campus/lib/src/learn_courses.dart @@ -0,0 +1,120 @@ +part of '../thulium_campus.dart'; + +const _LEARN_ROAMING_ID = '3E401364BDD7AEA7EBF1EDE3F15ED4B7'; +const _LEARN_HOST = 'learn.tsinghua.edu.cn'; +const _LEARN_COURSES_PATH = + '/b/wlxt/kc/v_wlkc_xs_xkb_kcb_extend/student/loadCourseBySemesterId'; + +/// Opens the learning platform through the information-portal roaming flow. +/// +/// The roaming response establishes service-scoped cookies in the shared auth +/// client. Its CSRF token is taken from the returned page or the Learn cookie, +/// never from an unrelated information-portal XSRF-TOKEN cookie. +final class LearnPlatformSession { + const LearnPlatformSession(this._authClient); + + final TsinghuaAuthClient _authClient; + + Future open() async { + final landing = await _authClient.roamToPortalApp(_LEARN_ROAMING_ID); + final body = landing.body; + if (landing.statusCode == 401 || + landing.statusCode == 403 || + body.toLowerCase().contains('sm2publickey')) { + _authClient.traceUnexpectedResponse('learning-landing', landing); + throw const PortalSessionRejected(); + } + if (landing.statusCode < 200 || landing.statusCode >= 300) { + _authClient.traceUnexpectedResponse('learning-landing', landing); + throw StateError( + 'The learning platform returned HTTP ${landing.statusCode}.', + ); + } + + final match = RegExp( + r"""_csrf=([\w-]+)|name=["']_csrf["'][^>]*value=["']([\w-]+)""", + caseSensitive: false, + ).firstMatch(body); + final pageToken = match?.group(1) ?? match?.group(2); + if (pageToken != null && pageToken.isNotEmpty) return pageToken; + + // A successful roaming page can omit the token while setting the cookie. + // Match only the Learn host; the portal uses the same cookie name. + final cookies = _authClient.session?.scopedCookies ?? const []; + for (final cookie in cookies.reversed) { + final domain = cookie.domain.toLowerCase(); + if (cookie.name == 'XSRF-TOKEN' && + (_LEARN_HOST == domain || _LEARN_HOST.endsWith('.$domain')) && + cookie.value.isNotEmpty) { + return cookie.value; + } + } + _authClient.traceUnexpectedResponse('learning-landing', landing); + throw const FormatException( + 'The learning platform did not return a CSRF token.', + ); + } +} + +/// Fetches the learning platform's semester course-list response unchanged. +/// +/// This diagnostic API intentionally retains all response fields for CLI +/// inspection. It does not persist the course list or any credential values. +final class LearnCourseService { + const LearnCourseService(this._authClient, {this.now}); + + final TsinghuaAuthClient _authClient; + final DateTime Function()? now; + + Future> fetchSemester(String semesterId) async { + if (!RegExp(r'^\d{4}-\d{4}-[1-3]$').hasMatch(semesterId)) { + throw ArgumentError.value( + semesterId, + 'semesterId', + 'Invalid semester ID.', + ); + } + final session = _authClient.session; + if (session == null) { + throw StateError('Restore an authenticated session first.'); + } + final csrf = await LearnPlatformSession(_authClient).open(); + final target = + Uri.https(_LEARN_HOST, '$_LEARN_COURSES_PATH/$semesterId/zh', { + 'timestamp': '${(now ?? DateTime.now)().millisecondsSinceEpoch}', + '_csrf': csrf, + }); + final response = await _authClient.getAuthenticated( + TsinghuaWebVpnRedirect.forTarget(target), + ); + if (response.statusCode != 200) { + _authClient.traceUnexpectedResponse('learning-courses', response); + throw StateError( + 'The learning platform returned HTTP ${response.statusCode}.', + ); + } + + Object? decoded; + try { + decoded = jsonDecode(response.body); + } on FormatException { + _authClient.traceUnexpectedResponse('learning-courses', response); + throw const FormatException( + 'The learning platform did not return course-list JSON.', + ); + } + if (decoded is! Map || + decoded['message'] != 'success' || + decoded['resultList'] is! List || + (decoded['resultList'] as List).any((row) => row is! Map)) { + _authClient.traceUnexpectedResponse('learning-courses', response); + throw StateError( + 'The learning platform returned an unexpected course list.', + ); + } + if (decoded['currentUser'] != session.userId) { + throw StateError('The learning platform returned a different account.'); + } + return decoded; + } +} diff --git a/packages/campus/lib/thulium_campus.dart b/packages/campus/lib/thulium_campus.dart index 6388170..3f80645 100644 --- a/packages/campus/lib/thulium_campus.dart +++ b/packages/campus/lib/thulium_campus.dart @@ -8,3 +8,4 @@ import 'package:thulium_auth/thulium_auth.dart'; part 'src/course_schedule.dart'; part 'src/course_schedule_cache.dart'; part 'src/custom_plan.dart'; +part 'src/learn_courses.dart'; diff --git a/packages/campus/test/learn_courses_test.dart b/packages/campus/test/learn_courses_test.dart new file mode 100644 index 0000000..c4f7f36 --- /dev/null +++ b/packages/campus/test/learn_courses_test.dart @@ -0,0 +1,160 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:test/test.dart'; +import 'package:thulium_auth/thulium_auth.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +void main() { + test( + 'fetches the Learn course list through WebVPN with scoped cookies', + () async { + final transport = _LearnHttpClient(); + final store = MemoryAuthSessionStore(); + await store.write(_session); + final auth = TsinghuaAuthClient( + httpClient: transport, + sessionStore: store, + ); + expect(await auth.restore(), isNotNull); + + final response = await LearnCourseService( + auth, + now: () => DateTime.fromMillisecondsSinceEpoch(1790484534941), + ).fetchSemester('2026-2027-1'); + + expect(response['currentUser'], '2024012050'); + expect((response['resultList'] as List).single['kcm'], 'Course A'); + final request = transport.courseRequest!; + expect(request.url.host, TsinghuaWebVpnRedirect.WEBVPN_HOST); + expect( + request.url.path, + startsWith(TsinghuaWebVpnRedirect.LEARNING_PLATFORM_REDIRECT_PATH), + ); + expect(request.url.path, endsWith('/2026-2027-1/zh')); + expect(request.url.queryParameters['timestamp'], '1790484534941'); + expect(request.url.queryParameters['_csrf'], 'learn-csrf'); + final cookies = request.headers['cookie'] ?? ''; + expect(cookies, contains('JSESSIONID=learn-session')); + expect(cookies, contains('XSRF-TOKEN=learn-csrf')); + expect(cookies, contains('!Proxy!PHPSESSID=proxy-php')); + expect(cookies, contains('wengine_vpn_ticket=vpn-ticket')); + expect(cookies, isNot(contains('other-service-session'))); + expect(cookies, isNot(contains('portal-csrf'))); + }, + ); + + test('uses Learn XSRF cookie if landing page omits the CSRF field', () async { + final transport = _LearnHttpClient(omitPageCsrf: true); + final store = MemoryAuthSessionStore(); + await store.write(_session); + final auth = TsinghuaAuthClient(httpClient: transport, sessionStore: store); + await auth.restore(); + + await LearnCourseService(auth).fetchSemester('2026-2027-1'); + + expect(transport.courseRequest!.url.queryParameters['_csrf'], 'learn-csrf'); + }); + + test('rejects unsafe semester paths before making a request', () async { + final transport = _LearnHttpClient(); + final auth = TsinghuaAuthClient(httpClient: transport); + await expectLater( + LearnCourseService(auth).fetchSemester('../login'), + throwsArgumentError, + ); + expect(transport.courseRequest, isNull); + }); + + test('rejects a course list belonging to another account', () async { + final transport = _LearnHttpClient(currentUser: 'another-student'); + final store = MemoryAuthSessionStore(); + await store.write(_session); + final auth = TsinghuaAuthClient(httpClient: transport, sessionStore: store); + await auth.restore(); + + await expectLater( + LearnCourseService(auth).fetchSemester('2026-2027-1'), + throwsA(isA()), + ); + }); +} + +const _session = AuthSession( + userId: '2024012050', + fingerprint: 'test-fingerprint', + cookies: {'wengine_vpn_ticket': 'vpn-ticket'}, + scopedCookies: [ + AuthCookie( + name: 'wengine_vpn_ticket', + value: 'vpn-ticket', + domain: 'webvpn.tsinghua.edu.cn', + path: '/', + hostOnly: true, + secure: true, + ), + AuthCookie( + name: 'JSESSIONID', + value: 'other-service-session', + domain: 'zhjwxk.cic.tsinghua.edu.cn', + path: '/', + hostOnly: true, + secure: false, + ), + ], +); + +final class _LearnHttpClient extends http.BaseClient { + _LearnHttpClient({ + this.omitPageCsrf = false, + this.currentUser = '2024012050', + }); + + final bool omitPageCsrf; + final String currentUser; + http.BaseRequest? courseRequest; + + @override + Future send(http.BaseRequest request) async { + final path = request.url.path; + late final String body; + final headers = { + 'content-type': 'text/html; charset=utf-8', + }; + if (path == '/wengine-vpn/cookie') { + body = 'XSRF-TOKEN=portal-csrf; Path=/;'; + } else if (path.endsWith('onlineAppRedirect')) { + body = jsonEncode({ + 'object': { + 'roamingurl': + 'https://learn.tsinghua.edu.cn/f/wlxt/index/course/student/index', + }, + }); + } else if (path.endsWith('loadCourseBySemesterId/2026-2027-1/zh')) { + courseRequest = request; + body = jsonEncode({ + 'currentUser': currentUser, + 'message': 'success', + 'resultList': [ + {'kcm': 'Course A', 'wlkcid': 'course-id'}, + ], + }); + } else if (path.contains('/f/wlxt/index/course/student/index')) { + body = omitPageCsrf + ? 'Learn' + : '_csrf=learn-csrf'; + headers['set-cookie'] = + 'JSESSIONID=learn-session; Path=/; Secure, ' + 'XSRF-TOKEN=learn-csrf; Path=/; Secure, ' + '!Proxy!PHPSESSID=proxy-php; Path=/; Secure'; + } else { + throw StateError('Unexpected test path: $path'); + } + return http.StreamedResponse( + Stream.value(utf8.encode(body)), + 200, + headers: headers, + request: request, + ); + } +} diff --git a/packages/cli/bin/thulium.dart b/packages/cli/bin/thulium.dart index d3c3b80..c142ad2 100644 --- a/packages/cli/bin/thulium.dart +++ b/packages/cli/bin/thulium.dart @@ -7,6 +7,7 @@ import 'package:thulium_campus/thulium_campus.dart'; import 'package:thulium_auth/thulium_auth.dart'; import 'package:thulium_cli/cli_auth_session_store.dart'; import 'package:thulium_cli/cli_course_schedule_cache_store.dart'; +import 'package:thulium_cli/learn_course_formatter.dart'; // Uppercase snake case is the project convention for named constants. // ignore_for_file: constant_identifier_names @@ -63,13 +64,25 @@ ArgParser _buildParser() { help: 'Fetch the latest calendar instead of using the cache.', ), ); + parser.addCommand( + 'learn-courses', + ArgParser() + ..addOption( + 'semester', + abbr: 's', + help: 'Academic semester ID, for example 2026-2027-1.', + ) + ..addFlag('verbose', help: 'Print safe request diagnostics.'), + ); return parser; } Future _runCommand(ArgResults command) async { final name = command.command?.name; if (name == null) { - stdout.writeln('Usage: thulium '); + stdout.writeln( + 'Usage: thulium ', + ); return; } @@ -122,6 +135,19 @@ Future _runCommand(ArgResults command) async { forceRefresh: command.command!['refresh'] as bool, ); _printSchedule(schedule); + case 'learn-courses': + final session = await client.restore(); + if (session == null) { + throw StateError('Not logged in. Run `thulium login` first.'); + } + final semester = command.command!['semester'] as String?; + if (semester == null || semester.isEmpty) { + throw const FormatException( + 'Provide --semester, for example 2026-2027-1.', + ); + } + final response = await LearnCourseService(client).fetchSemester(semester); + stdout.writeln(formatLearnCourses(response, semester: semester)); } } @@ -325,7 +351,9 @@ Future _revealSessionCookies(AuthSession session) async { } bool _verboseRequested(String commandName, ArgResults command) => - (commandName == 'login' || commandName == 'schedule') && + (commandName == 'login' || + commandName == 'schedule' || + commandName == 'learn-courses') && command['verbose'] as bool; void _printSchedule(CourseSchedule schedule) { diff --git a/packages/cli/lib/learn_course_formatter.dart b/packages/cli/lib/learn_course_formatter.dart new file mode 100644 index 0000000..29e4945 --- /dev/null +++ b/packages/cli/lib/learn_course_formatter.dart @@ -0,0 +1,76 @@ +import 'dart:convert'; + +/// Formats the useful, understood fields of a Learn course list as YAML. +/// +/// The service keeps the complete provider response. This CLI view deliberately +/// omits undocumented counters rather than guessing what their abbreviations +/// mean. JSON-quoted strings are also valid YAML double-quoted scalars, so +/// names containing colons, quotes, or newlines remain safe to print. +String formatLearnCourses( + Map response, { + required String semester, +}) { + final rows = response['resultList']; + if (rows is! List || rows.any((row) => row is! Map)) { + throw const FormatException('The course list is not a list of courses.'); + } + + final output = StringBuffer(); + _writeField(output, 'studentId', response['currentUser']); + _writeField(output, 'semester', semester); + if (rows.isEmpty) return '${output}courses: []'; + + output.writeln('courses:'); + for (final row in rows.cast()) { + final fields = StringBuffer(); + _writeField(fields, 'courseId', row['wlkcid']); + _writeField(fields, 'courseCode', row['kch']); + _writeField(fields, 'sectionNumber', row['kxh'] ?? row['kxhnumber']); + _writeField(fields, 'name', row['kcm'] ?? row['zywkcm']); + if (row['zywkcm'] != row['kcm']) { + _writeField(fields, 'chineseName', row['zywkcm']); + } + _writeField(fields, 'englishName', row['ywkcm']); + _writeField(fields, 'teacherName', row['jsm']); + _writeField(fields, 'teacherId', row['jsh']); + _writeField(fields, 'schedule', row['sjddb']); + _writeField(fields, 'startTime', row['kssj']); + _writeField(fields, 'endTime', row['jssj']); + _writeField(fields, 'credits', row['xf']); + _writeField(fields, 'hours', row['xs']); + _writeField(fields, 'lectureHours', row['lls']); + _writeField(fields, 'studentCount', row['xss']); + _writeField(fields, 'boundStudentCount', row['xsbds']); + _writeField(fields, 'electiveStudentCount', row['xzxss']); + _writeField(fields, 'withdrawnStudentCount', row['tkxss']); + _writeField(fields, 'teachingClassPeriodCount', row['jxbjs']); + _writeField(fields, 'coursePeriodCount', row['jxkjs']); + _writeField(fields, 'teachingMethod', row['jxfs']); + _writeField(fields, 'courseType', row['kclx']); + _writeField(fields, 'examMethod', row['ksfs']); + _writeField(fields, 'referenceBooks', row['cks']); + _writeField(fields, 'courseContent', row['kcnr']); + _writeField(fields, 'remark', row['bz']); + _writeField(fields, 'notes', row['bznr']); + _writeField(fields, 'lastUpdated', row['czsj']); + + final lines = fields.toString().trimRight().split('\n'); + if (lines.length == 1 && lines.single.isEmpty) { + output.writeln(' - {}'); + continue; + } + for (var index = 0; index < lines.length; index++) { + output.writeln('${index == 0 ? ' - ' : ' '}${lines[index]}'); + } + } + return output.toString().trimRight(); +} + +void _writeField(StringBuffer output, String name, Object? value) { + if (value == null || value == '') return; + if (value is String) { + output.writeln('$name: ${jsonEncode(value)}'); + } else if (value is num || value is bool) { + output.writeln('$name: $value'); + } +} diff --git a/packages/cli/pubspec.lock b/packages/cli/pubspec.lock index 5e4e475..0aa0dc7 100644 --- a/packages/cli/pubspec.lock +++ b/packages/cli/pubspec.lock @@ -1,6 +1,22 @@ # Generated by pub # See https://dart.dev/tools/pub/glossary#lockfile packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: fdcd9f70f9eb80df3bc5ed0fa67280df2595fd481948df8a9ab082e6a40ad04b + url: "https://pub.dev" + source: hosted + version: "108.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: a51c769bff3b6dfbe9d60199b8606d808290702a296bef0c26a4ca391d414e46 + url: "https://pub.dev" + source: hosted + version: "14.4.0" args: dependency: "direct main" description: @@ -17,6 +33,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.13.1" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + cli_config: + dependency: transitive + description: + name: cli_config + sha256: ac20a183a07002b700f0c25e61b7ee46b23c309d76ab7b7640a028f18e4d99ec + url: "https://pub.dev" + source: hosted + version: "0.2.0" collection: dependency: transitive description: @@ -25,6 +57,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.1" + convert: + dependency: transitive + description: + name: convert + sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68 + url: "https://pub.dev" + source: hosted + version: "3.1.2" + coverage: + dependency: transitive + description: + name: coverage + sha256: "956a3de0725ca232ad353565a8290d3357592bf4250f6f298a185e2d949c5d3d" + url: "https://pub.dev" + source: hosted + version: "1.15.1" crypto: dependency: transitive description: @@ -65,6 +113,30 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + file: + dependency: transitive + description: + name: file + sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4 + url: "https://pub.dev" + source: hosted + version: "7.0.1" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + url: "https://pub.dev" + source: hosted + version: "4.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: "218aeb56050c714f62a3182775320dfa04602b55074873e24e31bbd39bda96fb" + url: "https://pub.dev" + source: hosted + version: "2.2.0" http: dependency: transitive description: @@ -73,6 +145,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.6.0" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: aa6199f908078bb1c5efb8d8638d4ae191aac11b311132c3ef48ce352fb52ef8 + url: "https://pub.dev" + source: hosted + version: "3.2.2" http_parser: dependency: transitive description: @@ -81,6 +161,14 @@ packages: url: "https://pub.dev" source: hosted version: "4.1.2" + io: + dependency: transitive + description: + name: io + sha256: "2635216ca6a737e60de577ffa1a48a0bec76ca8a62917cfc1bb88c14c570646f" + url: "https://pub.dev" + source: hosted + version: "1.1.0" keybay: dependency: "direct main" description: @@ -97,6 +185,22 @@ packages: url: "https://pub.dev" source: hosted version: "6.1.0" + logging: + dependency: transitive + description: + name: logging + sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61 + url: "https://pub.dev" + source: hosted + version: "1.3.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd" + url: "https://pub.dev" + source: hosted + version: "0.12.20" meta: dependency: transitive description: @@ -105,6 +209,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.19.0" + mime: + dependency: transitive + description: + name: mime + sha256: bd47de35f07e27267e69c8c8b22edf9473bfee170a60d60fcc93730c5144b7f6 + url: "https://pub.dev" + source: hosted + version: "2.1.0" + node_preamble: + dependency: transitive + description: + name: node_preamble + sha256: "6e7eac89047ab8a8d26cf16127b5ed26de65209847630400f9aefd7cd5c730db" + url: "https://pub.dev" + source: hosted + version: "2.0.2" + package_config: + dependency: transitive + description: + name: package_config + sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d + url: "https://pub.dev" + source: hosted + version: "3.0.0" path: dependency: transitive description: @@ -113,6 +241,70 @@ packages: url: "https://pub.dev" source: hosted version: "1.9.1" + pool: + dependency: transitive + description: + name: pool + sha256: "4177f68c237ea2128d1bee66ac17b2ce05ba3dbaafcbdd54c5d40a39d0b6b11c" + url: "https://pub.dev" + source: hosted + version: "1.5.3" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24" + url: "https://pub.dev" + source: hosted + version: "2.2.1" + shelf: + dependency: transitive + description: + name: shelf + sha256: e7dd780a7ffb623c57850b33f43309312fc863fb6aa3d276a754bb299839ef12 + url: "https://pub.dev" + source: hosted + version: "1.4.2" + shelf_packages_handler: + dependency: transitive + description: + name: shelf_packages_handler + sha256: "89f967eca29607c933ba9571d838be31d67f53f6e4ee15147d5dc2934fee1b1e" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + shelf_static: + dependency: transitive + description: + name: shelf_static + sha256: c87c3875f91262785dade62d135760c2c69cb217ac759485334c5857ad89f6e3 + url: "https://pub.dev" + source: hosted + version: "1.1.3" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "3632775c8e90d6c9712f883e633716432a27758216dfb61bd86a8321c0580925" + url: "https://pub.dev" + source: hosted + version: "3.0.0" + source_map_stack_trace: + dependency: transitive + description: + name: source_map_stack_trace + sha256: c0713a43e323c3302c2abe2a1cc89aa057a387101ebd280371d6a6c9fa68516b + url: "https://pub.dev" + source: hosted + version: "2.1.2" + source_maps: + dependency: transitive + description: + name: source_maps + sha256: "14c2945847669b44089bb1222f66873d7ff7103c58911917f2a63c5a62327898" + url: "https://pub.dev" + source: hosted + version: "0.10.14" source_span: dependency: transitive description: @@ -121,6 +313,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.10.2" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490" + url: "https://pub.dev" + source: hosted + version: "1.12.2" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d" + url: "https://pub.dev" + source: hosted + version: "2.1.4" string_scanner: dependency: transitive description: @@ -137,6 +345,30 @@ packages: url: "https://pub.dev" source: hosted version: "1.2.2" + test: + dependency: "direct dev" + description: + name: test + sha256: de5d145b0afff7921e5e788a880f52d7e5f3ae24068a202f6fd3b58e4ba26323 + url: "https://pub.dev" + source: hosted + version: "1.32.0" + test_api: + dependency: transitive + description: + name: test_api + sha256: "0a10344e901e5b2e63819567951cb6a06673ed6b84f40462188ff5a0c41f371f" + url: "https://pub.dev" + source: hosted + version: "0.7.14" + test_core: + dependency: transitive + description: + name: test_core + sha256: "80f3fb49087454e07e7e07c67578cfdd156c8c3a5227d8b3f47c7b2d019c2e93" + url: "https://pub.dev" + source: hosted + version: "0.6.20" thulium_auth: dependency: "direct main" description: @@ -159,6 +391,22 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: "5f37239c4851efcef929cea7824e76df7f2f0970aef85d66bbc430afa40e72f0" + url: "https://pub.dev" + source: hosted + version: "15.3.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "1398c9f081a753f9226febe8900fce8f7d0a67163334e1c94a2438339d79d635" + url: "https://pub.dev" + source: hosted + version: "1.2.1" web: dependency: transitive description: @@ -167,5 +415,37 @@ packages: url: "https://pub.dev" source: hosted version: "1.1.1" + web_socket: + dependency: transitive + description: + name: web_socket + sha256: "34d64019aa8e36bf9842ac014bb5d2f5586ca73df5e4d9bf5c936975cae6982c" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: d645757fb0f4773d602444000a8131ff5d48c9e47adfe9772652dd1a4f2d45c8 + url: "https://pub.dev" + source: hosted + version: "3.0.3" + webkit_inspection_protocol: + dependency: transitive + description: + name: webkit_inspection_protocol + sha256: "87d3f2333bb240704cd3f1c6b5b7acd8a10e7f0bc28c28dcf14e782014f4a572" + url: "https://pub.dev" + source: hosted + version: "1.2.1" + yaml: + dependency: transitive + description: + name: yaml + sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea + url: "https://pub.dev" + source: hosted + version: "3.1.4" sdks: dart: ">=3.12.2 <4.0.0" diff --git a/packages/cli/pubspec.yaml b/packages/cli/pubspec.yaml index ae65c7f..beff50c 100644 --- a/packages/cli/pubspec.yaml +++ b/packages/cli/pubspec.yaml @@ -15,3 +15,4 @@ dependencies: dev_dependencies: lints: ^6.0.0 + test: ^1.26.0 diff --git a/packages/cli/test/learn_course_formatter_test.dart b/packages/cli/test/learn_course_formatter_test.dart new file mode 100644 index 0000000..c31be76 --- /dev/null +++ b/packages/cli/test/learn_course_formatter_test.dart @@ -0,0 +1,53 @@ +import 'package:test/test.dart'; +import 'package:thulium_cli/learn_course_formatter.dart'; + +void main() { + test('prints meaningful English keys and omits unknown counters', () { + final output = formatLearnCourses({ + 'currentUser': '2022012050', + 'resultList': [ + { + 'wlkcid': '2026-2027-1152224984', + 'kch': '00000042', + 'kxh': 90, + 'kcm': 'New Cities', + 'ywkcm': 'A New Science of Cities', + 'jsm': 'Teacher', + 'sjddb': 'Week 1-16, Thursday', + 'xss': 25, + 'xsbds': 22, + 'lls': 20, + 'wpgs': 0, + 'xf': null, + }, + ], + }, semester: '2026-2027-1'); + + expect(output, contains('studentId: "2022012050"')); + expect(output, contains('semester: "2026-2027-1"')); + expect(output, contains(' - courseId: "2026-2027-1152224984"')); + expect(output, contains(' sectionNumber: 90')); + expect(output, contains(' studentCount: 25')); + expect(output, contains(' boundStudentCount: 22')); + expect(output, contains(' lectureHours: 20')); + expect(output, isNot(contains('wpgs'))); + expect(output, isNot(contains('credits:'))); + }); + + test('quotes punctuation and newlines in provider strings', () { + final output = formatLearnCourses({ + 'resultList': [ + {'kcm': 'A: "B"\nC'}, + ], + }, semester: '2026-2027-1'); + + expect(output, contains('name: "A: \\"B\\"\\nC"')); + }); + + test('prints an empty course list as a YAML sequence', () { + expect( + formatLearnCourses({'resultList': []}, semester: '2026-2027-1'), + 'semester: "2026-2027-1"\ncourses: []', + ); + }); +} From ea15e04b9d6642a18208af331c8160363365cfd5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AshGrey=F0=9F=A5=95?= Date: Sun, 27 Sep 2026 19:03:35 +0800 Subject: [PATCH 02/26] feat(cli): reconnect (#5) expired sessions for protected commands Retry schedule and learn-courses requests once after reconnecting with saved credentials, with an interactive sign-in fallback. Detect rejected learning platform sessions and document the recovery flow. --- README.md | 4 + packages/campus/lib/src/learn_courses.dart | 26 ++- packages/campus/test/learn_courses_test.dart | 19 +- packages/cli/bin/thulium.dart | 157 ++++++--------- packages/cli/lib/cli_session_reconnect.dart | 103 ++++++++++ .../cli/test/cli_session_reconnect_test.dart | 189 ++++++++++++++++++ 6 files changed, 394 insertions(+), 104 deletions(-) create mode 100644 packages/cli/lib/cli_session_reconnect.dart create mode 100644 packages/cli/test/cli_session_reconnect_test.dart diff --git a/README.md b/README.md index d75d8da..8e8f1d5 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,10 @@ semester and prints an English-keyed YAML view of the useful course fields. The output contains student-specific information, so avoid redirecting it to a shared log. +When a protected CLI request reports an expired session, the CLI tries the +saved credentials, then offers an interactive sign-in if needed. A successful +reconnection retries the original request once. + Interactive login attempts can be retried after credential, verification-code, or network errors. Each retry starts a fresh authentication flow. diff --git a/packages/campus/lib/src/learn_courses.dart b/packages/campus/lib/src/learn_courses.dart index 4e4f7e8..4ac4728 100644 --- a/packages/campus/lib/src/learn_courses.dart +++ b/packages/campus/lib/src/learn_courses.dart @@ -18,9 +18,11 @@ final class LearnPlatformSession { Future open() async { final landing = await _authClient.roamToPortalApp(_LEARN_ROAMING_ID); final body = landing.body; - if (landing.statusCode == 401 || - landing.statusCode == 403 || - body.toLowerCase().contains('sm2publickey')) { + if (_isLearnSignInResponse( + landing.statusCode, + landing.request?.url, + body, + )) { _authClient.traceUnexpectedResponse('learning-landing', landing); throw const PortalSessionRejected(); } @@ -87,6 +89,14 @@ final class LearnCourseService { final response = await _authClient.getAuthenticated( TsinghuaWebVpnRedirect.forTarget(target), ); + if (_isLearnSignInResponse( + response.statusCode, + response.request?.url, + response.body, + )) { + _authClient.traceUnexpectedResponse('learning-courses', response); + throw const PortalSessionRejected(); + } if (response.statusCode != 200) { _authClient.traceUnexpectedResponse('learning-courses', response); throw StateError( @@ -118,3 +128,13 @@ final class LearnCourseService { return decoded; } } + +bool _isLearnSignInResponse(int statusCode, Uri? uri, String body) { + return statusCode == 401 || + statusCode == 403 || + uri?.host == 'id.tsinghua.edu.cn' || + (uri?.host == TsinghuaWebVpnRedirect.WEBVPN_HOST && + uri?.path == '/login') || + uri?.path.startsWith('/wengine-vpn/failed') == true || + body.toLowerCase().contains('sm2publickey'); +} diff --git a/packages/campus/test/learn_courses_test.dart b/packages/campus/test/learn_courses_test.dart index c4f7f36..9be00ec 100644 --- a/packages/campus/test/learn_courses_test.dart +++ b/packages/campus/test/learn_courses_test.dart @@ -78,6 +78,19 @@ void main() { throwsA(isA()), ); }); + + test('reports an authentication response as a reconnectable error', () async { + final transport = _LearnHttpClient(courseStatusCode: 401); + final store = MemoryAuthSessionStore(); + await store.write(_session); + final auth = TsinghuaAuthClient(httpClient: transport, sessionStore: store); + await auth.restore(); + + await expectLater( + LearnCourseService(auth).fetchSemester('2026-2027-1'), + throwsA(isA()), + ); + }); } const _session = AuthSession( @@ -108,10 +121,12 @@ final class _LearnHttpClient extends http.BaseClient { _LearnHttpClient({ this.omitPageCsrf = false, this.currentUser = '2024012050', + this.courseStatusCode = 200, }); final bool omitPageCsrf; final String currentUser; + final int courseStatusCode; http.BaseRequest? courseRequest; @override @@ -152,7 +167,9 @@ final class _LearnHttpClient extends http.BaseClient { } return http.StreamedResponse( Stream.value(utf8.encode(body)), - 200, + path.endsWith('loadCourseBySemesterId/2026-2027-1/zh') + ? courseStatusCode + : 200, headers: headers, request: request, ); diff --git a/packages/cli/bin/thulium.dart b/packages/cli/bin/thulium.dart index c142ad2..508f8a1 100644 --- a/packages/cli/bin/thulium.dart +++ b/packages/cli/bin/thulium.dart @@ -7,6 +7,7 @@ import 'package:thulium_campus/thulium_campus.dart'; import 'package:thulium_auth/thulium_auth.dart'; import 'package:thulium_cli/cli_auth_session_store.dart'; import 'package:thulium_cli/cli_course_schedule_cache_store.dart'; +import 'package:thulium_cli/cli_session_reconnect.dart'; import 'package:thulium_cli/learn_course_formatter.dart'; // Uppercase snake case is the project convention for named constants. @@ -98,6 +99,26 @@ Future _runCommand(ArgResults command) async { ? (message) => stderr.writeln('[auth] $message') : null, ); + final reconnect = CliSessionReconnect( + credentialStore: store, + signIn: ({required userId, required password, required fingerprint}) async { + await client.login( + userId: userId, + password: password, + fingerprint: fingerprint, + ); + }, + interactive: stdin.hasTerminal, + askToSignIn: (commandName) { + final answer = _readLine( + 'Sign in again to retry $commandName? [Y/n]: ', + ).toLowerCase(); + return answer.isEmpty || answer == 'y' || answer == 'yes'; + }, + readPassword: () => _readSecret('Password: '), + writeMessage: stdout.writeln, + writeError: stderr.writeln, + ); switch (name) { case 'login': @@ -129,7 +150,7 @@ Future _runCommand(ArgResults command) async { stdout.writeln('Loading the current academic calendar...'); final schedule = await _loadScheduleWithReconnect( client, - store, + reconnect, session, cache: calendarCache, forceRefresh: command.command!['refresh'] as bool, @@ -146,119 +167,55 @@ Future _runCommand(ArgResults command) async { 'Provide --semester, for example 2026-2027-1.', ); } - final response = await LearnCourseService(client).fetchSemester(semester); + final response = await reconnect.run( + commandName: 'learn-courses', + savedSession: session, + request: (_) => LearnCourseService(client).fetchSemester(semester), + shouldReconnect: (error) => + error is PortalCsrfUnavailable || error is PortalSessionRejected, + ); stdout.writeln(formatLearnCourses(response, semester: semester)); } } Future _loadScheduleWithReconnect( TsinghuaAuthClient client, - AuthCredentialStore credentialStore, + CliSessionReconnect reconnect, AuthSession savedSession, { required CourseScheduleCache cache, required bool forceRefresh, }) async { - final service = CourseScheduleService( - client, - cache: cache, - trace: (message) { - if (client.trace != null) stderr.writeln('[calendar] $message'); - }, - ); - try { - final schedule = await service.loadCurrentTerm(forceRefresh: forceRefresh); - if (service.lastSource == CourseScheduleSource.freshCache) { - stdout.writeln('Using the saved academic calendar.'); - } else if (service.lastSource == CourseScheduleSource.staleCache) { - stdout.writeln( - 'The update failed; showing an older saved academic calendar.', - ); - } - return schedule; - } on CourseScheduleException catch (error) { - if (error.cause is! PortalCsrfUnavailable) rethrow; - return _reconnectAndRetrySchedule( - client, - credentialStore, - savedSession, - error, - cache, - ); - } on CourseScheduleSessionExpired catch (error) { - return _reconnectAndRetrySchedule( - client, - credentialStore, - savedSession, - error, - cache, - ); - } -} - -Future _reconnectAndRetrySchedule( - TsinghuaAuthClient client, - AuthCredentialStore credentialStore, - AuthSession savedSession, - Object originalError, - CourseScheduleCache cache, -) async { - final credentials = await credentialStore.readCredentials(); - if (credentials != null && credentials.userId == savedSession.userId) { - stdout.writeln('Reconnecting with saved credentials...'); - Object? reconnectError; - try { - await client.login( - userId: credentials.userId, - password: credentials.password, - fingerprint: savedSession.fingerprint, - ); - } catch (error) { - // An expired password or a second-factor prompt can still require an - // interactive retry. Never print the saved password in diagnostics. - reconnectError = error; - } - if (reconnectError == null) { - stdout.writeln('Reconnected. Retrying the academic calendar once...'); - return CourseScheduleService( + CourseScheduleSource? source; + final schedule = await reconnect.run( + commandName: 'schedule', + savedSession: savedSession, + request: (isRetry) async { + final service = CourseScheduleService( client, cache: cache, - ).loadCurrentTerm(forceRefresh: true); - } - stderr.writeln('Automatic reconnection failed: $reconnectError'); - } - - if (!stdin.hasTerminal) { - throw StateError( - 'The saved session could not be reconnected automatically. ' - 'Run `thulium login --force` in an interactive terminal, then retry ' - '`thulium schedule`. Original error: $originalError', + trace: (message) { + if (client.trace != null) stderr.writeln('[calendar] $message'); + }, + ); + final result = await service.loadCurrentTerm( + forceRefresh: forceRefresh || isRetry, + ); + source = service.lastSource; + return result; + }, + shouldReconnect: (error) => + error is CourseScheduleSessionExpired || + (error is CourseScheduleException && + error.cause is PortalCsrfUnavailable), + ); + if (source == CourseScheduleSource.freshCache) { + stdout.writeln('Using the saved academic calendar.'); + } else if (source == CourseScheduleSource.staleCache) { + stdout.writeln( + 'The update failed; showing an older saved academic calendar.', ); } - - stdout.writeln('The saved session could not be reconnected silently.'); - final answer = _readLine( - 'Sign in again to retry the schedule? [Y/n]: ', - ).toLowerCase(); - if (answer.isNotEmpty && answer != 'y' && answer != 'yes') { - throw originalError; - } - final password = _readSecret('Password: '); - if (password.isEmpty) { - throw StateError('A password is required to reconnect.'); - } - - // The account and fingerprint come from the saved session. A successful - // login replaces the separately stored credential with the new password. - await client.login( - userId: savedSession.userId, - password: password, - fingerprint: savedSession.fingerprint, - ); - stdout.writeln('Reconnected. Retrying the academic calendar once...'); - return CourseScheduleService( - client, - cache: cache, - ).loadCurrentTerm(forceRefresh: true); + return schedule; } Future _runSessionCommand( diff --git a/packages/cli/lib/cli_session_reconnect.dart b/packages/cli/lib/cli_session_reconnect.dart new file mode 100644 index 0000000..e0f863f --- /dev/null +++ b/packages/cli/lib/cli_session_reconnect.dart @@ -0,0 +1,103 @@ +import 'package:thulium_auth/thulium_auth.dart'; + +/// Runs an authenticated CLI request and reconnects only for session errors. +/// +/// The caller classifies its own errors, so malformed service data cannot +/// silently trigger a new login. A successful reconnect retries the original +/// request exactly once; a second failure is returned to the caller unchanged. +final class CliSessionReconnect { + const CliSessionReconnect({ + required this.credentialStore, + required this.signIn, + required this.interactive, + required this.askToSignIn, + required this.readPassword, + required this.writeMessage, + required this.writeError, + }); + + final AuthCredentialStore credentialStore; + final Future Function({ + required String userId, + required String password, + required String fingerprint, + }) + signIn; + final bool interactive; + final bool Function(String commandName) askToSignIn; + final String Function() readPassword; + final void Function(String message) writeMessage; + final void Function(String message) writeError; + + Future run({ + required String commandName, + required AuthSession savedSession, + required Future Function(bool isRetry) request, + required bool Function(Object error) shouldReconnect, + }) async { + try { + return await request(false); + } on Object catch (error) { + if (!shouldReconnect(error)) rethrow; + return _reconnectAndRetry( + commandName: commandName, + savedSession: savedSession, + originalError: error, + request: request, + ); + } + } + + Future _reconnectAndRetry({ + required String commandName, + required AuthSession savedSession, + required Object originalError, + required Future Function(bool isRetry) request, + }) async { + final credentials = await credentialStore.readCredentials(); + if (credentials != null && credentials.userId == savedSession.userId) { + writeMessage('Reconnecting with saved credentials...'); + var signedIn = false; + try { + await signIn( + userId: credentials.userId, + password: credentials.password, + fingerprint: savedSession.fingerprint, + ); + signedIn = true; + } on Object catch (error) { + writeError('Automatic reconnection failed: $error'); + } + if (signedIn) { + // A retry failure must propagate without another login or request. + writeMessage('Reconnected. Retrying $commandName once...'); + return request(true); + } + } + + if (!interactive) { + throw StateError( + 'The saved session could not be reconnected automatically. ' + 'Run `thulium login --force` in an interactive terminal, then retry ' + '`thulium $commandName`. Original error: $originalError', + ); + } + + writeMessage('The saved session could not be reconnected silently.'); + if (!askToSignIn(commandName)) throw originalError; + final password = readPassword(); + if (password.isEmpty) { + throw StateError('A password is required to reconnect.'); + } + + // Reuse only this account's fingerprint. The authentication client stores + // the replacement credential after a successful interactive sign-in. + await signIn( + userId: savedSession.userId, + password: password, + fingerprint: savedSession.fingerprint, + ); + writeMessage('Reconnected. Retrying $commandName once...'); + return request(true); + } +} diff --git a/packages/cli/test/cli_session_reconnect_test.dart b/packages/cli/test/cli_session_reconnect_test.dart new file mode 100644 index 0000000..8883041 --- /dev/null +++ b/packages/cli/test/cli_session_reconnect_test.dart @@ -0,0 +1,189 @@ +import 'package:test/test.dart'; +import 'package:thulium_auth/thulium_auth.dart'; +import 'package:thulium_cli/cli_session_reconnect.dart'; + +// Uppercase snake case is the project convention for named constants. +// ignore_for_file: constant_identifier_names + +void main() { + test('reconnects with saved credentials and retries once', () async { + final attempts = []; + var signIns = 0; + final runner = _runner( + credentials: const AuthCredentials( + userId: '2024012050', + password: 'saved-password', + ), + signIn: + ({required userId, required password, required fingerprint}) async { + expect(userId, '2024012050'); + expect(password, 'saved-password'); + expect(fingerprint, 'saved-fingerprint'); + signIns++; + }, + ); + + final result = await runner.run( + commandName: 'learn-courses', + savedSession: _SESSION, + request: (isRetry) async { + attempts.add(isRetry); + if (!isRetry) throw const PortalCsrfUnavailable('missing token'); + return 'course list'; + }, + shouldReconnect: (error) => error is PortalCsrfUnavailable, + ); + + expect(result, 'course list'); + expect(attempts, [false, true]); + expect(signIns, 1); + }); + + test('prompts after saved credentials fail', () async { + final passwords = []; + final runner = _runner( + credentials: const AuthCredentials( + userId: '2024012050', + password: 'expired-password', + ), + interactive: true, + signIn: + ({required userId, required password, required fingerprint}) async { + passwords.add(password); + if (password == 'expired-password') throw StateError('expired'); + }, + ); + + final result = await runner.run( + commandName: 'schedule', + savedSession: _SESSION, + request: (isRetry) async { + if (!isRetry) throw const PortalSessionRejected(); + return 42; + }, + shouldReconnect: (error) => error is PortalSessionRejected, + ); + + expect(result, 42); + expect(passwords, ['expired-password', 'new-password']); + }); + + test('does not reconnect for an unrelated data error', () async { + var signIns = 0; + final runner = _runner( + signIn: + ({required userId, required password, required fingerprint}) async { + signIns++; + }, + ); + + await expectLater( + runner.run( + commandName: 'learn-courses', + savedSession: _SESSION, + request: (_) async => throw const FormatException('bad course data'), + shouldReconnect: (error) => error is PortalCsrfUnavailable, + ), + throwsFormatException, + ); + expect(signIns, 0); + }); + + test('does not sign in again after the one request retry fails', () async { + var signIns = 0; + var requests = 0; + final runner = _runner( + credentials: const AuthCredentials( + userId: '2024012050', + password: 'saved-password', + ), + interactive: true, + signIn: + ({required userId, required password, required fingerprint}) async { + signIns++; + }, + ); + + await expectLater( + runner.run( + commandName: 'learn-courses', + savedSession: _SESSION, + request: (_) async { + requests++; + throw const PortalCsrfUnavailable('still unavailable'); + }, + shouldReconnect: (error) => error is PortalCsrfUnavailable, + ), + throwsA(isA()), + ); + expect(requests, 2); + expect(signIns, 1); + }); + + test('noninteractive recovery gives a login command', () async { + final runner = _runner( + credentials: const AuthCredentials( + userId: 'another-account', + password: 'wrong-account-password', + ), + ); + + await expectLater( + runner.run( + commandName: 'learn-courses', + savedSession: _SESSION, + request: (_) async => throw const PortalCsrfUnavailable('missing'), + shouldReconnect: (error) => error is PortalCsrfUnavailable, + ), + throwsA( + isA().having( + (error) => error.message, + 'message', + contains('thulium login --force'), + ), + ), + ); + }); +} + +const _SESSION = AuthSession( + userId: '2024012050', + fingerprint: 'saved-fingerprint', + cookies: {}, +); + +CliSessionReconnect _runner({ + AuthCredentials? credentials, + bool interactive = false, + Future Function({ + required String userId, + required String password, + required String fingerprint, + })? + signIn, +}) => CliSessionReconnect( + credentialStore: _CredentialStore(credentials), + signIn: + signIn ?? + ({required userId, required password, required fingerprint}) async {}, + interactive: interactive, + askToSignIn: (_) => true, + readPassword: () => 'new-password', + writeMessage: (_) {}, + writeError: (_) {}, +); + +final class _CredentialStore implements AuthCredentialStore { + const _CredentialStore(this.credentials); + + final AuthCredentials? credentials; + + @override + Future readCredentials() async => credentials; + + @override + Future writeCredentials(AuthCredentials credentials) async {} + + @override + Future clearCredentials() async {} +} From de9298494d6b1248b7c7bde37fae77d646b73710 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AshGrey=F0=9F=A5=95?= Date: Mon, 28 Sep 2026 11:23:45 +0800 Subject: [PATCH 03/26] =?UTF-8?q?feat(study):=20add=20course=20(#5)=20cata?= =?UTF-8?q?log=20UI=20for=20desktop=20and=20mobile=20Add=20a=20Study=20sec?= =?UTF-8?q?tion=20with=20course=20listings,=20refresh,=20loading,=20and=20?= =?UTF-8?q?stale-cache=20states.=20Cache=20the=20current=20semester?= =?UTF-8?q?=E2=80=99s=20courses=20for=2024=20hours,=20use=20English=20cour?= =?UTF-8?q?se=20titles=20in=20the=20calendar,=20and=20add=20CLI=20refresh?= =?UTF-8?q?=20support.?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 13 +- lib/app.dart | 6 + lib/auth/secure_learn_course_cache_store.dart | 33 +++ lib/l10n/app_en.arb | 7 + lib/l10n/app_zh.arb | 7 + lib/l10n/app_zh_CN.arb | 7 + lib/l10n/app_zh_TW.arb | 7 + lib/l10n/generated/app_localizations.dart | 42 ++++ lib/l10n/generated/app_localizations_en.dart | 22 ++ lib/l10n/generated/app_localizations_zh.dart | 63 ++++++ lib/pages/calendar_page.dart | 19 +- lib/pages/home_page.dart | 140 ++++++++++++- lib/pages/study_page.dart | 131 ++++++++++++ lib/widgets/calendar_course_block.dart | 9 +- lib/widgets/calendar_plan_details_dialog.dart | 8 +- packages/campus/lib/src/course_schedule.dart | 25 +++ .../campus/lib/src/course_schedule_cache.dart | 6 +- packages/campus/lib/src/custom_plan.dart | 34 ++- .../campus/lib/src/learn_course_cache.dart | 82 ++++++++ .../campus/lib/src/learn_course_catalog.dart | 193 ++++++++++++++++++ packages/campus/lib/src/learn_courses.dart | 4 +- packages/campus/lib/thulium_campus.dart | 2 + .../campus/test/course_schedule_test.dart | 54 +++++ packages/campus/test/custom_plan_test.dart | 63 ++++++ .../test/learn_course_catalog_test.dart | 175 ++++++++++++++++ packages/campus/test/learn_courses_test.dart | 70 ++++++- packages/cli/bin/thulium.dart | 51 ++++- .../cli/lib/cli_learn_course_cache_store.dart | 25 +++ test/calendar_course_block_test.dart | 39 ++++ test/study_page_test.dart | 67 ++++++ test/widget_test.dart | 21 +- 31 files changed, 1399 insertions(+), 26 deletions(-) create mode 100644 lib/auth/secure_learn_course_cache_store.dart create mode 100644 lib/pages/study_page.dart create mode 100644 packages/campus/lib/src/learn_course_cache.dart create mode 100644 packages/campus/lib/src/learn_course_catalog.dart create mode 100644 packages/campus/test/learn_course_catalog_test.dart create mode 100644 packages/cli/lib/cli_learn_course_cache_store.dart create mode 100644 test/study_page_test.dart diff --git a/README.md b/README.md index 8e8f1d5..5208537 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,9 @@ dart run bin/thulium.dart login --verbose dart run bin/thulium.dart status dart run bin/thulium.dart schedule dart run bin/thulium.dart schedule --refresh +dart run bin/thulium.dart learn-courses dart run bin/thulium.dart learn-courses --semester 2026-2027-1 +dart run bin/thulium.dart learn-courses --refresh dart run bin/thulium.dart logout ``` @@ -65,8 +67,15 @@ Logging out removes the saved calendar. `learn-courses` fetches the learning platform's course list for the requested semester and prints an English-keyed YAML view of the useful course fields. -The output contains student-specific information, so avoid redirecting it to a -shared log. +Without `--semester`, it selects the semester from the local date: autumn +starts September 15, spring starts February 15, and summer starts July 15. +The app and CLI keep the selected account's current semester course list for +24 hours, with an older copy available if an update fails. Switching semesters +replaces this single snapshot. `--refresh` bypasses the +fresh cache. Study shows these courses, and the teaching calendar uses their +English titles for matching lessons when the app language is English. Custom +plans keep their original names. The output contains student-specific +information, so avoid redirecting it to a shared log. When a protected CLI request reports an expired session, the CLI tries the saved credentials, then offers an interactive sign-in if needed. A successful diff --git a/lib/app.dart b/lib/app.dart index 67205a1..3619ab8 100644 --- a/lib/app.dart +++ b/lib/app.dart @@ -5,6 +5,7 @@ import 'package:thulium_auth/thulium_auth.dart'; import 'auth/secure_auth_session_store.dart'; import 'auth/secure_course_schedule_cache_store.dart'; +import 'auth/secure_learn_course_cache_store.dart'; import 'pages/home_page.dart'; import 'pages/welcome_page.dart'; @@ -87,6 +88,11 @@ final class _ThuliumAppState extends State { } catch (error) { debugPrint('Thulium calendar cache removal failed: $error'); } + try { + await SecureLearnCourseCacheStore().clear(); + } catch (error) { + debugPrint('Thulium course cache removal failed: $error'); + } } if (mounted) setState(() => _hasSession = false); diff --git a/lib/auth/secure_learn_course_cache_store.dart b/lib/auth/secure_learn_course_cache_store.dart new file mode 100644 index 0000000..bcf10fd --- /dev/null +++ b/lib/auth/secure_learn_course_cache_store.dart @@ -0,0 +1,33 @@ +// ignore_for_file: constant_identifier_names + +import 'package:flutter/foundation.dart' + show defaultTargetPlatform, TargetPlatform; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +const _LEARN_COURSE_CACHE_KEY = 'thulium.learn.courses.cache.v1'; + +/// Protects the compact Learn catalog independently from sign-in credentials. +final class SecureLearnCourseCacheStore implements LearnCourseCacheStore { + SecureLearnCourseCacheStore({FlutterSecureStorage? storage}) + : _storage = storage ?? _createStorage(); + + final FlutterSecureStorage _storage; + + static FlutterSecureStorage _createStorage() => + defaultTargetPlatform == TargetPlatform.macOS + ? const FlutterSecureStorage( + mOptions: MacOsOptions(usesDataProtectionKeychain: false), + ) + : const FlutterSecureStorage(); + + @override + Future read() => _storage.read(key: _LEARN_COURSE_CACHE_KEY); + + @override + Future write(String value) => + _storage.write(key: _LEARN_COURSE_CACHE_KEY, value: value); + + @override + Future clear() => _storage.delete(key: _LEARN_COURSE_CACHE_KEY); +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 02e7030..ae3cdad 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -131,6 +131,13 @@ "planCancelAction": "Cancel once", "studyTitle": "Study", "studyDescription": "Study tools and learning resources will appear here.", + "studyToolsTitle": "Study shortcuts", + "studyToolsPlaceholder": "Study shortcuts will appear here.", + "studyCoursesTitle": "My courses", + "studyRefresh": "Refresh courses", + "studyLoadError": "Could not load courses. Try refreshing.", + "studyStaleCourses": "Showing saved courses because the update failed.", + "studyNoCourses": "No courses were found for this semester.", "lifeTitle": "Life", "lifeDescription": "Campus life services and everyday tools will appear here." } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 1831e39..208137c 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -131,6 +131,13 @@ "planCancelAction": "取消本次", "studyTitle": "学习", "studyDescription": "学习工具和学习资源将在这里显示。", + "studyToolsTitle": "学习快捷入口", + "studyToolsPlaceholder": "这里将显示常用学习功能。", + "studyCoursesTitle": "我的课程", + "studyRefresh": "刷新课程", + "studyLoadError": "无法加载课程,请尝试刷新。", + "studyStaleCourses": "更新失败,正在显示已保存的课程。", + "studyNoCourses": "本学期暂无课程。", "lifeTitle": "生活", "lifeDescription": "校园生活服务和日常工具将在这里显示。" } diff --git a/lib/l10n/app_zh_CN.arb b/lib/l10n/app_zh_CN.arb index 22daff5..62a1bfa 100644 --- a/lib/l10n/app_zh_CN.arb +++ b/lib/l10n/app_zh_CN.arb @@ -131,6 +131,13 @@ "planCancelAction": "取消本次", "studyTitle": "学习", "studyDescription": "学习工具和学习资源将在这里显示。", + "studyToolsTitle": "学习快捷入口", + "studyToolsPlaceholder": "这里将显示常用学习功能。", + "studyCoursesTitle": "我的课程", + "studyRefresh": "刷新课程", + "studyLoadError": "无法加载课程,请尝试刷新。", + "studyStaleCourses": "更新失败,正在显示已保存的课程。", + "studyNoCourses": "本学期暂无课程。", "lifeTitle": "生活", "lifeDescription": "校园生活服务和日常工具将在这里显示。" } diff --git a/lib/l10n/app_zh_TW.arb b/lib/l10n/app_zh_TW.arb index b9a3b6e..94f5181 100644 --- a/lib/l10n/app_zh_TW.arb +++ b/lib/l10n/app_zh_TW.arb @@ -131,6 +131,13 @@ "planCancelAction": "取消本次", "studyTitle": "學習", "studyDescription": "學習工具和學習資源將在這裡顯示。", + "studyToolsTitle": "學習快速入口", + "studyToolsPlaceholder": "這裡將顯示常用學習功能。", + "studyCoursesTitle": "我的課程", + "studyRefresh": "重新整理課程", + "studyLoadError": "無法載入課程,請嘗試重新整理。", + "studyStaleCourses": "更新失敗,正在顯示已儲存的課程。", + "studyNoCourses": "本學期暫無課程。", "lifeTitle": "生活", "lifeDescription": "校園生活服務和日常工具將在這裡顯示。" } diff --git a/lib/l10n/generated/app_localizations.dart b/lib/l10n/generated/app_localizations.dart index 5e94b7d..542c95b 100644 --- a/lib/l10n/generated/app_localizations.dart +++ b/lib/l10n/generated/app_localizations.dart @@ -832,6 +832,48 @@ abstract class AppLocalizations { /// **'Study tools and learning resources will appear here.'** String get studyDescription; + /// No description provided for @studyToolsTitle. + /// + /// In en, this message translates to: + /// **'Study shortcuts'** + String get studyToolsTitle; + + /// No description provided for @studyToolsPlaceholder. + /// + /// In en, this message translates to: + /// **'Study shortcuts will appear here.'** + String get studyToolsPlaceholder; + + /// No description provided for @studyCoursesTitle. + /// + /// In en, this message translates to: + /// **'My courses'** + String get studyCoursesTitle; + + /// No description provided for @studyRefresh. + /// + /// In en, this message translates to: + /// **'Refresh courses'** + String get studyRefresh; + + /// No description provided for @studyLoadError. + /// + /// In en, this message translates to: + /// **'Could not load courses. Try refreshing.'** + String get studyLoadError; + + /// No description provided for @studyStaleCourses. + /// + /// In en, this message translates to: + /// **'Showing saved courses because the update failed.'** + String get studyStaleCourses; + + /// No description provided for @studyNoCourses. + /// + /// In en, this message translates to: + /// **'No courses were found for this semester.'** + String get studyNoCourses; + /// No description provided for @lifeTitle. /// /// In en, this message translates to: diff --git a/lib/l10n/generated/app_localizations_en.dart b/lib/l10n/generated/app_localizations_en.dart index 519ba6b..e3a2323 100644 --- a/lib/l10n/generated/app_localizations_en.dart +++ b/lib/l10n/generated/app_localizations_en.dart @@ -397,6 +397,28 @@ class AppLocalizationsEn extends AppLocalizations { String get studyDescription => 'Study tools and learning resources will appear here.'; + @override + String get studyToolsTitle => 'Study shortcuts'; + + @override + String get studyToolsPlaceholder => 'Study shortcuts will appear here.'; + + @override + String get studyCoursesTitle => 'My courses'; + + @override + String get studyRefresh => 'Refresh courses'; + + @override + String get studyLoadError => 'Could not load courses. Try refreshing.'; + + @override + String get studyStaleCourses => + 'Showing saved courses because the update failed.'; + + @override + String get studyNoCourses => 'No courses were found for this semester.'; + @override String get lifeTitle => 'Life'; diff --git a/lib/l10n/generated/app_localizations_zh.dart b/lib/l10n/generated/app_localizations_zh.dart index 88a5e6d..9488499 100644 --- a/lib/l10n/generated/app_localizations_zh.dart +++ b/lib/l10n/generated/app_localizations_zh.dart @@ -381,6 +381,27 @@ class AppLocalizationsZh extends AppLocalizations { @override String get studyDescription => '学习工具和学习资源将在这里显示。'; + @override + String get studyToolsTitle => '学习快捷入口'; + + @override + String get studyToolsPlaceholder => '这里将显示常用学习功能。'; + + @override + String get studyCoursesTitle => '我的课程'; + + @override + String get studyRefresh => '刷新课程'; + + @override + String get studyLoadError => '无法加载课程,请尝试刷新。'; + + @override + String get studyStaleCourses => '更新失败,正在显示已保存的课程。'; + + @override + String get studyNoCourses => '本学期暂无课程。'; + @override String get lifeTitle => '生活'; @@ -765,6 +786,27 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { @override String get studyDescription => '学习工具和学习资源将在这里显示。'; + @override + String get studyToolsTitle => '学习快捷入口'; + + @override + String get studyToolsPlaceholder => '这里将显示常用学习功能。'; + + @override + String get studyCoursesTitle => '我的课程'; + + @override + String get studyRefresh => '刷新课程'; + + @override + String get studyLoadError => '无法加载课程,请尝试刷新。'; + + @override + String get studyStaleCourses => '更新失败,正在显示已保存的课程。'; + + @override + String get studyNoCourses => '本学期暂无课程。'; + @override String get lifeTitle => '生活'; @@ -1149,6 +1191,27 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { @override String get studyDescription => '學習工具和學習資源將在這裡顯示。'; + @override + String get studyToolsTitle => '學習快速入口'; + + @override + String get studyToolsPlaceholder => '這裡將顯示常用學習功能。'; + + @override + String get studyCoursesTitle => '我的課程'; + + @override + String get studyRefresh => '重新整理課程'; + + @override + String get studyLoadError => '無法載入課程,請嘗試重新整理。'; + + @override + String get studyStaleCourses => '更新失敗,正在顯示已儲存的課程。'; + + @override + String get studyNoCourses => '本學期暫無課程。'; + @override String get lifeTitle => '生活'; diff --git a/lib/pages/calendar_page.dart b/lib/pages/calendar_page.dart index c5a7a5e..a2bf9b1 100644 --- a/lib/pages/calendar_page.dart +++ b/lib/pages/calendar_page.dart @@ -39,11 +39,13 @@ final class AcademicCalendarPage extends StatefulWidget { const AcademicCalendarPage({ required this.onSessionExpired, this.sessionStore, + this.courseCatalog, super.key, }); final VoidCallback onSessionExpired; final AuthSessionStore? sessionStore; + final LearnCourseCatalog? courseCatalog; @override State createState() => _AcademicCalendarPageState(); @@ -95,6 +97,18 @@ final class _AcademicCalendarPageState extends State if (state == AppLifecycleState.resumed) _now.value = DateTime.now(); } + @override + void didUpdateWidget(covariant AcademicCalendarPage oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.courseCatalog == widget.courseCatalog || _schedule == null) { + return; + } + final catalog = widget.courseCatalog; + if (catalog != null && catalog.semester == _schedule!.term.id) { + setState(() => _schedule = catalog.applyEnglishNames(_schedule!)); + } + } + @override void dispose() { _nowTimer?.cancel(); @@ -161,7 +175,10 @@ final class _AcademicCalendarPageState extends State ); final todayWeek = schedule.term.weekFor(DateTime.now()); setState(() { - _schedule = schedule; + final catalog = widget.courseCatalog; + _schedule = catalog != null && catalog.semester == schedule.term.id + ? catalog.applyEnglishNames(schedule) + : schedule; _customPlans = customPlans; _userId = savedSession.userId; _showingStaleCache = diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 4d607a5..d73555a 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -1,13 +1,19 @@ // ignore_for_file: constant_identifier_names +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:forui/forui.dart'; import 'package:thulium/l10n/generated/app_localizations.dart'; import 'package:thulium_auth/thulium_auth.dart'; +import 'package:thulium_campus/thulium_campus.dart'; +import '../auth/secure_auth_session_store.dart'; +import '../auth/secure_learn_course_cache_store.dart'; import '../widgets/language_button.dart'; import 'settings_page.dart'; import 'calendar_page.dart'; +import 'study_page.dart'; /// The authenticated application shell with the primary navigation sections. final class HomePage extends StatefulWidget { @@ -30,13 +36,128 @@ final class HomePage extends StatefulWidget { State createState() => _HomePageState(); } -final class _HomePageState extends State { +final class _HomePageState extends State with WidgetsBindingObserver { static const _HEADER_ICON_SIZE = 40.0; static const _HEADER_TOP = 4.0; static const _CALENDAR_TOP = _HEADER_TOP + _HEADER_ICON_SIZE + 4.0; + static const _LOAD_TIMEOUT = Duration(minutes: 2); int _selectedIndex = 0; bool _hasOpenedPlans = false; + late String _semester; + LearnCourseCatalog? _courseCatalog; + Object? _courseError; + bool _coursesLoading = true; + bool _coursesStale = false; + int _courseRequestGeneration = 0; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _semester = AcademicSemester.forDate(DateTime.now()); + // Start in the background on entering the authenticated shell so calendar + // translations can become available before the Study tab is opened. + unawaited(_loadCourses()); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) unawaited(_loadCourses()); + } + + @override + void dispose() { + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + Future _loadCourses({bool forceRefresh = false}) async { + final semester = AcademicSemester.forDate(DateTime.now()); + if (_courseRequestGeneration > 0 && + _coursesLoading && + !forceRefresh && + semester == _semester) { + return; + } + final generation = ++_courseRequestGeneration; + setState(() { + if (semester != _semester) _coursesStale = false; + _semester = semester; + _coursesLoading = true; + _courseError = null; + }); + try { + final store = widget.sessionStore ?? SecureAuthSessionStore(); + final credentials = store is AuthCredentialStore + ? store as AuthCredentialStore + : null; + final client = TsinghuaAuthClient( + sessionStore: store, + credentialStore: credentials, + trace: (message) => debugPrint('[auth] $message'), + ); + final session = await client.restore(); + if (session == null) throw const PortalSessionRejected(); + final service = LearnCourseCatalogService( + client, + cache: widget.sessionStore == null + ? LearnCourseCache(SecureLearnCourseCacheStore()) + : null, + ); + LearnCourseCatalog catalog; + try { + catalog = await service + .loadSemester(semester, forceRefresh: forceRefresh) + .timeout(_LOAD_TIMEOUT); + } on PortalCsrfUnavailable { + if (!await _reconnectCourses(client, credentials, session)) rethrow; + catalog = await service + .loadSemester(semester, forceRefresh: true) + .timeout(_LOAD_TIMEOUT); + } on PortalSessionRejected { + if (!await _reconnectCourses(client, credentials, session)) rethrow; + catalog = await service + .loadSemester(semester, forceRefresh: true) + .timeout(_LOAD_TIMEOUT); + } + if (!mounted || generation != _courseRequestGeneration) return; + setState(() { + _courseCatalog = catalog; + _coursesStale = service.lastSource == LearnCourseSource.staleCache; + _coursesLoading = false; + }); + } on TwoFactorInteractionRequired { + if (mounted) widget.onSessionExpired(); + } catch (error) { + debugPrint('[study] course loading failed type=${error.runtimeType}'); + if (!mounted || generation != _courseRequestGeneration) return; + setState(() { + _courseError = error; + _coursesStale = _courseCatalog?.semester == semester; + _coursesLoading = false; + }); + } + } + + Future _reconnectCourses( + TsinghuaAuthClient client, + AuthCredentialStore? store, + AuthSession session, + ) async { + final credentials = await store?.readCredentials(); + if (credentials == null || credentials.userId != session.userId) { + return false; + } + await client + .login( + userId: session.userId, + password: credentials.password, + fingerprint: session.fingerprint, + ) + .timeout(_LOAD_TIMEOUT); + return true; + } @override Widget build(BuildContext context) { @@ -78,7 +199,7 @@ final class _HomePageState extends State { bottom: false, child: Stack( children: [ - if (_selectedIndex != 1) + if (_selectedIndex != 1 && _selectedIndex != 2) Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 640), @@ -112,10 +233,25 @@ final class _HomePageState extends State { child: AcademicCalendarPage( sessionStore: widget.sessionStore, onSessionExpired: widget.onSessionExpired, + courseCatalog: _courseCatalog, ), ), ), ), + if (_selectedIndex == 2) + Positioned.fill( + top: _CALENDAR_TOP, + child: StudyPage( + semester: _semester, + catalog: _courseCatalog?.semester == _semester + ? _courseCatalog + : null, + isLoading: _coursesLoading, + isStale: _coursesStale, + error: _courseError, + onRefresh: () => unawaited(_loadCourses(forceRefresh: true)), + ), + ), Positioned( top: _HEADER_TOP, left: 8, diff --git a/lib/pages/study_page.dart b/lib/pages/study_page.dart new file mode 100644 index 0000000..6e71cb6 --- /dev/null +++ b/lib/pages/study_page.dart @@ -0,0 +1,131 @@ +import 'package:flutter/material.dart'; +import 'package:forui/forui.dart'; +import 'package:thulium/l10n/generated/app_localizations.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +/// Keeps room for future study shortcuts above the Learn course list. +final class StudyPage extends StatelessWidget { + const StudyPage({ + required this.semester, + required this.catalog, + required this.isLoading, + required this.isStale, + required this.error, + required this.onRefresh, + super.key, + }); + + final String semester; + final LearnCourseCatalog? catalog; + final bool isLoading; + final bool isStale; + final Object? error; + final VoidCallback onRefresh; + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final colors = context.theme.colors; + final locale = Localizations.localeOf(context).languageCode; + return ListView( + padding: const EdgeInsets.fromLTRB(16, 12, 16, 24), + children: [ + Text(l10n.studyToolsTitle, style: context.theme.typography.lg), + const SizedBox(height: 10), + Container( + key: const ValueKey('study-shortcut-reserved'), + height: 92, + alignment: Alignment.center, + decoration: BoxDecoration( + border: Border.all(color: colors.border), + borderRadius: BorderRadius.circular(12), + ), + child: Text( + l10n.studyToolsPlaceholder, + style: context.theme.typography.sm.copyWith( + color: colors.mutedForeground, + ), + ), + ), + const SizedBox(height: 24), + Row( + children: [ + Expanded( + child: Text( + l10n.studyCoursesTitle, + style: context.theme.typography.lg, + ), + ), + Tooltip( + message: l10n.studyRefresh, + child: FButton.icon( + variant: FButtonVariant.ghost, + onPress: isLoading ? null : onRefresh, + child: const Icon(Icons.refresh), + ), + ), + ], + ), + Text(semester, style: context.theme.typography.sm), + if (isStale) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(l10n.studyStaleCourses), + ), + if (isLoading && catalog == null) + const Padding( + padding: EdgeInsets.all(32), + child: Center(child: FCircularProgress()), + ) + else if (error != null && catalog == null) + Padding( + padding: const EdgeInsets.only(top: 20), + child: Text(l10n.studyLoadError), + ) + else if (catalog?.courses.isEmpty ?? false) + Padding( + padding: const EdgeInsets.only(top: 20), + child: Text(l10n.studyNoCourses), + ), + for (final course in catalog?.courses ?? []) + Padding( + padding: const EdgeInsets.only(top: 12), + child: DecoratedBox( + decoration: BoxDecoration( + color: colors.secondary.withValues(alpha: 0.18), + border: Border.all(color: colors.border), + borderRadius: BorderRadius.circular(12), + ), + child: Padding( + padding: const EdgeInsets.all(14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + locale == 'en' && course.englishName.isNotEmpty + ? course.englishName + : course.name, + style: context.theme.typography.md, + ), + if (course.teacherName.isNotEmpty || + course.schedule.isNotEmpty) ...[ + const SizedBox(height: 6), + Text( + [ + if (course.teacherName.isNotEmpty) course.teacherName, + if (course.schedule.isNotEmpty) course.schedule, + ].join(' · '), + style: context.theme.typography.sm.copyWith( + color: colors.mutedForeground, + ), + ), + ], + ], + ), + ), + ), + ), + ], + ); + } +} diff --git a/lib/widgets/calendar_course_block.dart b/lib/widgets/calendar_course_block.dart index b940560..d111c9c 100644 --- a/lib/widgets/calendar_course_block.dart +++ b/lib/widgets/calendar_course_block.dart @@ -39,9 +39,12 @@ final class _CalendarCourseBlockState extends State { final colors = context.theme.colors; final surfaceColor = widget.categoryColor ?? colors.primary; final reducedMotion = MediaQuery.disableAnimationsOf(context); + final displayName = widget.course.nameForLanguage( + Localizations.localeOf(context).languageCode, + ); return Semantics( - label: '${widget.course.name}, ${widget.course.location}', + label: '$displayName, ${widget.course.location}', child: SizedBox( key: const ValueKey('calendar-course-surface'), width: widget.width, @@ -164,7 +167,9 @@ final class _CalendarCourseBlockState extends State { crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( - widget.course.name, + widget.course.nameForLanguage( + Localizations.localeOf(context).languageCode, + ), maxLines: 1, softWrap: false, overflow: TextOverflow.ellipsis, diff --git a/lib/widgets/calendar_plan_details_dialog.dart b/lib/widgets/calendar_plan_details_dialog.dart index e6fea21..5f33dad 100644 --- a/lib/widgets/calendar_plan_details_dialog.dart +++ b/lib/widgets/calendar_plan_details_dialog.dart @@ -66,7 +66,13 @@ Future showCalendarPlanDetailsDialog( ], ), const SizedBox(height: 16), - _detail(context, l10n.planName, occurrence.name), + _detail( + context, + l10n.planName, + occurrence.nameForLanguage( + Localizations.localeOf(context).languageCode, + ), + ), _detail(context, l10n.planLocation, occurrence.location), _detail( context, diff --git a/packages/campus/lib/src/course_schedule.dart b/packages/campus/lib/src/course_schedule.dart index f0ac1a0..887b604 100644 --- a/packages/campus/lib/src/course_schedule.dart +++ b/packages/campus/lib/src/course_schedule.dart @@ -69,6 +69,7 @@ final class CourseOccurrence { required this.startsAt, required this.endsAt, required this.category, + this.coursesPlanEnglishName = '', }); final String name; @@ -76,6 +77,27 @@ final class CourseOccurrence { final DateTime startsAt; final DateTime endsAt; final String category; + + /// An optional Learn title for fetched lessons; user plans leave it empty. + final String coursesPlanEnglishName; + + String nameForLanguage(String languageCode) => + category == PlanCategories.LESSON && + languageCode == 'en' && + coursesPlanEnglishName.isNotEmpty + ? coursesPlanEnglishName + : name; + + CourseOccurrence copyWith({String? coursesPlanEnglishName}) => + CourseOccurrence( + name: name, + location: location, + startsAt: startsAt, + endsAt: endsAt, + category: category, + coursesPlanEnglishName: + coursesPlanEnglishName ?? this.coursesPlanEnglishName, + ); } /// A term and its combined actual-date course occurrences. @@ -126,6 +148,9 @@ final class CourseSchedule { startsAt: current.startsAt, endsAt: next.endsAt, category: current.category, + coursesPlanEnglishName: current.coursesPlanEnglishName.isNotEmpty + ? current.coursesPlanEnglishName + : next.coursesPlanEnglishName, ); } else { merged.add(current); diff --git a/packages/campus/lib/src/course_schedule_cache.dart b/packages/campus/lib/src/course_schedule_cache.dart index d848fae..42a6cb2 100644 --- a/packages/campus/lib/src/course_schedule_cache.dart +++ b/packages/campus/lib/src/course_schedule_cache.dart @@ -1,6 +1,6 @@ part of '../thulium_campus.dart'; -const _SCHEDULE_CACHE_VERSION = 2; +const _SCHEDULE_CACHE_VERSION = 3; const _MAX_CACHE_LENGTH = 1024 * 1024; /// A platform-specific store for one compressed, account-scoped timetable. @@ -53,6 +53,7 @@ final class CourseScheduleCache { final data = jsonDecode(utf8.decode(bytes)); if (data is! Map || (data['version'] != 1 && + data['version'] != 2 && data['version'] != _SCHEDULE_CACHE_VERSION) || data['userId'] != userId) { return null; @@ -78,6 +79,8 @@ final class CourseScheduleCache { final row = entry as Map; return CourseOccurrence( name: row['name'] as String, + coursesPlanEnglishName: + row['coursesPlanEnglishName'] as String? ?? '', location: row['location'] as String, // Version 1 predates categories and only stored lessons. category: data['version'] == 1 @@ -117,6 +120,7 @@ final class CourseScheduleCache { for (final row in schedule.occurrences) { 'name': row.name, + 'coursesPlanEnglishName': row.coursesPlanEnglishName, 'location': row.location, 'category': row.category, 'startsAt': row.startsAt.toIso8601String(), diff --git a/packages/campus/lib/src/custom_plan.dart b/packages/campus/lib/src/custom_plan.dart index daacc21..27a2d50 100644 --- a/packages/campus/lib/src/custom_plan.dart +++ b/packages/campus/lib/src/custom_plan.dart @@ -264,6 +264,27 @@ final class CustomPlanCollection { }; final entries = []; final rulesById = {for (final rule in plans) rule.id: rule}; + final fetchedByKey = { + for (final lesson in fetchedLessons) + (fetchedLessonSourceId(lesson), lesson.startsAt): lesson, + }; + + CourseOccurrence visibleReplacement( + CourseOccurrence replacement, + CourseOccurrence? original, + ) { + // A local edit of a fetched lesson should keep its translated title + // only while the Chinese title and lesson category remain unchanged. + // Resolve it from the current catalog-backed lesson, not the saved edit. + if (original == null || + replacement.name != original.name || + replacement.category != PlanCategories.LESSON) { + return replacement; + } + return replacement.copyWith( + coursesPlanEnglishName: original.coursesPlanEnglishName, + ); + } void addOriginal( CourseOccurrence occurrence, @@ -273,7 +294,11 @@ final class CustomPlanCollection { ) { final override = changes[(sourceId, occurrence.startsAt)]; if (override != null && override.replacement == null) return; - final visible = override?.replacement ?? occurrence; + final visible = override?.replacement == null + ? occurrence + : fetchedLesson + ? visibleReplacement(override!.replacement!, occurrence) + : override!.replacement!; if (!visible.startsAt.isBefore(start) && visible.startsAt.isBefore(end)) { entries.add( CalendarPlanEntry( @@ -309,7 +334,12 @@ final class CustomPlanCollection { final rule = rulesById[override.sourceId]; entries.add( CalendarPlanEntry( - occurrence: replacement, + occurrence: rule == null + ? visibleReplacement( + replacement, + fetchedByKey[(override.sourceId, override.originalStartsAt)], + ) + : replacement, sourceId: override.sourceId, originalStartsAt: override.originalStartsAt, fetchedLesson: rule == null, diff --git a/packages/campus/lib/src/learn_course_cache.dart b/packages/campus/lib/src/learn_course_cache.dart new file mode 100644 index 0000000..3d36426 --- /dev/null +++ b/packages/campus/lib/src/learn_course_cache.dart @@ -0,0 +1,82 @@ +part of '../thulium_campus.dart'; + +const _LEARN_CACHE_VERSION = 1; +const _LEARN_CACHE_MAX_LENGTH = 1024 * 1024; + +/// A platform-specific protected store for one account's semester catalog. +abstract interface class LearnCourseCacheStore { + Future read(); + Future write(String value); + Future clear(); +} + +final class CachedLearnCourses { + const CachedLearnCourses({required this.catalog, required this.fetchedAt}); + + final LearnCourseCatalog catalog; + final DateTime fetchedAt; + + bool isFresh(DateTime now, Duration maxAge) { + final age = now.difference(fetchedAt); + return !age.isNegative && age < maxAge; + } +} + +/// Stores the compressed catalog and CLI response, never auth credentials. +final class LearnCourseCache { + const LearnCourseCache(this._store); + + final LearnCourseCacheStore _store; + + Future readFor(String userId, String semester) async { + final encoded = await _store.read(); + if (encoded == null || encoded.length > _LEARN_CACHE_MAX_LENGTH) { + return null; + } + try { + final bytes = gzip.decode(base64Decode(encoded)); + if (bytes.length > _LEARN_CACHE_MAX_LENGTH) return null; + final data = jsonDecode(utf8.decode(bytes)); + if (data is! Map || + data['version'] != _LEARN_CACHE_VERSION || + data['userId'] != userId || + data['semester'] != semester) { + return null; + } + final rows = data['courses'] as List; + if (rows.length > 1000) return null; + return CachedLearnCourses( + fetchedAt: DateTime.parse(data['fetchedAt'] as String), + catalog: LearnCourseCatalog( + userId: userId, + semester: semester, + rawResponse: data['rawResponse'] is Map + ? Map.from(data['rawResponse'] as Map) + : null, + courses: [ + for (final raw in rows) + LearnCourse.fromJson(Map.from(raw as Map)), + ], + ), + ); + } on Exception { + return null; + } on TypeError { + return null; + } + } + + Future writeFor(LearnCourseCatalog catalog, DateTime fetchedAt) async { + final payload = jsonEncode({ + 'version': _LEARN_CACHE_VERSION, + 'userId': catalog.userId, + 'semester': catalog.semester, + 'fetchedAt': fetchedAt.toUtc().toIso8601String(), + 'courses': [for (final course in catalog.courses) course.toJson()], + if (catalog.rawResponse != null) 'rawResponse': catalog.rawResponse, + }); + await _store.write(base64Encode(gzip.encode(utf8.encode(payload)))); + } + + Future clear() => _store.clear(); +} diff --git a/packages/campus/lib/src/learn_course_catalog.dart b/packages/campus/lib/src/learn_course_catalog.dart new file mode 100644 index 0000000..1077629 --- /dev/null +++ b/packages/campus/lib/src/learn_course_catalog.dart @@ -0,0 +1,193 @@ +part of '../thulium_campus.dart'; + +const _LEARN_COURSE_CACHE_MAX_AGE = Duration(hours: 24); + +/// Converts a local calendar date into the academic semester used by Learn. +/// +/// The middle of February, July, and September is the chosen boundary. This +/// keeps the summer term attached to the academic year that just ended. +abstract final class AcademicSemester { + static String forDate(DateTime date) { + final year = date.year; + final month = date.month; + final day = date.day; + if (month > 9 || (month == 9 && day >= 15)) { + return '$year-${year + 1}-1'; + } + if (month > 7 || (month == 7 && day >= 15)) { + return '${year - 1}-$year-3'; + } + if (month > 2 || (month == 2 && day >= 15)) { + return '${year - 1}-$year-2'; + } + return '${year - 1}-$year-1'; + } +} + +/// One course from Learn, with names kept separate from calendar occurrences. +final class LearnCourse { + const LearnCourse({ + required this.id, + required this.name, + required this.englishName, + required this.teacherName, + required this.schedule, + }); + + final String id; + final String name; + final String englishName; + final String teacherName; + final String schedule; + + Map toJson() => { + 'id': id, + 'name': name, + 'englishName': englishName, + 'teacherName': teacherName, + 'schedule': schedule, + }; + + factory LearnCourse.fromJson(Map data) => LearnCourse( + id: data['id'] as String, + name: data['name'] as String, + englishName: data['englishName'] as String, + teacherName: data['teacherName'] as String, + schedule: data['schedule'] as String, + ); +} + +/// Account- and semester-scoped names used by Study and the teaching calendar. +final class LearnCourseCatalog { + LearnCourseCatalog({ + required this.userId, + required this.semester, + required List courses, + this.rawResponse, + }) : courses = List.unmodifiable(courses); + + final String userId; + final String semester; + final List courses; + + /// Retains the complete provider response for the CLI's detailed view. + final Map? rawResponse; + + factory LearnCourseCatalog.fromResponse( + Map response, + String semester, + ) { + final rows = response['resultList'] as List; + final courses = []; + for (final raw in rows) { + final row = raw as Map; + final primaryName = _courseField(row['kcm']); + final name = primaryName.isNotEmpty + ? primaryName + : _courseField(row['zywkcm']); + if (name.isEmpty) continue; + courses.add( + LearnCourse( + id: _courseField(row['wlkcid'] ?? row['kch']), + name: name, + englishName: _courseField(row['ywkcm']), + teacherName: _courseField(row['jsm']), + schedule: _courseField(row['sjddb']), + ), + ); + } + return LearnCourseCatalog( + userId: response['currentUser'] as String, + semester: semester, + courses: courses, + rawResponse: Map.unmodifiable(response), + ); + } + + /// Only exact, unambiguous names are translated; user plans are excluded. + CourseSchedule applyEnglishNames(CourseSchedule schedule) { + final translations = {}; + final ambiguous = {}; + for (final course in courses) { + final chinese = course.name.trim(); + final english = course.englishName.trim(); + if (chinese.isEmpty || english.isEmpty) continue; + if (translations.containsKey(chinese) && + translations[chinese] != english) { + ambiguous.add(chinese); + } else { + translations[chinese] = english; + } + } + return CourseSchedule( + term: schedule.term, + occurrences: [ + for (final occurrence in schedule.occurrences) + occurrence.category != PlanCategories.LESSON || + ambiguous.contains(occurrence.name.trim()) + ? occurrence + : occurrence.copyWith( + coursesPlanEnglishName: + translations[occurrence.name.trim()] ?? '', + ), + ], + ); + } +} + +String _courseField(Object? value) => value is String ? value.trim() : ''; + +enum LearnCourseSource { network, freshCache, staleCache } + +/// Reads Learn only when the semester cache is missing or older than a day. +final class LearnCourseCatalogService { + LearnCourseCatalogService(this._authClient, {this.cache, this.now}); + + final TsinghuaAuthClient _authClient; + final LearnCourseCache? cache; + final DateTime Function()? now; + + /// Origin of the most recent result, including offline fallback. + LearnCourseSource? lastSource; + + Future loadSemester( + String semester, { + bool forceRefresh = false, + }) async { + final userId = _authClient.session?.userId; + if (userId == null) throw StateError('Restore a session first.'); + final currentTime = (now ?? DateTime.now)(); + CachedLearnCourses? cached; + try { + cached = await cache?.readFor(userId, semester); + } on Exception { + // A secure-store read failure must not prevent a network request. + } + if (!forceRefresh && + cached != null && + cached.isFresh(currentTime, _LEARN_COURSE_CACHE_MAX_AGE)) { + lastSource = LearnCourseSource.freshCache; + return cached.catalog; + } + + try { + final response = await LearnCourseService( + _authClient, + now: now, + ).fetchSemester(semester); + final catalog = LearnCourseCatalog.fromResponse(response, semester); + try { + await cache?.writeFor(catalog, currentTime); + } on Exception { + // A successful response remains usable even if persistence fails. + } + lastSource = LearnCourseSource.network; + return catalog; + } on Object catch (error) { + if (error is! Exception && error is! StateError) rethrow; + if (cached == null || forceRefresh) rethrow; + lastSource = LearnCourseSource.staleCache; + return cached.catalog; + } + } +} diff --git a/packages/campus/lib/src/learn_courses.dart b/packages/campus/lib/src/learn_courses.dart index 4ac4728..d9aa6f7 100644 --- a/packages/campus/lib/src/learn_courses.dart +++ b/packages/campus/lib/src/learn_courses.dart @@ -60,8 +60,8 @@ final class LearnPlatformSession { /// Fetches the learning platform's semester course-list response unchanged. /// -/// This diagnostic API intentionally retains all response fields for CLI -/// inspection. It does not persist the course list or any credential values. +/// This low-level API retains all response fields for CLI inspection. The +/// catalog service may cache its result separately from credential values. final class LearnCourseService { const LearnCourseService(this._authClient, {this.now}); diff --git a/packages/campus/lib/thulium_campus.dart b/packages/campus/lib/thulium_campus.dart index 3f80645..6b84e44 100644 --- a/packages/campus/lib/thulium_campus.dart +++ b/packages/campus/lib/thulium_campus.dart @@ -9,3 +9,5 @@ part 'src/course_schedule.dart'; part 'src/course_schedule_cache.dart'; part 'src/custom_plan.dart'; part 'src/learn_courses.dart'; +part 'src/learn_course_catalog.dart'; +part 'src/learn_course_cache.dart'; diff --git a/packages/campus/test/course_schedule_test.dart b/packages/campus/test/course_schedule_test.dart index f69454c..755c3fc 100644 --- a/packages/campus/test/course_schedule_test.dart +++ b/packages/campus/test/course_schedule_test.dart @@ -410,6 +410,60 @@ void main() { ); }); + test('retains translated lesson names in a calendar snapshot', () async { + final cache = CourseScheduleCache(_MemoryCacheStore()); + final translated = CourseSchedule( + term: _cachedSchedule().term, + occurrences: [ + _cachedSchedule().occurrences.single.copyWith( + coursesPlanEnglishName: 'English Course', + ), + ], + ); + await cache.writeFor('2024222050', translated, DateTime.utc(2026, 9, 25)); + + final cached = await cache.readFor('2024222050'); + expect( + cached?.schedule.occurrences.single.nameForLanguage('en'), + 'English Course', + ); + }); + + test('reads older snapshots without an English lesson title', () async { + final store = _MemoryCacheStore(); + final current = _cachedSchedule(); + final occurrence = current.occurrences.single; + store.value = base64Encode( + gzip.encode( + utf8.encode( + jsonEncode({ + 'version': 2, + 'userId': '2024222050', + 'fetchedAt': '2026-09-25T10:00:00.000Z', + 'term': { + 'id': current.term.id, + 'name': current.term.name, + 'firstMonday': current.term.firstMonday.toIso8601String(), + 'weekCount': current.term.weekCount, + }, + 'occurrences': [ + { + 'name': occurrence.name, + 'location': occurrence.location, + 'category': occurrence.category, + 'startsAt': occurrence.startsAt.toIso8601String(), + 'endsAt': occurrence.endsAt.toIso8601String(), + }, + ], + }), + ), + ), + ); + + final cached = await CourseScheduleCache(store).readFor('2024222050'); + expect(cached?.schedule.occurrences.single.coursesPlanEnglishName, isEmpty); + }); + test('does not use a cache from an ended academic term', () async { final store = MemoryAuthSessionStore(); final session = _testSession(isGraduate: true); diff --git a/packages/campus/test/custom_plan_test.dart b/packages/campus/test/custom_plan_test.dart index d1dd229..385dfe5 100644 --- a/packages/campus/test/custom_plan_test.dart +++ b/packages/campus/test/custom_plan_test.dart @@ -232,6 +232,69 @@ void main() { expect(hidden.plans, isEmpty); }); + test( + 'edited fetched lessons inherit English names only without renaming', + () { + final lesson = CourseOccurrence( + name: '大学物理', + location: 'Room 1', + startsAt: start, + endsAt: end, + category: PlanCategories.LESSON, + coursesPlanEnglishName: 'Physics', + ); + final weekStart = DateTime(2026, 9, 21); + final weekEnd = DateTime(2026, 9, 28); + final entry = CustomPlanCollection.empty() + .entriesForWeek([lesson], weekStart, weekEnd) + .single; + final moved = CustomPlanCollection.empty().replaceOccurrence( + entry, + CourseOccurrence( + name: lesson.name, + location: 'Room 2', + startsAt: DateTime(2026, 9, 28, 9), + endsAt: DateTime(2026, 9, 28, 10), + category: PlanCategories.LESSON, + ), + ); + final restored = CustomPlanCollection.decode(moved.encode()); + final edited = restored.entriesForWeek( + [lesson], + DateTime(2026, 9, 28), + DateTime(2026, 10, 5), + ); + expect(edited.single.occurrence.nameForLanguage('en'), 'Physics'); + expect(edited.single.occurrence.location, 'Room 2'); + final renamed = restored.replaceOccurrence( + edited.single, + CourseOccurrence( + name: 'My physics plan', + location: 'Room 2', + startsAt: edited.single.occurrence.startsAt, + endsAt: edited.single.occurrence.endsAt, + category: PlanCategories.LESSON, + ), + ); + expect( + renamed + .entriesForWeek( + [lesson], + DateTime(2026, 9, 28), + DateTime(2026, 10, 5), + ) + .single + .occurrence + .nameForLanguage('en'), + 'My physics plan', + ); + expect( + fetchedLessonSourceId(lesson), + fetchedLessonSourceId(lesson.copyWith(coursesPlanEnglishName: '')), + ); + }, + ); + test('version-one data migrates and warning preferences persist', () { final old = jsonEncode({ 'version': 1, diff --git a/packages/campus/test/learn_course_catalog_test.dart b/packages/campus/test/learn_course_catalog_test.dart new file mode 100644 index 0000000..3fdac46 --- /dev/null +++ b/packages/campus/test/learn_course_catalog_test.dart @@ -0,0 +1,175 @@ +import 'package:test/test.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +void main() { + test('uses mid-month academic semester boundaries', () { + final examples = { + DateTime(2025, 9, 15): '2025-2026-1', + DateTime(2026, 2, 14): '2025-2026-1', + DateTime(2026, 2, 15): '2025-2026-2', + DateTime(2026, 7, 14): '2025-2026-2', + DateTime(2026, 7, 15): '2025-2026-3', + DateTime(2026, 9, 14): '2025-2026-3', + DateTime(2026, 9, 15): '2026-2027-1', + }; + for (final entry in examples.entries) { + expect(AcademicSemester.forDate(entry.key), entry.value); + } + }); + + test('translates only fetched lessons with an exact course name', () { + final catalog = LearnCourseCatalog( + userId: 'student', + semester: '2025-2026-1', + courses: [ + const LearnCourse( + id: 'id-1', + name: '大学物理', + englishName: 'University Physics', + teacherName: '', + schedule: '', + ), + ], + ); + final start = DateTime(2025, 9, 15, 8); + final lesson = CourseOccurrence( + name: '大学物理', + location: 'A101', + startsAt: start, + endsAt: start.add(const Duration(hours: 1)), + category: PlanCategories.LESSON, + ); + final personal = CourseOccurrence( + name: '大学物理', + location: 'Library', + startsAt: start.add(const Duration(hours: 2)), + endsAt: start.add(const Duration(hours: 3)), + category: 'my-category', + ); + final schedule = CourseSchedule( + term: AcademicTerm( + id: '2025-2026-1', + name: 'Fall', + firstMonday: DateTime(2025, 9, 15), + weekCount: 16, + ), + occurrences: [lesson, personal], + ); + + final translated = catalog.applyEnglishNames(schedule); + expect( + translated.occurrences.first.coursesPlanEnglishName, + 'University Physics', + ); + expect( + translated.occurrences.first.nameForLanguage('en'), + 'University Physics', + ); + expect(translated.occurrences.first.nameForLanguage('zh'), '大学物理'); + expect(translated.occurrences.last.coursesPlanEnglishName, isEmpty); + expect(translated.occurrences.last.nameForLanguage('en'), '大学物理'); + }); + + test('leaves ambiguous English titles untranslated', () { + final catalog = LearnCourseCatalog( + userId: 'student', + semester: '2025-2026-1', + courses: [ + for (final english in ['Course A', 'Course B']) + LearnCourse( + id: english, + name: '同名课程', + englishName: english, + teacherName: '', + schedule: '', + ), + ], + ); + final schedule = CourseSchedule( + term: AcademicTerm( + id: '2025-2026-1', + name: 'Fall', + firstMonday: DateTime(2025, 9, 15), + weekCount: 16, + ), + occurrences: [ + CourseOccurrence( + name: '同名课程', + location: 'A', + startsAt: DateTime(2025, 9, 15, 8), + endsAt: DateTime(2025, 9, 15, 9), + category: PlanCategories.LESSON, + ), + ], + ); + expect( + catalog + .applyEnglishNames(schedule) + .occurrences + .single + .nameForLanguage('en'), + '同名课程', + ); + }); + + test('course list cache is account- and semester-scoped', () async { + final store = _InMemoryStore(); + final cache = LearnCourseCache(store); + final catalog = LearnCourseCatalog( + userId: 'student-a', + semester: '2025-2026-1', + courses: [ + const LearnCourse( + id: 'course-1', + name: '课程', + englishName: 'Course', + teacherName: 'Teacher', + schedule: 'Monday', + ), + ], + rawResponse: const { + 'currentUser': 'student-a', + 'resultList': [ + {'kcm': '课程', 'xss': 25}, + ], + }, + ); + final fetchedAt = DateTime.utc(2026, 2, 1); + await cache.writeFor(catalog, fetchedAt); + + final restored = await cache.readFor('student-a', '2025-2026-1'); + expect(restored?.catalog.courses.single.englishName, 'Course'); + expect(restored?.catalog.rawResponse?['resultList'], isNotNull); + expect( + restored?.isFresh( + fetchedAt.add(const Duration(hours: 23)), + const Duration(hours: 24), + ), + isTrue, + ); + expect( + restored?.isFresh( + fetchedAt.add(const Duration(hours: 24)), + const Duration(hours: 24), + ), + isFalse, + ); + expect(await cache.readFor('student-b', '2025-2026-1'), isNull); + expect(await cache.readFor('student-a', '2025-2026-2'), isNull); + await cache.clear(); + expect(await cache.readFor('student-a', '2025-2026-1'), isNull); + }); +} + +final class _InMemoryStore implements LearnCourseCacheStore { + String? value; + + @override + Future read() async => value; + + @override + Future write(String value) async => this.value = value; + + @override + Future clear() async => value = null; +} diff --git a/packages/campus/test/learn_courses_test.dart b/packages/campus/test/learn_courses_test.dart index 9be00ec..c0d3620 100644 --- a/packages/campus/test/learn_courses_test.dart +++ b/packages/campus/test/learn_courses_test.dart @@ -91,6 +91,72 @@ void main() { throwsA(isA()), ); }); + + test( + 'reuses fresh course names and serves stale data after a failure', + () async { + final transport = _LearnHttpClient(); + final store = MemoryAuthSessionStore(); + await store.write(_session); + final auth = TsinghuaAuthClient( + httpClient: transport, + sessionStore: store, + ); + await auth.restore(); + final courseCache = LearnCourseCache(_LearnCacheStore()); + final firstTime = DateTime(2026, 9, 28, 8); + final first = LearnCourseCatalogService( + auth, + cache: courseCache, + now: () => firstTime, + ); + expect( + (await first.loadSemester('2026-2027-1')).courses.single.name, + 'Course A', + ); + expect(first.lastSource, LearnCourseSource.network); + expect(transport.courseRequestCount, 1); + expect(await courseCache.readFor('2024012050', '2026-2027-1'), isNotNull); + + final fresh = LearnCourseCatalogService( + auth, + cache: courseCache, + now: () => firstTime.add(const Duration(hours: 23)), + ); + await fresh.loadSemester('2026-2027-1'); + expect(fresh.lastSource, LearnCourseSource.freshCache); + expect(transport.courseRequestCount, 1); + + transport.courseStatusCode = 503; + final stale = LearnCourseCatalogService( + auth, + cache: courseCache, + now: () => firstTime.add(const Duration(hours: 25)), + ); + expect( + (await stale.loadSemester('2026-2027-1')).courses.single.name, + 'Course A', + ); + expect(stale.lastSource, LearnCourseSource.staleCache); + await expectLater( + stale.loadSemester('2026-2027-1', forceRefresh: true), + throwsStateError, + ); + }, + ); +} + +final class _LearnCacheStore implements LearnCourseCacheStore { + String? value; + + @override + Future read() async => value; + + @override + Future write(String value) async => this.value = value; + + @override + Future clear() async => value = null; } const _session = AuthSession( @@ -126,8 +192,9 @@ final class _LearnHttpClient extends http.BaseClient { final bool omitPageCsrf; final String currentUser; - final int courseStatusCode; + int courseStatusCode; http.BaseRequest? courseRequest; + int courseRequestCount = 0; @override Future send(http.BaseRequest request) async { @@ -147,6 +214,7 @@ final class _LearnHttpClient extends http.BaseClient { }); } else if (path.endsWith('loadCourseBySemesterId/2026-2027-1/zh')) { courseRequest = request; + courseRequestCount++; body = jsonEncode({ 'currentUser': currentUser, 'message': 'success', diff --git a/packages/cli/bin/thulium.dart b/packages/cli/bin/thulium.dart index 508f8a1..b2cf0ee 100644 --- a/packages/cli/bin/thulium.dart +++ b/packages/cli/bin/thulium.dart @@ -7,6 +7,7 @@ import 'package:thulium_campus/thulium_campus.dart'; import 'package:thulium_auth/thulium_auth.dart'; import 'package:thulium_cli/cli_auth_session_store.dart'; import 'package:thulium_cli/cli_course_schedule_cache_store.dart'; +import 'package:thulium_cli/cli_learn_course_cache_store.dart'; import 'package:thulium_cli/cli_session_reconnect.dart'; import 'package:thulium_cli/learn_course_formatter.dart'; @@ -71,9 +72,10 @@ ArgParser _buildParser() { ..addOption( 'semester', abbr: 's', - help: 'Academic semester ID, for example 2026-2027-1.', + help: 'Academic semester ID (defaults to the current semester).', ) - ..addFlag('verbose', help: 'Print safe request diagnostics.'), + ..addFlag('verbose', help: 'Print safe request diagnostics.') + ..addFlag('refresh', help: 'Fetch courses instead of using the cache.'), ); return parser; } @@ -89,6 +91,7 @@ Future _runCommand(ArgResults command) async { final store = CliAuthSessionStore(); final calendarCache = CourseScheduleCache(CliCourseScheduleCacheStore()); + final learnCache = LearnCourseCache(CliLearnCourseCacheStore()); final client = TsinghuaAuthClient( sessionStore: store, credentialStore: store, @@ -131,6 +134,7 @@ Future _runCommand(ArgResults command) async { await client.logout(); } finally { await calendarCache.clear(); + await learnCache.clear(); } stdout.writeln('Logged out.'); case 'status': @@ -161,20 +165,45 @@ Future _runCommand(ArgResults command) async { if (session == null) { throw StateError('Not logged in. Run `thulium login` first.'); } - final semester = command.command!['semester'] as String?; - if (semester == null || semester.isEmpty) { - throw const FormatException( - 'Provide --semester, for example 2026-2027-1.', - ); - } - final response = await reconnect.run( + final semester = + (command.command!['semester'] as String?) ?? + AcademicSemester.forDate(DateTime.now()); + final catalogService = LearnCourseCatalogService( + client, + cache: learnCache, + ); + final catalog = await reconnect.run( commandName: 'learn-courses', savedSession: session, - request: (_) => LearnCourseService(client).fetchSemester(semester), + request: (isRetry) => catalogService.loadSemester( + semester, + forceRefresh: isRetry || command.command!['refresh'] as bool, + ), shouldReconnect: (error) => error is PortalCsrfUnavailable || error is PortalSessionRejected, ); - stdout.writeln(formatLearnCourses(response, semester: semester)); + if (catalogService.lastSource == LearnCourseSource.staleCache) { + stderr.writeln('Update failed; showing the saved course list.'); + } + stdout.writeln( + formatLearnCourses( + catalog.rawResponse ?? + { + 'currentUser': catalog.userId, + 'resultList': [ + for (final course in catalog.courses) + { + 'wlkcid': course.id, + 'kcm': course.name, + 'ywkcm': course.englishName, + 'jsm': course.teacherName, + 'sjddb': course.schedule, + }, + ], + }, + semester: semester, + ), + ); } } diff --git a/packages/cli/lib/cli_learn_course_cache_store.dart b/packages/cli/lib/cli_learn_course_cache_store.dart new file mode 100644 index 0000000..f51ce39 --- /dev/null +++ b/packages/cli/lib/cli_learn_course_cache_store.dart @@ -0,0 +1,25 @@ +import 'package:keybay/keybay.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +// ignore_for_file: constant_identifier_names + +const _CLI_STORE_ID = 'dev.thulium.cli'; +const _LEARN_COURSE_CACHE_KEY = 'learn-course-cache-v1'; + +/// Persists student course titles in the CLI's encrypted local secret store. +final class CliLearnCourseCacheStore implements LearnCourseCacheStore { + CliLearnCourseCacheStore({SecretStorage? storage}) + : _storage = storage ?? SecretStorage(appId: _CLI_STORE_ID); + + final SecretStorage _storage; + + @override + Future read() => _storage.readString(_LEARN_COURSE_CACHE_KEY); + + @override + Future write(String value) => + _storage.writeString(_LEARN_COURSE_CACHE_KEY, value); + + @override + Future clear() => _storage.delete(_LEARN_COURSE_CACHE_KEY); +} diff --git a/test/calendar_course_block_test.dart b/test/calendar_course_block_test.dart index 59ed030..f73eb1c 100644 --- a/test/calendar_course_block_test.dart +++ b/test/calendar_course_block_test.dart @@ -1,10 +1,49 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:forui/forui.dart'; +import 'package:thulium/l10n/generated/app_localizations.dart'; import 'package:thulium/widgets/calendar_course_block.dart'; import 'package:thulium_campus/thulium_campus.dart'; void main() { + testWidgets('switches fetched lesson names with the app language', ( + tester, + ) async { + final course = CourseOccurrence( + name: '大学物理', + coursesPlanEnglishName: 'University Physics', + location: 'A101', + category: PlanCategories.LESSON, + startsAt: DateTime(2026, 9, 28, 8), + endsAt: DateTime(2026, 9, 28, 9), + ); + + Future show(Locale locale) async { + await tester.pumpWidget( + MaterialApp( + locale: locale, + supportedLocales: AppLocalizations.supportedLocales, + localizationsDelegates: [ + ...AppLocalizations.localizationsDelegates, + ...FLocalizations.localizationsDelegates, + ], + home: FTheme( + data: FThemes.neutral.light.touch, + child: Scaffold( + body: CalendarCourseBlock(course: course, width: 120, height: 90), + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + await show(const Locale('en')); + expect(find.text('University Physics'), findsOneWidget); + await show(const Locale('zh')); + expect(find.text('大学物理'), findsOneWidget); + }); + testWidgets('very short plans show a compact marker without text overflow', ( tester, ) async { diff --git a/test/study_page_test.dart b/test/study_page_test.dart new file mode 100644 index 0000000..9d028be --- /dev/null +++ b/test/study_page_test.dart @@ -0,0 +1,67 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:forui/forui.dart'; +import 'package:thulium/l10n/generated/app_localizations.dart'; +import 'package:thulium/pages/study_page.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +void main() { + testWidgets('reserves shortcut space and displays localized course titles', ( + tester, + ) async { + final catalog = LearnCourseCatalog( + userId: 'student', + semester: '2026-2027-1', + courses: [ + const LearnCourse( + id: 'course-1', + name: '大学物理', + englishName: 'University Physics', + teacherName: 'Teacher', + schedule: 'Monday, Room 101', + ), + ], + ); + + Future show(Locale locale) async { + await tester.pumpWidget( + MaterialApp( + locale: locale, + localizationsDelegates: [ + ...AppLocalizations.localizationsDelegates, + ...FLocalizations.localizationsDelegates, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => FTheme( + data: FThemes.neutral.light.touch, + child: child ?? const SizedBox.shrink(), + ), + home: Scaffold( + body: StudyPage( + semester: catalog.semester, + catalog: catalog, + isLoading: false, + isStale: false, + error: null, + onRefresh: () {}, + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + await show(const Locale('en')); + expect( + find.byKey(const ValueKey('study-shortcut-reserved')), + findsOneWidget, + ); + expect(find.text('My courses'), findsOneWidget); + expect(find.text('University Physics'), findsOneWidget); + + await show(const Locale('zh', 'CN')); + expect(find.text('我的课程'), findsOneWidget); + expect(find.text('大学物理'), findsOneWidget); + expect(find.text('University Physics'), findsNothing); + }); +} diff --git a/test/widget_test.dart b/test/widget_test.dart index fa8b473..4687d16 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -6,6 +6,7 @@ import 'package:thulium_auth/thulium_auth.dart'; import 'package:thulium/app.dart'; import 'package:thulium/pages/settings_page.dart'; +import 'package:thulium/pages/study_page.dart'; import 'package:thulium/widgets/language_button.dart'; void main() { @@ -17,7 +18,7 @@ void main() { expect(find.text('Explore'), findsOneWidget); }); - testWidgets('restores the authenticated home without a startup probe', ( + testWidgets('restores the home while courses load in the background', ( tester, ) async { final store = MemoryAuthSessionStore(); @@ -30,6 +31,24 @@ void main() { expect(find.text('Welcome, THUer'), findsNothing); }); + testWidgets('opens the Study course list from the bottom navigation', ( + tester, + ) async { + final store = MemoryAuthSessionStore(); + await store.write(_savedSession()); + + await tester.pumpWidget(ThuliumApp(sessionStore: store)); + await tester.pumpAndSettle(); + await tester.tap(find.byIcon(Icons.menu_book_outlined)); + await tester.pumpAndSettle(); + + expect(find.byType(StudyPage), findsOneWidget); + expect( + find.byKey(const ValueKey('study-shortcut-reserved')), + findsOneWidget, + ); + }); + testWidgets('opens settings from the authenticated home', (tester) async { final store = MemoryAuthSessionStore(); await store.write(_savedSession()); From 07a5aec16343d614b9eac0b97ced64da27af1181 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AshGrey=F0=9F=A5=95?= Date: Mon, 28 Sep 2026 11:35:21 +0800 Subject: [PATCH 04/26] refactor(test): group tests by scope and feature (#5) Move logic and storage tests under test/unit, and organize Flutter widget tests by app, calendar, plans, and study. Document the test layout and reserve integration_test for device-level end-to-end tests. --- README.md | 4 ++++ test/{ => unit/calendar}/calendar_course_layout_test.dart | 0 test/{ => unit/plans}/secure_custom_plan_store_test.dart | 0 test/{ => widget/app}/widget_test.dart | 0 test/{ => widget/calendar}/calendar_course_block_test.dart | 0 test/{ => widget/calendar}/calendar_document_export_test.dart | 0 test/{ => widget/calendar}/calendar_export_dialog_test.dart | 0 test/{ => widget/calendar}/calendar_now_line_test.dart | 0 test/{ => widget/calendar}/calendar_overlap_dialog_test.dart | 0 test/{ => widget/calendar}/calendar_vertical_pinch_test.dart | 0 test/{ => widget/calendar}/calendar_week_bar_test.dart | 0 test/{ => widget/calendar}/calendar_week_pager_test.dart | 0 .../{ => widget/calendar}/calendar_week_scroll_sync_test.dart | 0 test/{ => widget/plans}/add_plan_page_test.dart | 0 .../{ => widget/plans}/calendar_plan_details_dialog_test.dart | 0 test/{ => widget/study}/study_page_test.dart | 0 16 files changed, 4 insertions(+) rename test/{ => unit/calendar}/calendar_course_layout_test.dart (100%) rename test/{ => unit/plans}/secure_custom_plan_store_test.dart (100%) rename test/{ => widget/app}/widget_test.dart (100%) rename test/{ => widget/calendar}/calendar_course_block_test.dart (100%) rename test/{ => widget/calendar}/calendar_document_export_test.dart (100%) rename test/{ => widget/calendar}/calendar_export_dialog_test.dart (100%) rename test/{ => widget/calendar}/calendar_now_line_test.dart (100%) rename test/{ => widget/calendar}/calendar_overlap_dialog_test.dart (100%) rename test/{ => widget/calendar}/calendar_vertical_pinch_test.dart (100%) rename test/{ => widget/calendar}/calendar_week_bar_test.dart (100%) rename test/{ => widget/calendar}/calendar_week_pager_test.dart (100%) rename test/{ => widget/calendar}/calendar_week_scroll_sync_test.dart (100%) rename test/{ => widget/plans}/add_plan_page_test.dart (100%) rename test/{ => widget/plans}/calendar_plan_details_dialog_test.dart (100%) rename test/{ => widget/study}/study_page_test.dart (100%) diff --git a/README.md b/README.md index 5208537..7f58445 100644 --- a/README.md +++ b/README.md @@ -97,6 +97,10 @@ linux/ macos/ windows/ Desktop targets ## Checks +Tests are grouped by scope: `test/unit/` covers logic and adapters, while +`test/widget/` covers Flutter components and screen behavior. Device-level +end-to-end tests belong in `integration_test/`. + ```bash flutter analyze flutter test diff --git a/test/calendar_course_layout_test.dart b/test/unit/calendar/calendar_course_layout_test.dart similarity index 100% rename from test/calendar_course_layout_test.dart rename to test/unit/calendar/calendar_course_layout_test.dart diff --git a/test/secure_custom_plan_store_test.dart b/test/unit/plans/secure_custom_plan_store_test.dart similarity index 100% rename from test/secure_custom_plan_store_test.dart rename to test/unit/plans/secure_custom_plan_store_test.dart diff --git a/test/widget_test.dart b/test/widget/app/widget_test.dart similarity index 100% rename from test/widget_test.dart rename to test/widget/app/widget_test.dart diff --git a/test/calendar_course_block_test.dart b/test/widget/calendar/calendar_course_block_test.dart similarity index 100% rename from test/calendar_course_block_test.dart rename to test/widget/calendar/calendar_course_block_test.dart diff --git a/test/calendar_document_export_test.dart b/test/widget/calendar/calendar_document_export_test.dart similarity index 100% rename from test/calendar_document_export_test.dart rename to test/widget/calendar/calendar_document_export_test.dart diff --git a/test/calendar_export_dialog_test.dart b/test/widget/calendar/calendar_export_dialog_test.dart similarity index 100% rename from test/calendar_export_dialog_test.dart rename to test/widget/calendar/calendar_export_dialog_test.dart diff --git a/test/calendar_now_line_test.dart b/test/widget/calendar/calendar_now_line_test.dart similarity index 100% rename from test/calendar_now_line_test.dart rename to test/widget/calendar/calendar_now_line_test.dart diff --git a/test/calendar_overlap_dialog_test.dart b/test/widget/calendar/calendar_overlap_dialog_test.dart similarity index 100% rename from test/calendar_overlap_dialog_test.dart rename to test/widget/calendar/calendar_overlap_dialog_test.dart diff --git a/test/calendar_vertical_pinch_test.dart b/test/widget/calendar/calendar_vertical_pinch_test.dart similarity index 100% rename from test/calendar_vertical_pinch_test.dart rename to test/widget/calendar/calendar_vertical_pinch_test.dart diff --git a/test/calendar_week_bar_test.dart b/test/widget/calendar/calendar_week_bar_test.dart similarity index 100% rename from test/calendar_week_bar_test.dart rename to test/widget/calendar/calendar_week_bar_test.dart diff --git a/test/calendar_week_pager_test.dart b/test/widget/calendar/calendar_week_pager_test.dart similarity index 100% rename from test/calendar_week_pager_test.dart rename to test/widget/calendar/calendar_week_pager_test.dart diff --git a/test/calendar_week_scroll_sync_test.dart b/test/widget/calendar/calendar_week_scroll_sync_test.dart similarity index 100% rename from test/calendar_week_scroll_sync_test.dart rename to test/widget/calendar/calendar_week_scroll_sync_test.dart diff --git a/test/add_plan_page_test.dart b/test/widget/plans/add_plan_page_test.dart similarity index 100% rename from test/add_plan_page_test.dart rename to test/widget/plans/add_plan_page_test.dart diff --git a/test/calendar_plan_details_dialog_test.dart b/test/widget/plans/calendar_plan_details_dialog_test.dart similarity index 100% rename from test/calendar_plan_details_dialog_test.dart rename to test/widget/plans/calendar_plan_details_dialog_test.dart diff --git a/test/study_page_test.dart b/test/widget/study/study_page_test.dart similarity index 100% rename from test/study_page_test.dart rename to test/widget/study/study_page_test.dart From 1aa63e4958cd5999e1b9025f3b1fd18505646f45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AshGrey=F0=9F=A5=95?= Date: Mon, 28 Sep 2026 13:59:43 +0800 Subject: [PATCH 05/26] style(study): refine course list font size --- lib/pages/study_page.dart | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/lib/pages/study_page.dart b/lib/pages/study_page.dart index 6e71cb6..91f6cb4 100644 --- a/lib/pages/study_page.dart +++ b/lib/pages/study_page.dart @@ -27,6 +27,11 @@ final class StudyPage extends StatelessWidget { final l10n = AppLocalizations.of(context)!; final colors = context.theme.colors; final locale = Localizations.localeOf(context).languageCode; + final courseTitleStyle = context.theme.typography.md; + final courseMetadataStyle = context.theme.typography.sm.copyWith( + fontSize: 12, + color: colors.mutedForeground, + ); return ListView( padding: const EdgeInsets.fromLTRB(16, 12, 16, 24), children: [ @@ -105,7 +110,9 @@ final class StudyPage extends StatelessWidget { locale == 'en' && course.englishName.isNotEmpty ? course.englishName : course.name, - style: context.theme.typography.md, + style: courseTitleStyle.copyWith( + fontWeight: FontWeight.bold, + ), ), if (course.teacherName.isNotEmpty || course.schedule.isNotEmpty) ...[ @@ -115,9 +122,7 @@ final class StudyPage extends StatelessWidget { if (course.teacherName.isNotEmpty) course.teacherName, if (course.schedule.isNotEmpty) course.schedule, ].join(' · '), - style: context.theme.typography.sm.copyWith( - color: colors.mutedForeground, - ), + style: courseMetadataStyle, ), ], ], From 3121f80192ed2cde1937117126513b54d70ec34f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AshGrey=F0=9F=A5=95?= Date: Wed, 14 Oct 2026 08:49:43 +0800 Subject: [PATCH 06/26] feat(cli): add Learn homework counts Add the learn-homework command to report per-course and semester totals for unsubmitted, submitted-but-ungraded, and graded assignments. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fetch counts from Learn’s total-record metadata, keep YAML output clean by sending prompts and diagnostics to stderr, and document the command. --- README.md | 10 + packages/campus/lib/src/learn_homework.dart | 118 +++++++++++ packages/campus/lib/thulium_campus.dart | 1 + packages/campus/test/learn_homework_test.dart | 194 ++++++++++++++++++ packages/cli/bin/thulium.dart | 113 +++++++--- .../cli/lib/learn_homework_formatter.dart | 54 +++++ .../test/learn_homework_formatter_test.dart | 61 ++++++ 7 files changed, 527 insertions(+), 24 deletions(-) create mode 100644 packages/campus/lib/src/learn_homework.dart create mode 100644 packages/campus/test/learn_homework_test.dart create mode 100644 packages/cli/lib/learn_homework_formatter.dart create mode 100644 packages/cli/test/learn_homework_formatter_test.dart diff --git a/README.md b/README.md index 7f58445..62a7e5d 100644 --- a/README.md +++ b/README.md @@ -49,6 +49,8 @@ dart run bin/thulium.dart schedule --refresh dart run bin/thulium.dart learn-courses dart run bin/thulium.dart learn-courses --semester 2026-2027-1 dart run bin/thulium.dart learn-courses --refresh +dart run bin/thulium.dart learn-homework +dart run bin/thulium.dart learn-homework --semester 2026-2027-1 --refresh dart run bin/thulium.dart logout ``` @@ -77,6 +79,14 @@ English titles for matching lessons when the app language is English. Custom plans keep their original names. The output contains student-specific information, so avoid redirecting it to a shared log. +`learn-homework` reports current unsubmitted, submitted-but-ungraded, and graded +homework counts for every course in the selected semester, with semester totals +and per-course entries in YAML. It defaults to the current semester; `--refresh` +refreshes the course list, while homework counts are always fetched live. Counts +come from the server's total-record metadata, not the first five returned rows. +Diagnostics and reconnection messages go to stderr, keeping stdout valid YAML. +If any count cannot be fetched, the command fails instead of reporting it as zero. + When a protected CLI request reports an expired session, the CLI tries the saved credentials, then offers an interactive sign-in if needed. A successful reconnection retries the original request once. diff --git a/packages/campus/lib/src/learn_homework.dart b/packages/campus/lib/src/learn_homework.dart new file mode 100644 index 0000000..833e168 --- /dev/null +++ b/packages/campus/lib/src/learn_homework.dart @@ -0,0 +1,118 @@ +part of '../thulium_campus.dart'; + +/// Counts are taken from each status endpoint, independently of page size. +final class LearnHomeworkCounts { + const LearnHomeworkCounts({ + required this.unsubmitted, + required this.submittedUngraded, + required this.graded, + }); + + final int unsubmitted; + final int submittedUngraded; + final int graded; + + int get total => unsubmitted + submittedUngraded + graded; +} + +final class LearnCourseHomework { + const LearnCourseHomework({required this.course, required this.counts}); + + final LearnCourse course; + final LearnHomeworkCounts counts; +} + +/// Reads current homework totals using the captured GET `/student/index/` +/// API. OneTHU confirms Wj = unsubmitted, Yjwg = submitted but ungraded, +/// and Ypg = graded, although it uses a separate non-index POST API. +final class LearnHomeworkService { + const LearnHomeworkService(this._authClient); + + final TsinghuaAuthClient _authClient; + + Future> fetchCourses( + LearnCourseCatalog catalog, + ) async { + if (_authClient.session?.userId != catalog.userId) { + throw StateError('Restore the course catalog account first.'); + } + for (final course in catalog.courses) { + if (course.id.isEmpty) { + throw const FormatException('A course has no learning platform ID.'); + } + } + if (catalog.courses.isEmpty) return const []; + final csrf = await LearnPlatformSession(_authClient).open(); + final result = []; + // Keep requests sequential to avoid overwhelming Learn or racing its + // shared authentication cookies. One roaming session serves all courses. + for (final course in catalog.courses) { + final unsubmitted = await _fetchCount(course.id, 'zyListWj', csrf); + final submitted = await _fetchCount(course.id, 'zyListYjwg', csrf); + final graded = await _fetchCount(course.id, 'zyListYpg', csrf); + result.add( + LearnCourseHomework( + course: course, + counts: LearnHomeworkCounts( + unsubmitted: unsubmitted, + submittedUngraded: submitted, + graded: graded, + ), + ), + ); + } + return result; + } + + Future _fetchCount(String courseId, String endpoint, String csrf) async { + // The index route is captured for Wj. Reusing that prefix for Yjwg/Ypg + // is inferred from the sibling endpoint names; OneTHU confirms those + // names on its non-index POST route, not this GET variant. + final target = Uri.https( + _LEARN_HOST, + '/b/wlxt/kczy/zy/student/index/$endpoint', + {'wlkcid': courseId, 'size': '5', '_csrf': csrf}, + ); + final response = await _authClient.getAuthenticated( + TsinghuaWebVpnRedirect.forTarget(target), + ); + if (_isLearnSignInResponse( + response.statusCode, + response.request?.url, + response.body, + )) { + _authClient.traceUnexpectedResponse('learning-homework', response); + throw const PortalSessionRejected(); + } + if (response.statusCode != 200) { + throw StateError( + 'Homework request failed for $courseId ($endpoint): ' + 'HTTP ${response.statusCode}.', + ); + } + final Object? decoded; + try { + decoded = jsonDecode(response.body); + } on FormatException { + throw const FormatException('Learn did not return homework-list JSON.'); + } + if (decoded is! Map || + decoded['result'] != 'success' || + decoded['object'] is! Map) { + throw const FormatException('Learn returned an invalid homework list.'); + } + final data = decoded['object'] as Map; + // DataTables metadata is authoritative. aaData contains only this page, + // while iTotalDisplayRecords is the filtered count, not the full total. + final value = data['iTotalRecords']; + final count = value is int + ? value + : value is String + ? int.tryParse(value) + : null; + if (count == null || count < 0) { + throw const FormatException('Learn returned an invalid homework total.'); + } + return count; + } +} diff --git a/packages/campus/lib/thulium_campus.dart b/packages/campus/lib/thulium_campus.dart index 6b84e44..8228381 100644 --- a/packages/campus/lib/thulium_campus.dart +++ b/packages/campus/lib/thulium_campus.dart @@ -9,5 +9,6 @@ part 'src/course_schedule.dart'; part 'src/course_schedule_cache.dart'; part 'src/custom_plan.dart'; part 'src/learn_courses.dart'; +part 'src/learn_homework.dart'; part 'src/learn_course_catalog.dart'; part 'src/learn_course_cache.dart'; diff --git a/packages/campus/test/learn_homework_test.dart b/packages/campus/test/learn_homework_test.dart new file mode 100644 index 0000000..6c566b7 --- /dev/null +++ b/packages/campus/test/learn_homework_test.dart @@ -0,0 +1,194 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:test/test.dart'; +import 'package:thulium_auth/thulium_auth.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +void main() { + test( + 'counts all courses and statuses from totals rather than page rows', + () async { + final requests = []; + var landings = 0; + final auth = await _auth((request) { + requests.add(request); + final endpoint = request.url.path.split('/').last; + final count = request.url.queryParameters['wlkcid'] == 'empty-course' + ? 0 + : switch (endpoint) { + 'zyListWj' => 12, + 'zyListYjwg' => 3, + 'zyListYpg' => 8, + _ => throw StateError('Unexpected endpoint: $endpoint'), + }; + return http.Response( + jsonEncode({ + 'result': 'success', + 'object': { + 'iTotalRecords': endpoint == 'zyListYpg' ? count : '$count', + 'iTotalDisplayRecords': '$count', + 'aaData': [], + }, + }), + 200, + request: request, + ); + }, onLanding: () => landings++); + final result = await LearnHomeworkService(auth).fetchCourses(_catalog); + expect(result, hasLength(2)); + expect(result.first.counts.unsubmitted, 12); + expect(result.first.counts.submittedUngraded, 3); + expect(result.first.counts.graded, 8); + expect(result.first.counts.total, 23); + expect(result.last.counts.total, 0); + expect(landings, 1); + expect(requests, hasLength(6)); + for (final request in requests) { + expect(request.method, 'GET'); + expect(request.url.host, TsinghuaWebVpnRedirect.WEBVPN_HOST); + expect(request.url.path, contains('/b/wlxt/kczy/zy/student/index/')); + expect(request.url.queryParameters['_csrf'], 'learn-csrf'); + expect(request.url.queryParameters['size'], '5'); + expect(request.headers['cookie'], contains('JSESSIONID=learn-session')); + } + }, + ); + + test( + 'authentication failure is reconnectable and never a zero count', + () async { + final auth = await _auth( + (request) => http.Response('', 401, request: request), + ); + await expectLater( + LearnHomeworkService(auth).fetchCourses(_catalog), + throwsA(isA()), + ); + }, + ); + + test( + 'invalid totals and provider failures do not produce partial summaries', + () async { + for (final body in [ + 'not JSON', + jsonEncode({ + 'result': 'error', + 'object': {'iTotalRecords': '0'}, + }), + jsonEncode({'result': 'success', 'object': {}}), + for (final value in ['bad', '-1', 1.5, null]) + jsonEncode({ + 'result': 'success', + 'object': {'iTotalRecords': value}, + }), + ]) { + final auth = await _auth( + (request) => http.Response(body, 200, request: request), + ); + await expectLater( + LearnHomeworkService(auth).fetchCourses(_catalog), + throwsFormatException, + ); + } + }, + ); + + test('an empty catalog needs no homework requests', () async { + final auth = await _auth((_) => throw StateError('Unexpected request')); + expect( + await LearnHomeworkService(auth).fetchCourses( + LearnCourseCatalog( + userId: 'test-student', + semester: '2026-2027-1', + courses: [], + ), + ), + isEmpty, + ); + }); + + test( + 'rejects a catalog from another account before requesting data', + () async { + final auth = await _auth((_) => throw StateError('Unexpected request')); + await expectLater( + LearnHomeworkService(auth).fetchCourses( + LearnCourseCatalog( + userId: 'other-student', + semester: '2026-2027-1', + courses: [], + ), + ), + throwsStateError, + ); + }, + ); +} + +final _catalog = LearnCourseCatalog( + userId: 'test-student', + semester: '2026-2027-1', + courses: const [ + LearnCourse( + id: 'course-id', + name: 'Physics', + englishName: '', + teacherName: '', + schedule: '', + ), + LearnCourse( + id: 'empty-course', + name: 'Empty', + englishName: '', + teacherName: '', + schedule: '', + ), + ], +); + +Future _auth( + http.Response Function(http.Request) homeworkResponse, { + void Function()? onLanding, +}) async { + final transport = MockClient((request) async { + if (request.url.path == '/wengine-vpn/cookie') { + return http.Response( + 'XSRF-TOKEN=portal-csrf; Path=/;', + 200, + request: request, + ); + } + if (request.url.path.endsWith('onlineAppRedirect')) { + return http.Response( + jsonEncode({ + 'object': { + 'roamingurl': + 'https://learn.tsinghua.edu.cn/f/wlxt/index/course/student/index', + }, + }), + 200, + request: request, + ); + } + if (request.url.path.contains('/f/wlxt/index/course/student/index')) { + onLanding?.call(); + return http.Response( + '_csrf=learn-csrf', + 200, + headers: {'set-cookie': 'JSESSIONID=learn-session; Path=/; Secure'}, + request: request, + ); + } + return homeworkResponse(request); + }); + final store = MemoryAuthSessionStore(); + await store.write( + const AuthSession(userId: 'test-student', fingerprint: 'test', cookies: {}), + ); + final auth = TsinghuaAuthClient(httpClient: transport, sessionStore: store); + await auth.restore(); + return auth; +} diff --git a/packages/cli/bin/thulium.dart b/packages/cli/bin/thulium.dart index b2cf0ee..682fb8b 100644 --- a/packages/cli/bin/thulium.dart +++ b/packages/cli/bin/thulium.dart @@ -10,6 +10,7 @@ import 'package:thulium_cli/cli_course_schedule_cache_store.dart'; import 'package:thulium_cli/cli_learn_course_cache_store.dart'; import 'package:thulium_cli/cli_session_reconnect.dart'; import 'package:thulium_cli/learn_course_formatter.dart'; +import 'package:thulium_cli/learn_homework_formatter.dart'; // Uppercase snake case is the project convention for named constants. // ignore_for_file: constant_identifier_names @@ -77,6 +78,17 @@ ArgParser _buildParser() { ..addFlag('verbose', help: 'Print safe request diagnostics.') ..addFlag('refresh', help: 'Fetch courses instead of using the cache.'), ); + parser.addCommand( + 'learn-homework', + ArgParser() + ..addOption( + 'semester', + abbr: 's', + help: 'Academic semester ID (defaults to the current semester).', + ) + ..addFlag('verbose', help: 'Print safe request diagnostics.') + ..addFlag('refresh', help: 'Refresh the course list before counting.'), + ); return parser; } @@ -84,7 +96,7 @@ Future _runCommand(ArgResults command) async { final name = command.command?.name; if (name == null) { stdout.writeln( - 'Usage: thulium ', + 'Usage: thulium ', ); return; } @@ -92,12 +104,15 @@ Future _runCommand(ArgResults command) async { final store = CliAuthSessionStore(); final calendarCache = CourseScheduleCache(CliCourseScheduleCacheStore()); final learnCache = LearnCourseCache(CliLearnCourseCacheStore()); + final promptOutput = name == 'learn-homework' ? stderr : stdout; final client = TsinghuaAuthClient( sessionStore: store, credentialStore: store, - twoFactorMethodHandler: _handleTwoFactorMethod, - twoFactorCodeHandler: _readTwoFactorCode, - twoFactorTrustHandler: _askToTrustDevice, + twoFactorMethodHandler: (options) => + _handleTwoFactorMethod(options, output: promptOutput), + twoFactorCodeHandler: (verify) => + _readTwoFactorCode(verify, output: promptOutput), + twoFactorTrustHandler: () => _askToTrustDevice(output: promptOutput), trace: _verboseRequested(name, command.command!) ? (message) => stderr.writeln('[auth] $message') : null, @@ -115,11 +130,12 @@ Future _runCommand(ArgResults command) async { askToSignIn: (commandName) { final answer = _readLine( 'Sign in again to retry $commandName? [Y/n]: ', + output: promptOutput, ).toLowerCase(); return answer.isEmpty || answer == 'y' || answer == 'yes'; }, - readPassword: () => _readSecret('Password: '), - writeMessage: stdout.writeln, + readPassword: () => _readSecret('Password: ', output: promptOutput), + writeMessage: promptOutput.writeln, writeError: stderr.writeln, ); @@ -204,6 +220,41 @@ Future _runCommand(ArgResults command) async { semester: semester, ), ); + case 'learn-homework': + final session = await client.restore(); + if (session == null) { + throw StateError('Not logged in. Run `thulium login` first.'); + } + final semester = + (command.command!['semester'] as String?) ?? + AcademicSemester.forDate(DateTime.now()); + final catalogService = LearnCourseCatalogService( + client, + cache: learnCache, + ); + final homework = await reconnect.run( + commandName: 'learn-homework', + savedSession: session, + request: (isRetry) async { + final catalog = await catalogService.loadSemester( + semester, + forceRefresh: isRetry || command.command!['refresh'] as bool, + ); + if (catalogService.lastSource == LearnCourseSource.staleCache) { + stderr.writeln('Update failed; using the saved course list.'); + } + return LearnHomeworkService(client).fetchCourses(catalog); + }, + shouldReconnect: (error) => + error is PortalCsrfUnavailable || error is PortalSessionRejected, + ); + stdout.writeln( + formatLearnHomework( + homework, + studentId: session.userId, + semester: semester, + ), + ); } } @@ -339,7 +390,8 @@ Future _revealSessionCookies(AuthSession session) async { bool _verboseRequested(String commandName, ArgResults command) => (commandName == 'login' || commandName == 'schedule' || - commandName == 'learn-courses') && + commandName == 'learn-courses' || + commandName == 'learn-homework') && command['verbose'] as bool; void _printSchedule(CourseSchedule schedule) { @@ -446,9 +498,13 @@ bool _askToRetry() { return answer.isEmpty || answer == 'y' || answer == 'yes'; } -Future _handleTwoFactorMethod(TwoFactorOptions options) async { - stdout.writeln('Two-factor authentication is required.'); - stdout.writeln('Available methods:'); +Future _handleTwoFactorMethod( + TwoFactorOptions options, { + IOSink? output, +}) async { + final sink = output ?? stdout; + sink.writeln('Two-factor authentication is required.'); + sink.writeln('Available methods:'); final methods = <({TwoFactorMethod method, String label})>[]; if (options.hasWeChat) { methods.add((method: TwoFactorMethod.wechat, label: 'WeChat')); @@ -463,36 +519,44 @@ Future _handleTwoFactorMethod(TwoFactorOptions options) async { methods.add((method: TwoFactorMethod.totp, label: 'TOTP')); } for (var index = 0; index < methods.length; index++) { - stdout.writeln(' ${index + 1}. ${methods[index].label}'); + sink.writeln(' ${index + 1}. ${methods[index].label}'); } if (methods.isEmpty) { throw StateError('The account has no available two-factor methods.'); } - final choice = int.tryParse(_readLine('Choose a method: ')); + final choice = int.tryParse(_readLine('Choose a method: ', output: sink)); if (choice == null || choice < 1 || choice > methods.length) { throw const FormatException('The selected method is unavailable.'); } return methods[choice - 1].method; } -Future _readTwoFactorCode(TwoFactorCodeVerifier verifyCode) async { +Future _readTwoFactorCode( + TwoFactorCodeVerifier verifyCode, { + IOSink? output, +}) async { + final sink = output ?? stdout; // This callback runs only after SEND_CODE succeeds, so the notification is // expected to be available before the user is asked for the code. - stdout.writeln('A verification code was sent.'); + sink.writeln('A verification code was sent.'); while (true) { - final code = _readLine('Verification code: '); + final code = _readLine('Verification code: ', output: sink); if (await verifyCode(code)) return; - stdout.writeln('The verification code was not accepted. Please try again.'); + sink.writeln('The verification code was not accepted. Please try again.'); } } -Future _askToTrustDevice() async { - stdout.writeln( +Future _askToTrustDevice({IOSink? output}) async { + final sink = output ?? stdout; + sink.writeln( 'Trust this device to reduce future verification prompts? Only choose yes ' 'on a device you control.', ); - final answer = _readLine('Trust this device? [y/N]: ').toLowerCase(); + final answer = _readLine( + 'Trust this device? [y/N]: ', + output: sink, + ).toLowerCase(); return answer == 'y' || answer == 'yes'; } @@ -503,13 +567,14 @@ String _buildFingerprint() { '${Platform.localHostname}'; } -String _readLine(String prompt) { - stdout.write(prompt); +String _readLine(String prompt, {IOSink? output}) { + (output ?? stdout).write(prompt); return stdin.readLineSync()?.trim() ?? ''; } -String _readSecret(String prompt) { - stdout.write(prompt); +String _readSecret(String prompt, {IOSink? output}) { + final sink = output ?? stdout; + sink.write(prompt); if (!stdin.hasTerminal) { return stdin.readLineSync() ?? ''; } @@ -520,6 +585,6 @@ String _readSecret(String prompt) { return stdin.readLineSync() ?? ''; } finally { stdin.echoMode = echoMode; - stdout.writeln(); + sink.writeln(); } } diff --git a/packages/cli/lib/learn_homework_formatter.dart b/packages/cli/lib/learn_homework_formatter.dart new file mode 100644 index 0000000..87ff3da --- /dev/null +++ b/packages/cli/lib/learn_homework_formatter.dart @@ -0,0 +1,54 @@ +import 'dart:convert'; + +import 'package:thulium_campus/thulium_campus.dart'; + +/// Emits numeric homework totals and YAML-safe quoted course names. +String formatLearnHomework( + List courses, { + required String studentId, + required String semester, +}) { + final totals = LearnHomeworkCounts( + unsubmitted: courses.fold(0, (sum, row) => sum + row.counts.unsubmitted), + submittedUngraded: courses.fold( + 0, + (sum, row) => sum + row.counts.submittedUngraded, + ), + graded: courses.fold(0, (sum, row) => sum + row.counts.graded), + ); + final output = StringBuffer() + ..writeln('studentId: ${jsonEncode(studentId)}') + ..writeln('semester: ${jsonEncode(semester)}') + ..writeln('totals:'); + _writeCounts(output, totals, ' '); + if (courses.isEmpty) { + output.writeln('courses: []'); + } else { + output.writeln('courses:'); + for (final row in courses) { + output + ..writeln(' - courseId: ${jsonEncode(row.course.id)}') + ..writeln(' name: ${jsonEncode(row.course.name)}'); + if (row.course.englishName.isNotEmpty) { + output.writeln( + ' englishName: ${jsonEncode(row.course.englishName)}', + ); + } + output.writeln(' homework:'); + _writeCounts(output, row.counts, ' '); + } + } + return output.toString().trimRight(); +} + +void _writeCounts( + StringBuffer output, + LearnHomeworkCounts counts, + String indent, +) { + output + ..writeln('${indent}unsubmitted: ${counts.unsubmitted}') + ..writeln('${indent}submittedUngraded: ${counts.submittedUngraded}') + ..writeln('${indent}graded: ${counts.graded}') + ..writeln('${indent}total: ${counts.total}'); +} diff --git a/packages/cli/test/learn_homework_formatter_test.dart b/packages/cli/test/learn_homework_formatter_test.dart new file mode 100644 index 0000000..12bfea1 --- /dev/null +++ b/packages/cli/test/learn_homework_formatter_test.dart @@ -0,0 +1,61 @@ +import 'package:test/test.dart'; +import 'package:thulium_campus/thulium_campus.dart'; +import 'package:thulium_cli/learn_homework_formatter.dart'; + +void main() { + test('prints course counts and matching aggregate totals as YAML', () { + final output = formatLearnHomework( + const [ + LearnCourseHomework( + course: LearnCourse( + id: 'course-1', + name: 'Physics: "B"\nPart 2', + englishName: 'Physics B', + teacherName: '', + schedule: '', + ), + counts: LearnHomeworkCounts( + unsubmitted: 12, + submittedUngraded: 3, + graded: 8, + ), + ), + LearnCourseHomework( + course: LearnCourse( + id: 'course-2', + name: 'Empty', + englishName: '', + teacherName: '', + schedule: '', + ), + counts: LearnHomeworkCounts( + unsubmitted: 0, + submittedUngraded: 0, + graded: 0, + ), + ), + ], + studentId: 'test-student', + semester: '2026-2027-1', + ); + expect( + output, + startsWith( + 'studentId: "test-student"\nsemester: "2026-2027-1"\ntotals:\n unsubmitted: 12\n submittedUngraded: 3\n graded: 8\n total: 23', + ), + ); + expect(output, contains('name: "Physics: \\"B\\"\\nPart 2"')); + expect(output, contains(' homework:\n unsubmitted: 12')); + expect(output, contains(' homework:\n unsubmitted: 0')); + }); + + test('an empty semester still reports zero totals', () { + final output = formatLearnHomework( + [], + studentId: 'test-student', + semester: '2026-2027-1', + ); + expect(output, contains(' total: 0')); + expect(output, endsWith('courses: []')); + }); +} From 65b9fe2d4b7dd95625e170bb1724f083a17b2664 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AshGrey=F0=9F=A5=95?= Date: Wed, 14 Oct 2026 09:03:03 +0800 Subject: [PATCH 07/26] feat(study): show unsubmitted homework badges (#5) Fetch unsubmitted assignment totals for each course and display positive counts on Study cards. Add localized labels and loading/error states, with tests for badges, zero counts, and failed requests. --- lib/l10n/app_en.arb | 5 ++ lib/l10n/app_zh.arb | 2 + lib/l10n/app_zh_CN.arb | 2 + lib/l10n/app_zh_TW.arb | 2 + lib/l10n/generated/app_localizations.dart | 12 +++ lib/l10n/generated/app_localizations_en.dart | 9 ++ lib/l10n/generated/app_localizations_zh.dart | 24 ++++++ lib/pages/home_page.dart | 62 +++++++++++++- lib/pages/study_page.dart | 61 ++++++++++++-- packages/campus/lib/src/learn_homework.dart | 32 +++++-- packages/campus/test/learn_homework_test.dart | 24 ++++++ test/widget/study/study_page_test.dart | 83 +++++++++++++++++++ 12 files changed, 301 insertions(+), 17 deletions(-) diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index ae3cdad..e963a71 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -138,6 +138,11 @@ "studyLoadError": "Could not load courses. Try refreshing.", "studyStaleCourses": "Showing saved courses because the update failed.", "studyNoCourses": "No courses were found for this semester.", + "studyUnsubmittedHomework": "Unsubmitted assignments: {count}", + "@studyUnsubmittedHomework": { + "placeholders": { "count": { "type": "int" } } + }, + "studyHomeworkLoadError": "Could not load assignment counts. Try refreshing.", "lifeTitle": "Life", "lifeDescription": "Campus life services and everyday tools will appear here." } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 208137c..6910d38 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -138,6 +138,8 @@ "studyLoadError": "无法加载课程,请尝试刷新。", "studyStaleCourses": "更新失败,正在显示已保存的课程。", "studyNoCourses": "本学期暂无课程。", + "studyUnsubmittedHomework": "未交作业:{count} 份", + "studyHomeworkLoadError": "未交作业数量加载失败,请刷新重试。", "lifeTitle": "生活", "lifeDescription": "校园生活服务和日常工具将在这里显示。" } diff --git a/lib/l10n/app_zh_CN.arb b/lib/l10n/app_zh_CN.arb index 62a1bfa..7fb2892 100644 --- a/lib/l10n/app_zh_CN.arb +++ b/lib/l10n/app_zh_CN.arb @@ -138,6 +138,8 @@ "studyLoadError": "无法加载课程,请尝试刷新。", "studyStaleCourses": "更新失败,正在显示已保存的课程。", "studyNoCourses": "本学期暂无课程。", + "studyUnsubmittedHomework": "未交作业:{count} 份", + "studyHomeworkLoadError": "未交作业数量加载失败,请刷新重试。", "lifeTitle": "生活", "lifeDescription": "校园生活服务和日常工具将在这里显示。" } diff --git a/lib/l10n/app_zh_TW.arb b/lib/l10n/app_zh_TW.arb index 94f5181..0d4db25 100644 --- a/lib/l10n/app_zh_TW.arb +++ b/lib/l10n/app_zh_TW.arb @@ -138,6 +138,8 @@ "studyLoadError": "無法載入課程,請嘗試重新整理。", "studyStaleCourses": "更新失敗,正在顯示已儲存的課程。", "studyNoCourses": "本學期暫無課程。", + "studyUnsubmittedHomework": "未交作業:{count} 份", + "studyHomeworkLoadError": "未交作業數量載入失敗,請重新整理。", "lifeTitle": "生活", "lifeDescription": "校園生活服務和日常工具將在這裡顯示。" } diff --git a/lib/l10n/generated/app_localizations.dart b/lib/l10n/generated/app_localizations.dart index 542c95b..852450e 100644 --- a/lib/l10n/generated/app_localizations.dart +++ b/lib/l10n/generated/app_localizations.dart @@ -874,6 +874,18 @@ abstract class AppLocalizations { /// **'No courses were found for this semester.'** String get studyNoCourses; + /// No description provided for @studyUnsubmittedHomework. + /// + /// In en, this message translates to: + /// **'Unsubmitted assignments: {count}'** + String studyUnsubmittedHomework(int count); + + /// No description provided for @studyHomeworkLoadError. + /// + /// In en, this message translates to: + /// **'Could not load assignment counts. Try refreshing.'** + String get studyHomeworkLoadError; + /// No description provided for @lifeTitle. /// /// In en, this message translates to: diff --git a/lib/l10n/generated/app_localizations_en.dart b/lib/l10n/generated/app_localizations_en.dart index e3a2323..764baec 100644 --- a/lib/l10n/generated/app_localizations_en.dart +++ b/lib/l10n/generated/app_localizations_en.dart @@ -419,6 +419,15 @@ class AppLocalizationsEn extends AppLocalizations { @override String get studyNoCourses => 'No courses were found for this semester.'; + @override + String studyUnsubmittedHomework(int count) { + return 'Unsubmitted assignments: $count'; + } + + @override + String get studyHomeworkLoadError => + 'Could not load assignment counts. Try refreshing.'; + @override String get lifeTitle => 'Life'; diff --git a/lib/l10n/generated/app_localizations_zh.dart b/lib/l10n/generated/app_localizations_zh.dart index 9488499..3366263 100644 --- a/lib/l10n/generated/app_localizations_zh.dart +++ b/lib/l10n/generated/app_localizations_zh.dart @@ -402,6 +402,14 @@ class AppLocalizationsZh extends AppLocalizations { @override String get studyNoCourses => '本学期暂无课程。'; + @override + String studyUnsubmittedHomework(int count) { + return '未交作业:$count 份'; + } + + @override + String get studyHomeworkLoadError => '未交作业数量加载失败,请刷新重试。'; + @override String get lifeTitle => '生活'; @@ -807,6 +815,14 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { @override String get studyNoCourses => '本学期暂无课程。'; + @override + String studyUnsubmittedHomework(int count) { + return '未交作业:$count 份'; + } + + @override + String get studyHomeworkLoadError => '未交作业数量加载失败,请刷新重试。'; + @override String get lifeTitle => '生活'; @@ -1212,6 +1228,14 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { @override String get studyNoCourses => '本學期暫無課程。'; + @override + String studyUnsubmittedHomework(int count) { + return '未交作業:$count 份'; + } + + @override + String get studyHomeworkLoadError => '未交作業數量載入失敗,請重新整理。'; + @override String get lifeTitle => '生活'; diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index d73555a..b093470 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -50,6 +50,9 @@ final class _HomePageState extends State with WidgetsBindingObserver { bool _coursesLoading = true; bool _coursesStale = false; int _courseRequestGeneration = 0; + Map _unsubmittedHomework = const {}; + bool _homeworkLoading = false; + bool _homeworkFailed = false; @override void initState() { @@ -75,7 +78,7 @@ final class _HomePageState extends State with WidgetsBindingObserver { Future _loadCourses({bool forceRefresh = false}) async { final semester = AcademicSemester.forDate(DateTime.now()); if (_courseRequestGeneration > 0 && - _coursesLoading && + (_coursesLoading || _homeworkLoading) && !forceRefresh && semester == _semester) { return; @@ -86,6 +89,9 @@ final class _HomePageState extends State with WidgetsBindingObserver { _semester = semester; _coursesLoading = true; _courseError = null; + _unsubmittedHomework = const {}; + _homeworkLoading = false; + _homeworkFailed = false; }); try { final store = widget.sessionStore ?? SecureAuthSessionStore(); @@ -126,9 +132,13 @@ final class _HomePageState extends State with WidgetsBindingObserver { _courseCatalog = catalog; _coursesStale = service.lastSource == LearnCourseSource.staleCache; _coursesLoading = false; + _homeworkLoading = true; }); + await _loadHomework(client, credentials, session, catalog, generation); } on TwoFactorInteractionRequired { - if (mounted) widget.onSessionExpired(); + if (mounted && generation == _courseRequestGeneration) { + widget.onSessionExpired(); + } } catch (error) { debugPrint('[study] course loading failed type=${error.runtimeType}'); if (!mounted || generation != _courseRequestGeneration) return; @@ -140,6 +150,51 @@ final class _HomePageState extends State with WidgetsBindingObserver { } } + Future _loadHomework( + TsinghuaAuthClient client, + AuthCredentialStore? credentials, + AuthSession session, + LearnCourseCatalog catalog, + int generation, + ) async { + try { + final service = LearnHomeworkService(client); + Map counts; + try { + counts = await service + .fetchUnsubmittedCounts(catalog) + .timeout(_LOAD_TIMEOUT); + } on Object catch (error) { + if (error is! PortalCsrfUnavailable && + error is! PortalSessionRejected) { + rethrow; + } + if (!mounted || generation != _courseRequestGeneration) return; + if (!await _reconnectCourses(client, credentials, session)) rethrow; + counts = await service + .fetchUnsubmittedCounts(catalog) + .timeout(_LOAD_TIMEOUT); + } + if (!mounted || generation != _courseRequestGeneration) return; + setState(() { + _unsubmittedHomework = counts; + _homeworkLoading = false; + }); + } on TwoFactorInteractionRequired { + if (mounted && generation == _courseRequestGeneration) { + setState(() => _homeworkLoading = false); + widget.onSessionExpired(); + } + } on Object catch (error) { + debugPrint('[study] homework loading failed type=${error.runtimeType}'); + if (!mounted || generation != _courseRequestGeneration) return; + setState(() { + _homeworkLoading = false; + _homeworkFailed = true; + }); + } + } + Future _reconnectCourses( TsinghuaAuthClient client, AuthCredentialStore? store, @@ -249,6 +304,9 @@ final class _HomePageState extends State with WidgetsBindingObserver { isLoading: _coursesLoading, isStale: _coursesStale, error: _courseError, + unsubmittedHomework: _unsubmittedHomework, + homeworkLoading: _homeworkLoading, + homeworkFailed: _homeworkFailed, onRefresh: () => unawaited(_loadCourses(forceRefresh: true)), ), ), diff --git a/lib/pages/study_page.dart b/lib/pages/study_page.dart index 91f6cb4..50b336f 100644 --- a/lib/pages/study_page.dart +++ b/lib/pages/study_page.dart @@ -12,6 +12,9 @@ final class StudyPage extends StatelessWidget { required this.isStale, required this.error, required this.onRefresh, + this.unsubmittedHomework = const {}, + this.homeworkLoading = false, + this.homeworkFailed = false, super.key, }); @@ -21,6 +24,9 @@ final class StudyPage extends StatelessWidget { final bool isStale; final Object? error; final VoidCallback onRefresh; + final Map unsubmittedHomework; + final bool homeworkLoading; + final bool homeworkFailed; @override Widget build(BuildContext context) { @@ -61,17 +67,26 @@ final class StudyPage extends StatelessWidget { style: context.theme.typography.lg, ), ), + if (homeworkLoading) ...[ + const FCircularProgress(size: FCircularProgressSizeVariant.xs), + const SizedBox(width: 8), + ], Tooltip( message: l10n.studyRefresh, child: FButton.icon( variant: FButtonVariant.ghost, - onPress: isLoading ? null : onRefresh, + onPress: isLoading || homeworkLoading ? null : onRefresh, child: const Icon(Icons.refresh), ), ), ], ), Text(semester, style: context.theme.typography.sm), + if (homeworkFailed) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(l10n.studyHomeworkLoadError), + ), if (isStale) Padding( padding: const EdgeInsets.only(top: 8), @@ -106,13 +121,43 @@ final class StudyPage extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - Text( - locale == 'en' && course.englishName.isNotEmpty - ? course.englishName - : course.name, - style: courseTitleStyle.copyWith( - fontWeight: FontWeight.bold, - ), + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Text( + locale == 'en' && course.englishName.isNotEmpty + ? course.englishName + : course.name, + style: courseTitleStyle.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ), + if (!homeworkFailed && + (unsubmittedHomework[course.id] ?? 0) > 0) ...[ + const SizedBox(width: 8), + Semantics( + label: l10n.studyUnsubmittedHomework( + unsubmittedHomework[course.id]!, + ), + excludeSemantics: true, + child: Tooltip( + message: l10n.studyUnsubmittedHomework( + unsubmittedHomework[course.id]!, + ), + excludeFromSemantics: true, + child: FBadge( + key: ValueKey('homework-badge-${course.id}'), + variant: FBadgeVariant.destructive, + child: Text( + '${unsubmittedHomework[course.id]}', + ), + ), + ), + ), + ], + ], ), if (course.teacherName.isNotEmpty || course.schedule.isNotEmpty) ...[ diff --git a/packages/campus/lib/src/learn_homework.dart b/packages/campus/lib/src/learn_homework.dart index 833e168..0535845 100644 --- a/packages/campus/lib/src/learn_homework.dart +++ b/packages/campus/lib/src/learn_homework.dart @@ -30,17 +30,24 @@ final class LearnHomeworkService { final TsinghuaAuthClient _authClient; - Future> fetchCourses( + /// Fetches only Wj totals for course reminders, without graded-list requests. + Future> fetchUnsubmittedCounts( LearnCourseCatalog catalog, ) async { - if (_authClient.session?.userId != catalog.userId) { - throw StateError('Restore the course catalog account first.'); - } + _validateCatalog(catalog); + if (catalog.courses.isEmpty) return const {}; + final csrf = await LearnPlatformSession(_authClient).open(); + final counts = {}; for (final course in catalog.courses) { - if (course.id.isEmpty) { - throw const FormatException('A course has no learning platform ID.'); - } + counts[course.id] = await _fetchCount(course.id, 'zyListWj', csrf); } + return Map.unmodifiable(counts); + } + + Future> fetchCourses( + LearnCourseCatalog catalog, + ) async { + _validateCatalog(catalog); if (catalog.courses.isEmpty) return const []; final csrf = await LearnPlatformSession(_authClient).open(); final result = []; @@ -64,6 +71,17 @@ final class LearnHomeworkService { return result; } + void _validateCatalog(LearnCourseCatalog catalog) { + if (_authClient.session?.userId != catalog.userId) { + throw StateError('Restore the course catalog account first.'); + } + for (final course in catalog.courses) { + if (course.id.isEmpty) { + throw const FormatException('A course has no learning platform ID.'); + } + } + } + Future _fetchCount(String courseId, String endpoint, String csrf) async { // The index route is captured for Wj. Reusing that prefix for Yjwg/Ypg // is inferred from the sibling endpoint names; OneTHU confirms those diff --git a/packages/campus/test/learn_homework_test.dart b/packages/campus/test/learn_homework_test.dart index 6c566b7..f861ba3 100644 --- a/packages/campus/test/learn_homework_test.dart +++ b/packages/campus/test/learn_homework_test.dart @@ -7,6 +7,30 @@ import 'package:thulium_auth/thulium_auth.dart'; import 'package:thulium_campus/thulium_campus.dart'; void main() { + test('course reminders request only unsubmitted totals', () async { + final requests = []; + final auth = await _auth((request) { + requests.add(request); + expect(request.url.path, endsWith('/index/zyListWj')); + final count = request.url.queryParameters['wlkcid'] == 'course-id' + ? 9 + : 0; + return http.Response( + jsonEncode({ + 'result': 'success', + 'object': {'iTotalRecords': '$count', 'aaData': []}, + }), + 200, + request: request, + ); + }); + expect(await LearnHomeworkService(auth).fetchUnsubmittedCounts(_catalog), { + 'course-id': 9, + 'empty-course': 0, + }); + expect(requests, hasLength(2)); + }); + test( 'counts all courses and statuses from totals rather than page rows', () async { diff --git a/test/widget/study/study_page_test.dart b/test/widget/study/study_page_test.dart index 9d028be..a8a205f 100644 --- a/test/widget/study/study_page_test.dart +++ b/test/widget/study/study_page_test.dart @@ -6,6 +6,89 @@ import 'package:thulium/pages/study_page.dart'; import 'package:thulium_campus/thulium_campus.dart'; void main() { + testWidgets('course badges show only positive, available homework counts', ( + tester, + ) async { + tester.view.physicalSize = const Size(320, 800); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final catalog = LearnCourseCatalog( + userId: 'student', + semester: '2026-2027-1', + courses: const [ + LearnCourse( + id: 'physics', + name: '大学物理', + englishName: 'A long physics course name that wraps on mobile', + teacherName: 'Teacher', + schedule: 'Room 101', + ), + LearnCourse( + id: 'math', + name: 'Math', + englishName: '', + teacherName: '', + schedule: '', + ), + ], + ); + Future show(Map counts, {bool failed = false}) async { + await tester.pumpWidget( + MaterialApp( + locale: const Locale('en'), + localizationsDelegates: [ + ...AppLocalizations.localizationsDelegates, + ...FLocalizations.localizationsDelegates, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => + FTheme(data: FThemes.neutral.light.touch, child: child!), + home: Scaffold( + body: StudyPage( + semester: catalog.semester, + catalog: catalog, + isLoading: false, + isStale: false, + error: null, + onRefresh: () {}, + unsubmittedHomework: counts, + homeworkFailed: failed, + ), + ), + ), + ); + await tester.pumpAndSettle(); + } + + await show({'physics': 12, 'math': 0}); + expect(find.byType(FBadge), findsOneWidget); + expect( + find.byKey(const ValueKey('homework-badge-physics')), + findsOneWidget, + ); + expect(find.byKey(const ValueKey('homework-badge-math')), findsNothing); + expect(find.byTooltip('Unsubmitted assignments: 12'), findsOneWidget); + final title = find.text(catalog.courses.first.englishName); + expect( + tester.getTopRight(find.byType(FBadge)).dx, + greaterThan(tester.getTopRight(title).dx), + ); + expect(tester.takeException(), isNull); + + await show({'physics': 0, 'math': 0}); + expect(find.byType(FBadge), findsNothing); + await show({}); + expect(find.byType(FBadge), findsNothing); + await show({'physics': 12}, failed: true); + expect(find.byType(FBadge), findsNothing); + expect( + find.text('Could not load assignment counts. Try refreshing.'), + findsOneWidget, + ); + expect(title, findsOneWidget); + }); + testWidgets('reserves shortcut space and displays localized course titles', ( tester, ) async { From b861616dafe78790b40b16ba8d251090566551fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AshGrey=F0=9F=A5=95?= Date: Thu, 22 Oct 2026 08:46:37 +0800 Subject: [PATCH 08/26] feat(homework): add cached assignment overview (#5) Persist account- and semester-scoped assignment snapshots and refresh them on app entry, resume, and manual refresh. Show course-linked deadlines and urgency countdowns on the first tab, with loading, stale-data, error, and empty states. Add localized labels, theme-aware status colors, and UI coverage. --- README.md | 6 + lib/app.dart | 11 +- .../secure_learn_homework_cache_store.dart | 33 + lib/homework/homework_presentation.dart | 53 ++ lib/homework/homework_theme.dart | 45 ++ lib/homework/homework_urgency.dart | 78 +++ lib/l10n/app_en.arb | 43 +- lib/l10n/app_zh.arb | 37 +- lib/l10n/app_zh_CN.arb | 37 +- lib/l10n/app_zh_TW.arb | 37 +- lib/l10n/generated/app_localizations.dart | 210 ++++++ lib/l10n/generated/app_localizations_en.dart | 125 ++++ lib/l10n/generated/app_localizations_zh.dart | 351 ++++++++++ lib/pages/home_page.dart | 160 +++-- lib/pages/study_page.dart | 7 + lib/widgets/app_bottom_navigation.dart | 47 ++ lib/widgets/homework_overview_card.dart | 646 ++++++++++++++++++ lib/widgets/scrolling_badge.dart | 194 ++++++ packages/campus/lib/src/learn_homework.dart | 123 +++- .../campus/lib/src/learn_homework_cache.dart | 134 ++++ packages/campus/lib/thulium_campus.dart | 1 + .../test/learn_homework_cache_test.dart | 112 +++ packages/campus/test/learn_homework_test.dart | 64 ++ test/support/homework_preview.dart | 30 + test/unit/homework/homework_urgency_test.dart | 137 ++++ ...ecure_learn_homework_cache_store_test.dart | 34 + test/widget/app/widget_test.dart | 17 +- test/widget/homework/homework_cache_test.dart | 121 ++++ .../homework/homework_overview_card_test.dart | 256 +++++++ .../homework_redesign_capture_test.dart | 103 +++ 30 files changed, 3198 insertions(+), 54 deletions(-) create mode 100644 lib/auth/secure_learn_homework_cache_store.dart create mode 100644 lib/homework/homework_presentation.dart create mode 100644 lib/homework/homework_theme.dart create mode 100644 lib/homework/homework_urgency.dart create mode 100644 lib/widgets/app_bottom_navigation.dart create mode 100644 lib/widgets/homework_overview_card.dart create mode 100644 lib/widgets/scrolling_badge.dart create mode 100644 packages/campus/lib/src/learn_homework_cache.dart create mode 100644 packages/campus/test/learn_homework_cache_test.dart create mode 100644 test/support/homework_preview.dart create mode 100644 test/unit/homework/homework_urgency_test.dart create mode 100644 test/unit/homework/secure_learn_homework_cache_store_test.dart create mode 100644 test/widget/homework/homework_cache_test.dart create mode 100644 test/widget/homework/homework_overview_card_test.dart create mode 100644 test/widget/homework/homework_redesign_capture_test.dart diff --git a/README.md b/README.md index 62a7e5d..2ca12c4 100644 --- a/README.md +++ b/README.md @@ -87,6 +87,12 @@ come from the server's total-record metadata, not the first five returned rows. Diagnostics and reconnection messages go to stderr, keeping stdout valid YAML. If any count cannot be fetched, the command fails instead of reporting it as zero. +The app persists unsubmitted assignments and course badge counts in secure +storage, scoped to the account and semester. Saved data appears while a live +update runs; an offline or failed update retains it with a notice. Every app +entry, resume, and manual refresh requests current assignments. Logout clears +the snapshot. Deadlines are stored as UTC instants and countdowns are recalculated. + When a protected CLI request reports an expired session, the CLI tries the saved credentials, then offers an interactive sign-in if needed. A successful reconnection retries the original request once. diff --git a/lib/app.dart b/lib/app.dart index 3619ab8..546f980 100644 --- a/lib/app.dart +++ b/lib/app.dart @@ -6,7 +6,9 @@ import 'package:thulium_auth/thulium_auth.dart'; import 'auth/secure_auth_session_store.dart'; import 'auth/secure_course_schedule_cache_store.dart'; import 'auth/secure_learn_course_cache_store.dart'; +import 'auth/secure_learn_homework_cache_store.dart'; import 'pages/home_page.dart'; +import 'homework/homework_theme.dart'; import 'pages/welcome_page.dart'; /// The root application widget owns global locale and theme state. @@ -93,6 +95,11 @@ final class _ThuliumAppState extends State { } catch (error) { debugPrint('Thulium course cache removal failed: $error'); } + try { + await SecureLearnHomeworkCacheStore().clear(); + } catch (error) { + debugPrint('Thulium homework cache removal failed: $error'); + } } if (mounted) setState(() => _hasSession = false); @@ -101,8 +108,8 @@ final class _ThuliumAppState extends State { @override Widget build(BuildContext context) { - final lightTheme = FThemes.neutral.light.touch; - final darkTheme = FThemes.neutral.dark.touch; + final lightTheme = withHomeworkTheme(FThemes.neutral.light.touch); + final darkTheme = withHomeworkTheme(FThemes.neutral.dark.touch); return MaterialApp( title: 'Thulium', diff --git a/lib/auth/secure_learn_homework_cache_store.dart b/lib/auth/secure_learn_homework_cache_store.dart new file mode 100644 index 0000000..059cfdb --- /dev/null +++ b/lib/auth/secure_learn_homework_cache_store.dart @@ -0,0 +1,33 @@ +// ignore_for_file: constant_identifier_names + +import 'package:flutter/foundation.dart' + show defaultTargetPlatform, TargetPlatform; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +const _HOMEWORK_CACHE_KEY = 'thulium.learn.homework.cache.v1'; + +/// Protects assignment data separately from course catalogs and credentials. +final class SecureLearnHomeworkCacheStore implements LearnHomeworkCacheStore { + SecureLearnHomeworkCacheStore({FlutterSecureStorage? storage}) + : _storage = storage ?? _createStorage(); + + final FlutterSecureStorage _storage; + + static FlutterSecureStorage _createStorage() => + defaultTargetPlatform == TargetPlatform.macOS + ? const FlutterSecureStorage( + mOptions: MacOsOptions(usesDataProtectionKeychain: false), + ) + : const FlutterSecureStorage(); + + @override + Future read() => _storage.read(key: _HOMEWORK_CACHE_KEY); + + @override + Future write(String value) => + _storage.write(key: _HOMEWORK_CACHE_KEY, value: value); + + @override + Future clear() => _storage.delete(key: _HOMEWORK_CACHE_KEY); +} diff --git a/lib/homework/homework_presentation.dart b/lib/homework/homework_presentation.dart new file mode 100644 index 0000000..f494d02 --- /dev/null +++ b/lib/homework/homework_presentation.dart @@ -0,0 +1,53 @@ +import 'package:flutter/widgets.dart'; +import 'package:forui/forui.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +/// Presentation-only capabilities. Null means the data layer cannot supply it. +/// Callbacks must perform real operations; the list never changes submission +/// state optimistically or invents grading metadata. +final class HomeworkActions { + const HomeworkActions({this.openWeb, this.remindLater, this.markSubmitted}); + final Future Function(LearnHomework)? openWeb; + final Future Function(LearnHomework)? remindLater; + final Future Function(LearnHomework)? markSubmitted; +} + +double textContrast(Color foreground, Color background) { + final a = foreground.computeLuminance(); + final b = background.computeLuminance(); + return (a > b ? a + .05 : b + .05) / (a > b ? b + .05 : a + .05); +} + +/// Choose only existing theme tokens; do not introduce a second palette. +Color readableSecondary(FThemeData theme) => + textContrast(theme.colors.mutedForeground, theme.colors.background) >= 4.5 + ? theme.colors.mutedForeground + : theme.colors.foreground; + +Color destructiveBadgeText(FThemeData theme) { + return badgeTextOn(theme, theme.colors.destructive); +} + +Color badgeTextOn(FThemeData theme, Color background) { + final candidates = [ + theme.colors.destructiveForeground, + theme.colors.foreground, + theme.colors.background, + ]; + return candidates.reduce( + (a, b) => + textContrast(a, background) >= textContrast(b, background) ? a : b, + ); +} + +/// Flat resting surface; interaction feedback continues to use Forui variants. +FItemStyleDelta homeworkTileStyle(FThemeData theme) => FItemStyleDelta.delta( + backgroundColor: FVariantsValueDelta.delta([ + FVariantValueDeltaOperation.base(theme.colors.background), + ]), + contentDecoration: FVariantsDelta.delta([ + FVariantOperation.base( + DecorationDelta.shapeDelta(color: theme.colors.background), + ), + ]), +); diff --git a/lib/homework/homework_theme.dart b/lib/homework/homework_theme.dart new file mode 100644 index 0000000..35aad87 --- /dev/null +++ b/lib/homework/homework_theme.dart @@ -0,0 +1,45 @@ +import 'package:flutter/material.dart' show ThemeExtension; +import 'package:flutter/widgets.dart'; +import 'package:forui/forui.dart'; + +/// Homework status tokens. Light mode preserves the original yellow and green; +/// dark mode uses their lighter counterparts for legibility. +class HomeworkPalette extends ThemeExtension { + const HomeworkPalette({required this.yellow, required this.green}); + + factory HomeworkPalette.forBrightness(Brightness brightness) => + brightness == Brightness.dark + ? const HomeworkPalette( + yellow: Color(0xFFFACC15), + green: Color(0xFF4ADE80), + ) + : const HomeworkPalette( + yellow: Color(0xFFA16207), + green: Color(0xFF15803D), + ); + + final Color yellow; + final Color green; + + @override + HomeworkPalette copyWith({Color? yellow, Color? green}) => HomeworkPalette( + yellow: yellow ?? this.yellow, + green: green ?? this.green, + ); + + @override + HomeworkPalette lerp(covariant HomeworkPalette? other, double t) => + other == null + ? this + : HomeworkPalette( + yellow: Color.lerp(yellow, other.yellow, t)!, + green: Color.lerp(green, other.green, t)!, + ); +} + +FThemeData withHomeworkTheme(FThemeData theme) => theme.copyWith( + extensions: { + ...theme.extensions.where((extension) => extension is! HomeworkPalette), + HomeworkPalette.forBrightness(theme.colors.brightness), + }, +); diff --git a/lib/homework/homework_urgency.dart b/lib/homework/homework_urgency.dart new file mode 100644 index 0000000..6761289 --- /dev/null +++ b/lib/homework/homework_urgency.dart @@ -0,0 +1,78 @@ +import 'package:thulium_campus/thulium_campus.dart'; + +/// Time boundaries are inclusive; an assignment due now is already overdue. +enum HomeworkUrgency { + expired, + withinHour, + withinDay, + withinThreeDays, + later, + unknown, +} + +enum HomeworkGroup { today, thisWeek, later, overdue } + +DateTime beijingTime(DateTime instant) => + instant.toUtc().add(const Duration(hours: 8)); + +HomeworkUrgency homeworkUrgency(DateTime? deadline, DateTime now) { + if (deadline == null) return HomeworkUrgency.unknown; + final remaining = deadline.difference(now); + if (remaining <= Duration.zero) return HomeworkUrgency.expired; + if (remaining <= const Duration(hours: 1)) return HomeworkUrgency.withinHour; + if (remaining <= const Duration(hours: 24)) return HomeworkUrgency.withinDay; + if (remaining <= const Duration(days: 3)) { + return HomeworkUrgency.withinThreeDays; + } + return HomeworkUrgency.later; +} + +List sortHomeworkByUrgency( + Iterable assignments, + DateTime now, +) => assignments.toList() + ..sort((left, right) { + final leftExpired = left.deadline != null && !left.deadline!.isAfter(now); + final rightExpired = + right.deadline != null && !right.deadline!.isAfter(now); + if (leftExpired != rightExpired) return leftExpired ? 1 : -1; + final a = left.deadline; + final b = right.deadline; + if (a == null && b != null) return 1; + if (a != null && b == null) return -1; + final date = a != null && b != null ? a.compareTo(b) : 0; + if (date != 0) return date; + final course = left.course.id.compareTo(right.course.id); + return course != 0 ? course : left.id.compareTo(right.id); + }); + +HomeworkGroup homeworkGroup(DateTime? deadline, DateTime now) { + if (deadline == null) return HomeworkGroup.later; + if (!deadline.isAfter(now)) return HomeworkGroup.overdue; + final today = beijingTime(now); + final date = beijingTime(deadline); + final tomorrow = DateTime.utc(today.year, today.month, today.day + 1); + if (date.isBefore(tomorrow)) return HomeworkGroup.today; + final nextMonday = DateTime.utc( + today.year, + today.month, + today.day + (8 - today.weekday), + ); + return date.isBefore(nextMonday) + ? HomeworkGroup.thisWeek + : HomeworkGroup.later; +} + +Map> groupHomework( + Iterable assignments, + DateTime now, +) { + final groups = >{}; + for (final assignment in sortHomeworkByUrgency(assignments, now)) { + (groups[homeworkGroup(assignment.deadline, now)] ??= []).add(assignment); + } + return { + for (final group in HomeworkGroup.values) + if (groups.containsKey(group)) group: groups[group]!, + }; +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index e963a71..f2110f2 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -143,6 +143,47 @@ "placeholders": { "count": { "type": "int" } } }, "studyHomeworkLoadError": "Could not load assignment counts. Try refreshing.", + "homeworkTitle": "Upcoming assignments", + "homeworkEmpty": "All done", + "homeworkStale": "Could not update assignments; showing saved data.", + "homeworkLoadError": "Could not load assignments. Try refreshing.", + "homeworkExpired": "Overdue", + "homeworkUnknownDeadline": "Deadline unavailable", + "homeworkDueAt": "Due: {deadline} (Beijing time)", + "homeworkRemainingDays": "{days}d {hours}h left", + "homeworkRemainingHours": "{hours}h {minutes}m left", + "homeworkRemainingMinutes": "{minutes}m left", + "@homeworkDueAt": {"placeholders":{"deadline":{"type":"String"}}}, + "@homeworkRemainingDays": {"placeholders":{"days":{"type":"int"},"hours":{"type":"int"}}}, + "@homeworkRemainingHours": {"placeholders":{"hours":{"type":"int"},"minutes":{"type":"int"}}}, + "@homeworkRemainingMinutes": {"placeholders":{"minutes":{"type":"int"}}}, "lifeTitle": "Life", - "lifeDescription": "Campus life services and everyday tools will appear here." + "lifeDescription": "Campus life services and everyday tools will appear here.", + "homeworkTimezone": "All deadlines use Beijing time (UTC+8).", + "homeworkRefresh": "Refresh assignments", + "homeworkNeverUpdated": "Not updated yet", + "homeworkUpdatedNow": "Updated just now", + "homeworkUpdatedMinutes": "Updated {minutes, plural, =1{1 minute ago} other{{minutes} minutes ago}}", + "homeworkLoading": "Loading assignments", + "homeworkGroupOverdue": "Overdue", + "homeworkGroupToday": "Today", + "homeworkGroupThisWeek": "This week", + "homeworkGroupLater": "Later", + "homeworkWithinHour": "Within 1h", + "homeworkWithinDay": "Within 24h", + "homeworkWithinThreeDays": "Within 3 days", + "homeworkLater": "Later", + "homeworkDeadline": "Due {deadline}", + "homeworkRowTimezone": "Beijing time", + "homeworkNoGrade": "Not graded", + "homeworkDetails": "Assignment details", + "homeworkBack": "Back", + "homeworkActions": "Assignment actions", + "homeworkOpenWeb": "Open website", + "homeworkRemindLater": "Remind me later", + "homeworkMarkSubmitted": "Mark as submitted", + "homeworkActionsUnavailable": "Actions without a connected provider are unavailable.", + "homeworkActionFailed": "Action failed. Please try again.", + "@homeworkUpdatedMinutes": {"placeholders": {"minutes": {"type": "int"}}}, + "@homeworkDeadline": {"placeholders": {"deadline": {"type": "String"}}} } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 6910d38..7b08ef3 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -140,6 +140,41 @@ "studyNoCourses": "本学期暂无课程。", "studyUnsubmittedHomework": "未交作业:{count} 份", "studyHomeworkLoadError": "未交作业数量加载失败,请刷新重试。", + "homeworkTitle": "近期作业", + "homeworkEmpty": "全部完成", + "homeworkStale": "作业更新失败,正在显示已保存的数据。", + "homeworkLoadError": "作业加载失败,请刷新重试。", + "homeworkExpired": "已逾期", + "homeworkUnknownDeadline": "截止时间未知", + "homeworkDueAt": "截止:{deadline}(北京时间)", + "homeworkRemainingDays": "剩余 {days} 天 {hours} 小时", + "homeworkRemainingHours": "剩余 {hours} 小时 {minutes} 分钟", + "homeworkRemainingMinutes": "剩余 {minutes} 分钟", "lifeTitle": "生活", - "lifeDescription": "校园生活服务和日常工具将在这里显示。" + "lifeDescription": "校园生活服务和日常工具将在这里显示。", + "homeworkTimezone": "截止时间均为北京时间(UTC+8)", + "homeworkRefresh": "刷新作业", + "homeworkNeverUpdated": "尚未更新", + "homeworkUpdatedNow": "刚刚更新", + "homeworkUpdatedMinutes": "更新于 {minutes} 分钟前", + "homeworkLoading": "正在加载作业", + "homeworkGroupOverdue": "已逾期", + "homeworkGroupToday": "今天", + "homeworkGroupThisWeek": "本周", + "homeworkGroupLater": "之后", + "homeworkWithinHour": "1 小时内", + "homeworkWithinDay": "24 小时内", + "homeworkWithinThreeDays": "3 天内", + "homeworkLater": "更晚", + "homeworkDeadline": "截止 {deadline}", + "homeworkRowTimezone": "北京时间", + "homeworkNoGrade": "不计分", + "homeworkDetails": "作业详情", + "homeworkBack": "返回", + "homeworkActions": "作业操作", + "homeworkOpenWeb": "打开网页", + "homeworkRemindLater": "稍后提醒", + "homeworkMarkSubmitted": "标记已提交", + "homeworkActionsUnavailable": "未接入的操作当前不可用。", + "homeworkActionFailed": "操作失败,请重试。" } diff --git a/lib/l10n/app_zh_CN.arb b/lib/l10n/app_zh_CN.arb index 7fb2892..2b5c46c 100644 --- a/lib/l10n/app_zh_CN.arb +++ b/lib/l10n/app_zh_CN.arb @@ -140,6 +140,41 @@ "studyNoCourses": "本学期暂无课程。", "studyUnsubmittedHomework": "未交作业:{count} 份", "studyHomeworkLoadError": "未交作业数量加载失败,请刷新重试。", + "homeworkTitle": "近期作业", + "homeworkEmpty": "全部完成", + "homeworkStale": "作业更新失败,正在显示已保存的数据。", + "homeworkLoadError": "作业加载失败,请刷新重试。", + "homeworkExpired": "已逾期", + "homeworkUnknownDeadline": "截止时间未知", + "homeworkDueAt": "截止:{deadline}(北京时间)", + "homeworkRemainingDays": "剩余 {days} 天 {hours} 小时", + "homeworkRemainingHours": "剩余 {hours} 小时 {minutes} 分钟", + "homeworkRemainingMinutes": "剩余 {minutes} 分钟", "lifeTitle": "生活", - "lifeDescription": "校园生活服务和日常工具将在这里显示。" + "lifeDescription": "校园生活服务和日常工具将在这里显示。", + "homeworkTimezone": "截止时间均为北京时间(UTC+8)", + "homeworkRefresh": "刷新作业", + "homeworkNeverUpdated": "尚未更新", + "homeworkUpdatedNow": "刚刚更新", + "homeworkUpdatedMinutes": "更新于 {minutes} 分钟前", + "homeworkLoading": "正在加载作业", + "homeworkGroupOverdue": "已逾期", + "homeworkGroupToday": "今天", + "homeworkGroupThisWeek": "本周", + "homeworkGroupLater": "之后", + "homeworkWithinHour": "1 小时内", + "homeworkWithinDay": "24 小时内", + "homeworkWithinThreeDays": "3 天内", + "homeworkLater": "更晚", + "homeworkDeadline": "截止 {deadline}", + "homeworkRowTimezone": "北京时间", + "homeworkNoGrade": "不计分", + "homeworkDetails": "作业详情", + "homeworkBack": "返回", + "homeworkActions": "作业操作", + "homeworkOpenWeb": "打开网页", + "homeworkRemindLater": "稍后提醒", + "homeworkMarkSubmitted": "标记已提交", + "homeworkActionsUnavailable": "未接入的操作当前不可用。", + "homeworkActionFailed": "操作失败,请重试。" } diff --git a/lib/l10n/app_zh_TW.arb b/lib/l10n/app_zh_TW.arb index 0d4db25..819979e 100644 --- a/lib/l10n/app_zh_TW.arb +++ b/lib/l10n/app_zh_TW.arb @@ -140,6 +140,41 @@ "studyNoCourses": "本學期暫無課程。", "studyUnsubmittedHomework": "未交作業:{count} 份", "studyHomeworkLoadError": "未交作業數量載入失敗,請重新整理。", + "homeworkTitle": "近期作業", + "homeworkEmpty": "全部完成", + "homeworkStale": "作業更新失敗,正在顯示已儲存的資料。", + "homeworkLoadError": "作業載入失敗,請重新整理。", + "homeworkExpired": "已逾期", + "homeworkUnknownDeadline": "截止時間未知", + "homeworkDueAt": "截止:{deadline}(北京時間)", + "homeworkRemainingDays": "剩餘 {days} 天 {hours} 小時", + "homeworkRemainingHours": "剩餘 {hours} 小時 {minutes} 分鐘", + "homeworkRemainingMinutes": "剩餘 {minutes} 分鐘", "lifeTitle": "生活", - "lifeDescription": "校園生活服務和日常工具將在這裡顯示。" + "lifeDescription": "校園生活服務和日常工具將在這裡顯示。", + "homeworkTimezone": "截止時間均為北京時間(UTC+8)", + "homeworkRefresh": "重新整理作業", + "homeworkNeverUpdated": "尚未更新", + "homeworkUpdatedNow": "剛剛更新", + "homeworkUpdatedMinutes": "更新於 {minutes} 分鐘前", + "homeworkLoading": "正在載入作業", + "homeworkGroupOverdue": "已逾期", + "homeworkGroupToday": "今天", + "homeworkGroupThisWeek": "本週", + "homeworkGroupLater": "之後", + "homeworkWithinHour": "1 小時內", + "homeworkWithinDay": "24 小時內", + "homeworkWithinThreeDays": "3 天內", + "homeworkLater": "更晚", + "homeworkDeadline": "截止 {deadline}", + "homeworkRowTimezone": "北京時間", + "homeworkNoGrade": "不計分", + "homeworkDetails": "作業詳情", + "homeworkBack": "返回", + "homeworkActions": "作業操作", + "homeworkOpenWeb": "開啟網頁", + "homeworkRemindLater": "稍後提醒", + "homeworkMarkSubmitted": "標記已提交", + "homeworkActionsUnavailable": "未接入的操作目前無法使用。", + "homeworkActionFailed": "操作失敗,請重試。" } diff --git a/lib/l10n/generated/app_localizations.dart b/lib/l10n/generated/app_localizations.dart index 852450e..6006d91 100644 --- a/lib/l10n/generated/app_localizations.dart +++ b/lib/l10n/generated/app_localizations.dart @@ -886,6 +886,66 @@ abstract class AppLocalizations { /// **'Could not load assignment counts. Try refreshing.'** String get studyHomeworkLoadError; + /// No description provided for @homeworkTitle. + /// + /// In en, this message translates to: + /// **'Upcoming assignments'** + String get homeworkTitle; + + /// No description provided for @homeworkEmpty. + /// + /// In en, this message translates to: + /// **'All done'** + String get homeworkEmpty; + + /// No description provided for @homeworkStale. + /// + /// In en, this message translates to: + /// **'Could not update assignments; showing saved data.'** + String get homeworkStale; + + /// No description provided for @homeworkLoadError. + /// + /// In en, this message translates to: + /// **'Could not load assignments. Try refreshing.'** + String get homeworkLoadError; + + /// No description provided for @homeworkExpired. + /// + /// In en, this message translates to: + /// **'Overdue'** + String get homeworkExpired; + + /// No description provided for @homeworkUnknownDeadline. + /// + /// In en, this message translates to: + /// **'Deadline unavailable'** + String get homeworkUnknownDeadline; + + /// No description provided for @homeworkDueAt. + /// + /// In en, this message translates to: + /// **'Due: {deadline} (Beijing time)'** + String homeworkDueAt(String deadline); + + /// No description provided for @homeworkRemainingDays. + /// + /// In en, this message translates to: + /// **'{days}d {hours}h left'** + String homeworkRemainingDays(int days, int hours); + + /// No description provided for @homeworkRemainingHours. + /// + /// In en, this message translates to: + /// **'{hours}h {minutes}m left'** + String homeworkRemainingHours(int hours, int minutes); + + /// No description provided for @homeworkRemainingMinutes. + /// + /// In en, this message translates to: + /// **'{minutes}m left'** + String homeworkRemainingMinutes(int minutes); + /// No description provided for @lifeTitle. /// /// In en, this message translates to: @@ -897,6 +957,156 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Campus life services and everyday tools will appear here.'** String get lifeDescription; + + /// No description provided for @homeworkTimezone. + /// + /// In en, this message translates to: + /// **'All deadlines use Beijing time (UTC+8).'** + String get homeworkTimezone; + + /// No description provided for @homeworkRefresh. + /// + /// In en, this message translates to: + /// **'Refresh assignments'** + String get homeworkRefresh; + + /// No description provided for @homeworkNeverUpdated. + /// + /// In en, this message translates to: + /// **'Not updated yet'** + String get homeworkNeverUpdated; + + /// No description provided for @homeworkUpdatedNow. + /// + /// In en, this message translates to: + /// **'Updated just now'** + String get homeworkUpdatedNow; + + /// No description provided for @homeworkUpdatedMinutes. + /// + /// In en, this message translates to: + /// **'Updated {minutes, plural, =1{1 minute ago} other{{minutes} minutes ago}}'** + String homeworkUpdatedMinutes(int minutes); + + /// No description provided for @homeworkLoading. + /// + /// In en, this message translates to: + /// **'Loading assignments'** + String get homeworkLoading; + + /// No description provided for @homeworkGroupOverdue. + /// + /// In en, this message translates to: + /// **'Overdue'** + String get homeworkGroupOverdue; + + /// No description provided for @homeworkGroupToday. + /// + /// In en, this message translates to: + /// **'Today'** + String get homeworkGroupToday; + + /// No description provided for @homeworkGroupThisWeek. + /// + /// In en, this message translates to: + /// **'This week'** + String get homeworkGroupThisWeek; + + /// No description provided for @homeworkGroupLater. + /// + /// In en, this message translates to: + /// **'Later'** + String get homeworkGroupLater; + + /// No description provided for @homeworkWithinHour. + /// + /// In en, this message translates to: + /// **'Within 1h'** + String get homeworkWithinHour; + + /// No description provided for @homeworkWithinDay. + /// + /// In en, this message translates to: + /// **'Within 24h'** + String get homeworkWithinDay; + + /// No description provided for @homeworkWithinThreeDays. + /// + /// In en, this message translates to: + /// **'Within 3 days'** + String get homeworkWithinThreeDays; + + /// No description provided for @homeworkLater. + /// + /// In en, this message translates to: + /// **'Later'** + String get homeworkLater; + + /// No description provided for @homeworkDeadline. + /// + /// In en, this message translates to: + /// **'Due {deadline}'** + String homeworkDeadline(String deadline); + + /// No description provided for @homeworkRowTimezone. + /// + /// In en, this message translates to: + /// **'Beijing time'** + String get homeworkRowTimezone; + + /// No description provided for @homeworkNoGrade. + /// + /// In en, this message translates to: + /// **'Not graded'** + String get homeworkNoGrade; + + /// No description provided for @homeworkDetails. + /// + /// In en, this message translates to: + /// **'Assignment details'** + String get homeworkDetails; + + /// No description provided for @homeworkBack. + /// + /// In en, this message translates to: + /// **'Back'** + String get homeworkBack; + + /// No description provided for @homeworkActions. + /// + /// In en, this message translates to: + /// **'Assignment actions'** + String get homeworkActions; + + /// No description provided for @homeworkOpenWeb. + /// + /// In en, this message translates to: + /// **'Open website'** + String get homeworkOpenWeb; + + /// No description provided for @homeworkRemindLater. + /// + /// In en, this message translates to: + /// **'Remind me later'** + String get homeworkRemindLater; + + /// No description provided for @homeworkMarkSubmitted. + /// + /// In en, this message translates to: + /// **'Mark as submitted'** + String get homeworkMarkSubmitted; + + /// No description provided for @homeworkActionsUnavailable. + /// + /// In en, this message translates to: + /// **'Actions without a connected provider are unavailable.'** + String get homeworkActionsUnavailable; + + /// No description provided for @homeworkActionFailed. + /// + /// In en, this message translates to: + /// **'Action failed. Please try again.'** + String get homeworkActionFailed; } class _AppLocalizationsDelegate diff --git a/lib/l10n/generated/app_localizations_en.dart b/lib/l10n/generated/app_localizations_en.dart index 764baec..b4864cd 100644 --- a/lib/l10n/generated/app_localizations_en.dart +++ b/lib/l10n/generated/app_localizations_en.dart @@ -428,10 +428,135 @@ class AppLocalizationsEn extends AppLocalizations { String get studyHomeworkLoadError => 'Could not load assignment counts. Try refreshing.'; + @override + String get homeworkTitle => 'Upcoming assignments'; + + @override + String get homeworkEmpty => 'All done'; + + @override + String get homeworkStale => + 'Could not update assignments; showing saved data.'; + + @override + String get homeworkLoadError => 'Could not load assignments. Try refreshing.'; + + @override + String get homeworkExpired => 'Overdue'; + + @override + String get homeworkUnknownDeadline => 'Deadline unavailable'; + + @override + String homeworkDueAt(String deadline) { + return 'Due: $deadline (Beijing time)'; + } + + @override + String homeworkRemainingDays(int days, int hours) { + return '${days}d ${hours}h left'; + } + + @override + String homeworkRemainingHours(int hours, int minutes) { + return '${hours}h ${minutes}m left'; + } + + @override + String homeworkRemainingMinutes(int minutes) { + return '${minutes}m left'; + } + @override String get lifeTitle => 'Life'; @override String get lifeDescription => 'Campus life services and everyday tools will appear here.'; + + @override + String get homeworkTimezone => 'All deadlines use Beijing time (UTC+8).'; + + @override + String get homeworkRefresh => 'Refresh assignments'; + + @override + String get homeworkNeverUpdated => 'Not updated yet'; + + @override + String get homeworkUpdatedNow => 'Updated just now'; + + @override + String homeworkUpdatedMinutes(int minutes) { + String _temp0 = intl.Intl.pluralLogic( + minutes, + locale: localeName, + other: '$minutes minutes ago', + one: '1 minute ago', + ); + return 'Updated $_temp0'; + } + + @override + String get homeworkLoading => 'Loading assignments'; + + @override + String get homeworkGroupOverdue => 'Overdue'; + + @override + String get homeworkGroupToday => 'Today'; + + @override + String get homeworkGroupThisWeek => 'This week'; + + @override + String get homeworkGroupLater => 'Later'; + + @override + String get homeworkWithinHour => 'Within 1h'; + + @override + String get homeworkWithinDay => 'Within 24h'; + + @override + String get homeworkWithinThreeDays => 'Within 3 days'; + + @override + String get homeworkLater => 'Later'; + + @override + String homeworkDeadline(String deadline) { + return 'Due $deadline'; + } + + @override + String get homeworkRowTimezone => 'Beijing time'; + + @override + String get homeworkNoGrade => 'Not graded'; + + @override + String get homeworkDetails => 'Assignment details'; + + @override + String get homeworkBack => 'Back'; + + @override + String get homeworkActions => 'Assignment actions'; + + @override + String get homeworkOpenWeb => 'Open website'; + + @override + String get homeworkRemindLater => 'Remind me later'; + + @override + String get homeworkMarkSubmitted => 'Mark as submitted'; + + @override + String get homeworkActionsUnavailable => + 'Actions without a connected provider are unavailable.'; + + @override + String get homeworkActionFailed => 'Action failed. Please try again.'; } diff --git a/lib/l10n/generated/app_localizations_zh.dart b/lib/l10n/generated/app_localizations_zh.dart index 3366263..95c37b9 100644 --- a/lib/l10n/generated/app_localizations_zh.dart +++ b/lib/l10n/generated/app_localizations_zh.dart @@ -410,11 +410,128 @@ class AppLocalizationsZh extends AppLocalizations { @override String get studyHomeworkLoadError => '未交作业数量加载失败,请刷新重试。'; + @override + String get homeworkTitle => '近期作业'; + + @override + String get homeworkEmpty => '全部完成'; + + @override + String get homeworkStale => '作业更新失败,正在显示已保存的数据。'; + + @override + String get homeworkLoadError => '作业加载失败,请刷新重试。'; + + @override + String get homeworkExpired => '已逾期'; + + @override + String get homeworkUnknownDeadline => '截止时间未知'; + + @override + String homeworkDueAt(String deadline) { + return '截止:$deadline(北京时间)'; + } + + @override + String homeworkRemainingDays(int days, int hours) { + return '剩余 $days 天 $hours 小时'; + } + + @override + String homeworkRemainingHours(int hours, int minutes) { + return '剩余 $hours 小时 $minutes 分钟'; + } + + @override + String homeworkRemainingMinutes(int minutes) { + return '剩余 $minutes 分钟'; + } + @override String get lifeTitle => '生活'; @override String get lifeDescription => '校园生活服务和日常工具将在这里显示。'; + + @override + String get homeworkTimezone => '截止时间均为北京时间(UTC+8)'; + + @override + String get homeworkRefresh => '刷新作业'; + + @override + String get homeworkNeverUpdated => '尚未更新'; + + @override + String get homeworkUpdatedNow => '刚刚更新'; + + @override + String homeworkUpdatedMinutes(int minutes) { + return '更新于 $minutes 分钟前'; + } + + @override + String get homeworkLoading => '正在加载作业'; + + @override + String get homeworkGroupOverdue => '已逾期'; + + @override + String get homeworkGroupToday => '今天'; + + @override + String get homeworkGroupThisWeek => '本周'; + + @override + String get homeworkGroupLater => '之后'; + + @override + String get homeworkWithinHour => '1 小时内'; + + @override + String get homeworkWithinDay => '24 小时内'; + + @override + String get homeworkWithinThreeDays => '3 天内'; + + @override + String get homeworkLater => '更晚'; + + @override + String homeworkDeadline(String deadline) { + return '截止 $deadline'; + } + + @override + String get homeworkRowTimezone => '北京时间'; + + @override + String get homeworkNoGrade => '不计分'; + + @override + String get homeworkDetails => '作业详情'; + + @override + String get homeworkBack => '返回'; + + @override + String get homeworkActions => '作业操作'; + + @override + String get homeworkOpenWeb => '打开网页'; + + @override + String get homeworkRemindLater => '稍后提醒'; + + @override + String get homeworkMarkSubmitted => '标记已提交'; + + @override + String get homeworkActionsUnavailable => '未接入的操作当前不可用。'; + + @override + String get homeworkActionFailed => '操作失败,请重试。'; } /// The translations for Chinese, as used in China (`zh_CN`). @@ -823,11 +940,128 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { @override String get studyHomeworkLoadError => '未交作业数量加载失败,请刷新重试。'; + @override + String get homeworkTitle => '近期作业'; + + @override + String get homeworkEmpty => '全部完成'; + + @override + String get homeworkStale => '作业更新失败,正在显示已保存的数据。'; + + @override + String get homeworkLoadError => '作业加载失败,请刷新重试。'; + + @override + String get homeworkExpired => '已逾期'; + + @override + String get homeworkUnknownDeadline => '截止时间未知'; + + @override + String homeworkDueAt(String deadline) { + return '截止:$deadline(北京时间)'; + } + + @override + String homeworkRemainingDays(int days, int hours) { + return '剩余 $days 天 $hours 小时'; + } + + @override + String homeworkRemainingHours(int hours, int minutes) { + return '剩余 $hours 小时 $minutes 分钟'; + } + + @override + String homeworkRemainingMinutes(int minutes) { + return '剩余 $minutes 分钟'; + } + @override String get lifeTitle => '生活'; @override String get lifeDescription => '校园生活服务和日常工具将在这里显示。'; + + @override + String get homeworkTimezone => '截止时间均为北京时间(UTC+8)'; + + @override + String get homeworkRefresh => '刷新作业'; + + @override + String get homeworkNeverUpdated => '尚未更新'; + + @override + String get homeworkUpdatedNow => '刚刚更新'; + + @override + String homeworkUpdatedMinutes(int minutes) { + return '更新于 $minutes 分钟前'; + } + + @override + String get homeworkLoading => '正在加载作业'; + + @override + String get homeworkGroupOverdue => '已逾期'; + + @override + String get homeworkGroupToday => '今天'; + + @override + String get homeworkGroupThisWeek => '本周'; + + @override + String get homeworkGroupLater => '之后'; + + @override + String get homeworkWithinHour => '1 小时内'; + + @override + String get homeworkWithinDay => '24 小时内'; + + @override + String get homeworkWithinThreeDays => '3 天内'; + + @override + String get homeworkLater => '更晚'; + + @override + String homeworkDeadline(String deadline) { + return '截止 $deadline'; + } + + @override + String get homeworkRowTimezone => '北京时间'; + + @override + String get homeworkNoGrade => '不计分'; + + @override + String get homeworkDetails => '作业详情'; + + @override + String get homeworkBack => '返回'; + + @override + String get homeworkActions => '作业操作'; + + @override + String get homeworkOpenWeb => '打开网页'; + + @override + String get homeworkRemindLater => '稍后提醒'; + + @override + String get homeworkMarkSubmitted => '标记已提交'; + + @override + String get homeworkActionsUnavailable => '未接入的操作当前不可用。'; + + @override + String get homeworkActionFailed => '操作失败,请重试。'; } /// The translations for Chinese, as used in Taiwan (`zh_TW`). @@ -1236,9 +1470,126 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { @override String get studyHomeworkLoadError => '未交作業數量載入失敗,請重新整理。'; + @override + String get homeworkTitle => '近期作業'; + + @override + String get homeworkEmpty => '全部完成'; + + @override + String get homeworkStale => '作業更新失敗,正在顯示已儲存的資料。'; + + @override + String get homeworkLoadError => '作業載入失敗,請重新整理。'; + + @override + String get homeworkExpired => '已逾期'; + + @override + String get homeworkUnknownDeadline => '截止時間未知'; + + @override + String homeworkDueAt(String deadline) { + return '截止:$deadline(北京時間)'; + } + + @override + String homeworkRemainingDays(int days, int hours) { + return '剩餘 $days 天 $hours 小時'; + } + + @override + String homeworkRemainingHours(int hours, int minutes) { + return '剩餘 $hours 小時 $minutes 分鐘'; + } + + @override + String homeworkRemainingMinutes(int minutes) { + return '剩餘 $minutes 分鐘'; + } + @override String get lifeTitle => '生活'; @override String get lifeDescription => '校園生活服務和日常工具將在這裡顯示。'; + + @override + String get homeworkTimezone => '截止時間均為北京時間(UTC+8)'; + + @override + String get homeworkRefresh => '重新整理作業'; + + @override + String get homeworkNeverUpdated => '尚未更新'; + + @override + String get homeworkUpdatedNow => '剛剛更新'; + + @override + String homeworkUpdatedMinutes(int minutes) { + return '更新於 $minutes 分鐘前'; + } + + @override + String get homeworkLoading => '正在載入作業'; + + @override + String get homeworkGroupOverdue => '已逾期'; + + @override + String get homeworkGroupToday => '今天'; + + @override + String get homeworkGroupThisWeek => '本週'; + + @override + String get homeworkGroupLater => '之後'; + + @override + String get homeworkWithinHour => '1 小時內'; + + @override + String get homeworkWithinDay => '24 小時內'; + + @override + String get homeworkWithinThreeDays => '3 天內'; + + @override + String get homeworkLater => '更晚'; + + @override + String homeworkDeadline(String deadline) { + return '截止 $deadline'; + } + + @override + String get homeworkRowTimezone => '北京時間'; + + @override + String get homeworkNoGrade => '不計分'; + + @override + String get homeworkDetails => '作業詳情'; + + @override + String get homeworkBack => '返回'; + + @override + String get homeworkActions => '作業操作'; + + @override + String get homeworkOpenWeb => '開啟網頁'; + + @override + String get homeworkRemindLater => '稍後提醒'; + + @override + String get homeworkMarkSubmitted => '標記已提交'; + + @override + String get homeworkActionsUnavailable => '未接入的操作目前無法使用。'; + + @override + String get homeworkActionFailed => '操作失敗,請重試。'; } diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index b093470..bf4e0ed 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -10,7 +10,10 @@ import 'package:thulium_campus/thulium_campus.dart'; import '../auth/secure_auth_session_store.dart'; import '../auth/secure_learn_course_cache_store.dart'; +import '../auth/secure_learn_homework_cache_store.dart'; import '../widgets/language_button.dart'; +import '../widgets/app_bottom_navigation.dart'; +import '../widgets/homework_overview_card.dart'; import 'settings_page.dart'; import 'calendar_page.dart'; import 'study_page.dart'; @@ -23,6 +26,7 @@ final class HomePage extends StatefulWidget { required this.onLogout, required this.onSessionExpired, this.sessionStore, + this.homeworkCacheStore, super.key, }); @@ -31,15 +35,13 @@ final class HomePage extends StatefulWidget { final Future Function() onLogout; final VoidCallback onSessionExpired; final AuthSessionStore? sessionStore; + final LearnHomeworkCacheStore? homeworkCacheStore; @override State createState() => _HomePageState(); } final class _HomePageState extends State with WidgetsBindingObserver { - static const _HEADER_ICON_SIZE = 40.0; - static const _HEADER_TOP = 4.0; - static const _CALENDAR_TOP = _HEADER_TOP + _HEADER_ICON_SIZE + 4.0; static const _LOAD_TIMEOUT = Duration(minutes: 2); int _selectedIndex = 0; @@ -51,8 +53,18 @@ final class _HomePageState extends State with WidgetsBindingObserver { bool _coursesStale = false; int _courseRequestGeneration = 0; Map _unsubmittedHomework = const {}; + List _homeworkAssignments = const []; bool _homeworkLoading = false; bool _homeworkFailed = false; + bool _hasHomeworkSnapshot = false; + DateTime? _homeworkUpdatedAt; + String? _homeworkUserId; + late final LearnHomeworkCache? _homeworkCache = + widget.homeworkCacheStore != null + ? LearnHomeworkCache(widget.homeworkCacheStore!) + : widget.sessionStore == null + ? LearnHomeworkCache(SecureLearnHomeworkCacheStore()) + : null; @override void initState() { @@ -85,11 +97,16 @@ final class _HomePageState extends State with WidgetsBindingObserver { } final generation = ++_courseRequestGeneration; setState(() { - if (semester != _semester) _coursesStale = false; + if (semester != _semester) { + _coursesStale = false; + _unsubmittedHomework = const {}; + _homeworkAssignments = const []; + _hasHomeworkSnapshot = false; + _homeworkUpdatedAt = null; + } _semester = semester; _coursesLoading = true; _courseError = null; - _unsubmittedHomework = const {}; _homeworkLoading = false; _homeworkFailed = false; }); @@ -105,6 +122,8 @@ final class _HomePageState extends State with WidgetsBindingObserver { ); final session = await client.restore(); if (session == null) throw const PortalSessionRejected(); + await _restoreHomework(session.userId, semester, generation); + if (!mounted || generation != _courseRequestGeneration) return; final service = LearnCourseCatalogService( client, cache: widget.sessionStore == null @@ -150,6 +169,42 @@ final class _HomePageState extends State with WidgetsBindingObserver { } } + Future _restoreHomework( + String userId, + String semester, + int generation, + ) async { + if (!mounted || generation != _courseRequestGeneration) return; + if (_homeworkUserId != userId) { + setState(() { + _homeworkUserId = userId; + _unsubmittedHomework = const {}; + _homeworkAssignments = const []; + _hasHomeworkSnapshot = false; + _homeworkUpdatedAt = null; + }); + } + if (_hasHomeworkSnapshot) return; + CachedLearnHomework? cached; + try { + cached = await _homeworkCache?.readFor(userId, semester); + } on Object catch (error) { + debugPrint( + '[study] homework cache read failed type=${error.runtimeType}', + ); + } + if (cached == null || !mounted || generation != _courseRequestGeneration) { + return; + } + final snapshot = cached.snapshot; + setState(() { + _unsubmittedHomework = snapshot.counts; + _homeworkAssignments = snapshot.assignments; + _homeworkUpdatedAt = cached!.fetchedAt; + _hasHomeworkSnapshot = true; + }); + } + Future _loadHomework( TsinghuaAuthClient client, AuthCredentialStore? credentials, @@ -159,10 +214,10 @@ final class _HomePageState extends State with WidgetsBindingObserver { ) async { try { final service = LearnHomeworkService(client); - Map counts; + LearnHomeworkSnapshot snapshot; try { - counts = await service - .fetchUnsubmittedCounts(catalog) + snapshot = await service + .fetchUnsubmittedHomework(catalog) .timeout(_LOAD_TIMEOUT); } on Object catch (error) { if (error is! PortalCsrfUnavailable && @@ -171,15 +226,32 @@ final class _HomePageState extends State with WidgetsBindingObserver { } if (!mounted || generation != _courseRequestGeneration) return; if (!await _reconnectCourses(client, credentials, session)) rethrow; - counts = await service - .fetchUnsubmittedCounts(catalog) + snapshot = await service + .fetchUnsubmittedHomework(catalog) .timeout(_LOAD_TIMEOUT); } if (!mounted || generation != _courseRequestGeneration) return; + final fetchedAt = DateTime.now(); setState(() { - _unsubmittedHomework = counts; + _homeworkUpdatedAt = fetchedAt; + _unsubmittedHomework = snapshot.counts; + _homeworkAssignments = snapshot.assignments; + _hasHomeworkSnapshot = true; _homeworkLoading = false; }); + try { + await _homeworkCache?.writeFor( + session.userId, + catalog.semester, + snapshot, + fetchedAt, + ); + } on Object catch (error) { + // Persistence failure cannot replace a successfully fetched result. + debugPrint( + '[study] homework cache write failed type=${error.runtimeType}', + ); + } } on TwoFactorInteractionRequired { if (mounted && generation == _courseRequestGeneration) { setState(() => _homeworkLoading = false); @@ -223,38 +295,41 @@ final class _HomePageState extends State with WidgetsBindingObserver { (title: l10n.studyTitle, description: l10n.studyDescription), (title: l10n.lifeTitle, description: l10n.lifeDescription), ]; - final labels = [l10n.eventsTab, l10n.plansTab, l10n.studyTab, l10n.lifeTab]; - final icons = [ - Icons.event_outlined, - Icons.calendar_month_outlined, - Icons.menu_book_outlined, - Icons.home_outlined, - ]; + final theme = context.theme; + final headerIconSize = theme.style.sizes.tile; + final headerTop = theme.style.pagePadding.top; + final calendarTop = headerTop + headerIconSize + headerTop; return FScaffold( - footer: FBottomNavigationBar( + footer: AppBottomNavigation( index: _selectedIndex, onChange: (index) => setState(() { _selectedIndex = index; if (index == 1) _hasOpenedPlans = true; }), - children: [ - for (var index = 0; index < labels.length; index++) - MergeSemantics( - child: Semantics( - label: labels[index], - button: true, - selected: index == _selectedIndex, - child: FBottomNavigationBarItem(icon: Icon(icons[index])), - ), - ), - ], ), child: SafeArea( bottom: false, child: Stack( children: [ - if (_selectedIndex != 1 && _selectedIndex != 2) + if (_selectedIndex == 0) + Positioned.fill( + top: calendarTop, + child: HomeworkOverviewCard( + assignments: _homeworkAssignments, + isLoading: _coursesLoading || _homeworkLoading, + hasSnapshot: _hasHomeworkSnapshot, + updatedAt: _homeworkUpdatedAt, + isStale: + _hasHomeworkSnapshot && + (_homeworkFailed || _courseError != null), + failed: + !_hasHomeworkSnapshot && + (_homeworkFailed || _courseError != null), + onRefresh: () => _loadCourses(forceRefresh: true), + ), + ), + if (_selectedIndex == 3) Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 640), @@ -280,7 +355,7 @@ final class _HomePageState extends State with WidgetsBindingObserver { ), if (_hasOpenedPlans) Positioned.fill( - top: _CALENDAR_TOP, + top: calendarTop, child: Offstage( offstage: _selectedIndex != 1, child: Padding( @@ -295,7 +370,7 @@ final class _HomePageState extends State with WidgetsBindingObserver { ), if (_selectedIndex == 2) Positioned.fill( - top: _CALENDAR_TOP, + top: calendarTop, child: StudyPage( semester: _semester, catalog: _courseCatalog?.semester == _semester @@ -306,22 +381,25 @@ final class _HomePageState extends State with WidgetsBindingObserver { error: _courseError, unsubmittedHomework: _unsubmittedHomework, homeworkLoading: _homeworkLoading, - homeworkFailed: _homeworkFailed, + homeworkFailed: _homeworkFailed && !_hasHomeworkSnapshot, + homeworkStale: + _hasHomeworkSnapshot && + (_homeworkFailed || _courseError != null), onRefresh: () => unawaited(_loadCourses(forceRefresh: true)), ), ), Positioned( - top: _HEADER_TOP, - left: 8, + top: headerTop, + left: theme.style.pagePadding.left, child: Row( mainAxisSize: MainAxisSize.min, children: [ LanguageButton( onSelected: widget.onLocaleSelected, - buttonSize: _HEADER_ICON_SIZE, + buttonSize: headerIconSize, ), SizedBox.square( - dimension: _HEADER_ICON_SIZE, + dimension: headerIconSize, child: IconButton( tooltip: l10n.theme, padding: EdgeInsets.zero, @@ -338,10 +416,10 @@ final class _HomePageState extends State with WidgetsBindingObserver { ), ), Positioned( - top: _HEADER_TOP, - right: 8, + top: headerTop, + right: theme.style.pagePadding.right, child: SizedBox.square( - dimension: _HEADER_ICON_SIZE, + dimension: headerIconSize, child: IconButton( tooltip: l10n.settingsTitle, padding: EdgeInsets.zero, diff --git a/lib/pages/study_page.dart b/lib/pages/study_page.dart index 50b336f..6594a04 100644 --- a/lib/pages/study_page.dart +++ b/lib/pages/study_page.dart @@ -15,6 +15,7 @@ final class StudyPage extends StatelessWidget { this.unsubmittedHomework = const {}, this.homeworkLoading = false, this.homeworkFailed = false, + this.homeworkStale = false, super.key, }); @@ -27,6 +28,7 @@ final class StudyPage extends StatelessWidget { final Map unsubmittedHomework; final bool homeworkLoading; final bool homeworkFailed; + final bool homeworkStale; @override Widget build(BuildContext context) { @@ -82,6 +84,11 @@ final class StudyPage extends StatelessWidget { ], ), Text(semester, style: context.theme.typography.sm), + if (homeworkStale) + Padding( + padding: const EdgeInsets.only(top: 8), + child: Text(l10n.homeworkStale), + ), if (homeworkFailed) Padding( padding: const EdgeInsets.only(top: 8), diff --git a/lib/widgets/app_bottom_navigation.dart b/lib/widgets/app_bottom_navigation.dart new file mode 100644 index 0000000..de2a9e6 --- /dev/null +++ b/lib/widgets/app_bottom_navigation.dart @@ -0,0 +1,47 @@ +import 'package:flutter/material.dart' show Icons; +import 'package:flutter/widgets.dart'; +import 'package:forui/forui.dart'; + +import '../l10n/generated/app_localizations.dart'; + +/// Shared shell navigation, with visible labels and explicit selection semantics. +class AppBottomNavigation extends StatelessWidget { + const AppBottomNavigation({ + required this.index, + required this.onChange, + super.key, + }); + + final int index; + final ValueChanged onChange; + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final labels = [l10n.eventsTab, l10n.plansTab, l10n.studyTab, l10n.lifeTab]; + const icons = [ + Icons.event_outlined, + Icons.calendar_month_outlined, + Icons.menu_book_outlined, + Icons.home_outlined, + ]; + return FBottomNavigationBar( + safeAreaBottom: true, + index: index, + onChange: onChange, + children: [ + for (var item = 0; item < labels.length; item++) + MergeSemantics( + child: Semantics( + button: true, + selected: index == item, + child: FBottomNavigationBarItem( + icon: Icon(icons[item]), + label: Text(labels[item]), + ), + ), + ), + ], + ); + } +} diff --git a/lib/widgets/homework_overview_card.dart b/lib/widgets/homework_overview_card.dart new file mode 100644 index 0000000..83c9116 --- /dev/null +++ b/lib/widgets/homework_overview_card.dart @@ -0,0 +1,646 @@ +import 'dart:async'; + +import 'package:flutter/material.dart' show Icons, RefreshIndicator; +import 'package:flutter/widgets.dart'; +import 'package:forui/forui.dart'; +import 'package:intl/intl.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +import '../homework/homework_presentation.dart'; +import '../homework/homework_urgency.dart'; +import '../homework/homework_theme.dart'; +import 'scrolling_badge.dart'; +import '../l10n/generated/app_localizations.dart'; + +/// Presentation of the existing snapshot. No network, cache, or submission +/// state is owned here. The historic class name is retained for its callers. +final class HomeworkOverviewCard extends StatefulWidget { + const HomeworkOverviewCard({ + required this.assignments, + required this.isLoading, + required this.failed, + required this.onRefresh, + this.hasSnapshot = false, + this.isStale = false, + this.updatedAt, + this.now, + this.deviceTimeZoneOffset, + this.actions = const HomeworkActions(), + this.countsTowardGrade, + super.key, + }); + + final List assignments; + final bool isLoading; + final bool failed; + final FutureOr Function() onRefresh; + final bool hasSnapshot; + final bool isStale; + final DateTime? updatedAt; + final DateTime? now; + final Duration? deviceTimeZoneOffset; + final HomeworkActions actions; + + /// Unknown grading policy stays null; only explicit false shows a badge. + final bool? Function(LearnHomework)? countsTowardGrade; + + @override + State createState() => _HomeworkOverviewCardState(); +} + +final class _HomeworkOverviewCardState extends State + with WidgetsBindingObserver { + Timer? _timer; + late DateTime _now; + late DateTime _enteredAt; + + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addObserver(this); + _enter(); + } + + void _enter() { + _enteredAt = _now = widget.now ?? DateTime.now(); + _scheduleUrgentUpdates(); + } + + void _scheduleUrgentUpdates() { + _timer?.cancel(); + if (widget.now != null || + !widget.assignments.any( + (item) => + homeworkUrgency(item.deadline, _now) == + HomeworkUrgency.withinHour, + )) { + return; + } + _timer = Timer.periodic(const Duration(minutes: 1), (_) { + if (!mounted) return; + setState(() => _now = DateTime.now()); + if (!widget.assignments.any( + (item) => + homeworkUrgency(item.deadline, _now) == HomeworkUrgency.withinHour, + )) { + _timer?.cancel(); + } + }); + } + + @override + void didUpdateWidget(covariant HomeworkOverviewCard oldWidget) { + super.didUpdateWidget(oldWidget); + _enter(); + } + + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed && mounted) setState(_enter); + } + + @override + void dispose() { + _timer?.cancel(); + WidgetsBinding.instance.removeObserver(this); + super.dispose(); + } + + Future _refresh() async => await widget.onRefresh(); + + @override + Widget build(BuildContext context) { + final theme = context.theme; + final l10n = AppLocalizations.of(context)!; + final gap = theme.style.pagePadding.top; + final groups = groupHomework(widget.assignments, _now); + return ColoredBox( + color: theme.colors.background, + child: FScaffold( + childPad: false, + header: FHeader( + title: Text( + l10n.homeworkTitle, + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ), + child: RefreshIndicator( + onRefresh: _refresh, + color: theme.colors.foreground, + backgroundColor: theme.colors.background, + semanticsLabel: l10n.homeworkRefresh, + child: ListView( + key: const ValueKey('homework-scroll'), + physics: const AlwaysScrollableScrollPhysics(), + padding: theme.style.pagePadding, + children: [ + Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: gap, + runSpacing: gap, + children: [ + _UpdateAge(updatedAt: widget.updatedAt, now: widget.now), + ConstrainedBox( + constraints: BoxConstraints( + minHeight: theme.style.sizes.tile, + minWidth: theme.style.sizes.tile, + ), + child: FButton.icon( + size: FButtonSizeVariant.lg, + variant: FButtonVariant.ghost, + semanticsLabel: l10n.homeworkRefresh, + onPress: widget.isLoading + ? null + : () => unawaited(_refresh()), + child: const Icon(Icons.refresh), + ), + ), + ], + ), + SizedBox(height: gap), + if (widget.isStale) ...[ + FAlert(title: Text(l10n.homeworkStale)), + SizedBox(height: gap), + ], + if (widget.isLoading && !widget.hasSnapshot) + _HomeworkSkeleton(label: l10n.homeworkLoading) + else if (widget.failed) ...[ + FAlert(title: Text(l10n.homeworkLoadError)), + SizedBox(height: gap), + FButton( + onPress: () => unawaited(_refresh()), + child: Flexible( + child: Text( + l10n.calendarRetry, + textAlign: TextAlign.center, + ), + ), + ), + ] else if (groups.isEmpty) + Padding( + padding: theme.style.pagePadding, + child: Text(l10n.homeworkEmpty, style: theme.typography.lg), + ) + else + for (final entry in groups.entries) ...[ + SizedBox(height: gap), + SizedBox( + width: double.infinity, + child: FTileGroup( + intrinsicWidth: false, + physics: const NeverScrollableScrollPhysics(), + divider: FItemDivider.full, + label: Row( + children: [ + Expanded(child: Text(_groupName(l10n, entry.key))), + FBadge( + variant: FBadgeVariant.outline, + child: Text( + NumberFormat.decimalPattern( + l10n.localeName, + ).format(entry.value.length), + ), + ), + ], + ), + children: [ + for (final item in entry.value) + FTile.raw( + style: homeworkTileStyle(theme), + key: ValueKey( + 'homework-${item.course.id}-${item.id}', + ), + onPress: () => _showDetails(context, item), + onLongPress: () => _showActions(context, item), + child: ConstrainedBox( + constraints: BoxConstraints( + minHeight: theme.style.sizes.tile, + ), + child: Padding( + padding: theme.style.pagePadding, + child: _AssignmentContent( + homework: item, + now: _rowNow(item), + deviceOffset: + widget.deviceTimeZoneOffset ?? + DateTime.now().timeZoneOffset, + countsTowardGrade: widget.countsTowardGrade + ?.call(item), + ), + ), + ), + ), + ], + ), + ), + SizedBox(height: gap), + ], + ], + ), + ), + ), + ); + } + + DateTime _rowNow(LearnHomework item) => + homeworkUrgency(item.deadline, _enteredAt) == HomeworkUrgency.withinHour + ? _now + : _enteredAt; + + Future _showDetails( + BuildContext context, + LearnHomework homework, + ) async { + await Navigator.of(context).push( + PageRouteBuilder( + pageBuilder: (context, _, _) { + final l10n = AppLocalizations.of(context)!; + final theme = context.theme; + return FScaffold( + header: FHeader.nested( + title: Text(l10n.homeworkDetails), + prefixes: [ + FButton.icon( + size: FButtonSizeVariant.lg, + variant: FButtonVariant.ghost, + semanticsLabel: l10n.homeworkBack, + onPress: () => Navigator.of(context).pop(), + child: const Icon(FLucideIcons.arrowLeft), + ), + ], + ), + child: ListView( + padding: theme.style.pagePadding, + children: [ + FTileGroup( + intrinsicWidth: false, + physics: const NeverScrollableScrollPhysics(), + children: [ + FTile.raw( + style: homeworkTileStyle(theme), + child: Padding( + padding: theme.style.pagePadding, + child: _AssignmentContent( + homework: homework, + now: widget.now ?? DateTime.now(), + deviceOffset: + widget.deviceTimeZoneOffset ?? + DateTime.now().timeZoneOffset, + countsTowardGrade: widget.countsTowardGrade?.call( + homework, + ), + fullTitle: true, + ), + ), + ), + ], + ), + SizedBox(height: theme.style.pagePadding.top), + FButton( + variant: FButtonVariant.outline, + onPress: () => _showActions(context, homework), + child: Flexible( + child: Text( + l10n.homeworkActions, + textAlign: TextAlign.center, + ), + ), + ), + ], + ), + ); + }, + ), + ); + if (mounted) setState(_enter); + } + + void _showActions(BuildContext context, LearnHomework homework) { + final l10n = AppLocalizations.of(context)!; + final options = [ + (l10n.homeworkOpenWeb, widget.actions.openWeb), + (l10n.homeworkRemindLater, widget.actions.remindLater), + (l10n.homeworkMarkSubmitted, widget.actions.markSubmitted), + ]; + unawaited( + showFSheet( + context: context, + side: FLayout.btt, + useSafeArea: true, + builder: (sheetContext) => SingleChildScrollView( + padding: sheetContext.theme.style.pagePadding, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + l10n.homeworkActions, + style: sheetContext.theme.typography.lg, + ), + if (options.any((option) => option.$2 == null)) ...[ + SizedBox(height: sheetContext.theme.style.pagePadding.top), + FAlert(title: Text(l10n.homeworkActionsUnavailable)), + ], + for (final option in options) ...[ + SizedBox(height: sheetContext.theme.style.pagePadding.top), + FButton( + size: FButtonSizeVariant.lg, + variant: FButtonVariant.outline, + onPress: option.$2 == null + ? null + : () { + Navigator.of(sheetContext).pop(); + unawaited(_execute(context, option.$2!, homework)); + }, + child: Flexible( + child: Text(option.$1, textAlign: TextAlign.center), + ), + ), + ], + ], + ), + ), + ), + ); + } + + Future _execute( + BuildContext context, + Future Function(LearnHomework) action, + LearnHomework homework, + ) async { + try { + await action(homework); + } on Object { + if (!context.mounted) return; + final l10n = AppLocalizations.of(context)!; + await showFDialog( + context: context, + builder: (context, _, animation) => FDialog.adaptive( + animation: animation, + title: Text(l10n.homeworkActionFailed), + actions: [ + FButton( + onPress: () => Navigator.of(context).pop(), + child: Flexible( + child: Text(l10n.confirmAction, textAlign: TextAlign.center), + ), + ), + ], + ), + ); + } + } +} + +class _AssignmentContent extends StatelessWidget { + const _AssignmentContent({ + required this.homework, + required this.now, + required this.deviceOffset, + this.countsTowardGrade, + this.fullTitle = false, + }); + final LearnHomework homework; + final DateTime now; + final Duration deviceOffset; + final bool? countsTowardGrade; + final bool fullTitle; + + @override + Widget build(BuildContext context) { + final theme = context.theme; + final l10n = AppLocalizations.of(context)!; + final gap = theme.style.pagePadding.top; + final urgency = homeworkUrgency(homework.deadline, now); + final palette = + theme.extensions.whereType().firstOrNull ?? + HomeworkPalette.forBrightness(theme.colors.brightness); + final statusColor = switch (urgency) { + HomeworkUrgency.expired || + HomeworkUrgency.unknown => readableSecondary(theme), + HomeworkUrgency.withinHour || + HomeworkUrgency.withinDay => theme.colors.destructive, + HomeworkUrgency.withinThreeDays => palette.yellow, + HomeworkUrgency.later => palette.green, + }; + final muted = + urgency == HomeworkUrgency.expired || + urgency == HomeworkUrgency.unknown; + final background = muted ? theme.colors.secondary : statusColor; + final foreground = muted + ? theme.colors.secondaryForeground + : badgeTextOn(theme, background); + final badgeStyle = theme.badgeStyles.secondary.copyWith( + decoration: DecorationDelta.shapeDelta(color: background), + contentStyle: FBadgeContentStyleDelta.delta( + labelTextStyle: TextStyleDelta.delta(color: foreground), + ), + ); + final locale = l10n.localeName; + final deadline = homework.deadline; + final date = deadline == null + ? l10n.homeworkUnknownDeadline + : l10n.homeworkDeadline( + DateFormat.yMMMd(locale).add_Hm().format(beijingTime(deadline)), + ); + final course = + Localizations.localeOf(context).languageCode == 'en' && + homework.course.englishName.isNotEmpty + ? homework.course.englishName + : homework.course.name; + final secondary = theme.typography.xs.copyWith( + color: readableSecondary(theme), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + flex: 3, + child: Text( + homework.title, + maxLines: fullTitle ? null : 2, + overflow: fullTitle ? null : TextOverflow.ellipsis, + style: theme.typography.sm.copyWith( + fontWeight: FontWeight.w600, + ), + ), + ), + SizedBox(width: gap), + Flexible( + flex: 2, + child: Align( + alignment: AlignmentDirectional.topEnd, + child: ScrollingBadge( + label: _urgencyName(l10n, urgency), + style: badgeStyle, + ), + ), + ), + ], + ), + SizedBox(height: gap), + Text(course, style: secondary), + SizedBox(height: gap), + Wrap( + spacing: gap, + runSpacing: gap, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + deviceOffset == const Duration(hours: 8) + ? date + : '$date · ${l10n.homeworkRowTimezone}', + style: secondary, + ), + if (deadline != null && deadline.isAfter(now)) + Text( + _countdown(l10n, deadline, now), + key: ValueKey('homework-countdown-${homework.id}'), + style: secondary.copyWith( + fontFeatures: const [FontFeature.tabularFigures()], + ), + ), + if (countsTowardGrade == false) + FBadge( + variant: FBadgeVariant.outline, + child: Text(l10n.homeworkNoGrade), + ), + ], + ), + ], + ); + } +} + +class _HomeworkSkeleton extends StatelessWidget { + const _HomeworkSkeleton({required this.label}); + final String label; + @override + Widget build(BuildContext context) { + final theme = context.theme; + final gap = theme.style.pagePadding.top; + return Semantics( + label: label, + child: ExcludeSemantics( + child: Column( + children: [ + for (var index = 0; index < 3; index++) + Padding( + padding: theme.style.pagePadding, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + for (final size in [ + theme.typography.sm.fontSize!, + theme.typography.xs.fontSize!, + theme.typography.xs.fontSize!, + ]) ...[ + Container( + height: size, + width: index.isEven + ? double.infinity + : theme.style.sizes.tile * 4, + decoration: BoxDecoration( + color: theme.colors.muted, + borderRadius: theme.style.borderRadius.sm, + ), + ), + SizedBox(height: gap), + ], + ], + ), + ), + ], + ), + ), + ); + } +} + +class _UpdateAge extends StatefulWidget { + const _UpdateAge({required this.updatedAt, this.now}); + final DateTime? updatedAt; + final DateTime? now; + @override + State<_UpdateAge> createState() => _UpdateAgeState(); +} + +class _UpdateAgeState extends State<_UpdateAge> { + Timer? _timer; + @override + void initState() { + super.initState(); + if (widget.now == null) { + _timer = Timer.periodic(const Duration(minutes: 1), (_) { + if (mounted) setState(() {}); + }); + } + } + + @override + void dispose() { + _timer?.cancel(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final updatedAt = widget.updatedAt; + final minutes = updatedAt == null + ? null + : (widget.now ?? DateTime.now()).difference(updatedAt).inMinutes; + final label = minutes == null + ? l10n.homeworkNeverUpdated + : minutes <= 0 + ? l10n.homeworkUpdatedNow + : l10n.homeworkUpdatedMinutes(minutes); + return Text( + label, + style: context.theme.typography.xs.copyWith( + color: readableSecondary(context.theme), + fontFeatures: const [FontFeature.tabularFigures()], + ), + ); + } +} + +String _groupName(AppLocalizations l10n, HomeworkGroup group) => + switch (group) { + HomeworkGroup.overdue => l10n.homeworkGroupOverdue, + HomeworkGroup.today => l10n.homeworkGroupToday, + HomeworkGroup.thisWeek => l10n.homeworkGroupThisWeek, + HomeworkGroup.later => l10n.homeworkGroupLater, + }; +String _urgencyName(AppLocalizations l10n, HomeworkUrgency urgency) => + switch (urgency) { + HomeworkUrgency.expired => l10n.homeworkExpired, + HomeworkUrgency.withinHour => l10n.homeworkWithinHour, + HomeworkUrgency.withinDay => l10n.homeworkWithinDay, + HomeworkUrgency.withinThreeDays => l10n.homeworkWithinThreeDays, + HomeworkUrgency.later => l10n.homeworkLater, + HomeworkUrgency.unknown => l10n.homeworkUnknownDeadline, + }; +String _countdown(AppLocalizations l10n, DateTime? deadline, DateTime now) { + if (deadline == null) return l10n.homeworkUnknownDeadline; + final remaining = deadline.difference(now); + if (remaining <= Duration.zero) return l10n.homeworkExpired; + if (remaining.inDays > 0) { + return l10n.homeworkRemainingDays(remaining.inDays, remaining.inHours % 24); + } + if (remaining.inHours > 0) { + return l10n.homeworkRemainingHours( + remaining.inHours, + remaining.inMinutes % 60, + ); + } + return l10n.homeworkRemainingMinutes( + (remaining.inMilliseconds / 60000).ceil(), + ); +} diff --git a/lib/widgets/scrolling_badge.dart b/lib/widgets/scrolling_badge.dart new file mode 100644 index 0000000..987811d --- /dev/null +++ b/lib/widgets/scrolling_badge.dart @@ -0,0 +1,194 @@ +import 'dart:math' as math; + +import 'package:flutter/widgets.dart'; +import 'package:forui/forui.dart'; + +/// A single-line badge. Overflowing labels loop continuously right to left. +/// Reduced-motion users can scroll the label manually instead. +class ScrollingBadge extends StatelessWidget { + const ScrollingBadge({required this.label, required this.style, super.key}); + final String label; + final FBadgeStyle style; + + @override + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) { + final padding = style.contentStyle.padding.resolve( + Directionality.of(context), + ); + final textStyle = style.contentStyle.labelTextStyle; + final painter = TextPainter( + text: TextSpan(text: label, style: textStyle), + textDirection: Directionality.of(context), + textScaler: MediaQuery.textScalerOf(context), + maxLines: 1, + )..layout(); + final textWidth = painter.width.ceilToDouble(); + final height = painter.height.ceilToDouble(); + painter.dispose(); + final width = math.min( + textWidth + padding.horizontal, + constraints.maxWidth, + ); + final viewport = math.max(0.0, width - padding.horizontal); + return Align( + alignment: AlignmentDirectional.topEnd, + child: SizedBox( + width: width, + height: height + padding.vertical, + child: FBadge.raw( + style: style, + builder: (_, _) => SizedBox( + width: width, + height: height + padding.vertical, + child: Padding( + padding: padding, + child: Semantics( + label: label, + child: ExcludeSemantics( + child: _ScrollingLabel( + label: label, + style: textStyle, + width: textWidth, + height: height, + gap: context.theme.style.pagePadding.horizontal, + distance: math.max(0.0, textWidth - viewport), + reduceMotion: MediaQuery.disableAnimationsOf(context), + ), + ), + ), + ), + ), + ), + ), + ); + }, + ); +} + +class _ScrollingLabel extends StatefulWidget { + const _ScrollingLabel({ + required this.label, + required this.style, + required this.width, + required this.height, + required this.gap, + required this.distance, + required this.reduceMotion, + }); + final String label; + final TextStyle style; + final double width; + final double height; + final double gap; + final double distance; + final bool reduceMotion; + @override + State<_ScrollingLabel> createState() => _ScrollingLabelState(); +} + +class _ScrollingLabelState extends State<_ScrollingLabel> + with SingleTickerProviderStateMixin { + late final AnimationController _controller = AnimationController( + vsync: this, + duration: const Duration(seconds: 4), + ); + + @override + void initState() { + super.initState(); + _restart(); + } + + @override + void didUpdateWidget(covariant _ScrollingLabel oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.label != widget.label || + oldWidget.distance != widget.distance || + oldWidget.gap != widget.gap || + oldWidget.reduceMotion != widget.reduceMotion) { + _restart(); + } + } + + void _restart() { + _controller.stop(); + _controller.value = 0; + // Keep the same reading speed when text scaling changes the label width. + _controller.duration = Duration( + milliseconds: ((widget.width + widget.gap) * 35).round(), + ); + if (widget.distance > 0 && !widget.reduceMotion) _controller.repeat(); + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + final text = SizedBox( + width: widget.width, + height: widget.height, + child: Text( + widget.label, + style: widget.style, + maxLines: 1, + softWrap: false, + ), + ); + if (widget.distance <= 0) return text; + if (widget.reduceMotion) { + return SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: text, + ); + } + final period = widget.width + widget.gap; + return ClipRect( + child: AnimatedBuilder( + animation: _controller, + child: OverflowBox( + alignment: AlignmentDirectional.centerStart, + minWidth: period + widget.width, + maxWidth: period + widget.width, + child: SizedBox( + width: period + widget.width, + height: widget.height, + child: Stack( + clipBehavior: Clip.none, + children: [ + Positioned(left: 0, top: 0, child: text), + Positioned( + left: period, + top: 0, + child: SizedBox( + width: widget.width, + height: widget.height, + child: RichText( + text: TextSpan( + text: widget.label, + style: DefaultTextStyle.of( + context, + ).style.merge(widget.style), + ), + textScaler: MediaQuery.textScalerOf(context), + maxLines: 1, + softWrap: false, + ), + ), + ), + ], + ), + ), + ), + builder: (_, child) => Transform.translate( + offset: Offset(-period * _controller.value, 0), + child: child, + ), + ), + ); + } +} diff --git a/packages/campus/lib/src/learn_homework.dart b/packages/campus/lib/src/learn_homework.dart index 0535845..889505e 100644 --- a/packages/campus/lib/src/learn_homework.dart +++ b/packages/campus/lib/src/learn_homework.dart @@ -22,6 +22,32 @@ final class LearnCourseHomework { final LearnHomeworkCounts counts; } +/// An unsubmitted assignment; deadline is an absolute UTC instant when known. +final class LearnHomework { + const LearnHomework({ + required this.id, + required this.course, + required this.title, + required this.deadline, + }); + + final String id; + final LearnCourse course; + final String title; + final DateTime? deadline; +} + +final class LearnHomeworkSnapshot { + LearnHomeworkSnapshot({ + required Map counts, + required List assignments, + }) : counts = Map.unmodifiable(counts), + assignments = List.unmodifiable(assignments); + + final Map counts; + final List assignments; +} + /// Reads current homework totals using the captured GET `/student/index/` /// API. OneTHU confirms Wj = unsubmitted, Yjwg = submitted but ungraded, /// and Ypg = graded, although it uses a separate non-index POST API. @@ -30,6 +56,65 @@ final class LearnHomeworkService { final TsinghuaAuthClient _authClient; + /// Expands the captured size-limited list to its server-reported total. + /// Incomplete responses fail instead of silently dropping reminders. + Future fetchUnsubmittedHomework( + LearnCourseCatalog catalog, + ) async { + _validateCatalog(catalog); + final counts = {}; + final assignments = []; + if (catalog.courses.isEmpty) { + return LearnHomeworkSnapshot(counts: counts, assignments: assignments); + } + final csrf = await LearnPlatformSession(_authClient).open(); + for (final course in catalog.courses) { + var data = await _fetchData(course.id, 'zyListWj', csrf); + var total = _readTotal(data); + if (total > 5) { + data = await _fetchData(course.id, 'zyListWj', csrf, size: total); + total = _readTotal(data); + } + final rows = data['aaData']; + if (rows is! List || rows.length != total) { + throw const FormatException( + 'Learn returned an incomplete homework list.', + ); + } + final ids = {}; + for (final row in rows) { + if (row is! Map || + (row['wlkcid'] != null && row['wlkcid'] != course.id) || + (row['xh'] != null && row['xh'] != catalog.userId)) { + throw const FormatException( + 'Learn returned homework for another course or account.', + ); + } + final id = row['xszyid'] ?? row['zyid']; + final title = row['bt']; + if (id is! String || + id.isEmpty || + !ids.add(id) || + title is! String || + title.trim().isEmpty) { + throw const FormatException( + 'Learn returned invalid homework details.', + ); + } + assignments.add( + LearnHomework( + id: id, + course: course, + title: title, + deadline: _homeworkDeadline(row), + ), + ); + } + counts[course.id] = total; + } + return LearnHomeworkSnapshot(counts: counts, assignments: assignments); + } + /// Fetches only Wj totals for course reminders, without graded-list requests. Future> fetchUnsubmittedCounts( LearnCourseCatalog catalog, @@ -82,14 +167,25 @@ final class LearnHomeworkService { } } - Future _fetchCount(String courseId, String endpoint, String csrf) async { + Future _fetchCount( + String courseId, + String endpoint, + String csrf, + ) async => _readTotal(await _fetchData(courseId, endpoint, csrf)); + + Future _fetchData( + String courseId, + String endpoint, + String csrf, { + int size = 5, + }) async { // The index route is captured for Wj. Reusing that prefix for Yjwg/Ypg // is inferred from the sibling endpoint names; OneTHU confirms those // names on its non-index POST route, not this GET variant. final target = Uri.https( _LEARN_HOST, '/b/wlxt/kczy/zy/student/index/$endpoint', - {'wlkcid': courseId, 'size': '5', '_csrf': csrf}, + {'wlkcid': courseId, 'size': '$size', '_csrf': csrf}, ); final response = await _authClient.getAuthenticated( TsinghuaWebVpnRedirect.forTarget(target), @@ -119,7 +215,10 @@ final class LearnHomeworkService { decoded['object'] is! Map) { throw const FormatException('Learn returned an invalid homework list.'); } - final data = decoded['object'] as Map; + return decoded['object'] as Map; + } + + int _readTotal(Map data) { // DataTables metadata is authoritative. aaData contains only this page, // while iTotalDisplayRecords is the filtered count, not the full total. final value = data['iTotalRecords']; @@ -134,3 +233,21 @@ final class LearnHomeworkService { return count; } } + +DateTime? _homeworkDeadline(Map row) { + final value = row['jzsj']; + final millis = value is int + ? value + : value is String + ? int.tryParse(value) + : null; + if (millis != null && millis > 0 && millis <= 8640000000000000) { + return DateTime.fromMillisecondsSinceEpoch(millis, isUtc: true); + } + final text = row['jzsjStr']; + if (text is! String || text.trim().isEmpty) return null; + // Learn's zone-less string describes campus time, never the device zone. + // Use the normal deadline jzsj; bjjzsj is a separate late-submission deadline + // according to OneTHU, whose applicability is not established by this list. + return DateTime.tryParse('${text.trim().replaceFirst(' ', 'T')}+08:00'); +} diff --git a/packages/campus/lib/src/learn_homework_cache.dart b/packages/campus/lib/src/learn_homework_cache.dart new file mode 100644 index 0000000..98356e6 --- /dev/null +++ b/packages/campus/lib/src/learn_homework_cache.dart @@ -0,0 +1,134 @@ +part of '../thulium_campus.dart'; + +const _HOMEWORK_CACHE_VERSION = 1; +const _HOMEWORK_CACHE_MAX_LENGTH = 2 * 1024 * 1024; + +abstract interface class LearnHomeworkCacheStore { + Future read(); + Future write(String value); + Future clear(); +} + +final class CachedLearnHomework { + const CachedLearnHomework({required this.snapshot, required this.fetchedAt}); + + final LearnHomeworkSnapshot snapshot; + final DateTime fetchedAt; +} + +/// Retains one account's semester snapshot for display while updating/offline. +/// Deadlines remain absolute instants; countdowns and urgency are never stored. +final class LearnHomeworkCache { + const LearnHomeworkCache(this._store); + + final LearnHomeworkCacheStore _store; + + Future readFor(String userId, String semester) async { + final value = await _store.read(); + if (value == null || value.length > _HOMEWORK_CACHE_MAX_LENGTH) return null; + try { + final data = jsonDecode(value); + if (data is! Map || + data['version'] != _HOMEWORK_CACHE_VERSION || + data['userId'] != userId || + data['semester'] != semester) { + return null; + } + final fetchedAt = _utcTime(data['fetchedAt']); + if (fetchedAt == null) return null; + final rawCounts = data['counts'] as Map; + if (rawCounts.length > 1000) return null; + final counts = {}; + for (final entry in rawCounts.entries) { + if (entry.key is! String || + (entry.key as String).isEmpty || + entry.value is! int || + (entry.value as int) < 0) { + return null; + } + counts[entry.key as String] = entry.value as int; + } + final rows = data['assignments'] as List; + if (rows.length > 10000) return null; + final assignments = []; + final ids = <(String, String)>{}; + final actualCounts = {for (final id in counts.keys) id: 0}; + for (final row in rows) { + final entry = row as Map; + final course = LearnCourse.fromJson( + Map.from(entry['course'] as Map), + ); + final id = entry['id'] as String; + final title = entry['title'] as String; + final deadline = entry['deadline'] == null + ? null + : _utcTime(entry['deadline']); + if (!counts.containsKey(course.id) || + id.isEmpty || + title.trim().isEmpty || + !ids.add((course.id, id)) || + (entry['deadline'] != null && deadline == null)) { + return null; + } + actualCounts[course.id] = actualCounts[course.id]! + 1; + assignments.add( + LearnHomework( + id: id, + course: course, + title: title, + deadline: deadline, + ), + ); + } + if (counts.entries.any( + (entry) => actualCounts[entry.key] != entry.value, + )) { + return null; + } + return CachedLearnHomework( + fetchedAt: fetchedAt, + snapshot: LearnHomeworkSnapshot( + counts: counts, + assignments: assignments, + ), + ); + } on Exception { + return null; + } on TypeError { + return null; + } + } + + Future writeFor( + String userId, + String semester, + LearnHomeworkSnapshot snapshot, + DateTime fetchedAt, + ) async { + final payload = jsonEncode({ + 'version': _HOMEWORK_CACHE_VERSION, + 'userId': userId, + 'semester': semester, + 'fetchedAt': fetchedAt.toUtc().toIso8601String(), + 'counts': snapshot.counts, + 'assignments': [ + for (final assignment in snapshot.assignments) + { + 'id': assignment.id, + 'course': assignment.course.toJson(), + 'title': assignment.title, + 'deadline': assignment.deadline?.toUtc().toIso8601String(), + }, + ], + }); + if (payload.length > _HOMEWORK_CACHE_MAX_LENGTH) { + throw const FormatException('Homework snapshot is too large to cache.'); + } + await _store.write(payload); + } + + Future clear() => _store.clear(); + + DateTime? _utcTime(Object? value) => + value is String && value.endsWith('Z') ? DateTime.tryParse(value) : null; +} diff --git a/packages/campus/lib/thulium_campus.dart b/packages/campus/lib/thulium_campus.dart index 8228381..7b6ca57 100644 --- a/packages/campus/lib/thulium_campus.dart +++ b/packages/campus/lib/thulium_campus.dart @@ -10,5 +10,6 @@ part 'src/course_schedule_cache.dart'; part 'src/custom_plan.dart'; part 'src/learn_courses.dart'; part 'src/learn_homework.dart'; +part 'src/learn_homework_cache.dart'; part 'src/learn_course_catalog.dart'; part 'src/learn_course_cache.dart'; diff --git a/packages/campus/test/learn_homework_cache_test.dart b/packages/campus/test/learn_homework_cache_test.dart new file mode 100644 index 0000000..7c05146 --- /dev/null +++ b/packages/campus/test/learn_homework_cache_test.dart @@ -0,0 +1,112 @@ +import 'dart:convert'; + +import 'package:test/test.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +void main() { + test( + 'restores a complete snapshot through a new cache instance with UTC deadlines', + () async { + final store = _Store(); + final fetchedAt = DateTime.utc(2026, 10, 14); + await LearnHomeworkCache( + store, + ).writeFor('student', '2026-2027-1', _snapshot, fetchedAt); + final restored = await LearnHomeworkCache( + store, + ).readFor('student', '2026-2027-1'); + expect(restored!.fetchedAt, fetchedAt); + expect(restored.snapshot.counts, {'physics': 1, 'zero-homework': 0}); + expect(restored.snapshot.assignments.single.title, '大学物理作业'); + expect( + restored.snapshot.assignments.single.course.englishName, + 'Physics', + ); + expect( + restored.snapshot.assignments.single.deadline, + DateTime.utc(2026, 10, 21, 15, 59), + ); + expect(restored.snapshot.assignments.single.deadline!.isUtc, isTrue); + }, + ); + + test( + 'cache never supplies another account or semester and clear removes it', + () async { + final store = _Store(); + final cache = LearnHomeworkCache(store); + await cache.writeFor('student', '2026-2027-1', _snapshot, DateTime.now()); + expect(await cache.readFor('other-student', '2026-2027-1'), isNull); + expect(await cache.readFor('student', '2026-2027-2'), isNull); + await cache.clear(); + expect(await cache.readFor('student', '2026-2027-1'), isNull); + }, + ); + + test('corrupt, incompatible or inconsistent payloads are ignored', () async { + final store = _Store(); + final cache = LearnHomeworkCache(store); + await cache.writeFor('student', '2026-2027-1', _snapshot, DateTime.now()); + final valid = store.value!; + for (final change in )>[ + (data) => data['version'] = 99, + (data) => data['fetchedAt'] = 'bad-time', + (data) => data['counts'] = {'physics': 2}, + (data) => data['counts'] = {'physics': -1}, + (data) => (data['assignments'] as List).first['deadline'] = + '2026-10-21T15:59:00', + (data) => data['assignments'] = [null], + ]) { + final data = jsonDecode(valid) as Map; + change(data); + store.value = jsonEncode(data); + expect(await cache.readFor('student', '2026-2027-1'), isNull); + } + store.value = '{broken'; + expect(await cache.readFor('student', '2026-2027-1'), isNull); + }); + + test( + 'an empty successful snapshot is preserved as a known zero result', + () async { + final cache = LearnHomeworkCache(_Store()); + await cache.writeFor( + 'student', + '2026-2027-1', + LearnHomeworkSnapshot(counts: {}, assignments: []), + DateTime.now(), + ); + final restored = await cache.readFor('student', '2026-2027-1'); + expect(restored, isNotNull); + expect(restored!.snapshot.assignments, isEmpty); + }, + ); +} + +final _snapshot = LearnHomeworkSnapshot( + counts: {'physics': 1, 'zero-homework': 0}, + assignments: [ + LearnHomework( + id: 'assignment-1', + course: const LearnCourse( + id: 'physics', + name: '物理', + englishName: 'Physics', + teacherName: '', + schedule: '', + ), + title: '大学物理作业', + deadline: DateTime.utc(2026, 10, 21, 15, 59), + ), + ], +); + +final class _Store implements LearnHomeworkCacheStore { + String? value; + @override + Future read() async => value; + @override + Future write(String value) async => this.value = value; + @override + Future clear() async => value = null; +} diff --git a/packages/campus/test/learn_homework_test.dart b/packages/campus/test/learn_homework_test.dart index f861ba3..a18fe06 100644 --- a/packages/campus/test/learn_homework_test.dart +++ b/packages/campus/test/learn_homework_test.dart @@ -7,6 +7,70 @@ import 'package:thulium_auth/thulium_auth.dart'; import 'package:thulium_campus/thulium_campus.dart'; void main() { + test( + 'fetches complete reminder details and interprets deadlines in China time', + () async { + final sizes = []; + final deadline = DateTime.utc(2026, 10, 21, 15, 59); + final auth = await _auth((request) { + final size = request.url.queryParameters['size']!; + sizes.add(size); + final empty = request.url.queryParameters['wlkcid'] == 'empty-course'; + final count = empty ? 0 : 7; + final rows = empty + ? [] + : List.generate( + size == '5' ? 5 : 7, + (index) => { + 'xszyid': 'assignment-$index', + 'bt': 'Assignment $index', + 'wlkcid': 'course-id', + 'xh': 'test-student', + 'jzsj': index == 0 ? deadline.millisecondsSinceEpoch : null, + 'jzsjStr': index == 1 ? '2026-10-21 23:59' : '', + }, + ); + return http.Response( + jsonEncode({ + 'result': 'success', + 'object': {'iTotalRecords': '$count', 'aaData': rows}, + }), + 200, + request: request, + ); + }); + final snapshot = await LearnHomeworkService( + auth, + ).fetchUnsubmittedHomework(_catalog); + expect(snapshot.counts, {'course-id': 7, 'empty-course': 0}); + expect(snapshot.assignments, hasLength(7)); + expect(snapshot.assignments[0].deadline, deadline); + expect(snapshot.assignments[1].deadline, deadline); + expect(snapshot.assignments[2].deadline, isNull); + expect(sizes, ['5', '7', '5']); + }, + ); + + test( + 'a still-truncated assignment response is not presented as complete', + () async { + final auth = await _auth( + (request) => http.Response( + jsonEncode({ + 'result': 'success', + 'object': {'iTotalRecords': '7', 'aaData': []}, + }), + 200, + request: request, + ), + ); + await expectLater( + LearnHomeworkService(auth).fetchUnsubmittedHomework(_catalog), + throwsFormatException, + ); + }, + ); + test('course reminders request only unsubmitted totals', () async { final requests = []; final auth = await _auth((request) { diff --git a/test/support/homework_preview.dart b/test/support/homework_preview.dart new file mode 100644 index 0000000..ae27b8b --- /dev/null +++ b/test/support/homework_preview.dart @@ -0,0 +1,30 @@ +import 'package:thulium_campus/thulium_campus.dart'; + +final previewNow = DateTime.utc(2026, 10, 21, 8); +const previewCourse = LearnCourse( + id: 'physics', + name: '大学物理 B(2)', + englishName: 'University Physics B', + teacherName: '', + schedule: '', +); +final previewAssignments = [ + LearnHomework( + id: 'overdue', + course: previewCourse, + title: '第一次作业:力学基础', + deadline: previewNow.subtract(const Duration(hours: 2)), + ), + LearnHomework( + id: 'urgent', + course: previewCourse, + title: '第二次作业:电场与电势', + deadline: previewNow.add(const Duration(minutes: 35)), + ), + LearnHomework( + id: 'ungraded', + course: previewCourse, + title: '课前练习:磁场与电磁感应', + deadline: previewNow.add(const Duration(days: 2)), + ), +]; diff --git a/test/unit/homework/homework_urgency_test.dart b/test/unit/homework/homework_urgency_test.dart new file mode 100644 index 0000000..94f115b --- /dev/null +++ b/test/unit/homework/homework_urgency_test.dart @@ -0,0 +1,137 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:forui/forui.dart'; +import 'package:thulium/homework/homework_presentation.dart'; +import 'package:thulium/homework/homework_theme.dart'; +import 'package:thulium/homework/homework_urgency.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +void main() { + final now = DateTime.utc(2026, 10, 21, 8); // Wednesday, 16:00 Beijing. + LearnHomework entry(String id, DateTime? deadline) => + LearnHomework(id: id, title: id, course: _course, deadline: deadline); + test( + 'urgency boundaries include exactly one hour, one day and three days', + () { + final cases = { + const Duration(seconds: -1): HomeworkUrgency.expired, + Duration.zero: HomeworkUrgency.expired, + const Duration(seconds: 1): HomeworkUrgency.withinHour, + const Duration(hours: 1): HomeworkUrgency.withinHour, + const Duration(hours: 1, seconds: 1): HomeworkUrgency.withinDay, + const Duration(hours: 24): HomeworkUrgency.withinDay, + const Duration(hours: 24, seconds: 1): HomeworkUrgency.withinThreeDays, + const Duration(days: 3): HomeworkUrgency.withinThreeDays, + const Duration(days: 3, seconds: 1): HomeworkUrgency.later, + }; + for (final testCase in cases.entries) { + expect(homeworkUrgency(now.add(testCase.key), now), testCase.value); + } + expect(homeworkUrgency(null, now), HomeworkUrgency.unknown); + }, + ); + test( + 'sorts upcoming deadlines first and overdue last without mutating input', + () { + final input = [ + entry('unknown', null), + entry('later', now.add(const Duration(days: 6))), + entry('b', now), + entry('old', now.subtract(const Duration(days: 1))), + entry('a', now), + ]; + expect(sortHomeworkByUrgency(input, now).map((e) => e.id), [ + 'later', + 'unknown', + 'old', + 'a', + 'b', + ]); + expect(input.first.id, 'unknown'); + }, + ); + test('groups by Beijing dates, Monday week boundary, omits empty groups', () { + final groups = groupHomework([ + entry('next-week', DateTime.utc(2026, 10, 25, 16)), + entry('sunday', DateTime.utc(2026, 10, 25, 15, 59)), + entry('tomorrow', DateTime.utc(2026, 10, 21, 16)), + entry('today', DateTime.utc(2026, 10, 21, 15, 59)), + entry('expired', now), + entry('unknown', null), + ], now); + expect(groups.keys, HomeworkGroup.values); + expect(groups[HomeworkGroup.overdue]!.single.id, 'expired'); + expect(groups[HomeworkGroup.today]!.single.id, 'today'); + expect(groups[HomeworkGroup.thisWeek]!.map((e) => e.id), [ + 'tomorrow', + 'sunday', + ]); + expect(groups[HomeworkGroup.later]!.map((e) => e.id), [ + 'next-week', + 'unknown', + ]); + expect(groupHomework([], now), isEmpty); + expect( + groupHomework([ + entry('today', now.add(const Duration(minutes: 1))), + ], now).keys, + [HomeworkGroup.today], + ); + }); + test( + 'Beijing grouping crosses UTC month and year without device timezone', + () { + final newYear = DateTime.utc(2026, 12, 31, 16); + expect(beijingTime(newYear), DateTime.utc(2027)); + expect( + homeworkGroup(newYear.add(const Duration(hours: 1)), newYear), + HomeworkGroup.today, + ); + final sunday = DateTime.utc(2026, 10, 25, 15); + expect( + homeworkGroup(sunday.add(const Duration(hours: 1)), sunday), + HomeworkGroup.later, + ); + }, + ); + for (final dark in [false, true]) { + test( + 'small text contrast meets WCAG AA in ${dark ? 'dark' : 'light'} theme', + () { + final theme = dark + ? FThemes.neutral.dark.touch + : FThemes.neutral.light.touch; + expect( + textContrast(readableSecondary(theme), theme.colors.background), + greaterThanOrEqualTo(4.5), + ); + expect( + textContrast(destructiveBadgeText(theme), theme.colors.destructive), + greaterThanOrEqualTo(4.5), + ); + final palette = HomeworkPalette.forBrightness(theme.colors.brightness); + for (final background in [palette.yellow, palette.green]) { + expect( + textContrast(badgeTextOn(theme, background), background), + greaterThanOrEqualTo(4.5), + ); + } + final badge = theme.badgeStyles.resolve({FBadgeVariant.secondary}); + expect( + textContrast( + badge.contentStyle.labelTextStyle.color!, + theme.colors.secondary, + ), + greaterThanOrEqualTo(4.5), + ); + }, + ); + } +} + +const _course = LearnCourse( + id: 'physics', + name: '物理', + englishName: 'Physics', + teacherName: '', + schedule: '', +); diff --git a/test/unit/homework/secure_learn_homework_cache_store_test.dart b/test/unit/homework/secure_learn_homework_cache_store_test.dart new file mode 100644 index 0000000..04bd947 --- /dev/null +++ b/test/unit/homework/secure_learn_homework_cache_store_test.dart @@ -0,0 +1,34 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:thulium/auth/secure_learn_homework_cache_store.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test( + 'new store instances recover persisted homework and clear leaves course data intact', + () async { + FlutterSecureStorage.setMockInitialValues({ + 'thulium.learn.courses.cache.v1': 'course-data', + }); + final first = LearnHomeworkCache(SecureLearnHomeworkCacheStore()); + await first.writeFor( + 'student', + '2026-2027-1', + LearnHomeworkSnapshot(counts: {}, assignments: []), + DateTime.now(), + ); + final restored = LearnHomeworkCache(SecureLearnHomeworkCacheStore()); + expect(await restored.readFor('student', '2026-2027-1'), isNotNull); + await restored.clear(); + expect(await first.readFor('student', '2026-2027-1'), isNull); + expect( + await const FlutterSecureStorage().read( + key: 'thulium.learn.courses.cache.v1', + ), + 'course-data', + ); + }, + ); +} diff --git a/test/widget/app/widget_test.dart b/test/widget/app/widget_test.dart index 4687d16..844b303 100644 --- a/test/widget/app/widget_test.dart +++ b/test/widget/app/widget_test.dart @@ -27,7 +27,7 @@ void main() { await tester.pumpWidget(ThuliumApp(sessionStore: store)); await tester.pumpAndSettle(); - expect(find.text('Student events'), findsOneWidget); + expect(find.text('Upcoming assignments'), findsOneWidget); expect(find.text('Welcome, THUer'), findsNothing); }); @@ -71,9 +71,18 @@ void main() { await tester.pumpWidget(ThuliumApp(sessionStore: store)); await tester.pumpAndSettle(); - expect(tester.getSize(find.byType(LanguageButton)), const Size(40, 40)); - expect(tester.getSize(find.byTooltip('Theme')), const Size(40, 40)); - expect(tester.getSize(find.byTooltip('Settings')), const Size(40, 40)); + expect( + tester.getSize(find.byType(LanguageButton)), + Size.square(FThemes.neutral.light.touch.style.sizes.tile), + ); + expect( + tester.getSize(find.byTooltip('Theme')), + Size.square(FThemes.neutral.light.touch.style.sizes.tile), + ); + expect( + tester.getSize(find.byTooltip('Settings')), + Size.square(FThemes.neutral.light.touch.style.sizes.tile), + ); await tester.tap(find.byType(LanguageButton)); await tester.pumpAndSettle(); diff --git a/test/widget/homework/homework_cache_test.dart b/test/widget/homework/homework_cache_test.dart new file mode 100644 index 0000000..c886832 --- /dev/null +++ b/test/widget/homework/homework_cache_test.dart @@ -0,0 +1,121 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:forui/forui.dart'; +import 'package:thulium/l10n/generated/app_localizations.dart'; +import 'package:thulium/pages/home_page.dart'; +import 'package:thulium/widgets/homework_overview_card.dart'; +import 'package:thulium_auth/thulium_auth.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +void main() { + testWidgets( + 'offline app restart displays saved assignments but another account cannot', + (tester) async { + final cacheStore = _Store(); + final semester = AcademicSemester.forDate(DateTime.now()); + await LearnHomeworkCache(cacheStore).writeFor( + 'student', + semester, + LearnHomeworkSnapshot( + counts: {'physics': 1}, + assignments: [ + LearnHomework( + id: 'assignment-1', + title: 'Saved assignment', + course: const LearnCourse( + id: 'physics', + name: '物理', + englishName: 'Physics', + teacherName: '', + schedule: '', + ), + deadline: DateTime.now().toUtc().add(const Duration(days: 2)), + ), + ], + ), + DateTime.now(), + ); + + Future mount(String userId) async { + final sessionStore = MemoryAuthSessionStore(); + await sessionStore.write( + AuthSession(userId: userId, fingerprint: 'test', cookies: {}), + ); + await tester.pumpWidget( + MaterialApp( + locale: const Locale('en'), + localizationsDelegates: [ + ...AppLocalizations.localizationsDelegates, + ...FLocalizations.localizationsDelegates, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (_, child) => + FTheme(data: FThemes.neutral.light.touch, child: child!), + home: HomePage( + key: UniqueKey(), + sessionStore: sessionStore, + homeworkCacheStore: cacheStore, + onLocaleSelected: (_) {}, + onThemeToggle: () {}, + onLogout: () async => true, + onSessionExpired: () {}, + ), + ), + ); + // Flutter widget tests block live HTTP requests; catalog refresh fails. + await tester.pumpAndSettle(); + // Static skeletons deliberately do not keep frames scheduled. Wait for + // the mocked HTTP failure explicitly rather than relying on a spinner. + for (var attempt = 0; attempt < 50; attempt++) { + if (!tester + .widget(find.byType(HomeworkOverviewCard)) + .isLoading) { + break; + } + await tester.pump(const Duration(milliseconds: 100)); + } + expect( + tester + .widget(find.byType(HomeworkOverviewCard)) + .isLoading, + isFalse, + ); + } + + await mount('student'); + expect(find.text('Saved assignment'), findsOneWidget); + expect( + find.text('Could not update assignments; showing saved data.'), + findsOneWidget, + ); + expect( + find.text('Could not load assignments. Try refreshing.'), + findsNothing, + ); + expect(tester.takeException(), isNull); + + await tester.pumpWidget(const SizedBox.shrink()); + await mount('student'); + expect(find.text('Saved assignment'), findsOneWidget); + + await tester.pumpWidget(const SizedBox.shrink()); + await mount('other-student'); + expect(find.text('Saved assignment'), findsNothing); + expect( + find.text('Could not load assignments. Try refreshing.'), + findsOneWidget, + ); + expect(tester.takeException(), isNull); + }, + ); +} + +final class _Store implements LearnHomeworkCacheStore { + String? value; + @override + Future read() async => value; + @override + Future write(String value) async => this.value = value; + @override + Future clear() async => value = null; +} diff --git a/test/widget/homework/homework_overview_card_test.dart b/test/widget/homework/homework_overview_card_test.dart new file mode 100644 index 0000000..1df9ebb --- /dev/null +++ b/test/widget/homework/homework_overview_card_test.dart @@ -0,0 +1,256 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:forui/forui.dart'; +import 'package:thulium/homework/homework_presentation.dart'; +import 'package:thulium/l10n/generated/app_localizations.dart'; +import 'package:thulium/widgets/app_bottom_navigation.dart'; +import 'package:thulium/widgets/homework_overview_card.dart'; +import 'package:thulium/widgets/scrolling_badge.dart'; + +import '../../support/homework_preview.dart'; + +void main() { + Future show( + WidgetTester tester, { + double scale = 1, + bool reduceMotion = true, + bool dark = false, + bool loading = false, + bool failed = false, + bool empty = false, + Duration offset = const Duration(hours: 8), + VoidCallback? refresh, + HomeworkActions actions = const HomeworkActions(), + Locale locale = const Locale('en'), + }) async { + tester.view.physicalSize = const Size(390, 1100); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final theme = dark + ? FThemes.neutral.dark.touch + : FThemes.neutral.light.touch; + await tester.pumpWidget( + MaterialApp( + locale: locale, + localizationsDelegates: [ + ...AppLocalizations.localizationsDelegates, + ...FLocalizations.localizationsDelegates, + ], + supportedLocales: AppLocalizations.supportedLocales, + theme: theme.toApproximateMaterialTheme(), + builder: (context, child) => FTheme( + data: theme, + child: MediaQuery( + data: MediaQuery.of(context).copyWith( + textScaler: TextScaler.linear(scale), + disableAnimations: reduceMotion, + ), + child: child!, + ), + ), + home: FScaffold( + childPad: false, + footer: AppBottomNavigation(index: 0, onChange: (_) {}), + child: HomeworkOverviewCard( + assignments: empty ? [] : previewAssignments, + isLoading: loading, + failed: failed, + onRefresh: refresh ?? () {}, + now: previewNow, + updatedAt: previewNow.subtract(const Duration(minutes: 7)), + deviceTimeZoneOffset: offset, + countsTowardGrade: (item) => item.id == 'ungraded' ? false : null, + actions: actions, + ), + ), + ), + ); + if (reduceMotion) { + await tester.pumpAndSettle(); + } else { + await tester.pump(const Duration(milliseconds: 300)); + } + } + + testWidgets( + 'uses grouped tiles, icon refresh and overdue last without timezone prose', + (tester) async { + await show(tester); + expect(find.byType(FCard), findsNothing); + expect(find.byType(FTileGroup), findsNWidgets(3)); + expect(find.text('Today'), findsOneWidget); + expect(find.text('Within 1h'), findsOneWidget); + expect(find.text('Not graded'), findsOneWidget); + expect(find.text('Updated 7 minutes ago'), findsOneWidget); + expect( + find.text('All deadlines use Beijing time (UTC+8).'), + findsNothing, + ); + expect(find.textContaining('Beijing time'), findsNothing); + expect( + tester.getTopLeft(find.text(previewAssignments[0].title)).dy, + greaterThan( + tester.getTopLeft(find.text(previewAssignments[1].title)).dy, + ), + ); + expect(tester.takeException(), isNull); + }, + ); + for (final dark in [false, true]) { + for (final locale in [const Locale('en'), const Locale('zh', 'CN')]) { + testWidgets( + '200% text fits ${dark ? 'dark' : 'light'} ${locale.languageCode}', + (tester) async { + await show(tester, scale: 2, dark: dark, locale: locale); + await tester.drag( + find.byKey(const ValueKey('homework-scroll')), + const Offset(0, -650), + ); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + final navItems = find.byType(FBottomNavigationBarItem); + expect(navItems, findsNWidgets(4)); + for (final element in navItems.evaluate()) { + expect( + tester.getSize(find.byWidget(element.widget)).height, + greaterThanOrEqualTo(44), + ); + } + }, + ); + } + } + testWidgets( + 'tap opens details, long press exposes disabled unconnected actions', + (tester) async { + await show(tester); + await tester.tap(find.text(previewAssignments.first.title)); + await tester.pumpAndSettle(); + expect(find.text('Assignment details'), findsOneWidget); + await tester.tap(find.bySemanticsLabel('Back')); + await tester.pumpAndSettle(); + await tester.longPress(find.text(previewAssignments.first.title)); + await tester.pumpAndSettle(); + for (final label in [ + 'Open website', + 'Remind me later', + 'Mark as submitted', + ]) { + final button = tester.widget( + find.ancestor(of: find.text(label), matching: find.byType(FButton)), + ); + expect(button.onPress, isNull); + } + expect(tester.takeException(), isNull); + }, + ); + testWidgets('supports real action callbacks and refresh', (tester) async { + var refreshes = 0; + var opened = false; + await show( + tester, + refresh: () => refreshes++, + actions: HomeworkActions(openWeb: (_) async => opened = true), + ); + await tester.tap(find.byIcon(Icons.refresh)); + await tester.pumpAndSettle(); + await tester.drag( + find.byKey(const ValueKey('homework-scroll')), + const Offset(0, 350), + ); + await tester.pumpAndSettle(); + expect(refreshes, 2); + await tester.longPress(find.text(previewAssignments.first.title)); + await tester.pumpAndSettle(); + await tester.tap(find.text('Open website')); + await tester.pumpAndSettle(); + expect(opened, isTrue); + expect(tester.takeException(), isNull); + }); + testWidgets('long badge labels stay on one line and scroll when clipped', ( + tester, + ) async { + await show(tester, scale: 2, reduceMotion: false); + await tester.scrollUntilVisible( + find.text('Within 3 days'), + 250, + scrollable: find + .descendant( + of: find.byKey(const ValueKey('homework-scroll')), + matching: find.byType(Scrollable), + ) + .first, + ); + final label = find.text('Within 3 days'); + final text = tester.widget(label); + expect(text.maxLines, 1); + expect(text.softWrap, isFalse); + final badge = find.ancestor( + of: label, + matching: find.byType(ScrollingBadge), + ); + final translation = find + .descendant(of: badge, matching: find.byType(Transform)) + .first; + final before = tester + .widget(translation) + .transform + .getTranslation() + .x; + await tester.pump(const Duration(seconds: 2)); + await tester.pump(const Duration(seconds: 1)); + final after = tester + .widget(translation) + .transform + .getTranslation() + .x; + expect(after, lessThan(before)); + final animation = + tester + .widget( + find + .descendant( + of: badge, + matching: find.byType(AnimatedBuilder), + ) + .first, + ) + .animation + as AnimationController; + final cycle = animation.duration!.inMicroseconds; + await tester.pump(Duration(microseconds: (cycle * .35).round())); + final furtherLeft = tester + .widget(translation) + .transform + .getTranslation() + .x; + expect(furtherLeft, lessThan(after)); + await tester.pump( + Duration(microseconds: (cycle * (1 - animation.value + .05)).round()), + ); + final nextLoop = tester + .widget(translation) + .transform + .getTranslation() + .x; + expect(nextLoop, greaterThan(furtherLeft)); + expect(animation.isAnimating, isTrue); + expect(tester.takeException(), isNull); + }); + testWidgets('loading, retry and empty states are accessible', (tester) async { + await show(tester, loading: true); + expect(find.bySemanticsLabel('Loading assignments'), findsOneWidget); + await show(tester, failed: true); + expect(find.byType(FAlert), findsOneWidget); + expect(find.text('Retry'), findsOneWidget); + await show(tester, empty: true); + expect(find.text('All done'), findsOneWidget); + }); + testWidgets('adds per-row Beijing notice only outside Beijing timezone', ( + tester, + ) async { + await show(tester, offset: Duration.zero); + expect(find.textContaining('· Beijing time'), findsNWidgets(3)); + }); +} diff --git a/test/widget/homework/homework_redesign_capture_test.dart b/test/widget/homework/homework_redesign_capture_test.dart new file mode 100644 index 0000000..fcbe77a --- /dev/null +++ b/test/widget/homework/homework_redesign_capture_test.dart @@ -0,0 +1,103 @@ +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:forui/forui.dart'; +import 'package:thulium/l10n/generated/app_localizations.dart'; +import 'package:thulium/widgets/homework_overview_card.dart'; +import 'package:thulium/widgets/app_bottom_navigation.dart'; + +import '../../support/homework_preview.dart'; + +void main() { + testWidgets( + 'capture homework review screenshots', + (tester) async { + final font = Platform.environment['HOMEWORK_SCREENSHOT_FONT']!; + final bytes = ByteData.sublistView(File(font).readAsBytesSync()); + await tester.runAsync( + () => (FontLoader( + 'HomeworkPreview', + )..addFont(Future.value(bytes))).load(), + ); + final icons = await rootBundle.load( + 'packages/forui_assets/assets/lucide.ttf', + ); + await tester.runAsync( + () => (FontLoader( + 'packages/forui_assets/ForuiLucideIcons', + )..addFont(Future.value(icons))).load(), + ); + final materialIcons = await rootBundle.load( + 'fonts/MaterialIcons-Regular.otf', + ); + await tester.runAsync( + () => (FontLoader( + 'MaterialIcons', + )..addFont(Future.value(materialIcons))).load(), + ); + tester.view.physicalSize = const Size(390, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final output = Directory('artifacts/homework-redesign'); + output.createSync(recursive: true); + for (final dark in [false, true]) { + final colors = + (dark ? FThemes.neutral.dark.touch : FThemes.neutral.light.touch) + .colors; + final theme = FThemeData( + colors: colors, + touch: true, + typography: FTypography(fontFamily: 'HomeworkPreview'), + ); + final key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + locale: const Locale('zh', 'CN'), + localizationsDelegates: [ + ...AppLocalizations.localizationsDelegates, + ...FLocalizations.localizationsDelegates, + ], + supportedLocales: AppLocalizations.supportedLocales, + theme: theme.toApproximateMaterialTheme(), + builder: (_, child) => FTheme(data: theme, child: child!), + home: RepaintBoundary( + key: key, + child: FScaffold( + childPad: false, + footer: AppBottomNavigation(index: 0, onChange: (_) {}), + child: HomeworkOverviewCard( + assignments: previewAssignments, + isLoading: false, + failed: false, + onRefresh: () {}, + now: previewNow, + updatedAt: previewNow.subtract(const Duration(minutes: 7)), + countsTowardGrade: (item) => + item.id == 'ungraded' ? false : null, + deviceTimeZoneOffset: const Duration(hours: 8), + ), + ), + ), + ), + ); + await tester.pumpAndSettle(); + final boundary = + key.currentContext!.findRenderObject()! as RenderRepaintBoundary; + await tester.runAsync(() async { + final image = await boundary.toImage(); + final data = await image.toByteData(format: ui.ImageByteFormat.png); + File( + '${output.path}/${Platform.environment['HOMEWORK_CAPTURE_STAGE']}-${dark ? 'dark' : 'light'}.png', + ).writeAsBytesSync(data!.buffer.asUint8List()); + image.dispose(); + }); + } + }, + skip: Platform.environment['HOMEWORK_CAPTURE_STAGE'] == null, + ); +} From ffd0dd50ca89975bba6434a60e8f358d548a1c0e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AshGrey=F0=9F=A5=95?= Date: Thu, 22 Oct 2026 11:37:03 +0800 Subject: [PATCH 09/26] feat(cli): add learn materials listing (#5) List course materials with semester, course, and result-limit options, and format metadata as YAML. Flag potentially truncated results without claiming a total count. Share flat Forui tile styling between Study courses and the homework overview. --- lib/homework/homework_presentation.dart | 12 - lib/pages/study_page.dart | 136 +++++---- lib/widgets/flat_tile_style.dart | 13 + lib/widgets/homework_overview_card.dart | 5 +- packages/campus/lib/src/learn_materials.dart | 202 ++++++++++++ packages/campus/lib/thulium_campus.dart | 1 + .../campus/test/learn_materials_test.dart | 287 ++++++++++++++++++ packages/cli/bin/thulium.dart | 98 +++++- .../cli/lib/learn_materials_formatter.dart | 59 ++++ .../test/learn_materials_formatter_test.dart | 86 ++++++ 10 files changed, 820 insertions(+), 79 deletions(-) create mode 100644 lib/widgets/flat_tile_style.dart create mode 100644 packages/campus/lib/src/learn_materials.dart create mode 100644 packages/campus/test/learn_materials_test.dart create mode 100644 packages/cli/lib/learn_materials_formatter.dart create mode 100644 packages/cli/test/learn_materials_formatter_test.dart diff --git a/lib/homework/homework_presentation.dart b/lib/homework/homework_presentation.dart index f494d02..ce7ac27 100644 --- a/lib/homework/homework_presentation.dart +++ b/lib/homework/homework_presentation.dart @@ -39,15 +39,3 @@ Color badgeTextOn(FThemeData theme, Color background) { textContrast(a, background) >= textContrast(b, background) ? a : b, ); } - -/// Flat resting surface; interaction feedback continues to use Forui variants. -FItemStyleDelta homeworkTileStyle(FThemeData theme) => FItemStyleDelta.delta( - backgroundColor: FVariantsValueDelta.delta([ - FVariantValueDeltaOperation.base(theme.colors.background), - ]), - contentDecoration: FVariantsDelta.delta([ - FVariantOperation.base( - DecorationDelta.shapeDelta(color: theme.colors.background), - ), - ]), -); diff --git a/lib/pages/study_page.dart b/lib/pages/study_page.dart index 6594a04..4d22703 100644 --- a/lib/pages/study_page.dart +++ b/lib/pages/study_page.dart @@ -3,6 +3,8 @@ import 'package:forui/forui.dart'; import 'package:thulium/l10n/generated/app_localizations.dart'; import 'package:thulium_campus/thulium_campus.dart'; +import '../widgets/flat_tile_style.dart'; + /// Keeps room for future study shortcuts above the Learn course list. final class StudyPage extends StatelessWidget { const StudyPage({ @@ -33,11 +35,11 @@ final class StudyPage extends StatelessWidget { @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context)!; - final colors = context.theme.colors; + final theme = context.theme; + final colors = theme.colors; final locale = Localizations.localeOf(context).languageCode; final courseTitleStyle = context.theme.typography.md; - final courseMetadataStyle = context.theme.typography.sm.copyWith( - fontSize: 12, + final courseMetadataStyle = theme.typography.xs.copyWith( color: colors.mutedForeground, ); return ListView( @@ -114,72 +116,82 @@ final class StudyPage extends StatelessWidget { padding: const EdgeInsets.only(top: 20), child: Text(l10n.studyNoCourses), ), - for (final course in catalog?.courses ?? []) + if (catalog?.courses.isNotEmpty ?? false) Padding( - padding: const EdgeInsets.only(top: 12), - child: DecoratedBox( - decoration: BoxDecoration( - color: colors.secondary.withValues(alpha: 0.18), - border: Border.all(color: colors.border), - borderRadius: BorderRadius.circular(12), - ), - child: Padding( - padding: const EdgeInsets.all(14), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: Text( - locale == 'en' && course.englishName.isNotEmpty - ? course.englishName - : course.name, - style: courseTitleStyle.copyWith( - fontWeight: FontWeight.bold, - ), - ), - ), - if (!homeworkFailed && - (unsubmittedHomework[course.id] ?? 0) > 0) ...[ - const SizedBox(width: 8), - Semantics( - label: l10n.studyUnsubmittedHomework( - unsubmittedHomework[course.id]!, - ), - excludeSemantics: true, - child: Tooltip( - message: l10n.studyUnsubmittedHomework( - unsubmittedHomework[course.id]!, - ), - excludeFromSemantics: true, - child: FBadge( - key: ValueKey('homework-badge-${course.id}'), - variant: FBadgeVariant.destructive, + padding: EdgeInsets.only(top: theme.style.pagePadding.top), + child: FTileGroup( + intrinsicWidth: false, + physics: const NeverScrollableScrollPhysics(), + divider: FItemDivider.full, + children: [ + for (final course in catalog!.courses) + FTile.raw( + key: ValueKey('study-course-${course.id}'), + style: flatTileStyle(theme), + child: Padding( + padding: theme.style.pagePadding, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( child: Text( - '${unsubmittedHomework[course.id]}', + locale == 'en' && + course.englishName.isNotEmpty + ? course.englishName + : course.name, + style: courseTitleStyle.copyWith( + fontWeight: FontWeight.bold, + ), ), ), - ), + if (!homeworkFailed && + (unsubmittedHomework[course.id] ?? 0) > + 0) ...[ + const SizedBox(width: 8), + Semantics( + label: l10n.studyUnsubmittedHomework( + unsubmittedHomework[course.id]!, + ), + excludeSemantics: true, + child: Tooltip( + message: l10n.studyUnsubmittedHomework( + unsubmittedHomework[course.id]!, + ), + excludeFromSemantics: true, + child: FBadge( + key: ValueKey( + 'homework-badge-${course.id}', + ), + variant: FBadgeVariant.destructive, + child: Text( + '${unsubmittedHomework[course.id]}', + ), + ), + ), + ), + ], + ], ), + if (course.teacherName.isNotEmpty || + course.schedule.isNotEmpty) ...[ + const SizedBox(height: 6), + Text( + [ + if (course.teacherName.isNotEmpty) + course.teacherName, + if (course.schedule.isNotEmpty) course.schedule, + ].join(' · '), + style: courseMetadataStyle, + ), + ], ], - ], - ), - if (course.teacherName.isNotEmpty || - course.schedule.isNotEmpty) ...[ - const SizedBox(height: 6), - Text( - [ - if (course.teacherName.isNotEmpty) course.teacherName, - if (course.schedule.isNotEmpty) course.schedule, - ].join(' · '), - style: courseMetadataStyle, ), - ], - ], - ), - ), + ), + ), + ], ), ), ], diff --git a/lib/widgets/flat_tile_style.dart b/lib/widgets/flat_tile_style.dart new file mode 100644 index 0000000..5cff894 --- /dev/null +++ b/lib/widgets/flat_tile_style.dart @@ -0,0 +1,13 @@ +import 'package:forui/forui.dart'; + +/// Flat resting surface; interaction feedback continues to use Forui variants. +FItemStyleDelta flatTileStyle(FThemeData theme) => FItemStyleDelta.delta( + backgroundColor: FVariantsValueDelta.delta([ + FVariantValueDeltaOperation.base(theme.colors.background), + ]), + contentDecoration: FVariantsDelta.delta([ + FVariantOperation.base( + DecorationDelta.shapeDelta(color: theme.colors.background), + ), + ]), +); diff --git a/lib/widgets/homework_overview_card.dart b/lib/widgets/homework_overview_card.dart index 83c9116..707bb53 100644 --- a/lib/widgets/homework_overview_card.dart +++ b/lib/widgets/homework_overview_card.dart @@ -10,6 +10,7 @@ import '../homework/homework_presentation.dart'; import '../homework/homework_urgency.dart'; import '../homework/homework_theme.dart'; import 'scrolling_badge.dart'; +import 'flat_tile_style.dart'; import '../l10n/generated/app_localizations.dart'; /// Presentation of the existing snapshot. No network, cache, or submission @@ -208,7 +209,7 @@ final class _HomeworkOverviewCardState extends State children: [ for (final item in entry.value) FTile.raw( - style: homeworkTileStyle(theme), + style: flatTileStyle(theme), key: ValueKey( 'homework-${item.course.id}-${item.id}', ), @@ -279,7 +280,7 @@ final class _HomeworkOverviewCardState extends State physics: const NeverScrollableScrollPhysics(), children: [ FTile.raw( - style: homeworkTileStyle(theme), + style: flatTileStyle(theme), child: Padding( padding: theme.style.pagePadding, child: _AssignmentContent( diff --git a/packages/campus/lib/src/learn_materials.dart b/packages/campus/lib/src/learn_materials.dart new file mode 100644 index 0000000..47c0045 --- /dev/null +++ b/packages/campus/lib/src/learn_materials.dart @@ -0,0 +1,202 @@ +part of '../thulium_campus.dart'; + +/// Metadata for one Learn material. Times are absolute UTC instants. +final class LearnMaterial { + factory LearnMaterial.fromResponse(Map row) { + for (final key in ['kjxxid', 'wlkcid', 'bt', 'wjid']) { + if (row[key] is! String || (row[key] as String).trim().isEmpty) { + throw const FormatException( + 'Learn returned invalid material metadata.', + ); + } + } + return LearnMaterial._(row); + } + + LearnMaterial._(Map row) + : id = row['kjxxid'] as String, + courseId = row['wlkcid'] as String, + title = row['bt'] as String, + fileId = row['wjid'] as String, + fileType = _materialText(row['wjlx']), + displaySize = _materialText(row['fileSize']), + sizeBytes = _materialCount(row['wjdx']), + uploadedAt = _materialUploadTime(row['scsj']), + availableAt = _materialEpoch(row['sxsj']), + isNew = switch (row['isNew']) { + 1 || '1' || true => true, + 0 || '0' || false => false, + _ => null, + }, + description = _materialText(row['ms']), + categoryId = _materialText(row['kjflid']), + viewCount = _materialCount(row['llcs']), + downloadCount = _materialCount(row['xzcs']), + rawResponse = Map.unmodifiable(row); + + final String id; + final String courseId; + final String title; + final String fileId; + final String fileType; + final String displaySize; + final int? sizeBytes; + final DateTime? uploadedAt; + final DateTime? availableAt; + final bool? isNew; + final String description; + final String categoryId; + final int? viewCount; + final int? downloadCount; + + /// Keeps unverified fields available without assigning guessed semantics. + /// In particular, OneTHU maps sfqd to "important", while the captured + /// response does not establish that meaning; do not call it attendance. + final Map rawResponse; +} + +/// A bounded material list, not an authoritative total for the course. +final class LearnCourseMaterials { + LearnCourseMaterials({ + required this.course, + required List materials, + required this.requestedLimit, + }) : materials = List.unmodifiable(materials); + + final LearnCourse course; + final List materials; + final int requestedLimit; + bool get mayBeTruncated => materials.length >= requestedLimit; +} + +/// Lists material metadata through the captured Learn student endpoint. +final class LearnMaterialService { + const LearnMaterialService(this._authClient); + final TsinghuaAuthClient _authClient; + + /// OneTHU uses 200 here. This endpoint has no offset or total count in the + /// supplied response, so preserve the limit and never claim a complete list. + Future> fetchCourses( + LearnCourseCatalog catalog, { + String? courseId, + int size = 200, + }) async { + if (size <= 0) throw ArgumentError.value(size, 'size', 'Must be positive.'); + if (_authClient.session?.userId != catalog.userId) { + throw StateError('Restore the course catalog account first.'); + } + final courses = catalog.courses + .where((course) => courseId == null || course.id == courseId) + .toList(); + if (courseId != null && courses.isEmpty) { + throw ArgumentError.value( + courseId, + 'courseId', + 'Course is not in this semester catalog.', + ); + } + if (courses.any((course) => course.id.isEmpty)) { + throw const FormatException('A course has no learning platform ID.'); + } + if (courses.isEmpty) return const []; + final csrf = await LearnPlatformSession(_authClient).open(); + final result = []; + // One shared roaming session; sequential requests preserve existing Learn + // authentication behavior and avoid sending a burst for the whole semester. + for (final course in courses) { + result.add( + LearnCourseMaterials( + course: course, + requestedLimit: size, + materials: await _fetch(course.id, size, csrf), + ), + ); + } + return List.unmodifiable(result); + } + + Future> _fetch( + String courseId, + int size, + String csrf, + ) async { + final target = Uri.https( + _LEARN_HOST, + '/b/wlxt/kj/wlkc_kjxxb/student/kjxxbByWlkcidAndSizeForStudent', + {'wlkcid': courseId, 'size': '$size', '_csrf': csrf}, + ); + final response = await _authClient.getAuthenticated( + TsinghuaWebVpnRedirect.forTarget(target), + ); + if (_isLearnSignInResponse( + response.statusCode, + response.request?.url, + response.body, + )) { + _authClient.traceUnexpectedResponse('learning-materials', response); + throw const PortalSessionRejected(); + } + if (response.statusCode != 200) { + throw StateError( + 'Materials request failed for $courseId: HTTP ${response.statusCode}.', + ); + } + final Object? decoded; + try { + decoded = jsonDecode(response.body); + } on FormatException { + throw const FormatException('Learn did not return material-list JSON.'); + } + if (decoded is! Map || + decoded['result'] != 'success' || + decoded['object'] is! List) { + throw const FormatException('Learn returned an invalid material list.'); + } + final rows = decoded['object'] as List; + final ids = {}; + final materials = []; + for (final row in rows) { + if (row is! Map || row['wlkcid'] != courseId) { + throw const FormatException( + 'Learn returned materials for another course.', + ); + } + final material = LearnMaterial.fromResponse(row); + if (!ids.add(material.id)) { + throw const FormatException('Learn returned duplicate material IDs.'); + } + materials.add(material); + } + return materials; + } +} + +String _materialText(Object? value) => value is String ? value : ''; + +int? _materialCount(Object? value) { + final count = value is int + ? value + : value is String + ? int.tryParse(value) + : null; + return count != null && count >= 0 ? count : null; +} + +DateTime? _materialUploadTime(Object? value) { + if (value is! String || + !RegExp( + r'^\d{4}-\d{2}-\d{2} \d{2}:\d{2}(:\d{2})?$', + ).hasMatch(value.trim())) { + return null; + } + // scsj is a Beijing wall-clock string, not a time in the device's timezone. + return DateTime.tryParse( + '${value.trim().replaceFirst(' ', 'T')}+08:00', + )?.toUtc(); +} + +DateTime? _materialEpoch(Object? value) { + final millis = _materialCount(value); + if (millis == null || millis <= 0 || millis > 8640000000000000) return null; + return DateTime.fromMillisecondsSinceEpoch(millis, isUtc: true); +} diff --git a/packages/campus/lib/thulium_campus.dart b/packages/campus/lib/thulium_campus.dart index 7b6ca57..35809c6 100644 --- a/packages/campus/lib/thulium_campus.dart +++ b/packages/campus/lib/thulium_campus.dart @@ -10,6 +10,7 @@ part 'src/course_schedule_cache.dart'; part 'src/custom_plan.dart'; part 'src/learn_courses.dart'; part 'src/learn_homework.dart'; +part 'src/learn_materials.dart'; part 'src/learn_homework_cache.dart'; part 'src/learn_course_catalog.dart'; part 'src/learn_course_cache.dart'; diff --git a/packages/campus/test/learn_materials_test.dart b/packages/campus/test/learn_materials_test.dart new file mode 100644 index 0000000..c92aa51 --- /dev/null +++ b/packages/campus/test/learn_materials_test.dart @@ -0,0 +1,287 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:test/test.dart'; +import 'package:thulium_auth/thulium_auth.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +void main() { + test( + 'requests the captured route with shared roaming, scoped cookies and limit', + () async { + final requests = []; + var landings = 0; + final auth = await _auth((request) { + requests.add(request); + return _response( + request, + request.url.queryParameters['wlkcid'] == 'physics' ? [_row()] : [], + ); + }, onLanding: () => landings++); + final courses = await LearnMaterialService(auth).fetchCourses(_catalog); + expect(landings, 1); + expect(requests, hasLength(2)); + for (final request in requests) { + expect(request.method, 'GET'); + expect(request.url.host, TsinghuaWebVpnRedirect.WEBVPN_HOST); + expect( + request.url.path, + endsWith( + '/b/wlxt/kj/wlkc_kjxxb/student/kjxxbByWlkcidAndSizeForStudent', + ), + ); + expect(request.url.queryParameters['size'], '200'); + expect(request.url.queryParameters['_csrf'], 'learn-csrf'); + expect(request.headers['cookie'], contains('JSESSIONID=learn-session')); + } + final item = courses.first.materials.single; + expect(item.title, 'ATP synthase'); + expect(item.sizeBytes, 2855509); + expect( + item.displaySize, + '2.0M', + ); // Do not infer bytes from the rounded label. + expect(item.uploadedAt, DateTime.utc(2026, 10, 20, 7, 12)); + expect( + item.availableAt, + DateTime.fromMillisecondsSinceEpoch(1792562400000, isUtc: true), + ); + expect(item.isNew, isTrue); + expect(item.viewCount, 0); + expect(item.downloadCount, 5); + expect(item.rawResponse['sfqd'], 0); + expect(courses.first.mayBeTruncated, isFalse); + expect(courses.last.materials, isEmpty); + }, + ); + + test( + 'filters before requests and flags a response at the requested limit', + () async { + final requests = []; + final auth = await _auth((request) { + requests.add(request); + return _response(request, [_row()]); + }); + final result = await LearnMaterialService( + auth, + ).fetchCourses(_catalog, courseId: 'physics', size: 1); + expect(requests, hasLength(1)); + expect(requests.single.url.queryParameters['wlkcid'], 'physics'); + expect(requests.single.url.queryParameters['size'], '1'); + expect(result.single.requestedLimit, 1); + expect(result.single.mayBeTruncated, isTrue); + }, + ); + + test( + 'invalid size, account and course selection fail before any network access', + () async { + final auth = await _auth( + (_) => throw StateError('Unexpected request'), + onLanding: () => fail('Unexpected roaming'), + ); + final service = LearnMaterialService(auth); + for (final size in [0, -1]) { + await expectLater( + service.fetchCourses(_catalog, size: size), + throwsArgumentError, + ); + } + await expectLater( + service.fetchCourses(_catalog, courseId: 'missing'), + throwsArgumentError, + ); + await expectLater( + service.fetchCourses( + LearnCourseCatalog( + userId: 'other', + semester: '2026-2027-1', + courses: [], + ), + ), + throwsStateError, + ); + final result = await service.fetchCourses( + LearnCourseCatalog( + userId: 'student', + semester: '2026-2027-1', + courses: [], + ), + ); + expect(result, isEmpty); + }, + ); + + test( + 'auth failures remain reconnectable and HTTP failures are not empty results', + () async { + for (final status in [401, 403, 500]) { + final auth = await _auth( + (request) => http.Response('', status, request: request), + ); + await expectLater( + LearnMaterialService(auth).fetchCourses(_catalog), + status == 500 + ? throwsStateError + : throwsA(isA()), + ); + } + final auth = await _auth( + (request) => + http.Response('sm2publickey', 200, request: request), + ); + await expectLater( + LearnMaterialService(auth).fetchCourses(_catalog), + throwsA(isA()), + ); + }, + ); + + test( + 'malformed responses and cross-course rows fail instead of silently omitting files', + () async { + for (final body in [ + 'not JSON', + jsonEncode({'result': 'error', 'object': []}), + jsonEncode({'result': 'success', 'object': {}}), + jsonEncode({ + 'result': 'success', + 'object': [null], + }), + jsonEncode({ + 'result': 'success', + 'object': [_row()..['wlkcid'] = 'another-course'], + }), + jsonEncode({ + 'result': 'success', + 'object': [_row()..['wjid'] = null], + }), + jsonEncode({ + 'result': 'success', + 'object': [_row(), _row()], + }), + ]) { + final auth = await _auth( + (request) => http.Response(body, 200, request: request), + ); + await expectLater( + LearnMaterialService(auth).fetchCourses(_catalog), + throwsFormatException, + ); + } + }, + ); + + test( + 'optional fields stay unknown, string numbers parse, raw fields stay immutable', + () { + final row = _row() + ..['wjdx'] = '2855509' + ..['isNew'] = '0' + ..['scsj'] = 'not a timestamp' + ..['sxsj'] = '99999999999999999999' + ..['llcs'] = -1 + ..['xzcs'] = '7'; + final material = LearnMaterial.fromResponse(row); + expect(material.sizeBytes, 2855509); + expect(material.isNew, isFalse); + expect(material.uploadedAt, isNull); + expect(material.availableAt, isNull); + expect(material.viewCount, isNull); + expect(material.downloadCount, 7); + expect(() => material.rawResponse['sfqd'] = 1, throwsUnsupportedError); + }, + ); +} + +Map _row() => { + 'wlkcid': 'physics', + 'kjxxid': 'material-1', + 'bt': 'ATP synthase', + 'wjid': 'file-1', + 'wjlx': 'pdf', + 'sfqd': 0, + 'scsj': '2026-10-20 15:12', + 'sxsj': 1792562400000, + 'isNew': 1, + 'fileSize': '2.0M', + 'wjdx': 2855509, + 'llcs': 0, + 'xzcs': 5, + 'ms': '', + 'kjflid': 'category-1', +}; + +http.Response _response(http.Request request, List rows) => + http.Response( + jsonEncode({'result': 'success', 'object': rows}), + 200, + request: request, + ); + +final _catalog = LearnCourseCatalog( + userId: 'student', + semester: '2026-2027-1', + courses: const [ + LearnCourse( + id: 'physics', + name: 'Physics', + englishName: '', + teacherName: '', + schedule: '', + ), + LearnCourse( + id: 'empty', + name: 'Empty', + englishName: '', + teacherName: '', + schedule: '', + ), + ], +); + +Future _auth( + http.Response Function(http.Request) respond, { + void Function()? onLanding, +}) async { + final transport = MockClient((request) async { + if (request.url.path == '/wengine-vpn/cookie') { + return http.Response( + 'XSRF-TOKEN=portal-csrf; Path=/;', + 200, + request: request, + ); + } + if (request.url.path.endsWith('onlineAppRedirect')) { + return http.Response( + jsonEncode({ + 'object': { + 'roamingurl': + 'https://learn.tsinghua.edu.cn/f/wlxt/index/course/student/index', + }, + }), + 200, + request: request, + ); + } + if (request.url.path.contains('/f/wlxt/index/course/student/index')) { + onLanding?.call(); + return http.Response( + '_csrf=learn-csrf', + 200, + headers: {'set-cookie': 'JSESSIONID=learn-session; Path=/; Secure'}, + request: request, + ); + } + return respond(request); + }); + final store = MemoryAuthSessionStore(); + await store.write( + const AuthSession(userId: 'student', fingerprint: 'test', cookies: {}), + ); + final client = TsinghuaAuthClient(httpClient: transport, sessionStore: store); + await client.restore(); + return client; +} diff --git a/packages/cli/bin/thulium.dart b/packages/cli/bin/thulium.dart index 682fb8b..baefeca 100644 --- a/packages/cli/bin/thulium.dart +++ b/packages/cli/bin/thulium.dart @@ -11,6 +11,7 @@ import 'package:thulium_cli/cli_learn_course_cache_store.dart'; import 'package:thulium_cli/cli_session_reconnect.dart'; import 'package:thulium_cli/learn_course_formatter.dart'; import 'package:thulium_cli/learn_homework_formatter.dart'; +import 'package:thulium_cli/learn_materials_formatter.dart'; // Uppercase snake case is the project convention for named constants. // ignore_for_file: constant_identifier_names @@ -89,6 +90,35 @@ ArgParser _buildParser() { ..addFlag('verbose', help: 'Print safe request diagnostics.') ..addFlag('refresh', help: 'Refresh the course list before counting.'), ); + parser.addCommand( + 'learn-materials', + ArgParser() + ..addOption( + 'semester', + abbr: 's', + help: 'Academic semester ID (defaults to the current semester).', + ) + ..addOption( + 'course-id', + help: 'List only this course from the semester catalog.', + ) + ..addOption( + 'size', + defaultsTo: '200', + help: 'Maximum materials requested per course (not a total count).', + ) + ..addFlag('verbose', help: 'Print safe request diagnostics.') + ..addFlag( + 'refresh', + help: 'Refresh the course catalog before listing materials.', + ) + ..addFlag( + 'help', + abbr: 'h', + negatable: false, + help: 'Show command usage.', + ), + ); return parser; } @@ -96,15 +126,37 @@ Future _runCommand(ArgResults command) async { final name = command.command?.name; if (name == null) { stdout.writeln( - 'Usage: thulium ', + 'Usage: thulium ', ); return; } + int? materialSize; + if (name == 'learn-materials') { + if (command.command!['help'] as bool) { + stdout.writeln('Usage: thulium learn-materials [options]'); + stdout.writeln(_buildParser().commands['learn-materials']!.usage); + return; + } + materialSize = int.tryParse(command.command!['size'] as String); + if (materialSize == null || materialSize <= 0) { + throw const FormatException('--size must be a positive integer.'); + } + final courseId = command.command!['course-id'] as String?; + if (courseId != null && courseId.trim().isEmpty) { + throw const FormatException('--course-id must not be empty.'); + } + if (command.command!.rest.isNotEmpty) { + throw const FormatException('Use --course-id to select a course.'); + } + } + final store = CliAuthSessionStore(); final calendarCache = CourseScheduleCache(CliCourseScheduleCacheStore()); final learnCache = LearnCourseCache(CliLearnCourseCacheStore()); - final promptOutput = name == 'learn-homework' ? stderr : stdout; + final promptOutput = name == 'learn-homework' || name == 'learn-materials' + ? stderr + : stdout; final client = TsinghuaAuthClient( sessionStore: store, credentialStore: store, @@ -220,6 +272,45 @@ Future _runCommand(ArgResults command) async { semester: semester, ), ); + case 'learn-materials': + final session = await client.restore(); + if (session == null) { + throw StateError('Not logged in. Run `thulium login` first.'); + } + final semester = + (command.command!['semester'] as String?) ?? + AcademicSemester.forDate(DateTime.now()); + final catalogService = LearnCourseCatalogService( + client, + cache: learnCache, + ); + final materials = await reconnect.run( + commandName: 'learn-materials', + savedSession: session, + request: (isRetry) async { + final catalog = await catalogService.loadSemester( + semester, + forceRefresh: isRetry || command.command!['refresh'] as bool, + ); + if (catalogService.lastSource == LearnCourseSource.staleCache) { + stderr.writeln('Update failed; using the saved course list.'); + } + return LearnMaterialService(client).fetchCourses( + catalog, + courseId: command.command!['course-id'] as String?, + size: materialSize!, + ); + }, + shouldReconnect: (error) => + error is PortalCsrfUnavailable || error is PortalSessionRejected, + ); + stdout.writeln( + formatLearnMaterials( + materials, + studentId: session.userId, + semester: semester, + ), + ); case 'learn-homework': final session = await client.restore(); if (session == null) { @@ -391,7 +482,8 @@ bool _verboseRequested(String commandName, ArgResults command) => (commandName == 'login' || commandName == 'schedule' || commandName == 'learn-courses' || - commandName == 'learn-homework') && + commandName == 'learn-homework' || + commandName == 'learn-materials') && command['verbose'] as bool; void _printSchedule(CourseSchedule schedule) { diff --git a/packages/cli/lib/learn_materials_formatter.dart b/packages/cli/lib/learn_materials_formatter.dart new file mode 100644 index 0000000..4486b82 --- /dev/null +++ b/packages/cli/lib/learn_materials_formatter.dart @@ -0,0 +1,59 @@ +import 'dart:convert'; + +import 'package:thulium_campus/thulium_campus.dart'; + +/// Quotes provider text as YAML-safe JSON strings; never includes credentials. +String formatLearnMaterials( + List courses, { + required String studentId, + required String semester, +}) { + final output = StringBuffer() + ..writeln('studentId: ${jsonEncode(studentId)}') + ..writeln('semester: ${jsonEncode(semester)}'); + if (courses.isEmpty) return '${output}courses: []'; + output.writeln('courses:'); + for (final row in courses) { + output + ..writeln(' - courseId: ${jsonEncode(row.course.id)}') + ..writeln(' name: ${jsonEncode(row.course.name)}'); + if (row.course.englishName.isNotEmpty) { + output.writeln(' englishName: ${jsonEncode(row.course.englishName)}'); + } + output + ..writeln(' requestedLimit: ${row.requestedLimit}') + ..writeln(' returnedCount: ${row.materials.length}') + ..writeln(' mayBeTruncated: ${row.mayBeTruncated}'); + if (row.materials.isEmpty) { + output.writeln(' materials: []'); + continue; + } + output.writeln(' materials:'); + for (final item in row.materials) { + output + ..writeln(' - materialId: ${jsonEncode(item.id)}') + ..writeln(' title: ${jsonEncode(item.title)}') + ..writeln(' fileId: ${jsonEncode(item.fileId)}'); + final fields = { + 'fileType': item.fileType, + 'sizeBytes': item.sizeBytes, + 'displaySize': item.displaySize, + 'uploadedAt': item.uploadedAt?.toIso8601String(), + 'availableAt': item.availableAt?.toIso8601String(), + 'isNew': item.isNew, + 'description': item.description, + 'categoryId': item.categoryId, + 'viewCount': item.viewCount, + 'downloadCount': item.downloadCount, + }; + for (final field in fields.entries) { + final value = field.value; + if (value == null || value == '') continue; + output.writeln( + ' ${field.key}: ${value is String ? jsonEncode(value) : value}', + ); + } + } + } + return output.toString().trimRight(); +} diff --git a/packages/cli/test/learn_materials_formatter_test.dart b/packages/cli/test/learn_materials_formatter_test.dart new file mode 100644 index 0000000..737a55e --- /dev/null +++ b/packages/cli/test/learn_materials_formatter_test.dart @@ -0,0 +1,86 @@ +import 'package:test/test.dart'; +import 'package:thulium_campus/thulium_campus.dart'; +import 'package:thulium_cli/learn_materials_formatter.dart'; + +void main() { + test('prints YAML-safe metadata, UTC times and honest bounded counts', () { + final material = LearnMaterial.fromResponse({ + 'kjxxid': 'material-1', + 'wlkcid': 'course-1', + 'bt': 'ATP: "synthase"\nPaper', + 'wjid': 'file&1', + 'wjlx': 'pdf', + 'wjdx': 2855509, + 'fileSize': '2.0M', + 'scsj': '2026-10-20 15:12', + 'isNew': 1, + 'llcs': 0, + 'sfqd': 0, + }); + final output = formatLearnMaterials( + [ + LearnCourseMaterials( + course: _course, + materials: [material], + requestedLimit: 1, + ), + ], + studentId: 'student', + semester: '2026-2027-1', + ); + expect( + output, + startsWith('studentId: "student"\nsemester: "2026-2027-1"\ncourses:'), + ); + expect(output, contains('title: "ATP: \\"synthase\\"\\nPaper"')); + expect(output, contains('fileId: "file&1"')); + expect( + output, + contains( + 'requestedLimit: 1\n returnedCount: 1\n mayBeTruncated: true', + ), + ); + expect(output, contains('sizeBytes: 2855509')); + expect(output, contains('uploadedAt: "2026-10-20T07:12:00.000Z"')); + expect(output, contains('isNew: true')); + expect(output, contains('viewCount: 0')); + expect(output, isNot(contains('availableAt:'))); + expect(output, isNot(contains('sfqd:'))); + expect(output, isNot(contains('important:'))); + expect(output, isNot(contains('total:'))); + }); + + test('empty courses and semesters remain valid YAML collections', () { + final empty = formatLearnMaterials( + [], + studentId: 'student', + semester: '2026-2027-1', + ); + expect(empty, endsWith('courses: []')); + final output = formatLearnMaterials( + [ + LearnCourseMaterials( + course: _course, + materials: [], + requestedLimit: 200, + ), + ], + studentId: 'student', + semester: '2026-2027-1', + ); + expect( + output, + contains( + 'returnedCount: 0\n mayBeTruncated: false\n materials: []', + ), + ); + }); +} + +const _course = LearnCourse( + id: 'course-1', + name: '生物化学', + englishName: 'Biochemistry', + teacherName: '', + schedule: '', +); From 7953124da1f27ac73034820639acca4a8b0e56c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AshGrey=F0=9F=A5=95?= Date: Thu, 29 Oct 2026 09:27:01 +0800 Subject: [PATCH 10/26] feat(cli): download (#5) learn course materials Add authenticated binary downloads for course materials and preserve response metadata needed to save files. Extend the Learn materials command with file download handling, and cover byte responses and saved-file behavior with tests. --- packages/auth/lib/thulium_auth.dart | 69 +++++++- .../auth/test/authenticated_bytes_test.dart | 141 ++++++++++++++++ packages/campus/lib/src/learn_materials.dart | 88 ++++++++++ .../campus/test/learn_materials_test.dart | 158 ++++++++++++++++++ packages/cli/bin/thulium.dart | 142 +++++++++++++--- packages/cli/lib/material_download_file.dart | 39 +++++ .../cli/test/material_download_file_test.dart | 67 ++++++++ 7 files changed, 675 insertions(+), 29 deletions(-) create mode 100644 packages/auth/test/authenticated_bytes_test.dart create mode 100644 packages/cli/lib/material_download_file.dart create mode 100644 packages/cli/test/material_download_file_test.dart diff --git a/packages/auth/lib/thulium_auth.dart b/packages/auth/lib/thulium_auth.dart index c947c13..1ea3ee1 100644 --- a/packages/auth/lib/thulium_auth.dart +++ b/packages/auth/lib/thulium_auth.dart @@ -630,6 +630,37 @@ final class TsinghuaAuthClient { return _asTextResponse(response); } + /// Sends an authenticated GET without decoding or re-encoding file bytes. + /// Redirect cookies and timeout behavior match [getAuthenticated]. + Future getAuthenticatedBytes(Uri uri, {Uri? referer}) async { + if (_session == null) { + throw StateError( + 'Restore an authenticated session before making requests.', + ); + } + if (!_isTsinghuaHost(uri.host) || + (referer != null && !_isTsinghuaHost(referer.host))) { + throw ArgumentError('Only Tsinghua hosts are allowed.'); + } + final requestUri = + uri.host.toLowerCase() == TsinghuaWebVpnRedirect.ACADEMIC_CALENDAR_HOST + ? TsinghuaWebVpnRedirect.forTarget(uri) + : uri; + final response = await _request( + requestUri, + decodeBody: false, + tsinghuaRedirectsOnly: true, + referer: referer, + ); + await _persistSession(); + return http.Response.bytes( + response.bytes, + response.statusCode, + headers: response.headers, + request: http.Request('GET', response.uri), + ); + } + /// Establishes a WebVPN session for a campus service using its roaming ID. /// /// The returned response is the target service's landing page. Only the @@ -1275,6 +1306,9 @@ final class TsinghuaAuthClient { Uri uri, { String method = 'GET', Map? form, + bool decodeBody = true, + bool tsinghuaRedirectsOnly = false, + Uri? referer, }) async { var current = uri; var currentMethod = method; @@ -1291,6 +1325,7 @@ final class TsinghuaAuthClient { ..followRedirects = false ..headers['User-Agent'] = _USER_AGENT ..headers['Cookie'] = _cookieHeaderForRequest(current); + if (referer != null) request.headers['Referer'] = referer.toString(); if (currentForm != null) { request.headers['Content-Type'] = 'application/x-www-form-urlencoded'; request.bodyFields = currentForm; @@ -1316,11 +1351,13 @@ final class TsinghuaAuthClient { ); rethrow; } - final body = _decodeResponseBody( - bytes, - response.headers['content-type'], - current, - ); + final body = decodeBody + ? _decodeResponseBody( + bytes, + response.headers['content-type'], + current, + ) + : ''; _captureResponseCookies(current, response.headers['set-cookie']); final location = response.headers['location']; trace?.call( @@ -1332,9 +1369,18 @@ final class TsinghuaAuthClient { if (location == null || response.statusCode < 300 || response.statusCode >= 400) { - return _Response(response.statusCode, response.headers, body, current); + return _Response( + response.statusCode, + response.headers, + body, + current, + bytes, + ); } final redirected = current.resolveUri(Uri.parse(location)); + if (tsinghuaRedirectsOnly && !_isTsinghuaHost(redirected.host)) { + throw StateError('The file download redirected outside Tsinghua.'); + } // The academic calendar can redirect to an absolute origin URL. Keep // that hop in the same WebVPN session as the original calendar request. current = @@ -1477,7 +1523,16 @@ final class TsinghuaAuthClient { } final class _Response { - const _Response(this.statusCode, this.headers, this.body, this.uri); + const _Response( + this.statusCode, + this.headers, + this.body, + this.uri, + this.bytes, + ); + + /// Unmodified bytes for authenticated binary downloads. + final List bytes; /// HTTP status returned by the identity or WebVPN endpoint. final int statusCode; diff --git a/packages/auth/test/authenticated_bytes_test.dart b/packages/auth/test/authenticated_bytes_test.dart new file mode 100644 index 0000000..1a6691f --- /dev/null +++ b/packages/auth/test/authenticated_bytes_test.dart @@ -0,0 +1,141 @@ +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:test/test.dart'; +import 'package:thulium_auth/thulium_auth.dart'; + +void main() { + test( + 'binary requests preserve every byte and headers across cookie-setting redirects', + () async { + final bytes = List.generate(256, (index) => index); + final requests = []; + final store = MemoryAuthSessionStore(); + await store.write( + const AuthSession( + userId: 'student', + fingerprint: 'test', + cookies: {}, + scopedCookies: [ + AuthCookie( + name: 'JSESSIONID', + value: 'learn-session', + domain: 'learn.tsinghua.edu.cn', + path: '/', + hostOnly: true, + secure: true, + ), + ], + ), + ); + final target = TsinghuaWebVpnRedirect.forTarget( + Uri.parse('https://learn.tsinghua.edu.cn/file'), + ); + final referer = target.replace(path: '${target.path}/viewer'); + final transport = MockClient((request) async { + requests.add(request); + if (requests.length == 1) { + return http.Response( + '', + 302, + headers: { + 'location': '${target.path}/bytes', + 'set-cookie': 'download-token=test; Path=/; Secure', + }, + request: request, + ); + } + return http.Response.bytes( + bytes, + 200, + headers: {'content-type': 'application/pdf', 'content-length': '256'}, + request: request, + ); + }); + final auth = TsinghuaAuthClient( + sessionStore: store, + httpClient: transport, + ); + await auth.restore(); + final response = await auth.getAuthenticatedBytes( + target, + referer: referer, + ); + expect(response.bodyBytes, bytes); + expect(response.headers['content-type'], 'application/pdf'); + expect(response.headers['content-length'], '256'); + expect(requests, hasLength(2)); + for (final request in requests) { + expect(request.headers['referer'], referer.toString()); + expect(request.headers['cookie'], contains('JSESSIONID=learn-session')); + } + expect(requests.last.headers['cookie'], contains('download-token=test')); + expect( + (await store.read())!.scopedCookies.any( + (cookie) => cookie.name == 'download-token', + ), + isTrue, + ); + }, + ); + + test( + 'binary requests require a session and reject non-Tsinghua targets and referers', + () async { + final store = MemoryAuthSessionStore(); + final auth = TsinghuaAuthClient( + sessionStore: store, + httpClient: MockClient( + (_) async => throw StateError('Unexpected network access'), + ), + ); + final target = Uri.parse('https://learn.tsinghua.edu.cn/file'); + await expectLater(auth.getAuthenticatedBytes(target), throwsStateError); + await store.write( + const AuthSession(userId: 'student', fingerprint: 'test', cookies: {}), + ); + await auth.restore(); + await expectLater( + auth.getAuthenticatedBytes(Uri.parse('https://example.com/file')), + throwsArgumentError, + ); + await expectLater( + auth.getAuthenticatedBytes( + target, + referer: Uri.parse('https://example.com/'), + ), + throwsArgumentError, + ); + }, + ); + + test( + 'binary requests reject an unexpected external redirect before following it', + () async { + var requests = 0; + final store = MemoryAuthSessionStore(); + await store.write( + const AuthSession(userId: 'student', fingerprint: 'test', cookies: {}), + ); + final auth = TsinghuaAuthClient( + sessionStore: store, + httpClient: MockClient((request) async { + requests++; + return http.Response( + '', + 302, + headers: {'location': 'https://example.com/file'}, + request: request, + ); + }), + ); + await auth.restore(); + await expectLater( + auth.getAuthenticatedBytes( + Uri.parse('https://learn.tsinghua.edu.cn/file'), + ), + throwsStateError, + ); + expect(requests, 1); + }, + ); +} diff --git a/packages/campus/lib/src/learn_materials.dart b/packages/campus/lib/src/learn_materials.dart index 47c0045..d01ce5a 100644 --- a/packages/campus/lib/src/learn_materials.dart +++ b/packages/campus/lib/src/learn_materials.dart @@ -115,6 +115,94 @@ final class LearnMaterialService { return List.unmodifiable(result); } + /// Downloads all pages of the PDF representation. + Future> downloadPdf({ + required String fileId, + required String courseId, + }) => _downloadPdf(fileId: fileId, courseId: courseId, pageType: 'all'); + + /// Downloads the cover preview for use by clients such as the app. + Future> downloadPdfCover({ + required String fileId, + required String courseId, + }) => _downloadPdf(fileId: fileId, courseId: courseId, pageType: 'first'); + + Future> _downloadPdf({ + required String fileId, + required String courseId, + required String pageType, + }) async { + final idPattern = RegExp(r'^[A-Za-z0-9_-]+$'); + if (!idPattern.hasMatch(fileId) || !idPattern.hasMatch(courseId)) { + throw ArgumentError( + 'File and course IDs must contain only letters, numbers, underscores or hyphens.', + ); + } + await LearnPlatformSession(_authClient).open(); + final target = Uri( + scheme: 'https', + host: _LEARN_HOST, + pathSegments: [ + 'f', + 'wlxt', + 'kc', + 'wj_wjb', + 'student', + 'downloadPdfStream', + pageType, + fileId, + courseId, + 'mk_kcwj', + ], + ); + final referer = Uri.https( + _LEARN_HOST, + '/f/wlxt/kc/wj_wjb/student/beforePlay', + { + 'sfgk': '0', + 'wjid': fileId, + 'mk': 'mk_kcwj', + 'pageType': pageType, + 'browser': '-1', + }, + ); + final response = await _authClient.getAuthenticatedBytes( + TsinghuaWebVpnRedirect.forTarget(target), + referer: TsinghuaWebVpnRedirect.forTarget(referer), + ); + final bytes = response.bodyBytes; + final signature = latin1.decode(bytes.take(1024).toList()); + final contentType = response.headers['content-type']?.toLowerCase() ?? ''; + final isPdf = + RegExp(r'%PDF-[12]\.\d').hasMatch(signature) && + !contentType.startsWith('text/html') && + !contentType.contains('json'); + final preview = utf8.decode( + bytes.take(4096).toList(), + allowMalformed: true, + ); + if (_isLearnSignInResponse( + response.statusCode, + response.request?.url, + isPdf ? '' : preview, + )) { + // Do not log response previews here: a successful binary response may + // contain private course content rather than an authentication page. + throw const PortalSessionRejected(); + } + if (response.statusCode != 200) { + throw StateError( + 'Material download failed: HTTP ${response.statusCode}.', + ); + } + if (!isPdf) { + throw const FormatException( + 'Learn did not return a PDF. The file may not support PDF preview or the session may have expired.', + ); + } + return bytes; + } + Future> _fetch( String courseId, int size, diff --git a/packages/campus/test/learn_materials_test.dart b/packages/campus/test/learn_materials_test.dart index c92aa51..9ceeabe 100644 --- a/packages/campus/test/learn_materials_test.dart +++ b/packages/campus/test/learn_materials_test.dart @@ -7,6 +7,164 @@ import 'package:thulium_auth/thulium_auth.dart'; import 'package:thulium_campus/thulium_campus.dart'; void main() { + test( + 'downloads the captured PDF route with its viewer referer and exact bytes', + () async { + final bytes = [ + ...utf8.encode( + '%PDF-1.7\n% sm2publickey is document content, not a login page\n', + ), + ...List.generate(256, (index) => index), + ...utf8.encode('\n%%EOF'), + ]; + final auth = await _auth((request) { + expect( + request.url.path, + endsWith( + '/f/wlxt/kc/wj_wjb/student/downloadPdfStream/all/file-1/physics/mk_kcwj', + ), + ); + expect(request.url.host, TsinghuaWebVpnRedirect.WEBVPN_HOST); + final referer = Uri.parse(request.headers['referer']!); + expect(referer.path, endsWith('/f/wlxt/kc/wj_wjb/student/beforePlay')); + expect(referer.queryParameters, { + 'sfgk': '0', + 'wjid': 'file-1', + 'mk': 'mk_kcwj', + 'pageType': 'all', + 'browser': '-1', + }); + expect(request.headers['cookie'], contains('JSESSIONID=learn-session')); + return http.Response.bytes( + bytes, + 200, + headers: {'content-type': 'application/pdf'}, + request: request, + ); + }); + expect( + await LearnMaterialService( + auth, + ).downloadPdf(fileId: 'file-1', courseId: 'physics'), + bytes, + ); + }, + ); + + test( + 'cover download retains the first-page route and viewer referer', + () async { + final bytes = utf8.encode('%PDF-1.7\ncover\n%%EOF'); + final auth = await _auth((request) { + expect( + request.url.path, + endsWith('/downloadPdfStream/first/file-1/physics/mk_kcwj'), + ); + expect( + Uri.parse(request.headers['referer']!).queryParameters['pageType'], + 'first', + ); + return http.Response.bytes( + bytes, + 200, + headers: {'content-type': 'application/pdf'}, + request: request, + ); + }); + expect( + await LearnMaterialService( + auth, + ).downloadPdfCover(fileId: 'file-1', courseId: 'physics'), + bytes, + ); + }, + ); + + test( + 'download session errors are reconnectable, not saved as PDFs', + () async { + for (final status in [200, 401, 403]) { + final auth = await _auth( + (request) => http.Response( + 'sm2publickey', + status, + headers: {'content-type': 'text/html'}, + request: request, + ), + ); + await expectLater( + LearnMaterialService( + auth, + ).downloadPdf(fileId: 'file-1', courseId: 'physics'), + throwsA(isA()), + ); + } + }, + ); + + test( + 'empty, non-PDF, misleading HTML, partial and failed downloads are rejected', + () async { + for (final body in [ + '', + 'Unavailable', + '{"error":"PDF unavailable"}', + ]) { + final auth = await _auth( + (request) => http.Response(body, 200, request: request), + ); + await expectLater( + LearnMaterialService( + auth, + ).downloadPdf(fileId: 'file-1', courseId: 'physics'), + throwsFormatException, + ); + } + final html = await _auth( + (request) => http.Response( + '%PDF-1.7 not available', + 200, + headers: {'content-type': 'text/html'}, + request: request, + ), + ); + await expectLater( + LearnMaterialService( + html, + ).downloadPdf(fileId: 'file-1', courseId: 'physics'), + throwsFormatException, + ); + for (final status in [206, 404, 500]) { + final auth = await _auth( + (request) => http.Response('%PDF-1.7', status, request: request), + ); + await expectLater( + LearnMaterialService( + auth, + ).downloadPdf(fileId: 'file-1', courseId: 'physics'), + throwsStateError, + ); + } + }, + ); + + test('invalid download IDs fail before opening a Learn session', () async { + final auth = await _auth( + (_) => throw StateError('Unexpected network access'), + onLanding: () => fail('Unexpected roaming'), + ); + for (final id in ['', '../file', 'file?x=1', 'file/other']) { + await expectLater( + LearnMaterialService(auth).downloadPdf(fileId: id, courseId: 'physics'), + throwsArgumentError, + ); + await expectLater( + LearnMaterialService(auth).downloadPdf(fileId: 'file-1', courseId: id), + throwsArgumentError, + ); + } + }); + test( 'requests the captured route with shared roaming, scoped cookies and limit', () async { diff --git a/packages/cli/bin/thulium.dart b/packages/cli/bin/thulium.dart index baefeca..280dd28 100644 --- a/packages/cli/bin/thulium.dart +++ b/packages/cli/bin/thulium.dart @@ -12,6 +12,7 @@ import 'package:thulium_cli/cli_session_reconnect.dart'; import 'package:thulium_cli/learn_course_formatter.dart'; import 'package:thulium_cli/learn_homework_formatter.dart'; import 'package:thulium_cli/learn_materials_formatter.dart'; +import 'package:thulium_cli/material_download_file.dart'; // Uppercase snake case is the project convention for named constants. // ignore_for_file: constant_identifier_names @@ -93,6 +94,7 @@ ArgParser _buildParser() { parser.addCommand( 'learn-materials', ArgParser() + ..addCommand('download', _materialDownloadParser()) ..addOption( 'semester', abbr: 's', @@ -119,42 +121,103 @@ ArgParser _buildParser() { help: 'Show command usage.', ), ); + parser.addCommand( + 'learn-materials-cover', + _materialDownloadParser(cover: true) + ..addCommand('download', _materialDownloadParser(cover: true)), + ); return parser; } +ArgParser _materialDownloadParser({bool cover = false}) => ArgParser() + ..addOption('file-id', help: 'File ID from learn-materials output.') + ..addOption('course-id', help: 'Course ID that owns the file.') + ..addOption( + 'output', + abbr: 'o', + help: 'Destination path (defaults to FILE_ID${cover ? '-cover' : ''}.pdf).', + ) + ..addFlag('force', negatable: false, help: 'Replace an existing output file.') + ..addFlag('verbose', help: 'Print safe request diagnostics.') + ..addFlag('help', abbr: 'h', negatable: false, help: 'Show download usage.'); + Future _runCommand(ArgResults command) async { final name = command.command?.name; if (name == null) { stdout.writeln( - 'Usage: thulium ', + 'Usage: thulium ', ); return; } int? materialSize; - if (name == 'learn-materials') { - if (command.command!['help'] as bool) { - stdout.writeln('Usage: thulium learn-materials [options]'); - stdout.writeln(_buildParser().commands['learn-materials']!.usage); + final isMaterialDownload = + name == 'learn-materials-cover' || + (name == 'learn-materials' && + command.command!.command?.name == 'download'); + final materialOptions = isMaterialDownload + ? command.command!.command ?? command.command! + : command.command!; + String? materialOutput; + if (name == 'learn-materials' || name == 'learn-materials-cover') { + if (materialOptions['help'] as bool || + (isMaterialDownload && command.command!['help'] as bool)) { + final parser = _buildParser().commands[name]!; + stdout.writeln( + 'Usage: thulium $name${command.command!.command?.name == 'download' ? ' download' : ''} [options]', + ); + stdout.writeln( + command.command!.command?.name == 'download' + ? parser.commands['download']!.usage + : parser.usage, + ); return; } - materialSize = int.tryParse(command.command!['size'] as String); - if (materialSize == null || materialSize <= 0) { - throw const FormatException('--size must be a positive integer.'); - } - final courseId = command.command!['course-id'] as String?; - if (courseId != null && courseId.trim().isEmpty) { - throw const FormatException('--course-id must not be empty.'); + if (isMaterialDownload) { + for (final name in ['file-id', 'course-id']) { + final value = materialOptions[name] as String?; + if (value == null || !RegExp(r'^[A-Za-z0-9_-]+$').hasMatch(value)) { + throw FormatException( + '--$name is required and must be a valid Learn ID.', + ); + } + } + materialOutput = + materialOptions['output'] as String? ?? + '${materialOptions['file-id']}${name == 'learn-materials-cover' ? '-cover' : ''}.pdf'; + if (materialOutput.trim().isEmpty) { + throw const FormatException('--output must not be empty.'); + } + if (!(materialOptions['force'] as bool) && + await FileSystemEntity.type(materialOutput, followLinks: false) != + FileSystemEntityType.notFound) { + throw FileSystemException( + 'Output already exists. Use --force to replace it.', + materialOutput, + ); + } + } else { + materialSize = int.tryParse(materialOptions['size'] as String); + if (materialSize == null || materialSize <= 0) { + throw const FormatException('--size must be a positive integer.'); + } + final courseId = materialOptions['course-id'] as String?; + if (courseId != null && courseId.trim().isEmpty) { + throw const FormatException('--course-id must not be empty.'); + } } - if (command.command!.rest.isNotEmpty) { - throw const FormatException('Use --course-id to select a course.'); + if (materialOptions.rest.isNotEmpty) { + throw const FormatException('Specify IDs using the named options.'); } } final store = CliAuthSessionStore(); final calendarCache = CourseScheduleCache(CliCourseScheduleCacheStore()); final learnCache = LearnCourseCache(CliLearnCourseCacheStore()); - final promptOutput = name == 'learn-homework' || name == 'learn-materials' + final promptOutput = + name == 'learn-homework' || + name == 'learn-materials' || + name == 'learn-materials-cover' ? stderr : stdout; final client = TsinghuaAuthClient( @@ -272,11 +335,39 @@ Future _runCommand(ArgResults command) async { semester: semester, ), ); + case 'learn-materials-cover': case 'learn-materials': final session = await client.restore(); if (session == null) { throw StateError('Not logged in. Run `thulium login` first.'); } + if (isMaterialDownload) { + final bytes = await reconnect.run( + commandName: name == 'learn-materials-cover' + ? name + : 'learn-materials download', + savedSession: session, + request: (_) { + final service = LearnMaterialService(client); + final download = name == 'learn-materials-cover' + ? service.downloadPdfCover + : service.downloadPdf; + return download( + fileId: materialOptions['file-id'] as String, + courseId: materialOptions['course-id'] as String, + ); + }, + shouldReconnect: (error) => + error is PortalCsrfUnavailable || error is PortalSessionRejected, + ); + final saved = await saveMaterialDownload( + bytes, + outputPath: materialOutput!, + overwrite: materialOptions['force'] as bool, + ); + stdout.writeln('Saved ${bytes.length} bytes to ${saved.path}'); + return; + } final semester = (command.command!['semester'] as String?) ?? AcademicSemester.forDate(DateTime.now()); @@ -478,13 +569,20 @@ Future _revealSessionCookies(AuthSession session) async { } } -bool _verboseRequested(String commandName, ArgResults command) => - (commandName == 'login' || - commandName == 'schedule' || - commandName == 'learn-courses' || - commandName == 'learn-homework' || - commandName == 'learn-materials') && - command['verbose'] as bool; +bool _verboseRequested(String commandName, ArgResults command) { + if ((commandName == 'learn-materials' || + commandName == 'learn-materials-cover') && + command.command?.name == 'download') { + return command.command!['verbose'] as bool || command['verbose'] as bool; + } + return (commandName == 'login' || + commandName == 'schedule' || + commandName == 'learn-courses' || + commandName == 'learn-homework' || + (commandName == 'learn-materials' || + commandName == 'learn-materials-cover')) && + command['verbose'] as bool; +} void _printSchedule(CourseSchedule schedule) { final courses = schedule.occurrences.toList() diff --git a/packages/cli/lib/material_download_file.dart b/packages/cli/lib/material_download_file.dart new file mode 100644 index 0000000..1aef69e --- /dev/null +++ b/packages/cli/lib/material_download_file.dart @@ -0,0 +1,39 @@ +import 'dart:io'; + +/// Writes a validated download in the destination directory and renames it +/// into place. Exclusive creation prevents replacing an existing file unless +/// the user explicitly requested overwrite. +Future saveMaterialDownload( + List bytes, { + required String outputPath, + bool overwrite = false, +}) async { + if (bytes.isEmpty) throw ArgumentError('The download is empty.'); + final output = File(outputPath).absolute; + if (await FileSystemEntity.type(output.path, followLinks: false) != + FileSystemEntityType.notFound && + !overwrite) { + throw FileSystemException( + 'Output already exists. Use --force to replace it.', + output.path, + ); + } + await output.parent.create(recursive: true); + final temporary = await output.parent.createTemp('.thulium-material-'); + var reserved = false; + try { + final partial = await File( + '${temporary.path}/download.part', + ).writeAsBytes(bytes, flush: true); + if (!overwrite) { + await output.create(exclusive: true); + reserved = true; + } + final saved = await partial.rename(output.path); + reserved = false; + return saved; + } finally { + if (reserved) await output.delete(); + await temporary.delete(recursive: true); + } +} diff --git a/packages/cli/test/material_download_file_test.dart b/packages/cli/test/material_download_file_test.dart new file mode 100644 index 0000000..14740ee --- /dev/null +++ b/packages/cli/test/material_download_file_test.dart @@ -0,0 +1,67 @@ +import 'dart:io'; + +import 'package:test/test.dart'; +import 'package:thulium_cli/material_download_file.dart'; + +void main() { + late Directory directory; + setUp( + () async => directory = await Directory.systemTemp.createTemp( + 'thulium-download-test-', + ), + ); + tearDown(() async => directory.delete(recursive: true)); + + test( + 'saves exact bytes, creates parent directories and removes temporary data', + () async { + final bytes = List.generate(256, (index) => index); + final path = '${directory.path}/nested/material.pdf'; + final result = await saveMaterialDownload(bytes, outputPath: path); + expect(await result.readAsBytes(), bytes); + expect(await result.parent.list().map((entry) => entry.path).toList(), [ + result.path, + ]); + }, + ); + + test( + 'preserves existing data unless overwrite is explicitly requested', + () async { + final file = await File( + '${directory.path}/material.pdf', + ).writeAsString('existing data'); + await expectLater( + saveMaterialDownload([1, 2, 3], outputPath: file.path), + throwsA(isA()), + ); + expect(await file.readAsString(), 'existing data'); + await saveMaterialDownload( + [1, 2, 3], + outputPath: file.path, + overwrite: true, + ); + expect(await file.readAsBytes(), [1, 2, 3]); + expect(await directory.list().length, 1); + }, + ); + + test( + 'empty downloads and invalid destinations do not leave output or temporary files', + () async { + await expectLater( + saveMaterialDownload([], outputPath: '${directory.path}/empty.pdf'), + throwsArgumentError, + ); + final target = await Directory('${directory.path}/folder').create(); + await expectLater( + saveMaterialDownload([1, 2], outputPath: target.path, overwrite: true), + throwsA(isA()), + ); + expect(await target.exists(), isTrue); + expect(await directory.list().map((entry) => entry.path).toList(), [ + target.path, + ]); + }, + ); +} From 4d4c01c59c9056d9102f40392b1d7601a46c36d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AshGrey=F0=9F=A5=95?= Date: Thu, 29 Oct 2026 10:38:56 +0800 Subject: [PATCH 11/26] agents: update project instruction for agents --- AGENTS.md | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 AGENTS.md diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..17ccc70 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,23 @@ +# Interface Style + +Use a restrained, dark, minimalist visual language for Thulium, consistent with +the existing calendar and Forui components. + +- Prefer Forui components and their theme tokens. Keep surfaces simple, with + clear hierarchy, fine borders, compact spacing, and consistent interaction + states. +- Use near-black backgrounds, subtle grid lines, and low-contrast cards for + dense calendar views. Reserve saturated colors for meaningful categories, + urgency, selection, or other necessary emphasis. +- Favor legible typography, concise labels, and predictable alignment. Let + spacing, weight, and a small number of semantic colors establish hierarchy + instead of decoration. +- Keep shadows, gradients, rounded containers, and ornamental effects subtle. + Avoid visual clutter and unnecessary card-on-card layouts. +- Maintain sufficient contrast and readable text in both light and dark themes; + use the shared theme rather than hard-coding colors when practical. +- Keep interactions visually quiet and consistent: use unobtrusive controls, + clear selected and focus states, and touch targets appropriate to each + platform. +- Do not introduce Material-styled widgets into Forui product surfaces. Use the + existing project patterns for platform integration where needed. From d93b570610b62101a946746f31ac8bbaf25ee0c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?AshGrey=F0=9F=A5=95?= Date: Thu, 29 Oct 2026 21:15:17 +0800 Subject: [PATCH 12/26] refactor(cli): split command dispatch from runtime Move CLI command definitions into a CommandRunner and service operations into CliRuntime. Preserve existing commands and implicit material-list and cover-download behavior, with command-runner tests. --- packages/cli/bin/thulium.dart | 770 +----------------- packages/cli/lib/cli_command_runner.dart | 312 +++++++ packages/cli/lib/cli_runtime.dart | 640 +++++++++++++++ .../cli/test/cli_command_runner_test.dart | 165 ++++ 4 files changed, 1125 insertions(+), 762 deletions(-) create mode 100644 packages/cli/lib/cli_command_runner.dart create mode 100644 packages/cli/lib/cli_runtime.dart create mode 100644 packages/cli/test/cli_command_runner_test.dart diff --git a/packages/cli/bin/thulium.dart b/packages/cli/bin/thulium.dart index 280dd28..d7e48d1 100644 --- a/packages/cli/bin/thulium.dart +++ b/packages/cli/bin/thulium.dart @@ -1,32 +1,14 @@ -import 'dart:async'; -import 'dart:convert'; import 'dart:io'; -import 'package:args/args.dart'; -import 'package:thulium_campus/thulium_campus.dart'; -import 'package:thulium_auth/thulium_auth.dart'; +import 'package:args/command_runner.dart'; import 'package:thulium_cli/cli_auth_session_store.dart'; -import 'package:thulium_cli/cli_course_schedule_cache_store.dart'; -import 'package:thulium_cli/cli_learn_course_cache_store.dart'; -import 'package:thulium_cli/cli_session_reconnect.dart'; -import 'package:thulium_cli/learn_course_formatter.dart'; -import 'package:thulium_cli/learn_homework_formatter.dart'; -import 'package:thulium_cli/learn_materials_formatter.dart'; -import 'package:thulium_cli/material_download_file.dart'; - -// Uppercase snake case is the project convention for named constants. -// ignore_for_file: constant_identifier_names - -const _DEFAULT_FINGERPRINT_PREFIX = 'thulium-cli'; +import 'package:thulium_cli/cli_command_runner.dart'; Future main(List arguments) async { - final parser = _buildParser(); try { - final command = parser.parse(arguments); - await _runCommand(command); - } on FormatException catch (error) { - stderr.writeln('Error: ${error.message}'); - stderr.writeln(parser.usage); + await ThuliumCommandRunner().run(arguments); + } on UsageException catch (error) { + stderr.writeln(error); exitCode = 2; } on CliAuthStorageException catch (error) { stderr.writeln('Secure storage error: ${error.message}'); @@ -34,747 +16,11 @@ Future main(List arguments) async { 'Make sure an operating system keyring is available and unlocked.', ); exitCode = 1; + } on FormatException catch (error) { + stderr.writeln('Error: ${error.message}'); + exitCode = 2; } catch (error) { stderr.writeln('Error: $error'); exitCode = 1; } } - -ArgParser _buildParser() { - final parser = ArgParser(); - parser.addCommand( - 'login', - ArgParser() - ..addFlag( - 'force', - abbr: 'f', - help: 'Ignore the stored session and log in again.', - ) - ..addFlag('verbose', help: 'Print safe authentication diagnostics.'), - ); - parser.addCommand('logout'); - parser.addCommand('status'); - parser.addCommand( - 'session', - ArgParser() - ..addCommand('inspect') - ..addCommand('reveal-cookies'), - ); - parser.addCommand( - 'schedule', - ArgParser() - ..addFlag('verbose', help: 'Print safe request diagnostics.') - ..addFlag( - 'refresh', - help: 'Fetch the latest calendar instead of using the cache.', - ), - ); - parser.addCommand( - 'learn-courses', - ArgParser() - ..addOption( - 'semester', - abbr: 's', - help: 'Academic semester ID (defaults to the current semester).', - ) - ..addFlag('verbose', help: 'Print safe request diagnostics.') - ..addFlag('refresh', help: 'Fetch courses instead of using the cache.'), - ); - parser.addCommand( - 'learn-homework', - ArgParser() - ..addOption( - 'semester', - abbr: 's', - help: 'Academic semester ID (defaults to the current semester).', - ) - ..addFlag('verbose', help: 'Print safe request diagnostics.') - ..addFlag('refresh', help: 'Refresh the course list before counting.'), - ); - parser.addCommand( - 'learn-materials', - ArgParser() - ..addCommand('download', _materialDownloadParser()) - ..addOption( - 'semester', - abbr: 's', - help: 'Academic semester ID (defaults to the current semester).', - ) - ..addOption( - 'course-id', - help: 'List only this course from the semester catalog.', - ) - ..addOption( - 'size', - defaultsTo: '200', - help: 'Maximum materials requested per course (not a total count).', - ) - ..addFlag('verbose', help: 'Print safe request diagnostics.') - ..addFlag( - 'refresh', - help: 'Refresh the course catalog before listing materials.', - ) - ..addFlag( - 'help', - abbr: 'h', - negatable: false, - help: 'Show command usage.', - ), - ); - parser.addCommand( - 'learn-materials-cover', - _materialDownloadParser(cover: true) - ..addCommand('download', _materialDownloadParser(cover: true)), - ); - return parser; -} - -ArgParser _materialDownloadParser({bool cover = false}) => ArgParser() - ..addOption('file-id', help: 'File ID from learn-materials output.') - ..addOption('course-id', help: 'Course ID that owns the file.') - ..addOption( - 'output', - abbr: 'o', - help: 'Destination path (defaults to FILE_ID${cover ? '-cover' : ''}.pdf).', - ) - ..addFlag('force', negatable: false, help: 'Replace an existing output file.') - ..addFlag('verbose', help: 'Print safe request diagnostics.') - ..addFlag('help', abbr: 'h', negatable: false, help: 'Show download usage.'); - -Future _runCommand(ArgResults command) async { - final name = command.command?.name; - if (name == null) { - stdout.writeln( - 'Usage: thulium ', - ); - return; - } - - int? materialSize; - final isMaterialDownload = - name == 'learn-materials-cover' || - (name == 'learn-materials' && - command.command!.command?.name == 'download'); - final materialOptions = isMaterialDownload - ? command.command!.command ?? command.command! - : command.command!; - String? materialOutput; - if (name == 'learn-materials' || name == 'learn-materials-cover') { - if (materialOptions['help'] as bool || - (isMaterialDownload && command.command!['help'] as bool)) { - final parser = _buildParser().commands[name]!; - stdout.writeln( - 'Usage: thulium $name${command.command!.command?.name == 'download' ? ' download' : ''} [options]', - ); - stdout.writeln( - command.command!.command?.name == 'download' - ? parser.commands['download']!.usage - : parser.usage, - ); - return; - } - if (isMaterialDownload) { - for (final name in ['file-id', 'course-id']) { - final value = materialOptions[name] as String?; - if (value == null || !RegExp(r'^[A-Za-z0-9_-]+$').hasMatch(value)) { - throw FormatException( - '--$name is required and must be a valid Learn ID.', - ); - } - } - materialOutput = - materialOptions['output'] as String? ?? - '${materialOptions['file-id']}${name == 'learn-materials-cover' ? '-cover' : ''}.pdf'; - if (materialOutput.trim().isEmpty) { - throw const FormatException('--output must not be empty.'); - } - if (!(materialOptions['force'] as bool) && - await FileSystemEntity.type(materialOutput, followLinks: false) != - FileSystemEntityType.notFound) { - throw FileSystemException( - 'Output already exists. Use --force to replace it.', - materialOutput, - ); - } - } else { - materialSize = int.tryParse(materialOptions['size'] as String); - if (materialSize == null || materialSize <= 0) { - throw const FormatException('--size must be a positive integer.'); - } - final courseId = materialOptions['course-id'] as String?; - if (courseId != null && courseId.trim().isEmpty) { - throw const FormatException('--course-id must not be empty.'); - } - } - if (materialOptions.rest.isNotEmpty) { - throw const FormatException('Specify IDs using the named options.'); - } - } - - final store = CliAuthSessionStore(); - final calendarCache = CourseScheduleCache(CliCourseScheduleCacheStore()); - final learnCache = LearnCourseCache(CliLearnCourseCacheStore()); - final promptOutput = - name == 'learn-homework' || - name == 'learn-materials' || - name == 'learn-materials-cover' - ? stderr - : stdout; - final client = TsinghuaAuthClient( - sessionStore: store, - credentialStore: store, - twoFactorMethodHandler: (options) => - _handleTwoFactorMethod(options, output: promptOutput), - twoFactorCodeHandler: (verify) => - _readTwoFactorCode(verify, output: promptOutput), - twoFactorTrustHandler: () => _askToTrustDevice(output: promptOutput), - trace: _verboseRequested(name, command.command!) - ? (message) => stderr.writeln('[auth] $message') - : null, - ); - final reconnect = CliSessionReconnect( - credentialStore: store, - signIn: ({required userId, required password, required fingerprint}) async { - await client.login( - userId: userId, - password: password, - fingerprint: fingerprint, - ); - }, - interactive: stdin.hasTerminal, - askToSignIn: (commandName) { - final answer = _readLine( - 'Sign in again to retry $commandName? [Y/n]: ', - output: promptOutput, - ).toLowerCase(); - return answer.isEmpty || answer == 'y' || answer == 'yes'; - }, - readPassword: () => _readSecret('Password: ', output: promptOutput), - writeMessage: promptOutput.writeln, - writeError: stderr.writeln, - ); - - switch (name) { - case 'login': - await _login(client, force: command.command!['force'] as bool); - case 'logout': - // Each CLI invocation starts with an empty in-memory cookie jar. Restore - // the persisted session so the logout request can invalidate it remotely. - await client.restore(); - try { - await client.logout(); - } finally { - await calendarCache.clear(); - await learnCache.clear(); - } - stdout.writeln('Logged out.'); - case 'status': - final session = await client.restore(); - if (session == null) { - stdout.writeln('Not logged in.'); - } else { - stdout.writeln('Logged in as ${session.userId}.'); - } - case 'session': - await _runSessionCommand(client, command.command!); - case 'schedule': - final session = await client.restore(); - if (session == null) { - throw StateError('Not logged in. Run `thulium login` first.'); - } - stdout.writeln('Loading the current academic calendar...'); - final schedule = await _loadScheduleWithReconnect( - client, - reconnect, - session, - cache: calendarCache, - forceRefresh: command.command!['refresh'] as bool, - ); - _printSchedule(schedule); - case 'learn-courses': - final session = await client.restore(); - if (session == null) { - throw StateError('Not logged in. Run `thulium login` first.'); - } - final semester = - (command.command!['semester'] as String?) ?? - AcademicSemester.forDate(DateTime.now()); - final catalogService = LearnCourseCatalogService( - client, - cache: learnCache, - ); - final catalog = await reconnect.run( - commandName: 'learn-courses', - savedSession: session, - request: (isRetry) => catalogService.loadSemester( - semester, - forceRefresh: isRetry || command.command!['refresh'] as bool, - ), - shouldReconnect: (error) => - error is PortalCsrfUnavailable || error is PortalSessionRejected, - ); - if (catalogService.lastSource == LearnCourseSource.staleCache) { - stderr.writeln('Update failed; showing the saved course list.'); - } - stdout.writeln( - formatLearnCourses( - catalog.rawResponse ?? - { - 'currentUser': catalog.userId, - 'resultList': [ - for (final course in catalog.courses) - { - 'wlkcid': course.id, - 'kcm': course.name, - 'ywkcm': course.englishName, - 'jsm': course.teacherName, - 'sjddb': course.schedule, - }, - ], - }, - semester: semester, - ), - ); - case 'learn-materials-cover': - case 'learn-materials': - final session = await client.restore(); - if (session == null) { - throw StateError('Not logged in. Run `thulium login` first.'); - } - if (isMaterialDownload) { - final bytes = await reconnect.run( - commandName: name == 'learn-materials-cover' - ? name - : 'learn-materials download', - savedSession: session, - request: (_) { - final service = LearnMaterialService(client); - final download = name == 'learn-materials-cover' - ? service.downloadPdfCover - : service.downloadPdf; - return download( - fileId: materialOptions['file-id'] as String, - courseId: materialOptions['course-id'] as String, - ); - }, - shouldReconnect: (error) => - error is PortalCsrfUnavailable || error is PortalSessionRejected, - ); - final saved = await saveMaterialDownload( - bytes, - outputPath: materialOutput!, - overwrite: materialOptions['force'] as bool, - ); - stdout.writeln('Saved ${bytes.length} bytes to ${saved.path}'); - return; - } - final semester = - (command.command!['semester'] as String?) ?? - AcademicSemester.forDate(DateTime.now()); - final catalogService = LearnCourseCatalogService( - client, - cache: learnCache, - ); - final materials = await reconnect.run( - commandName: 'learn-materials', - savedSession: session, - request: (isRetry) async { - final catalog = await catalogService.loadSemester( - semester, - forceRefresh: isRetry || command.command!['refresh'] as bool, - ); - if (catalogService.lastSource == LearnCourseSource.staleCache) { - stderr.writeln('Update failed; using the saved course list.'); - } - return LearnMaterialService(client).fetchCourses( - catalog, - courseId: command.command!['course-id'] as String?, - size: materialSize!, - ); - }, - shouldReconnect: (error) => - error is PortalCsrfUnavailable || error is PortalSessionRejected, - ); - stdout.writeln( - formatLearnMaterials( - materials, - studentId: session.userId, - semester: semester, - ), - ); - case 'learn-homework': - final session = await client.restore(); - if (session == null) { - throw StateError('Not logged in. Run `thulium login` first.'); - } - final semester = - (command.command!['semester'] as String?) ?? - AcademicSemester.forDate(DateTime.now()); - final catalogService = LearnCourseCatalogService( - client, - cache: learnCache, - ); - final homework = await reconnect.run( - commandName: 'learn-homework', - savedSession: session, - request: (isRetry) async { - final catalog = await catalogService.loadSemester( - semester, - forceRefresh: isRetry || command.command!['refresh'] as bool, - ); - if (catalogService.lastSource == LearnCourseSource.staleCache) { - stderr.writeln('Update failed; using the saved course list.'); - } - return LearnHomeworkService(client).fetchCourses(catalog); - }, - shouldReconnect: (error) => - error is PortalCsrfUnavailable || error is PortalSessionRejected, - ); - stdout.writeln( - formatLearnHomework( - homework, - studentId: session.userId, - semester: semester, - ), - ); - } -} - -Future _loadScheduleWithReconnect( - TsinghuaAuthClient client, - CliSessionReconnect reconnect, - AuthSession savedSession, { - required CourseScheduleCache cache, - required bool forceRefresh, -}) async { - CourseScheduleSource? source; - final schedule = await reconnect.run( - commandName: 'schedule', - savedSession: savedSession, - request: (isRetry) async { - final service = CourseScheduleService( - client, - cache: cache, - trace: (message) { - if (client.trace != null) stderr.writeln('[calendar] $message'); - }, - ); - final result = await service.loadCurrentTerm( - forceRefresh: forceRefresh || isRetry, - ); - source = service.lastSource; - return result; - }, - shouldReconnect: (error) => - error is CourseScheduleSessionExpired || - (error is CourseScheduleException && - error.cause is PortalCsrfUnavailable), - ); - if (source == CourseScheduleSource.freshCache) { - stdout.writeln('Using the saved academic calendar.'); - } else if (source == CourseScheduleSource.staleCache) { - stdout.writeln( - 'The update failed; showing an older saved academic calendar.', - ); - } - return schedule; -} - -Future _runSessionCommand( - TsinghuaAuthClient client, - ArgResults command, -) async { - final action = command.command?.name; - if (action == null) { - stdout.writeln('Usage: thulium session '); - return; - } - if (action == 'reveal-cookies' && - (!stdin.hasTerminal || !stdout.hasTerminal)) { - throw StateError( - 'Cookie values can only be revealed in an interactive terminal.', - ); - } - - final session = await client.restore(); - if (session == null) { - stdout.writeln('No stored session. Run `thulium login` first.'); - return; - } - - switch (action) { - case 'inspect': - _printSessionMetadata(session); - case 'reveal-cookies': - await _revealSessionCookies(session); - } -} - -void _printSessionMetadata(AuthSession session) { - final now = DateTime.now().toUtc(); - final cookies = session.scopedCookies; - stdout.writeln('Account: ${session.userId}'); - stdout.writeln('Scoped cookies: ${cookies.length}'); - if (cookies.isEmpty) { - stdout.writeln('No scoped cookies are stored.'); - return; - } - - for (final cookie in cookies) { - final expiry = cookie.expiresAt?.toUtc(); - final expiryLabel = expiry == null - ? 'session cookie' - : expiry.isBefore(now) - ? 'expired ${expiry.toIso8601String()}' - : 'expires ${expiry.toIso8601String()}'; - stdout.writeln( - '- ${cookie.name}: domain=${cookie.domain}, path=${cookie.path}, ' - 'hostOnly=${cookie.hostOnly}, secure=${cookie.secure}, $expiryLabel', - ); - } - stdout.writeln('Cookie values are hidden.'); -} - -Future _revealSessionCookies(AuthSession session) async { - if (!stdin.hasTerminal || !stdout.hasTerminal) { - throw StateError( - 'Cookie values can only be revealed in an interactive terminal.', - ); - } - - stderr.writeln( - 'Warning: These cookies are active login credentials. Anyone who sees ' - 'them may be able to use your account until the session expires or is ' - 'revoked. Do not capture, share, or redirect this output.', - ); - if (_readLine('Type REVEAL COOKIES to continue: ') != 'REVEAL COOKIES') { - stdout.writeln('Cancelled.'); - return; - } - - if (session.scopedCookies.isEmpty) { - stdout.writeln('No scoped cookies are stored.'); - return; - } - - stdout.writeln('Stored cookie values (sensitive):'); - for (final cookie in session.scopedCookies) { - // JSON string encoding keeps control characters from affecting the - // terminal while leaving each secret value visible for manual inspection. - stdout.writeln( - '${cookie.name}=${jsonEncode(cookie.value)}\t' - 'domain=${cookie.domain}; path=${cookie.path}; ' - 'hostOnly=${cookie.hostOnly}; secure=${cookie.secure}', - ); - } -} - -bool _verboseRequested(String commandName, ArgResults command) { - if ((commandName == 'learn-materials' || - commandName == 'learn-materials-cover') && - command.command?.name == 'download') { - return command.command!['verbose'] as bool || command['verbose'] as bool; - } - return (commandName == 'login' || - commandName == 'schedule' || - commandName == 'learn-courses' || - commandName == 'learn-homework' || - (commandName == 'learn-materials' || - commandName == 'learn-materials-cover')) && - command['verbose'] as bool; -} - -void _printSchedule(CourseSchedule schedule) { - final courses = schedule.occurrences.toList() - ..sort((left, right) => left.startsAt.compareTo(right.startsAt)); - stdout.writeln('${schedule.term.name} (${schedule.term.weekCount} weeks)'); - stdout.writeln('Fetched ${courses.length} course occurrences.'); - if (courses.isEmpty) { - stdout.writeln('No course occurrences were returned.'); - return; - } - - for (final course in courses) { - final start = course.startsAt; - final end = course.endsAt; - final date = - '${start.year.toString().padLeft(4, '0')}-' - '${start.month.toString().padLeft(2, '0')}-' - '${start.day.toString().padLeft(2, '0')}'; - final startTime = - '${start.hour.toString().padLeft(2, '0')}:' - '${start.minute.toString().padLeft(2, '0')}'; - final endTime = - '${end.hour.toString().padLeft(2, '0')}:' - '${end.minute.toString().padLeft(2, '0')}'; - final location = course.location.isEmpty ? '' : ' @ ${course.location}'; - stdout.writeln( - '$date ${_WEEKDAY_NAMES[start.weekday - 1]} ' - '$startTime-$endTime ${course.name}$location', - ); - } -} - -const _WEEKDAY_NAMES = [ - 'Mon', - 'Tue', - 'Wed', - 'Thu', - 'Fri', - 'Sat', - 'Sun', -]; - -Future _login(TsinghuaAuthClient client, {required bool force}) async { - while (true) { - try { - await _loginAttempt(client, force: force); - return; - } catch (error) { - // A failed password, expired verification code, or temporary network - // error should not terminate an interactive login session. Each retry - // starts the complete flow again so stale cookies and one-time codes are - // not accidentally reused. - stderr.writeln('Login attempt failed: $error'); - if (!_askToRetry()) return; - force = true; - } - } -} - -Future _loginAttempt( - TsinghuaAuthClient client, { - required bool force, -}) async { - if (!force) { - final existing = await client.restore(); - if (existing != null) { - stdout.writeln('Already logged in as ${existing.userId}.'); - stdout.writeln('Use `thulium login --force` to replace the session.'); - return; - } - } - - final userId = _readLine('Tsinghua student ID: '); - if (userId.isEmpty) throw const FormatException('Student ID is required.'); - - // The password is read without terminal echo and is never passed as a - // command-line argument, where it could be exposed through process listings. - final password = _readSecret('Password: '); - if (password.isEmpty) throw const FormatException('Password is required.'); - - // Preserve the trusted-device identity on forced reauthentication. The - // account check prevents reusing another user's fingerprint on this host. - final previousSession = await client.restore(); - final fingerprint = previousSession?.userId == userId - ? previousSession!.fingerprint - : _buildFingerprint(); - - stdout.writeln('Signing in...'); - final session = await client.login( - userId: userId, - password: password, - fingerprint: fingerprint, - ); - stdout.writeln('Login succeeded for ${session.userId}.'); - stdout.writeln('The session was saved in the operating system keyring.'); -} - -bool _askToRetry() { - if (!stdin.hasTerminal) return false; - final answer = _readLine('Retry login? [Y/n]: ').toLowerCase(); - // Retrying is the default because transient network failures and expired - // one-time codes are common during interactive authentication. - return answer.isEmpty || answer == 'y' || answer == 'yes'; -} - -Future _handleTwoFactorMethod( - TwoFactorOptions options, { - IOSink? output, -}) async { - final sink = output ?? stdout; - sink.writeln('Two-factor authentication is required.'); - sink.writeln('Available methods:'); - final methods = <({TwoFactorMethod method, String label})>[]; - if (options.hasWeChat) { - methods.add((method: TwoFactorMethod.wechat, label: 'WeChat')); - } - if (options.phone != null) { - methods.add(( - method: TwoFactorMethod.mobile, - label: 'SMS (${options.phone})', - )); - } - if (options.hasTotp) { - methods.add((method: TwoFactorMethod.totp, label: 'TOTP')); - } - for (var index = 0; index < methods.length; index++) { - sink.writeln(' ${index + 1}. ${methods[index].label}'); - } - if (methods.isEmpty) { - throw StateError('The account has no available two-factor methods.'); - } - - final choice = int.tryParse(_readLine('Choose a method: ', output: sink)); - if (choice == null || choice < 1 || choice > methods.length) { - throw const FormatException('The selected method is unavailable.'); - } - return methods[choice - 1].method; -} - -Future _readTwoFactorCode( - TwoFactorCodeVerifier verifyCode, { - IOSink? output, -}) async { - final sink = output ?? stdout; - // This callback runs only after SEND_CODE succeeds, so the notification is - // expected to be available before the user is asked for the code. - sink.writeln('A verification code was sent.'); - while (true) { - final code = _readLine('Verification code: ', output: sink); - if (await verifyCode(code)) return; - sink.writeln('The verification code was not accepted. Please try again.'); - } -} - -Future _askToTrustDevice({IOSink? output}) async { - final sink = output ?? stdout; - sink.writeln( - 'Trust this device to reduce future verification prompts? Only choose yes ' - 'on a device you control.', - ); - final answer = _readLine( - 'Trust this device? [y/N]: ', - output: sink, - ).toLowerCase(); - return answer == 'y' || answer == 'yes'; -} - -String _buildFingerprint() { - // A stable, non-secret identifier makes the identity provider's device - // fingerprint consistent across CLI invocations without storing a password. - return '$_DEFAULT_FINGERPRINT_PREFIX:${Platform.operatingSystem}:' - '${Platform.localHostname}'; -} - -String _readLine(String prompt, {IOSink? output}) { - (output ?? stdout).write(prompt); - return stdin.readLineSync()?.trim() ?? ''; -} - -String _readSecret(String prompt, {IOSink? output}) { - final sink = output ?? stdout; - sink.write(prompt); - if (!stdin.hasTerminal) { - return stdin.readLineSync() ?? ''; - } - - final echoMode = stdin.echoMode; - try { - stdin.echoMode = false; - return stdin.readLineSync() ?? ''; - } finally { - stdin.echoMode = echoMode; - sink.writeln(); - } -} diff --git a/packages/cli/lib/cli_command_runner.dart b/packages/cli/lib/cli_command_runner.dart new file mode 100644 index 0000000..1ebadec --- /dev/null +++ b/packages/cli/lib/cli_command_runner.dart @@ -0,0 +1,312 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:args/args.dart'; +import 'package:args/command_runner.dart'; + +import 'cli_runtime.dart'; + +/// Standard args command dispatch, with compatibility for implicit list and +/// cover-download operations in earlier versions of the CLI. +class ThuliumCommandRunner extends CommandRunner { + ThuliumCommandRunner({CliRuntime? runtime, void Function(String)? writeLine}) + : writeLine = writeLine ?? stdout.writeln, + super( + 'thulium', + 'Tsinghua campus services from your terminal.', + usageLineLength: 100, + ) { + final operations = runtime ?? CliRuntime(); + addCommand( + _ActionCommand( + 'login', + 'Sign in and save the session in the operating system keyring.', + operations.login, + category: 'Account', + configure: (parser) { + parser.addFlag( + 'force', + abbr: 'f', + help: 'Ignore the stored session and log in again.', + ); + _verbose(parser); + }, + examples: ['thulium login', 'thulium login --force --verbose'], + ), + ); + addCommand( + _ActionCommand( + 'logout', + 'Sign out and clear the saved session and course caches.', + operations.logout, + category: 'Account', + ), + ); + addCommand( + _ActionCommand( + 'status', + 'Show whether a session is stored and which account it belongs to.', + operations.status, + category: 'Account', + ), + ); + final session = _ActionCommand( + 'session', + 'Inspect stored session metadata or explicitly reveal cookies.', + null, + category: 'Account', + ); + session.addSubcommand( + _ActionCommand( + 'inspect', + 'Show cookie scope and expiration without revealing values.', + operations.inspectSession, + ), + ); + session.addSubcommand( + _ActionCommand( + 'reveal-cookies', + 'Reveal cookie values after confirmation in an interactive terminal.', + operations.revealCookies, + ), + ); + addCommand(session); + addCommand( + _ActionCommand( + 'schedule', + 'Show the current academic calendar.', + operations.schedule, + category: 'Campus', + configure: (parser) { + _verbose(parser); + parser.addFlag( + 'refresh', + help: 'Fetch the latest calendar instead of using the cache.', + ); + }, + examples: ['thulium schedule --refresh'], + ), + ); + addCommand( + _ActionCommand( + 'learn-courses', + 'List semester courses as YAML.', + operations.courses, + category: 'Learn', + configure: _catalogOptions, + examples: [ + 'thulium learn-courses', + 'thulium learn-courses --semester 2026-2027-1 --refresh', + ], + ), + ); + addCommand( + _ActionCommand( + 'learn-homework', + 'Show assignment counts for all semester courses as YAML.', + operations.homework, + category: 'Learn', + configure: _catalogOptions, + examples: ['thulium learn-homework --semester 2026-2027-1'], + ), + ); + final materials = _ActionCommand( + 'learn-materials', + 'List course materials or download a complete PDF.', + null, + category: 'Learn', + configure: _materialOptions, + examples: [ + 'thulium learn-materials', + 'thulium learn-materials list --course-id COURSE_ID', + 'thulium learn-materials download --course-id COURSE_ID --file-id FILE_ID -o material.pdf', + ], + ); + materials.addSubcommand( + _ActionCommand( + 'list', + 'List material metadata as YAML; defaults to up to 200 files per course.', + operations.materials, + configure: _materialOptions, + ), + ); + materials.addSubcommand( + _ActionCommand( + 'download', + 'Download all pages of the PDF representation.', + operations.downloadMaterial, + configure: _downloadOptions, + examples: [ + 'thulium learn-materials download --course-id COURSE_ID --file-id FILE_ID -o material.pdf', + ], + ), + ); + addCommand(materials); + final cover = _ActionCommand( + 'learn-materials-cover', + 'Download the first-page PDF cover preview.', + null, + category: 'Learn', + configure: (parser) => _downloadOptions(parser, cover: true), + examples: [ + 'thulium learn-materials-cover --course-id COURSE_ID --file-id FILE_ID -o cover.pdf', + ], + ); + cover.addSubcommand( + _ActionCommand( + 'download', + 'Download the first-page PDF cover preview.', + (options) => operations.downloadMaterial(options, cover: true), + configure: (parser) => _downloadOptions(parser, cover: true), + ), + ); + addCommand(cover); + } + + final void Function(String) writeLine; + + @override + String get usageFooter => + 'Examples:\n thulium login\n thulium learn-materials --course-id COURSE_ID\n thulium help learn-materials download'; + + @override + void printUsage() => writeLine(usage); + + @override + ArgResults parse(Iterable args) { + final arguments = args.toList(); + final parsed = super.parse(arguments); + final command = parsed.command; + // Only supply an implicit operation when no explicit/unknown subcommand + // or help request is present. args remains responsible for all dispatch. + if (command != null && + command.command == null && + command.rest.isEmpty && + !parsed.flag('help') && + !command.flag('help')) { + final implicit = { + 'learn-materials': 'list', + 'learn-materials-cover': 'download', + 'session': '--help', + }[command.name]; + if (implicit != null) return super.parse([...arguments, implicit]); + } + return parsed; + } +} + +typedef _Action = Future Function(Map options); + +class _ActionCommand extends Command { + _ActionCommand( + this.name, + this.description, + this.action, { + this.category = '', + void Function(ArgParser)? configure, + this.examples = const [], + }) { + configure?.call(argParser); + } + + @override + final String name; + @override + final String description; + @override + final String category; + @override + bool get takesArguments => false; + + final _Action? action; + final List examples; + + @override + String? get usageFooter => examples.isEmpty + ? null + : 'Examples:\n${examples.map((example) => ' $example').join('\n')}'; + + @override + void printUsage() => (runner! as ThuliumCommandRunner).writeLine(usage); + + @override + Future run() async { + final options = {}; + // Preserve parent flags used before a subcommand; explicitly supplied leaf + // options take precedence, otherwise use the parent's supplied value. + final lineage = >[]; + for (Command? node = this; node != null; node = node.parent) { + lineage.insert(0, node); + } + for (final node in lineage) { + final results = node.argResults!; + for (final key in results.options) { + if (!options.containsKey(key) || results.wasParsed(key)) { + options[key] = results[key]; + } + } + } + try { + await action!(options); + } on FormatException catch (error) { + usageException(error.message); + } + } +} + +void _verbose(ArgParser parser) => + parser.addFlag('verbose', help: 'Print safe request diagnostics.'); + +void _catalogOptions(ArgParser parser) { + parser.addOption( + 'semester', + abbr: 's', + valueHelp: 'ID', + help: 'Academic semester ID (defaults to the current semester).', + ); + _verbose(parser); + parser.addFlag( + 'refresh', + help: 'Fetch the latest course catalog instead of using the cache.', + ); +} + +void _materialOptions(ArgParser parser) { + _catalogOptions(parser); + parser.addOption( + 'course-id', + valueHelp: 'ID', + help: 'List only this course from the semester catalog.', + ); + parser.addOption( + 'size', + valueHelp: 'COUNT', + defaultsTo: '200', + help: 'Maximum materials requested per course; not a total count.', + ); +} + +void _downloadOptions(ArgParser parser, {bool cover = false}) { + parser.addOption( + 'file-id', + valueHelp: 'ID', + help: 'Required. File ID from the material list.', + ); + parser.addOption( + 'course-id', + valueHelp: 'ID', + help: 'Required. Course ID that owns the file.', + ); + parser.addOption( + 'output', + abbr: 'o', + valueHelp: 'PATH', + help: 'Destination (defaults to FILE_ID${cover ? '-cover' : ''}.pdf).', + ); + parser.addFlag( + 'force', + negatable: false, + help: 'Replace an existing output file.', + ); + _verbose(parser); +} diff --git a/packages/cli/lib/cli_runtime.dart b/packages/cli/lib/cli_runtime.dart new file mode 100644 index 0000000..cae1fa8 --- /dev/null +++ b/packages/cli/lib/cli_runtime.dart @@ -0,0 +1,640 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:thulium_campus/thulium_campus.dart'; +import 'package:thulium_auth/thulium_auth.dart'; +import 'package:thulium_cli/cli_auth_session_store.dart'; +import 'package:thulium_cli/cli_course_schedule_cache_store.dart'; +import 'package:thulium_cli/cli_learn_course_cache_store.dart'; +import 'package:thulium_cli/cli_session_reconnect.dart'; +import 'package:thulium_cli/learn_course_formatter.dart'; +import 'package:thulium_cli/learn_homework_formatter.dart'; +import 'package:thulium_cli/learn_materials_formatter.dart'; +import 'package:thulium_cli/material_download_file.dart'; + +// ignore_for_file: constant_identifier_names +const _DEFAULT_FINGERPRINT_PREFIX = 'thulium-cli'; + +/// Executes CLI operations. Construction and help never access secure storage. +class CliRuntime { + Future login(Map options) async { + final context = _context('login', options['verbose'] == true); + await _login(context.client, force: options['force'] as bool); + } + + Future logout(Map options) async { + final context = _context('logout', options['verbose'] == true); + // Each CLI invocation starts with an empty in-memory cookie jar. Restore + // the persisted session so the logout request can invalidate it remotely. + await context.client.restore(); + try { + await context.client.logout(); + } finally { + await context.calendarCache.clear(); + await context.learnCache.clear(); + } + stdout.writeln('Logged out.'); + } + + Future status(Map options) async { + final context = _context('status', options['verbose'] == true); + final session = await context.client.restore(); + if (session == null) { + stdout.writeln('Not logged in.'); + } else { + stdout.writeln('Logged in as ${session.userId}.'); + } + } + + Future schedule(Map options) async { + final context = _context('schedule', options['verbose'] == true); + final session = await context.client.restore(); + if (session == null) { + throw StateError('Not logged in. Run `thulium login` first.'); + } + stdout.writeln('Loading the current academic calendar...'); + final schedule = await _loadScheduleWithReconnect( + context.client, + context.reconnect, + session, + cache: context.calendarCache, + forceRefresh: options['refresh'] as bool, + ); + _printSchedule(schedule); + } + + Future courses(Map options) async { + final context = _context('learn-courses', options['verbose'] == true); + final session = await context.client.restore(); + if (session == null) { + throw StateError('Not logged in. Run `thulium login` first.'); + } + final semester = + (options['semester'] as String?) ?? + AcademicSemester.forDate(DateTime.now()); + final catalogService = LearnCourseCatalogService( + context.client, + cache: context.learnCache, + ); + final catalog = await context.reconnect.run( + commandName: 'learn-courses', + savedSession: session, + request: (isRetry) => catalogService.loadSemester( + semester, + forceRefresh: isRetry || options['refresh'] as bool, + ), + shouldReconnect: (error) => + error is PortalCsrfUnavailable || error is PortalSessionRejected, + ); + if (catalogService.lastSource == LearnCourseSource.staleCache) { + stderr.writeln('Update failed; showing the saved course list.'); + } + stdout.writeln( + formatLearnCourses( + catalog.rawResponse ?? + { + 'currentUser': catalog.userId, + 'resultList': [ + for (final course in catalog.courses) + { + 'wlkcid': course.id, + 'kcm': course.name, + 'ywkcm': course.englishName, + 'jsm': course.teacherName, + 'sjddb': course.schedule, + }, + ], + }, + semester: semester, + ), + ); + } + + Future homework(Map options) async { + final context = _context('learn-homework', options['verbose'] == true); + final session = await context.client.restore(); + if (session == null) { + throw StateError('Not logged in. Run `thulium login` first.'); + } + final semester = + (options['semester'] as String?) ?? + AcademicSemester.forDate(DateTime.now()); + final catalogService = LearnCourseCatalogService( + context.client, + cache: context.learnCache, + ); + final homework = await context.reconnect.run( + commandName: 'learn-homework', + savedSession: session, + request: (isRetry) async { + final catalog = await catalogService.loadSemester( + semester, + forceRefresh: isRetry || options['refresh'] as bool, + ); + if (catalogService.lastSource == LearnCourseSource.staleCache) { + stderr.writeln('Update failed; using the saved course list.'); + } + return LearnHomeworkService(context.client).fetchCourses(catalog); + }, + shouldReconnect: (error) => + error is PortalCsrfUnavailable || error is PortalSessionRejected, + ); + stdout.writeln( + formatLearnHomework( + homework, + studentId: session.userId, + semester: semester, + ), + ); + } + + Future materials(Map options) async { + final size = int.tryParse(options['size'] as String); + if (size == null || size <= 0) { + throw const FormatException('--size must be a positive integer.'); + } + final courseId = options['course-id'] as String?; + if (courseId != null && courseId.trim().isEmpty) { + throw const FormatException('--course-id must not be empty.'); + } + final context = _context('learn-materials', options['verbose'] == true); + final session = await context.client.restore(); + if (session == null) { + throw StateError('Not logged in. Run `thulium login` first.'); + } + final semester = + (options['semester'] as String?) ?? + AcademicSemester.forDate(DateTime.now()); + final catalogService = LearnCourseCatalogService( + context.client, + cache: context.learnCache, + ); + final materials = await context.reconnect.run( + commandName: 'learn-materials', + savedSession: session, + request: (isRetry) async { + final catalog = await catalogService.loadSemester( + semester, + forceRefresh: isRetry || options['refresh'] as bool, + ); + if (catalogService.lastSource == LearnCourseSource.staleCache) { + stderr.writeln('Update failed; using the saved course list.'); + } + return LearnMaterialService(context.client).fetchCourses( + catalog, + courseId: options['course-id'] as String?, + size: size, + ); + }, + shouldReconnect: (error) => + error is PortalCsrfUnavailable || error is PortalSessionRejected, + ); + stdout.writeln( + formatLearnMaterials( + materials, + studentId: session.userId, + semester: semester, + ), + ); + } + + Future downloadMaterial( + Map options, { + bool cover = false, + }) async { + for (final key in ['file-id', 'course-id']) { + final value = options[key] as String?; + if (value == null || !RegExp(r'^[A-Za-z0-9_-]+$').hasMatch(value)) { + throw FormatException( + '--$key is required and must be a valid Learn ID.', + ); + } + } + final output = + options['output'] as String? ?? + '${options['file-id']}${cover ? '-cover' : ''}.pdf'; + if (output.trim().isEmpty) { + throw const FormatException('--output must not be empty.'); + } + if (!(options['force'] as bool) && + await FileSystemEntity.type(output, followLinks: false) != + FileSystemEntityType.notFound) { + throw FileSystemException( + 'Output already exists. Use --force to replace it.', + output, + ); + } + final context = _context( + cover ? 'learn-materials-cover' : 'learn-materials', + options['verbose'] == true, + ); + + final session = await context.client.restore(); + if (session == null) { + throw StateError('Not logged in. Run `thulium login` first.'); + } + + final bytes = await context.reconnect.run( + commandName: cover ? 'learn-materials-cover' : 'learn-materials download', + savedSession: session, + request: (_) { + final service = LearnMaterialService(context.client); + final download = cover ? service.downloadPdfCover : service.downloadPdf; + return download( + fileId: options['file-id'] as String, + courseId: options['course-id'] as String, + ); + }, + shouldReconnect: (error) => + error is PortalCsrfUnavailable || error is PortalSessionRejected, + ); + final saved = await saveMaterialDownload( + bytes, + outputPath: output, + overwrite: options['force'] as bool, + ); + stdout.writeln('Saved ${bytes.length} bytes to ${saved.path}'); + return; + } + + Future inspectSession(Map options) => + _runSessionCommand(_context('session', false).client, 'inspect'); + Future revealCookies(Map options) => + _runSessionCommand(_context('session', false).client, 'reveal-cookies'); +} + +typedef _Context = ({ + TsinghuaAuthClient client, + CliSessionReconnect reconnect, + CourseScheduleCache calendarCache, + LearnCourseCache learnCache, +}); + +_Context _context(String name, bool verbose) { + final store = CliAuthSessionStore(); + final calendarCache = CourseScheduleCache(CliCourseScheduleCacheStore()); + final learnCache = LearnCourseCache(CliLearnCourseCacheStore()); + final promptOutput = + name == 'learn-homework' || + name == 'learn-materials' || + name == 'learn-materials-cover' + ? stderr + : stdout; + final client = TsinghuaAuthClient( + sessionStore: store, + credentialStore: store, + twoFactorMethodHandler: (options) => + _handleTwoFactorMethod(options, output: promptOutput), + twoFactorCodeHandler: (verify) => + _readTwoFactorCode(verify, output: promptOutput), + twoFactorTrustHandler: () => _askToTrustDevice(output: promptOutput), + trace: verbose ? (message) => stderr.writeln('[auth] $message') : null, + ); + final reconnect = CliSessionReconnect( + credentialStore: store, + signIn: ({required userId, required password, required fingerprint}) async { + await client.login( + userId: userId, + password: password, + fingerprint: fingerprint, + ); + }, + interactive: stdin.hasTerminal, + askToSignIn: (commandName) { + final answer = _readLine( + 'Sign in again to retry $commandName? [Y/n]: ', + output: promptOutput, + ).toLowerCase(); + return answer.isEmpty || answer == 'y' || answer == 'yes'; + }, + readPassword: () => _readSecret('Password: ', output: promptOutput), + writeMessage: promptOutput.writeln, + writeError: stderr.writeln, + ); + return ( + client: client, + reconnect: reconnect, + calendarCache: calendarCache, + learnCache: learnCache, + ); +} + +Future _loadScheduleWithReconnect( + TsinghuaAuthClient client, + CliSessionReconnect reconnect, + AuthSession savedSession, { + required CourseScheduleCache cache, + required bool forceRefresh, +}) async { + CourseScheduleSource? source; + final schedule = await reconnect.run( + commandName: 'schedule', + savedSession: savedSession, + request: (isRetry) async { + final service = CourseScheduleService( + client, + cache: cache, + trace: (message) { + if (client.trace != null) stderr.writeln('[calendar] $message'); + }, + ); + final result = await service.loadCurrentTerm( + forceRefresh: forceRefresh || isRetry, + ); + source = service.lastSource; + return result; + }, + shouldReconnect: (error) => + error is CourseScheduleSessionExpired || + (error is CourseScheduleException && + error.cause is PortalCsrfUnavailable), + ); + if (source == CourseScheduleSource.freshCache) { + stdout.writeln('Using the saved academic calendar.'); + } else if (source == CourseScheduleSource.staleCache) { + stdout.writeln( + 'The update failed; showing an older saved academic calendar.', + ); + } + return schedule; +} + +Future _runSessionCommand( + TsinghuaAuthClient client, + String action, +) async { + if (action == 'reveal-cookies' && + (!stdin.hasTerminal || !stdout.hasTerminal)) { + throw StateError( + 'Cookie values can only be revealed in an interactive terminal.', + ); + } + + final session = await client.restore(); + if (session == null) { + stdout.writeln('No stored session. Run `thulium login` first.'); + return; + } + + switch (action) { + case 'inspect': + _printSessionMetadata(session); + case 'reveal-cookies': + await _revealSessionCookies(session); + } +} + +void _printSessionMetadata(AuthSession session) { + final now = DateTime.now().toUtc(); + final cookies = session.scopedCookies; + stdout.writeln('Account: ${session.userId}'); + stdout.writeln('Scoped cookies: ${cookies.length}'); + if (cookies.isEmpty) { + stdout.writeln('No scoped cookies are stored.'); + return; + } + + for (final cookie in cookies) { + final expiry = cookie.expiresAt?.toUtc(); + final expiryLabel = expiry == null + ? 'session cookie' + : expiry.isBefore(now) + ? 'expired ${expiry.toIso8601String()}' + : 'expires ${expiry.toIso8601String()}'; + stdout.writeln( + '- ${cookie.name}: domain=${cookie.domain}, path=${cookie.path}, ' + 'hostOnly=${cookie.hostOnly}, secure=${cookie.secure}, $expiryLabel', + ); + } + stdout.writeln('Cookie values are hidden.'); +} + +Future _revealSessionCookies(AuthSession session) async { + if (!stdin.hasTerminal || !stdout.hasTerminal) { + throw StateError( + 'Cookie values can only be revealed in an interactive terminal.', + ); + } + + stderr.writeln( + 'Warning: These cookies are active login credentials. Anyone who sees ' + 'them may be able to use your account until the session expires or is ' + 'revoked. Do not capture, share, or redirect this output.', + ); + if (_readLine('Type REVEAL COOKIES to continue: ') != 'REVEAL COOKIES') { + stdout.writeln('Cancelled.'); + return; + } + + if (session.scopedCookies.isEmpty) { + stdout.writeln('No scoped cookies are stored.'); + return; + } + + stdout.writeln('Stored cookie values (sensitive):'); + for (final cookie in session.scopedCookies) { + // JSON string encoding keeps control characters from affecting the + // terminal while leaving each secret value visible for manual inspection. + stdout.writeln( + '${cookie.name}=${jsonEncode(cookie.value)}\t' + 'domain=${cookie.domain}; path=${cookie.path}; ' + 'hostOnly=${cookie.hostOnly}; secure=${cookie.secure}', + ); + } +} + +void _printSchedule(CourseSchedule schedule) { + final courses = schedule.occurrences.toList() + ..sort((left, right) => left.startsAt.compareTo(right.startsAt)); + stdout.writeln('${schedule.term.name} (${schedule.term.weekCount} weeks)'); + stdout.writeln('Fetched ${courses.length} course occurrences.'); + if (courses.isEmpty) { + stdout.writeln('No course occurrences were returned.'); + return; + } + + for (final course in courses) { + final start = course.startsAt; + final end = course.endsAt; + final date = + '${start.year.toString().padLeft(4, '0')}-' + '${start.month.toString().padLeft(2, '0')}-' + '${start.day.toString().padLeft(2, '0')}'; + final startTime = + '${start.hour.toString().padLeft(2, '0')}:' + '${start.minute.toString().padLeft(2, '0')}'; + final endTime = + '${end.hour.toString().padLeft(2, '0')}:' + '${end.minute.toString().padLeft(2, '0')}'; + final location = course.location.isEmpty ? '' : ' @ ${course.location}'; + stdout.writeln( + '$date ${_WEEKDAY_NAMES[start.weekday - 1]} ' + '$startTime-$endTime ${course.name}$location', + ); + } +} + +const _WEEKDAY_NAMES = [ + 'Mon', + 'Tue', + 'Wed', + 'Thu', + 'Fri', + 'Sat', + 'Sun', +]; + +Future _login(TsinghuaAuthClient client, {required bool force}) async { + while (true) { + try { + await _loginAttempt(client, force: force); + return; + } catch (error) { + // A failed password, expired verification code, or temporary network + // error should not terminate an interactive login session. Each retry + // starts the complete flow again so stale cookies and one-time codes are + // not accidentally reused. + stderr.writeln('Login attempt failed: $error'); + if (!_askToRetry()) return; + force = true; + } + } +} + +Future _loginAttempt( + TsinghuaAuthClient client, { + required bool force, +}) async { + if (!force) { + final existing = await client.restore(); + if (existing != null) { + stdout.writeln('Already logged in as ${existing.userId}.'); + stdout.writeln('Use `thulium login --force` to replace the session.'); + return; + } + } + + final userId = _readLine('Tsinghua student ID: '); + if (userId.isEmpty) throw const FormatException('Student ID is required.'); + + // The password is read without terminal echo and is never passed as a + // command-line argument, where it could be exposed through process listings. + final password = _readSecret('Password: '); + if (password.isEmpty) throw const FormatException('Password is required.'); + + // Preserve the trusted-device identity on forced reauthentication. The + // account check prevents reusing another user's fingerprint on this host. + final previousSession = await client.restore(); + final fingerprint = previousSession?.userId == userId + ? previousSession!.fingerprint + : _buildFingerprint(); + + stdout.writeln('Signing in...'); + final session = await client.login( + userId: userId, + password: password, + fingerprint: fingerprint, + ); + stdout.writeln('Login succeeded for ${session.userId}.'); + stdout.writeln('The session was saved in the operating system keyring.'); +} + +bool _askToRetry() { + if (!stdin.hasTerminal) return false; + final answer = _readLine('Retry login? [Y/n]: ').toLowerCase(); + // Retrying is the default because transient network failures and expired + // one-time codes are common during interactive authentication. + return answer.isEmpty || answer == 'y' || answer == 'yes'; +} + +Future _handleTwoFactorMethod( + TwoFactorOptions options, { + IOSink? output, +}) async { + final sink = output ?? stdout; + sink.writeln('Two-factor authentication is required.'); + sink.writeln('Available methods:'); + final methods = <({TwoFactorMethod method, String label})>[]; + if (options.hasWeChat) { + methods.add((method: TwoFactorMethod.wechat, label: 'WeChat')); + } + if (options.phone != null) { + methods.add(( + method: TwoFactorMethod.mobile, + label: 'SMS (${options.phone})', + )); + } + if (options.hasTotp) { + methods.add((method: TwoFactorMethod.totp, label: 'TOTP')); + } + for (var index = 0; index < methods.length; index++) { + sink.writeln(' ${index + 1}. ${methods[index].label}'); + } + if (methods.isEmpty) { + throw StateError('The account has no available two-factor methods.'); + } + + final choice = int.tryParse(_readLine('Choose a method: ', output: sink)); + if (choice == null || choice < 1 || choice > methods.length) { + throw const FormatException('The selected method is unavailable.'); + } + return methods[choice - 1].method; +} + +Future _readTwoFactorCode( + TwoFactorCodeVerifier verifyCode, { + IOSink? output, +}) async { + final sink = output ?? stdout; + // This callback runs only after SEND_CODE succeeds, so the notification is + // expected to be available before the user is asked for the code. + sink.writeln('A verification code was sent.'); + while (true) { + final code = _readLine('Verification code: ', output: sink); + if (await verifyCode(code)) return; + sink.writeln('The verification code was not accepted. Please try again.'); + } +} + +Future _askToTrustDevice({IOSink? output}) async { + final sink = output ?? stdout; + sink.writeln( + 'Trust this device to reduce future verification prompts? Only choose yes ' + 'on a device you control.', + ); + final answer = _readLine( + 'Trust this device? [y/N]: ', + output: sink, + ).toLowerCase(); + return answer == 'y' || answer == 'yes'; +} + +String _buildFingerprint() { + // A stable, non-secret identifier makes the identity provider's device + // fingerprint consistent across CLI invocations without storing a password. + return '$_DEFAULT_FINGERPRINT_PREFIX:${Platform.operatingSystem}:' + '${Platform.localHostname}'; +} + +String _readLine(String prompt, {IOSink? output}) { + (output ?? stdout).write(prompt); + return stdin.readLineSync()?.trim() ?? ''; +} + +String _readSecret(String prompt, {IOSink? output}) { + final sink = output ?? stdout; + sink.write(prompt); + if (!stdin.hasTerminal) { + return stdin.readLineSync() ?? ''; + } + + final echoMode = stdin.echoMode; + try { + stdin.echoMode = false; + return stdin.readLineSync() ?? ''; + } finally { + stdin.echoMode = echoMode; + sink.writeln(); + } +} diff --git a/packages/cli/test/cli_command_runner_test.dart b/packages/cli/test/cli_command_runner_test.dart new file mode 100644 index 0000000..fd7c21d --- /dev/null +++ b/packages/cli/test/cli_command_runner_test.dart @@ -0,0 +1,165 @@ +import 'package:args/command_runner.dart'; +import 'package:test/test.dart'; +import 'package:thulium_cli/cli_command_runner.dart'; +import 'package:thulium_cli/cli_runtime.dart'; + +void main() { + test('all levels of help avoid executing account operations', () async { + final output = []; + final runtime = _Runtime(); + final runner = ThuliumCommandRunner( + runtime: runtime, + writeLine: output.add, + ); + for (final arguments in >[ + [], + ['--help'], + ['help'], + ['session'], + for (final name in [ + 'login', + 'logout', + 'status', + 'session', + 'schedule', + 'learn-courses', + 'learn-homework', + 'learn-materials', + 'learn-materials-cover', + ]) + [name, '--help'], + ['help', 'learn-materials', 'download'], + ['learn-materials-cover', 'download', '--help'], + ]) { + output.clear(); + await runner.run(arguments); + expect(output.join('\n'), contains('Usage: thulium')); + expect(runtime.calls, isEmpty); + } + }); + + test( + 'existing account, session and campus commands retain dispatch and flags', + () async { + final runtime = _Runtime(); + final runner = ThuliumCommandRunner(runtime: runtime); + final cases = >{ + 'login': ['login', '--force', '--verbose'], + 'logout': ['logout'], + 'status': ['status'], + 'inspect': ['session', 'inspect'], + 'reveal': ['session', 'reveal-cookies'], + 'schedule': ['schedule', '--refresh'], + 'courses': ['learn-courses', '-s', '2026-2027-1'], + 'homework': ['learn-homework', '--refresh'], + }; + for (final entry in cases.entries) { + await runner.run(entry.value); + expect(runtime.calls.last.$1, entry.key); + } + expect(runtime.calls.first.$2['force'], isTrue); + expect(runtime.calls.first.$2['verbose'], isTrue); + expect(runtime.calls.last.$2['refresh'], isTrue); + }, + ); + + test( + 'legacy list, explicit list and cover aliases retain options and precedence', + () async { + final runtime = _Runtime(); + final runner = ThuliumCommandRunner(runtime: runtime); + await runner.run(['learn-materials', '--size', '7', '--refresh']); + expect(runtime.calls.last.$1, 'materials'); + expect(runtime.calls.last.$2['size'], '7'); + expect(runtime.calls.last.$2['refresh'], isTrue); + await runner.run([ + 'learn-materials', + '--size', + '7', + 'list', + '--size', + '9', + ]); + expect(runtime.calls.last.$2['size'], '9'); + await runner.run([ + 'learn-materials', + '--verbose', + 'download', + '--file-id', + 'file', + '--course-id', + 'course', + ]); + expect(runtime.calls.last.$1, 'full'); + expect(runtime.calls.last.$2['verbose'], isTrue); + for (final prefix in [ + ['learn-materials-cover'], + ['learn-materials-cover', 'download'], + ]) { + await runner.run([ + ...prefix, + '--file-id', + 'file', + '--course-id', + 'course', + ]); + expect(runtime.calls.last.$1, 'cover'); + } + }, + ); + + test( + 'invalid input gets relevant usage before accessing an account', + () async { + final runner = ThuliumCommandRunner(); + for (final args in >[ + ['missing'], + ['login', '--missing'], + ['status', 'unexpected'], + ['learn-materials', 'missing'], + ['learn-materials', '--size', '0'], + ['learn-materials', 'download'], + ['learn-materials-cover', '--file-id', 'bad/path'], + ]) { + await expectLater(runner.run(args), throwsA(isA())); + } + }, + ); +} + +class _Runtime extends CliRuntime { + final calls = <(String, Map)>[]; + Future record(String name, Map options) async => + calls.add((name, options)); + @override + Future login(Map options) => record('login', options); + @override + Future logout(Map options) => + record('logout', options); + @override + Future status(Map options) => + record('status', options); + @override + Future inspectSession(Map options) => + record('inspect', options); + @override + Future revealCookies(Map options) => + record('reveal', options); + @override + Future schedule(Map options) => + record('schedule', options); + @override + Future courses(Map options) => + record('courses', options); + @override + Future homework(Map options) => + record('homework', options); + @override + Future materials(Map options) async => + calls.add(('materials', options)); + @override + Future downloadMaterial( + Map options, { + bool cover = false, + }) async => calls.add((cover ? 'cover' : 'full', options)); +} From 5a85dbfa76a5b86a2221d9e0ecf9380a61004352 Mon Sep 17 00:00:00 2001 From: ashgrey Date: Tue, 17 Nov 2026 13:57:49 +0800 Subject: [PATCH 13/26] fix(nix): provide libsecret for Linux CLI secure storage Add secret-tool to the Linux development shell and document NixOS Secret Service setup. --- README.md | 13 ++ flake.nix | 24 ++- .../homework_redesign_capture_test.dart | 161 +++++++++--------- 3 files changed, 112 insertions(+), 86 deletions(-) diff --git a/README.md b/README.md index 2ca12c4..c0b1ea8 100644 --- a/README.md +++ b/README.md @@ -61,6 +61,19 @@ it to a project file. Linux uses Secret Service and macOS uses Keychain. Other platforms will report that a secure session backend is not available until one is added. +On Linux, the CLI requires `secret-tool` (provided by `libsecret`, included in +the Nix development shell) and an unlocked Secret Service keyring in the current +desktop session. On NixOS, if no Secret Service provider is already configured, +enable GNOME Keyring in your system configuration: + +```nix +services.gnome.gnome-keyring.enable = true; +``` + +Rebuild your NixOS configuration and log out and back in. If the keyring remains +locked, unlock it with a keyring manager such as Seahorse. Then re-enter +`nix develop` and run the CLI from `packages/cli`. + The application and CLI cache the current academic calendar per account in platform secure storage. A successful fetch is reused for 24 hours; an older copy can be shown if the portal is temporarily unavailable. Manual refresh and diff --git a/flake.nix b/flake.nix index 66609d7..b425674 100644 --- a/flake.nix +++ b/flake.nix @@ -16,7 +16,20 @@ { devShells = forAllSystems (system: let - pkgs = import nixpkgs { inherit system; }; + pkgs = import nixpkgs { + inherit system; + config = { + android_sdk.accept_license = true; + allowUnfreePredicate = pkg: + (pkg.meta.homepage or "") == "https://developer.android.com/tools"; + }; + }; + androidSdk = pkgs.androidenv.composeAndroidPackages { + platformVersions = [ "36" ]; + buildToolsVersions = [ "36.0.0" ]; + includeNDK = true; + ndkVersions = [ "28.2.13676358" ]; + }; in { default = pkgs.mkShell { @@ -24,10 +37,15 @@ flutter git just - ]; + jdk17 + androidSdk.androidsdk + ] ++ pkgs.lib.optionals pkgs.stdenv.isLinux [ pkgs.libsecret ]; + + ANDROID_HOME = "${androidSdk.androidsdk}/libexec/android-sdk"; + ANDROID_SDK_ROOT = "${androidSdk.androidsdk}/libexec/android-sdk"; shellHook = '' - echo "Thulium development shell ready. Run 'flutter pub get' to fetch dependencies." + echo "Thulium Flutter and Android development shell ready." ''; }; }); diff --git a/test/widget/homework/homework_redesign_capture_test.dart b/test/widget/homework/homework_redesign_capture_test.dart index fcbe77a..fde6853 100644 --- a/test/widget/homework/homework_redesign_capture_test.dart +++ b/test/widget/homework/homework_redesign_capture_test.dart @@ -13,91 +13,86 @@ import 'package:thulium/widgets/app_bottom_navigation.dart'; import '../../support/homework_preview.dart'; void main() { - testWidgets( - 'capture homework review screenshots', - (tester) async { - final font = Platform.environment['HOMEWORK_SCREENSHOT_FONT']!; - final bytes = ByteData.sublistView(File(font).readAsBytesSync()); - await tester.runAsync( - () => (FontLoader( - 'HomeworkPreview', - )..addFont(Future.value(bytes))).load(), + testWidgets('capture homework review screenshots', (tester) async { + final font = Platform.environment['HOMEWORK_SCREENSHOT_FONT']!; + final bytes = ByteData.sublistView(File(font).readAsBytesSync()); + await tester.runAsync( + () => + (FontLoader('HomeworkPreview')..addFont(Future.value(bytes))).load(), + ); + final icons = await rootBundle.load( + 'packages/forui_assets/assets/lucide.ttf', + ); + await tester.runAsync( + () => (FontLoader( + 'packages/forui_assets/ForuiLucideIcons', + )..addFont(Future.value(icons))).load(), + ); + final materialIcons = await rootBundle.load( + 'fonts/MaterialIcons-Regular.otf', + ); + await tester.runAsync( + () => (FontLoader( + 'MaterialIcons', + )..addFont(Future.value(materialIcons))).load(), + ); + tester.view.physicalSize = const Size(390, 1000); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final output = Directory('artifacts/homework-redesign'); + output.createSync(recursive: true); + for (final dark in [false, true]) { + final colors = + (dark ? FThemes.neutral.dark.touch : FThemes.neutral.light.touch) + .colors; + final theme = FThemeData( + colors: colors, + touch: true, + typography: FTypography(fontFamily: 'HomeworkPreview'), ); - final icons = await rootBundle.load( - 'packages/forui_assets/assets/lucide.ttf', - ); - await tester.runAsync( - () => (FontLoader( - 'packages/forui_assets/ForuiLucideIcons', - )..addFont(Future.value(icons))).load(), - ); - final materialIcons = await rootBundle.load( - 'fonts/MaterialIcons-Regular.otf', - ); - await tester.runAsync( - () => (FontLoader( - 'MaterialIcons', - )..addFont(Future.value(materialIcons))).load(), - ); - tester.view.physicalSize = const Size(390, 1000); - tester.view.devicePixelRatio = 1; - addTearDown(tester.view.resetPhysicalSize); - addTearDown(tester.view.resetDevicePixelRatio); - final output = Directory('artifacts/homework-redesign'); - output.createSync(recursive: true); - for (final dark in [false, true]) { - final colors = - (dark ? FThemes.neutral.dark.touch : FThemes.neutral.light.touch) - .colors; - final theme = FThemeData( - colors: colors, - touch: true, - typography: FTypography(fontFamily: 'HomeworkPreview'), - ); - final key = GlobalKey(); - await tester.pumpWidget( - MaterialApp( - locale: const Locale('zh', 'CN'), - localizationsDelegates: [ - ...AppLocalizations.localizationsDelegates, - ...FLocalizations.localizationsDelegates, - ], - supportedLocales: AppLocalizations.supportedLocales, - theme: theme.toApproximateMaterialTheme(), - builder: (_, child) => FTheme(data: theme, child: child!), - home: RepaintBoundary( - key: key, - child: FScaffold( - childPad: false, - footer: AppBottomNavigation(index: 0, onChange: (_) {}), - child: HomeworkOverviewCard( - assignments: previewAssignments, - isLoading: false, - failed: false, - onRefresh: () {}, - now: previewNow, - updatedAt: previewNow.subtract(const Duration(minutes: 7)), - countsTowardGrade: (item) => - item.id == 'ungraded' ? false : null, - deviceTimeZoneOffset: const Duration(hours: 8), - ), + final key = GlobalKey(); + await tester.pumpWidget( + MaterialApp( + locale: const Locale('zh', 'CN'), + localizationsDelegates: [ + ...AppLocalizations.localizationsDelegates, + ...FLocalizations.localizationsDelegates, + ], + supportedLocales: AppLocalizations.supportedLocales, + theme: theme.toApproximateMaterialTheme(), + builder: (_, child) => FTheme(data: theme, child: child!), + home: RepaintBoundary( + key: key, + child: FScaffold( + childPad: false, + footer: AppBottomNavigation(index: 0, onChange: (_) {}), + child: HomeworkOverviewCard( + assignments: previewAssignments, + isLoading: false, + failed: false, + onRefresh: () {}, + now: previewNow, + updatedAt: previewNow.subtract(const Duration(minutes: 7)), + countsTowardGrade: (item) => + item.id == 'ungraded' ? false : null, + deviceTimeZoneOffset: const Duration(hours: 8), ), ), ), - ); - await tester.pumpAndSettle(); - final boundary = - key.currentContext!.findRenderObject()! as RenderRepaintBoundary; - await tester.runAsync(() async { - final image = await boundary.toImage(); - final data = await image.toByteData(format: ui.ImageByteFormat.png); - File( - '${output.path}/${Platform.environment['HOMEWORK_CAPTURE_STAGE']}-${dark ? 'dark' : 'light'}.png', - ).writeAsBytesSync(data!.buffer.asUint8List()); - image.dispose(); - }); - } - }, - skip: Platform.environment['HOMEWORK_CAPTURE_STAGE'] == null, - ); + ), + ); + await tester.pumpAndSettle(); + final boundary = + key.currentContext!.findRenderObject()! as RenderRepaintBoundary; + await tester.runAsync(() async { + final image = await boundary.toImage(); + final data = await image.toByteData(format: ui.ImageByteFormat.png); + File( + '${output.path}/${Platform.environment['HOMEWORK_CAPTURE_STAGE']}-${dark ? 'dark' : 'light'}.png', + ).writeAsBytesSync(data!.buffer.asUint8List()); + image.dispose(); + }); + } + }, skip: Platform.environment['HOMEWORK_CAPTURE_STAGE'] == null); } From be0031b552adb0923c72dc1804190d90c0afd3df Mon Sep 17 00:00:00 2001 From: ashgrey Date: Tue, 17 Nov 2026 14:39:35 +0800 Subject: [PATCH 14/26] fix(nix): include SDK components required by Android JNI builds Provide Android API 35 and CMake 3.22.1 so Gradle does not attempt to install missing components into the read-only Nix store. --- flake.nix | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/flake.nix b/flake.nix index b425674..e0d40e7 100644 --- a/flake.nix +++ b/flake.nix @@ -25,8 +25,11 @@ }; }; androidSdk = pkgs.androidenv.composeAndroidPackages { - platformVersions = [ "36" ]; + # jni_flutter compiles against API 35; the app uses API 36. + platformVersions = [ "35" "36" ]; buildToolsVersions = [ "36.0.0" ]; + includeCmake = true; + cmakeVersions = [ "3.22.1" ]; includeNDK = true; ndkVersions = [ "28.2.13676358" ]; }; From 24842528b3aac54af986345b01b0d344d21cead8 Mon Sep 17 00:00:00 2001 From: ashgrey Date: Tue, 17 Nov 2026 14:39:46 +0800 Subject: [PATCH 15/26] style: replace course and assignment list borders with dividers Remove the surrounding borders from My courses and Upcoming assignments while preserving separators between adjacent items. --- lib/pages/study_page.dart | 1 + lib/widgets/flat_tile_style.dart | 6 ++++++ lib/widgets/homework_overview_card.dart | 1 + 3 files changed, 8 insertions(+) diff --git a/lib/pages/study_page.dart b/lib/pages/study_page.dart index 4d22703..f1ed66e 100644 --- a/lib/pages/study_page.dart +++ b/lib/pages/study_page.dart @@ -120,6 +120,7 @@ final class StudyPage extends StatelessWidget { Padding( padding: EdgeInsets.only(top: theme.style.pagePadding.top), child: FTileGroup( + style: flatTileGroupStyle, intrinsicWidth: false, physics: const NeverScrollableScrollPhysics(), divider: FItemDivider.full, diff --git a/lib/widgets/flat_tile_style.dart b/lib/widgets/flat_tile_style.dart index 5cff894..7dc1666 100644 --- a/lib/widgets/flat_tile_style.dart +++ b/lib/widgets/flat_tile_style.dart @@ -1,5 +1,11 @@ +import 'package:flutter/widgets.dart'; import 'package:forui/forui.dart'; +/// Keep only the group's internal dividers, without a surrounding card border. +const flatTileGroupStyle = FTileGroupStyleDelta.delta( + decoration: DecorationDelta.value(BoxDecoration()), +); + /// Flat resting surface; interaction feedback continues to use Forui variants. FItemStyleDelta flatTileStyle(FThemeData theme) => FItemStyleDelta.delta( backgroundColor: FVariantsValueDelta.delta([ diff --git a/lib/widgets/homework_overview_card.dart b/lib/widgets/homework_overview_card.dart index 707bb53..7e1cd2e 100644 --- a/lib/widgets/homework_overview_card.dart +++ b/lib/widgets/homework_overview_card.dart @@ -190,6 +190,7 @@ final class _HomeworkOverviewCardState extends State SizedBox( width: double.infinity, child: FTileGroup( + style: flatTileGroupStyle, intrinsicWidth: false, physics: const NeverScrollableScrollPhysics(), divider: FItemDivider.full, From 3305b6dcfe9b6b777d6812df57f164666985c5f3 Mon Sep 17 00:00:00 2001 From: ashgrey Date: Tue, 17 Nov 2026 14:50:52 +0800 Subject: [PATCH 16/26] style(assignment): keep assignment backgrounds stable and actions sheet opaque Disable assignment row background highlights and give the actions sheet a solid theme background. --- lib/widgets/flat_tile_style.dart | 16 ++++-- lib/widgets/homework_overview_card.dart | 66 ++++++++++++++----------- 2 files changed, 48 insertions(+), 34 deletions(-) diff --git a/lib/widgets/flat_tile_style.dart b/lib/widgets/flat_tile_style.dart index 7dc1666..b329ee1 100644 --- a/lib/widgets/flat_tile_style.dart +++ b/lib/widgets/flat_tile_style.dart @@ -7,13 +7,21 @@ const flatTileGroupStyle = FTileGroupStyleDelta.delta( ); /// Flat resting surface; interaction feedback continues to use Forui variants. -FItemStyleDelta flatTileStyle(FThemeData theme) => FItemStyleDelta.delta( +FItemStyleDelta flatTileStyle( + FThemeData theme, { + bool highlightOnInteraction = true, +}) => FItemStyleDelta.delta( backgroundColor: FVariantsValueDelta.delta([ FVariantValueDeltaOperation.base(theme.colors.background), ]), contentDecoration: FVariantsDelta.delta([ - FVariantOperation.base( - DecorationDelta.shapeDelta(color: theme.colors.background), - ), + if (highlightOnInteraction) + FVariantOperation.base( + DecorationDelta.shapeDelta(color: theme.colors.background), + ) + else + FVariantOperation.all( + DecorationDelta.shapeDelta(color: theme.colors.background), + ), ]), ); diff --git a/lib/widgets/homework_overview_card.dart b/lib/widgets/homework_overview_card.dart index 7e1cd2e..75c3e3c 100644 --- a/lib/widgets/homework_overview_card.dart +++ b/lib/widgets/homework_overview_card.dart @@ -210,7 +210,10 @@ final class _HomeworkOverviewCardState extends State children: [ for (final item in entry.value) FTile.raw( - style: flatTileStyle(theme), + style: flatTileStyle( + theme, + highlightOnInteraction: false, + ), key: ValueKey( 'homework-${item.course.id}-${item.id}', ), @@ -331,37 +334,40 @@ final class _HomeworkOverviewCardState extends State context: context, side: FLayout.btt, useSafeArea: true, - builder: (sheetContext) => SingleChildScrollView( - padding: sheetContext.theme.style.pagePadding, - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Text( - l10n.homeworkActions, - style: sheetContext.theme.typography.lg, - ), - if (options.any((option) => option.$2 == null)) ...[ - SizedBox(height: sheetContext.theme.style.pagePadding.top), - FAlert(title: Text(l10n.homeworkActionsUnavailable)), - ], - for (final option in options) ...[ - SizedBox(height: sheetContext.theme.style.pagePadding.top), - FButton( - size: FButtonSizeVariant.lg, - variant: FButtonVariant.outline, - onPress: option.$2 == null - ? null - : () { - Navigator.of(sheetContext).pop(); - unawaited(_execute(context, option.$2!, homework)); - }, - child: Flexible( - child: Text(option.$1, textAlign: TextAlign.center), - ), + builder: (sheetContext) => ColoredBox( + color: sheetContext.theme.colors.background, + child: SingleChildScrollView( + padding: sheetContext.theme.style.pagePadding, + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + l10n.homeworkActions, + style: sheetContext.theme.typography.lg, ), + if (options.any((option) => option.$2 == null)) ...[ + SizedBox(height: sheetContext.theme.style.pagePadding.top), + FAlert(title: Text(l10n.homeworkActionsUnavailable)), + ], + for (final option in options) ...[ + SizedBox(height: sheetContext.theme.style.pagePadding.top), + FButton( + size: FButtonSizeVariant.lg, + variant: FButtonVariant.outline, + onPress: option.$2 == null + ? null + : () { + Navigator.of(sheetContext).pop(); + unawaited(_execute(context, option.$2!, homework)); + }, + child: Flexible( + child: Text(option.$1, textAlign: TextAlign.center), + ), + ), + ], ], - ], + ), ), ), ), From f1752d8c73ce446e12ef1fbb728e2bc60bf8c7af Mon Sep 17 00:00:00 2001 From: ashgrey Date: Tue, 17 Nov 2026 19:20:28 +0800 Subject: [PATCH 17/26] feat(study): add course content browsing and document previews Make courses in My courses selectable and open a course detail page with teacher and schedule information, course files, and assignments. Course content: - Load file metadata through the existing authenticated Learn service. - Display file titles, types, sizes, empty states, and list-limit warnings. - Group assignments into unsubmitted, submitted awaiting grading, and graded sections. - Expand each assignment list to its server-reported total instead of displaying only the first five entries. - Add refresh controls, loading indicators, retry actions, and session-expiration messages. Document previews: - Add pdfx and render authenticated PDF bytes inside the app. - Preview Word documents through Learn's PDF conversion endpoint. - Support vertical page navigation, zooming, and page-count display. - Release the PDF controller and native document when leaving preview. - Show an unsupported-platform message on Linux. - Register desktop plugins and configure the Windows PDFium version. Authentication: - Restore and check the account before requesting course content. - Attempt one credential-based reconnection after session or CSRF errors. - Keep the restored home and cached information visible when background course or homework refresh requires interactive two-factor verification. - Show a localized Sign in prompt instead of immediately returning to Welcome, and clear the prompt after a successful refresh. Add English, Simplified Chinese, and Traditional Chinese translations, regenerate localization bindings, and document preview behavior and limits. Validation: - Flutter static analysis passed. - Seven app startup/navigation tests and five course/study widget tests passed. - Twenty homework and material-service tests passed. - Five calendar export and plan-editing failures in the full Flutter suite were also reproduced on an unmodified HEAD checkout. Limitations: - Word preview requires an available PDF representation from Learn. - Submitted and graded assignment GET endpoints need live-account verification. - Android device rendering and a release APK build have not been verified. --- README.md | 15 + lib/l10n/app_en.arb | 23 +- lib/l10n/app_zh.arb | 16 +- lib/l10n/app_zh_CN.arb | 16 +- lib/l10n/app_zh_TW.arb | 16 +- lib/l10n/generated/app_localizations.dart | 84 ++++++ lib/l10n/generated/app_localizations_en.dart | 49 ++++ lib/l10n/generated/app_localizations_zh.dart | 132 +++++++++ lib/pages/course_detail_page.dart | 272 ++++++++++++++++++ lib/pages/home_page.dart | 61 +++- lib/pages/study_page.dart | 5 + lib/study/course_content_source.dart | 67 +++++ lib/widgets/course_document_preview.dart | 99 +++++++ macos/Flutter/GeneratedPluginRegistrant.swift | 2 + packages/campus/lib/src/learn_homework.dart | 33 ++- packages/campus/test/learn_homework_test.dart | 46 +++ pubspec.lock | 40 +++ pubspec.yaml | 1 + test/widget/app/widget_test.dart | 47 +++ .../widget/study/course_detail_page_test.dart | 140 +++++++++ windows/CMakeLists.txt | 1 + .../flutter/generated_plugin_registrant.cc | 3 + windows/flutter/generated_plugins.cmake | 1 + 23 files changed, 1159 insertions(+), 10 deletions(-) create mode 100644 lib/pages/course_detail_page.dart create mode 100644 lib/study/course_content_source.dart create mode 100644 lib/widgets/course_document_preview.dart create mode 100644 test/widget/study/course_detail_page_test.dart diff --git a/README.md b/README.md index c0b1ea8..cdf3dd0 100644 --- a/README.md +++ b/README.md @@ -15,6 +15,21 @@ The project currently uses Forui `0.22.x`, which is compatible with Flutter 3.44. Forui `0.26.x` requires Flutter 3.47 or newer; upgrade the dependency after upgrading Flutter. +## Course documents + +Select a course under My courses to open its files or assignments. Assignment +lists include unsubmitted, submitted (awaiting grading), and graded sections. +The latter two use the same sibling GET endpoints already used by the shared +homework counts service; they still need verification with a live Learn account. + +Document previews use `pdfx` to render the authenticated PDF representation +returned by Learn. Word documents are displayed through Learn's PDF conversion, +not a local DOC/DOCX parser. Files without an available PDF representation show +a retryable error. In-app preview supports Android, iOS, macOS, Windows and Web; +Linux shows an unsupported-platform message. The app does not send documents +to an additional conversion service. The native viewer may create temporary +files in the application's private cache directory. + ## Localization Application strings are stored in ARB files under `lib/l10n` and generated with: diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index f2110f2..eb656f9 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -185,5 +185,26 @@ "homeworkActionsUnavailable": "Actions without a connected provider are unavailable.", "homeworkActionFailed": "Action failed. Please try again.", "@homeworkUpdatedMinutes": {"placeholders": {"minutes": {"type": "int"}}}, - "@homeworkDeadline": {"placeholders": {"deadline": {"type": "String"}}} + "@homeworkDeadline": {"placeholders": {"deadline": {"type": "String"}}}, + "courseFiles": "Course files", + "courseAssignments": "Course assignments", + "courseAssignmentsScope": "Unsubmitted, submitted and graded", + "courseFilesEmpty": "No course files yet.", + "courseFilesLimited": "Showing up to {count} files; more files may be available on Learn.", + "courseContentError": "Could not load course content. Please try again.", + "coursePreviewError": "Preview is unavailable. The file may not have a PDF preview on Learn. Please retry or open it on the teaching platform.", + "courseSessionExpired": "Your session has expired. Sign in again to continue.", + "@courseFilesLimited": { + "placeholders": { + "count": { + "type": "int" + } + } + }, + "courseUnsubmitted": "Unsubmitted", + "courseSubmitted": "Submitted, awaiting grading", + "courseGraded": "Graded", + "courseAssignmentsEmpty": "No assignments in this category.", + "coursePreviewUnsupported": "Document preview is not supported on Linux yet.", + "sessionVerificationRequired": "Verification is required to refresh campus data. Your saved information is still available." } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 7b08ef3..f2a82f8 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -176,5 +176,19 @@ "homeworkRemindLater": "稍后提醒", "homeworkMarkSubmitted": "标记已提交", "homeworkActionsUnavailable": "未接入的操作当前不可用。", - "homeworkActionFailed": "操作失败,请重试。" + "homeworkActionFailed": "操作失败,请重试。", + "courseFiles": "课程文件", + "courseAssignments": "课程作业", + "courseAssignmentsScope": "未提交、已提交及已批改", + "courseFilesEmpty": "暂无课程文件。", + "courseFilesLimited": "最多显示 {count} 个文件,教学平台上可能还有更多文件。", + "courseContentError": "无法加载课程内容,请重试。", + "coursePreviewError": "无法预览,教学平台可能尚未提供此文件的 PDF 预览。请重试或前往教学平台查看。", + "courseSessionExpired": "登录已过期,请重新登录。", + "courseUnsubmitted": "未提交", + "courseSubmitted": "已提交,待批改", + "courseGraded": "已批改", + "courseAssignmentsEmpty": "此分类暂无作业。", + "coursePreviewUnsupported": "Linux 暂不支持文档预览。", + "sessionVerificationRequired": "更新校园数据需要重新验证,已保存的信息仍可查看。" } diff --git a/lib/l10n/app_zh_CN.arb b/lib/l10n/app_zh_CN.arb index 2b5c46c..021598e 100644 --- a/lib/l10n/app_zh_CN.arb +++ b/lib/l10n/app_zh_CN.arb @@ -176,5 +176,19 @@ "homeworkRemindLater": "稍后提醒", "homeworkMarkSubmitted": "标记已提交", "homeworkActionsUnavailable": "未接入的操作当前不可用。", - "homeworkActionFailed": "操作失败,请重试。" + "homeworkActionFailed": "操作失败,请重试。", + "courseFiles": "课程文件", + "courseAssignments": "课程作业", + "courseAssignmentsScope": "未提交、已提交及已批改", + "courseFilesEmpty": "暂无课程文件。", + "courseFilesLimited": "最多显示 {count} 个文件,教学平台上可能还有更多文件。", + "courseContentError": "无法加载课程内容,请重试。", + "coursePreviewError": "无法预览,教学平台可能尚未提供此文件的 PDF 预览。请重试或前往教学平台查看。", + "courseSessionExpired": "登录已过期,请重新登录。", + "courseUnsubmitted": "未提交", + "courseSubmitted": "已提交,待批改", + "courseGraded": "已批改", + "courseAssignmentsEmpty": "此分类暂无作业。", + "coursePreviewUnsupported": "Linux 暂不支持文档预览。", + "sessionVerificationRequired": "更新校园数据需要重新验证,已保存的信息仍可查看。" } diff --git a/lib/l10n/app_zh_TW.arb b/lib/l10n/app_zh_TW.arb index 819979e..e6a7750 100644 --- a/lib/l10n/app_zh_TW.arb +++ b/lib/l10n/app_zh_TW.arb @@ -176,5 +176,19 @@ "homeworkRemindLater": "稍後提醒", "homeworkMarkSubmitted": "標記已提交", "homeworkActionsUnavailable": "未接入的操作目前無法使用。", - "homeworkActionFailed": "操作失敗,請重試。" + "homeworkActionFailed": "操作失敗,請重試。", + "courseFiles": "課程檔案", + "courseAssignments": "課程作業", + "courseAssignmentsScope": "未繳交、已繳交及已批改", + "courseFilesEmpty": "暫無課程檔案。", + "courseFilesLimited": "最多顯示 {count} 個檔案,教學平台上可能還有更多檔案。", + "courseContentError": "無法載入課程內容,請重試。", + "coursePreviewError": "無法預覽,教學平台可能尚未提供此檔案的 PDF 預覽。請重試或前往教學平台查看。", + "courseSessionExpired": "登入已過期,請重新登入。", + "courseUnsubmitted": "未繳交", + "courseSubmitted": "已繳交,待批改", + "courseGraded": "已批改", + "courseAssignmentsEmpty": "此分類暫無作業。", + "coursePreviewUnsupported": "Linux 暫不支援文件預覽。", + "sessionVerificationRequired": "更新校園資料需要重新驗證,已儲存的資訊仍可查看。" } diff --git a/lib/l10n/generated/app_localizations.dart b/lib/l10n/generated/app_localizations.dart index 6006d91..4d039fc 100644 --- a/lib/l10n/generated/app_localizations.dart +++ b/lib/l10n/generated/app_localizations.dart @@ -1107,6 +1107,90 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Action failed. Please try again.'** String get homeworkActionFailed; + + /// No description provided for @courseFiles. + /// + /// In en, this message translates to: + /// **'Course files'** + String get courseFiles; + + /// No description provided for @courseAssignments. + /// + /// In en, this message translates to: + /// **'Course assignments'** + String get courseAssignments; + + /// No description provided for @courseAssignmentsScope. + /// + /// In en, this message translates to: + /// **'Unsubmitted, submitted and graded'** + String get courseAssignmentsScope; + + /// No description provided for @courseFilesEmpty. + /// + /// In en, this message translates to: + /// **'No course files yet.'** + String get courseFilesEmpty; + + /// No description provided for @courseFilesLimited. + /// + /// In en, this message translates to: + /// **'Showing up to {count} files; more files may be available on Learn.'** + String courseFilesLimited(int count); + + /// No description provided for @courseContentError. + /// + /// In en, this message translates to: + /// **'Could not load course content. Please try again.'** + String get courseContentError; + + /// No description provided for @coursePreviewError. + /// + /// In en, this message translates to: + /// **'Preview is unavailable. The file may not have a PDF preview on Learn. Please retry or open it on the teaching platform.'** + String get coursePreviewError; + + /// No description provided for @courseSessionExpired. + /// + /// In en, this message translates to: + /// **'Your session has expired. Sign in again to continue.'** + String get courseSessionExpired; + + /// No description provided for @courseUnsubmitted. + /// + /// In en, this message translates to: + /// **'Unsubmitted'** + String get courseUnsubmitted; + + /// No description provided for @courseSubmitted. + /// + /// In en, this message translates to: + /// **'Submitted, awaiting grading'** + String get courseSubmitted; + + /// No description provided for @courseGraded. + /// + /// In en, this message translates to: + /// **'Graded'** + String get courseGraded; + + /// No description provided for @courseAssignmentsEmpty. + /// + /// In en, this message translates to: + /// **'No assignments in this category.'** + String get courseAssignmentsEmpty; + + /// No description provided for @coursePreviewUnsupported. + /// + /// In en, this message translates to: + /// **'Document preview is not supported on Linux yet.'** + String get coursePreviewUnsupported; + + /// No description provided for @sessionVerificationRequired. + /// + /// In en, this message translates to: + /// **'Verification is required to refresh campus data. Your saved information is still available.'** + String get sessionVerificationRequired; } class _AppLocalizationsDelegate diff --git a/lib/l10n/generated/app_localizations_en.dart b/lib/l10n/generated/app_localizations_en.dart index b4864cd..2607e33 100644 --- a/lib/l10n/generated/app_localizations_en.dart +++ b/lib/l10n/generated/app_localizations_en.dart @@ -559,4 +559,53 @@ class AppLocalizationsEn extends AppLocalizations { @override String get homeworkActionFailed => 'Action failed. Please try again.'; + + @override + String get courseFiles => 'Course files'; + + @override + String get courseAssignments => 'Course assignments'; + + @override + String get courseAssignmentsScope => 'Unsubmitted, submitted and graded'; + + @override + String get courseFilesEmpty => 'No course files yet.'; + + @override + String courseFilesLimited(int count) { + return 'Showing up to $count files; more files may be available on Learn.'; + } + + @override + String get courseContentError => + 'Could not load course content. Please try again.'; + + @override + String get coursePreviewError => + 'Preview is unavailable. The file may not have a PDF preview on Learn. Please retry or open it on the teaching platform.'; + + @override + String get courseSessionExpired => + 'Your session has expired. Sign in again to continue.'; + + @override + String get courseUnsubmitted => 'Unsubmitted'; + + @override + String get courseSubmitted => 'Submitted, awaiting grading'; + + @override + String get courseGraded => 'Graded'; + + @override + String get courseAssignmentsEmpty => 'No assignments in this category.'; + + @override + String get coursePreviewUnsupported => + 'Document preview is not supported on Linux yet.'; + + @override + String get sessionVerificationRequired => + 'Verification is required to refresh campus data. Your saved information is still available.'; } diff --git a/lib/l10n/generated/app_localizations_zh.dart b/lib/l10n/generated/app_localizations_zh.dart index 95c37b9..bf26902 100644 --- a/lib/l10n/generated/app_localizations_zh.dart +++ b/lib/l10n/generated/app_localizations_zh.dart @@ -532,6 +532,50 @@ class AppLocalizationsZh extends AppLocalizations { @override String get homeworkActionFailed => '操作失败,请重试。'; + + @override + String get courseFiles => '课程文件'; + + @override + String get courseAssignments => '课程作业'; + + @override + String get courseAssignmentsScope => '未提交、已提交及已批改'; + + @override + String get courseFilesEmpty => '暂无课程文件。'; + + @override + String courseFilesLimited(int count) { + return '最多显示 $count 个文件,教学平台上可能还有更多文件。'; + } + + @override + String get courseContentError => '无法加载课程内容,请重试。'; + + @override + String get coursePreviewError => '无法预览,教学平台可能尚未提供此文件的 PDF 预览。请重试或前往教学平台查看。'; + + @override + String get courseSessionExpired => '登录已过期,请重新登录。'; + + @override + String get courseUnsubmitted => '未提交'; + + @override + String get courseSubmitted => '已提交,待批改'; + + @override + String get courseGraded => '已批改'; + + @override + String get courseAssignmentsEmpty => '此分类暂无作业。'; + + @override + String get coursePreviewUnsupported => 'Linux 暂不支持文档预览。'; + + @override + String get sessionVerificationRequired => '更新校园数据需要重新验证,已保存的信息仍可查看。'; } /// The translations for Chinese, as used in China (`zh_CN`). @@ -1062,6 +1106,50 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { @override String get homeworkActionFailed => '操作失败,请重试。'; + + @override + String get courseFiles => '课程文件'; + + @override + String get courseAssignments => '课程作业'; + + @override + String get courseAssignmentsScope => '未提交、已提交及已批改'; + + @override + String get courseFilesEmpty => '暂无课程文件。'; + + @override + String courseFilesLimited(int count) { + return '最多显示 $count 个文件,教学平台上可能还有更多文件。'; + } + + @override + String get courseContentError => '无法加载课程内容,请重试。'; + + @override + String get coursePreviewError => '无法预览,教学平台可能尚未提供此文件的 PDF 预览。请重试或前往教学平台查看。'; + + @override + String get courseSessionExpired => '登录已过期,请重新登录。'; + + @override + String get courseUnsubmitted => '未提交'; + + @override + String get courseSubmitted => '已提交,待批改'; + + @override + String get courseGraded => '已批改'; + + @override + String get courseAssignmentsEmpty => '此分类暂无作业。'; + + @override + String get coursePreviewUnsupported => 'Linux 暂不支持文档预览。'; + + @override + String get sessionVerificationRequired => '更新校园数据需要重新验证,已保存的信息仍可查看。'; } /// The translations for Chinese, as used in Taiwan (`zh_TW`). @@ -1592,4 +1680,48 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { @override String get homeworkActionFailed => '操作失敗,請重試。'; + + @override + String get courseFiles => '課程檔案'; + + @override + String get courseAssignments => '課程作業'; + + @override + String get courseAssignmentsScope => '未繳交、已繳交及已批改'; + + @override + String get courseFilesEmpty => '暫無課程檔案。'; + + @override + String courseFilesLimited(int count) { + return '最多顯示 $count 個檔案,教學平台上可能還有更多檔案。'; + } + + @override + String get courseContentError => '無法載入課程內容,請重試。'; + + @override + String get coursePreviewError => '無法預覽,教學平台可能尚未提供此檔案的 PDF 預覽。請重試或前往教學平台查看。'; + + @override + String get courseSessionExpired => '登入已過期,請重新登入。'; + + @override + String get courseUnsubmitted => '未繳交'; + + @override + String get courseSubmitted => '已繳交,待批改'; + + @override + String get courseGraded => '已批改'; + + @override + String get courseAssignmentsEmpty => '此分類暫無作業。'; + + @override + String get coursePreviewUnsupported => 'Linux 暫不支援文件預覽。'; + + @override + String get sessionVerificationRequired => '更新校園資料需要重新驗證,已儲存的資訊仍可查看。'; } diff --git a/lib/pages/course_detail_page.dart b/lib/pages/course_detail_page.dart new file mode 100644 index 0000000..28b76f0 --- /dev/null +++ b/lib/pages/course_detail_page.dart @@ -0,0 +1,272 @@ +import 'package:flutter/widgets.dart'; +import 'package:forui/forui.dart'; +import 'package:intl/intl.dart'; +import 'package:thulium_auth/thulium_auth.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +import '../l10n/generated/app_localizations.dart'; +import '../study/course_content_source.dart'; +import '../widgets/flat_tile_style.dart'; +import '../widgets/course_document_preview.dart'; + +class CourseDetailPage extends StatelessWidget { + const CourseDetailPage({ + required this.course, + required this.source, + required this.onSessionExpired, + super.key, + }); + + final LearnCourse course; + final CourseContentSource source; + final VoidCallback onSessionExpired; + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + final theme = context.theme; + final name = + Localizations.localeOf(context).languageCode == 'en' && + course.englishName.isNotEmpty + ? course.englishName + : course.name; + return FScaffold( + header: _header(context, name), + child: ListView( + children: [ + if (course.teacherName.isNotEmpty) + Text(course.teacherName, style: theme.typography.sm), + if (course.schedule.isNotEmpty) + Text(course.schedule, style: theme.typography.sm), + SizedBox(height: theme.style.pagePadding.top), + FTileGroup( + style: flatTileGroupStyle, + intrinsicWidth: false, + divider: FItemDivider.full, + children: [ + FTile( + title: Text(l10n.courseFiles), + prefix: const Icon(FLucideIcons.files), + onPress: () => _push( + context, + _CourseResourcePage( + title: l10n.courseFiles, + load: () => source.materials(course), + onSessionExpired: onSessionExpired, + builder: (context, data, refresh) => ListView( + children: [ + if (data.mayBeTruncated) + FAlert( + title: Text( + l10n.courseFilesLimited(data.requestedLimit), + ), + ), + if (data.materials.isEmpty) Text(l10n.courseFilesEmpty), + FTileGroup( + style: flatTileGroupStyle, + intrinsicWidth: false, + divider: FItemDivider.full, + children: [ + for (final file in data.materials) + FTile( + key: ValueKey('course-file-${file.id}'), + title: Text(file.title), + subtitle: Text( + [file.fileType, file.displaySize] + .where((value) => value.isNotEmpty) + .join(' · '), + ), + prefix: const Icon(FLucideIcons.fileText), + onPress: () => _push( + context, + _CourseResourcePage>( + title: file.title, + load: () => source.document(file), + onSessionExpired: onSessionExpired, + document: true, + builder: (context, bytes, refresh) => + CourseDocumentPreview(bytes: bytes), + ), + ), + ), + ], + ), + ], + ), + ), + ), + ), + FTile( + title: Text(l10n.courseAssignments), + subtitle: Text(l10n.courseAssignmentsScope), + prefix: const Icon(FLucideIcons.listTodo), + onPress: () => _push( + context, + _CourseResourcePage< + Map> + >( + title: l10n.courseAssignments, + load: () => source.assignments(course), + onSessionExpired: onSessionExpired, + builder: (context, groups, refresh) => ListView( + children: [ + for (final entry in groups.entries) ...[ + FTileGroup( + style: flatTileGroupStyle, + intrinsicWidth: false, + divider: FItemDivider.full, + label: Text(switch (entry.key) { + LearnHomeworkStatus.unsubmitted => + l10n.courseUnsubmitted, + LearnHomeworkStatus.submitted => + l10n.courseSubmitted, + LearnHomeworkStatus.graded => l10n.courseGraded, + }), + children: [ + for (final assignment in entry.value) + FTile( + title: Text(assignment.title), + subtitle: Text( + assignment.deadline == null + ? l10n.homeworkUnknownDeadline + : l10n.homeworkDeadline( + DateFormat.yMMMd( + l10n.localeName, + ).add_Hm().format( + assignment.deadline!.toLocal(), + ), + ), + ), + ), + ], + ), + if (entry.value.isEmpty) + Text(l10n.courseAssignmentsEmpty), + SizedBox(height: context.theme.style.pagePadding.top), + ], + ], + ), + ), + ), + ), + ], + ), + ], + ), + ); + } +} + +void _push(BuildContext context, Widget page) => Navigator.of( + context, +).push(PageRouteBuilder(pageBuilder: (_, _, _) => page)); + +FHeader _header(BuildContext context, String title, {Widget? suffix}) => + FHeader.nested( + title: Text(title, maxLines: 2, overflow: TextOverflow.ellipsis), + prefixes: [ + FButton.icon( + variant: FButtonVariant.ghost, + semanticsLabel: AppLocalizations.of(context)!.homeworkBack, + onPress: () => Navigator.of(context).pop(), + child: const Icon(FLucideIcons.arrowLeft), + ), + ], + suffixes: [?suffix], + ); + +class _CourseResourcePage extends StatefulWidget { + const _CourseResourcePage({ + required this.title, + required this.load, + required this.builder, + required this.onSessionExpired, + this.document = false, + }); + final String title; + final Future Function() load; + final Widget Function(BuildContext, T, Future Function()) builder; + final VoidCallback onSessionExpired; + final bool document; + + @override + State<_CourseResourcePage> createState() => _CourseResourcePageState(); +} + +class _CourseResourcePageState extends State<_CourseResourcePage> { + late Future _future = widget.load(); + int _generation = 0; + + Future _refresh() async { + final future = widget.load(); + setState(() { + _future = future; + _generation++; + }); + // FutureBuilder owns error presentation, including failures during refresh. + try { + await future; + } on Object { + /* Displayed by FutureBuilder. */ + } + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + return FScaffold( + childPad: !widget.document, + header: _header( + context, + widget.title, + suffix: FButton.icon( + variant: FButtonVariant.ghost, + semanticsLabel: l10n.studyRefresh, + onPress: _refresh, + child: const Icon(FLucideIcons.refreshCw), + ), + ), + child: FutureBuilder( + key: ValueKey(_generation), + future: _future, + builder: (context, snapshot) { + if (snapshot.connectionState != ConnectionState.done) { + return const Center(child: FCircularProgress()); + } + if (snapshot.hasError) { + final expired = + snapshot.error is PortalSessionRejected || + snapshot.error is PortalCsrfUnavailable; + return Center( + child: Padding( + padding: context.theme.style.pagePadding, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + FAlert( + title: Text( + expired + ? l10n.courseSessionExpired + : widget.document + ? l10n.coursePreviewError + : l10n.courseContentError, + ), + ), + SizedBox(height: context.theme.style.pagePadding.top), + FButton( + onPress: expired ? widget.onSessionExpired : _refresh, + child: Text( + expired ? l10n.loginTitle : l10n.calendarRetry, + ), + ), + ], + ), + ), + ); + } + return widget.builder(context, snapshot.data as T, _refresh); + }, + ), + ); + } +} diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index bf4e0ed..b6969be 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -17,6 +17,8 @@ import '../widgets/homework_overview_card.dart'; import 'settings_page.dart'; import 'calendar_page.dart'; import 'study_page.dart'; +import 'course_detail_page.dart'; +import '../study/course_content_source.dart'; /// The authenticated application shell with the primary navigation sections. final class HomePage extends StatefulWidget { @@ -46,6 +48,7 @@ final class _HomePageState extends State with WidgetsBindingObserver { int _selectedIndex = 0; bool _hasOpenedPlans = false; + bool _requiresSignIn = false; late String _semester; LearnCourseCatalog? _courseCatalog; Object? _courseError; @@ -148,15 +151,22 @@ final class _HomePageState extends State with WidgetsBindingObserver { } if (!mounted || generation != _courseRequestGeneration) return; setState(() { + _requiresSignIn = false; _courseCatalog = catalog; _coursesStale = service.lastSource == LearnCourseSource.staleCache; _coursesLoading = false; _homeworkLoading = true; }); await _loadHomework(client, credentials, session, catalog, generation); - } on TwoFactorInteractionRequired { + } on TwoFactorInteractionRequired catch (error) { if (mounted && generation == _courseRequestGeneration) { - widget.onSessionExpired(); + setState(() { + _requiresSignIn = true; + _courseError = error; + _coursesStale = _courseCatalog?.semester == semester; + _coursesLoading = false; + _homeworkLoading = false; + }); } } catch (error) { debugPrint('[study] course loading failed type=${error.runtimeType}'); @@ -233,6 +243,7 @@ final class _HomePageState extends State with WidgetsBindingObserver { if (!mounted || generation != _courseRequestGeneration) return; final fetchedAt = DateTime.now(); setState(() { + _requiresSignIn = false; _homeworkUpdatedAt = fetchedAt; _unsubmittedHomework = snapshot.counts; _homeworkAssignments = snapshot.assignments; @@ -254,8 +265,11 @@ final class _HomePageState extends State with WidgetsBindingObserver { } } on TwoFactorInteractionRequired { if (mounted && generation == _courseRequestGeneration) { - setState(() => _homeworkLoading = false); - widget.onSessionExpired(); + setState(() { + _requiresSignIn = true; + _homeworkLoading = false; + _homeworkFailed = true; + }); } } on Object catch (error) { debugPrint('[study] homework loading failed type=${error.runtimeType}'); @@ -301,6 +315,28 @@ final class _HomePageState extends State with WidgetsBindingObserver { final calendarTop = headerTop + headerIconSize + headerTop; return FScaffold( + header: _requiresSignIn + ? SafeArea( + bottom: false, + child: Padding( + padding: theme.style.pagePadding, + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + l10n.sessionVerificationRequired, + style: theme.typography.sm, + ), + SizedBox(height: theme.style.pagePadding.top), + FButton( + onPress: widget.onSessionExpired, + child: Text(l10n.signInAction), + ), + ], + ), + ), + ) + : null, footer: AppBottomNavigation( index: _selectedIndex, onChange: (index) => setState(() { @@ -386,6 +422,23 @@ final class _HomePageState extends State with WidgetsBindingObserver { _hasHomeworkSnapshot && (_homeworkFailed || _courseError != null), onRefresh: () => unawaited(_loadCourses(forceRefresh: true)), + onCourseSelected: (course) { + final catalog = _courseCatalog; + if (catalog == null) return; + Navigator.of(context).push( + PageRouteBuilder( + pageBuilder: (_, _, _) => CourseDetailPage( + course: course, + source: CourseContentSource( + store: + widget.sessionStore ?? SecureAuthSessionStore(), + catalog: catalog, + ), + onSessionExpired: widget.onSessionExpired, + ), + ), + ); + }, ), ), Positioned( diff --git a/lib/pages/study_page.dart b/lib/pages/study_page.dart index f1ed66e..a4b1bf6 100644 --- a/lib/pages/study_page.dart +++ b/lib/pages/study_page.dart @@ -14,6 +14,7 @@ final class StudyPage extends StatelessWidget { required this.isStale, required this.error, required this.onRefresh, + this.onCourseSelected, this.unsubmittedHomework = const {}, this.homeworkLoading = false, this.homeworkFailed = false, @@ -27,6 +28,7 @@ final class StudyPage extends StatelessWidget { final bool isStale; final Object? error; final VoidCallback onRefresh; + final ValueChanged? onCourseSelected; final Map unsubmittedHomework; final bool homeworkLoading; final bool homeworkFailed; @@ -127,6 +129,9 @@ final class StudyPage extends StatelessWidget { children: [ for (final course in catalog!.courses) FTile.raw( + onPress: onCourseSelected == null + ? null + : () => onCourseSelected!(course), key: ValueKey('study-course-${course.id}'), style: flatTileStyle(theme), child: Padding( diff --git a/lib/study/course_content_source.dart b/lib/study/course_content_source.dart new file mode 100644 index 0000000..354a777 --- /dev/null +++ b/lib/study/course_content_source.dart @@ -0,0 +1,67 @@ +import 'package:thulium_auth/thulium_auth.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +/// Each request owns its authentication client so separate screens cannot race +/// session restoration. Authenticated document responses are never logged here. +class CourseContentSource { + const CourseContentSource({required this.store, required this.catalog}); + + final AuthSessionStore store; + final LearnCourseCatalog catalog; + + Future _request( + Future Function(TsinghuaAuthClient) operation, + ) async { + final credentials = store is AuthCredentialStore + ? store as AuthCredentialStore + : null; + final client = TsinghuaAuthClient( + sessionStore: store, + credentialStore: credentials, + ); + final session = await client.restore(); + if (session == null || session.userId != catalog.userId) { + throw const PortalSessionRejected(); + } + try { + return await operation(client); + } on Object catch (error) { + if (error is! PortalSessionRejected && error is! PortalCsrfUnavailable) { + rethrow; + } + final saved = await credentials?.readCredentials(); + if (saved == null || saved.userId != session.userId) rethrow; + await client.login( + userId: session.userId, + password: saved.password, + fingerprint: session.fingerprint, + ); + return operation(client); + } + } + + LearnCourseCatalog _single(LearnCourse course) => LearnCourseCatalog( + userId: catalog.userId, + semester: catalog.semester, + courses: [course], + ); + + Future materials(LearnCourse course) => _request( + (client) async => (await LearnMaterialService( + client, + ).fetchCourses(_single(course), courseId: course.id)).single, + ).timeout(const Duration(minutes: 2)); + + Future>> assignments( + LearnCourse course, + ) => _request( + (client) => + LearnHomeworkService(client).fetchCourseAssignments(_single(course)), + ).timeout(const Duration(minutes: 2)); + + Future> document(LearnMaterial material) => _request( + (client) => LearnMaterialService( + client, + ).downloadPdf(fileId: material.fileId, courseId: material.courseId), + ).timeout(const Duration(minutes: 2)); +} diff --git a/lib/widgets/course_document_preview.dart b/lib/widgets/course_document_preview.dart new file mode 100644 index 0000000..fad5b3a --- /dev/null +++ b/lib/widgets/course_document_preview.dart @@ -0,0 +1,99 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:forui/forui.dart'; +import 'package:pdfx/pdfx.dart'; + +import '../l10n/generated/app_localizations.dart'; + +/// Owns the native document controller for the lifetime of one preview route. +class CourseDocumentPreview extends StatefulWidget { + const CourseDocumentPreview({required this.bytes, super.key}); + final List bytes; + + @override + State createState() => _CourseDocumentPreviewState(); +} + +class _CourseDocumentPreviewState extends State { + PdfController? _controller; + Future? _document; + int _page = 1; + int? _pages; + + bool get _supported => + kIsWeb || defaultTargetPlatform != TargetPlatform.linux; + + @override + void initState() { + super.initState(); + if (_supported) { + _document = PdfDocument.openData(Uint8List.fromList(widget.bytes)); + _controller = PdfController(document: _document!); + } + } + + @override + void dispose() { + _controller?.dispose(); + final document = _document; + if (document != null) unawaited(_closeDocument(document)); + super.dispose(); + } + + Future _closeDocument(Future future) async { + try { + final document = await future; + if (!document.isClosed) await document.close(); + } on Object { + // Loading errors are presented in the viewer; cleanup must not rethrow. + } + } + + @override + Widget build(BuildContext context) { + final l10n = AppLocalizations.of(context)!; + if (!_supported) { + return Center( + child: Padding( + padding: context.theme.style.pagePadding, + child: Text(l10n.coursePreviewUnsupported), + ), + ); + } + return Column( + children: [ + Expanded( + child: PdfView( + controller: _controller!, + scrollDirection: Axis.vertical, + backgroundDecoration: BoxDecoration( + color: context.theme.colors.background, + ), + onDocumentLoaded: (document) { + if (mounted) setState(() => _pages = document.pagesCount); + }, + onPageChanged: (page) { + if (mounted) setState(() => _page = page); + }, + builders: PdfViewBuilders( + options: const DefaultBuilderOptions(), + documentLoaderBuilder: (_) => + const Center(child: FCircularProgress()), + pageLoaderBuilder: (_) => + const Center(child: FCircularProgress()), + errorBuilder: (context, error) => + Center(child: Text(l10n.coursePreviewError)), + ), + ), + ), + if (_pages != null) + Padding( + padding: context.theme.style.pagePadding, + child: Text('$_page / $_pages', style: context.theme.typography.xs), + ), + ], + ); + } +} diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index cd242f8..931668b 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -7,10 +7,12 @@ import Foundation import file_selector_macos import flutter_secure_storage_darwin +import pdfx import share_plus func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) FlutterSecureStorageDarwinPlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStorageDarwinPlugin")) + PdfxPlugin.register(with: registry.registrar(forPlugin: "PdfxPlugin")) SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin")) } diff --git a/packages/campus/lib/src/learn_homework.dart b/packages/campus/lib/src/learn_homework.dart index 889505e..b0c3e3b 100644 --- a/packages/campus/lib/src/learn_homework.dart +++ b/packages/campus/lib/src/learn_homework.dart @@ -1,5 +1,14 @@ part of '../thulium_campus.dart'; +enum LearnHomeworkStatus { + unsubmitted('zyListWj'), + submitted('zyListYjwg'), + graded('zyListYpg'); + + const LearnHomeworkStatus(this.endpoint); + final String endpoint; +} + /// Counts are taken from each status endpoint, independently of page size. final class LearnHomeworkCounts { const LearnHomeworkCounts({ @@ -60,6 +69,26 @@ final class LearnHomeworkService { /// Incomplete responses fail instead of silently dropping reminders. Future fetchUnsubmittedHomework( LearnCourseCatalog catalog, + ) => _fetchHomework(catalog, 'zyListWj'); + + /// Uses the same sibling endpoints as [fetchCourses], expanding every list + /// to its reported total rather than showing only the first five entries. + Future>> fetchCourseAssignments( + LearnCourseCatalog catalog, + ) async { + final result = >{}; + for (final status in LearnHomeworkStatus.values) { + result[status] = (await _fetchHomework( + catalog, + status.endpoint, + )).assignments; + } + return Map.unmodifiable(result); + } + + Future _fetchHomework( + LearnCourseCatalog catalog, + String endpoint, ) async { _validateCatalog(catalog); final counts = {}; @@ -69,10 +98,10 @@ final class LearnHomeworkService { } final csrf = await LearnPlatformSession(_authClient).open(); for (final course in catalog.courses) { - var data = await _fetchData(course.id, 'zyListWj', csrf); + var data = await _fetchData(course.id, endpoint, csrf); var total = _readTotal(data); if (total > 5) { - data = await _fetchData(course.id, 'zyListWj', csrf, size: total); + data = await _fetchData(course.id, endpoint, csrf, size: total); total = _readTotal(data); } final rows = data['aaData']; diff --git a/packages/campus/test/learn_homework_test.dart b/packages/campus/test/learn_homework_test.dart index a18fe06..9a2c11d 100644 --- a/packages/campus/test/learn_homework_test.dart +++ b/packages/campus/test/learn_homework_test.dart @@ -7,6 +7,52 @@ import 'package:thulium_auth/thulium_auth.dart'; import 'package:thulium_campus/thulium_campus.dart'; void main() { + test( + 'course assignment lists expand each status and keep statuses separate', + () async { + final requested = []; + final auth = await _auth((request) { + final status = request.url.pathSegments.last; + requested.add(status); + final empty = request.url.queryParameters['wlkcid'] == 'empty-course'; + final size = int.parse(request.url.queryParameters['size']!); + return http.Response( + jsonEncode({ + 'result': 'success', + 'object': { + 'iTotalRecords': empty ? 0 : 6, + 'aaData': empty + ? [] + : List.generate( + size < 6 ? size : 6, + (i) => { + 'xszyid': '$status-$i', + 'bt': '$status assignment $i', + 'wlkcid': 'course-id', + 'xh': 'test-student', + }, + ), + }, + }), + 200, + request: request, + ); + }); + final result = await LearnHomeworkService( + auth, + ).fetchCourseAssignments(_catalog); + expect(result.keys, LearnHomeworkStatus.values); + for (final status in LearnHomeworkStatus.values) { + expect(result[status], hasLength(6)); + expect(result[status]!.first.id, '${status.endpoint}-0'); + expect( + requested.where((path) => path == status.endpoint), + hasLength(3), + ); + } + }, + ); + test( 'fetches complete reminder details and interprets deadlines in China time', () async { diff --git a/pubspec.lock b/pubspec.lock index 4c432b2..c61a950 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -169,6 +169,14 @@ packages: url: "https://pub.dev" source: hosted version: "4.0.6" + extension: + dependency: transitive + description: + name: extension + sha256: "1d6cc5a2d173407284780b68fd94f2b547184d4190ca7dbf6d0bf43eb43c29d8" + url: "https://pub.dev" + source: hosted + version: "1.0.0" fake_async: dependency: transitive description: @@ -637,6 +645,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.12.0" + pdfx: + dependency: "direct main" + description: + name: pdfx + sha256: "83bcd2b971fc2f6ee4299659c96d7d66b2ba4807748571a8a4889f1cde14b754" + url: "https://pub.dev" + source: hosted + version: "2.11.0" petitparser: dependency: transitive description: @@ -645,6 +661,14 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.2" + photo_view: + dependency: transitive + description: + name: photo_view + sha256: "1fc3d970a91295fbd1364296575f854c9863f225505c28c46e0a03e48960c75e" + url: "https://pub.dev" + source: hosted + version: "0.15.0" platform: dependency: transitive description: @@ -802,6 +826,14 @@ packages: url: "https://pub.dev" source: hosted version: "4.0.0" + synchronized: + dependency: transitive + description: + name: synchronized + sha256: a77637ebe1460f3b48cac89a790d2eb634f0a8593cab0d3f340c6db174ba9b94 + url: "https://pub.dev" + source: hosted + version: "3.6.1+1" term_glyph: dependency: transitive description: @@ -856,6 +888,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.4.0" + universal_platform: + dependency: transitive + description: + name: universal_platform + sha256: "64e16458a0ea9b99260ceb5467a214c1f298d647c659af1bff6d3bf82536b1ec" + url: "https://pub.dev" + source: hosted + version: "1.1.0" url_launcher_linux: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 3955596..754ae3b 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -47,6 +47,7 @@ dependencies: # Forui 0.22.x supports the Flutter 3.44 toolchain currently installed here. # Upgrade to ^0.26.0 after moving to Flutter 3.47+. forui: ^0.22.0 + pdfx: ^2.11.0 dev_dependencies: flutter_test: diff --git a/test/widget/app/widget_test.dart b/test/widget/app/widget_test.dart index 844b303..40151bb 100644 --- a/test/widget/app/widget_test.dart +++ b/test/widget/app/widget_test.dart @@ -10,6 +10,29 @@ import 'package:thulium/pages/study_page.dart'; import 'package:thulium/widgets/language_button.dart'; void main() { + testWidgets( + 'background verification keeps the home until sign in is requested', + (tester) async { + final store = _VerificationRequiredStore(_savedSession()); + await tester.pumpWidget(ThuliumApp(sessionStore: store)); + await tester.pumpAndSettle(); + + expect(find.text('Upcoming assignments'), findsOneWidget); + expect(find.text('Welcome, THUer'), findsNothing); + expect( + find.textContaining('Verification is required to refresh campus data.'), + findsOneWidget, + ); + expect(store.clears, 0); + expect(store.saved, isNotNull); + + await tester.tap(find.text('Sign in')); + await tester.pumpAndSettle(); + expect(find.text('Welcome, THUer'), findsOneWidget); + expect(store.clears, 0); + }, + ); + testWidgets('shows the Thulium welcome page', (tester) async { await tester.pumpWidget(ThuliumApp(sessionStore: MemoryAuthSessionStore())); await tester.pumpAndSettle(); @@ -131,3 +154,27 @@ void main() { AuthSession _savedSession() => const AuthSession(userId: '2022012050', fingerprint: 'test', cookies: {}); + +/// The first restore succeeds. A subsequent background operation requires +/// interactive verification, reproducing the home-to-welcome regression. +class _VerificationRequiredStore implements AuthSessionStore { + _VerificationRequiredStore(this.saved); + AuthSession? saved; + int _reads = 0; + int clears = 0; + + @override + Future read() async { + if (++_reads > 1) throw const TwoFactorInteractionRequired(); + return saved; + } + + @override + Future write(AuthSession session) async => saved = session; + + @override + Future clear() async { + clears++; + saved = null; + } +} diff --git a/test/widget/study/course_detail_page_test.dart b/test/widget/study/course_detail_page_test.dart new file mode 100644 index 0000000..f401a20 --- /dev/null +++ b/test/widget/study/course_detail_page_test.dart @@ -0,0 +1,140 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:forui/forui.dart'; +import 'package:thulium/l10n/generated/app_localizations.dart'; +import 'package:thulium/pages/course_detail_page.dart'; +import 'package:thulium/study/course_content_source.dart'; +import 'package:thulium_auth/thulium_auth.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +const course = LearnCourse( + id: 'physics', + name: '物理', + englishName: 'Physics', + teacherName: 'Teacher', + schedule: 'Room 101', +); + +class FakeContent extends CourseContentSource { + FakeContent() + : super( + store: MemoryAuthSessionStore(), + catalog: LearnCourseCatalog( + userId: 'student', + semester: '2026-2027-1', + courses: [course], + ), + ); + bool fail = false; + int documentRequests = 0; + @override + Future materials(LearnCourse course) async { + if (fail) throw const PortalSessionRejected(); + return LearnCourseMaterials( + course: course, + requestedLimit: 1, + materials: [ + LearnMaterial.fromResponse({ + 'kjxxid': 'material', + 'wlkcid': 'physics', + 'bt': 'Lecture.docx', + 'wjid': 'file', + 'wjlx': 'docx', + }), + ], + ); + } + + @override + Future> document(LearnMaterial material) async { + documentRequests++; + throw const FormatException('No PDF conversion'); + } + + @override + Future>> assignments( + LearnCourse course, + ) async => { + for (final status in LearnHomeworkStatus.values) + status: [ + LearnHomework( + id: status.name, + course: course, + title: '${status.name} assignment', + deadline: null, + ), + ], + }; +} + +void main() { + Future show( + WidgetTester tester, + FakeContent source, { + VoidCallback? expired, + }) async { + final theme = FThemes.neutral.dark.touch; + await tester.pumpWidget( + MaterialApp( + locale: const Locale('en'), + localizationsDelegates: [ + ...AppLocalizations.localizationsDelegates, + ...FLocalizations.localizationsDelegates, + ], + supportedLocales: AppLocalizations.supportedLocales, + theme: theme.toApproximateMaterialTheme(), + builder: (_, child) => FTheme(data: theme, child: child!), + home: CourseDetailPage( + course: course, + source: source, + onSessionExpired: expired ?? () {}, + ), + ), + ); + await tester.pumpAndSettle(); + } + + testWidgets('files open preview and conversion failures offer retry', ( + tester, + ) async { + final source = FakeContent(); + await show(tester, source); + await tester.tap(find.text('Course files')); + await tester.pumpAndSettle(); + expect(find.text('Lecture.docx'), findsOneWidget); + expect(find.textContaining('Showing up to 1'), findsOneWidget); + await tester.tap(find.text('Lecture.docx')); + await tester.pumpAndSettle(); + expect(find.textContaining('Preview is unavailable.'), findsOneWidget); + expect(source.documentRequests, 1); + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + expect(source.documentRequests, 2); + expect(tester.takeException(), isNull); + }); + + testWidgets('course assignments include all three statuses', (tester) async { + await show(tester, FakeContent()); + await tester.tap(find.text('Course assignments')); + await tester.pumpAndSettle(); + for (final status in LearnHomeworkStatus.values) { + expect(find.text('${status.name} assignment'), findsOneWidget); + } + expect(tester.takeException(), isNull); + }); + + testWidgets('expired session offers sign in', (tester) async { + var expired = false; + await show( + tester, + FakeContent()..fail = true, + expired: () => expired = true, + ); + await tester.tap(find.text('Course files')); + await tester.pumpAndSettle(); + expect(find.textContaining('Your session has expired.'), findsOneWidget); + await tester.tap(find.text('Sign in to Thulium')); + await tester.pumpAndSettle(); + expect(expired, isTrue); + }); +} diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index a7d6313..b432764 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -1,6 +1,7 @@ # Project-level configuration. cmake_minimum_required(VERSION 3.14) project(thulium LANGUAGES CXX) +set(PDFIUM_VERSION "4638" CACHE STRING "PDFium version used by pdfx") # The name of the executable created for the application. Change this to change # the on-disk name of your application. diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc index 23bcdc8..75f9bfd 100644 --- a/windows/flutter/generated_plugin_registrant.cc +++ b/windows/flutter/generated_plugin_registrant.cc @@ -8,6 +8,7 @@ #include #include +#include #include #include @@ -16,6 +17,8 @@ void RegisterPlugins(flutter::PluginRegistry* registry) { registry->GetRegistrarForPlugin("FileSelectorWindows")); FlutterSecureStorageWindowsPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("FlutterSecureStorageWindowsPlugin")); + PdfxPluginRegisterWithRegistrar( + registry->GetRegistrarForPlugin("PdfxPlugin")); SharePlusWindowsPluginCApiRegisterWithRegistrar( registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi")); UrlLauncherWindowsRegisterWithRegistrar( diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake index bb6d400..9b4de5e 100644 --- a/windows/flutter/generated_plugins.cmake +++ b/windows/flutter/generated_plugins.cmake @@ -5,6 +5,7 @@ list(APPEND FLUTTER_PLUGIN_LIST file_selector_windows flutter_secure_storage_windows + pdfx share_plus url_launcher_windows ) From fdf60325d1cdf2efa6c201b3a455c50aab9d0972 Mon Sep 17 00:00:00 2001 From: ashgrey Date: Tue, 17 Nov 2026 20:40:05 +0800 Subject: [PATCH 18/26] refactor(ui): unify quiet surfaces, copy and page transitions Keep list backgrounds stable, remove redundant descriptions, and standardize navigation, loading, and nested page chrome. Document the UI conventions and preserve the calendar panel. --- .agents/skills/thulium-ui/SKILL.md | 100 +++++++ .agents/skills/thulium-ui/agents/openai.yaml | 4 + AGENTS.md | 6 + lib/app.dart | 2 +- lib/l10n/app_en.arb | 89 +++--- lib/l10n/app_zh.arb | 85 +++--- lib/l10n/app_zh_CN.arb | 85 +++--- lib/l10n/app_zh_TW.arb | 85 +++--- lib/l10n/generated/app_localizations.dart | 104 +++---- lib/l10n/generated/app_localizations_en.dart | 95 +++--- lib/l10n/generated/app_localizations_zh.dart | 273 +++++++++--------- lib/navigation/app_page_route.dart | 36 +++ lib/pages/add_plan_page.dart | 31 +- lib/pages/calendar_page.dart | 8 +- lib/pages/course_detail_page.dart | 220 +++++++++----- lib/pages/home_page.dart | 47 ++- lib/pages/login_page.dart | 23 +- lib/pages/settings_page.dart | 66 ++--- lib/pages/study_page.dart | 36 +-- lib/pages/welcome_page.dart | 20 +- lib/widgets/app_icon_button.dart | 31 ++ lib/widgets/app_page_scaffold.dart | 57 ++++ lib/widgets/course_content_loading.dart | 59 ++++ lib/widgets/course_document_preview.dart | 22 +- lib/widgets/flat_tile_style.dart | 11 +- lib/widgets/homework_overview_card.dart | 23 +- lib/widgets/language_button.dart | 65 +++-- test/widget/app/widget_test.dart | 11 +- .../calendar/calendar_export_dialog_test.dart | 2 +- test/widget/homework/homework_cache_test.dart | 6 +- .../homework/homework_overview_card_test.dart | 2 +- .../widget/study/course_detail_page_test.dart | 240 ++++++++++++++- test/widget/study/study_page_test.dart | 109 +++---- 33 files changed, 1304 insertions(+), 749 deletions(-) create mode 100644 .agents/skills/thulium-ui/SKILL.md create mode 100644 .agents/skills/thulium-ui/agents/openai.yaml create mode 100644 lib/navigation/app_page_route.dart create mode 100644 lib/widgets/app_icon_button.dart create mode 100644 lib/widgets/app_page_scaffold.dart create mode 100644 lib/widgets/course_content_loading.dart diff --git a/.agents/skills/thulium-ui/SKILL.md b/.agents/skills/thulium-ui/SKILL.md new file mode 100644 index 0000000..d421b73 --- /dev/null +++ b/.agents/skills/thulium-ui/SKILL.md @@ -0,0 +1,100 @@ +--- +name: thulium-ui +description: Implement or review Thulium Flutter screens, UI copy, lists, interaction states, loading, and navigation using the project's restrained Forui design language. Use for Thulium UI changes, not generic website design or backend-only work. +--- + +# Thulium interface + +Thulium is a campus tool for students checking courses, deadlines, files, and +calendar plans. Prioritize finding real information quickly. The established +identity is a quiet neutral surface, readable text, compact rows, fine dividers, +and color reserved for urgency, categories, selection, and errors. + +## Start from the implementation + +Read repository `AGENTS.md` and the affected screen. Check the Forui version in +`pubspec.yaml`: online docs may describe APIs newer than the pinned dependency. +Use the installed package source to confirm a style or variant API. Reuse: + +- `lib/widgets/flat_tile_style.dart` for list groups and rows +- `lib/widgets/app_page_scaffold.dart` for nested page chrome and reading width +- `lib/navigation/app_page_route.dart` for pushed routes +- `lib/widgets/course_content_loading.dart` for course loading surfaces + +## Calendar boundary + +The user has approved the central calendar panel. Preserve its grid, layout, +colors, and interactions during general UI work. Shared navigation outside the +panel may be updated; changing the panel itself needs an explicit user request. + +## Surfaces and hierarchy + +- Use `context.theme` colors, typography, spacing, and border tokens. Keep light + and dark themes coherent. The neutral dark reference is background `#09090B`, + foreground `#FAFAFA`, muted foreground `#A1A1AA`, border `#27272A`; these are + design references, not permission to hard-code runtime colors. +- Use the existing system type family. Titles are semibold; metadata is smaller + and muted. Keep the same left edge and page padding through a navigation flow. +- Courses, assignments, and file lists use a single page surface and thin lines + between adjacent rows. Do not add per-row boxes, outer list borders, stacked + cards, shadows, or gradients. Preserve meaningful badges and deadline colors. +- Navigation rows keep the page background on press and hover. Retain a visible + keyboard focus outline, semantic labels, and practical touch targets. Selected + controls and destructive buttons still need their semantic interaction states. +- Use Forui controls and Lucide icons for product surfaces. Flutter layout and + platform integration are fine; avoid Material-styled product controls. + +## Copy + +- Short titles, labels, notices, empty states, and slogans normally have no final + period in English or Chinese. Preserve questions, necessary punctuation within + multi-sentence explanations, decimal numbers, and file extensions. +- A title plus an icon should usually explain a navigation action. Do not add + subtitles that restate them or explain the categories on the following screen. +- Keep actual content metadata: instructor, schedule, file size/type, deadline, + and assignment state. These are not slogans. +- Loading, errors, and empty states should explain the current state concisely. + Provide an action when it helps. Keep safety-critical explanations intact. +- Put interface copy in `lib/l10n/app_en.arb`, translate the other ARBs, and run + `flutter gen-l10n`. Update affected copy assertions. Do not trim translations + at render time or silently rewrite user-provided course/document content. + +## Navigation and asynchronous content + +- Keep back/title/action placement and background stable from course detail to + files or assignments to document preview. Forms and settings use the same + nested-page shell. Calendar grids can retain their dense, full-width layout. +- Use the shared route: a short fade with a small directional horizontal offset + on navigation. Honor reduced motion with zero duration. Avoid unanimated + `PageRouteBuilder`, inconsistent platform transitions, decorative page-load + entrances, or staggered list-item animation. +- Keep existing content visible during refresh. Show progress in an existing + action slot; don't replace the whole page with an empty spinner. +- Match loading placeholders to the eventual layout. Use the same document + loading surface while fetching bytes and opening the native PDF renderer. + Loading-to-content transitions should be brief and honor reduced motion. +- Do not invert document pages to simulate dark mode. Theme the viewer chrome + and surrounding surface; keep the document's actual colors. +- Preserve cached campus information if background reauthentication needs user + verification. Offer an explicit sign-in action rather than an abrupt redirect. + +## Review and finish + +Check the affected flow in both themes and on a narrow screen. Check pressed +rows, keyboard focus, long titles, loading, empty/error states, refresh, back +navigation, and reduced motion where relevant. Prefer screenshots for visual +review when the environment supports them; describe device-only gaps honestly. +Run relevant analysis and behavioral tests. Include a Git commit description +that matches the actual diff and any new untracked files. + +## Reference documentation + +Use these for interaction and composition principles, not as pixel templates or +permission to replace Flutter with React: + +- [Forui themes](https://forui.dev/docs/concepts/themes) +- [Forui tile groups](https://forui.dev/docs/widgets/tile/tile-group) +- [Forui widget styles](https://forui.dev/docs/guides/customizing-widget-styles) +- [shadcn/ui items](https://ui.shadcn.com/docs/components/item) +- [shadcn/ui separators](https://ui.shadcn.com/docs/components/separator) +- [shadcn/ui semantic themes](https://ui.shadcn.com/docs/theming) diff --git a/.agents/skills/thulium-ui/agents/openai.yaml b/.agents/skills/thulium-ui/agents/openai.yaml new file mode 100644 index 0000000..524a49e --- /dev/null +++ b/.agents/skills/thulium-ui/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Thulium UI" + short_description: "Maintain Thulium’s quiet Forui interface" + default_prompt: "Use $thulium-ui to implement or review a Thulium interface change" diff --git a/AGENTS.md b/AGENTS.md index 17ccc70..d2ce9da 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,5 +1,8 @@ # Interface Style +For Thulium UI work, consult `.agents/skills/thulium-ui/SKILL.md` for shared +components, copy, interaction states, navigation, and review conventions. + Use a restrained, dark, minimalist visual language for Thulium, consistent with the existing calendar and Forui components. @@ -21,3 +24,6 @@ the existing calendar and Forui components. platform. - Do not introduce Material-styled widgets into Forui product surfaces. Use the existing project patterns for platform integration where needed. +- Preserve the accepted central calendar panel: its grid, layout, colors, and + interactions should remain unchanged during general UI refactors unless the + user explicitly requests changes to that panel. diff --git a/lib/app.dart b/lib/app.dart index 546f980..21594fc 100644 --- a/lib/app.dart +++ b/lib/app.dart @@ -147,7 +147,7 @@ final class _ThuliumAppState extends State { ); }, home: _isRestoringSession - ? const Scaffold(body: Center(child: CircularProgressIndicator())) + ? const FScaffold(child: Center(child: FCircularProgress())) : _hasSession ? HomePage( onLocaleSelected: _setLocale, diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index eb656f9..0cf00fe 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -2,7 +2,7 @@ "@@locale": "en", "appTitle": "Thulium", "welcomeTitle": "Welcome, THUer", - "welcomeDescription": "Campus information, useful services, and everyday tools in one place.", + "welcomeDescription": "Campus information, useful services, and everyday tools in one place", "explore": "Explore", "language": "Language", "theme": "Theme", @@ -15,8 +15,8 @@ "passwordLabel": "Password", "passwordHint": "Enter your password", "signInAction": "Sign in", - "requiredField": "This field is required.", - "loginError": "Sign-in failed. Check your student ID and password, then try again.", + "requiredField": "This field is required", + "loginError": "Sign-in failed. Check your student ID and password, then try again", "showPassword": "Show password", "hidePassword": "Hide password", "twoFactorTitle": "Two-factor authentication", @@ -32,9 +32,9 @@ "totpMethod": "TOTP", "verificationCodeTitle": "Verification code", "verificationCodeHint": "Enter the verification code", - "verificationCodeInvalid": "That code was not accepted. Please try again.", + "verificationCodeInvalid": "That code was not accepted. Please try again", "trustDeviceTitle": "Trust this device?", - "trustDeviceDescription": "Tsinghua may remember this device and ask for fewer verification codes. Only choose this on a device you control.", + "trustDeviceDescription": "Tsinghua may remember this device and ask for fewer verification codes. Only choose this on a device you control", "trustDeviceAction": "Trust device", "notNowAction": "Not now", "confirmAction": "Confirm", @@ -42,15 +42,15 @@ "backAction": "Back", "settingsTitle": "Settings", "logoutAction": "Log out", - "logoutError": "Could not clear the saved session. Please try again.", + "logoutError": "Could not clear the saved session. Please try again", "eventsTab": "Events", "plansTab": "Plans", "studyTab": "Study", "lifeTab": "Life", "eventsTitle": "Student events", - "eventsDescription": "Upcoming classes, academic calendar reminders, and other student-related events will appear here.", + "eventsDescription": "Upcoming classes, academic calendar reminders, and other student-related events will appear here", "plansTitle": "Student plans", - "plansDescription": "Your academic calendar and custom plans will appear here.", + "plansDescription": "Your academic calendar and custom plans will appear here", "calendarWeek": "Week {week}", "@calendarWeek": {"placeholders": {"week": {"type": "int"}}}, "calendarPreviousWeek": "Previous week", @@ -63,7 +63,7 @@ "calendarExportFormatPdf": "PDF (.pdf)", "calendarExportFormatXlsx": "Excel (.xlsx)", "calendarExportFormatPng": "Image (.png)", - "calendarExportPngCurrentWeekOnly": "PNG exports the current week only.", + "calendarExportPngCurrentWeekOnly": "PNG exports the current week only", "calendarExportDateColumn": "Date", "calendarExportStartColumn": "Start", "calendarExportEndColumn": "End", @@ -77,14 +77,14 @@ "calendarExportSchoolCourses": "School courses", "calendarExportPersonalPlans": "Personal plans", "calendarExportAction": "Export", - "calendarExportNoEvents": "No events are available for the selected options.", - "calendarExportFailed": "Could not export the calendar. Please try again.", - "calendarExportSaved": "Calendar file saved.", + "calendarExportNoEvents": "No events are available for the selected options", + "calendarExportFailed": "Could not export the calendar. Please try again", + "calendarExportSaved": "Calendar file saved", "calendarLoading": "Loading calendar…", - "calendarLoadError": "Could not load the academic calendar.", - "calendarStaleCache": "Showing a saved calendar because the latest update failed.", + "calendarLoadError": "Could not load the academic calendar", + "calendarStaleCache": "Showing a saved calendar because the latest update failed", "calendarRetry": "Retry", - "calendarNoCourses": "No plans scheduled for this week.", + "calendarNoCourses": "No plans scheduled for this week", "calendarOverlappingPlans": "Overlapping plans", "planAddTitle": "Add plan", "planName": "Name", @@ -97,7 +97,7 @@ "planNewCategory": "New category", "planCategoryName": "Category name", "planCategoryColor": "Category color", - "planCategoryDuplicate": "A category with this name already exists.", + "planCategoryDuplicate": "A category with this name already exists", "planRepeat": "Repeat", "planRepeatNone": "Never", "planRepeatDaily": "Daily", @@ -106,11 +106,11 @@ "planRepeatEveryDays": "Every {days} days", "@planRepeatEveryDays": {"placeholders": {"days": {"type": "int"}}}, "planIntervalDays": "Interval in days", - "planIntervalInvalid": "Enter a positive number of days.", - "planTimeRequired": "Choose a date, start time, and end time.", - "planEndAfterStart": "End time must be later than start time on the same day.", + "planIntervalInvalid": "Enter a positive number of days", + "planTimeRequired": "Choose a date, start time, and end time", + "planEndAfterStart": "End time must be later than start time on the same day", "planSave": "Save plan", - "planSaveError": "Could not save this plan. Please try again.", + "planSaveError": "Could not save this plan. Please try again", "planEditTitle": "Edit plan", "planSaveChanges": "Save changes", "planDetailsTitle": "Plan details", @@ -123,30 +123,30 @@ "planCancelOccurrence": "Cancel this occurrence", "planConfirmDeleteTitle": "Delete plan?", "planConfirmCancelTitle": "Cancel occurrence?", - "planConfirmFetchedLesson": "This lesson will be hidden in Thulium only. School calendar data will not be changed.", - "planConfirmDeleteSeries": "Every occurrence of this repeating plan will be deleted, including individual edits.", - "planConfirmOneOccurrence": "Only this occurrence will be removed. Other occurrences will remain.", + "planConfirmFetchedLesson": "This lesson will be hidden in Thulium only. School calendar data will not be changed", + "planConfirmDeleteSeries": "Every occurrence of this repeating plan will be deleted, including individual edits", + "planConfirmOneOccurrence": "Only this occurrence will be removed. Other occurrences will remain", "planDontAskAgain": "Don't ask again for this action", "planDeleteAction": "Delete", "planCancelAction": "Cancel once", "studyTitle": "Study", - "studyDescription": "Study tools and learning resources will appear here.", + "studyDescription": "Study tools and learning resources will appear here", "studyToolsTitle": "Study shortcuts", - "studyToolsPlaceholder": "Study shortcuts will appear here.", + "studyToolsPlaceholder": "Study shortcuts will appear here", "studyCoursesTitle": "My courses", "studyRefresh": "Refresh courses", - "studyLoadError": "Could not load courses. Try refreshing.", - "studyStaleCourses": "Showing saved courses because the update failed.", - "studyNoCourses": "No courses were found for this semester.", + "studyLoadError": "Could not load courses. Try refreshing", + "studyStaleCourses": "Showing saved courses because the update failed", + "studyNoCourses": "No courses were found for this semester", "studyUnsubmittedHomework": "Unsubmitted assignments: {count}", "@studyUnsubmittedHomework": { "placeholders": { "count": { "type": "int" } } }, - "studyHomeworkLoadError": "Could not load assignment counts. Try refreshing.", + "studyHomeworkLoadError": "Could not load assignment counts. Try refreshing", "homeworkTitle": "Upcoming assignments", "homeworkEmpty": "All done", - "homeworkStale": "Could not update assignments; showing saved data.", - "homeworkLoadError": "Could not load assignments. Try refreshing.", + "homeworkStale": "Could not update assignments; showing saved data", + "homeworkLoadError": "Could not load assignments. Try refreshing", "homeworkExpired": "Overdue", "homeworkUnknownDeadline": "Deadline unavailable", "homeworkDueAt": "Due: {deadline} (Beijing time)", @@ -158,8 +158,8 @@ "@homeworkRemainingHours": {"placeholders":{"hours":{"type":"int"},"minutes":{"type":"int"}}}, "@homeworkRemainingMinutes": {"placeholders":{"minutes":{"type":"int"}}}, "lifeTitle": "Life", - "lifeDescription": "Campus life services and everyday tools will appear here.", - "homeworkTimezone": "All deadlines use Beijing time (UTC+8).", + "lifeDescription": "Campus life services and everyday tools will appear here", + "homeworkTimezone": "All deadlines use Beijing time (UTC+8)", "homeworkRefresh": "Refresh assignments", "homeworkNeverUpdated": "Not updated yet", "homeworkUpdatedNow": "Updated just now", @@ -182,18 +182,17 @@ "homeworkOpenWeb": "Open website", "homeworkRemindLater": "Remind me later", "homeworkMarkSubmitted": "Mark as submitted", - "homeworkActionsUnavailable": "Actions without a connected provider are unavailable.", - "homeworkActionFailed": "Action failed. Please try again.", + "homeworkActionsUnavailable": "Actions without a connected provider are unavailable", + "homeworkActionFailed": "Action failed. Please try again", "@homeworkUpdatedMinutes": {"placeholders": {"minutes": {"type": "int"}}}, "@homeworkDeadline": {"placeholders": {"deadline": {"type": "String"}}}, "courseFiles": "Course files", "courseAssignments": "Course assignments", - "courseAssignmentsScope": "Unsubmitted, submitted and graded", - "courseFilesEmpty": "No course files yet.", - "courseFilesLimited": "Showing up to {count} files; more files may be available on Learn.", - "courseContentError": "Could not load course content. Please try again.", - "coursePreviewError": "Preview is unavailable. The file may not have a PDF preview on Learn. Please retry or open it on the teaching platform.", - "courseSessionExpired": "Your session has expired. Sign in again to continue.", + "courseFilesEmpty": "No course files yet", + "courseFilesLimited": "Showing up to {count} files; more files may be available on Learn", + "courseContentError": "Could not load course content. Please try again", + "coursePreviewError": "Preview is unavailable. The file may not have a PDF preview on Learn. Please retry or open it on the teaching platform", + "courseSessionExpired": "Your session has expired. Sign in again to continue", "@courseFilesLimited": { "placeholders": { "count": { @@ -204,7 +203,9 @@ "courseUnsubmitted": "Unsubmitted", "courseSubmitted": "Submitted, awaiting grading", "courseGraded": "Graded", - "courseAssignmentsEmpty": "No assignments in this category.", - "coursePreviewUnsupported": "Document preview is not supported on Linux yet.", - "sessionVerificationRequired": "Verification is required to refresh campus data. Your saved information is still available." + "courseAssignmentsEmpty": "No assignments in this category", + "coursePreviewUnsupported": "Document preview is not supported on Linux yet", + "sessionVerificationRequired": "Verification is required to refresh campus data. Your saved information is still available", + "courseContentLoading": "Loading course content", + "coursePreviewLoading": "Loading document" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index f2a82f8..cb6e03e 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -15,8 +15,8 @@ "passwordLabel": "密码", "passwordHint": "请输入密码", "signInAction": "登录", - "requiredField": "此字段为必填项。", - "loginError": "登录失败,请检查学号和密码后重试。", + "requiredField": "此字段为必填项", + "loginError": "登录失败,请检查学号和密码后重试", "showPassword": "显示密码", "hidePassword": "隐藏密码", "twoFactorTitle": "二次认证", @@ -32,9 +32,9 @@ "totpMethod": "TOTP", "verificationCodeTitle": "验证码", "verificationCodeHint": "请输入验证码", - "verificationCodeInvalid": "验证码不正确,请重试。", + "verificationCodeInvalid": "验证码不正确,请重试", "trustDeviceTitle": "信任此设备?", - "trustDeviceDescription": "清华身份认证服务可能会记住此设备,减少后续验证码验证。请仅在你本人控制的设备上选择信任。", + "trustDeviceDescription": "清华身份认证服务可能会记住此设备,减少后续验证码验证。请仅在你本人控制的设备上选择信任", "trustDeviceAction": "信任设备", "notNowAction": "暂不", "confirmAction": "确认", @@ -42,15 +42,15 @@ "backAction": "返回", "settingsTitle": "设置", "logoutAction": "退出登录", - "logoutError": "无法清除已保存的登录状态,请重试。", + "logoutError": "无法清除已保存的登录状态,请重试", "eventsTab": "事件", "plansTab": "计划", "studyTab": "学习", "lifeTab": "生活", "eventsTitle": "学生事件", - "eventsDescription": "即将开始的课程、校历提醒和其他与学生相关的事件将在这里显示。", + "eventsDescription": "即将开始的课程、校历提醒和其他与学生相关的事件将在这里显示", "plansTitle": "学生计划", - "plansDescription": "你的教学日历和自定义计划将在这里显示。", + "plansDescription": "你的教学日历和自定义计划将在这里显示", "calendarWeek": "第 {week} 周", "@calendarWeek": {"placeholders": {"week": {"type": "int"}}}, "calendarPreviousWeek": "上一周", @@ -63,7 +63,7 @@ "calendarExportFormatPdf": "PDF (.pdf)", "calendarExportFormatXlsx": "Excel (.xlsx)", "calendarExportFormatPng": "图片 (.png)", - "calendarExportPngCurrentWeekOnly": "PNG 仅导出当前周。", + "calendarExportPngCurrentWeekOnly": "PNG 仅导出当前周", "calendarExportDateColumn": "日期", "calendarExportStartColumn": "开始", "calendarExportEndColumn": "结束", @@ -77,14 +77,14 @@ "calendarExportSchoolCourses": "学校课程", "calendarExportPersonalPlans": "个人计划", "calendarExportAction": "导出", - "calendarExportNoEvents": "所选范围和内容没有可导出的日程。", - "calendarExportFailed": "无法导出日历,请重试。", - "calendarExportSaved": "日历文件已保存。", + "calendarExportNoEvents": "所选范围和内容没有可导出的日程", + "calendarExportFailed": "无法导出日历,请重试", + "calendarExportSaved": "日历文件已保存", "calendarLoading": "正在加载日历…", - "calendarLoadError": "无法加载教学日历。", - "calendarStaleCache": "更新失败,当前显示已保存的日历。", + "calendarLoadError": "无法加载教学日历", + "calendarStaleCache": "更新失败,当前显示已保存的日历", "calendarRetry": "重试", - "calendarNoCourses": "本周没有计划。", + "calendarNoCourses": "本周没有计划", "calendarOverlappingPlans": "重叠的计划", "planAddTitle": "添加计划", "planName": "名称", @@ -97,7 +97,7 @@ "planNewCategory": "新建分类", "planCategoryName": "分类名称", "planCategoryColor": "分类颜色", - "planCategoryDuplicate": "已有同名分类。", + "planCategoryDuplicate": "已有同名分类", "planRepeat": "重复方式", "planRepeatNone": "不重复", "planRepeatDaily": "每天", @@ -106,11 +106,11 @@ "planRepeatEveryDays": "每隔 {days} 天", "@planRepeatEveryDays": {"placeholders": {"days": {"type": "int"}}}, "planIntervalDays": "间隔天数", - "planIntervalInvalid": "请输入大于零的天数。", - "planTimeRequired": "请选择日期、开始时间和结束时间。", - "planEndAfterStart": "结束时间必须晚于同一天的开始时间。", + "planIntervalInvalid": "请输入大于零的天数", + "planTimeRequired": "请选择日期、开始时间和结束时间", + "planEndAfterStart": "结束时间必须晚于同一天的开始时间", "planSave": "保存计划", - "planSaveError": "无法保存计划,请重试。", + "planSaveError": "无法保存计划,请重试", "planEditTitle": "编辑计划", "planSaveChanges": "保存修改", "planDetailsTitle": "计划详情", @@ -123,27 +123,27 @@ "planCancelOccurrence": "临时取消本次计划", "planConfirmDeleteTitle": "确认删除计划?", "planConfirmCancelTitle": "确认取消本次计划?", - "planConfirmFetchedLesson": "这节课只会在 Thulium 中隐藏,不会修改学校教学日历的数据。", - "planConfirmDeleteSeries": "将删除此重复计划的所有次数,包括单次修改。", - "planConfirmOneOccurrence": "只移除本次计划,其他次数仍会保留。", + "planConfirmFetchedLesson": "这节课只会在 Thulium 中隐藏,不会修改学校教学日历的数据", + "planConfirmDeleteSeries": "将删除此重复计划的所有次数,包括单次修改", + "planConfirmOneOccurrence": "只移除本次计划,其他次数仍会保留", "planDontAskAgain": "此操作下次不再提醒", "planDeleteAction": "删除", "planCancelAction": "取消本次", "studyTitle": "学习", - "studyDescription": "学习工具和学习资源将在这里显示。", + "studyDescription": "学习工具和学习资源将在这里显示", "studyToolsTitle": "学习快捷入口", - "studyToolsPlaceholder": "这里将显示常用学习功能。", + "studyToolsPlaceholder": "这里将显示常用学习功能", "studyCoursesTitle": "我的课程", "studyRefresh": "刷新课程", - "studyLoadError": "无法加载课程,请尝试刷新。", - "studyStaleCourses": "更新失败,正在显示已保存的课程。", - "studyNoCourses": "本学期暂无课程。", + "studyLoadError": "无法加载课程,请尝试刷新", + "studyStaleCourses": "更新失败,正在显示已保存的课程", + "studyNoCourses": "本学期暂无课程", "studyUnsubmittedHomework": "未交作业:{count} 份", - "studyHomeworkLoadError": "未交作业数量加载失败,请刷新重试。", + "studyHomeworkLoadError": "未交作业数量加载失败,请刷新重试", "homeworkTitle": "近期作业", "homeworkEmpty": "全部完成", - "homeworkStale": "作业更新失败,正在显示已保存的数据。", - "homeworkLoadError": "作业加载失败,请刷新重试。", + "homeworkStale": "作业更新失败,正在显示已保存的数据", + "homeworkLoadError": "作业加载失败,请刷新重试", "homeworkExpired": "已逾期", "homeworkUnknownDeadline": "截止时间未知", "homeworkDueAt": "截止:{deadline}(北京时间)", @@ -151,7 +151,7 @@ "homeworkRemainingHours": "剩余 {hours} 小时 {minutes} 分钟", "homeworkRemainingMinutes": "剩余 {minutes} 分钟", "lifeTitle": "生活", - "lifeDescription": "校园生活服务和日常工具将在这里显示。", + "lifeDescription": "校园生活服务和日常工具将在这里显示", "homeworkTimezone": "截止时间均为北京时间(UTC+8)", "homeworkRefresh": "刷新作业", "homeworkNeverUpdated": "尚未更新", @@ -175,20 +175,21 @@ "homeworkOpenWeb": "打开网页", "homeworkRemindLater": "稍后提醒", "homeworkMarkSubmitted": "标记已提交", - "homeworkActionsUnavailable": "未接入的操作当前不可用。", - "homeworkActionFailed": "操作失败,请重试。", + "homeworkActionsUnavailable": "未接入的操作当前不可用", + "homeworkActionFailed": "操作失败,请重试", "courseFiles": "课程文件", "courseAssignments": "课程作业", - "courseAssignmentsScope": "未提交、已提交及已批改", - "courseFilesEmpty": "暂无课程文件。", - "courseFilesLimited": "最多显示 {count} 个文件,教学平台上可能还有更多文件。", - "courseContentError": "无法加载课程内容,请重试。", - "coursePreviewError": "无法预览,教学平台可能尚未提供此文件的 PDF 预览。请重试或前往教学平台查看。", - "courseSessionExpired": "登录已过期,请重新登录。", + "courseFilesEmpty": "暂无课程文件", + "courseFilesLimited": "最多显示 {count} 个文件,教学平台上可能还有更多文件", + "courseContentError": "无法加载课程内容,请重试", + "coursePreviewError": "无法预览,教学平台可能尚未提供此文件的 PDF 预览。请重试或前往教学平台查看", + "courseSessionExpired": "登录已过期,请重新登录", "courseUnsubmitted": "未提交", "courseSubmitted": "已提交,待批改", "courseGraded": "已批改", - "courseAssignmentsEmpty": "此分类暂无作业。", - "coursePreviewUnsupported": "Linux 暂不支持文档预览。", - "sessionVerificationRequired": "更新校园数据需要重新验证,已保存的信息仍可查看。" + "courseAssignmentsEmpty": "此分类暂无作业", + "coursePreviewUnsupported": "Linux 暂不支持文档预览", + "sessionVerificationRequired": "更新校园数据需要重新验证,已保存的信息仍可查看", + "courseContentLoading": "正在加载课程内容", + "coursePreviewLoading": "正在加载文档" } diff --git a/lib/l10n/app_zh_CN.arb b/lib/l10n/app_zh_CN.arb index 021598e..a6d921f 100644 --- a/lib/l10n/app_zh_CN.arb +++ b/lib/l10n/app_zh_CN.arb @@ -15,8 +15,8 @@ "passwordLabel": "密码", "passwordHint": "请输入密码", "signInAction": "登录", - "requiredField": "此字段为必填项。", - "loginError": "登录失败,请检查学号和密码后重试。", + "requiredField": "此字段为必填项", + "loginError": "登录失败,请检查学号和密码后重试", "showPassword": "显示密码", "hidePassword": "隐藏密码", "twoFactorTitle": "二次认证", @@ -32,9 +32,9 @@ "totpMethod": "TOTP", "verificationCodeTitle": "验证码", "verificationCodeHint": "请输入验证码", - "verificationCodeInvalid": "验证码不正确,请重试。", + "verificationCodeInvalid": "验证码不正确,请重试", "trustDeviceTitle": "信任此设备?", - "trustDeviceDescription": "清华身份认证服务可能会记住此设备,减少后续验证码验证。请仅在你本人控制的设备上选择信任。", + "trustDeviceDescription": "清华身份认证服务可能会记住此设备,减少后续验证码验证。请仅在你本人控制的设备上选择信任", "trustDeviceAction": "信任设备", "notNowAction": "暂不", "confirmAction": "确认", @@ -42,15 +42,15 @@ "backAction": "返回", "settingsTitle": "设置", "logoutAction": "退出登录", - "logoutError": "无法清除已保存的登录状态,请重试。", + "logoutError": "无法清除已保存的登录状态,请重试", "eventsTab": "事件", "plansTab": "计划", "studyTab": "学习", "lifeTab": "生活", "eventsTitle": "学生事件", - "eventsDescription": "即将开始的课程、校历提醒和其他与学生相关的事件将在这里显示。", + "eventsDescription": "即将开始的课程、校历提醒和其他与学生相关的事件将在这里显示", "plansTitle": "学生计划", - "plansDescription": "你的教学日历和自定义计划将在这里显示。", + "plansDescription": "你的教学日历和自定义计划将在这里显示", "calendarWeek": "第 {week} 周", "@calendarWeek": {"placeholders": {"week": {"type": "int"}}}, "calendarPreviousWeek": "上一周", @@ -63,7 +63,7 @@ "calendarExportFormatPdf": "PDF (.pdf)", "calendarExportFormatXlsx": "Excel (.xlsx)", "calendarExportFormatPng": "图片 (.png)", - "calendarExportPngCurrentWeekOnly": "PNG 仅导出当前周。", + "calendarExportPngCurrentWeekOnly": "PNG 仅导出当前周", "calendarExportDateColumn": "日期", "calendarExportStartColumn": "开始", "calendarExportEndColumn": "结束", @@ -77,14 +77,14 @@ "calendarExportSchoolCourses": "学校课程", "calendarExportPersonalPlans": "个人计划", "calendarExportAction": "导出", - "calendarExportNoEvents": "所选范围和内容没有可导出的日程。", - "calendarExportFailed": "无法导出日历,请重试。", - "calendarExportSaved": "日历文件已保存。", + "calendarExportNoEvents": "所选范围和内容没有可导出的日程", + "calendarExportFailed": "无法导出日历,请重试", + "calendarExportSaved": "日历文件已保存", "calendarLoading": "正在加载日历…", - "calendarLoadError": "无法加载教学日历。", - "calendarStaleCache": "更新失败,当前显示已保存的日历。", + "calendarLoadError": "无法加载教学日历", + "calendarStaleCache": "更新失败,当前显示已保存的日历", "calendarRetry": "重试", - "calendarNoCourses": "本周没有计划。", + "calendarNoCourses": "本周没有计划", "calendarOverlappingPlans": "重叠的计划", "planAddTitle": "添加计划", "planName": "名称", @@ -97,7 +97,7 @@ "planNewCategory": "新建分类", "planCategoryName": "分类名称", "planCategoryColor": "分类颜色", - "planCategoryDuplicate": "已有同名分类。", + "planCategoryDuplicate": "已有同名分类", "planRepeat": "重复方式", "planRepeatNone": "不重复", "planRepeatDaily": "每天", @@ -106,11 +106,11 @@ "planRepeatEveryDays": "每隔 {days} 天", "@planRepeatEveryDays": {"placeholders": {"days": {"type": "int"}}}, "planIntervalDays": "间隔天数", - "planIntervalInvalid": "请输入大于零的天数。", - "planTimeRequired": "请选择日期、开始时间和结束时间。", - "planEndAfterStart": "结束时间必须晚于同一天的开始时间。", + "planIntervalInvalid": "请输入大于零的天数", + "planTimeRequired": "请选择日期、开始时间和结束时间", + "planEndAfterStart": "结束时间必须晚于同一天的开始时间", "planSave": "保存计划", - "planSaveError": "无法保存计划,请重试。", + "planSaveError": "无法保存计划,请重试", "planEditTitle": "编辑计划", "planSaveChanges": "保存修改", "planDetailsTitle": "计划详情", @@ -123,27 +123,27 @@ "planCancelOccurrence": "临时取消本次计划", "planConfirmDeleteTitle": "确认删除计划?", "planConfirmCancelTitle": "确认取消本次计划?", - "planConfirmFetchedLesson": "这节课只会在 Thulium 中隐藏,不会修改学校教学日历的数据。", - "planConfirmDeleteSeries": "将删除此重复计划的所有次数,包括单次修改。", - "planConfirmOneOccurrence": "只移除本次计划,其他次数仍会保留。", + "planConfirmFetchedLesson": "这节课只会在 Thulium 中隐藏,不会修改学校教学日历的数据", + "planConfirmDeleteSeries": "将删除此重复计划的所有次数,包括单次修改", + "planConfirmOneOccurrence": "只移除本次计划,其他次数仍会保留", "planDontAskAgain": "此操作下次不再提醒", "planDeleteAction": "删除", "planCancelAction": "取消本次", "studyTitle": "学习", - "studyDescription": "学习工具和学习资源将在这里显示。", + "studyDescription": "学习工具和学习资源将在这里显示", "studyToolsTitle": "学习快捷入口", - "studyToolsPlaceholder": "这里将显示常用学习功能。", + "studyToolsPlaceholder": "这里将显示常用学习功能", "studyCoursesTitle": "我的课程", "studyRefresh": "刷新课程", - "studyLoadError": "无法加载课程,请尝试刷新。", - "studyStaleCourses": "更新失败,正在显示已保存的课程。", - "studyNoCourses": "本学期暂无课程。", + "studyLoadError": "无法加载课程,请尝试刷新", + "studyStaleCourses": "更新失败,正在显示已保存的课程", + "studyNoCourses": "本学期暂无课程", "studyUnsubmittedHomework": "未交作业:{count} 份", - "studyHomeworkLoadError": "未交作业数量加载失败,请刷新重试。", + "studyHomeworkLoadError": "未交作业数量加载失败,请刷新重试", "homeworkTitle": "近期作业", "homeworkEmpty": "全部完成", - "homeworkStale": "作业更新失败,正在显示已保存的数据。", - "homeworkLoadError": "作业加载失败,请刷新重试。", + "homeworkStale": "作业更新失败,正在显示已保存的数据", + "homeworkLoadError": "作业加载失败,请刷新重试", "homeworkExpired": "已逾期", "homeworkUnknownDeadline": "截止时间未知", "homeworkDueAt": "截止:{deadline}(北京时间)", @@ -151,7 +151,7 @@ "homeworkRemainingHours": "剩余 {hours} 小时 {minutes} 分钟", "homeworkRemainingMinutes": "剩余 {minutes} 分钟", "lifeTitle": "生活", - "lifeDescription": "校园生活服务和日常工具将在这里显示。", + "lifeDescription": "校园生活服务和日常工具将在这里显示", "homeworkTimezone": "截止时间均为北京时间(UTC+8)", "homeworkRefresh": "刷新作业", "homeworkNeverUpdated": "尚未更新", @@ -175,20 +175,21 @@ "homeworkOpenWeb": "打开网页", "homeworkRemindLater": "稍后提醒", "homeworkMarkSubmitted": "标记已提交", - "homeworkActionsUnavailable": "未接入的操作当前不可用。", - "homeworkActionFailed": "操作失败,请重试。", + "homeworkActionsUnavailable": "未接入的操作当前不可用", + "homeworkActionFailed": "操作失败,请重试", "courseFiles": "课程文件", "courseAssignments": "课程作业", - "courseAssignmentsScope": "未提交、已提交及已批改", - "courseFilesEmpty": "暂无课程文件。", - "courseFilesLimited": "最多显示 {count} 个文件,教学平台上可能还有更多文件。", - "courseContentError": "无法加载课程内容,请重试。", - "coursePreviewError": "无法预览,教学平台可能尚未提供此文件的 PDF 预览。请重试或前往教学平台查看。", - "courseSessionExpired": "登录已过期,请重新登录。", + "courseFilesEmpty": "暂无课程文件", + "courseFilesLimited": "最多显示 {count} 个文件,教学平台上可能还有更多文件", + "courseContentError": "无法加载课程内容,请重试", + "coursePreviewError": "无法预览,教学平台可能尚未提供此文件的 PDF 预览。请重试或前往教学平台查看", + "courseSessionExpired": "登录已过期,请重新登录", "courseUnsubmitted": "未提交", "courseSubmitted": "已提交,待批改", "courseGraded": "已批改", - "courseAssignmentsEmpty": "此分类暂无作业。", - "coursePreviewUnsupported": "Linux 暂不支持文档预览。", - "sessionVerificationRequired": "更新校园数据需要重新验证,已保存的信息仍可查看。" + "courseAssignmentsEmpty": "此分类暂无作业", + "coursePreviewUnsupported": "Linux 暂不支持文档预览", + "sessionVerificationRequired": "更新校园数据需要重新验证,已保存的信息仍可查看", + "courseContentLoading": "正在加载课程内容", + "coursePreviewLoading": "正在加载文档" } diff --git a/lib/l10n/app_zh_TW.arb b/lib/l10n/app_zh_TW.arb index e6a7750..84576e9 100644 --- a/lib/l10n/app_zh_TW.arb +++ b/lib/l10n/app_zh_TW.arb @@ -15,8 +15,8 @@ "passwordLabel": "密碼", "passwordHint": "請輸入密碼", "signInAction": "登入", - "requiredField": "此欄位為必填項目。", - "loginError": "登入失敗,請檢查學號和密碼後重試。", + "requiredField": "此欄位為必填項目", + "loginError": "登入失敗,請檢查學號和密碼後重試", "showPassword": "顯示密碼", "hidePassword": "隱藏密碼", "twoFactorTitle": "雙重驗證", @@ -32,9 +32,9 @@ "totpMethod": "TOTP", "verificationCodeTitle": "驗證碼", "verificationCodeHint": "請輸入驗證碼", - "verificationCodeInvalid": "驗證碼不正確,請重試。", + "verificationCodeInvalid": "驗證碼不正確,請重試", "trustDeviceTitle": "信任此裝置?", - "trustDeviceDescription": "清華身分驗證服務可能會記住此裝置,減少後續驗證碼驗證。請僅在你本人控制的裝置上選擇信任。", + "trustDeviceDescription": "清華身分驗證服務可能會記住此裝置,減少後續驗證碼驗證。請僅在你本人控制的裝置上選擇信任", "trustDeviceAction": "信任裝置", "notNowAction": "暫不", "confirmAction": "確認", @@ -42,15 +42,15 @@ "backAction": "返回", "settingsTitle": "設定", "logoutAction": "登出", - "logoutError": "無法清除已儲存的登入狀態,請重試。", + "logoutError": "無法清除已儲存的登入狀態,請重試", "eventsTab": "事件", "plansTab": "計畫", "studyTab": "學習", "lifeTab": "生活", "eventsTitle": "學生事件", - "eventsDescription": "即將開始的課程、校曆提醒和其他與學生相關的事件將在這裡顯示。", + "eventsDescription": "即將開始的課程、校曆提醒和其他與學生相關的事件將在這裡顯示", "plansTitle": "學生計畫", - "plansDescription": "你的教學日曆和自訂計畫將在這裡顯示。", + "plansDescription": "你的教學日曆和自訂計畫將在這裡顯示", "calendarWeek": "第 {week} 週", "@calendarWeek": {"placeholders": {"week": {"type": "int"}}}, "calendarPreviousWeek": "上一週", @@ -63,7 +63,7 @@ "calendarExportFormatPdf": "PDF (.pdf)", "calendarExportFormatXlsx": "Excel (.xlsx)", "calendarExportFormatPng": "圖片 (.png)", - "calendarExportPngCurrentWeekOnly": "PNG 僅匯出目前週。", + "calendarExportPngCurrentWeekOnly": "PNG 僅匯出目前週", "calendarExportDateColumn": "日期", "calendarExportStartColumn": "開始", "calendarExportEndColumn": "結束", @@ -77,14 +77,14 @@ "calendarExportSchoolCourses": "學校課程", "calendarExportPersonalPlans": "個人計畫", "calendarExportAction": "匯出", - "calendarExportNoEvents": "所選範圍和內容沒有可匯出的行程。", - "calendarExportFailed": "無法匯出日曆,請重試。", - "calendarExportSaved": "日曆檔案已儲存。", + "calendarExportNoEvents": "所選範圍和內容沒有可匯出的行程", + "calendarExportFailed": "無法匯出日曆,請重試", + "calendarExportSaved": "日曆檔案已儲存", "calendarLoading": "正在載入日曆…", - "calendarLoadError": "無法載入教學日曆。", - "calendarStaleCache": "更新失敗,目前顯示已儲存的日曆。", + "calendarLoadError": "無法載入教學日曆", + "calendarStaleCache": "更新失敗,目前顯示已儲存的日曆", "calendarRetry": "重試", - "calendarNoCourses": "本週沒有計畫。", + "calendarNoCourses": "本週沒有計畫", "calendarOverlappingPlans": "重疊的計劃", "planAddTitle": "新增計畫", "planName": "名稱", @@ -97,7 +97,7 @@ "planNewCategory": "新增分類", "planCategoryName": "分類名稱", "planCategoryColor": "分類顏色", - "planCategoryDuplicate": "已有同名分類。", + "planCategoryDuplicate": "已有同名分類", "planRepeat": "重複方式", "planRepeatNone": "不重複", "planRepeatDaily": "每天", @@ -106,11 +106,11 @@ "planRepeatEveryDays": "每隔 {days} 天", "@planRepeatEveryDays": {"placeholders": {"days": {"type": "int"}}}, "planIntervalDays": "間隔天數", - "planIntervalInvalid": "請輸入大於零的天數。", - "planTimeRequired": "請選擇日期、開始時間和結束時間。", - "planEndAfterStart": "結束時間必須晚於同一天的開始時間。", + "planIntervalInvalid": "請輸入大於零的天數", + "planTimeRequired": "請選擇日期、開始時間和結束時間", + "planEndAfterStart": "結束時間必須晚於同一天的開始時間", "planSave": "儲存計畫", - "planSaveError": "無法儲存計畫,請重試。", + "planSaveError": "無法儲存計畫,請重試", "planEditTitle": "編輯計畫", "planSaveChanges": "儲存修改", "planDetailsTitle": "計畫詳情", @@ -123,27 +123,27 @@ "planCancelOccurrence": "暫時取消本次計畫", "planConfirmDeleteTitle": "確認刪除計畫?", "planConfirmCancelTitle": "確認取消本次計畫?", - "planConfirmFetchedLesson": "這堂課只會在 Thulium 中隱藏,不會修改學校教學日曆的資料。", - "planConfirmDeleteSeries": "將刪除此重複計畫的所有次數,包括單次修改。", - "planConfirmOneOccurrence": "只移除本次計畫,其他次數仍會保留。", + "planConfirmFetchedLesson": "這堂課只會在 Thulium 中隱藏,不會修改學校教學日曆的資料", + "planConfirmDeleteSeries": "將刪除此重複計畫的所有次數,包括單次修改", + "planConfirmOneOccurrence": "只移除本次計畫,其他次數仍會保留", "planDontAskAgain": "此操作下次不再提醒", "planDeleteAction": "刪除", "planCancelAction": "取消本次", "studyTitle": "學習", - "studyDescription": "學習工具和學習資源將在這裡顯示。", + "studyDescription": "學習工具和學習資源將在這裡顯示", "studyToolsTitle": "學習快速入口", - "studyToolsPlaceholder": "這裡將顯示常用學習功能。", + "studyToolsPlaceholder": "這裡將顯示常用學習功能", "studyCoursesTitle": "我的課程", "studyRefresh": "重新整理課程", - "studyLoadError": "無法載入課程,請嘗試重新整理。", - "studyStaleCourses": "更新失敗,正在顯示已儲存的課程。", - "studyNoCourses": "本學期暫無課程。", + "studyLoadError": "無法載入課程,請嘗試重新整理", + "studyStaleCourses": "更新失敗,正在顯示已儲存的課程", + "studyNoCourses": "本學期暫無課程", "studyUnsubmittedHomework": "未交作業:{count} 份", - "studyHomeworkLoadError": "未交作業數量載入失敗,請重新整理。", + "studyHomeworkLoadError": "未交作業數量載入失敗,請重新整理", "homeworkTitle": "近期作業", "homeworkEmpty": "全部完成", - "homeworkStale": "作業更新失敗,正在顯示已儲存的資料。", - "homeworkLoadError": "作業載入失敗,請重新整理。", + "homeworkStale": "作業更新失敗,正在顯示已儲存的資料", + "homeworkLoadError": "作業載入失敗,請重新整理", "homeworkExpired": "已逾期", "homeworkUnknownDeadline": "截止時間未知", "homeworkDueAt": "截止:{deadline}(北京時間)", @@ -151,7 +151,7 @@ "homeworkRemainingHours": "剩餘 {hours} 小時 {minutes} 分鐘", "homeworkRemainingMinutes": "剩餘 {minutes} 分鐘", "lifeTitle": "生活", - "lifeDescription": "校園生活服務和日常工具將在這裡顯示。", + "lifeDescription": "校園生活服務和日常工具將在這裡顯示", "homeworkTimezone": "截止時間均為北京時間(UTC+8)", "homeworkRefresh": "重新整理作業", "homeworkNeverUpdated": "尚未更新", @@ -175,20 +175,21 @@ "homeworkOpenWeb": "開啟網頁", "homeworkRemindLater": "稍後提醒", "homeworkMarkSubmitted": "標記已提交", - "homeworkActionsUnavailable": "未接入的操作目前無法使用。", - "homeworkActionFailed": "操作失敗,請重試。", + "homeworkActionsUnavailable": "未接入的操作目前無法使用", + "homeworkActionFailed": "操作失敗,請重試", "courseFiles": "課程檔案", "courseAssignments": "課程作業", - "courseAssignmentsScope": "未繳交、已繳交及已批改", - "courseFilesEmpty": "暫無課程檔案。", - "courseFilesLimited": "最多顯示 {count} 個檔案,教學平台上可能還有更多檔案。", - "courseContentError": "無法載入課程內容,請重試。", - "coursePreviewError": "無法預覽,教學平台可能尚未提供此檔案的 PDF 預覽。請重試或前往教學平台查看。", - "courseSessionExpired": "登入已過期,請重新登入。", + "courseFilesEmpty": "暫無課程檔案", + "courseFilesLimited": "最多顯示 {count} 個檔案,教學平台上可能還有更多檔案", + "courseContentError": "無法載入課程內容,請重試", + "coursePreviewError": "無法預覽,教學平台可能尚未提供此檔案的 PDF 預覽。請重試或前往教學平台查看", + "courseSessionExpired": "登入已過期,請重新登入", "courseUnsubmitted": "未繳交", "courseSubmitted": "已繳交,待批改", "courseGraded": "已批改", - "courseAssignmentsEmpty": "此分類暫無作業。", - "coursePreviewUnsupported": "Linux 暫不支援文件預覽。", - "sessionVerificationRequired": "更新校園資料需要重新驗證,已儲存的資訊仍可查看。" + "courseAssignmentsEmpty": "此分類暫無作業", + "coursePreviewUnsupported": "Linux 暫不支援文件預覽", + "sessionVerificationRequired": "更新校園資料需要重新驗證,已儲存的資訊仍可查看", + "courseContentLoading": "正在載入課程內容", + "coursePreviewLoading": "正在載入文件" } diff --git a/lib/l10n/generated/app_localizations.dart b/lib/l10n/generated/app_localizations.dart index 4d039fc..21435e6 100644 --- a/lib/l10n/generated/app_localizations.dart +++ b/lib/l10n/generated/app_localizations.dart @@ -115,7 +115,7 @@ abstract class AppLocalizations { /// No description provided for @welcomeDescription. /// /// In en, this message translates to: - /// **'Campus information, useful services, and everyday tools in one place.'** + /// **'Campus information, useful services, and everyday tools in one place'** String get welcomeDescription; /// No description provided for @explore. @@ -193,13 +193,13 @@ abstract class AppLocalizations { /// No description provided for @requiredField. /// /// In en, this message translates to: - /// **'This field is required.'** + /// **'This field is required'** String get requiredField; /// No description provided for @loginError. /// /// In en, this message translates to: - /// **'Sign-in failed. Check your student ID and password, then try again.'** + /// **'Sign-in failed. Check your student ID and password, then try again'** String get loginError; /// No description provided for @showPassword. @@ -253,7 +253,7 @@ abstract class AppLocalizations { /// No description provided for @verificationCodeInvalid. /// /// In en, this message translates to: - /// **'That code was not accepted. Please try again.'** + /// **'That code was not accepted. Please try again'** String get verificationCodeInvalid; /// No description provided for @trustDeviceTitle. @@ -265,7 +265,7 @@ abstract class AppLocalizations { /// No description provided for @trustDeviceDescription. /// /// In en, this message translates to: - /// **'Tsinghua may remember this device and ask for fewer verification codes. Only choose this on a device you control.'** + /// **'Tsinghua may remember this device and ask for fewer verification codes. Only choose this on a device you control'** String get trustDeviceDescription; /// No description provided for @trustDeviceAction. @@ -313,7 +313,7 @@ abstract class AppLocalizations { /// No description provided for @logoutError. /// /// In en, this message translates to: - /// **'Could not clear the saved session. Please try again.'** + /// **'Could not clear the saved session. Please try again'** String get logoutError; /// No description provided for @eventsTab. @@ -349,7 +349,7 @@ abstract class AppLocalizations { /// No description provided for @eventsDescription. /// /// In en, this message translates to: - /// **'Upcoming classes, academic calendar reminders, and other student-related events will appear here.'** + /// **'Upcoming classes, academic calendar reminders, and other student-related events will appear here'** String get eventsDescription; /// No description provided for @plansTitle. @@ -361,7 +361,7 @@ abstract class AppLocalizations { /// No description provided for @plansDescription. /// /// In en, this message translates to: - /// **'Your academic calendar and custom plans will appear here.'** + /// **'Your academic calendar and custom plans will appear here'** String get plansDescription; /// No description provided for @calendarWeek. @@ -433,7 +433,7 @@ abstract class AppLocalizations { /// No description provided for @calendarExportPngCurrentWeekOnly. /// /// In en, this message translates to: - /// **'PNG exports the current week only.'** + /// **'PNG exports the current week only'** String get calendarExportPngCurrentWeekOnly; /// No description provided for @calendarExportDateColumn. @@ -517,19 +517,19 @@ abstract class AppLocalizations { /// No description provided for @calendarExportNoEvents. /// /// In en, this message translates to: - /// **'No events are available for the selected options.'** + /// **'No events are available for the selected options'** String get calendarExportNoEvents; /// No description provided for @calendarExportFailed. /// /// In en, this message translates to: - /// **'Could not export the calendar. Please try again.'** + /// **'Could not export the calendar. Please try again'** String get calendarExportFailed; /// No description provided for @calendarExportSaved. /// /// In en, this message translates to: - /// **'Calendar file saved.'** + /// **'Calendar file saved'** String get calendarExportSaved; /// No description provided for @calendarLoading. @@ -541,13 +541,13 @@ abstract class AppLocalizations { /// No description provided for @calendarLoadError. /// /// In en, this message translates to: - /// **'Could not load the academic calendar.'** + /// **'Could not load the academic calendar'** String get calendarLoadError; /// No description provided for @calendarStaleCache. /// /// In en, this message translates to: - /// **'Showing a saved calendar because the latest update failed.'** + /// **'Showing a saved calendar because the latest update failed'** String get calendarStaleCache; /// No description provided for @calendarRetry. @@ -559,7 +559,7 @@ abstract class AppLocalizations { /// No description provided for @calendarNoCourses. /// /// In en, this message translates to: - /// **'No plans scheduled for this week.'** + /// **'No plans scheduled for this week'** String get calendarNoCourses; /// No description provided for @calendarOverlappingPlans. @@ -637,7 +637,7 @@ abstract class AppLocalizations { /// No description provided for @planCategoryDuplicate. /// /// In en, this message translates to: - /// **'A category with this name already exists.'** + /// **'A category with this name already exists'** String get planCategoryDuplicate; /// No description provided for @planRepeat. @@ -685,19 +685,19 @@ abstract class AppLocalizations { /// No description provided for @planIntervalInvalid. /// /// In en, this message translates to: - /// **'Enter a positive number of days.'** + /// **'Enter a positive number of days'** String get planIntervalInvalid; /// No description provided for @planTimeRequired. /// /// In en, this message translates to: - /// **'Choose a date, start time, and end time.'** + /// **'Choose a date, start time, and end time'** String get planTimeRequired; /// No description provided for @planEndAfterStart. /// /// In en, this message translates to: - /// **'End time must be later than start time on the same day.'** + /// **'End time must be later than start time on the same day'** String get planEndAfterStart; /// No description provided for @planSave. @@ -709,7 +709,7 @@ abstract class AppLocalizations { /// No description provided for @planSaveError. /// /// In en, this message translates to: - /// **'Could not save this plan. Please try again.'** + /// **'Could not save this plan. Please try again'** String get planSaveError; /// No description provided for @planEditTitle. @@ -787,19 +787,19 @@ abstract class AppLocalizations { /// No description provided for @planConfirmFetchedLesson. /// /// In en, this message translates to: - /// **'This lesson will be hidden in Thulium only. School calendar data will not be changed.'** + /// **'This lesson will be hidden in Thulium only. School calendar data will not be changed'** String get planConfirmFetchedLesson; /// No description provided for @planConfirmDeleteSeries. /// /// In en, this message translates to: - /// **'Every occurrence of this repeating plan will be deleted, including individual edits.'** + /// **'Every occurrence of this repeating plan will be deleted, including individual edits'** String get planConfirmDeleteSeries; /// No description provided for @planConfirmOneOccurrence. /// /// In en, this message translates to: - /// **'Only this occurrence will be removed. Other occurrences will remain.'** + /// **'Only this occurrence will be removed. Other occurrences will remain'** String get planConfirmOneOccurrence; /// No description provided for @planDontAskAgain. @@ -829,7 +829,7 @@ abstract class AppLocalizations { /// No description provided for @studyDescription. /// /// In en, this message translates to: - /// **'Study tools and learning resources will appear here.'** + /// **'Study tools and learning resources will appear here'** String get studyDescription; /// No description provided for @studyToolsTitle. @@ -841,7 +841,7 @@ abstract class AppLocalizations { /// No description provided for @studyToolsPlaceholder. /// /// In en, this message translates to: - /// **'Study shortcuts will appear here.'** + /// **'Study shortcuts will appear here'** String get studyToolsPlaceholder; /// No description provided for @studyCoursesTitle. @@ -859,19 +859,19 @@ abstract class AppLocalizations { /// No description provided for @studyLoadError. /// /// In en, this message translates to: - /// **'Could not load courses. Try refreshing.'** + /// **'Could not load courses. Try refreshing'** String get studyLoadError; /// No description provided for @studyStaleCourses. /// /// In en, this message translates to: - /// **'Showing saved courses because the update failed.'** + /// **'Showing saved courses because the update failed'** String get studyStaleCourses; /// No description provided for @studyNoCourses. /// /// In en, this message translates to: - /// **'No courses were found for this semester.'** + /// **'No courses were found for this semester'** String get studyNoCourses; /// No description provided for @studyUnsubmittedHomework. @@ -883,7 +883,7 @@ abstract class AppLocalizations { /// No description provided for @studyHomeworkLoadError. /// /// In en, this message translates to: - /// **'Could not load assignment counts. Try refreshing.'** + /// **'Could not load assignment counts. Try refreshing'** String get studyHomeworkLoadError; /// No description provided for @homeworkTitle. @@ -901,13 +901,13 @@ abstract class AppLocalizations { /// No description provided for @homeworkStale. /// /// In en, this message translates to: - /// **'Could not update assignments; showing saved data.'** + /// **'Could not update assignments; showing saved data'** String get homeworkStale; /// No description provided for @homeworkLoadError. /// /// In en, this message translates to: - /// **'Could not load assignments. Try refreshing.'** + /// **'Could not load assignments. Try refreshing'** String get homeworkLoadError; /// No description provided for @homeworkExpired. @@ -955,13 +955,13 @@ abstract class AppLocalizations { /// No description provided for @lifeDescription. /// /// In en, this message translates to: - /// **'Campus life services and everyday tools will appear here.'** + /// **'Campus life services and everyday tools will appear here'** String get lifeDescription; /// No description provided for @homeworkTimezone. /// /// In en, this message translates to: - /// **'All deadlines use Beijing time (UTC+8).'** + /// **'All deadlines use Beijing time (UTC+8)'** String get homeworkTimezone; /// No description provided for @homeworkRefresh. @@ -1099,13 +1099,13 @@ abstract class AppLocalizations { /// No description provided for @homeworkActionsUnavailable. /// /// In en, this message translates to: - /// **'Actions without a connected provider are unavailable.'** + /// **'Actions without a connected provider are unavailable'** String get homeworkActionsUnavailable; /// No description provided for @homeworkActionFailed. /// /// In en, this message translates to: - /// **'Action failed. Please try again.'** + /// **'Action failed. Please try again'** String get homeworkActionFailed; /// No description provided for @courseFiles. @@ -1120,40 +1120,34 @@ abstract class AppLocalizations { /// **'Course assignments'** String get courseAssignments; - /// No description provided for @courseAssignmentsScope. - /// - /// In en, this message translates to: - /// **'Unsubmitted, submitted and graded'** - String get courseAssignmentsScope; - /// No description provided for @courseFilesEmpty. /// /// In en, this message translates to: - /// **'No course files yet.'** + /// **'No course files yet'** String get courseFilesEmpty; /// No description provided for @courseFilesLimited. /// /// In en, this message translates to: - /// **'Showing up to {count} files; more files may be available on Learn.'** + /// **'Showing up to {count} files; more files may be available on Learn'** String courseFilesLimited(int count); /// No description provided for @courseContentError. /// /// In en, this message translates to: - /// **'Could not load course content. Please try again.'** + /// **'Could not load course content. Please try again'** String get courseContentError; /// No description provided for @coursePreviewError. /// /// In en, this message translates to: - /// **'Preview is unavailable. The file may not have a PDF preview on Learn. Please retry or open it on the teaching platform.'** + /// **'Preview is unavailable. The file may not have a PDF preview on Learn. Please retry or open it on the teaching platform'** String get coursePreviewError; /// No description provided for @courseSessionExpired. /// /// In en, this message translates to: - /// **'Your session has expired. Sign in again to continue.'** + /// **'Your session has expired. Sign in again to continue'** String get courseSessionExpired; /// No description provided for @courseUnsubmitted. @@ -1177,20 +1171,32 @@ abstract class AppLocalizations { /// No description provided for @courseAssignmentsEmpty. /// /// In en, this message translates to: - /// **'No assignments in this category.'** + /// **'No assignments in this category'** String get courseAssignmentsEmpty; /// No description provided for @coursePreviewUnsupported. /// /// In en, this message translates to: - /// **'Document preview is not supported on Linux yet.'** + /// **'Document preview is not supported on Linux yet'** String get coursePreviewUnsupported; /// No description provided for @sessionVerificationRequired. /// /// In en, this message translates to: - /// **'Verification is required to refresh campus data. Your saved information is still available.'** + /// **'Verification is required to refresh campus data. Your saved information is still available'** String get sessionVerificationRequired; + + /// No description provided for @courseContentLoading. + /// + /// In en, this message translates to: + /// **'Loading course content'** + String get courseContentLoading; + + /// No description provided for @coursePreviewLoading. + /// + /// In en, this message translates to: + /// **'Loading document'** + String get coursePreviewLoading; } class _AppLocalizationsDelegate diff --git a/lib/l10n/generated/app_localizations_en.dart b/lib/l10n/generated/app_localizations_en.dart index 2607e33..c50b472 100644 --- a/lib/l10n/generated/app_localizations_en.dart +++ b/lib/l10n/generated/app_localizations_en.dart @@ -16,7 +16,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get welcomeDescription => - 'Campus information, useful services, and everyday tools in one place.'; + 'Campus information, useful services, and everyday tools in one place'; @override String get explore => 'Explore'; @@ -55,11 +55,11 @@ class AppLocalizationsEn extends AppLocalizations { String get signInAction => 'Sign in'; @override - String get requiredField => 'This field is required.'; + String get requiredField => 'This field is required'; @override String get loginError => - 'Sign-in failed. Check your student ID and password, then try again.'; + 'Sign-in failed. Check your student ID and password, then try again'; @override String get showPassword => 'Show password'; @@ -89,14 +89,14 @@ class AppLocalizationsEn extends AppLocalizations { @override String get verificationCodeInvalid => - 'That code was not accepted. Please try again.'; + 'That code was not accepted. Please try again'; @override String get trustDeviceTitle => 'Trust this device?'; @override String get trustDeviceDescription => - 'Tsinghua may remember this device and ask for fewer verification codes. Only choose this on a device you control.'; + 'Tsinghua may remember this device and ask for fewer verification codes. Only choose this on a device you control'; @override String get trustDeviceAction => 'Trust device'; @@ -121,7 +121,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get logoutError => - 'Could not clear the saved session. Please try again.'; + 'Could not clear the saved session. Please try again'; @override String get eventsTab => 'Events'; @@ -140,14 +140,14 @@ class AppLocalizationsEn extends AppLocalizations { @override String get eventsDescription => - 'Upcoming classes, academic calendar reminders, and other student-related events will appear here.'; + 'Upcoming classes, academic calendar reminders, and other student-related events will appear here'; @override String get plansTitle => 'Student plans'; @override String get plansDescription => - 'Your academic calendar and custom plans will appear here.'; + 'Your academic calendar and custom plans will appear here'; @override String calendarWeek(int week) { @@ -186,7 +186,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get calendarExportPngCurrentWeekOnly => - 'PNG exports the current week only.'; + 'PNG exports the current week only'; @override String get calendarExportDateColumn => 'Date'; @@ -229,30 +229,30 @@ class AppLocalizationsEn extends AppLocalizations { @override String get calendarExportNoEvents => - 'No events are available for the selected options.'; + 'No events are available for the selected options'; @override String get calendarExportFailed => - 'Could not export the calendar. Please try again.'; + 'Could not export the calendar. Please try again'; @override - String get calendarExportSaved => 'Calendar file saved.'; + String get calendarExportSaved => 'Calendar file saved'; @override String get calendarLoading => 'Loading calendar…'; @override - String get calendarLoadError => 'Could not load the academic calendar.'; + String get calendarLoadError => 'Could not load the academic calendar'; @override String get calendarStaleCache => - 'Showing a saved calendar because the latest update failed.'; + 'Showing a saved calendar because the latest update failed'; @override String get calendarRetry => 'Retry'; @override - String get calendarNoCourses => 'No plans scheduled for this week.'; + String get calendarNoCourses => 'No plans scheduled for this week'; @override String get calendarOverlappingPlans => 'Overlapping plans'; @@ -292,7 +292,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get planCategoryDuplicate => - 'A category with this name already exists.'; + 'A category with this name already exists'; @override String get planRepeat => 'Repeat'; @@ -318,20 +318,20 @@ class AppLocalizationsEn extends AppLocalizations { String get planIntervalDays => 'Interval in days'; @override - String get planIntervalInvalid => 'Enter a positive number of days.'; + String get planIntervalInvalid => 'Enter a positive number of days'; @override - String get planTimeRequired => 'Choose a date, start time, and end time.'; + String get planTimeRequired => 'Choose a date, start time, and end time'; @override String get planEndAfterStart => - 'End time must be later than start time on the same day.'; + 'End time must be later than start time on the same day'; @override String get planSave => 'Save plan'; @override - String get planSaveError => 'Could not save this plan. Please try again.'; + String get planSaveError => 'Could not save this plan. Please try again'; @override String get planEditTitle => 'Edit plan'; @@ -371,15 +371,15 @@ class AppLocalizationsEn extends AppLocalizations { @override String get planConfirmFetchedLesson => - 'This lesson will be hidden in Thulium only. School calendar data will not be changed.'; + 'This lesson will be hidden in Thulium only. School calendar data will not be changed'; @override String get planConfirmDeleteSeries => - 'Every occurrence of this repeating plan will be deleted, including individual edits.'; + 'Every occurrence of this repeating plan will be deleted, including individual edits'; @override String get planConfirmOneOccurrence => - 'Only this occurrence will be removed. Other occurrences will remain.'; + 'Only this occurrence will be removed. Other occurrences will remain'; @override String get planDontAskAgain => 'Don\'t ask again for this action'; @@ -395,13 +395,13 @@ class AppLocalizationsEn extends AppLocalizations { @override String get studyDescription => - 'Study tools and learning resources will appear here.'; + 'Study tools and learning resources will appear here'; @override String get studyToolsTitle => 'Study shortcuts'; @override - String get studyToolsPlaceholder => 'Study shortcuts will appear here.'; + String get studyToolsPlaceholder => 'Study shortcuts will appear here'; @override String get studyCoursesTitle => 'My courses'; @@ -410,14 +410,14 @@ class AppLocalizationsEn extends AppLocalizations { String get studyRefresh => 'Refresh courses'; @override - String get studyLoadError => 'Could not load courses. Try refreshing.'; + String get studyLoadError => 'Could not load courses. Try refreshing'; @override String get studyStaleCourses => - 'Showing saved courses because the update failed.'; + 'Showing saved courses because the update failed'; @override - String get studyNoCourses => 'No courses were found for this semester.'; + String get studyNoCourses => 'No courses were found for this semester'; @override String studyUnsubmittedHomework(int count) { @@ -426,7 +426,7 @@ class AppLocalizationsEn extends AppLocalizations { @override String get studyHomeworkLoadError => - 'Could not load assignment counts. Try refreshing.'; + 'Could not load assignment counts. Try refreshing'; @override String get homeworkTitle => 'Upcoming assignments'; @@ -436,10 +436,10 @@ class AppLocalizationsEn extends AppLocalizations { @override String get homeworkStale => - 'Could not update assignments; showing saved data.'; + 'Could not update assignments; showing saved data'; @override - String get homeworkLoadError => 'Could not load assignments. Try refreshing.'; + String get homeworkLoadError => 'Could not load assignments. Try refreshing'; @override String get homeworkExpired => 'Overdue'; @@ -472,10 +472,10 @@ class AppLocalizationsEn extends AppLocalizations { @override String get lifeDescription => - 'Campus life services and everyday tools will appear here.'; + 'Campus life services and everyday tools will appear here'; @override - String get homeworkTimezone => 'All deadlines use Beijing time (UTC+8).'; + String get homeworkTimezone => 'All deadlines use Beijing time (UTC+8)'; @override String get homeworkRefresh => 'Refresh assignments'; @@ -555,10 +555,10 @@ class AppLocalizationsEn extends AppLocalizations { @override String get homeworkActionsUnavailable => - 'Actions without a connected provider are unavailable.'; + 'Actions without a connected provider are unavailable'; @override - String get homeworkActionFailed => 'Action failed. Please try again.'; + String get homeworkActionFailed => 'Action failed. Please try again'; @override String get courseFiles => 'Course files'; @@ -567,27 +567,24 @@ class AppLocalizationsEn extends AppLocalizations { String get courseAssignments => 'Course assignments'; @override - String get courseAssignmentsScope => 'Unsubmitted, submitted and graded'; - - @override - String get courseFilesEmpty => 'No course files yet.'; + String get courseFilesEmpty => 'No course files yet'; @override String courseFilesLimited(int count) { - return 'Showing up to $count files; more files may be available on Learn.'; + return 'Showing up to $count files; more files may be available on Learn'; } @override String get courseContentError => - 'Could not load course content. Please try again.'; + 'Could not load course content. Please try again'; @override String get coursePreviewError => - 'Preview is unavailable. The file may not have a PDF preview on Learn. Please retry or open it on the teaching platform.'; + 'Preview is unavailable. The file may not have a PDF preview on Learn. Please retry or open it on the teaching platform'; @override String get courseSessionExpired => - 'Your session has expired. Sign in again to continue.'; + 'Your session has expired. Sign in again to continue'; @override String get courseUnsubmitted => 'Unsubmitted'; @@ -599,13 +596,19 @@ class AppLocalizationsEn extends AppLocalizations { String get courseGraded => 'Graded'; @override - String get courseAssignmentsEmpty => 'No assignments in this category.'; + String get courseAssignmentsEmpty => 'No assignments in this category'; @override String get coursePreviewUnsupported => - 'Document preview is not supported on Linux yet.'; + 'Document preview is not supported on Linux yet'; @override String get sessionVerificationRequired => - 'Verification is required to refresh campus data. Your saved information is still available.'; + 'Verification is required to refresh campus data. Your saved information is still available'; + + @override + String get courseContentLoading => 'Loading course content'; + + @override + String get coursePreviewLoading => 'Loading document'; } diff --git a/lib/l10n/generated/app_localizations_zh.dart b/lib/l10n/generated/app_localizations_zh.dart index bf26902..06c7fdd 100644 --- a/lib/l10n/generated/app_localizations_zh.dart +++ b/lib/l10n/generated/app_localizations_zh.dart @@ -54,10 +54,10 @@ class AppLocalizationsZh extends AppLocalizations { String get signInAction => '登录'; @override - String get requiredField => '此字段为必填项。'; + String get requiredField => '此字段为必填项'; @override - String get loginError => '登录失败,请检查学号和密码后重试。'; + String get loginError => '登录失败,请检查学号和密码后重试'; @override String get showPassword => '显示密码'; @@ -86,14 +86,14 @@ class AppLocalizationsZh extends AppLocalizations { String get verificationCodeHint => '请输入验证码'; @override - String get verificationCodeInvalid => '验证码不正确,请重试。'; + String get verificationCodeInvalid => '验证码不正确,请重试'; @override String get trustDeviceTitle => '信任此设备?'; @override String get trustDeviceDescription => - '清华身份认证服务可能会记住此设备,减少后续验证码验证。请仅在你本人控制的设备上选择信任。'; + '清华身份认证服务可能会记住此设备,减少后续验证码验证。请仅在你本人控制的设备上选择信任'; @override String get trustDeviceAction => '信任设备'; @@ -117,7 +117,7 @@ class AppLocalizationsZh extends AppLocalizations { String get logoutAction => '退出登录'; @override - String get logoutError => '无法清除已保存的登录状态,请重试。'; + String get logoutError => '无法清除已保存的登录状态,请重试'; @override String get eventsTab => '事件'; @@ -135,13 +135,13 @@ class AppLocalizationsZh extends AppLocalizations { String get eventsTitle => '学生事件'; @override - String get eventsDescription => '即将开始的课程、校历提醒和其他与学生相关的事件将在这里显示。'; + String get eventsDescription => '即将开始的课程、校历提醒和其他与学生相关的事件将在这里显示'; @override String get plansTitle => '学生计划'; @override - String get plansDescription => '你的教学日历和自定义计划将在这里显示。'; + String get plansDescription => '你的教学日历和自定义计划将在这里显示'; @override String calendarWeek(int week) { @@ -179,7 +179,7 @@ class AppLocalizationsZh extends AppLocalizations { String get calendarExportFormatPng => '图片 (.png)'; @override - String get calendarExportPngCurrentWeekOnly => 'PNG 仅导出当前周。'; + String get calendarExportPngCurrentWeekOnly => 'PNG 仅导出当前周'; @override String get calendarExportDateColumn => '日期'; @@ -221,28 +221,28 @@ class AppLocalizationsZh extends AppLocalizations { String get calendarExportAction => '导出'; @override - String get calendarExportNoEvents => '所选范围和内容没有可导出的日程。'; + String get calendarExportNoEvents => '所选范围和内容没有可导出的日程'; @override - String get calendarExportFailed => '无法导出日历,请重试。'; + String get calendarExportFailed => '无法导出日历,请重试'; @override - String get calendarExportSaved => '日历文件已保存。'; + String get calendarExportSaved => '日历文件已保存'; @override String get calendarLoading => '正在加载日历…'; @override - String get calendarLoadError => '无法加载教学日历。'; + String get calendarLoadError => '无法加载教学日历'; @override - String get calendarStaleCache => '更新失败,当前显示已保存的日历。'; + String get calendarStaleCache => '更新失败,当前显示已保存的日历'; @override String get calendarRetry => '重试'; @override - String get calendarNoCourses => '本周没有计划。'; + String get calendarNoCourses => '本周没有计划'; @override String get calendarOverlappingPlans => '重叠的计划'; @@ -281,7 +281,7 @@ class AppLocalizationsZh extends AppLocalizations { String get planCategoryColor => '分类颜色'; @override - String get planCategoryDuplicate => '已有同名分类。'; + String get planCategoryDuplicate => '已有同名分类'; @override String get planRepeat => '重复方式'; @@ -307,19 +307,19 @@ class AppLocalizationsZh extends AppLocalizations { String get planIntervalDays => '间隔天数'; @override - String get planIntervalInvalid => '请输入大于零的天数。'; + String get planIntervalInvalid => '请输入大于零的天数'; @override - String get planTimeRequired => '请选择日期、开始时间和结束时间。'; + String get planTimeRequired => '请选择日期、开始时间和结束时间'; @override - String get planEndAfterStart => '结束时间必须晚于同一天的开始时间。'; + String get planEndAfterStart => '结束时间必须晚于同一天的开始时间'; @override String get planSave => '保存计划'; @override - String get planSaveError => '无法保存计划,请重试。'; + String get planSaveError => '无法保存计划,请重试'; @override String get planEditTitle => '编辑计划'; @@ -358,13 +358,13 @@ class AppLocalizationsZh extends AppLocalizations { String get planConfirmCancelTitle => '确认取消本次计划?'; @override - String get planConfirmFetchedLesson => '这节课只会在 Thulium 中隐藏,不会修改学校教学日历的数据。'; + String get planConfirmFetchedLesson => '这节课只会在 Thulium 中隐藏,不会修改学校教学日历的数据'; @override - String get planConfirmDeleteSeries => '将删除此重复计划的所有次数,包括单次修改。'; + String get planConfirmDeleteSeries => '将删除此重复计划的所有次数,包括单次修改'; @override - String get planConfirmOneOccurrence => '只移除本次计划,其他次数仍会保留。'; + String get planConfirmOneOccurrence => '只移除本次计划,其他次数仍会保留'; @override String get planDontAskAgain => '此操作下次不再提醒'; @@ -379,13 +379,13 @@ class AppLocalizationsZh extends AppLocalizations { String get studyTitle => '学习'; @override - String get studyDescription => '学习工具和学习资源将在这里显示。'; + String get studyDescription => '学习工具和学习资源将在这里显示'; @override String get studyToolsTitle => '学习快捷入口'; @override - String get studyToolsPlaceholder => '这里将显示常用学习功能。'; + String get studyToolsPlaceholder => '这里将显示常用学习功能'; @override String get studyCoursesTitle => '我的课程'; @@ -394,13 +394,13 @@ class AppLocalizationsZh extends AppLocalizations { String get studyRefresh => '刷新课程'; @override - String get studyLoadError => '无法加载课程,请尝试刷新。'; + String get studyLoadError => '无法加载课程,请尝试刷新'; @override - String get studyStaleCourses => '更新失败,正在显示已保存的课程。'; + String get studyStaleCourses => '更新失败,正在显示已保存的课程'; @override - String get studyNoCourses => '本学期暂无课程。'; + String get studyNoCourses => '本学期暂无课程'; @override String studyUnsubmittedHomework(int count) { @@ -408,7 +408,7 @@ class AppLocalizationsZh extends AppLocalizations { } @override - String get studyHomeworkLoadError => '未交作业数量加载失败,请刷新重试。'; + String get studyHomeworkLoadError => '未交作业数量加载失败,请刷新重试'; @override String get homeworkTitle => '近期作业'; @@ -417,10 +417,10 @@ class AppLocalizationsZh extends AppLocalizations { String get homeworkEmpty => '全部完成'; @override - String get homeworkStale => '作业更新失败,正在显示已保存的数据。'; + String get homeworkStale => '作业更新失败,正在显示已保存的数据'; @override - String get homeworkLoadError => '作业加载失败,请刷新重试。'; + String get homeworkLoadError => '作业加载失败,请刷新重试'; @override String get homeworkExpired => '已逾期'; @@ -452,7 +452,7 @@ class AppLocalizationsZh extends AppLocalizations { String get lifeTitle => '生活'; @override - String get lifeDescription => '校园生活服务和日常工具将在这里显示。'; + String get lifeDescription => '校园生活服务和日常工具将在这里显示'; @override String get homeworkTimezone => '截止时间均为北京时间(UTC+8)'; @@ -528,10 +528,10 @@ class AppLocalizationsZh extends AppLocalizations { String get homeworkMarkSubmitted => '标记已提交'; @override - String get homeworkActionsUnavailable => '未接入的操作当前不可用。'; + String get homeworkActionsUnavailable => '未接入的操作当前不可用'; @override - String get homeworkActionFailed => '操作失败,请重试。'; + String get homeworkActionFailed => '操作失败,请重试'; @override String get courseFiles => '课程文件'; @@ -540,24 +540,21 @@ class AppLocalizationsZh extends AppLocalizations { String get courseAssignments => '课程作业'; @override - String get courseAssignmentsScope => '未提交、已提交及已批改'; - - @override - String get courseFilesEmpty => '暂无课程文件。'; + String get courseFilesEmpty => '暂无课程文件'; @override String courseFilesLimited(int count) { - return '最多显示 $count 个文件,教学平台上可能还有更多文件。'; + return '最多显示 $count 个文件,教学平台上可能还有更多文件'; } @override - String get courseContentError => '无法加载课程内容,请重试。'; + String get courseContentError => '无法加载课程内容,请重试'; @override - String get coursePreviewError => '无法预览,教学平台可能尚未提供此文件的 PDF 预览。请重试或前往教学平台查看。'; + String get coursePreviewError => '无法预览,教学平台可能尚未提供此文件的 PDF 预览。请重试或前往教学平台查看'; @override - String get courseSessionExpired => '登录已过期,请重新登录。'; + String get courseSessionExpired => '登录已过期,请重新登录'; @override String get courseUnsubmitted => '未提交'; @@ -569,13 +566,19 @@ class AppLocalizationsZh extends AppLocalizations { String get courseGraded => '已批改'; @override - String get courseAssignmentsEmpty => '此分类暂无作业。'; + String get courseAssignmentsEmpty => '此分类暂无作业'; @override - String get coursePreviewUnsupported => 'Linux 暂不支持文档预览。'; + String get coursePreviewUnsupported => 'Linux 暂不支持文档预览'; @override - String get sessionVerificationRequired => '更新校园数据需要重新验证,已保存的信息仍可查看。'; + String get sessionVerificationRequired => '更新校园数据需要重新验证,已保存的信息仍可查看'; + + @override + String get courseContentLoading => '正在加载课程内容'; + + @override + String get coursePreviewLoading => '正在加载文档'; } /// The translations for Chinese, as used in China (`zh_CN`). @@ -628,10 +631,10 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get signInAction => '登录'; @override - String get requiredField => '此字段为必填项。'; + String get requiredField => '此字段为必填项'; @override - String get loginError => '登录失败,请检查学号和密码后重试。'; + String get loginError => '登录失败,请检查学号和密码后重试'; @override String get showPassword => '显示密码'; @@ -660,14 +663,14 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get verificationCodeHint => '请输入验证码'; @override - String get verificationCodeInvalid => '验证码不正确,请重试。'; + String get verificationCodeInvalid => '验证码不正确,请重试'; @override String get trustDeviceTitle => '信任此设备?'; @override String get trustDeviceDescription => - '清华身份认证服务可能会记住此设备,减少后续验证码验证。请仅在你本人控制的设备上选择信任。'; + '清华身份认证服务可能会记住此设备,减少后续验证码验证。请仅在你本人控制的设备上选择信任'; @override String get trustDeviceAction => '信任设备'; @@ -691,7 +694,7 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get logoutAction => '退出登录'; @override - String get logoutError => '无法清除已保存的登录状态,请重试。'; + String get logoutError => '无法清除已保存的登录状态,请重试'; @override String get eventsTab => '事件'; @@ -709,13 +712,13 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get eventsTitle => '学生事件'; @override - String get eventsDescription => '即将开始的课程、校历提醒和其他与学生相关的事件将在这里显示。'; + String get eventsDescription => '即将开始的课程、校历提醒和其他与学生相关的事件将在这里显示'; @override String get plansTitle => '学生计划'; @override - String get plansDescription => '你的教学日历和自定义计划将在这里显示。'; + String get plansDescription => '你的教学日历和自定义计划将在这里显示'; @override String calendarWeek(int week) { @@ -753,7 +756,7 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get calendarExportFormatPng => '图片 (.png)'; @override - String get calendarExportPngCurrentWeekOnly => 'PNG 仅导出当前周。'; + String get calendarExportPngCurrentWeekOnly => 'PNG 仅导出当前周'; @override String get calendarExportDateColumn => '日期'; @@ -795,28 +798,28 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get calendarExportAction => '导出'; @override - String get calendarExportNoEvents => '所选范围和内容没有可导出的日程。'; + String get calendarExportNoEvents => '所选范围和内容没有可导出的日程'; @override - String get calendarExportFailed => '无法导出日历,请重试。'; + String get calendarExportFailed => '无法导出日历,请重试'; @override - String get calendarExportSaved => '日历文件已保存。'; + String get calendarExportSaved => '日历文件已保存'; @override String get calendarLoading => '正在加载日历…'; @override - String get calendarLoadError => '无法加载教学日历。'; + String get calendarLoadError => '无法加载教学日历'; @override - String get calendarStaleCache => '更新失败,当前显示已保存的日历。'; + String get calendarStaleCache => '更新失败,当前显示已保存的日历'; @override String get calendarRetry => '重试'; @override - String get calendarNoCourses => '本周没有计划。'; + String get calendarNoCourses => '本周没有计划'; @override String get calendarOverlappingPlans => '重叠的计划'; @@ -855,7 +858,7 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get planCategoryColor => '分类颜色'; @override - String get planCategoryDuplicate => '已有同名分类。'; + String get planCategoryDuplicate => '已有同名分类'; @override String get planRepeat => '重复方式'; @@ -881,19 +884,19 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get planIntervalDays => '间隔天数'; @override - String get planIntervalInvalid => '请输入大于零的天数。'; + String get planIntervalInvalid => '请输入大于零的天数'; @override - String get planTimeRequired => '请选择日期、开始时间和结束时间。'; + String get planTimeRequired => '请选择日期、开始时间和结束时间'; @override - String get planEndAfterStart => '结束时间必须晚于同一天的开始时间。'; + String get planEndAfterStart => '结束时间必须晚于同一天的开始时间'; @override String get planSave => '保存计划'; @override - String get planSaveError => '无法保存计划,请重试。'; + String get planSaveError => '无法保存计划,请重试'; @override String get planEditTitle => '编辑计划'; @@ -932,13 +935,13 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get planConfirmCancelTitle => '确认取消本次计划?'; @override - String get planConfirmFetchedLesson => '这节课只会在 Thulium 中隐藏,不会修改学校教学日历的数据。'; + String get planConfirmFetchedLesson => '这节课只会在 Thulium 中隐藏,不会修改学校教学日历的数据'; @override - String get planConfirmDeleteSeries => '将删除此重复计划的所有次数,包括单次修改。'; + String get planConfirmDeleteSeries => '将删除此重复计划的所有次数,包括单次修改'; @override - String get planConfirmOneOccurrence => '只移除本次计划,其他次数仍会保留。'; + String get planConfirmOneOccurrence => '只移除本次计划,其他次数仍会保留'; @override String get planDontAskAgain => '此操作下次不再提醒'; @@ -953,13 +956,13 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get studyTitle => '学习'; @override - String get studyDescription => '学习工具和学习资源将在这里显示。'; + String get studyDescription => '学习工具和学习资源将在这里显示'; @override String get studyToolsTitle => '学习快捷入口'; @override - String get studyToolsPlaceholder => '这里将显示常用学习功能。'; + String get studyToolsPlaceholder => '这里将显示常用学习功能'; @override String get studyCoursesTitle => '我的课程'; @@ -968,13 +971,13 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get studyRefresh => '刷新课程'; @override - String get studyLoadError => '无法加载课程,请尝试刷新。'; + String get studyLoadError => '无法加载课程,请尝试刷新'; @override - String get studyStaleCourses => '更新失败,正在显示已保存的课程。'; + String get studyStaleCourses => '更新失败,正在显示已保存的课程'; @override - String get studyNoCourses => '本学期暂无课程。'; + String get studyNoCourses => '本学期暂无课程'; @override String studyUnsubmittedHomework(int count) { @@ -982,7 +985,7 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { } @override - String get studyHomeworkLoadError => '未交作业数量加载失败,请刷新重试。'; + String get studyHomeworkLoadError => '未交作业数量加载失败,请刷新重试'; @override String get homeworkTitle => '近期作业'; @@ -991,10 +994,10 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get homeworkEmpty => '全部完成'; @override - String get homeworkStale => '作业更新失败,正在显示已保存的数据。'; + String get homeworkStale => '作业更新失败,正在显示已保存的数据'; @override - String get homeworkLoadError => '作业加载失败,请刷新重试。'; + String get homeworkLoadError => '作业加载失败,请刷新重试'; @override String get homeworkExpired => '已逾期'; @@ -1026,7 +1029,7 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get lifeTitle => '生活'; @override - String get lifeDescription => '校园生活服务和日常工具将在这里显示。'; + String get lifeDescription => '校园生活服务和日常工具将在这里显示'; @override String get homeworkTimezone => '截止时间均为北京时间(UTC+8)'; @@ -1102,10 +1105,10 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get homeworkMarkSubmitted => '标记已提交'; @override - String get homeworkActionsUnavailable => '未接入的操作当前不可用。'; + String get homeworkActionsUnavailable => '未接入的操作当前不可用'; @override - String get homeworkActionFailed => '操作失败,请重试。'; + String get homeworkActionFailed => '操作失败,请重试'; @override String get courseFiles => '课程文件'; @@ -1114,24 +1117,21 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get courseAssignments => '课程作业'; @override - String get courseAssignmentsScope => '未提交、已提交及已批改'; - - @override - String get courseFilesEmpty => '暂无课程文件。'; + String get courseFilesEmpty => '暂无课程文件'; @override String courseFilesLimited(int count) { - return '最多显示 $count 个文件,教学平台上可能还有更多文件。'; + return '最多显示 $count 个文件,教学平台上可能还有更多文件'; } @override - String get courseContentError => '无法加载课程内容,请重试。'; + String get courseContentError => '无法加载课程内容,请重试'; @override - String get coursePreviewError => '无法预览,教学平台可能尚未提供此文件的 PDF 预览。请重试或前往教学平台查看。'; + String get coursePreviewError => '无法预览,教学平台可能尚未提供此文件的 PDF 预览。请重试或前往教学平台查看'; @override - String get courseSessionExpired => '登录已过期,请重新登录。'; + String get courseSessionExpired => '登录已过期,请重新登录'; @override String get courseUnsubmitted => '未提交'; @@ -1143,13 +1143,19 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { String get courseGraded => '已批改'; @override - String get courseAssignmentsEmpty => '此分类暂无作业。'; + String get courseAssignmentsEmpty => '此分类暂无作业'; + + @override + String get coursePreviewUnsupported => 'Linux 暂不支持文档预览'; + + @override + String get sessionVerificationRequired => '更新校园数据需要重新验证,已保存的信息仍可查看'; @override - String get coursePreviewUnsupported => 'Linux 暂不支持文档预览。'; + String get courseContentLoading => '正在加载课程内容'; @override - String get sessionVerificationRequired => '更新校园数据需要重新验证,已保存的信息仍可查看。'; + String get coursePreviewLoading => '正在加载文档'; } /// The translations for Chinese, as used in Taiwan (`zh_TW`). @@ -1202,10 +1208,10 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get signInAction => '登入'; @override - String get requiredField => '此欄位為必填項目。'; + String get requiredField => '此欄位為必填項目'; @override - String get loginError => '登入失敗,請檢查學號和密碼後重試。'; + String get loginError => '登入失敗,請檢查學號和密碼後重試'; @override String get showPassword => '顯示密碼'; @@ -1234,14 +1240,14 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get verificationCodeHint => '請輸入驗證碼'; @override - String get verificationCodeInvalid => '驗證碼不正確,請重試。'; + String get verificationCodeInvalid => '驗證碼不正確,請重試'; @override String get trustDeviceTitle => '信任此裝置?'; @override String get trustDeviceDescription => - '清華身分驗證服務可能會記住此裝置,減少後續驗證碼驗證。請僅在你本人控制的裝置上選擇信任。'; + '清華身分驗證服務可能會記住此裝置,減少後續驗證碼驗證。請僅在你本人控制的裝置上選擇信任'; @override String get trustDeviceAction => '信任裝置'; @@ -1265,7 +1271,7 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get logoutAction => '登出'; @override - String get logoutError => '無法清除已儲存的登入狀態,請重試。'; + String get logoutError => '無法清除已儲存的登入狀態,請重試'; @override String get eventsTab => '事件'; @@ -1283,13 +1289,13 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get eventsTitle => '學生事件'; @override - String get eventsDescription => '即將開始的課程、校曆提醒和其他與學生相關的事件將在這裡顯示。'; + String get eventsDescription => '即將開始的課程、校曆提醒和其他與學生相關的事件將在這裡顯示'; @override String get plansTitle => '學生計畫'; @override - String get plansDescription => '你的教學日曆和自訂計畫將在這裡顯示。'; + String get plansDescription => '你的教學日曆和自訂計畫將在這裡顯示'; @override String calendarWeek(int week) { @@ -1327,7 +1333,7 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get calendarExportFormatPng => '圖片 (.png)'; @override - String get calendarExportPngCurrentWeekOnly => 'PNG 僅匯出目前週。'; + String get calendarExportPngCurrentWeekOnly => 'PNG 僅匯出目前週'; @override String get calendarExportDateColumn => '日期'; @@ -1369,28 +1375,28 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get calendarExportAction => '匯出'; @override - String get calendarExportNoEvents => '所選範圍和內容沒有可匯出的行程。'; + String get calendarExportNoEvents => '所選範圍和內容沒有可匯出的行程'; @override - String get calendarExportFailed => '無法匯出日曆,請重試。'; + String get calendarExportFailed => '無法匯出日曆,請重試'; @override - String get calendarExportSaved => '日曆檔案已儲存。'; + String get calendarExportSaved => '日曆檔案已儲存'; @override String get calendarLoading => '正在載入日曆…'; @override - String get calendarLoadError => '無法載入教學日曆。'; + String get calendarLoadError => '無法載入教學日曆'; @override - String get calendarStaleCache => '更新失敗,目前顯示已儲存的日曆。'; + String get calendarStaleCache => '更新失敗,目前顯示已儲存的日曆'; @override String get calendarRetry => '重試'; @override - String get calendarNoCourses => '本週沒有計畫。'; + String get calendarNoCourses => '本週沒有計畫'; @override String get calendarOverlappingPlans => '重疊的計劃'; @@ -1429,7 +1435,7 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get planCategoryColor => '分類顏色'; @override - String get planCategoryDuplicate => '已有同名分類。'; + String get planCategoryDuplicate => '已有同名分類'; @override String get planRepeat => '重複方式'; @@ -1455,19 +1461,19 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get planIntervalDays => '間隔天數'; @override - String get planIntervalInvalid => '請輸入大於零的天數。'; + String get planIntervalInvalid => '請輸入大於零的天數'; @override - String get planTimeRequired => '請選擇日期、開始時間和結束時間。'; + String get planTimeRequired => '請選擇日期、開始時間和結束時間'; @override - String get planEndAfterStart => '結束時間必須晚於同一天的開始時間。'; + String get planEndAfterStart => '結束時間必須晚於同一天的開始時間'; @override String get planSave => '儲存計畫'; @override - String get planSaveError => '無法儲存計畫,請重試。'; + String get planSaveError => '無法儲存計畫,請重試'; @override String get planEditTitle => '編輯計畫'; @@ -1506,13 +1512,13 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get planConfirmCancelTitle => '確認取消本次計畫?'; @override - String get planConfirmFetchedLesson => '這堂課只會在 Thulium 中隱藏,不會修改學校教學日曆的資料。'; + String get planConfirmFetchedLesson => '這堂課只會在 Thulium 中隱藏,不會修改學校教學日曆的資料'; @override - String get planConfirmDeleteSeries => '將刪除此重複計畫的所有次數,包括單次修改。'; + String get planConfirmDeleteSeries => '將刪除此重複計畫的所有次數,包括單次修改'; @override - String get planConfirmOneOccurrence => '只移除本次計畫,其他次數仍會保留。'; + String get planConfirmOneOccurrence => '只移除本次計畫,其他次數仍會保留'; @override String get planDontAskAgain => '此操作下次不再提醒'; @@ -1527,13 +1533,13 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get studyTitle => '學習'; @override - String get studyDescription => '學習工具和學習資源將在這裡顯示。'; + String get studyDescription => '學習工具和學習資源將在這裡顯示'; @override String get studyToolsTitle => '學習快速入口'; @override - String get studyToolsPlaceholder => '這裡將顯示常用學習功能。'; + String get studyToolsPlaceholder => '這裡將顯示常用學習功能'; @override String get studyCoursesTitle => '我的課程'; @@ -1542,13 +1548,13 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get studyRefresh => '重新整理課程'; @override - String get studyLoadError => '無法載入課程,請嘗試重新整理。'; + String get studyLoadError => '無法載入課程,請嘗試重新整理'; @override - String get studyStaleCourses => '更新失敗,正在顯示已儲存的課程。'; + String get studyStaleCourses => '更新失敗,正在顯示已儲存的課程'; @override - String get studyNoCourses => '本學期暫無課程。'; + String get studyNoCourses => '本學期暫無課程'; @override String studyUnsubmittedHomework(int count) { @@ -1556,7 +1562,7 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { } @override - String get studyHomeworkLoadError => '未交作業數量載入失敗,請重新整理。'; + String get studyHomeworkLoadError => '未交作業數量載入失敗,請重新整理'; @override String get homeworkTitle => '近期作業'; @@ -1565,10 +1571,10 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get homeworkEmpty => '全部完成'; @override - String get homeworkStale => '作業更新失敗,正在顯示已儲存的資料。'; + String get homeworkStale => '作業更新失敗,正在顯示已儲存的資料'; @override - String get homeworkLoadError => '作業載入失敗,請重新整理。'; + String get homeworkLoadError => '作業載入失敗,請重新整理'; @override String get homeworkExpired => '已逾期'; @@ -1600,7 +1606,7 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get lifeTitle => '生活'; @override - String get lifeDescription => '校園生活服務和日常工具將在這裡顯示。'; + String get lifeDescription => '校園生活服務和日常工具將在這裡顯示'; @override String get homeworkTimezone => '截止時間均為北京時間(UTC+8)'; @@ -1676,10 +1682,10 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get homeworkMarkSubmitted => '標記已提交'; @override - String get homeworkActionsUnavailable => '未接入的操作目前無法使用。'; + String get homeworkActionsUnavailable => '未接入的操作目前無法使用'; @override - String get homeworkActionFailed => '操作失敗,請重試。'; + String get homeworkActionFailed => '操作失敗,請重試'; @override String get courseFiles => '課程檔案'; @@ -1688,24 +1694,21 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get courseAssignments => '課程作業'; @override - String get courseAssignmentsScope => '未繳交、已繳交及已批改'; - - @override - String get courseFilesEmpty => '暫無課程檔案。'; + String get courseFilesEmpty => '暫無課程檔案'; @override String courseFilesLimited(int count) { - return '最多顯示 $count 個檔案,教學平台上可能還有更多檔案。'; + return '最多顯示 $count 個檔案,教學平台上可能還有更多檔案'; } @override - String get courseContentError => '無法載入課程內容,請重試。'; + String get courseContentError => '無法載入課程內容,請重試'; @override - String get coursePreviewError => '無法預覽,教學平台可能尚未提供此檔案的 PDF 預覽。請重試或前往教學平台查看。'; + String get coursePreviewError => '無法預覽,教學平台可能尚未提供此檔案的 PDF 預覽。請重試或前往教學平台查看'; @override - String get courseSessionExpired => '登入已過期,請重新登入。'; + String get courseSessionExpired => '登入已過期,請重新登入'; @override String get courseUnsubmitted => '未繳交'; @@ -1717,11 +1720,17 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { String get courseGraded => '已批改'; @override - String get courseAssignmentsEmpty => '此分類暫無作業。'; + String get courseAssignmentsEmpty => '此分類暫無作業'; + + @override + String get coursePreviewUnsupported => 'Linux 暫不支援文件預覽'; + + @override + String get sessionVerificationRequired => '更新校園資料需要重新驗證,已儲存的資訊仍可查看'; @override - String get coursePreviewUnsupported => 'Linux 暫不支援文件預覽。'; + String get courseContentLoading => '正在載入課程內容'; @override - String get sessionVerificationRequired => '更新校園資料需要重新驗證,已儲存的資訊仍可查看。'; + String get coursePreviewLoading => '正在載入文件'; } diff --git a/lib/navigation/app_page_route.dart b/lib/navigation/app_page_route.dart new file mode 100644 index 0000000..86143de --- /dev/null +++ b/lib/navigation/app_page_route.dart @@ -0,0 +1,36 @@ +import 'package:flutter/widgets.dart'; + +/// A short, directional response to navigation, shared by all pushed pages. +/// Reduced motion removes both the transition and the loading crossfade. +class AppPageRoute extends PageRouteBuilder { + AppPageRoute({ + required BuildContext context, + required WidgetBuilder builder, + super.settings, + }) : super( + transitionDuration: MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : const Duration(milliseconds: 200), + reverseTransitionDuration: MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : const Duration(milliseconds: 160), + pageBuilder: (context, _, _) => builder(context), + transitionsBuilder: (context, animation, secondaryAnimation, child) { + final direction = Directionality.of(context) == TextDirection.rtl + ? -1.0 + : 1.0; + final curve = animation.drive( + CurveTween(curve: Curves.easeOutCubic), + ); + return FadeTransition( + opacity: curve, + child: SlideTransition( + position: curve.drive( + Tween(begin: Offset(0.025 * direction, 0), end: Offset.zero), + ), + child: child, + ), + ); + }, + ); +} diff --git a/lib/pages/add_plan_page.dart b/lib/pages/add_plan_page.dart index 4804562..8346ac9 100644 --- a/lib/pages/add_plan_page.dart +++ b/lib/pages/add_plan_page.dart @@ -2,6 +2,8 @@ import 'package:flutter/material.dart'; import 'package:forui/forui.dart'; + +import '../widgets/app_page_scaffold.dart'; import 'package:thulium_campus/thulium_campus.dart'; import 'package:thulium/l10n/generated/app_localizations.dart'; @@ -188,36 +190,23 @@ final class _AddPlanPageState extends State { PlanRepeat.weekly: l10n.planRepeatWeekly, PlanRepeat.intervalDays: l10n.planRepeatInterval, }; - return FScaffold( + return AppPageScaffold( + title: widget.initialPlan == null && widget.initialOccurrence == null + ? l10n.planAddTitle + : l10n.planEditTitle, + maxWidth: 560, child: SafeArea( - child: Center( + child: Align( + alignment: Alignment.topCenter, child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 560), child: SingleChildScrollView( - padding: const EdgeInsets.all(24), + padding: const EdgeInsets.symmetric(vertical: 16), child: Form( key: _formKey, child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Align( - alignment: Alignment.centerLeft, - child: FButton.icon( - semanticsLabel: l10n.backAction, - variant: FButtonVariant.ghost, - onPress: () => Navigator.of(context).pop(), - child: const Icon(Icons.arrow_back), - ), - ), - const SizedBox(height: 16), - Text( - widget.initialPlan == null && - widget.initialOccurrence == null - ? l10n.planAddTitle - : l10n.planEditTitle, - style: context.theme.typography.xl2, - ), - const SizedBox(height: 24), FTextFormField( control: FTextFieldControl.managed(controller: _name), label: Text(l10n.planName), diff --git a/lib/pages/calendar_page.dart b/lib/pages/calendar_page.dart index a2bf9b1..1d3d9b6 100644 --- a/lib/pages/calendar_page.dart +++ b/lib/pages/calendar_page.dart @@ -10,6 +10,8 @@ import 'package:flutter/material.dart'; import 'package:flutter/foundation.dart' show defaultTargetPlatform, kIsWeb, TargetPlatform; import 'package:forui/forui.dart'; + +import '../navigation/app_page_route.dart'; import 'package:intl/intl.dart'; import 'package:share_plus/share_plus.dart'; import 'package:thulium_campus/thulium_campus.dart'; @@ -264,7 +266,8 @@ final class _AcademicCalendarPageState extends State ? today : monday; await Navigator.of(context).push( - MaterialPageRoute( + AppPageRoute( + context: context, builder: (context) => AddPlanPage( initialDate: date, categories: _customPlans.categories, @@ -505,7 +508,8 @@ final class _AcademicCalendarPageState extends State }) async { final initialRule = editSeries ? entry.rule! : null; await Navigator.of(context).push( - MaterialPageRoute( + AppPageRoute( + context: context, builder: (context) => AddPlanPage( initialDate: editSeries ? initialRule!.startsAt diff --git a/lib/pages/course_detail_page.dart b/lib/pages/course_detail_page.dart index 28b76f0..cbc4961 100644 --- a/lib/pages/course_detail_page.dart +++ b/lib/pages/course_detail_page.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/widgets.dart'; import 'package:forui/forui.dart'; import 'package:intl/intl.dart'; @@ -8,6 +10,9 @@ import '../l10n/generated/app_localizations.dart'; import '../study/course_content_source.dart'; import '../widgets/flat_tile_style.dart'; import '../widgets/course_document_preview.dart'; +import '../widgets/app_page_scaffold.dart'; +import '../navigation/app_page_route.dart'; +import '../widgets/course_content_loading.dart'; class CourseDetailPage extends StatelessWidget { const CourseDetailPage({ @@ -30,14 +35,24 @@ class CourseDetailPage extends StatelessWidget { course.englishName.isNotEmpty ? course.englishName : course.name; - return FScaffold( - header: _header(context, name), + return AppPageScaffold( + title: name, child: ListView( children: [ if (course.teacherName.isNotEmpty) - Text(course.teacherName, style: theme.typography.sm), + Text( + course.teacherName, + style: theme.typography.sm.copyWith( + color: theme.colors.mutedForeground, + ), + ), if (course.schedule.isNotEmpty) - Text(course.schedule, style: theme.typography.sm), + Text( + course.schedule, + style: theme.typography.sm.copyWith( + color: theme.colors.mutedForeground, + ), + ), SizedBox(height: theme.style.pagePadding.top), FTileGroup( style: flatTileGroupStyle, @@ -45,6 +60,7 @@ class CourseDetailPage extends StatelessWidget { divider: FItemDivider.full, children: [ FTile( + style: flatTileStyle(theme), title: Text(l10n.courseFiles), prefix: const Icon(FLucideIcons.files), onPress: () => _push( @@ -69,6 +85,7 @@ class CourseDetailPage extends StatelessWidget { children: [ for (final file in data.materials) FTile( + style: flatTileStyle(context.theme), key: ValueKey('course-file-${file.id}'), title: Text(file.title), subtitle: Text( @@ -97,8 +114,8 @@ class CourseDetailPage extends StatelessWidget { ), ), FTile( + style: flatTileStyle(theme), title: Text(l10n.courseAssignments), - subtitle: Text(l10n.courseAssignmentsScope), prefix: const Icon(FLucideIcons.listTodo), onPress: () => _push( context, @@ -125,6 +142,7 @@ class CourseDetailPage extends StatelessWidget { children: [ for (final assignment in entry.value) FTile( + style: flatTileStyle(context.theme), title: Text(assignment.title), subtitle: Text( assignment.deadline == null @@ -159,21 +177,7 @@ class CourseDetailPage extends StatelessWidget { void _push(BuildContext context, Widget page) => Navigator.of( context, -).push(PageRouteBuilder(pageBuilder: (_, _, _) => page)); - -FHeader _header(BuildContext context, String title, {Widget? suffix}) => - FHeader.nested( - title: Text(title, maxLines: 2, overflow: TextOverflow.ellipsis), - prefixes: [ - FButton.icon( - variant: FButtonVariant.ghost, - semanticsLabel: AppLocalizations.of(context)!.homeworkBack, - onPress: () => Navigator.of(context).pop(), - child: const Icon(FLucideIcons.arrowLeft), - ), - ], - suffixes: [?suffix], - ); +).push(AppPageRoute(context: context, builder: (_) => page)); class _CourseResourcePage extends StatefulWidget { const _CourseResourcePage({ @@ -194,78 +198,138 @@ class _CourseResourcePage extends StatefulWidget { } class _CourseResourcePageState extends State<_CourseResourcePage> { - late Future _future = widget.load(); - int _generation = 0; + T? _data; + Object? _error; + bool _loading = true; + int _contentGeneration = 0; + + @override + void initState() { + super.initState(); + unawaited(_load()); + } Future _refresh() async { - final future = widget.load(); + if (_loading) return; setState(() { - _future = future; - _generation++; + _loading = true; + _error = null; }); - // FutureBuilder owns error presentation, including failures during refresh. + await _load(); + } + + Future _load() async { try { - await future; - } on Object { - /* Displayed by FutureBuilder. */ + final data = await widget.load(); + if (!mounted) return; + setState(() { + _data = data; + _error = null; + _loading = false; + _contentGeneration++; + }); + } on Object catch (error) { + if (!mounted) return; + setState(() { + _error = error; + _loading = false; + }); } } @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context)!; - return FScaffold( - childPad: !widget.document, - header: _header( - context, - widget.title, - suffix: FButton.icon( + final expired = + _error is PortalSessionRejected || + _error is PortalCsrfUnavailable || + _error is TwoFactorInteractionRequired; + final errorText = expired + ? l10n.courseSessionExpired + : widget.document + ? l10n.coursePreviewError + : l10n.courseContentError; + final data = _data; + final Widget content; + if (data != null) { + content = Column( + children: [ + if (_error != null) + Padding( + padding: context.theme.style.pagePadding, + child: FAlert( + title: Text(errorText), + subtitle: expired + ? FButton( + onPress: widget.onSessionExpired, + child: Text(l10n.signInAction), + ) + : null, + ), + ), + Expanded( + child: KeyedSubtree( + key: ValueKey(widget.document ? _contentGeneration : 0), + child: widget.builder(context, data, _refresh), + ), + ), + ], + ); + } else if (_loading) { + content = CourseContentLoading(document: widget.document); + } else { + content = Center( + child: Padding( + padding: context.theme.style.pagePadding, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + errorText, + style: context.theme.typography.sm, + textAlign: TextAlign.center, + ), + SizedBox(height: context.theme.style.pagePadding.top), + FButton( + onPress: expired ? widget.onSessionExpired : _refresh, + child: Text(expired ? l10n.signInAction : l10n.calendarRetry), + ), + ], + ), + ), + ); + } + return AppPageScaffold( + title: widget.title, + fullBleed: widget.document, + actions: [ + FButton.icon( variant: FButtonVariant.ghost, semanticsLabel: l10n.studyRefresh, - onPress: _refresh, - child: const Icon(FLucideIcons.refreshCw), + onPress: _loading ? null : _refresh, + child: _loading + ? const FCircularProgress(size: FCircularProgressSizeVariant.xs) + : const Icon(FLucideIcons.refreshCw), + ), + ], + child: AnimatedSwitcher( + duration: MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : const Duration(milliseconds: 160), + switchInCurve: Curves.easeOut, + switchOutCurve: Curves.easeIn, + layoutBuilder: (current, previous) => + Stack(fit: StackFit.expand, children: [...previous, ?current]), + child: KeyedSubtree( + key: ValueKey( + data != null + ? 'content' + : _loading + ? 'loading' + : 'error', + ), + child: content, ), - ), - child: FutureBuilder( - key: ValueKey(_generation), - future: _future, - builder: (context, snapshot) { - if (snapshot.connectionState != ConnectionState.done) { - return const Center(child: FCircularProgress()); - } - if (snapshot.hasError) { - final expired = - snapshot.error is PortalSessionRejected || - snapshot.error is PortalCsrfUnavailable; - return Center( - child: Padding( - padding: context.theme.style.pagePadding, - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - FAlert( - title: Text( - expired - ? l10n.courseSessionExpired - : widget.document - ? l10n.coursePreviewError - : l10n.courseContentError, - ), - ), - SizedBox(height: context.theme.style.pagePadding.top), - FButton( - onPress: expired ? widget.onSessionExpired : _refresh, - child: Text( - expired ? l10n.loginTitle : l10n.calendarRetry, - ), - ), - ], - ), - ), - ); - } - return widget.builder(context, snapshot.data as T, _refresh); - }, ), ); } diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index b6969be..85d2414 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -4,6 +4,8 @@ import 'dart:async'; import 'package:flutter/material.dart'; import 'package:forui/forui.dart'; + +import '../navigation/app_page_route.dart'; import 'package:thulium/l10n/generated/app_localizations.dart'; import 'package:thulium_auth/thulium_auth.dart'; import 'package:thulium_campus/thulium_campus.dart'; @@ -12,6 +14,7 @@ import '../auth/secure_auth_session_store.dart'; import '../auth/secure_learn_course_cache_store.dart'; import '../auth/secure_learn_homework_cache_store.dart'; import '../widgets/language_button.dart'; +import '../widgets/app_icon_button.dart'; import '../widgets/app_bottom_navigation.dart'; import '../widgets/homework_overview_card.dart'; import 'settings_page.dart'; @@ -426,8 +429,9 @@ final class _HomePageState extends State with WidgetsBindingObserver { final catalog = _courseCatalog; if (catalog == null) return; Navigator.of(context).push( - PageRouteBuilder( - pageBuilder: (_, _, _) => CourseDetailPage( + AppPageRoute( + context: context, + builder: (_) => CourseDetailPage( course: course, source: CourseContentSource( store: @@ -451,19 +455,13 @@ final class _HomePageState extends State with WidgetsBindingObserver { onSelected: widget.onLocaleSelected, buttonSize: headerIconSize, ), - SizedBox.square( - dimension: headerIconSize, - child: IconButton( - tooltip: l10n.theme, - padding: EdgeInsets.zero, - iconSize: 20, - icon: Icon( - Theme.of(context).brightness == Brightness.dark - ? Icons.light_mode_outlined - : Icons.dark_mode_outlined, - ), - onPressed: widget.onThemeToggle, - ), + AppIconButton( + label: l10n.theme, + size: headerIconSize, + icon: Theme.of(context).brightness == Brightness.dark + ? FLucideIcons.sun + : FLucideIcons.moon, + onPress: widget.onThemeToggle, ), ], ), @@ -471,17 +469,14 @@ final class _HomePageState extends State with WidgetsBindingObserver { Positioned( top: headerTop, right: theme.style.pagePadding.right, - child: SizedBox.square( - dimension: headerIconSize, - child: IconButton( - tooltip: l10n.settingsTitle, - padding: EdgeInsets.zero, - iconSize: 20, - icon: const Icon(Icons.settings_outlined), - onPressed: () => Navigator.of(context).push( - MaterialPageRoute( - builder: (_) => SettingsPage(onLogout: widget.onLogout), - ), + child: AppIconButton( + label: l10n.settingsTitle, + size: headerIconSize, + icon: FLucideIcons.settings, + onPress: () => Navigator.of(context).push( + AppPageRoute( + context: context, + builder: (_) => SettingsPage(onLogout: widget.onLogout), ), ), ), diff --git a/lib/pages/login_page.dart b/lib/pages/login_page.dart index de892bd..08a4850 100644 --- a/lib/pages/login_page.dart +++ b/lib/pages/login_page.dart @@ -1,6 +1,8 @@ import 'package:flutter/widgets.dart'; import 'package:flutter/services.dart' show TextInputAction; import 'package:forui/forui.dart'; + +import '../widgets/app_page_scaffold.dart'; import 'package:thulium/l10n/generated/app_localizations.dart'; import 'package:thulium_auth/thulium_auth.dart'; @@ -278,10 +280,12 @@ final class _LoginPageState extends State { Widget build(BuildContext context) { final l10n = AppLocalizations.of(context)!; - return FScaffold( + return AppPageScaffold( + title: l10n.loginTitle, + maxWidth: 480, child: SafeArea( child: SingleChildScrollView( - padding: const EdgeInsets.all(24), + padding: const EdgeInsets.symmetric(vertical: 16), child: Center( child: ConstrainedBox( constraints: const BoxConstraints(maxWidth: 480), @@ -290,21 +294,6 @@ final class _LoginPageState extends State { child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Align( - alignment: Alignment.centerLeft, - child: FButton.icon( - semanticsLabel: l10n.backAction, - variant: FButtonVariant.ghost, - onPress: () => Navigator.of(context).pop(), - child: context.theme.icons.arrowLeft( - context, - semanticsLabel: l10n.backAction, - ), - ), - ), - const SizedBox(height: 32), - Text(l10n.loginTitle, style: context.theme.typography.xl2), - const SizedBox(height: 32), FTextFormField( control: FTextFieldControl.managed( controller: _studentIdController, diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 2f46c0e..784d5b2 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -1,5 +1,7 @@ -import 'package:flutter/material.dart'; +import 'package:flutter/widgets.dart'; import 'package:forui/forui.dart'; + +import '../widgets/app_page_scaffold.dart'; import 'package:thulium/l10n/generated/app_localizations.dart'; /// Contains account and application settings for the authenticated user. @@ -41,50 +43,28 @@ final class _SettingsPageState extends State { Widget build(BuildContext context) { final l10n = AppLocalizations.of(context)!; - return FScaffold( - child: SafeArea( - child: Center( - child: ConstrainedBox( - constraints: const BoxConstraints(maxWidth: 640), - child: Padding( - padding: const EdgeInsets.all(24), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - Align( - alignment: Alignment.centerLeft, - child: IconButton( - tooltip: l10n.backAction, - icon: const Icon(Icons.arrow_back), - onPressed: () => Navigator.of(context).pop(), - ), - ), - const SizedBox(height: 24), - Text(l10n.settingsTitle, style: context.theme.typography.xl2), - const SizedBox(height: 24), - FButton( - variant: FButtonVariant.destructive, - onPress: _isLoggingOut ? null : _logout, - child: _isLoggingOut - ? const FCircularProgress( - size: FCircularProgressSizeVariant.sm, - ) - : Text(l10n.logoutAction), - ), - if (_logoutFailed) ...[ - const SizedBox(height: 12), - Text( - l10n.logoutError, - style: context.theme.typography.sm.copyWith( - color: context.theme.colors.error, - ), - ), - ], - ], + return AppPageScaffold( + title: l10n.settingsTitle, + maxWidth: 560, + child: ListView( + children: [ + FButton( + variant: FButtonVariant.destructive, + onPress: _isLoggingOut ? null : _logout, + child: _isLoggingOut + ? const FCircularProgress(size: FCircularProgressSizeVariant.sm) + : Text(l10n.logoutAction), + ), + if (_logoutFailed) ...[ + SizedBox(height: context.theme.style.pagePadding.top), + Text( + l10n.logoutError, + style: context.theme.typography.sm.copyWith( + color: context.theme.colors.error, ), ), - ), - ), + ], + ], ), ); } diff --git a/lib/pages/study_page.dart b/lib/pages/study_page.dart index a4b1bf6..bb17ee6 100644 --- a/lib/pages/study_page.dart +++ b/lib/pages/study_page.dart @@ -4,8 +4,9 @@ import 'package:thulium/l10n/generated/app_localizations.dart'; import 'package:thulium_campus/thulium_campus.dart'; import '../widgets/flat_tile_style.dart'; +import '../widgets/app_icon_button.dart'; -/// Keeps room for future study shortcuts above the Learn course list. +/// Semester courses and their current assignment counts. final class StudyPage extends StatelessWidget { const StudyPage({ required this.semester, @@ -47,24 +48,6 @@ final class StudyPage extends StatelessWidget { return ListView( padding: const EdgeInsets.fromLTRB(16, 12, 16, 24), children: [ - Text(l10n.studyToolsTitle, style: context.theme.typography.lg), - const SizedBox(height: 10), - Container( - key: const ValueKey('study-shortcut-reserved'), - height: 92, - alignment: Alignment.center, - decoration: BoxDecoration( - border: Border.all(color: colors.border), - borderRadius: BorderRadius.circular(12), - ), - child: Text( - l10n.studyToolsPlaceholder, - style: context.theme.typography.sm.copyWith( - color: colors.mutedForeground, - ), - ), - ), - const SizedBox(height: 24), Row( children: [ Expanded( @@ -77,13 +60,10 @@ final class StudyPage extends StatelessWidget { const FCircularProgress(size: FCircularProgressSizeVariant.xs), const SizedBox(width: 8), ], - Tooltip( - message: l10n.studyRefresh, - child: FButton.icon( - variant: FButtonVariant.ghost, - onPress: isLoading || homeworkLoading ? null : onRefresh, - child: const Icon(Icons.refresh), - ), + AppIconButton( + label: l10n.studyRefresh, + icon: FLucideIcons.refreshCw, + onPress: isLoading || homeworkLoading ? null : onRefresh, ), ], ), @@ -135,7 +115,9 @@ final class StudyPage extends StatelessWidget { key: ValueKey('study-course-${course.id}'), style: flatTileStyle(theme), child: Padding( - padding: theme.style.pagePadding, + padding: EdgeInsets.symmetric( + vertical: theme.style.pagePadding.top, + ), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ diff --git a/lib/pages/welcome_page.dart b/lib/pages/welcome_page.dart index 125d6b1..4de0c84 100644 --- a/lib/pages/welcome_page.dart +++ b/lib/pages/welcome_page.dart @@ -1,8 +1,11 @@ import 'package:flutter/material.dart'; import 'package:forui/forui.dart'; + +import '../navigation/app_page_route.dart'; import 'package:thulium/l10n/generated/app_localizations.dart'; import '../widgets/language_button.dart'; +import '../widgets/app_icon_button.dart'; import 'login_page.dart'; /// The unauthenticated landing page shown before the student signs in. @@ -48,7 +51,8 @@ final class WelcomePage extends StatelessWidget { FButton( onPress: () { Navigator.of(context).push( - MaterialPageRoute( + AppPageRoute( + context: context, builder: (_) => LoginPage( onLoginSuccess: () { Navigator.of(context).pop(); @@ -72,14 +76,12 @@ final class WelcomePage extends StatelessWidget { mainAxisSize: MainAxisSize.min, children: [ LanguageButton(onSelected: onLocaleSelected), - IconButton( - tooltip: l10n.theme, - icon: Icon( - Theme.of(context).brightness == Brightness.dark - ? Icons.light_mode_outlined - : Icons.dark_mode_outlined, - ), - onPressed: onThemeToggle, + AppIconButton( + label: l10n.theme, + icon: Theme.of(context).brightness == Brightness.dark + ? FLucideIcons.sun + : FLucideIcons.moon, + onPress: onThemeToggle, ), ], ), diff --git a/lib/widgets/app_icon_button.dart b/lib/widgets/app_icon_button.dart new file mode 100644 index 0000000..f2fa2ed --- /dev/null +++ b/lib/widgets/app_icon_button.dart @@ -0,0 +1,31 @@ +import 'package:flutter/widgets.dart'; +import 'package:forui/forui.dart'; + +/// A quiet Forui action with a consistent target, tooltip, and accessible name. +class AppIconButton extends StatelessWidget { + const AppIconButton({ + required this.label, + required this.icon, + required this.onPress, + this.size, + super.key, + }); + final String label; + final IconData icon; + final VoidCallback? onPress; + final double? size; + + @override + Widget build(BuildContext context) => SizedBox.square( + dimension: size ?? context.theme.style.sizes.tile, + child: FTooltip( + tipBuilder: (_, _) => Text(label), + child: FButton.icon( + variant: FButtonVariant.ghost, + semanticsLabel: label, + onPress: onPress, + child: Icon(icon, size: 20), + ), + ), + ); +} diff --git a/lib/widgets/app_page_scaffold.dart b/lib/widgets/app_page_scaffold.dart new file mode 100644 index 0000000..1a7f572 --- /dev/null +++ b/lib/widgets/app_page_scaffold.dart @@ -0,0 +1,57 @@ +import 'package:flutter/widgets.dart'; +import 'package:forui/forui.dart'; + +import '../l10n/generated/app_localizations.dart'; + +/// Stable chrome and a shared reading width across nested pages. +class AppPageScaffold extends StatelessWidget { + const AppPageScaffold({ + required this.title, + required this.child, + this.actions = const [], + this.fullBleed = false, + this.maxWidth = 720, + super.key, + }); + + final String title; + final Widget child; + final List actions; + final bool fullBleed; + final double maxWidth; + + @override + Widget build(BuildContext context) { + final theme = context.theme; + return ColoredBox( + color: theme.colors.background, + child: FScaffold( + childPad: false, + header: FHeader.nested( + title: Text(title, maxLines: 2, overflow: TextOverflow.ellipsis), + prefixes: [ + FButton.icon( + variant: FButtonVariant.ghost, + semanticsLabel: AppLocalizations.of(context)!.backAction, + onPress: () => Navigator.of(context).pop(), + child: const Icon(FLucideIcons.arrowLeft), + ), + ], + suffixes: actions, + ), + child: fullBleed + ? child + : Align( + alignment: Alignment.topCenter, + child: ConstrainedBox( + constraints: BoxConstraints(maxWidth: maxWidth), + child: Padding( + padding: theme.style.pagePadding, + child: child, + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/course_content_loading.dart b/lib/widgets/course_content_loading.dart new file mode 100644 index 0000000..4fd8a20 --- /dev/null +++ b/lib/widgets/course_content_loading.dart @@ -0,0 +1,59 @@ +import 'package:flutter/widgets.dart'; +import 'package:forui/forui.dart'; + +import '../l10n/generated/app_localizations.dart'; + +/// Loading keeps the same page surface and approximate content geometry. +class CourseContentLoading extends StatelessWidget { + const CourseContentLoading({this.document = false, super.key}); + final bool document; + + @override + Widget build(BuildContext context) { + final theme = context.theme; + if (document) { + return Semantics( + label: AppLocalizations.of(context)!.coursePreviewLoading, + child: Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(FLucideIcons.fileText, color: theme.colors.mutedForeground), + SizedBox(height: theme.style.pagePadding.top), + const FCircularProgress(size: FCircularProgressSizeVariant.sm), + ], + ), + ), + ); + } + return Semantics( + label: AppLocalizations.of(context)!.courseContentLoading, + child: ExcludeSemantics( + child: ListView.separated( + itemCount: 5, + separatorBuilder: (_, _) => Container( + height: theme.style.borderWidth, + color: theme.colors.border, + ), + itemBuilder: (_, index) => Padding( + padding: theme.style.pagePadding, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + FractionallySizedBox( + widthFactor: index.isEven ? 0.65 : 0.45, + child: Container(height: 14, color: theme.colors.muted), + ), + const SizedBox(height: 10), + FractionallySizedBox( + widthFactor: 0.3, + child: Container(height: 10, color: theme.colors.muted), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/course_document_preview.dart b/lib/widgets/course_document_preview.dart index fad5b3a..afc2985 100644 --- a/lib/widgets/course_document_preview.dart +++ b/lib/widgets/course_document_preview.dart @@ -6,6 +6,7 @@ import 'package:forui/forui.dart'; import 'package:pdfx/pdfx.dart'; import '../l10n/generated/app_localizations.dart'; +import 'course_content_loading.dart'; /// Owns the native document controller for the lifetime of one preview route. class CourseDocumentPreview extends StatefulWidget { @@ -78,21 +79,28 @@ class _CourseDocumentPreviewState extends State { if (mounted) setState(() => _page = page); }, builders: PdfViewBuilders( - options: const DefaultBuilderOptions(), + options: DefaultBuilderOptions( + loaderSwitchDuration: MediaQuery.disableAnimationsOf(context) + ? Duration.zero + : const Duration(milliseconds: 160), + ), documentLoaderBuilder: (_) => - const Center(child: FCircularProgress()), + const CourseContentLoading(document: true), pageLoaderBuilder: (_) => - const Center(child: FCircularProgress()), + const CourseContentLoading(document: true), errorBuilder: (context, error) => Center(child: Text(l10n.coursePreviewError)), ), ), ), - if (_pages != null) - Padding( - padding: context.theme.style.pagePadding, - child: Text('$_page / $_pages', style: context.theme.typography.xs), + SizedBox( + height: context.theme.style.sizes.tile, + child: Center( + child: _pages == null + ? const SizedBox.shrink() + : Text('$_page / $_pages', style: context.theme.typography.xs), ), + ), ], ); } diff --git a/lib/widgets/flat_tile_style.dart b/lib/widgets/flat_tile_style.dart index b329ee1..df1ff37 100644 --- a/lib/widgets/flat_tile_style.dart +++ b/lib/widgets/flat_tile_style.dart @@ -6,13 +6,18 @@ const flatTileGroupStyle = FTileGroupStyleDelta.delta( decoration: DecorationDelta.value(BoxDecoration()), ); -/// Flat resting surface; interaction feedback continues to use Forui variants. +/// Navigation rows stay on the page surface, including while pressed/hovered. +/// Forui's keyboard focus outline is retained independently of the background. FItemStyleDelta flatTileStyle( FThemeData theme, { - bool highlightOnInteraction = true, + bool highlightOnInteraction = false, }) => FItemStyleDelta.delta( + padding: const EdgeInsetsGeometryDelta.value(EdgeInsets.zero), + rawContentStyle: const FRawItemContentStyleDelta.delta( + padding: EdgeInsetsGeometryDelta.value(EdgeInsets.zero), + ), backgroundColor: FVariantsValueDelta.delta([ - FVariantValueDeltaOperation.base(theme.colors.background), + FVariantValueDeltaOperation.all(theme.colors.background), ]), contentDecoration: FVariantsDelta.delta([ if (highlightOnInteraction) diff --git a/lib/widgets/homework_overview_card.dart b/lib/widgets/homework_overview_card.dart index 75c3e3c..a6233f7 100644 --- a/lib/widgets/homework_overview_card.dart +++ b/lib/widgets/homework_overview_card.dart @@ -11,6 +11,8 @@ import '../homework/homework_urgency.dart'; import '../homework/homework_theme.dart'; import 'scrolling_badge.dart'; import 'flat_tile_style.dart'; +import '../navigation/app_page_route.dart'; +import 'app_page_scaffold.dart'; import '../l10n/generated/app_localizations.dart'; /// Presentation of the existing snapshot. No network, cache, or submission @@ -259,27 +261,18 @@ final class _HomeworkOverviewCardState extends State LearnHomework homework, ) async { await Navigator.of(context).push( - PageRouteBuilder( - pageBuilder: (context, _, _) { + AppPageRoute( + context: context, + builder: (context) { final l10n = AppLocalizations.of(context)!; final theme = context.theme; - return FScaffold( - header: FHeader.nested( - title: Text(l10n.homeworkDetails), - prefixes: [ - FButton.icon( - size: FButtonSizeVariant.lg, - variant: FButtonVariant.ghost, - semanticsLabel: l10n.homeworkBack, - onPress: () => Navigator.of(context).pop(), - child: const Icon(FLucideIcons.arrowLeft), - ), - ], - ), + return AppPageScaffold( + title: l10n.homeworkDetails, child: ListView( padding: theme.style.pagePadding, children: [ FTileGroup( + style: flatTileGroupStyle, intrinsicWidth: false, physics: const NeverScrollableScrollPhysics(), children: [ diff --git a/lib/widgets/language_button.dart b/lib/widgets/language_button.dart index de2837d..75b7aa9 100644 --- a/lib/widgets/language_button.dart +++ b/lib/widgets/language_button.dart @@ -1,42 +1,49 @@ -import 'package:flutter/material.dart'; -import 'package:thulium/l10n/generated/app_localizations.dart'; +import 'package:flutter/widgets.dart'; +import 'package:forui/forui.dart'; -/// Displays the supported locales using their native names. +import '../l10n/generated/app_localizations.dart'; + +/// Displays recognizable language autonyms in the shared Forui menu surface. final class LanguageButton extends StatelessWidget { const LanguageButton({required this.onSelected, this.buttonSize, super.key}); - final ValueChanged onSelected; final double? buttonSize; @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context)!; - // Language options use autonyms rather than translated names. This keeps - // every language recognizable even when the current interface language is - // unfamiliar to the user. - final button = PopupMenuButton( - tooltip: l10n.language, - icon: const Icon(Icons.language_outlined), - iconSize: buttonSize == null ? null : 20, - padding: buttonSize == null ? const EdgeInsets.all(8) : EdgeInsets.zero, - onSelected: onSelected, - itemBuilder: (context) => [ - PopupMenuItem( - value: const Locale('en'), - child: Text(l10n.englishLanguage), - ), - PopupMenuItem( - value: const Locale('zh', 'CN'), - child: Text(l10n.simplifiedChineseLanguage), - ), - PopupMenuItem( - value: const Locale('zh', 'TW'), - child: Text(l10n.traditionalChineseLanguage), + final languages = [ + (const Locale('en'), l10n.englishLanguage), + (const Locale('zh', 'CN'), l10n.simplifiedChineseLanguage), + (const Locale('zh', 'TW'), l10n.traditionalChineseLanguage), + ]; + return SizedBox.square( + dimension: buttonSize ?? context.theme.style.sizes.tile, + child: FPopoverMenu.tiles( + menuAnchor: Alignment.topLeft, + childAnchor: Alignment.bottomLeft, + menuBuilder: (context, controller, _) => [ + FTileGroup( + children: [ + for (final (locale, label) in languages) + FTile( + title: Text(label), + selected: Localizations.localeOf(context) == locale, + onPress: () async { + await controller.hide(); + onSelected(locale); + }, + ), + ], + ), + ], + builder: (context, controller, _) => FButton.icon( + variant: FButtonVariant.ghost, + semanticsLabel: l10n.language, + onPress: controller.toggle, + child: const Icon(FLucideIcons.languages, size: 20), ), - ], + ), ); - return buttonSize == null - ? button - : SizedBox.square(dimension: buttonSize, child: button); } } diff --git a/test/widget/app/widget_test.dart b/test/widget/app/widget_test.dart index 40151bb..d76b11f 100644 --- a/test/widget/app/widget_test.dart +++ b/test/widget/app/widget_test.dart @@ -66,10 +66,7 @@ void main() { await tester.pumpAndSettle(); expect(find.byType(StudyPage), findsOneWidget); - expect( - find.byKey(const ValueKey('study-shortcut-reserved')), - findsOneWidget, - ); + expect(find.byKey(const ValueKey('study-shortcut-reserved')), findsNothing); }); testWidgets('opens settings from the authenticated home', (tester) async { @@ -78,7 +75,7 @@ void main() { await tester.pumpWidget(ThuliumApp(sessionStore: store)); await tester.pumpAndSettle(); - await tester.tap(find.byTooltip('Settings')); + await tester.tap(find.bySemanticsLabel('Settings')); await tester.pumpAndSettle(); expect(find.text('Settings'), findsOneWidget); @@ -99,11 +96,11 @@ void main() { Size.square(FThemes.neutral.light.touch.style.sizes.tile), ); expect( - tester.getSize(find.byTooltip('Theme')), + tester.getSize(find.bySemanticsLabel('Theme')), Size.square(FThemes.neutral.light.touch.style.sizes.tile), ); expect( - tester.getSize(find.byTooltip('Settings')), + tester.getSize(find.bySemanticsLabel('Settings')), Size.square(FThemes.neutral.light.touch.style.sizes.tile), ); diff --git a/test/widget/calendar/calendar_export_dialog_test.dart b/test/widget/calendar/calendar_export_dialog_test.dart index c00db03..b4ce897 100644 --- a/test/widget/calendar/calendar_export_dialog_test.dart +++ b/test/widget/calendar/calendar_export_dialog_test.dart @@ -39,7 +39,7 @@ void main() { await tester.pumpAndSettle(); await tester.tap(find.text('Image (.png)').last); await tester.pumpAndSettle(); - expect(find.text('PNG exports the current week only.'), findsOneWidget); + expect(find.text('PNG exports the current week only'), findsOneWidget); await tester.tap(find.text('Export').last); await tester.pumpAndSettle(); expect(selection?.format, CalendarExportFormat.png); diff --git a/test/widget/homework/homework_cache_test.dart b/test/widget/homework/homework_cache_test.dart index c886832..a2d0400 100644 --- a/test/widget/homework/homework_cache_test.dart +++ b/test/widget/homework/homework_cache_test.dart @@ -85,11 +85,11 @@ void main() { await mount('student'); expect(find.text('Saved assignment'), findsOneWidget); expect( - find.text('Could not update assignments; showing saved data.'), + find.text('Could not update assignments; showing saved data'), findsOneWidget, ); expect( - find.text('Could not load assignments. Try refreshing.'), + find.text('Could not load assignments. Try refreshing'), findsNothing, ); expect(tester.takeException(), isNull); @@ -102,7 +102,7 @@ void main() { await mount('other-student'); expect(find.text('Saved assignment'), findsNothing); expect( - find.text('Could not load assignments. Try refreshing.'), + find.text('Could not load assignments. Try refreshing'), findsOneWidget, ); expect(tester.takeException(), isNull); diff --git a/test/widget/homework/homework_overview_card_test.dart b/test/widget/homework/homework_overview_card_test.dart index 1df9ebb..21f7b00 100644 --- a/test/widget/homework/homework_overview_card_test.dart +++ b/test/widget/homework/homework_overview_card_test.dart @@ -84,7 +84,7 @@ void main() { expect(find.text('Not graded'), findsOneWidget); expect(find.text('Updated 7 minutes ago'), findsOneWidget); expect( - find.text('All deadlines use Beijing time (UTC+8).'), + find.text('All deadlines use Beijing time (UTC+8)'), findsNothing, ); expect(find.textContaining('Beijing time'), findsNothing); diff --git a/test/widget/study/course_detail_page_test.dart b/test/widget/study/course_detail_page_test.dart index f401a20..672cdbe 100644 --- a/test/widget/study/course_detail_page_test.dart +++ b/test/widget/study/course_detail_page_test.dart @@ -1,8 +1,17 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:ui' as ui; + import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:forui/forui.dart'; import 'package:thulium/l10n/generated/app_localizations.dart'; import 'package:thulium/pages/course_detail_page.dart'; +import 'package:thulium/pages/study_page.dart'; +import 'package:thulium/navigation/app_page_route.dart'; +import 'package:thulium/widgets/app_page_scaffold.dart'; import 'package:thulium/study/course_content_source.dart'; import 'package:thulium_auth/thulium_auth.dart'; import 'package:thulium_campus/thulium_campus.dart'; @@ -27,12 +36,15 @@ class FakeContent extends CourseContentSource { ); bool fail = false; int documentRequests = 0; + int fileLimit = 1; + Completer? pendingMaterials; @override Future materials(LearnCourse course) async { if (fail) throw const PortalSessionRejected(); + if (pendingMaterials != null) return pendingMaterials!.future; return LearnCourseMaterials( course: course, - requestedLimit: 1, + requestedLimit: fileLimit, materials: [ LearnMaterial.fromResponse({ 'kjxxid': 'material', @@ -72,8 +84,18 @@ void main() { WidgetTester tester, FakeContent source, { VoidCallback? expired, + bool dark = true, + bool reducedMotion = false, + bool study = false, }) async { - final theme = FThemes.neutral.dark.touch; + var theme = dark ? FThemes.neutral.dark.touch : FThemes.neutral.light.touch; + if (Platform.environment.containsKey('THULIUM_UI_CAPTURE_DIR')) { + theme = FThemeData( + colors: theme.colors, + touch: true, + typography: FTypography(fontFamily: 'UiReview'), + ); + } await tester.pumpWidget( MaterialApp( locale: const Locale('en'), @@ -83,17 +105,148 @@ void main() { ], supportedLocales: AppLocalizations.supportedLocales, theme: theme.toApproximateMaterialTheme(), - builder: (_, child) => FTheme(data: theme, child: child!), - home: CourseDetailPage( - course: course, - source: source, - onSessionExpired: expired ?? () {}, + builder: (context, child) => RepaintBoundary( + key: const ValueKey('ui-review'), + child: MediaQuery( + data: MediaQuery.of( + context, + ).copyWith(disableAnimations: reducedMotion), + child: FTheme(data: theme, child: child!), + ), ), + home: study + ? Builder( + builder: (context) => FScaffold( + child: StudyPage( + semester: source.catalog.semester, + catalog: source.catalog, + isLoading: false, + isStale: false, + error: null, + onRefresh: () {}, + onCourseSelected: (course) => Navigator.of(context).push( + AppPageRoute( + context: context, + builder: (_) => CourseDetailPage( + course: course, + source: source, + onSessionExpired: expired ?? () {}, + ), + ), + ), + ), + ), + ) + : CourseDetailPage( + course: course, + source: source, + onSessionExpired: expired ?? () {}, + ), ), ); await tester.pumpAndSettle(); } + Future snapshot(WidgetTester tester) async { + final boundary = tester.renderObject( + find.byKey(const ValueKey('ui-review')), + ); + return tester + .runAsync(() => boundary.toImage(pixelRatio: 1)) + .then((image) => image!); + } + + Future backgroundPixel(WidgetTester tester, Offset point) async { + final image = await snapshot(tester); + final bytes = await tester.runAsync( + () => image.toByteData(format: ui.ImageByteFormat.rawRgba), + ); + final offset = (point.dy.floor() * image.width + point.dx.floor()) * 4; + final pixel = bytes!.getUint32(offset); + image.dispose(); + return pixel; + } + + testWidgets('course actions stay flat while pressed in both themes', ( + tester, + ) async { + for (final dark in [false, true]) { + await show(tester, FakeContent(), dark: dark); + expect(find.text('Unsubmitted, submitted and graded'), findsNothing); + for (final title in ['Course files', 'Course assignments']) { + final tile = find.ancestor( + of: find.text(title), + matching: find.byType(FTile), + ); + final rect = tester.getRect(tile); + final point = Offset(rect.right - 12, rect.center.dy); + final before = await backgroundPixel(tester, point); + final gesture = await tester.startGesture(tester.getCenter(tile)); + await tester.pump(const Duration(milliseconds: 120)); + expect(await backgroundPixel(tester, point), before); + await gesture.cancel(); + await tester.pumpAndSettle(); + } + } + }); + + testWidgets( + 'My courses keeps its background on press and opens a shared route', + (tester) async { + await show(tester, FakeContent(), study: true); + final tile = find.byKey(const ValueKey('study-course-physics')); + final rect = tester.getRect(tile); + final point = Offset(rect.right - 12, rect.center.dy); + final before = await backgroundPixel(tester, point); + final gesture = await tester.startGesture(tester.getCenter(tile)); + await tester.pump(const Duration(milliseconds: 120)); + expect(await backgroundPixel(tester, point), before); + await gesture.cancel(); + await tester.pumpAndSettle(); + await tester.tap(find.text('Physics')); + await tester.pumpAndSettle(); + expect(find.text('Course files'), findsOneWidget); + final route = ModalRoute.of(tester.element(find.text('Course files')))!; + expect(route, isA>()); + expect(route.transitionDuration, const Duration(milliseconds: 200)); + }, + ); + + testWidgets( + 'refresh keeps file rows visible while the next request is pending', + (tester) async { + final source = FakeContent(); + await show(tester, source); + await tester.tap(find.text('Course files')); + await tester.pumpAndSettle(); + source.pendingMaterials = Completer(); + await tester.tap(find.bySemanticsLabel('Refresh courses')); + await tester.pump(); + expect(find.text('Lecture.docx'), findsOneWidget); + source.pendingMaterials!.completeError(const FormatException('offline')); + await tester.pumpAndSettle(); + expect(find.text('Lecture.docx'), findsOneWidget); + expect( + find.textContaining('Could not load course content'), + findsOneWidget, + ); + }, + ); + + testWidgets( + 'nested course routes honor reduced motion and use shared chrome', + (tester) async { + await show(tester, FakeContent(), reducedMotion: true); + await tester.tap(find.text('Course files')); + await tester.pumpAndSettle(); + final context = tester.element(find.text('Lecture.docx')); + final route = ModalRoute.of(context)! as AppPageRoute; + expect(route.transitionDuration, Duration.zero); + expect(route.reverseTransitionDuration, Duration.zero); + expect(find.byType(AppPageScaffold), findsOneWidget); + }, + ); + testWidgets('files open preview and conversion failures offer retry', ( tester, ) async { @@ -133,8 +286,79 @@ void main() { await tester.tap(find.text('Course files')); await tester.pumpAndSettle(); expect(find.textContaining('Your session has expired.'), findsOneWidget); - await tester.tap(find.text('Sign in to Thulium')); + await tester.tap(find.text('Sign in')); await tester.pumpAndSettle(); expect(expired, isTrue); }); + if (Platform.environment.containsKey('THULIUM_UI_CAPTURE_DIR')) { + testWidgets('capture course flow for visual review', (tester) async { + tester.view.physicalSize = const Size(390, 844); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final font = File( + Platform.environment['THULIUM_UI_REVIEW_FONT']!, + ).readAsBytesSync(); + await tester.runAsync( + () => (FontLoader( + 'UiReview', + )..addFont(Future.value(ByteData.sublistView(font)))).load(), + ); + final icons = await rootBundle.load( + 'packages/forui_assets/assets/lucide.ttf', + ); + await tester.runAsync( + () => (FontLoader( + 'packages/forui_assets/ForuiLucideIcons', + )..addFont(Future.value(icons))).load(), + ); + final output = Directory(Platform.environment['THULIUM_UI_CAPTURE_DIR']!); + output.createSync(recursive: true); + Future capture(String name) async { + final image = await snapshot(tester); + final data = await tester.runAsync( + () => image.toByteData(format: ui.ImageByteFormat.png), + ); + File( + '${output.path}/$name.png', + ).writeAsBytesSync(data!.buffer.asUint8List()); + image.dispose(); + } + + for (final dark in [false, true]) { + final source = FakeContent(); + source.fileLimit = 200; + final mode = dark ? 'dark' : 'light'; + await show(tester, source, dark: dark, study: true); + await capture('$mode-study'); + await tester.tap(find.text('Physics')); + await tester.pumpAndSettle(); + await capture('$mode-course'); + await tester.tap(find.text('Course files')); + await tester.pumpAndSettle(); + await capture('$mode-files'); + await tester.tap(find.bySemanticsLabel('Back')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Course assignments')); + await tester.pumpAndSettle(); + await capture('$mode-assignments'); + await tester.tap(find.bySemanticsLabel('Back')); + await tester.pumpAndSettle(); + source.pendingMaterials = Completer(); + await tester.tap(find.text('Course files')); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 250)); + await capture('$mode-loading'); + source.pendingMaterials!.completeError( + const FormatException('offline'), + ); + await tester.pumpAndSettle(); + await capture('$mode-error'); + await tester.tap(find.bySemanticsLabel('Back')); + await tester.pumpAndSettle(); + await tester.tap(find.bySemanticsLabel('Back')); + await tester.pumpAndSettle(); + } + }); + } } diff --git a/test/widget/study/study_page_test.dart b/test/widget/study/study_page_test.dart index a8a205f..f819e50 100644 --- a/test/widget/study/study_page_test.dart +++ b/test/widget/study/study_page_test.dart @@ -83,68 +83,69 @@ void main() { await show({'physics': 12}, failed: true); expect(find.byType(FBadge), findsNothing); expect( - find.text('Could not load assignment counts. Try refreshing.'), + find.text('Could not load assignment counts. Try refreshing'), findsOneWidget, ); expect(title, findsOneWidget); }); - testWidgets('reserves shortcut space and displays localized course titles', ( - tester, - ) async { - final catalog = LearnCourseCatalog( - userId: 'student', - semester: '2026-2027-1', - courses: [ - const LearnCourse( - id: 'course-1', - name: '大学物理', - englishName: 'University Physics', - teacherName: 'Teacher', - schedule: 'Monday, Room 101', - ), - ], - ); - - Future show(Locale locale) async { - await tester.pumpWidget( - MaterialApp( - locale: locale, - localizationsDelegates: [ - ...AppLocalizations.localizationsDelegates, - ...FLocalizations.localizationsDelegates, - ], - supportedLocales: AppLocalizations.supportedLocales, - builder: (context, child) => FTheme( - data: FThemes.neutral.light.touch, - child: child ?? const SizedBox.shrink(), + testWidgets( + 'displays localized course titles without a reserved tools card', + (tester) async { + final catalog = LearnCourseCatalog( + userId: 'student', + semester: '2026-2027-1', + courses: [ + const LearnCourse( + id: 'course-1', + name: '大学物理', + englishName: 'University Physics', + teacherName: 'Teacher', + schedule: 'Monday, Room 101', ), - home: Scaffold( - body: StudyPage( - semester: catalog.semester, - catalog: catalog, - isLoading: false, - isStale: false, - error: null, - onRefresh: () {}, + ], + ); + + Future show(Locale locale) async { + await tester.pumpWidget( + MaterialApp( + locale: locale, + localizationsDelegates: [ + ...AppLocalizations.localizationsDelegates, + ...FLocalizations.localizationsDelegates, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => FTheme( + data: FThemes.neutral.light.touch, + child: child ?? const SizedBox.shrink(), + ), + home: Scaffold( + body: StudyPage( + semester: catalog.semester, + catalog: catalog, + isLoading: false, + isStale: false, + error: null, + onRefresh: () {}, + ), ), ), - ), - ); - await tester.pumpAndSettle(); - } + ); + await tester.pumpAndSettle(); + } - await show(const Locale('en')); - expect( - find.byKey(const ValueKey('study-shortcut-reserved')), - findsOneWidget, - ); - expect(find.text('My courses'), findsOneWidget); - expect(find.text('University Physics'), findsOneWidget); + await show(const Locale('en')); + expect( + find.byKey(const ValueKey('study-shortcut-reserved')), + findsNothing, + ); + expect(find.text('My courses'), findsOneWidget); + expect(find.text('University Physics'), findsOneWidget); - await show(const Locale('zh', 'CN')); - expect(find.text('我的课程'), findsOneWidget); - expect(find.text('大学物理'), findsOneWidget); - expect(find.text('University Physics'), findsNothing); - }); + await show(const Locale('zh', 'CN')); + expect(find.text('我的课程'), findsOneWidget); + expect(find.text('大学物理'), findsOneWidget); + expect(find.text('University Physics'), findsNothing); + }, + ); } From 9230e755ed377d4c1e00e2236e36382eccbf4458 Mon Sep 17 00:00:00 2001 From: ashgrey Date: Tue, 17 Nov 2026 23:34:29 +0800 Subject: [PATCH 19/26] fix(auth): coordinate session recovery across app screens Serialize shared session operations to prevent stale cookie writes and duplicate logins. Retry authenticated requests with saved credentials while preserving trusted-device state, and coordinate explicit sign-in and sign-out with background requests. --- lib/app.dart | 10 +- lib/auth/secure_auth_session_store.dart | 9 +- lib/pages/calendar_page.dart | 110 +++---- lib/pages/home_page.dart | 120 +++----- lib/pages/login_page.dart | 12 +- lib/study/course_content_source.dart | 37 +-- packages/auth/README.md | 19 ++ packages/auth/lib/src/session_runner.dart | 82 ++++++ packages/auth/lib/thulium_auth.dart | 2 + packages/auth/test/session_runner_test.dart | 273 ++++++++++++++++++ .../auth/secure_auth_session_store_test.dart | 41 +++ 11 files changed, 525 insertions(+), 190 deletions(-) create mode 100644 packages/auth/lib/src/session_runner.dart create mode 100644 packages/auth/test/session_runner_test.dart create mode 100644 test/unit/auth/secure_auth_session_store_test.dart diff --git a/lib/app.dart b/lib/app.dart index 21594fc..a8aaa0e 100644 --- a/lib/app.dart +++ b/lib/app.dart @@ -55,17 +55,25 @@ final class _ThuliumAppState extends State { Future _logout() async { final sessionStore = widget.sessionStore ?? SecureAuthSessionStore(); + return AuthSessionRunner.exclusive( + sessionStore, + () => _logoutStoredSession(sessionStore), + ); + } + + Future _logoutStoredSession(AuthSessionStore sessionStore) async { try { // Restore the persisted cookies before calling logout so the identity // service can invalidate the active remote session as well. final client = TsinghuaAuthClient( sessionStore: sessionStore, + requestTimeout: const Duration(seconds: 8), credentialStore: sessionStore is AuthCredentialStore ? sessionStore as AuthCredentialStore : null, ); await client.restore(); - await client.logout().timeout(const Duration(seconds: 8)); + await client.logout(); } catch (error) { // Logout should still work offline: the auth client's finally block // clears local data, and this fallback covers failures during restore. diff --git a/lib/auth/secure_auth_session_store.dart b/lib/auth/secure_auth_session_store.dart index d09b9f9..41b7873 100644 --- a/lib/auth/secure_auth_session_store.dart +++ b/lib/auth/secure_auth_session_store.dart @@ -13,8 +13,13 @@ import 'package:thulium_auth/thulium_auth.dart'; /// Persists sessions and reusable credentials under distinct secure keys. final class SecureAuthSessionStore implements AuthSessionStore, AuthCredentialStore { - SecureAuthSessionStore({FlutterSecureStorage? storage}) - : _storage = storage ?? _createStorage(); + factory SecureAuthSessionStore({FlutterSecureStorage? storage}) => + storage == null ? _shared : SecureAuthSessionStore._(storage); + + SecureAuthSessionStore._(this._storage); + + // Every default app client must participate in the same authentication queue. + static final _shared = SecureAuthSessionStore._(_createStorage()); // A single stable key keeps the storage format independent from the // platform-specific secure-storage implementation. diff --git a/lib/pages/calendar_page.dart b/lib/pages/calendar_page.dart index 1d3d9b6..0797ef4 100644 --- a/lib/pages/calendar_page.dart +++ b/lib/pages/calendar_page.dart @@ -129,48 +129,40 @@ final class _AcademicCalendarPageState extends State try { final sessionStore = widget.sessionStore ?? SecureAuthSessionStore(); - final credentialStore = sessionStore is AuthCredentialStore - ? sessionStore as AuthCredentialStore - : null; - final client = TsinghuaAuthClient( - sessionStore: sessionStore, - credentialStore: credentialStore, - trace: (message) => debugPrint('[auth] $message'), - ); - final savedSession = await client.restore(); - if (savedSession == null) throw const CourseScheduleSessionExpired(); - final cache = widget.sessionStore == null - ? CourseScheduleCache(SecureCourseScheduleCacheStore()) - : null; - final service = CourseScheduleService( - client, - cache: cache, - trace: (message) => debugPrint('[calendar] $message'), - ); - CourseSchedule schedule; - try { - schedule = await service - .loadCurrentTerm(forceRefresh: forceRefresh) - .timeout(_LOAD_TIMEOUT); - } on CourseScheduleException catch (error) { - if (error.cause is! PortalCsrfUnavailable) rethrow; - // An empty WebVPN cookie response alone does not prove logout. Only - // after the bounded cookie/SSO recovery fails do we try one fresh - // password-based login, then repeat the calendar request once. - if (!await _reconnect(client, credentialStore, savedSession)) rethrow; - debugPrint('[calendar] reconnect succeeded; retrying once'); - schedule = await service - .loadCurrentTerm(forceRefresh: true) - .timeout(_LOAD_TIMEOUT); - } on CourseScheduleSessionExpired { - if (!await _reconnect(client, credentialStore, savedSession)) rethrow; - debugPrint('[calendar] reconnect succeeded; retrying once'); - schedule = await service - .loadCurrentTerm(forceRefresh: true) - .timeout(_LOAD_TIMEOUT); - } + CourseScheduleSource? source; + String? userId; + final schedule = + await AuthSessionRunner( + sessionStore, + trace: (message) => debugPrint('[auth] $message'), + ) + .run( + shouldReconnect: (error) => + error is CourseScheduleSessionExpired || + error is PortalSessionRejected || + error is PortalCsrfUnavailable || + (error is CourseScheduleException && + (error.cause is PortalCsrfUnavailable || + error.cause is PortalSessionRejected)), + request: (client, isRetry) async { + userId = client.session!.userId; + final service = CourseScheduleService( + client, + cache: widget.sessionStore == null + ? CourseScheduleCache(SecureCourseScheduleCacheStore()) + : null, + trace: (message) => debugPrint('[calendar] $message'), + ); + final schedule = await service.loadCurrentTerm( + forceRefresh: forceRefresh || isRetry, + ); + source = service.lastSource; + return schedule; + }, + ) + .timeout(_LOAD_TIMEOUT); if (!mounted) return; - final customPlans = await _customPlanStore.readFor(savedSession.userId); + final customPlans = await _customPlanStore.readFor(userId!); if (!mounted) return; debugPrint( '[calendar] loading completed occurrences=${schedule.occurrences.length}', @@ -182,9 +174,8 @@ final class _AcademicCalendarPageState extends State ? catalog.applyEnglishNames(schedule) : schedule; _customPlans = customPlans; - _userId = savedSession.userId; - _showingStaleCache = - service.lastSource == CourseScheduleSource.staleCache; + _userId = userId; + _showingStaleCache = source == CourseScheduleSource.staleCache; _selectedWeek = (_selectedWeek ?? todayWeek).clamp( 1, schedule.term.weekCount, @@ -208,37 +199,6 @@ final class _AcademicCalendarPageState extends State } } - Future _reconnect( - TsinghuaAuthClient client, - AuthCredentialStore? credentialStore, - AuthSession savedSession, - ) async { - final credentials = await credentialStore?.readCredentials(); - if (credentials == null || credentials.userId != savedSession.userId) { - debugPrint('[calendar] no matching saved credentials for reconnect'); - return false; - } - - debugPrint('[calendar] reconnecting with saved credentials'); - try { - await client - .login( - userId: savedSession.userId, - password: credentials.password, - fingerprint: savedSession.fingerprint, - ) - .timeout(_LOAD_TIMEOUT); - return true; - } catch (error) { - // A trusted device may not need a second factor; otherwise the regular - // sign-in screen can collect one. Do not print secrets from the error. - debugPrint( - '[calendar] credential reconnect failed type=${error.runtimeType}', - ); - rethrow; - } - } - void _changeWeek(int delta) { _weekPagerKey.currentState?.animateBy(delta); } diff --git a/lib/pages/home_page.dart b/lib/pages/home_page.dart index 85d2414..4408a78 100644 --- a/lib/pages/home_page.dart +++ b/lib/pages/home_page.dart @@ -118,49 +118,43 @@ final class _HomePageState extends State with WidgetsBindingObserver { }); try { final store = widget.sessionStore ?? SecureAuthSessionStore(); - final credentials = store is AuthCredentialStore - ? store as AuthCredentialStore - : null; - final client = TsinghuaAuthClient( - sessionStore: store, - credentialStore: credentials, - trace: (message) => debugPrint('[auth] $message'), - ); - final session = await client.restore(); - if (session == null) throw const PortalSessionRejected(); - await _restoreHomework(session.userId, semester, generation); - if (!mounted || generation != _courseRequestGeneration) return; - final service = LearnCourseCatalogService( - client, - cache: widget.sessionStore == null - ? LearnCourseCache(SecureLearnCourseCacheStore()) - : null, - ); - LearnCourseCatalog catalog; - try { - catalog = await service - .loadSemester(semester, forceRefresh: forceRefresh) - .timeout(_LOAD_TIMEOUT); - } on PortalCsrfUnavailable { - if (!await _reconnectCourses(client, credentials, session)) rethrow; - catalog = await service - .loadSemester(semester, forceRefresh: true) - .timeout(_LOAD_TIMEOUT); - } on PortalSessionRejected { - if (!await _reconnectCourses(client, credentials, session)) rethrow; - catalog = await service - .loadSemester(semester, forceRefresh: true) - .timeout(_LOAD_TIMEOUT); - } + LearnCourseSource? source; + final catalog = + await AuthSessionRunner( + store, + trace: (message) => debugPrint('[auth] $message'), + ) + .run( + request: (client, isRetry) async { + final session = client.session!; + await _restoreHomework(session.userId, semester, generation); + if (!mounted || generation != _courseRequestGeneration) { + throw StateError('Course refresh was superseded.'); + } + final service = LearnCourseCatalogService( + client, + cache: widget.sessionStore == null + ? LearnCourseCache(SecureLearnCourseCacheStore()) + : null, + ); + final catalog = await service.loadSemester( + semester, + forceRefresh: forceRefresh || isRetry, + ); + source = service.lastSource; + return catalog; + }, + ) + .timeout(_LOAD_TIMEOUT); if (!mounted || generation != _courseRequestGeneration) return; setState(() { _requiresSignIn = false; _courseCatalog = catalog; - _coursesStale = service.lastSource == LearnCourseSource.staleCache; + _coursesStale = source == LearnCourseSource.staleCache; _coursesLoading = false; _homeworkLoading = true; }); - await _loadHomework(client, credentials, session, catalog, generation); + await _loadHomework(store, catalog, generation); } on TwoFactorInteractionRequired catch (error) { if (mounted && generation == _courseRequestGeneration) { setState(() { @@ -219,30 +213,23 @@ final class _HomePageState extends State with WidgetsBindingObserver { } Future _loadHomework( - TsinghuaAuthClient client, - AuthCredentialStore? credentials, - AuthSession session, + AuthSessionStore store, LearnCourseCatalog catalog, int generation, ) async { try { - final service = LearnHomeworkService(client); - LearnHomeworkSnapshot snapshot; - try { - snapshot = await service - .fetchUnsubmittedHomework(catalog) - .timeout(_LOAD_TIMEOUT); - } on Object catch (error) { - if (error is! PortalCsrfUnavailable && - error is! PortalSessionRejected) { - rethrow; - } - if (!mounted || generation != _courseRequestGeneration) return; - if (!await _reconnectCourses(client, credentials, session)) rethrow; - snapshot = await service - .fetchUnsubmittedHomework(catalog) - .timeout(_LOAD_TIMEOUT); - } + final snapshot = + await AuthSessionRunner( + store, + trace: (message) => debugPrint('[auth] $message'), + ) + .run( + expectedUserId: catalog.userId, + request: (client, _) => LearnHomeworkService( + client, + ).fetchUnsubmittedHomework(catalog), + ) + .timeout(_LOAD_TIMEOUT); if (!mounted || generation != _courseRequestGeneration) return; final fetchedAt = DateTime.now(); setState(() { @@ -255,7 +242,7 @@ final class _HomePageState extends State with WidgetsBindingObserver { }); try { await _homeworkCache?.writeFor( - session.userId, + catalog.userId, catalog.semester, snapshot, fetchedAt, @@ -284,25 +271,6 @@ final class _HomePageState extends State with WidgetsBindingObserver { } } - Future _reconnectCourses( - TsinghuaAuthClient client, - AuthCredentialStore? store, - AuthSession session, - ) async { - final credentials = await store?.readCredentials(); - if (credentials == null || credentials.userId != session.userId) { - return false; - } - await client - .login( - userId: session.userId, - password: credentials.password, - fingerprint: session.fingerprint, - ) - .timeout(_LOAD_TIMEOUT); - return true; - } - @override Widget build(BuildContext context) { final l10n = AppLocalizations.of(context)!; diff --git a/lib/pages/login_page.dart b/lib/pages/login_page.dart index 08a4850..a0ad295 100644 --- a/lib/pages/login_page.dart +++ b/lib/pages/login_page.dart @@ -160,11 +160,13 @@ final class _LoginPageState extends State { }); try { - await _authClient.login( - userId: _studentIdController.text.trim(), - password: _passwordController.text, - fingerprint: await _sessionStore.getOrCreateFingerprint(), - ); + await AuthSessionRunner.exclusive(_sessionStore, () async { + await _authClient.login( + userId: _studentIdController.text.trim(), + password: _passwordController.text, + fingerprint: await _sessionStore.getOrCreateFingerprint(), + ); + }); if (mounted) widget.onLoginSuccess(); } catch (error) { // Do not expose server internals or distinguish which credential was diff --git a/lib/study/course_content_source.dart b/lib/study/course_content_source.dart index 354a777..a7c0eef 100644 --- a/lib/study/course_content_source.dart +++ b/lib/study/course_content_source.dart @@ -1,44 +1,19 @@ import 'package:thulium_auth/thulium_auth.dart'; import 'package:thulium_campus/thulium_campus.dart'; -/// Each request owns its authentication client so separate screens cannot race -/// session restoration. Authenticated document responses are never logged here. +/// Course requests share the app's authentication queue. Document responses +/// are not logged, and only typed session failures trigger credential recovery. class CourseContentSource { const CourseContentSource({required this.store, required this.catalog}); final AuthSessionStore store; final LearnCourseCatalog catalog; - Future _request( - Future Function(TsinghuaAuthClient) operation, - ) async { - final credentials = store is AuthCredentialStore - ? store as AuthCredentialStore - : null; - final client = TsinghuaAuthClient( - sessionStore: store, - credentialStore: credentials, - ); - final session = await client.restore(); - if (session == null || session.userId != catalog.userId) { - throw const PortalSessionRejected(); - } - try { - return await operation(client); - } on Object catch (error) { - if (error is! PortalSessionRejected && error is! PortalCsrfUnavailable) { - rethrow; - } - final saved = await credentials?.readCredentials(); - if (saved == null || saved.userId != session.userId) rethrow; - await client.login( - userId: session.userId, - password: saved.password, - fingerprint: session.fingerprint, + Future _request(Future Function(TsinghuaAuthClient) operation) => + AuthSessionRunner(store).run( + expectedUserId: catalog.userId, + request: (client, _) => operation(client), ); - return operation(client); - } - } LearnCourseCatalog _single(LearnCourse course) => LearnCourseCatalog( userId: catalog.userId, diff --git a/packages/auth/README.md b/packages/auth/README.md index 492e1e9..e338832 100644 --- a/packages/auth/README.md +++ b/packages/auth/README.md @@ -11,3 +11,22 @@ The package implements the Tsinghua WebVPN and identity login flow: 5. Persist the resulting Cookie-based session through `AuthSessionStore`. `AuthSession` deliberately contains no password. Flutter applications should provide a Keychain/Keystore-backed store, while CLI clients can provide an operating-system credential-store implementation. + +## Coordinated session recovery + +App screens that share persistent cookies should use `AuthSessionRunner` with +the same `AuthSessionStore` object. The default Flutter `SecureAuthSessionStore` +provides that shared identity. The runner restores the latest session inside a +queue, preventing independent screens from overwriting refreshed cookies with +older snapshots. + +For a typed authentication failure, the runner reads matching saved credentials, +reuses the session fingerprint and trusted-device token, logs in, and retries +the complete service operation once. Services can classify their own wrapped +authentication errors with `shouldReconnect`. Network and parsing errors do not +trigger a credential login. A server-required second factor is propagated for +the caller's verification flow; it does not clear saved credentials. + +Coordinate explicit sign-in and sign-out with `AuthSessionRunner.exclusive` as +well. Apply any UI timeout outside `run`, so a timed-out caller does not release +the queue while its underlying request can still persist cookies. diff --git a/packages/auth/lib/src/session_runner.dart b/packages/auth/lib/src/session_runner.dart new file mode 100644 index 0000000..0ae9696 --- /dev/null +++ b/packages/auth/lib/src/session_runner.dart @@ -0,0 +1,82 @@ +part of '../thulium_auth.dart'; + +/// Coordinates clients which persist into the same session store. +/// +/// Restore happens inside the queue, so a waiting request observes cookies and +/// trusted-device state refreshed by its predecessor rather than overwriting +/// them with an earlier snapshot. Callers must share their session-store object. +final class AuthSessionRunner { + const AuthSessionRunner(this.store, {this.trace, this.createClient}); + + final AuthSessionStore store; + final AuthTraceHandler? trace; + + /// Allows a caller to configure the transport. The client must use [store]. + final TsinghuaAuthClient Function()? createClient; + static final _gates = Expando<_AuthSessionGate>(); + + /// Also coordinates explicit sign-in/sign-out with background requests. + static Future exclusive( + AuthSessionStore store, + Future Function() operation, + ) async { + final gate = _gates[store] ??= _AuthSessionGate(); + final previous = gate.tail; + final released = Completer(); + gate.tail = released.future; + await previous; + try { + return await operation(); + } finally { + released.complete(); + } + } + + /// Retries the complete service operation once after a credential login. + /// Network, parsing, and unrelated service failures never trigger a login. + Future run({ + required Future Function(TsinghuaAuthClient client, bool isRetry) + request, + bool Function(Object error)? shouldReconnect, + String? expectedUserId, + }) => exclusive(store, () async { + final credentials = store is AuthCredentialStore + ? store as AuthCredentialStore + : null; + final client = + createClient?.call() ?? + TsinghuaAuthClient( + sessionStore: store, + credentialStore: credentials, + trace: trace, + ); + final session = await client.restore(); + if (session == null || + (expectedUserId != null && session.userId != expectedUserId)) { + throw const PortalSessionRejected(); + } + try { + return await request(client, false); + } on Object catch (error) { + final reconnect = + shouldReconnect?.call(error) ?? + (error is PortalSessionRejected || error is PortalCsrfUnavailable); + if (!reconnect) rethrow; + final saved = await credentials?.readCredentials(); + if (saved == null || saved.userId != session.userId) rethrow; + trace?.call('Reconnecting with saved credentials; retrying once.'); + await client.login( + userId: session.userId, + password: saved.password, + fingerprint: session.fingerprint, + ); + // Keep this outside the first attempt's catch: a failed retry must not + // launch a second login. login() retains the restored trusted-device token. + return request(client, true); + } + }); +} + +final class _AuthSessionGate { + Future tail = Future.value(); +} diff --git a/packages/auth/lib/thulium_auth.dart b/packages/auth/lib/thulium_auth.dart index 1ea3ee1..9fad1b5 100644 --- a/packages/auth/lib/thulium_auth.dart +++ b/packages/auth/lib/thulium_auth.dart @@ -18,6 +18,8 @@ import 'package:http/http.dart' as http; import 'src/response_diagnostics.dart'; import 'tsinghua_webvpn_redirect.dart'; +part 'src/session_runner.dart'; + // Entry point that starts the WebVPN OAuth flow and redirects to the identity // provider. Keeping these endpoints in one place makes protocol updates easier // to review and prevents URL fragments from being duplicated throughout the diff --git a/packages/auth/test/session_runner_test.dart b/packages/auth/test/session_runner_test.dart new file mode 100644 index 0000000..b7c0093 --- /dev/null +++ b/packages/auth/test/session_runner_test.dart @@ -0,0 +1,273 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:dart_sm/dart_sm.dart'; +import 'package:http/http.dart' as http; +import 'package:test/test.dart'; +import 'package:thulium_auth/thulium_auth.dart'; + +final _resource = Uri.parse('https://info.tsinghua.edu.cn/resource'); +const _session = AuthSession( + userId: '1234567890', + fingerprint: 'stable-device', + cookies: {}, + fingerGenPrint: 'trusted-device', + scopedCookies: [ + AuthCookie( + name: 'JSESSIONID', + value: 'old', + domain: 'info.tsinghua.edu.cn', + path: '/', + hostOnly: true, + secure: true, + ), + ], +); + +void main() { + test( + 'service-specific authentication errors can recover through the same queue', + () async { + final store = _Store(); + final transport = _Transport(); + var attempts = 0; + final expired = StateError('wrapped session error'); + final result = await _runner(store, transport).run( + shouldReconnect: (error) => identical(error, expired), + request: (client, isRetry) async { + attempts++; + if (!isRetry) throw expired; + return _load(client, isRetry); + }, + ); + expect(result, 'content'); + expect(attempts, 2); + expect(transport.logins, 1); + }, + ); + + test( + 'concurrent callers reuse one credential login and the latest cookies', + () async { + final store = _Store(); + final transport = _Transport()..releaseFirst = Completer(); + final runner = _runner(store, transport); + final first = runner.run(request: _load); + await transport.firstResource.future; + final second = _runner(store, transport).run(request: _load); + await Future.delayed(Duration.zero); + expect(transport.resourceCookies, hasLength(1)); + transport.releaseFirst!.complete(); + expect(await Future.wait([first, second]), ['content', 'content']); + expect(transport.logins, 1); + expect(transport.resourceCookies, hasLength(3)); + expect(transport.resourceCookies.last, contains('ROTATED=fresh')); + expect(transport.identityForms, hasLength(2)); + for (final form in transport.identityForms) { + expect(form['fingerPrint'], 'stable-device'); + expect(form['fingerGenPrint'], 'trusted-device'); + } + expect(store.saved!.fingerGenPrint, 'trusted-device'); + expect(store.credentials!.password, 'saved-password'); + }, + ); + + test('a rejected retry does not cause a second credential login', () async { + final store = _Store(); + final transport = _Transport()..rejectRetry = true; + await expectLater( + _runner(store, transport).run(request: _load), + throwsA(isA()), + ); + expect(transport.logins, 1); + expect(transport.resourceCookies, hasLength(2)); + }); + + test('network and malformed-content errors do not trigger a login', () async { + for (final error in [ + TimeoutException('offline'), + const FormatException('bad JSON'), + ]) { + final store = _Store(); + final transport = _Transport(); + await expectLater( + _runner( + store, + transport, + ).run(request: (_, _) async => throw error), + throwsA(same(error)), + ); + expect(transport.logins, 0); + expect(store.saved, same(_session)); + expect(store.credentialReads, 0); + } + }); + + test('missing or other-account credentials never trigger a login', () async { + for (final credentials in [ + null, + const AuthCredentials(userId: 'other', password: 'other'), + ]) { + final store = _Store()..credentials = credentials; + final transport = _Transport(); + await expectLater( + _runner(store, transport).run(request: _load), + throwsA(isA()), + ); + expect(transport.logins, 0); + } + }); + + test('queued operations cannot act on a different account', () async { + final store = _Store(); + var requested = false; + await expectLater( + _runner(store, _Transport()).run( + expectedUserId: 'other-account', + request: (_, _) async { + requested = true; + }, + ), + throwsA(isA()), + ); + expect(requested, isFalse); + }); + + test( + 'interactive verification preserves credentials and releases the queue', + () async { + final store = _Store(); + final transport = _Transport()..needsVerification = true; + await expectLater( + _runner(store, transport).run(request: _load), + throwsA(isA()), + ); + expect(store.saved, isNotNull); + expect(store.credentials!.password, 'saved-password'); + expect( + await _runner(store, transport).run(request: (_, _) async => 'cached'), + 'cached', + ); + }, + ); + + test( + 'logout waits for an active request and prevents queued session resurrection', + () async { + final store = _Store(); + final transport = _Transport()..releaseFirst = Completer(); + final first = _runner(store, transport).run(request: _load); + await transport.firstResource.future; + final logout = AuthSessionRunner.exclusive(store, () async { + await store.clear(); + await store.clearCredentials(); + }); + final afterLogout = expectLater( + _runner(store, transport).run(request: _load), + throwsA(isA()), + ); + transport.releaseFirst!.complete(); + await first; + await logout; + await afterLogout; + expect(store.saved, isNull); + expect(store.credentials, isNull); + expect(transport.logins, 1); + }, + ); +} + +AuthSessionRunner _runner(_Store store, _Transport transport) => + AuthSessionRunner( + store, + createClient: () => TsinghuaAuthClient( + httpClient: transport, + sessionStore: store, + credentialStore: store, + ), + ); + +Future _load(TsinghuaAuthClient client, bool isRetry) async { + final response = await client.getAuthenticated(_resource); + if (response.statusCode == 401) throw const PortalSessionRejected(); + return response.body; +} + +class _Store implements AuthSessionStore, AuthCredentialStore { + AuthSession? saved = _session; + AuthCredentials? credentials = const AuthCredentials( + userId: '1234567890', + password: 'saved-password', + ); + int credentialReads = 0; + @override + Future read() async => saved; + @override + Future write(AuthSession session) async => saved = session; + @override + Future clear() async => saved = null; + @override + Future readCredentials() async { + credentialReads++; + return credentials; + } + + @override + Future writeCredentials(AuthCredentials value) async => + credentials = value; + @override + Future clearCredentials() async => credentials = null; +} + +class _Transport extends http.BaseClient { + final firstResource = Completer(); + Completer? releaseFirst; + final resourceCookies = []; + final identityForms = >[]; + final publicKey = SM2.generateKeyPair().publicKey; + int logins = 0; + bool rejectRetry = false; + bool needsVerification = false; + + @override + Future send(http.BaseRequest request) async { + String body = ''; + var status = 200; + final headers = {}; + switch (request.url.path) { + case '/resource': + final cookies = request.headers['Cookie'] ?? ''; + resourceCookies.add(cookies); + if (!firstResource.isCompleted) { + firstResource.complete(); + await releaseFirst?.future; + } + if (cookies.contains('JSESSIONID=new') && !rejectRetry) { + body = 'content'; + headers['set-cookie'] = 'ROTATED=fresh; Path=/; Secure'; + } else { + status = 401; + } + case '/login': + logins++; + body = '$publicKey'; + case final path when path.startsWith('/do/off/ui/auth/login/form/'): + body = '$publicKey'; + case '/do/off/ui/auth/login/check': + identityForms.add(Uri.splitQueryString((request as http.Request).body)); + body = needsVerification + ? '二次认证' + : '登录成功。正在重定向到'; + case '/wengine-vpn/cookie': + body = 'XSRF-TOKEN=new-csrf; JSESSIONID=new;'; + case final path when path.endsWith('/b/info/gxfw_fg/common/grjbxx'): + body = '{"result":"success","object":{"ryh":"1234567890"}}'; + } + return http.StreamedResponse( + Stream.value(utf8.encode(body)), + status, + request: request, + headers: headers, + ); + } +} diff --git a/test/unit/auth/secure_auth_session_store_test.dart b/test/unit/auth/secure_auth_session_store_test.dart new file mode 100644 index 0000000..e247c6f --- /dev/null +++ b/test/unit/auth/secure_auth_session_store_test.dart @@ -0,0 +1,41 @@ +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:thulium/auth/secure_auth_session_store.dart'; +import 'package:thulium_auth/thulium_auth.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test( + 'default stores share the session coordination identity and retain persisted credentials', + () async { + const session = AuthSession( + userId: '1234567890', + fingerprint: 'stable-device', + cookies: {}, + fingerGenPrint: 'trusted-device', + ); + FlutterSecureStorage.setMockInitialValues({ + 'thulium.auth.session': session.encode(), + 'thulium.auth.credentials': + '{"userId":"1234567890","password":"saved-password"}', + 'thulium.auth.fingerprint': 'stable-device', + }); + final home = SecureAuthSessionStore(); + final calendar = SecureAuthSessionStore(); + final documents = SecureAuthSessionStore(); + expect(identical(home, calendar), isTrue); + expect(identical(calendar, documents), isTrue); + expect((await documents.read())!.fingerGenPrint, 'trusted-device'); + expect((await calendar.readCredentials())!.password, 'saved-password'); + expect(await home.getOrCreateFingerprint(), 'stable-device'); + + await home.clear(); + expect(await calendar.read(), isNull); + expect((await documents.readCredentials())!.password, 'saved-password'); + await home.clearCredentials(); + expect(await documents.readCredentials(), isNull); + expect(await home.getOrCreateFingerprint(), 'stable-device'); + }, + ); +} From ba0f97a1eea3e9b58563d53def2098a4048a76c5 Mon Sep 17 00:00:00 2001 From: ashgrey Date: Wed, 18 Nov 2026 01:09:25 +0800 Subject: [PATCH 20/26] fix(auth): reuse trusted-browser SSO across login stages Collect trust consent before the initial credential submission, persist browser consent independently of legacy tokens, and follow trusted-browser forms during portal login and silent renewal. --- packages/auth/README.md | 9 + packages/auth/lib/thulium_auth.dart | 183 +++++++-- packages/auth/pubspec.lock | 16 + packages/auth/pubspec.yaml | 1 + packages/auth/test/thulium_auth_test.dart | 436 +++++++++++++++++++++- packages/campus/pubspec.lock | 16 + packages/cli/pubspec.lock | 16 + pubspec.lock | 16 + 8 files changed, 648 insertions(+), 45 deletions(-) diff --git a/packages/auth/README.md b/packages/auth/README.md index e338832..80bebb3 100644 --- a/packages/auth/README.md +++ b/packages/auth/README.md @@ -27,6 +27,15 @@ authentication errors with `shouldReconnect`. Network and parsing errors do not trigger a credential login. A server-required second factor is propagated for the caller's verification flow; it does not clear saved credentials. +Device trust records browser consent separately from the optional legacy +`fingerGenPrint` token. Sign-in asks once before the first credential submission, +so trusted-browser `singleLogin` fields are present from the WebVPN stage onward. +Fingerprint registration still happens only after successful code verification. +Server-provided `checkSingle` forms are followed before falling back to +credentials, including during silent portal renewal. This allows the WebVPN and +information-portal stages to share a verified identity without unnecessarily +requesting another code. A genuine server challenge is still verified. + Coordinate explicit sign-in and sign-out with `AuthSessionRunner.exclusive` as well. Apply any UI timeout outside `run`, so a timed-out caller does not release the queue while its underlying request can still persist cookies. diff --git a/packages/auth/lib/thulium_auth.dart b/packages/auth/lib/thulium_auth.dart index 9fad1b5..15bce27 100644 --- a/packages/auth/lib/thulium_auth.dart +++ b/packages/auth/lib/thulium_auth.dart @@ -14,6 +14,7 @@ import 'dart:io' show HttpDate, HttpException; import 'package:dart_sm/dart_sm.dart'; import 'package:fast_gbk/fast_gbk.dart' as gbk_codec; import 'package:http/http.dart' as http; +import 'package:html/parser.dart' as html; import 'src/response_diagnostics.dart'; import 'tsinghua_webvpn_redirect.dart'; @@ -140,6 +141,7 @@ final class AuthSession { required this.cookies, this.scopedCookies = const [], this.fingerGenPrint, + this.trustedBrowser = false, }); /// The numeric Tsinghua account identifier used during sign-in. @@ -166,6 +168,11 @@ final class AuthSession { /// This value is sensitive and must be persisted only through a secure store. final String? fingerGenPrint; + /// Whether the user allowed trusted-browser SSO on this installation. + /// This is independent of an optional legacy token; the server still decides + /// whether the browser is trusted and whether verification is necessary. + final bool trustedBrowser; + /// Converts the session to a JSON-compatible map for secure persistence. Map toJson() => { 'userId': userId, @@ -173,6 +180,7 @@ final class AuthSession { 'cookies': cookies, 'scopedCookies': scopedCookies.map((cookie) => cookie.toJson()).toList(), if (fingerGenPrint != null) 'fingerGenPrint': fingerGenPrint, + if (trustedBrowser) 'trustedBrowser': true, }; /// Reconstructs a session previously produced by [toJson]. @@ -187,6 +195,10 @@ final class AuthSession { ) .toList(growable: false), fingerGenPrint: json['fingerGenPrint'] as String?, + trustedBrowser: + json['trustedBrowser'] as bool? ?? + (json['fingerGenPrint'] is String && + (json['fingerGenPrint'] as String).isNotEmpty), ); /// Encodes this session as a single string for key-value secure stores. @@ -535,6 +547,9 @@ final class TsinghuaAuthClient { AuthSession? get session => _session; AuthSession? _session; String? _fingerGenPrint; + bool _trustedBrowser = false; + bool? _trustDecision; + bool _registeredDuringLogin = false; /// Restores the last session without asking for the password. Future restore() async { @@ -552,6 +567,8 @@ final class TsinghuaAuthClient { } _session = restored; + _trustedBrowser = + restored.trustedBrowser || restored.fingerGenPrint?.isNotEmpty == true; _cookieJar.restore(restored.scopedCookies); return restored; } @@ -864,13 +881,20 @@ final class TsinghuaAuthClient { } Future _trySilentPortalReconnect() async { - if (_session == null) return; + final session = _session; + if (session == null) return; try { trace?.call('Trying portal reconnection with the saved SSO cookies.'); await _request(Uri.parse(_WEB_VPN_OAUTH_LOGIN_URL)); - final portal = await _request( + var portal = await _request( Uri.parse('$_ID_LOGIN_FORM_URL$_INFO_ROAMING_ID'), ); + portal = + await _trustedIdentityEntry( + portal, + fingerprint: session.fingerprint, + ) ?? + portal; if (portal.body.contains('登录成功。正在重定向到')) { await _finishIdentityRedirect(portal.body, throughWebVpnOAuth: true); } @@ -934,6 +958,7 @@ final class TsinghuaAuthClient { cookies: Map.unmodifiable(_cookieJar.legacyValues), scopedCookies: _cookieJar.cookies, fingerGenPrint: current.fingerGenPrint, + trustedBrowser: current.trustedBrowser || _trustedBrowser, ); _session = updated; await _sessionStore?.write(updated); @@ -950,6 +975,7 @@ final class TsinghuaAuthClient { _cookieJar.clear(); _session = null; _fingerGenPrint = null; + _trustedBrowser = false; await _sessionStore?.clear(); return false; } @@ -973,30 +999,30 @@ final class TsinghuaAuthClient { previousSession.fingerprint == fingerprint ? previousSession.fingerGenPrint : null; + _trustedBrowser = + previousSession != null && + previousSession.userId == userId && + previousSession.fingerprint == fingerprint && + (previousSession.trustedBrowser || + previousSession.fingerGenPrint?.isNotEmpty == true); + // singleLogin must be present on the initial credential submission, before + // WebVPN and the portal establish separate ID sessions. Ask once up front + // rather than first asking after verification, when that POST is too late. + _trustDecision = + _trustedBrowser || + await (twoFactorTrustHandler?.call() ?? Future.value(false)); + _registeredDuringLogin = false; // The old account must not be used to probe or silently renew the portal // while a new credential-based login is establishing its own session. _session = null; _cookieJar.clear(); final loginPage = await _request(Uri.parse(_WEB_VPN_OAUTH_LOGIN_URL)); - final publicKey = _extract( - loginPage.body, - 'id="sm2publicKey"[^>]*>([^<]+)', - ); - if (publicKey == null || publicKey.isEmpty) { - throw StateError('The identity login public key was not found.'); - } - - var response = await _request( - Uri.parse(_ID_LOGIN_URL), - method: 'POST', - form: { - 'i_user': userId, - 'i_pass': '04${SM2.encrypt(password, publicKey)}', - 'fingerPrint': fingerprint, - 'fingerGenPrint': _fingerGenPrint ?? '', - 'i_captcha': '', - }, + var response = await _identityEntry( + loginPage, + userId: userId, + password: password, + fingerprint: fingerprint, ); if (response.body.contains('二次认证')) { @@ -1023,6 +1049,7 @@ final class TsinghuaAuthClient { cookies: Map.unmodifiable(_cookieJar.legacyValues), scopedCookies: _cookieJar.cookies, fingerGenPrint: _fingerGenPrint, + trustedBrowser: _trustedBrowser || _trustDecision == true, ); _session = result; await _sessionStore?.write(result); @@ -1039,6 +1066,7 @@ final class TsinghuaAuthClient { _cookieJar.clear(); _session = null; _fingerGenPrint = null; + _trustedBrowser = false; try { await _sessionStore?.clear(); } finally { @@ -1125,7 +1153,7 @@ final class TsinghuaAuthClient { // Only a well-formed server rejection reaches this branch. A caller can // keep its input surface open without treating network failures as a // rejected code. - trace?.call('2FA code verification was rejected; requesting another.'); + trace?.call('2FA code verification was rejected; awaiting corrected input.'); return false; }); if (verified == null) { @@ -1133,9 +1161,11 @@ final class TsinghuaAuthClient { } final verifiedResponse = verified!; - // Match the upstream trust-device flow: only register after explicit user - // consent, then retain the returned finger3 for the next CAS service stage. - if (await (twoFactorTrustHandler?.call() ?? Future.value(false))) { + // Register only after verified 2FA and explicit consent. A legacy token is + // optional; browser SSO can be established without one. + _trustDecision ??= + await (twoFactorTrustHandler?.call() ?? Future.value(false)); + if (_trustDecision! && !_registeredDuringLogin) { await _saveTrustedDevice(fingerprint); } @@ -1176,12 +1206,17 @@ final class TsinghuaAuthClient { trace?.call('Trusted-device registration was not accepted.'); return; } + // Current deployments can acknowledge registration without an object. + // Browser SSO is not conditional on receiving a legacy token string. + _trustedBrowser = true; + _registeredDuringLogin = true; + trace?.call('Trusted-device registration accepted.'); final token = response['object']; if (token is String && token.isNotEmpty) { _fingerGenPrint = token; trace?.call('Trusted-device credential received.'); } else { - trace?.call('Trusted-device registration returned no credential.'); + trace?.call('Trusted-device registration needs no legacy credential.'); } } catch (_) { // Device trust is optional; its failure must not invalidate successful @@ -1256,17 +1291,43 @@ final class TsinghuaAuthClient { final loginPage = await _request( Uri.parse('$_ID_LOGIN_FORM_URL$_INFO_ROAMING_ID'), ); - final publicKey = _extract( - loginPage.body, - 'id="sm2publicKey"[^>]*>([^<]+)', + var response = await _identityEntry( + loginPage, + userId: userId, + password: password, + fingerprint: fingerprint, ); - if (publicKey == null || publicKey.isEmpty) { - throw StateError( - 'The information-portal identity public key was not found.', - ); + if (response.body.contains('二次认证')) { + response = await _completeTwoFactor(fingerprint: fingerprint); } + _ensureIdentityLoginSucceeded(response.body); + await _finishIdentityRedirect(response.body, throughWebVpnOAuth: true); + } - var response = await _request( + /// Follow the server's trusted-browser entry before resubmitting a password. + /// Only the documented ID-origin actions may receive the supplied fields. + Future<_Response> _identityEntry( + _Response entry, { + required String userId, + required String password, + required String fingerprint, + }) async { + if (entry.body.contains('登录成功。正在重定向到')) return entry; + final trusted = await _trustedIdentityEntry( + entry, + fingerprint: fingerprint, + ); + final document = html.parse(trusted?.body ?? entry.body); + final publicKey = document.getElementById('sm2publicKey')?.text.trim(); + if (trusted != null && (publicKey == null || publicKey.isEmpty)) { + return trusted; + } + // A denied SSO entry can return a fresh credential form. Fall back once + // using that public key, retaining any server-required second factor. + if (publicKey == null || publicKey.isEmpty) { + throw StateError('The identity login public key was not found.'); + } + return _request( Uri.parse(_ID_LOGIN_URL), method: 'POST', form: { @@ -1275,13 +1336,61 @@ final class TsinghuaAuthClient { 'fingerPrint': fingerprint, 'fingerGenPrint': _fingerGenPrint ?? '', 'i_captcha': '', + if (_trustedBrowser || _trustDecision == true) 'singleLogin': 'on', + if (_trustedBrowser || _trustDecision == true) 'deviceName': 'Thulium', }, ); - if (response.body.contains('二次认证')) { - response = await _completeTwoFactor(fingerprint: fingerprint); + } + + Future<_Response?> _trustedIdentityEntry( + _Response entry, { + required String fingerprint, + }) async { + if (!_trustedBrowser && _trustDecision != true) return null; + final document = html.parse(entry.body); + if (document.getElementById('sm2publicKey') != null) return null; + final forms = document + .querySelectorAll('form') + .where( + (form) => form.querySelector('input[name="fingerPrint"]') != null, + ); + if (forms.isEmpty) return null; + final form = forms.first; + final action = Uri.parse( + _ID_HOST_URL, + ).resolve(form.attributes['action'] ?? ''); + if (action.scheme != 'https' || + action.host != Uri.parse(_ID_HOST_URL).host || + action.port != 443 || + action.userInfo.isNotEmpty || + !const [ + '/do/off/ui/auth/login/checkSingle', + '/security_check', + ].contains(action.path)) { + throw StateError('The trusted-browser form has an unexpected action.'); } - _ensureIdentityLoginSucceeded(response.body); - await _finishIdentityRedirect(response.body, throughWebVpnOAuth: true); + final fields = {}; + for (final input in form.querySelectorAll('input[name]')) { + final name = input.attributes['name']!; + final type = input.attributes['type']?.toLowerCase(); + if (input.attributes.containsKey('disabled') || + const [ + 'password', + 'file', + 'submit', + 'button', + 'reset', + ].contains(type) || + (const ['checkbox', 'radio'].contains(type) && + !input.attributes.containsKey('checked'))) { + continue; + } + fields[name] = name == 'fingerPrint' + ? fingerprint + : input.attributes['value'] ?? ''; + } + trace?.call('Using the trusted-browser identity entry.'); + return _request(action, method: 'POST', form: fields); } Uri _webVpnOAuthRedirectUri(Uri target) { diff --git a/packages/auth/pubspec.lock b/packages/auth/pubspec.lock index 489d67d..9af1c90 100644 --- a/packages/auth/pubspec.lock +++ b/packages/auth/pubspec.lock @@ -81,6 +81,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.7" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" dart_sm: dependency: "direct main" description: @@ -121,6 +129,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + html: + dependency: "direct main" + description: + name: html + sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" + url: "https://pub.dev" + source: hosted + version: "0.15.7" http: dependency: "direct main" description: diff --git a/packages/auth/pubspec.yaml b/packages/auth/pubspec.yaml index e8212fe..a45fd57 100644 --- a/packages/auth/pubspec.yaml +++ b/packages/auth/pubspec.yaml @@ -9,6 +9,7 @@ environment: dependencies: dart_sm: ^0.1.5 fast_gbk: ^1.0.0 + html: ^0.15.7 http: ^1.4.0 dev_dependencies: diff --git a/packages/auth/test/thulium_auth_test.dart b/packages/auth/test/thulium_auth_test.dart index bbf6066..8f7fbc8 100644 --- a/packages/auth/test/thulium_auth_test.dart +++ b/packages/auth/test/thulium_auth_test.dart @@ -120,6 +120,25 @@ void main() { final restored = AuthSession.decode(session.encode()); expect(restored.fingerGenPrint, 'trusted-device-token'); + expect(restored.trustedBrowser, isTrue); + }); + + test('trusted browser consent round-trips without a legacy token', () { + const session = AuthSession( + userId: '1234567890', + fingerprint: 'device', + cookies: {}, + trustedBrowser: true, + ); + final restored = AuthSession.decode(session.encode()); + expect(restored.trustedBrowser, isTrue); + expect(restored.fingerGenPrint, isNull); + final legacy = AuthSession.fromJson({ + 'userId': '1234567890', + 'fingerprint': 'device', + 'cookies': {}, + }); + expect(legacy.trustedBrowser, isFalse); }); test('memory store restores and clears a session', () async { @@ -736,6 +755,353 @@ void main() { }, ); + test( + 'trust registration without a token prevents a second code and survives relaunch', + () async { + final client = _FakeAuthClient( + trustWithoutToken: true, + honorTrustedBrowser: true, + ); + final store = MemoryAuthSessionStore(); + var codes = 0; + var trustPrompts = 0; + final auth = TsinghuaAuthClient( + httpClient: client, + sessionStore: store, + twoFactorMethodHandler: (_) async => TwoFactorMethod.wechat, + twoFactorCodeHandler: (verify) async { + codes++; + expect(await verify('incorrect'), isFalse); + expect(await verify('123456'), isTrue); + }, + twoFactorTrustHandler: () async { + trustPrompts++; + return true; + }, + ); + final session = await auth.login( + userId: '1234567890', + password: 'password', + fingerprint: 'stable-device', + ); + expect(codes, 1); + expect(trustPrompts, 1); + expect(session.trustedBrowser, isTrue); + expect(session.fingerGenPrint, isNull); + expect( + client.requests.where( + (r) => r is http.Request && r.body.contains('SEND_CODE'), + ), + hasLength(1), + ); + final portal = + client.requests + .where((r) => r.url.path == '/do/off/ui/auth/login/check') + .last + as http.Request; + expect(portal.bodyFields['singleLogin'], 'on'); + final initial = + client.requests.firstWhere( + (r) => r.url.path == '/do/off/ui/auth/login/check', + ) + as http.Request; + expect(initial.bodyFields['singleLogin'], 'on'); + expect(portal.bodyFields['deviceName'], 'Thulium'); + + final nextTransport = _FakeAuthClient( + honorTrustedBrowser: true, + previouslyRegistered: true, + ); + final next = TsinghuaAuthClient( + httpClient: nextTransport, + sessionStore: store, + ); + await next.restore(); + await next.login( + userId: '1234567890', + password: 'password', + fingerprint: 'stable-device', + ); + expect( + nextTransport.requests.where( + (r) => r.url.path == '/b/doubleAuth/login', + ), + isEmpty, + ); + }, + ); + + test( + 'portal trusted-browser form reuses verified identity without requesting another code', + () async { + final client = _FakeAuthClient( + trustWithoutToken: true, + trustedPortalForm: true, + ); + final auth = TsinghuaAuthClient( + httpClient: client, + twoFactorMethodHandler: (_) async => TwoFactorMethod.wechat, + twoFactorCodeHandler: (verify) async { + expect(await verify('incorrect'), isFalse); + expect(await verify('123456'), isTrue); + }, + twoFactorTrustHandler: () async => true, + ); + await auth.login( + userId: '1234567890', + password: 'password', + fingerprint: 'stable-device', + ); + final single = + client.requests.singleWhere( + (r) => r.url.path == '/do/off/ui/auth/login/checkSingle', + ) + as http.Request; + expect(single.bodyFields, { + 'fingerPrint': 'stable-device', + 'i_rememberme': 'on', + 'execution': 'one&two', + }); + expect( + client.requests.where( + (r) => r.url.path == '/do/off/ui/auth/login/check', + ), + hasLength(1), + ); + expect( + client.requests.where( + (r) => r is http.Request && r.body.contains('SEND_CODE'), + ), + hasLength(1), + ); + }, + ); + + test('rejected browser SSO falls back to credentials once', () async { + final client = _FakeAuthClient( + trustedPortalForm: true, + denySingleLogin: true, + ); + final auth = TsinghuaAuthClient( + httpClient: client, + twoFactorMethodHandler: (_) async => TwoFactorMethod.wechat, + twoFactorCodeHandler: (verify) async { + expect(await verify('incorrect'), isFalse); + expect(await verify('123456'), isTrue); + }, + twoFactorTrustHandler: () async => true, + ); + await auth.login( + userId: '1234567890', + password: 'password', + fingerprint: 'stable-device', + ); + expect( + client.requests.where( + (r) => r.url.path == '/do/off/ui/auth/login/checkSingle', + ), + hasLength(1), + ); + expect( + client.requests.where((r) => r.url.path == '/do/off/ui/auth/login/check'), + hasLength(2), + ); + expect( + client.requests.where( + (r) => r is http.Request && r.body.contains('SEND_CODE'), + ), + hasLength(1), + ); + }); + + test( + 'trusted-browser forms cannot send fields to unexpected origins or endpoints', + () async { + for (final action in [ + 'https://example.com/do/off/ui/auth/login/checkSingle', + 'http://id.tsinghua.edu.cn/do/off/ui/auth/login/checkSingle', + '/unexpected', + ]) { + final client = _FakeAuthClient( + trustedPortalForm: true, + singleLoginAction: action, + ); + final auth = TsinghuaAuthClient( + httpClient: client, + twoFactorMethodHandler: (_) async => TwoFactorMethod.wechat, + twoFactorCodeHandler: (verify) async { + await verify('incorrect'); + await verify('123456'); + }, + twoFactorTrustHandler: () async => true, + ); + await expectLater( + auth.login( + userId: '1234567890', + password: 'password', + fingerprint: 'stable-device', + ), + throwsStateError, + ); + expect( + client.requests.any( + (r) => r.url.host == 'example.com' || r.url.path == '/unexpected', + ), + isFalse, + ); + } + }, + ); + + test( + 'declining trust does not enable browser SSO or register a device', + () async { + final client = _FakeAuthClient( + trustWithoutToken: true, + honorTrustedBrowser: true, + ); + var trustPrompts = 0; + final auth = TsinghuaAuthClient( + httpClient: client, + twoFactorMethodHandler: (_) async => TwoFactorMethod.wechat, + twoFactorCodeHandler: (verify) async { + while (!await verify('123456')) {} + }, + twoFactorTrustHandler: () async { + trustPrompts++; + return false; + }, + ); + final session = await auth.login( + userId: '1234567890', + password: 'password', + fingerprint: 'device', + ); + expect(session.trustedBrowser, isFalse); + expect(trustPrompts, 1); + expect( + client.requests.where( + (r) => r.url.path == '/b/doubleAuth/personal/saveFinger', + ), + isEmpty, + ); + for (final request in client.requests.where( + (r) => r.url.path == '/do/off/ui/auth/login/check', + )) { + expect( + (request as http.Request).bodyFields.containsKey('singleLogin'), + isFalse, + ); + } + }, + ); + + test( + 'a genuine second server challenge is honored without registering trust twice', + () async { + final client = _FakeAuthClient(trustWithoutToken: true); + var codePrompts = 0; + var trustPrompts = 0; + final auth = TsinghuaAuthClient( + httpClient: client, + twoFactorMethodHandler: (_) async => TwoFactorMethod.wechat, + twoFactorCodeHandler: (verify) async { + codePrompts++; + while (!await verify('123456')) {} + }, + twoFactorTrustHandler: () async { + trustPrompts++; + return true; + }, + ); + await auth.login( + userId: '1234567890', + password: 'password', + fingerprint: 'device', + ); + expect(codePrompts, 2); + expect(trustPrompts, 1); + expect( + client.requests.where( + (r) => r.url.path == '/b/doubleAuth/personal/saveFinger', + ), + hasLength(1), + ); + }, + ); + + test( + 'trusted browser state is not reused for a different account or fingerprint', + () async { + for (final target in [ + ('1234567890', 'other-device'), + ('9876543210', 'device'), + ]) { + final store = MemoryAuthSessionStore(); + await store.write( + const AuthSession( + userId: '1234567890', + fingerprint: 'device', + cookies: {}, + trustedBrowser: true, + ), + ); + final client = _FakeAuthClient(honorTrustedBrowser: true); + final auth = TsinghuaAuthClient( + httpClient: client, + sessionStore: store, + ); + await expectLater( + auth.login( + userId: target.$1, + password: 'password', + fingerprint: target.$2, + ), + throwsA(isA()), + ); + final request = + client.requests.singleWhere( + (r) => r.url.path == '/do/off/ui/auth/login/check', + ) + as http.Request; + expect(request.bodyFields.containsKey('singleLogin'), isFalse); + } + }, + ); + + test( + 'silent portal renewal uses the stored trusted-browser form without another password login', + () async { + final store = MemoryAuthSessionStore(); + await store.write( + AuthSession.fromJson({ + ..._savedSession().toJson(), + 'trustedBrowser': true, + }), + ); + final client = _SessionValidationClient( + studentId: '1234567890', + trustedEntry: true, + ); + final auth = TsinghuaAuthClient(httpClient: client, sessionStore: store); + await auth.restore(); + expect(await auth.validateSession(), isTrue); + expect( + client.requests.where( + (r) => r.url.path == '/do/off/ui/auth/login/checkSingle', + ), + hasLength(1), + ); + expect( + client.requests.where( + (r) => r.url.path == '/do/off/ui/auth/login/check', + ), + isEmpty, + ); + expect((await store.read())!.trustedBrowser, isTrue); + }, + ); + test('does not save a login when WebVPN rejects the portal ticket', () async { final store = MemoryAuthSessionStore(); final credentialStore = _MemoryCredentialStore(); @@ -798,8 +1164,11 @@ final class _SessionValidationClient extends http.BaseClient { _SessionValidationClient({ required this.studentId, this.emptyCookieResponses = 0, + this.trustedEntry = false, }); + final bool trustedEntry; + bool _singleCompleted = false; final String studentId; final int emptyCookieResponses; final requests = []; @@ -808,13 +1177,27 @@ final class _SessionValidationClient extends http.BaseClient { @override Future send(http.BaseRequest request) async { requests.add(request); - final body = request.url.path == '/wengine-vpn/cookie' - ? ++cookieRequests <= emptyCookieResponses - ? '' - : 'XSRF-TOKEN=csrf-value; JSESSIONID=portal-session;' - : jsonEncode({ - 'object': {'ryh': studentId}, - }); + final String body; + if (trustedEntry && + request.url.path.startsWith('/do/off/ui/auth/login/form/')) { + body = + '
'; + } else if (trustedEntry && + request.url.path == '/do/off/ui/auth/login/checkSingle') { + _singleCompleted = true; + body = '登录成功。正在重定向到'; + } else if (request.url.path == '/wengine-vpn/cookie') { + cookieRequests++; + body = + (trustedEntry && !_singleCompleted) || + cookieRequests <= emptyCookieResponses + ? '' + : 'XSRF-TOKEN=csrf-value; JSESSIONID=portal-session;'; + } else { + body = jsonEncode({ + 'object': {'ryh': studentId}, + }); + } return http.StreamedResponse( Stream>.value(utf8.encode(body)), 200, @@ -867,9 +1250,23 @@ final class _StalledClient extends http.BaseClient { } final class _FakeAuthClient extends http.BaseClient { - _FakeAuthClient({this.failInformationRedirect = false}); + _FakeAuthClient({ + this.failInformationRedirect = false, + this.trustWithoutToken = false, + this.trustedPortalForm = false, + this.honorTrustedBrowser = false, + this.denySingleLogin = false, + this.singleLoginAction = '/do/off/ui/auth/login/checkSingle', + bool previouslyRegistered = false, + }) : _registered = previouslyRegistered; final bool failInformationRedirect; + bool _registered; + final bool trustWithoutToken; + final bool trustedPortalForm; + final bool honorTrustedBrowser; + final bool denySingleLogin; + final String singleLoginAction; final requests = []; var _verificationAttempts = 0; var _identityLoginAttempts = 0; @@ -878,12 +1275,33 @@ final class _FakeAuthClient extends http.BaseClient { Future send(http.BaseRequest request) async { requests.add(request); final requestBody = request is http.Request ? request.body : ''; + if (request.url.path == '/b/doubleAuth/personal/saveFinger') { + _registered = true; + } final body = switch (request.url.path) { '/login' => '', '/login-form' => '${SM2.generateKeyPair().publicKey}', + _ + when trustedPortalForm && + request.url.path.startsWith('/do/off/ui/auth/login/form/') => + '
' + '' + '' + '' + '' + '
', _ when request.url.path.startsWith('/do/off/ui/auth/login/form/') => '${SM2.generateKeyPair().publicKey}', + '/do/off/ui/auth/login/checkSingle' when denySingleLogin => + '${SM2.generateKeyPair().publicKey}', + '/do/off/ui/auth/login/checkSingle' => + '登录成功。正在重定向到', + '/do/off/ui/auth/login/check' + when honorTrustedBrowser && + _registered && + requestBody.contains('singleLogin=on') => + '登录成功。正在重定向到', '/do/off/ui/auth/login/check' when ++_identityLoginAttempts == 1 => '二次认证', '/do/off/ui/auth/login/check' @@ -900,6 +1318,8 @@ final class _FakeAuthClient extends http.BaseClient { '{"result":"error","msg":"invalid code"}', '/b/doubleAuth/login' => '{"result":"success","object":{"redirectUrl":"http://id.tsinghua.edu.cn/two-factor-redirect"}}', + '/b/doubleAuth/personal/saveFinger' when trustWithoutToken => + '{"result":"success"}', '/b/doubleAuth/personal/saveFinger' => '{"result":"success","object":"trusted-device-token"}', '/two-factor-redirect' => '登录成功。正在重定向到', diff --git a/packages/campus/pubspec.lock b/packages/campus/pubspec.lock index e218707..f515e28 100644 --- a/packages/campus/pubspec.lock +++ b/packages/campus/pubspec.lock @@ -81,6 +81,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.7" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" dart_sm: dependency: transitive description: @@ -121,6 +129,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + html: + dependency: transitive + description: + name: html + sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" + url: "https://pub.dev" + source: hosted + version: "0.15.7" http: dependency: "direct main" description: diff --git a/packages/cli/pubspec.lock b/packages/cli/pubspec.lock index 0aa0dc7..3515b70 100644 --- a/packages/cli/pubspec.lock +++ b/packages/cli/pubspec.lock @@ -89,6 +89,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.9.0" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" dart_sm: dependency: transitive description: @@ -137,6 +145,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + html: + dependency: transitive + description: + name: html + sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" + url: "https://pub.dev" + source: hosted + version: "0.15.7" http: dependency: transitive description: diff --git a/pubspec.lock b/pubspec.lock index c61a950..d98c553 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -137,6 +137,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.0.7" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.dev" + source: hosted + version: "1.0.2" dart_sm: dependency: transitive description: @@ -405,6 +413,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.0.2" + html: + dependency: transitive + description: + name: html + sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" + url: "https://pub.dev" + source: hosted + version: "0.15.7" http: dependency: transitive description: From d4774f323d7091fe835d5b541477445567c64927 Mon Sep 17 00:00:00 2001 From: ashgrey Date: Wed, 18 Nov 2026 19:56:05 +0800 Subject: [PATCH 21/26] fix(auth): isolate Learn failures from university session recovery Verify the main account before rebuilding an expired Learn session. Retry Learn reads once without unnecessary credential login. Keep saved-password recovery for expired university sessions. Avoid treating file permission errors or quoted login markup as logout. Include Learn CSRF tokens in PDF requests and handle obsolete landing URLs. Preserve retry actions for temporary course service failures. Add service recovery, concurrency and UI regression coverage. --- lib/pages/course_detail_page.dart | 1 - lib/pages/login_page.dart | 116 ++++-- lib/study/course_content_source.dart | 6 +- packages/auth/README.md | 31 ++ packages/auth/lib/src/session_runner.dart | 32 +- packages/auth/lib/thulium_auth.dart | 50 ++- packages/auth/test/session_runner_test.dart | 144 ++++++- .../test/support/fake_auth_http_client.dart | 130 +++++++ packages/auth/test/thulium_auth_test.dart | 264 ++++++------- packages/campus/lib/src/course_schedule.dart | 10 + .../campus/lib/src/learn_course_catalog.dart | 4 + packages/campus/lib/src/learn_courses.dart | 191 +++++++--- packages/campus/lib/src/learn_homework.dart | 135 +++---- packages/campus/lib/src/learn_materials.dart | 153 ++++---- packages/campus/lib/thulium_campus.dart | 1 + packages/campus/pubspec.lock | 2 +- packages/campus/pubspec.yaml | 1 + .../campus/test/course_schedule_test.dart | 38 +- packages/campus/test/learn_courses_test.dart | 55 ++- .../campus/test/learn_materials_test.dart | 21 +- .../test/learn_session_recovery_test.dart | 356 ++++++++++++++++++ test/widget/auth/login_page_test.dart | 239 ++++++++++++ .../widget/study/course_detail_page_test.dart | 23 ++ 23 files changed, 1633 insertions(+), 370 deletions(-) create mode 100644 packages/auth/test/support/fake_auth_http_client.dart create mode 100644 packages/campus/test/learn_session_recovery_test.dart create mode 100644 test/widget/auth/login_page_test.dart diff --git a/lib/pages/course_detail_page.dart b/lib/pages/course_detail_page.dart index cbc4961..27901e4 100644 --- a/lib/pages/course_detail_page.dart +++ b/lib/pages/course_detail_page.dart @@ -242,7 +242,6 @@ class _CourseResourcePageState extends State<_CourseResourcePage> { final l10n = AppLocalizations.of(context)!; final expired = _error is PortalSessionRejected || - _error is PortalCsrfUnavailable || _error is TwoFactorInteractionRequired; final errorText = expired ? l10n.courseSessionExpired diff --git a/lib/pages/login_page.dart b/lib/pages/login_page.dart index a0ad295..3960b32 100644 --- a/lib/pages/login_page.dart +++ b/lib/pages/login_page.dart @@ -8,11 +8,27 @@ import 'package:thulium_auth/thulium_auth.dart'; import '../auth/secure_auth_session_store.dart'; +/// Configures a transport while retaining the real page's verification dialogs. +typedef LoginAuthClientBuilder = + TsinghuaAuthClient Function({ + required AuthSessionStore sessionStore, + required AuthCredentialStore credentialStore, + required TwoFactorMethodHandler twoFactorMethodHandler, + required TwoFactorCodeHandler twoFactorCodeHandler, + required TwoFactorTrustHandler twoFactorTrustHandler, + required AuthTraceHandler trace, + }); + /// Collects credentials and performs the shared Tsinghua authentication flow. final class LoginPage extends StatefulWidget { - const LoginPage({required this.onLoginSuccess, super.key}); + const LoginPage({ + required this.onLoginSuccess, + this.authClientBuilder, + super.key, + }); final VoidCallback onLoginSuccess; + final LoginAuthClientBuilder? authClientBuilder; @override State createState() => _LoginPageState(); @@ -56,6 +72,9 @@ final class _VerificationCodeDialogState } Future _verify() async { + if (!mounted || _isVerifying || ModalRoute.of(context)?.isCurrent != true) { + return; + } final code = _controller.text.trim(); if (code.isEmpty) { setState(() => _isInvalid = true); @@ -65,14 +84,18 @@ final class _VerificationCodeDialogState setState(() => _isVerifying = true); try { if (await widget.verifyCode(code)) { - if (mounted) Navigator.of(context).pop(true); + if (mounted && ModalRoute.of(context)?.isCurrent == true) { + Navigator.of(context).pop(true); + } } else if (mounted) { setState(() => _isInvalid = true); } } catch (_) { // A transport failure is not a bad code; end this dialog so the outer // login flow can report its normal sign-in error instead of hanging. - if (mounted) Navigator.of(context).pop(false); + if (mounted && ModalRoute.of(context)?.isCurrent == true) { + Navigator.of(context).pop(false); + } } finally { if (mounted) setState(() => _isVerifying = false); } @@ -120,7 +143,14 @@ final class _VerificationCodeDialogState ), FButton( variant: FButtonVariant.outline, - onPress: _isVerifying ? null : () => Navigator.of(context).pop(false), + onPress: _isVerifying + ? null + : () { + if (!_isVerifying && + ModalRoute.of(context)?.isCurrent == true) { + Navigator.of(context).pop(false); + } + }, child: Text(widget.cancelLabel), ), ], @@ -132,17 +162,21 @@ final class _LoginPageState extends State { final _studentIdController = TextEditingController(); final _passwordController = TextEditingController(); final _sessionStore = SecureAuthSessionStore(); - late final TsinghuaAuthClient _authClient = TsinghuaAuthClient( - sessionStore: _sessionStore, - credentialStore: _sessionStore, - twoFactorMethodHandler: _selectTwoFactorMethod, - twoFactorCodeHandler: _readTwoFactorCode, - twoFactorTrustHandler: _askToTrustDevice, - trace: (message) => debugPrint('[auth] $message'), - ); + late final TsinghuaAuthClient _authClient = + (widget.authClientBuilder ?? TsinghuaAuthClient.new)( + sessionStore: _sessionStore, + credentialStore: _sessionStore, + twoFactorMethodHandler: _selectTwoFactorMethod, + twoFactorCodeHandler: _readTwoFactorCode, + twoFactorTrustHandler: _askToTrustDevice, + trace: (message) => debugPrint('[auth][signin=$_attemptId] $message'), + ); bool _isSubmitting = false; String? _errorMessage; + Future? _trustChoice; + static int _nextAttemptId = 0; + int _attemptId = 0; @override void dispose() { @@ -152,26 +186,39 @@ final class _LoginPageState extends State { } Future _submit() async { + if (!mounted) return; + if (_isSubmitting) { + debugPrint('[signin] attempt=$_attemptId stage=duplicate_submit_ignored'); + return; + } if (!(_formKey.currentState?.validate() ?? false)) return; + final userId = _studentIdController.text.trim(); + final password = _passwordController.text; FocusScope.of(context).unfocus(); setState(() { + _attemptId = ++_nextAttemptId; + _trustChoice = null; _errorMessage = null; _isSubmitting = true; }); + debugPrint('[signin] attempt=$_attemptId stage=start'); try { await AuthSessionRunner.exclusive(_sessionStore, () async { await _authClient.login( - userId: _studentIdController.text.trim(), - password: _passwordController.text, + userId: userId, + password: password, fingerprint: await _sessionStore.getOrCreateFingerprint(), ); }); + debugPrint('[signin] attempt=$_attemptId stage=success'); if (mounted) widget.onLoginSuccess(); } catch (error) { // Do not expose server internals or distinguish which credential was // incorrect. The same localized message also covers network failures. - debugPrint('Thulium login failed: $error'); + debugPrint( + '[signin] attempt=$_attemptId stage=failed type=${error.runtimeType}', + ); if (mounted) { setState( () => _errorMessage = AppLocalizations.of(context)!.loginError, @@ -186,6 +233,13 @@ final class _LoginPageState extends State { TwoFactorOptions options, ) async { final l10n = AppLocalizations.of(context)!; + var answered = false; + void answer(BuildContext dialogContext, TwoFactorMethod? method) { + if (answered || ModalRoute.of(dialogContext)?.isCurrent != true) return; + answered = true; + Navigator.of(dialogContext).pop(method); + } + final methods = <({TwoFactorMethod method, String label})>[]; if (options.hasWeChat) { methods.add((method: TwoFactorMethod.wechat, label: l10n.wechatMethod)); @@ -214,7 +268,7 @@ final class _LoginPageState extends State { padding: const EdgeInsets.only(bottom: 8), child: FButton( variant: FButtonVariant.outline, - onPress: () => Navigator.of(context).pop(option.method), + onPress: () => answer(context, option.method), child: Text(option.label), ), ), @@ -223,7 +277,7 @@ final class _LoginPageState extends State { actions: [ FButton( variant: FButtonVariant.outline, - onPress: () => Navigator.of(context).pop(), + onPress: () => answer(context, null), child: Text(l10n.cancelAction), ), ], @@ -254,9 +308,27 @@ final class _LoginPageState extends State { } } - Future _askToTrustDevice() async { + Future _askToTrustDevice() { + final existing = _trustChoice; + if (existing != null) { + debugPrint('[signin] attempt=$_attemptId stage=trust_choice_reused'); + return existing; + } + return _trustChoice = _showTrustDeviceDialog(); + } + + Future _showTrustDeviceDialog() async { final l10n = AppLocalizations.of(context)!; - return await showFDialog( + var answered = false; + void answer(BuildContext dialogContext, bool choice) { + if (answered || ModalRoute.of(dialogContext)?.isCurrent != true) return; + answered = true; + Navigator.of(dialogContext).pop(choice); + } + + debugPrint('[signin] attempt=$_attemptId stage=trust_dialog_shown'); + final choice = + await showFDialog( context: context, builder: (context, _, animation) => FDialog.adaptive( animation: animation, @@ -265,17 +337,19 @@ final class _LoginPageState extends State { actions: [ FButton( variant: FButtonVariant.outline, - onPress: () => Navigator.of(context).pop(false), + onPress: () => answer(context, false), child: Text(l10n.notNowAction), ), FButton( - onPress: () => Navigator.of(context).pop(true), + onPress: () => answer(context, true), child: Text(l10n.trustDeviceAction), ), ], ), ) ?? false; + debugPrint('[signin] attempt=$_attemptId stage=trust_dialog_resolved'); + return choice; } @override diff --git a/lib/study/course_content_source.dart b/lib/study/course_content_source.dart index a7c0eef..70f1257 100644 --- a/lib/study/course_content_source.dart +++ b/lib/study/course_content_source.dart @@ -1,3 +1,4 @@ +import 'package:flutter/foundation.dart'; import 'package:thulium_auth/thulium_auth.dart'; import 'package:thulium_campus/thulium_campus.dart'; @@ -10,7 +11,10 @@ class CourseContentSource { final LearnCourseCatalog catalog; Future _request(Future Function(TsinghuaAuthClient) operation) => - AuthSessionRunner(store).run( + AuthSessionRunner( + store, + trace: (message) => debugPrint('[auth][course-content] $message'), + ).run( expectedUserId: catalog.userId, request: (client, _) => operation(client), ); diff --git a/packages/auth/README.md b/packages/auth/README.md index 80bebb3..ceef5f3 100644 --- a/packages/auth/README.md +++ b/packages/auth/README.md @@ -27,6 +27,31 @@ authentication errors with `shouldReconnect`. Network and parsing errors do not trigger a credential login. A server-required second factor is propagated for the caller's verification flow; it does not clear saved credentials. +A login page from the portal cookie endpoint first triggers silent SSO renewal; +it does not immediately prove the identity session has expired. If bounded +cookie retries, account probes, and silent SSO still end in +`PortalCsrfUnavailable`, the runner attempts one saved-credential login without +declaring the account signed out. Network failures do not trigger this fallback. +Course and calendar caches propagate recoverable auth failures to the runner +instead of hiding them behind stale data. When validation does invalidate +cookies, the client retains a cookie-free snapshot of +device trust for its credential recovery, restricted to the same account and +fingerprint. Explicit logout also clears this snapshot. + +If validation cleared rejected cookies and credential recovery fails, the runner +persists only the original account/device identity, without cookies. This keeps a +later refresh eligible for recovery while preserving separately saved passwords. + +Learn follows the service-first recovery policy used by OneTHU: a confirmed +Learn login page or HTTP 401 first verifies the main account. If that account is +still authenticated, rebuild only Learn through roaming and retry the read once. +Confirmed main-session rejection is escalated to credential recovery; the +runner's bounded portal-CSRF fallback remains available as described above. +Bare file HTTP 403/404/5xx responses and unsupported PDF conversions remain +service errors. JSON content and injected scripts mentioning login controls do +not prove logout. PDF reads carry the current Learn CSRF token, and temporary +service failures offer retry rather than sending users back to sign-in. + Device trust records browser consent separately from the optional legacy `fingerGenPrint` token. Sign-in asks once before the first credential submission, so trusted-browser `singleLogin` fields are present from the WebVPN stage onward. @@ -39,3 +64,9 @@ requesting another code. A genuine server challenge is still verified. Coordinate explicit sign-in and sign-out with `AuthSessionRunner.exclusive` as well. Apply any UI timeout outside `run`, so a timed-out caller does not release the queue while its underlying request can still persist cookies. + +Serialization orders separate operations; it does not deduplicate interactive +sign-in submissions. The login page guards button and keyboard callbacks before +enqueueing work, snapshots the submitted credentials, and caches one trust +choice for that attempt. Verification and dialog completion also reject repeat +callbacks. Diagnostic attempt IDs and phase names contain no credential values. diff --git a/packages/auth/lib/src/session_runner.dart b/packages/auth/lib/src/session_runner.dart index 0ae9696..414b6c4 100644 --- a/packages/auth/lib/src/session_runner.dart +++ b/packages/auth/lib/src/session_runner.dart @@ -29,6 +29,10 @@ final class AuthSessionRunner { return await operation(); } finally { released.complete(); + if (identical(gate.tail, released.future)) { + // An idle store needs no completed future retained from an older zone. + _gates[store] = null; + } } } @@ -65,11 +69,29 @@ final class AuthSessionRunner { final saved = await credentials?.readCredentials(); if (saved == null || saved.userId != session.userId) rethrow; trace?.call('Reconnecting with saved credentials; retrying once.'); - await client.login( - userId: session.userId, - password: saved.password, - fingerprint: session.fingerprint, - ); + try { + await client.login( + userId: session.userId, + password: saved.password, + fingerprint: session.fingerprint, + ); + } on Object { + // Validation may have cleared rejected cookies before this attempt. + // Retain only the account/device identity so the next refresh can still + // recover with saved credentials instead of failing at restore(). + if (await store.read() == null) { + await store.write( + AuthSession( + userId: session.userId, + fingerprint: session.fingerprint, + cookies: const {}, + fingerGenPrint: session.fingerGenPrint, + trustedBrowser: session.trustedBrowser, + ), + ); + } + rethrow; + } // Keep this outside the first attempt's catch: a failed retry must not // launch a second login. login() retains the restored trusted-device token. return request(client, true); diff --git a/packages/auth/lib/thulium_auth.dart b/packages/auth/lib/thulium_auth.dart index 15bce27..05cb40e 100644 --- a/packages/auth/lib/thulium_auth.dart +++ b/packages/auth/lib/thulium_auth.dart @@ -550,6 +550,19 @@ final class TsinghuaAuthClient { bool _trustedBrowser = false; bool? _trustDecision; bool _registeredDuringLogin = false; + // Keep device trust separate from invalidated cookies for a bounded reconnect. + // This snapshot contains no cookies and is cleared by explicit logout. + AuthSession? _reconnectIdentity; + + void _rememberIdentity(AuthSession session) { + _reconnectIdentity = AuthSession( + userId: session.userId, + fingerprint: session.fingerprint, + cookies: const {}, + fingerGenPrint: session.fingerGenPrint, + trustedBrowser: session.trustedBrowser, + ); + } /// Restores the last session without asking for the password. Future restore() async { @@ -567,6 +580,7 @@ final class TsinghuaAuthClient { } _session = restored; + _rememberIdentity(restored); _trustedBrowser = restored.trustedBrowser || restored.fingerGenPrint?.isNotEmpty == true; _cookieJar.restore(restored.scopedCookies); @@ -609,6 +623,18 @@ final class TsinghuaAuthClient { _traceUnexpectedRawResponse('portal-user-data', userDataResponse); rethrow; } + if (decoded is Map) { + final message = decoded['msg'] ?? decoded['message']; + if (decoded['status'] == 401 || + decoded['code'] == 401 || + (message is String && + RegExp( + r'^(?:未登录|请先登录|登录已失效|登录状态已失效|login required|not authenticated)[。.!]?$', + caseSensitive: false, + ).hasMatch(message.trim()))) { + return null; + } + } if (decoded is! Map || decoded['object'] is! Map) { _traceUnexpectedRawResponse('portal-user-data', userDataResponse); throw StateError( @@ -704,6 +730,9 @@ final class TsinghuaAuthClient { }, ), ); + if (_isLoginRequired(roamingResponse)) { + throw const PortalSessionRejected(); + } Object? roamingJson; try { roamingJson = jsonDecode(roamingResponse.body); @@ -811,7 +840,13 @@ final class TsinghuaAuthClient { PortalCsrfUnavailable? lastFailure; for (var attempt = 0; attempt < _CSRF_FETCH_ATTEMPTS; attempt++) { final response = await _request(Uri.parse(_INFO_CSRF_COOKIE_URL)); - if (_isLoginRequired(response)) throw const PortalSessionRejected(); + if (_isLoginRequired(response)) { + // An expired portal cookie does not prove that the ID/SSO session has + // expired too. Attempt the silent recovery below before asking for a + // new credential login. There is no restored SSO during initial login. + if (_session == null) throw const PortalSessionRejected(); + break; + } try { return _readInformationPortalCsrf(response); } on PortalCsrfUnavailable catch (error) { @@ -992,7 +1027,8 @@ final class TsinghuaAuthClient { // Reuse a trusted-device credential only when both its account and stable // fingerprint match this login. - final previousSession = _session ?? await _sessionStore?.read(); + final previousSession = + _session ?? await _sessionStore?.read() ?? _reconnectIdentity; _fingerGenPrint = previousSession != null && previousSession.userId == userId && @@ -1052,6 +1088,7 @@ final class TsinghuaAuthClient { trustedBrowser: _trustedBrowser || _trustDecision == true, ); _session = result; + _rememberIdentity(result); await _sessionStore?.write(result); await credentialStore?.writeCredentials( AuthCredentials(userId: userId, password: password), @@ -1067,6 +1104,7 @@ final class TsinghuaAuthClient { _session = null; _fingerGenPrint = null; _trustedBrowser = false; + _reconnectIdentity = null; try { await _sessionStore?.clear(); } finally { @@ -1153,7 +1191,9 @@ final class TsinghuaAuthClient { // Only a well-formed server rejection reaches this branch. A caller can // keep its input surface open without treating network failures as a // rejected code. - trace?.call('2FA code verification was rejected; awaiting corrected input.'); + trace?.call( + '2FA code verification was rejected; awaiting corrected input.', + ); return false; }); if (verified == null) { @@ -1163,9 +1203,7 @@ final class TsinghuaAuthClient { // Register only after verified 2FA and explicit consent. A legacy token is // optional; browser SSO can be established without one. - _trustDecision ??= - await (twoFactorTrustHandler?.call() ?? Future.value(false)); - if (_trustDecision! && !_registeredDuringLogin) { + if (_trustDecision == true && !_registeredDuringLogin) { await _saveTrustedDevice(fingerprint); } diff --git a/packages/auth/test/session_runner_test.dart b/packages/auth/test/session_runner_test.dart index b7c0093..b53c97f 100644 --- a/packages/auth/test/session_runner_test.dart +++ b/packages/auth/test/session_runner_test.dart @@ -25,6 +25,135 @@ const _session = AuthSession( ); void main() { + test( + 'exhausted CSRF recovery falls back to saved credentials once', + () async { + final store = _Store(); + final transport = _Transport(); + const error = PortalCsrfUnavailable('temporary cookie service failure'); + final result = await _runner(store, transport).run( + request: (client, isRetry) async { + if (!isRetry) throw error; + return _load(client, isRetry); + }, + ); + expect(result, 'content'); + expect(transport.logins, 1); + expect(store.credentialReads, 1); + expect(transport.identityForms.first['i_user'], _session.userId); + expect( + transport.identityForms.first['fingerPrint'], + _session.fingerprint, + ); + }, + ); + + test( + 'an empty cookie endpoint attempts silent SSO before credential recovery', + () async { + final store = _Store(); + final transport = _Transport()..emptyCookieUntilPassword = true; + final events = []; + final runner = AuthSessionRunner( + store, + trace: events.add, + createClient: () => TsinghuaAuthClient( + sessionStore: store, + credentialStore: store, + httpClient: transport, + trace: events.add, + ), + ); + var attempts = 0; + expect( + await runner.run( + request: (client, _) async { + attempts++; + expect(await client.validateSession(), isTrue); + return 'refreshed'; + }, + ), + 'refreshed', + ); + expect(attempts, 2); + expect(store.credentialReads, 1); + expect( + transport.logins, + 2, + ); // One silent SSO GET, one password login GET. + expect( + events, + contains('Trying portal reconnection with the saved SSO cookies.'), + ); + expect( + events.where( + (event) => event.startsWith('Reconnecting with saved credentials'), + ), + hasLength(1), + ); + }, + ); + + test( + 'a sign-in response from roaming triggers saved-credential recovery', + () async { + final store = _Store(); + final transport = _Transport()..rejectRoamingUntilPassword = true; + final response = await _runner( + store, + transport, + ).run(request: (client, _) => client.roamToPortalApp('abc123')); + expect(response.statusCode, 200); + expect(transport.logins, 1); + expect(store.credentialReads, 1); + expect(transport.roamingRequests, 2); + }, + ); + + test('a repeated CSRF failure does not loop credential recovery', () async { + final store = _Store(); + final transport = _Transport(); + const error = PortalCsrfUnavailable('still unavailable'); + var attempts = 0; + await expectLater( + _runner(store, transport).run( + request: (_, _) async { + attempts++; + throw error; + }, + ), + throwsA(same(error)), + ); + expect(attempts, 2); + expect(transport.logins, 1); + }); + + test( + 'cleared cookies and failed recovery retain identity for a later refresh', + () async { + final store = _Store(); + final transport = _Transport()..needsVerification = true; + await expectLater( + _runner(store, transport).run( + request: (_, _) async { + await store.clear(); // A service has rejected the restored cookies. + throw const PortalSessionRejected(); + }, + ), + throwsA(isA()), + ); + expect(store.saved!.userId, _session.userId); + expect(store.saved!.fingerprint, _session.fingerprint); + expect(store.saved!.fingerGenPrint, _session.fingerGenPrint); + expect(store.saved!.cookies, isEmpty); + expect(store.saved!.scopedCookies, isEmpty); + expect(store.credentials!.password, 'saved-password'); + transport.needsVerification = false; + expect(await _runner(store, transport).run(request: _load), 'content'); + expect(transport.logins, 2); + }, + ); + test( 'service-specific authentication errors can recover through the same queue', () async { @@ -228,6 +357,9 @@ class _Transport extends http.BaseClient { int logins = 0; bool rejectRetry = false; bool needsVerification = false; + bool emptyCookieUntilPassword = false; + bool rejectRoamingUntilPassword = false; + int roamingRequests = 0; @override Future send(http.BaseRequest request) async { @@ -259,7 +391,17 @@ class _Transport extends http.BaseClient { ? '二次认证' : '登录成功。正在重定向到'; case '/wengine-vpn/cookie': - body = 'XSRF-TOKEN=new-csrf; JSESSIONID=new;'; + body = emptyCookieUntilPassword && identityForms.isEmpty + ? '' + : 'XSRF-TOKEN=new-csrf; JSESSIONID=new;'; + case final path when path.endsWith('onlineAppRedirect'): + roamingRequests++; + if (rejectRoamingUntilPassword && identityForms.isEmpty) { + body = '$publicKey'; + } else { + body = + '{"object":{"roamingurl":"https://info.tsinghua.edu.cn/landing"}}'; + } case final path when path.endsWith('/b/info/gxfw_fg/common/grjbxx'): body = '{"result":"success","object":{"ryh":"1234567890"}}'; } diff --git a/packages/auth/test/support/fake_auth_http_client.dart b/packages/auth/test/support/fake_auth_http_client.dart new file mode 100644 index 0000000..07ca5b0 --- /dev/null +++ b/packages/auth/test/support/fake_auth_http_client.dart @@ -0,0 +1,130 @@ +import 'dart:convert'; + +import 'package:dart_sm/dart_sm.dart'; +import 'package:http/http.dart' as http; + +final class FakeAuthHttpClient extends http.BaseClient { + FakeAuthHttpClient({ + this.failInformationRedirect = false, + this.expireCookieBeforeLogin = false, + this.trustWithoutToken = false, + this.trustedPortalForm = false, + this.honorTrustedBrowser = false, + this.denySingleLogin = false, + this.singleLoginAction = '/do/off/ui/auth/login/checkSingle', + bool previouslyRegistered = false, + }) : _registered = previouslyRegistered; + + final bool failInformationRedirect; + final bool expireCookieBeforeLogin; + bool _credentialsSubmitted = false; + bool _registered; + final bool trustWithoutToken; + final bool trustedPortalForm; + final bool honorTrustedBrowser; + final bool denySingleLogin; + final String singleLoginAction; + final requests = []; + var _verificationAttempts = 0; + int get verificationRequestCount => requests + .where( + (request) => + request is http.Request && + request.url.path == '/b/doubleAuth/login' && + request.body.contains('VERITY_CODE'), + ) + .length; + + var _identityLoginAttempts = 0; + + @override + Future send(http.BaseRequest request) async { + requests.add(request); + final requestBody = request is http.Request ? request.body : ''; + if (request.url.path == '/do/off/ui/auth/login/check') { + _credentialsSubmitted = true; + } + if (request.url.path == '/b/doubleAuth/personal/saveFinger') { + _registered = true; + } + final body = switch (request.url.path) { + '/login' => '', + '/login-form' => + '${SM2.generateKeyPair().publicKey}', + _ + when trustedPortalForm && + request.url.path.startsWith('/do/off/ui/auth/login/form/') => + '
' + '' + '' + '' + '' + '
', + _ when request.url.path.startsWith('/do/off/ui/auth/login/form/') => + '${SM2.generateKeyPair().publicKey}', + '/do/off/ui/auth/login/checkSingle' when denySingleLogin => + '${SM2.generateKeyPair().publicKey}', + '/do/off/ui/auth/login/checkSingle' => + '登录成功。正在重定向到', + '/do/off/ui/auth/login/check' + when honorTrustedBrowser && + _registered && + requestBody.contains('singleLogin=on') => + '登录成功。正在重定向到', + '/do/off/ui/auth/login/check' when ++_identityLoginAttempts == 1 => + '二次认证', + '/do/off/ui/auth/login/check' + when requestBody.contains('fingerGenPrint=trusted-device-token') => + '登录成功。正在重定向到', + '/do/off/ui/auth/login/check' => '二次认证', + '/b/doubleAuth/login' when requestBody.contains('FIND_APPROACHES') => + '{"result":"success","object":{"hasWeChatBool":true,"phone":null,"hasTotp":false}}', + '/b/doubleAuth/login' when requestBody.contains('SEND_CODE') => + '{"result":"success"}', + '/b/doubleAuth/login' + when requestBody.contains('VERITY_CODE') && + ++_verificationAttempts == 1 => + '{"result":"error","msg":"invalid code"}', + '/b/doubleAuth/login' => + '{"result":"success","object":{"redirectUrl":"http://id.tsinghua.edu.cn/two-factor-redirect"}}', + '/b/doubleAuth/personal/saveFinger' when trustWithoutToken => + '{"result":"success"}', + '/b/doubleAuth/personal/saveFinger' => + '{"result":"success","object":"trusted-device-token"}', + '/two-factor-redirect' => '登录成功。正在重定向到', + '/callback' => '', + '/lb-auth/lbredirect' => '', + '/wengine-vpn/failed' => 'WebVPN service failed', + '/wengine-vpn/cookie' + when expireCookieBeforeLogin && !_credentialsSubmitted => + 'expired', + '/wengine-vpn/cookie' => + 'XSRF-TOKEN=csrf-value; JSESSIONID=portal-session;', + _ when request.url.path.endsWith('/b/info/gxfw_fg/common/grjbxx') => + '{"result":"success","object":{"ryh":"1234567890"}}', + _ => '{}', + }; + return http.StreamedResponse( + Stream>.value(utf8.encode(body)), + request.url.path == '/login' + ? 302 + : request.url.path == '/lb-auth/lbredirect' && failInformationRedirect + ? 307 + : 200, + headers: switch (request.url.path) { + '/login' => const { + 'location': '/login-form', + 'set-cookie': + 'JSESSIONID=webvpn-session; Path=/; Secure, PATH_ONLY=portal-value; Path=/https; Secure, EXPIRED=old; Path=/; Expires=Wed, 21 Oct 2015 07:28:00 GMT, SESSION=session-value; Path=/, SHARED=shared-value; Domain=.tsinghua.edu.cn; Path=/; Secure', + }, + '/do/off/ui/auth/login/check' => const { + 'set-cookie': 'JSESSIONID=identity-session; Path=/; Secure', + }, + '/lb-auth/lbredirect' when failInformationRedirect => const { + 'location': 'https://webvpn.tsinghua.edu.cn/wengine-vpn/failed', + }, + _ => const {}, + }, + ); + } +} diff --git a/packages/auth/test/thulium_auth_test.dart b/packages/auth/test/thulium_auth_test.dart index 8f7fbc8..2d18011 100644 --- a/packages/auth/test/thulium_auth_test.dart +++ b/packages/auth/test/thulium_auth_test.dart @@ -1,12 +1,13 @@ import 'dart:async'; import 'dart:convert'; -import 'package:dart_sm/dart_sm.dart'; import 'package:fast_gbk/fast_gbk.dart' as gbk_codec; import 'package:http/http.dart' as http; import 'package:test/test.dart'; import 'package:thulium_auth/thulium_auth.dart'; +import 'support/fake_auth_http_client.dart'; + void main() { group('TsinghuaWebVpnRedirect', () { test('uses the published information portal redirect path', () { @@ -158,7 +159,7 @@ void main() { final sessionStore = MemoryAuthSessionStore(); final credentialStore = _MemoryCredentialStore(); final auth = TsinghuaAuthClient( - httpClient: _FakeAuthClient(), + httpClient: FakeAuthHttpClient(), sessionStore: sessionStore, credentialStore: credentialStore, twoFactorMethodHandler: (_) async => TwoFactorMethod.wechat, @@ -435,7 +436,7 @@ void main() { ], ), ); - final client = _FakeAuthClient(); + final client = FakeAuthHttpClient(); final auth = TsinghuaAuthClient(httpClient: client, sessionStore: store); expect(await auth.restore(), isNotNull); @@ -469,7 +470,7 @@ void main() { ); test('signals when reconnect needs interactive two-factor input', () async { - final auth = TsinghuaAuthClient(httpClient: _FakeAuthClient()); + final auth = TsinghuaAuthClient(httpClient: FakeAuthHttpClient()); await expectLater( auth.login( @@ -556,7 +557,7 @@ void main() { test( 'retries a rejected two-factor code without sending another code', () async { - final client = _FakeAuthClient(); + final client = FakeAuthHttpClient(); final events = []; var rejectedEmptyCode = false; var rejectedIncorrectCode = false; @@ -714,7 +715,7 @@ void main() { test( 'registers a trusted device and reuses finger3 during portal roaming', () async { - final client = _FakeAuthClient(); + final client = FakeAuthHttpClient(); final store = MemoryAuthSessionStore(); final auth = TsinghuaAuthClient( httpClient: client, @@ -758,7 +759,7 @@ void main() { test( 'trust registration without a token prevents a second code and survives relaunch', () async { - final client = _FakeAuthClient( + final client = FakeAuthHttpClient( trustWithoutToken: true, honorTrustedBrowser: true, ); @@ -808,7 +809,7 @@ void main() { expect(initial.bodyFields['singleLogin'], 'on'); expect(portal.bodyFields['deviceName'], 'Thulium'); - final nextTransport = _FakeAuthClient( + final nextTransport = FakeAuthHttpClient( honorTrustedBrowser: true, previouslyRegistered: true, ); @@ -834,7 +835,7 @@ void main() { test( 'portal trusted-browser form reuses verified identity without requesting another code', () async { - final client = _FakeAuthClient( + final client = FakeAuthHttpClient( trustWithoutToken: true, trustedPortalForm: true, ); @@ -878,7 +879,7 @@ void main() { ); test('rejected browser SSO falls back to credentials once', () async { - final client = _FakeAuthClient( + final client = FakeAuthHttpClient( trustedPortalForm: true, denySingleLogin: true, ); @@ -922,7 +923,7 @@ void main() { 'http://id.tsinghua.edu.cn/do/off/ui/auth/login/checkSingle', '/unexpected', ]) { - final client = _FakeAuthClient( + final client = FakeAuthHttpClient( trustedPortalForm: true, singleLoginAction: action, ); @@ -956,7 +957,7 @@ void main() { test( 'declining trust does not enable browser SSO or register a device', () async { - final client = _FakeAuthClient( + final client = FakeAuthHttpClient( trustWithoutToken: true, honorTrustedBrowser: true, ); @@ -999,7 +1000,7 @@ void main() { test( 'a genuine second server challenge is honored without registering trust twice', () async { - final client = _FakeAuthClient(trustWithoutToken: true); + final client = FakeAuthHttpClient(trustWithoutToken: true); var codePrompts = 0; var trustPrompts = 0; final auth = TsinghuaAuthClient( @@ -1046,7 +1047,7 @@ void main() { trustedBrowser: true, ), ); - final client = _FakeAuthClient(honorTrustedBrowser: true); + final client = FakeAuthHttpClient(honorTrustedBrowser: true); final auth = TsinghuaAuthClient( httpClient: client, sessionStore: store, @@ -1102,11 +1103,127 @@ void main() { }, ); + test( + 'expired portal cookie recovers through live trusted SSO without a password or code', + () async { + final store = MemoryAuthSessionStore(); + await store.write( + AuthSession.fromJson({ + ..._savedSession().toJson(), + 'trustedBrowser': true, + }), + ); + final client = _SessionValidationClient( + studentId: '1234567890', + trustedEntry: true, + rejectExpiredCookie: true, + ); + final auth = TsinghuaAuthClient(httpClient: client, sessionStore: store); + await auth.restore(); + expect(await auth.validateSession(), isTrue); + expect( + client.requests.where( + (r) => r.url.path == '/do/off/ui/auth/login/checkSingle', + ), + hasLength(1), + ); + expect( + client.requests.where( + (r) => r.url.path == '/do/off/ui/auth/login/check', + ), + isEmpty, + ); + expect( + client.requests.where((r) => r.url.path == '/b/doubleAuth/login'), + isEmpty, + ); + expect((await store.read())!.trustedBrowser, isTrue); + }, + ); + + test( + 'invalidated cookies retain cookie-free device identity for credential recovery', + () async { + final store = MemoryAuthSessionStore(); + await store.write( + AuthSession.fromJson({ + ..._savedSession().toJson(), + 'trustedBrowser': true, + }), + ); + final client = FakeAuthHttpClient( + expireCookieBeforeLogin: true, + honorTrustedBrowser: true, + previouslyRegistered: true, + ); + final auth = TsinghuaAuthClient(httpClient: client, sessionStore: store); + await auth.restore(); + expect(await auth.validateSession(), isFalse); + expect(await store.read(), isNull); + // The expired cookies are gone, but this client can still request browser + // SSO for the same account/device during its one credential recovery. + final session = await auth.login( + userId: '1234567890', + password: 'password', + fingerprint: 'saved-device', + ); + expect(session.trustedBrowser, isTrue); + expect( + client.requests.where((r) => r.url.path == '/b/doubleAuth/login'), + isEmpty, + ); + final post = + client.requests.firstWhere( + (r) => r.url.path == '/do/off/ui/auth/login/check', + ) + as http.Request; + expect(post.bodyFields['singleLogin'], 'on'); + expect( + post.headers['Cookie'] ?? '', + isNot(contains('SESSION=webvpn-session')), + ); + }, + ); + + test( + 'explicit logout removes the reconnect identity as well as cookies', + () async { + final store = MemoryAuthSessionStore(); + await store.write( + AuthSession.fromJson({ + ..._savedSession().toJson(), + 'trustedBrowser': true, + }), + ); + final client = FakeAuthHttpClient( + honorTrustedBrowser: true, + previouslyRegistered: true, + ); + final auth = TsinghuaAuthClient(httpClient: client, sessionStore: store); + await auth.restore(); + await auth.logout(); + await expectLater( + auth.login( + userId: '1234567890', + password: 'password', + fingerprint: 'saved-device', + ), + throwsA(isA()), + ); + final post = + client.requests.singleWhere( + (r) => r.url.path == '/do/off/ui/auth/login/check', + ) + as http.Request; + expect(post.bodyFields.containsKey('singleLogin'), isFalse); + }, + ); + test('does not save a login when WebVPN rejects the portal ticket', () async { final store = MemoryAuthSessionStore(); final credentialStore = _MemoryCredentialStore(); final auth = TsinghuaAuthClient( - httpClient: _FakeAuthClient(failInformationRedirect: true), + httpClient: FakeAuthHttpClient(failInformationRedirect: true), sessionStore: store, credentialStore: credentialStore, twoFactorMethodHandler: (_) async => TwoFactorMethod.wechat, @@ -1165,9 +1282,11 @@ final class _SessionValidationClient extends http.BaseClient { required this.studentId, this.emptyCookieResponses = 0, this.trustedEntry = false, + this.rejectExpiredCookie = false, }); final bool trustedEntry; + final bool rejectExpiredCookie; bool _singleCompleted = false; final String studentId; final int emptyCookieResponses; @@ -1188,9 +1307,10 @@ final class _SessionValidationClient extends http.BaseClient { body = '登录成功。正在重定向到'; } else if (request.url.path == '/wengine-vpn/cookie') { cookieRequests++; - body = - (trustedEntry && !_singleCompleted) || - cookieRequests <= emptyCookieResponses + body = trustedEntry && !_singleCompleted && rejectExpiredCookie + ? 'expired' + : (trustedEntry && !_singleCompleted) || + cookieRequests <= emptyCookieResponses ? '' : 'XSRF-TOKEN=csrf-value; JSESSIONID=portal-session;'; } else { @@ -1248,111 +1368,3 @@ final class _StalledClient extends http.BaseClient { Future send(http.BaseRequest request) => Completer().future; } - -final class _FakeAuthClient extends http.BaseClient { - _FakeAuthClient({ - this.failInformationRedirect = false, - this.trustWithoutToken = false, - this.trustedPortalForm = false, - this.honorTrustedBrowser = false, - this.denySingleLogin = false, - this.singleLoginAction = '/do/off/ui/auth/login/checkSingle', - bool previouslyRegistered = false, - }) : _registered = previouslyRegistered; - - final bool failInformationRedirect; - bool _registered; - final bool trustWithoutToken; - final bool trustedPortalForm; - final bool honorTrustedBrowser; - final bool denySingleLogin; - final String singleLoginAction; - final requests = []; - var _verificationAttempts = 0; - var _identityLoginAttempts = 0; - - @override - Future send(http.BaseRequest request) async { - requests.add(request); - final requestBody = request is http.Request ? request.body : ''; - if (request.url.path == '/b/doubleAuth/personal/saveFinger') { - _registered = true; - } - final body = switch (request.url.path) { - '/login' => '', - '/login-form' => - '${SM2.generateKeyPair().publicKey}', - _ - when trustedPortalForm && - request.url.path.startsWith('/do/off/ui/auth/login/form/') => - '
' - '' - '' - '' - '' - '
', - _ when request.url.path.startsWith('/do/off/ui/auth/login/form/') => - '${SM2.generateKeyPair().publicKey}', - '/do/off/ui/auth/login/checkSingle' when denySingleLogin => - '${SM2.generateKeyPair().publicKey}', - '/do/off/ui/auth/login/checkSingle' => - '登录成功。正在重定向到', - '/do/off/ui/auth/login/check' - when honorTrustedBrowser && - _registered && - requestBody.contains('singleLogin=on') => - '登录成功。正在重定向到', - '/do/off/ui/auth/login/check' when ++_identityLoginAttempts == 1 => - '二次认证', - '/do/off/ui/auth/login/check' - when requestBody.contains('fingerGenPrint=trusted-device-token') => - '登录成功。正在重定向到', - '/do/off/ui/auth/login/check' => '二次认证', - '/b/doubleAuth/login' when requestBody.contains('FIND_APPROACHES') => - '{"result":"success","object":{"hasWeChatBool":true,"phone":null,"hasTotp":false}}', - '/b/doubleAuth/login' when requestBody.contains('SEND_CODE') => - '{"result":"success"}', - '/b/doubleAuth/login' - when requestBody.contains('VERITY_CODE') && - ++_verificationAttempts == 1 => - '{"result":"error","msg":"invalid code"}', - '/b/doubleAuth/login' => - '{"result":"success","object":{"redirectUrl":"http://id.tsinghua.edu.cn/two-factor-redirect"}}', - '/b/doubleAuth/personal/saveFinger' when trustWithoutToken => - '{"result":"success"}', - '/b/doubleAuth/personal/saveFinger' => - '{"result":"success","object":"trusted-device-token"}', - '/two-factor-redirect' => '登录成功。正在重定向到', - '/callback' => '', - '/lb-auth/lbredirect' => '', - '/wengine-vpn/failed' => 'WebVPN service failed', - '/wengine-vpn/cookie' => - 'XSRF-TOKEN=csrf-value; JSESSIONID=portal-session;', - _ when request.url.path.endsWith('/b/info/gxfw_fg/common/grjbxx') => - '{"result":"success","object":{"ryh":"1234567890"}}', - _ => '{}', - }; - return http.StreamedResponse( - Stream>.value(utf8.encode(body)), - request.url.path == '/login' - ? 302 - : request.url.path == '/lb-auth/lbredirect' && failInformationRedirect - ? 307 - : 200, - headers: switch (request.url.path) { - '/login' => const { - 'location': '/login-form', - 'set-cookie': - 'JSESSIONID=webvpn-session; Path=/; Secure, PATH_ONLY=portal-value; Path=/https; Secure, EXPIRED=old; Path=/; Expires=Wed, 21 Oct 2015 07:28:00 GMT, SESSION=session-value; Path=/, SHARED=shared-value; Domain=.tsinghua.edu.cn; Path=/; Secure', - }, - '/do/off/ui/auth/login/check' => const { - 'set-cookie': 'JSESSIONID=identity-session; Path=/; Secure', - }, - '/lb-auth/lbredirect' when failInformationRedirect => const { - 'location': 'https://webvpn.tsinghua.edu.cn/wengine-vpn/failed', - }, - _ => const {}, - }, - ); - } -} diff --git a/packages/campus/lib/src/course_schedule.dart b/packages/campus/lib/src/course_schedule.dart index 887b604..d3e520c 100644 --- a/packages/campus/lib/src/course_schedule.dart +++ b/packages/campus/lib/src/course_schedule.dart @@ -244,6 +244,16 @@ final class CourseScheduleService { lastSource = CourseScheduleSource.network; return schedule; } on Exception catch (error) { + // Cached data must not hide a failure that the caller can recover by + // logging in with saved credentials. + if (error is CourseScheduleSessionExpired || + error is PortalSessionRejected || + error is PortalCsrfUnavailable || + (error is CourseScheduleException && + (error.cause is PortalSessionRejected || + error.cause is PortalCsrfUnavailable))) { + rethrow; + } if (cached == null || forceRefresh) rethrow; trace?.call('Calendar using stale cache after ${error.runtimeType}'); lastSource = CourseScheduleSource.staleCache; diff --git a/packages/campus/lib/src/learn_course_catalog.dart b/packages/campus/lib/src/learn_course_catalog.dart index 1077629..d97902a 100644 --- a/packages/campus/lib/src/learn_course_catalog.dart +++ b/packages/campus/lib/src/learn_course_catalog.dart @@ -184,6 +184,10 @@ final class LearnCourseCatalogService { lastSource = LearnCourseSource.network; return catalog; } on Object catch (error) { + // Let the caller renew authentication before falling back to old data. + if (error is PortalSessionRejected || error is PortalCsrfUnavailable) { + rethrow; + } if (error is! Exception && error is! StateError) rethrow; if (cached == null || forceRefresh) rethrow; lastSource = LearnCourseSource.staleCache; diff --git a/packages/campus/lib/src/learn_courses.dart b/packages/campus/lib/src/learn_courses.dart index d9aa6f7..58eeb20 100644 --- a/packages/campus/lib/src/learn_courses.dart +++ b/packages/campus/lib/src/learn_courses.dart @@ -15,8 +15,44 @@ final class LearnPlatformSession { final TsinghuaAuthClient _authClient; - Future open() async { - final landing = await _authClient.roamToPortalApp(_LEARN_ROAMING_ID); + Future open() => run((csrf) async => csrf); + + /// A failed Learn session does not establish that the university login died. + /// Verify the main account, then re-roam Learn and retry the read once. + Future run(Future Function(String csrf) read) async { + try { + return await read(await _open()); + } on _LearnSessionExpired { + _authClient.trace?.call( + 'Learn session rejected; verifying the main session.', + ); + if (!await _authClient.validateSession()) { + throw const PortalSessionRejected(); + } + _authClient.trace?.call( + 'Main session verified; rebuilding Learn without a password.', + ); + try { + return await read(await _open()); + } on _LearnSessionExpired { + throw StateError( + 'The learning platform session could not be established.', + ); + } + } + } + + Future _open() async { + var landing = await _authClient.roamToPortalApp(_LEARN_ROAMING_ID); + if (landing.statusCode == 404) { + // Older roaming links can still point at the removed /student/index + // route. OneTHU checks the current course page to establish readiness. + landing = await _authClient.getAuthenticated( + TsinghuaWebVpnRedirect.forTarget( + Uri.https(_LEARN_HOST, '/f/wlxt/index/course/student/'), + ), + ); + } final body = landing.body; if (_isLearnSignInResponse( landing.statusCode, @@ -24,7 +60,7 @@ final class LearnPlatformSession { body, )) { _authClient.traceUnexpectedResponse('learning-landing', landing); - throw const PortalSessionRejected(); + throw const _LearnSessionExpired(); } if (landing.statusCode < 200 || landing.statusCode >= 300) { _authClient.traceUnexpectedResponse('learning-landing', landing); @@ -33,11 +69,16 @@ final class LearnPlatformSession { ); } + final document = html.parse(body); + final field = document.querySelector('input[name="_csrf"]'); final match = RegExp( - r"""_csrf=([\w-]+)|name=["']_csrf["'][^>]*value=["']([\w-]+)""", - caseSensitive: false, + r"""_csrf=([^&"'\s<>]+)|["']?_csrf["']?\s*[:=]\s*["']([^"'\s]+)["']|["']csrfToken["']\s*:\s*["']([^"']+)["']""", ).firstMatch(body); - final pageToken = match?.group(1) ?? match?.group(2); + final pageToken = + field?.attributes['value'] ?? + match?.group(1) ?? + match?.group(2) ?? + match?.group(3); if (pageToken != null && pageToken.isNotEmpty) return pageToken; // A successful roaming page can omit the token while setting the cookie. @@ -52,9 +93,7 @@ final class LearnPlatformSession { } } _authClient.traceUnexpectedResponse('learning-landing', landing); - throw const FormatException( - 'The learning platform did not return a CSRF token.', - ); + throw const _LearnSessionExpired(); } } @@ -80,61 +119,99 @@ final class LearnCourseService { if (session == null) { throw StateError('Restore an authenticated session first.'); } - final csrf = await LearnPlatformSession(_authClient).open(); - final target = - Uri.https(_LEARN_HOST, '$_LEARN_COURSES_PATH/$semesterId/zh', { - 'timestamp': '${(now ?? DateTime.now)().millisecondsSinceEpoch}', - '_csrf': csrf, - }); - final response = await _authClient.getAuthenticated( - TsinghuaWebVpnRedirect.forTarget(target), - ); - if (_isLearnSignInResponse( - response.statusCode, - response.request?.url, - response.body, - )) { - _authClient.traceUnexpectedResponse('learning-courses', response); - throw const PortalSessionRejected(); - } - if (response.statusCode != 200) { - _authClient.traceUnexpectedResponse('learning-courses', response); - throw StateError( - 'The learning platform returned HTTP ${response.statusCode}.', + return LearnPlatformSession(_authClient).run((csrf) async { + final target = + Uri.https(_LEARN_HOST, '$_LEARN_COURSES_PATH/$semesterId/zh', { + 'timestamp': '${(now ?? DateTime.now)().millisecondsSinceEpoch}', + '_csrf': csrf, + }); + final response = await _authClient.getAuthenticated( + TsinghuaWebVpnRedirect.forTarget(target), ); - } + if (_isLearnSignInResponse( + response.statusCode, + response.request?.url, + response.body, + )) { + _authClient.traceUnexpectedResponse('learning-courses', response); + throw const _LearnSessionExpired(); + } + if (response.statusCode != 200) { + _authClient.traceUnexpectedResponse('learning-courses', response); + throw StateError( + 'The learning platform returned HTTP ${response.statusCode}.', + ); + } - Object? decoded; - try { - decoded = jsonDecode(response.body); - } on FormatException { - _authClient.traceUnexpectedResponse('learning-courses', response); - throw const FormatException( - 'The learning platform did not return course-list JSON.', - ); - } - if (decoded is! Map || - decoded['message'] != 'success' || - decoded['resultList'] is! List || - (decoded['resultList'] as List).any((row) => row is! Map)) { - _authClient.traceUnexpectedResponse('learning-courses', response); - throw StateError( - 'The learning platform returned an unexpected course list.', - ); - } - if (decoded['currentUser'] != session.userId) { - throw StateError('The learning platform returned a different account.'); - } - return decoded; + Object? decoded; + try { + decoded = jsonDecode(response.body); + } on FormatException { + _authClient.traceUnexpectedResponse('learning-courses', response); + throw const FormatException( + 'The learning platform did not return course-list JSON.', + ); + } + if (decoded is! Map || + decoded['message'] != 'success' || + decoded['resultList'] is! List || + (decoded['resultList'] as List).any((row) => row is! Map)) { + _authClient.traceUnexpectedResponse('learning-courses', response); + throw StateError( + 'The learning platform returned an unexpected course list.', + ); + } + if (decoded['currentUser'] != session.userId) { + throw StateError('The learning platform returned a different account.'); + } + return decoded; + }); } } +final class _LearnSessionExpired implements Exception { + const _LearnSessionExpired(); +} + bool _isLearnSignInResponse(int statusCode, Uri? uri, String body) { - return statusCode == 401 || - statusCode == 403 || + if (statusCode == 401 || uri?.host == 'id.tsinghua.edu.cn' || (uri?.host == TsinghuaWebVpnRedirect.WEBVPN_HOST && uri?.path == '/login') || - uri?.path.startsWith('/wengine-vpn/failed') == true || - body.toLowerCase().contains('sm2publickey'); + uri?.path.endsWith('/f/login') == true) { + return true; + } + // Course JSON and gateway scripts can quote authentication markup without + // being a login page. A bare 403 is a service/permission failure, not logout. + try { + jsonDecode(body); + return false; + } on FormatException { + // Inspect actual HTML controls rather than document text or script strings. + } + final document = html.parse(body); + for (final node in document.querySelectorAll( + 'script, style, template, noscript', + )) { + node.remove(); + } + if (document.querySelector('#sm2publicKey, input[name="i_pass"]') != null) { + return true; + } + return document + .querySelectorAll('form') + .any( + (form) => + form.attributes['action']?.contains( + 'j_spring_security_check', + ) == + true, + ) || + document.querySelectorAll('a, form').any((node) { + final target = + node.attributes['href'] ?? node.attributes['action'] ?? ''; + return target.contains('/f/login') || + target.contains('/do/off/ui/auth/login/') || + target.contains('oauth.tsinghua.edu.cn/thu-oauth/auth'); + }); } diff --git a/packages/campus/lib/src/learn_homework.dart b/packages/campus/lib/src/learn_homework.dart index b0c3e3b..b113aed 100644 --- a/packages/campus/lib/src/learn_homework.dart +++ b/packages/campus/lib/src/learn_homework.dart @@ -96,52 +96,53 @@ final class LearnHomeworkService { if (catalog.courses.isEmpty) { return LearnHomeworkSnapshot(counts: counts, assignments: assignments); } - final csrf = await LearnPlatformSession(_authClient).open(); - for (final course in catalog.courses) { - var data = await _fetchData(course.id, endpoint, csrf); - var total = _readTotal(data); - if (total > 5) { - data = await _fetchData(course.id, endpoint, csrf, size: total); - total = _readTotal(data); - } - final rows = data['aaData']; - if (rows is! List || rows.length != total) { - throw const FormatException( - 'Learn returned an incomplete homework list.', - ); - } - final ids = {}; - for (final row in rows) { - if (row is! Map || - (row['wlkcid'] != null && row['wlkcid'] != course.id) || - (row['xh'] != null && row['xh'] != catalog.userId)) { + return LearnPlatformSession(_authClient).run((csrf) async { + for (final course in catalog.courses) { + var data = await _fetchData(course.id, endpoint, csrf); + var total = _readTotal(data); + if (total > 5) { + data = await _fetchData(course.id, endpoint, csrf, size: total); + total = _readTotal(data); + } + final rows = data['aaData']; + if (rows is! List || rows.length != total) { throw const FormatException( - 'Learn returned homework for another course or account.', + 'Learn returned an incomplete homework list.', ); } - final id = row['xszyid'] ?? row['zyid']; - final title = row['bt']; - if (id is! String || - id.isEmpty || - !ids.add(id) || - title is! String || - title.trim().isEmpty) { - throw const FormatException( - 'Learn returned invalid homework details.', + final ids = {}; + for (final row in rows) { + if (row is! Map || + (row['wlkcid'] != null && row['wlkcid'] != course.id) || + (row['xh'] != null && row['xh'] != catalog.userId)) { + throw const FormatException( + 'Learn returned homework for another course or account.', + ); + } + final id = row['xszyid'] ?? row['zyid']; + final title = row['bt']; + if (id is! String || + id.isEmpty || + !ids.add(id) || + title is! String || + title.trim().isEmpty) { + throw const FormatException( + 'Learn returned invalid homework details.', + ); + } + assignments.add( + LearnHomework( + id: id, + course: course, + title: title, + deadline: _homeworkDeadline(row), + ), ); } - assignments.add( - LearnHomework( - id: id, - course: course, - title: title, - deadline: _homeworkDeadline(row), - ), - ); + counts[course.id] = total; } - counts[course.id] = total; - } - return LearnHomeworkSnapshot(counts: counts, assignments: assignments); + return LearnHomeworkSnapshot(counts: counts, assignments: assignments); + }); } /// Fetches only Wj totals for course reminders, without graded-list requests. @@ -150,12 +151,13 @@ final class LearnHomeworkService { ) async { _validateCatalog(catalog); if (catalog.courses.isEmpty) return const {}; - final csrf = await LearnPlatformSession(_authClient).open(); - final counts = {}; - for (final course in catalog.courses) { - counts[course.id] = await _fetchCount(course.id, 'zyListWj', csrf); - } - return Map.unmodifiable(counts); + return LearnPlatformSession(_authClient).run((csrf) async { + final counts = {}; + for (final course in catalog.courses) { + counts[course.id] = await _fetchCount(course.id, 'zyListWj', csrf); + } + return Map.unmodifiable(counts); + }); } Future> fetchCourses( @@ -163,26 +165,27 @@ final class LearnHomeworkService { ) async { _validateCatalog(catalog); if (catalog.courses.isEmpty) return const []; - final csrf = await LearnPlatformSession(_authClient).open(); - final result = []; - // Keep requests sequential to avoid overwhelming Learn or racing its - // shared authentication cookies. One roaming session serves all courses. - for (final course in catalog.courses) { - final unsubmitted = await _fetchCount(course.id, 'zyListWj', csrf); - final submitted = await _fetchCount(course.id, 'zyListYjwg', csrf); - final graded = await _fetchCount(course.id, 'zyListYpg', csrf); - result.add( - LearnCourseHomework( - course: course, - counts: LearnHomeworkCounts( - unsubmitted: unsubmitted, - submittedUngraded: submitted, - graded: graded, + return LearnPlatformSession(_authClient).run((csrf) async { + final result = []; + // Keep requests sequential to avoid overwhelming Learn or racing its + // shared authentication cookies. One roaming session serves all courses. + for (final course in catalog.courses) { + final unsubmitted = await _fetchCount(course.id, 'zyListWj', csrf); + final submitted = await _fetchCount(course.id, 'zyListYjwg', csrf); + final graded = await _fetchCount(course.id, 'zyListYpg', csrf); + result.add( + LearnCourseHomework( + course: course, + counts: LearnHomeworkCounts( + unsubmitted: unsubmitted, + submittedUngraded: submitted, + graded: graded, + ), ), - ), - ); - } - return result; + ); + } + return result; + }); } void _validateCatalog(LearnCourseCatalog catalog) { @@ -225,7 +228,7 @@ final class LearnHomeworkService { response.body, )) { _authClient.traceUnexpectedResponse('learning-homework', response); - throw const PortalSessionRejected(); + throw const _LearnSessionExpired(); } if (response.statusCode != 200) { throw StateError( diff --git a/packages/campus/lib/src/learn_materials.dart b/packages/campus/lib/src/learn_materials.dart index d01ce5a..b63621b 100644 --- a/packages/campus/lib/src/learn_materials.dart +++ b/packages/campus/lib/src/learn_materials.dart @@ -99,20 +99,21 @@ final class LearnMaterialService { throw const FormatException('A course has no learning platform ID.'); } if (courses.isEmpty) return const []; - final csrf = await LearnPlatformSession(_authClient).open(); - final result = []; - // One shared roaming session; sequential requests preserve existing Learn - // authentication behavior and avoid sending a burst for the whole semester. - for (final course in courses) { - result.add( - LearnCourseMaterials( - course: course, - requestedLimit: size, - materials: await _fetch(course.id, size, csrf), - ), - ); - } - return List.unmodifiable(result); + return LearnPlatformSession(_authClient).run((csrf) async { + final result = []; + // One shared roaming session; sequential requests preserve existing Learn + // authentication behavior and avoid sending a burst for the whole semester. + for (final course in courses) { + result.add( + LearnCourseMaterials( + course: course, + requestedLimit: size, + materials: await _fetch(course.id, size, csrf), + ), + ); + } + return List.unmodifiable(result); + }); } /// Downloads all pages of the PDF representation. @@ -138,69 +139,69 @@ final class LearnMaterialService { 'File and course IDs must contain only letters, numbers, underscores or hyphens.', ); } - await LearnPlatformSession(_authClient).open(); - final target = Uri( - scheme: 'https', - host: _LEARN_HOST, - pathSegments: [ - 'f', - 'wlxt', - 'kc', - 'wj_wjb', - 'student', - 'downloadPdfStream', - pageType, - fileId, - courseId, - 'mk_kcwj', - ], - ); - final referer = Uri.https( - _LEARN_HOST, - '/f/wlxt/kc/wj_wjb/student/beforePlay', - { - 'sfgk': '0', - 'wjid': fileId, - 'mk': 'mk_kcwj', - 'pageType': pageType, - 'browser': '-1', - }, - ); - final response = await _authClient.getAuthenticatedBytes( - TsinghuaWebVpnRedirect.forTarget(target), - referer: TsinghuaWebVpnRedirect.forTarget(referer), - ); - final bytes = response.bodyBytes; - final signature = latin1.decode(bytes.take(1024).toList()); - final contentType = response.headers['content-type']?.toLowerCase() ?? ''; - final isPdf = - RegExp(r'%PDF-[12]\.\d').hasMatch(signature) && - !contentType.startsWith('text/html') && - !contentType.contains('json'); - final preview = utf8.decode( - bytes.take(4096).toList(), - allowMalformed: true, - ); - if (_isLearnSignInResponse( - response.statusCode, - response.request?.url, - isPdf ? '' : preview, - )) { - // Do not log response previews here: a successful binary response may - // contain private course content rather than an authentication page. - throw const PortalSessionRejected(); - } - if (response.statusCode != 200) { - throw StateError( - 'Material download failed: HTTP ${response.statusCode}.', + return LearnPlatformSession(_authClient).run((csrf) async { + final target = Uri( + scheme: 'https', + host: _LEARN_HOST, + pathSegments: [ + 'f', + 'wlxt', + 'kc', + 'wj_wjb', + 'student', + 'downloadPdfStream', + pageType, + fileId, + courseId, + 'mk_kcwj', + ], + queryParameters: {'_csrf': csrf}, ); - } - if (!isPdf) { - throw const FormatException( - 'Learn did not return a PDF. The file may not support PDF preview or the session may have expired.', + final referer = + Uri.https(_LEARN_HOST, '/f/wlxt/kc/wj_wjb/student/beforePlay', { + 'sfgk': '0', + 'wjid': fileId, + 'mk': 'mk_kcwj', + 'pageType': pageType, + 'browser': '-1', + '_csrf': csrf, + }); + final response = await _authClient.getAuthenticatedBytes( + TsinghuaWebVpnRedirect.forTarget(target), + referer: TsinghuaWebVpnRedirect.forTarget(referer), ); - } - return bytes; + final bytes = response.bodyBytes; + final signature = latin1.decode(bytes.take(1024).toList()); + final contentType = response.headers['content-type']?.toLowerCase() ?? ''; + final isPdf = + RegExp(r'%PDF-[12]\.\d').hasMatch(signature) && + !contentType.startsWith('text/html') && + !contentType.contains('json'); + final preview = utf8.decode( + bytes.take(4096).toList(), + allowMalformed: true, + ); + if (_isLearnSignInResponse( + response.statusCode, + response.request?.url, + isPdf ? '' : preview, + )) { + // Do not log response previews here: a successful binary response may + // contain private course content rather than an authentication page. + throw const _LearnSessionExpired(); + } + if (response.statusCode != 200) { + throw StateError( + 'Material download failed: HTTP ${response.statusCode}.', + ); + } + if (!isPdf) { + throw const FormatException( + 'Learn did not return a PDF. The file may not support PDF preview or the session may have expired.', + ); + } + return bytes; + }); } Future> _fetch( @@ -222,7 +223,7 @@ final class LearnMaterialService { response.body, )) { _authClient.traceUnexpectedResponse('learning-materials', response); - throw const PortalSessionRejected(); + throw const _LearnSessionExpired(); } if (response.statusCode != 200) { throw StateError( diff --git a/packages/campus/lib/thulium_campus.dart b/packages/campus/lib/thulium_campus.dart index 35809c6..9f43194 100644 --- a/packages/campus/lib/thulium_campus.dart +++ b/packages/campus/lib/thulium_campus.dart @@ -3,6 +3,7 @@ library; import 'dart:convert'; import 'dart:io'; +import 'package:html/parser.dart' as html; import 'package:thulium_auth/thulium_auth.dart'; part 'src/course_schedule.dart'; diff --git a/packages/campus/pubspec.lock b/packages/campus/pubspec.lock index f515e28..76b84ff 100644 --- a/packages/campus/pubspec.lock +++ b/packages/campus/pubspec.lock @@ -130,7 +130,7 @@ packages: source: hosted version: "2.2.0" html: - dependency: transitive + dependency: "direct main" description: name: html sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" diff --git a/packages/campus/pubspec.yaml b/packages/campus/pubspec.yaml index 536ee0e..bf30d0b 100644 --- a/packages/campus/pubspec.yaml +++ b/packages/campus/pubspec.yaml @@ -7,6 +7,7 @@ environment: sdk: ^3.12.2 dependencies: + html: ^0.15.7 http: ^1.4.0 thulium_auth: path: ../auth diff --git a/packages/campus/test/course_schedule_test.dart b/packages/campus/test/course_schedule_test.dart index 755c3fc..cdf8651 100644 --- a/packages/campus/test/course_schedule_test.dart +++ b/packages/campus/test/course_schedule_test.dart @@ -322,10 +322,7 @@ void main() { final store = MemoryAuthSessionStore(); final session = _testSession(isGraduate: true); await store.write(session); - final transport = _ScheduleHttpClient( - isGraduate: true, - emptyCookieBody: true, - ); + final transport = _ScheduleHttpClient(isGraduate: true, offline: true); final cache = CourseScheduleCache(_MemoryCacheStore()); final fetchedAt = DateTime.utc(2026, 9, 25, 10); await cache.writeFor(session.userId, _cachedSchedule(), fetchedAt); @@ -345,6 +342,36 @@ void main() { expect(transport.requestedUris, isNotEmpty); }); + test('stale calendar cache does not suppress credential recovery', () async { + final store = MemoryAuthSessionStore(); + final session = _testSession(isGraduate: true); + await store.write(session); + final transport = _ScheduleHttpClient( + isGraduate: true, + emptyCookieBody: true, + ); + final cache = CourseScheduleCache(_MemoryCacheStore()); + final fetchedAt = DateTime.utc(2026, 9, 25, 10); + await cache.writeFor(session.userId, _cachedSchedule(), fetchedAt); + final service = CourseScheduleService( + TsinghuaAuthClient(httpClient: transport, sessionStore: store), + cache: cache, + now: () => fetchedAt.add(const Duration(days: 2)), + ); + await expectLater( + service.loadCurrentTerm(), + throwsA( + isA().having( + (error) => error.cause, + 'cause', + isA(), + ), + ), + ); + expect(service.lastSource, isNull); + expect(await cache.readFor(session.userId), isNotNull); + }); + test('ignores corrupt schedule cache data', () async { final store = _MemoryCacheStore()..value = 'not-base64'; expect(await CourseScheduleCache(store).readFor('2024222050'), isNull); @@ -574,6 +601,7 @@ final class _ScheduleHttpClient extends http.BaseClient { this.malformedPrimary = false, this.invalidUserData = false, this.emptyCookieBody = false, + this.offline = false, }); final bool isGraduate; @@ -581,6 +609,7 @@ final class _ScheduleHttpClient extends http.BaseClient { final bool malformedPrimary; final bool invalidUserData; final bool emptyCookieBody; + final bool offline; final requestedUris = []; final requestCookieHeaders = {}; @@ -588,6 +617,7 @@ final class _ScheduleHttpClient extends http.BaseClient { Future send(http.BaseRequest request) async { final uri = request.url; requestedUris.add(uri); + if (offline) throw http.ClientException('offline'); requestCookieHeaders[uri] = request.headers['cookie']; final body = switch (uri.path) { '/wengine-vpn/cookie' => diff --git a/packages/campus/test/learn_courses_test.dart b/packages/campus/test/learn_courses_test.dart index c0d3620..dabe40e 100644 --- a/packages/campus/test/learn_courses_test.dart +++ b/packages/campus/test/learn_courses_test.dart @@ -56,6 +56,47 @@ void main() { expect(transport.courseRequest!.url.queryParameters['_csrf'], 'learn-csrf'); }); + for (final csrfUnavailable in [false, true]) { + test( + 'stale course cache propagates ${csrfUnavailable ? 'CSRF' : 'sign-in'} failures for recovery', + () async { + final transport = _LearnHttpClient(); + final store = MemoryAuthSessionStore(); + await store.write(_session); + final auth = TsinghuaAuthClient( + httpClient: transport, + sessionStore: store, + ); + await auth.restore(); + final cache = LearnCourseCache(_LearnCacheStore()); + final fetchedAt = DateTime(2026, 9, 28); + await LearnCourseCatalogService( + auth, + cache: cache, + now: () => fetchedAt, + ).loadSemester('2026-2027-1'); + transport.courseStatusCode = 401; + transport.mainExpired = true; + transport.cookieUnavailable = csrfUnavailable; + final service = LearnCourseCatalogService( + auth, + cache: cache, + now: () => fetchedAt.add(const Duration(days: 2)), + ); + await expectLater( + service.loadSemester('2026-2027-1'), + throwsA( + csrfUnavailable + ? isA() + : isA(), + ), + ); + expect(service.lastSource, isNull); + expect(await cache.readFor(_session.userId, '2026-2027-1'), isNotNull); + }, + ); + } + test('rejects unsafe semester paths before making a request', () async { final transport = _LearnHttpClient(); final auth = TsinghuaAuthClient(httpClient: transport); @@ -80,7 +121,8 @@ void main() { }); test('reports an authentication response as a reconnectable error', () async { - final transport = _LearnHttpClient(courseStatusCode: 401); + final transport = _LearnHttpClient(courseStatusCode: 401) + ..mainExpired = true; final store = MemoryAuthSessionStore(); await store.write(_session); final auth = TsinghuaAuthClient(httpClient: transport, sessionStore: store); @@ -193,18 +235,27 @@ final class _LearnHttpClient extends http.BaseClient { final bool omitPageCsrf; final String currentUser; int courseStatusCode; + bool cookieUnavailable = false; + bool mainExpired = false; http.BaseRequest? courseRequest; int courseRequestCount = 0; @override Future send(http.BaseRequest request) async { final path = request.url.path; + if (path.endsWith('/grjbxx')) { + return http.StreamedResponse( + Stream.value(utf8.encode('{"object":{"ryh":"2024012050"}}')), + mainExpired ? 401 : 200, + request: request, + ); + } late final String body; final headers = { 'content-type': 'text/html; charset=utf-8', }; if (path == '/wengine-vpn/cookie') { - body = 'XSRF-TOKEN=portal-csrf; Path=/;'; + body = cookieUnavailable ? '' : 'XSRF-TOKEN=portal-csrf; Path=/;'; } else if (path.endsWith('onlineAppRedirect')) { body = jsonEncode({ 'object': { diff --git a/packages/campus/test/learn_materials_test.dart b/packages/campus/test/learn_materials_test.dart index 9ceeabe..1aa2da0 100644 --- a/packages/campus/test/learn_materials_test.dart +++ b/packages/campus/test/learn_materials_test.dart @@ -25,6 +25,7 @@ void main() { ), ); expect(request.url.host, TsinghuaWebVpnRedirect.WEBVPN_HOST); + expect(request.url.queryParameters['_csrf'], 'learn-csrf'); final referer = Uri.parse(request.headers['referer']!); expect(referer.path, endsWith('/f/wlxt/kc/wj_wjb/student/beforePlay')); expect(referer.queryParameters, { @@ -33,6 +34,7 @@ void main() { 'mk': 'mk_kcwj', 'pageType': 'all', 'browser': '-1', + '_csrf': 'learn-csrf', }); expect(request.headers['cookie'], contains('JSESSIONID=learn-session')); return http.Response.bytes( @@ -86,11 +88,12 @@ void main() { for (final status in [200, 401, 403]) { final auth = await _auth( (request) => http.Response( - 'sm2publickey', + '', status, headers: {'content-type': 'text/html'}, request: request, ), + mainExpired: true, ); await expectLater( LearnMaterialService( @@ -278,17 +281,19 @@ void main() { for (final status in [401, 403, 500]) { final auth = await _auth( (request) => http.Response('', status, request: request), + mainExpired: true, ); await expectLater( LearnMaterialService(auth).fetchCourses(_catalog), - status == 500 + status != 401 ? throwsStateError : throwsA(isA()), ); } final auth = await _auth( (request) => - http.Response('sm2publickey', 200, request: request), + http.Response('', 200, request: request), + mainExpired: true, ); await expectLater( LearnMaterialService(auth).fetchCourses(_catalog), @@ -403,8 +408,18 @@ final _catalog = LearnCourseCatalog( Future _auth( http.Response Function(http.Request) respond, { void Function()? onLanding, + bool mainExpired = false, }) async { final transport = MockClient((request) async { + if (request.url.path.endsWith('/grjbxx')) { + return http.Response( + jsonEncode({ + 'object': {'ryh': 'student'}, + }), + mainExpired ? 401 : 200, + request: request, + ); + } if (request.url.path == '/wengine-vpn/cookie') { return http.Response( 'XSRF-TOKEN=portal-csrf; Path=/;', diff --git a/packages/campus/test/learn_session_recovery_test.dart b/packages/campus/test/learn_session_recovery_test.dart new file mode 100644 index 0000000..1cbc674 --- /dev/null +++ b/packages/campus/test/learn_session_recovery_test.dart @@ -0,0 +1,356 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:test/test.dart'; +import 'package:thulium_auth/thulium_auth.dart'; +import 'package:thulium_campus/thulium_campus.dart'; + +void main() { + test( + 'obsolete roaming landing falls back to the current Learn page without relogin', + () async { + final fixture = _Fixture()..obsoleteLanding = true; + expect(await fixture.courses(), isNotEmpty); + expect(fixture.landings, 2); + expect(fixture.accountProbes, 0); + expect(fixture.store.credentialReads, 0); + }, + ); + test( + 'material-list permission failure leaves the main account and other services usable', + () async { + final fixture = _Fixture()..materialStatus = 403; + await expectLater(fixture.materials(), throwsStateError); + expect(await fixture.courses(), isNotEmpty); + expect((await fixture.homework()).counts, {'course': 0}); + fixture.materialStatus = 200; + expect((await fixture.materials()).single.materials, hasLength(1)); + expect(fixture.credentialPosts, 0); + expect(fixture.store.credentialReads, 0); + expect(fixture.store.clears, 0); + }, + ); + + test( + 'queued file reads reuse the repaired session without a second password login', + () async { + final fixture = _Fixture()..firstFileLoginPage = ''; + final results = await Future.wait([ + fixture.download(), + fixture.download(), + ]); + expect(results, hasLength(2)); + expect(fixture.fileRequests, 3); + expect(fixture.accountProbes, 1); + expect(fixture.store.credentialReads, 0); + }, + ); + + for (final status in [403, 404, 500]) { + test( + 'file HTTP $status does not relogin or break subsequent courses', + () async { + final fixture = _Fixture()..fileStatus = status; + await expectLater(fixture.download(), throwsStateError); + expect(await fixture.courses(), isNotEmpty); + expect((await fixture.homework()).counts, {'course': 0}); + expect(fixture.store.credentialReads, 0); + expect(fixture.credentialPosts, 0); + expect(fixture.store.clears, 0); + expect(fixture.store.session!.fingerGenPrint, 'trusted-token'); + }, + ); + } + + for (final loginPage in [ + '
', + '重新登录', + 'key', + ]) { + test( + 'expired file response repairs Learn before retrying the download: $loginPage', + () async { + final fixture = _Fixture()..firstFileLoginPage = loginPage; + expect(await fixture.download(), utf8.encode('%PDF-1.7\n%%EOF')); + expect(fixture.fileRequests, 2); + expect(fixture.landings, 2); + expect(fixture.accountProbes, 1); + expect(fixture.store.credentialReads, 0); + expect(fixture.store.clears, 0); + }, + ); + } + + test( + 'persistent Learn rejection preserves main login and stops after one retry', + () async { + final fixture = _Fixture()..fileStatus = 401; + await expectLater(fixture.download(), throwsStateError); + expect(fixture.fileRequests, 2); + expect(fixture.credentialPosts, 0); + expect(fixture.store.credentialReads, 0); + expect(fixture.store.clears, 0); + expect(await fixture.courses(), isNotEmpty); + }, + ); + + for (final jsonRejection in [false, true]) { + test( + 'confirmed main expiry after a file error uses saved password and retries (JSON: $jsonRejection)', + () async { + final fixture = _Fixture() + ..mainExpired = true + ..jsonRejection = jsonRejection; + expect(await fixture.download(), utf8.encode('%PDF-1.7\n%%EOF')); + expect(fixture.fileRequests, 2); + expect(fixture.store.credentialReads, 1); + expect(fixture.credentialPosts, 2); // WebVPN then information portal. + expect(fixture.store.session!.fingerGenPrint, 'trusted-token'); + expect(await fixture.courses(), isNotEmpty); + }, + ); + } + + for (final tokenMarkup in [ + '', + '', + '', + ]) { + test( + 'Learn readiness accepts the reference token encoding: $tokenMarkup', + () async { + final fixture = _Fixture()..landingMarkup = tokenMarkup; + expect(await fixture.courses(), isNotEmpty); + expect(fixture.store.credentialReads, 0); + expect(fixture.accountProbes, 0); + }, + ); + } + + test( + 'gateway script and course text quoting login markup do not cause relogin', + () async { + final fixture = _Fixture() + ..landingMarkup = + '' + ..quoteLoginMarkup = true; + expect(await fixture.courses(), isNotEmpty); + expect( + (await fixture.materials()).single.materials.single.title, + '', + ); + expect(fixture.accountProbes, 0); + expect(fixture.store.credentialReads, 0); + }, + ); +} + +final _catalog = LearnCourseCatalog( + userId: '1234567890', + semester: '2026-2027-1', + courses: const [ + LearnCourse( + id: 'course', + name: 'Course', + englishName: '', + teacherName: '', + schedule: '', + ), + ], +); + +final class _Fixture { + final store = _Store(); + int fileStatus = 200; + int materialStatus = 200; + bool mainExpired = false; + bool jsonRejection = false; + bool quoteLoginMarkup = false; + bool obsoleteLanding = false; + String? firstFileLoginPage; + String landingMarkup = ''; + int fileRequests = 0; + int landings = 0; + int accountProbes = 0; + int credentialPosts = 0; + bool _signedIn = false; + late final transport = MockClient(_respond); + + AuthSessionRunner get runner => AuthSessionRunner( + store, + createClient: () => TsinghuaAuthClient( + httpClient: transport, + sessionStore: store, + credentialStore: store, + ), + ); + + Future> download() => runner.run( + request: (client, _) => LearnMaterialService( + client, + ).downloadPdf(fileId: 'file', courseId: 'course'), + ); + + Future> courses() => runner.run( + request: (client, _) => + LearnCourseService(client).fetchSemester('2026-2027-1'), + ); + + Future homework() => runner.run( + request: (client, _) => + LearnHomeworkService(client).fetchUnsubmittedHomework(_catalog), + ); + + Future> materials() => runner.run( + request: (client, _) => LearnMaterialService(client).fetchCourses(_catalog), + ); + + Future _respond(http.Request request) async { + final path = request.url.path; + http.Response reply(String body, [int status = 200]) => http.Response( + body, + status, + headers: {'content-type': 'text/html; charset=utf-8'}, + request: request, + ); + if (path == '/wengine-vpn/cookie') { + return reply('XSRF-TOKEN=portal-csrf; JSESSIONID=portal;'); + } + if (path.endsWith('/grjbxx')) { + accountProbes++; + if (mainExpired && !_signedIn && jsonRejection) { + return reply('{"code":401,"message":"login required"}'); + } + return reply( + '{"object":{"ryh":"1234567890"}}', + mainExpired && !_signedIn ? 401 : 200, + ); + } + if (path.endsWith('onlineAppRedirect')) { + return reply( + jsonEncode({ + 'object': { + 'roamingurl': obsoleteLanding + ? 'https://learn.tsinghua.edu.cn/f/wlxt/index/course/student/index' + : 'https://learn.tsinghua.edu.cn/f/wlxt/index/course/student/', + }, + }), + ); + } + if (path.endsWith('/f/wlxt/index/course/student/')) { + landings++; + return reply(landingMarkup); + } + if (path.endsWith('/f/wlxt/index/course/student/index')) { + landings++; + return reply('Page not found', 404); + } + if (path.contains('/downloadPdfStream/')) { + expect(request.url.queryParameters['_csrf'], 'learn-csrf'); + fileRequests++; + if (mainExpired && !_signedIn) return reply('', 401); + if (fileRequests == 1 && firstFileLoginPage != null) { + return reply(firstFileLoginPage!); + } + return http.Response.bytes( + utf8.encode('%PDF-1.7\n%%EOF'), + fileStatus, + headers: {'content-type': 'application/pdf'}, + request: request, + ); + } + if (path.contains('loadCourseBySemesterId')) { + expect(request.url.queryParameters['_csrf'], 'learn-csrf'); + return reply( + jsonEncode({ + 'currentUser': '1234567890', + 'message': 'success', + 'resultList': [ + { + 'kcm': quoteLoginMarkup ? '' : 'Course', + 'wlkcid': 'course', + }, + ], + }), + ); + } + if (path.endsWith('/kjxxbByWlkcidAndSizeForStudent')) { + return reply( + jsonEncode({ + 'result': 'success', + 'object': [ + { + 'kjxxid': 'material', + 'wlkcid': 'course', + 'wjid': 'file', + 'bt': quoteLoginMarkup ? '' : 'File', + }, + ], + }), + materialStatus, + ); + } + if (path.endsWith('/zyListWj')) { + return reply( + '{"result":"success","object":{"iTotalRecords":0,"aaData":[]}}', + ); + } + // The SM2 curve generator is a valid synthetic public key; no real key or + // account is used by this end-to-end credential recovery fixture. + const publicKey = + '0432c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7' + 'bc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0'; + if (path == '/login' || path.startsWith('/do/off/ui/auth/login/form/')) { + return reply('$publicKey'); + } + if (path == '/do/off/ui/auth/login/check') { + credentialPosts++; + expect(request.bodyFields['i_user'], '1234567890'); + expect(request.bodyFields['fingerGenPrint'], 'trusted-token'); + _signedIn = true; + return reply( + '登录成功。正在重定向到', + ); + } + if (path == '/callback' || path == '/lb-auth/lbredirect') return reply(''); + throw StateError('Unexpected synthetic request: $path'); + } +} + +final class _Store implements AuthSessionStore, AuthCredentialStore { + AuthSession? session = const AuthSession( + userId: '1234567890', + fingerprint: 'device', + cookies: {}, + trustedBrowser: true, + fingerGenPrint: 'trusted-token', + ); + int credentialReads = 0; + int clears = 0; + AuthCredentials credentials = const AuthCredentials( + userId: '1234567890', + password: 'synthetic-password', + ); + @override + Future read() async => session; + @override + Future write(AuthSession value) async => session = value; + @override + Future clear() async { + clears++; + session = null; + } + + @override + Future readCredentials() async { + credentialReads++; + return credentials; + } + + @override + Future writeCredentials(AuthCredentials value) async => + credentials = value; + @override + Future clearCredentials() async {} +} diff --git a/test/widget/auth/login_page_test.dart b/test/widget/auth/login_page_test.dart new file mode 100644 index 0000000..b9c9103 --- /dev/null +++ b/test/widget/auth/login_page_test.dart @@ -0,0 +1,239 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:forui/forui.dart'; +import 'package:thulium/l10n/generated/app_localizations.dart'; +import 'package:thulium/pages/login_page.dart'; +import 'package:thulium_auth/thulium_auth.dart'; + +import '../../../packages/auth/test/support/fake_auth_http_client.dart'; + +class _Dialogs extends NavigatorObserver { + int opened = 0; + @override + void didPush(Route route, Route? previousRoute) { + if (route is FDialogRoute) opened++; + } +} + +void main() { + setUp(() => FlutterSecureStorage.setMockInitialValues({})); + + // Login deliberately keeps an indeterminate progress indicator alive while + // a dialog waits for input, so bounded frame pumps replace pumpAndSettle. + Future tick(WidgetTester tester) async { + for (var i = 0; i < 8; i++) { + await tester.pump(const Duration(milliseconds: 50)); + } + } + + Future show( + WidgetTester tester, + FakeAuthHttpClient transport, + _Dialogs dialogs, { + VoidCallback? success, + bool repeatTrustCallback = false, + }) async { + final theme = FThemes.neutral.dark.touch; + await tester.pumpWidget( + MaterialApp( + localizationsDelegates: [ + ...AppLocalizations.localizationsDelegates, + ...FLocalizations.localizationsDelegates, + ], + supportedLocales: AppLocalizations.supportedLocales, + theme: theme.toApproximateMaterialTheme(), + navigatorObservers: [dialogs], + builder: (_, child) => FTheme(data: theme, child: child!), + home: LoginPage( + onLoginSuccess: success ?? () {}, + authClientBuilder: + ({ + required sessionStore, + required credentialStore, + required twoFactorMethodHandler, + required twoFactorCodeHandler, + required twoFactorTrustHandler, + required trace, + }) => TsinghuaAuthClient( + httpClient: transport, + sessionStore: sessionStore, + credentialStore: credentialStore, + twoFactorMethodHandler: twoFactorMethodHandler, + twoFactorCodeHandler: twoFactorCodeHandler, + twoFactorTrustHandler: () async { + final choice = await twoFactorTrustHandler(); + if (repeatTrustCallback) { + expect(await twoFactorTrustHandler(), choice); + } + return choice; + }, + trace: trace, + ), + ), + ), + ); + await tick(tester); + await tester.enterText(find.byType(EditableText).first, '1234567890'); + await tester.enterText(find.byType(EditableText).last, 'password'); + } + + Future verify(WidgetTester tester) async { + await tester.tap(find.text('Trust device')); + await tick(tester); + await tester.tap(find.text('WeChat')); + await tick(tester); + await tester.enterText(find.byType(EditableText).last, '123456'); + // The fixture deliberately rejects the first submitted code. + await tester.tap(find.text('Confirm')); + await tick(tester); + await tester.tap(find.text('Confirm')); + await tick(tester); + } + + testWidgets( + 'button plus keyboard submission does not restart trust after a verified login fails', + (tester) async { + final transport = FakeAuthHttpClient(failInformationRedirect: true); + final dialogs = _Dialogs(); + await show(tester, transport, dialogs); + final button = tester.widget( + find.widgetWithText(FButton, 'Sign in'), + ); + final password = tester.widget( + find.byType(EditableText).last, + ); + // Both callbacks can be dispatched before the disabled button is rebuilt. + button.onPress!(); + password.onSubmitted!('password'); + await tick(tester); + await verify(tester); + expect(find.text('Trust this device?'), findsNothing); + expect(find.textContaining('Sign-in failed'), findsOneWidget); + expect(dialogs.opened, 3); // trust, method, code + expect( + transport.requests.where((r) => r.url.path == '/login'), + hasLength(1), + ); + }, + // Flutter 3.47 + Forui form semantics currently assert in the framework. + // This test exercises callback/routing behavior, not accessibility output. + semanticsEnabled: false, + ); + + testWidgets('a successful two-stage login asks for trust only once', ( + tester, + ) async { + final transport = FakeAuthHttpClient( + trustedPortalForm: true, + trustWithoutToken: true, + ); + final dialogs = _Dialogs(); + var successes = 0; + await show(tester, transport, dialogs, success: () => successes++); + await tester.tap(find.text('Sign in')); + await tick(tester); + await verify(tester); + expect(successes, 1); + expect(dialogs.opened, 3); + expect(find.text('Trust this device?'), findsNothing); + expect( + transport.requests.where( + (r) => r.url.path == '/do/off/ui/auth/login/checkSingle', + ), + hasLength(1), + ); + }, semanticsEnabled: false); + testWidgets('repeated trust callbacks reuse the choice within one attempt', ( + tester, + ) async { + final transport = FakeAuthHttpClient( + trustedPortalForm: true, + trustWithoutToken: true, + ); + final dialogs = _Dialogs(); + var successes = 0; + await show( + tester, + transport, + dialogs, + success: () => successes++, + repeatTrustCallback: true, + ); + await tester.tap(find.text('Sign in')); + await tick(tester); + await verify(tester); + expect(successes, 1); + expect(dialogs.opened, 3); + }, semanticsEnabled: false); + + testWidgets('repeated trust and method taps cannot pop the following route', ( + tester, + ) async { + final transport = FakeAuthHttpClient( + trustedPortalForm: true, + trustWithoutToken: true, + ); + final dialogs = _Dialogs(); + var successes = 0; + await show(tester, transport, dialogs, success: () => successes++); + await tester.tap(find.text('Sign in')); + await tick(tester); + final trust = tester + .widget(find.widgetWithText(FButton, 'Trust device')) + .onPress!; + trust(); + trust(); + await tick(tester); + final method = tester + .widget(find.widgetWithText(FButton, 'WeChat')) + .onPress!; + method(); + method(); + await tick(tester); + expect(find.text('Verification code'), findsOneWidget); + await tester.enterText(find.byType(EditableText).last, '123456'); + await tester.tap(find.text('Confirm')); + await tick(tester); + await tester.tap(find.text('Confirm')); + await tick(tester); + expect(successes, 1); + expect(dialogs.opened, 3); + }, semanticsEnabled: false); + + testWidgets( + 'repeated verification callbacks send only one in-flight request', + (tester) async { + final transport = FakeAuthHttpClient( + trustedPortalForm: true, + trustWithoutToken: true, + ); + final dialogs = _Dialogs(); + var successes = 0; + await show(tester, transport, dialogs, success: () => successes++); + await tester.tap(find.text('Sign in')); + await tick(tester); + await tester.tap(find.text('Trust device')); + await tick(tester); + await tester.tap(find.text('WeChat')); + await tick(tester); + await tester.enterText(find.byType(EditableText).last, '123456'); + final confirm = tester + .widget(find.widgetWithText(FButton, 'Confirm')) + .onPress!; + confirm(); + confirm(); + await tick(tester); + expect( + find.text('That code was not accepted. Please try again'), + findsOneWidget, + ); + await tester.tap(find.text('Confirm')); + await tick(tester); + expect(successes, 1); + // Two requests total: one rejected code and one deliberate retry. + expect(transport.verificationRequestCount, 2); + }, + semanticsEnabled: false, + ); +} diff --git a/test/widget/study/course_detail_page_test.dart b/test/widget/study/course_detail_page_test.dart index 672cdbe..20d49e6 100644 --- a/test/widget/study/course_detail_page_test.dart +++ b/test/widget/study/course_detail_page_test.dart @@ -35,11 +35,13 @@ class FakeContent extends CourseContentSource { ), ); bool fail = false; + Object? materialError; int documentRequests = 0; int fileLimit = 1; Completer? pendingMaterials; @override Future materials(LearnCourse course) async { + if (materialError != null) throw materialError!; if (fail) throw const PortalSessionRejected(); if (pendingMaterials != null) return pendingMaterials!.future; return LearnCourseMaterials( @@ -276,6 +278,27 @@ void main() { expect(tester.takeException(), isNull); }); + testWidgets( + 'unavailable portal offers retry without discarding the signed-in screen', + (tester) async { + final source = FakeContent() + ..materialError = const PortalCsrfUnavailable( + 'temporarily unavailable', + ); + var expired = false; + await show(tester, source, expired: () => expired = true); + await tester.tap(find.text('Course files')); + await tester.pumpAndSettle(); + expect(find.text('Sign in'), findsNothing); + expect(find.text('Retry'), findsOneWidget); + source.materialError = null; + await tester.tap(find.text('Retry')); + await tester.pumpAndSettle(); + expect(find.text('Lecture.docx'), findsOneWidget); + expect(expired, isFalse); + }, + ); + testWidgets('expired session offers sign in', (tester) async { var expired = false; await show( From 8ea3357655ee6220f9e6f8aef11f47c0735567e3 Mon Sep 17 00:00:00 2001 From: ashgrey Date: Wed, 18 Nov 2026 22:26:30 +0800 Subject: [PATCH 22/26] feat(diagnostics): export persistent logs and repair session renewal Export filtered local diagnostics from settings and welcome screens. Retain bounded logs across restarts with version and recovery stages. Restore main-compatible login fields and trusted-token confirmation. Persist theme and language preferences. Add diagnostics, authentication and UI regression coverage. --- README.md | 14 + lib/app.dart | 50 ++- lib/diagnostics/diagnostic_export.dart | 81 ++++ lib/diagnostics/diagnostic_log.dart | 413 ++++++++++++++++++ lib/l10n/app_en.arb | 4 +- lib/l10n/app_zh.arb | 4 +- lib/l10n/app_zh_CN.arb | 4 +- lib/l10n/app_zh_TW.arb | 4 +- lib/l10n/generated/app_localizations.dart | 12 + lib/l10n/generated/app_localizations_en.dart | 7 + lib/l10n/generated/app_localizations_zh.dart | 18 + lib/main.dart | 3 + lib/pages/settings_page.dart | 73 +++- lib/pages/welcome_page.dart | 11 + lib/preferences/app_preferences_store.dart | 66 +++ macos/Flutter/GeneratedPluginRegistrant.swift | 4 + packages/auth/README.md | 17 +- packages/auth/lib/src/session_runner.dart | 21 +- packages/auth/lib/thulium_auth.dart | 36 +- packages/auth/test/session_runner_test.dart | 64 ++- .../test/support/fake_auth_http_client.dart | 13 +- packages/auth/test/thulium_auth_test.dart | 72 ++- pubspec.lock | 72 +++ pubspec.yaml | 3 + .../diagnostics/diagnostic_export_test.dart | 76 ++++ .../unit/diagnostics/diagnostic_log_test.dart | 244 +++++++++++ test/widget/app/preferences_test.dart | 235 ++++++++++ .../settings/diagnostic_export_test.dart | 103 +++++ 28 files changed, 1678 insertions(+), 46 deletions(-) create mode 100644 lib/diagnostics/diagnostic_export.dart create mode 100644 lib/diagnostics/diagnostic_log.dart create mode 100644 lib/preferences/app_preferences_store.dart create mode 100644 test/unit/diagnostics/diagnostic_export_test.dart create mode 100644 test/unit/diagnostics/diagnostic_log_test.dart create mode 100644 test/widget/app/preferences_test.dart create mode 100644 test/widget/settings/diagnostic_export_test.dart diff --git a/README.md b/README.md index cdf3dd0..e2d76ca 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,20 @@ android/ ios/ web/ Mobile and web targets linux/ macos/ windows/ Desktop targets ``` +## Diagnostic logs + +Open Settings → Export diagnostic logs to share a text file on Android/iOS. +The welcome page also exposes Settings, so export remains available when login +cannot complete. Linux uses a file save dialog. + +The app retains up to 2,000 structural events from the last seven days locally, +including across restarts. Export includes the installed app version/build, +platform, UTC timestamps, request categories, HTTP status codes, recovery causes, +and the stage requesting verification. Event filtering happens before storage: +passwords, verification codes, account identifiers, cookie/token values, full +URLs, response previews, course titles and document content are not retained. +Logs are only shared when the user chooses export and a destination. + ## Checks Tests are grouped by scope: `test/unit/` covers logic and adapters, while diff --git a/lib/app.dart b/lib/app.dart index a8aaa0e..62a6c8e 100644 --- a/lib/app.dart +++ b/lib/app.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:flutter/material.dart'; import 'package:forui/forui.dart'; import 'package:thulium/l10n/generated/app_localizations.dart'; @@ -10,13 +12,15 @@ import 'auth/secure_learn_homework_cache_store.dart'; import 'pages/home_page.dart'; import 'homework/homework_theme.dart'; import 'pages/welcome_page.dart'; +import 'preferences/app_preferences_store.dart'; /// The root application widget owns global locale and theme state. final class ThuliumApp extends StatefulWidget { - const ThuliumApp({this.sessionStore, super.key}); + const ThuliumApp({this.sessionStore, this.preferencesStore, super.key}); /// Allows tests and alternate clients to provide their own session storage. final AuthSessionStore? sessionStore; + final AppPreferencesStore? preferencesStore; @override State createState() => _ThuliumAppState(); @@ -27,13 +31,32 @@ final class _ThuliumAppState extends State { // the theme button, the app switches to an explicit light or dark mode. ThemeMode _themeMode = ThemeMode.system; Locale _locale = const Locale('en'); - bool _isRestoringSession = true; + bool _isRestoringState = true; bool _hasSession = false; + late final AppPreferencesStore _preferencesStore = + widget.preferencesStore ?? LocalAppPreferencesStore(); + Future _preferenceWrites = Future.value(); @override void initState() { super.initState(); - _restoreSession(); + unawaited(_restoreState()); + } + + Future _restoreState() async { + await Future.wait([_restoreSession(), _restorePreferences()]); + if (mounted) setState(() => _isRestoringState = false); + } + + Future _restorePreferences() async { + try { + final preferences = await _preferencesStore.read(); + if (!mounted) return; + _themeMode = preferences.themeMode; + _locale = preferences.locale; + } catch (error) { + debugPrint('Thulium preference restoration failed: ${error.runtimeType}'); + } } Future _restoreSession() async { @@ -48,8 +71,6 @@ final class _ThuliumAppState extends State { // A secure-storage failure must not block access to the sign-in page. // Keep the failure visible in diagnostic logs without exposing secrets. debugPrint('Thulium session restoration failed: $error'); - } finally { - if (mounted) setState(() => _isRestoringSession = false); } } @@ -154,7 +175,7 @@ final class _ThuliumAppState extends State { child: child ?? const SizedBox.shrink(), ); }, - home: _isRestoringSession + home: _isRestoringState ? const FScaffold(child: Center(child: FCircularProgress())) : _hasSession ? HomePage( @@ -176,6 +197,7 @@ final class _ThuliumAppState extends State { void _setLocale(Locale locale) { setState(() => _locale = locale); + _savePreferences(); } void _toggleTheme() { @@ -187,5 +209,21 @@ final class _ThuliumAppState extends State { Brightness.dark); _themeMode = isDark ? ThemeMode.light : ThemeMode.dark; }); + _savePreferences(); + } + + void _savePreferences() { + final preferences = AppPreferences(themeMode: _themeMode, locale: _locale); + // Serialize snapshots so a slower earlier write cannot replace the user's + // latest language or theme choice. A failed write must not block later ones. + _preferenceWrites = _preferenceWrites.then((_) async { + try { + await _preferencesStore.write(preferences); + } catch (error) { + debugPrint( + 'Thulium preference persistence failed: ${error.runtimeType}', + ); + } + }); } } diff --git a/lib/diagnostics/diagnostic_export.dart b/lib/diagnostics/diagnostic_export.dart new file mode 100644 index 0000000..8e2813a --- /dev/null +++ b/lib/diagnostics/diagnostic_export.dart @@ -0,0 +1,81 @@ +import 'dart:convert'; +import 'dart:ui'; + +import 'package:file_selector/file_selector.dart' as fs; +import 'package:flutter/foundation.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:share_plus/share_plus.dart'; + +import 'diagnostic_log.dart'; + +final class DiagnosticExport { + DiagnosticExport({ + DiagnosticLog? log, + Future Function()? packageInfo, + Future Function(ShareParams)? share, + }) : _log = log ?? DiagnosticLog.instance, + _packageInfo = packageInfo ?? PackageInfo.fromPlatform, + _share = share ?? SharePlus.instance.share; + + final DiagnosticLog _log; + final Future Function() _packageInfo; + final Future Function(ShareParams) _share; + + Future export({ + required String title, + Rect? sharePositionOrigin, + }) async { + _log.record('[app] event=export-requested'); + String version = 'unknown'; + String build = 'unknown'; + try { + final info = await _packageInfo(); + String safe(String value) => + RegExp(r'^[A-Za-z0-9_.+\-]{1,80}$').hasMatch(value) + ? value + : 'unknown'; + version = safe(info.version); + build = safe(info.buildNumber); + } catch (_) { + // Metadata failure should not prevent exporting the useful event log. + } + final now = DateTime.now().toUtc(); + final name = + 'thulium-diagnostics-${now.toIso8601String().replaceAll(RegExp(r'[^0-9TZ]'), '')}.txt'; + final report = + 'Thulium diagnostics v1\n' + 'Generated (UTC): ${now.toIso8601String()}\n' + 'App version: $version+$build\n' + 'Platform: ${kIsWeb ? 'web' : defaultTargetPlatform.name}\n' + 'Mode: ${kReleaseMode + ? 'release' + : kProfileMode + ? 'profile' + : 'debug'}\n' + 'Content: structural events only; no request values or response bodies\n\n' + '${await _log.snapshot()}\n'; + final file = fs.XFile.fromData( + utf8.encode(report), + name: name, + mimeType: 'text/plain', + ); + if (!kIsWeb && defaultTargetPlatform == TargetPlatform.linux) { + final location = await fs.getSaveLocation( + suggestedName: name, + acceptedTypeGroups: const [ + fs.XTypeGroup(label: 'Text', extensions: ['txt']), + ], + ); + if (location != null) await file.saveTo(location.path); + } else { + await _share( + ShareParams( + title: title, + files: [file], + fileNameOverrides: [name], + sharePositionOrigin: sharePositionOrigin, + ), + ); + } + } +} diff --git a/lib/diagnostics/diagnostic_log.dart b/lib/diagnostics/diagnostic_log.dart new file mode 100644 index 0000000..8c7c5c0 --- /dev/null +++ b/lib/diagnostics/diagnostic_log.dart @@ -0,0 +1,413 @@ +// ignore_for_file: constant_identifier_names + +import 'dart:async'; +import 'dart:ui'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/widgets.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +abstract interface class DiagnosticLogStore { + Future> read(); + Future write(List lines); +} + +final class LocalDiagnosticLogStore implements DiagnosticLogStore { + static const _KEY = 'thulium.diagnostics.v1'; + SharedPreferencesAsync? _preferences; + SharedPreferencesAsync get _storage => + _preferences ??= SharedPreferencesAsync(); + @override + Future> read() async => await _storage.getStringList(_KEY) ?? []; + @override + Future write(List lines) => _storage.setStringList(_KEY, lines); +} + +/// Stores only recognized structural events, never arbitrary console messages. +/// Filtering happens before events reach memory, persistence or export. +final class DiagnosticLog { + DiagnosticLog({ + DiagnosticLogStore? store, + DateTime Function()? now, + this.maxEntries = 2000, + }) : _store = store ?? LocalDiagnosticLogStore(), + _now = now ?? DateTime.now; + + static final instance = DiagnosticLog(); + final DiagnosticLogStore _store; + final DateTime Function() _now; + final int maxEntries; + final _lines = []; + Future? _initialization; + Future _writes = Future.value(); + Timer? _persistTimer; + bool _ready = false; + bool _installed = false; + AppLifecycleListener? _lifecycle; + + void install() { + if (_installed) return; + _installed = true; + final previousPrint = debugPrint; + debugPrint = (String? message, {int? wrapWidth}) { + if (message != null) record(message); + previousPrint(message, wrapWidth: wrapWidth); + }; + final previousFlutterError = FlutterError.onError; + FlutterError.onError = (details) { + recordError('flutter-error', details.exception, details.stack); + previousFlutterError?.call(details); + }; + final previousPlatformError = PlatformDispatcher.instance.onError; + PlatformDispatcher.instance.onError = (error, stack) { + recordError('platform-error', error, stack); + return previousPlatformError?.call(error, stack) ?? false; + }; + _lifecycle = AppLifecycleListener( + onStateChange: (state) { + record('[app] event=lifecycle-${state.name}'); + if (state == AppLifecycleState.paused || + state == AppLifecycleState.detached) { + unawaited(flush()); + } + }, + ); + record('[app] event=started'); + unawaited(initialize()); + } + + Future initialize() => _initialization ??= _load(); + + Future _load() async { + try { + final saved = await _store.read(); + final current = List.of(_lines); + _lines.clear(); + for (final line in saved) { + final split = line.indexOf(' '); + if (split < 0 || DateTime.tryParse(line.substring(0, split)) == null) { + continue; + } + final safe = sanitizeDiagnosticMessage(line.substring(split + 1)); + if (safe != null) _lines.add('${line.substring(0, split)} $safe'); + } + _lines.addAll(current); + } catch (_) { + _lines.add( + '${_now().toUtc().toIso8601String()} [app] event=log-storage-read-failed', + ); + } + _ready = true; + _trim(); + _schedule(); + } + + void record(String message) { + final safe = sanitizeDiagnosticMessage(message); + if (safe == null) return; + _lines.add('${_now().toUtc().toIso8601String()} $safe'); + _trim(); + if (_ready) _schedule(); + } + + void recordError(String kind, Object error, StackTrace? stack) { + record('[app] event=$kind type=${error.runtimeType}'); + if (stack == null) return; + for (final match in RegExp( + r'package:[a-zA-Z0-9_/.\-]+\.dart:\d+:\d+', + ).allMatches(stack.toString()).take(8)) { + record('[app] frame=${match.group(0)}'); + } + } + + void _trim() { + final cutoff = _now().toUtc().subtract(const Duration(days: 7)); + _lines.removeWhere( + (line) => + DateTime.parse(line.substring(0, line.indexOf(' '))).isBefore(cutoff), + ); + if (_lines.length > maxEntries) { + _lines.removeRange(0, _lines.length - maxEntries); + } + } + + void _schedule() { + _persistTimer?.cancel(); + _persistTimer = Timer(const Duration(seconds: 1), () => unawaited(flush())); + } + + Future flush() async { + await initialize(); + _persistTimer?.cancel(); + _persistTimer = null; + final snapshot = List.of(_lines); + _writes = _writes.then((_) async { + try { + await _store.write(snapshot); + } catch (_) { + // Logging failure must not break login, export or schedule more writes. + } + }); + await _writes; + } + + Future snapshot() async { + await flush(); + _trim(); + return _lines.join('\n'); + } + + @visibleForTesting + void dispose() { + _persistTimer?.cancel(); + _lifecycle?.dispose(); + } +} + +const _TYPES = { + 'StateError', + 'FormatException', + 'TimeoutException', + 'SocketException', + 'HttpException', + 'PlatformException', + 'MissingPluginException', + 'PortalCsrfUnavailable', + 'PortalSessionRejected', + 'CourseScheduleException', + 'CourseScheduleSessionExpired', + 'TwoFactorInteractionRequired', + 'UnsupportedError', + 'FlutterError', + 'TypeError', +}; + +const _EVENTS = { + 'started', + 'flutter-error', + 'platform-error', + 'log-storage-read-failed', + 'session-restore-failed', + 'preferences-restore-failed', + 'preferences-write-failed', + 'lifecycle-resumed', + 'lifecycle-inactive', + 'lifecycle-paused', + 'lifecycle-hidden', + 'lifecycle-detached', + 'portal-cookies-imported', + 'portal-silent-reconnect', + 'portal-silent-reconnect-failed', + 'portal-cached-token-verified', + 'portal-refreshed-token-verified', + 'trusted-confirmation', + 'credential-retry', + 'trust-accepted', + 'trust-token-received', + 'trust-rejected', + 'trust-no-token', + 'trust-failed', + 'verification-sent', + 'verification-accepted', + 'verification-rejected', + 'learn-main-probe', + 'learn-rebuild', + 'course-load-failed', + 'homework-load-failed', + 'calendar-load-failed', + 'export-failed', + 'calendar-expired', + 'calendar-verification-required', + 'export-requested', + 'network-timeout', +}; + +const _MESSAGES = { + 'Trying portal reconnection with the saved SSO cookies.': + 'portal-silent-reconnect', + 'Silent portal reconnection did not complete.': + 'portal-silent-reconnect-failed', + 'A stored portal CSRF token passed the account probe.': + 'portal-cached-token-verified', + 'The portal CSRF token remained usable after reconnect.': + 'portal-refreshed-token-verified', + 'Using the trusted-browser identity entry.': 'trusted-confirmation', + 'Reconnecting with saved credentials; retrying once.': 'credential-retry', + 'Trusted-device registration accepted.': 'trust-accepted', + 'Trusted-device credential received.': 'trust-token-received', + 'Trusted-device registration was not accepted.': 'trust-rejected', + 'Trusted-device registration needs no legacy credential.': 'trust-no-token', + 'Trusted-device registration failed; continuing login.': 'trust-failed', + '2FA verification code request succeeded.': 'verification-sent', + '2FA code verification succeeded.': 'verification-accepted', + '2FA code verification was rejected; awaiting corrected input.': + 'verification-rejected', + 'Learn session rejected; verifying the main session.': 'learn-main-probe', + 'Main session verified; rebuilding Learn without a password.': + 'learn-rebuild', + 'session expired': 'calendar-expired', + 'interactive two-factor verification required': + 'calendar-verification-required', +}; + +const _ENDPOINTS = { + '/wengine-vpn/cookie': 'portal-cookie', + '/do/off/ui/auth/login/form/': 'identity-form', + '/do/off/ui/auth/login/checkSingle': 'identity-confirmation', + '/security_check': 'identity-confirmation', + '/do/off/ui/auth/login/check': 'identity-credentials', + '/b/doubleAuth/personal/saveFinger': 'device-registration', + '/b/doubleAuth/login': 'second-factor', + '/grjbxx': 'portal-account', + 'onlineAppRedirect': 'portal-roaming', + 'downloadPdfStream': 'learn-preview', + 'beforePlay': 'learn-viewer', + 'kjxxbByWlkcidAndSizeForStudent': 'learn-materials', + 'loadCourseBySemesterId': 'learn-courses', + 'zyList': 'learn-homework', + 'getCurrentAndNextSemester': 'academic-term', + 'jxmh_out.do': 'academic-calendar', + 'portal3rd.do': 'academic-calendar-secondary', + '/login': 'webvpn-entry', + '/logout': 'logout', +}; + +/// An allowlist of event shapes, rather than redaction of arbitrary prose. +/// Unknown messages, response previews, URLs and request values are discarded. +String? sanitizeDiagnosticMessage(String input) { + final prefix = RegExp( + r'^\[(auth|signin|study|calendar|app)\](?:\[[^\]\r\n]{0,80}\])?\s*', + ).firstMatch(input); + if (prefix == null) { + if (input.startsWith('Thulium session restoration failed:')) { + return '[app] event=session-restore-failed'; + } + if (input.startsWith('Thulium preference restoration failed:')) { + return '[app] event=preferences-restore-failed'; + } + if (input.startsWith('Thulium preference persistence failed:')) { + return '[app] event=preferences-write-failed'; + } + return null; + } + final scope = prefix.group(1)!; + final body = input.substring(prefix.end); + String? value(String name) => + RegExp('(?:^|[ ;])$name=([A-Za-z0-9_-]+)').firstMatch(body)?.group(1); + final type = _TYPES.contains(value('type')) ? value('type') : 'other'; + final event = value('event'); + if (_EVENTS.contains(event)) { + return '[$scope] event=$event${body.contains('type=') ? ' type=$type' : ''}'; + } + if (scope == 'app') { + final frame = RegExp( + r'^frame=(package:[a-zA-Z0-9_/.\-]+\.dart:\d+:\d+)$', + ).firstMatch(body); + return frame == null ? null : '[app] frame=${frame.group(1)}'; + } + if (scope == 'signin') { + final stage = value('stage'); + if (!const { + 'start', + 'success', + 'failed', + 'duplicate_submit_ignored', + 'trust_choice_reused', + 'trust_dialog_shown', + 'trust_dialog_resolved', + }.contains(stage)) { + return null; + } + final attempt = int.tryParse(value('attempt') ?? ''); + return '[signin] attempt=${attempt ?? 0} stage=$stage${stage == 'failed' ? ' type=$type' : ''}'; + } + final request = RegExp(r'^HTTP (GET|POST) ').firstMatch(body); + if (request != null) { + var endpoint = 'other'; + final existing = value('endpoint'); + if (_ENDPOINTS.values.contains(existing)) { + endpoint = existing!; + } else { + for (final entry in _ENDPOINTS.entries) { + if (body.contains(entry.key)) { + endpoint = entry.value; + break; + } + } + } + return '[$scope] HTTP ${request.group(1)} endpoint=$endpoint'; + } + if (body.startsWith('HTTP response ')) { + final status = int.tryParse(value('status') ?? '') ?? 0; + final elapsed = int.tryParse(value('elapsedMs') ?? '') ?? 0; + return '[$scope] HTTP response status=$status elapsedMs=$elapsed'; + } + if (body.startsWith('HTTP timeout ')) return '[$scope] event=network-timeout'; + if (body.startsWith('Unexpected response ')) { + final stage = value('stage'); + final safeStage = + const { + 'portal-csrf-cookie', + 'portal-user-data', + 'portal-roaming', + 'learning-landing', + 'learning-courses', + 'learning-materials', + 'learning-homework', + 'semester-list', + 'primary-calendar', + 'secondary-calendar', + }.contains(stage) + ? stage + : 'other'; + final bodyType = + const {'empty', 'html', 'json', 'other'}.contains(value('bodyType')) + ? value('bodyType') + : 'other'; + return '[$scope] Unexpected response stage=$safeStage status=${int.tryParse(value('status') ?? '') ?? 0} bodyType=$bodyType bodyLength=${int.tryParse(value('bodyLength') ?? '') ?? 0}'; + } + if (body.startsWith('Credential recovery:')) { + final cause = _TYPES.contains(value('cause')) ? value('cause') : 'other'; + return '[$scope] Credential recovery: cause=$cause trustedCredentialPresent=${value('trustedCredentialPresent') == 'true'}'; + } + if (body.startsWith('Session restored:')) { + return '[$scope] Session restored: trustedCredentialPresent=${value('trustedCredentialPresent') == 'true'} deviceTrustConsent=${value('deviceTrustConsent') == 'true'}'; + } + if (body.startsWith('Session recovery unavailable:') || + body.startsWith('Credential recovery skipped:')) { + final reason = + const { + 'no-session', + 'account-mismatch', + 'missing-credentials', + }.contains(value('reason')) + ? value('reason') + : 'other'; + final action = body.startsWith('Session recovery') + ? 'Session recovery unavailable' + : 'Credential recovery skipped'; + return '[$scope] $action: reason=$reason'; + } + if (body.startsWith('Second-factor challenge:')) { + final stage = value('stage') == 'webvpn' ? 'webvpn' : 'information-portal'; + return '[$scope] Second-factor challenge: stage=$stage trustedCredentialPresent=${value('trustedCredentialPresent') == 'true'}'; + } + final fixed = _MESSAGES[body]; + if (fixed != null) return '[$scope] event=$fixed'; + if (body.startsWith('Information-portal cookie bundle imported:')) { + return '[$scope] event=portal-cookies-imported'; + } + final failed = RegExp( + r'^(course loading failed|homework loading failed|loading failed|export failed) type=', + ).firstMatch(body); + if (failed != null) { + final name = switch (failed.group(1)) { + 'course loading failed' => 'course-load-failed', + 'homework loading failed' => 'homework-load-failed', + 'loading failed' => 'calendar-load-failed', + _ => 'export-failed', + }; + return '[$scope] event=$name type=$type'; + } + return null; +} diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 0cf00fe..1dc8f20 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -207,5 +207,7 @@ "coursePreviewUnsupported": "Document preview is not supported on Linux yet", "sessionVerificationRequired": "Verification is required to refresh campus data. Your saved information is still available", "courseContentLoading": "Loading course content", - "coursePreviewLoading": "Loading document" + "coursePreviewLoading": "Loading document", + "exportDiagnostics": "Export diagnostic logs", + "exportDiagnosticsError": "Could not export logs, please try again" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index cb6e03e..c489505 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -191,5 +191,7 @@ "coursePreviewUnsupported": "Linux 暂不支持文档预览", "sessionVerificationRequired": "更新校园数据需要重新验证,已保存的信息仍可查看", "courseContentLoading": "正在加载课程内容", - "coursePreviewLoading": "正在加载文档" + "coursePreviewLoading": "正在加载文档", + "exportDiagnostics": "导出诊断日志", + "exportDiagnosticsError": "日志导出失败,请重试" } diff --git a/lib/l10n/app_zh_CN.arb b/lib/l10n/app_zh_CN.arb index a6d921f..051926c 100644 --- a/lib/l10n/app_zh_CN.arb +++ b/lib/l10n/app_zh_CN.arb @@ -191,5 +191,7 @@ "coursePreviewUnsupported": "Linux 暂不支持文档预览", "sessionVerificationRequired": "更新校园数据需要重新验证,已保存的信息仍可查看", "courseContentLoading": "正在加载课程内容", - "coursePreviewLoading": "正在加载文档" + "coursePreviewLoading": "正在加载文档", + "exportDiagnostics": "导出诊断日志", + "exportDiagnosticsError": "日志导出失败,请重试" } diff --git a/lib/l10n/app_zh_TW.arb b/lib/l10n/app_zh_TW.arb index 84576e9..1d99d74 100644 --- a/lib/l10n/app_zh_TW.arb +++ b/lib/l10n/app_zh_TW.arb @@ -191,5 +191,7 @@ "coursePreviewUnsupported": "Linux 暫不支援文件預覽", "sessionVerificationRequired": "更新校園資料需要重新驗證,已儲存的資訊仍可查看", "courseContentLoading": "正在載入課程內容", - "coursePreviewLoading": "正在載入文件" + "coursePreviewLoading": "正在載入文件", + "exportDiagnostics": "匯出診斷日誌", + "exportDiagnosticsError": "日誌匯出失敗,請重試" } diff --git a/lib/l10n/generated/app_localizations.dart b/lib/l10n/generated/app_localizations.dart index 21435e6..c35e7d7 100644 --- a/lib/l10n/generated/app_localizations.dart +++ b/lib/l10n/generated/app_localizations.dart @@ -1197,6 +1197,18 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Loading document'** String get coursePreviewLoading; + + /// No description provided for @exportDiagnostics. + /// + /// In en, this message translates to: + /// **'Export diagnostic logs'** + String get exportDiagnostics; + + /// No description provided for @exportDiagnosticsError. + /// + /// In en, this message translates to: + /// **'Could not export logs, please try again'** + String get exportDiagnosticsError; } class _AppLocalizationsDelegate diff --git a/lib/l10n/generated/app_localizations_en.dart b/lib/l10n/generated/app_localizations_en.dart index c50b472..8f5686b 100644 --- a/lib/l10n/generated/app_localizations_en.dart +++ b/lib/l10n/generated/app_localizations_en.dart @@ -611,4 +611,11 @@ class AppLocalizationsEn extends AppLocalizations { @override String get coursePreviewLoading => 'Loading document'; + + @override + String get exportDiagnostics => 'Export diagnostic logs'; + + @override + String get exportDiagnosticsError => + 'Could not export logs, please try again'; } diff --git a/lib/l10n/generated/app_localizations_zh.dart b/lib/l10n/generated/app_localizations_zh.dart index 06c7fdd..3be5c3a 100644 --- a/lib/l10n/generated/app_localizations_zh.dart +++ b/lib/l10n/generated/app_localizations_zh.dart @@ -579,6 +579,12 @@ class AppLocalizationsZh extends AppLocalizations { @override String get coursePreviewLoading => '正在加载文档'; + + @override + String get exportDiagnostics => '导出诊断日志'; + + @override + String get exportDiagnosticsError => '日志导出失败,请重试'; } /// The translations for Chinese, as used in China (`zh_CN`). @@ -1156,6 +1162,12 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { @override String get coursePreviewLoading => '正在加载文档'; + + @override + String get exportDiagnostics => '导出诊断日志'; + + @override + String get exportDiagnosticsError => '日志导出失败,请重试'; } /// The translations for Chinese, as used in Taiwan (`zh_TW`). @@ -1733,4 +1745,10 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { @override String get coursePreviewLoading => '正在載入文件'; + + @override + String get exportDiagnostics => '匯出診斷日誌'; + + @override + String get exportDiagnosticsError => '日誌匯出失敗,請重試'; } diff --git a/lib/main.dart b/lib/main.dart index 2a6418e..898ca67 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,8 +1,11 @@ import 'package:flutter/material.dart'; import 'app.dart'; +import 'diagnostics/diagnostic_log.dart'; void main() { + WidgetsFlutterBinding.ensureInitialized(); + DiagnosticLog.instance.install(); // Keep the executable entry point small; application composition lives in // app.dart so pages and reusable widgets can evolve independently. runApp(const ThuliumApp()); diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 784d5b2..2391a96 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -2,13 +2,15 @@ import 'package:flutter/widgets.dart'; import 'package:forui/forui.dart'; import '../widgets/app_page_scaffold.dart'; +import '../diagnostics/diagnostic_export.dart'; import 'package:thulium/l10n/generated/app_localizations.dart'; /// Contains account and application settings for the authenticated user. final class SettingsPage extends StatefulWidget { - const SettingsPage({required this.onLogout, super.key}); + const SettingsPage({this.onLogout, this.exportDiagnostics, super.key}); - final Future Function() onLogout; + final Future Function()? onLogout; + final Future Function(Rect? sharePositionOrigin)? exportDiagnostics; @override State createState() => _SettingsPageState(); @@ -17,6 +19,36 @@ final class SettingsPage extends StatefulWidget { final class _SettingsPageState extends State { bool _isLoggingOut = false; bool _logoutFailed = false; + bool _isExporting = false; + bool _exportFailed = false; + final _exportKey = GlobalKey(); + + Future _exportDiagnostics() async { + if (_isExporting) return; + setState(() { + _isExporting = true; + _exportFailed = false; + }); + final box = _exportKey.currentContext?.findRenderObject(); + final origin = box is RenderBox && box.hasSize + ? box.localToGlobal(Offset.zero) & box.size + : null; + try { + final export = widget.exportDiagnostics; + if (export != null) { + await export(origin); + } else { + await DiagnosticExport().export( + title: AppLocalizations.of(context)!.exportDiagnostics, + sharePositionOrigin: origin, + ); + } + } catch (_) { + if (mounted) setState(() => _exportFailed = true); + } finally { + if (mounted) setState(() => _isExporting = false); + } + } Future _logout() async { setState(() { @@ -24,7 +56,7 @@ final class _SettingsPageState extends State { _logoutFailed = false; }); - final succeeded = await widget.onLogout(); + final succeeded = await widget.onLogout!(); if (!mounted) return; if (succeeded) { // Settings is pushed over the authenticated home. Remove that route so @@ -49,21 +81,44 @@ final class _SettingsPageState extends State { child: ListView( children: [ FButton( - variant: FButtonVariant.destructive, - onPress: _isLoggingOut ? null : _logout, - child: _isLoggingOut + key: _exportKey, + variant: FButtonVariant.outline, + onPress: _isExporting ? null : _exportDiagnostics, + prefix: const Icon(FLucideIcons.fileText, size: 18), + child: _isExporting ? const FCircularProgress(size: FCircularProgressSizeVariant.sm) - : Text(l10n.logoutAction), + : Text(l10n.exportDiagnostics), ), - if (_logoutFailed) ...[ + if (_exportFailed) ...[ SizedBox(height: context.theme.style.pagePadding.top), Text( - l10n.logoutError, + l10n.exportDiagnosticsError, style: context.theme.typography.sm.copyWith( color: context.theme.colors.error, ), ), ], + if (widget.onLogout != null) ...[ + SizedBox(height: context.theme.style.pagePadding.top), + FButton( + variant: FButtonVariant.destructive, + onPress: _isLoggingOut ? null : _logout, + child: _isLoggingOut + ? const FCircularProgress( + size: FCircularProgressSizeVariant.sm, + ) + : Text(l10n.logoutAction), + ), + if (_logoutFailed) ...[ + SizedBox(height: context.theme.style.pagePadding.top), + Text( + l10n.logoutError, + style: context.theme.typography.sm.copyWith( + color: context.theme.colors.error, + ), + ), + ], + ], ], ), ); diff --git a/lib/pages/welcome_page.dart b/lib/pages/welcome_page.dart index 4de0c84..d7c2e81 100644 --- a/lib/pages/welcome_page.dart +++ b/lib/pages/welcome_page.dart @@ -7,6 +7,7 @@ import 'package:thulium/l10n/generated/app_localizations.dart'; import '../widgets/language_button.dart'; import '../widgets/app_icon_button.dart'; import 'login_page.dart'; +import 'settings_page.dart'; /// The unauthenticated landing page shown before the student signs in. final class WelcomePage extends StatelessWidget { @@ -83,6 +84,16 @@ final class WelcomePage extends StatelessWidget { : FLucideIcons.moon, onPress: onThemeToggle, ), + AppIconButton( + label: l10n.settingsTitle, + icon: FLucideIcons.settings, + onPress: () => Navigator.of(context).push( + AppPageRoute( + context: context, + builder: (_) => const SettingsPage(), + ), + ), + ), ], ), ), diff --git a/lib/preferences/app_preferences_store.dart b/lib/preferences/app_preferences_store.dart new file mode 100644 index 0000000..f6d7222 --- /dev/null +++ b/lib/preferences/app_preferences_store.dart @@ -0,0 +1,66 @@ +import 'dart:convert'; + +import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Installation preferences are independent of accounts and login credentials. +final class AppPreferences { + const AppPreferences({ + this.themeMode = ThemeMode.system, + this.locale = const Locale('en'), + }); + + final ThemeMode themeMode; + final Locale locale; + + factory AppPreferences.decode(String encoded) { + final Object? value; + try { + value = jsonDecode(encoded); + } on FormatException { + return const AppPreferences(); + } + if (value is! Map) return const AppPreferences(); + return AppPreferences( + themeMode: switch (value['theme']) { + 'dark' => ThemeMode.dark, + 'light' => ThemeMode.light, + _ => ThemeMode.system, + }, + locale: switch (value['locale']) { + 'zh-CN' => const Locale('zh', 'CN'), + 'zh-TW' => const Locale('zh', 'TW'), + 'zh' => const Locale('zh'), + _ => const Locale('en'), + }, + ); + } + + String encode() => + jsonEncode({'theme': themeMode.name, 'locale': locale.toLanguageTag()}); +} + +abstract interface class AppPreferencesStore { + Future read(); + Future write(AppPreferences preferences); +} + +final class LocalAppPreferencesStore implements AppPreferencesStore { + // ignore: constant_identifier_names + static const _PREFERENCES_KEY = 'thulium.preferences.v1'; + SharedPreferencesAsync? _preferences; + SharedPreferencesAsync get _storage => + _preferences ??= SharedPreferencesAsync(); + + @override + Future read() async { + final encoded = await _storage.getString(_PREFERENCES_KEY); + return encoded == null + ? const AppPreferences() + : AppPreferences.decode(encoded); + } + + @override + Future write(AppPreferences preferences) => + _storage.setString(_PREFERENCES_KEY, preferences.encode()); +} diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift index 931668b..64b610d 100644 --- a/macos/Flutter/GeneratedPluginRegistrant.swift +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -7,12 +7,16 @@ import Foundation import file_selector_macos import flutter_secure_storage_darwin +import package_info_plus import pdfx import share_plus +import shared_preferences_foundation func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { FileSelectorPlugin.register(with: registry.registrar(forPlugin: "FileSelectorPlugin")) FlutterSecureStorageDarwinPlugin.register(with: registry.registrar(forPlugin: "FlutterSecureStorageDarwinPlugin")) + FPPPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FPPPackageInfoPlusPlugin")) PdfxPlugin.register(with: registry.registrar(forPlugin: "PdfxPlugin")) SharePlusMacosPlugin.register(with: registry.registrar(forPlugin: "SharePlusMacosPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) } diff --git a/packages/auth/README.md b/packages/auth/README.md index ceef5f3..419d349 100644 --- a/packages/auth/README.md +++ b/packages/auth/README.md @@ -52,12 +52,17 @@ service errors. JSON content and injected scripts mentioning login controls do not prove logout. PDF reads carry the current Learn CSRF token, and temporary service failures offer retry rather than sending users back to sign-in. -Device trust records browser consent separately from the optional legacy -`fingerGenPrint` token. Sign-in asks once before the first credential submission, -so trusted-browser `singleLogin` fields are present from the WebVPN stage onward. -Fingerprint registration still happens only after successful code verification. +Device trust records registration consent separately from the optional legacy +`fingerGenPrint` token. Sign-in asks once and registers the fingerprint only after +successful code verification. Credential forms match `main`: account, encrypted +password, fingerprint, trusted-device token and captcha. They do not implicitly +enable the separate `singleLogin`/`deviceName` browser-SSO option. A remembered +trust choice alone is not proof that the server will waive verification. Server-provided `checkSingle` forms are followed before falling back to -credentials, including during silent portal renewal. This allows the WebVPN and +credentials, including during silent portal renewal. Restoring a session also +hydrates its trusted-device token; confirmation forms explicitly receive that +token, the stable fingerprint and `i_rememberme=on` for `checkSingle`, even when +the server omits the inputs or supplies empty placeholders. This allows the WebVPN and information-portal stages to share a verified identity without unnecessarily requesting another code. A genuine server challenge is still verified. @@ -70,3 +75,5 @@ sign-in submissions. The login page guards button and keyboard callbacks before enqueueing work, snapshots the submitted credentials, and caches one trust choice for that attempt. Verification and dialog completion also reject repeat callbacks. Diagnostic attempt IDs and phase names contain no credential values. +Recovery diagnostics record the triggering error type, the challenge stage +(`webvpn` or `information-portal`) and token presence, never token values. diff --git a/packages/auth/lib/src/session_runner.dart b/packages/auth/lib/src/session_runner.dart index 414b6c4..a95f790 100644 --- a/packages/auth/lib/src/session_runner.dart +++ b/packages/auth/lib/src/session_runner.dart @@ -55,8 +55,12 @@ final class AuthSessionRunner { trace: trace, ); final session = await client.restore(); - if (session == null || - (expectedUserId != null && session.userId != expectedUserId)) { + if (session == null) { + trace?.call('Session recovery unavailable: reason=no-session.'); + throw const PortalSessionRejected(); + } + if (expectedUserId != null && session.userId != expectedUserId) { + trace?.call('Session recovery unavailable: reason=account-mismatch.'); throw const PortalSessionRejected(); } try { @@ -67,7 +71,18 @@ final class AuthSessionRunner { (error is PortalSessionRejected || error is PortalCsrfUnavailable); if (!reconnect) rethrow; final saved = await credentials?.readCredentials(); - if (saved == null || saved.userId != session.userId) rethrow; + if (saved == null) { + trace?.call('Credential recovery skipped: reason=missing-credentials.'); + rethrow; + } + if (saved.userId != session.userId) { + trace?.call('Credential recovery skipped: reason=account-mismatch.'); + rethrow; + } + trace?.call( + 'Credential recovery: cause=${error.runtimeType} ' + 'trustedCredentialPresent=${session.fingerGenPrint?.isNotEmpty == true}.', + ); trace?.call('Reconnecting with saved credentials; retrying once.'); try { await client.login( diff --git a/packages/auth/lib/thulium_auth.dart b/packages/auth/lib/thulium_auth.dart index 05cb40e..344d5d5 100644 --- a/packages/auth/lib/thulium_auth.dart +++ b/packages/auth/lib/thulium_auth.dart @@ -168,7 +168,7 @@ final class AuthSession { /// This value is sensitive and must be persisted only through a secure store. final String? fingerGenPrint; - /// Whether the user allowed trusted-browser SSO on this installation. + /// Whether the user allowed device registration on this installation. /// This is independent of an optional legacy token; the server still decides /// whether the browser is trusted and whether verification is necessary. final bool trustedBrowser; @@ -511,7 +511,7 @@ final class TsinghuaAuthClient { /// Called only after the selected second-factor code has been requested. final TwoFactorCodeHandler? twoFactorCodeHandler; - /// Called after code verification to obtain explicit consent for device trust. + /// Called once per sign-in to obtain consent for post-verification trust. final TwoFactorTrustHandler? twoFactorTrustHandler; /// Optional diagnostic callback. Messages contain no passwords, codes, or @@ -581,9 +581,14 @@ final class TsinghuaAuthClient { _session = restored; _rememberIdentity(restored); + _fingerGenPrint = restored.fingerGenPrint; _trustedBrowser = restored.trustedBrowser || restored.fingerGenPrint?.isNotEmpty == true; _cookieJar.restore(restored.scopedCookies); + trace?.call( + 'Session restored: trustedCredentialPresent=${_fingerGenPrint?.isNotEmpty == true} ' + 'deviceTrustConsent=${restored.trustedBrowser}.', + ); return restored; } @@ -1041,9 +1046,9 @@ final class TsinghuaAuthClient { previousSession.fingerprint == fingerprint && (previousSession.trustedBrowser || previousSession.fingerGenPrint?.isNotEmpty == true); - // singleLogin must be present on the initial credential submission, before - // WebVPN and the portal establish separate ID sessions. Ask once up front - // rather than first asking after verification, when that POST is too late. + // Cache one device-registration choice for this attempt. Device trust and + // the ID site's optional singleLogin checkbox are separate choices; routine + // credential recovery must keep the same fields as the main branch. _trustDecision = _trustedBrowser || await (twoFactorTrustHandler?.call() ?? Future.value(false)); @@ -1062,6 +1067,10 @@ final class TsinghuaAuthClient { ); if (response.body.contains('二次认证')) { + trace?.call( + 'Second-factor challenge: stage=webvpn ' + 'trustedCredentialPresent=${_fingerGenPrint?.isNotEmpty == true}.', + ); response = await _completeTwoFactor(fingerprint: fingerprint); } _ensureIdentityLoginSucceeded(response.body); @@ -1336,6 +1345,10 @@ final class TsinghuaAuthClient { fingerprint: fingerprint, ); if (response.body.contains('二次认证')) { + trace?.call( + 'Second-factor challenge: stage=information-portal ' + 'trustedCredentialPresent=${_fingerGenPrint?.isNotEmpty == true}.', + ); response = await _completeTwoFactor(fingerprint: fingerprint); } _ensureIdentityLoginSucceeded(response.body); @@ -1374,8 +1387,6 @@ final class TsinghuaAuthClient { 'fingerPrint': fingerprint, 'fingerGenPrint': _fingerGenPrint ?? '', 'i_captcha': '', - if (_trustedBrowser || _trustDecision == true) 'singleLogin': 'on', - if (_trustedBrowser || _trustDecision == true) 'deviceName': 'Thulium', }, ); } @@ -1390,7 +1401,11 @@ final class TsinghuaAuthClient { final forms = document .querySelectorAll('form') .where( - (form) => form.querySelector('input[name="fingerPrint"]') != null, + (form) => + form.querySelector('input[name="fingerPrint"]') != null || + RegExp( + r'checkSingle|security_check', + ).hasMatch(form.attributes['action'] ?? ''), ); if (forms.isEmpty) return null; final form = forms.first; @@ -1427,6 +1442,11 @@ final class TsinghuaAuthClient { ? fingerprint : input.attributes['value'] ?? ''; } + // Server forms may omit these inputs or leave a token placeholder empty. + // The persisted device credential must survive process/session restoration. + fields['fingerPrint'] = fingerprint; + fields['fingerGenPrint'] = _fingerGenPrint ?? ''; + if (action.path.endsWith('/checkSingle')) fields['i_rememberme'] = 'on'; trace?.call('Using the trusted-browser identity entry.'); return _request(action, method: 'POST', form: fields); } diff --git a/packages/auth/test/session_runner_test.dart b/packages/auth/test/session_runner_test.dart index b53c97f..85d9d3a 100644 --- a/packages/auth/test/session_runner_test.dart +++ b/packages/auth/test/session_runner_test.dart @@ -25,6 +25,62 @@ const _session = AuthSession( ); void main() { + for (final portalOnly in [false, true]) { + test( + 'verification diagnostics identify ${portalOnly ? 'portal' : 'WebVPN'} without exposing credentials', + () async { + final store = _Store(); + final transport = _Transport() + ..needsVerification = true + ..verifyPortalOnly = portalOnly; + final events = []; + final runner = AuthSessionRunner( + store, + trace: events.add, + createClient: () => TsinghuaAuthClient( + httpClient: transport, + sessionStore: store, + credentialStore: store, + trace: events.add, + ), + ); + await expectLater( + runner.run(request: _load), + throwsA(isA()), + ); + expect( + events, + contains( + 'Second-factor challenge: stage=${portalOnly ? 'information-portal' : 'webvpn'} trustedCredentialPresent=true.', + ), + ); + expect(events.join('\n'), isNot(contains('saved-password'))); + expect(events.join('\n'), isNot(contains('trusted-device'))); + }, + ); + } + + test( + 'credential recovery keeps the main-branch form without optional SSO consent', + () async { + final store = _Store(); + final transport = _Transport()..challengeForSingleLogin = true; + expect(await _runner(store, transport).run(request: _load), 'content'); + expect(transport.logins, 1); + for (final form in transport.identityForms) { + expect(form.keys.toSet(), { + 'i_user', + 'i_pass', + 'fingerPrint', + 'fingerGenPrint', + 'i_captcha', + }); + expect(form['fingerPrint'], _session.fingerprint); + expect(form['fingerGenPrint'], _session.fingerGenPrint); + } + }, + ); + test( 'exhausted CSRF recovery falls back to saved credentials once', () async { @@ -357,6 +413,8 @@ class _Transport extends http.BaseClient { int logins = 0; bool rejectRetry = false; bool needsVerification = false; + bool challengeForSingleLogin = false; + bool verifyPortalOnly = false; bool emptyCookieUntilPassword = false; bool rejectRoamingUntilPassword = false; int roamingRequests = 0; @@ -387,7 +445,11 @@ class _Transport extends http.BaseClient { body = '$publicKey'; case '/do/off/ui/auth/login/check': identityForms.add(Uri.splitQueryString((request as http.Request).body)); - body = needsVerification + body = + ((needsVerification && + (!verifyPortalOnly || identityForms.length > 1)) || + (challengeForSingleLogin && + identityForms.last['singleLogin'] == 'on')) ? '二次认证' : '登录成功。正在重定向到'; case '/wengine-vpn/cookie': diff --git a/packages/auth/test/support/fake_auth_http_client.dart b/packages/auth/test/support/fake_auth_http_client.dart index 07ca5b0..d811ddb 100644 --- a/packages/auth/test/support/fake_auth_http_client.dart +++ b/packages/auth/test/support/fake_auth_http_client.dart @@ -12,13 +12,18 @@ final class FakeAuthHttpClient extends http.BaseClient { this.honorTrustedBrowser = false, this.denySingleLogin = false, this.singleLoginAction = '/do/off/ui/auth/login/checkSingle', + String registeredFingerprint = 'stable-device', bool previouslyRegistered = false, - }) : _registered = previouslyRegistered; + }) : _registered = previouslyRegistered, + // Keep the synthetic server's registration identity configurable. + // ignore: prefer_initializing_formals + _registeredFingerprint = registeredFingerprint; final bool failInformationRedirect; final bool expireCookieBeforeLogin; bool _credentialsSubmitted = false; bool _registered; + String _registeredFingerprint; final bool trustWithoutToken; final bool trustedPortalForm; final bool honorTrustedBrowser; @@ -46,6 +51,9 @@ final class FakeAuthHttpClient extends http.BaseClient { } if (request.url.path == '/b/doubleAuth/personal/saveFinger') { _registered = true; + _registeredFingerprint = Uri.splitQueryString( + requestBody, + )['fingerprint']!; } final body = switch (request.url.path) { '/login' => '', @@ -69,7 +77,8 @@ final class FakeAuthHttpClient extends http.BaseClient { '/do/off/ui/auth/login/check' when honorTrustedBrowser && _registered && - requestBody.contains('singleLogin=on') => + Uri.splitQueryString(requestBody)['fingerPrint'] == + _registeredFingerprint => '登录成功。正在重定向到', '/do/off/ui/auth/login/check' when ++_identityLoginAttempts == 1 => '二次认证', diff --git a/packages/auth/test/thulium_auth_test.dart b/packages/auth/test/thulium_auth_test.dart index 2d18011..a3e8f14 100644 --- a/packages/auth/test/thulium_auth_test.dart +++ b/packages/auth/test/thulium_auth_test.dart @@ -800,14 +800,14 @@ void main() { .where((r) => r.url.path == '/do/off/ui/auth/login/check') .last as http.Request; - expect(portal.bodyFields['singleLogin'], 'on'); + expect(portal.bodyFields.containsKey('singleLogin'), isFalse); final initial = client.requests.firstWhere( (r) => r.url.path == '/do/off/ui/auth/login/check', ) as http.Request; - expect(initial.bodyFields['singleLogin'], 'on'); - expect(portal.bodyFields['deviceName'], 'Thulium'); + expect(initial.bodyFields.containsKey('singleLogin'), isFalse); + expect(portal.bodyFields.containsKey('deviceName'), isFalse); final nextTransport = FakeAuthHttpClient( honorTrustedBrowser: true, @@ -860,6 +860,7 @@ void main() { as http.Request; expect(single.bodyFields, { 'fingerPrint': 'stable-device', + 'fingerGenPrint': '', 'i_rememberme': 'on', 'execution': 'one&two', }); @@ -1103,6 +1104,52 @@ void main() { }, ); + test( + 'silent trusted confirmation supplies the persisted token and remember-me field', + () async { + final store = MemoryAuthSessionStore(); + await store.write( + AuthSession.fromJson({ + ..._savedSession().toJson(), + 'fingerGenPrint': 'saved-trusted-credential', + }), + ); + final transport = _SessionValidationClient( + studentId: '1234567890', + trustedEntry: true, + rejectExpiredCookie: true, + requiredTrustedCredential: 'saved-trusted-credential', + ); + final auth = TsinghuaAuthClient( + httpClient: transport, + sessionStore: store, + ); + await auth.restore(); + expect(await auth.validateSession(), isTrue); + final confirmation = + transport.requests.singleWhere( + (request) => + request.url.path == '/do/off/ui/auth/login/checkSingle', + ) + as http.Request; + expect( + confirmation.bodyFields['fingerPrint'], + _savedSession().fingerprint, + ); + expect( + confirmation.bodyFields['fingerGenPrint'], + 'saved-trusted-credential', + ); + expect(confirmation.bodyFields['i_rememberme'], 'on'); + expect( + transport.requests.where( + (request) => request.url.path == '/do/off/ui/auth/login/check', + ), + isEmpty, + ); + }, + ); + test( 'expired portal cookie recovers through live trusted SSO without a password or code', () async { @@ -1154,14 +1201,15 @@ void main() { final client = FakeAuthHttpClient( expireCookieBeforeLogin: true, honorTrustedBrowser: true, + registeredFingerprint: 'saved-device', previouslyRegistered: true, ); final auth = TsinghuaAuthClient(httpClient: client, sessionStore: store); await auth.restore(); expect(await auth.validateSession(), isFalse); expect(await store.read(), isNull); - // The expired cookies are gone, but this client can still request browser - // SSO for the same account/device during its one credential recovery. + // The expired cookies are gone; the same fingerprint remains available + // for server-side device trust without opting into singleLogin. final session = await auth.login( userId: '1234567890', password: 'password', @@ -1177,7 +1225,7 @@ void main() { (r) => r.url.path == '/do/off/ui/auth/login/check', ) as http.Request; - expect(post.bodyFields['singleLogin'], 'on'); + expect(post.bodyFields.containsKey('singleLogin'), isFalse); expect( post.headers['Cookie'] ?? '', isNot(contains('SESSION=webvpn-session')), @@ -1283,10 +1331,12 @@ final class _SessionValidationClient extends http.BaseClient { this.emptyCookieResponses = 0, this.trustedEntry = false, this.rejectExpiredCookie = false, + this.requiredTrustedCredential, }); final bool trustedEntry; final bool rejectExpiredCookie; + final String? requiredTrustedCredential; bool _singleCompleted = false; final String studentId; final int emptyCookieResponses; @@ -1303,8 +1353,14 @@ final class _SessionValidationClient extends http.BaseClient { '
'; } else if (trustedEntry && request.url.path == '/do/off/ui/auth/login/checkSingle') { - _singleCompleted = true; - body = '登录成功。正在重定向到'; + final fields = (request as http.Request).bodyFields; + _singleCompleted = + requiredTrustedCredential == null || + (fields['fingerGenPrint'] == requiredTrustedCredential && + fields['i_rememberme'] == 'on'); + body = _singleCompleted + ? '登录成功。正在重定向到' + : '二次认证'; } else if (request.url.path == '/wengine-vpn/cookie') { cookieRequests++; body = trustedEntry && !_singleCompleted && rejectExpiredCookie diff --git a/pubspec.lock b/pubspec.lock index d98c553..e023631 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -589,6 +589,22 @@ packages: url: "https://pub.dev" source: hosted version: "2.2.0" + package_info_plus: + dependency: "direct main" + description: + name: package_info_plus + sha256: "73ef2cd5c11a7548f9b7f6fc2a4f6113de2e64aa2a70de63feede95548822908" + url: "https://pub.dev" + source: hosted + version: "10.2.2" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + sha256: db762cb2f4f25ee60fb6359773861b0f199e00b90d237bd85a76a1e806b46ef4 + url: "https://pub.dev" + source: hosted + version: "4.1.0" path: dependency: transitive description: @@ -749,6 +765,62 @@ packages: url: "https://pub.dev" source: hosted version: "7.2.0" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f" + url: "https://pub.dev" + source: hosted + version: "2.5.6" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + sha256: "1e12aafe408aa50da80edfd679a2a6bf63ba7ab37c7fa98286da459a757b3399" + url: "https://pub.dev" + source: hosted + version: "2.4.28" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + sha256: "2ec3934efa51e46117f23031cc141b8fc878e8525b94ec1ea4f7f586cf1b47ea" + url: "https://pub.dev" + source: hosted + version: "2.5.7" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + shared_preferences_platform_interface: + dependency: "direct dev" + description: + name: shared_preferences_platform_interface + sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019 + url: "https://pub.dev" + source: hosted + version: "2.4.3" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1" + url: "https://pub.dev" + source: hosted + version: "2.4.1" shelf: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 754ae3b..7ca68f9 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -48,11 +48,14 @@ dependencies: # Upgrade to ^0.26.0 after moving to Flutter 3.47+. forui: ^0.22.0 pdfx: ^2.11.0 + shared_preferences: ^2.5.6 + package_info_plus: ^10.2.2 dev_dependencies: flutter_test: sdk: flutter test: ^1.26.0 + shared_preferences_platform_interface: ^2.4.2 # The "flutter_lints" package below contains a set of recommended lints to # encourage good coding practices. The lint set provided by the package is diff --git a/test/unit/diagnostics/diagnostic_export_test.dart b/test/unit/diagnostics/diagnostic_export_test.dart new file mode 100644 index 0000000..ef761ed --- /dev/null +++ b/test/unit/diagnostics/diagnostic_export_test.dart @@ -0,0 +1,76 @@ +import 'dart:ui'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:package_info_plus/package_info_plus.dart'; +import 'package:share_plus/share_plus.dart'; +import 'package:thulium/diagnostics/diagnostic_export.dart'; +import 'package:thulium/diagnostics/diagnostic_log.dart'; + +void main() { + test( + 'mobile export shares a named text file with version and sanitized events', + () async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final log = DiagnosticLog(store: _Store()); + addTearDown(log.dispose); + log.record( + '[auth] Credential recovery: cause=PortalCsrfUnavailable trustedCredentialPresent=true.', + ); + ShareParams? shared; + final export = DiagnosticExport( + log: log, + packageInfo: () async => PackageInfo( + appName: 'Thulium', + packageName: 'dev.thulium.app', + version: '1.0.0', + buildNumber: '2002', + ), + share: (params) async { + shared = params; + return const ShareResult('', ShareResultStatus.success); + }, + ); + const origin = Rect.fromLTWH(1, 2, 100, 40); + await export.export( + title: 'Export diagnostic logs', + sharePositionOrigin: origin, + ); + expect(shared!.sharePositionOrigin, origin); + expect( + shared!.fileNameOverrides!.single, + startsWith('thulium-diagnostics-'), + ); + expect(shared!.fileNameOverrides!.single, endsWith('.txt')); + final contents = await shared!.files!.single.readAsString(); + expect(contents, contains('App version: 1.0.0+2002')); + expect(contents, contains('Platform: android')); + expect(contents, contains('cause=PortalCsrfUnavailable')); + }, + ); + + test('unavailable package metadata does not block log export', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.android; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final log = DiagnosticLog(store: _Store()); + addTearDown(log.dispose); + String? report; + await DiagnosticExport( + log: log, + packageInfo: () async => throw StateError('unavailable metadata'), + share: (params) async { + report = await params.files!.single.readAsString(); + return const ShareResult('', ShareResultStatus.dismissed); + }, + ).export(title: 'Logs'); + expect(report, contains('App version: unknown+unknown')); + }); +} + +class _Store implements DiagnosticLogStore { + @override + Future> read() async => []; + @override + Future write(List lines) async {} +} diff --git a/test/unit/diagnostics/diagnostic_log_test.dart b/test/unit/diagnostics/diagnostic_log_test.dart new file mode 100644 index 0000000..6ed19d7 --- /dev/null +++ b/test/unit/diagnostics/diagnostic_log_test.dart @@ -0,0 +1,244 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; +import 'package:thulium/diagnostics/diagnostic_log.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test( + 'installed hooks collect live events and preserve existing error handlers', + () async { + final previousPrint = debugPrint; + final previousFlutterError = FlutterError.onError; + final previousPlatformError = PlatformDispatcher.instance.onError; + final log = DiagnosticLog(store: _Store()); + addTearDown(() { + log.dispose(); + debugPrint = previousPrint; + FlutterError.onError = previousFlutterError; + PlatformDispatcher.instance.onError = previousPlatformError; + }); + var printed = 0; + var flutterErrors = 0; + debugPrint = (String? message, {int? wrapWidth}) => printed++; + FlutterError.onError = (_) => flutterErrors++; + PlatformDispatcher.instance.onError = (_, _) => true; + log.install(); + debugPrint('[auth] HTTP response status=401 elapsedMs=8'); + FlutterError.onError!( + FlutterErrorDetails(exception: StateError('private-message')), + ); + expect( + PlatformDispatcher.instance.onError!( + const FormatException('private-message'), + StackTrace.empty, + ), + isTrue, + ); + final report = await log.snapshot(); + expect(printed, 1); + expect(flutterErrors, 1); + expect(report, contains('status=401')); + expect(report, contains('event=flutter-error type=StateError')); + expect(report, contains('event=platform-error type=FormatException')); + expect(report, isNot(contains('private-message'))); + }, + ); + + test( + 'the platform log store survives recreation without replacing appearance preferences', + () async { + final previous = SharedPreferencesAsyncPlatform.instance; + SharedPreferencesAsyncPlatform.instance = + InMemorySharedPreferencesAsync.withData({ + 'thulium.preferences.v1': 'appearance-preferences', + }); + addTearDown(() => SharedPreferencesAsyncPlatform.instance = previous); + final first = DiagnosticLog(store: LocalDiagnosticLogStore()); + addTearDown(first.dispose); + first.record('[app] event=started'); + await first.flush(); + final restarted = DiagnosticLog(store: LocalDiagnosticLogStore()); + addTearDown(restarted.dispose); + expect(await restarted.snapshot(), contains('event=started')); + expect( + await SharedPreferencesAsync().getString('thulium.preferences.v1'), + 'appearance-preferences', + ); + }, + ); + + test( + 'recording retains structural diagnosis without credential, URL or content values', + () async { + final store = _Store(); + final log = DiagnosticLog( + store: store, + now: () => DateTime.utc(2026, 11, 18), + ); + addTearDown(log.dispose); + const secrets = [ + 'password-value', + '1234567890', + '654321', + 'secret-token', + 'private-file', + 'private-course-title', + ]; + log.record( + '[auth] HTTP GET webvpn.tsinghua.edu.cn/https/encoded/downloadPdfStream/all/private-file/1234567890?token=secret-token formKeys=i_pass cookieNames=SESSION', + ); + log.record( + '[auth] HTTP response status=403 elapsedMs=42 location=https://example.com?ticket=secret-token cookieNames=SESSION', + ); + log.record( + '[auth] Unexpected response stage=portal-user-data status=401 host=webvpn.tsinghua.edu.cn bodyType=html bodyLength=99 preview="private-course-title password-value 654321 secret-token"', + ); + log.record( + '[auth] Credential recovery: cause=PortalSessionRejected trustedCredentialPresent=true.', + ); + log.record( + '[auth] Second-factor challenge: stage=webvpn trustedCredentialPresent=true.', + ); + log.record('arbitrary password=password-value cookie=secret-token'); + log.record('[auth] cookie=secret-token'); + log.recordError( + 'flutter-error', + StateError('password-value'), + StackTrace.fromString( + '#0 fn (package:thulium/pages/login_page.dart:12:3)\n#1 /home/private-file.dart:1:2', + ), + ); + final report = await log.snapshot(); + for (final secret in secrets) { + expect(report, isNot(contains(secret))); + expect(store.lines.join('\n'), isNot(contains(secret))); + } + expect(report, contains('HTTP GET endpoint=learn-preview')); + expect(report, contains('status=403 elapsedMs=42')); + expect(report, contains('cause=PortalSessionRejected')); + expect(report, contains('stage=webvpn trustedCredentialPresent=true')); + expect(report, contains('package:thulium/pages/login_page.dart:12:3')); + }, + ); + + test( + 'persisted events survive restart and are filtered again on import', + () async { + final store = _Store(); + final first = DiagnosticLog( + store: store, + now: () => DateTime.utc(2026, 11, 18), + ); + addTearDown(first.dispose); + first.record( + '[auth][signin=2] Using the trusted-browser identity entry.', + ); + first.record( + '[auth] Session restored: trustedCredentialPresent=true deviceTrustConsent=true.', + ); + first.record( + '[auth] Credential recovery skipped: reason=missing-credentials.', + ); + first.record( + '[auth] HTTP timeout phase=body host=private-host elapsedMs=30000', + ); + first.record( + '[signin] attempt=2 stage=failed type=TwoFactorInteractionRequired', + ); + final original = await first.snapshot(); + store.lines.add('2026-11-18T00:00:00.000Z unrecognized secret-value'); + final second = DiagnosticLog( + store: store, + now: () => DateTime.utc(2026, 11, 18), + ); + addTearDown(second.dispose); + expect(await second.snapshot(), original); + expect(store.lines.join('\n'), isNot(contains('secret-value'))); + }, + ); + + test('old logs expire and event count stays bounded', () async { + final store = _Store() + ..lines = [ + '2026-10-01T00:00:00.000Z [app] event=started', + '2026-11-17T00:00:00.000Z [app] event=started', + ]; + final log = DiagnosticLog( + store: store, + now: () => DateTime.utc(2026, 11, 18), + maxEntries: 3, + ); + addTearDown(log.dispose); + await log.initialize(); + for (var index = 1; index <= 4; index++) { + log.record('[signin] attempt=$index stage=start'); + } + await log.flush(); + expect(store.lines, hasLength(3)); + expect(store.lines.first, contains('attempt=2')); + expect(store.lines.last, contains('attempt=4')); + }); + + test( + 'storage failures do not discard in-memory diagnostics or prevent exporting', + () async { + final store = _Store()..fail = true; + final log = DiagnosticLog(store: store); + addTearDown(log.dispose); + log.record( + '[auth] Second-factor challenge: stage=information-portal trustedCredentialPresent=false.', + ); + expect( + await log.snapshot(), + contains('stage=information-portal trustedCredentialPresent=false'), + ); + store.fail = false; + await log.flush(); + expect(store.lines.join('\n'), contains('information-portal')); + }, + ); + + test('overlapping flushes preserve the newest log snapshot', () async { + final store = _Store()..blockedWrite = Completer(); + final log = DiagnosticLog(store: store); + addTearDown(log.dispose); + log.record('[signin] attempt=1 stage=start'); + final first = log.flush(); + await store.writeStarted.future; + log.record('[signin] attempt=1 stage=success'); + final second = log.flush(); + expect(store.writes, 1); + store.blockedWrite!.complete(); + await Future.wait([first, second]); + expect(store.lines.last, contains('stage=success')); + expect(store.writes, 2); + }); +} + +class _Store implements DiagnosticLogStore { + List lines = []; + bool fail = false; + int writes = 0; + Completer? blockedWrite; + final writeStarted = Completer(); + @override + Future> read() async { + if (fail) throw StateError('synthetic read failure'); + return List.of(lines); + } + + @override + Future write(List value) async { + writes++; + if (!writeStarted.isCompleted) writeStarted.complete(); + if (writes == 1) await blockedWrite?.future; + if (fail) throw StateError('synthetic write failure'); + lines = List.of(value); + } +} diff --git a/test/widget/app/preferences_test.dart b/test/widget/app/preferences_test.dart new file mode 100644 index 0000000..5974985 --- /dev/null +++ b/test/widget/app/preferences_test.dart @@ -0,0 +1,235 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences_platform_interface/in_memory_shared_preferences_async.dart'; +import 'package:shared_preferences_platform_interface/shared_preferences_async_platform_interface.dart'; +import 'package:thulium/app.dart'; +import 'package:thulium/pages/home_page.dart'; +import 'package:thulium/pages/welcome_page.dart'; +import 'package:thulium/preferences/app_preferences_store.dart'; +import 'package:thulium/widgets/language_button.dart'; +import 'package:thulium_auth/thulium_auth.dart'; + +void main() { + setUp(() { + final original = SharedPreferencesAsyncPlatform.instance; + SharedPreferencesAsyncPlatform.instance = + InMemorySharedPreferencesAsync.empty(); + addTearDown(() => SharedPreferencesAsyncPlatform.instance = original); + }); + for (final locale in [ + const Locale('en'), + const Locale('zh', 'CN'), + const Locale('zh', 'TW'), + ]) { + testWidgets('restores theme and $locale after rebuilding the app', ( + tester, + ) async { + final preferences = LocalAppPreferencesStore(); + final session = MemoryAuthSessionStore(); + await tester.pumpWidget( + ThuliumApp( + sessionStore: session, + preferencesStore: LocalAppPreferencesStore(), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.bySemanticsLabel('Theme')); + tester + .widget(find.byType(LanguageButton)) + .onSelected(locale); + await tester.pumpAndSettle(); + expect(_app(tester).themeMode, ThemeMode.dark); + expect(_app(tester).locale, locale); + + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpWidget( + ThuliumApp(sessionStore: session, preferencesStore: preferences), + ); + await tester.pumpAndSettle(); + expect(_app(tester).themeMode, ThemeMode.dark); + expect(_app(tester).locale, locale); + expect(find.byType(WelcomePage), findsOneWidget); + }); + } + + testWidgets('an explicit light theme overrides a dark system after restart', ( + tester, + ) async { + tester.platformDispatcher.platformBrightnessTestValue = Brightness.dark; + addTearDown(tester.platformDispatcher.clearPlatformBrightnessTestValue); + final preferences = LocalAppPreferencesStore(); + final session = MemoryAuthSessionStore(); + await tester.pumpWidget( + ThuliumApp(sessionStore: session, preferencesStore: preferences), + ); + await tester.pumpAndSettle(); + await tester.tap(find.bySemanticsLabel('Theme')); + await tester.pumpAndSettle(); + await tester.pumpWidget(const SizedBox.shrink()); + await tester.pumpWidget( + ThuliumApp(sessionStore: session, preferencesStore: preferences), + ); + await tester.pumpAndSettle(); + expect(_app(tester).themeMode, ThemeMode.light); + }); + + testWidgets('logout retains installation theme and language', (tester) async { + final preferences = LocalAppPreferencesStore(); + await preferences.write( + const AppPreferences( + themeMode: ThemeMode.dark, + locale: Locale('zh', 'TW'), + ), + ); + final session = MemoryAuthSessionStore(); + await session.write( + const AuthSession(userId: '1234567890', fingerprint: 'test', cookies: {}), + ); + await tester.pumpWidget( + ThuliumApp(sessionStore: session, preferencesStore: preferences), + ); + await tester.pumpAndSettle(); + expect( + await tester.widget(find.byType(HomePage)).onLogout(), + isTrue, + ); + await tester.pumpAndSettle(); + expect(find.byType(WelcomePage), findsOneWidget); + final retained = await LocalAppPreferencesStore().read(); + expect(retained.themeMode, ThemeMode.dark); + expect(retained.locale, const Locale('zh', 'TW')); + }); + + testWidgets('waits for saved preferences before showing welcome content', ( + tester, + ) async { + final loaded = Completer(); + final preferences = _PreferencesStore()..pendingRead = loaded; + await tester.pumpWidget( + ThuliumApp( + sessionStore: MemoryAuthSessionStore(), + preferencesStore: preferences, + ), + ); + await tester.pump(); + expect(find.byType(WelcomePage), findsNothing); + loaded.complete( + const AppPreferences( + themeMode: ThemeMode.dark, + locale: Locale('zh', 'TW'), + ), + ); + await tester.pumpAndSettle(); + expect(find.byType(WelcomePage), findsOneWidget); + expect(_app(tester).themeMode, ThemeMode.dark); + expect(_app(tester).locale, const Locale('zh', 'TW')); + }); + + testWidgets( + 'read failure falls back to defaults and a failed write does not block later choices', + (tester) async { + final preferences = _PreferencesStore() + ..failRead = true + ..failNextWrite = true; + await tester.pumpWidget( + ThuliumApp( + sessionStore: MemoryAuthSessionStore(), + preferencesStore: preferences, + ), + ); + await tester.pumpAndSettle(); + expect(_app(tester).themeMode, ThemeMode.system); + expect(_app(tester).locale, const Locale('en')); + await tester.tap(find.bySemanticsLabel('Theme')); + await tester.pumpAndSettle(); + tester + .widget(find.byType(LanguageButton)) + .onSelected(const Locale('zh', 'CN')); + await tester.pumpAndSettle(); + final saved = AppPreferences.decode(preferences.encoded!); + expect(saved.themeMode, ThemeMode.dark); + expect(saved.locale, const Locale('zh', 'CN')); + expect(tester.takeException(), isNull); + }, + ); + + testWidgets( + 'a slow write cannot overwrite a newer theme and language choice', + (tester) async { + final firstWrite = Completer(); + final preferences = _PreferencesStore()..pendingWrite = firstWrite; + await tester.pumpWidget( + ThuliumApp( + sessionStore: MemoryAuthSessionStore(), + preferencesStore: preferences, + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.bySemanticsLabel('Theme')); + await tester.pump(); + tester + .widget(find.byType(LanguageButton)) + .onSelected(const Locale('zh', 'TW')); + await tester.pump(); + expect(preferences.writes, 1); + firstWrite.complete(); + await tester.pumpAndSettle(); + final saved = AppPreferences.decode(preferences.encoded!); + expect(saved.themeMode, ThemeMode.dark); + expect(saved.locale, const Locale('zh', 'TW')); + expect(preferences.writes, 2); + }, + ); + + test( + 'corrupt and obsolete preferences preserve supported values and defaults', + () { + expect(AppPreferences.decode('broken').themeMode, ThemeMode.system); + expect(AppPreferences.decode('[]').locale, const Locale('en')); + final obsolete = AppPreferences.decode( + '{"theme":"obsolete","locale":"zh-TW"}', + ); + expect(obsolete.themeMode, ThemeMode.system); + expect(obsolete.locale, const Locale('zh', 'TW')); + final unknownLanguage = AppPreferences.decode( + '{"theme":"dark","locale":"unknown"}', + ); + expect(unknownLanguage.themeMode, ThemeMode.dark); + expect(unknownLanguage.locale, const Locale('en')); + }, + ); +} + +MaterialApp _app(WidgetTester tester) => + tester.widget(find.byType(MaterialApp)); + +class _PreferencesStore implements AppPreferencesStore { + String? encoded; + Completer? pendingRead; + Completer? pendingWrite; + bool failRead = false; + bool failNextWrite = false; + int writes = 0; + + @override + Future read() async { + if (failRead) throw StateError('synthetic read failure'); + if (pendingRead != null) return pendingRead!.future; + return encoded == null + ? const AppPreferences() + : AppPreferences.decode(encoded!); + } + + @override + Future write(AppPreferences preferences) async { + writes++; + if (failNextWrite) { + failNextWrite = false; + throw StateError('synthetic write failure'); + } + if (writes == 1) await pendingWrite?.future; + encoded = preferences.encode(); + } +} diff --git a/test/widget/settings/diagnostic_export_test.dart b/test/widget/settings/diagnostic_export_test.dart new file mode 100644 index 0000000..20b2d76 --- /dev/null +++ b/test/widget/settings/diagnostic_export_test.dart @@ -0,0 +1,103 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:forui/forui.dart'; +import 'package:thulium/l10n/generated/app_localizations.dart'; +import 'package:thulium/pages/settings_page.dart'; +import 'package:thulium/pages/welcome_page.dart'; + +void main() { + testWidgets('export is single flight and supplies an iPad share anchor', ( + tester, + ) async { + final completed = Completer(); + var exports = 0; + Rect? anchor; + await tester.pumpWidget( + _app( + SettingsPage( + exportDiagnostics: (origin) async { + exports++; + anchor = origin; + await completed.future; + }, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Export diagnostic logs')); + await tester.pump(); + await tester.tap(find.byType(FButton).last); + await tester.pump(); + expect(exports, 1); + expect(anchor, isNotNull); + expect(anchor!.width, greaterThan(0)); + completed.complete(); + await tester.pumpAndSettle(); + expect(find.text('Export diagnostic logs'), findsOneWidget); + expect(find.text('Log out'), findsNothing); + }); + + testWidgets('failed sharing offers retry and does not log out the account', ( + tester, + ) async { + var exports = 0; + var logouts = 0; + await tester.pumpWidget( + _app( + SettingsPage( + onLogout: () async { + logouts++; + return false; + }, + exportDiagnostics: (_) async { + if (++exports == 1) throw StateError('synthetic export failure'); + }, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('Export diagnostic logs')); + await tester.pumpAndSettle(); + expect( + find.text('Could not export logs, please try again'), + findsOneWidget, + ); + await tester.tap(find.text('Export diagnostic logs')); + await tester.pumpAndSettle(); + expect(exports, 2); + expect(logouts, 0); + expect(find.text('Could not export logs, please try again'), findsNothing); + }); + + testWidgets('welcome exposes log export even when sign-in is unavailable', ( + tester, + ) async { + await tester.pumpWidget( + _app( + WelcomePage( + onLocaleSelected: (_) {}, + onThemeToggle: () {}, + onLoginSuccess: () {}, + ), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.bySemanticsLabel('Settings')); + await tester.pumpAndSettle(); + expect(find.text('Export diagnostic logs'), findsOneWidget); + expect(find.text('Log out'), findsNothing); + }); +} + +Widget _app(Widget home) => MaterialApp( + localizationsDelegates: [ + ...AppLocalizations.localizationsDelegates, + ...FLocalizations.localizationsDelegates, + ], + supportedLocales: AppLocalizations.supportedLocales, + builder: (context, child) => + FTheme(data: FThemes.neutral.light.touch, child: child!), + home: home, +); From 5857321c26e5a2fbc0e42902105bf27ec42fad90 Mon Sep 17 00:00:00 2001 From: ashgrey Date: Thu, 19 Nov 2026 00:44:13 +0800 Subject: [PATCH 23/26] fix(auth): handle trusted-device registration failures explicitly Request device trust only after successful verification and reuse the choice throughout the login attempt. Show a clear warning when the trusted-device quota is reached, then continue sign-in without marking the device as trusted. Surface other registration failures instead of silently ignoring them. Allow users to retry sign-in without device registration. Record classified failure reasons and HTTP status codes in diagnostic exports without retaining raw provider messages or sensitive values. Add regression coverage for registration failures, quota warnings, successful token persistence, and sign-in recovery. --- lib/diagnostics/diagnostic_log.dart | 16 ++ lib/l10n/app_en.arb | 6 +- lib/l10n/app_zh.arb | 6 +- lib/l10n/app_zh_CN.arb | 6 +- lib/l10n/app_zh_TW.arb | 6 +- lib/l10n/generated/app_localizations.dart | 24 +++ lib/l10n/generated/app_localizations_en.dart | 14 ++ lib/l10n/generated/app_localizations_zh.dart | 39 ++++ lib/pages/login_page.dart | 30 ++- packages/auth/README.md | 18 +- packages/auth/lib/thulium_auth.dart | 156 +++++++++++---- packages/auth/test/device_trust_test.dart | 177 ++++++++++++++++++ .../test/support/fake_auth_http_client.dart | 24 ++- packages/campus/lib/src/learn_courses.dart | 2 +- packages/campus/lib/src/learn_homework.dart | 12 +- packages/campus/lib/src/learn_materials.dart | 8 +- packages/cli/lib/cli_runtime.dart | 4 + .../unit/diagnostics/diagnostic_log_test.dart | 10 + test/widget/auth/login_page_test.dart | 101 +++++++++- 19 files changed, 587 insertions(+), 72 deletions(-) create mode 100644 packages/auth/test/device_trust_test.dart diff --git a/lib/diagnostics/diagnostic_log.dart b/lib/diagnostics/diagnostic_log.dart index 8c7c5c0..04ce544 100644 --- a/lib/diagnostics/diagnostic_log.dart +++ b/lib/diagnostics/diagnostic_log.dart @@ -177,6 +177,7 @@ const _TYPES = { 'CourseScheduleException', 'CourseScheduleSessionExpired', 'TwoFactorInteractionRequired', + 'DeviceTrustRegistrationException', 'UnsupportedError', 'FlutterError', 'TypeError', @@ -370,6 +371,21 @@ String? sanitizeDiagnosticMessage(String input) { final cause = _TYPES.contains(value('cause')) ? value('cause') : 'other'; return '[$scope] Credential recovery: cause=$cause trustedCredentialPresent=${value('trustedCredentialPresent') == 'true'}'; } + if (body.startsWith('Trusted-device registration rejected:')) { + final reason = + const { + 'limit-reached', + 'session-rejected', + 'access-restricted', + 'invalid-fingerprint', + 'invalid-response', + 'network-error', + 'rejected', + }.contains(value('reason')) + ? value('reason') + : 'rejected'; + return '[$scope] Trusted-device registration rejected: reason=$reason status=${int.tryParse(value('status') ?? '') ?? 0}'; + } if (body.startsWith('Session restored:')) { return '[$scope] Session restored: trustedCredentialPresent=${value('trustedCredentialPresent') == 'true'} deviceTrustConsent=${value('deviceTrustConsent') == 'true'}'; } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 1dc8f20..3733287 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -209,5 +209,9 @@ "courseContentLoading": "Loading course content", "coursePreviewLoading": "Loading document", "exportDiagnostics": "Export diagnostic logs", - "exportDiagnosticsError": "Could not export logs, please try again" + "exportDiagnosticsError": "Could not export logs, please try again", + "deviceTrustLimitTitle": "Trusted device limit reached", + "deviceTrustLimitDescription": "Sign-in can continue, but this device will not be remembered. Manage old trusted browsers at id.tsinghua.edu.cn, then try again", + "continueSignInAction": "Continue sign-in", + "deviceTrustRegistrationError": "Could not trust this device. Try signing in again and choose Not now, or export diagnostic logs" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index c489505..3274911 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -193,5 +193,9 @@ "courseContentLoading": "正在加载课程内容", "coursePreviewLoading": "正在加载文档", "exportDiagnostics": "导出诊断日志", - "exportDiagnosticsError": "日志导出失败,请重试" + "exportDiagnosticsError": "日志导出失败,请重试", + "deviceTrustLimitTitle": "信任设备数量已达上限", + "deviceTrustLimitDescription": "本次可以继续登录,但不会记住此设备。请到 id.tsinghua.edu.cn 管理旧的信任浏览器后重试", + "continueSignInAction": "继续登录", + "deviceTrustRegistrationError": "无法信任此设备,请重新登录并选择“暂不”,或导出诊断日志" } diff --git a/lib/l10n/app_zh_CN.arb b/lib/l10n/app_zh_CN.arb index 051926c..65f9c20 100644 --- a/lib/l10n/app_zh_CN.arb +++ b/lib/l10n/app_zh_CN.arb @@ -193,5 +193,9 @@ "courseContentLoading": "正在加载课程内容", "coursePreviewLoading": "正在加载文档", "exportDiagnostics": "导出诊断日志", - "exportDiagnosticsError": "日志导出失败,请重试" + "exportDiagnosticsError": "日志导出失败,请重试", + "deviceTrustLimitTitle": "信任设备数量已达上限", + "deviceTrustLimitDescription": "本次可以继续登录,但不会记住此设备。请到 id.tsinghua.edu.cn 管理旧的信任浏览器后重试", + "continueSignInAction": "继续登录", + "deviceTrustRegistrationError": "无法信任此设备,请重新登录并选择“暂不”,或导出诊断日志" } diff --git a/lib/l10n/app_zh_TW.arb b/lib/l10n/app_zh_TW.arb index 1d99d74..3ce1e40 100644 --- a/lib/l10n/app_zh_TW.arb +++ b/lib/l10n/app_zh_TW.arb @@ -193,5 +193,9 @@ "courseContentLoading": "正在載入課程內容", "coursePreviewLoading": "正在載入文件", "exportDiagnostics": "匯出診斷日誌", - "exportDiagnosticsError": "日誌匯出失敗,請重試" + "exportDiagnosticsError": "日誌匯出失敗,請重試", + "deviceTrustLimitTitle": "信任裝置數量已達上限", + "deviceTrustLimitDescription": "本次可以繼續登入,但不會記住此裝置。請到 id.tsinghua.edu.cn 管理舊的信任瀏覽器後重試", + "continueSignInAction": "繼續登入", + "deviceTrustRegistrationError": "無法信任此裝置,請重新登入並選擇「暫不」,或匯出診斷日誌" } diff --git a/lib/l10n/generated/app_localizations.dart b/lib/l10n/generated/app_localizations.dart index c35e7d7..161d44d 100644 --- a/lib/l10n/generated/app_localizations.dart +++ b/lib/l10n/generated/app_localizations.dart @@ -1209,6 +1209,30 @@ abstract class AppLocalizations { /// In en, this message translates to: /// **'Could not export logs, please try again'** String get exportDiagnosticsError; + + /// No description provided for @deviceTrustLimitTitle. + /// + /// In en, this message translates to: + /// **'Trusted device limit reached'** + String get deviceTrustLimitTitle; + + /// No description provided for @deviceTrustLimitDescription. + /// + /// In en, this message translates to: + /// **'Sign-in can continue, but this device will not be remembered. Manage old trusted browsers at id.tsinghua.edu.cn, then try again'** + String get deviceTrustLimitDescription; + + /// No description provided for @continueSignInAction. + /// + /// In en, this message translates to: + /// **'Continue sign-in'** + String get continueSignInAction; + + /// No description provided for @deviceTrustRegistrationError. + /// + /// In en, this message translates to: + /// **'Could not trust this device. Try signing in again and choose Not now, or export diagnostic logs'** + String get deviceTrustRegistrationError; } class _AppLocalizationsDelegate diff --git a/lib/l10n/generated/app_localizations_en.dart b/lib/l10n/generated/app_localizations_en.dart index 8f5686b..c822ed6 100644 --- a/lib/l10n/generated/app_localizations_en.dart +++ b/lib/l10n/generated/app_localizations_en.dart @@ -618,4 +618,18 @@ class AppLocalizationsEn extends AppLocalizations { @override String get exportDiagnosticsError => 'Could not export logs, please try again'; + + @override + String get deviceTrustLimitTitle => 'Trusted device limit reached'; + + @override + String get deviceTrustLimitDescription => + 'Sign-in can continue, but this device will not be remembered. Manage old trusted browsers at id.tsinghua.edu.cn, then try again'; + + @override + String get continueSignInAction => 'Continue sign-in'; + + @override + String get deviceTrustRegistrationError => + 'Could not trust this device. Try signing in again and choose Not now, or export diagnostic logs'; } diff --git a/lib/l10n/generated/app_localizations_zh.dart b/lib/l10n/generated/app_localizations_zh.dart index 3be5c3a..2d06966 100644 --- a/lib/l10n/generated/app_localizations_zh.dart +++ b/lib/l10n/generated/app_localizations_zh.dart @@ -585,6 +585,19 @@ class AppLocalizationsZh extends AppLocalizations { @override String get exportDiagnosticsError => '日志导出失败,请重试'; + + @override + String get deviceTrustLimitTitle => '信任设备数量已达上限'; + + @override + String get deviceTrustLimitDescription => + '本次可以继续登录,但不会记住此设备。请到 id.tsinghua.edu.cn 管理旧的信任浏览器后重试'; + + @override + String get continueSignInAction => '继续登录'; + + @override + String get deviceTrustRegistrationError => '无法信任此设备,请重新登录并选择“暂不”,或导出诊断日志'; } /// The translations for Chinese, as used in China (`zh_CN`). @@ -1168,6 +1181,19 @@ class AppLocalizationsZhCn extends AppLocalizationsZh { @override String get exportDiagnosticsError => '日志导出失败,请重试'; + + @override + String get deviceTrustLimitTitle => '信任设备数量已达上限'; + + @override + String get deviceTrustLimitDescription => + '本次可以继续登录,但不会记住此设备。请到 id.tsinghua.edu.cn 管理旧的信任浏览器后重试'; + + @override + String get continueSignInAction => '继续登录'; + + @override + String get deviceTrustRegistrationError => '无法信任此设备,请重新登录并选择“暂不”,或导出诊断日志'; } /// The translations for Chinese, as used in Taiwan (`zh_TW`). @@ -1751,4 +1777,17 @@ class AppLocalizationsZhTw extends AppLocalizationsZh { @override String get exportDiagnosticsError => '日誌匯出失敗,請重試'; + + @override + String get deviceTrustLimitTitle => '信任裝置數量已達上限'; + + @override + String get deviceTrustLimitDescription => + '本次可以繼續登入,但不會記住此裝置。請到 id.tsinghua.edu.cn 管理舊的信任瀏覽器後重試'; + + @override + String get continueSignInAction => '繼續登入'; + + @override + String get deviceTrustRegistrationError => '無法信任此裝置,請重新登入並選擇「暫不」,或匯出診斷日誌'; } diff --git a/lib/pages/login_page.dart b/lib/pages/login_page.dart index 3960b32..3b4a50e 100644 --- a/lib/pages/login_page.dart +++ b/lib/pages/login_page.dart @@ -16,6 +16,7 @@ typedef LoginAuthClientBuilder = required TwoFactorMethodHandler twoFactorMethodHandler, required TwoFactorCodeHandler twoFactorCodeHandler, required TwoFactorTrustHandler twoFactorTrustHandler, + required TwoFactorAuthLimitHandler twoFactorAuthLimitHandler, required AuthTraceHandler trace, }); @@ -169,6 +170,7 @@ final class _LoginPageState extends State { twoFactorMethodHandler: _selectTwoFactorMethod, twoFactorCodeHandler: _readTwoFactorCode, twoFactorTrustHandler: _askToTrustDevice, + twoFactorAuthLimitHandler: _showDeviceTrustLimit, trace: (message) => debugPrint('[auth][signin=$_attemptId] $message'), ); @@ -221,7 +223,9 @@ final class _LoginPageState extends State { ); if (mounted) { setState( - () => _errorMessage = AppLocalizations.of(context)!.loginError, + () => _errorMessage = error is DeviceTrustRegistrationException + ? AppLocalizations.of(context)!.deviceTrustRegistrationError + : AppLocalizations.of(context)!.loginError, ); } } finally { @@ -317,6 +321,30 @@ final class _LoginPageState extends State { return _trustChoice = _showTrustDeviceDialog(); } + Future _showDeviceTrustLimit() async { + if (!mounted) return; + final l10n = AppLocalizations.of(context)!; + var answered = false; + await showFDialog( + context: context, + builder: (context, _, animation) => FDialog.adaptive( + animation: animation, + title: Text(l10n.deviceTrustLimitTitle), + body: Text(l10n.deviceTrustLimitDescription), + actions: [ + FButton( + onPress: () { + if (answered || ModalRoute.of(context)?.isCurrent != true) return; + answered = true; + Navigator.of(context).pop(); + }, + child: Text(l10n.continueSignInAction), + ), + ], + ), + ); + } + Future _showTrustDeviceDialog() async { final l10n = AppLocalizations.of(context)!; var answered = false; diff --git a/packages/auth/README.md b/packages/auth/README.md index 419d349..b6e0ed3 100644 --- a/packages/auth/README.md +++ b/packages/auth/README.md @@ -42,9 +42,9 @@ If validation cleared rejected cookies and credential recovery fails, the runner persists only the original account/device identity, without cookies. This keeps a later refresh eligible for recovery while preserving separately saved passwords. -Learn follows the service-first recovery policy used by OneTHU: a confirmed -Learn login page or HTTP 401 first verifies the main account. If that account is -still authenticated, rebuild only Learn through roaming and retry the read once. +For a confirmed Learn login page or HTTP 401, first verify the main account. +If that account is still authenticated, rebuild only Learn through roaming and +retry the read once. Confirmed main-session rejection is escalated to credential recovery; the runner's bounded portal-CSRF fallback remains available as described above. Bare file HTTP 403/404/5xx responses and unsupported PDF conversions remain @@ -53,9 +53,15 @@ not prove logout. PDF reads carry the current Learn CSRF token, and temporary service failures offer retry rather than sending users back to sign-in. Device trust records registration consent separately from the optional legacy -`fingerGenPrint` token. Sign-in asks once and registers the fingerprint only after -successful code verification. Credential forms match `main`: account, encrypted -password, fingerprint, trusted-device token and captcha. They do not implicitly +`fingerGenPrint` token. Sign-in asks once only after successful code verification, +then registers the fingerprint. A quota rejection invokes +`twoFactorAuthLimitHandler` once and continues without claiming this device was +trusted. Other registration, transport and malformed-response failures throw +`DeviceTrustRegistrationException` instead of silently succeeding. Provider +messages are classified into fixed diagnostic reason codes; their raw text is +not persisted or exported. No registration retry is made later in the same +login, and no post-login registration is attempted. Credential forms contain the +account, encrypted password, fingerprint, trusted-device token and captcha. They do not implicitly enable the separate `singleLogin`/`deviceName` browser-SSO option. A remembered trust choice alone is not proof that the server will waive verification. Server-provided `checkSingle` forms are followed before falling back to diff --git a/packages/auth/lib/thulium_auth.dart b/packages/auth/lib/thulium_auth.dart index 344d5d5..784d025 100644 --- a/packages/auth/lib/thulium_auth.dart +++ b/packages/auth/lib/thulium_auth.dart @@ -475,6 +475,38 @@ typedef TwoFactorCodeHandler = /// Asks whether the user wants this installation registered as a trusted device. typedef TwoFactorTrustHandler = Future Function(); +/// Reports the server's trusted-device quota while allowing sign-in to continue. +typedef TwoFactorAuthLimitHandler = Future Function(); + +enum DeviceTrustFailureReason { + limitReached, + sessionRejected, + accessRestricted, + invalidFingerprint, + invalidResponse, + networkError, + rejected; + + String get diagnosticCode => switch (this) { + limitReached => 'limit-reached', + sessionRejected => 'session-rejected', + accessRestricted => 'access-restricted', + invalidFingerprint => 'invalid-fingerprint', + invalidResponse => 'invalid-response', + networkError => 'network-error', + rejected => 'rejected', + }; +} + +/// Contains only a classified reason; provider messages can contain private data. +final class DeviceTrustRegistrationException implements Exception { + const DeviceTrustRegistrationException(this.reason); + final DeviceTrustFailureReason reason; + @override + String toString() => + 'DeviceTrustRegistrationException: ${reason.diagnosticCode}'; +} + /// Receives safe authentication diagnostics without credential values. typedef AuthTraceHandler = void Function(String message); @@ -487,6 +519,7 @@ final class TsinghuaAuthClient { this.twoFactorMethodHandler, this.twoFactorCodeHandler, this.twoFactorTrustHandler, + this.twoFactorAuthLimitHandler, this.trace, this.requestTimeout = _DEFAULT_REQUEST_TIMEOUT, }) : _http = httpClient ?? http.Client(), @@ -511,9 +544,11 @@ final class TsinghuaAuthClient { /// Called only after the selected second-factor code has been requested. final TwoFactorCodeHandler? twoFactorCodeHandler; - /// Called once per sign-in to obtain consent for post-verification trust. + /// Called once after successful code verification to request device trust. final TwoFactorTrustHandler? twoFactorTrustHandler; + final TwoFactorAuthLimitHandler? twoFactorAuthLimitHandler; + /// Optional diagnostic callback. Messages contain no passwords, codes, or /// cookie values and are disabled by default. final AuthTraceHandler? trace; @@ -786,9 +821,9 @@ final class TsinghuaAuthClient { String _readInformationPortalCsrf(_Response response) { // The WebVPN cookie endpoint returns a cookie string in its response body, - // not in Set-Cookie. OneTHU imports that string into its jar before using - // the target service. Keep each imported cookie scoped to the service that - // owns it; WebVPN infrastructure cookies remain with the proxy host. + // not in Set-Cookie. Import that string before using the target service. + // Keep imported cookies scoped to their owning service; WebVPN + // infrastructure cookies remain with the proxy host. final pairs = {}; if (response.statusCode == 200 && !response.body.contains('<')) { for (final part in response.body.split(RegExp(r'[;\r\n]'))) { @@ -1046,12 +1081,9 @@ final class TsinghuaAuthClient { previousSession.fingerprint == fingerprint && (previousSession.trustedBrowser || previousSession.fingerGenPrint?.isNotEmpty == true); - // Cache one device-registration choice for this attempt. Device trust and - // the ID site's optional singleLogin checkbox are separate choices; routine - // credential recovery must keep the same fields as the main branch. - _trustDecision = - _trustedBrowser || - await (twoFactorTrustHandler?.call() ?? Future.value(false)); + // Ask about registration only after a code is verified, and + // reuse that one choice across the WebVPN and portal stages. + _trustDecision = null; _registeredDuringLogin = false; // The old account must not be used to probe or silently renew the portal // while a new credential-based login is establishing its own session. @@ -1210,6 +1242,9 @@ final class TsinghuaAuthClient { } final verifiedResponse = verified!; + _trustDecision ??= + await (twoFactorTrustHandler?.call() ?? Future.value(false)); + // Register only after verified 2FA and explicit consent. A legacy token is // optional; browser SSO can be established without one. if (_trustDecision == true && !_registeredDuringLogin) { @@ -1237,39 +1272,84 @@ final class TsinghuaAuthClient { } Future _saveTrustedDevice(String fingerprint) async { + late final _Response raw; try { - final response = _decodeJsonObject( - (await _request( - Uri.parse(_SAVE_FINGER_URL), - method: 'POST', - form: { - 'fingerprint': fingerprint, - 'deviceName': 'Thulium', - 'radioVal': '是', - }, - )).body, + raw = await _request( + Uri.parse(_SAVE_FINGER_URL), + method: 'POST', + form: { + 'fingerprint': fingerprint, + 'deviceName': 'Thulium', + 'radioVal': '是', + }, + ); + } catch (_) { + _rejectDeviceTrust(DeviceTrustFailureReason.networkError, 0); + throw const DeviceTrustRegistrationException( + DeviceTrustFailureReason.networkError, ); - if (response['result'] != _TWO_FACTOR_SUCCESS) { - trace?.call('Trusted-device registration was not accepted.'); + } + final Map response; + try { + response = _decodeJsonObject(raw.body); + } catch (_) { + final reason = raw.statusCode == 401 + ? DeviceTrustFailureReason.sessionRejected + : raw.statusCode == 403 || raw.statusCode == 429 + ? DeviceTrustFailureReason.accessRestricted + : DeviceTrustFailureReason.invalidResponse; + _rejectDeviceTrust(reason, raw.statusCode); + throw DeviceTrustRegistrationException(reason); + } + if (raw.statusCode < 200 || + raw.statusCode >= 300 || + response['result'] != _TWO_FACTOR_SUCCESS) { + final message = response['msg'] ?? response['message']; + final text = message is String ? message.toLowerCase() : ''; + final reason = + raw.statusCode == 401 || + RegExp( + r'未登录|登录.*(?:失效|过期)|not authenticated|login required', + ).hasMatch(text) + ? DeviceTrustFailureReason.sessionRejected + : raw.statusCode == 403 || + raw.statusCode == 429 || + RegExp(r'频繁|rate.?limit|access denied|访问受限').hasMatch(text) + ? DeviceTrustFailureReason.accessRestricted + : RegExp(r'上限|limit|too many.*(?:device|browser)').hasMatch(text) + ? DeviceTrustFailureReason.limitReached + : RegExp( + r'指纹.*(?:无效|错误|格式|长度)|invalid.*fingerprint|fingerprint.*(?:invalid|format|length)', + ).hasMatch(text) + ? DeviceTrustFailureReason.invalidFingerprint + : DeviceTrustFailureReason.rejected; + _rejectDeviceTrust(reason, raw.statusCode); + if (reason == DeviceTrustFailureReason.limitReached) { + await twoFactorAuthLimitHandler?.call(); return; } - // Current deployments can acknowledge registration without an object. - // Browser SSO is not conditional on receiving a legacy token string. - _trustedBrowser = true; - _registeredDuringLogin = true; - trace?.call('Trusted-device registration accepted.'); - final token = response['object']; - if (token is String && token.isNotEmpty) { - _fingerGenPrint = token; - trace?.call('Trusted-device credential received.'); - } else { - trace?.call('Trusted-device registration needs no legacy credential.'); - } - } catch (_) { - // Device trust is optional; its failure must not invalidate successful - // credential and second-factor verification. - trace?.call('Trusted-device registration failed; continuing login.'); + throw DeviceTrustRegistrationException(reason); } + // Current deployments can acknowledge registration without an object. + // Browser SSO is not conditional on receiving a legacy token string. + _trustedBrowser = true; + _registeredDuringLogin = true; + trace?.call('Trusted-device registration accepted.'); + final token = response['object']; + if (token is String && token.isNotEmpty) { + _fingerGenPrint = token; + trace?.call('Trusted-device credential received.'); + } else { + trace?.call('Trusted-device registration needs no legacy credential.'); + } + } + + void _rejectDeviceTrust(DeviceTrustFailureReason reason, int status) { + _trustedBrowser = false; + _trustDecision = false; + trace?.call( + 'Trusted-device registration rejected: reason=${reason.diagnosticCode} status=$status.', + ); } Map _decodeJsonObject(String body) { diff --git a/packages/auth/test/device_trust_test.dart b/packages/auth/test/device_trust_test.dart new file mode 100644 index 0000000..a038b3d --- /dev/null +++ b/packages/auth/test/device_trust_test.dart @@ -0,0 +1,177 @@ +import 'package:test/test.dart'; +import 'package:thulium_auth/thulium_auth.dart'; + +import 'support/fake_auth_http_client.dart'; + +void main() { + test( + 'an already trusted device does not prompt or register again without 2FA', + () async { + final store = MemoryAuthSessionStore(); + await store.write( + const AuthSession( + userId: '1234567890', + fingerprint: 'stable-device', + cookies: {}, + trustedBrowser: true, + fingerGenPrint: 'trusted-device-token', + ), + ); + final transport = FakeAuthHttpClient( + honorTrustedBrowser: true, + previouslyRegistered: true, + ); + final auth = TsinghuaAuthClient( + httpClient: transport, + sessionStore: store, + twoFactorTrustHandler: () async { + fail('No trust prompt is needed for an authenticated device'); + }, + ); + final session = await auth.login( + userId: '1234567890', + password: 'password', + fingerprint: 'stable-device', + ); + expect(session.fingerGenPrint, 'trusted-device-token'); + expect( + transport.requests.where( + (request) => request.url.path.endsWith('/saveFinger'), + ), + isEmpty, + ); + }, + ); + + for (final message in ['信任浏览器数量已达上限', 'Trusted browser limit reached']) { + test( + 'device quota warns once and continues without claiming trust: $message', + () async { + final transport = FakeAuthHttpClient(trustRejectionMessage: message); + final store = MemoryAuthSessionStore(); + await store.write( + const AuthSession( + userId: '1234567890', + fingerprint: 'device', + cookies: {}, + trustedBrowser: true, + ), + ); + var verified = false; + var choices = 0; + var limits = 0; + final auth = TsinghuaAuthClient( + httpClient: transport, + sessionStore: store, + twoFactorMethodHandler: (_) async => TwoFactorMethod.wechat, + twoFactorCodeHandler: (verify) async { + while (!await verify('123456')) {} + verified = true; + }, + twoFactorTrustHandler: () async { + expect(verified, isTrue); + choices++; + return true; + }, + twoFactorAuthLimitHandler: () async => limits++, + ); + final session = await auth.login( + userId: '1234567890', + password: 'password', + fingerprint: 'device', + ); + expect(choices, 1); + expect(limits, 1); + expect(session.trustedBrowser, isFalse); + expect(session.fingerGenPrint, isNull); + expect((await store.read())!.trustedBrowser, isFalse); + expect( + transport.requests.where( + (request) => request.url.path.endsWith('/saveFinger'), + ), + hasLength(1), + ); + }, + ); + } + + for (final entry in { + '身份异常': DeviceTrustFailureReason.rejected, + '登录已过期': DeviceTrustFailureReason.sessionRejected, + 'invalid fingerprint': DeviceTrustFailureReason.invalidFingerprint, + 'rate limit exceeded': DeviceTrustFailureReason.accessRestricted, + }.entries) { + test( + 'non-quota registration failure is explicit: ${entry.value}', + () async { + final store = MemoryAuthSessionStore(); + final trace = []; + var limits = 0; + final auth = TsinghuaAuthClient( + httpClient: FakeAuthHttpClient( + trustRejectionMessage: '${entry.key} private-token', + ), + sessionStore: store, + trace: trace.add, + twoFactorMethodHandler: (_) async => TwoFactorMethod.wechat, + twoFactorCodeHandler: (verify) async { + while (!await verify('123456')) {} + }, + twoFactorTrustHandler: () async => true, + twoFactorAuthLimitHandler: () async => limits++, + ); + await expectLater( + auth.login( + userId: '1234567890', + password: 'password', + fingerprint: 'device', + ), + throwsA( + isA().having( + (error) => error.reason, + 'reason', + entry.value, + ), + ), + ); + expect(await store.read(), isNull); + expect(limits, 0); + expect( + trace.join('\n'), + contains('reason=${entry.value.diagnosticCode}'), + ); + expect(trace.join('\n'), isNot(contains('private-token'))); + }, + ); + } + + for (final transport in [ + FakeAuthHttpClient(malformedTrustResponse: true), + FakeAuthHttpClient(throwTrustRequest: true), + ]) { + test( + 'invalid or failed registration transport does not report successful trust: ${transport.malformedTrustResponse}', + () async { + final store = MemoryAuthSessionStore(); + final auth = TsinghuaAuthClient( + httpClient: transport, + sessionStore: store, + twoFactorMethodHandler: (_) async => TwoFactorMethod.wechat, + twoFactorCodeHandler: (verify) async { + while (!await verify('123456')) {} + }, + twoFactorTrustHandler: () async => true, + ); + await expectLater( + auth.login( + userId: '1234567890', + password: 'password', + fingerprint: 'device', + ), + throwsA(isA()), + ); + expect(await store.read(), isNull); + }, + ); + } +} diff --git a/packages/auth/test/support/fake_auth_http_client.dart b/packages/auth/test/support/fake_auth_http_client.dart index d811ddb..77e8fae 100644 --- a/packages/auth/test/support/fake_auth_http_client.dart +++ b/packages/auth/test/support/fake_auth_http_client.dart @@ -12,6 +12,10 @@ final class FakeAuthHttpClient extends http.BaseClient { this.honorTrustedBrowser = false, this.denySingleLogin = false, this.singleLoginAction = '/do/off/ui/auth/login/checkSingle', + this.trustRejectionMessage, + this.trustStatusCode = 200, + this.malformedTrustResponse = false, + this.throwTrustRequest = false, String registeredFingerprint = 'stable-device', bool previouslyRegistered = false, }) : _registered = previouslyRegistered, @@ -20,6 +24,10 @@ final class FakeAuthHttpClient extends http.BaseClient { _registeredFingerprint = registeredFingerprint; final bool failInformationRedirect; + final String? trustRejectionMessage; + final int trustStatusCode; + final bool malformedTrustResponse; + final bool throwTrustRequest; final bool expireCookieBeforeLogin; bool _credentialsSubmitted = false; bool _registered; @@ -50,7 +58,13 @@ final class FakeAuthHttpClient extends http.BaseClient { _credentialsSubmitted = true; } if (request.url.path == '/b/doubleAuth/personal/saveFinger') { - _registered = true; + if (throwTrustRequest) { + throw http.ClientException('synthetic private transport details'); + } + _registered = + trustRejectionMessage == null && + !malformedTrustResponse && + trustStatusCode == 200; _registeredFingerprint = Uri.splitQueryString( requestBody, )['fingerprint']!; @@ -96,6 +110,10 @@ final class FakeAuthHttpClient extends http.BaseClient { '{"result":"error","msg":"invalid code"}', '/b/doubleAuth/login' => '{"result":"success","object":{"redirectUrl":"http://id.tsinghua.edu.cn/two-factor-redirect"}}', + '/b/doubleAuth/personal/saveFinger' when malformedTrustResponse => + 'invalid response', + '/b/doubleAuth/personal/saveFinger' when trustRejectionMessage != null => + jsonEncode({'result': 'error', 'msg': trustRejectionMessage}), '/b/doubleAuth/personal/saveFinger' when trustWithoutToken => '{"result":"success"}', '/b/doubleAuth/personal/saveFinger' => @@ -115,7 +133,9 @@ final class FakeAuthHttpClient extends http.BaseClient { }; return http.StreamedResponse( Stream>.value(utf8.encode(body)), - request.url.path == '/login' + request.url.path == '/b/doubleAuth/personal/saveFinger' + ? trustStatusCode + : request.url.path == '/login' ? 302 : request.url.path == '/lb-auth/lbredirect' && failInformationRedirect ? 307 diff --git a/packages/campus/lib/src/learn_courses.dart b/packages/campus/lib/src/learn_courses.dart index 58eeb20..d16866e 100644 --- a/packages/campus/lib/src/learn_courses.dart +++ b/packages/campus/lib/src/learn_courses.dart @@ -46,7 +46,7 @@ final class LearnPlatformSession { var landing = await _authClient.roamToPortalApp(_LEARN_ROAMING_ID); if (landing.statusCode == 404) { // Older roaming links can still point at the removed /student/index - // route. OneTHU checks the current course page to establish readiness. + // route. Check the current course page to establish readiness. landing = await _authClient.getAuthenticated( TsinghuaWebVpnRedirect.forTarget( Uri.https(_LEARN_HOST, '/f/wlxt/index/course/student/'), diff --git a/packages/campus/lib/src/learn_homework.dart b/packages/campus/lib/src/learn_homework.dart index b113aed..4c9167b 100644 --- a/packages/campus/lib/src/learn_homework.dart +++ b/packages/campus/lib/src/learn_homework.dart @@ -58,8 +58,8 @@ final class LearnHomeworkSnapshot { } /// Reads current homework totals using the captured GET `/student/index/` -/// API. OneTHU confirms Wj = unsubmitted, Yjwg = submitted but ungraded, -/// and Ypg = graded, although it uses a separate non-index POST API. +/// API. Uses Wj for unsubmitted, Yjwg for submitted but ungraded, and Ypg +/// for graded assignments. final class LearnHomeworkService { const LearnHomeworkService(this._authClient); @@ -212,8 +212,8 @@ final class LearnHomeworkService { int size = 5, }) async { // The index route is captured for Wj. Reusing that prefix for Yjwg/Ypg - // is inferred from the sibling endpoint names; OneTHU confirms those - // names on its non-index POST route, not this GET variant. + // is inferred from the sibling endpoint names; those GET variants have + // not been captured independently. final target = Uri.https( _LEARN_HOST, '/b/wlxt/kczy/zy/student/index/$endpoint', @@ -279,7 +279,7 @@ DateTime? _homeworkDeadline(Map row) { final text = row['jzsjStr']; if (text is! String || text.trim().isEmpty) return null; // Learn's zone-less string describes campus time, never the device zone. - // Use the normal deadline jzsj; bjjzsj is a separate late-submission deadline - // according to OneTHU, whose applicability is not established by this list. + // Use jzsj for the normal deadline; this list does not establish when the + // separate bjjzsj value applies. return DateTime.tryParse('${text.trim().replaceFirst(' ', 'T')}+08:00'); } diff --git a/packages/campus/lib/src/learn_materials.dart b/packages/campus/lib/src/learn_materials.dart index b63621b..02cdcd4 100644 --- a/packages/campus/lib/src/learn_materials.dart +++ b/packages/campus/lib/src/learn_materials.dart @@ -50,8 +50,8 @@ final class LearnMaterial { final int? downloadCount; /// Keeps unverified fields available without assigning guessed semantics. - /// In particular, OneTHU maps sfqd to "important", while the captured - /// response does not establish that meaning; do not call it attendance. + /// The captured response does not establish the meaning of sfqd, so retain + /// it without treating it as an importance or attendance flag. final Map rawResponse; } @@ -74,8 +74,8 @@ final class LearnMaterialService { const LearnMaterialService(this._authClient); final TsinghuaAuthClient _authClient; - /// OneTHU uses 200 here. This endpoint has no offset or total count in the - /// supplied response, so preserve the limit and never claim a complete list. + /// Requests up to 200 files by default. This endpoint supplies no offset or + /// total count, so preserve the limit and never claim a complete list. Future> fetchCourses( LearnCourseCatalog catalog, { String? courseId, diff --git a/packages/cli/lib/cli_runtime.dart b/packages/cli/lib/cli_runtime.dart index cae1fa8..1ceab2d 100644 --- a/packages/cli/lib/cli_runtime.dart +++ b/packages/cli/lib/cli_runtime.dart @@ -289,6 +289,10 @@ _Context _context(String name, bool verbose) { twoFactorCodeHandler: (verify) => _readTwoFactorCode(verify, output: promptOutput), twoFactorTrustHandler: () => _askToTrustDevice(output: promptOutput), + twoFactorAuthLimitHandler: () async => promptOutput.writeln( + 'Trusted device limit reached. This sign-in will continue without remembering ' + 'the device. Manage old trusted browsers at id.tsinghua.edu.cn, then try again.', + ), trace: verbose ? (message) => stderr.writeln('[auth] $message') : null, ); final reconnect = CliSessionReconnect( diff --git a/test/unit/diagnostics/diagnostic_log_test.dart b/test/unit/diagnostics/diagnostic_log_test.dart index 6ed19d7..34bafeb 100644 --- a/test/unit/diagnostics/diagnostic_log_test.dart +++ b/test/unit/diagnostics/diagnostic_log_test.dart @@ -102,6 +102,9 @@ void main() { log.record( '[auth] Credential recovery: cause=PortalSessionRejected trustedCredentialPresent=true.', ); + log.record( + '[auth] Trusted-device registration rejected: reason=limit-reached status=200 msg=secret-token', + ); log.record( '[auth] Second-factor challenge: stage=webvpn trustedCredentialPresent=true.', ); @@ -122,6 +125,10 @@ void main() { expect(report, contains('HTTP GET endpoint=learn-preview')); expect(report, contains('status=403 elapsedMs=42')); expect(report, contains('cause=PortalSessionRejected')); + expect( + report, + contains('registration rejected: reason=limit-reached status=200'), + ); expect(report, contains('stage=webvpn trustedCredentialPresent=true')); expect(report, contains('package:thulium/pages/login_page.dart:12:3')); }, @@ -139,6 +146,9 @@ void main() { first.record( '[auth][signin=2] Using the trusted-browser identity entry.', ); + first.record( + '[auth] Trusted-device registration rejected: reason=limit-reached status=200 private-token', + ); first.record( '[auth] Session restored: trustedCredentialPresent=true deviceTrustConsent=true.', ); diff --git a/test/widget/auth/login_page_test.dart b/test/widget/auth/login_page_test.dart index b9c9103..2f8218b 100644 --- a/test/widget/auth/login_page_test.dart +++ b/test/widget/auth/login_page_test.dart @@ -4,6 +4,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:forui/forui.dart'; import 'package:thulium/l10n/generated/app_localizations.dart'; import 'package:thulium/pages/login_page.dart'; +import 'package:thulium/auth/secure_auth_session_store.dart'; import 'package:thulium_auth/thulium_auth.dart'; import '../../../packages/auth/test/support/fake_auth_http_client.dart'; @@ -54,6 +55,7 @@ void main() { required twoFactorMethodHandler, required twoFactorCodeHandler, required twoFactorTrustHandler, + required twoFactorAuthLimitHandler, required trace, }) => TsinghuaAuthClient( httpClient: transport, @@ -68,6 +70,7 @@ void main() { } return choice; }, + twoFactorAuthLimitHandler: twoFactorAuthLimitHandler, trace: trace, ), ), @@ -79,8 +82,6 @@ void main() { } Future verify(WidgetTester tester) async { - await tester.tap(find.text('Trust device')); - await tick(tester); await tester.tap(find.text('WeChat')); await tick(tester); await tester.enterText(find.byType(EditableText).last, '123456'); @@ -89,8 +90,88 @@ void main() { await tick(tester); await tester.tap(find.text('Confirm')); await tick(tester); + await tester.tap(find.text('Trust device')); + await tick(tester); } + testWidgets( + 'device quota explains the limit and allows an untrusted sign-in', + (tester) async { + final transport = FakeAuthHttpClient(trustRejectionMessage: '受信设备数已达上限'); + var successes = 0; + await show(tester, transport, _Dialogs(), success: () => successes++); + await tester.tap(find.text('Sign in')); + await tick(tester); + expect(find.text('Trust this device?'), findsNothing); + await verify(tester); + expect(find.text('Trusted device limit reached'), findsOneWidget); + expect(find.textContaining('id.tsinghua.edu.cn'), findsOneWidget); + expect(successes, 0); + await tester.tap(find.text('Continue sign-in')); + await tick(tester); + // The portal may require its own code when registration was refused. + await tester.tap(find.text('WeChat')); + await tick(tester); + await tester.enterText(find.byType(EditableText).last, '123456'); + await tester.tap(find.text('Confirm')); + await tick(tester); + expect(successes, 1); + expect(find.text('Trust this device?'), findsNothing); + expect((await SecureAuthSessionStore().read())!.trustedBrowser, isFalse); + expect( + transport.requests.where( + (request) => request.url.path.endsWith('/saveFinger'), + ), + hasLength(1), + ); + }, + semanticsEnabled: false, + ); + + testWidgets( + 'other registration rejection is visible and never reports successful sign-in', + (tester) async { + final transport = FakeAuthHttpClient( + trustRejectionMessage: '身份异常 private-token', + ); + var successes = 0; + await show(tester, transport, _Dialogs(), success: () => successes++); + await tester.tap(find.text('Sign in')); + await tick(tester); + await verify(tester); + expect( + find.textContaining('Could not trust this device'), + findsOneWidget, + ); + expect(find.textContaining('private-token'), findsNothing); + expect(successes, 0); + // The same screen can retry without registration, rather than trapping + // an account behind a provider error from SAVE_FINGER. + await tester.tap(find.text('Sign in')); + await tick(tester); + await tester.tap(find.text('WeChat')); + await tick(tester); + await tester.enterText(find.byType(EditableText).last, '123456'); + await tester.tap(find.text('Confirm')); + await tick(tester); + await tester.tap(find.text('Not now')); + await tick(tester); + await tester.tap(find.text('WeChat')); + await tick(tester); + await tester.enterText(find.byType(EditableText).last, '123456'); + await tester.tap(find.text('Confirm')); + await tick(tester); + expect(successes, 1); + expect( + transport.requests.where( + (request) => request.url.path.endsWith('/saveFinger'), + ), + hasLength(1), + ); + }, + semanticsEnabled: false, + ); + testWidgets( 'button plus keyboard submission does not restart trust after a verified login fails', (tester) async { @@ -179,12 +260,6 @@ void main() { await show(tester, transport, dialogs, success: () => successes++); await tester.tap(find.text('Sign in')); await tick(tester); - final trust = tester - .widget(find.widgetWithText(FButton, 'Trust device')) - .onPress!; - trust(); - trust(); - await tick(tester); final method = tester .widget(find.widgetWithText(FButton, 'WeChat')) .onPress!; @@ -197,6 +272,12 @@ void main() { await tick(tester); await tester.tap(find.text('Confirm')); await tick(tester); + final trust = tester + .widget(find.widgetWithText(FButton, 'Trust device')) + .onPress!; + trust(); + trust(); + await tick(tester); expect(successes, 1); expect(dialogs.opened, 3); }, semanticsEnabled: false); @@ -213,8 +294,6 @@ void main() { await show(tester, transport, dialogs, success: () => successes++); await tester.tap(find.text('Sign in')); await tick(tester); - await tester.tap(find.text('Trust device')); - await tick(tester); await tester.tap(find.text('WeChat')); await tick(tester); await tester.enterText(find.byType(EditableText).last, '123456'); @@ -230,6 +309,8 @@ void main() { ); await tester.tap(find.text('Confirm')); await tick(tester); + await tester.tap(find.text('Trust device')); + await tick(tester); expect(successes, 1); // Two requests total: one rejected code and one deliberate retry. expect(transport.verificationRequestCount, 2); From c6dd90a56b89b904e9c17f899043b46acec395ce Mon Sep 17 00:00:00 2001 From: ashgrey Date: Thu, 19 Nov 2026 10:38:05 +0800 Subject: [PATCH 24/26] chore(format): add format command --- justfile | 3 +++ test/widget/homework/homework_overview_card_test.dart | 5 +---- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/justfile b/justfile index bbb6040..db1fe4f 100644 --- a/justfile +++ b/justfile @@ -13,6 +13,9 @@ auth-deps: cli-deps: cd packages/cli && {{ DART }} pub get --enforce-lockfile +format: + {{ DART }} format lib test packages/auth/lib packages/auth/test packages/cli/bin packages/cli/lib + format-check: {{ DART }} format --output=none --set-exit-if-changed lib test packages/auth/lib packages/auth/test packages/cli/bin packages/cli/lib diff --git a/test/widget/homework/homework_overview_card_test.dart b/test/widget/homework/homework_overview_card_test.dart index 21f7b00..53a7d14 100644 --- a/test/widget/homework/homework_overview_card_test.dart +++ b/test/widget/homework/homework_overview_card_test.dart @@ -83,10 +83,7 @@ void main() { expect(find.text('Within 1h'), findsOneWidget); expect(find.text('Not graded'), findsOneWidget); expect(find.text('Updated 7 minutes ago'), findsOneWidget); - expect( - find.text('All deadlines use Beijing time (UTC+8)'), - findsNothing, - ); + expect(find.text('All deadlines use Beijing time (UTC+8)'), findsNothing); expect(find.textContaining('Beijing time'), findsNothing); expect( tester.getTopLeft(find.text(previewAssignments[0].title)).dy, From b16b707719b2796edc95a097cbd00741e3cd0572 Mon Sep 17 00:00:00 2001 From: ashgrey Date: Thu, 19 Nov 2026 10:56:54 +0800 Subject: [PATCH 25/26] ci: align Flutter SDK with locked dependencies Pin CI and release workflows to Flutter 3.47.4. Update SDK constraints, lockfile and development documentation. Limit the legacy semantics workaround to five functional tests. --- .github/workflows/ci.yml | 2 +- .github/workflows/nightly-release.yml | 8 +- README.md | 159 +----------------- pubspec.lock | 2 +- pubspec.yaml | 4 +- .../calendar/calendar_export_dialog_test.dart | 4 +- test/widget/plans/add_plan_page_test.dart | 11 +- 7 files changed, 23 insertions(+), 167 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index f0e9d85..c61be1d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,7 +26,7 @@ jobs: - name: Set up Flutter uses: subosito/flutter-action@v2 with: - flutter-version: 3.44.8 + flutter-version: 3.47.4 cache: true - name: Run project quality checks diff --git a/.github/workflows/nightly-release.yml b/.github/workflows/nightly-release.yml index f14eb54..446d4a0 100644 --- a/.github/workflows/nightly-release.yml +++ b/.github/workflows/nightly-release.yml @@ -31,7 +31,7 @@ jobs: - name: Set up Flutter uses: subosito/flutter-action@v2 with: - flutter-version: 3.44.8 + flutter-version: 3.47.4 cache: true - name: Run project quality checks @@ -61,7 +61,7 @@ jobs: - name: Set up Flutter uses: subosito/flutter-action@v2 with: - flutter-version: 3.44.8 + flutter-version: 3.47.4 cache: true - name: Build Android APK @@ -122,7 +122,7 @@ jobs: - name: Set up Flutter uses: subosito/flutter-action@v2 with: - flutter-version: 3.44.8 + flutter-version: 3.47.4 cache: true - name: Install Linux build dependencies @@ -201,7 +201,7 @@ jobs: - name: Set up Flutter and Dart uses: subosito/flutter-action@v2 with: - flutter-version: 3.44.8 + flutter-version: 3.47.4 cache: true - name: Prepare CLI output directory diff --git a/README.md b/README.md index e2d76ca..94f65a3 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ Thulium is a cross-platform Flutter application for Tsinghua University students. It uses [Forui](https://github.com/duobaseio/forui) for UI components -and reserves `packages/cli` for future Dart command-line tools. +and reserves `packages/cli` for Dart command-line tools. ## Development @@ -11,156 +11,7 @@ flutter pub get flutter run -d chrome ``` -The project currently uses Forui `0.22.x`, which is compatible with Flutter -3.44. Forui `0.26.x` requires Flutter 3.47 or newer; upgrade the dependency -after upgrading Flutter. - -## Course documents - -Select a course under My courses to open its files or assignments. Assignment -lists include unsubmitted, submitted (awaiting grading), and graded sections. -The latter two use the same sibling GET endpoints already used by the shared -homework counts service; they still need verification with a live Learn account. - -Document previews use `pdfx` to render the authenticated PDF representation -returned by Learn. Word documents are displayed through Learn's PDF conversion, -not a local DOC/DOCX parser. Files without an available PDF representation show -a retryable error. In-app preview supports Android, iOS, macOS, Windows and Web; -Linux shows an unsupported-platform message. The app does not send documents -to an additional conversion service. The native viewer may create temporary -files in the application's private cache directory. - -## Localization - -Application strings are stored in ARB files under `lib/l10n` and generated with: - -```bash -flutter gen-l10n -``` - -Add new user-facing strings to `app_en.arb` first, then add translations to the -other locale files. Do not put localized text directly in Dart source files. - -## Authentication - -Authentication logic is shared by the Flutter application and the future CLI -through `packages/auth`. The Flutter application uses `SecureAuthSessionStore`, -which persists the authenticated session and reusable credentials under separate -keys in platform secure storage. Passwords are never included in the shared -session model or calendar cache. - -## CLI authentication - -The Dart CLI provides interactive authentication and persists the resulting -session in the operating system credential store: - -```bash -cd packages/cli -dart run bin/thulium.dart login -dart run bin/thulium.dart login --verbose -dart run bin/thulium.dart status -dart run bin/thulium.dart schedule -dart run bin/thulium.dart schedule --refresh -dart run bin/thulium.dart learn-courses -dart run bin/thulium.dart learn-courses --semester 2026-2027-1 -dart run bin/thulium.dart learn-courses --refresh -dart run bin/thulium.dart learn-homework -dart run bin/thulium.dart learn-homework --semester 2026-2027-1 --refresh -dart run bin/thulium.dart logout -``` - -The optional `--verbose` flag prints safe authentication diagnostics for -troubleshooting. It never prints passwords, verification codes, or cookie -values. The CLI never accepts the password as a command-line argument and never writes -it to a project file. Linux uses Secret Service and macOS uses Keychain. Other -platforms will report that a secure session backend is not available until one -is added. - -On Linux, the CLI requires `secret-tool` (provided by `libsecret`, included in -the Nix development shell) and an unlocked Secret Service keyring in the current -desktop session. On NixOS, if no Secret Service provider is already configured, -enable GNOME Keyring in your system configuration: - -```nix -services.gnome.gnome-keyring.enable = true; -``` - -Rebuild your NixOS configuration and log out and back in. If the keyring remains -locked, unlock it with a keyring manager such as Seahorse. Then re-enter -`nix develop` and run the CLI from `packages/cli`. - -The application and CLI cache the current academic calendar per account in -platform secure storage. A successful fetch is reused for 24 hours; an older -copy can be shown if the portal is temporarily unavailable. Manual refresh and -`schedule --refresh` request a new copy instead of silently using stale data. -Logging out removes the saved calendar. - -`learn-courses` fetches the learning platform's course list for the requested -semester and prints an English-keyed YAML view of the useful course fields. -Without `--semester`, it selects the semester from the local date: autumn -starts September 15, spring starts February 15, and summer starts July 15. -The app and CLI keep the selected account's current semester course list for -24 hours, with an older copy available if an update fails. Switching semesters -replaces this single snapshot. `--refresh` bypasses the -fresh cache. Study shows these courses, and the teaching calendar uses their -English titles for matching lessons when the app language is English. Custom -plans keep their original names. The output contains student-specific -information, so avoid redirecting it to a shared log. - -`learn-homework` reports current unsubmitted, submitted-but-ungraded, and graded -homework counts for every course in the selected semester, with semester totals -and per-course entries in YAML. It defaults to the current semester; `--refresh` -refreshes the course list, while homework counts are always fetched live. Counts -come from the server's total-record metadata, not the first five returned rows. -Diagnostics and reconnection messages go to stderr, keeping stdout valid YAML. -If any count cannot be fetched, the command fails instead of reporting it as zero. - -The app persists unsubmitted assignments and course badge counts in secure -storage, scoped to the account and semester. Saved data appears while a live -update runs; an offline or failed update retains it with a notice. Every app -entry, resume, and manual refresh requests current assignments. Logout clears -the snapshot. Deadlines are stored as UTC instants and countdowns are recalculated. - -When a protected CLI request reports an expired session, the CLI tries the -saved credentials, then offers an interactive sign-in if needed. A successful -reconnection retries the original request once. - -Interactive login attempts can be retried after credential, verification-code, -or network errors. Each retry starts a fresh authentication flow. - -## Project structure - -```text -lib/ Flutter application -lib/l10n/ ARB resources and generated localization code -packages/auth/ Shared Dart authentication and session library -packages/cli/ Standalone Dart CLI package for future tools -android/ ios/ web/ Mobile and web targets -linux/ macos/ windows/ Desktop targets -``` - -## Diagnostic logs - -Open Settings → Export diagnostic logs to share a text file on Android/iOS. -The welcome page also exposes Settings, so export remains available when login -cannot complete. Linux uses a file save dialog. - -The app retains up to 2,000 structural events from the last seven days locally, -including across restarts. Export includes the installed app version/build, -platform, UTC timestamps, request categories, HTTP status codes, recovery causes, -and the stage requesting verification. Event filtering happens before storage: -passwords, verification codes, account identifiers, cookie/token values, full -URLs, response previews, course titles and document content are not retained. -Logs are only shared when the user chooses export and a destination. - -## Checks - -Tests are grouped by scope: `test/unit/` covers logic and adapters, while -`test/widget/` covers Flutter components and screen behavior. Device-level -end-to-end tests belong in `integration_test/`. - -```bash -flutter analyze -flutter test -dart analyze packages/cli -``` +Use Flutter `3.47.4`, matching the pinned Nix development environment, CI and +release workflows. Flutter's SDK packages constrain several test dependencies, +so a different SDK version may require changes to `pubspec.lock` and fail +`--enforce-lockfile`. The project currently uses Forui `0.22.x`. \ No newline at end of file diff --git a/pubspec.lock b/pubspec.lock index e023631..e43710d 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -1114,4 +1114,4 @@ packages: version: "3.1.4" sdks: dart: ">=3.12.2 <4.0.0" - flutter: ">=3.44.0" + flutter: ">=3.47.4" diff --git a/pubspec.yaml b/pubspec.yaml index 7ca68f9..609107c 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -20,6 +20,7 @@ version: 1.0.0+1 environment: sdk: ^3.12.2 + flutter: '>=3.47.4' # Dependencies specify other packages that your package needs in order to work. # To automatically upgrade your package dependencies to the latest versions @@ -44,8 +45,7 @@ dependencies: thulium_campus: path: packages/campus - # Forui 0.22.x supports the Flutter 3.44 toolchain currently installed here. - # Upgrade to ^0.26.0 after moving to Flutter 3.47+. + # Keep the current component APIs while using the pinned Flutter toolchain. forui: ^0.22.0 pdfx: ^2.11.0 shared_preferences: ^2.5.6 diff --git a/test/widget/calendar/calendar_export_dialog_test.dart b/test/widget/calendar/calendar_export_dialog_test.dart index b4ce897..b494195 100644 --- a/test/widget/calendar/calendar_export_dialog_test.dart +++ b/test/widget/calendar/calendar_export_dialog_test.dart @@ -5,6 +5,8 @@ import 'package:thulium/l10n/generated/app_localizations.dart'; import 'package:thulium/widgets/calendar_export_dialog.dart'; void main() { + // This functional dropdown test does not validate accessibility. Flutter + // 3.47 asserts while merging the legacy component's popover semantics. testWidgets('format dropdown selects PNG and limits it to the current week', ( tester, ) async { @@ -44,5 +46,5 @@ void main() { await tester.pumpAndSettle(); expect(selection?.format, CalendarExportFormat.png); expect(selection?.range, CalendarExportRange.currentWeek); - }); + }, semanticsEnabled: false); } diff --git a/test/widget/plans/add_plan_page_test.dart b/test/widget/plans/add_plan_page_test.dart index 8feca73..8743ca2 100644 --- a/test/widget/plans/add_plan_page_test.dart +++ b/test/widget/plans/add_plan_page_test.dart @@ -6,6 +6,9 @@ import 'package:thulium/pages/add_plan_page.dart'; import 'package:thulium_campus/thulium_campus.dart'; void main() { + // These tests cover form values and persistence. Flutter 3.47 currently + // asserts in the legacy components' merged semantics during interaction; + // accessibility behavior needs separate coverage after component migration. testWidgets('saves a new weekly plan and its category together', ( tester, ) async { @@ -60,7 +63,7 @@ void main() { expect(savedCategory?.name, 'Study'); expect(savedPlan?.category, savedCategory?.id); expect(tester.takeException(), isNull); - }); + }, semanticsEnabled: false); testWidgets('offers a saved category on the next plan', (tester) async { tester.view.physicalSize = const Size(320, 640); @@ -110,7 +113,7 @@ void main() { expect(savedPlan?.category, 'user.study'); expect(createdCategory, isNull); expect(tester.takeException(), isNull); - }); + }, semanticsEnabled: false); testWidgets('prefills a lesson with no location for a one-off edit', ( tester, @@ -155,7 +158,7 @@ void main() { expect(edited?.location, 'Room 101'); expect(edited?.startsAt, lesson.startsAt); expect(edited?.repeat, PlanRepeat.none); - }); + }, semanticsEnabled: false); testWidgets('prefills and preserves the repeat rule for a series edit', ( tester, @@ -201,5 +204,5 @@ void main() { expect(edited?.name, 'Revised group'); expect(edited?.startsAt, original.startsAt); expect(edited?.repeat, PlanRepeat.weekly); - }); + }, semanticsEnabled: false); } From 01ca1343d280b7612cff68005b6c4442fb7b4c15 Mon Sep 17 00:00:00 2001 From: ashgrey Date: Thu, 19 Nov 2026 11:08:44 +0800 Subject: [PATCH 26/26] fix(windows): remove unavailable PDFium version override Remove the hardcoded PDFium 4638 override whose download URL returns 404. Allow pdfx to select its default PDFium version for the target architecture. --- windows/CMakeLists.txt | 1 - 1 file changed, 1 deletion(-) diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt index b432764..a7d6313 100644 --- a/windows/CMakeLists.txt +++ b/windows/CMakeLists.txt @@ -1,7 +1,6 @@ # Project-level configuration. cmake_minimum_required(VERSION 3.14) project(thulium LANGUAGES CXX) -set(PDFIUM_VERSION "4638" CACHE STRING "PDFium version used by pdfx") # The name of the executable created for the application. Change this to change # the on-disk name of your application.