feat(training): 支持课程附件预览与整页阅读

This commit is contained in:
2026-10-20 13:36:58 +08:00
parent 091d17ff21
commit b149295e66
53 changed files with 4233 additions and 632 deletions
+3
View File
@@ -56,6 +56,9 @@
exceptions = ( exceptions = (
93FF17D72FFB84950033C304 /* Exceptions for "suixinkan" folder in "suixinkan" target */, 93FF17D72FFB84950033C304 /* Exceptions for "suixinkan" folder in "suixinkan" target */,
); );
explicitFolders = (
Resources/TrainingDocumentPreview,
);
path = suixinkan; path = suixinkan;
sourceTree = "<group>"; sourceTree = "<group>";
}; };
@@ -0,0 +1,147 @@
import Foundation
/// 课程附件允许在 App 内预览的文件格式,旧版 DOC 不作为 DOCX 处理。
enum TrainingDocumentKind: String, Sendable {
case pdf, docx, txt, md
/// 优先使用附件名称中的格式;无扩展名时才参考 URL 和 MIME。
static func resolve(name: String, mimeType: String, url: URL) throws -> Self {
let namedExtension = (name as NSString).pathExtension.lowercased()
let fileExtension = namedExtension.isEmpty ? url.pathExtension.lowercased() : namedExtension
if !fileExtension.isEmpty {
guard let kind = Self(rawValue: fileExtension) else { throw TrainingDocumentError.unsupported }
return kind
}
switch mimeType.lowercased().split(separator: ";").first.map(String.init) {
case "application/pdf": return .pdf
case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": return .docx
case "text/plain": return .txt
case "text/markdown", "text/x-markdown": return .md
default: throw TrainingDocumentError.unsupported
}
}
}
/// 单次预览持有的私有临时文件,离开页面或切换附件后明确清理。
struct TrainingLocalDocument: Sendable {
let fileURL: URL
let kind: TrainingDocumentKind
let name: String
let temporaryDirectory: URL?
/// 只清理由下载器为本次预览创建的目录。
func removeTemporaryFile() {
if let temporaryDirectory { try? FileManager.default.removeItem(at: temporaryDirectory) }
}
}
/// 下载替身与正式实现共用的入口;不依赖视图或 App 登录客户端。
protocol TrainingDocumentLoading: Sendable {
/// 原样读取授权链接,返回预览器可使用的本地文件。
func load(attachment: TrainingAttachmentInfo, link: TrainingAttachmentLink) async throws -> TrainingLocalDocument
}
/// 文件预览失败的可恢复原因。
enum TrainingDocumentError: LocalizedError {
case unsupported, invalidURL, tooLarge, empty, invalidResponse, invalidFile
var errorDescription: String? {
switch self {
case .unsupported: return "暂不支持此文件格式,请使用 PDF、DOCX、TXT 或 MD"
case .invalidURL: return "附件访问地址无效,请重试"
case .tooLarge: return "附件超过 30 MB,暂时无法预览"
case .empty: return "附件内容为空"
case .invalidResponse: return "附件下载失败,请重试"
case .invalidFile: return "附件格式不正确或文件已损坏"
}
}
}
/// 独立的无凭证文件下载器,不复用带 Token 的业务网络会话。
final class TrainingDocumentLoader: TrainingDocumentLoading, @unchecked Sendable {
static let maximumBytes = 30 * 1_024 * 1_024
private let session: URLSession
/// 使用短期、无 Cookie、无凭证存储的下载会话。
init() {
let configuration = URLSessionConfiguration.ephemeral
configuration.httpCookieStorage = nil
configuration.httpShouldSetCookies = false
configuration.urlCredentialStorage = nil
configuration.urlCache = nil
configuration.timeoutIntervalForRequest = 60
configuration.timeoutIntervalForResource = 120
session = URLSession(configuration: configuration)
}
/// 下载时保留 URL 的完整签名参数;文件名不会参与磁盘路径拼接。
func load(attachment: TrainingAttachmentInfo, link: TrainingAttachmentLink) async throws -> TrainingLocalDocument {
guard Self.isAllowed(link.url) else { throw TrainingDocumentError.invalidURL }
let kind = try TrainingDocumentKind.resolve(name: attachment.name, mimeType: attachment.mimeType, url: link.url)
guard attachment.sizeBytes <= Self.maximumBytes else { throw TrainingDocumentError.tooLarge }
var request = URLRequest(url: link.url, cachePolicy: .reloadIgnoringLocalCacheData)
request.httpShouldHandleCookies = false
let delegate = TrainingDocumentDownloadDelegate()
let download: URL
let response: URLResponse
do { (download, response) = try await session.download(for: request, delegate: delegate) }
catch {
if delegate.exceededSize { throw TrainingDocumentError.tooLarge }
throw error
}
defer { try? FileManager.default.removeItem(at: download) }
try Task.checkCancellation()
guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode),
let finalURL = http.url, Self.isAllowed(finalURL) else { throw TrainingDocumentError.invalidResponse }
let size = (try FileManager.default.attributesOfItem(atPath: download.path)[.size] as? NSNumber)?.intValue ?? 0
guard size > 0 else { throw TrainingDocumentError.empty }
guard size <= Self.maximumBytes, response.expectedContentLength <= Self.maximumBytes else { throw TrainingDocumentError.tooLarge }
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("training-preview-\(UUID().uuidString)", isDirectory: true)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
do {
let target = directory.appendingPathComponent("document.\(kind.rawValue)")
try FileManager.default.moveItem(at: download, to: target)
try Task.checkCancellation()
return TrainingLocalDocument(fileURL: target, kind: kind, name: attachment.name, temporaryDirectory: directory)
} catch {
try? FileManager.default.removeItem(at: directory)
throw error
}
}
/// 授权文件与重定向均只允许有效 HTTP/HTTPS 地址。
static func isAllowed(_ url: URL) -> Bool {
["http", "https"].contains(url.scheme?.lowercased() ?? "") && url.host?.isEmpty == false
&& url.user == nil && url.password == nil
}
deinit { session.invalidateAndCancel() }
}
/// 下载过程中限制体积;重定向不允许进入本地协议或携带账号口令。
private final class TrainingDocumentDownloadDelegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
private let lock = NSLock()
private var sizeExceeded = false
var exceededSize: Bool { lock.withLock { sizeExceeded } }
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if totalBytesWritten > TrainingDocumentLoader.maximumBytes || totalBytesExpectedToWrite > TrainingDocumentLoader.maximumBytes {
lock.withLock { sizeExceeded = true }
downloadTask.cancel()
}
}
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {}
func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
guard let url = request.url, TrainingDocumentLoader.isAllowed(url) else { completionHandler(nil); return }
var safe = request
safe.setValue(nil, forHTTPHeaderField: "Authorization")
safe.setValue(nil, forHTTPHeaderField: "Cookie")
safe.setValue(nil, forHTTPHeaderField: "Referer")
safe.httpShouldHandleCookies = false
completionHandler(safe)
}
}
@@ -8,26 +8,28 @@ final class TrainingRemoteReadingViewModel {
private(set) var task: TrainingTaskDetail? private(set) var task: TrainingTaskDetail?
/// 已加载的课程元信息,不包含全部正文。 /// 已加载的课程元信息,不包含全部正文。
private(set) var course: TrainingCourseInfo? 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 attachments: [TrainingAttachmentInfo] = []
/// 当前选中文档,授权或预览失败时仍保留,供用户重试。
private(set) var currentAttachment: TrainingAttachmentInfo?
/// 当前文档经任务授权的访问地址,不附带 App Token。
private(set) var currentAttachmentLink: TrainingAttachmentLink?
/// 每次选择或重试生成新票据,拒绝同一个附件的旧下载或渲染回调。
private(set) var attachmentPreviewID: UUID?
/// 只有当前附件已成功渲染后才可累计有效阅读。
private(set) var isAttachmentRendered = false
/// 当前附件授权或预览错误,不被进度刷新清除。
private(set) var attachmentErrorMessage: String?
/// 仅用于附件分页的提示,不阻挡当前已经显示的文档或有效阅读。
private(set) var attachmentListErrorMessage: String?
/// 最新后端确认的学习进度与资格。 /// 最新后端确认的学习进度与资格。
private(set) var progress: TrainingProgressSnapshot? private(set) var progress: TrainingProgressSnapshot?
/// 首次加载或切换正文期间阻止重复内容操作。 /// 首次加载或切换附件期间阻止重复内容操作。
private(set) var isLoading = false private(set) var isLoading = false
/// 小节目录下一页正在加载。
private(set) var isLoadingSections = false
/// 附件目录下一页正在加载。 /// 附件目录下一页正在加载。
private(set) var isLoadingAttachments = false private(set) var isLoadingAttachments = false
/// 附件链接正在授权。 /// 附件链接正在授权。
private(set) var isAuthorizingAttachment = false private(set) var isAuthorizingAttachment = false
/// 小节目录是否还有用户可主动读取的页面。
private(set) var hasMoreSections = false
/// 附件目录是否还有用户可主动读取的页面。 /// 附件目录是否还有用户可主动读取的页面。
private(set) var hasMoreAttachments = false private(set) var hasMoreAttachments = false
/// 已经读取过附件第一页,避免反复取相同元信息。 /// 已经读取过附件第一页,避免反复取相同元信息。
@@ -47,9 +49,7 @@ final class TrainingRemoteReadingViewModel {
private let validateIdentity: @MainActor @Sendable () -> Bool private let validateIdentity: @MainActor @Sendable () -> Bool
private let now: @Sendable () -> Date private let now: @Sendable () -> Date
private var generation = 0 private var generation = 0
private var sectionCursor: String?
private var attachmentCursor: String? private var attachmentCursor: String?
private var bodies: [String: TrainingSectionContent] = [:]
private var contentErrorMessage: String? private var contentErrorMessage: String?
private var session: TrainingStudySession? private var session: TrainingStudySession?
private var sessionRequestID: String? private var sessionRequestID: String?
@@ -85,7 +85,10 @@ final class TrainingRemoteReadingViewModel {
} }
/// 页面展示的内容或保存错误,不用中文文案判断恢复分支。 /// 页面展示的内容或保存错误,不用中文文案判断恢复分支。
var errorMessage: String? { readingErrorMessage ?? contentErrorMessage } var errorMessage: String? { readingErrorMessage ?? attachmentErrorMessage ?? contentErrorMessage }
/// 当前附件标识,预览失败时用于重试同一份文档。
var currentAttachmentID: String? { currentAttachment?.id }
/// 显示未确认读时的倒计时,但只有服务器确认后才允许开始考试。 /// 显示未确认读时的倒计时,但只有服务器确认后才允许开始考试。
var remainingSeconds: Int { var remainingSeconds: Int {
@@ -97,16 +100,19 @@ final class TrainingRemoteReadingViewModel {
/// 当前后端是否允许继续有效学习,完成或只读任务不建立新会话。 /// 当前后端是否允许继续有效学习,完成或只读任务不建立新会话。
var canStudy: Bool { progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated } var canStudy: Bool { progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated }
/// 同课程快照中已读取的正文可直接复用,页面无需为缓存切换显示请求进度。 /// 首次只读课程元信息、附件第一页与进度,并为首个附件授权;不请求小节标题或 HTML。
func isSectionCached(id: String) -> Bool { bodies[id] != nil }
/// 首次只取元信息、目录第一页、首节正文和小型进度,不预取附件或其他小节正文。
func load() async { func load() async {
guard !isLoading, !isInvalidated else { return } guard !isLoading, !isInvalidated else { return }
let epoch = generation let epoch = generation
isLoading = true isLoading = true
contentErrorMessage = nil contentErrorMessage = nil
attachmentErrorMessage = nil
attachmentListErrorMessage = nil
resetAttachmentPreview()
pauseReading()
defer { if generation == epoch { isLoading = false } } defer { if generation == epoch { isLoading = false } }
await flush(final: true)
guard generation == epoch, !isInvalidated, !Task.isCancelled else { return }
do { do {
let detail = try await service.task(id: taskID) let detail = try await service.task(id: taskID)
try await checkIdentity(epoch) try await checkIdentity(epoch)
@@ -115,80 +121,74 @@ final class TrainingRemoteReadingViewModel {
} }
let courseID = detail.summary.courseSnapshotID let courseID = detail.summary.courseSnapshotID
async let metadata = service.course(id: courseID, taskID: taskID) async let metadata = service.course(id: courseID, taskID: taskID)
async let directory = service.sections(courseID: courseID, taskID: taskID, cursor: nil, limit: 20) async let documents = service.attachments(courseID: courseID, taskID: taskID, cursor: nil, limit: 20)
async let savedProgress = service.progress(taskID: taskID) async let savedProgress = service.progress(taskID: taskID)
let (info, page, saved) = try await (metadata, directory, savedProgress) let (info, page, saved) = try await (metadata, documents, 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) try await checkIdentity(epoch)
guard saved.canViewCourse else { throw TrainingRemoteError.forbidden("当前任务不能查看课程") }
task = detail task = detail
course = info course = info
sections = page.items attachments = page.items
sectionCursor = page.nextCursor attachmentCursor = page.nextCursor
hasMoreSections = page.hasMore hasMoreAttachments = page.hasMore
currentSectionID = first.id hasLoadedAttachments = true
currentSection = body
bodies[body.id] = body
progress = saved progress = saved
if let first = attachments.first {
await prepareAttachment(first, epoch: epoch)
}
} catch { saveContentError(error, epoch: epoch) } } catch { saveContentError(error, epoch: epoch) }
} }
/// 返回已缓存课程时只刷新本人资格与进度,保留正文和目录缓存。 /// 返回已缓存课程时只刷新本人资格与进度,保留文档和预览错误。
func refreshProgress() async { func refreshProgress() async {
let epoch = generation let epoch = generation
guard !isInvalidated else { return } guard !isInvalidated else { return }
do { do {
let value = try await service.progress(taskID: taskID) let value = try await service.progress(taskID: taskID)
try await checkIdentity(epoch) try await checkIdentity(epoch)
guard value.canViewCourse else { throw TrainingRemoteError.forbidden("当前任务不能查看课程") }
progress = value progress = value
if !value.canStudy || value.readingCompleted { pauseReading() } if !value.canStudy || value.readingCompleted { pauseReading() }
contentErrorMessage = nil contentErrorMessage = nil
} catch { saveContentError(error, epoch: epoch) } } catch { saveContentError(error, epoch: epoch) }
} }
/// 切章节立即暂停;只读取选中正文,已经看过的同快照正文直接复用。 /// 选择或重试附件时先关闭旧读时片段,再为选中的文档重新授权。
func selectSection(id: String) async { func selectAttachment(id: String) async {
guard !isLoading, !isInvalidated, let course else { return } guard !isLoading, !isInvalidated,
let attachment = attachments.first(where: { $0.id == id }) else { return }
let epoch = generation let epoch = generation
isLoading = true isLoading = true
defer { if generation == epoch { isLoading = false } } defer { if generation == epoch { isLoading = false } }
resetAttachmentPreview()
pauseReading() pauseReading()
await flush(final: true) await flush(final: true)
guard generation == epoch, !isInvalidated, !Task.isCancelled else { return } guard generation == epoch, !isInvalidated, !Task.isCancelled else { return }
contentErrorMessage = nil contentErrorMessage = nil
currentSectionID = id await prepareAttachment(attachment, epoch: epoch)
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 { @discardableResult
guard !isLoadingSections, hasMoreSections, let cursor = sectionCursor, let course, !isInvalidated else { return } func markAttachmentRendered(id: String, previewID: UUID) -> Bool {
let epoch = generation guard !isInvalidated, !isLoading, currentAttachmentID == id,
isLoadingSections = true attachmentPreviewID == previewID, currentAttachmentLink != nil,
defer { if generation == epoch { isLoadingSections = false } } attachmentErrorMessage == nil else { return false }
do { isAttachmentRendered = true
let page = try await service.sections(courseID: course.id, taskID: taskID, cursor: cursor, limit: 20) return true
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 reportAttachmentFailure(id: String, previewID: UUID, message: String) {
guard !isInvalidated, currentAttachmentID == id, attachmentPreviewID == previewID else { return }
isAttachmentRendered = false
attachmentErrorMessage = message
pauseReading()
}
/// 后续附件页仅由用户主动读取;已有第一页不重复获取。
func loadAttachments(loadMore: Bool = false) async { func loadAttachments(loadMore: Bool = false) async {
guard !isLoadingAttachments, let course, !isInvalidated else { return } guard !isLoading, !isLoadingAttachments, let course, !isInvalidated else { return }
if hasLoadedAttachments && !loadMore { return } if hasLoadedAttachments && !loadMore { return }
if loadMore && (!hasMoreAttachments || attachmentCursor == nil) { return } if loadMore && (!hasMoreAttachments || attachmentCursor == nil) { return }
let epoch = generation let epoch = generation
@@ -203,11 +203,11 @@ final class TrainingRemoteReadingViewModel {
attachmentCursor = page.nextCursor attachmentCursor = page.nextCursor
hasMoreAttachments = page.hasMore hasMoreAttachments = page.hasMore
hasLoadedAttachments = true hasLoadedAttachments = true
contentErrorMessage = nil attachmentListErrorMessage = nil
} catch { saveContentError(error, epoch: epoch) } } catch { saveAttachmentListError(error, epoch: epoch) }
} }
/// 点击附件时取得有效 HTTP/HTTPS 链接,原样交给系统浏览器,不附 App Token。 /// 获取同一附件的有效 HTTP/HTTPS 授权地址,保持签名参数原样,不附 App Token。
func authorizeAttachment(id: String) async -> TrainingAttachmentLink? { func authorizeAttachment(id: String) async -> TrainingAttachmentLink? {
guard !isAuthorizingAttachment, let course, !isInvalidated else { return nil } guard !isAuthorizingAttachment, let course, !isInvalidated else { return nil }
let epoch = generation let epoch = generation
@@ -217,23 +217,42 @@ final class TrainingRemoteReadingViewModel {
let link = try await service.attachmentURL(courseID: course.id, attachmentID: id, taskID: taskID) let link = try await service.attachmentURL(courseID: course.id, attachmentID: id, taskID: taskID)
try await checkIdentity(epoch) try await checkIdentity(epoch)
let scheme = link.url.scheme?.lowercased() let scheme = link.url.scheme?.lowercased()
guard scheme == "http" || scheme == "https", link.url.host?.isEmpty == false, guard link.id == id, scheme == "http" || scheme == "https", link.url.host?.isEmpty == false,
link.url.user == nil, link.url.password == nil, link.expiresAt > now() else { link.url.user == nil, link.url.password == nil, link.expiresAt > now() else {
throw TrainingRemoteError.paramInvalid("附件访问地址无效或已过期,请重试") throw TrainingRemoteError.paramInvalid("附件访问地址无效或已过期,请重试")
} }
contentErrorMessage = nil attachmentErrorMessage = nil
return link return link
} catch { saveContentError(error, epoch: epoch); return nil } } catch { saveAttachmentError(error, epoch: epoch); return nil }
} }
/// 正文已经在前台可见时建立或恢复会话;创建丢响应时沿用原 requestID。 private func prepareAttachment(_ attachment: TrainingAttachmentInfo, epoch: Int) async {
currentAttachment = attachment
attachmentErrorMessage = nil
let previewID = UUID()
attachmentPreviewID = previewID
let link = await authorizeAttachment(id: attachment.id)
guard generation == epoch, !isInvalidated, !Task.isCancelled,
attachmentPreviewID == previewID, currentAttachmentID == attachment.id else { return }
currentAttachmentLink = link
}
private func resetAttachmentPreview() {
currentAttachment = nil
currentAttachmentLink = nil
attachmentPreviewID = nil
isAttachmentRendered = false
attachmentErrorMessage = nil
}
/// 附件已渲染且前台可见时建立或恢复会话;创建丢响应时沿用原 requestID。
func startReading(at uptime: TimeInterval) async { func startReading(at uptime: TimeInterval) async {
guard currentSection != nil, canStudy else { return } guard isAttachmentRendered, currentAttachmentLink != nil, canStudy else { return }
let epoch = generation let epoch = generation
wantsReading = true wantsReading = true
lastVisibleUptime = uptime lastVisibleUptime = uptime
await waitForSessionOperation(epoch: epoch) await waitForSessionOperation(epoch: epoch)
guard generation == epoch, !isInvalidated, wantsReading, canStudy, currentSection != nil else { return } guard generation == epoch, !isInvalidated, wantsReading, canStudy, isAttachmentRendered else { return }
isSessionBusy = true isSessionBusy = true
defer { finishSessionOperation(epoch: epoch) } defer { finishSessionOperation(epoch: epoch) }
do { do {
@@ -242,7 +261,7 @@ final class TrainingRemoteReadingViewModel {
try await sendHeartbeats(epoch: epoch) try await sendHeartbeats(epoch: epoch)
} }
if session == nil && canStudy { try await createSession(epoch: epoch) } if session == nil && canStudy { try await createSession(epoch: epoch) }
if wantsReading, session != nil, canStudy { if wantsReading, session != nil, canStudy, isAttachmentRendered {
readingErrorMessage = nil readingErrorMessage = nil
readingClock.resume(at: uptime) readingClock.resume(at: uptime)
isReading = true isReading = true
@@ -253,7 +272,7 @@ final class TrainingRemoteReadingViewModel {
/// 由前台定时器驱动,每次最多记一秒;到间隔或门槛才发送网络心跳。 /// 由前台定时器驱动,每次最多记一秒;到间隔或门槛才发送网络心跳。
func recordVisibleTime(at uptime: TimeInterval) async { func recordVisibleTime(at uptime: TimeInterval) async {
lastVisibleUptime = uptime lastVisibleUptime = uptime
guard isReading, wantsReading, canStudy, !isSessionBusy, pendingHeartbeat == nil, guard isReading, wantsReading, canStudy, isAttachmentRendered, !isSessionBusy, pendingHeartbeat == nil,
readingClock.takeSecond(at: uptime) else { return } readingClock.takeSecond(at: uptime) else { return }
activeSecondsTotal += 1 activeSecondsTotal += 1
let interval = max(1, session?.heartbeatIntervalSeconds ?? 5) let interval = max(1, session?.heartbeatIntervalSeconds ?? 5)
@@ -262,7 +281,7 @@ final class TrainingRemoteReadingViewModel {
} }
} }
/// 页面隐藏、锁屏、正文切换或附件打开时同步停止计时,丢弃未满一秒片段。 /// 页面隐藏、锁屏、文档切换或预览失败时同步停止计时,丢弃未满一秒片段。
func pauseReading() { func pauseReading() {
wantsReading = false wantsReading = false
finalRequested = true finalRequested = true
@@ -293,22 +312,17 @@ final class TrainingRemoteReadingViewModel {
clearSession() clearSession()
task = nil task = nil
course = nil course = nil
sections = []
currentSection = nil
currentSectionID = nil
attachments = [] attachments = []
bodies = [:] resetAttachmentPreview()
attachmentListErrorMessage = nil
progress = nil progress = nil
contentErrorMessage = nil contentErrorMessage = nil
readingErrorMessage = nil readingErrorMessage = nil
readingNotice = nil readingNotice = nil
sectionCursor = nil
attachmentCursor = nil attachmentCursor = nil
hasMoreSections = false
hasMoreAttachments = false hasMoreAttachments = false
hasLoadedAttachments = false hasLoadedAttachments = false
isLoading = false isLoading = false
isLoadingSections = false
isLoadingAttachments = false isLoadingAttachments = false
isAuthorizingAttachment = false isAuthorizingAttachment = false
isSessionBusy = false isSessionBusy = false
@@ -406,6 +420,28 @@ final class TrainingRemoteReadingViewModel {
contentErrorMessage = mapped.localizedDescription contentErrorMessage = mapped.localizedDescription
} }
private func saveAttachmentError(_ error: Error, epoch: Int) {
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
let mapped = TrainingRemoteError.map(error)
let code = (mapped as? TrainingRemoteError)?.code
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 {
invalidate()
return
}
attachmentErrorMessage = mapped.localizedDescription
}
private func saveAttachmentListError(_ error: Error, epoch: Int) {
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
let mapped = TrainingRemoteError.map(error)
let code = (mapped as? TrainingRemoteError)?.code
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 {
invalidate()
return
}
attachmentListErrorMessage = mapped.localizedDescription
}
private func handleReadingError(_ error: Error, epoch: Int) async { private func handleReadingError(_ error: Error, epoch: Int) async {
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return } guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
let mapped = TrainingRemoteError.map(error) let mapped = TrainingRemoteError.map(error)
@@ -421,7 +457,7 @@ final class TrainingRemoteReadingViewModel {
do { do {
let saved = try await service.progress(taskID: taskID) let saved = try await service.progress(taskID: taskID)
try await checkIdentity(epoch) try await checkIdentity(epoch)
let shouldResume = wantsReading && code != 150102 let shouldResume = wantsReading && isAttachmentRendered && code != 150102
clearSession() clearSession()
progress = saved progress = saved
wantsReading = shouldResume wantsReading = shouldResume
@@ -431,7 +467,7 @@ final class TrainingRemoteReadingViewModel {
} }
if shouldResume, canStudy { if shouldResume, canStudy {
try await createSession(epoch: epoch) try await createSession(epoch: epoch)
if wantsReading, canStudy { if wantsReading, canStudy, isAttachmentRendered {
readingClock.resume(at: lastVisibleUptime) readingClock.resume(at: lastVisibleUptime)
isReading = true isReading = true
readingErrorMessage = nil readingErrorMessage = nil
+11
View File
@@ -2,6 +2,17 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0"> <plist version="1.0">
<dict> <dict>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>vipsky.oss-cn-shanghai.aliyuncs.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
</dict>
</dict>
</dict>
<key>CFBundleURLTypes</key> <key>CFBundleURLTypes</key>
<array> <array>
<dict> <dict>
@@ -0,0 +1,22 @@
# Third-party notices
The application includes the following browser libraries as local, version-pinned assets:
| Library | Version | Upstream | License used |
|---|---|---|---|
| docx-preview | 0.4.1 | https://github.com/VolodymyrBaydalka/docxjs | Apache-2.0 |
| JSZip | 3.10.2 | https://github.com/Stuk/jszip | MIT (chosen from its MIT/GPL license alternatives) |
| markdown-it | 15.0.3 | https://github.com/markdown-it/markdown-it | MIT |
| DOMPurify | 3.4.17 | https://github.com/cure53/DOMPurify | Apache-2.0 (chosen from its Apache/MPL license alternatives) |
Copyright Volodymyr Baydalka (docx-preview).
Copyright (c) 2009-2016 Stuart Knightley, David Duponchel, Franz Buchinger, António Afonso (JSZip).
Copyright (c) 2014 Vitaly Puzrin, Alex Kocharin (markdown-it).
Copyright (c) Cure53 and other contributors (DOMPurify; see upstream license and preserved bundle header).
The distributed JavaScript is transformed to ES2017 syntax and minified by esbuild 0.28.2; no library feature code is intentionally changed. Exact upstream tarball integrity, source SHA-256, output SHA-256, and transformations are recorded in `vendor-manifest.json`.
Full upstream license texts appear in `licenses/`. Bundled dependency license families include JSZip's pako, lie/immediate, readable-stream and its support packages, setimmediate; markdown-it's mdurl, uc.micro, entities, linkify-it and punycode.js. Their preserved license texts appear in `licenses/bundled/` (the manifest's `licenseSourceVersion` identifies the package used to obtain that text, not a separate runtime package install). Browser dependency code is fixed by the parent library's bundled asset hash; the application does not fetch dependencies at runtime.
@@ -0,0 +1,33 @@
# Training document preview shell
This local shell renders **DOCX, TXT, and Markdown** inside the native course card. PDF uses each platform's native PDF component. Legacy `.doc` is deliberately unsupported. All parser scripts ship with the application; no CDN, online converter, analytics, application token, or signed attachment URL is used in this page.
## Native host contract
- Open `index.html?type=docx|txt|md&requestId=<opaque>` on a trusted local origin. `requestId` is a newly generated document-load ID matching `[A-Za-z0-9_-]{1,80}` and contains no course/user/URL credentials.
- iOS uses `training-document://preview/`; Android uses intercepted `https://training-preview.invalid/`.
- Serve the current downloaded attachment bytes at the relative path `./document/<requestId>/file`. Only the exact active ID is valid. The native host downloads the remote URL and enforces its own identity, expiry, file type, size, and redirect policy. The shell never receives the remote URL or auth headers.
- Serve this directory's files only by an explicit asset allowlist, without filesystem path traversal. Deny requests for every other scheme, host, document ID, and path. The page's CSP is defense in depth; the native host must also block all remote navigation and subresources.
- Resource loading uses `XMLHttpRequest` so WKURLSchemeHandler can serve bytes. If WebKit requires a CORS response header, add it only to this trusted local resource response; never enable general remote access.
- iOS messages: `window.webkit.messageHandlers.trainingDocument.postMessage(event)`.
- Android messages: `window.TrainingDocument.postMessage(JSON.stringify(event))`. Expose only this tiny bridge on the trusted local main-frame origin. Prefer origin-scoped WebMessageListener when available.
- Every event has `{ type, requestId }`. Native must discard stale IDs and messages from subframes/other origins.
- `ready`: `{ type: "ready", requestId, height }`, sent after content render, embedded-image settlement, and two animation frames. Native must also verify its view is visible before counting study time; Android should use its visual state callback.
- `error`: `{ type: "error", requestId, code, message }`; stop study time and expose a native retry action. Do not count navigation/onload as successful rendering.
- `link`: `{ type: "link", requestId, url }`; sent only for HTTP/HTTPS anchor clicks. Native validates again and explicitly opens the external browser, pausing study time. The local shell never navigates away.
- A retry or attachment change creates a fresh request ID and reloads the page. A closed/replaced view must not restart timing after late events.
## Rendering and compatibility
- Libraries are pinned by exact version, upstream npm SHA-512 integrity and file SHA-256 in `vendor-manifest.json`.
- Upstream browser bundles are transformed only with `esbuild 0.28.2 --target=es2017 --minify --legal-comments=inline`. This removes ES2020 optional chaining/nullish syntax from docx-preview for older Android WebViews. `compat.js` supplies `globalThis`, `Array.flatMap`, and the `Promise.allSettled` used by docx-preview only when missing. No full polyfill framework is loaded. The pinned browser bundles do not use `Promise.finally`, `Object.fromEntries`, or `String.replaceAll`; these are deliberately not patched. iOS 16 and Android WebView 58+ with ES2017 support are the intended baseline; device rendering tests remain required.
- DOCX uses `docx-preview` with `renderAltChunks: false`, no experimental features or embedded-font loading. It renders into a detached tree, then DOMPurify sanitizes the result before insertion. Script/frame/object/form/SVG/MathML content and unsafe links are removed. Style URLs are filtered, and CSP blocks remote images/fonts/styles/connections. Legal embedded bitmap images use local blob/data URLs. Complex Word pagination, fonts, and unsupported drawings may differ from Microsoft Word.
- Markdown uses markdown-it with raw HTML, automatic linkification and typographic rewrites disabled, followed by DOMPurify. Markdown external/relative images do not perform network requests; their alt text is displayed instead. HTTP/HTTPS links are handed to native on a user click.
- TXT uses a text node, never `innerHTML`. UTF-8, UTF-16 BOM or detectable ASCII UTF-16 byte order, then GB18030 fallback are supported. Binary control characters, empty text, and undecodable input produce an error.
- Native and shell both cap source files at **30 MiB**. Text is capped at **5 MiB**. DOCX checks the ZIP central directory before inflation and bounds actual streamed inflation: at most **1000 entries**, **20 MiB per entry**, and **100 MiB total**. ZIP64, split/encrypted archives, unsupported compression, malformed files and missing required DOCX parts are rejected.
## Licensing and maintenance
See `NOTICE.md`, `licenses/`, and `vendor-manifest.json`. Keep the copyright headers, license texts, notices, and exact version metadata whenever updating these files. The same resource directory is copied byte-for-byte to Android `app/src/main/assets/training-document-preview/`.
To regenerate each bundle, download the exact upstream tarball in the manifest, verify its integrity, extract the named `upstreamSource`, run the esbuild command above, then verify the listed asset SHA-256. Do not load a remote "latest" bundle at runtime.
@@ -0,0 +1,45 @@
/* Compatibility helpers for Android WebView with ES2017 support. */
(function () {
'use strict';
if (typeof globalThis === 'undefined') { window.globalThis = window; }
// docx-preview waits for embedded images with allSettled (Chrome 76+).
// Keep rejected optional resources from rejecting the entire document render.
if (!Promise.allSettled) {
Object.defineProperty(Promise, 'allSettled', {
configurable: true,
writable: true,
value: function (values) {
var Constructor = this;
try {
var results = Array.from(values).map(function (value) {
return Constructor.resolve(value).then(function (result) {
return { status: 'fulfilled', value: result };
}, function (reason) {
return { status: 'rejected', reason: reason };
});
});
return Constructor.all(results);
} catch (error) { return Constructor.reject(error); }
}
});
}
if (!Array.prototype.flatMap) {
Object.defineProperty(Array.prototype, 'flatMap', {
configurable: true,
writable: true,
value: function (callback, receiver) {
var result = [];
for (var i = 0; i < this.length; i += 1) {
if (!(i in this)) { continue; }
var item = callback.call(receiver, this[i], i, this);
if (Array.isArray(item)) {
for (var j = 0; j < item.length; j += 1) {
if (j in item) { result.push(item[j]); }
}
} else { result.push(item); }
}
return result;
}
});
}
}());
@@ -0,0 +1,21 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src data: blob:; font-src data: blob:; connect-src 'self' training-document://preview; frame-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'">
<meta name="referrer" content="no-referrer">
<title>课程附件</title>
<link rel="stylesheet" href="preview.css">
<script src="compat.js" defer></script>
<script src="vendor/jszip.min.js" defer></script>
<script src="vendor/docx-preview.min.js" defer></script>
<script src="vendor/markdown-it.min.js" defer></script>
<script src="vendor/purify.min.js" defer></script>
<script src="preview.js" defer></script>
</head>
<body>
<p id="status" role="status">正在加载附件…</p>
<main id="document" aria-label="课程附件内容" hidden></main>
</body>
</html>
@@ -0,0 +1,19 @@
Copyright Node.js contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
@@ -0,0 +1,11 @@
Copyright (c) Felix Böhm
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -0,0 +1,20 @@
Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, Domenic Denicola, Brian Cavalier
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,16 @@
The ISC License
Copyright (c) Isaac Z. Schlueter
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
@@ -0,0 +1,60 @@
# isarray
`Array#isArray` for older browsers.
[![build status](https://secure.travis-ci.org/juliangruber/isarray.svg)](http://travis-ci.org/juliangruber/isarray)
[![downloads](https://img.shields.io/npm/dm/isarray.svg)](https://www.npmjs.org/package/isarray)
[![browser support](https://ci.testling.com/juliangruber/isarray.png)
](https://ci.testling.com/juliangruber/isarray)
## Usage
```js
var isArray = require('isarray');
console.log(isArray([])); // => true
console.log(isArray({})); // => false
```
## Installation
With [npm](http://npmjs.org) do
```bash
$ npm install isarray
```
Then bundle for the browser with
[browserify](https://github.com/substack/browserify).
With [component](http://component.io) do
```bash
$ component install juliangruber/isarray
```
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,7 @@
#Copyright (c) 2014-2018 Calvin Metcalf, Jordan Harband
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
**THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.**
@@ -0,0 +1,22 @@
Copyright (c) 2015 Vitaly Puzrin.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,134 @@
[
{
"name": "mdurl",
"licenseSourceVersion": "2.1.0",
"licenseFiles": [
"mdurl-LICENSE"
]
},
{
"name": "uc.micro",
"licenseSourceVersion": "3.0.0",
"licenseFiles": [
"uc.micro-LICENSE.txt"
]
},
{
"name": "entities",
"licenseSourceVersion": "8.1.0",
"license": "BSD-2-Clause",
"repository": {
"url": "git+https://github.com/fb55/entities.git",
"type": "git"
},
"licenseFiles": [
"entities-LICENSE"
]
},
{
"name": "linkify-it",
"licenseSourceVersion": "6.1.0",
"licenseFiles": [
"linkify-it-LICENSE"
]
},
{
"name": "punycode.js",
"licenseSourceVersion": "2.3.1",
"licenseFiles": [
"punycode.js-LICENSE-MIT.txt"
]
},
{
"name": "pako",
"licenseSourceVersion": "1.0.11",
"licenseFiles": [
"pako-LICENSE"
]
},
{
"name": "lie",
"licenseSourceVersion": "3.3.0",
"licenseFiles": [
"lie-license.md"
]
},
{
"name": "immediate",
"licenseSourceVersion": "3.0.6",
"licenseFiles": [
"immediate-LICENSE.txt"
]
},
{
"name": "readable-stream",
"licenseSourceVersion": "2.3.8",
"license": "MIT",
"repository": {
"url": "git://github.com/nodejs/readable-stream.git",
"type": "git"
},
"licenseFiles": [
"readable-stream-LICENSE"
]
},
{
"name": "core-util-is",
"licenseSourceVersion": "1.0.3",
"licenseFiles": [
"core-util-is-LICENSE"
]
},
{
"name": "inherits",
"licenseSourceVersion": "2.0.4",
"licenseFiles": [
"inherits-LICENSE"
]
},
{
"name": "isarray",
"licenseSourceVersion": "1.0.0",
"license": "MIT",
"repository": {
"url": "git://github.com/juliangruber/isarray.git",
"type": "git"
},
"licenseFiles": [
"isarray-LICENSE-README.md"
]
},
{
"name": "safe-buffer",
"licenseSourceVersion": "5.1.2",
"licenseFiles": [
"safe-buffer-LICENSE"
]
},
{
"name": "string_decoder",
"licenseSourceVersion": "1.1.1",
"licenseFiles": [
"string_decoder-LICENSE"
]
},
{
"name": "util-deprecate",
"licenseSourceVersion": "1.0.2",
"licenseFiles": [
"util-deprecate-LICENSE"
]
},
{
"name": "setimmediate",
"licenseSourceVersion": "1.0.5",
"license": "MIT",
"repository": {
"url": "git+https://github.com/yuzujs/setImmediate.git",
"type": "git"
},
"licenseFiles": [
"setimmediate-LICENSE.txt"
]
}
]
@@ -0,0 +1,45 @@
Copyright (c) 2015 Vitaly Puzrin, Alex Kocharin.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------------------
.parse() is based on Joyent's node.js `url` code:
Copyright Joyent, Inc. and other Node contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
@@ -0,0 +1,21 @@
(The MIT License)
Copyright (C) 2014-2017 by Vitaly Puzrin and Andrei Tuputcyn
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,20 @@
Copyright Mathias Bynens <https://mathiasbynens.be/>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,47 @@
Node.js is licensed for use as follows:
"""
Copyright Node.js contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""
This license applies to parts of Node.js originating from the
https://github.com/joyent/node repository:
"""
Copyright Joyent, Inc. and other Node contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Feross Aboukhadijeh
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
@@ -0,0 +1,20 @@
Copyright (c) 2012 Barnesandnoble.com, llc, Donavon West, and Domenic Denicola
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,48 @@
Node.js is licensed for use as follows:
"""
Copyright Node.js contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""
This license applies to parts of Node.js originating from the
https://github.com/joyent/node repository:
"""
Copyright Joyent, Inc. and other Node contributors. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.
"""
@@ -0,0 +1,20 @@
Copyright Mathias Bynens <https://mathiasbynens.be/>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,24 @@
(The MIT License)
Copyright (c) 2014 Nathan Rajlich <nathan@tootallnate.net>
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright (c) 2016-2023 Volodymyr Baydalka
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
@@ -0,0 +1,651 @@
JSZip is dual licensed. At your choice you may use it under the MIT license *or* the GPLv3
license.
The MIT License
===============
Copyright (c) 2009-2016 Stuart Knightley, David Duponchel, Franz Buchinger, António Afonso
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
GPL version 3
=============
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
@@ -0,0 +1,22 @@
Copyright (c) 2014 Vitaly Puzrin, Alex Kocharin.
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,25 @@
:root { color-scheme: light; }
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; background: #fff; color: #25334b; }
body { font: 16px/1.8 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans SC", sans-serif; overflow-wrap: break-word; -webkit-text-size-adjust: 100%; }
#status { padding: 20px 16px; margin: 0; color: #8897ad; white-space: pre-wrap; }
#document { min-height: 80px; padding: 16px; width: 100%; overflow-x: auto; }
#document[hidden], #status[hidden] { display: none; }
#document > :first-child { margin-top: 0; }
#document > :last-child { margin-bottom: 0; }
h1, h2, h3, h4, h5, h6 { line-height: 1.5; color: #182238; margin: 1.2em 0 .6em; }
h1 { font-size: 1.5em; } h2 { font-size: 1.3em; } h3 { font-size: 1.15em; }
p { margin: .65em 0; }
a { color: #2679ff; text-decoration: underline; }
img { max-width: 100%; height: auto; }
table { max-width: 100%; border-collapse: collapse; }
th, td { border: 1px solid #dfe7f2; padding: 6px 8px; vertical-align: top; }
pre { white-space: pre-wrap; overflow-wrap: break-word; margin: 0; font: inherit; tab-size: 4; }
pre code { font: 13px/1.6 ui-monospace, Menlo, Consolas, monospace; }
code { background: #f3f6fa; border-radius: 3px; padding: .1em .25em; }
pre:has(code) { padding: 12px; background: #f3f6fa; border-radius: 6px; }
blockquote { margin: 1em 0; padding: 0 12px; border-left: 3px solid #dfe7f2; color: #687b98; }
ul, ol { padding-left: 1.6em; }
.docx-wrapper { padding: 0 !important; background: transparent !important; }
.docx-wrapper > section.docx { box-shadow: none !important; margin: 0 !important; padding: 0 !important; min-height: 0 !important; width: 100% !important; max-width: 100% !important; }
section.docx article { min-height: 0 !important; }
@@ -0,0 +1,264 @@
/* Trusted local document renderer. No application token or remote attachment URL enters this page. */
(function () {
'use strict';
var params = new URLSearchParams(window.location.search);
var requestId = params.get('requestId') || '';
var kind = params.get('type') || '';
var content = document.getElementById('document');
var status = document.getElementById('status');
var finished = false;
var limits = { source: 30 * 1024 * 1024, text: 5 * 1024 * 1024, entries: 1000, item: 20 * 1024 * 1024, total: 100 * 1024 * 1024 };
/** Send only request-scoped, explicitly understood messages to the native host. */
function post(type, fields) {
var message = { type: type, requestId: requestId };
Object.keys(fields || {}).forEach(function (key) { message[key] = fields[key]; });
if (window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.trainingDocument) {
window.webkit.messageHandlers.trainingDocument.postMessage(message);
} else if (window.TrainingDocument && typeof window.TrainingDocument.postMessage === 'function') {
window.TrainingDocument.postMessage(JSON.stringify(message));
}
}
function previewError(code, message) {
var error = new Error(message);
error.previewCode = code;
return error;
}
function fail(error) {
if (finished) { return; }
finished = true;
content.hidden = true;
content.textContent = '';
status.hidden = false;
status.textContent = error && error.message ? error.message : '附件无法预览,请重试';
post('error', { code: error.previewCode || 'render_failed', message: status.textContent });
}
/** XHR also works for local WKURLSchemeHandler resources without exposing remote origins. */
function loadBytes() {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', './document/' + requestId + '/file', true);
xhr.responseType = 'arraybuffer';
xhr.timeout = 30000;
xhr.withCredentials = false;
xhr.onprogress = function (event) {
if (event.loaded > limits.source) {
xhr.abort();
reject(previewError('file_too_large', '附件超过 30 MB,暂时无法预览'));
}
};
xhr.onload = function () {
if (xhr.status !== 0 && (xhr.status < 200 || xhr.status >= 300)) {
reject(previewError('document_unavailable', '附件加载失败,请重试')); return;
}
if (!(xhr.response instanceof ArrayBuffer) || !xhr.response.byteLength) {
reject(previewError('empty_document', '附件内容为空')); return;
}
if (xhr.response.byteLength > limits.source) {
reject(previewError('file_too_large', '附件超过 30 MB,暂时无法预览')); return;
}
resolve(xhr.response);
};
xhr.onerror = function () { reject(previewError('document_unavailable', '附件加载失败,请重试')); };
xhr.ontimeout = function () { reject(previewError('document_timeout', '附件加载超时,请重试')); };
xhr.onabort = function () { reject(previewError('document_cancelled', '附件加载已取消')); };
xhr.send();
});
}
/** Decode common Chinese text encodings, refusing binary input rather than showing corrupt markup. */
function decodeText(buffer) {
if (buffer.byteLength > limits.text) { throw previewError('text_too_large', '文本附件超过 5 MB,暂时无法预览'); }
var bytes = new Uint8Array(buffer);
var encoding = 'utf-8';
if (bytes[0] === 0xff && bytes[1] === 0xfe) { encoding = 'utf-16le'; }
else if (bytes[0] === 0xfe && bytes[1] === 0xff) { encoding = 'utf-16be'; }
else {
// Some TXT exporters omit the UTF-16 byte-order mark.
var evenNul = 0; var oddNul = 0; var count = Math.min(bytes.length, 256);
for (var i = 0; i < count; i += 1) { if (!bytes[i]) { if (i % 2) { oddNul += 1; } else { evenNul += 1; } } }
if (count > 4 && oddNul > count / 5 && evenNul === 0) { encoding = 'utf-16le'; }
else if (count > 4 && evenNul > count / 5 && oddNul === 0) { encoding = 'utf-16be'; }
}
var text;
try { text = new TextDecoder(encoding, { fatal: true }).decode(bytes); }
catch (error) {
if (encoding !== 'utf-8') { throw previewError('unsupported_encoding', '附件文本编码无法识别'); }
try { text = new TextDecoder('gb18030', { fatal: true }).decode(bytes); }
catch (fallbackError) { throw previewError('unsupported_encoding', '附件文本编码无法识别'); }
}
if (/[\u0000-\u0008\u000e-\u001f]/.test(text)) { throw previewError('invalid_text', '附件不是可预览的文本文件'); }
if (!text.trim()) { throw previewError('empty_document', '附件内容为空'); }
return text.replace(/^\uFEFF/, '');
}
/** Check advertised ZIP sizes before any decompression; ZIP64, encryption, split archives are unsupported. */
function checkZipDirectory(buffer) {
var view = new DataView(buffer);
var end = -1;
for (var i = buffer.byteLength - 22; i >= Math.max(0, buffer.byteLength - 65557); i -= 1) {
if (view.getUint32(i, true) === 0x06054b50 && i + 22 + view.getUint16(i + 20, true) === buffer.byteLength) { end = i; break; }
}
if (end < 0 || view.getUint16(end + 4, true) || view.getUint16(end + 6, true)) { throw previewError('invalid_docx', 'DOCX 文件损坏或格式不受支持'); }
var count = view.getUint16(end + 10, true);
var cursor = view.getUint32(end + 16, true);
var directorySize = view.getUint32(end + 12, true);
if (count > limits.entries || count === 0xffff || cursor + directorySize > end) { throw previewError('docx_too_large', 'DOCX 结构过大,暂时无法预览'); }
var total = 0;
for (var item = 0; item < count; item += 1) {
if (cursor + 46 > end || view.getUint32(cursor, true) !== 0x02014b50) { throw previewError('invalid_docx', 'DOCX 文件结构不完整'); }
var size = view.getUint32(cursor + 24, true);
var flags = view.getUint16(cursor + 8, true);
var compression = view.getUint16(cursor + 10, true);
if ((flags & 1) || (compression !== 0 && compression !== 8)) { throw previewError('encrypted_docx', '暂不支持加密的 DOCX 附件'); }
total += size;
if (size > limits.item || total > limits.total) { throw previewError('docx_too_large', 'DOCX 解压后内容过大,暂时无法预览'); }
cursor += 46 + view.getUint16(cursor + 28, true) + view.getUint16(cursor + 30, true) + view.getUint16(cursor + 32, true);
}
if (cursor !== view.getUint32(end + 16, true) + directorySize) { throw previewError('invalid_docx', 'DOCX 文件结构不完整'); }
}
/** Bound actual inflated bytes as well as directory declarations before docx-preview reads entries. */
async function validateDocx(buffer) {
checkZipDirectory(buffer);
var zip = await JSZip.loadAsync(buffer);
var names = Object.keys(zip.files);
if (!zip.file('word/document.xml') || !zip.file('[Content_Types].xml') || names.length > limits.entries) {
throw previewError('invalid_docx', '附件不是有效的 DOCX 文件');
}
var total = 0;
for (var i = 0; i < names.length; i += 1) {
var entry = zip.files[names[i]];
if (entry.dir) { continue; }
await new Promise(function (resolve, reject) {
var size = 0;
var stream = entry.internalStream('uint8array');
stream.on('data', function (chunk) {
size += chunk.length; total += chunk.length;
if (size > limits.item || total > limits.total) {
stream.pause(); reject(previewError('docx_too_large', 'DOCX 解压后内容过大,暂时无法预览'));
}
});
stream.on('error', function () { reject(previewError('invalid_docx', 'DOCX 文件损坏,无法预览')); });
stream.on('end', resolve);
stream.resume();
});
}
}
/** Remove network-bearing attributes before connecting sanitized document nodes to the visible tree. */
function cleanDocument(root) {
root.querySelectorAll('img').forEach(function (image) {
var src = image.getAttribute('src') || '';
if (!/^(?:blob:|data:image\/(?:png|jpeg|gif|webp|bmp);base64,)/i.test(src)) {
var fallback = document.createElement('span');
fallback.textContent = image.getAttribute('alt') || '';
image.parentNode.replaceChild(fallback, image);
return;
}
image.removeAttribute('srcset');
image.removeAttribute('onload');
image.removeAttribute('onerror');
});
root.querySelectorAll('[href]').forEach(function (link) {
var href = link.getAttribute('href') || '';
if (!/^(https?:\/\/|#)/i.test(href)) { link.removeAttribute('href'); }
link.removeAttribute('target');
link.removeAttribute('download');
link.setAttribute('rel', 'noopener noreferrer');
});
root.querySelectorAll('[style]').forEach(function (element) {
var style = element.getAttribute('style');
if (/(?:url\s*\(|@import|expression\s*\()/i.test(style || '')) { element.removeAttribute('style'); }
});
root.querySelectorAll('style').forEach(function (sheet) {
if (/(?:@import|url\s*\((?!\s*["']?(?:blob:|data:)))/i.test(sheet.textContent || '')) { sheet.remove(); }
});
}
async function render(buffer) {
if (kind === 'txt') {
var pre = document.createElement('pre');
pre.textContent = decodeText(buffer);
content.appendChild(pre);
} else if (kind === 'md') {
var parser = window.markdownit({ html: false, linkify: false, typographer: false, breaks: true });
var html = parser.render(decodeText(buffer));
var fragment = DOMPurify.sanitize(html, { RETURN_DOM_FRAGMENT: true, USE_PROFILES: { html: true }, FORBID_TAGS: ['style', 'form', 'input', 'button', 'iframe', 'object', 'embed', 'video', 'audio'] });
cleanDocument(fragment);
content.appendChild(fragment);
} else {
await validateDocx(buffer);
var body = document.createElement('div');
var styles = document.createElement('div');
await window.docx.renderAsync(buffer, body, styles, {
className: 'docx', inWrapper: true, ignoreWidth: true, ignoreHeight: true,
ignoreFonts: true, breakPages: false, experimental: false, renderChanges: false,
renderHeaders: true, renderFooters: true, renderFootnotes: true, renderEndnotes: true,
renderComments: false, renderAltChunks: false, useBase64URL: false
});
var combined = document.createElement('div');
combined.appendChild(styles); combined.appendChild(body);
var safe = DOMPurify.sanitize(combined, {
RETURN_DOM_FRAGMENT: true, ADD_TAGS: ['style'], ADD_ATTR: ['style'],
FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form', 'input', 'button', 'video', 'audio', 'svg', 'math'],
ALLOWED_URI_REGEXP: /^(?:(?:https?|blob):|data:image\/|#)/i,
ALLOW_DATA_ATTR: false
});
cleanDocument(safe);
var pages = safe.querySelectorAll('section.docx');
var hasText = Array.prototype.some.call(pages, function (page) { return page.textContent.trim().length > 0; });
if (!hasText && !safe.querySelector('img[src]')) { throw previewError('empty_document', 'DOCX 文件没有可预览的内容'); }
content.appendChild(safe);
}
}
/** Wait for visible content and images to settle, then two paint opportunities before allowing reading time. */
async function visibleReady() {
status.hidden = true;
content.hidden = false;
var images = Array.prototype.slice.call(content.querySelectorAll('img[src]'));
await Promise.all(images.map(function (image) {
if (image.complete) { return Promise.resolve(); }
return new Promise(function (resolve) {
var timeout = setTimeout(function () { image.removeAttribute('src'); resolve(); }, 8000);
var complete = function () { clearTimeout(timeout); resolve(); };
image.addEventListener('load', complete, { once: true });
image.addEventListener('error', complete, { once: true });
});
}));
if (document.fonts && document.fonts.ready) { await document.fonts.ready; }
await new Promise(function (resolve) { requestAnimationFrame(function () { requestAnimationFrame(resolve); }); });
if (finished) { return; }
if (content.getBoundingClientRect().height <= 0) { throw previewError('render_failed', '附件内容尚未显示,请重试'); }
finished = true;
post('ready', { height: Math.ceil(Math.max(content.scrollHeight, content.getBoundingClientRect().height)) });
}
// Block every generated link from navigating this trusted local shell.
document.addEventListener('click', function (event) {
var element = event.target instanceof Element ? event.target.closest('a') : null;
if (!element) { return; }
event.preventDefault();
var href = element.getAttribute('href') || '';
if (/^https?:\/\//i.test(href)) {
try {
var url = new URL(href);
if ((url.protocol === 'http:' || url.protocol === 'https:') && !url.username && !url.password) { post('link', { url: url.href }); }
} catch (error) { /* Malformed or unsupported destinations do not leave the document. */ }
} else if (href.charAt(0) === '#') {
var anchor = document.getElementById(href.slice(1));
if (anchor) { anchor.scrollIntoView(); }
}
}, true);
if (!/^[A-Za-z0-9_-]{1,80}$/.test(requestId) || ['docx', 'txt', 'md'].indexOf(kind) === -1) {
fail(previewError('unsupported_type', '暂不支持此附件格式')); return;
}
loadBytes().then(render).then(visibleReady).catch(function (error) {
fail(error.previewCode ? error : previewError('render_failed', '附件无法预览,文件可能已损坏'));
});
}());
@@ -0,0 +1,70 @@
[
{
"name": "docx-preview",
"version": "0.4.1",
"license": "Apache-2.0",
"selectedLicense": "Apache-2.0",
"repository": {
"url": "git+https://github.com/VolodymyrBaydalka/docxjs.git",
"type": "git"
},
"tarball": "https://registry.npmjs.org/docx-preview/-/docx-preview-0.4.1.tgz",
"integrity": "sha512-Dv4g+LeE0swHpPvNC0lAT0YsR5Zq5pAxw7d3vHQ8EChBLgIrqqe9VPL5nVt2HBJap8bEZbXUI0TJob7kBeNU9w==",
"upstreamSource": "dist/docx-preview.min.js",
"sourceSHA256": "c4a133c65a112799e35b143c572dfff9e923a3bf39b5fd3b07a06aa0f8f530c2",
"asset": "docx-preview.min.js",
"assetSHA256": "a0f8943d67e0fddec3d96ff7e1d3829ac63ce5d81598ac6ba2ab808afd520ad6",
"transformation": "esbuild 0.28.2 --target=es2017 --minify --legal-comments=inline"
},
{
"name": "jszip",
"version": "3.10.2",
"license": "(MIT OR GPL-3.0-or-later)",
"selectedLicense": "MIT",
"repository": {
"url": "git+https://github.com/Stuk/jszip.git",
"type": "git"
},
"tarball": "https://registry.npmjs.org/jszip/-/jszip-3.10.2.tgz",
"integrity": "sha512-3l+rb15IOWtUhU0H5MFqES/T6Kh7abYwjosBey/vD6hDt8zoEffkSC5Ws5SGtgVw3gBx2NEbhTeSW1+kWkpyTQ==",
"upstreamSource": "dist/jszip.min.js",
"sourceSHA256": "7f839b2d4688b845c105ebf5d2f9803075f91ea0fe72bdaac176c3a04dd3d2c1",
"asset": "jszip.min.js",
"assetSHA256": "3ba8b2e2542143b2d970056513529b237f6b15ca71ff8a002d7287e813326e7c",
"transformation": "esbuild 0.28.2 --target=es2017 --minify --legal-comments=inline"
},
{
"name": "markdown-it",
"version": "15.0.3",
"license": "MIT",
"selectedLicense": "MIT",
"repository": {
"url": "git+https://github.com/markdown-it/markdown-it.git",
"type": "git"
},
"tarball": "https://registry.npmjs.org/markdown-it/-/markdown-it-15.0.3.tgz",
"integrity": "sha512-+Az7Ojz3iRGu8KYMvJ6xVhvrxP3eE+vEtJX75Ow88XBpcQNV/0lGX5ZynIIBftREo4DC2jsveAMDaeltmm8QvQ==",
"upstreamSource": "dist/browser/markdown-it.umd.min.js",
"sourceSHA256": "391f2aa638e75e6c7859d0a5c5650ef0956722a45998f17e05b83bc655778e1e",
"asset": "markdown-it.min.js",
"assetSHA256": "431b4cc500c46c4935d4e2fc48d16f9b65705e0466d6e5026cf584c480ba303f",
"transformation": "esbuild 0.28.2 --target=es2017 --minify --legal-comments=inline"
},
{
"name": "dompurify",
"version": "3.4.17",
"license": "(MPL-2.0 OR Apache-2.0)",
"selectedLicense": "Apache-2.0",
"repository": {
"url": "git://github.com/cure53/DOMPurify.git",
"type": "git"
},
"tarball": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.17.tgz",
"integrity": "sha512-B/pSlYVHQ58kqISD/yDjuJ1yfzI34m1gF4lAod2bwSRhiN4K5Cl3H8Af7hqB2PmTL911tdEudnnXn5FnhRoz0w==",
"upstreamSource": "dist/purify.min.js",
"sourceSHA256": "cd37898f9782adf54820c413191b5691803f0f137c799d6edcfd38523b4c2c31",
"asset": "purify.min.js",
"assetSHA256": "01de8dd1aba9bfc934898eef69ff980fdcb2c7ec5f7da856cfe785e864a5c443",
"transformation": "esbuild 0.28.2 --target=es2017 --minify --legal-comments=inline"
}
]
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -1,19 +1,26 @@
import SafariServices import SafariServices
import SnapKit import SnapKit
import UIKit import UIKit
import WebKit
/// 正式课程按需阅读:正文分页、附件授权与服务端确认的前台读时。 /// 原生课程信息与附件文件预览,并上报服务端确认的有效前台读时。
@MainActor @MainActor
final class TrainingCourseViewController: TrainingBaseViewController { final class TrainingCourseViewController: TrainingBaseViewController {
private let service: any TrainingDataServing private let service: any TrainingDataServing
private let viewModel: TrainingRemoteReadingViewModel private let viewModel: TrainingRemoteReadingViewModel
private let webView: WKWebView private let validateIdentity: @MainActor @Sendable () -> Bool
private let headerStack = UIStackView() private let documentLoader: any TrainingDocumentLoading
private let toolbar = UIStackView() private let scrollView = UIScrollView()
private let contentStack = UIStackView()
private let metadataStack = UIStackView()
private let taskTitleLabel = TrainingUI.text(size: 17, weight: .semibold)
private let courseNameLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
private let examInfoLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
private let introductionLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
private let attachmentButton = TrainingUI.button("", plain: true)
private let previewView = TrainingDocumentPreviewView()
private var previewHeightConstraint: Constraint?
private var localDocument: TrainingLocalDocument?
private let stepView = TrainingStepView(currentStep: .learning) private let stepView = TrainingStepView(currentStep: .learning)
private let sectionsButton = TrainingUI.button("章节目录", secondary: true)
private let attachmentsButton = TrainingUI.button("课程附件", secondary: true)
private let bottomStack = UIStackView() private let bottomStack = UIStackView()
private let noticeLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary) private let noticeLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
private let actionButton = TrainingUI.button("正在加载课程…") private let actionButton = TrainingUI.button("正在加载课程…")
@@ -22,9 +29,8 @@ final class TrainingCourseViewController: TrainingBaseViewController {
private var readingTask: Task<Void, Never>? private var readingTask: Task<Void, Never>?
private var closingTask: Task<Void, Never>? private var closingTask: Task<Void, Never>?
private var closingGeneration = 0 private var closingGeneration = 0
private var contentNavigation: WKNavigation?
private var appIsActive = UIApplication.shared.applicationState == .active private var appIsActive = UIApplication.shared.applicationState == .active
private var isOpeningResource = false private var isOpeningExternalLink = false
private var contentIsReady = false private var contentIsReady = false
private var contentLoadFailed = false private var contentLoadFailed = false
private var pageIsVisible = false private var pageIsVisible = false
@@ -39,22 +45,22 @@ final class TrainingCourseViewController: TrainingBaseViewController {
/// 当前任务标识,成绩页可复用已有课程页面。 /// 当前任务标识,成绩页可复用已有课程页面。
var taskID: String { viewModel.taskID } var taskID: String { viewModel.taskID }
/// 使用正式数据源读取课程,课程 HTML 禁用脚本执行。 /// 使用正式接口与独立文件下载器读取课程附件,支持测试注入本地文件。
init(taskID: String, service: any TrainingDataServing) { init(taskID: String, service: any TrainingDataServing, documentLoader: any TrainingDocumentLoading = TrainingDocumentLoader()) {
self.service = service self.service = service
self.documentLoader = documentLoader
let session = AppStore.shared.session let session = AppStore.shared.session
let scope = session.accountCachePrefix let scope = session.accountCachePrefix
let scenicID = session.currentScenicId let scenicID = session.currentScenicId
let storeID = session.currentStoreId let storeID = session.currentStoreId
let token = session.token let token = session.token
viewModel = TrainingRemoteReadingViewModel(taskID: taskID, service: service, validateIdentity: { let validate: @MainActor @Sendable () -> Bool = {
let current = AppStore.shared.session let current = AppStore.shared.session
return current.accountCachePrefix == scope && current.currentScenicId == scenicID return current.accountCachePrefix == scope && current.currentScenicId == scenicID
&& current.currentStoreId == storeID && current.token == token && current.currentStoreId == storeID && current.token == token
}) }
let configuration = WKWebViewConfiguration() validateIdentity = validate
configuration.defaultWebpagePreferences.allowsContentJavaScript = false viewModel = TrainingRemoteReadingViewModel(taskID: taskID, service: service, validateIdentity: validate)
webView = WKWebView(frame: .zero, configuration: configuration)
super.init(nibName: nil, bundle: nil) super.init(nibName: nil, bundle: nil)
} }
@@ -65,16 +71,27 @@ final class TrainingCourseViewController: TrainingBaseViewController {
override func setupUI() { override func setupUI() {
view.backgroundColor = TrainingUI.background view.backgroundColor = TrainingUI.background
webView.navigationDelegate = self scrollView.delegate = self
webView.backgroundColor = TrainingUI.background scrollView.accessibilityIdentifier = "training.reading.scroll"
webView.isOpaque = false scrollView.alwaysBounceVertical = true
toolbar.spacing = 10 contentStack.axis = .vertical
toolbar.distribution = .fillEqually contentStack.spacing = 14
toolbar.addArrangedSubview(sectionsButton) metadataStack.axis = .vertical
toolbar.addArrangedSubview(attachmentsButton) metadataStack.spacing = 8
headerStack.axis = .vertical metadataStack.isHidden = true
headerStack.spacing = 20 [taskTitleLabel, courseNameLabel, examInfoLabel, introductionLabel].forEach(metadataStack.addArrangedSubview)
headerStack.addArrangedSubview(toolbar) taskTitleLabel.accessibilityIdentifier = "training.reading.taskTitle"
courseNameLabel.accessibilityIdentifier = "training.reading.courseName"
examInfoLabel.accessibilityIdentifier = "training.reading.examInfo"
introductionLabel.accessibilityIdentifier = "training.reading.introduction"
attachmentButton.contentHorizontalAlignment = .leading
attachmentButton.accessibilityIdentifier = "training.reading.documentPicker"
attachmentButton.showsMenuAsPrimaryAction = true
attachmentButton.isHidden = true
contentStack.addArrangedSubview(metadataStack)
contentStack.addArrangedSubview(attachmentButton)
contentStack.addArrangedSubview(previewView)
stepView.isHidden = true
bottomStack.axis = .vertical bottomStack.axis = .vertical
bottomStack.spacing = 8 bottomStack.spacing = 8
bottomStack.layoutMargins = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12) bottomStack.layoutMargins = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12)
@@ -83,31 +100,69 @@ final class TrainingCourseViewController: TrainingBaseViewController {
bottomStack.addArrangedSubview(noticeLabel) bottomStack.addArrangedSubview(noticeLabel)
bottomStack.addArrangedSubview(actionButton) bottomStack.addArrangedSubview(actionButton)
actionButton.accessibilityIdentifier = "training.reading.action" actionButton.accessibilityIdentifier = "training.reading.action"
sectionsButton.accessibilityIdentifier = "training.reading.sections" view.addSubview(stepView)
attachmentsButton.accessibilityIdentifier = "training.reading.attachments" view.addSubview(scrollView)
view.addSubview(headerStack) scrollView.addSubview(contentStack)
view.addSubview(webView)
view.addSubview(bottomStack) view.addSubview(bottomStack)
previewView.onReady = { [weak self] previewID in
guard let self else { return }
guard self.validateIdentity() else { self.identityChanged(); return }
guard let id = self.viewModel.currentAttachmentID,
self.viewModel.markAttachmentRendered(id: id, previewID: previewID) else { return }
self.contentIsReady = true
self.contentLoadFailed = false
self.applyState()
self.resumeReading()
}
previewView.onFailure = { [weak self] previewID, message in
guard let self, self.viewModel.attachmentPreviewID == previewID,
let id = self.viewModel.currentAttachmentID else { return }
self.viewModel.reportAttachmentFailure(id: id, previewID: previewID, message: message)
self.contentIsReady = false
self.contentLoadFailed = true
self.pauseReading()
self.applyState()
}
previewView.onOpenLink = { [weak self] url in self?.openExternalLink(url) }
previewView.onContentHeightChange = { [weak self] height in
guard let self else { return }
self.previewHeightConstraint?.update(offset: height)
self.view.layoutIfNeeded()
let minimum = -self.scrollView.adjustedContentInset.top
let maximum = max(minimum, self.scrollView.contentSize.height - self.scrollView.bounds.height
+ self.scrollView.adjustedContentInset.bottom)
if self.scrollView.contentOffset.y > maximum {
self.scrollView.setContentOffset(CGPoint(x: 0, y: maximum), animated: false)
}
self.previewView.notifyIfRenderedAndVisible()
if self.isContentVisible { self.resumeReading() }
}
previewView.onScrollToPosition = { [weak self] top in self?.scrollToDocumentPosition(top) }
applyState() applyState()
} }
override func setupConstraints() { override func setupConstraints() {
headerStack.snp.makeConstraints { stepView.snp.makeConstraints {
$0.top.equalTo(view.safeAreaLayoutGuide).offset(8) $0.top.equalTo(view.safeAreaLayoutGuide).offset(8)
$0.leading.trailing.equalToSuperview().inset(13) $0.leading.trailing.equalToSuperview().inset(13)
} }
webView.snp.makeConstraints { scrollView.snp.makeConstraints {
$0.top.equalTo(headerStack.snp.bottom).offset(8) $0.top.equalTo(stepView.snp.bottom).offset(8)
$0.leading.trailing.equalTo(view.safeAreaLayoutGuide) $0.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.bottom.equalTo(bottomStack.snp.top) $0.bottom.equalTo(bottomStack.snp.top)
} }
contentStack.snp.makeConstraints {
$0.edges.equalTo(scrollView.contentLayoutGuide).inset(UIEdgeInsets(top: 14, left: 13, bottom: 14, right: 13))
$0.width.equalTo(scrollView.frameLayoutGuide).offset(-26)
}
previewView.snp.makeConstraints {
previewHeightConstraint = $0.height.equalTo(previewView.preferredContentHeight).constraint
}
bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) } bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
} }
override func bindActions() { override func bindActions() {
actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside) actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside)
sectionsButton.addTarget(self, action: #selector(sectionsTapped), for: .touchUpInside)
attachmentsButton.addTarget(self, action: #selector(attachmentsTapped), for: .touchUpInside)
NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange, NotificationName.userDidLogout] { for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange, NotificationName.userDidLogout] {
@@ -125,9 +180,8 @@ final class TrainingCourseViewController: TrainingBaseViewController {
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self, guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self,
userRequestID == nil else { return } userRequestID == nil else { return }
if viewModel.task == nil { loadCourse() } if viewModel.task == nil { loadCourse() }
else if viewModel.currentSection == nil, let id = viewModel.currentSectionID { selectSection(id) } else if localDocument == nil, let id = viewModel.currentAttachmentID { selectAttachment(id) }
else { else {
if contentNavigation == nil { renderCurrentSection() }
await viewModel.refreshProgress() await viewModel.refreshProgress()
applyState() applyState()
resumeReading() resumeReading()
@@ -145,78 +199,151 @@ final class TrainingCourseViewController: TrainingBaseViewController {
override func onSessionDidExpire() { identityChanged() } override func onSessionDidExpire() { identityChanged() }
private var isContentVisible: Bool { private var isContentVisible: Bool {
pageIsVisible && contentIsReady && !contentLoadFailed && !isOpeningResource && presentedViewController == nil let visibleFrame = previewView.convert(previewView.bounds, to: view).intersection(scrollView.frame)
return pageIsVisible && contentIsReady && viewModel.isAttachmentRendered && previewView.isReady
&& visibleFrame.height >= 40 && !contentLoadFailed && !isOpeningExternalLink && presentedViewController == nil
&& navigationController?.topViewController === self && appIsActive && UIApplication.shared.applicationState == .active && navigationController?.topViewController === self && appIsActive && UIApplication.shared.applicationState == .active
} }
private func loadCourse() { private func loadCourse() {
guard let request = beginUserRequest(showsLoading: true) else { return } guard let request = beginUserRequest(showsLoading: true) else { return }
resetDocument()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await performUserRequest(request) {
await self.viewModel.load()
await self.loadSelectedDocument()
}
self.applyMetadata()
self.applyState()
}
}
private func selectAttachment(_ id: String) {
guard let request = beginUserRequest(showsLoading: true) else { return }
resetDocument()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await performUserRequest(request) {
await self.viewModel.selectAttachment(id: id)
await self.loadSelectedDocument()
}
self.applyMetadata()
self.applyState()
}
}
private func resetDocument() {
pauseReading() pauseReading()
contentIsReady = false contentIsReady = false
contentLoadFailed = false contentLoadFailed = false
contentNavigation = nil previewView.showStatus("正在加载附件…")
contentTask = Task { @MainActor [weak self] in localDocument?.removeTemporaryFile()
localDocument = nil
scrollView.setContentOffset(CGPoint(x: 0, y: -scrollView.adjustedContentInset.top), animated: false)
}
private func scrollToDocumentPosition(_ top: CGFloat) {
view.layoutIfNeeded()
let target = previewView.convert(CGPoint(x: 0, y: top), to: scrollView).y - scrollView.adjustedContentInset.top
let minimum = -scrollView.adjustedContentInset.top
let maximum = max(minimum, scrollView.contentSize.height - scrollView.bounds.height + scrollView.adjustedContentInset.bottom)
scrollView.setContentOffset(CGPoint(x: 0, y: min(maximum, max(minimum, target))), animated: true)
}
private func loadSelectedDocument() async {
guard !Task.isCancelled, pageIsVisible, !viewModel.isInvalidated else { return }
applyMetadata()
guard let attachment = viewModel.currentAttachment, let link = viewModel.currentAttachmentLink,
let previewID = viewModel.attachmentPreviewID else {
contentLoadFailed = viewModel.errorMessage != nil
previewView.showStatus(viewModel.errorMessage ?? "暂未上传课程附件")
return
}
do {
let document = try await documentLoader.load(attachment: attachment, link: link)
guard !Task.isCancelled, pageIsVisible, !viewModel.isInvalidated,
viewModel.attachmentPreviewID == previewID else { document.removeTemporaryFile(); return }
guard validateIdentity() else {
document.removeTemporaryFile()
identityChanged()
return
}
localDocument = document
previewView.show(document, requestID: previewID)
} catch {
guard !Task.isCancelled, pageIsVisible, !viewModel.isInvalidated,
viewModel.attachmentPreviewID == previewID else { return }
contentLoadFailed = true
viewModel.reportAttachmentFailure(id: attachment.id, previewID: previewID, message: error.localizedDescription)
previewView.showStatus(error.localizedDescription)
}
}
private func applyMetadata() {
guard let task = viewModel.task?.summary, let course = viewModel.course else { return }
metadataStack.isHidden = false
taskTitleLabel.text = task.title
courseNameLabel.text = course.title
courseNameLabel.isHidden = course.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
examInfoLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格" : "仅学习"
introductionLabel.text = course.introduction
introductionLabel.isHidden = course.introduction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
attachmentButton.isHidden = viewModel.currentAttachment == nil
var configuration = attachmentButton.configuration
configuration?.title = viewModel.currentAttachment?.name
let canSwitch = viewModel.attachments.count > 1 || viewModel.hasMoreAttachments
configuration?.image = canSwitch ? UIImage(systemName: "chevron.down") : nil
configuration?.imagePlacement = .trailing
configuration?.imagePadding = 8
configuration?.contentInsets = .zero
configuration?.titleLineBreakMode = .byWordWrapping
attachmentButton.configuration = configuration
attachmentButton.isUserInteractionEnabled = canSwitch && userRequestID == nil
var actions = viewModel.attachments.map { attachment in
UIAction(title: attachment.name, state: attachment.id == viewModel.currentAttachmentID ? .on : .off) { [weak self] _ in
guard attachment.id != self?.viewModel.currentAttachmentID else { return }
self?.selectAttachment(attachment.id)
}
}
if viewModel.hasMoreAttachments {
actions.append(UIAction(title: "加载更多附件") { [weak self] _ in self?.loadMoreAttachments() })
}
attachmentButton.menu = UIMenu(children: actions)
}
private func loadMoreAttachments() {
guard let request = beginUserRequest(showsLoading: true) else { return }
Task { @MainActor [weak self] in
guard let self else { return } guard let self else { return }
await performUserRequest(request) { await self.viewModel.load() } await performUserRequest(request) { await self.viewModel.loadAttachments(loadMore: true) }
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return } applyMetadata()
renderCurrentSection() if let message = viewModel.attachmentListErrorMessage { showToast(message) }
applyState()
} }
} }
private func selectSection(_ id: String) {
guard let request = beginUserRequest(showsLoading: !viewModel.isSectionCached(id: id)) else { return }
isOpeningResource = false
pauseReading()
contentIsReady = false
contentLoadFailed = false
contentNavigation = nil
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await performUserRequest(request) { await self.viewModel.selectSection(id: id) }
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
renderCurrentSection()
applyState()
}
}
private func renderCurrentSection() {
guard !viewModel.isInvalidated, let task = viewModel.task?.summary,
let course = viewModel.course, let section = viewModel.currentSection else { return }
let metadata = task.mode == .exam
? "学习 + 考试 · \(course.sectionCount) 节 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格"
: "仅学习 · \(course.sectionCount) 节"
contentNavigation = webView.loadHTMLString("""
<!doctype html><html lang="zh-CN"><head><meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
<style>
*{box-sizing:border-box}body{font:15px -apple-system,BlinkMacSystemFont,sans-serif;color:#34435b;background:#f5f8fc;margin:0;padding:0 13px 14px;line-height:1.95;overflow-wrap:anywhere}
h1{font-size:17px;font-weight:600;line-height:1.6;color:#172033;margin:14px 0 6px}h2{font-size:15.5px;font-weight:600;color:#172033;margin:0 0 10px}img{max-width:100%;height:auto}table{max-width:100%;display:block;overflow:auto}a{color:#2379ff}
.muted{font-size:12.5px;color:#8491a6;line-height:1.65;margin:6px 0}.reading{background:white;border:1px solid #e3ebf5;border-radius:11px;padding:14px;margin-top:14px}
</style></head><body>
<h1>\(escape(task.title))</h1><p class='muted'>\(escape(course.title))</p><p class='muted'>\(metadata)</p><p class='muted'>\(escape(course.introduction))</p>
<p class='muted'>第 \(section.order) / \(course.sectionCount) 节</p><div class='reading'><h2>\(escape(section.title))</h2>\(section.contentHTML)</div></body></html>
""", baseURL: nil)
}
private func escape(_ text: String) -> String {
text.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
}
private func applyState() { private func applyState() {
guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return } guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return }
if let task = viewModel.task?.summary { if let task = viewModel.task?.summary {
stepView.configure(mode: task.mode) stepView.configure(mode: task.mode)
if stepView.superview == nil { headerStack.addArrangedSubview(stepView) } stepView.isHidden = false
} }
let canInteract = userRequestID == nil let canInteract = userRequestID == nil
sectionsButton.isUserInteractionEnabled = canInteract
attachmentsButton.isUserInteractionEnabled = canInteract
actionButton.isUserInteractionEnabled = canInteract actionButton.isUserInteractionEnabled = canInteract
attachmentButton.isUserInteractionEnabled = canInteract && (viewModel.attachments.count > 1 || viewModel.hasMoreAttachments)
guard canInteract else { return } guard canInteract else { return }
sectionsButton.isEnabled = !viewModel.sections.isEmpty if contentLoadFailed || viewModel.attachmentErrorMessage != nil || viewModel.task == nil {
attachmentsButton.isEnabled = (viewModel.course?.attachmentCount ?? 0) > 0 noticeLabel.text = viewModel.errorMessage ?? "正在加载课程…"
setActionTitle(contentLoadFailed || viewModel.errorMessage != nil ? "重新加载附件" : "正在加载课程…")
actionButton.isEnabled = !viewModel.isLoading && (contentLoadFailed || viewModel.errorMessage != nil)
return
}
if viewModel.hasLoadedAttachments && viewModel.attachments.isEmpty {
noticeLabel.text = "暂未上传课程附件"
setActionTitle("返回培训中心")
actionButton.isEnabled = true
return
}
if let progress = viewModel.progress, progress.readingCompleted { if let progress = viewModel.progress, progress.readingCompleted {
noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成" noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成"
if viewModel.task?.summary.mode == .exam && progress.canStartExam { setActionTitle("开始考试") } if viewModel.task?.summary.mode == .exam && progress.canStartExam { setActionTitle("开始考试") }
@@ -226,10 +353,10 @@ final class TrainingCourseViewController: TrainingBaseViewController {
readingTimer = nil readingTimer = nil
return return
} }
if contentLoadFailed || viewModel.currentSection == nil { if !contentIsReady {
noticeLabel.text = viewModel.errorMessage ?? (contentLoadFailed ? "课程正文加载失败,请重试" : "正在加载课程…") noticeLabel.text = "正在打开课程附件…"
setActionTitle(contentLoadFailed || viewModel.errorMessage != nil ? "重新加载课程" : "正在加载课程…") setActionTitle("正在加载附件…")
actionButton.isEnabled = !viewModel.isLoading && (contentLoadFailed || viewModel.errorMessage != nil) actionButton.isEnabled = false
return return
} }
if !viewModel.canStudy { if !viewModel.canStudy {
@@ -345,28 +472,36 @@ final class TrainingCourseViewController: TrainingBaseViewController {
contentTask?.cancel() contentTask?.cancel()
readingTask?.cancel() readingTask?.cancel()
closingTask?.cancel() closingTask?.cancel()
contentNavigation = nil previewView.showStatus("")
localDocument?.removeTemporaryFile()
localDocument = nil
viewModel.invalidate() viewModel.invalidate()
leaveUnavailableCourse() leaveUnavailableCourse()
} }
@objc private func actionTapped() { @objc private func actionTapped() {
guard userRequestID == nil else { return } guard userRequestID == nil else { return }
if let progress = viewModel.progress, progress.readingCompleted { if contentLoadFailed || viewModel.attachmentErrorMessage != nil || viewModel.task == nil {
if let id = viewModel.currentAttachmentID { selectAttachment(id) }
else { loadCourse() }
} else if viewModel.attachments.isEmpty { returnToCenter() }
else if let progress = viewModel.progress, progress.readingCompleted {
pauseReading() pauseReading()
if viewModel.task?.summary.mode == .exam && progress.canStartExam { if viewModel.task?.summary.mode == .exam && progress.canStartExam {
navigationController?.pushViewController(TrainingExamViewController(taskID: taskID, service: service), animated: true) navigationController?.pushViewController(TrainingExamViewController(taskID: taskID, service: service), animated: true)
} else { returnToCenter() } } else { returnToCenter() }
} else if contentLoadFailed || viewModel.currentSection == nil {
if let sectionID = viewModel.currentSectionID { selectSection(sectionID) }
else { loadCourse() }
} else if !viewModel.canStudy { returnToCenter() } } else if !viewModel.canStudy { returnToCenter() }
else if viewModel.readingErrorMessage != nil { else if viewModel.readingErrorMessage != nil { resumeReading(retrying: true) }
resumeReading(retrying: true) else if viewModel.errorMessage != nil { loadCourse() }
} else if viewModel.errorMessage != nil {
if let sectionID = viewModel.currentSectionID { selectSection(sectionID) }
else { loadCourse() }
} }
private func openExternalLink(_ url: URL) {
guard TrainingDocumentLoader.isAllowed(url), presentedViewController == nil else { return }
isOpeningExternalLink = true
pauseReading()
let controller = SFSafariViewController(url: url)
controller.delegate = self
present(controller, animated: true)
} }
private func returnToCenter() { private func returnToCenter() {
@@ -378,251 +513,34 @@ final class TrainingCourseViewController: TrainingBaseViewController {
private func leaveUnavailableCourse() { private func leaveUnavailableCourse() {
readingTimer?.invalidate() readingTimer?.invalidate()
readingTimer = nil readingTimer = nil
contentNavigation = nil previewView.showStatus("")
webView.stopLoading() localDocument?.removeTemporaryFile()
webView.loadHTMLString("", baseURL: nil) localDocument = nil
if let presentedViewController { if let presentedViewController {
presentedViewController.dismiss(animated: false) { [weak self] in self?.returnToCenter() } presentedViewController.dismiss(animated: false) { [weak self] in self?.returnToCenter() }
} else { returnToCenter() } } else { returnToCenter() }
} }
@objc private func sectionsTapped() { deinit { localDocument?.removeTemporaryFile() }
guard userRequestID == nil, !viewModel.sections.isEmpty else { return }
isOpeningResource = true
pauseReading()
let picker = TrainingCoursePickerViewController(title: "章节目录", rows: sectionRows(), hasMore: viewModel.hasMoreSections,
selectedID: viewModel.currentSectionID, select: { [weak self] id in self?.selectSection(id) },
loadMore: { [weak self] in
guard let self else { return ([], false) }
guard viewModel.hasMoreSections, let request = beginUserRequest(showsLoading: true) else {
return (sectionRows(), viewModel.hasMoreSections)
}
await performUserRequest(request) { await self.viewModel.loadMoreSections() }
applyState()
if let error = viewModel.errorMessage { showToast(error) }
return (sectionRows(), viewModel.hasMoreSections)
}, close: { [weak self] in self?.finishResourcePresentation() })
presentPicker(picker)
}
private func sectionRows() -> [TrainingCoursePickerRow] { private func finishExternalLinkPresentation() {
viewModel.sections.map { TrainingCoursePickerRow(id: $0.id, title: "\($0.order). \($0.title)") } isOpeningExternalLink = false
}
@objc private func attachmentsTapped() {
guard let request = beginUserRequest(showsLoading: !viewModel.hasLoadedAttachments) else { return }
isOpeningResource = true
pauseReading()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await performUserRequest(request) { await self.viewModel.loadAttachments() }
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
if viewModel.isInvalidated { applyState(); return }
if let error = viewModel.errorMessage { isOpeningResource = false; showToast(error); applyState(); return }
let picker = TrainingCoursePickerViewController(title: "课程附件", rows: attachmentRows(), hasMore: viewModel.hasMoreAttachments,
select: { [weak self] id in self?.openAttachment(id) }, loadMore: { [weak self] in
guard let self else { return ([], false) }
guard viewModel.hasMoreAttachments, let request = beginUserRequest(showsLoading: true) else {
return (attachmentRows(), viewModel.hasMoreAttachments)
}
await performUserRequest(request) { await self.viewModel.loadAttachments(loadMore: true) }
applyState()
if let error = viewModel.errorMessage { showToast(error) }
return (attachmentRows(), viewModel.hasMoreAttachments)
}, close: { [weak self] in self?.finishResourcePresentation() })
presentPicker(picker)
}
}
private func attachmentRows() -> [TrainingCoursePickerRow] {
viewModel.attachments.map { TrainingCoursePickerRow(id: $0.id, title: $0.name) }
}
private func presentPicker(_ picker: TrainingCoursePickerViewController) {
let navigation = UINavigationController(rootViewController: picker)
navigation.modalPresentationStyle = .pageSheet
navigation.sheetPresentationController?.detents = [.medium(), .large()]
navigation.sheetPresentationController?.prefersGrabberVisible = true
navigation.presentationController?.delegate = picker
present(navigation, animated: true)
}
private func openAttachment(_ id: String) {
guard let request = beginUserRequest(showsLoading: true) else { return }
isOpeningResource = true
pauseReading()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
let link = await performUserRequest(request) { await self.viewModel.authorizeAttachment(id: id) }
guard pageIsVisible, navigationController?.topViewController === self, !Task.isCancelled else { return }
guard let link else {
isOpeningResource = false
if let error = viewModel.errorMessage { showToast(error) }
applyState()
return
}
let controller = SFSafariViewController(url: link.url)
controller.delegate = self
present(controller, animated: true)
}
}
private func finishResourcePresentation() {
isOpeningResource = false
resumeReading() resumeReading()
} }
} }
extension TrainingCourseViewController: WKNavigationDelegate { extension TrainingCourseViewController: UIScrollViewDelegate {
/// 当前正文渲染完成且页面可见后才开始有效阅读。 /// 原生课程信息滚动到覆盖整个预览区时暂停,文件再次可见时才恢复。
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { func scrollViewDidScroll(_ scrollView: UIScrollView) {
guard let contentNavigation, navigation === contentNavigation else { return } previewView.notifyIfRenderedAndVisible()
contentIsReady = true if isContentVisible { resumeReading() }
contentLoadFailed = false else if viewModel.isReading { pauseReading() }
applyState()
resumeReading()
}
/// 正文初始加载失败时停止计时,保留重试入口。
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
/// 正文导航失败时不把失败页面停留计入学习。
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
/// 仅允许本机 HTML 初始加载;用户点击的 HTTPS 链接交给 Safari。
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .other, navigationAction.request.url?.absoluteString == "about:blank" {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
guard navigationAction.navigationType == .linkActivated,
let url = navigationAction.request.url, url.scheme?.lowercased() == "https", url.host != nil else { return }
isOpeningResource = true
pauseReading()
let controller = SFSafariViewController(url: url)
controller.delegate = self
present(controller, animated: true)
} }
} }
extension TrainingCourseViewController: SFSafariViewControllerDelegate { extension TrainingCourseViewController: SFSafariViewControllerDelegate {
/// 关闭外部链接后,仅在正文重新可见时建立新的阅读片段。 /// 关闭外部链接后,仅在正文重新可见时建立新的阅读片段。
func safariViewControllerDidFinish(_ controller: SFSafariViewController) { func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true) { [weak self] in self?.finishResourcePresentation() } controller.dismiss(animated: true) { [weak self] in self?.finishExternalLinkPresentation() }
} }
} }
/// 目录或附件选择器的一行展示数据,不携带业务行为。
private struct TrainingCoursePickerRow: Hashable {
let id: String
let title: String
}
/// 原生可滚动资源选择器;用户按需加载更多,选中或关闭后明确通知课程页面。
@MainActor
private final class TrainingCoursePickerViewController: UIViewController, UITableViewDelegate, UIAdaptivePresentationControllerDelegate {
/// 差异化列表中的资源项与主动分页入口。
private enum Item: Hashable { case resource(String), more }
private var rows: [TrainingCoursePickerRow]
private var hasMore: Bool
private let selectedID: String?
private let select: (String) -> Void
private let loadMore: () async -> ([TrainingCoursePickerRow], Bool)
private let close: () -> Void
private let tableView = UITableView(frame: .zero, style: .insetGrouped)
private var dataSource: UITableViewDiffableDataSource<Int, Item>!
private var isLoadingMore = false
/// 使用页面提供的展示行、明确选择动作与分页动作构造选择器。
init(title: String, rows: [TrainingCoursePickerRow], hasMore: Bool, selectedID: String? = nil,
select: @escaping (String) -> Void, loadMore: @escaping () async -> ([TrainingCoursePickerRow], Bool), close: @escaping () -> Void) {
self.rows = rows
self.hasMore = hasMore
self.selectedID = selectedID
self.select = select
self.loadMore = loadMore
self.close = close
super.init(nibName: nil, bundle: nil)
self.title = title
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = TrainingUI.background
navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak self] _ in
guard let self else { return }
dismiss(animated: true, completion: close)
})
tableView.delegate = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 52
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "resource")
view.addSubview(tableView)
tableView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
dataSource = UITableViewDiffableDataSource<Int, Item>(tableView: tableView) { [weak self] table, indexPath, item in
guard let self else { return nil }
let cell = table.dequeueReusableCell(withIdentifier: "resource", for: indexPath)
var content = UIListContentConfiguration.cell()
switch item {
case .resource(let id):
content.text = rows.first(where: { $0.id == id })?.title
content.textProperties.numberOfLines = 0
cell.accessoryType = id == selectedID ? .checkmark : .none
case .more:
content.text = isLoadingMore ? "正在加载…" : "加载更多"
content.textProperties.color = TrainingUI.primary
cell.accessoryType = .none
}
cell.contentConfiguration = content
return cell
}
applyRows()
}
private func applyRows() {
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
snapshot.appendSections([0])
snapshot.appendItems(rows.map { .resource($0.id) })
if hasMore { snapshot.appendItems([.more]) }
if hasMore, dataSource.snapshot().indexOfItem(.more) != nil { snapshot.reconfigureItems([.more]) }
dataSource.apply(snapshot, animatingDifferences: true)
}
/// 选择后等待模态页面完全关闭,再让课程加载正文或授权附件。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard !isLoadingMore, let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .resource(let id): dismiss(animated: true) { [select] in select(id) }
case .more:
isLoadingMore = true
applyRows()
Task { @MainActor [weak self] in
guard let self else { return }
(rows, hasMore) = await loadMore()
isLoadingMore = false
applyRows()
}
}
}
/// 下拉关闭选择器时恢复正文可见性,由课程页面重新核验计时条件。
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { close() }
}
@@ -0,0 +1,335 @@
import PDFKit
import SnapKit
import UIKit
import WebKit
/// 白色卡片内的文件预览:PDF 使用 PDFKit,其他格式使用离线、受控的 WebView。
@MainActor
final class TrainingDocumentPreviewView: UIView {
/// 当前票据的文件已真正进入可阅读状态。
var onReady: ((UUID) -> Void)?
/// 当前票据的文件无法渲染,交由课程页面停止计时并展示重试。
var onFailure: ((UUID, String) -> Void)?
/// 用户明确点击文档外部链接。
var onOpenLink: ((URL) -> Void)?
/// 文档排版高度变化时通知课程页更新卡片高度,由外层页面统一滚动。
var onContentHeightChange: ((CGFloat) -> Void)?
/// 文档目录锚点的位置,由课程页在外层滚动区域中定位。
var onScrollToPosition: ((CGFloat) -> Void)?
/// 包含卡片边框的完整内容高度,加载和错误状态使用紧凑占位高度。
private(set) var preferredContentHeight: CGFloat = 160
/// 当前文件是否已渲染成功,供页面与布局测试查询。
private(set) var isReady = false
override var isHidden: Bool {
didSet { if !isHidden { pdfView.notifyIfRenderedAndVisible() } }
}
private let resourceHandler = TrainingDocumentResourceHandler()
private let messageProxy = TrainingDocumentMessageProxy()
private let pdfView = TrainingPDFDocumentView()
private let statusLabel = TrainingUI.text("正在加载附件…", size: 13, color: TrainingUI.muted)
private var currentID: UUID?
private var currentNavigation: WKNavigation?
private var renderWatchdog: Task<Void, Never>?
private lazy var webView: WKWebView = {
let configuration = WKWebViewConfiguration()
configuration.websiteDataStore = .nonPersistent()
configuration.setURLSchemeHandler(resourceHandler, forURLScheme: "training-document")
configuration.userContentController.add(messageProxy, name: "trainingDocument")
configuration.userContentController.addUserScript(WKUserScript(source: Self.pageLayoutScript,
injectionTime: .atDocumentStart, forMainFrameOnly: true))
let view = WKWebView(frame: .zero, configuration: configuration)
view.navigationDelegate = self
view.isOpaque = false
view.backgroundColor = .white
view.scrollView.backgroundColor = .white
view.scrollView.isScrollEnabled = false
view.scrollView.bounces = false
view.scrollView.contentInsetAdjustmentBehavior = .never
return view
}()
/// 创建独立文档沙箱,不共享登录 Cookie、业务脚本或 JS Bridge。
init() {
super.init(frame: .zero)
backgroundColor = .white
layer.cornerRadius = 11
layer.borderWidth = 1
layer.borderColor = TrainingUI.border.cgColor
clipsToBounds = true
accessibilityIdentifier = "training.reading.preview"
pdfView.backgroundColor = .white
pdfView.onContentHeightChange = { [weak self] height in
guard let self, self.currentID != nil else { return }
self.updateContentHeight(height)
}
pdfView.onOpenLink = { [weak self] url in
if TrainingDocumentLoader.isAllowed(url) { self?.onOpenLink?(url) }
}
statusLabel.textAlignment = .center
[pdfView, webView, statusLabel].forEach(addSubview)
pdfView.snp.makeConstraints { $0.edges.equalToSuperview().inset(1) }
webView.snp.makeConstraints { $0.edges.equalToSuperview().inset(1) }
statusLabel.snp.makeConstraints { $0.center.equalToSuperview(); $0.leading.trailing.equalToSuperview().inset(20) }
messageProxy.owner = self
showStatus("正在加载附件…")
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 加载中、空态和失败态均停止显示旧文件。
func showStatus(_ message: String) {
renderWatchdog?.cancel()
renderWatchdog = nil
currentID = nil
currentNavigation = nil
isReady = false
setPreferredContentHeight(160)
webView.stopLoading()
resourceHandler.clear()
webView.isHidden = true
pdfView.isHidden = true
pdfView.onVisiblePageDrawn = nil
pdfView.document = nil
statusLabel.text = message
statusLabel.isHidden = false
}
/// 外层页面滚动后重新检查 PDF 已绘制页面是否真正进入阅读区域。
func notifyIfRenderedAndVisible() { pdfView.notifyIfRenderedAndVisible() }
/// 用唯一票据隔离同一附件重试时迟到的文档事件。
func show(_ document: TrainingLocalDocument, requestID: UUID) {
showStatus("正在打开附件…")
currentID = requestID
if document.kind == .pdf {
guard let pdf = PDFDocument(url: document.fileURL), !pdf.isLocked, pdf.pageCount > 0 else {
fail(requestID, message: TrainingDocumentError.invalidFile.localizedDescription)
return
}
pdfView.onVisiblePageDrawn = { [weak self, weak pdf] in
guard let self, let pdf, self.currentID == requestID,
self.pdfView.document === pdf, self.window != nil, !self.pdfView.isHidden else { return }
self.complete(requestID)
}
pdfView.document = pdf
pdfView.isHidden = false
layoutIfNeeded()
pdfView.layoutIfNeeded()
} else {
resourceHandler.configure(document: document, requestID: requestID)
webView.isHidden = false
let value = "training-document://preview/index.html?type=\(document.kind.rawValue)&requestId=\(requestID.uuidString)"
currentNavigation = webView.load(URLRequest(url: URL(string: value)!))
renderWatchdog = Task { @MainActor [weak self] in
do { try await Task.sleep(for: .seconds(40)) } catch { return }
self?.fail(requestID, message: "附件预览超时,请重试")
}
}
}
fileprivate func receive(_ message: WKScriptMessage) {
guard message.frameInfo.isMainFrame,
message.frameInfo.securityOrigin.protocol == "training-document",
message.frameInfo.securityOrigin.host == "preview",
let payload = message.body as? [String: Any], let rawID = payload["requestId"] as? String,
let id = UUID(uuidString: rawID), currentID == id else { return }
switch payload["type"] as? String {
case "ready":
if let height = payload["height"] as? NSNumber { updateContentHeight(CGFloat(height.doubleValue)) }
complete(id)
case "layout":
if let height = payload["height"] as? NSNumber { updateContentHeight(CGFloat(height.doubleValue)) }
case "scroll":
if isReady, let value = payload["top"] as? NSNumber {
let top = CGFloat(value.doubleValue)
if top.isFinite, top >= 0 { onScrollToPosition?(min(top + 1, preferredContentHeight)) }
}
case "error":
let message = (payload["message"] as? String).flatMap { $0.isEmpty || $0.count > 200 ? nil : $0 }
fail(id, message: message ?? "附件预览失败,文件可能已损坏或格式不受支持,请重试")
case "link":
if let value = payload["url"] as? String, let url = URL(string: value), TrainingDocumentLoader.isAllowed(url) { onOpenLink?(url) }
default: break
}
}
private func updateContentHeight(_ height: CGFloat) {
guard height.isFinite, height > 0 else { return }
setPreferredContentHeight(max(82, ceil(height) + 2))
}
private func setPreferredContentHeight(_ height: CGFloat) {
guard abs(height - preferredContentHeight) >= 1 else { return }
preferredContentHeight = height
onContentHeightChange?(height)
}
private func complete(_ id: UUID) {
guard currentID == id, !isReady else { return }
renderWatchdog?.cancel()
renderWatchdog = nil
isReady = true
statusLabel.isHidden = true
onReady?(id)
}
private func fail(_ id: UUID, message: String) {
guard currentID == id else { return }
currentID = nil
currentNavigation = nil
renderWatchdog?.cancel()
renderWatchdog = nil
webView.stopLoading()
resourceHandler.clear()
isReady = false
setPreferredContentHeight(160)
statusLabel.text = message
statusLabel.isHidden = false
webView.isHidden = true
pdfView.isHidden = true
onFailure?(id, message)
}
// 只注入 iOS 宿主:观察内容本身而非 WebView 视口,短文件才能正确缩回。
// 锚点交给外层 UIScrollView,避免 scrollIntoView 在禁用手势后仍改变内部偏移。
private static let pageLayoutScript = """
(function () {
'use strict';
var requestId = new URLSearchParams(window.location.search).get('requestId');
function post(type, fields) {
var message = Object.assign({ type: type, requestId: requestId }, fields);
window.webkit.messageHandlers.trainingDocument.postMessage(message);
}
document.addEventListener('click', function (event) {
var link = event.target instanceof Element ? event.target.closest('a') : null;
var href = link && link.getAttribute('href');
if (!href || href.charAt(0) !== '#') { return; }
event.preventDefault();
event.stopImmediatePropagation();
var identifier;
try { identifier = decodeURIComponent(href.slice(1)); } catch (_) { return; }
var target = document.getElementById(identifier);
if (target) { post('scroll', { top: Math.max(0, target.getBoundingClientRect().top + window.scrollY) }); }
}, true);
function observe() {
var content = document.getElementById('document');
if (!content) { return; }
var scheduled = false;
var previousHeight = 0;
function measure() {
scheduled = false;
if (content.hidden) { return; }
var height = Math.ceil(Math.max(content.scrollHeight, content.getBoundingClientRect().height));
if (height > 0 && height !== previousHeight) {
previousHeight = height;
post('layout', { height: height });
}
}
function schedule() {
if (scheduled) { return; }
scheduled = true;
requestAnimationFrame(measure);
}
new ResizeObserver(schedule).observe(content);
new MutationObserver(schedule).observe(content, { attributes: true, attributeFilter: ['hidden'] });
window.addEventListener('resize', schedule);
schedule();
}
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', observe, { once: true }); }
else { observe(); }
}());
"""
}
extension TrainingDocumentPreviewView: WKNavigationDelegate {
/// WebView 只加载 App 提供的本地预览壳,文档不能直接导航到远端网页。
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let url = navigationAction.request.url
let local = url?.scheme == "training-document" && url?.host == "preview" && url?.path == "/index.html"
decisionHandler(local ? .allow : .cancel)
if navigationAction.navigationType == .linkActivated, let url, TrainingDocumentLoader.isAllowed(url) { onOpenLink?(url) }
}
/// 壳加载失败不会触发阅读成功事件。
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
guard let currentNavigation, navigation === currentNavigation, (error as NSError).code != NSURLErrorCancelled else { return }
if let id = currentID { fail(id, message: "附件预览加载失败,请重试") }
}
/// 当前壳已开始导航后失败,同样撤销预览状态。
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
guard let currentNavigation, navigation === currentNavigation, (error as NSError).code != NSURLErrorCancelled else { return }
if let id = currentID { fail(id, message: "附件预览加载失败,请重试") }
}
/// 文档渲染进程退出时立即撤销可阅读状态。
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
if currentNavigation != nil, !webView.isHidden, let id = currentID { fail(id, message: "附件预览已中断,请重试") }
}
}
/// 弱引用消息转发,避免 WKUserContentController 长期持有预览视图。
@MainActor
private final class TrainingDocumentMessageProxy: NSObject, WKScriptMessageHandler {
weak var owner: TrainingDocumentPreviewView?
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { owner?.receive(message) }
}
/// 仅响应当前票据的私有文件和固定 App 资源,不代理任何远程地址。
@MainActor
private final class TrainingDocumentResourceHandler: NSObject, WKURLSchemeHandler {
private var document: TrainingLocalDocument?
private var requestID: UUID?
private var active: Set<ObjectIdentifier> = []
func configure(document: TrainingLocalDocument, requestID: UUID) { self.document = document; self.requestID = requestID }
func clear() { document = nil; requestID = nil; active.removeAll() }
func webView(_ webView: WKWebView, start urlSchemeTask: any WKURLSchemeTask) {
let token = ObjectIdentifier(urlSchemeTask)
guard let url = urlSchemeTask.request.url, url.scheme == "training-document", url.host == "preview" else {
urlSchemeTask.didFailWithError(URLError(.unsupportedURL)); return
}
let file: URL?
let mime: String
if let requestID, url.path == "/document/\(requestID.uuidString)/file", let document {
file = document.fileURL
mime = "application/octet-stream"
} else {
let path = url.path.dropFirst()
guard !path.contains(".."), !path.hasPrefix("/"), !path.isEmpty,
let root = Bundle.main.url(forResource: "TrainingDocumentPreview", withExtension: nil) else {
urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist)); return
}
file = root.appendingPathComponent(String(path))
switch (String(path) as NSString).pathExtension {
case "html": mime = "text/html"
case "js": mime = "text/javascript"
case "css": mime = "text/css"
default: urlSchemeTask.didFailWithError(URLError(.unsupportedURL)); return
}
}
guard let file else { urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist)); return }
active.insert(token)
Task { @MainActor [weak self] in
let result = await Task.detached(priority: .userInitiated) { Result { try Data(contentsOf: file) } }.value
guard let self, self.active.remove(token) != nil else { return }
switch result {
case .success(let data):
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [
"Content-Type": "\(mime); charset=utf-8", "Cache-Control": "no-store", "Access-Control-Allow-Origin": "*"
])!
urlSchemeTask.didReceive(response)
urlSchemeTask.didReceive(data)
urlSchemeTask.didFinish()
case .failure(let error): urlSchemeTask.didFailWithError(error)
}
}
}
func webView(_ webView: WKWebView, stop urlSchemeTask: any WKURLSchemeTask) { active.remove(ObjectIdentifier(urlSchemeTask)) }
}
@@ -0,0 +1,247 @@
import PDFKit
import UIKit
/// 将 PDF 按页面宽度展开为原生绘制视图,由课程页统一负责纵向滚动。
@MainActor
final class TrainingPDFDocumentView: UIView {
/// 当前附件;替换文档时清除旧页面和绘制状态。
var document: PDFDocument? {
didSet { rebuildPages() }
}
/// 至少一个实际完成绘制的页面进入课程页可见区域。
var onVisiblePageDrawn: (() -> Void)?
/// 用户点击 PDF 中的 URL 注解,由宿主校验并打开。
var onOpenLink: ((URL) -> Void)?
/// 按当前宽度排版后的全部页面高度,供宿主更新白色卡片约束。
var onContentHeightChange: ((CGFloat) -> Void)?
private var pageViews: [TrainingPDFPageDrawingView] = []
private var contentHeight: CGFloat = 0
private var lastLayoutWidth: CGFloat = 0
private let pageSpacing: CGFloat = 12
override var intrinsicContentSize: CGSize {
CGSize(width: UIView.noIntrinsicMetric, height: contentHeight)
}
override var isHidden: Bool {
didSet { if !isHidden { notifyIfRenderedAndVisible() } }
}
/// 创建不含内部滚动视图的 PDF 页面容器。
init() {
super.init(frame: .zero)
backgroundColor = .white
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func layoutSubviews() {
super.layoutSubviews()
let width = bounds.width
guard width.isFinite, width > 0 else { return }
if abs(width - lastLayoutWidth) > 0.5 {
lastLayoutWidth = width
var offset: CGFloat = 0
for page in pageViews {
let height = ceil(width * page.heightToWidthRatio)
page.frame = CGRect(x: 0, y: offset, width: width, height: height)
offset += height + pageSpacing
}
let height = pageViews.isEmpty ? 0 : offset - pageSpacing
updateContentHeight(height)
}
notifyIfRenderedAndVisible()
}
override func didMoveToWindow() {
super.didMoveToWindow()
notifyIfRenderedAndVisible()
}
/// 外层滚动、隐藏恢复或布局更新后,确认已绘制内容确实与可见区域相交。
func notifyIfRenderedAndVisible() {
guard document != nil, pageViews.contains(where: { $0.hasVisibleDrawnTile() }) else { return }
onVisiblePageDrawn?()
}
private func rebuildPages() {
pageViews.forEach { $0.removeFromSuperview() }
pageViews.removeAll()
lastLayoutWidth = 0
let drawingLock = NSLock()
if let document {
for index in 0..<document.pageCount {
guard let page = document.page(at: index),
let pageView = TrainingPDFPageDrawingView(document: document, page: page, drawingLock: drawingLock) else { continue }
pageView.onDrawn = { [weak self] in self?.notifyIfRenderedAndVisible() }
pageView.onOpenLink = { [weak self] url in self?.onOpenLink?(url) }
pageViews.append(pageView)
addSubview(pageView)
}
}
if pageViews.isEmpty { updateContentHeight(0) }
setNeedsLayout()
}
private func updateContentHeight(_ height: CGFloat) {
guard height.isFinite, abs(contentHeight - height) > 0.5 else { return }
contentHeight = height
invalidateIntrinsicContentSize()
onContentHeightChange?(height)
}
}
/// 单页使用分块图层按需绘制,避免将长 PDF 的所有页面预先生成大图。
@MainActor
private final class TrainingPDFPageDrawingView: UIView {
let heightToWidthRatio: CGFloat
var onDrawn: (() -> Void)?
var onOpenLink: ((URL) -> Void)?
private let drawingState: TrainingPDFPageDrawingState
private var drawnTiles: [CGRect] = []
private var lastDrawingSize: CGSize = .zero
override class var layerClass: AnyClass { TrainingPDFPageTiledLayer.self }
init?(document: PDFDocument, page: PDFPage, drawingLock: NSLock) {
let transform = page.transform(for: .cropBox)
let displayBounds = page.bounds(for: .cropBox).applying(transform).standardized
guard displayBounds.width.isFinite, displayBounds.height.isFinite,
displayBounds.width > 0, displayBounds.height > 0 else { return nil }
heightToWidthRatio = displayBounds.height / displayBounds.width
drawingState = TrainingPDFPageDrawingState(document: document, page: page,
displayBounds: displayBounds, pageTransform: transform, drawingLock: drawingLock)
super.init(frame: .zero)
backgroundColor = .white
isOpaque = true
accessibilityLabel = page.label.map { "PDF 第 \($0) 页" } ?? "PDF 页面"
let tiledLayer = layer as! TrainingPDFPageTiledLayer
tiledLayer.contentsScale = UIScreen.main.scale
tiledLayer.tileSize = CGSize(width: 512, height: 512)
tiledLayer.levelsOfDetail = 1
tiledLayer.levelsOfDetailBias = 0
tiledLayer.needsDisplayOnBoundsChange = true
drawingState.onDraw = { [weak self] rect, size in
Task { @MainActor [weak self] in
guard let self, self.bounds.size == size else { return }
if !self.drawnTiles.contains(rect) { self.drawnTiles.append(rect) }
self.onDrawn?()
}
}
tiledLayer.configure(drawingState)
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(openLink(_:))))
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func layoutSubviews() {
super.layoutSubviews()
if bounds.size != lastDrawingSize {
lastDrawingSize = bounds.size
drawnTiles.removeAll()
layer.setNeedsDisplay()
}
}
func hasVisibleDrawnTile() -> Bool {
guard let window, !drawnTiles.isEmpty else { return false }
var visible = convert(bounds, to: window).intersection(window.bounds)
var ancestor: UIView? = self
while let view = ancestor {
guard !view.isHidden, view.alpha > 0.01 else { return false }
if view.clipsToBounds { visible = visible.intersection(view.convert(view.bounds, to: window)) }
guard !visible.isNull, !visible.isEmpty else { return false }
ancestor = view.superview
}
return drawnTiles.contains { !convert($0, to: window).intersection(visible).isEmpty }
}
@objc private func openLink(_ gesture: UITapGestureRecognizer) {
guard let url = drawingState.link(at: gesture.location(in: self), size: bounds.size) else { return }
onOpenLink?(url)
}
}
/// 持有不可变页数据,以文档级锁串行化后台绘制和主线程链接查询。
private final class TrainingPDFPageDrawingState: @unchecked Sendable {
private let document: PDFDocument
private let page: PDFPage
private let displayBounds: CGRect
private let pageTransform: CGAffineTransform
private let drawingLock: NSLock
var onDraw: (@Sendable (CGRect, CGSize) -> Void)?
init(document: PDFDocument, page: PDFPage, displayBounds: CGRect,
pageTransform: CGAffineTransform, drawingLock: NSLock) {
self.document = document
self.page = page
self.displayBounds = displayBounds
self.pageTransform = pageTransform
self.drawingLock = drawingLock
}
func draw(in context: CGContext, bounds: CGRect) {
guard bounds.width > 0, bounds.height > 0 else { return }
let tile = context.boundingBoxOfClipPath.intersection(bounds)
guard !tile.isNull, !tile.isEmpty else { return }
drawingLock.lock()
context.saveGState()
context.setFillColor(UIColor.white.cgColor)
context.fill(bounds)
let scale = bounds.width / displayBounds.width
context.translateBy(x: -displayBounds.minX * scale, y: bounds.height + displayBounds.minY * scale)
context.scaleBy(x: scale, y: -scale)
page.draw(with: .cropBox, to: context)
context.restoreGState()
drawingLock.unlock()
onDraw?(tile, bounds.size)
}
func link(at point: CGPoint, size: CGSize) -> URL? {
guard size.width > 0 else { return nil }
drawingLock.lock()
defer { drawingLock.unlock() }
let scale = size.width / displayBounds.width
let displayPoint = CGPoint(x: point.x / scale + displayBounds.minX,
y: (size.height - point.y) / scale + displayBounds.minY)
let pagePoint = displayPoint.applying(pageTransform.inverted())
return page.annotation(at: pagePoint)?.url
}
}
/// CATiledLayer 可在后台请求图块;状态快照受锁保护,回调仅返回已绘制的页内矩形。
private final class TrainingPDFPageTiledLayer: CATiledLayer {
private let stateLock = NSLock()
private var state: TrainingPDFPageDrawingState?
override class func fadeDuration() -> CFTimeInterval { 0 }
override init() { super.init() }
override init(layer: Any) {
super.init(layer: layer)
if let source = layer as? TrainingPDFPageTiledLayer { state = source.snapshot() }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
func configure(_ state: TrainingPDFPageDrawingState) {
stateLock.lock()
self.state = state
stateLock.unlock()
setNeedsDisplay()
}
override func draw(in context: CGContext) { snapshot()?.draw(in: context, bounds: bounds) }
private func snapshot() -> TrainingPDFPageDrawingState? {
stateLock.lock()
defer { stateLock.unlock() }
return state
}
}
@@ -7,6 +7,7 @@ final class TrainingResultViewController: TrainingBaseViewController {
private let taskID: String private let taskID: String
private let attemptID: String private let attemptID: String
private let service: any TrainingDataServing private let service: any TrainingDataServing
private let documentLoader: any TrainingDocumentLoading
private let viewModel: TrainingRemoteResultViewModel private let viewModel: TrainingRemoteResultViewModel
private let validateIdentity: () -> Bool private let validateIdentity: () -> Bool
private var loadFailed = false private var loadFailed = false
@@ -21,10 +22,12 @@ final class TrainingResultViewController: TrainingBaseViewController {
private let actionButton = TrainingUI.button("完成,返回培训中心") private let actionButton = TrainingUI.button("完成,返回培训中心")
/// 使用记录 ID 读取最新本人任务,禁止通过后从旧失败记录继续重考。 /// 使用记录 ID 读取最新本人任务,禁止通过后从旧失败记录继续重考。
init(taskID: String, attemptID: String, service: any TrainingDataServing, initialDetail: TrainingAttemptDetail? = nil) { init(taskID: String, attemptID: String, service: any TrainingDataServing, initialDetail: TrainingAttemptDetail? = nil,
documentLoader: any TrainingDocumentLoading = TrainingDocumentLoader()) {
self.taskID = taskID self.taskID = taskID
self.attemptID = attemptID self.attemptID = attemptID
self.service = service self.service = service
self.documentLoader = documentLoader
let session = AppStore.shared.session let session = AppStore.shared.session
let scope = session.accountCachePrefix let scope = session.accountCachePrefix
let token = session.token let token = session.token
@@ -281,7 +284,7 @@ final class TrainingResultViewController: TrainingBaseViewController {
if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) { if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) {
navigationController.popToViewController(course, animated: true) navigationController.popToViewController(course, animated: true)
} else { } else {
navigationController.pushViewController(TrainingCourseViewController(taskID: taskID, service: service), animated: true) navigationController.pushViewController(TrainingCourseViewController(taskID: taskID, service: service, documentLoader: documentLoader), animated: true)
} }
} }
@@ -0,0 +1 @@
Not a ZIP document
@@ -0,0 +1,2 @@
培训课程 GB18030
中文内容正常显示。
@@ -0,0 +1,18 @@
# 培训课程
这是 **Markdown** 附件内容。
- 服务规范
- 现场安全
| 项目 | 要求 |
|---|---|
| 阅读 | 完整阅读 |
[外部资料](https://example.com/training)
![禁止远程图片](https://example.com/image.png)
<script>alert(1)</script>
[恶意链接](javascript:alert(1))
@@ -0,0 +1,32 @@
%PDF-1.4
1 0 obj
<< /Type /Catalog /Pages 2 0 R >>
endobj
2 0 obj
<< /Type /Pages /Kids [3 0 R] /Count 1 >>
endobj
3 0 obj
<< /Type /Page /Parent 2 0 R /MediaBox [0 0 320 440] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>
endobj
4 0 obj
<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>
endobj
5 0 obj
<< /Length 109 >>
stream
BT /F1 20 Tf 28 380 Td (Training Course PDF) Tj 0 -32 Td /F1 12 Tf (Read the complete course document.) Tj ET
endstream
endobj
xref
0 6
0000000000 65535 f
0000000009 00000 n
0000000058 00000 n
0000000115 00000 n
0000000241 00000 n
0000000311 00000 n
trailer
<< /Size 6 /Root 1 0 R >>
startxref
471
%%EOF
@@ -0,0 +1,4 @@
培训课程
这是一份 UTF-8 文本附件。
<script>alert(1)</script>
第二段正文。
@@ -1,4 +1,3 @@
import SafariServices
import UIKit import UIKit
import WebKit import WebKit
import XCTest import XCTest
@@ -45,7 +44,7 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
await source.configure { await source.configure {
$0.taskHandler = { _ in await first.wait(); throw URLError(.timedOut) } $0.taskHandler = { _ in await first.wait(); throw URLError(.timedOut) }
} }
let controller = TrainingCourseViewController(taskID: "task_1", service: source) let controller = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: TrainingFixtureDocumentLoader())
let window = try makeWindow(controller) let window = try makeWindow(controller)
defer { closeWindow(window, controller: controller) } defer { closeWindow(window, controller: controller) }
try await waitUntil { await first.requestCount == 1 } try await waitUntil { await first.requestCount == 1 }
@@ -72,133 +71,70 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
XCTAssertFalse(GlobalLoadingManager.shared.isShowing) XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
} }
/// 目录分页和未缓存正文显示进度;缓存切换无额外正文请求或进度闪烁。 /// 下载错误保留原生课程信息;用户重试重新授权文件并保持全局进度与防重复请求。
func testDirectoryPaginationAndCachedSectionReuse() async throws { func testDocumentDownloadFailureAndRetryKeepMetadataAndLoading() async throws {
let page = TrainingCourseLoadingGate() let download = TrainingCourseLoadingGate()
let body = TrainingCourseLoadingGate() let retry = TrainingCourseLoadingGate()
defer { Task { await page.release(); await body.release() } } defer { Task { await download.release(); await retry.release() } }
let loader = TrainingFixtureDocumentLoader { _, _ in
await download.wait()
if await download.requestCount == 1 { throw URLError(.networkConnectionLost) }
await retry.wait()
return try TrainingDocumentTestFixtures.document()
}
let source = TrainingDataStub() let source = TrainingDataStub()
await source.configure { let controller = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: loader)
$0.sectionsHandler = { cursor in
if cursor != nil {
await page.wait()
return TrainingCursorPage(items: [TrainingSectionInfo(id: "s3", order: 3, title: "后续小节")], nextCursor: nil, hasMore: false, serverTime: nil)
}
return TrainingCursorPage(items: [TrainingSectionInfo(id: "s1", order: 1, title: "首节"), TrainingSectionInfo(id: "s2", order: 2, title: "第二节")], nextCursor: "next", hasMore: true, serverTime: nil)
}
$0.sectionHandler = { id in
if id == "s2" { await body.wait() }
return TrainingSectionContent(id: id, order: id == "s1" ? 1 : 2, title: id, contentHTML: "<p>\(id)</p>")
}
}
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
let window = try makeWindow(controller) let window = try makeWindow(controller)
defer { closeWindow(window, controller: controller) } defer { closeWindow(window, controller: controller) }
try await waitUntil { await download.requestCount == 1 }
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
await download.release()
let action = try button("training.reading.action", in: controller.view)
try await waitUntil { action.isEnabled && action.isUserInteractionEnabled && !GlobalLoadingManager.shared.isShowing }
XCTAssertEqual(action.configuration?.title, "重新加载附件")
let labels = allViews(controller.view).compactMap { $0 as? UILabel }
XCTAssertEqual(labels.first { $0.accessibilityIdentifier == "training.reading.taskTitle" }?.text, "一线服务规范学习")
XCTAssertEqual(labels.first { $0.accessibilityIdentifier == "training.reading.courseName" }?.text, "景区服务规范")
let appearance = (action.isEnabled, action.alpha, action.configuration?.baseBackgroundColor)
action.sendActions(for: .touchUpInside)
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
XCTAssertEqual(action.isEnabled, appearance.0)
XCTAssertEqual(action.alpha, appearance.1)
XCTAssertEqual(action.configuration?.baseBackgroundColor, appearance.2)
XCTAssertFalse(action.isUserInteractionEnabled)
action.sendActions(for: .touchUpInside)
try await waitUntil { await retry.requestCount == 1 }
let pendingCalls = await source.calls
XCTAssertEqual(pendingCalls.filter { $0.name == "attachmentURL" }.count, 2)
XCTAssertEqual(pendingCalls.filter { $0.name == "task" }.count, 1)
await retry.release()
try await waitUntil { self.isReady(controller) } try await waitUntil { self.isReady(controller) }
let picker = try await openPicker("training.reading.sections", controller: controller, rows: 3)
selectRow(2, in: picker.table)
selectRow(2, in: picker.table)
try await waitUntil { await page.requestCount == 1 }
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
await page.release()
try await waitUntil { self.rowTitle(2, in: picker.table) == "3. 后续小节" && !GlobalLoadingManager.shared.isShowing }
selectRow(1, in: picker.table)
try await waitUntil { await body.requestCount == 1 }
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
await body.release()
try await waitUntil { self.isReady(controller) && controller.presentedViewController == nil }
let cached = try await openPicker("training.reading.sections", controller: controller, rows: 3)
XCTAssertFalse(GlobalLoadingManager.shared.isShowing) XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
selectRow(0, in: cached.table) let downloadCount = await download.requestCount
try await waitUntil { controller.presentedViewController == nil && self.isReady(controller) } XCTAssertEqual(downloadCount, 2)
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
let calls = await source.calls
XCTAssertEqual(calls.filter { $0.name == "section" }.count, 2)
XCTAssertEqual(calls.filter { $0.name == "sections" && $0.cursor == "next" }.count, 1)
} }
/// HTTP 附件分页和授权显示进度,复用目录及呈现 Safari 前已释放进度。 /// 离页取消请求后清理原票据,迟到响应不能隐藏其它请求,返回会重新加载课程。
func testHTTPAttachmentLoadingPaginationReuseAndAuthorization() async throws { func testLeavingAndReturningRestoresCanceledCourseWithoutEndingOtherLoading() async throws {
let first = TrainingCourseLoadingGate()
let next = TrainingCourseLoadingGate()
let authorization = TrainingCourseLoadingGate()
defer { Task { await first.release(); await next.release(); await authorization.release() } }
let source = TrainingDataStub()
await source.configure {
$0.courseHandler = { TrainingCourseInfo(id: "course_1", title: "课程", introduction: "简介", sectionCount: 2, attachmentCount: 2) }
$0.attachmentsHandler = { cursor in
if cursor == nil { await first.wait() } else { await next.wait() }
let id = cursor == nil ? "a1" : "a2"
let item = TrainingAttachmentInfo(id: id, name: id, mimeType: "application/pdf", sizeBytes: 120,
fileID: id, downloadURL: nil, expiresAt: nil)
return TrainingCursorPage(items: [item], nextCursor: cursor == nil ? "next" : nil, hasMore: cursor == nil, serverTime: nil)
}
$0.attachmentURLHandler = { id in
await authorization.wait()
return TrainingAttachmentLink(id: id, name: id, url: URL(string: "http://example.test/training.pdf?Signature=a%2Bb%3D")!, expiresAt: Date().addingTimeInterval(60))
}
}
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
let window = try makeWindow(controller)
defer { closeWindow(window, controller: controller) }
try await waitUntil { self.isReady(controller) }
let attachments = try button("training.reading.attachments", in: controller.view)
attachments.sendActions(for: .touchUpInside)
attachments.sendActions(for: .touchUpInside)
try await waitUntil { await first.requestCount == 1 }
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
XCTAssertTrue(attachments.isEnabled)
await first.release()
let picker = try await currentPicker(controller, rows: 2)
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
selectRow(1, in: picker.table)
try await waitUntil { await next.requestCount == 1 }
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
await next.release()
try await waitUntil { self.rowTitle(1, in: picker.table) == "a2" && !GlobalLoadingManager.shared.isShowing }
try activate(try XCTUnwrap(picker.navigation.topViewController?.navigationItem.rightBarButtonItem))
try await waitUntil { controller.presentedViewController == nil && self.isReady(controller) }
attachments.sendActions(for: .touchUpInside)
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
let reused = try await currentPicker(controller, rows: 2)
let calls = await source.calls
XCTAssertEqual(calls.filter { $0.name == "attachments" }.count, 2)
selectRow(0, in: reused.table)
try await waitUntil { await authorization.requestCount == 1 }
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
await authorization.release()
try await waitUntil { controller.presentedViewController is SFSafariViewController }
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
}
/// 离页取消请求后清理原票据,迟到响应不能隐藏其它请求,返回会补载并渲染原选中正文。
func testLeavingAndReturningRestoresCanceledSectionWithoutEndingOtherLoading() async throws {
let body = TrainingCourseLoadingGate() let body = TrainingCourseLoadingGate()
defer { Task { await body.release() } } defer { Task { await body.release() } }
let source = TrainingDataStub() let source = TrainingDataStub()
await source.configure { let loader = TrainingFixtureDocumentLoader { _, _ in
$0.sectionHandler = { id in await body.wait()
if id == "s2" { await body.wait() } return try TrainingDocumentTestFixtures.document()
return TrainingSectionContent(id: id, order: id == "s1" ? 1 : 2, title: id, contentHTML: "<p>visible-\(id)</p>")
} }
} let controller = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: loader)
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
let window = try makeWindow(controller) let window = try makeWindow(controller)
defer { closeWindow(window, controller: controller) } defer { closeWindow(window, controller: controller) }
try await waitUntil { self.isReady(controller) }
let picker = try await openPicker("training.reading.sections", controller: controller, rows: 2)
selectRow(1, in: picker.table)
try await waitUntil { await body.requestCount == 1 } try await waitUntil { await body.requestCount == 1 }
XCTAssertTrue(GlobalLoadingManager.shared.isShowing) XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
let navigation = try XCTUnwrap(controller.navigationController) let navigation = try XCTUnwrap(controller.navigationController)
try await waitUntil { try await waitUntil {
controller.presentedViewController == nil && controller.transitionCoordinator == nil controller.transitionCoordinator == nil && navigation.transitionCoordinator == nil
&& navigation.transitionCoordinator == nil && !picker.navigation.isBeingDismissed
&& picker.navigation.transitionCoordinator == nil
} }
let destination = UIViewController() let destination = UIViewController()
navigation.pushViewController(destination, animated: false) navigation.pushViewController(destination, animated: false)
// 正文响应仍被 gate 挂起;这里只等待 UIKit 完成真实离页与页面票据释放。 // 文件下载仍被 gate 挂起;这里只等待 UIKit 完成真实离页与页面票据释放。
try await waitUntil { try await waitUntil {
navigation.topViewController === destination && destination.view.window === window navigation.topViewController === destination && destination.view.window === window
&& navigation.transitionCoordinator == nil && controller.transitionCoordinator == nil && navigation.transitionCoordinator == nil && controller.transitionCoordinator == nil
@@ -208,7 +144,8 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
let other = GlobalLoadingManager.shared.beginRequest() let other = GlobalLoadingManager.shared.beginRequest()
defer { GlobalLoadingManager.shared.endRequest(other) } defer { GlobalLoadingManager.shared.endRequest(other) }
await body.release() await body.release()
try await waitUntil { self.allViews(controller.view).compactMap { $0 as? UIButton }.allSatisfy { $0.isUserInteractionEnabled } } let action = try button("training.reading.action", in: controller.view)
try await waitUntil { action.isUserInteractionEnabled }
XCTAssertTrue(GlobalLoadingManager.shared.isShowing) XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
GlobalLoadingManager.shared.endRequest(other) GlobalLoadingManager.shared.endRequest(other)
navigation.popViewController(animated: false) navigation.popViewController(animated: false)
@@ -220,11 +157,14 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
try await waitUntil { try await waitUntil {
guard self.isReady(controller), !webView.isLoading else { return false } guard self.isReady(controller), !webView.isLoading else { return false }
let text = try? await webView.evaluateJavaScript("document.body.textContent") as? String let text = try? await webView.evaluateJavaScript("document.body.textContent") as? String
return text?.contains("visible-s2") == true return text?.contains("这是一份 UTF-8 文本附件。") == true
} }
XCTAssertFalse(GlobalLoadingManager.shared.isShowing) XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
let calls = await source.calls let calls = await source.calls
XCTAssertEqual(calls.filter { $0.name == "section" }.count, 3) XCTAssertEqual(calls.filter { $0.name == "attachmentURL" }.count, 2)
let downloadCount = await body.requestCount
XCTAssertEqual(downloadCount, 2)
XCTAssertFalse(calls.contains { ["section", "sections"].contains($0.name) })
} }
/// 正文就绪后的自动会话、暂停保存与恢复不显示进度,只有用户重试失败会话显示。 /// 正文就绪后的自动会话、暂停保存与恢复不显示进度,只有用户重试失败会话显示。
@@ -240,7 +180,7 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
throw URLError(.timedOut) throw URLError(.timedOut)
} }
let source = TrainingDataStub(configuration: configuration) let source = TrainingDataStub(configuration: configuration)
let controller = TrainingCourseViewController(taskID: "task_1", service: source) let controller = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: TrainingFixtureDocumentLoader())
let window = try makeWindow(controller) let window = try makeWindow(controller)
defer { closeWindow(window, controller: controller) } defer { closeWindow(window, controller: controller) }
try await waitUntil { await initial.requestCount == 1 } try await waitUntil { await initial.requestCount == 1 }
@@ -299,42 +239,11 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
} }
private func isReady(_ controller: TrainingCourseViewController) -> Bool { private func isReady(_ controller: TrainingCourseViewController) -> Bool {
guard let sections = try? button("training.reading.sections", in: controller.view) else { return false } let views = allViews(controller.view)
return sections.isEnabled && sections.isUserInteractionEnabled && !GlobalLoadingManager.shared.isShowing guard let step = views.first(where: { $0 is TrainingStepView }), !step.isHidden,
} let preview = views.compactMap({ $0 as? TrainingDocumentPreviewView }).first,
let action = try? button("training.reading.action", in: controller.view) else { return false }
private func openPicker(_ identifier: String, controller: TrainingCourseViewController, rows: Int) async throws -> (navigation: UINavigationController, table: UITableView) { return preview.isReady && action.isUserInteractionEnabled && !GlobalLoadingManager.shared.isShowing
try button(identifier, in: controller.view).sendActions(for: .touchUpInside)
return try await currentPicker(controller, rows: rows)
}
private func currentPicker(_ controller: TrainingCourseViewController, rows: Int) async throws -> (navigation: UINavigationController, table: UITableView) {
try await waitUntil {
guard let navigation = controller.presentedViewController as? UINavigationController,
let picker = navigation.topViewController,
!navigation.isBeingPresented, picker.transitionCoordinator == nil,
let table = self.allViews(picker.view).compactMap({ $0 as? UITableView }).first else { return false }
return table.numberOfRows(inSection: 0) == rows
}
let navigation = try XCTUnwrap(controller.presentedViewController as? UINavigationController)
let picker = try XCTUnwrap(navigation.topViewController)
let table = try XCTUnwrap(allViews(picker.view).compactMap { $0 as? UITableView }.first)
return (navigation, table)
}
private func selectRow(_ index: Int, in table: UITableView) {
table.delegate?.tableView?(table, didSelectRowAt: IndexPath(row: index, section: 0))
}
private func rowTitle(_ index: Int, in table: UITableView) -> String? {
(table.cellForRow(at: IndexPath(row: index, section: 0))?.contentConfiguration as? UIListContentConfiguration)?.text
}
private func activate(_ item: UIBarButtonItem) throws {
let action = try XCTUnwrap(item.primaryAction)
let dispatcher = UIButton(type: .system)
dispatcher.addAction(action, for: .touchUpInside)
dispatcher.sendActions(for: .touchUpInside)
} }
private func allViews(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap { allViews($0) } } private func allViews(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap { allViews($0) } }
@@ -344,7 +253,7 @@ final class TrainingCourseRequestLoadingTests: XCTestCase {
} }
private func waitUntil(_ condition: @MainActor () async -> Bool) async throws { private func waitUntil(_ condition: @MainActor () async -> Bool) async throws {
let deadline = ContinuousClock.now.advanced(by: .seconds(5)) let deadline = ContinuousClock.now.advanced(by: .seconds(15))
while !(await condition()), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) } while !(await condition()), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
let reached = await condition() let reached = await condition()
XCTAssertTrue(reached, "未在期限内进入预期 UI / 请求状态") XCTAssertTrue(reached, "未在期限内进入预期 UI / 请求状态")
+11 -5
View File
@@ -20,6 +20,11 @@ enum TrainingRemoteFixtures {
static func progress(seconds: Int = 20, completed: Bool = false) -> TrainingProgressSnapshot { static func progress(seconds: Int = 20, completed: Bool = false) -> TrainingProgressSnapshot {
TrainingProgressSnapshot(taskID: "task_1", readingSeconds: seconds, requiredReadingSeconds: 20, completedSectionCount: seconds >= 20 ? 2 : 0, sectionCount: 2, progressPercent: seconds >= 20 ? 100 : 0, readingCompleted: seconds >= 20, learnerStatus: completed ? .completed : .pendingExam, completedAt: completed ? now : nil, hasDraft: false, canViewCourse: true, canStudy: seconds < 20 && !completed, canStartExam: seconds >= 20 && !completed, canRetry: !completed, blockReason: completed ? "completed" : seconds < 20 ? "reading_required" : nil, serverTime: now) TrainingProgressSnapshot(taskID: "task_1", readingSeconds: seconds, requiredReadingSeconds: 20, completedSectionCount: seconds >= 20 ? 2 : 0, sectionCount: 2, progressPercent: seconds >= 20 ? 100 : 0, readingCompleted: seconds >= 20, learnerStatus: completed ? .completed : .pendingExam, completedAt: completed ? now : nil, hasDraft: false, canViewCourse: true, canStudy: seconds < 20 && !completed, canStartExam: seconds >= 20 && !completed, canRetry: !completed, blockReason: completed ? "completed" : seconds < 20 ? "reading_required" : nil, serverTime: now)
} }
/// 轻量课程文档,默认使用可由本地替身稳定预览的纯文本。
static func attachment(id: String = "file_1", name: String = "培训资料.txt", mimeType: String = "text/plain") -> TrainingAttachmentInfo {
TrainingAttachmentInfo(id: id, name: name, mimeType: mimeType, sizeBytes: 1024,
fileID: id, downloadURL: nil, expiresAt: nil)
}
/// 单次已提交成绩。 /// 单次已提交成绩。
static func attempt(id: String = "attempt_1", passed: Bool = true, questionCount: Int = 30, reviewAvailable: Bool = true) -> TrainingAttemptSummary { static func attempt(id: String = "attempt_1", passed: Bool = true, questionCount: Int = 30, reviewAvailable: Bool = true) -> TrainingAttemptSummary {
TrainingAttemptSummary(id: id, taskID: "task_1", taskTitle: "一线服务规范学习", courseSnapshotID: "course_1", courseTitle: "景区服务规范", paperSnapshotID: "paper_1", submittedAt: now, scoreHundredths: passed ? 10000 : 5000, correctCount: passed ? questionCount : questionCount / 2, questionCount: questionCount, passScore: 80, passed: passed, reviewAvailable: reviewAvailable) TrainingAttemptSummary(id: id, taskID: "task_1", taskTitle: "一线服务规范学习", courseSnapshotID: "course_1", courseTitle: "景区服务规范", paperSnapshotID: "paper_1", submittedAt: now, scoreHundredths: passed ? 10000 : 5000, correctCount: passed ? questionCount : questionCount / 2, questionCount: questionCount, passScore: 80, passed: passed, reviewAvailable: reviewAvailable)
@@ -44,6 +49,7 @@ actor TrainingDataStub: TrainingDataServing {
var cursor: String? = nil var cursor: String? = nil
var offset: Int? = nil var offset: Int? = nil
var limit: Int? = nil var limit: Int? = nil
var resourceID: String? = nil
} }
/// 心跳的固定幂等负载。 /// 心跳的固定幂等负载。
struct HeartbeatCall: Equatable, Sendable { struct HeartbeatCall: Equatable, Sendable {
@@ -129,7 +135,7 @@ actor TrainingDataStub: TrainingDataServing {
func course(id: String, taskID: String) async throws -> TrainingCourseInfo { func course(id: String, taskID: String) async throws -> TrainingCourseInfo {
calls.append(Call(name: "course", taskID: taskID)) calls.append(Call(name: "course", taskID: taskID))
if let handler = configuration.courseHandler { return try await handler() } if let handler = configuration.courseHandler { return try await handler() }
return TrainingCourseInfo(id: id, title: "景区服务规范", introduction: "正式课程简介", sectionCount: 2, attachmentCount: 0) return TrainingCourseInfo(id: id, title: "景区服务规范", introduction: "正式课程简介", sectionCount: 2, attachmentCount: 1)
} }
/// 小节目录,仅含标题与序号。 /// 小节目录,仅含标题与序号。
func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingSectionInfo> { func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingSectionInfo> {
@@ -147,13 +153,13 @@ actor TrainingDataStub: TrainingDataServing {
func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttachmentInfo> { func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttachmentInfo> {
calls.append(Call(name: "attachments", taskID: taskID, cursor: cursor, limit: limit)) calls.append(Call(name: "attachments", taskID: taskID, cursor: cursor, limit: limit))
if let handler = configuration.attachmentsHandler { return try await handler(cursor) } if let handler = configuration.attachmentsHandler { return try await handler(cursor) }
return TrainingCursorPage(items: [], nextCursor: nil, hasMore: false, serverTime: nil) return TrainingCursorPage(items: [TrainingRemoteFixtures.attachment()], nextCursor: nil, hasMore: false, serverTime: nil)
} }
/// 返回用于 Safari 的授权 HTTPS URL。 /// 返回供文档加载替身读取的授权 HTTPS URL。
func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink { func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink {
calls.append(Call(name: "attachmentURL", taskID: taskID)) calls.append(Call(name: "attachmentURL", taskID: taskID, resourceID: attachmentID))
if let handler = configuration.attachmentURLHandler { return try await handler(attachmentID) } if let handler = configuration.attachmentURLHandler { return try await handler(attachmentID) }
return TrainingAttachmentLink(id: attachmentID, name: "培训附件", url: URL(string: "https://example.test/training.pdf")!, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600)) return TrainingAttachmentLink(id: attachmentID, name: "培训资料.txt", url: URL(string: "https://example.test/training.txt")!, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600))
} }
/// 只返回权威读时。 /// 只返回权威读时。
func progress(taskID: String) async throws -> TrainingProgressSnapshot { func progress(taskID: String) async throws -> TrainingProgressSnapshot {
@@ -0,0 +1,471 @@
import PDFKit
import UIKit
import WebKit
import XCTest
@testable import suixinkan
/// 真机使用正式预览组件读取本地文件,验证实际内容与渲染成功事件。
@MainActor
final class TrainingDocumentPreviewTests: XCTestCase {
private var previousKeyWindow: UIWindow?
/// PDF 经 PDFKit 显示并保留可阅读的页内容。
func testPDFFileRendersWithPDFKit() async throws {
let (preview, window) = try makePreviewWindow()
defer { closeWindow(window) }
try await showDocument(.pdf, in: preview)
let pdf = try XCTUnwrap(allViews(preview).compactMap { $0 as? TrainingPDFDocumentView }.first)
XCTAssertFalse(pdf.isHidden)
XCTAssertEqual(pdf.document?.pageCount, 1)
XCTAssertTrue(pdf.document?.string?.contains("Training Course PDF") == true)
let image = UIGraphicsImageRenderer(size: preview.bounds.size).image { _ in
preview.drawHierarchy(in: preview.bounds, afterScreenUpdates: true)
}
record(image, name: "课程附件-PDF真机预览")
}
/// 文件已装入但预览仍隐藏时不得发 ready;可见页真实绘制后才打开门禁。
func testPDFDoesNotBecomeReadyUntilVisiblePageIsDrawn() async throws {
let (preview, window) = try makePreviewWindow()
defer { closeWindow(window) }
preview.isHidden = true
let id = UUID()
var readyID: UUID?
preview.onReady = { readyID = $0 }
preview.show(try TrainingDocumentTestFixtures.document(kind: .pdf), requestID: id)
try await Task.sleep(for: .milliseconds(100))
XCTAssertNil(readyID)
XCTAssertFalse(preview.isReady)
preview.isHidden = false
try await waitUntil { readyID == id }
XCTAssertTrue(preview.isReady)
}
/// 祖先滚动区域裁剪掉 PDF 时,即使图层已排版也不能开始读时。
func testPDFWaitsUntilItsDrawnPageEntersOuterViewport() async throws {
let controller = UIViewController()
let scroll = UIScrollView(frame: CGRect(x: 0, y: 80, width: 390, height: 600))
scroll.clipsToBounds = true
scroll.contentInsetAdjustmentBehavior = .never
scroll.contentSize = CGSize(width: 390, height: 1600)
let preview = TrainingDocumentPreviewView()
preview.frame = CGRect(x: 12, y: 850, width: 366, height: 550)
controller.view.addSubview(scroll)
scroll.addSubview(preview)
let window = try makeWindow(controller)
defer { closeWindow(window) }
let id = UUID()
var readyID: UUID?
preview.onReady = { readyID = $0 }
preview.show(try TrainingDocumentTestFixtures.document(kind: .pdf), requestID: id)
_ = UIGraphicsImageRenderer(size: preview.bounds.size).image { _ in
preview.drawHierarchy(in: preview.bounds, afterScreenUpdates: true)
}
preview.notifyIfRenderedAndVisible()
try await Task.sleep(for: .milliseconds(100))
XCTAssertNil(readyID)
XCTAssertFalse(preview.isReady)
scroll.setContentOffset(CGPoint(x: 0, y: 800), animated: false)
controller.view.layoutIfNeeded()
preview.notifyIfRenderedAndVisible()
try await waitUntil { readyID == id }
XCTAssertTrue(preview.isReady)
}
/// 切到 PDF 后,旧 WebView 进程退出不能把当前 PDF 当成预览失败。
func testOldWebProcessTerminationDoesNotInvalidateCurrentPDF() async throws {
let (preview, window) = try makePreviewWindow()
defer { closeWindow(window) }
try await showDocument(.docx, in: preview)
let oldWeb = try documentWebView(in: preview)
try await showDocument(.pdf, in: preview)
var failure: String?
preview.onFailure = { _, message in failure = message }
preview.webViewWebContentProcessDidTerminate(oldWeb)
XCTAssertNil(failure)
XCTAssertTrue(preview.isReady)
XCTAssertFalse(try XCTUnwrap(allViews(preview).compactMap { $0 as? TrainingPDFDocumentView }.first).isHidden)
}
/// DOCX 必须通过正式本地 JS 解析器产生段落与表格,不能只报告页面加载完成。
func testDOCXFileRendersRealParagraphAndTable() async throws {
let (preview, window) = try makePreviewWindow()
defer { closeWindow(window) }
try await showDocument(.docx, in: preview)
let web = try documentWebView(in: preview)
let text = try await web.evaluateJavaScript("document.getElementById('document').textContent") as? String
XCTAssertTrue(text?.contains("培训课程 DOCX") == true)
XCTAssertTrue(text?.contains("这是 Word 文档正文,包含中文内容。") == true)
XCTAssertTrue(text?.contains("服务规范") == true)
let tableCount = try await web.evaluateJavaScript("document.querySelectorAll('#document table').length") as? Int
XCTAssertEqual(tableCount, 1)
record(try await web.takeSnapshot(configuration: nil), name: "课程附件-DOCX真机预览")
}
/// TXT 显示原文字面量,不能把文件里的 HTML 片段执行成网页。
func testTXTFileRendersPlainText() async throws {
let (preview, window) = try makePreviewWindow()
defer { closeWindow(window) }
try await showDocument(.txt, in: preview)
let web = try documentWebView(in: preview)
let text = try await web.evaluateJavaScript("document.querySelector('#document pre').textContent") as? String
XCTAssertTrue(text?.contains("这是一份 UTF-8 文本附件。") == true)
XCTAssertTrue(text?.contains("<script>alert(1)</script>") == true)
let scriptCount = try await web.evaluateJavaScript("document.querySelectorAll('#document script').length") as? Int
XCTAssertEqual(scriptCount, 0)
record(try await web.takeSnapshot(configuration: nil), name: "课程附件-TXT真机预览")
}
/// Markdown 渲染成标题、强调和表格,外部图片与危险链接不能进入有效属性。
func testMarkdownFileRendersFormattedContent() async throws {
let (preview, window) = try makePreviewWindow()
defer { closeWindow(window) }
try await showDocument(.md, in: preview)
let web = try documentWebView(in: preview)
let heading = try await web.evaluateJavaScript("document.querySelector('#document h1').textContent") as? String
let strong = try await web.evaluateJavaScript("document.querySelector('#document strong').textContent") as? String
let tableCount = try await web.evaluateJavaScript("document.querySelectorAll('#document table').length") as? Int
let unsafeCount = try await web.evaluateJavaScript("document.querySelectorAll('#document script, #document img[src], #document a[href^=\"javascript:\"]').length") as? Int
XCTAssertEqual(heading, "培训课程")
XCTAssertEqual(strong, "Markdown")
XCTAssertEqual(tableCount, 1)
XCTAssertEqual(unsafeCount, 0)
record(try await web.takeSnapshot(configuration: nil), name: "课程附件-Markdown真机预览")
}
/// ZIP 损坏必须通过失败回调回到原生重试状态,不能累计阅读。
func testBrokenDOCXFailsWithoutReadyEvent() async throws {
let (preview, window) = try makePreviewWindow()
defer { closeWindow(window) }
let requestID = UUID()
var readyID: UUID?
var failureID: UUID?
var failureMessage: String?
preview.onReady = { readyID = $0 }
preview.onFailure = { failureID = $0; failureMessage = $1 }
preview.show(try TrainingDocumentTestFixtures.document(kind: .docx, resource: "training-preview-broken"), requestID: requestID)
try await waitUntil { failureID != nil || readyID != nil }
XCTAssertEqual(failureID, requestID)
XCTAssertNil(readyID)
XCTAssertNotNil(failureMessage)
XCTAssertFalse(preview.isReady)
}
/// 旧 DOC 文件明确拒绝,即使服务器错误地声明为 DOCX MIME。
func testLegacyDOCIsRejectedBeforeDownload() async throws {
let url = try XCTUnwrap(URL(string: "https://example.test/legacy.doc"))
for mime in ["application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"] {
XCTAssertThrowsError(try TrainingDocumentKind.resolve(name: "旧版文档.doc", mimeType: mime, url: url)) { error in
XCTAssertEqual(error.localizedDescription, TrainingDocumentError.unsupported.localizedDescription)
}
}
let attachment = TrainingRemoteFixtures.attachment(name: "旧版文档.doc", mimeType: "application/msword")
let link = TrainingAttachmentLink(id: attachment.id, name: attachment.name, url: url,
expiresAt: Date().addingTimeInterval(60))
do {
_ = try await TrainingFixtureDocumentLoader().load(attachment: attachment, link: link)
XCTFail("旧 DOC 不应被当作 DOCX 或文本加载")
} catch {
XCTAssertEqual(error.localizedDescription, TrainingDocumentError.unsupported.localizedDescription)
}
}
/// 课程元信息只出现在 UIKit 标签中,WebView DOM 只包含附件文件内容。
func testCourseMetadataIsNativeAndAbsentFromDocument() async throws {
let source = TrainingDataStub()
await source.configure {
$0.taskHandler = { _ in
TrainingTaskDetail(summary: TrainingRemoteFixtures.task(title: "NATIVE_TASK_ONLY"), requiredReadingSeconds: 20,
readingRule: "course_duration", scoring: "equal-percentage-v1", serverTime: TrainingRemoteFixtures.now)
}
$0.courseHandler = {
TrainingCourseInfo(id: "course_1", title: "NATIVE_COURSE_ONLY", introduction: "NATIVE_INTRODUCTION_ONLY", sectionCount: 1, attachmentCount: 1)
}
}
let controller = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: TrainingFixtureDocumentLoader())
let window = try makeWindow(UINavigationController(rootViewController: controller))
defer { closeWindow(window) }
try await waitUntil {
self.allViews(controller.view).compactMap { $0 as? TrainingDocumentPreviewView }.first?.isReady == true
}
let labels = allViews(controller.view).compactMap { $0 as? UILabel }
let expected = ["training.reading.taskTitle": "NATIVE_TASK_ONLY", "training.reading.courseName": "NATIVE_COURSE_ONLY",
"training.reading.examInfo": "学习 + 考试 · 30 题 · 80 分及格", "training.reading.introduction": "NATIVE_INTRODUCTION_ONLY"]
for (identifier, value) in expected {
XCTAssertEqual(labels.first { $0.accessibilityIdentifier == identifier }?.text, value)
}
let web = try documentWebView(in: controller.view)
let content = try await web.evaluateJavaScript("document.body.textContent") as? String
let text = try XCTUnwrap(content)
XCTAssertTrue(text.contains("这是一份 UTF-8 文本附件。"))
for value in expected.values { XCTAssertFalse(text.contains(value)) }
let calls = await source.calls
XCTAssertFalse(calls.contains { ["sections", "section"].contains($0.name) })
}
/// 长文件由课程页面统一滚动,原生信息随正文离屏,换为短文件后不残留空白高度。
func testLongTextUsesOuterPageScrollingAndShrinksForNextDocument() async throws {
let lines = (1...120).map { "第 \($0) 行:这是完整课程阅读内容,向上滑动时标题和正文应一同移动。" }
let document = try temporaryDocument(text: (lines + ["END_OF_LONG_COURSE"]).joined(separator: "\n"), kind: .txt)
defer { try? FileManager.default.removeItem(at: document.fileURL.deletingLastPathComponent()) }
let (controller, preview, scroll, window) = try await makeCourseWindow(document: document)
defer { closeWindow(window) }
let web = try documentWebView(in: preview)
try await waitUntil { scroll.contentSize.height > scroll.bounds.height * 3 }
XCTAssertFalse(web.scrollView.isScrollEnabled)
let title = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? UILabel }
.first { $0.accessibilityIdentifier == "training.reading.taskTitle" })
let initialTitleY = title.convert(title.bounds, to: controller.view).minY
scrollToBottom(scroll)
controller.view.layoutIfNeeded()
let movedTitle = title.convert(title.bounds, to: controller.view)
XCTAssertLessThan(movedTitle.maxY, scroll.frame.minY)
XCTAssertLessThan(movedTitle.minY, initialTitleY - scroll.bounds.height)
let documentBottom = web.convert(CGPoint(x: 0, y: web.bounds.maxY), to: scroll).y
XCTAssertLessThanOrEqual(documentBottom, scroll.bounds.maxY + 3)
XCTAssertGreaterThan(documentBottom, scroll.bounds.minY)
XCTAssertEqual(web.scrollView.contentOffset.y, 0, accuracy: 1)
let originalHeight = preview.preferredContentHeight
let shortDocument = try temporaryDocument(text: "新的短文档,只有一行。", kind: .txt)
defer { try? FileManager.default.removeItem(at: shortDocument.fileURL.deletingLastPathComponent()) }
preview.show(shortDocument, requestID: UUID())
try await waitUntil { preview.isReady && preview.preferredContentHeight < originalHeight / 4 }
controller.view.layoutIfNeeded()
XCTAssertLessThan(scroll.contentSize.height, scroll.bounds.height)
XCTAssertEqual(scroll.contentOffset.y, -scroll.adjustedContentInset.top, accuracy: 1)
XCTAssertEqual(web.scrollView.contentOffset.y, 0, accuracy: 1)
XCTAssertTrue(title.convert(title.bounds, to: controller.view).intersects(scroll.frame))
}
/// 异步排版变化和宽度重排会撑开或缩回卡片,不能依赖固定 WebView 高度。
func testMarkdownAndDOCXTrackLateLayoutAndWidthChanges() async throws {
let (preview, window) = try makePreviewWindow()
defer { closeWindow(window) }
preview.onContentHeightChange = { [weak preview] height in
guard let preview else { return }
preview.frame.size.height = height
preview.layoutIfNeeded()
}
for kind in [TrainingDocumentKind.md, .docx] {
preview.frame.size.width = 366
try await showDocument(kind, in: preview)
let web = try documentWebView(in: preview)
let baseline = preview.preferredContentHeight
_ = try await web.evaluateJavaScript("""
(() => {
const section = document.createElement('section');
section.id = 'late-course-content';
for (let i = 0; i < 20; i++) {
const paragraph = document.createElement('p');
paragraph.textContent = '动态课程段落应完整排版,字体与宽度变化后,页面仍能读到最后一行。'.repeat(4);
section.appendChild(paragraph);
}
document.getElementById('document').appendChild(section);
})();
""")
try await waitUntil { preview.preferredContentHeight > baseline + 500 }
let wideHeight = preview.preferredContentHeight
preview.frame.size.width = 220
preview.layoutIfNeeded()
try await waitUntil { preview.preferredContentHeight > wideHeight + 100 }
XCTAssertFalse(web.scrollView.isScrollEnabled)
XCTAssertEqual(web.scrollView.contentOffset.y, 0, accuracy: 1)
_ = try await web.evaluateJavaScript("document.getElementById('late-course-content').remove()")
preview.frame.size.width = 366
preview.layoutIfNeeded()
try await waitUntil { abs(preview.preferredContentHeight - baseline) < 5 }
XCTAssertEqual(preview.bounds.height, preview.preferredContentHeight, accuracy: 1)
XCTAssertTrue(preview.isReady)
}
}
/// 文内目录定位使用外层页面偏移,WebView 自己不能跳到目标而截断顶部内容。
func testDocumentAnchorScrollsOuterPageWithoutMovingInnerWebView() async throws {
let document = try TrainingDocumentTestFixtures.document(kind: .md)
let (controller, preview, scroll, window) = try await makeCourseWindow(document: document)
defer { closeWindow(window) }
let web = try documentWebView(in: preview)
_ = try await web.evaluateJavaScript("""
(() => {
const content = document.getElementById('document');
const link = document.createElement('a');
link.id = 'course-directory-link'; link.href = '#course-last-heading'; link.textContent = '跳到课程结尾';
content.prepend(link);
for (let i = 0; i < 55; i++) {
const paragraph = document.createElement('p');
paragraph.textContent = '课程学习段落 ' + i + ':继续阅读服务规范。'; content.appendChild(paragraph);
}
const target = document.createElement('h2');
target.id = 'course-last-heading'; target.textContent = 'COURSE_ANCHOR_DESTINATION'; content.appendChild(target);
const footer = document.createElement('div'); footer.style.height = '700px'; content.appendChild(footer);
})();
""")
try await waitUntil { preview.preferredContentHeight > 2500 }
_ = try await web.evaluateJavaScript("document.getElementById('course-directory-link').click()")
try await waitUntil { scroll.contentOffset.y > 1000 && !scroll.isDecelerating && !scroll.isDragging }
let targetResult = try await web.evaluateJavaScript("document.getElementById('course-last-heading').getBoundingClientRect().top") as? Double
let targetY = try XCTUnwrap(targetResult)
try await waitUntil {
let position = web.convert(CGPoint(x: 0, y: CGFloat(targetY)), to: scroll).y - scroll.bounds.minY
return abs(position - scroll.adjustedContentInset.top) < 5
}
XCTAssertFalse(web.scrollView.isScrollEnabled)
XCTAssertEqual(web.scrollView.contentOffset.y, 0, accuracy: 1)
let innerOffset = try await web.evaluateJavaScript("window.scrollY") as? Double
XCTAssertEqual(innerOffset ?? -1, 0, accuracy: 1)
record(UIGraphicsImageRenderer(size: controller.view.bounds.size).image { _ in
controller.view.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}, name: "课程附件-文内锚点整页定位")
}
/// 多页 PDF 完整撑高,最后一页可通过课程页面滚动抵达,不再嵌套 PDFKit 滚动容器。
func testMultipagePDFReachesLastPageUsingOuterScrollView() async throws {
let renderer = UIGraphicsPDFRenderer(bounds: CGRect(x: 0, y: 0, width: 300, height: 450))
let headingFont = try XCTUnwrap(UIFont(name: "Helvetica", size: 18))
let markerFont = try XCTUnwrap(UIFont(name: "Helvetica", size: 14))
let data = renderer.pdfData { context in
for page in 1...6 {
context.beginPage()
("Training PDF page \(page) of 6" as NSString).draw(at: CGPoint(x: 24, y: 28), withAttributes: [.font: headingFont])
("PDF_PAGE_END_\(page)" as NSString).draw(at: CGPoint(x: 24, y: 410), withAttributes: [.font: markerFont])
}
}
let fixture = try XCTUnwrap(PDFDocument(data: data))
// 页身份保存在 PDF 自身的注解中,避免把字体字形映射的文本抽取能力混入滚动回归。
for index in 0..<fixture.pageCount {
let page = try XCTUnwrap(fixture.page(at: index))
let identity = PDFAnnotation(bounds: CGRect(x: 0, y: 0, width: 1, height: 1), forType: .link, withProperties: nil)
identity.contents = "COURSE_PAGE_\(index + 1)"
identity.url = URL(string: "https://example.test/course-page/\(index + 1)")
page.addAnnotation(identity)
}
let serialized = try XCTUnwrap(fixture.dataRepresentation())
let document = try temporaryDocument(data: serialized, kind: .pdf)
defer { try? FileManager.default.removeItem(at: document.fileURL.deletingLastPathComponent()) }
let (controller, preview, scroll, window) = try await makeCourseWindow(document: document)
defer { closeWindow(window) }
let pdf = try XCTUnwrap(allViews(preview).compactMap { $0 as? TrainingPDFDocumentView }.first)
XCTAssertEqual(pdf.document?.pageCount, 6)
let lastPage = try XCTUnwrap(pdf.document?.page(at: 5))
XCTAssertEqual(lastPage.annotations.compactMap(\.contents), ["COURSE_PAGE_6"])
XCTAssertTrue(allViews(pdf).compactMap { $0 as? UIScrollView }.isEmpty)
XCTAssertGreaterThan(preview.preferredContentHeight, scroll.bounds.height * 4)
XCTAssertEqual(preview.bounds.height, preview.preferredContentHeight, accuracy: 1)
scrollToBottom(scroll)
controller.view.layoutIfNeeded()
let pdfBottom = pdf.convert(CGPoint(x: 0, y: pdf.bounds.maxY), to: scroll).y
XCTAssertLessThanOrEqual(pdfBottom, scroll.bounds.maxY + 3)
XCTAssertGreaterThan(pdfBottom, scroll.bounds.minY)
try await Task.sleep(for: .milliseconds(200))
record(UIGraphicsImageRenderer(size: controller.view.bounds.size).image { _ in
controller.view.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}, name: "课程附件-多页PDF整页滑至末页")
}
private func temporaryDocument(text: String, kind: TrainingDocumentKind) throws -> TrainingLocalDocument {
try temporaryDocument(data: Data(text.utf8), kind: kind)
}
private func temporaryDocument(data: Data, kind: TrainingDocumentKind) throws -> TrainingLocalDocument {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("training-scroll-test-\(UUID().uuidString)")
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let file = directory.appendingPathComponent("course.\(kind.rawValue)")
try data.write(to: file)
return TrainingLocalDocument(fileURL: file, kind: kind, name: file.lastPathComponent, temporaryDirectory: nil)
}
private func makeCourseWindow(document: TrainingLocalDocument) async throws -> (TrainingCourseViewController, TrainingDocumentPreviewView, UIScrollView, UIWindow) {
let source = TrainingDataStub()
let name = document.name
let mime: String
switch document.kind {
case .pdf: mime = "application/pdf"
case .docx: mime = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
case .txt: mime = "text/plain"
case .md: mime = "text/markdown"
}
await source.configure {
$0.attachmentsHandler = { _ in TrainingCursorPage(items: [TrainingRemoteFixtures.attachment(name: name, mimeType: mime)], nextCursor: nil, hasMore: false, serverTime: nil) }
}
let controller = TrainingCourseViewController(taskID: "task_1", service: source,
documentLoader: TrainingFixtureDocumentLoader { _, _ in document })
let window = try makeWindow(UINavigationController(rootViewController: controller))
do {
let preview = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? TrainingDocumentPreviewView }.first)
try await waitUntil { preview.isReady }
let scroll = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? UIScrollView }
.first { $0.accessibilityIdentifier == "training.reading.scroll" })
return (controller, preview, scroll, window)
} catch {
closeWindow(window)
throw error
}
}
private func scrollToBottom(_ scroll: UIScrollView) {
let bottom = max(-scroll.adjustedContentInset.top,
scroll.contentSize.height - scroll.bounds.height + scroll.adjustedContentInset.bottom)
scroll.setContentOffset(CGPoint(x: 0, y: bottom), animated: false)
}
private func showDocument(_ kind: TrainingDocumentKind, in preview: TrainingDocumentPreviewView) async throws {
let id = UUID()
var readyID: UUID?
var failure: String?
preview.onReady = { readyID = $0 }
preview.onFailure = { _, message in failure = message }
preview.show(try TrainingDocumentTestFixtures.document(kind: kind), requestID: id)
try await waitUntil { readyID != nil || failure != nil }
XCTAssertNil(failure)
XCTAssertEqual(readyID, id)
XCTAssertTrue(preview.isReady)
guard preview.isReady else { throw TrainingDocumentError.invalidFile }
}
private func makePreviewWindow() throws -> (TrainingDocumentPreviewView, UIWindow) {
let controller = UIViewController()
let preview = TrainingDocumentPreviewView()
controller.view.addSubview(preview)
preview.frame = CGRect(x: 12, y: 80, width: 366, height: 640)
return (preview, try makeWindow(controller))
}
private func makeWindow(_ controller: UIViewController) throws -> UIWindow {
let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
previousKeyWindow = scene.windows.first { $0.isKeyWindow }
let window = UIWindow(windowScene: scene)
window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
window.rootViewController = controller
window.makeKeyAndVisible()
controller.view.layoutIfNeeded()
return window
}
private func closeWindow(_ window: UIWindow) {
window.isHidden = true
window.rootViewController = nil
previousKeyWindow?.makeKey()
previousKeyWindow = nil
}
private func documentWebView(in view: UIView) throws -> WKWebView {
try XCTUnwrap(allViews(view).compactMap { $0 as? WKWebView }.first)
}
private func allViews(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap { allViews($0) } }
private func record(_ image: UIImage, name: String) {
let attachment = XCTAttachment(image: image)
attachment.name = name
attachment.lifetime = .keepAlways
add(attachment)
}
private func waitUntil(_ condition: @MainActor () async -> Bool) async throws {
let deadline = ContinuousClock.now.advanced(by: .seconds(15))
while !(await condition()), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
let reached = await condition()
XCTAssertTrue(reached, "文档未在期限内完成真实渲染或返回失败事件")
guard reached else { throw CancellationError() }
}
}
@@ -0,0 +1,35 @@
import Foundation
@testable import suixinkan
/// 定位测试 target 的附件资源,避免依赖开发机文件路径或真实网络。
enum TrainingDocumentTestFixtures {
/// 返回已打包的本地文档,资源不会由预览器删除。
static func document(kind: TrainingDocumentKind = .txt, resource: String = "training-preview-sample") throws -> TrainingLocalDocument {
let bundle = Bundle(for: TrainingDocumentBundleMarker.self)
let file = bundle.url(forResource: resource, withExtension: kind.rawValue)
?? bundle.url(forResource: resource, withExtension: kind.rawValue, subdirectory: "Fixtures/TrainingDocuments")
guard let file else { throw CocoaError(.fileNoSuchFile) }
return TrainingLocalDocument(fileURL: file, kind: kind, name: "\(resource).\(kind.rawValue)", temporaryDirectory: nil)
}
}
/// 给 Bundle 定位测试资源使用的普通 NSObject 类型。
private final class TrainingDocumentBundleMarker: NSObject {}
/// 注入真实本地文件,可在下载入口挂起或失败,仍通过正式渲染器展示。
struct TrainingFixtureDocumentLoader: TrainingDocumentLoading {
/// 可覆盖一次下载过程;默认依据授权附件类型读取测试文件。
var handler: (@Sendable (TrainingAttachmentInfo, TrainingAttachmentLink) async throws -> TrainingLocalDocument)?
/// 创建无网络的文档加载器,允许测试控制请求的完成时机。
init(handler: (@Sendable (TrainingAttachmentInfo, TrainingAttachmentLink) async throws -> TrainingLocalDocument)? = nil) {
self.handler = handler
}
/// 保留正式格式识别规则,只替换文件获取路径。
func load(attachment: TrainingAttachmentInfo, link: TrainingAttachmentLink) async throws -> TrainingLocalDocument {
if let handler { return try await handler(attachment, link) }
let kind = try TrainingDocumentKind.resolve(name: attachment.name, mimeType: attachment.mimeType, url: link.url)
return try TrainingDocumentTestFixtures.document(kind: kind)
}
}
+278 -60
View File
@@ -24,33 +24,35 @@ struct TrainingRemoteReadingTests {
} }
} }
/// 百节课程首次只读一页目录和一节正文,明确选择过的正文才缓存。 private func loadRendered(_ model: TrainingRemoteReadingViewModel) async {
@Test("首次不遍历百节正文,目录主动分页,正文按选择复用") await model.load()
if let id = model.currentAttachmentID, let previewID = model.attachmentPreviewID {
#expect(model.markAttachmentRendered(id: id, previewID: previewID))
}
}
/// 首屏只读取一页附件并授权首项,不请求已经停用的小节 HTML。
@Test("首次仅请求附件第一页并授权首项,不加载小节 HTML")
func lazyCourseResources() async { func lazyCourseResources() async {
let source = source() let source = source()
await source.configure { await source.configure {
$0.courseHandler = { TrainingCourseInfo(id: "course_1", title: "课程", introduction: "简介", sectionCount: 100, attachmentCount: 20) } $0.courseHandler = { TrainingCourseInfo(id: "course_1", title: "课程", introduction: "简介", sectionCount: 100, attachmentCount: 20) }
$0.sectionsHandler = { cursor in $0.attachmentsHandler = { _ in
let range = cursor == nil ? 1...20 : 21...40 TrainingCursorPage(items: (1...20).map { TrainingRemoteFixtures.attachment(id: "file_\($0)") },
return TrainingCursorPage(items: range.map { TrainingSectionInfo(id: "s\($0)", order: $0, title: "小节\($0)") }, nextCursor: "next", hasMore: true, serverTime: nil)
nextCursor: cursor == nil ? "next" : "last", hasMore: true, serverTime: nil)
} }
} }
let model = model(source) let model = model(source)
await model.load() await model.load()
var calls = await source.calls let calls = await source.calls
#expect(model.sections.count == 20) #expect(model.attachments.count == 20)
#expect(calls.filter { $0.name == "sections" }.count == 1) #expect(model.currentAttachmentID == "file_1")
#expect(calls.first { $0.name == "sections" }?.limit == 20) #expect(model.currentAttachmentLink?.id == "file_1")
#expect(calls.filter { $0.name == "section" }.count == 1) #expect(calls.filter { $0.name == "attachments" }.count == 1)
#expect(!calls.contains { ["attachments", "paper", "questions", "draft", "attempts"].contains($0.name) }) #expect(calls.first { $0.name == "attachments" }?.limit == 20)
await model.loadMoreSections() #expect(calls.filter { $0.name == "attachmentURL" }.map(\.resourceID) == ["file_1"])
#expect(model.sections.count == 40) #expect(!calls.contains { ["sections", "section", "paper", "questions", "draft", "attempts"].contains($0.name) })
await model.selectSection(id: "s2") #expect(!model.isAttachmentRendered)
await model.selectSection(id: "s1")
calls = await source.calls
#expect(calls.filter { $0.name == "section" }.count == 2)
#expect(calls.filter { $0.name == "sections" }.last?.cursor == "next")
} }
/// 倒计时本地刷新,五秒合并网络上报,最后一个片段关闭会话。 /// 倒计时本地刷新,五秒合并网络上报,最后一个片段关闭会话。
@@ -58,7 +60,7 @@ struct TrainingRemoteReadingTests {
func batchedHeartbeatAndCompletion() async { func batchedHeartbeatAndCompletion() async {
let source = source() let source = source()
let model = model(source) let model = model(source)
await model.load() await loadRendered(model)
await model.startReading(at: 0) await model.startReading(at: 0)
for second in 1...4 { await model.recordVisibleTime(at: Double(second)) } for second in 1...4 { await model.recordVisibleTime(at: Double(second)) }
#expect(await source.heartbeats.isEmpty) #expect(await source.heartbeats.isEmpty)
@@ -78,7 +80,7 @@ struct TrainingRemoteReadingTests {
func historyAndSessionAreSeparate() async { func historyAndSessionAreSeparate() async {
let source = source(seconds: 12) let source = source(seconds: 12)
let model = model(source) let model = model(source)
await model.load() await loadRendered(model)
await model.startReading(at: 0) await model.startReading(at: 0)
for second in 1...8 { await model.recordVisibleTime(at: Double(second)) } for second in 1...8 { await model.recordVisibleTime(at: Double(second)) }
let calls = await source.heartbeats let calls = await source.heartbeats
@@ -93,7 +95,7 @@ struct TrainingRemoteReadingTests {
func pauseDoesNotCountBackgroundTime() async { func pauseDoesNotCountBackgroundTime() async {
let source = source() let source = source()
let model = model(source) let model = model(source)
await model.load() await loadRendered(model)
await model.startReading(at: 0) await model.startReading(at: 0)
for second in 1...3 { await model.recordVisibleTime(at: Double(second)) } for second in 1...3 { await model.recordVisibleTime(at: Double(second)) }
model.pauseReading() model.pauseReading()
@@ -120,7 +122,7 @@ struct TrainingRemoteReadingTests {
let server = TrainingReadingReplyController(loseCreateResponse: true) let server = TrainingReadingReplyController(loseCreateResponse: true)
await bind(server, to: source) await bind(server, to: source)
let model = model(source) let model = model(source)
await model.load() await loadRendered(model)
await model.startReading(at: 0) await model.startReading(at: 0)
#expect(model.readingErrorMessage != nil) #expect(model.readingErrorMessage != nil)
await model.startReading(at: 10) await model.startReading(at: 10)
@@ -138,7 +140,7 @@ struct TrainingRemoteReadingTests {
let server = TrainingReadingReplyController(loseHeartbeatResponse: true) let server = TrainingReadingReplyController(loseHeartbeatResponse: true)
await bind(server, to: source) await bind(server, to: source)
let model = model(source) let model = model(source)
await model.load() await loadRendered(model)
await model.startReading(at: 0) await model.startReading(at: 0)
for second in 1...5 { await model.recordVisibleTime(at: Double(second)) } for second in 1...5 { await model.recordVisibleTime(at: Double(second)) }
#expect(model.progress?.readingSeconds == 0) #expect(model.progress?.readingSeconds == 0)
@@ -158,7 +160,7 @@ struct TrainingRemoteReadingTests {
let server = TrainingReadingReplyController(loseHeartbeatResponse: true) let server = TrainingReadingReplyController(loseHeartbeatResponse: true)
await bind(server, to: source) await bind(server, to: source)
let model = model(source) let model = model(source)
await model.load() await loadRendered(model)
await model.startReading(at: 0) await model.startReading(at: 0)
for second in 1...3 { await model.recordVisibleTime(at: Double(second)) } for second in 1...3 { await model.recordVisibleTime(at: Double(second)) }
model.pauseReading() model.pauseReading()
@@ -184,7 +186,7 @@ struct TrainingRemoteReadingTests {
let gate = TrainingReadingHeartbeatGate() let gate = TrainingReadingHeartbeatGate()
await source.configure { $0.heartbeatHandler = { await gate.confirm($0) } } await source.configure { $0.heartbeatHandler = { await gate.confirm($0) } }
let model = model(source) let model = model(source)
await model.load() await loadRendered(model)
await model.startReading(at: 0) await model.startReading(at: 0)
for second in 1...4 { await model.recordVisibleTime(at: Double(second)) } for second in 1...4 { await model.recordVisibleTime(at: Double(second)) }
let operation = Task { await model.recordVisibleTime(at: 5) } let operation = Task { await model.recordVisibleTime(at: 5) }
@@ -216,7 +218,7 @@ struct TrainingRemoteReadingTests {
return try await server.confirm(call) return try await server.confirm(call)
} } } }
let model = model(source) let model = model(source)
await model.load() await loadRendered(model)
await model.startReading(at: 0) await model.startReading(at: 0)
for second in 1...3 { await model.recordVisibleTime(at: Double(second)) } for second in 1...3 { await model.recordVisibleTime(at: Double(second)) }
let closing = Task { await model.flush(final: true) } let closing = Task { await model.flush(final: true) }
@@ -246,7 +248,7 @@ struct TrainingRemoteReadingTests {
func notWritableRefreshesReadOnlyState() async { func notWritableRefreshesReadOnlyState() async {
let source = source() let source = source()
let model = model(source) let model = model(source)
await model.load() await loadRendered(model)
await model.startReading(at: 0) await model.startReading(at: 0)
let saved = TrainingRemoteFixtures.progress(seconds: 7) let saved = TrainingRemoteFixtures.progress(seconds: 7)
let readOnly = TrainingProgressSnapshot(taskID: saved.taskID, readingSeconds: saved.readingSeconds, let readOnly = TrainingProgressSnapshot(taskID: saved.taskID, readingSeconds: saved.readingSeconds,
@@ -263,7 +265,7 @@ struct TrainingRemoteReadingTests {
for second in 1...5 { await model.recordVisibleTime(at: Double(second)) } for second in 1...5 { await model.recordVisibleTime(at: Double(second)) }
#expect(!model.canStudy) #expect(!model.canStudy)
#expect(model.progress?.blockReason == "closed") #expect(model.progress?.blockReason == "closed")
#expect(model.currentSection != nil) #expect(model.currentAttachmentLink != nil)
await model.startReading(at: 100) await model.startReading(at: 100)
#expect(await source.startReadingRequests.count == 1) #expect(await source.startReadingRequests.count == 1)
#expect(!model.isReading) #expect(!model.isReading)
@@ -277,14 +279,14 @@ struct TrainingRemoteReadingTests {
func accessDenialInvalidatesCourse(_ failure: TrainingRemoteError) async { func accessDenialInvalidatesCourse(_ failure: TrainingRemoteError) async {
let source = source() let source = source()
let model = model(source) let model = model(source)
await model.load() await loadRendered(model)
await model.startReading(at: 0) await model.startReading(at: 0)
await source.configure { $0.heartbeatHandler = { _ in throw failure } } await source.configure { $0.heartbeatHandler = { _ in throw failure } }
for second in 1...5 { await model.recordVisibleTime(at: Double(second)) } for second in 1...5 { await model.recordVisibleTime(at: Double(second)) }
#expect(model.isInvalidated) #expect(model.isInvalidated)
#expect(model.currentSection == nil) #expect(model.currentAttachmentLink == nil)
#expect(model.progress == nil) #expect(model.progress == nil)
#expect(model.sections.isEmpty) #expect(model.attachments.isEmpty)
#expect(!model.isReading) #expect(!model.isReading)
} }
@@ -298,7 +300,7 @@ struct TrainingRemoteReadingTests {
let server = TrainingReadingReplyController(nextFailure: failure) let server = TrainingReadingReplyController(nextFailure: failure)
await bind(server, to: source) await bind(server, to: source)
let model = model(source) let model = model(source)
await model.load() await loadRendered(model)
await model.startReading(at: 0) await model.startReading(at: 0)
for second in 1...5 { await model.recordVisibleTime(at: Double(second)) } for second in 1...5 { await model.recordVisibleTime(at: Double(second)) }
#expect(model.isReading) #expect(model.isReading)
@@ -314,12 +316,12 @@ struct TrainingRemoteReadingTests {
#expect((await source.calls).filter { $0.name == "progress" }.count >= 2) #expect((await source.calls).filter { $0.name == "progress" }.count >= 2)
} }
/// 正文请求挂起时切身份,旧正文不能回到已经关闭的学员页面。 /// 授权请求挂起时切身份,旧短链不能重新打开已经关闭的页面。
@Test("身份切换丢弃迟到正文和权威进度") @Test("身份切换丢弃迟到附件授权和权威进度")
func identityChangeDiscardsLateBody() async { func identityChangeDiscardsLateAttachment() async {
let source = source() let source = source()
let gate = TrainingReadingBodyGate() let gate = TrainingReadingAttachmentGate()
await source.configure { $0.sectionHandler = { _ in await gate.body() } } await source.configure { $0.attachmentURLHandler = { _ in await gate.link() } }
let model = model(source) let model = model(source)
let operation = Task { await model.load() } let operation = Task { await model.load() }
await gate.waitUntilRequested() await gate.waitUntilRequested()
@@ -328,37 +330,251 @@ struct TrainingRemoteReadingTests {
await operation.value await operation.value
#expect(model.isInvalidated) #expect(model.isInvalidated)
#expect(model.task == nil) #expect(model.task == nil)
#expect(model.currentSection == nil) #expect(model.currentAttachment == nil)
#expect(model.currentAttachmentLink == nil)
#expect(model.attachmentPreviewID == nil)
#expect(model.progress == nil) #expect(model.progress == nil)
#expect(model.sections.isEmpty) #expect(model.attachments.isEmpty)
} }
/// 元信息不提前授权文件,用户点击附件时才申请短期可打开链接。 /// 后续附件页需要用户主动读取,分页不能提前授权其余文档。
@Test("附件目录按需分页,点击才获取授权地址") @Test("附件目录主动分页且只在选择时授权后续附件")
func attachmentsAreLazyAndAuthorized() async { func attachmentsAreLazyAndAuthorized() async {
let source = source(seconds: 20) let source = source(seconds: 20)
await source.configure { await source.configure {
$0.attachmentsHandler = { cursor in $0.attachmentsHandler = { cursor in
let id = cursor == nil ? "file_1" : "file_2" let id = cursor == nil ? "file_1" : "file_2"
let item = TrainingAttachmentInfo(id: id, name: "培训.pdf", mimeType: "application/pdf", sizeBytes: 1024, return TrainingCursorPage(items: [TrainingRemoteFixtures.attachment(id: id)],
fileID: id, downloadURL: nil, expiresAt: nil) nextCursor: cursor == nil ? "next" : nil,
return TrainingCursorPage(items: [item], nextCursor: cursor == nil ? "next" : nil,
hasMore: cursor == nil, serverTime: nil) hasMore: cursor == nil, serverTime: nil)
} }
} }
let model = model(source) let model = model(source)
await model.load() await model.load()
#expect(!(await source.calls).contains { $0.name == "attachments" })
await model.loadAttachments() await model.loadAttachments()
await model.loadAttachments() await model.loadAttachments()
#expect((await source.calls).filter { $0.name == "attachments" }.count == 1) #expect((await source.calls).filter { $0.name == "attachments" }.count == 1)
#expect(!(await source.calls).contains { $0.name == "attachmentURL" }) #expect((await source.calls).filter { $0.name == "attachmentURL" }.count == 1)
await model.loadAttachments(loadMore: true) await model.loadAttachments(loadMore: true)
#expect(model.attachments.count == 2) #expect(model.attachments.count == 2)
let link = await model.authorizeAttachment(id: "file_1") #expect((await source.calls).filter { $0.name == "attachments" }.last?.cursor == "next")
#expect(link?.url.scheme == "https")
#expect(link?.expiresAt == TrainingRemoteFixtures.now.addingTimeInterval(3600))
#expect((await source.calls).filter { $0.name == "attachmentURL" }.count == 1) #expect((await source.calls).filter { $0.name == "attachmentURL" }.count == 1)
await model.selectAttachment(id: "file_2")
#expect(model.currentAttachmentID == "file_2")
#expect(model.currentAttachmentLink?.expiresAt == TrainingRemoteFixtures.now.addingTimeInterval(3600))
#expect((await source.calls).filter { $0.name == "attachmentURL" }.map(\.resourceID) == ["file_1", "file_2"])
#expect(!model.isAttachmentRendered)
}
/// 分页失败只提示列表错误,不能把已显示文件变成失败态或丢弃已累计秒数。
@Test("附件分页失败可重试,当前文档继续阅读且成功后清提示")
func attachmentPaginationErrorDoesNotInterruptReading() async throws {
let source = source()
await source.configure {
$0.attachmentsHandler = { _ in
TrainingCursorPage(items: [TrainingRemoteFixtures.attachment()], nextCursor: "next", hasMore: true, serverTime: nil)
}
}
let model = model(source)
await loadRendered(model)
let previewID = try #require(model.attachmentPreviewID)
let link = try #require(model.currentAttachmentLink)
await model.startReading(at: 0)
await model.recordVisibleTime(at: 1)
await source.configure { $0.attachmentsHandler = { _ in throw URLError(.timedOut) } }
await model.loadAttachments(loadMore: true)
#expect(model.attachmentListErrorMessage != nil)
#expect(model.attachmentErrorMessage == nil && model.errorMessage == nil)
#expect(model.isAttachmentRendered && model.isReading && model.canStudy)
#expect(model.currentAttachmentLink == link && model.attachmentPreviewID == previewID)
#expect(model.attachments.count == 1 && model.hasMoreAttachments)
#expect(model.markAttachmentRendered(id: "file_1", previewID: previewID))
await model.recordVisibleTime(at: 2)
#expect(model.activeSecondsTotal == 2)
await source.configure {
$0.attachmentsHandler = { _ in
TrainingCursorPage(items: [TrainingRemoteFixtures.attachment(id: "file_2")], nextCursor: nil, hasMore: false, serverTime: nil)
}
}
await model.loadAttachments(loadMore: true)
#expect(model.attachmentListErrorMessage == nil && model.errorMessage == nil)
#expect(model.attachments.map(\.id) == ["file_1", "file_2"])
#expect(!model.hasMoreAttachments)
#expect(model.currentAttachmentLink == link && model.attachmentPreviewID == previewID)
#expect(model.isAttachmentRendered && model.isReading)
await model.recordVisibleTime(at: 3)
model.pauseReading()
await model.flush()
let heartbeats = await source.heartbeats
#expect(heartbeats.count == 1)
#expect(heartbeats.first?.activeSecondsTotal == 3 && heartbeats.first?.final == true)
#expect(await source.startReadingRequests.count == 1)
let calls = await source.calls
#expect(calls.filter { $0.name == "attachments" }.map(\.cursor) == [nil, "next", "next"])
#expect(calls.filter { $0.name == "attachmentURL" }.count == 1)
}
/// 授权被撤回不是普通分页故障,必须清理已经可读的文件并立即停止学习。
@Test("附件分页返回账号或权限失效时仍清内容退出", arguments: [
TrainingRemoteError.accountInvalid("account no longer eligible"),
TrainingRemoteError.forbidden("assignment revoked")
])
func attachmentPaginationAccessDenialInvalidatesCourse(_ failure: TrainingRemoteError) async {
let source = source()
await source.configure {
$0.attachmentsHandler = { _ in
TrainingCursorPage(items: [TrainingRemoteFixtures.attachment()], nextCursor: "next", hasMore: true, serverTime: nil)
}
}
let model = model(source)
await loadRendered(model)
await model.startReading(at: 0)
await source.configure { $0.attachmentsHandler = { _ in throw failure } }
await model.loadAttachments(loadMore: true)
#expect(model.isInvalidated)
#expect(!model.isReading && !model.isAttachmentRendered)
#expect(model.attachments.isEmpty && model.currentAttachmentLink == nil)
#expect(model.attachmentListErrorMessage == nil)
}
/// 只有文档下载与渲染都结束并由页面确认后才建立学习会话。
@Test("附件授权不代表已展示,渲染确认前不能累计读时")
func authorizedAttachmentWaitsForRendering() async throws {
let source = source()
let model = model(source)
await model.load()
#expect(model.currentAttachmentLink != nil)
await model.startReading(at: 0)
await model.recordVisibleTime(at: 100)
#expect(await source.startReadingRequests.isEmpty)
#expect(await source.heartbeats.isEmpty)
let previewID = try #require(model.attachmentPreviewID)
#expect(!model.markAttachmentRendered(id: "another-file", previewID: previewID))
#expect(!model.markAttachmentRendered(id: "file_1", previewID: UUID()))
#expect(model.markAttachmentRendered(id: "file_1", previewID: previewID))
await model.startReading(at: 200)
await model.recordVisibleTime(at: 201)
#expect(model.isReading)
#expect(model.activeSecondsTotal == 1)
#expect(await source.startReadingRequests.count == 1)
}
/// 没有课程文档时保留元信息空态,不请求 HTML,也不能通过空白页获得进度。
@Test("无附件保留课程元信息但不建立会话或回退 HTML")
func missingAttachmentDoesNotCountReading() async {
let source = source()
await source.configure {
$0.attachmentsHandler = { _ in TrainingCursorPage(items: [], nextCursor: nil, hasMore: false, serverTime: nil) }
}
let model = model(source)
await model.load()
await model.startReading(at: 0)
await model.recordVisibleTime(at: 1000)
#expect(model.task != nil && model.course != nil && model.progress != nil)
#expect(model.hasLoadedAttachments)
#expect(model.currentAttachment == nil)
#expect(model.currentAttachmentLink == nil)
#expect(!model.isAttachmentRendered)
#expect(!model.markAttachmentRendered(id: "file_1", previewID: UUID()))
#expect(!(await source.calls).contains { ["section", "sections", "attachmentURL", "startReading", "heartbeat"].contains($0.name) })
}
/// 授权失败仍展示课程规则和附件名,重试成功后也要等待实际渲染。
@Test("授权失败可重试同一附件,课程元信息不丢失")
func authorizationFailureKeepsMetadataForRetry() async throws {
let source = source()
await source.configure { $0.attachmentURLHandler = { _ in throw URLError(.timedOut) } }
let model = model(source)
await model.load()
#expect(model.task != nil && model.course != nil && model.progress != nil)
#expect(model.currentAttachmentID == "file_1")
#expect(model.currentAttachmentLink == nil)
#expect(model.attachmentErrorMessage != nil)
await model.startReading(at: 0)
#expect(await source.startReadingRequests.isEmpty)
let failedPreviewID = try #require(model.attachmentPreviewID)
await source.configure { $0.attachmentURLHandler = nil }
await model.selectAttachment(id: "file_1")
let nextPreviewID = try #require(model.attachmentPreviewID)
#expect(nextPreviewID != failedPreviewID)
#expect(model.currentAttachmentLink != nil)
#expect(model.attachmentErrorMessage == nil)
#expect(!model.markAttachmentRendered(id: "file_1", previewID: failedPreviewID))
#expect(model.markAttachmentRendered(id: "file_1", previewID: nextPreviewID))
}
/// 预览失败停止当前片段,进度刷新不得误清错误或恢复读时。
@Test("附件预览失败停止读时,错误跨进度刷新保留")
func previewFailureStopsReadingAndSurvivesProgressRefresh() async throws {
let source = source()
let model = model(source)
await loadRendered(model)
let previewID = try #require(model.attachmentPreviewID)
await model.startReading(at: 0)
for second in 1...3 { await model.recordVisibleTime(at: Double(second)) }
model.reportAttachmentFailure(id: "file_1", previewID: previewID, message: "文档加载失败")
#expect(!model.isReading && !model.isAttachmentRendered)
await model.flush()
await model.refreshProgress()
#expect(model.attachmentErrorMessage == "文档加载失败")
#expect(model.errorMessage == "文档加载失败")
#expect(!model.markAttachmentRendered(id: "file_1", previewID: previewID))
await model.startReading(at: 100)
await model.recordVisibleTime(at: 101)
let calls = await source.heartbeats
#expect(calls.count == 1)
#expect(calls.first?.activeSecondsTotal == 3 && calls.first?.final == true)
#expect(await source.startReadingRequests.count == 1)
#expect(model.progress?.readingSeconds == 3)
}
/// 切文档关闭旧片段,旧下载成功或失败回调都不能改变新文档。
@Test("切附件先 final 保存,旧预览回调无效,新文档重新计时")
func switchingAttachmentClosesReadingAndRejectsLatePreview() async throws {
let source = source()
await source.configure {
$0.attachmentsHandler = { _ in TrainingCursorPage(items: [TrainingRemoteFixtures.attachment(), TrainingRemoteFixtures.attachment(id: "file_2")], nextCursor: nil, hasMore: false, serverTime: nil) }
}
let model = model(source)
await loadRendered(model)
let oldPreviewID = try #require(model.attachmentPreviewID)
await model.startReading(at: 0)
for second in 1...3 { await model.recordVisibleTime(at: Double(second)) }
await model.selectAttachment(id: "file_2")
let calls = await source.heartbeats
#expect(calls.count == 1)
#expect(calls.first?.activeSecondsTotal == 3 && calls.first?.final == true)
#expect(!model.isReading && !model.isAttachmentRendered)
#expect(!model.markAttachmentRendered(id: "file_1", previewID: oldPreviewID))
model.reportAttachmentFailure(id: "file_1", previewID: oldPreviewID, message: "迟到错误")
#expect(model.attachmentErrorMessage == nil)
await model.startReading(at: 100)
#expect(await source.startReadingRequests.count == 1)
let previewID = try #require(model.attachmentPreviewID)
#expect(model.markAttachmentRendered(id: "file_2", previewID: previewID))
await model.startReading(at: 200)
await model.recordVisibleTime(at: 201)
#expect(model.activeSecondsTotal == 1)
#expect(await source.startReadingRequests.count == 2)
#expect(model.progress?.readingSeconds == 3)
}
/// 不能显示服务端错误返回的另一份附件,即使地址本身和有效期合法。
@Test("附件授权响应必须匹配所选附件标识")
func mismatchedAttachmentAuthorizationIsRejected() async {
let source = source()
await source.configure { $0.attachmentURLHandler = { _ in
TrainingAttachmentLink(id: "other-file", name: "另一份文档.txt",
url: URL(string: "https://example.test/other.txt")!,
expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(60))
} }
let model = model(source)
await model.load()
#expect(model.currentAttachmentID == "file_1")
#expect(model.currentAttachmentLink == nil)
#expect(model.attachmentErrorMessage != nil)
await model.startReading(at: 0)
#expect(await source.startReadingRequests.isEmpty)
} }
/// 两种网页协议都能打开,带签名的查询参数不在客户端改写。 /// 两种网页协议都能打开,带签名的查询参数不在客户端改写。
@@ -414,10 +630,10 @@ struct TrainingRemoteReadingTests {
func readOnlyDoesNotStartSession() async { func readOnlyDoesNotStartSession() async {
let source = source(seconds: 20) let source = source(seconds: 20)
let model = model(source) let model = model(source)
await model.load() await loadRendered(model)
await model.startReading(at: 0) await model.startReading(at: 0)
await model.recordVisibleTime(at: 1000) await model.recordVisibleTime(at: 1000)
#expect(model.currentSection != nil) #expect(model.currentAttachmentLink != nil)
#expect(await source.startReadingRequests.isEmpty) #expect(await source.startReadingRequests.isEmpty)
#expect(await source.heartbeats.isEmpty) #expect(await source.heartbeats.isEmpty)
#expect(!model.isReading) #expect(!model.isReading)
@@ -473,13 +689,13 @@ private actor TrainingReadingReplyController {
} }
} }
/// 不使用固定延时的正文响应闸门,精确控制身份切换和迟到响应的先后顺序。 /// 不使用固定延时的附件授权响应闸门,控制身份切换和迟到响应顺序。
private actor TrainingReadingBodyGate { private actor TrainingReadingAttachmentGate {
private var response: CheckedContinuation<TrainingSectionContent, Never>? private var response: CheckedContinuation<TrainingAttachmentLink, Never>?
private var waiters: [CheckedContinuation<Void, Never>] = [] private var waiters: [CheckedContinuation<Void, Never>] = []
/// 等待测试明确释放正文,通知等待请求已发出的测试代码。 /// 等待测试释放短链,通知测试请求已挂起。
func body() async -> TrainingSectionContent { func link() async -> TrainingAttachmentLink {
await withCheckedContinuation { await withCheckedContinuation {
response = $0 response = $0
waiters.forEach { $0.resume() } waiters.forEach { $0.resume() }
@@ -487,15 +703,17 @@ private actor TrainingReadingBodyGate {
} }
} }
/// 不轮询地等待正文请求已经挂起。 /// 等待授权请求已经挂起。
func waitUntilRequested() async { func waitUntilRequested() async {
if response != nil { return } if response != nil { return }
await withCheckedContinuation { waiters.append($0) } await withCheckedContinuation { waiters.append($0) }
} }
/// 在身份已变化后返回旧账号正文。 /// 在身份变化后返回旧任务附件地址。
func release() { func release() {
response?.resume(returning: TrainingSectionContent(id: "s1", order: 1, title: "旧正文", contentHTML: "<p>旧账号课程</p>")) response?.resume(returning: TrainingAttachmentLink(id: "file_1", name: "旧文档.txt",
url: URL(string: "https://example.test/training.txt")!,
expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600)))
response = nil response = nil
} }
} }
+43 -7
View File
@@ -1,6 +1,7 @@
import Foundation import Foundation
import Testing import Testing
import UIKit import UIKit
import WebKit
@testable import suixinkan @testable import suixinkan
#if DEBUG #if DEBUG
@@ -66,17 +67,24 @@ struct TrainingUIRenderingTests {
let model = TrainingRemoteExamViewModel(taskID: "task_1", context: context, let model = TrainingRemoteExamViewModel(taskID: "task_1", context: context,
pendingStore: TrainingPendingSubmissionStore(defaults: defaults), currentContext: { context }) pendingStore: TrainingPendingSubmissionStore(defaults: defaults), currentContext: { context })
let source = TrainingDataStub() let source = TrainingDataStub()
let course = TrainingCourseViewController(taskID: "task_1", service: source) let course = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: TrainingFixtureDocumentLoader())
let exam = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model) let exam = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
for (controller, selectedTitle) in [(course as UIViewController, "1 课程学习"), (exam, "2 在线考试")] { for (controller, selectedTitle) in [(course as UIViewController, "1 课程学习"), (exam, "2 在线考试")] {
let navigation = UINavigationController(rootViewController: controller) let navigation = UINavigationController(rootViewController: controller)
let window = try makeWindow(navigation, width: width) let window = try makeWindow(navigation, width: width)
defer { window.isHidden = true } defer { window.isHidden = true }
let deadline = ContinuousClock.now.advanced(by: .seconds(5)) let isReady: () -> Bool = {
while (!allViews(controller.view).contains { $0 is TrainingStepView } guard self.allViews(controller.view).contains(where: { $0 is TrainingStepView && !$0.isHidden }) else { return false }
|| (controller === exam && !model.canEdit)), ContinuousClock.now < deadline { if controller === course {
return self.allViews(controller.view).compactMap({ $0 as? TrainingDocumentPreviewView }).first?.isReady == true
}
return model.canEdit
}
let deadline = ContinuousClock.now.advanced(by: .seconds(15))
while !isReady(), ContinuousClock.now < deadline {
try await Task.sleep(for: .milliseconds(10)) try await Task.sleep(for: .milliseconds(10))
} }
#expect(isReady())
let steps = allViews(controller.view).compactMap { $0 as? TrainingStepView } let steps = allViews(controller.view).compactMap { $0 as? TrainingStepView }
#expect(steps.count == 1) #expect(steps.count == 1)
let step = try #require(steps.first) let step = try #require(steps.first)
@@ -91,6 +99,34 @@ struct TrainingUIRenderingTests {
#expect(labels.filter { $0.accessibilityTraits.contains(.selected) }.map(\.text) == [selectedTitle]) #expect(labels.filter { $0.accessibilityTraits.contains(.selected) }.map(\.text) == [selectedTitle])
#expect(labels.first { $0.text == selectedTitle }?.textColor == TrainingUI.primary) #expect(labels.first { $0.text == selectedTitle }?.textColor == TrainingUI.primary)
#expect(step.bounds.height >= 44) #expect(step.bounds.height >= 44)
if controller === course {
let buttons = allViews(controller.view).compactMap { $0 as? UIButton }
#expect(!buttons.contains { $0.accessibilityIdentifier == "training.reading.sections" || $0.accessibilityIdentifier == "training.reading.attachments" })
#expect(!buttons.contains { $0.configuration?.title == "章节目录" || $0.configuration?.title == "课程附件" })
let frame = step.convert(step.bounds, to: controller.view)
#expect(abs(frame.minY - controller.view.safeAreaInsets.top - 8) < 1)
let preview = try #require(allViews(controller.view).compactMap { $0 as? TrainingDocumentPreviewView }.first)
let scroll = try #require(preview.superview?.superview as? UIScrollView)
#expect(abs(scroll.frame.minY - frame.maxY - 8) < 1)
let metadataLabels = allViews(controller.view).compactMap { $0 as? UILabel }.filter {
["training.reading.taskTitle", "training.reading.courseName", "training.reading.examInfo", "training.reading.introduction"].contains($0.accessibilityIdentifier ?? "")
}
#expect(metadataLabels.count == 4)
for label in metadataLabels {
let labelFrame = label.convert(label.bounds, to: scroll)
#expect(labelFrame.minX >= 0 && labelFrame.maxX <= scroll.bounds.width + 1)
#expect(label.numberOfLines == 0)
}
let web = try #require(allViews(preview).compactMap { $0 as? WKWebView }.first)
if width == 390 {
let webImage = try await web.takeSnapshot(configuration: nil)
let image = UIGraphicsImageRenderer(size: navigation.view.bounds.size).image { _ in
navigation.view.drawHierarchy(in: navigation.view.bounds, afterScreenUpdates: true)
webImage.draw(in: web.convert(web.bounds, to: navigation.view))
}
Attachment.record(image, named: "课程页原生信息与附件正文", as: .png)
}
}
Attachment.record(render(step), named: "\(Int(width))点-\(selectedTitle)", as: .png) Attachment.record(render(step), named: "\(Int(width))点-\(selectedTitle)", as: .png)
if width == 320 { if width == 320 {
@@ -119,8 +155,8 @@ struct TrainingUIRenderingTests {
await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(passed: false) } } await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(passed: false) } }
let attempt = TrainingRemoteFixtures.attempt(passed: false) let attempt = TrainingRemoteFixtures.attempt(passed: false)
let center = TrainingCenterViewController(service: source) let center = TrainingCenterViewController(service: source)
let course = TrainingCourseViewController(taskID: "task_1", service: source) let course = TrainingCourseViewController(taskID: "task_1", service: source, documentLoader: TrainingFixtureDocumentLoader())
let result = TrainingResultViewController(taskID: "task_1", attemptID: attempt.id, service: source) let result = TrainingResultViewController(taskID: "task_1", attemptID: attempt.id, service: source, documentLoader: TrainingFixtureDocumentLoader())
let navigation = UINavigationController() let navigation = UINavigationController()
navigation.setViewControllers([center, course, result], animated: false) navigation.setViewControllers([center, course, result], animated: false)
let window = try makeWindow(navigation) let window = try makeWindow(navigation)
@@ -164,7 +200,7 @@ struct TrainingUIRenderingTests {
await result.reload() await result.reload()
#expect(action.configuration?.title == "完成,返回培训中心") #expect(action.configuration?.title == "完成,返回培训中心")
await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(passed: true) } } await source.configure { $0.attemptHandler = { _ in TrainingRemoteFixtures.result(passed: true) } }
let passedResult = TrainingResultViewController(taskID: "task_1", attemptID: passed.id, service: source) let passedResult = TrainingResultViewController(taskID: "task_1", attemptID: passed.id, service: source, documentLoader: TrainingFixtureDocumentLoader())
navigation.setViewControllers([center, passedResult], animated: false) navigation.setViewControllers([center, passedResult], animated: false)
try await settleTransitions(in: navigation) try await settleTransitions(in: navigation)
await passedResult.reload() await passedResult.reload()