feat(training): 接入真实培训接口与学习答题恢复
This commit is contained in:
@@ -0,0 +1,472 @@
|
||||
import Foundation
|
||||
|
||||
/// 分页考试状态;全局已答题号与当前页答案分离,交卷只消费服务端草稿版本。
|
||||
final class TrainingRemoteExamViewModel {
|
||||
/// 固定的本人任务标识。
|
||||
let taskID: String
|
||||
/// 已验证的轻量任务摘要。
|
||||
private(set) var task: TrainingTaskSummary?
|
||||
/// 服务端当前考试资格。
|
||||
private(set) var progress: TrainingProgressSnapshot?
|
||||
/// 冻结试卷规则与总题数。
|
||||
private(set) var paper: TrainingPaperInfo?
|
||||
/// 当前展示题位,使用从零开始的索引。
|
||||
private(set) var currentIndex = 0
|
||||
/// 服务端确认的全部已答题号,题号从一开始。
|
||||
private(set) var answeredQuestionOrders: Set<Int> = []
|
||||
/// 最近确认的草稿版本,未加载前为零。
|
||||
private(set) var draftRevision = 0
|
||||
/// 当前操作期间阻止并发写入。
|
||||
private(set) var isBusy = false
|
||||
/// 最近失败的展示文案,业务分支不依赖文案。
|
||||
private(set) var errorMessage: String?
|
||||
/// 已提交或恢复的成绩,可直接进入成绩页面。
|
||||
private(set) var submittedAttempt: TrainingAttemptSummary?
|
||||
/// 首次交卷返回的成绩及资格,成绩首屏可复用而无需等待额外请求。
|
||||
private(set) var submittedResult: TrainingAttemptDetail?
|
||||
/// 账号不支持培训或任务无访问权限时返回培训中心,身份变化时退出到根页面。
|
||||
private(set) var shouldReturnToCenter = false
|
||||
|
||||
private let pageSize: Int
|
||||
private let pendingStore: TrainingPendingSubmissionStore
|
||||
private let currentContext: @MainActor @Sendable () -> TrainingContext?
|
||||
private var context: TrainingContext?
|
||||
private var questionCache: [Int: TrainingQuestionItem] = [:]
|
||||
private var answerCache: TrainingAnswers = [:]
|
||||
private var loadedDraftIndices: Set<Int> = []
|
||||
private var pendingSubmission: TrainingPendingSubmission?
|
||||
private var pendingMutation: DraftMutation?
|
||||
private var initialResetRequested = false
|
||||
private var needsDraftRefresh = false
|
||||
private var recoveryStorageFailed = false
|
||||
private var identityIsValid = true
|
||||
|
||||
/// 未确认的草稿写入保持原请求 ID、版本和内容,不能被新的选择替换。
|
||||
private enum DraftMutation {
|
||||
case save(TrainingDraftSaveRequest)
|
||||
case reset(TrainingDraftResetRequest)
|
||||
}
|
||||
|
||||
/// 注入身份与持久化域,测试不访问全局登录态或网络。
|
||||
init(taskID: String, context: TrainingContext? = nil, pageSize: Int = 10,
|
||||
pendingStore: TrainingPendingSubmissionStore = TrainingPendingSubmissionStore(),
|
||||
currentContext: @escaping @MainActor @Sendable () -> TrainingContext? = { TrainingPendingSubmissionStore.currentContext() }) {
|
||||
self.taskID = taskID
|
||||
self.context = context
|
||||
self.pageSize = min(20, max(1, pageSize))
|
||||
self.pendingStore = pendingStore
|
||||
self.currentContext = currentContext
|
||||
}
|
||||
|
||||
/// 已知总题数,无需获取全部题目正文。
|
||||
var questionCount: Int { paper?.questionCount ?? 0 }
|
||||
/// 全局已答数量,不把未下载的答案当成漏答。
|
||||
var answeredCount: Int { answeredQuestionOrders.count }
|
||||
/// 当前已加载的题目。
|
||||
var currentQuestion: TrainingQuestionItem? { questionCache[currentIndex] }
|
||||
/// 当前题已确认保存的选择。
|
||||
var currentSelectedIDs: Set<String> { currentQuestion.flatMap { answerCache[$0.id] } ?? [] }
|
||||
/// 第一处真正漏答的题位。
|
||||
var firstUnansweredIndex: Int? {
|
||||
guard questionCount > 0 else { return nil }
|
||||
return (1...questionCount).first { !answeredQuestionOrders.contains($0) }.map { $0 - 1 }
|
||||
}
|
||||
/// 存在未确认交卷时暂停编辑,直到恢复同一次结果。
|
||||
var hasPendingSubmission: Bool { pendingSubmission != nil }
|
||||
/// 页面所属账号、景区或店铺已变化,不能继续显示原身份的数据。
|
||||
var isIdentityInvalid: Bool { !identityIsValid }
|
||||
/// 草稿请求失败后只允许重试原操作。
|
||||
var hasPendingMutation: Bool { pendingMutation != nil }
|
||||
/// 当前题正文和对应草稿范围均成功读取后,才可展示为可编辑答案。
|
||||
var isCurrentPageReady: Bool { currentQuestion != nil && loadedDraftIndices.contains(currentIndex) && !needsDraftRefresh }
|
||||
/// 页读取或冲突后的恢复失败时,沿当前题位重试读取,保留其它页缓存。
|
||||
var canRetryCurrentPage: Bool {
|
||||
!isBusy && identityIsValid && !hasPendingSubmission && !hasPendingMutation && !recoveryStorageFailed
|
||||
&& !shouldReturnToCenter && submittedAttempt == nil && paper != nil && !isCurrentPageReady
|
||||
&& progress?.canStartExam == true && progress?.learnerStatus != .completed
|
||||
}
|
||||
/// 只有权威资格允许且所有写入均确认后才能修改答案。
|
||||
var canEdit: Bool {
|
||||
!isBusy && identityIsValid && !hasPendingSubmission && !hasPendingMutation && !needsDraftRefresh && !recoveryStorageFailed
|
||||
&& submittedAttempt == nil && progress?.canStartExam == true && progress?.learnerStatus != .completed
|
||||
&& !shouldReturnToCenter && paper != nil && isCurrentPageReady
|
||||
}
|
||||
|
||||
/// 返回已提交页面前再次核对身份,避免把缓存成绩显示给切换后的账号。
|
||||
func validateIdentity() async {
|
||||
do { try await authorize() }
|
||||
catch { report(error) }
|
||||
}
|
||||
|
||||
/// 恢复待确认提交优先于考试资格校验;正常加载只取恢复题位所在的一页。
|
||||
func load(service: any TrainingDataServing, resetDraft: Bool = false) async {
|
||||
guard !isBusy else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await authorize()
|
||||
guard let context else { throw TrainingRemoteError.identityChanged }
|
||||
do {
|
||||
pendingSubmission = try pendingStore.load(taskID: taskID, context: context)
|
||||
recoveryStorageFailed = false
|
||||
} catch {
|
||||
recoveryStorageFailed = true
|
||||
throw error
|
||||
}
|
||||
if pendingSubmission != nil {
|
||||
_ = try await recoverSubmission(service: service)
|
||||
return
|
||||
}
|
||||
if pendingMutation != nil {
|
||||
try await performMutation(service: service)
|
||||
return
|
||||
}
|
||||
let detail = try await service.task(id: taskID)
|
||||
try await authorize()
|
||||
let latestProgress = try await service.progress(taskID: taskID)
|
||||
try await authorize()
|
||||
task = detail.summary
|
||||
progress = latestProgress
|
||||
try requireExamAllowed()
|
||||
guard let paperID = task?.paperSnapshotID else { throw TrainingError.invalidPaper }
|
||||
let loadedPaper = try await service.paper(id: paperID, taskID: taskID)
|
||||
try await authorize()
|
||||
guard loadedPaper.id == paperID, (1...500).contains(loadedPaper.questionCount),
|
||||
loadedPaper.scoring == TrainingTask.equalPercentageScoring else { throw TrainingError.invalidPaper }
|
||||
if paper?.id != loadedPaper.id { questionCache = [:]; answerCache = [:]; loadedDraftIndices = [] }
|
||||
paper = loadedPaper
|
||||
let metadata = try await service.draft(taskID: taskID, offset: 0, limit: 0)
|
||||
try await authorize()
|
||||
try applyMetadata(metadata)
|
||||
currentIndex = (1...questionCount).contains(metadata.lastQuestionOrder) ? metadata.lastQuestionOrder - 1 : 0
|
||||
if resetDraft, !initialResetRequested {
|
||||
initialResetRequested = true
|
||||
pendingMutation = .reset(TrainingDraftResetRequest(requestID: UUID().uuidString, paperSnapshotID: paperID, baseRevision: draftRevision))
|
||||
try await performMutation(service: service)
|
||||
} else {
|
||||
try await loadCurrentPage(service: service)
|
||||
}
|
||||
} catch { report(error) }
|
||||
}
|
||||
|
||||
/// 随机跳题直接获取所在页,并保存浏览位置;不遍历前面的题目页。
|
||||
func goToQuestion(_ index: Int, service: any TrainingDataServing) async {
|
||||
guard canEdit, (0..<questionCount).contains(index) else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await authorize()
|
||||
currentIndex = index
|
||||
try await loadCurrentPage(service: service)
|
||||
guard let paper else { throw TrainingError.invalidPaper }
|
||||
pendingMutation = .save(TrainingDraftSaveRequest(requestID: UUID().uuidString, paperSnapshotID: paper.id,
|
||||
baseRevision: draftRevision, lastQuestionOrder: index + 1, changes: []))
|
||||
try await performMutation(service: service)
|
||||
} catch { report(error) }
|
||||
}
|
||||
|
||||
/// 增量保存当前一题,网络结果未知时保留原 ID 和完整请求供重试。
|
||||
func select(optionID: String, service: any TrainingDataServing) async {
|
||||
guard canEdit, let question = currentQuestion, let paper,
|
||||
question.options.contains(where: { $0.id == optionID }) else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await authorize()
|
||||
var selected = currentSelectedIDs
|
||||
if question.type == .single { selected = [optionID] }
|
||||
else if selected.contains(optionID) { selected.remove(optionID) }
|
||||
else { selected.insert(optionID) }
|
||||
pendingMutation = .save(TrainingDraftSaveRequest(requestID: UUID().uuidString, paperSnapshotID: paper.id,
|
||||
baseRevision: draftRevision, lastQuestionOrder: question.order,
|
||||
changes: [TrainingDraftChange(questionID: question.id, selectedOptionIDs: selected.sorted())]))
|
||||
try await performMutation(service: service)
|
||||
} catch { report(error) }
|
||||
}
|
||||
|
||||
/// 沿用失败草稿写入的原请求,不生成新的幂等键。
|
||||
func retryMutation(service: any TrainingDataServing) async {
|
||||
guard !isBusy, pendingMutation != nil, !hasPendingSubmission else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do { try await authorize(); try await performMutation(service: service) }
|
||||
catch { report(error) }
|
||||
}
|
||||
|
||||
/// 仅重读当前未就绪题位;已确认的其它页不会因一次网络失败被清空。
|
||||
func retryCurrentPage(service: any TrainingDataServing) async {
|
||||
guard canRetryCurrentPage else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await authorize()
|
||||
if needsDraftRefresh { try await refreshDraft(service: service) }
|
||||
else { try await loadCurrentPage(service: service) }
|
||||
} catch { report(error) }
|
||||
}
|
||||
|
||||
/// 持久保存交卷请求后提交;未知结果先查原键,再重试原版本。
|
||||
func submit(service: any TrainingDataServing) async -> TrainingAttemptSummary? {
|
||||
guard !isBusy, !hasPendingMutation, !recoveryStorageFailed else { return nil }
|
||||
let wasEditable = canEdit
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await authorize()
|
||||
if pendingSubmission != nil { return try await recoverSubmission(service: service) }
|
||||
guard let context else { throw TrainingRemoteError.identityChanged }
|
||||
if let persisted = try pendingStore.load(taskID: taskID, context: context) {
|
||||
pendingSubmission = persisted
|
||||
return try await recoverSubmission(service: service)
|
||||
}
|
||||
guard wasEditable, firstUnansweredIndex == nil else {
|
||||
errorMessage = "还有 \(questionCount - answeredCount) 道题未作答"
|
||||
return nil
|
||||
}
|
||||
try requireExamAllowed()
|
||||
guard let paper else { throw TrainingError.invalidPaper }
|
||||
let request = TrainingSubmissionRequest(submissionID: UUID().uuidString, paperSnapshotID: paper.id, draftRevision: draftRevision)
|
||||
let pending = TrainingPendingSubmission(taskID: taskID, request: request, context: context)
|
||||
do { try pendingStore.save(pending) }
|
||||
catch TrainingPendingSubmissionError.alreadyPending {
|
||||
pendingSubmission = try pendingStore.load(taskID: taskID, context: context)
|
||||
return try await recoverSubmission(service: service)
|
||||
}
|
||||
pendingSubmission = pending
|
||||
return try await sendSubmission(pending, service: service)
|
||||
} catch { report(error); return nil }
|
||||
}
|
||||
|
||||
private func report(_ error: Error) {
|
||||
errorMessage = error.localizedDescription
|
||||
switch error {
|
||||
case TrainingRemoteError.identityChanged:
|
||||
identityIsValid = false
|
||||
shouldReturnToCenter = true
|
||||
task = nil
|
||||
progress = nil
|
||||
paper = nil
|
||||
questionCache = [:]
|
||||
answerCache = [:]
|
||||
loadedDraftIndices = []
|
||||
answeredQuestionOrders = []
|
||||
draftRevision = 0
|
||||
currentIndex = 0
|
||||
submittedAttempt = nil
|
||||
submittedResult = nil
|
||||
// 保留原身份的未知请求,不能因切换账号而删除或换键重试。
|
||||
case TrainingRemoteError.forbidden, TrainingRemoteError.accountInvalid: shouldReturnToCenter = true
|
||||
default: break
|
||||
}
|
||||
}
|
||||
|
||||
private func authorize() async throws {
|
||||
guard let actual = await currentContext() else { identityIsValid = false; throw TrainingRemoteError.identityChanged }
|
||||
if context == nil { context = actual }
|
||||
guard actual == context else { identityIsValid = false; throw TrainingRemoteError.identityChanged }
|
||||
identityIsValid = true
|
||||
}
|
||||
|
||||
private func requireExamAllowed() throws {
|
||||
guard task?.id == taskID, progress?.taskID == taskID else { throw TrainingError.invalidPaper }
|
||||
guard task?.mode == .exam, task?.learnerStatus != .completed,
|
||||
progress?.learnerStatus != .completed, progress?.completedAt == nil,
|
||||
progress?.canStartExam == true, progress?.readingCompleted == true else {
|
||||
throw TrainingRemoteError.examNotAllowed("当前任务暂不能考试,请返回课程确认学习进度和任务状态")
|
||||
}
|
||||
}
|
||||
|
||||
private func applyMetadata(_ value: TrainingDraftPage) throws {
|
||||
let orders = Set(value.answeredQuestionOrders)
|
||||
guard value.taskID == taskID, value.paperSnapshotID == paper?.id, value.total == questionCount,
|
||||
value.draftRevision > 0, orders.count == value.answeredCount,
|
||||
orders.allSatisfy({ (1...questionCount).contains($0) }) else { throw TrainingError.invalidAnswers }
|
||||
if value.draftRevision != draftRevision { answerCache = [:]; loadedDraftIndices = [] }
|
||||
draftRevision = value.draftRevision
|
||||
answeredQuestionOrders = orders
|
||||
}
|
||||
|
||||
private func loadCurrentPage(service: any TrainingDataServing) async throws {
|
||||
guard let paper else { throw TrainingError.invalidPaper }
|
||||
let offset = currentIndex / pageSize * pageSize
|
||||
if questionCache[currentIndex] == nil {
|
||||
try await fetchQuestions(offset: offset, paperID: paper.id, service: service)
|
||||
// 大小预算允许后端缩短页;远处题号直接请求目标位置,避免遍历此前的页。
|
||||
if questionCache[currentIndex] == nil, currentIndex != offset {
|
||||
try await fetchQuestions(offset: currentIndex, paperID: paper.id, service: service)
|
||||
}
|
||||
guard currentQuestion != nil else { throw TrainingError.invalidPaper }
|
||||
}
|
||||
if !loadedDraftIndices.contains(currentIndex) {
|
||||
try await fetchDraft(offset: offset, service: service)
|
||||
if !loadedDraftIndices.contains(currentIndex), currentIndex != offset {
|
||||
try await fetchDraft(offset: currentIndex, service: service)
|
||||
}
|
||||
guard loadedDraftIndices.contains(currentIndex) else { throw TrainingError.invalidAnswers }
|
||||
}
|
||||
if let question = currentQuestion {
|
||||
let selected = answerCache[question.id] ?? []
|
||||
guard selected.isSubset(of: Set(question.options.map(\.id))),
|
||||
question.type != .single || selected.count <= 1 else { throw TrainingError.invalidAnswers }
|
||||
}
|
||||
needsDraftRefresh = false
|
||||
}
|
||||
|
||||
private func fetchQuestions(offset: Int, paperID: String, service: any TrainingDataServing) async throws {
|
||||
let page = try await service.questions(paperID: paperID, taskID: taskID, offset: offset, limit: pageSize)
|
||||
try await authorize()
|
||||
let end = min(questionCount, offset + pageSize)
|
||||
guard page.paperSnapshotID == paperID, page.total == questionCount, page.offset == offset,
|
||||
!page.items.isEmpty, page.items.count <= end - offset,
|
||||
Set(page.items.map(\.order)).count == page.items.count,
|
||||
Set(page.items.map(\.id)).count == page.items.count else { throw TrainingError.invalidPaper }
|
||||
for question in page.items {
|
||||
guard (offset + 1...end).contains(question.order), !question.id.isEmpty,
|
||||
(2...6).contains(question.options.count), Set(question.options.map(\.id)).count == question.options.count,
|
||||
!questionCache.values.contains(where: { $0.id == question.id && $0.order != question.order }) else {
|
||||
throw TrainingError.invalidPaper
|
||||
}
|
||||
questionCache[question.order - 1] = question
|
||||
}
|
||||
}
|
||||
|
||||
private func fetchDraft(offset: Int, service: any TrainingDataServing) async throws {
|
||||
let page = try await service.draft(taskID: taskID, offset: offset, limit: pageSize)
|
||||
try await authorize()
|
||||
try applyMetadata(page)
|
||||
let requestedEnd = min(questionCount, offset + pageSize)
|
||||
let coveredEnd = page.nextOffset ?? requestedEnd
|
||||
guard page.offset == offset, coveredEnd > offset, coveredEnd <= requestedEnd,
|
||||
Set(page.items.map(\.questionID)).count == page.items.count,
|
||||
Set(page.items.map(\.order)).count == page.items.count else { throw TrainingError.invalidAnswers }
|
||||
for index in offset..<coveredEnd {
|
||||
if let question = questionCache[index] { answerCache[question.id] = [] }
|
||||
}
|
||||
for answer in page.items {
|
||||
guard (offset + 1...coveredEnd).contains(answer.order), !answer.questionID.isEmpty,
|
||||
Set(answer.selectedOptionIDs).count == answer.selectedOptionIDs.count else { throw TrainingError.invalidAnswers }
|
||||
if let question = questionCache[answer.order - 1] {
|
||||
guard question.id == answer.questionID,
|
||||
Set(answer.selectedOptionIDs).isSubset(of: Set(question.options.map(\.id))),
|
||||
question.type != .single || answer.selectedOptionIDs.count <= 1 else { throw TrainingError.invalidAnswers }
|
||||
}
|
||||
answerCache[answer.questionID] = Set(answer.selectedOptionIDs)
|
||||
}
|
||||
loadedDraftIndices.formUnion(offset..<coveredEnd)
|
||||
}
|
||||
|
||||
private func refreshDraft(service: any TrainingDataServing) async throws {
|
||||
needsDraftRefresh = true
|
||||
let metadata = try await service.draft(taskID: taskID, offset: 0, limit: 0)
|
||||
try await authorize()
|
||||
answerCache = [:]
|
||||
loadedDraftIndices = []
|
||||
try applyMetadata(metadata)
|
||||
try await loadCurrentPage(service: service)
|
||||
}
|
||||
|
||||
private func performMutation(service: any TrainingDataServing) async throws {
|
||||
guard let mutation = pendingMutation else { return }
|
||||
do {
|
||||
let confirmation: TrainingDraftConfirmation
|
||||
switch mutation {
|
||||
case .save(let request): confirmation = try await service.saveDraft(taskID: taskID, request: request)
|
||||
case .reset(let request): confirmation = try await service.resetDraft(taskID: taskID, request: request)
|
||||
}
|
||||
try await authorize()
|
||||
guard confirmation.draftRevision >= draftRevision, (0...questionCount).contains(confirmation.answeredCount) else {
|
||||
throw TrainingError.invalidAnswers
|
||||
}
|
||||
pendingMutation = nil
|
||||
draftRevision = confirmation.draftRevision
|
||||
switch mutation {
|
||||
case .reset:
|
||||
// 重置重试返回当前实况,不能根据成功响应把之后的新答案清空。
|
||||
currentIndex = 0
|
||||
try await refreshDraft(service: service)
|
||||
case .save(let request):
|
||||
for change in request.changes {
|
||||
answerCache[change.questionID] = Set(change.selectedOptionIDs)
|
||||
if let question = questionCache.values.first(where: { $0.id == change.questionID }) {
|
||||
if change.selectedOptionIDs.isEmpty { answeredQuestionOrders.remove(question.order) }
|
||||
else { answeredQuestionOrders.insert(question.order) }
|
||||
}
|
||||
}
|
||||
if answeredCount != confirmation.answeredCount { try await refreshDraft(service: service) }
|
||||
}
|
||||
} catch {
|
||||
if case TrainingRemoteError.draftRevisionConflict = error {
|
||||
pendingMutation = nil
|
||||
try? await refreshDraft(service: service)
|
||||
} else if let remote = error as? TrainingRemoteError, remote.code != nil {
|
||||
if case .idempotencyConflict = remote { /* 保留原请求,禁止换键覆盖。 */ }
|
||||
else {
|
||||
pendingMutation = nil
|
||||
if let latest = try? await service.progress(taskID: taskID) {
|
||||
try await authorize()
|
||||
progress = latest
|
||||
} else { progress = nil }
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private func recoverSubmission(service: any TrainingDataServing) async throws -> TrainingAttemptSummary? {
|
||||
guard let pending = pendingSubmission else { return nil }
|
||||
let page = try await service.attempts(taskID: taskID, submissionID: pending.request.submissionID, cursor: nil, limit: 1)
|
||||
try await authorize()
|
||||
guard page.items.count <= 1 else { throw TrainingError.invalidAnswers }
|
||||
if let attempt = page.items.first {
|
||||
return try finishSubmission(pending, attempt: attempt, serverTime: page.serverTime ?? attempt.submittedAt)
|
||||
}
|
||||
return try await sendSubmission(pending, service: service)
|
||||
}
|
||||
|
||||
private func sendSubmission(_ pending: TrainingPendingSubmission, service: any TrainingDataServing) async throws -> TrainingAttemptSummary? {
|
||||
do {
|
||||
let result = try await service.submit(taskID: taskID, request: pending.request)
|
||||
try await authorize()
|
||||
draftRevision = max(draftRevision, result.draftRevision)
|
||||
let attempt = try finishSubmission(pending, attempt: result.attempt, serverTime: result.serverTime)
|
||||
submittedResult = TrainingAttemptDetail(attempt: result.attempt, taskState: result.taskState, serverTime: result.serverTime)
|
||||
return attempt
|
||||
} catch {
|
||||
if let remote = error as? TrainingRemoteError, remote.code != nil {
|
||||
switch remote {
|
||||
case .idempotencyConflict, .forbidden, .accountInvalid:
|
||||
// 权限拒绝无法证明原请求未成功,保留恢复键。
|
||||
break
|
||||
default:
|
||||
try await authorize()
|
||||
try pendingStore.remove(pending)
|
||||
pendingSubmission = nil
|
||||
needsDraftRefresh = true
|
||||
if let latest = try? await service.progress(taskID: taskID) {
|
||||
try await authorize()
|
||||
progress = latest
|
||||
if latest.canStartExam { try? await refreshDraft(service: service) }
|
||||
}
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private func finishSubmission(_ pending: TrainingPendingSubmission, attempt: TrainingAttemptSummary, serverTime: Date) throws -> TrainingAttemptSummary {
|
||||
guard attempt.taskID == taskID, attempt.paperSnapshotID == pending.request.paperSnapshotID else { throw TrainingError.invalidAnswers }
|
||||
try pendingStore.remove(pending)
|
||||
pendingSubmission = nil
|
||||
submittedAttempt = attempt
|
||||
let state = TrainingTaskState(learnerStatus: attempt.passed ? .completed : .pendingExam,
|
||||
completedAt: attempt.passed ? attempt.submittedAt : nil, canRetry: false, blockReason: attempt.passed ? "completed" : nil)
|
||||
submittedResult = TrainingAttemptDetail(attempt: attempt, taskState: state, serverTime: serverTime)
|
||||
return attempt
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import Foundation
|
||||
|
||||
/// 培训列表只保存摘要和服务端游标,不聚合课程、试卷或解析。
|
||||
final class TrainingRemoteCenterViewModel {
|
||||
/// 当前页面入口。
|
||||
var tab: TrainingCenterTab = .home
|
||||
/// 服务端任务状态筛选。
|
||||
var filter: TrainingLearnerStatus = .pendingExam
|
||||
/// 服务端同时搜索任务名和课程名。
|
||||
var keyword = ""
|
||||
/// 当前任务摘要页。
|
||||
private(set) var tasks: [TrainingTaskSummary] = []
|
||||
/// 当前成绩摘要页。
|
||||
private(set) var records: [TrainingAttemptSummary] = []
|
||||
/// 不受分页和关键词影响的概览。
|
||||
private(set) var summary: TrainingSummary?
|
||||
/// 首次加载或刷新状态。
|
||||
private(set) var isLoading = false
|
||||
/// 翻页状态,避免重复消费同一游标。
|
||||
private(set) var isLoadingMore = false
|
||||
/// 最近失败说明。
|
||||
private(set) var errorMessage: String?
|
||||
/// 是否仍有下一页。
|
||||
private(set) var hasMore = false
|
||||
/// 进入时的身份已失效,页面应关闭而不是展示旧作用域统计。
|
||||
private(set) var isIdentityInvalid = false
|
||||
private var nextCursor: String?
|
||||
private var generation = UUID()
|
||||
|
||||
/// 概览中的待完成数量。
|
||||
var pendingCount: Int { summary?.pendingCount ?? 0 }
|
||||
/// 概览中的已完成数量。
|
||||
var completedCount: Int { summary?.completedCount ?? 0 }
|
||||
/// 最近成绩只来自概览接口,不遍历历史。
|
||||
var latestScore: String { summary?.latestAttempt.map { TrainingScore.text($0.scoreHundredths) } ?? "—" }
|
||||
|
||||
/// 切换入口时保留筛选状态,清除搜索和旧游标。
|
||||
func selectTab(_ tab: TrainingCenterTab) {
|
||||
self.tab = tab
|
||||
keyword = ""
|
||||
generation = UUID()
|
||||
nextCursor = nil
|
||||
hasMore = false
|
||||
}
|
||||
|
||||
/// 搜索文本变化立即失效游标与旧请求,网络首屏可以稍后防抖执行。
|
||||
func setKeyword(_ value: String) {
|
||||
keyword = value
|
||||
generation = UUID()
|
||||
nextCursor = nil
|
||||
hasMore = false
|
||||
isLoading = false
|
||||
isLoadingMore = false
|
||||
}
|
||||
|
||||
/// 页面并行读取概览和当前摘要页,保留顶部统计而不遍历其他资源。
|
||||
func load(service: any TrainingDataServing) async {
|
||||
let requestID = UUID()
|
||||
generation = requestID
|
||||
isLoading = true
|
||||
isLoadingMore = false
|
||||
errorMessage = nil
|
||||
hasMore = false
|
||||
nextCursor = nil
|
||||
let requestedTab = tab
|
||||
let requestedFilter = filter
|
||||
let query = keyword.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
defer { if generation == requestID { isLoading = false } }
|
||||
do {
|
||||
async let overview = service.summary()
|
||||
switch requestedTab {
|
||||
case .home:
|
||||
async let page = service.tasks(status: .pendingExam, keyword: "", cursor: nil, limit: 3)
|
||||
let (loadedSummary, loadedPage) = try await (overview, page)
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
summary = loadedSummary
|
||||
tasks = loadedPage.items
|
||||
records = []
|
||||
case .tasks:
|
||||
let page = try await service.tasks(status: requestedFilter, keyword: query, cursor: nil, limit: 20)
|
||||
let loadedSummary = try await overview
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
summary = loadedSummary
|
||||
tasks = page.items
|
||||
records = []
|
||||
nextCursor = page.hasMore ? page.nextCursor : nil
|
||||
hasMore = nextCursor != nil
|
||||
case .records:
|
||||
let page = try await service.attempts(taskID: nil, submissionID: nil, cursor: nil, limit: 20)
|
||||
let loadedSummary = try await overview
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
summary = loadedSummary
|
||||
records = page.items
|
||||
tasks = []
|
||||
nextCursor = page.hasMore ? page.nextCursor : nil
|
||||
hasMore = nextCursor != nil
|
||||
}
|
||||
} catch {
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
tasks = []
|
||||
records = []
|
||||
summary = nil
|
||||
isIdentityInvalid = error as? TrainingRemoteError == .identityChanged
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// 用户主动加载下一页,不提前遍历全部任务或成绩。
|
||||
func loadMore(service: any TrainingDataServing) async {
|
||||
guard !isLoading, !isLoadingMore, let cursor = nextCursor, tab != .home else { return }
|
||||
isLoadingMore = true
|
||||
errorMessage = nil
|
||||
let requestID = generation
|
||||
defer { if generation == requestID { isLoadingMore = false } }
|
||||
do {
|
||||
if tab == .tasks {
|
||||
let page = try await service.tasks(status: filter, keyword: keyword.trimmingCharacters(in: .whitespacesAndNewlines), cursor: cursor, limit: 20)
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
let existing = Set(tasks.map(\.id))
|
||||
tasks += page.items.filter { !existing.contains($0.id) }
|
||||
nextCursor = page.hasMore && page.nextCursor != cursor ? page.nextCursor : nil
|
||||
} else {
|
||||
let page = try await service.attempts(taskID: nil, submissionID: nil, cursor: cursor, limit: 20)
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
let existing = Set(records.map(\.id))
|
||||
records += page.items.filter { !existing.contains($0.id) }
|
||||
nextCursor = page.hasMore && page.nextCursor != cursor ? page.nextCursor : nil
|
||||
}
|
||||
hasMore = nextCursor != nil
|
||||
} catch {
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
if error as? TrainingRemoteError == .identityChanged {
|
||||
tasks = []; records = []; summary = nil; nextCursor = nil; hasMore = false
|
||||
isIdentityInvalid = true
|
||||
}
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 成绩首屏只读单次摘要,解析由展开或翻页动作触发。
|
||||
final class TrainingRemoteResultViewModel {
|
||||
/// 服务端成绩主键。
|
||||
let attemptID: String
|
||||
/// 当前摘要与最新操作资格。
|
||||
private(set) var detail: TrainingAttemptDetail?
|
||||
/// 已按需读取的解析页。
|
||||
private(set) var reviews: [TrainingReviewItem] = []
|
||||
/// 摘要加载状态。
|
||||
private(set) var isLoading = false
|
||||
/// 解析分页状态。
|
||||
private(set) var isLoadingReviews = false
|
||||
/// 是否已成功加载解析首屏。
|
||||
private(set) var hasLoadedReviews = false
|
||||
/// 解析是否仍可继续翻页。
|
||||
private(set) var hasMoreReviews = false
|
||||
/// 摘要失败信息。
|
||||
private(set) var errorMessage: String?
|
||||
/// 解析失败信息,不替换已成功显示的成绩。
|
||||
private(set) var reviewErrorMessage: String?
|
||||
/// 登录身份变化后清空成绩与解析,页面应退出旧身份作用域。
|
||||
private(set) var isIdentityInvalid = false
|
||||
/// 非店铺账号或任务权限撤回时退出该次成绩。
|
||||
private(set) var isAccessRevoked = false
|
||||
private var reviewCursor: String?
|
||||
private var generation = UUID()
|
||||
|
||||
/// 通过成绩 ID 定位,不读取任务的所有历史。
|
||||
init(attemptID: String, initialDetail: TrainingAttemptDetail? = nil) {
|
||||
self.attemptID = attemptID
|
||||
self.detail = initialDetail
|
||||
}
|
||||
|
||||
/// 返回页面时更新操作资格,但保留已读取的冻结解析。
|
||||
func load(service: any TrainingDataServing) async {
|
||||
let requestID = UUID()
|
||||
generation = requestID
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
defer { if generation == requestID { isLoading = false } }
|
||||
do {
|
||||
let loaded = try await service.attempt(id: attemptID)
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
detail = loaded
|
||||
if !loaded.attempt.reviewAvailable {
|
||||
reviews = []
|
||||
hasLoadedReviews = false
|
||||
hasMoreReviews = false
|
||||
reviewCursor = nil
|
||||
reviewErrorMessage = nil
|
||||
}
|
||||
} catch {
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
detail = nil
|
||||
reviews = []
|
||||
hasLoadedReviews = false
|
||||
hasMoreReviews = false
|
||||
isIdentityInvalid = error as? TrainingRemoteError == .identityChanged
|
||||
isAccessRevoked = [150100, 150101].contains((error as? TrainingRemoteError)?.code ?? 0)
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// 初次展开只取第一页,再次展开复用已有解析。
|
||||
func loadReviews(service: any TrainingDataServing, nextPage: Bool = false) async {
|
||||
guard !isLoadingReviews, detail?.attempt.reviewAvailable == true else { return }
|
||||
if nextPage { guard hasMoreReviews, reviewCursor != nil else { return } }
|
||||
else if hasLoadedReviews { return }
|
||||
let cursor = nextPage ? reviewCursor : nil
|
||||
let requestID = generation
|
||||
isLoadingReviews = true
|
||||
reviewErrorMessage = nil
|
||||
defer { isLoadingReviews = false }
|
||||
do {
|
||||
let page = try await service.reviews(attemptID: attemptID, cursor: cursor, limit: 10)
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
let existing = Set(reviews.map(\.id))
|
||||
reviews += page.items.filter { !existing.contains($0.id) }
|
||||
hasLoadedReviews = true
|
||||
reviewCursor = page.hasMore && page.nextCursor != cursor ? page.nextCursor : nil
|
||||
hasMoreReviews = reviewCursor != nil
|
||||
} catch {
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
isAccessRevoked = [150100, 150101].contains((error as? TrainingRemoteError)?.code ?? 0)
|
||||
if error as? TrainingRemoteError == .identityChanged || isAccessRevoked {
|
||||
detail = nil
|
||||
reviews = []
|
||||
hasLoadedReviews = false
|
||||
hasMoreReviews = false
|
||||
reviewCursor = nil
|
||||
isIdentityInvalid = error as? TrainingRemoteError == .identityChanged
|
||||
}
|
||||
reviewErrorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 服务端百分之一分的整数使用最多两位小数展示。
|
||||
enum TrainingScore {
|
||||
/// 不自行判分,只格式化已确认的成绩。
|
||||
static func text(_ hundredths: Int) -> String {
|
||||
let whole = hundredths / 100
|
||||
let fraction = hundredths % 100
|
||||
guard fraction != 0 else { return String(whole) }
|
||||
let digits = String(format: "%02d", fraction)
|
||||
return "\(whole).\(fraction.isMultiple(of: 10) ? String(digits.prefix(1)) : digits)"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,444 @@
|
||||
import Foundation
|
||||
|
||||
/// 正式课程按需读取与有效前台读时;页面在操作完成后主动读取状态并刷新。
|
||||
final class TrainingRemoteReadingViewModel {
|
||||
/// 当前本人任务标识。
|
||||
let taskID: String
|
||||
/// 已加载的轻量任务规则与快照引用。
|
||||
private(set) var task: TrainingTaskDetail?
|
||||
/// 已加载的课程元信息,不包含全部正文。
|
||||
private(set) var course: TrainingCourseInfo?
|
||||
/// 用户已请求的小节目录,首次最多二十项。
|
||||
private(set) var sections: [TrainingSectionInfo] = []
|
||||
/// 当前选择的小节正式正文。
|
||||
private(set) var currentSection: TrainingSectionContent?
|
||||
/// 当前小节标识,正文加载失败时供重试使用。
|
||||
private(set) var currentSectionID: String?
|
||||
/// 用户已请求的附件元信息,不包含文件内容。
|
||||
private(set) var attachments: [TrainingAttachmentInfo] = []
|
||||
/// 最新后端确认的学习进度与资格。
|
||||
private(set) var progress: TrainingProgressSnapshot?
|
||||
/// 首次加载或切换正文期间阻止重复内容操作。
|
||||
private(set) var isLoading = false
|
||||
/// 小节目录下一页正在加载。
|
||||
private(set) var isLoadingSections = false
|
||||
/// 附件目录下一页正在加载。
|
||||
private(set) var isLoadingAttachments = false
|
||||
/// 附件链接正在授权。
|
||||
private(set) var isAuthorizingAttachment = false
|
||||
/// 小节目录是否还有用户可主动读取的页面。
|
||||
private(set) var hasMoreSections = 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 sectionCursor: String?
|
||||
private var attachmentCursor: String?
|
||||
private var bodies: [String: TrainingSectionContent] = [:]
|
||||
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 ?? contentErrorMessage }
|
||||
|
||||
/// 显示未确认读时的倒计时,但只有服务器确认后才允许开始考试。
|
||||
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 { progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated }
|
||||
|
||||
/// 首次只取元信息、目录第一页、首节正文和小型进度,不预取附件或其他小节正文。
|
||||
func load() async {
|
||||
guard !isLoading, !isInvalidated else { return }
|
||||
let epoch = generation
|
||||
isLoading = true
|
||||
contentErrorMessage = nil
|
||||
defer { if generation == epoch { isLoading = false } }
|
||||
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 directory = service.sections(courseID: courseID, taskID: taskID, cursor: nil, limit: 20)
|
||||
async let savedProgress = service.progress(taskID: taskID)
|
||||
let (info, page, saved) = try await (metadata, directory, savedProgress)
|
||||
try await checkIdentity(epoch)
|
||||
guard let first = page.items.first else { throw TrainingRemoteError.contentMissing("暂无课程内容") }
|
||||
let body = try await service.section(courseID: courseID, sectionID: first.id, taskID: taskID)
|
||||
try await checkIdentity(epoch)
|
||||
task = detail
|
||||
course = info
|
||||
sections = page.items
|
||||
sectionCursor = page.nextCursor
|
||||
hasMoreSections = page.hasMore
|
||||
currentSectionID = first.id
|
||||
currentSection = body
|
||||
bodies[body.id] = body
|
||||
progress = saved
|
||||
} 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)
|
||||
progress = value
|
||||
if !value.canStudy || value.readingCompleted { pauseReading() }
|
||||
contentErrorMessage = nil
|
||||
} catch { saveContentError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 切章节立即暂停;只读取选中正文,已经看过的同快照正文直接复用。
|
||||
func selectSection(id: String) async {
|
||||
guard !isLoading, !isInvalidated, let course else { return }
|
||||
let epoch = generation
|
||||
isLoading = true
|
||||
defer { if generation == epoch { isLoading = false } }
|
||||
pauseReading()
|
||||
await flush(final: true)
|
||||
guard generation == epoch, !isInvalidated, !Task.isCancelled else { return }
|
||||
contentErrorMessage = nil
|
||||
currentSectionID = id
|
||||
currentSection = nil
|
||||
do {
|
||||
let body: TrainingSectionContent
|
||||
if let cached = bodies[id] { body = cached }
|
||||
else { body = try await service.section(courseID: course.id, sectionID: id, taskID: taskID) }
|
||||
try await checkIdentity(epoch)
|
||||
currentSection = body
|
||||
bodies[id] = body
|
||||
} catch { saveContentError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 仅用户点击加载更多时读取目录下一页,不为展示一个小节遍历全部目录。
|
||||
func loadMoreSections() async {
|
||||
guard !isLoadingSections, hasMoreSections, let cursor = sectionCursor, let course, !isInvalidated else { return }
|
||||
let epoch = generation
|
||||
isLoadingSections = true
|
||||
defer { if generation == epoch { isLoadingSections = false } }
|
||||
do {
|
||||
let page = try await service.sections(courseID: course.id, taskID: taskID, cursor: cursor, limit: 20)
|
||||
try await checkIdentity(epoch)
|
||||
let existing = Set(sections.map(\.id))
|
||||
sections.append(contentsOf: page.items.filter { !existing.contains($0.id) })
|
||||
sectionCursor = page.nextCursor
|
||||
hasMoreSections = page.hasMore
|
||||
contentErrorMessage = nil
|
||||
} catch { saveContentError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 首次打开附件目录才读取第一页;后续页也由用户主动请求。
|
||||
func loadAttachments(loadMore: Bool = false) async {
|
||||
guard !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
|
||||
contentErrorMessage = nil
|
||||
} catch { saveContentError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 点击附件时取得可直接交给系统浏览器的有效 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)
|
||||
guard link.url.scheme?.lowercased() == "https", link.url.host != nil, link.expiresAt > now() else {
|
||||
throw TrainingRemoteError.paramInvalid("附件访问地址无效或已过期,请重试")
|
||||
}
|
||||
contentErrorMessage = nil
|
||||
return link
|
||||
} catch { saveContentError(error, epoch: epoch); return nil }
|
||||
}
|
||||
|
||||
/// 正文已经在前台可见时建立或恢复会话;创建丢响应时沿用原 requestID。
|
||||
func startReading(at uptime: TimeInterval) async {
|
||||
guard currentSection != nil, canStudy else { return }
|
||||
let epoch = generation
|
||||
wantsReading = true
|
||||
lastVisibleUptime = uptime
|
||||
await waitForSessionOperation(epoch: epoch)
|
||||
guard generation == epoch, !isInvalidated, wantsReading, canStudy, currentSection != nil 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 {
|
||||
readingErrorMessage = nil
|
||||
readingClock.resume(at: uptime)
|
||||
isReading = true
|
||||
} else if session != nil { try await sendHeartbeats(epoch: epoch) }
|
||||
} catch { await handleReadingError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 由前台定时器驱动,每次最多记一秒;到间隔或门槛才发送网络心跳。
|
||||
func recordVisibleTime(at uptime: TimeInterval) async {
|
||||
lastVisibleUptime = uptime
|
||||
guard isReading, wantsReading, canStudy, !isSessionBusy, pendingHeartbeat == nil,
|
||||
readingClock.takeSecond(at: uptime) else { return }
|
||||
activeSecondsTotal += 1
|
||||
let interval = max(1, session?.heartbeatIntervalSeconds ?? 5)
|
||||
if activeSecondsTotal - acceptedActiveSecondsTotal >= interval || remainingSeconds == 0 {
|
||||
await flush(final: remainingSeconds == 0)
|
||||
}
|
||||
}
|
||||
|
||||
/// 页面隐藏、锁屏、正文切换或附件打开时同步停止计时,丢弃未满一秒片段。
|
||||
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
|
||||
sections = []
|
||||
currentSection = nil
|
||||
currentSectionID = nil
|
||||
attachments = []
|
||||
bodies = [:]
|
||||
progress = nil
|
||||
contentErrorMessage = nil
|
||||
readingErrorMessage = nil
|
||||
readingNotice = nil
|
||||
sectionCursor = nil
|
||||
attachmentCursor = nil
|
||||
hasMoreSections = false
|
||||
hasMoreAttachments = false
|
||||
hasLoadedAttachments = false
|
||||
isLoading = false
|
||||
isLoadingSections = 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 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 && 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 {
|
||||
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 }
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user