350 lines
12 KiB
Dart
350 lines
12 KiB
Dart
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,
|
|
authenticating,
|
|
connected,
|
|
expired,
|
|
unknown,
|
|
}
|
|
|
|
class SchoolSession extends ChangeNotifier {
|
|
SchoolSession() {
|
|
web = WebViewController()
|
|
..setJavaScriptMode(JavaScriptMode.unrestricted)
|
|
..setNavigationDelegate(
|
|
NavigationDelegate(
|
|
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,
|
|
)) {
|
|
if (kDebugMode && request.isMainFrame) {
|
|
debugPrint(
|
|
'Blocked school navigation origin: ${uri?.scheme}://${uri?.host}',
|
|
);
|
|
}
|
|
if (request.isMainFrame) _failure('学校跳转到了其他地址,请返回学校认证入口重试。');
|
|
return NavigationDecision.prevent;
|
|
}
|
|
return NavigationDecision.navigate;
|
|
},
|
|
onPageStarted: (_) {
|
|
_pageGeneration++;
|
|
_reader.invalidate();
|
|
pendingDraft = null;
|
|
pendingExams = null;
|
|
if (!hasOpened) return;
|
|
_loading = true;
|
|
notifyListeners();
|
|
},
|
|
onPageFinished: _loaded,
|
|
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 &&
|
|
generation == _pageGeneration &&
|
|
error.request != null &&
|
|
error.request!.uri == current) {
|
|
_failure('学校请求未完成,请稍后重试。');
|
|
}
|
|
},
|
|
),
|
|
);
|
|
}
|
|
late final WebViewController web;
|
|
final _reader = SchoolReader(SchoolPageAdapter());
|
|
final _flow = SchoolLoginFlow();
|
|
Timer? _timeout;
|
|
SchoolConnectionState connectionState = SchoolConnectionState.signedOut;
|
|
bool _loading = false,
|
|
hasOpened = false,
|
|
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;
|
|
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://yjsjy.uestc.edu.cn/pyxx/jzsso/login',
|
|
);
|
|
static final timetableUrl = Uri.parse(
|
|
'https://yjsjy.uestc.edu.cn/pyxx/pygl/xskbcx/index/1',
|
|
);
|
|
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;
|
|
pendingExams = null;
|
|
requestingExams = exams;
|
|
logoutFailed = false;
|
|
hasOpened = true;
|
|
_loading = true;
|
|
_flow.begin(_target);
|
|
final connected =
|
|
connectionState == SchoolConnectionState.connected && !forceAuth;
|
|
finding = connected;
|
|
message = connected ? _findingMessage : '请在学校网页中完成登录与验证码。';
|
|
if (connected) _armTimeout();
|
|
notifyListeners();
|
|
try {
|
|
await web.loadRequest(connected ? _target : authUrl);
|
|
} catch (_) {
|
|
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;
|
|
}
|
|
}
|
|
|
|
bool _truth(Object value) => value == true || value.toString() == 'true';
|
|
Future<void> _loaded(String url) async {
|
|
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;
|
|
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 {
|
|
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;
|
|
_failure(
|
|
'没有读取到完整${requestingExams ? '考试信息' : '课表'},请检查学校页面后重试。已有数据保持不变。',
|
|
);
|
|
return;
|
|
}
|
|
} 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, _html);
|
|
}
|
|
|
|
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();
|
|
_flow.reset();
|
|
_timeout?.cancel();
|
|
hasOpened = false;
|
|
pendingDraft = null;
|
|
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();
|
|
}
|
|
}
|