501 lines
23 KiB
Swift
501 lines
23 KiB
Swift
import Foundation
|
|
|
|
/// 正式课程按需读取与有效前台读时;页面在操作完成后主动读取状态并刷新。
|
|
final class TrainingRemoteReadingViewModel {
|
|
/// 当前本人任务标识。
|
|
let taskID: String
|
|
/// 已加载的轻量任务规则与快照引用。
|
|
private(set) var task: TrainingTaskDetail?
|
|
/// 已加载的课程元信息,不包含全部正文。
|
|
private(set) var course: TrainingCourseInfo?
|
|
/// 用户已请求的附件元信息,不包含文件内容。
|
|
private(set) var attachments: [TrainingAttachmentInfo] = []
|
|
/// 当前选中文档,授权或预览失败时仍保留,供用户重试。
|
|
private(set) var currentAttachment: TrainingAttachmentInfo?
|
|
/// 当前文档经任务授权的访问地址,不附带 App Token。
|
|
private(set) var currentAttachmentLink: TrainingAttachmentLink?
|
|
/// 每次选择或重试生成新票据,拒绝同一个附件的旧下载或渲染回调。
|
|
private(set) var attachmentPreviewID: UUID?
|
|
/// 只有当前附件已成功渲染后才可累计有效阅读。
|
|
private(set) var isAttachmentRendered = false
|
|
/// 当前附件授权或预览错误,不被进度刷新清除。
|
|
private(set) var attachmentErrorMessage: String?
|
|
/// 仅用于附件分页的提示,不阻挡当前已经显示的文档或有效阅读。
|
|
private(set) var attachmentListErrorMessage: String?
|
|
/// 最新后端确认的学习进度与资格。
|
|
private(set) var progress: TrainingProgressSnapshot?
|
|
/// 首次加载或切换附件期间阻止重复内容操作。
|
|
private(set) var isLoading = false
|
|
/// 附件目录下一页正在加载。
|
|
private(set) var isLoadingAttachments = false
|
|
/// 附件链接正在授权。
|
|
private(set) var isAuthorizingAttachment = false
|
|
/// 附件目录是否还有用户可主动读取的页面。
|
|
private(set) var hasMoreAttachments = false
|
|
/// 已经读取过附件第一页,避免反复取相同元信息。
|
|
private(set) var hasLoadedAttachments = false
|
|
/// 是否正在累计本次会话的可见读时。
|
|
private(set) var isReading = false
|
|
/// 当前会话本地累计秒数;新会话始终从零开始。
|
|
private(set) var activeSecondsTotal = 0
|
|
/// 最近一次阅读保存失败,可用原请求安全重试。
|
|
private(set) var readingErrorMessage: String?
|
|
/// 会话恢复提示,与当前操作资格分开展示。
|
|
private(set) var readingNotice: String?
|
|
/// 身份已经切换,所有迟到结果都应被丢弃。
|
|
private(set) var isInvalidated = false
|
|
|
|
private let service: any TrainingDataServing
|
|
private let validateIdentity: @MainActor @Sendable () -> Bool
|
|
private let now: @Sendable () -> Date
|
|
private var generation = 0
|
|
private var attachmentCursor: String?
|
|
private var contentErrorMessage: String?
|
|
private var session: TrainingStudySession?
|
|
private var sessionRequestID: String?
|
|
private var acceptedActiveSecondsTotal = 0
|
|
private var nextSequence = 1
|
|
private var pendingHeartbeat: PendingHeartbeat?
|
|
private var finalRequested = false
|
|
private var wantsReading = false
|
|
private var isSessionBusy = false
|
|
private var sessionWaiters: [CheckedContinuation<Void, Never>] = []
|
|
private var readingClock = TrainingReadingClock()
|
|
private var lastVisibleUptime: TimeInterval = 0
|
|
|
|
/// 一次冻结的幂等心跳;重试时序号、累计秒数与 final 均不能变更。
|
|
private struct PendingHeartbeat {
|
|
let sessionID: String
|
|
let sequence: Int
|
|
let activeSecondsTotal: Int
|
|
let final: Bool
|
|
}
|
|
|
|
/// 注入正式数据源、身份校验与时钟,不让 ViewModel 依赖 UIKit 或共享登录视图。
|
|
init(
|
|
taskID: String,
|
|
service: any TrainingDataServing,
|
|
now: @escaping @Sendable () -> Date = { Date() },
|
|
validateIdentity: @escaping @MainActor @Sendable () -> Bool = { true }
|
|
) {
|
|
self.taskID = taskID
|
|
self.service = service
|
|
self.now = now
|
|
self.validateIdentity = validateIdentity
|
|
}
|
|
|
|
/// 页面展示的内容或保存错误,不用中文文案判断恢复分支。
|
|
var errorMessage: String? { readingErrorMessage ?? attachmentErrorMessage ?? contentErrorMessage }
|
|
|
|
/// 当前附件标识,预览失败时用于重试同一份文档。
|
|
var currentAttachmentID: String? { currentAttachment?.id }
|
|
|
|
/// 显示未确认读时的倒计时,但只有服务器确认后才允许开始考试。
|
|
var remainingSeconds: Int {
|
|
guard let progress else { return task?.requiredReadingSeconds ?? 0 }
|
|
let unconfirmed = max(0, activeSecondsTotal - acceptedActiveSecondsTotal)
|
|
return max(0, progress.requiredReadingSeconds - progress.readingSeconds - unconfirmed)
|
|
}
|
|
|
|
/// 当前后端是否允许继续有效学习,完成或只读任务不建立新会话。
|
|
var canStudy: Bool {
|
|
task?.summary.learnerStatus == .pendingExam && progress?.learnerStatus == .pendingExam
|
|
&& progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated
|
|
}
|
|
|
|
/// 上一次请求结束后才允许发送下一次心跳;保存失败交由用户重试。
|
|
var needsReadingFlush: Bool {
|
|
guard !isInvalidated, !isSessionBusy, readingErrorMessage == nil, let session else { return false }
|
|
return finalRequested || activeSecondsTotal - acceptedActiveSecondsTotal >= max(1, session.heartbeatIntervalSeconds)
|
|
}
|
|
|
|
/// 首次只读课程元信息、附件第一页与进度,并为首个附件授权;不请求小节标题或 HTML。
|
|
func load() async {
|
|
guard !isLoading, !isInvalidated else { return }
|
|
let epoch = generation
|
|
isLoading = true
|
|
contentErrorMessage = nil
|
|
attachmentErrorMessage = nil
|
|
attachmentListErrorMessage = nil
|
|
resetAttachmentPreview()
|
|
pauseReading()
|
|
defer { if generation == epoch { isLoading = false } }
|
|
await flush(final: true)
|
|
guard generation == epoch, !isInvalidated, !Task.isCancelled else { return }
|
|
do {
|
|
let detail = try await service.task(id: taskID)
|
|
try await checkIdentity(epoch)
|
|
guard detail.summary.learning.canViewCourse else {
|
|
throw TrainingRemoteError.forbidden("当前任务不能查看课程")
|
|
}
|
|
let courseID = detail.summary.courseSnapshotID
|
|
async let metadata = service.course(id: courseID, taskID: taskID)
|
|
async let documents = service.attachments(courseID: courseID, taskID: taskID, cursor: nil, limit: 20)
|
|
async let savedProgress = service.progress(taskID: taskID)
|
|
let (info, page, saved) = try await (metadata, documents, savedProgress)
|
|
try await checkIdentity(epoch)
|
|
guard saved.canViewCourse else { throw TrainingRemoteError.forbidden("当前任务不能查看课程") }
|
|
task = detail
|
|
course = info
|
|
attachments = page.items
|
|
attachmentCursor = page.nextCursor
|
|
hasMoreAttachments = page.hasMore
|
|
hasLoadedAttachments = true
|
|
progress = saved
|
|
if let first = attachments.first {
|
|
await prepareAttachment(first, epoch: epoch)
|
|
}
|
|
} catch { saveContentError(error, epoch: epoch) }
|
|
}
|
|
|
|
/// 返回已缓存课程时只刷新本人资格与进度,保留文档和预览错误。
|
|
func refreshProgress() async {
|
|
let epoch = generation
|
|
guard !isInvalidated else { return }
|
|
do {
|
|
let value = try await service.progress(taskID: taskID)
|
|
try await checkIdentity(epoch)
|
|
guard value.canViewCourse else { throw TrainingRemoteError.forbidden("当前任务不能查看课程") }
|
|
progress = value
|
|
if !value.canStudy || value.readingCompleted { pauseReading() }
|
|
contentErrorMessage = nil
|
|
} catch { saveContentError(error, epoch: epoch) }
|
|
}
|
|
|
|
/// 选择或重试附件时先关闭旧读时片段,再为选中的文档重新授权。
|
|
func selectAttachment(id: String) async {
|
|
guard !isLoading, !isInvalidated,
|
|
let attachment = attachments.first(where: { $0.id == id }) else { return }
|
|
let epoch = generation
|
|
isLoading = true
|
|
defer { if generation == epoch { isLoading = false } }
|
|
resetAttachmentPreview()
|
|
pauseReading()
|
|
await flush(final: true)
|
|
guard generation == epoch, !isInvalidated, !Task.isCancelled else { return }
|
|
contentErrorMessage = nil
|
|
await prepareAttachment(attachment, epoch: epoch)
|
|
}
|
|
|
|
/// 当前文档真正展示完成才打开读时门禁;过期页面或旧下载回调不能恢复学习。
|
|
@discardableResult
|
|
func markAttachmentRendered(id: String, previewID: UUID) -> Bool {
|
|
guard !isInvalidated, !isLoading, currentAttachmentID == id,
|
|
attachmentPreviewID == previewID, currentAttachmentLink != nil,
|
|
attachmentErrorMessage == nil else { return false }
|
|
isAttachmentRendered = true
|
|
return true
|
|
}
|
|
|
|
/// 文档下载或渲染失败立即停止累计,页面随后通过已有保存管线关闭会话。
|
|
func reportAttachmentFailure(id: String, previewID: UUID, message: String) {
|
|
guard !isInvalidated, currentAttachmentID == id, attachmentPreviewID == previewID else { return }
|
|
isAttachmentRendered = false
|
|
attachmentErrorMessage = message
|
|
pauseReading()
|
|
}
|
|
|
|
/// 后续附件页仅由用户主动读取;已有第一页不重复获取。
|
|
func loadAttachments(loadMore: Bool = false) async {
|
|
guard !isLoading, !isLoadingAttachments, let course, !isInvalidated else { return }
|
|
if hasLoadedAttachments && !loadMore { return }
|
|
if loadMore && (!hasMoreAttachments || attachmentCursor == nil) { return }
|
|
let epoch = generation
|
|
isLoadingAttachments = true
|
|
defer { if generation == epoch { isLoadingAttachments = false } }
|
|
do {
|
|
let page = try await service.attachments(courseID: course.id, taskID: taskID, cursor: loadMore ? attachmentCursor : nil, limit: 20)
|
|
try await checkIdentity(epoch)
|
|
let existing = Set(attachments.map(\.id))
|
|
if !loadMore { attachments = page.items }
|
|
else { attachments.append(contentsOf: page.items.filter { !existing.contains($0.id) }) }
|
|
attachmentCursor = page.nextCursor
|
|
hasMoreAttachments = page.hasMore
|
|
hasLoadedAttachments = true
|
|
attachmentListErrorMessage = nil
|
|
} catch { saveAttachmentListError(error, epoch: epoch) }
|
|
}
|
|
|
|
/// 获取同一附件的有效 HTTP/HTTPS 授权地址,保持签名参数原样,不附 App Token。
|
|
func authorizeAttachment(id: String) async -> TrainingAttachmentLink? {
|
|
guard !isAuthorizingAttachment, let course, !isInvalidated else { return nil }
|
|
let epoch = generation
|
|
isAuthorizingAttachment = true
|
|
defer { if generation == epoch { isAuthorizingAttachment = false } }
|
|
do {
|
|
let link = try await service.attachmentURL(courseID: course.id, attachmentID: id, taskID: taskID)
|
|
try await checkIdentity(epoch)
|
|
let scheme = link.url.scheme?.lowercased()
|
|
guard link.id == id, scheme == "http" || scheme == "https", link.url.host?.isEmpty == false,
|
|
link.url.user == nil, link.url.password == nil, link.expiresAt > now() else {
|
|
throw TrainingRemoteError.paramInvalid("附件访问地址无效或已过期,请重试")
|
|
}
|
|
attachmentErrorMessage = nil
|
|
return link
|
|
} catch { saveAttachmentError(error, epoch: epoch); return nil }
|
|
}
|
|
|
|
private func prepareAttachment(_ attachment: TrainingAttachmentInfo, epoch: Int) async {
|
|
currentAttachment = attachment
|
|
attachmentErrorMessage = nil
|
|
let previewID = UUID()
|
|
attachmentPreviewID = previewID
|
|
let link = await authorizeAttachment(id: attachment.id)
|
|
guard generation == epoch, !isInvalidated, !Task.isCancelled,
|
|
attachmentPreviewID == previewID, currentAttachmentID == attachment.id else { return }
|
|
currentAttachmentLink = link
|
|
}
|
|
|
|
private func resetAttachmentPreview() {
|
|
currentAttachment = nil
|
|
currentAttachmentLink = nil
|
|
attachmentPreviewID = nil
|
|
isAttachmentRendered = false
|
|
attachmentErrorMessage = nil
|
|
}
|
|
|
|
/// 附件已渲染且前台可见时建立或恢复会话;正在阅读时重复调用不重启计时。
|
|
func startReading(at uptime: TimeInterval) async {
|
|
guard isAttachmentRendered, currentAttachmentLink != nil, canStudy else { return }
|
|
lastVisibleUptime = uptime
|
|
guard !isReading else { return }
|
|
let epoch = generation
|
|
wantsReading = true
|
|
await waitForSessionOperation(epoch: epoch)
|
|
guard generation == epoch, !isInvalidated, wantsReading, canStudy, isAttachmentRendered, !isReading else { return }
|
|
isSessionBusy = true
|
|
defer { finishSessionOperation(epoch: epoch) }
|
|
do {
|
|
try await checkIdentity(epoch)
|
|
if pendingHeartbeat != nil || finalRequested {
|
|
try await sendHeartbeats(epoch: epoch)
|
|
}
|
|
if session == nil && canStudy { try await createSession(epoch: epoch) }
|
|
if wantsReading, session != nil, canStudy, isAttachmentRendered {
|
|
readingErrorMessage = nil
|
|
readingClock.resume(at: uptime)
|
|
isReading = true
|
|
} else if session != nil { try await sendHeartbeats(epoch: epoch) }
|
|
} catch { await handleReadingError(error, epoch: epoch) }
|
|
}
|
|
|
|
/// 前台可见时每次最多记一秒;网络心跳进行中仍累计,到门槛时同步停止。
|
|
@discardableResult
|
|
func accumulateVisibleTime(at uptime: TimeInterval) -> Bool {
|
|
lastVisibleUptime = uptime
|
|
guard session != nil, isReading, wantsReading, canStudy, isAttachmentRendered, readingErrorMessage == nil,
|
|
readingClock.takeSecond(at: uptime) else { return false }
|
|
activeSecondsTotal += 1
|
|
if remainingSeconds == 0 { pauseReading() }
|
|
return true
|
|
}
|
|
|
|
/// 累计可见读时并等待本次保存;持续刷新的页面可分别调用累计与保存方法。
|
|
func recordVisibleTime(at uptime: TimeInterval) async {
|
|
accumulateVisibleTime(at: uptime)
|
|
if needsReadingFlush { await flush() }
|
|
}
|
|
|
|
/// 页面隐藏、锁屏、文档切换或预览失败时同步停止计时,丢弃未满一秒片段。
|
|
func pauseReading() {
|
|
wantsReading = false
|
|
finalRequested = true
|
|
isReading = false
|
|
readingClock.pause()
|
|
}
|
|
|
|
/// 保存已累计片段;先重试冻结的旧请求,再用新序号发送最终关闭请求。
|
|
func flush(final: Bool = false) async {
|
|
if final { pauseReading() }
|
|
let epoch = generation
|
|
await waitForSessionOperation(epoch: epoch)
|
|
guard generation == epoch, !isInvalidated, session != nil else { return }
|
|
isSessionBusy = true
|
|
defer { finishSessionOperation(epoch: epoch) }
|
|
do {
|
|
try await checkIdentity(epoch)
|
|
try await sendHeartbeats(epoch: epoch)
|
|
readingErrorMessage = nil
|
|
} catch { await handleReadingError(error, epoch: epoch) }
|
|
}
|
|
|
|
/// 身份切换使所有异步操作失效,清理旧账号内容和未确认片段。
|
|
func invalidate() {
|
|
generation += 1
|
|
isInvalidated = true
|
|
pauseReading()
|
|
clearSession()
|
|
task = nil
|
|
course = nil
|
|
attachments = []
|
|
resetAttachmentPreview()
|
|
attachmentListErrorMessage = nil
|
|
progress = nil
|
|
contentErrorMessage = nil
|
|
readingErrorMessage = nil
|
|
readingNotice = nil
|
|
attachmentCursor = nil
|
|
hasMoreAttachments = false
|
|
hasLoadedAttachments = false
|
|
isLoading = false
|
|
isLoadingAttachments = false
|
|
isAuthorizingAttachment = false
|
|
isSessionBusy = false
|
|
resumeSessionWaiters()
|
|
}
|
|
|
|
private func createSession(epoch: Int) async throws {
|
|
let requestID = sessionRequestID ?? UUID().uuidString
|
|
sessionRequestID = requestID
|
|
let value = try await service.startReading(taskID: taskID, requestID: requestID)
|
|
try await checkIdentity(epoch)
|
|
session = value
|
|
progress = value.progress
|
|
activeSecondsTotal = 0
|
|
acceptedActiveSecondsTotal = 0
|
|
nextSequence = 1
|
|
finalRequested = !wantsReading || !canStudy
|
|
}
|
|
|
|
private func sendHeartbeats(epoch: Int) async throws {
|
|
while let session {
|
|
if pendingHeartbeat == nil {
|
|
guard finalRequested || activeSecondsTotal > acceptedActiveSecondsTotal else { return }
|
|
pendingHeartbeat = PendingHeartbeat(sessionID: session.sessionID, sequence: nextSequence,
|
|
activeSecondsTotal: activeSecondsTotal, final: finalRequested)
|
|
}
|
|
guard let pending = pendingHeartbeat else { return }
|
|
let response = try await service.heartbeat(sessionID: pending.sessionID, sequence: pending.sequence,
|
|
activeSecondsTotal: pending.activeSecondsTotal, final: pending.final)
|
|
try await checkIdentity(epoch)
|
|
guard response.sessionID == pending.sessionID, response.acceptedSequence == pending.sequence,
|
|
response.acceptedActiveSecondsTotal >= acceptedActiveSecondsTotal,
|
|
response.acceptedActiveSecondsTotal <= pending.activeSecondsTotal else {
|
|
throw TrainingRemoteError.sessionConflict("学习上报确认与请求不一致")
|
|
}
|
|
progress = response.progress
|
|
acceptedActiveSecondsTotal = response.acceptedActiveSecondsTotal
|
|
nextSequence = pending.sequence + 1
|
|
pendingHeartbeat = nil
|
|
if response.sessionClosed || pending.final {
|
|
clearSession()
|
|
return
|
|
}
|
|
if response.progress.readingCompleted || !response.progress.canStudy { pauseReading() }
|
|
if !finalRequested { return }
|
|
}
|
|
}
|
|
|
|
private func clearSession() {
|
|
session = nil
|
|
sessionRequestID = nil
|
|
pendingHeartbeat = nil
|
|
activeSecondsTotal = 0
|
|
acceptedActiveSecondsTotal = 0
|
|
nextSequence = 1
|
|
finalRequested = false
|
|
isReading = false
|
|
readingClock.pause()
|
|
}
|
|
|
|
private func waitForSessionOperation(epoch: Int) async {
|
|
while isSessionBusy, generation == epoch, !isInvalidated {
|
|
await withCheckedContinuation { sessionWaiters.append($0) }
|
|
}
|
|
}
|
|
|
|
private func finishSessionOperation(epoch: Int) {
|
|
guard generation == epoch else { return }
|
|
isSessionBusy = false
|
|
resumeSessionWaiters()
|
|
}
|
|
|
|
private func resumeSessionWaiters() {
|
|
let waiters = sessionWaiters
|
|
sessionWaiters = []
|
|
waiters.forEach { $0.resume() }
|
|
}
|
|
|
|
private func checkIdentity(_ epoch: Int) async throws {
|
|
guard generation == epoch, !isInvalidated, !Task.isCancelled else { throw CancellationError() }
|
|
guard await validateIdentity() else {
|
|
invalidate()
|
|
throw TrainingRemoteError.identityChanged
|
|
}
|
|
}
|
|
|
|
private func saveContentError(_ error: Error, epoch: Int) {
|
|
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
|
|
let mapped = TrainingRemoteError.map(error)
|
|
let code = (mapped as? TrainingRemoteError)?.code
|
|
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 {
|
|
invalidate()
|
|
return
|
|
}
|
|
contentErrorMessage = mapped.localizedDescription
|
|
}
|
|
|
|
private func saveAttachmentError(_ error: Error, epoch: Int) {
|
|
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
|
|
let mapped = TrainingRemoteError.map(error)
|
|
let code = (mapped as? TrainingRemoteError)?.code
|
|
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 {
|
|
invalidate()
|
|
return
|
|
}
|
|
attachmentErrorMessage = mapped.localizedDescription
|
|
}
|
|
|
|
private func saveAttachmentListError(_ error: Error, epoch: Int) {
|
|
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
|
|
let mapped = TrainingRemoteError.map(error)
|
|
let code = (mapped as? TrainingRemoteError)?.code
|
|
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 {
|
|
invalidate()
|
|
return
|
|
}
|
|
attachmentListErrorMessage = mapped.localizedDescription
|
|
}
|
|
|
|
private func handleReadingError(_ error: Error, epoch: Int) async {
|
|
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
|
|
let mapped = TrainingRemoteError.map(error)
|
|
let code = (mapped as? TrainingRemoteError)?.code
|
|
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 {
|
|
invalidate()
|
|
return
|
|
}
|
|
isReading = false
|
|
readingClock.pause()
|
|
readingErrorMessage = mapped.localizedDescription
|
|
guard code == 150104 || code == 150105 || code == 150102 else { return }
|
|
do {
|
|
let saved = try await service.progress(taskID: taskID)
|
|
try await checkIdentity(epoch)
|
|
let shouldResume = wantsReading && isAttachmentRendered && code != 150102
|
|
clearSession()
|
|
progress = saved
|
|
wantsReading = shouldResume
|
|
if code == 150104 || code == 150105 {
|
|
readingErrorMessage = nil
|
|
readingNotice = "学习会话已恢复,继续阅读即可"
|
|
}
|
|
if shouldResume, canStudy {
|
|
try await createSession(epoch: epoch)
|
|
if wantsReading, canStudy, isAttachmentRendered {
|
|
readingClock.resume(at: lastVisibleUptime)
|
|
isReading = true
|
|
readingErrorMessage = nil
|
|
readingNotice = "学习会话已恢复,继续阅读即可"
|
|
} else if session != nil { try await sendHeartbeats(epoch: epoch) }
|
|
}
|
|
} catch {
|
|
guard generation == epoch, !isInvalidated else { return }
|
|
let mapped = TrainingRemoteError.map(error)
|
|
let code = (mapped as? TrainingRemoteError)?.code
|
|
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 { invalidate() }
|
|
else { readingErrorMessage = mapped.localizedDescription }
|
|
}
|
|
}
|
|
}
|