179 lines
9.8 KiB
Swift
179 lines
9.8 KiB
Swift
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"
|
|
}
|
|
}
|
|
}
|