feat(training): 接入真实培训接口与学习答题恢复
This commit is contained in:
@@ -0,0 +1,720 @@
|
||||
import Foundation
|
||||
|
||||
/// 培训契约日期解析;独立于全局网络解码器,兼容 RFC3339 的小数秒。
|
||||
enum TrainingAPIDateCodec {
|
||||
/// 解析带时区的 RFC3339 日期,拒绝无时区字符串。
|
||||
static func decode(_ value: String) -> Date? {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
||||
if let date = formatter.date(from: value) { return date }
|
||||
formatter.formatOptions = [.withInternetDateTime]
|
||||
return formatter.date(from: value)
|
||||
}
|
||||
|
||||
/// 按 RFC3339 编码日期,供测试和持久化使用。
|
||||
static func encode(_ date: Date) -> String {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
||||
return formatter.string(from: date)
|
||||
}
|
||||
}
|
||||
|
||||
/// 必填 RFC3339 日期,业务属性直接读写 Date。
|
||||
@propertyWrapper
|
||||
struct TrainingAPIDate: Codable, Equatable, Sendable {
|
||||
var wrappedValue: Date
|
||||
/// 从业务日期创建包装,保留 DTO 的普通成员初始化方式。
|
||||
init(wrappedValue: Date) { self.wrappedValue = wrappedValue }
|
||||
/// 从契约字符串解码,格式错误不转换为虚假时间。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
let raw = try container.decode(String.self)
|
||||
guard let value = TrainingAPIDateCodec.decode(raw) else {
|
||||
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid RFC3339 training date")
|
||||
}
|
||||
wrappedValue = value
|
||||
}
|
||||
/// 编码为带时区字符串。
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(TrainingAPIDateCodec.encode(wrappedValue))
|
||||
}
|
||||
}
|
||||
|
||||
/// 可空 RFC3339 日期;无有效期边界保持 nil,不使用本机时间代替。
|
||||
@propertyWrapper
|
||||
struct TrainingAPIOptionalDate: Codable, Equatable, Sendable {
|
||||
var wrappedValue: Date?
|
||||
/// 从可空业务日期创建包装。
|
||||
init(wrappedValue: Date?) { self.wrappedValue = wrappedValue }
|
||||
/// 解码 null 或 RFC3339 字符串。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
if container.decodeNil() { wrappedValue = nil; return }
|
||||
let raw = try container.decode(String.self)
|
||||
guard let value = TrainingAPIDateCodec.decode(raw) else {
|
||||
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid RFC3339 training date")
|
||||
}
|
||||
wrappedValue = value
|
||||
}
|
||||
/// 编码可空日期。
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
if let value = wrappedValue { try container.encode(TrainingAPIDateCodec.encode(value)) }
|
||||
else { try container.encodeNil() }
|
||||
}
|
||||
}
|
||||
|
||||
extension KeyedDecodingContainer {
|
||||
/// 可选日期允许省略字段;分页的 server_time 并非每个资源都会返回。
|
||||
func decode(_ type: TrainingAPIOptionalDate.Type, forKey key: Key) throws -> TrainingAPIOptionalDate {
|
||||
try decodeIfPresent(type, forKey: key) ?? TrainingAPIOptionalDate(wrappedValue: nil)
|
||||
}
|
||||
}
|
||||
|
||||
extension TrainingLearnerStatus: Codable {
|
||||
/// 将正式接口 pending 映射到页面已有的待考试状态。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
switch try container.decode(String.self) {
|
||||
case "pending": self = .pendingExam
|
||||
case "completed": self = .completed
|
||||
default: throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unknown training learner status")
|
||||
}
|
||||
}
|
||||
/// 输出正式接口状态,不使用本地 enum 的 pendingExam 字符串。
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(apiValue)
|
||||
}
|
||||
/// 查询参数使用的正式状态值。
|
||||
var apiValue: String { self == .completed ? "completed" : "pending" }
|
||||
}
|
||||
|
||||
/// 游标分页;小节、附件、任务和成绩复用相同分页边界。
|
||||
struct TrainingCursorPage<Item: Codable & Equatable & Sendable>: Codable, Equatable, Sendable {
|
||||
let items: [Item]
|
||||
let nextCursor: String?
|
||||
let hasMore: Bool
|
||||
@TrainingAPIOptionalDate var serverTime: Date?
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case items
|
||||
case nextCursor = "next_cursor"
|
||||
case hasMore = "has_more"
|
||||
case serverTime = "server_time"
|
||||
}
|
||||
}
|
||||
|
||||
/// 概览最近成绩,只有首屏所需字段。
|
||||
struct TrainingLatestAttempt: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let scoreHundredths: Int
|
||||
@TrainingAPIDate var submittedAt: Date
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "attempt_id"
|
||||
case scoreHundredths = "score_hundredths"
|
||||
case submittedAt = "submitted_at"
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前学员全部分配任务的概览统计。
|
||||
struct TrainingSummary: Codable, Equatable, Sendable {
|
||||
let pendingCount: Int
|
||||
let completedCount: Int
|
||||
let latestAttempt: TrainingLatestAttempt?
|
||||
@TrainingAPIDate var serverTime: Date
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case pendingCount = "pending_count"
|
||||
case completedCount = "completed_count"
|
||||
case latestAttempt = "latest_attempt"
|
||||
case serverTime = "server_time"
|
||||
}
|
||||
}
|
||||
|
||||
/// 任务列表中的本人阅读与操作资格,不包含草稿或成绩数组。
|
||||
struct TrainingLearningFlags: Codable, Equatable, Sendable {
|
||||
let progressPercent: Int
|
||||
let readingCompleted: Bool
|
||||
let hasDraft: Bool
|
||||
let canViewCourse: Bool
|
||||
let canStudy: Bool
|
||||
let canStartExam: Bool
|
||||
let blockReason: String?
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case progressPercent = "progress_percent"
|
||||
case readingCompleted = "reading_completed"
|
||||
case hasDraft = "has_draft"
|
||||
case canViewCourse = "can_view_course"
|
||||
case canStudy = "can_study"
|
||||
case canStartExam = "can_start_exam"
|
||||
case blockReason = "block_reason"
|
||||
}
|
||||
}
|
||||
|
||||
/// 任务摘要与快照引用;课程正文和试卷独立按需读取。
|
||||
struct TrainingTaskSummary: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let title: String
|
||||
let publisherName: String?
|
||||
let mode: TrainingMode
|
||||
let taskStatus: TrainingTaskStatus
|
||||
let learnerStatus: TrainingLearnerStatus
|
||||
@TrainingAPIOptionalDate var startAt: Date?
|
||||
@TrainingAPIOptionalDate var endAt: Date?
|
||||
let courseSnapshotID: String
|
||||
let courseTitle: String
|
||||
let paperSnapshotID: String?
|
||||
let sectionCount: Int
|
||||
let questionCount: Int
|
||||
let passScore: Int?
|
||||
let learning: TrainingLearningFlags
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "task_id"
|
||||
case title
|
||||
case publisherName = "publisher_name"
|
||||
case mode
|
||||
case taskStatus = "task_status"
|
||||
case learnerStatus = "learner_status"
|
||||
case startAt = "start_at"
|
||||
case endAt = "end_at"
|
||||
case courseSnapshotID = "course_snapshot_id"
|
||||
case courseTitle = "course_title"
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case sectionCount = "section_count"
|
||||
case questionCount = "question_count"
|
||||
case passScore = "pass_score"
|
||||
case learning
|
||||
}
|
||||
}
|
||||
|
||||
/// 平铺任务详情,客户端以 summary 复用列表摘要。
|
||||
struct TrainingTaskDetail: Codable, Equatable, Sendable {
|
||||
let summary: TrainingTaskSummary
|
||||
let requiredReadingSeconds: Int
|
||||
let readingRule: String
|
||||
let scoring: String?
|
||||
let serverTime: Date
|
||||
|
||||
/// 使用已解码摘要和规则创建详情,便于纯逻辑测试。
|
||||
init(summary: TrainingTaskSummary, requiredReadingSeconds: Int, readingRule: String, scoring: String?, serverTime: Date) {
|
||||
self.summary = summary
|
||||
self.requiredReadingSeconds = requiredReadingSeconds
|
||||
self.readingRule = readingRule
|
||||
self.scoring = scoring
|
||||
self.serverTime = serverTime
|
||||
}
|
||||
/// 从与摘要同一层的详情字段解码,避免要求不存在的 summary 对象。
|
||||
init(from decoder: Decoder) throws {
|
||||
summary = try TrainingTaskSummary(from: decoder)
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
requiredReadingSeconds = try container.decode(Int.self, forKey: .requiredReadingSeconds)
|
||||
readingRule = try container.decode(String.self, forKey: .readingRule)
|
||||
scoring = try container.decodeIfPresent(String.self, forKey: .scoring)
|
||||
serverTime = try container.decode(TrainingAPIDate.self, forKey: .serverTime).wrappedValue
|
||||
}
|
||||
/// 保持服务端平铺字段布局。
|
||||
func encode(to encoder: Encoder) throws {
|
||||
try summary.encode(to: encoder)
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(requiredReadingSeconds, forKey: .requiredReadingSeconds)
|
||||
try container.encode(readingRule, forKey: .readingRule)
|
||||
try container.encodeIfPresent(scoring, forKey: .scoring)
|
||||
try container.encode(TrainingAPIDate(wrappedValue: serverTime), forKey: .serverTime)
|
||||
}
|
||||
/// 详情额外字段的契约映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case requiredReadingSeconds = "required_reading_seconds"
|
||||
case readingRule = "reading_rule"
|
||||
case scoring
|
||||
case serverTime = "server_time"
|
||||
}
|
||||
}
|
||||
|
||||
/// 课程快照元信息,不含小节正文。
|
||||
struct TrainingCourseInfo: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let title: String
|
||||
let introduction: String
|
||||
let sectionCount: Int
|
||||
let attachmentCount: Int
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "course_snapshot_id"
|
||||
case title
|
||||
case introduction
|
||||
case sectionCount = "section_count"
|
||||
case attachmentCount = "attachment_count"
|
||||
}
|
||||
}
|
||||
|
||||
/// 冻结的小节目录项,序号从一开始。
|
||||
struct TrainingSectionInfo: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let order: Int
|
||||
let title: String
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "section_id"
|
||||
case order
|
||||
case title
|
||||
}
|
||||
}
|
||||
|
||||
/// 单节正式正文;HTML 按后端发布快照读取。
|
||||
struct TrainingSectionContent: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let order: Int
|
||||
let title: String
|
||||
let contentHTML: String
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "section_id"
|
||||
case order
|
||||
case title
|
||||
case contentHTML = "content_html"
|
||||
}
|
||||
}
|
||||
|
||||
/// 附件元信息,私有附件访问前单独申请授权链接。
|
||||
struct TrainingAttachmentInfo: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let name: String
|
||||
let mimeType: String
|
||||
let sizeBytes: Int
|
||||
let fileID: String
|
||||
let downloadURL: URL?
|
||||
@TrainingAPIOptionalDate var expiresAt: Date?
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "attachment_id"
|
||||
case name
|
||||
case mimeType = "mime_type"
|
||||
case sizeBytes = "size_bytes"
|
||||
case fileID = "file_id"
|
||||
case downloadURL = "download_url"
|
||||
case expiresAt = "expires_at"
|
||||
}
|
||||
}
|
||||
|
||||
/// 经当前任务授权的短期附件访问链接。
|
||||
struct TrainingAttachmentLink: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let name: String
|
||||
let url: URL
|
||||
@TrainingAPIDate var expiresAt: Date
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "attachment_id"
|
||||
case name
|
||||
case url
|
||||
case expiresAt = "expires_at"
|
||||
}
|
||||
}
|
||||
|
||||
/// 服务端权威进度与当前资格;不含课程、草稿答案或历史成绩。
|
||||
struct TrainingProgressSnapshot: Codable, Equatable, Sendable {
|
||||
let taskID: String
|
||||
let readingSeconds: Int
|
||||
let requiredReadingSeconds: Int
|
||||
let completedSectionCount: Int
|
||||
let sectionCount: Int
|
||||
let progressPercent: Int
|
||||
let readingCompleted: Bool
|
||||
let learnerStatus: TrainingLearnerStatus
|
||||
@TrainingAPIOptionalDate var completedAt: Date?
|
||||
let hasDraft: Bool
|
||||
let canViewCourse: Bool
|
||||
let canStudy: Bool
|
||||
let canStartExam: Bool
|
||||
let canRetry: Bool
|
||||
let blockReason: String?
|
||||
@TrainingAPIDate var serverTime: Date
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case taskID = "task_id"
|
||||
case readingSeconds = "reading_seconds"
|
||||
case requiredReadingSeconds = "required_reading_seconds"
|
||||
case completedSectionCount = "completed_section_count"
|
||||
case sectionCount = "section_count"
|
||||
case progressPercent = "progress_percent"
|
||||
case readingCompleted = "reading_completed"
|
||||
case learnerStatus = "learner_status"
|
||||
case completedAt = "completed_at"
|
||||
case hasDraft = "has_draft"
|
||||
case canViewCourse = "can_view_course"
|
||||
case canStudy = "can_study"
|
||||
case canStartExam = "can_start_exam"
|
||||
case canRetry = "can_retry"
|
||||
case blockReason = "block_reason"
|
||||
case serverTime = "server_time"
|
||||
}
|
||||
}
|
||||
|
||||
/// 阅读会话、上报规则及创建时已保存进度。
|
||||
struct TrainingStudySession: Codable, Equatable, Sendable {
|
||||
let sessionID: String
|
||||
@TrainingAPIDate var expiresAt: Date
|
||||
let heartbeatIntervalSeconds: Int
|
||||
let maxHeartbeatGapSeconds: Int
|
||||
let progress: TrainingProgressSnapshot
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case sessionID = "session_id"
|
||||
case expiresAt = "expires_at"
|
||||
case heartbeatIntervalSeconds = "heartbeat_interval_seconds"
|
||||
case maxHeartbeatGapSeconds = "max_heartbeat_gap_seconds"
|
||||
case progress
|
||||
}
|
||||
}
|
||||
|
||||
/// 幂等阅读上报确认;累计秒数只用于当前会话。
|
||||
struct TrainingHeartbeatConfirmation: Codable, Equatable, Sendable {
|
||||
let sessionID: String
|
||||
let acceptedSequence: Int
|
||||
let acceptedActiveSecondsTotal: Int
|
||||
let sessionClosed: Bool
|
||||
let progress: TrainingProgressSnapshot
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case sessionID = "session_id"
|
||||
case acceptedSequence = "accepted_sequence"
|
||||
case acceptedActiveSecondsTotal = "accepted_active_seconds_total"
|
||||
case sessionClosed = "session_closed"
|
||||
case progress
|
||||
}
|
||||
}
|
||||
|
||||
/// 冻结试卷规则与题数,不携带全卷或正确答案。
|
||||
struct TrainingPaperInfo: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let scoring: String
|
||||
let questionCount: Int
|
||||
let maxOptionsPerQuestion: Int
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "paper_snapshot_id"
|
||||
case scoring
|
||||
case questionCount = "question_count"
|
||||
case maxOptionsPerQuestion = "max_options_per_question"
|
||||
}
|
||||
}
|
||||
|
||||
/// 考前选项,不透明 ID 按原值提交。
|
||||
struct TrainingQuestionOption: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let text: String
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "option_id"
|
||||
case text
|
||||
}
|
||||
}
|
||||
|
||||
/// 一题考前快照,不包含答案和解析。
|
||||
struct TrainingQuestionItem: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let order: Int
|
||||
let type: TrainingQuestionType
|
||||
let stem: String
|
||||
let options: [TrainingQuestionOption]
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "question_id"
|
||||
case order
|
||||
case type
|
||||
case stem
|
||||
case options
|
||||
}
|
||||
}
|
||||
|
||||
/// 按冻结题位随机访问的试题页。
|
||||
struct TrainingQuestionPage: Codable, Equatable, Sendable {
|
||||
let paperSnapshotID: String
|
||||
let total: Int
|
||||
let offset: Int
|
||||
let nextOffset: Int?
|
||||
let hasMore: Bool
|
||||
let items: [TrainingQuestionItem]
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case total
|
||||
case offset
|
||||
case nextOffset = "next_offset"
|
||||
case hasMore = "has_more"
|
||||
case items
|
||||
}
|
||||
}
|
||||
|
||||
/// 固定题位范围内已保存的本人选择。
|
||||
struct TrainingDraftAnswerItem: Codable, Equatable, Sendable {
|
||||
let questionID: String
|
||||
let order: Int
|
||||
let selectedOptionIDs: [String]
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case questionID = "question_id"
|
||||
case order
|
||||
case selectedOptionIDs = "selected_option_ids"
|
||||
}
|
||||
}
|
||||
|
||||
/// 草稿版本、恢复位置、全部已答题号及当前题位答案页。
|
||||
struct TrainingDraftPage: Codable, Equatable, Sendable {
|
||||
let taskID: String
|
||||
let paperSnapshotID: String
|
||||
let draftRevision: Int
|
||||
@TrainingAPIOptionalDate var savedAt: Date?
|
||||
let lastQuestionOrder: Int
|
||||
let answeredCount: Int
|
||||
let answeredQuestionOrders: [Int]
|
||||
let total: Int
|
||||
let offset: Int
|
||||
let nextOffset: Int?
|
||||
let hasMore: Bool
|
||||
let items: [TrainingDraftAnswerItem]
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case taskID = "task_id"
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case draftRevision = "draft_revision"
|
||||
case savedAt = "saved_at"
|
||||
case lastQuestionOrder = "last_question_order"
|
||||
case answeredCount = "answered_count"
|
||||
case answeredQuestionOrders = "answered_question_orders"
|
||||
case total
|
||||
case offset
|
||||
case nextOffset = "next_offset"
|
||||
case hasMore = "has_more"
|
||||
case items
|
||||
}
|
||||
}
|
||||
|
||||
/// 增量保存中一题的完整选择集合,空数组取消该题作答。
|
||||
struct TrainingDraftChange: Codable, Equatable, Sendable {
|
||||
let questionID: String
|
||||
let selectedOptionIDs: [String]
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case questionID = "question_id"
|
||||
case selectedOptionIDs = "selected_option_ids"
|
||||
}
|
||||
}
|
||||
|
||||
/// 带乐观版本与幂等键的增量草稿请求。
|
||||
struct TrainingDraftSaveRequest: Codable, Equatable, Sendable {
|
||||
let requestID: String
|
||||
let paperSnapshotID: String
|
||||
let baseRevision: Int
|
||||
let lastQuestionOrder: Int?
|
||||
let changes: [TrainingDraftChange]
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case requestID = "request_id"
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case baseRevision = "base_revision"
|
||||
case lastQuestionOrder = "last_question_order"
|
||||
case changes
|
||||
}
|
||||
}
|
||||
|
||||
/// 用户明确重考时请求重置;重试沿用同一 requestID。
|
||||
struct TrainingDraftResetRequest: Codable, Equatable, Sendable {
|
||||
let requestID: String
|
||||
let paperSnapshotID: String
|
||||
let baseRevision: Int
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case requestID = "request_id"
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case baseRevision = "base_revision"
|
||||
}
|
||||
}
|
||||
|
||||
/// 保存或重置后草稿实况;重置重试不能据此盲清本地答案。
|
||||
struct TrainingDraftConfirmation: Codable, Equatable, Sendable {
|
||||
let draftRevision: Int
|
||||
@TrainingAPIDate var savedAt: Date
|
||||
let answeredCount: Int
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case draftRevision = "draft_revision"
|
||||
case savedAt = "saved_at"
|
||||
case answeredCount = "answered_count"
|
||||
}
|
||||
}
|
||||
|
||||
/// 消费服务端已保存草稿版本的幂等交卷请求,不重新上传答案。
|
||||
struct TrainingSubmissionRequest: Codable, Equatable, Sendable {
|
||||
let submissionID: String
|
||||
let paperSnapshotID: String
|
||||
let draftRevision: Int
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case submissionID = "submission_id"
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case draftRevision = "draft_revision"
|
||||
}
|
||||
}
|
||||
|
||||
/// 冻结成绩摘要;解析独立读取,资格由最新任务状态决定。
|
||||
struct TrainingAttemptSummary: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let taskID: String
|
||||
let taskTitle: String
|
||||
let courseSnapshotID: String
|
||||
let courseTitle: String
|
||||
let paperSnapshotID: String
|
||||
@TrainingAPIDate var submittedAt: Date
|
||||
let scoreHundredths: Int
|
||||
let correctCount: Int
|
||||
let questionCount: Int
|
||||
let passScore: Int
|
||||
let passed: Bool
|
||||
let reviewAvailable: Bool
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "attempt_id"
|
||||
case taskID = "task_id"
|
||||
case taskTitle = "task_title"
|
||||
case courseSnapshotID = "course_snapshot_id"
|
||||
case courseTitle = "course_title"
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case submittedAt = "submitted_at"
|
||||
case scoreHundredths = "score_hundredths"
|
||||
case correctCount = "correct_count"
|
||||
case questionCount = "question_count"
|
||||
case passScore = "pass_score"
|
||||
case passed
|
||||
case reviewAvailable = "review_available"
|
||||
}
|
||||
}
|
||||
|
||||
extension TrainingAttemptSummary {
|
||||
/// 百分之一分整数转为最多两位小数的展示分数,不改变通过判断。
|
||||
var scoreText: String {
|
||||
let whole = scoreHundredths / 100
|
||||
let fraction = scoreHundredths % 100
|
||||
if fraction == 0 { return String(whole) }
|
||||
let digits = String(format: "%02d", fraction)
|
||||
return "\(whole).\(fraction.isMultiple(of: 10) ? String(digits.prefix(1)) : digits)"
|
||||
}
|
||||
}
|
||||
|
||||
/// 成绩页面使用的最新本人任务操作资格。
|
||||
struct TrainingTaskState: Codable, Equatable, Sendable {
|
||||
let learnerStatus: TrainingLearnerStatus
|
||||
@TrainingAPIOptionalDate var completedAt: Date?
|
||||
let canRetry: Bool
|
||||
let blockReason: String?
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case learnerStatus = "learner_status"
|
||||
case completedAt = "completed_at"
|
||||
case canRetry = "can_retry"
|
||||
case blockReason = "block_reason"
|
||||
}
|
||||
}
|
||||
|
||||
/// 单次历史成绩与最新重考资格,不含解析。
|
||||
struct TrainingAttemptDetail: Codable, Equatable, Sendable {
|
||||
let attempt: TrainingAttemptSummary
|
||||
let taskState: TrainingTaskState
|
||||
@TrainingAPIDate var serverTime: Date
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case attempt
|
||||
case taskState = "task_state"
|
||||
case serverTime = "server_time"
|
||||
}
|
||||
}
|
||||
|
||||
/// 原子交卷结果,直接显示成绩摘要并更新草稿版本。
|
||||
struct TrainingSubmissionResult: Codable, Equatable, Sendable {
|
||||
let attempt: TrainingAttemptSummary
|
||||
let taskState: TrainingTaskState
|
||||
let draftRevision: Int
|
||||
@TrainingAPIDate var serverTime: Date
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case attempt
|
||||
case taskState = "task_state"
|
||||
case draftRevision = "draft_revision"
|
||||
case serverTime = "server_time"
|
||||
}
|
||||
}
|
||||
|
||||
/// 本次考试冻结的题目、本人答案和考后解析。
|
||||
struct TrainingReviewItem: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let order: Int
|
||||
let type: TrainingQuestionType
|
||||
let stem: String
|
||||
let options: [TrainingQuestionOption]
|
||||
let selectedOptionIDs: [String]
|
||||
let correctOptionIDs: [String]
|
||||
let isCorrect: Bool
|
||||
let explanation: String
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "question_id"
|
||||
case order
|
||||
case type
|
||||
case stem
|
||||
case options
|
||||
case selectedOptionIDs = "selected_option_ids"
|
||||
case correctOptionIDs = "correct_option_ids"
|
||||
case isCorrect = "is_correct"
|
||||
case explanation
|
||||
}
|
||||
}
|
||||
|
||||
/// 成绩解析游标页,每次只读取最多十题。
|
||||
struct TrainingReviewPage: Codable, Equatable, Sendable {
|
||||
let attemptID: String
|
||||
let items: [TrainingReviewItem]
|
||||
let nextCursor: String?
|
||||
let hasMore: Bool
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case attemptID = "attempt_id"
|
||||
case items
|
||||
case nextCursor = "next_cursor"
|
||||
case hasMore = "has_more"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import Foundation
|
||||
|
||||
/// 正式培训 API,显式在主 Actor 协调网络及登录上下文,不加载无关子资源。
|
||||
@MainActor
|
||||
final class TrainingAPI: TrainingDataServing {
|
||||
private let client: APIClient
|
||||
private let tokenOverride: String?
|
||||
private let eligible: Bool
|
||||
private let validateContext: (@MainActor () -> Bool)?
|
||||
private let prefix = "/api/app/training"
|
||||
|
||||
/// 注入网络客户端;正式页面通过工厂固定本次身份,测试可单独注入校验。
|
||||
init(client: APIClient, tokenOverride: String? = nil, eligible: Bool = true, validateContext: (@MainActor () -> Bool)? = nil) {
|
||||
self.client = client
|
||||
self.tokenOverride = tokenOverride
|
||||
self.eligible = eligible
|
||||
self.validateContext = validateContext
|
||||
}
|
||||
|
||||
/// 为一次页面会话建立固定凭证及身份校验的数据源。
|
||||
func scoped(token: String, eligible: Bool, validateContext: @escaping @MainActor () -> Bool) -> TrainingAPI {
|
||||
TrainingAPI(client: client, tokenOverride: token, eligible: eligible, validateContext: validateContext)
|
||||
}
|
||||
|
||||
/// GET /summary:读取本人统计。
|
||||
func summary() async throws -> TrainingSummary { try await read("/summary") }
|
||||
|
||||
/// GET /tasks:状态和关键词只影响本次摘要页。
|
||||
func tasks(status: TrainingLearnerStatus?, keyword: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingTaskSummary> {
|
||||
var query = cursorQuery(cursor, limit: limit, maximum: 50)
|
||||
if let status { query.append(item("learner_status", status.apiValue)) }
|
||||
if !keyword.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { query.append(item("keyword", keyword)) }
|
||||
return try await read("/tasks", query: query)
|
||||
}
|
||||
|
||||
/// GET /tasks/{id}:平铺任务规则,不读取正文或试卷。
|
||||
func task(id: String) async throws -> TrainingTaskDetail { try await read("/tasks/" + component(id)) }
|
||||
|
||||
/// GET /courses/{id}:快照访问带本人 task_id。
|
||||
func course(id: String, taskID: String) async throws -> TrainingCourseInfo {
|
||||
try await read("/courses/" + component(id), query: taskQuery(taskID))
|
||||
}
|
||||
|
||||
/// GET /courses/{id}/sections:只读取目录页。
|
||||
func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingSectionInfo> {
|
||||
try await read("/courses/" + component(courseID) + "/sections", query: taskQuery(taskID) + cursorQuery(cursor, limit: limit, maximum: 50))
|
||||
}
|
||||
|
||||
/// GET /courses/{id}/sections/{id}:只读取一个小节。
|
||||
func section(courseID: String, sectionID: String, taskID: String) async throws -> TrainingSectionContent {
|
||||
try await read("/courses/" + component(courseID) + "/sections/" + component(sectionID), query: taskQuery(taskID))
|
||||
}
|
||||
|
||||
/// GET /courses/{id}/attachments:只读取附件元信息页。
|
||||
func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttachmentInfo> {
|
||||
try await read("/courses/" + component(courseID) + "/attachments", query: taskQuery(taskID) + cursorQuery(cursor, limit: limit, maximum: 50))
|
||||
}
|
||||
|
||||
/// GET /courses/{id}/attachments/{id}:获取短时授权访问地址。
|
||||
func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink {
|
||||
try await read("/courses/" + component(courseID) + "/attachments/" + component(attachmentID), query: taskQuery(taskID))
|
||||
}
|
||||
|
||||
/// GET /tasks/{id}/progress:读取已保存进度及资格。
|
||||
func progress(taskID: String) async throws -> TrainingProgressSnapshot { try await read("/tasks/" + component(taskID) + "/progress") }
|
||||
|
||||
/// POST /tasks/{id}/study-sessions:幂等创建阅读会话。
|
||||
func startReading(taskID: String, requestID: String) async throws -> TrainingStudySession {
|
||||
try await write(.post, "/tasks/" + component(taskID) + "/study-sessions", body: ReadingStartBody(requestID: requestID))
|
||||
}
|
||||
|
||||
/// POST /study-sessions/{id}/heartbeat:确认当前会话读时,不自动生成新序号。
|
||||
func heartbeat(sessionID: String, sequence: Int, activeSecondsTotal: Int, final: Bool) async throws -> TrainingHeartbeatConfirmation {
|
||||
try await write(.post, "/study-sessions/" + component(sessionID) + "/heartbeat", body: HeartbeatBody(sequence: sequence, activeSecondsTotal: activeSecondsTotal, final: final))
|
||||
}
|
||||
|
||||
/// GET /papers/{id}:读取冻结计分规则。
|
||||
func paper(id: String, taskID: String) async throws -> TrainingPaperInfo {
|
||||
try await read("/papers/" + component(id), query: taskQuery(taskID))
|
||||
}
|
||||
|
||||
/// GET /papers/{id}/questions:按固定题位读取考前题目页。
|
||||
func questions(paperID: String, taskID: String, offset: Int, limit: Int) async throws -> TrainingQuestionPage {
|
||||
try await read("/papers/" + component(paperID) + "/questions", query: taskQuery(taskID) + offsetQuery(offset, limit: limit, maximum: 20))
|
||||
}
|
||||
|
||||
/// GET /tasks/{id}/draft:允许 limit=0 获取恢复位置和答题卡。
|
||||
func draft(taskID: String, offset: Int, limit: Int) async throws -> TrainingDraftPage {
|
||||
try await read("/tasks/" + component(taskID) + "/draft", query: offsetQuery(offset, limit: limit, maximum: 100, minimum: 0))
|
||||
}
|
||||
|
||||
/// PATCH /tasks/{id}/draft:只传变化题目的完整选择集合。
|
||||
func saveDraft(taskID: String, request: TrainingDraftSaveRequest) async throws -> TrainingDraftConfirmation {
|
||||
try await write(.patch, "/tasks/" + component(taskID) + "/draft", body: request)
|
||||
}
|
||||
|
||||
/// POST /tasks/{id}/draft/reset:返回当前草稿实况,调用者按版本同步。
|
||||
func resetDraft(taskID: String, request: TrainingDraftResetRequest) async throws -> TrainingDraftConfirmation {
|
||||
try await write(.post, "/tasks/" + component(taskID) + "/draft/reset", body: request)
|
||||
}
|
||||
|
||||
/// POST /tasks/{id}/submissions:消费已确认的草稿版本,不回传全部答案。
|
||||
func submit(taskID: String, request: TrainingSubmissionRequest) async throws -> TrainingSubmissionResult {
|
||||
try await write(.post, "/tasks/" + component(taskID) + "/submissions", body: request)
|
||||
}
|
||||
|
||||
/// GET /attempts:任务筛选和提交恢复复用成绩分页接口。
|
||||
func attempts(taskID: String?, submissionID: String?, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttemptSummary> {
|
||||
var query = cursorQuery(cursor, limit: limit, maximum: 50)
|
||||
if let taskID { query.append(item("task_id", taskID)) }
|
||||
if let submissionID { query.append(item("submission_id", submissionID)) }
|
||||
return try await read("/attempts", query: query)
|
||||
}
|
||||
|
||||
/// GET /attempts/{id}:单次成绩和最新重考资格。
|
||||
func attempt(id: String) async throws -> TrainingAttemptDetail { try await read("/attempts/" + component(id)) }
|
||||
|
||||
/// GET /attempts/{id}/reviews:单页最多十条,不自动下载全部解析。
|
||||
func reviews(attemptID: String, cursor: String?, limit: Int) async throws -> TrainingReviewPage {
|
||||
try await read("/attempts/" + component(attemptID) + "/reviews", query: cursorQuery(cursor, limit: limit, maximum: 10))
|
||||
}
|
||||
|
||||
private func read<Response: Decodable>(_ path: String, query: [URLQueryItem] = []) async throws -> Response {
|
||||
try await perform(APIRequest<Response>(method: .get, path: prefix + path, queryItems: query, logsPayload: false))
|
||||
}
|
||||
|
||||
private func write<Response: Decodable, Body: Encodable>(_ method: HTTPMethod, _ path: String, body: Body) async throws -> Response {
|
||||
try await perform(APIRequest<Response>(method: method, path: prefix + path, body: body, logsPayload: false))
|
||||
}
|
||||
|
||||
private func perform<Response: Decodable>(_ request: APIRequest<Response>) async throws -> Response {
|
||||
try checkContext()
|
||||
do {
|
||||
let response = try await client.send(request, tokenOverride: tokenOverride)
|
||||
try checkContext()
|
||||
return response
|
||||
} catch {
|
||||
try checkContext()
|
||||
throw TrainingRemoteError.map(error)
|
||||
}
|
||||
}
|
||||
|
||||
private func checkContext() throws {
|
||||
guard eligible else { throw TrainingRemoteError.accountInvalid("请切换到店铺账号后进入培训中心") }
|
||||
guard validateContext?() != false else { throw TrainingRemoteError.identityChanged }
|
||||
}
|
||||
|
||||
nonisolated private func item(_ name: String, _ value: String) -> URLQueryItem { URLQueryItem(name: name, value: value) }
|
||||
nonisolated private func taskQuery(_ id: String) -> [URLQueryItem] { [item("task_id", id)] }
|
||||
nonisolated private func cursorQuery(_ cursor: String?, limit: Int, maximum: Int) -> [URLQueryItem] {
|
||||
var query = [item("limit", String(min(max(limit, 1), maximum)))]
|
||||
if let cursor, !cursor.isEmpty { query.append(item("cursor", cursor)) }
|
||||
return query
|
||||
}
|
||||
nonisolated private func offsetQuery(_ offset: Int, limit: Int, maximum: Int, minimum: Int = 1) -> [URLQueryItem] {
|
||||
[item("offset", String(max(offset, 0))), item("limit", String(min(max(limit, minimum), maximum)))]
|
||||
}
|
||||
nonisolated private func component(_ id: String) -> String {
|
||||
id.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~"))) ?? id
|
||||
}
|
||||
|
||||
/// 阅读会话创建请求,幂等键由业务状态持久保留。
|
||||
private struct ReadingStartBody: Encodable {
|
||||
let requestID: String
|
||||
enum CodingKeys: String, CodingKey { case requestID = "request_id" }
|
||||
}
|
||||
|
||||
/// 会话心跳请求;累计读时为本会话范围。
|
||||
private struct HeartbeatBody: Encodable {
|
||||
let sequence: Int
|
||||
let activeSecondsTotal: Int
|
||||
let final: Bool
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case sequence, final
|
||||
case activeSecondsTotal = "active_seconds_total"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import Foundation
|
||||
|
||||
/// 正式培训数据源;各资源独立读取,不为页面拼接全量任务聚合。
|
||||
protocol TrainingDataServing: Sendable {
|
||||
/// 获取当前学员全局统计。
|
||||
func summary() async throws -> TrainingSummary
|
||||
/// 按状态和关键词读取任务摘要页。
|
||||
func tasks(status: TrainingLearnerStatus?, keyword: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingTaskSummary>
|
||||
/// 获取任务规则和快照引用。
|
||||
func task(id: String) async throws -> TrainingTaskDetail
|
||||
/// 获取课程元信息,附当前授权任务。
|
||||
func course(id: String, taskID: String) async throws -> TrainingCourseInfo
|
||||
/// 获取小节目录页。
|
||||
func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingSectionInfo>
|
||||
/// 读取一个小节的正式正文。
|
||||
func section(courseID: String, sectionID: String, taskID: String) async throws -> TrainingSectionContent
|
||||
/// 读取附件元信息页。
|
||||
func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttachmentInfo>
|
||||
/// 获取短期附件授权链接。
|
||||
func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink
|
||||
/// 刷新服务端已保存进度与操作资格。
|
||||
func progress(taskID: String) async throws -> TrainingProgressSnapshot
|
||||
/// 按幂等键建立阅读会话。
|
||||
func startReading(taskID: String, requestID: String) async throws -> TrainingStudySession
|
||||
/// 按会话序号确认有效读时;重试保持相同请求内容。
|
||||
func heartbeat(sessionID: String, sequence: Int, activeSecondsTotal: Int, final: Bool) async throws -> TrainingHeartbeatConfirmation
|
||||
/// 读取考试规则,不获取全部试题。
|
||||
func paper(id: String, taskID: String) async throws -> TrainingPaperInfo
|
||||
/// 按固定题位读取试题页。
|
||||
func questions(paperID: String, taskID: String, offset: Int, limit: Int) async throws -> TrainingQuestionPage
|
||||
/// 获取草稿元信息及当前题位答案;limit=0 只读取元信息。
|
||||
func draft(taskID: String, offset: Int, limit: Int) async throws -> TrainingDraftPage
|
||||
/// 串行增量保存本人选择。
|
||||
func saveDraft(taskID: String, request: TrainingDraftSaveRequest) async throws -> TrainingDraftConfirmation
|
||||
/// 用户确认重考后重置草稿;响应是当前实况而非恒定空草稿。
|
||||
func resetDraft(taskID: String, request: TrainingDraftResetRequest) async throws -> TrainingDraftConfirmation
|
||||
/// 消费已保存草稿版本并幂等交卷。
|
||||
func submit(taskID: String, request: TrainingSubmissionRequest) async throws -> TrainingSubmissionResult
|
||||
/// 分页读取成绩;taskID+submissionID 可恢复一次交卷结果。
|
||||
func attempts(taskID: String?, submissionID: String?, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttemptSummary>
|
||||
/// 读取一条成绩和最新重考资格。
|
||||
func attempt(id: String) async throws -> TrainingAttemptDetail
|
||||
/// 用户展开时读取解析页。
|
||||
func reviews(attemptID: String, cursor: String?, limit: Int) async throws -> TrainingReviewPage
|
||||
}
|
||||
|
||||
/// 培训稳定业务码及身份切换;保留服务器文案,恢复逻辑只依据枚举或 code。
|
||||
enum TrainingRemoteError: Error, LocalizedError, Equatable, Sendable {
|
||||
case accountInvalid(String), forbidden(String), notWritable(String), readingRequired(String)
|
||||
case sessionExpired(String), sessionConflict(String), draftRevisionConflict(String), idempotencyConflict(String)
|
||||
case answerInvalid(String), answerIncomplete(String), examNotAllowed(String), contentMissing(String)
|
||||
case attemptNotFound(String), paramInvalid(String), identityChanged
|
||||
|
||||
/// 返回稳定业务码,身份切换属于本地拒绝,没有服务端 code。
|
||||
var code: Int? {
|
||||
switch self {
|
||||
case .accountInvalid: 150100
|
||||
case .forbidden: 150101
|
||||
case .notWritable: 150102
|
||||
case .readingRequired: 150103
|
||||
case .sessionExpired: 150104
|
||||
case .sessionConflict: 150105
|
||||
case .draftRevisionConflict: 150106
|
||||
case .idempotencyConflict: 150107
|
||||
case .answerInvalid: 150108
|
||||
case .answerIncomplete: 150109
|
||||
case .examNotAllowed: 150110
|
||||
case .contentMissing: 150111
|
||||
case .attemptNotFound: 150112
|
||||
case .paramInvalid: 150113
|
||||
case .identityChanged: nil
|
||||
}
|
||||
}
|
||||
|
||||
/// 用于页面展示的错误文案,不参与错误分类。
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case let .accountInvalid(message), let .forbidden(message), let .notWritable(message), let .readingRequired(message),
|
||||
let .sessionExpired(message), let .sessionConflict(message), let .draftRevisionConflict(message),
|
||||
let .idempotencyConflict(message), let .answerInvalid(message), let .answerIncomplete(message),
|
||||
let .examNotAllowed(message), let .contentMissing(message), let .attemptNotFound(message), let .paramInvalid(message): message
|
||||
case .identityChanged: "学习账号或业务身份已切换,请重新进入培训中心"
|
||||
}
|
||||
}
|
||||
|
||||
/// 转换培训业务错误;网络和真正登录失效错误仍保留原类型。
|
||||
static func map(_ error: Error) -> Error {
|
||||
guard let apiError = error as? APIError,
|
||||
case let .serverCode(code, message) = apiError else { return error }
|
||||
switch code {
|
||||
case 150100: return Self.accountInvalid(message)
|
||||
case 150101: return Self.forbidden(message)
|
||||
case 150102: return Self.notWritable(message)
|
||||
case 150103: return Self.readingRequired(message)
|
||||
case 150104: return Self.sessionExpired(message)
|
||||
case 150105: return Self.sessionConflict(message)
|
||||
case 150106: return Self.draftRevisionConflict(message)
|
||||
case 150107: return Self.idempotencyConflict(message)
|
||||
case 150108: return Self.answerInvalid(message)
|
||||
case 150109: return Self.answerIncomplete(message)
|
||||
case 150110: return Self.examNotAllowed(message)
|
||||
case 150111: return Self.contentMissing(message)
|
||||
case 150112: return Self.attemptNotFound(message)
|
||||
case 150113: return Self.paramInvalid(message)
|
||||
default: return error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 生产数据源固定进入时的账号和业务上下文,拒绝切换身份后的迟到响应。
|
||||
enum TrainingRemoteServiceFactory {
|
||||
/// 当前店铺身份才可接入;Token 与业务范围固定在本次页面会话。
|
||||
@MainActor static func production() -> any TrainingDataServing {
|
||||
let session = AppStore.shared.session
|
||||
let token = session.token
|
||||
let scope = session.accountCachePrefix
|
||||
let scenicID = session.currentScenicId
|
||||
let storeID = session.currentStoreId
|
||||
let eligible = !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
&& session.accountType == .storeUser && !scope.isEmpty
|
||||
return NetworkServices.shared.trainingAPI.scoped(token: token, eligible: eligible, validateContext: {
|
||||
let current = AppStore.shared.session
|
||||
return current.isLoggedIn && current.accountType == .storeUser
|
||||
&& current.accountCachePrefix == scope && current.token == token
|
||||
&& current.currentScenicId == scenicID && current.currentStoreId == storeID
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import Foundation
|
||||
|
||||
/// 未确认交卷的原始请求及所属业务身份,供 App 重启后沿原键恢复。
|
||||
struct TrainingPendingSubmission: Codable, Equatable, Sendable {
|
||||
let taskID: String
|
||||
let request: TrainingSubmissionRequest
|
||||
let accountScope: String
|
||||
let scenicID: Int
|
||||
let storeID: Int
|
||||
|
||||
/// 固定本次提交的身份和请求,恢复时不读取新的草稿版本替换它。
|
||||
init(taskID: String, request: TrainingSubmissionRequest, context: TrainingContext) {
|
||||
self.taskID = taskID
|
||||
self.request = request
|
||||
accountScope = context.accountScope
|
||||
scenicID = context.scenicID
|
||||
storeID = context.storeID
|
||||
}
|
||||
|
||||
/// 本次交卷的持久化作用域,不包含 Token。
|
||||
var context: TrainingContext {
|
||||
TrainingContext(accountScope: accountScope, scenicID: scenicID, storeID: storeID)
|
||||
}
|
||||
}
|
||||
|
||||
/// 待恢复记录损坏时停止生成新提交,避免重复成绩。
|
||||
enum TrainingPendingSubmissionError: Error, LocalizedError, Equatable, Sendable {
|
||||
case invalidRecord, alreadyPending
|
||||
|
||||
/// 告知用户尚不能安全恢复本次提交。
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidRecord: "上次交卷状态暂无法确认,请联系工作人员核查成绩后重试"
|
||||
case .alreadyPending: "上次交卷尚未确认,请先恢复原提交结果"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 按账号、景区、店铺和任务隔离待确认交卷,支持注入独立 UserDefaults 测试。
|
||||
final class TrainingPendingSubmissionStore {
|
||||
private static let lock = NSRecursiveLock()
|
||||
private let defaults: UserDefaults
|
||||
|
||||
/// 使用指定的持久化域保存不含凭证的交卷请求。
|
||||
init(defaults: UserDefaults = .standard) { self.defaults = defaults }
|
||||
|
||||
/// 当前店铺登录身份;与正式数据源一致,不要求景区 ID 大于零。
|
||||
@MainActor static func currentContext() -> TrainingContext? {
|
||||
let session = AppStore.shared.session
|
||||
guard session.isLoggedIn, session.accountType == .storeUser, !session.accountCachePrefix.isEmpty else { return nil }
|
||||
return TrainingContext(accountScope: session.accountCachePrefix, scenicID: session.currentScenicId, storeID: session.currentStoreId)
|
||||
}
|
||||
|
||||
/// 读取当前作用域记录,损坏记录不当作首次交卷处理。
|
||||
func load(taskID: String, context: TrainingContext) throws -> TrainingPendingSubmission? {
|
||||
Self.lock.lock()
|
||||
defer { Self.lock.unlock() }
|
||||
guard let data = defaults.data(forKey: key(taskID: taskID, context: context)) else { return nil }
|
||||
guard let value = try? JSONDecoder().decode(TrainingPendingSubmission.self, from: data),
|
||||
value.taskID == taskID, value.context == context,
|
||||
!value.request.submissionID.isEmpty, !value.request.paperSnapshotID.isEmpty,
|
||||
value.request.draftRevision > 0 else { throw TrainingPendingSubmissionError.invalidRecord }
|
||||
return value
|
||||
}
|
||||
|
||||
/// 在发起网络提交前保存原始请求;不得用当前版本覆盖待恢复版本。
|
||||
func save(_ value: TrainingPendingSubmission) throws {
|
||||
Self.lock.lock()
|
||||
defer { Self.lock.unlock() }
|
||||
if let existing = try load(taskID: value.taskID, context: value.context), existing != value {
|
||||
throw TrainingPendingSubmissionError.alreadyPending
|
||||
}
|
||||
let storageKey = key(taskID: value.taskID, context: value.context)
|
||||
defaults.set(try JSONEncoder().encode(value), forKey: storageKey)
|
||||
}
|
||||
|
||||
/// 只移除仍对应这次提交的记录,避免迟到响应删除后续待恢复请求。
|
||||
func remove(_ value: TrainingPendingSubmission) throws {
|
||||
Self.lock.lock()
|
||||
defer { Self.lock.unlock() }
|
||||
guard try load(taskID: value.taskID, context: value.context) == value else { return }
|
||||
defaults.removeObject(forKey: key(taskID: value.taskID, context: value.context))
|
||||
}
|
||||
|
||||
private func key(taskID: String, context: TrainingContext) -> String {
|
||||
let scope = Data(context.accountScope.utf8).map { String(format: "%02x", $0) }.joined()
|
||||
let task = Data(taskID.utf8).map { String(format: "%02x", $0) }.joined()
|
||||
return "training-pending-submission:v1:\(scope):scenic_\(context.scenicID):store_\(context.storeID):task_\(task)"
|
||||
}
|
||||
}
|
||||
@@ -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