Files
suixinkan_uikit/suixinkan/UI/Training/TrainingCourseViewController.swift
T

565 lines
26 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import SafariServices
import SnapKit
import UIKit
import WebKit
/// 正式课程按需阅读:正文分页、附件授权与服务端确认的前台读时。
@MainActor
final class TrainingCourseViewController: TrainingBaseViewController {
private let service: any TrainingDataServing
private let viewModel: TrainingRemoteReadingViewModel
private let webView: WKWebView
private let toolbar = UIStackView()
private let sectionsButton = TrainingUI.button("章节目录", secondary: true)
private let attachmentsButton = TrainingUI.button("课程附件", secondary: true)
private let bottomStack = UIStackView()
private let noticeLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
private let actionButton = TrainingUI.button("正在加载课程…")
private var readingTimer: Timer?
private var contentTask: Task<Void, Never>?
private var readingTask: Task<Void, Never>?
private var closingTask: Task<Void, Never>?
private var closingGeneration = 0
private var contentNavigation: WKNavigation?
private var appIsActive = UIApplication.shared.applicationState == .active
private var isOpeningResource = false
private var contentIsReady = false
private var contentLoadFailed = false
private var pageIsVisible = false
/// 当前任务标识,成绩页可复用已有课程页面。
var taskID: String { viewModel.taskID }
/// 使用正式数据源读取课程,课程 HTML 禁用脚本执行。
init(taskID: String, service: any TrainingDataServing) {
self.service = service
let session = AppStore.shared.session
let scope = session.accountCachePrefix
let scenicID = session.currentScenicId
let storeID = session.currentStoreId
let token = session.token
viewModel = TrainingRemoteReadingViewModel(taskID: taskID, service: service, validateIdentity: {
let current = AppStore.shared.session
return current.accountCachePrefix == scope && current.currentScenicId == scenicID
&& current.currentStoreId == storeID && current.token == token
})
let configuration = WKWebViewConfiguration()
configuration.defaultWebpagePreferences.allowsContentJavaScript = false
webView = WKWebView(frame: .zero, configuration: configuration)
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func setupNavigationBar() { TrainingUI.navigation(self, title: "课程学习") }
override func setupUI() {
view.backgroundColor = TrainingUI.background
webView.navigationDelegate = self
webView.backgroundColor = TrainingUI.background
webView.isOpaque = false
toolbar.spacing = 10
toolbar.distribution = .fillEqually
toolbar.addArrangedSubview(sectionsButton)
toolbar.addArrangedSubview(attachmentsButton)
bottomStack.axis = .vertical
bottomStack.spacing = 8
bottomStack.layoutMargins = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12)
bottomStack.isLayoutMarginsRelativeArrangement = true
bottomStack.backgroundColor = AppColor.cardBackground
bottomStack.addArrangedSubview(noticeLabel)
bottomStack.addArrangedSubview(actionButton)
actionButton.accessibilityIdentifier = "training.reading.action"
sectionsButton.accessibilityIdentifier = "training.reading.sections"
attachmentsButton.accessibilityIdentifier = "training.reading.attachments"
view.addSubview(toolbar)
view.addSubview(webView)
view.addSubview(bottomStack)
applyState()
}
override func setupConstraints() {
toolbar.snp.makeConstraints {
$0.top.equalTo(view.safeAreaLayoutGuide).offset(8)
$0.leading.trailing.equalToSuperview().inset(13)
}
webView.snp.makeConstraints {
$0.top.equalTo(toolbar.snp.bottom).offset(8)
$0.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.bottom.equalTo(bottomStack.snp.top)
}
bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
}
override func bindActions() {
actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside)
sectionsButton.addTarget(self, action: #selector(sectionsTapped), for: .touchUpInside)
attachmentsButton.addTarget(self, action: #selector(attachmentsTapped), for: .touchUpInside)
NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange, NotificationName.userDidLogout] {
NotificationCenter.default.addObserver(self, selector: #selector(identityChanged), name: name, object: nil)
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
pageIsVisible = true
if viewModel.task == nil { loadCourse() }
else {
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.refreshProgress()
applyState()
resumeReading()
}
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
pageIsVisible = false
pauseReading()
}
override func onSessionDidExpire() { identityChanged() }
private var isContentVisible: Bool {
pageIsVisible && contentIsReady && !contentLoadFailed && !isOpeningResource && presentedViewController == nil
&& navigationController?.topViewController === self && appIsActive && UIApplication.shared.applicationState == .active
}
private func loadCourse() {
pauseReading()
contentIsReady = false
contentLoadFailed = false
contentNavigation = nil
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.load()
guard !Task.isCancelled else { return }
renderCurrentSection()
applyState()
}
}
private func selectSection(_ id: String) {
isOpeningResource = false
pauseReading()
contentIsReady = false
contentLoadFailed = false
contentNavigation = nil
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.selectSection(id: id)
guard !Task.isCancelled else { return }
renderCurrentSection()
applyState()
}
}
private func renderCurrentSection() {
guard !viewModel.isInvalidated, let task = viewModel.task?.summary,
let course = viewModel.course, let section = viewModel.currentSection else { return }
let metadata = task.mode == .exam
? "学习 + 考试 · \(course.sectionCount) 节 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格"
: "仅学习 · \(course.sectionCount) 节"
contentNavigation = webView.loadHTMLString("""
<!doctype html><html lang="zh-CN"><head><meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
<style>
*{box-sizing:border-box}body{font:15px -apple-system,BlinkMacSystemFont,sans-serif;color:#34435b;background:#f5f8fc;margin:0;padding:14px 13px;line-height:1.95;overflow-wrap:anywhere}
h1{font-size:17px;font-weight:600;line-height:1.6;color:#172033;margin:14px 0 6px}h2{font-size:15.5px;font-weight:600;color:#172033;margin:0 0 10px}img{max-width:100%;height:auto}table{max-width:100%;display:block;overflow:auto}a{color:#2379ff}
.step{display:flex;gap:20px;background:#edf1f7;padding:9px 12px;border-radius:8px;font-size:13px;color:#8994a6}.step b{font-weight:500;color:#2379ff}
.muted{font-size:12.5px;color:#8491a6;line-height:1.65;margin:6px 0}.reading{background:white;border:1px solid #e3ebf5;border-radius:11px;padding:14px;margin-top:14px}
</style></head><body><div class='step'><b>1 课程学习</b><span>\(task.mode == .exam ? "2 在线考试" : "完成学习")</span></div>
<h1>\(escape(task.title))</h1><p class='muted'>\(escape(course.title))</p><p class='muted'>\(metadata)</p><p class='muted'>\(escape(course.introduction))</p>
<p class='muted'>第 \(section.order) / \(course.sectionCount) 节</p><div class='reading'><h2>\(escape(section.title))</h2>\(section.contentHTML)</div></body></html>
""", baseURL: nil)
}
private func escape(_ text: String) -> String {
text.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
}
private func applyState() {
guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return }
sectionsButton.isEnabled = !viewModel.isLoading && !viewModel.sections.isEmpty
attachmentsButton.isEnabled = !viewModel.isLoading && (viewModel.course?.attachmentCount ?? 0) > 0
if let progress = viewModel.progress, progress.readingCompleted {
noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成"
if viewModel.task?.summary.mode == .exam && progress.canStartExam { setActionTitle("开始考试") }
else { setActionTitle("返回培训中心") }
actionButton.isEnabled = true
readingTimer?.invalidate()
readingTimer = nil
return
}
if contentLoadFailed || viewModel.currentSection == nil {
noticeLabel.text = viewModel.errorMessage ?? (contentLoadFailed ? "课程正文加载失败,请重试" : "正在加载课程…")
setActionTitle(contentLoadFailed || viewModel.errorMessage != nil ? "重新加载课程" : "正在加载课程…")
actionButton.isEnabled = !viewModel.isLoading && (contentLoadFailed || viewModel.errorMessage != nil)
return
}
if !viewModel.canStudy {
readingTimer?.invalidate()
readingTimer = nil
noticeLabel.text = viewModel.readingErrorMessage ?? "当前任务可回顾课程,不能继续提交学习记录"
setActionTitle("返回培训中心")
actionButton.isEnabled = true
} else if let error = viewModel.errorMessage {
readingTimer?.invalidate()
readingTimer = nil
noticeLabel.text = error
setActionTitle(viewModel.readingErrorMessage != nil ? "重试保存并继续学习" : "重新加载课程")
actionButton.isEnabled = true
} else {
let action = viewModel.task?.summary.mode == .exam ? "开始考试" : "完成学习"
noticeLabel.text = viewModel.readingNotice ?? (viewModel.remainingSeconds == 0 ? "正在确认学习进度…" : "请在前台阅读课程内容,倒计时结束后等待保存确认")
setActionTitle("\(action)(\(viewModel.remainingSeconds)s)")
actionButton.isEnabled = false
}
}
private func setActionTitle(_ title: String) {
var configuration = actionButton.configuration
configuration?.title = title
actionButton.configuration = configuration
}
@objc private func pauseReading() {
readingTimer?.invalidate()
readingTimer = nil
viewModel.pauseReading()
let previousClose = closingTask
closingGeneration += 1
let epoch = closingGeneration
closingTask = Task { @MainActor [weak self] in
guard let self else { return }
await previousClose?.value
await viewModel.flush()
if closingGeneration == epoch { closingTask = nil }
applyState()
resumeReading()
}
}
@objc private func appWillResignActive() { appIsActive = false; pauseReading() }
@objc private func appDidBecomeActive() { appIsActive = true; resumeReading() }
private func resumeReading(retrying: Bool = false) {
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), readingTask == nil else { return }
let pendingClose = closingTask
readingTask = Task { @MainActor [weak self] in
guard let self else { return }
await pendingClose?.value
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), !Task.isCancelled else {
readingTask = nil
return
}
await viewModel.startReading(at: ProcessInfo.processInfo.systemUptime)
readingTask = nil
applyState()
if isContentVisible && viewModel.isReading { installReadingTimer() }
}
}
private func installReadingTimer() {
guard readingTimer == nil else { return }
let timer = Timer(timeInterval: 0.25, repeats: true) { [weak self] _ in
Task { @MainActor in self?.readingTick() }
}
readingTimer = timer
RunLoop.main.add(timer, forMode: .common)
}
private func readingTick() {
guard isContentVisible, readingTask == nil, viewModel.isReading else { return }
readingTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.recordVisibleTime(at: ProcessInfo.processInfo.systemUptime)
readingTask = nil
applyState()
if isContentVisible, viewModel.canStudy, !viewModel.isReading { resumeReading() }
}
}
@objc private func identityChanged() {
readingTimer?.invalidate()
readingTimer = nil
contentTask?.cancel()
readingTask?.cancel()
closingTask?.cancel()
contentNavigation = nil
viewModel.invalidate()
leaveUnavailableCourse()
}
@objc private func actionTapped() {
if let progress = viewModel.progress, progress.readingCompleted {
pauseReading()
if viewModel.task?.summary.mode == .exam && progress.canStartExam {
navigationController?.pushViewController(TrainingExamViewController(taskID: taskID, service: service), animated: true)
} else { returnToCenter() }
} else if contentLoadFailed || viewModel.currentSection == nil {
if let sectionID = viewModel.currentSectionID { selectSection(sectionID) }
else { loadCourse() }
} else if !viewModel.canStudy { returnToCenter() }
else if viewModel.readingErrorMessage != nil {
resumeReading(retrying: true)
} else if viewModel.errorMessage != nil {
if let sectionID = viewModel.currentSectionID { selectSection(sectionID) }
else { loadCourse() }
}
}
private func returnToCenter() {
if let center = navigationController?.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
navigationController?.popToViewController(center, animated: true)
} else { navigationController?.popToRootViewController(animated: true) }
}
private func leaveUnavailableCourse() {
readingTimer?.invalidate()
readingTimer = nil
contentNavigation = nil
webView.stopLoading()
webView.loadHTMLString("", baseURL: nil)
if let presentedViewController {
presentedViewController.dismiss(animated: false) { [weak self] in self?.returnToCenter() }
} else { returnToCenter() }
}
@objc private func sectionsTapped() {
isOpeningResource = true
pauseReading()
let picker = TrainingCoursePickerViewController(title: "章节目录", rows: sectionRows(), hasMore: viewModel.hasMoreSections,
selectedID: viewModel.currentSectionID, select: { [weak self] id in self?.selectSection(id) },
loadMore: { [weak self] in
guard let self else { return ([], false) }
await viewModel.loadMoreSections()
applyState()
if let error = viewModel.errorMessage { showToast(error) }
return (sectionRows(), viewModel.hasMoreSections)
}, close: { [weak self] in self?.finishResourcePresentation() })
presentPicker(picker)
}
private func sectionRows() -> [TrainingCoursePickerRow] {
viewModel.sections.map { TrainingCoursePickerRow(id: $0.id, title: "\($0.order). \($0.title)") }
}
@objc private func attachmentsTapped() {
isOpeningResource = true
pauseReading()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await viewModel.loadAttachments()
guard !Task.isCancelled else { return }
if viewModel.isInvalidated { applyState(); return }
if let error = viewModel.errorMessage { isOpeningResource = false; showToast(error); applyState(); return }
let picker = TrainingCoursePickerViewController(title: "课程附件", rows: attachmentRows(), hasMore: viewModel.hasMoreAttachments,
select: { [weak self] id in self?.openAttachment(id) }, loadMore: { [weak self] in
guard let self else { return ([], false) }
await viewModel.loadAttachments(loadMore: true)
applyState()
if let error = viewModel.errorMessage { showToast(error) }
return (attachmentRows(), viewModel.hasMoreAttachments)
}, close: { [weak self] in self?.finishResourcePresentation() })
presentPicker(picker)
}
}
private func attachmentRows() -> [TrainingCoursePickerRow] {
viewModel.attachments.map { TrainingCoursePickerRow(id: $0.id, title: $0.name) }
}
private func presentPicker(_ picker: TrainingCoursePickerViewController) {
let navigation = UINavigationController(rootViewController: picker)
navigation.modalPresentationStyle = .pageSheet
navigation.sheetPresentationController?.detents = [.medium(), .large()]
navigation.sheetPresentationController?.prefersGrabberVisible = true
navigation.presentationController?.delegate = picker
present(navigation, animated: true)
}
private func openAttachment(_ id: String) {
isOpeningResource = true
pauseReading()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
guard let link = await viewModel.authorizeAttachment(id: id), !Task.isCancelled else {
isOpeningResource = false
if let error = viewModel.errorMessage { showToast(error) }
applyState()
return
}
let controller = SFSafariViewController(url: link.url)
controller.delegate = self
present(controller, animated: true)
}
}
private func finishResourcePresentation() {
isOpeningResource = false
resumeReading()
}
}
extension TrainingCourseViewController: WKNavigationDelegate {
/// 当前正文渲染完成且页面可见后才开始有效阅读。
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = true
contentLoadFailed = false
applyState()
resumeReading()
}
/// 正文初始加载失败时停止计时,保留重试入口。
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
/// 正文导航失败时不把失败页面停留计入学习。
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
/// 仅允许本机 HTML 初始加载;用户点击的 HTTPS 链接交给 Safari。
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .other, navigationAction.request.url?.absoluteString == "about:blank" {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
guard navigationAction.navigationType == .linkActivated,
let url = navigationAction.request.url, url.scheme?.lowercased() == "https", url.host != nil else { return }
isOpeningResource = true
pauseReading()
let controller = SFSafariViewController(url: url)
controller.delegate = self
present(controller, animated: true)
}
}
extension TrainingCourseViewController: SFSafariViewControllerDelegate {
/// 关闭外部链接后,仅在正文重新可见时建立新的阅读片段。
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true) { [weak self] in self?.finishResourcePresentation() }
}
}
/// 目录或附件选择器的一行展示数据,不携带业务行为。
private struct TrainingCoursePickerRow: Hashable {
let id: String
let title: String
}
/// 原生可滚动资源选择器;用户按需加载更多,选中或关闭后明确通知课程页面。
@MainActor
private final class TrainingCoursePickerViewController: UIViewController, UITableViewDelegate, UIAdaptivePresentationControllerDelegate {
/// 差异化列表中的资源项与主动分页入口。
private enum Item: Hashable { case resource(String), more }
private var rows: [TrainingCoursePickerRow]
private var hasMore: Bool
private let selectedID: String?
private let select: (String) -> Void
private let loadMore: () async -> ([TrainingCoursePickerRow], Bool)
private let close: () -> Void
private let tableView = UITableView(frame: .zero, style: .insetGrouped)
private var dataSource: UITableViewDiffableDataSource<Int, Item>!
private var isLoadingMore = false
/// 使用页面提供的展示行、明确选择动作与分页动作构造选择器。
init(title: String, rows: [TrainingCoursePickerRow], hasMore: Bool, selectedID: String? = nil,
select: @escaping (String) -> Void, loadMore: @escaping () async -> ([TrainingCoursePickerRow], Bool), close: @escaping () -> Void) {
self.rows = rows
self.hasMore = hasMore
self.selectedID = selectedID
self.select = select
self.loadMore = loadMore
self.close = close
super.init(nibName: nil, bundle: nil)
self.title = title
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = TrainingUI.background
navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak self] _ in
guard let self else { return }
dismiss(animated: true, completion: close)
})
tableView.delegate = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 52
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "resource")
view.addSubview(tableView)
tableView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
dataSource = UITableViewDiffableDataSource<Int, Item>(tableView: tableView) { [weak self] table, indexPath, item in
guard let self else { return nil }
let cell = table.dequeueReusableCell(withIdentifier: "resource", for: indexPath)
var content = UIListContentConfiguration.cell()
switch item {
case .resource(let id):
content.text = rows.first(where: { $0.id == id })?.title
content.textProperties.numberOfLines = 0
cell.accessoryType = id == selectedID ? .checkmark : .none
case .more:
content.text = isLoadingMore ? "正在加载…" : "加载更多"
content.textProperties.color = TrainingUI.primary
cell.accessoryType = .none
}
cell.contentConfiguration = content
return cell
}
applyRows()
}
private func applyRows() {
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
snapshot.appendSections([0])
snapshot.appendItems(rows.map { .resource($0.id) })
if hasMore { snapshot.appendItems([.more]) }
if hasMore, dataSource.snapshot().indexOfItem(.more) != nil { snapshot.reconfigureItems([.more]) }
dataSource.apply(snapshot, animatingDifferences: true)
}
/// 选择后等待模态页面完全关闭,再让课程加载正文或授权附件。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard !isLoadingMore, let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .resource(let id): dismiss(animated: true) { [select] in select(id) }
case .more:
isLoadingMore = true
applyRows()
Task { @MainActor [weak self] in
guard let self else { return }
(rows, hasMore) = await loadMore()
isLoadingMore = false
applyRows()
}
}
}
/// 下拉关闭选择器时恢复正文可见性,由课程页面重新核验计时条件。
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { close() }
}