feat: parse undergraduate timetable activity data
This commit is contained in:
@@ -0,0 +1,139 @@
|
||||
class UndergraduateActivity {
|
||||
UndergraduateActivity(
|
||||
this.teacher,
|
||||
this.name,
|
||||
this.courseCode,
|
||||
this.room,
|
||||
this.indices,
|
||||
this.weeks,
|
||||
);
|
||||
final String teacher, name, courseCode, room;
|
||||
final Set<int> indices, weeks;
|
||||
bool get cancelled => room == '停课';
|
||||
}
|
||||
|
||||
List<UndergraduateActivity> parseActivityData(
|
||||
String script, {
|
||||
required int unitCount,
|
||||
}) {
|
||||
if (unitCount != 12) throw const FormatException('本科节次结构无效');
|
||||
final matches = RegExp(
|
||||
r'new\s+TaskActivity\s*\((.*?)\)\s*;',
|
||||
dotAll: true,
|
||||
).allMatches(script).toList();
|
||||
final result = <UndergraduateActivity>[];
|
||||
for (var i = 0; i < matches.length; i++) {
|
||||
final m = matches[i], args = _strings(m[1]!);
|
||||
if (args.length != 7) throw const FormatException('课程活动字段不完整');
|
||||
final suffix = RegExp(r'\(([A-Za-z0-9_.-]+)\)$').firstMatch(args[3]);
|
||||
if (suffix == null || args[1].trim().isEmpty || args[5].trim().isEmpty)
|
||||
throw const FormatException('教师、教室或课程序号缺失');
|
||||
final bitmap = args[6];
|
||||
if (!RegExp(r'^0[01]+$').hasMatch(bitmap) ||
|
||||
bitmap.length > 64 ||
|
||||
(bitmap.length > 31 && bitmap.substring(31).contains('1')))
|
||||
throw const FormatException('上课周次超出1–30周');
|
||||
final weeks = {
|
||||
for (var w = 1; w < bitmap.length && w <= 30; w++)
|
||||
if (bitmap[w] == '1') w,
|
||||
};
|
||||
if (weeks.isEmpty) throw const FormatException('课程周次为空');
|
||||
var end = i + 1 < matches.length ? matches[i + 1].start : script.length;
|
||||
final finish = script.indexOf('table0.marshalTable', m.end);
|
||||
if (finish >= 0 && finish < end) end = finish;
|
||||
final body = script.substring(m.end, end);
|
||||
final indices = <int>{};
|
||||
final assignments = RegExp(r'\bindex\s*=\s*([^;]+);')
|
||||
.allMatches(body)
|
||||
.toList();
|
||||
final appends = RegExp(
|
||||
r'table\d+\.activities\[index\]\s*\[[^;]+?\]\s*=\s*activity\s*;',
|
||||
).allMatches(body).length;
|
||||
if (assignments.isEmpty || assignments.length != appends)
|
||||
throw const FormatException('课程节次赋值不完整');
|
||||
for (final assignment in assignments) {
|
||||
final expression = RegExp(r'^\s*(\d+)\s*\*\s*unitCount\s*\+\s*(\d+)\s*$')
|
||||
.firstMatch(assignment[1]!);
|
||||
if (expression == null) throw const FormatException('不支持的节次表达式');
|
||||
final day = int.parse(expression[1]!), period = int.parse(expression[2]!);
|
||||
if (day > 6 || period >= unitCount)
|
||||
throw const FormatException('课程星期或节次无效');
|
||||
indices.add(day * unitCount + period);
|
||||
}
|
||||
result.add(
|
||||
UndergraduateActivity(
|
||||
args[1].trim(),
|
||||
args[3].substring(0, suffix.start).trim(),
|
||||
suffix[1]!,
|
||||
args[5].trim(),
|
||||
indices,
|
||||
weeks,
|
||||
),
|
||||
);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Reads only quoted JS literals; expressions and calls are never evaluated.
|
||||
List<String> _strings(String input) {
|
||||
final out = <String>[];
|
||||
var p = 0;
|
||||
void spaces() {
|
||||
while (p < input.length && RegExp(r'\s').hasMatch(input[p])) {
|
||||
p++;
|
||||
}
|
||||
}
|
||||
|
||||
while (true) {
|
||||
spaces();
|
||||
if (p >= input.length) break;
|
||||
final quote = input[p++];
|
||||
if (quote != '"' && quote != "'") throw const FormatException('活动参数必须为字符串');
|
||||
final b = StringBuffer();
|
||||
var closed = false;
|
||||
while (p < input.length) {
|
||||
var c = input[p++];
|
||||
if (c == quote) {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
if (c == '\\') {
|
||||
if (p >= input.length) throw const FormatException('字符串转义不完整');
|
||||
c = input[p++];
|
||||
const escapes = {
|
||||
'n': '\n',
|
||||
'r': '\r',
|
||||
't': '\t',
|
||||
'b': '\b',
|
||||
'f': '\f',
|
||||
'v': '\u000b',
|
||||
'0': '\u0000',
|
||||
};
|
||||
if (c == 'u' || c == 'x') {
|
||||
final count = c == 'u' ? 4 : 2;
|
||||
if (p + count > input.length) throw const FormatException('字符串转义无效');
|
||||
final hex = input.substring(p, p + count);
|
||||
if (!RegExp(r'^[0-9a-fA-F]+$').hasMatch(hex))
|
||||
throw const FormatException('字符串转义无效');
|
||||
b.writeCharCode(int.parse(hex, radix: 16));
|
||||
p += count;
|
||||
} else if (escapes.containsKey(c)) {
|
||||
b.write(escapes[c]);
|
||||
} else if (const ['"', "'", '\\', '/'].contains(c)) {
|
||||
b.write(c);
|
||||
} else {
|
||||
throw const FormatException('不支持的字符串转义');
|
||||
}
|
||||
} else {
|
||||
if (c == '\n' || c == '\r') throw const FormatException('字符串未闭合');
|
||||
b.write(c);
|
||||
}
|
||||
}
|
||||
if (!closed) throw const FormatException('字符串未闭合');
|
||||
out.add(b.toString());
|
||||
spaces();
|
||||
if (p == input.length) break;
|
||||
if (input[p++] != ',') throw const FormatException('活动字段分隔无效');
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:html/parser.dart' as html;
|
||||
|
||||
import '../../../data/json_schedule_import.dart';
|
||||
import '../../../domain/course.dart';
|
||||
import '../../../domain/school_identity.dart';
|
||||
import '../../../domain/school_term.dart';
|
||||
import 'activity_data.dart';
|
||||
|
||||
class UndergraduateTimetableAdapter {
|
||||
static ImportDraft extract(
|
||||
String content,
|
||||
Uri uri, {
|
||||
CourseSource source = CourseSource.school,
|
||||
}) {
|
||||
try {
|
||||
if (uri.scheme != 'https' ||
|
||||
uri.host != 'eams.uestc.edu.cn' ||
|
||||
uri.port != 443 ||
|
||||
uri.userInfo.isNotEmpty ||
|
||||
!uri.path.startsWith('/eams/') ||
|
||||
source == CourseSource.demo ||
|
||||
utf8.encode(content).length > 2 * 1024 * 1024)
|
||||
throw const FormatException('不是本科课表页面');
|
||||
final doc = html.parse(content),
|
||||
table = html
|
||||
.parse(content)
|
||||
.querySelector('#manualArrangeCourseTable');
|
||||
if (table == null || doc.querySelector('input[type="password"]') != null)
|
||||
throw const FormatException('请先在学校网页打开课表');
|
||||
final termIds = doc
|
||||
.querySelectorAll('input[name="semester.id"]')
|
||||
.map((e) => e.attributes['value'])
|
||||
.toSet();
|
||||
if (termIds.length != 1) throw const FormatException('课表学期不明确');
|
||||
final term = SchoolTerm(
|
||||
int.parse(termIds.single!),
|
||||
school: SupportedSchool.uestcUndergraduate,
|
||||
);
|
||||
final scripts = doc
|
||||
.querySelectorAll('script')
|
||||
.map((e) => e.text)
|
||||
.join('\n');
|
||||
final units = RegExp(r'\b(?:var\s+)?unitCount\s*=\s*(\d+)\s*;')
|
||||
.allMatches(scripts)
|
||||
.map((m) => int.parse(m[1]!))
|
||||
.toSet();
|
||||
final activities = units.length == 1
|
||||
? parseActivityData(scripts, unitCount: units.single)
|
||||
: <UndergraduateActivity>[];
|
||||
final explicitEmpty =
|
||||
activities.isEmpty && RegExp(r'暂无课程|无课程安排|没有课程').hasMatch(table.text);
|
||||
if (activities.isEmpty && !explicitEmpty)
|
||||
throw const FormatException('课表尚未加载完整');
|
||||
final roster = <String, ({String code, String notes})>{};
|
||||
for (final grid in doc.querySelectorAll('table')) {
|
||||
final rows = grid.querySelectorAll('tr');
|
||||
if (rows.isEmpty) continue;
|
||||
final headers = rows.first.children.map((e) => e.text.trim()).toList();
|
||||
if (!headers.contains('课程序号') || !headers.contains('课程代码')) continue;
|
||||
final seq = headers.indexOf('课程序号'),
|
||||
code = headers.indexOf('课程代码'),
|
||||
note = headers.indexOf('选课备注');
|
||||
for (final row in rows.skip(1)) {
|
||||
final cells = row.children;
|
||||
if (cells.length != headers.length)
|
||||
throw const FormatException('课程名单不完整');
|
||||
roster[cells[seq].text.trim()] = (
|
||||
code: cells[code].text.trim(),
|
||||
notes: note >= 0 ? cells[note].text.trim() : '',
|
||||
);
|
||||
}
|
||||
}
|
||||
final cancellations = <String, Set<int>>{};
|
||||
for (final a in activities.where((a) => a.cancelled)) {
|
||||
for (final index in a.indices) {
|
||||
cancellations
|
||||
.putIfAbsent('${a.courseCode}/$index', () => {})
|
||||
.addAll(a.weeks);
|
||||
}
|
||||
}
|
||||
final cells =
|
||||
<String, ({UndergraduateActivity a, int index, Set<int> weeks})>{};
|
||||
for (final a in activities.where((a) => !a.cancelled)) {
|
||||
for (final index in a.indices) {
|
||||
final weeks = a.weeks.difference(
|
||||
cancellations['${a.courseCode}/$index'] ?? {},
|
||||
);
|
||||
if (weeks.isEmpty) continue;
|
||||
final key = jsonEncode([
|
||||
a.courseCode,
|
||||
a.name,
|
||||
a.teacher,
|
||||
a.room,
|
||||
index,
|
||||
]);
|
||||
final cell = cells.putIfAbsent(
|
||||
key,
|
||||
() => (a: a, index: index, weeks: <int>{}),
|
||||
);
|
||||
cell.weeks.addAll(weeks);
|
||||
}
|
||||
}
|
||||
final groups =
|
||||
<
|
||||
String,
|
||||
({UndergraduateActivity a, Set<int> weeks, List<int> indices})
|
||||
>{};
|
||||
for (final cell in cells.values) {
|
||||
final key = jsonEncode([
|
||||
cell.a.courseCode,
|
||||
cell.a.name,
|
||||
cell.a.teacher,
|
||||
cell.a.room,
|
||||
cell.index ~/ 12,
|
||||
cell.weeks.toList()..sort(),
|
||||
]);
|
||||
groups
|
||||
.putIfAbsent(
|
||||
key,
|
||||
() => (a: cell.a, weeks: cell.weeks, indices: <int>[]),
|
||||
)
|
||||
.indices
|
||||
.add(cell.index);
|
||||
}
|
||||
final courses = <Course>[];
|
||||
for (final group in groups.values) {
|
||||
final indices = group.indices..sort();
|
||||
for (var p = 0; p < indices.length;) {
|
||||
final first = indices[p];
|
||||
var last = first;
|
||||
p++;
|
||||
while (p < indices.length && indices[p] == last + 1) {
|
||||
last = indices[p++];
|
||||
}
|
||||
final a = group.a, info = roster[a.courseCode];
|
||||
final identity = jsonEncode([
|
||||
term.id,
|
||||
a.courseCode,
|
||||
a.name,
|
||||
a.teacher,
|
||||
a.room,
|
||||
first,
|
||||
last,
|
||||
group.weeks.toList()..sort(),
|
||||
]);
|
||||
courses.add(
|
||||
Course(
|
||||
id: 'uestc-undergraduate-${term.id}-${_hash(identity)}',
|
||||
name: a.name,
|
||||
teacher: a.teacher,
|
||||
room: a.room,
|
||||
weekday: first ~/ 12 + 1,
|
||||
startPeriod: first % 12 + 1,
|
||||
endPeriod: last % 12 + 1,
|
||||
weeks: group.weeks,
|
||||
source: source,
|
||||
courseCode: info?.code ?? a.courseCode,
|
||||
notes: info?.notes ?? '',
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
if (courses.isEmpty && !explicitEmpty)
|
||||
throw const FormatException('没有识别到有效上课安排');
|
||||
return ImportDraft(
|
||||
courses: List.unmodifiable(courses),
|
||||
explicitlyEmpty: explicitEmpty,
|
||||
source: source,
|
||||
parserVersion: 'uestc-undergraduate-v1',
|
||||
schoolTerm: term,
|
||||
semesterLabel: term.label,
|
||||
);
|
||||
} on FormatException {
|
||||
rethrow;
|
||||
} catch (_) {
|
||||
throw const FormatException('本科课表结构或学期无效,原课表保持不变');
|
||||
}
|
||||
}
|
||||
|
||||
static String _hash(String value) {
|
||||
var h = 0x811c9dc5;
|
||||
for (final b in utf8.encode(value)) {
|
||||
h = ((h ^ b) * 0x01000193) & 0xffffffff;
|
||||
}
|
||||
return h.toRadixString(16).padLeft(8, '0');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user