feat: deliver RSchedule service login exams and elastic glass navigation
This commit is contained in:
@@ -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();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user