feat: deliver RSchedule service login exams and elastic glass navigation

This commit is contained in:
Codex
2026-10-13 17:06:50 +08:00
parent 9193fd8e43
commit 8f20a341c4
35 changed files with 1742 additions and 453 deletions
+202
View File
@@ -0,0 +1,202 @@
import 'dart:convert';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import '../../app/app_controller.dart';
import '../../app/app_theme.dart';
import '../school/school_exam_adapter.dart';
class ExamsPage extends StatelessWidget {
const ExamsPage({super.key, required this.controller, required this.onSync});
final AppController controller;
final VoidCallback onSync;
Future<void> _import(BuildContext context) async {
try {
final file = await FilePicker.pickFile(
type: FileType.custom,
allowedExtensions: ['html', 'htm'],
);
if (file == null) return;
final bytes = BytesBuilder(copy: false);
var length = 0;
await for (final chunk in file.readAsByteStream()) {
length += chunk.length;
if (length > 2 * 1024 * 1024) {
throw const FormatException('文件不能超过 2 MB');
}
bytes.add(chunk);
}
final draft = SchoolExamAdapter.extract(utf8.decode(bytes.takeBytes()));
if (!context.mounted) return;
final confirmed = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: const Text('导入考试信息'),
content: Text(
'${draft.semesterLabel} · ${draft.records.length} 门课程\n将更新本机考试列表,尚未公布的字段显示为“尚未安排”。',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('确认导入'),
),
],
),
);
if (confirmed == true) {
await controller.applyExams(draft);
if (context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(controller.lastError ?? '考试信息已导入')),
);
}
}
} catch (error) {
if (context.mounted) {
ScaffoldMessenger.of(context)
.showSnackBar(SnackBar(content: Text('导入未完成:$error')));
}
}
}
@override
Widget build(BuildContext context) {
final schedule = controller.snapshot.examSchedule;
return ListView(
key: const PageStorageKey('exams-scroll'),
padding: EdgeInsets.fromLTRB(
22,
10,
22,
140 + MediaQuery.paddingOf(context).bottom,
),
children: [
const Text(
'RSchedule',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700),
),
const SizedBox(height: 18),
Row(
children: [
const Expanded(
child: Text(
'考试安排',
style: TextStyle(fontSize: 25, fontWeight: FontWeight.w700),
),
),
IconButton(
tooltip: '从学校更新考试',
onPressed: onSync,
icon: const Icon(Icons.sync_rounded),
),
IconButton(
tooltip: '导入考试 HTML',
onPressed: () => _import(context),
icon: const Icon(Icons.file_download_outlined),
),
],
),
const SizedBox(height: 8),
if (schedule == null) ...[
const SizedBox(height: 54),
const Icon(
Icons.assignment_outlined,
size: 64,
color: Color(0xFF9ABBE8),
),
const SizedBox(height: 20),
const Text(
'等待学校公布考试安排',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
),
const SizedBox(height: 12),
const Text(
'连接研究生系统,或导入学校考试页面的 HTML。',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 13, height: 1.8),
),
const SizedBox(height: 24),
Center(
child: FilledButton.icon(
onPressed: onSync,
icon: const Icon(Icons.school_outlined),
label: const Text('连接学校考试查询'),
),
),
] else ...[
Text(
'${schedule.semesterLabel} · ${schedule.records.length} 门课程',
style: TextStyle(fontSize: 13, color: ink.withValues(alpha: 0.55)),
),
const SizedBox(height: 18),
if (schedule.records.isEmpty) const Text('该学期暂无考试课程'),
for (final exam in schedule.records)
Padding(
padding: const EdgeInsets.only(bottom: 14),
child: SurfaceCard(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
exam.name,
style: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 14),
_field(Icons.schedule_rounded, '考试时间', exam.time),
_field(Icons.location_on_outlined, '考场', exam.room),
_field(Icons.event_seat_outlined, '座位号', exam.seat),
if (exam.assessment.isNotEmpty)
_field(
Icons.assignment_outlined,
'考核方式',
exam.assessment,
),
if (exam.candidate.isNotEmpty)
_field(Icons.badge_outlined, '考生编号', exam.candidate),
if (exam.sequence.isNotEmpty)
_field(
Icons.format_list_numbered,
'考场顺序号',
exam.sequence,
),
],
),
),
),
const Text(
'排考信息以学校最新公布为准。',
textAlign: TextAlign.center,
style: TextStyle(fontSize: 11, color: Color(0xFF8493A5)),
),
],
],
);
}
Widget _field(IconData icon, String label, String value) => Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 17, color: const Color(0xFF007AFF)),
const SizedBox(width: 9),
Expanded(
child: Text(
'$label:${value.isEmpty ? '尚未安排' : value}',
style: const TextStyle(fontSize: 13, height: 1.5),
),
),
],
),
);
}
@@ -17,11 +17,12 @@ class ProfilePage extends StatelessWidget {
required this.onLogin,
this.authStatus = '未登录',
this.onLogout,
this.logoutLabel = '退出学校登录',
});
final AppController controller;
final VoidCallback onLogin;
final VoidCallback? onLogout;
final String authStatus;
final String authStatus, logoutLabel;
Future<void> _import(BuildContext context) async {
try {
final file = await FilePicker.pickFile(
@@ -67,7 +68,7 @@ class ProfilePage extends StatelessWidget {
),
children: [
const Text(
'Riverside Schedule',
'RSchedule',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.w700),
),
const SizedBox(height: 16),
@@ -114,7 +115,7 @@ class ProfilePage extends StatelessWidget {
Center(
child: TextButton(
onPressed: onLogout,
child: const Text('退出学校登录'),
child: Text(logoutLabel),
),
),
],
@@ -210,7 +211,7 @@ class ProfilePage extends StatelessWidget {
child: Column(
children: [
const Text(
'Riverside Schedule',
'RSchedule',
style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600),
),
const SizedBox(height: 6),
+80 -151
View File
@@ -2,8 +2,6 @@ import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../app/app_controller.dart';
import '../../app/app_theme.dart';
import '../profile/import_preview.dart';
import 'school_session.dart';
class SchoolAuthPage extends StatefulWidget {
@@ -19,202 +17,133 @@ class SchoolAuthPage extends StatefulWidget {
}
class _SchoolAuthPageState extends State<SchoolAuthPage> {
final _username = TextEditingController(),
_password = TextEditingController();
bool _showWeb = false, _previewing = false;
bool _saving = false;
@override
void initState() {
super.initState();
widget.session.addListener(_changed);
if (!widget.session.hasOpened) {
widget.session.open();
}
WidgetsBinding.instance.addPostFrameCallback((_) => _changed());
}
void _changed() {
if (!mounted) return;
setState(() {});
final draft = widget.session.pendingDraft;
if (draft != null && !_previewing) {
_previewing = true;
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (!mounted) return;
await showModalBottomSheet<bool>(
context: context,
isScrollControlled: true,
showDragHandle: true,
builder: (_) =>
ImportPreview(draft: draft, controller: widget.controller),
final s = widget.session;
final courses = s.pendingDraft, exams = s.pendingExams;
final generation = s.pageGeneration;
final route = ModalRoute.of(context);
if (_saving || (courses == null && exams == null)) return;
_saving = true;
WidgetsBinding.instance.addPostFrameCallback((_) async {
if (!mounted) {
_saving = false;
return;
}
// The session draft must still belong to the same page after navigation.
if (generation != s.pageGeneration ||
courses != s.pendingDraft ||
exams != s.pendingExams) {
_saving = false;
_changed();
return;
}
if (courses != null) {
await widget.controller.applyImport(courses, confirmedEmpty: false);
}
if (exams != null) await widget.controller.applyExams(exams);
final success = widget.controller.lastError == null;
final acknowledged = s.saved(
success: success,
generation: generation,
draft: courses,
exams: exams,
);
_saving = false;
if (!mounted) return;
if (!acknowledged) {
_changed();
return;
}
if (success && route?.isCurrent == true) {
Navigator.of(context).pop();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(exams == null ? '课表已导入;请核对学期开始日。' : '考试信息已更新'),
),
);
widget.session.pendingDraft = null;
_previewing = false;
});
}
} else {
setState(() {});
}
});
}
@override
void dispose() {
widget.session.removeListener(_changed);
_password.clear();
_username.clear();
_password.dispose();
_username.dispose();
super.dispose();
}
Future<void> _submit() async {
if (_username.text.trim().isEmpty || _password.text.isEmpty) {
ScaffoldMessenger.of(context)
.showSnackBar(const SnackBar(content: Text('请输入学号和密码')));
return;
}
try {
await widget.session.submitCredentials(
_username.text.trim(),
_password.text,
);
} finally {
_password.clear();
if (mounted) {
setState(() => _showWeb = true);
}
}
}
@override
Widget build(BuildContext context) {
final s = widget.session;
return Scaffold(
appBar: AppBar(
title: const Text(
'学校认证',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.w700),
),
title: const Text('学校认证'),
actions: [
IconButton(
tooltip: _showWeb ? '应用登录界面' : '学校页面',
onPressed: () => setState(() => _showWeb = !_showWeb),
icon: Icon(
_showWeb ? Icons.person_outline : Icons.language_rounded,
),
tooltip: '重新认证',
onPressed: _saving ? null : s.openAuthentication,
icon: const Icon(Icons.refresh_rounded),
),
IconButton(
tooltip: '打开学校课表',
onPressed: () {
setState(() => _showWeb = true);
s.openTimetable();
},
icon: const Icon(Icons.calendar_month_outlined),
tooltip: '重试读取',
onPressed: _saving
? null
: (s.requestingExams ? s.openExams : s.openTimetable),
icon: const Icon(Icons.sync_rounded),
),
],
),
body: Column(
children: [
if (s.busy) const LinearProgressIndicator(minHeight: 2),
if (s.busy || _saving) const LinearProgressIndicator(minHeight: 2),
Container(
width: double.infinity,
padding: const EdgeInsets.all(13),
color: river.withValues(alpha: 0.07),
padding: const EdgeInsets.all(12),
color: const Color(0xFFEFF6FF),
child: Text(
s.message,
style: const TextStyle(fontSize: 12, height: 1.5, color: ink),
style: const TextStyle(fontSize: 12, height: 1.5),
),
),
Expanded(
child: _showWeb
? WebViewWidget(controller: s.web)
: ListView(
padding: const EdgeInsets.all(24),
children: [
const SizedBox(height: 20),
const Icon(Icons.school_outlined, size: 48, color: river),
const SizedBox(height: 20),
const Text(
'登录,连接你的每一天。',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 23,
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 10),
Text(
'电子科技大学统一身份认证',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 13,
color: ink.withValues(alpha: 0.5),
),
),
const SizedBox(height: 30),
SurfaceCard(
child: Stack(
children: [
WebViewWidget(controller: s.web),
if (s.finding || _saving)
Positioned.fill(
child: ColoredBox(
color: const Color(0xFFF5F9FE),
child: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
TextField(
controller: _username,
textInputAction: TextInputAction.next,
autocorrect: false,
decoration: const InputDecoration(
labelText: '学号/工号',
prefixIcon: Icon(Icons.person_outline),
),
),
const SizedBox(height: 16),
TextField(
controller: _password,
obscureText: true,
enableSuggestions: false,
autocorrect: false,
decoration: const InputDecoration(
labelText: '学校密码',
prefixIcon: Icon(Icons.lock_outline),
),
onSubmitted: (_) => _submit(),
),
const CircularProgressIndicator(),
const SizedBox(height: 20),
SizedBox(
width: double.infinity,
child: FilledButton(
onPressed: !s.busy && s.formReady
? _submit
: null,
child: Text(s.busy ? '正在准备学校认证…' : '登录并打开课表'),
),
),
const SizedBox(height: 10),
TextButton(
onPressed: () {
_password.clear();
setState(() => _showWeb = true);
s.openAuthentication();
},
child: const Text('使用学校页面登录'),
Text(
_saving
? '正在保存,请稍候'
: (s.requestingExams
? '正在查找考试安排,请稍候'
: '正在查找课表,请稍候'),
),
],
),
),
const SizedBox(height: 20),
Text(
'密码仅交给学校处理,不在应用中保存。需要验证码或其他验证时,将由学校页面继续处理。',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
height: 1.7,
color: ink.withValues(alpha: 0.45),
),
),
const SizedBox(height: 14),
Text(
'学校课表识别待登录后联调;也可通过「我的」导入课表文件。',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 11,
height: 1.6,
color: ink.withValues(alpha: 0.45),
),
),
],
),
),
],
),
),
],
),
@@ -0,0 +1,91 @@
import 'dart:convert';
import 'package:html/parser.dart' as html;
import '../../domain/exam_schedule.dart';
class SchoolExamAdapter {
static ExamSchedule extract(String content) {
try {
if (utf8.encode(content).length > 2 * 1024 * 1024) {
throw const FormatException();
}
final document = html.parse(content);
final selected = document.querySelector('#xqbh option[selected]');
final term = selected?.attributes['value'];
final table = document.querySelector('#sample-table-1');
const headers = [
'id',
'序号',
'学号',
'姓名',
'课程代码',
'课程名称',
'考核方式',
'考生编号',
'考场顺序号',
'考场',
'座位号',
'考试时间',
];
if (selected == null ||
term == null ||
table == null ||
!RegExp(r'^\d+$').hasMatch(term)) {
throw const FormatException();
}
final rows = table.querySelectorAll('tr');
if (rows.isEmpty || rows.first.children.length != headers.length) {
throw const FormatException();
}
for (var i = 0; i < headers.length; i++) {
if (rows.first.children[i].text.trim() != headers[i]) {
throw const FormatException();
}
}
final records = <ExamRecord>[];
var explicitlyEmpty = false;
for (final row in rows.skip(1)) {
// DataTables can insert a single explicit no-data placeholder.
if (row.children.length == 1 &&
row.children.first.attributes['colspan'] == '12' &&
const [
'没有数据',
'暂无数据',
'无数据',
'No data available in table',
].contains(row.text.trim())) {
explicitlyEmpty = true;
continue;
}
if (row.children.length != 12 ||
row.querySelector('script,style') != null) {
throw const FormatException();
}
final cells = row.children.map((c) => c.text.trim()).toList();
records.add(
ExamRecord(
code: cells[4],
name: cells[5],
assessment: cells[6],
candidate: cells[7],
sequence: cells[8],
room: cells[9],
seat: cells[10],
time: cells[11],
),
);
}
if (records.isEmpty && !explicitlyEmpty) throw const FormatException();
return ExamSchedule.fromJson(
ExamSchedule(
semesterLabel: selected.text.trim(),
termId: term,
records: records,
).toJson(),
);
} catch (_) {
throw const FormatException('未识别到完整的考试查询表,已有考试信息保持不变。');
}
}
}
@@ -0,0 +1,34 @@
import 'school_navigation_policy.dart';
/// Only the authenticated graduate system may advance the service handshake.
class SchoolLoginFlow {
Uri? _target;
bool _requested = false;
void begin(Uri target) {
_target = target;
_requested = false;
}
void reset() {
_target = null;
_requested = false;
}
Uri? onLoaded(Uri uri, {required bool authenticated}) {
if (_target == null || !SchoolNavigationPolicy.isSchoolPage(uri)) {
return null;
}
if (uri.host == 'idas.uestc.edu.cn') {
_requested = false;
return null;
}
if (uri.path == _target!.path ||
_requested ||
!authenticated ||
!uri.path.startsWith('/pyxx/')) {
return null;
}
_requested = true;
return _target;
}
}
@@ -1,4 +1,21 @@
class SchoolNavigationPolicy {
static Uri? secureIdentityRedirect(Uri uri) {
if (uri.scheme != 'http' ||
uri.port != 80 ||
uri.userInfo.isNotEmpty ||
uri.host != 'idas.uestc.edu.cn' ||
uri.path != '/authserver/login') {
return null;
}
return Uri(
scheme: 'https',
host: uri.host,
path: uri.path,
query: uri.hasQuery ? uri.query : null,
fragment: uri.hasFragment ? uri.fragment : null,
);
}
static bool canNavigate(Uri uri, {required bool isMainFrame}) => isMainFrame
? isSchoolPage(uri)
: (uri.scheme == 'https' && uri.userInfo.isEmpty) ||
@@ -17,6 +34,18 @@ class SchoolNavigationPolicy {
r'$',
).hasMatch(uri.path);
static bool isSchoolPage(Uri uri) =>
(_https(uri) &&
const {
'idas.uestc.edu.cn',
'yjsjy.uestc.edu.cn',
}.contains(uri.host)) ||
(uri.scheme == 'http' &&
uri.port == 80 &&
uri.userInfo.isEmpty &&
uri.host == 'yjsjy.uestc.edu.cn' &&
uri.path.startsWith('/pyxx/'));
static bool isExam(Uri uri) =>
_https(uri) &&
const {'idas.uestc.edu.cn', 'yjsjy.uestc.edu.cn'}.contains(uri.host);
uri.host == 'yjsjy.uestc.edu.cn' &&
uri.path == '/pyxx/pygl/kskcxx/index';
}
+253 -171
View File
@@ -1,11 +1,15 @@
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../data/json_schedule_import.dart';
import '../../domain/exam_schedule.dart';
import 'school_navigation_policy.dart';
import 'school_page_adapter.dart';
import 'school_exam_adapter.dart';
import 'school_login_flow.dart';
enum SchoolConnectionState {
signedOut,
@@ -21,15 +25,30 @@ class SchoolSession extends ChangeNotifier {
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(
onNavigationRequest: (request) {
onNavigationRequest: (request) async {
final uri = Uri.tryParse(request.url);
final upgrade = uri == null || !request.isMainFrame
? null
: SchoolNavigationPolicy.secureIdentityRedirect(uri);
if (upgrade != null) {
try {
await web.loadRequest(upgrade);
} catch (_) {
_failure('学校身份认证暂时无法打开,请重试。');
}
return NavigationDecision.prevent;
}
if (uri == null ||
!SchoolNavigationPolicy.canNavigate(
uri,
isMainFrame: request.isMainFrame,
)) {
message = '学校跳转到了其他地址,已停止自动交接登录信息。';
notifyListeners();
if (kDebugMode && request.isMainFrame) {
debugPrint(
'Blocked school navigation origin: ${uri?.scheme}://${uri?.host}',
);
}
if (request.isMainFrame) _failure('学校跳转到了其他地址,请返回学校认证入口重试。');
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
@@ -38,230 +57,293 @@ class SchoolSession extends ChangeNotifier {
_pageGeneration++;
_reader.invalidate();
pendingDraft = null;
if (!hasOpened) {
return;
}
pendingExams = null;
if (!hasOpened) return;
_loading = true;
formReady = false;
notifyListeners();
},
onPageFinished: _loaded,
onWebResourceError: (error) {
if (error.isForMainFrame == true) {
_loading = false;
message = '学校页面暂时未能加载,请检查网络或使用统一认证入口。';
notifyListeners();
onWebResourceError: (error) async {
if (error.isForMainFrame != true || error.url == null) return;
final generation = _pageGeneration;
final current = await web.currentUrl();
if (hasOpened &&
generation == _pageGeneration &&
error.url == current) {
_failure('学校页面暂时未能加载,请检查网络后重试。');
}
},
onHttpError: (error) async {
final generation = _pageGeneration;
final current = Uri.tryParse(await web.currentUrl() ?? '');
if (!hasOpened ||
error.request == null ||
error.request!.uri != current) {
return;
if (hasOpened &&
generation == _pageGeneration &&
error.request != null &&
error.request!.uri == current) {
_failure('学校请求未完成,请稍后重试。');
}
_loading = false;
message = '学校页面请求未完成,可稍后重试。';
notifyListeners();
},
),
);
}
late final WebViewController web;
final _reader = SchoolReader(SchoolPageAdapter());
final _flow = SchoolLoginFlow();
Timer? _timeout;
SchoolConnectionState connectionState = SchoolConnectionState.signedOut;
bool _loading = false,
_submitting = false,
hasOpened = false,
formReady = false;
bool get busy => _loading || _submitting || _reader.busy;
finding = false,
requestingExams = false;
bool logoutFailed = false;
bool get canLogout => hasOpened || logoutFailed;
bool get busy => _loading || _reader.busy;
int _pageGeneration = 0;
int get pageGeneration => _pageGeneration;
Future<void>? _logoutFuture;
int _openSerial = 0;
ImportDraft? pendingDraft;
String message = '请通过学校统一身份认证登录。';
String get statusLabel => switch (connectionState) {
SchoolConnectionState.signedOut => '未登录',
SchoolConnectionState.authenticating => '请在学校页面完成认证',
SchoolConnectionState.connected => '学校认证已确认',
SchoolConnectionState.expired => '学校登录已过期',
SchoolConnectionState.unknown => '学校页面已打开 · 等待完整课表',
};
ExamSchedule? pendingExams;
String message = '请在学校网页中完成登录与验证码。';
String get statusLabel => logoutFailed
? '学校退出未完成,请重试'
: switch (connectionState) {
SchoolConnectionState.signedOut => '未登录',
SchoolConnectionState.authenticating => '请在学校页面完成认证',
SchoolConnectionState.connected => '研究生系统已连接',
SchoolConnectionState.expired => '学校登录已过期',
SchoolConnectionState.unknown => '学校连接未确认',
};
// HTTPS entry produces the same official HTTP service callback. Do not drop
// the graduate-service query by opening a generic identity login page.
static final authUrl = Uri.parse(
'https://idas.uestc.edu.cn/authserver/login',
'https://yjsjy.uestc.edu.cn/pyxx/jzsso/login',
);
static final timetableUrl = Uri.parse(
'https://yjsjy.uestc.edu.cn/pyxx/pygl/xskbcx/index/1',
);
Future<void> open() => openTimetable();
Future<void> openTimetable() async {
hasOpened = true;
_loading = true;
static final examUrl = Uri.parse(
'https://yjsjy.uestc.edu.cn/pyxx/pygl/kskcxx/index',
);
Uri get _target => requestingExams ? examUrl : timetableUrl;
Future<void> open() => _open(exams: false);
Future<void> openTimetable() => _open(exams: false);
Future<void> openExams() => _open(exams: true);
Future<void> openAuthentication() =>
_open(exams: requestingExams, forceAuth: true);
Future<void> _open({required bool exams, bool forceAuth = false}) async {
final serial = ++_openSerial;
final closing = _logoutFuture;
if (closing != null) await closing;
if (serial != _openSerial) return;
_timeout?.cancel();
_pageGeneration++;
_reader.invalidate();
pendingDraft = null;
message = '正在打开研究生课表页面…';
notifyListeners();
try {
await web.loadRequest(timetableUrl);
} catch (_) {
_loading = false;
message = '学校课表页面无法打开,请检查校园网络。';
notifyListeners();
}
}
Future<void> openAuthentication() async {
pendingExams = null;
requestingExams = exams;
logoutFailed = false;
hasOpened = true;
_loading = true;
message = '正在准备学校认证…';
_flow.begin(_target);
final connected =
connectionState == SchoolConnectionState.connected && !forceAuth;
finding = connected;
message = connected ? _findingMessage : '请在学校网页中完成登录与验证码。';
if (connected) _armTimeout();
notifyListeners();
try {
await web.loadRequest(authUrl);
await web.loadRequest(connected ? _target : authUrl);
} catch (_) {
_loading = false;
message = '学校认证页面暂时不可用。';
notifyListeners();
if (serial == _openSerial) _failure('学校入口无法打开,请检查校园网络后重试。');
}
}
String get _findingMessage => requestingExams ? '正在查找考试安排,请稍候' : '正在查找课表,请稍候';
void _armTimeout() {
_timeout?.cancel();
_timeout = Timer(
const Duration(seconds: 45),
() => _failure('查找超时,请检查学校页面后重试。已有数据保持不变。'),
);
}
void _failure(String text) {
if (!hasOpened) return;
_pageGeneration++;
_reader.invalidate();
_timeout?.cancel();
finding = false;
_loading = false;
message = text;
notifyListeners();
}
Future<String> _html() async {
final raw = await web.runJavaScriptReturningResult(
'JSON.stringify(document.documentElement.outerHTML)',
);
final value = raw is String ? raw : raw.toString();
try {
final decoded = jsonDecode(value);
return decoded is String ? decoded : value;
} catch (_) {
return value;
}
}
static const _readyScript = """(() => {
if (location.origin !== 'https://idas.uestc.edu.cn' || location.pathname !== '/authserver/login') return false;
const f = document.querySelector('.login-main #pwdFromId');
if (!f || f.method.toLowerCase() !== 'post') return false;
const action = new URL(f.action, location.href);
return action.origin === location.origin && action.pathname === '/authserver/login'
&& !!f.querySelector('#username') && !!f.querySelector('#password')
&& !!f.querySelector('#saltPassword') && !!f.querySelector('#pwdEncryptSalt')
&& !!f.querySelector('#login_submit') && typeof window.startLogin === 'function'
&& typeof window.encryptPassword === 'function' && typeof window.checkUserCaptcha === 'function';
})()""";
bool _truth(Object value) => value == true || value.toString() == 'true';
Future<void> _loaded(String url) async {
if (!hasOpened) {
if (!hasOpened) return;
final generation = _pageGeneration;
final uri = Uri.tryParse(url);
final current = await web.currentUrl();
if (!hasOpened ||
generation != _pageGeneration ||
current != url ||
uri == null ||
!SchoolNavigationPolicy.isSchoolPage(uri)) {
return;
}
_loading = false;
final generation = _pageGeneration;
final uri = Uri.tryParse(url);
if (uri != null && SchoolNavigationPolicy.canInjectCredentials(uri)) {
connectionState = connectionState == SchoolConnectionState.connected
? SchoolConnectionState.expired
: SchoolConnectionState.authenticating;
if (uri.host == 'idas.uestc.edu.cn') {
_timeout?.cancel();
finding = false;
connectionState = SchoolConnectionState.authenticating;
_flow.onLoaded(uri, authenticated: false);
message = '请在学校网页中完成登录与验证码。';
notifyListeners();
return;
}
final targetPage = requestingExams
? SchoolNavigationPolicy.isExam(uri)
: SchoolNavigationPolicy.isTimetable(uri);
if (targetPage) {
finding = true;
message = _findingMessage;
notifyListeners();
try {
final ready = _truth(
await web.runJavaScriptReturningResult(_readyScript),
);
if (!hasOpened || generation != _pageGeneration) return;
formReady = ready;
if (requestingExams) {
final text = await _html();
if (!hasOpened || generation != _pageGeneration) return;
final draft = SchoolExamAdapter.extract(text);
pendingExams = draft;
} else {
final draft = await readTimetable();
if (!hasOpened || generation != _pageGeneration) return;
pendingDraft = draft;
}
_timeout?.cancel();
connectionState = SchoolConnectionState.connected;
message = '读取成功,正在保存…';
} catch (_) {
if (!hasOpened || generation != _pageGeneration) return;
formReady = false;
}
message = formReady ? '可以使用应用界面登录;验证码会在学校页面完成。' : '请使用学校原页面完成认证。';
} else if (uri != null && SchoolNavigationPolicy.isTimetable(uri)) {
connectionState = SchoolConnectionState.unknown;
message = '已打开课表页面,正在核对课程结构。';
try {
final draft = await readTimetable();
if (!hasOpened || generation != _pageGeneration) return;
pendingDraft = draft;
connectionState = SchoolConnectionState.connected;
} catch (error) {
if (!hasOpened || generation != _pageGeneration) return;
message = error is UnsupportedSchoolLayout
? error.toString()
: '课表读取未完成,已有课表保持不变。';
}
} else {
connectionState = SchoolConnectionState.unknown;
message = '可点击右上角日历打开学校课表。';
}
notifyListeners();
}
Future<void> submitCredentials(String username, String password) async {
if (busy) return;
_submitting = true;
message = '正在交接学校认证…';
notifyListeners();
try {
final url = Uri.tryParse(await web.currentUrl() ?? '');
if (url == null ||
!SchoolNavigationPolicy.canInjectCredentials(url) ||
!_truth(await web.runJavaScriptReturningResult(_readyScript))) {
throw StateError('学校表单尚未准备好,请使用学校页面登录');
}
final result = await web.runJavaScriptReturningResult('''(() => {
if (!($_readyScript)) return false;
const f = document.querySelector('.login-main #pwdFromId');
const u = f.querySelector('#username'), p = f.querySelector('#password');
u.value = ${jsonEncode(username)}; p.value = ${jsonEncode(password)};
p.removeAttribute('readonly');
u.dispatchEvent(new Event('input', {bubbles:true}));
p.dispatchEvent(new Event('input', {bubbles:true}));
window.checkUserCaptcha(); return true;
})()''');
if (!_truth(result)) throw StateError('学校表单已变化,请使用学校页面登录');
var settled = false;
for (var i = 0; i < 20; i++) {
if (_truth(
await web.runJavaScriptReturningResult(
'!!window.jQuery && window.jQuery.active === 0',
),
)) {
settled = true;
break;
}
await Future<void>.delayed(const Duration(milliseconds: 200));
}
final current = Uri.tryParse(await web.currentUrl() ?? '');
if (!settled ||
current == null ||
!SchoolNavigationPolicy.canInjectCredentials(current)) {
message = '请在学校页面继续完成验证。';
_failure(
'没有读取到完整${requestingExams ? '考试信息' : '课表'},请检查学校页面后重试。已有数据保持不变。',
);
return;
}
await web.runJavaScript('''(() => {
if (!($_readyScript)) return;
window.startLogin(document.querySelector('.login-main #pwdFromId #login_submit'));
})()''');
message = '已交给学校处理;如有验证码,请在学校页面完成。';
} catch (_) {
message = '登录交接未完成,请使用学校页面继续。';
} finally {
_submitting = false;
notifyListeners();
} else {
// A logout link is evidence of a graduate-system session, unlike simply
// returning to a callback URL or the identity administration dashboard.
bool authenticated = false;
try {
authenticated = _truth(
await web.runJavaScriptReturningResult("""(() => {
return Array.from(document.querySelectorAll('a[href]')).some(a => {
try { const u = new URL(a.href, location.href); return u.hostname === 'yjsjy.uestc.edu.cn' && u.pathname === '/pyxx/home/exit'; } catch (_) { return false; }
});
})()"""),
);
} catch (_) {
/* Keep the school page available for manual recovery. */
}
if (!hasOpened || generation != _pageGeneration) return;
final next = _flow.onLoaded(uri, authenticated: authenticated);
if (next != null) {
finding = true;
_loading = true;
message = _findingMessage;
_armTimeout();
notifyListeners();
try {
await web.loadRequest(next);
} catch (_) {
_failure('课表查询页面暂时无法打开,请重试。');
}
return;
}
finding = false;
message = '请在学校网页完成认证;进入研究生系统后会自动读取。';
}
notifyListeners();
}
Future<ImportDraft> readTimetable() async {
final uri = Uri.tryParse(await web.currentUrl() ?? '');
if (uri == null) throw UnsupportedSchoolLayout();
return _reader.read(uri, () async {
final raw = await web.runJavaScriptReturningResult(
'JSON.stringify(document.documentElement.outerHTML)',
);
final value = raw is String ? raw : raw.toString();
try {
final decoded = jsonDecode(value);
return decoded is String ? decoded : value;
} catch (_) {
return value;
}
});
return _reader.read(uri, _html);
}
Future<void> logout() async {
bool saved({
required bool success,
required int generation,
ImportDraft? draft,
ExamSchedule? exams,
}) {
if (generation != _pageGeneration ||
draft != pendingDraft ||
exams != pendingExams) {
return false;
}
pendingDraft = null;
pendingExams = null;
finding = false;
message = success
? '${requestingExams ? '考试安排' : '课表'}已导入并在本机保存。'
: '保存未完成,请重试。';
notifyListeners();
return true;
}
Future<void> logout() {
if (_logoutFuture != null) return _logoutFuture!;
final future = _performLogout();
_logoutFuture = future;
return future.whenComplete(() => _logoutFuture = null);
}
Future<void> _performLogout() async {
_openSerial++;
_pageGeneration++;
_reader.invalidate();
hasOpened = false;
await WebViewCookieManager().clearCookies();
await web.clearCache();
await web.clearLocalStorage();
await web.loadHtmlString('<html></html>');
_loading = false;
_flow.reset();
_timeout?.cancel();
hasOpened = false;
pendingDraft = null;
formReady = false;
connectionState = SchoolConnectionState.signedOut;
message = '已退出学校登录。';
pendingExams = null;
finding = false;
var failed = false;
try {
await WebViewCookieManager().clearCookies();
await web.clearCache();
await web.clearLocalStorage();
await web.loadHtmlString('<html></html>');
} catch (_) {
failed = true;
}
_loading = false;
logoutFailed = failed;
connectionState = failed
? SchoolConnectionState.unknown
: SchoolConnectionState.signedOut;
message = failed ? '学校退出未完成,请重试;重新连接会再次经过学校认证。' : '已退出学校登录。';
notifyListeners();
}
@override
void dispose() {
_timeout?.cancel();
super.dispose();
}
}
@@ -32,6 +32,7 @@ class _TimetablePageState extends State<TimetablePage> {
: term.firstMonday.add(Duration(days: (week - 1) * 7));
final sunday = monday.add(const Duration(days: 6));
return ListView(
key: const PageStorageKey('timetable-scroll'),
padding: EdgeInsets.fromLTRB(
8,
10,
@@ -40,7 +41,7 @@ class _TimetablePageState extends State<TimetablePage> {
),
children: [
const Text(
'Riverside Schedule',
'RSchedule',
style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.w700,
@@ -157,7 +158,7 @@ class _TimetablePageState extends State<TimetablePage> {
),
const SizedBox(height: 12),
Text(
'在「我的」设置学期并导入课程,\n或先看看示例课表。',
'在「个人设置」设置学期并导入课程,\n或先看看示例课表。',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 13,