Compare commits
18
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b4aad7c401 | ||
|
|
186e9ad3e4 | ||
|
|
27be1f30ed | ||
|
|
b149295e66 | ||
|
|
091d17ff21 | ||
|
|
aaed9da964 | ||
|
|
fdb4550ba8 | ||
|
|
19e29a6970 | ||
|
|
6d5e273d8c | ||
|
|
ccc1b85b7e | ||
|
|
ce6cccf2b7 | ||
|
|
8c8ba00778 | ||
|
|
01068bb24e | ||
|
|
8862ae5401 | ||
|
|
736b5515c0 | ||
|
|
d12dbc6bb0 | ||
|
|
3823d10423 | ||
|
|
c4b0e7798b |
+3
-3
@@ -295,7 +295,7 @@ iOS 通过 APNs/极光收到 `userInfo` 字典。与 Android 相比:
|
||||
| --- | --- |
|
||||
| 标题示例 | `付款成功通知` |
|
||||
| 正文示例 | `您的订单 #260722128006 已支付成功,支付金额 ¥0.01` |
|
||||
| 客户端点击行为 | Android、iOS 均进入收款记录页 |
|
||||
| 客户端点击行为 | iOS 进入订单 Tab,恢复默认筛选并刷新;Android 行为以 Android 实现为准 |
|
||||
|
||||
`data` 字段:
|
||||
|
||||
@@ -410,9 +410,9 @@ iOS 通过 APNs/极光收到 `userInfo` 字典。与 Android 相比:
|
||||
## 7. 客户端解析约定
|
||||
|
||||
1. Android、iOS 的通知点击路由只根据业务字段 `type` 判断,不读取标题、正文、`data`、`route`、`uri`、`action` 或极光内部字段决定页面。
|
||||
2. `type = 1`:进入收款记录页。
|
||||
2. iOS `type = 1`、`type = 5`:进入订单 Tab 根页面,清空搜索、日期与状态筛选并刷新列表;不进入订单详情。Android 行为以 Android 实现为准。
|
||||
3. `type = 6`:进入收款详情页。
|
||||
4. 其他任意 `type`、缺少 `type`、类型无法解析或 payload 损坏:进入消息中心。
|
||||
4. iOS `type = 14`:有效 `ai_retouch_batch_id` 进入 AI 修图任务详情,否则进入任务列表。其余未单独处理的 `type`、缺少 `type` 或类型无法解析:进入消息中心。
|
||||
5. Android 从 `notificationExtras` 或厂商通道包装字段中提取 `type`;iOS 优先读取 payload 顶层 `type`,并兼容常见推送包装层中的 `type`。
|
||||
6. `data` 仍可按消息类型用于页面内容刷新,但不参与通知点击路由。新增字段应保持向后兼容,客户端应忽略当前版本不认识的额外字段。
|
||||
7. 金额继续使用字符串;时间戳建议统一为 Unix 秒级整数,并在协议中固定单位。
|
||||
|
||||
@@ -56,6 +56,9 @@
|
||||
exceptions = (
|
||||
93FF17D72FFB84950033C304 /* Exceptions for "suixinkan" folder in "suixinkan" target */,
|
||||
);
|
||||
explicitFolders = (
|
||||
Resources/TrainingDocumentPreview,
|
||||
);
|
||||
path = suixinkan;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
@@ -436,7 +439,7 @@
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_ENTITLEMENTS = suixinkan/suixinkan.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1040101;
|
||||
CURRENT_PROJECT_VERSION = 2020101;
|
||||
DEVELOPMENT_TEAM = 56GVN5RNVN;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
"FRAMEWORK_SEARCH_PATHS[sdk=iphoneos*]" = (
|
||||
@@ -455,12 +458,13 @@
|
||||
INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen;
|
||||
INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait;
|
||||
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
|
||||
INFOPLIST_KEY_UIUserInterfaceStyle = Light;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 16;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.4.1;
|
||||
MARKETING_VERSION = 2.2.1;
|
||||
OTHER_LDFLAGS = (
|
||||
"$(inherited)",
|
||||
"-ObjC",
|
||||
@@ -502,7 +506,7 @@
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_ENTITLEMENTS = suixinkan/suixinkan.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1040101;
|
||||
CURRENT_PROJECT_VERSION = 2020101;
|
||||
DEVELOPMENT_TEAM = 56GVN5RNVN;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
"FRAMEWORK_SEARCH_PATHS[sdk=iphoneos*]" = (
|
||||
@@ -521,12 +525,13 @@
|
||||
INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen;
|
||||
INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait;
|
||||
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
|
||||
INFOPLIST_KEY_UIUserInterfaceStyle = Light;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 16;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.4.1;
|
||||
MARKETING_VERSION = 2.2.1;
|
||||
OTHER_LDFLAGS = (
|
||||
"$(inherited)",
|
||||
"-ObjC",
|
||||
@@ -741,7 +746,7 @@
|
||||
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
|
||||
CODE_SIGN_ENTITLEMENTS = suixinkan/suixinkan.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 1040101;
|
||||
CURRENT_PROJECT_VERSION = 2020101;
|
||||
DEVELOPMENT_TEAM = 56GVN5RNVN;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
GENERATE_INFOPLIST_FILE = YES;
|
||||
@@ -756,12 +761,13 @@
|
||||
INFOPLIST_KEY_UILaunchStoryboardName = LaunchScreen;
|
||||
INFOPLIST_KEY_UISupportedInterfaceOrientations = UIInterfaceOrientationPortrait;
|
||||
INFOPLIST_KEY_UISupportedInterfaceOrientations_iPad = "UIInterfaceOrientationLandscapeLeft UIInterfaceOrientationLandscapeRight UIInterfaceOrientationPortrait UIInterfaceOrientationPortraitUpsideDown";
|
||||
INFOPLIST_KEY_UIUserInterfaceStyle = Light;
|
||||
IPHONEOS_DEPLOYMENT_TARGET = 16;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/Frameworks",
|
||||
);
|
||||
MARKETING_VERSION = 1.4.1;
|
||||
MARKETING_VERSION = 2.2.1;
|
||||
OTHER_LDFLAGS = (
|
||||
"$(inherited)",
|
||||
"-ObjC",
|
||||
|
||||
@@ -61,6 +61,7 @@
|
||||
ignoresPersistentStateOnLaunch = "NO"
|
||||
debugDocumentVersioning = "YES"
|
||||
debugServiceExtension = "internal"
|
||||
enableGPUFrameCaptureMode = "3"
|
||||
allowLocationSimulation = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
|
||||
@@ -18,6 +18,8 @@ final class NetworkServices {
|
||||
let homeAPI: HomeAPI
|
||||
let paymentAPI: PaymentAPI
|
||||
let offlineCollectionAPI: OfflineCollectionAPI
|
||||
/// 正式培训资源 API,页面使用身份作用域工厂创建会话。
|
||||
let trainingAPI: TrainingAPI
|
||||
let taskAPI: TaskAPI
|
||||
let inviteAPI: InviteAPI
|
||||
let walletAPI: WalletAPI
|
||||
@@ -45,6 +47,7 @@ final class NetworkServices {
|
||||
homeAPI = HomeAPI(client: client)
|
||||
paymentAPI = PaymentAPI(client: client)
|
||||
offlineCollectionAPI = OfflineCollectionAPI(client: client)
|
||||
trainingAPI = TrainingAPI(client: client)
|
||||
taskAPI = TaskAPI(client: client)
|
||||
inviteAPI = InviteAPI(client: client)
|
||||
walletAPI = WalletAPI(client: client)
|
||||
@@ -77,6 +80,7 @@ final class NetworkServices {
|
||||
homeAPI = HomeAPI(client: apiClient)
|
||||
paymentAPI = PaymentAPI(client: apiClient)
|
||||
offlineCollectionAPI = OfflineCollectionAPI(client: apiClient)
|
||||
trainingAPI = TrainingAPI(client: apiClient)
|
||||
taskAPI = TaskAPI(client: apiClient)
|
||||
inviteAPI = InviteAPI(client: apiClient)
|
||||
walletAPI = WalletAPI(client: apiClient)
|
||||
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"images": [
|
||||
{
|
||||
"filename": "payment_sailimu_background.png",
|
||||
"idiom": "universal",
|
||||
"scale": "1x"
|
||||
},
|
||||
{
|
||||
"idiom": "universal",
|
||||
"scale": "2x"
|
||||
},
|
||||
{
|
||||
"idiom": "universal",
|
||||
"scale": "3x"
|
||||
}
|
||||
],
|
||||
"info": {
|
||||
"author": "xcode",
|
||||
"version": 1
|
||||
}
|
||||
}
|
||||
suixinkan/Assets.xcassets/Payment/payment_sailimu_background.imageset/payment_sailimu_background.png
Vendored
BIN
Binary file not shown.
|
After Width: | Height: | Size: 1.2 MiB |
+21
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"images": [
|
||||
{
|
||||
"filename": "payment_sailimu_logo.png",
|
||||
"idiom": "universal",
|
||||
"scale": "1x"
|
||||
},
|
||||
{
|
||||
"idiom": "universal",
|
||||
"scale": "2x"
|
||||
},
|
||||
{
|
||||
"idiom": "universal",
|
||||
"scale": "3x"
|
||||
}
|
||||
],
|
||||
"info": {
|
||||
"author": "xcode",
|
||||
"version": 1
|
||||
}
|
||||
}
|
||||
BIN
Binary file not shown.
|
After Width: | Height: | Size: 53 KiB |
@@ -26,6 +26,9 @@ enum NotificationName {
|
||||
/// 已登录状态下切换景区/门店账号
|
||||
static let accountDidSwitch = name("accountDidSwitch")
|
||||
|
||||
/// 当前角色菜单权限已持久化,object 为实际写入的 AppPermissionStore。
|
||||
static let permissionItemsDidChange = name("permissionItemsDidChange")
|
||||
|
||||
/// Token 失效或鉴权失败,需重新登录
|
||||
static let sessionDidExpire = name("sessionDidExpire")
|
||||
|
||||
|
||||
@@ -234,6 +234,10 @@ final class APIClient {
|
||||
|
||||
if !apiRequest.queryItems.isEmpty {
|
||||
components.queryItems = apiRequest.queryItems
|
||||
// URLComponents 将 + 视为合法查询字符;PHP 表单式查询解析会把它当作空格。
|
||||
// 在已有百分号编码之后只替换字面 +,保留 %2B、空格和其他字符的原编码。
|
||||
components.percentEncodedQuery = components.percentEncodedQuery?
|
||||
.replacingOccurrences(of: "+", with: "%2B")
|
||||
}
|
||||
|
||||
guard let url = components.url else {
|
||||
@@ -301,7 +305,7 @@ final class APIClient {
|
||||
return payload
|
||||
}
|
||||
|
||||
/// 区分身份注销受限与凭证失效;150015 附带原请求 Token,便于忽略切换身份后的旧错误。
|
||||
/// 区分注销受限与凭证失效;已绑定会话时,旧 Token 的迟到错误不使新会话退出。
|
||||
private func notifySessionErrorIfNeeded(for error: APIError, request: URLRequest) {
|
||||
if case .serverCode(150015, _) = error {
|
||||
guard let token = request.value(forHTTPHeaderField: "token"), !token.isEmpty else { return }
|
||||
@@ -313,6 +317,13 @@ final class APIClient {
|
||||
return
|
||||
}
|
||||
guard APIError.isAuthenticationExpired(error) else { return }
|
||||
if let authTokenProvider {
|
||||
let requestToken = request.value(forHTTPHeaderField: "token")?
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||
let currentToken = authTokenProvider()?
|
||||
.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||
guard requestToken == currentToken else { return }
|
||||
}
|
||||
notificationCenter.post(name: NotificationName.sessionDidExpire, object: nil)
|
||||
}
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import Foundation
|
||||
enum HTTPMethod: String {
|
||||
case get = "GET"
|
||||
case post = "POST"
|
||||
case patch = "PATCH"
|
||||
case put = "PUT"
|
||||
case delete = "DELETE"
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import Foundation
|
||||
|
||||
/// 推送点击后可到达的业务页面。
|
||||
enum PushDestination: Sendable, Equatable {
|
||||
case paymentRecord
|
||||
case orders
|
||||
case paymentDetails
|
||||
case messageCenter
|
||||
case aiRetouchTaskList
|
||||
@@ -36,8 +36,8 @@ struct PushPayload: Sendable, Equatable {
|
||||
/// 仅根据后端业务消息类型解析目标页面。
|
||||
nonisolated var destination: PushDestination {
|
||||
switch type {
|
||||
case "1":
|
||||
return .paymentRecord
|
||||
case "1", "5":
|
||||
return .orders
|
||||
case "6":
|
||||
return .paymentDetails
|
||||
case "14":
|
||||
|
||||
@@ -46,9 +46,10 @@ final class AppPermissionStore {
|
||||
load([RolePermissionResponse].self, for: .rolePermissionList) ?? []
|
||||
}
|
||||
|
||||
/// 保存当前角色扁平权限。
|
||||
/// 保存当前角色扁平权限,写入后通知入口页面读取最新快照。
|
||||
func savePermissionItems(_ items: [HomePermissionItem]) {
|
||||
save(items, for: .permissionItems)
|
||||
guard save(items, for: .permissionItems) else { return }
|
||||
NotificationCenter.default.post(name: NotificationName.permissionItemsDidChange, object: self)
|
||||
}
|
||||
|
||||
/// 读取当前角色扁平权限。
|
||||
@@ -82,10 +83,12 @@ final class AppPermissionStore {
|
||||
Key.allCases.forEach { defaults.removeObject(forKey: "\(accountScope)_\($0.rawValue)") }
|
||||
}
|
||||
|
||||
private func save<Value: Encodable>(_ value: Value, for key: Key) {
|
||||
@discardableResult
|
||||
private func save<Value: Encodable>(_ value: Value, for key: Key) -> Bool {
|
||||
guard let scopedKey = scopedKey(key),
|
||||
let data = try? JSONEncoder().encode(value) else { return }
|
||||
let data = try? JSONEncoder().encode(value) else { return false }
|
||||
defaults.set(data, forKey: scopedKey)
|
||||
return true
|
||||
}
|
||||
|
||||
private func load<Value: Decodable>(_ type: Value.Type, for key: Key) -> Value? {
|
||||
|
||||
@@ -18,7 +18,7 @@ final class HomeCommonMenuStore {
|
||||
func savedCommonURIs(accountScope: String, roleCode: String) -> [String] {
|
||||
guard let key = storageKey(accountScope: accountScope, roleCode: roleCode) else { return [] }
|
||||
let saved = defaults.stringArray(forKey: key) ?? []
|
||||
let sanitized = saved.filter(HomeMenuCatalog.isCustomizable(uri:))
|
||||
let sanitized = Self.normalizedCommonURIs(saved)
|
||||
if sanitized != saved {
|
||||
defaults.set(sanitized, forKey: key)
|
||||
}
|
||||
@@ -28,12 +28,12 @@ final class HomeCommonMenuStore {
|
||||
/// 保存常用 URI 列表。
|
||||
func saveCommonURIs(_ uris: [String], accountScope: String, roleCode: String) {
|
||||
guard let key = storageKey(accountScope: accountScope, roleCode: roleCode) else { return }
|
||||
defaults.set(uris.filter(HomeMenuCatalog.isCustomizable(uri:)), forKey: key)
|
||||
defaults.set(Self.normalizedCommonURIs(uris), forKey: key)
|
||||
}
|
||||
|
||||
/// 根据权限生成默认常用 URI(最多 4 个)。
|
||||
static func defaultCommonURIs(from permissions: [HomePermissionItem]) -> [String] {
|
||||
let uris = permissions.map(\.uri).filter(HomeMenuCatalog.isCustomizable(uri:))
|
||||
let uris = normalizedCommonURIs(permissions.map(\.uri))
|
||||
return uris.count > 4 ? Array(uris.prefix(4)) : uris
|
||||
}
|
||||
|
||||
@@ -55,13 +55,17 @@ final class HomeCommonMenuStore {
|
||||
from allMenus: [HomeMenuItem],
|
||||
commonURIs: [String]
|
||||
) -> (common: [HomeMenuItem], more: [HomeMenuItem]) {
|
||||
let commonSet = Set(commonURIs)
|
||||
let commonSet = Set(normalizedCommonURIs(commonURIs))
|
||||
let customizableMenus = allMenus.filter { HomeMenuCatalog.isCustomizable(uri: $0.uri) }
|
||||
let common = customizableMenus.filter { commonSet.contains($0.uri) }
|
||||
let more = customizableMenus.filter { !commonSet.contains($0.uri) }
|
||||
return (common, more)
|
||||
}
|
||||
|
||||
private static func normalizedCommonURIs(_ uris: [String]) -> [String] {
|
||||
HomeMenuCatalog.canonicalURIs(uris).filter(HomeMenuCatalog.isCustomizable(uri:))
|
||||
}
|
||||
|
||||
private func storageKey(accountScope: String, roleCode: String) -> String? {
|
||||
let normalizedScope = accountScope.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let normalizedRoleCode = roleCode.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
|
||||
@@ -21,6 +21,7 @@ enum HomeMenuCatalog {
|
||||
HomeMenuItem(uri: "schedule_management", title: "日程管理", iconName: "calendar"),
|
||||
HomeMenuItem(uri: "system_settings", title: "设置中心", iconName: "gearshape.fill"),
|
||||
HomeMenuItem(uri: "message_center", title: "消息中心", iconName: "bell.fill"),
|
||||
HomeMenuItem(uri: "/training", title: "培训中心", iconName: "graduationcap.fill"),
|
||||
HomeMenuItem(uri: "checkin_points", title: "打卡点管理", iconName: "home_menu_punch_point"),
|
||||
HomeMenuItem(uri: "sample_management", title: "样片管理", iconName: "sample_ic_home_menu_route"),
|
||||
HomeMenuItem(uri: "live_stream_management", title: "直播管理", iconName: "dot.radiowaves.left.and.right"),
|
||||
@@ -44,11 +45,16 @@ enum HomeMenuCatalog {
|
||||
HomeMenuItem(uri: "cooperation_order", title: "合作订单", iconName: "person.2"),
|
||||
]
|
||||
|
||||
/// 将服务端权限映射为可展示菜单,保持服务端顺序。
|
||||
/// 将服务端权限映射为可展示菜单;培训两种 URI 只保留首次出现的位置。
|
||||
static func visibleMenus(from permissions: [HomePermissionItem]) -> [HomeMenuItem] {
|
||||
permissions.compactMap { permission in
|
||||
var hasTraining = false
|
||||
return permissions.compactMap { permission in
|
||||
guard isCustomizable(uri: permission.uri) else { return nil }
|
||||
guard let catalog = allItems.first(where: { $0.uri == permission.uri }) else { return nil }
|
||||
guard let catalog = item(for: permission.uri) else { return nil }
|
||||
if catalog.uri == "/training" {
|
||||
guard !hasTraining else { return nil }
|
||||
hasTraining = true
|
||||
}
|
||||
return HomeMenuItem(
|
||||
uri: catalog.uri,
|
||||
title: catalog.title,
|
||||
@@ -60,7 +66,25 @@ enum HomeMenuCatalog {
|
||||
|
||||
/// 查找 catalog 项。
|
||||
static func item(for uri: String) -> HomeMenuItem? {
|
||||
allItems.first { $0.uri == uri }
|
||||
allItems.first { $0.uri == canonicalURI(for: uri) }
|
||||
}
|
||||
|
||||
/// 仅将服务端 training 别名映射为内部 /training,不泛化其它 URI。
|
||||
static func canonicalURI(for uri: String) -> String {
|
||||
uri == "training" ? "/training" : uri
|
||||
}
|
||||
|
||||
/// 常用配置统一培训 URI 并保留首项,其它菜单的顺序和重复项保持原样。
|
||||
static func canonicalURIs(_ uris: [String]) -> [String] {
|
||||
var hasTraining = false
|
||||
return uris.compactMap { uri in
|
||||
let canonical = canonicalURI(for: uri)
|
||||
if canonical == "/training" {
|
||||
guard !hasTraining else { return nil }
|
||||
hasTraining = true
|
||||
}
|
||||
return canonical
|
||||
}
|
||||
}
|
||||
|
||||
/// 判断入口是否允许出现在首页常用应用及其自定义页面中。
|
||||
|
||||
@@ -16,12 +16,13 @@ enum HomeRouteHandler {
|
||||
storeItem: StoreItem?,
|
||||
onCommonMenusChanged: (() -> Void)? = nil
|
||||
) {
|
||||
let uri = HomeMenuCatalog.canonicalURI(for: uri)
|
||||
if uri == "pilot_controller" {
|
||||
showDeveloping(from: viewController)
|
||||
return
|
||||
}
|
||||
|
||||
if uri != "pilot_controller", uri != "wallet", AppStore.shared.session.currentScenicId <= 0 {
|
||||
if uri != "pilot_controller", uri != "wallet", uri != "/training", AppStore.shared.session.currentScenicId <= 0 {
|
||||
showToast("请先选择景区", from: viewController)
|
||||
return
|
||||
}
|
||||
@@ -39,6 +40,9 @@ enum HomeRouteHandler {
|
||||
viewController.navigationController?.pushViewController(SettingViewController(), animated: true)
|
||||
case "message_center":
|
||||
viewController.navigationController?.pushViewController(MessageCenterViewController(), animated: true)
|
||||
case "/training":
|
||||
guard AppStore.shared.session.accountType == .storeUser else { return }
|
||||
viewController.navigationController?.pushViewController(TrainingCenterViewController(), animated: true)
|
||||
case "space_settings":
|
||||
viewController.navigationController?.pushViewController(ProfileSpaceSettingsViewController(), animated: true)
|
||||
case "cloud_management":
|
||||
|
||||
@@ -48,6 +48,7 @@ final class AllFunctionsViewModel {
|
||||
|
||||
/// 将菜单加入常用应用。
|
||||
func addToCommon(_ menu: HomeMenuItem) {
|
||||
guard isCurrentlyPermitted(menu) else { loadFunctions(); return }
|
||||
guard HomeMenuCatalog.isCustomizable(uri: menu.uri) else { return }
|
||||
guard !commonMenus.contains(where: { $0.uri == menu.uri }) else { return }
|
||||
commonMenus.append(menu)
|
||||
@@ -59,6 +60,7 @@ final class AllFunctionsViewModel {
|
||||
|
||||
/// 将菜单移出常用应用。
|
||||
func removeFromCommon(_ menu: HomeMenuItem) {
|
||||
guard isCurrentlyPermitted(menu) else { loadFunctions(); return }
|
||||
guard commonMenus.contains(where: { $0.uri == menu.uri }) else { return }
|
||||
commonMenus.removeAll { $0.uri == menu.uri }
|
||||
if !moreMenus.contains(where: { $0.uri == menu.uri }) {
|
||||
@@ -69,6 +71,10 @@ final class AllFunctionsViewModel {
|
||||
notifyStateChange()
|
||||
}
|
||||
|
||||
private func isCurrentlyPermitted(_ menu: HomeMenuItem) -> Bool {
|
||||
HomeMenuCatalog.visibleMenus(from: appStore.permissions.permissionItems()).contains { $0.uri == menu.uri }
|
||||
}
|
||||
|
||||
private func persistCommonMenus() {
|
||||
commonMenuStore.saveCommonURIs(
|
||||
commonMenus.map(\.uri),
|
||||
|
||||
@@ -280,7 +280,7 @@ final class HomeViewModel {
|
||||
isMinimalTopRole = currentAppRole?.usesHomeMinimalTopLayout ?? false
|
||||
}
|
||||
|
||||
/// 重建常用应用列表。
|
||||
/// 按服务端权限和本地常用配置重建应用列表。
|
||||
func rebuildCommonMenus() {
|
||||
let permissions = appStore.permissions.permissionItems()
|
||||
let allMenus = HomeMenuCatalog.visibleMenus(from: permissions)
|
||||
|
||||
@@ -8,6 +8,14 @@ import Foundation
|
||||
/// 店铺管理员押金单列表 ViewModel,对齐 Android `DepositOrderListViewModel`。
|
||||
final class DepositOrderListViewModel {
|
||||
|
||||
private let appStore: AppStore
|
||||
|
||||
/// 注入账号上下文,使订单查询与测试使用各自独立的会话。
|
||||
init(appStore: AppStore = .shared) {
|
||||
self.appStore = appStore
|
||||
}
|
||||
|
||||
|
||||
private(set) var searchText = ""
|
||||
private(set) var filterLabel = "全部"
|
||||
private(set) var tabIndex = 0
|
||||
@@ -22,6 +30,7 @@ final class DepositOrderListViewModel {
|
||||
var onStateChange: (() -> Void)?
|
||||
var onShowMessage: ((String) -> Void)?
|
||||
|
||||
private var listRequestID = UUID()
|
||||
private var currentPage = 1
|
||||
private var totalCount = 0
|
||||
private var searchDebounceTask: Task<Void, Never>?
|
||||
@@ -34,6 +43,18 @@ final class DepositOrderListViewModel {
|
||||
return formatter
|
||||
}()
|
||||
|
||||
/// 清除通知进入前的查询条件,由页面随后发起第一页刷新。
|
||||
func resetFiltersForOrderNotification() {
|
||||
searchDebounceTask?.cancel()
|
||||
searchDebounceTask = nil
|
||||
searchText = ""
|
||||
filterLabel = "全部"
|
||||
tabIndex = 0
|
||||
startTime = nil
|
||||
endTime = nil
|
||||
notifyStateChange()
|
||||
}
|
||||
|
||||
func refreshOrderList(api: OrderAPI) async {
|
||||
currentPage = 1
|
||||
isRefreshing = true
|
||||
@@ -102,7 +123,7 @@ final class DepositOrderListViewModel {
|
||||
onShowMessage?("核销码内容不完整")
|
||||
return
|
||||
}
|
||||
let storeId = AppStore.shared.session.currentStoreId
|
||||
let storeId = appStore.session.currentStoreId
|
||||
guard storeId > 0 else {
|
||||
onShowMessage?("店铺信息异常,请先选择店铺")
|
||||
return
|
||||
@@ -125,7 +146,7 @@ final class DepositOrderListViewModel {
|
||||
refundReason: String,
|
||||
api: OrderAPI
|
||||
) async {
|
||||
let storeId = AppStore.shared.session.currentStoreId
|
||||
let storeId = appStore.session.currentStoreId
|
||||
guard storeId > 0 else {
|
||||
onShowMessage?("店铺信息异常")
|
||||
return
|
||||
@@ -163,10 +184,12 @@ final class DepositOrderListViewModel {
|
||||
}
|
||||
|
||||
private func loadOrderList(refresh: Bool, api: OrderAPI) async {
|
||||
let requestID = UUID()
|
||||
listRequestID = requestID
|
||||
let phone = searchText.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
let isPhoneSearch = !phone.isEmpty && Self.isValidPhone(phone)
|
||||
|
||||
let storeId = AppStore.shared.session.currentStoreId
|
||||
let storeId = appStore.session.currentStoreId
|
||||
if storeId <= 0 {
|
||||
finishLoading()
|
||||
orderList = []
|
||||
@@ -201,6 +224,7 @@ final class DepositOrderListViewModel {
|
||||
startTime: start,
|
||||
endTime: end
|
||||
)
|
||||
guard listRequestID == requestID else { return }
|
||||
totalCount = response.total
|
||||
if refresh || currentPage == 1 {
|
||||
orderList = response.list
|
||||
@@ -213,6 +237,7 @@ final class DepositOrderListViewModel {
|
||||
} catch is CancellationError {
|
||||
return
|
||||
} catch {
|
||||
guard listRequestID == requestID else { return }
|
||||
onShowMessage?(error.localizedDescription)
|
||||
}
|
||||
finishLoading()
|
||||
|
||||
@@ -83,6 +83,14 @@ struct OrderSourceSelection: Equatable {
|
||||
/// 摄影师/景区管理员订单列表 ViewModel,对齐 Android `OrderListViewModel`。
|
||||
final class OrderListViewModel {
|
||||
|
||||
private let appStore: AppStore
|
||||
|
||||
/// 注入账号上下文,使订单查询与测试使用各自独立的会话。
|
||||
init(appStore: AppStore = .shared) {
|
||||
self.appStore = appStore
|
||||
}
|
||||
|
||||
|
||||
private(set) var orderList: [OrderEntity] = []
|
||||
private(set) var searchText = ""
|
||||
private(set) var filterLabel = "全部"
|
||||
@@ -110,6 +118,7 @@ final class OrderListViewModel {
|
||||
var onShowMessage: ((String) -> Void)?
|
||||
var onNavigateBindAcquirer: ((Int) -> Void)?
|
||||
|
||||
private var listRequestID = UUID()
|
||||
private var currentPage = 1
|
||||
private var totalCount = 0
|
||||
|
||||
@@ -122,7 +131,7 @@ final class OrderListViewModel {
|
||||
}()
|
||||
|
||||
var isScenicAdminReadOnly: Bool {
|
||||
AppStore.shared.session.currentAppRole == .scenicAdmin
|
||||
appStore.session.currentAppRole == .scenicAdmin
|
||||
}
|
||||
|
||||
var listAPIPath: String {
|
||||
@@ -131,6 +140,17 @@ final class OrderListViewModel {
|
||||
: "/api/yf-handset-app/photog/order/listv2"
|
||||
}
|
||||
|
||||
/// 清除通知进入前的查询条件,由页面随后发起第一页刷新。
|
||||
func resetFiltersForOrderNotification() {
|
||||
searchText = ""
|
||||
filterLabel = "全部"
|
||||
tabIndex = 0
|
||||
rTabIndex = 0
|
||||
startTime = nil
|
||||
endTime = nil
|
||||
notifyStateChange()
|
||||
}
|
||||
|
||||
func refreshOrderList(api: OrderAPI) async {
|
||||
currentPage = 1
|
||||
isRefreshing = true
|
||||
@@ -359,7 +379,7 @@ final class OrderListViewModel {
|
||||
isLoadingOrderSourcePeople = false
|
||||
notifyStateChange()
|
||||
}
|
||||
let storeId = AppStore.shared.session.currentStoreId
|
||||
let storeId = appStore.session.currentStoreId
|
||||
let storeIdParam = storeId > 0 ? String(storeId) : nil
|
||||
do {
|
||||
let response = try await api.cooperativeSalers(storeId: storeIdParam)
|
||||
@@ -402,7 +422,9 @@ final class OrderListViewModel {
|
||||
}
|
||||
|
||||
private func loadOrderList(api: OrderAPI, append: Bool) async {
|
||||
let scenicId = AppStore.shared.session.currentScenicId
|
||||
let requestID = UUID()
|
||||
listRequestID = requestID
|
||||
let scenicId = appStore.session.currentScenicId
|
||||
guard scenicId > 0 else {
|
||||
finishLoading()
|
||||
onShowMessage?("当前景区信息缺失")
|
||||
@@ -436,6 +458,7 @@ final class OrderListViewModel {
|
||||
isRefined: rTabIndex
|
||||
)
|
||||
}
|
||||
guard listRequestID == requestID else { return }
|
||||
totalCount = response.total
|
||||
if append {
|
||||
orderList.append(contentsOf: response.list)
|
||||
@@ -447,6 +470,7 @@ final class OrderListViewModel {
|
||||
} catch is CancellationError {
|
||||
return
|
||||
} catch {
|
||||
guard listRequestID == requestID else { return }
|
||||
onShowMessage?(error.localizedDescription)
|
||||
}
|
||||
finishLoading()
|
||||
@@ -479,7 +503,7 @@ final class OrderListViewModel {
|
||||
var json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else {
|
||||
return nil
|
||||
}
|
||||
json["scenic_id"] = String(AppStore.shared.session.currentScenicId)
|
||||
json["scenic_id"] = String(appStore.session.currentScenicId)
|
||||
guard let updated = try? JSONSerialization.data(withJSONObject: json),
|
||||
let string = String(data: updated, encoding: .utf8) else {
|
||||
return nil
|
||||
|
||||
@@ -35,6 +35,14 @@ struct PayPageConfig: Codable, Sendable, Equatable {
|
||||
subtitle: "那拉提景区"
|
||||
)
|
||||
|
||||
/// 赛里木湖景区随包默认文案,图片由展示层选择本地资源。
|
||||
static let sailimuDefault = PayPageConfig(
|
||||
background: "",
|
||||
logo: "",
|
||||
title: "赛里木湖旅拍管理\n收费平台",
|
||||
subtitle: "赛里木湖景区"
|
||||
)
|
||||
|
||||
/// 将服务端非空有效字段合并到当前可用配置。
|
||||
func merging(_ response: PayPageConfigResponse) -> PayPageConfig {
|
||||
PayPageConfig(
|
||||
@@ -61,10 +69,22 @@ enum PayPageBrandingPolicy {
|
||||
/// 那拉提景区正式 ID。
|
||||
static let nalatiScenicId = 128
|
||||
|
||||
/// 判断当前景区是否启用品牌收款页。
|
||||
/// 赛里木湖景区正式 ID。
|
||||
static let sailimuScenicId = 125
|
||||
|
||||
/// 判断当前景区是否为那拉提。
|
||||
static func isNalati(scenicId: Int) -> Bool {
|
||||
scenicId == nalatiScenicId
|
||||
}
|
||||
|
||||
/// 返回支持品牌收款页的景区默认配置;其他景区继续使用普通页面。
|
||||
static func defaultConfig(scenicId: Int) -> PayPageConfig? {
|
||||
switch scenicId {
|
||||
case nalatiScenicId: return .nalatiDefault
|
||||
case sailimuScenicId: return .sailimuDefault
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 收款页当前账号信息的展示文本格式化规则。
|
||||
|
||||
@@ -42,9 +42,7 @@ final class PaymentCollectionDetailsViewModel {
|
||||
scenicName = appStore.session.currentScenicName
|
||||
staffId = appStore.session.userId
|
||||
isVoiceBroadcastOpen = appStore.payment.isOpenReceiveVoice
|
||||
if PayPageBrandingPolicy.isNalati(scenicId: scenicId) {
|
||||
payPageConfig = payPageConfigCache.config(scenicId: scenicId) ?? .nalatiDefault
|
||||
}
|
||||
restorePayPageConfig()
|
||||
}
|
||||
|
||||
var hasPayCode: Bool {
|
||||
@@ -60,8 +58,26 @@ final class PaymentCollectionDetailsViewModel {
|
||||
scenicName.isEmpty ? "暂无景区" : scenicName
|
||||
}
|
||||
|
||||
var usesNalatiBranding: Bool {
|
||||
PayPageBrandingPolicy.isNalati(scenicId: scenicId)
|
||||
/// 是否启用品牌收款页,包含那拉提与赛里木湖。
|
||||
var usesBranding: Bool {
|
||||
PayPageBrandingPolicy.defaultConfig(scenicId: scenicId) != nil
|
||||
}
|
||||
|
||||
/// 当前景区的随包背景资源名称。
|
||||
var brandBackgroundAssetName: String {
|
||||
scenicId == PayPageBrandingPolicy.sailimuScenicId
|
||||
? "payment_sailimu_background" : "payment_nalati_background"
|
||||
}
|
||||
|
||||
/// 当前景区的随包 Logo 资源名称。
|
||||
var brandLogoAssetName: String {
|
||||
scenicId == PayPageBrandingPolicy.sailimuScenicId
|
||||
? "payment_sailimu_logo" : "payment_nalati_logo"
|
||||
}
|
||||
|
||||
/// 品牌主标题的最大行数,赛里木湖允许两行展示。
|
||||
var brandTitleNumberOfLines: Int {
|
||||
scenicId == PayPageBrandingPolicy.sailimuScenicId ? 2 : 1
|
||||
}
|
||||
|
||||
var displayPhotographerName: String {
|
||||
@@ -80,14 +96,18 @@ final class PaymentCollectionDetailsViewModel {
|
||||
scenicName = appStore.session.currentScenicName
|
||||
staffId = appStore.session.userId
|
||||
isVoiceBroadcastOpen = appStore.payment.isOpenReceiveVoice
|
||||
if usesNalatiBranding {
|
||||
payPageConfig = payPageConfigCache.config(scenicId: scenicId) ?? .nalatiDefault
|
||||
} else {
|
||||
payPageConfig = .nalatiDefault
|
||||
}
|
||||
restorePayPageConfig()
|
||||
notifyStateChange()
|
||||
}
|
||||
|
||||
private func restorePayPageConfig() {
|
||||
guard let defaults = PayPageBrandingPolicy.defaultConfig(scenicId: scenicId) else {
|
||||
payPageConfig = .nalatiDefault
|
||||
return
|
||||
}
|
||||
payPageConfig = payPageConfigCache.config(scenicId: scenicId) ?? defaults
|
||||
}
|
||||
|
||||
func loadPayCode(api: PaymentAPI) async {
|
||||
guard !loading else { return }
|
||||
loading = true
|
||||
@@ -116,12 +136,14 @@ final class PaymentCollectionDetailsViewModel {
|
||||
|
||||
func loadPayPageConfig(api: PaymentAPI) async {
|
||||
let requestedScenicId = appStore.session.currentScenicId
|
||||
guard PayPageBrandingPolicy.isNalati(scenicId: requestedScenicId) else { return }
|
||||
guard let defaults = PayPageBrandingPolicy.defaultConfig(scenicId: requestedScenicId) else { return }
|
||||
|
||||
do {
|
||||
let response = try await api.payPageConfig(scenicId: requestedScenicId)
|
||||
guard appStore.session.currentScenicId == requestedScenicId else { return }
|
||||
let resolved = payPageConfig.merging(response)
|
||||
guard appStore.session.currentScenicId == requestedScenicId,
|
||||
scenicId == requestedScenicId else { return }
|
||||
let cached = payPageConfigCache.config(scenicId: requestedScenicId) ?? defaults
|
||||
let resolved = cached.merging(response)
|
||||
payPageConfigCache.save(resolved, scenicId: requestedScenicId)
|
||||
payPageConfig = resolved
|
||||
brandingRefreshVersion += 1
|
||||
|
||||
@@ -70,6 +70,11 @@ final class ProfileViewModel {
|
||||
AppStore.shared.session.accountType == .storeUser
|
||||
}
|
||||
|
||||
/// 我的培训入口使用当前账号最新菜单权限,业务访问资格由点击路由和接口校验。
|
||||
var showsTrainingEntry: Bool {
|
||||
AppStore.shared.permissions.permissionItems().contains { HomeMenuCatalog.canonicalURI(for: $0.uri) == "/training" }
|
||||
}
|
||||
|
||||
var currentScenicName: String {
|
||||
let name = AppStore.shared.session.currentScenicName.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return name.isEmpty ? "--" : name
|
||||
|
||||
@@ -0,0 +1,721 @@
|
||||
import Foundation
|
||||
|
||||
/// 培训契约日期解析;独立于全局网络解码器,兼容 RFC3339 的小数秒。
|
||||
enum TrainingAPIDateCodec {
|
||||
/// 解析带时区的 RFC3339 日期,拒绝无时区字符串。
|
||||
static func decode(_ value: String) -> Date? {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
||||
if let date = formatter.date(from: value) { return date }
|
||||
formatter.formatOptions = [.withInternetDateTime]
|
||||
return formatter.date(from: value)
|
||||
}
|
||||
|
||||
/// 按 RFC3339 编码日期,供测试和持久化使用。
|
||||
static func encode(_ date: Date) -> String {
|
||||
let formatter = ISO8601DateFormatter()
|
||||
formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
|
||||
return formatter.string(from: date)
|
||||
}
|
||||
}
|
||||
|
||||
/// 必填 RFC3339 日期,业务属性直接读写 Date。
|
||||
@propertyWrapper
|
||||
struct TrainingAPIDate: Codable, Equatable, Sendable {
|
||||
var wrappedValue: Date
|
||||
/// 从业务日期创建包装,保留 DTO 的普通成员初始化方式。
|
||||
init(wrappedValue: Date) { self.wrappedValue = wrappedValue }
|
||||
/// 从契约字符串解码,格式错误不转换为虚假时间。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
let raw = try container.decode(String.self)
|
||||
guard let value = TrainingAPIDateCodec.decode(raw) else {
|
||||
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid RFC3339 training date")
|
||||
}
|
||||
wrappedValue = value
|
||||
}
|
||||
/// 编码为带时区字符串。
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(TrainingAPIDateCodec.encode(wrappedValue))
|
||||
}
|
||||
}
|
||||
|
||||
/// 可空 RFC3339 日期;无有效期边界保持 nil,不使用本机时间代替。
|
||||
@propertyWrapper
|
||||
struct TrainingAPIOptionalDate: Codable, Equatable, Sendable {
|
||||
var wrappedValue: Date?
|
||||
/// 从可空业务日期创建包装。
|
||||
init(wrappedValue: Date?) { self.wrappedValue = wrappedValue }
|
||||
/// 解码 null 或 RFC3339 字符串。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
if container.decodeNil() { wrappedValue = nil; return }
|
||||
let raw = try container.decode(String.self)
|
||||
guard let value = TrainingAPIDateCodec.decode(raw) else {
|
||||
throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid RFC3339 training date")
|
||||
}
|
||||
wrappedValue = value
|
||||
}
|
||||
/// 编码可空日期。
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
if let value = wrappedValue { try container.encode(TrainingAPIDateCodec.encode(value)) }
|
||||
else { try container.encodeNil() }
|
||||
}
|
||||
}
|
||||
|
||||
extension KeyedDecodingContainer {
|
||||
/// 可选日期允许省略字段;分页的 server_time 并非每个资源都会返回。
|
||||
func decode(_ type: TrainingAPIOptionalDate.Type, forKey key: Key) throws -> TrainingAPIOptionalDate {
|
||||
try decodeIfPresent(type, forKey: key) ?? TrainingAPIOptionalDate(wrappedValue: nil)
|
||||
}
|
||||
}
|
||||
|
||||
extension TrainingLearnerStatus: Codable {
|
||||
/// 将正式接口 pending 映射到页面已有的待考试状态。
|
||||
init(from decoder: Decoder) throws {
|
||||
let container = try decoder.singleValueContainer()
|
||||
switch try container.decode(String.self) {
|
||||
case "pending": self = .pendingExam
|
||||
case "completed": self = .completed
|
||||
case "ended": self = .ended
|
||||
default: throw DecodingError.dataCorruptedError(in: container, debugDescription: "Unknown training learner status")
|
||||
}
|
||||
}
|
||||
/// 输出正式接口状态,不使用本地 enum 的 pendingExam 字符串。
|
||||
func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.singleValueContainer()
|
||||
try container.encode(apiValue)
|
||||
}
|
||||
/// 查询参数使用的正式状态值。
|
||||
var apiValue: String { switch self { case .pendingExam: "pending"; case .completed: "completed"; case .ended: "ended" } }
|
||||
}
|
||||
|
||||
/// 游标分页;小节、附件、任务和成绩复用相同分页边界。
|
||||
struct TrainingCursorPage<Item: Codable & Equatable & Sendable>: Codable, Equatable, Sendable {
|
||||
let items: [Item]
|
||||
let nextCursor: String?
|
||||
let hasMore: Bool
|
||||
@TrainingAPIOptionalDate var serverTime: Date?
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case items
|
||||
case nextCursor = "next_cursor"
|
||||
case hasMore = "has_more"
|
||||
case serverTime = "server_time"
|
||||
}
|
||||
}
|
||||
|
||||
/// 概览最近成绩,只有首屏所需字段。
|
||||
struct TrainingLatestAttempt: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let scoreHundredths: Int
|
||||
@TrainingAPIDate var submittedAt: Date
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "attempt_id"
|
||||
case scoreHundredths = "score_hundredths"
|
||||
case submittedAt = "submitted_at"
|
||||
}
|
||||
}
|
||||
|
||||
/// 当前学员全部分配任务的概览统计。
|
||||
struct TrainingSummary: Codable, Equatable, Sendable {
|
||||
let pendingCount: Int
|
||||
let completedCount: Int
|
||||
let latestAttempt: TrainingLatestAttempt?
|
||||
@TrainingAPIDate var serverTime: Date
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case pendingCount = "pending_count"
|
||||
case completedCount = "completed_count"
|
||||
case latestAttempt = "latest_attempt"
|
||||
case serverTime = "server_time"
|
||||
}
|
||||
}
|
||||
|
||||
/// 任务列表中的本人阅读与操作资格,不包含草稿或成绩数组。
|
||||
struct TrainingLearningFlags: Codable, Equatable, Sendable {
|
||||
let progressPercent: Int
|
||||
let readingCompleted: Bool
|
||||
let hasDraft: Bool
|
||||
let canViewCourse: Bool
|
||||
let canStudy: Bool
|
||||
let canStartExam: Bool
|
||||
let blockReason: String?
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case progressPercent = "progress_percent"
|
||||
case readingCompleted = "reading_completed"
|
||||
case hasDraft = "has_draft"
|
||||
case canViewCourse = "can_view_course"
|
||||
case canStudy = "can_study"
|
||||
case canStartExam = "can_start_exam"
|
||||
case blockReason = "block_reason"
|
||||
}
|
||||
}
|
||||
|
||||
/// 任务摘要与快照引用;课程正文和试卷独立按需读取。
|
||||
struct TrainingTaskSummary: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let title: String
|
||||
let publisherName: String?
|
||||
let mode: TrainingMode
|
||||
let taskStatus: TrainingTaskStatus
|
||||
let learnerStatus: TrainingLearnerStatus
|
||||
@TrainingAPIOptionalDate var startAt: Date?
|
||||
@TrainingAPIOptionalDate var endAt: Date?
|
||||
let courseSnapshotID: String
|
||||
let courseTitle: String
|
||||
let paperSnapshotID: String?
|
||||
let sectionCount: Int
|
||||
let questionCount: Int
|
||||
let passScore: Int?
|
||||
let learning: TrainingLearningFlags
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "task_id"
|
||||
case title
|
||||
case publisherName = "publisher_name"
|
||||
case mode
|
||||
case taskStatus = "task_status"
|
||||
case learnerStatus = "learner_status"
|
||||
case startAt = "start_at"
|
||||
case endAt = "end_at"
|
||||
case courseSnapshotID = "course_snapshot_id"
|
||||
case courseTitle = "course_title"
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case sectionCount = "section_count"
|
||||
case questionCount = "question_count"
|
||||
case passScore = "pass_score"
|
||||
case learning
|
||||
}
|
||||
}
|
||||
|
||||
/// 平铺任务详情,客户端以 summary 复用列表摘要。
|
||||
struct TrainingTaskDetail: Codable, Equatable, Sendable {
|
||||
let summary: TrainingTaskSummary
|
||||
let requiredReadingSeconds: Int
|
||||
let readingRule: String
|
||||
let scoring: String?
|
||||
let serverTime: Date
|
||||
|
||||
/// 使用已解码摘要和规则创建详情,便于纯逻辑测试。
|
||||
init(summary: TrainingTaskSummary, requiredReadingSeconds: Int, readingRule: String, scoring: String?, serverTime: Date) {
|
||||
self.summary = summary
|
||||
self.requiredReadingSeconds = requiredReadingSeconds
|
||||
self.readingRule = readingRule
|
||||
self.scoring = scoring
|
||||
self.serverTime = serverTime
|
||||
}
|
||||
/// 从与摘要同一层的详情字段解码,避免要求不存在的 summary 对象。
|
||||
init(from decoder: Decoder) throws {
|
||||
summary = try TrainingTaskSummary(from: decoder)
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
requiredReadingSeconds = try container.decode(Int.self, forKey: .requiredReadingSeconds)
|
||||
readingRule = try container.decode(String.self, forKey: .readingRule)
|
||||
scoring = try container.decodeIfPresent(String.self, forKey: .scoring)
|
||||
serverTime = try container.decode(TrainingAPIDate.self, forKey: .serverTime).wrappedValue
|
||||
}
|
||||
/// 保持服务端平铺字段布局。
|
||||
func encode(to encoder: Encoder) throws {
|
||||
try summary.encode(to: encoder)
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(requiredReadingSeconds, forKey: .requiredReadingSeconds)
|
||||
try container.encode(readingRule, forKey: .readingRule)
|
||||
try container.encodeIfPresent(scoring, forKey: .scoring)
|
||||
try container.encode(TrainingAPIDate(wrappedValue: serverTime), forKey: .serverTime)
|
||||
}
|
||||
/// 详情额外字段的契约映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case requiredReadingSeconds = "required_reading_seconds"
|
||||
case readingRule = "reading_rule"
|
||||
case scoring
|
||||
case serverTime = "server_time"
|
||||
}
|
||||
}
|
||||
|
||||
/// 课程快照元信息,不含小节正文。
|
||||
struct TrainingCourseInfo: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let title: String
|
||||
let introduction: String
|
||||
let sectionCount: Int
|
||||
let attachmentCount: Int
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "course_snapshot_id"
|
||||
case title
|
||||
case introduction
|
||||
case sectionCount = "section_count"
|
||||
case attachmentCount = "attachment_count"
|
||||
}
|
||||
}
|
||||
|
||||
/// 冻结的小节目录项,序号从一开始。
|
||||
struct TrainingSectionInfo: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let order: Int
|
||||
let title: String
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "section_id"
|
||||
case order
|
||||
case title
|
||||
}
|
||||
}
|
||||
|
||||
/// 单节正式正文;HTML 按后端发布快照读取。
|
||||
struct TrainingSectionContent: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let order: Int
|
||||
let title: String
|
||||
let contentHTML: String
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "section_id"
|
||||
case order
|
||||
case title
|
||||
case contentHTML = "content_html"
|
||||
}
|
||||
}
|
||||
|
||||
/// 附件元信息,私有附件访问前单独申请授权链接。
|
||||
struct TrainingAttachmentInfo: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let name: String
|
||||
let mimeType: String
|
||||
let sizeBytes: Int
|
||||
let fileID: String
|
||||
let downloadURL: URL?
|
||||
@TrainingAPIOptionalDate var expiresAt: Date?
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "attachment_id"
|
||||
case name
|
||||
case mimeType = "mime_type"
|
||||
case sizeBytes = "size_bytes"
|
||||
case fileID = "file_id"
|
||||
case downloadURL = "download_url"
|
||||
case expiresAt = "expires_at"
|
||||
}
|
||||
}
|
||||
|
||||
/// 经当前任务授权的短期附件访问链接。
|
||||
struct TrainingAttachmentLink: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let name: String
|
||||
let url: URL
|
||||
@TrainingAPIDate var expiresAt: Date
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "attachment_id"
|
||||
case name
|
||||
case url
|
||||
case expiresAt = "expires_at"
|
||||
}
|
||||
}
|
||||
|
||||
/// 服务端权威进度与当前资格;不含课程、草稿答案或历史成绩。
|
||||
struct TrainingProgressSnapshot: Codable, Equatable, Sendable {
|
||||
let taskID: String
|
||||
let readingSeconds: Int
|
||||
let requiredReadingSeconds: Int
|
||||
let completedSectionCount: Int
|
||||
let sectionCount: Int
|
||||
let progressPercent: Int
|
||||
let readingCompleted: Bool
|
||||
let learnerStatus: TrainingLearnerStatus
|
||||
@TrainingAPIOptionalDate var completedAt: Date?
|
||||
let hasDraft: Bool
|
||||
let canViewCourse: Bool
|
||||
let canStudy: Bool
|
||||
let canStartExam: Bool
|
||||
let canRetry: Bool
|
||||
let blockReason: String?
|
||||
@TrainingAPIDate var serverTime: Date
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case taskID = "task_id"
|
||||
case readingSeconds = "reading_seconds"
|
||||
case requiredReadingSeconds = "required_reading_seconds"
|
||||
case completedSectionCount = "completed_section_count"
|
||||
case sectionCount = "section_count"
|
||||
case progressPercent = "progress_percent"
|
||||
case readingCompleted = "reading_completed"
|
||||
case learnerStatus = "learner_status"
|
||||
case completedAt = "completed_at"
|
||||
case hasDraft = "has_draft"
|
||||
case canViewCourse = "can_view_course"
|
||||
case canStudy = "can_study"
|
||||
case canStartExam = "can_start_exam"
|
||||
case canRetry = "can_retry"
|
||||
case blockReason = "block_reason"
|
||||
case serverTime = "server_time"
|
||||
}
|
||||
}
|
||||
|
||||
/// 阅读会话、上报规则及创建时已保存进度。
|
||||
struct TrainingStudySession: Codable, Equatable, Sendable {
|
||||
let sessionID: String
|
||||
@TrainingAPIDate var expiresAt: Date
|
||||
let heartbeatIntervalSeconds: Int
|
||||
let maxHeartbeatGapSeconds: Int
|
||||
let progress: TrainingProgressSnapshot
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case sessionID = "session_id"
|
||||
case expiresAt = "expires_at"
|
||||
case heartbeatIntervalSeconds = "heartbeat_interval_seconds"
|
||||
case maxHeartbeatGapSeconds = "max_heartbeat_gap_seconds"
|
||||
case progress
|
||||
}
|
||||
}
|
||||
|
||||
/// 幂等阅读上报确认;累计秒数只用于当前会话。
|
||||
struct TrainingHeartbeatConfirmation: Codable, Equatable, Sendable {
|
||||
let sessionID: String
|
||||
let acceptedSequence: Int
|
||||
let acceptedActiveSecondsTotal: Int
|
||||
let sessionClosed: Bool
|
||||
let progress: TrainingProgressSnapshot
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case sessionID = "session_id"
|
||||
case acceptedSequence = "accepted_sequence"
|
||||
case acceptedActiveSecondsTotal = "accepted_active_seconds_total"
|
||||
case sessionClosed = "session_closed"
|
||||
case progress
|
||||
}
|
||||
}
|
||||
|
||||
/// 冻结试卷规则与题数,不携带全卷或正确答案。
|
||||
struct TrainingPaperInfo: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let scoring: String
|
||||
let questionCount: Int
|
||||
let maxOptionsPerQuestion: Int
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "paper_snapshot_id"
|
||||
case scoring
|
||||
case questionCount = "question_count"
|
||||
case maxOptionsPerQuestion = "max_options_per_question"
|
||||
}
|
||||
}
|
||||
|
||||
/// 考前选项,不透明 ID 按原值提交。
|
||||
struct TrainingQuestionOption: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let text: String
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "option_id"
|
||||
case text
|
||||
}
|
||||
}
|
||||
|
||||
/// 一题考前快照,不包含答案和解析。
|
||||
struct TrainingQuestionItem: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let order: Int
|
||||
let type: TrainingQuestionType
|
||||
let stem: String
|
||||
let options: [TrainingQuestionOption]
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "question_id"
|
||||
case order
|
||||
case type
|
||||
case stem
|
||||
case options
|
||||
}
|
||||
}
|
||||
|
||||
/// 按冻结题位随机访问的试题页。
|
||||
struct TrainingQuestionPage: Codable, Equatable, Sendable {
|
||||
let paperSnapshotID: String
|
||||
let total: Int
|
||||
let offset: Int
|
||||
let nextOffset: Int?
|
||||
let hasMore: Bool
|
||||
let items: [TrainingQuestionItem]
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case total
|
||||
case offset
|
||||
case nextOffset = "next_offset"
|
||||
case hasMore = "has_more"
|
||||
case items
|
||||
}
|
||||
}
|
||||
|
||||
/// 固定题位范围内已保存的本人选择。
|
||||
struct TrainingDraftAnswerItem: Codable, Equatable, Sendable {
|
||||
let questionID: String
|
||||
let order: Int
|
||||
let selectedOptionIDs: [String]
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case questionID = "question_id"
|
||||
case order
|
||||
case selectedOptionIDs = "selected_option_ids"
|
||||
}
|
||||
}
|
||||
|
||||
/// 草稿版本、恢复位置、全部已答题号及当前题位答案页。
|
||||
struct TrainingDraftPage: Codable, Equatable, Sendable {
|
||||
let taskID: String
|
||||
let paperSnapshotID: String
|
||||
let draftRevision: Int
|
||||
@TrainingAPIOptionalDate var savedAt: Date?
|
||||
let lastQuestionOrder: Int
|
||||
let answeredCount: Int
|
||||
let answeredQuestionOrders: [Int]
|
||||
let total: Int
|
||||
let offset: Int
|
||||
let nextOffset: Int?
|
||||
let hasMore: Bool
|
||||
let items: [TrainingDraftAnswerItem]
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case taskID = "task_id"
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case draftRevision = "draft_revision"
|
||||
case savedAt = "saved_at"
|
||||
case lastQuestionOrder = "last_question_order"
|
||||
case answeredCount = "answered_count"
|
||||
case answeredQuestionOrders = "answered_question_orders"
|
||||
case total
|
||||
case offset
|
||||
case nextOffset = "next_offset"
|
||||
case hasMore = "has_more"
|
||||
case items
|
||||
}
|
||||
}
|
||||
|
||||
/// 增量保存中一题的完整选择集合,空数组取消该题作答。
|
||||
struct TrainingDraftChange: Codable, Equatable, Sendable {
|
||||
let questionID: String
|
||||
let selectedOptionIDs: [String]
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case questionID = "question_id"
|
||||
case selectedOptionIDs = "selected_option_ids"
|
||||
}
|
||||
}
|
||||
|
||||
/// 带乐观版本与幂等键的增量草稿请求。
|
||||
struct TrainingDraftSaveRequest: Codable, Equatable, Sendable {
|
||||
let requestID: String
|
||||
let paperSnapshotID: String
|
||||
let baseRevision: Int
|
||||
let lastQuestionOrder: Int?
|
||||
let changes: [TrainingDraftChange]
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case requestID = "request_id"
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case baseRevision = "base_revision"
|
||||
case lastQuestionOrder = "last_question_order"
|
||||
case changes
|
||||
}
|
||||
}
|
||||
|
||||
/// 用户明确重考时请求重置;重试沿用同一 requestID。
|
||||
struct TrainingDraftResetRequest: Codable, Equatable, Sendable {
|
||||
let requestID: String
|
||||
let paperSnapshotID: String
|
||||
let baseRevision: Int
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case requestID = "request_id"
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case baseRevision = "base_revision"
|
||||
}
|
||||
}
|
||||
|
||||
/// 保存或重置后草稿实况;重置重试不能据此盲清本地答案。
|
||||
struct TrainingDraftConfirmation: Codable, Equatable, Sendable {
|
||||
let draftRevision: Int
|
||||
@TrainingAPIDate var savedAt: Date
|
||||
let answeredCount: Int
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case draftRevision = "draft_revision"
|
||||
case savedAt = "saved_at"
|
||||
case answeredCount = "answered_count"
|
||||
}
|
||||
}
|
||||
|
||||
/// 消费服务端已保存草稿版本的幂等交卷请求,不重新上传答案。
|
||||
struct TrainingSubmissionRequest: Codable, Equatable, Sendable {
|
||||
let submissionID: String
|
||||
let paperSnapshotID: String
|
||||
let draftRevision: Int
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case submissionID = "submission_id"
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case draftRevision = "draft_revision"
|
||||
}
|
||||
}
|
||||
|
||||
/// 冻结成绩摘要;解析独立读取,资格由最新任务状态决定。
|
||||
struct TrainingAttemptSummary: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let taskID: String
|
||||
let taskTitle: String
|
||||
let courseSnapshotID: String
|
||||
let courseTitle: String
|
||||
let paperSnapshotID: String
|
||||
@TrainingAPIDate var submittedAt: Date
|
||||
let scoreHundredths: Int
|
||||
let correctCount: Int
|
||||
let questionCount: Int
|
||||
let passScore: Int
|
||||
let passed: Bool
|
||||
let reviewAvailable: Bool
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "attempt_id"
|
||||
case taskID = "task_id"
|
||||
case taskTitle = "task_title"
|
||||
case courseSnapshotID = "course_snapshot_id"
|
||||
case courseTitle = "course_title"
|
||||
case paperSnapshotID = "paper_snapshot_id"
|
||||
case submittedAt = "submitted_at"
|
||||
case scoreHundredths = "score_hundredths"
|
||||
case correctCount = "correct_count"
|
||||
case questionCount = "question_count"
|
||||
case passScore = "pass_score"
|
||||
case passed
|
||||
case reviewAvailable = "review_available"
|
||||
}
|
||||
}
|
||||
|
||||
extension TrainingAttemptSummary {
|
||||
/// 百分之一分整数转为最多两位小数的展示分数,不改变通过判断。
|
||||
var scoreText: String {
|
||||
let whole = scoreHundredths / 100
|
||||
let fraction = scoreHundredths % 100
|
||||
if fraction == 0 { return String(whole) }
|
||||
let digits = String(format: "%02d", fraction)
|
||||
return "\(whole).\(fraction.isMultiple(of: 10) ? String(digits.prefix(1)) : digits)"
|
||||
}
|
||||
}
|
||||
|
||||
/// 成绩页面使用的最新本人任务操作资格。
|
||||
struct TrainingTaskState: Codable, Equatable, Sendable {
|
||||
let learnerStatus: TrainingLearnerStatus
|
||||
@TrainingAPIOptionalDate var completedAt: Date?
|
||||
let canRetry: Bool
|
||||
let blockReason: String?
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case learnerStatus = "learner_status"
|
||||
case completedAt = "completed_at"
|
||||
case canRetry = "can_retry"
|
||||
case blockReason = "block_reason"
|
||||
}
|
||||
}
|
||||
|
||||
/// 单次历史成绩与最新重考资格,不含解析。
|
||||
struct TrainingAttemptDetail: Codable, Equatable, Sendable {
|
||||
let attempt: TrainingAttemptSummary
|
||||
let taskState: TrainingTaskState
|
||||
@TrainingAPIDate var serverTime: Date
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case attempt
|
||||
case taskState = "task_state"
|
||||
case serverTime = "server_time"
|
||||
}
|
||||
}
|
||||
|
||||
/// 原子交卷结果,直接显示成绩摘要并更新草稿版本。
|
||||
struct TrainingSubmissionResult: Codable, Equatable, Sendable {
|
||||
let attempt: TrainingAttemptSummary
|
||||
let taskState: TrainingTaskState
|
||||
let draftRevision: Int
|
||||
@TrainingAPIDate var serverTime: Date
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case attempt
|
||||
case taskState = "task_state"
|
||||
case draftRevision = "draft_revision"
|
||||
case serverTime = "server_time"
|
||||
}
|
||||
}
|
||||
|
||||
/// 本次考试冻结的题目、本人答案和考后解析。
|
||||
struct TrainingReviewItem: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let order: Int
|
||||
let type: TrainingQuestionType
|
||||
let stem: String
|
||||
let options: [TrainingQuestionOption]
|
||||
let selectedOptionIDs: [String]
|
||||
let correctOptionIDs: [String]
|
||||
let isCorrect: Bool
|
||||
let explanation: String
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case id = "question_id"
|
||||
case order
|
||||
case type
|
||||
case stem
|
||||
case options
|
||||
case selectedOptionIDs = "selected_option_ids"
|
||||
case correctOptionIDs = "correct_option_ids"
|
||||
case isCorrect = "is_correct"
|
||||
case explanation
|
||||
}
|
||||
}
|
||||
|
||||
/// 成绩解析游标页,每次只读取最多十题。
|
||||
struct TrainingReviewPage: Codable, Equatable, Sendable {
|
||||
let attemptID: String
|
||||
let items: [TrainingReviewItem]
|
||||
let nextCursor: String?
|
||||
let hasMore: Bool
|
||||
|
||||
/// 正式接口字段映射。
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case attemptID = "attempt_id"
|
||||
case items
|
||||
case nextCursor = "next_cursor"
|
||||
case hasMore = "has_more"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,268 @@
|
||||
import Foundation
|
||||
|
||||
/// 培训任务类型:仅学习或学习后考试。
|
||||
enum TrainingMode: String, Codable, Sendable { case study, exam }
|
||||
|
||||
/// 任务发布状态;关闭后只允许回顾。
|
||||
enum TrainingTaskStatus: String, Codable, Sendable { case published, closed }
|
||||
|
||||
/// 学员任务列表的待办、完成与结束状态。
|
||||
enum TrainingLearnerStatus: String, CaseIterable, Sendable {
|
||||
case pendingExam, completed, ended
|
||||
|
||||
/// 面向学员的状态名称。
|
||||
var title: String { switch self { case .pendingExam: "待考试"; case .completed: "已完成"; case .ended: "已结束" } }
|
||||
}
|
||||
|
||||
/// 单选和多选题型。
|
||||
enum TrainingQuestionType: String, Codable, Sendable { case single, multiple }
|
||||
|
||||
/// 发布时冻结的课程图文小节,HTML 应由服务端清洗。
|
||||
struct TrainingSection: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let title: String
|
||||
let contentHTML: String
|
||||
}
|
||||
|
||||
/// 具有授权 HTTPS 地址的课程附件。
|
||||
struct TrainingAttachment: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let name: String
|
||||
let url: URL?
|
||||
}
|
||||
|
||||
/// 学习端课程快照,保留文字小节和附件。
|
||||
struct TrainingCourse: Codable, Equatable, Sendable {
|
||||
let title: String
|
||||
let introduction: String
|
||||
let sections: [TrainingSection]
|
||||
let attachments: [TrainingAttachment]
|
||||
}
|
||||
|
||||
/// 试题选项 ID 与正文。
|
||||
struct TrainingOption: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let text: String
|
||||
}
|
||||
|
||||
/// 考前试题不携带正确答案和解析。
|
||||
struct TrainingQuestion: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let type: TrainingQuestionType
|
||||
let stem: String
|
||||
let options: [TrainingOption]
|
||||
}
|
||||
|
||||
/// 答题草稿,以题目和选项快照 ID 保存。
|
||||
typealias TrainingAnswers = [String: Set<String>]
|
||||
|
||||
/// 交卷后返回的单题解析与本次所选答案。
|
||||
struct TrainingQuestionReview: Codable, Equatable, Sendable {
|
||||
let question: TrainingQuestion
|
||||
let selectedIDs: Set<String>
|
||||
let correctIDs: Set<String>
|
||||
let explanation: String
|
||||
|
||||
/// 多选必须集合完全相等才算答对。
|
||||
var isCorrect: Bool { selectedIDs == correctIDs }
|
||||
|
||||
/// 将选项 ID 转为可读的字母序号和正文。
|
||||
func answerText(ids: Set<String>) -> String {
|
||||
let values = question.options.enumerated().compactMap { index, option in
|
||||
ids.contains(option.id) ? "\(TrainingQuestion.optionLetter(index)).\(option.text)" : nil
|
||||
}
|
||||
return values.isEmpty ? "未作答" : values.joined(separator: "\n")
|
||||
}
|
||||
}
|
||||
|
||||
extension TrainingQuestion {
|
||||
/// 题目最多六个选项,对外显示 A–F,提交仍使用原始 ID。
|
||||
static func optionLetter(_ index: Int) -> String {
|
||||
let letters = ["A", "B", "C", "D", "E", "F"]
|
||||
return letters.indices.contains(index) ? letters[index] : "?"
|
||||
}
|
||||
}
|
||||
|
||||
/// 小程序任务卡的展示状态;学习进度由已保存小节计算。
|
||||
struct TrainingTaskPresentation {
|
||||
let task: TrainingTask
|
||||
/// 判断任务开始与截止状态的时间,可注入以验证时间边界。
|
||||
var now = Date()
|
||||
|
||||
/// 已保存完成的小节占全部课程小节的整数百分比。
|
||||
var progressPercent: Int {
|
||||
guard !task.course.sections.isEmpty else { return 0 }
|
||||
return task.course.sections.filter { task.progress.completedSectionIDs.contains($0.id) }.count * 100 / task.course.sections.count
|
||||
}
|
||||
/// 已完成阅读且任务允许提交时才能进入考试。
|
||||
var canStartExam: Bool { task.mode == .exam && task.hasFinishedReading && task.submissionBlockReason(now: now) == nil }
|
||||
|
||||
/// 根据完成状态、有效期与草稿决定任务卡主按钮文案。
|
||||
var actionTitle: String {
|
||||
if task.learnerStatus == .completed { return "回顾学习" }
|
||||
if task.submissionBlockReason(now: now) != nil { return "查看课程" }
|
||||
if canStartExam { return task.progress.draftAnswers.values.contains(where: { !$0.isEmpty }) ? "继续答题" : "开始考试" }
|
||||
return "去学习"
|
||||
}
|
||||
/// 解释任务当前可执行操作或继续学习的条件。
|
||||
var hint: String {
|
||||
if task.learnerStatus == .completed { return "已完成本次学习任务" }
|
||||
if task.submissionBlockReason(now: now) != nil { return now < task.startAt ? "任务尚未开始,暂不能提交" : "任务已结束,仅可回顾内容" }
|
||||
if canStartExam { return "课程已学完,可以开始考试" }
|
||||
return "请阅读课程内容,倒计时结束后" + (task.mode == .exam ? "即可考试" : "完成学习")
|
||||
}
|
||||
}
|
||||
|
||||
/// 服务端考试记录;演示成绩必须明确标记。
|
||||
struct TrainingAttempt: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let submittedAt: Date
|
||||
let scoreHundredths: Int
|
||||
let correctCount: Int
|
||||
let questionCount: Int
|
||||
let passed: Bool
|
||||
let isDemo: Bool
|
||||
let reviews: [TrainingQuestionReview]
|
||||
|
||||
/// 分数最多两位小数,使用已经截断的百分之一分整数。
|
||||
var scoreText: String {
|
||||
let whole = scoreHundredths / 100
|
||||
let fraction = scoreHundredths % 100
|
||||
if fraction == 0 { return String(whole) }
|
||||
let digits = String(format: "%02d", fraction)
|
||||
return "\(whole).\(fraction.isMultiple(of: 10) ? String(digits.prefix(1)) : digits)"
|
||||
}
|
||||
}
|
||||
|
||||
/// 本人学习进度、草稿与全部考试历史。
|
||||
struct TrainingProgress: Codable, Equatable, Sendable {
|
||||
var readingSeconds = 0
|
||||
var completedSectionIDs: Set<String> = []
|
||||
var completedAt: Date?
|
||||
var draftAnswers: TrainingAnswers = [:]
|
||||
var attempts: [TrainingAttempt] = []
|
||||
}
|
||||
|
||||
/// 当前学员被分配的任务,内容以发布快照为准。
|
||||
struct TrainingTask: Codable, Equatable, Sendable {
|
||||
let id: String
|
||||
let title: String
|
||||
let publisherName: String?
|
||||
let mode: TrainingMode
|
||||
var status: TrainingTaskStatus
|
||||
let startAt: Date
|
||||
let endAt: Date
|
||||
let passScore: Int
|
||||
let scoring: String
|
||||
let course: TrainingCourse
|
||||
let questions: [TrainingQuestion]
|
||||
var progress: TrainingProgress
|
||||
|
||||
/// 与小程序统一的前台阅读门槛。
|
||||
static let requiredReadingSeconds = 20
|
||||
/// 当前百分制计分规则版本。
|
||||
static let equalPercentageScoring = "equal-percentage-v1"
|
||||
|
||||
/// 所有未完成状态均归入待考试。
|
||||
var learnerStatus: TrainingLearnerStatus {
|
||||
progress.completedAt != nil || progress.attempts.contains(where: \.passed) ? .completed : .pendingExam
|
||||
}
|
||||
|
||||
/// 读满时长且全部小节已经成功保存后才允许考试。
|
||||
var hasFinishedReading: Bool {
|
||||
progress.readingSeconds >= Self.requiredReadingSeconds
|
||||
&& !course.sections.isEmpty
|
||||
&& Set(course.sections.map(\.id)).isSubset(of: progress.completedSectionIDs)
|
||||
}
|
||||
|
||||
/// 显示真实发布人;缺失时不从课程创建人推测。
|
||||
var publisherText: String {
|
||||
guard let name = publisherName?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty else {
|
||||
return "未记录"
|
||||
}
|
||||
return name
|
||||
}
|
||||
|
||||
/// 时间窗口包含开始边界、不包含截止边界,完成后只可回顾。
|
||||
func submissionBlockReason(now: Date) -> String? {
|
||||
if learnerStatus == .completed { return "任务已完成,可回顾课程和考试记录" }
|
||||
if status == .closed { return "任务已结束,可回顾课程和考试记录" }
|
||||
if now < startAt { return "任务尚未开始" }
|
||||
if now >= endAt { return "任务已截止,可回顾课程和考试记录" }
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// 培训业务和存储失败;避免把保存失败显示为完成。
|
||||
enum TrainingError: Error, LocalizedError, Equatable {
|
||||
case unavailable, identityChanged, notFound, corruptStorage, saveFailed
|
||||
case blocked(String), readingRequired, invalidPaper, invalidAnswers, unanswered(Int)
|
||||
|
||||
/// 直接用于页面提示的错误说明。
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .unavailable: "培训服务尚未接入,请等待景区开通"
|
||||
case .identityChanged: "学习账号或景区已切换,请重新进入培训中心"
|
||||
case .notFound: "任务不存在或未分配给当前账号"
|
||||
case .corruptStorage: "本地演示数据异常,请联系管理员;原有记录未覆盖"
|
||||
case .saveFailed: "保存失败,请重试;本次操作尚未完成"
|
||||
case .blocked(let reason): reason
|
||||
case .readingRequired: "请先完成课程阅读"
|
||||
case .invalidPaper: "试卷或计分规则异常,请联系管理员"
|
||||
case .invalidAnswers: "答案包含无效题目或选项,请重新进入考试"
|
||||
case .unanswered(let count): "还有 \(count) 道题未作答"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 校验试卷和答案的纯逻辑;正式成绩由服务端核算。
|
||||
enum TrainingValidation {
|
||||
/// 校验百分制、唯一题目/选项及题型数量。
|
||||
static func validatePaper(_ task: TrainingTask) throws {
|
||||
guard task.scoring == TrainingTask.equalPercentageScoring,
|
||||
(1...100).contains(task.passScore), !task.questions.isEmpty,
|
||||
task.questions.count <= 500,
|
||||
Set(task.questions.map(\.id)).count == task.questions.count else { throw TrainingError.invalidPaper }
|
||||
for question in task.questions {
|
||||
guard !question.id.isEmpty, !question.stem.isEmpty,
|
||||
(2...6).contains(question.options.count),
|
||||
question.options.allSatisfy({ !$0.id.isEmpty && !$0.text.isEmpty }),
|
||||
Set(question.options.map(\.id)).count == question.options.count else { throw TrainingError.invalidPaper }
|
||||
}
|
||||
}
|
||||
|
||||
/// 校验所选 ID;完整交卷时返回漏答数量。
|
||||
static func validateAnswers(_ answers: TrainingAnswers, task: TrainingTask, requireComplete: Bool) throws {
|
||||
try validatePaper(task)
|
||||
guard Set(answers.keys).isSubset(of: Set(task.questions.map(\.id))) else { throw TrainingError.invalidAnswers }
|
||||
var missing = 0
|
||||
for question in task.questions {
|
||||
let selected = answers[question.id] ?? []
|
||||
guard selected.isSubset(of: Set(question.options.map(\.id))),
|
||||
question.type != .single || selected.count <= 1 else { throw TrainingError.invalidAnswers }
|
||||
if selected.isEmpty { missing += 1 }
|
||||
}
|
||||
if requireComplete, missing > 0 { throw TrainingError.unanswered(missing) }
|
||||
}
|
||||
}
|
||||
|
||||
/// 使用单调时间累计前台整秒,暂停后不补记后台或离开页面的时间。
|
||||
struct TrainingReadingClock {
|
||||
private var lastUptime: TimeInterval?
|
||||
|
||||
/// 暂停后开始新的计时片段;持续可见时重复恢复不改变正在累计的起点。
|
||||
mutating func resume(at uptime: TimeInterval) {
|
||||
guard lastUptime == nil else { return }
|
||||
lastUptime = uptime
|
||||
}
|
||||
|
||||
/// 失去前台可见性时丢弃未满一秒的片段。
|
||||
mutating func pause() { lastUptime = nil }
|
||||
|
||||
/// 每次最多累计一秒,不补记 run loop 阻塞期间的大段时间。
|
||||
mutating func takeSecond(at uptime: TimeInterval) -> Bool {
|
||||
guard let lastUptime, uptime - lastUptime >= 1 else { return false }
|
||||
self.lastUptime = uptime
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
import Foundation
|
||||
|
||||
/// 正式培训 API,显式在主 Actor 协调网络及登录上下文,不加载无关子资源。
|
||||
@MainActor
|
||||
final class TrainingAPI: TrainingDataServing {
|
||||
private let client: APIClient
|
||||
private let tokenOverride: String?
|
||||
private let eligible: Bool
|
||||
private let validateContext: (@MainActor () -> Bool)?
|
||||
private let prefix = "/api/app/training"
|
||||
|
||||
/// 注入网络客户端;正式页面通过工厂固定本次身份,测试可单独注入校验。
|
||||
init(client: APIClient, tokenOverride: String? = nil, eligible: Bool = true, validateContext: (@MainActor () -> Bool)? = nil) {
|
||||
self.client = client
|
||||
self.tokenOverride = tokenOverride
|
||||
self.eligible = eligible
|
||||
self.validateContext = validateContext
|
||||
}
|
||||
|
||||
/// 为一次页面会话建立固定凭证及身份校验的数据源。
|
||||
func scoped(token: String, eligible: Bool, validateContext: @escaping @MainActor () -> Bool) -> TrainingAPI {
|
||||
TrainingAPI(client: client, tokenOverride: token, eligible: eligible, validateContext: validateContext)
|
||||
}
|
||||
|
||||
/// GET /summary:读取本人统计。
|
||||
func summary() async throws -> TrainingSummary { try await read("/summary") }
|
||||
|
||||
/// GET /tasks:状态和关键词只影响本次摘要页。
|
||||
func tasks(status: TrainingLearnerStatus?, keyword: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingTaskSummary> {
|
||||
var query = cursorQuery(cursor, limit: limit, maximum: 50)
|
||||
if let status { query.append(item("learner_status", status.apiValue)) }
|
||||
if !keyword.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { query.append(item("keyword", keyword)) }
|
||||
return try await read("/tasks", query: query)
|
||||
}
|
||||
|
||||
/// GET /tasks/{id}:平铺任务规则,不读取正文或试卷。
|
||||
func task(id: String) async throws -> TrainingTaskDetail { try await read("/tasks/" + component(id)) }
|
||||
|
||||
/// GET /courses/{id}:快照访问带本人 task_id。
|
||||
func course(id: String, taskID: String) async throws -> TrainingCourseInfo {
|
||||
try await read("/courses/" + component(id), query: taskQuery(taskID))
|
||||
}
|
||||
|
||||
/// GET /courses/{id}/sections:只读取目录页。
|
||||
func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingSectionInfo> {
|
||||
try await read("/courses/" + component(courseID) + "/sections", query: taskQuery(taskID) + cursorQuery(cursor, limit: limit, maximum: 50))
|
||||
}
|
||||
|
||||
/// GET /courses/{id}/sections/{id}:只读取一个小节。
|
||||
func section(courseID: String, sectionID: String, taskID: String) async throws -> TrainingSectionContent {
|
||||
try await read("/courses/" + component(courseID) + "/sections/" + component(sectionID), query: taskQuery(taskID))
|
||||
}
|
||||
|
||||
/// GET /courses/{id}/attachments:只读取附件元信息页。
|
||||
func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttachmentInfo> {
|
||||
try await read("/courses/" + component(courseID) + "/attachments", query: taskQuery(taskID) + cursorQuery(cursor, limit: limit, maximum: 50))
|
||||
}
|
||||
|
||||
/// GET /courses/{id}/attachments/{id}:获取短时授权访问地址。
|
||||
func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink {
|
||||
try await read("/courses/" + component(courseID) + "/attachments/" + component(attachmentID), query: taskQuery(taskID))
|
||||
}
|
||||
|
||||
/// GET /tasks/{id}/progress:读取已保存进度及资格。
|
||||
func progress(taskID: String) async throws -> TrainingProgressSnapshot { try await read("/tasks/" + component(taskID) + "/progress") }
|
||||
|
||||
/// POST /tasks/{id}/study-sessions:幂等创建阅读会话。
|
||||
func startReading(taskID: String, requestID: String) async throws -> TrainingStudySession {
|
||||
try await write(.post, "/tasks/" + component(taskID) + "/study-sessions", body: ReadingStartBody(requestID: requestID))
|
||||
}
|
||||
|
||||
/// POST /study-sessions/{id}/heartbeat:确认当前会话读时,不自动生成新序号。
|
||||
func heartbeat(sessionID: String, sequence: Int, activeSecondsTotal: Int, final: Bool) async throws -> TrainingHeartbeatConfirmation {
|
||||
try await write(.post, "/study-sessions/" + component(sessionID) + "/heartbeat", body: HeartbeatBody(sequence: sequence, activeSecondsTotal: activeSecondsTotal, final: final))
|
||||
}
|
||||
|
||||
/// GET /papers/{id}:读取冻结计分规则。
|
||||
func paper(id: String, taskID: String) async throws -> TrainingPaperInfo {
|
||||
try await read("/papers/" + component(id), query: taskQuery(taskID))
|
||||
}
|
||||
|
||||
/// GET /papers/{id}/questions:按固定题位读取考前题目页。
|
||||
func questions(paperID: String, taskID: String, offset: Int, limit: Int) async throws -> TrainingQuestionPage {
|
||||
try await read("/papers/" + component(paperID) + "/questions", query: taskQuery(taskID) + offsetQuery(offset, limit: limit, maximum: 20))
|
||||
}
|
||||
|
||||
/// GET /tasks/{id}/draft:允许 limit=0 获取恢复位置和答题卡。
|
||||
func draft(taskID: String, offset: Int, limit: Int) async throws -> TrainingDraftPage {
|
||||
try await read("/tasks/" + component(taskID) + "/draft", query: offsetQuery(offset, limit: limit, maximum: 100, minimum: 0))
|
||||
}
|
||||
|
||||
/// PATCH /tasks/{id}/draft:只传变化题目的完整选择集合。
|
||||
func saveDraft(taskID: String, request: TrainingDraftSaveRequest) async throws -> TrainingDraftConfirmation {
|
||||
try await write(.patch, "/tasks/" + component(taskID) + "/draft", body: request)
|
||||
}
|
||||
|
||||
/// POST /tasks/{id}/draft/reset:返回当前草稿实况,调用者按版本同步。
|
||||
func resetDraft(taskID: String, request: TrainingDraftResetRequest) async throws -> TrainingDraftConfirmation {
|
||||
try await write(.post, "/tasks/" + component(taskID) + "/draft/reset", body: request)
|
||||
}
|
||||
|
||||
/// POST /tasks/{id}/submissions:消费已确认的草稿版本,不回传全部答案。
|
||||
func submit(taskID: String, request: TrainingSubmissionRequest) async throws -> TrainingSubmissionResult {
|
||||
try await write(.post, "/tasks/" + component(taskID) + "/submissions", body: request)
|
||||
}
|
||||
|
||||
/// GET /attempts:任务筛选和提交恢复复用成绩分页接口。
|
||||
func attempts(taskID: String?, submissionID: String?, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttemptSummary> {
|
||||
var query = cursorQuery(cursor, limit: limit, maximum: 50)
|
||||
if let taskID { query.append(item("task_id", taskID)) }
|
||||
if let submissionID { query.append(item("submission_id", submissionID)) }
|
||||
return try await read("/attempts", query: query)
|
||||
}
|
||||
|
||||
/// GET /attempts/{id}:单次成绩和最新重考资格。
|
||||
func attempt(id: String) async throws -> TrainingAttemptDetail { try await read("/attempts/" + component(id)) }
|
||||
|
||||
/// GET /attempts/{id}/reviews:单页最多十条,不自动下载全部解析。
|
||||
func reviews(attemptID: String, cursor: String?, limit: Int) async throws -> TrainingReviewPage {
|
||||
try await read("/attempts/" + component(attemptID) + "/reviews", query: cursorQuery(cursor, limit: limit, maximum: 10))
|
||||
}
|
||||
|
||||
private func read<Response: Decodable>(_ path: String, query: [URLQueryItem] = []) async throws -> Response {
|
||||
try await perform(APIRequest<Response>(method: .get, path: prefix + path, queryItems: query))
|
||||
}
|
||||
|
||||
private func write<Response: Decodable, Body: Encodable>(_ method: HTTPMethod, _ path: String, body: Body) async throws -> Response {
|
||||
try await perform(APIRequest<Response>(method: method, path: prefix + path, body: body))
|
||||
}
|
||||
|
||||
private func perform<Response: Decodable>(_ request: APIRequest<Response>) async throws -> Response {
|
||||
try checkContext()
|
||||
do {
|
||||
let response = try await client.send(request, tokenOverride: tokenOverride)
|
||||
try checkContext()
|
||||
return response
|
||||
} catch {
|
||||
try checkContext()
|
||||
throw TrainingRemoteError.map(error)
|
||||
}
|
||||
}
|
||||
|
||||
private func checkContext() throws {
|
||||
guard eligible else { throw TrainingRemoteError.accountInvalid("请切换到店铺账号后进入培训中心") }
|
||||
guard validateContext?() != false else { throw TrainingRemoteError.identityChanged }
|
||||
}
|
||||
|
||||
nonisolated private func item(_ name: String, _ value: String) -> URLQueryItem { URLQueryItem(name: name, value: value) }
|
||||
nonisolated private func taskQuery(_ id: String) -> [URLQueryItem] { [item("task_id", id)] }
|
||||
nonisolated private func cursorQuery(_ cursor: String?, limit: Int, maximum: Int) -> [URLQueryItem] {
|
||||
var query = [item("limit", String(min(max(limit, 1), maximum)))]
|
||||
if let cursor, !cursor.isEmpty { query.append(item("cursor", cursor)) }
|
||||
return query
|
||||
}
|
||||
nonisolated private func offsetQuery(_ offset: Int, limit: Int, maximum: Int, minimum: Int = 1) -> [URLQueryItem] {
|
||||
[item("offset", String(max(offset, 0))), item("limit", String(min(max(limit, minimum), maximum)))]
|
||||
}
|
||||
nonisolated private func component(_ id: String) -> String {
|
||||
id.addingPercentEncoding(withAllowedCharacters: CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~"))) ?? id
|
||||
}
|
||||
|
||||
/// 阅读会话创建请求,幂等键由业务状态持久保留。
|
||||
private struct ReadingStartBody: Encodable {
|
||||
let requestID: String
|
||||
enum CodingKeys: String, CodingKey { case requestID = "request_id" }
|
||||
}
|
||||
|
||||
/// 会话心跳请求;累计读时为本会话范围。
|
||||
private struct HeartbeatBody: Encodable {
|
||||
let sequence: Int
|
||||
let activeSecondsTotal: Int
|
||||
let final: Bool
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case sequence, final
|
||||
case activeSecondsTotal = "active_seconds_total"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import Foundation
|
||||
|
||||
/// 正式培训数据源;各资源独立读取,不为页面拼接全量任务聚合。
|
||||
protocol TrainingDataServing: Sendable {
|
||||
/// 获取当前学员全局统计。
|
||||
func summary() async throws -> TrainingSummary
|
||||
/// 按状态和关键词读取任务摘要页。
|
||||
func tasks(status: TrainingLearnerStatus?, keyword: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingTaskSummary>
|
||||
/// 获取任务规则和快照引用。
|
||||
func task(id: String) async throws -> TrainingTaskDetail
|
||||
/// 获取课程元信息,附当前授权任务。
|
||||
func course(id: String, taskID: String) async throws -> TrainingCourseInfo
|
||||
/// 获取小节目录页。
|
||||
func sections(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingSectionInfo>
|
||||
/// 读取一个小节的正式正文。
|
||||
func section(courseID: String, sectionID: String, taskID: String) async throws -> TrainingSectionContent
|
||||
/// 读取附件元信息页。
|
||||
func attachments(courseID: String, taskID: String, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttachmentInfo>
|
||||
/// 获取短期附件授权链接。
|
||||
func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink
|
||||
/// 刷新服务端已保存进度与操作资格。
|
||||
func progress(taskID: String) async throws -> TrainingProgressSnapshot
|
||||
/// 按幂等键建立阅读会话。
|
||||
func startReading(taskID: String, requestID: String) async throws -> TrainingStudySession
|
||||
/// 按会话序号确认有效读时;重试保持相同请求内容。
|
||||
func heartbeat(sessionID: String, sequence: Int, activeSecondsTotal: Int, final: Bool) async throws -> TrainingHeartbeatConfirmation
|
||||
/// 读取考试规则,不获取全部试题。
|
||||
func paper(id: String, taskID: String) async throws -> TrainingPaperInfo
|
||||
/// 按固定题位读取试题页。
|
||||
func questions(paperID: String, taskID: String, offset: Int, limit: Int) async throws -> TrainingQuestionPage
|
||||
/// 获取草稿元信息及当前题位答案;limit=0 只读取元信息。
|
||||
func draft(taskID: String, offset: Int, limit: Int) async throws -> TrainingDraftPage
|
||||
/// 串行增量保存本人选择。
|
||||
func saveDraft(taskID: String, request: TrainingDraftSaveRequest) async throws -> TrainingDraftConfirmation
|
||||
/// 用户确认重考后重置草稿;响应是当前实况而非恒定空草稿。
|
||||
func resetDraft(taskID: String, request: TrainingDraftResetRequest) async throws -> TrainingDraftConfirmation
|
||||
/// 消费已保存草稿版本并幂等交卷。
|
||||
func submit(taskID: String, request: TrainingSubmissionRequest) async throws -> TrainingSubmissionResult
|
||||
/// 分页读取成绩;taskID+submissionID 可恢复一次交卷结果。
|
||||
func attempts(taskID: String?, submissionID: String?, cursor: String?, limit: Int) async throws -> TrainingCursorPage<TrainingAttemptSummary>
|
||||
/// 读取一条成绩和最新重考资格。
|
||||
func attempt(id: String) async throws -> TrainingAttemptDetail
|
||||
/// 用户展开时读取解析页。
|
||||
func reviews(attemptID: String, cursor: String?, limit: Int) async throws -> TrainingReviewPage
|
||||
}
|
||||
|
||||
/// 培训稳定业务码及身份切换;保留服务器文案,恢复逻辑只依据枚举或 code。
|
||||
enum TrainingRemoteError: Error, LocalizedError, Equatable, Sendable {
|
||||
case accountInvalid(String), forbidden(String), notWritable(String), readingRequired(String)
|
||||
case sessionExpired(String), sessionConflict(String), draftRevisionConflict(String), idempotencyConflict(String)
|
||||
case answerInvalid(String), answerIncomplete(String), examNotAllowed(String), contentMissing(String)
|
||||
case attemptNotFound(String), paramInvalid(String), identityChanged
|
||||
|
||||
/// 返回稳定业务码,身份切换属于本地拒绝,没有服务端 code。
|
||||
var code: Int? {
|
||||
switch self {
|
||||
case .accountInvalid: 150100
|
||||
case .forbidden: 150101
|
||||
case .notWritable: 150102
|
||||
case .readingRequired: 150103
|
||||
case .sessionExpired: 150104
|
||||
case .sessionConflict: 150105
|
||||
case .draftRevisionConflict: 150106
|
||||
case .idempotencyConflict: 150107
|
||||
case .answerInvalid: 150108
|
||||
case .answerIncomplete: 150109
|
||||
case .examNotAllowed: 150110
|
||||
case .contentMissing: 150111
|
||||
case .attemptNotFound: 150112
|
||||
case .paramInvalid: 150113
|
||||
case .identityChanged: nil
|
||||
}
|
||||
}
|
||||
|
||||
/// 用于页面展示的错误文案,不参与错误分类。
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case let .accountInvalid(message), let .forbidden(message), let .notWritable(message), let .readingRequired(message),
|
||||
let .sessionExpired(message), let .sessionConflict(message), let .draftRevisionConflict(message),
|
||||
let .idempotencyConflict(message), let .answerInvalid(message), let .answerIncomplete(message),
|
||||
let .examNotAllowed(message), let .contentMissing(message), let .attemptNotFound(message), let .paramInvalid(message): message
|
||||
case .identityChanged: "学习账号或业务身份已切换,请重新进入培训中心"
|
||||
}
|
||||
}
|
||||
|
||||
/// 转换培训业务错误;网络和真正登录失效错误仍保留原类型。
|
||||
static func map(_ error: Error) -> Error {
|
||||
guard let apiError = error as? APIError,
|
||||
case let .serverCode(code, message) = apiError else { return error }
|
||||
switch code {
|
||||
case 150100: return Self.accountInvalid(message)
|
||||
case 150101: return Self.forbidden(message)
|
||||
case 150102: return Self.notWritable(message)
|
||||
case 150103: return Self.readingRequired(message)
|
||||
case 150104: return Self.sessionExpired(message)
|
||||
case 150105: return Self.sessionConflict(message)
|
||||
case 150106: return Self.draftRevisionConflict(message)
|
||||
case 150107: return Self.idempotencyConflict(message)
|
||||
case 150108: return Self.answerInvalid(message)
|
||||
case 150109: return Self.answerIncomplete(message)
|
||||
case 150110: return Self.examNotAllowed(message)
|
||||
case 150111: return Self.contentMissing(message)
|
||||
case 150112: return Self.attemptNotFound(message)
|
||||
case 150113: return Self.paramInvalid(message)
|
||||
default: return error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 生产数据源固定进入时的账号和业务上下文,拒绝切换身份后的迟到响应。
|
||||
enum TrainingRemoteServiceFactory {
|
||||
/// 当前店铺身份才可接入;Token 与业务范围固定在本次页面会话。
|
||||
@MainActor static func production() -> any TrainingDataServing {
|
||||
let session = AppStore.shared.session
|
||||
let token = session.token
|
||||
let scope = session.accountCachePrefix
|
||||
let scenicID = session.currentScenicId
|
||||
let storeID = session.currentStoreId
|
||||
let eligible = !token.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
&& session.accountType == .storeUser && !scope.isEmpty
|
||||
return NetworkServices.shared.trainingAPI.scoped(token: token, eligible: eligible, validateContext: {
|
||||
let current = AppStore.shared.session
|
||||
return current.isLoggedIn && current.accountType == .storeUser
|
||||
&& current.accountCachePrefix == scope && current.token == token
|
||||
&& current.currentScenicId == scenicID && current.currentStoreId == storeID
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
#if DEBUG
|
||||
import Foundation
|
||||
|
||||
/// 可替换的演示存储,用于验证原子保存与存储失败。
|
||||
protocol TrainingDemoStoring: Sendable {
|
||||
/// 不存在时返回 nil;读取错误必须向调用者报告。
|
||||
func read(key: String) throws -> Data?
|
||||
/// 原子写入一个作用域的完整快照。
|
||||
func write(_ data: Data, key: String) throws
|
||||
}
|
||||
|
||||
/// 使用原子文件保存本机演示,实际磁盘错误不会被忽略。
|
||||
struct TrainingDemoFileStorage: TrainingDemoStoring {
|
||||
let directory: URL
|
||||
|
||||
/// 默认存储在 App Application Support,不接触后台数据。
|
||||
init(directory: URL = URL.applicationSupportDirectory.appendingPathComponent("TrainingDemo", isDirectory: true)) {
|
||||
self.directory = directory
|
||||
}
|
||||
|
||||
/// 保留读取失败,避免把坏文件当作首次使用。
|
||||
func read(key: String) throws -> Data? {
|
||||
let url = fileURL(key: key)
|
||||
guard FileManager.default.fileExists(atPath: url.path) else { return nil }
|
||||
return try Data(contentsOf: url)
|
||||
}
|
||||
|
||||
/// 写入失败时原子文件不会被替换成不完整内容。
|
||||
func write(_ data: Data, key: String) throws {
|
||||
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
|
||||
try data.write(to: fileURL(key: key), options: .atomic)
|
||||
}
|
||||
|
||||
private func fileURL(key: String) -> URL {
|
||||
let name = Data(key.utf8).map { String(format: "%02x", $0) }.joined()
|
||||
return directory.appendingPathComponent(name).appendingPathExtension("json")
|
||||
}
|
||||
}
|
||||
|
||||
/// 仅开发演示使用的答案和解析,绝不进入正式试卷模型。
|
||||
struct TrainingDemoSolution: Codable, Sendable {
|
||||
let correctIDs: Set<String>
|
||||
let explanation: String
|
||||
}
|
||||
|
||||
/// 冻结任务内容、开发判分材料和学员进度。
|
||||
struct TrainingDemoPack: Codable, Sendable {
|
||||
var task: TrainingTask
|
||||
let solutions: [String: TrainingDemoSolution]
|
||||
}
|
||||
|
||||
/// 带版本的开发记录;未知版本和损坏文件均保留原数据。
|
||||
private struct TrainingDemoState: Codable {
|
||||
let version: Int
|
||||
var packs: [TrainingDemoPack]
|
||||
}
|
||||
|
||||
/// 开发演示数据源;actor 串行处理草稿、阅读和幂等交卷。
|
||||
actor TrainingDemoService: TrainingServing {
|
||||
/// 页面据此标记本机演示任务与成绩,区分正式数据源。
|
||||
nonisolated let isDemo = true
|
||||
private let context: TrainingContext
|
||||
private let storage: any TrainingDemoStoring
|
||||
private let now: @Sendable () -> Date
|
||||
private let seed: @Sendable (Date) -> [TrainingDemoPack]
|
||||
private let validateContext: @MainActor @Sendable () -> Bool
|
||||
|
||||
/// 注入时钟、存储与身份校验,便于真机测试全部边界。
|
||||
init(
|
||||
context: TrainingContext,
|
||||
storage: any TrainingDemoStoring = TrainingDemoFileStorage(),
|
||||
now: @escaping @Sendable () -> Date = { Date() },
|
||||
seed: @escaping @Sendable (Date) -> [TrainingDemoPack] = TrainingDemoFixtures.makePacks,
|
||||
validateContext: @escaping @MainActor @Sendable () -> Bool = { true }
|
||||
) {
|
||||
self.context = context
|
||||
self.storage = storage
|
||||
self.now = now
|
||||
self.seed = seed
|
||||
self.validateContext = validateContext
|
||||
}
|
||||
|
||||
/// 获取当前作用域全部本人演示任务。
|
||||
func listTasks() async throws -> [TrainingTask] {
|
||||
try await authorize()
|
||||
return try load().packs.map(\.task)
|
||||
}
|
||||
|
||||
/// 读取固定快照,后续示例代码更新不会覆盖已保存内容。
|
||||
func task(id: String) async throws -> TrainingTask {
|
||||
try await authorize()
|
||||
let state = try load()
|
||||
return state.packs[try index(id, in: state)].task
|
||||
}
|
||||
|
||||
/// 前台阅读每次增加一秒,写入成功后才向页面返回完成进度。
|
||||
func recordReadingSecond(taskID: String) async throws -> TrainingTask {
|
||||
try await authorize()
|
||||
var state = try load()
|
||||
let index = try index(taskID, in: state)
|
||||
var task = state.packs[index].task
|
||||
if task.learnerStatus == .completed || task.hasFinishedReading { return task }
|
||||
try ensureOpen(task)
|
||||
guard !task.course.sections.isEmpty,
|
||||
Set(task.course.sections.map(\.id)).count == task.course.sections.count else { throw TrainingError.invalidPaper }
|
||||
task.progress.readingSeconds = min(TrainingTask.requiredReadingSeconds, task.progress.readingSeconds + 1)
|
||||
if task.progress.readingSeconds >= TrainingTask.requiredReadingSeconds {
|
||||
task.progress.completedSectionIDs = Set(task.course.sections.map(\.id))
|
||||
if task.mode == .study { task.progress.completedAt = now() }
|
||||
}
|
||||
state.packs[index].task = task
|
||||
try save(state)
|
||||
return task
|
||||
}
|
||||
|
||||
/// 答案校验和保存作为同一笔操作,失败不清空原有草稿。
|
||||
func saveDraft(taskID: String, answers: TrainingAnswers) async throws {
|
||||
try await authorize()
|
||||
var state = try load()
|
||||
let index = try index(taskID, in: state)
|
||||
let task = state.packs[index].task
|
||||
try ensureExamAllowed(task)
|
||||
try TrainingValidation.validateAnswers(answers, task: task, requireComplete: false)
|
||||
state.packs[index].task.progress.draftAnswers = answers
|
||||
try save(state)
|
||||
}
|
||||
|
||||
/// 演示百分制本地判分;同一幂等键和答案返回原记录,正式服务须改为服务端判分。
|
||||
func submit(taskID: String, answers: TrainingAnswers, submissionID: String) async throws -> TrainingAttempt {
|
||||
try await authorize()
|
||||
var state = try load()
|
||||
let index = try index(taskID, in: state)
|
||||
let pack = state.packs[index]
|
||||
guard !submissionID.isEmpty else { throw TrainingError.invalidAnswers }
|
||||
if let attempt = pack.task.progress.attempts.first(where: { $0.id == submissionID }) {
|
||||
let submitted = Dictionary(uniqueKeysWithValues: attempt.reviews.map { ($0.question.id, $0.selectedIDs) })
|
||||
guard submitted == answers else { throw TrainingError.invalidAnswers }
|
||||
return attempt
|
||||
}
|
||||
try ensureExamAllowed(pack.task)
|
||||
try TrainingValidation.validateAnswers(answers, task: pack.task, requireComplete: true)
|
||||
let reviews = try pack.task.questions.map { question in
|
||||
guard let solution = pack.solutions[question.id],
|
||||
!solution.correctIDs.isEmpty,
|
||||
solution.correctIDs.isSubset(of: Set(question.options.map(\.id))),
|
||||
question.type == .single ? solution.correctIDs.count == 1 : solution.correctIDs.count >= 2 else {
|
||||
throw TrainingError.invalidPaper
|
||||
}
|
||||
return TrainingQuestionReview(question: question, selectedIDs: answers[question.id] ?? [],
|
||||
correctIDs: solution.correctIDs, explanation: solution.explanation)
|
||||
}
|
||||
let correct = reviews.filter(\.isCorrect).count
|
||||
let count = reviews.count
|
||||
let attempt = TrainingAttempt(id: submissionID, submittedAt: now(), scoreHundredths: correct * 10_000 / count,
|
||||
correctCount: correct, questionCount: count,
|
||||
passed: correct * 100 >= pack.task.passScore * count, isDemo: true, reviews: reviews)
|
||||
state.packs[index].task.progress.attempts.append(attempt)
|
||||
state.packs[index].task.progress.draftAnswers = [:]
|
||||
if attempt.passed { state.packs[index].task.progress.completedAt = attempt.submittedAt }
|
||||
try save(state)
|
||||
return attempt
|
||||
}
|
||||
|
||||
private func authorize() async throws {
|
||||
guard await validateContext() else { throw TrainingError.identityChanged }
|
||||
}
|
||||
|
||||
private func ensureOpen(_ task: TrainingTask) throws {
|
||||
if let reason = task.submissionBlockReason(now: now()) { throw TrainingError.blocked(reason) }
|
||||
}
|
||||
|
||||
private func ensureExamAllowed(_ task: TrainingTask) throws {
|
||||
try ensureOpen(task)
|
||||
guard task.mode == .exam else { throw TrainingError.invalidPaper }
|
||||
guard task.hasFinishedReading else { throw TrainingError.readingRequired }
|
||||
}
|
||||
|
||||
private func index(_ id: String, in state: TrainingDemoState) throws -> Int {
|
||||
guard let index = state.packs.firstIndex(where: { $0.task.id == id }) else { throw TrainingError.notFound }
|
||||
return index
|
||||
}
|
||||
|
||||
private func load() throws -> TrainingDemoState {
|
||||
let data: Data?
|
||||
do { data = try storage.read(key: context.storageKey) } catch { throw TrainingError.saveFailed }
|
||||
guard let data else {
|
||||
let initial = TrainingDemoState(version: 1, packs: seed(now()))
|
||||
try save(initial)
|
||||
return initial
|
||||
}
|
||||
guard let state = try? JSONDecoder().decode(TrainingDemoState.self, from: data), state.version == 1,
|
||||
Set(state.packs.map { $0.task.id }).count == state.packs.count,
|
||||
state.packs.allSatisfy({ !$0.task.id.isEmpty }) else { throw TrainingError.corruptStorage }
|
||||
return state
|
||||
}
|
||||
|
||||
private func save(_ state: TrainingDemoState) throws {
|
||||
do { try storage.write(JSONEncoder().encode(state), key: context.storageKey) }
|
||||
catch { throw TrainingError.saveFailed }
|
||||
}
|
||||
}
|
||||
|
||||
/// 示例取材于小程序培训内容;不代表正式景区政策。
|
||||
enum TrainingDemoFixtures {
|
||||
/// 首次建立固定课程和试卷快照,不根据真实人员名单生成任务。
|
||||
/// 任务有效期相对首次建立时间设置,后续读取保持已持久化快照。
|
||||
static func makePacks(now: Date) -> [TrainingDemoPack] {
|
||||
let sections = [
|
||||
TrainingSection(id: "section-1", title: "接待礼仪与服务告知", contentHTML: """
|
||||
<h2>让游客明白,再开始服务</h2><p>主动问候,介绍服务项目、费用、交付内容与时间。未经游客确认,不增加收费项目。</p>
|
||||
<p>遇到相似套餐,要讲清包含和不包含的项目。如果游客没有听清,应换一种表达再次说明,不把沉默当作确认。</p>
|
||||
<ul><li>主动、清晰地说明服务范围</li><li>尊重游客的知情与选择</li><li>保持耐心,不作无法兑现的承诺</li></ul>
|
||||
"""),
|
||||
TrainingSection(id: "section-2", title: "问题反馈与协同处理", contentHTML: """
|
||||
<h2>先倾听,再记录,再处理</h2><p>遇到问题先完整听取诉求,客观记录事情经过。超出职责范围时,联系景区工作人员协同处理,并跟进反馈。</p>
|
||||
<p>交接时说明已核实的信息、尚未解决的问题及后续负责人。预计无法按原时间反馈时,及时说明变化。</p>
|
||||
<p><strong>演示提醒:</strong>实际处理要求以景区发布的正式制度为准。</p>
|
||||
""")
|
||||
]
|
||||
let questions = [
|
||||
TrainingQuestion(id: "q1", type: .single, stem: "开始服务前,应先完成哪项工作?", options: [
|
||||
TrainingOption(id: "A", text: "说明项目、费用并取得游客确认"), TrainingOption(id: "B", text: "直接拍摄,结束后告知费用"),
|
||||
TrainingOption(id: "C", text: "仅口头承诺,不介绍交付内容")]),
|
||||
TrainingQuestion(id: "q2", type: .multiple, stem: "遇到超出职责范围的问题,以下做法正确的是?", options: [
|
||||
TrainingOption(id: "A", text: "倾听并记录游客诉求"), TrainingOption(id: "B", text: "联系景区工作人员协同处理"),
|
||||
TrainingOption(id: "C", text: "忽略问题,不再反馈")]),
|
||||
TrainingQuestion(id: "q3", type: .single, stem: "无法确定交付时间时,应该怎样回应?", options: [
|
||||
TrainingOption(id: "A", text: "随口给出一个时间"), TrainingOption(id: "B", text: "说明需要核实并约定反馈方式"),
|
||||
TrainingOption(id: "C", text: "先保证今天完成")]),
|
||||
TrainingQuestion(id: "q4", type: .multiple, stem: "交接服务时应明确哪些内容?", options: [
|
||||
TrainingOption(id: "A", text: "尚未解决的问题"), TrainingOption(id: "B", text: "后续负责人"),
|
||||
TrainingOption(id: "C", text: "已核实的信息"), TrainingOption(id: "D", text: "把未经核实的猜测作为事实")])
|
||||
]
|
||||
let solutions = [
|
||||
"q1": TrainingDemoSolution(correctIDs: ["A"], explanation: "开始服务前应清晰告知项目、费用及交付约定,并取得游客确认。"),
|
||||
"q2": TrainingDemoSolution(correctIDs: ["A", "B"], explanation: "先倾听记录,再协同处理,并跟进反馈。多选必须全部选对。"),
|
||||
"q3": TrainingDemoSolution(correctIDs: ["B"], explanation: "不确定的信息应核实后反馈,不作无法兑现的承诺。"),
|
||||
"q4": TrainingDemoSolution(correctIDs: ["A", "B", "C"], explanation: "交接应包含已核实信息、待办事项和后续负责人。")
|
||||
]
|
||||
let course = TrainingCourse(title: "景区服务规范与游客沟通", introduction: "从接待到反馈,统一一线服务标准。以下为开发演示材料。", sections: sections, attachments: [])
|
||||
func make(id: String, title: String, mode: TrainingMode, passScore: Int) -> TrainingDemoPack {
|
||||
let task = TrainingTask(id: id, title: title, publisherName: "演示管理员", mode: mode, status: .published,
|
||||
startAt: now.addingTimeInterval(-86400), endAt: now.addingTimeInterval(7 * 86400),
|
||||
passScore: passScore, scoring: TrainingTask.equalPercentageScoring, course: course,
|
||||
questions: mode == .exam ? questions : [], progress: TrainingProgress())
|
||||
return TrainingDemoPack(task: task, solutions: mode == .exam ? solutions : [:])
|
||||
}
|
||||
return [make(id: "demo-service", title: "一线服务规范学习(演示)", mode: .exam, passScore: 100),
|
||||
make(id: "demo-review", title: "游客沟通巩固练习(演示)", mode: .exam, passScore: 75),
|
||||
make(id: "demo-study", title: "接待礼仪课程学习(演示)", mode: .study, passScore: 100)]
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import Foundation
|
||||
import CryptoKit
|
||||
|
||||
/// 一题尚未确认的本机选择,题号用于离线恢复答题卡。
|
||||
struct TrainingDraftLocalAnswer: Codable, Equatable, Sendable {
|
||||
let questionID: String
|
||||
let order: Int
|
||||
let selectedOptionIDs: [String]
|
||||
}
|
||||
|
||||
/// 持久保存本机意图和已冻结的请求;账号范围中不保存登录凭证。
|
||||
struct TrainingDraftRecord: Codable, Equatable, Sendable {
|
||||
var generation: String = UUID().uuidString
|
||||
let taskID: String
|
||||
let paperSnapshotID: String
|
||||
let accountScope: String
|
||||
let scenicID: Int
|
||||
let storeID: Int
|
||||
var revision: Int
|
||||
var answers: [TrainingDraftLocalAnswer]
|
||||
var lastQuestionOrder: Int?
|
||||
var pendingSave: TrainingDraftSaveRequest?
|
||||
var pendingReset: TrainingDraftResetRequest?
|
||||
var hasConflict: Bool
|
||||
|
||||
/// 用固定的业务身份建立草稿日志。
|
||||
init(taskID: String, paperSnapshotID: String, context: TrainingContext, revision: Int,
|
||||
answers: [TrainingDraftLocalAnswer] = [], lastQuestionOrder: Int? = nil,
|
||||
pendingSave: TrainingDraftSaveRequest? = nil, pendingReset: TrainingDraftResetRequest? = nil,
|
||||
hasConflict: Bool = false) {
|
||||
self.taskID = taskID
|
||||
self.paperSnapshotID = paperSnapshotID
|
||||
accountScope = context.accountScope
|
||||
scenicID = context.scenicID
|
||||
storeID = context.storeID
|
||||
self.revision = revision
|
||||
self.answers = answers
|
||||
self.lastQuestionOrder = lastQuestionOrder
|
||||
self.pendingSave = pendingSave
|
||||
self.pendingReset = pendingReset
|
||||
self.hasConflict = hasConflict
|
||||
}
|
||||
|
||||
/// 草稿所属的账号、景区和店铺。
|
||||
var context: TrainingContext { TrainingContext(accountScope: accountScope, scenicID: scenicID, storeID: storeID) }
|
||||
}
|
||||
|
||||
/// 损坏日志或其它页面接管日志时,禁止继续覆盖未确认答案。
|
||||
enum TrainingDraftStorageError: Error, LocalizedError, Equatable {
|
||||
case invalidRecord, replaced, unavailable
|
||||
|
||||
/// 可呈现给用户的草稿恢复错误。
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidRecord: "本机未保存答案暂无法恢复,请保留当前页面并重试"
|
||||
case .replaced: "此任务已在另一答题页面打开,请返回后重新进入"
|
||||
case .unavailable: "未能保存本机答案,请检查可用空间后重试"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 按账号、景区、店铺、任务和试卷隔离草稿,以代次比较防止迟到回调覆盖新页面。
|
||||
final class TrainingDraftStore {
|
||||
private static let lock = NSRecursiveLock()
|
||||
private let defaults: UserDefaults
|
||||
private let directoryURL: URL?
|
||||
|
||||
/// 正式日志使用原子文件;测试可注入目录或独立 defaults 替身,不读取正式用户日志。
|
||||
init(defaults: UserDefaults = .standard, directoryURL: URL? = nil) {
|
||||
self.defaults = defaults
|
||||
if let directoryURL { self.directoryURL = directoryURL }
|
||||
else if defaults === UserDefaults.standard {
|
||||
let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first
|
||||
?? URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("Library/Application Support")
|
||||
self.directoryURL = support.appendingPathComponent("TrainingDrafts", isDirectory: true)
|
||||
} else { self.directoryURL = nil }
|
||||
}
|
||||
|
||||
/// 恢复日志;损坏记录不可当成无本机答案而自动覆盖。
|
||||
func load(taskID: String, paperSnapshotID: String, context: TrainingContext) throws -> TrainingDraftRecord? {
|
||||
Self.lock.lock()
|
||||
defer { Self.lock.unlock() }
|
||||
let storageKey = key(taskID, paperSnapshotID, context)
|
||||
let data: Data?
|
||||
if let fileURL = fileURL(storageKey), FileManager.default.fileExists(atPath: fileURL.path) {
|
||||
do { data = try Data(contentsOf: fileURL) }
|
||||
catch { throw TrainingDraftStorageError.unavailable }
|
||||
} else { data = defaults.data(forKey: storageKey) }
|
||||
guard let data else { return nil }
|
||||
guard let record = try? JSONDecoder().decode(TrainingDraftRecord.self, from: data),
|
||||
record.taskID == taskID, record.paperSnapshotID == paperSnapshotID, record.context == context,
|
||||
isValid(record) else { throw TrainingDraftStorageError.invalidRecord }
|
||||
return record
|
||||
}
|
||||
|
||||
/// 比较旧代次后原子更新日志,返回新代次;即使已保存也保留轻量代次防止旧页面复写。
|
||||
@discardableResult
|
||||
func save(_ value: TrainingDraftRecord, replacing generation: String?) throws -> String {
|
||||
Self.lock.lock()
|
||||
defer { Self.lock.unlock() }
|
||||
guard isValid(value) else { throw TrainingDraftStorageError.invalidRecord }
|
||||
let existing = try load(taskID: value.taskID, paperSnapshotID: value.paperSnapshotID, context: value.context)
|
||||
guard existing?.generation == generation else { throw TrainingDraftStorageError.replaced }
|
||||
var updated = value
|
||||
updated.generation = UUID().uuidString
|
||||
let data = try JSONEncoder().encode(updated)
|
||||
let storageKey = key(value.taskID, value.paperSnapshotID, value.context)
|
||||
if let fileURL = fileURL(storageKey), let directoryURL {
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true)
|
||||
// 原子替换完成才允许调用方发起 RPC;不依赖 UserDefaults 的异步磁盘刷新。
|
||||
try data.write(to: fileURL, options: .atomic)
|
||||
} catch { throw TrainingDraftStorageError.unavailable }
|
||||
} else { defaults.set(data, forKey: storageKey) }
|
||||
return updated.generation
|
||||
}
|
||||
|
||||
private func fileURL(_ storageKey: String) -> URL? {
|
||||
let name = SHA256.hash(data: Data(storageKey.utf8)).map { String(format: "%02x", $0) }.joined()
|
||||
return directoryURL?.appendingPathComponent(name + ".json")
|
||||
}
|
||||
|
||||
private func isValid(_ record: TrainingDraftRecord) -> Bool {
|
||||
func validOptions(_ values: [String]) -> Bool {
|
||||
values.count <= 6 && values.allSatisfy { !$0.isEmpty } && Set(values).count == values.count
|
||||
}
|
||||
func validPosition(_ value: Int?) -> Bool { value == nil || (1...500).contains(value!) }
|
||||
guard !record.generation.isEmpty, !record.taskID.isEmpty, !record.paperSnapshotID.isEmpty,
|
||||
!record.accountScope.isEmpty, record.revision > 0, validPosition(record.lastQuestionOrder),
|
||||
record.answers.count <= 500, Set(record.answers.map(\.questionID)).count == record.answers.count,
|
||||
Set(record.answers.map(\.order)).count == record.answers.count,
|
||||
record.answers.allSatisfy({ !$0.questionID.isEmpty && (1...500).contains($0.order) && validOptions($0.selectedOptionIDs) }),
|
||||
record.pendingSave == nil || record.pendingReset == nil else { return false }
|
||||
if let request = record.pendingSave {
|
||||
guard request.paperSnapshotID == record.paperSnapshotID, !request.requestID.isEmpty,
|
||||
request.baseRevision > 0, validPosition(request.lastQuestionOrder), request.changes.count <= 20,
|
||||
Set(request.changes.map(\.questionID)).count == request.changes.count,
|
||||
request.changes.allSatisfy({ !$0.questionID.isEmpty && validOptions($0.selectedOptionIDs) }) else { return false }
|
||||
}
|
||||
if let request = record.pendingReset {
|
||||
guard request.paperSnapshotID == record.paperSnapshotID, !request.requestID.isEmpty, request.baseRevision > 0 else { return false }
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private func key(_ task: String, _ paper: String, _ context: TrainingContext) -> String {
|
||||
let components = [context.accountScope, String(context.scenicID), String(context.storeID), task, paper]
|
||||
return "training-draft:v1:" + components.map { Data($0.utf8).base64EncodedString() }.joined(separator: ":")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import Foundation
|
||||
|
||||
/// 未确认交卷的原始请求及所属业务身份,供 App 重启后沿原键恢复。
|
||||
struct TrainingPendingSubmission: Codable, Equatable, Sendable {
|
||||
let taskID: String
|
||||
let request: TrainingSubmissionRequest
|
||||
let accountScope: String
|
||||
let scenicID: Int
|
||||
let storeID: Int
|
||||
|
||||
/// 固定本次提交的身份和请求,恢复时不读取新的草稿版本替换它。
|
||||
init(taskID: String, request: TrainingSubmissionRequest, context: TrainingContext) {
|
||||
self.taskID = taskID
|
||||
self.request = request
|
||||
accountScope = context.accountScope
|
||||
scenicID = context.scenicID
|
||||
storeID = context.storeID
|
||||
}
|
||||
|
||||
/// 本次交卷的持久化作用域,不包含 Token。
|
||||
var context: TrainingContext {
|
||||
TrainingContext(accountScope: accountScope, scenicID: scenicID, storeID: storeID)
|
||||
}
|
||||
}
|
||||
|
||||
/// 待恢复记录损坏时停止生成新提交,避免重复成绩。
|
||||
enum TrainingPendingSubmissionError: Error, LocalizedError, Equatable, Sendable {
|
||||
case invalidRecord, alreadyPending
|
||||
|
||||
/// 告知用户尚不能安全恢复本次提交。
|
||||
var errorDescription: String? {
|
||||
switch self {
|
||||
case .invalidRecord: "上次交卷状态暂无法确认,请联系工作人员核查成绩后重试"
|
||||
case .alreadyPending: "上次交卷尚未确认,请先恢复原提交结果"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 按账号、景区、店铺和任务隔离待确认交卷,支持注入独立 UserDefaults 测试。
|
||||
final class TrainingPendingSubmissionStore {
|
||||
private static let lock = NSRecursiveLock()
|
||||
private let defaults: UserDefaults
|
||||
|
||||
/// 使用指定的持久化域保存不含凭证的交卷请求。
|
||||
init(defaults: UserDefaults = .standard) { self.defaults = defaults }
|
||||
|
||||
/// 草稿与交卷使用同一注入域,但以独立的键和数据格式保存。
|
||||
func makeDraftStore() -> TrainingDraftStore { TrainingDraftStore(defaults: defaults) }
|
||||
|
||||
/// 当前店铺登录身份;与正式数据源一致,不要求景区 ID 大于零。
|
||||
@MainActor static func currentContext() -> TrainingContext? {
|
||||
let session = AppStore.shared.session
|
||||
guard session.isLoggedIn, session.accountType == .storeUser, !session.accountCachePrefix.isEmpty else { return nil }
|
||||
return TrainingContext(accountScope: session.accountCachePrefix, scenicID: session.currentScenicId, storeID: session.currentStoreId)
|
||||
}
|
||||
|
||||
/// 读取当前作用域记录,损坏记录不当作首次交卷处理。
|
||||
func load(taskID: String, context: TrainingContext) throws -> TrainingPendingSubmission? {
|
||||
Self.lock.lock()
|
||||
defer { Self.lock.unlock() }
|
||||
guard let data = defaults.data(forKey: key(taskID: taskID, context: context)) else { return nil }
|
||||
guard let value = try? JSONDecoder().decode(TrainingPendingSubmission.self, from: data),
|
||||
value.taskID == taskID, value.context == context,
|
||||
!value.request.submissionID.isEmpty, !value.request.paperSnapshotID.isEmpty,
|
||||
value.request.draftRevision > 0 else { throw TrainingPendingSubmissionError.invalidRecord }
|
||||
return value
|
||||
}
|
||||
|
||||
/// 在发起网络提交前保存原始请求;不得用当前版本覆盖待恢复版本。
|
||||
func save(_ value: TrainingPendingSubmission) throws {
|
||||
Self.lock.lock()
|
||||
defer { Self.lock.unlock() }
|
||||
if let existing = try load(taskID: value.taskID, context: value.context), existing != value {
|
||||
throw TrainingPendingSubmissionError.alreadyPending
|
||||
}
|
||||
let storageKey = key(taskID: value.taskID, context: value.context)
|
||||
defaults.set(try JSONEncoder().encode(value), forKey: storageKey)
|
||||
}
|
||||
|
||||
/// 只移除仍对应这次提交的记录,避免迟到响应删除后续待恢复请求。
|
||||
func remove(_ value: TrainingPendingSubmission) throws {
|
||||
Self.lock.lock()
|
||||
defer { Self.lock.unlock() }
|
||||
guard try load(taskID: value.taskID, context: value.context) == value else { return }
|
||||
defaults.removeObject(forKey: key(taskID: value.taskID, context: value.context))
|
||||
}
|
||||
|
||||
private func key(taskID: String, context: TrainingContext) -> String {
|
||||
let scope = Data(context.accountScope.utf8).map { String(format: "%02x", $0) }.joined()
|
||||
let task = Data(taskID.utf8).map { String(format: "%02x", $0) }.joined()
|
||||
return "training-pending-submission:v1:\(scope):scenic_\(context.scenicID):store_\(context.storeID):task_\(task)"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import Foundation
|
||||
|
||||
/// 培训数据源接口。正式实现应使用登录态授权,不接受任意学员 ID。
|
||||
protocol TrainingServing: Sendable {
|
||||
/// 是否为本机开发演示。
|
||||
var isDemo: Bool { get }
|
||||
/// 获取本人任务列表。
|
||||
func listTasks() async throws -> [TrainingTask]
|
||||
/// 获取本人任务、发布快照与进度。
|
||||
func task(id: String) async throws -> TrainingTask
|
||||
/// 累计一秒有效前台阅读,服务端实现需核验学习会话。
|
||||
func recordReadingSecond(taskID: String) async throws -> TrainingTask
|
||||
/// 保存本人当前试卷草稿。
|
||||
func saveDraft(taskID: String, answers: TrainingAnswers) async throws
|
||||
/// 按幂等键提交试卷,返回服务端成绩和考后解析。
|
||||
func submit(taskID: String, answers: TrainingAnswers, submissionID: String) async throws -> TrainingAttempt
|
||||
}
|
||||
|
||||
/// 尚未联调的正式数据源,不生成假任务或假成绩。
|
||||
struct UnconnectedTrainingService: TrainingServing {
|
||||
/// 占位正式服务不会生成本地演示内容。
|
||||
let isDemo = false
|
||||
/// 无正式接口时拒绝生成任务。
|
||||
func listTasks() async throws -> [TrainingTask] { throw TrainingError.unavailable }
|
||||
/// 无正式接口时拒绝生成课程或进度。
|
||||
func task(id: String) async throws -> TrainingTask { throw TrainingError.unavailable }
|
||||
/// 无正式接口时禁止记录真实学习完成。
|
||||
func recordReadingSecond(taskID: String) async throws -> TrainingTask { throw TrainingError.unavailable }
|
||||
/// 无正式接口时禁止保存正式草稿。
|
||||
func saveDraft(taskID: String, answers: TrainingAnswers) async throws { throw TrainingError.unavailable }
|
||||
/// 无正式接口时禁止返回正式成绩。
|
||||
func submit(taskID: String, answers: TrainingAnswers, submissionID: String) async throws -> TrainingAttempt {
|
||||
throw TrainingError.unavailable
|
||||
}
|
||||
}
|
||||
|
||||
/// 按登录账号、景区和店铺隔离本地开发记录;不表示自然人认证。
|
||||
struct TrainingContext: Equatable, Sendable {
|
||||
let accountScope: String
|
||||
let scenicID: Int
|
||||
let storeID: Int
|
||||
|
||||
/// 缺少有效登录身份时禁止初始化演示记录。
|
||||
@MainActor static func current() -> TrainingContext? {
|
||||
let session = AppStore.shared.session
|
||||
guard session.isLoggedIn, !session.accountCachePrefix.isEmpty, session.currentScenicId > 0 else { return nil }
|
||||
return TrainingContext(accountScope: session.accountCachePrefix, scenicID: session.currentScenicId, storeID: session.currentStoreId)
|
||||
}
|
||||
|
||||
/// 使用不含凭证的账号与业务上下文作为持久化作用域。
|
||||
var storageKey: String { "training-demo:v1:\(accountScope):scenic_\(scenicID):store_\(storeID)" }
|
||||
}
|
||||
|
||||
/// 开发环境显式提供示例入口,Release 始终使用待接入服务。
|
||||
enum TrainingServiceFactory {
|
||||
/// 正式入口默认处于待接入状态,避免演示替代真实任务。
|
||||
static func production() -> any TrainingServing { UnconnectedTrainingService() }
|
||||
|
||||
#if DEBUG
|
||||
/// 只在开发版本中创建隔离的本机演示数据源。
|
||||
@MainActor static func demo() throws -> any TrainingServing {
|
||||
guard let context = TrainingContext.current() else { throw TrainingError.identityChanged }
|
||||
return TrainingDemoService(context: context, validateContext: {
|
||||
TrainingContext.current() == context
|
||||
})
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,744 @@
|
||||
import Foundation
|
||||
|
||||
/// 分页考试状态;全局已答题号与当前页答案分离,交卷只消费服务端草稿版本。
|
||||
final class TrainingRemoteExamViewModel {
|
||||
/// 固定的本人任务标识。
|
||||
let taskID: String
|
||||
/// 已验证的轻量任务摘要。
|
||||
private(set) var task: TrainingTaskSummary?
|
||||
/// 服务端当前考试资格。
|
||||
private(set) var progress: TrainingProgressSnapshot?
|
||||
/// 冻结试卷规则与总题数。
|
||||
private(set) var paper: TrainingPaperInfo?
|
||||
/// 当前展示题位,使用从零开始的索引。
|
||||
private(set) var currentIndex = 0
|
||||
/// 服务端已答题号叠加本机期望选择,题号从一开始。
|
||||
var answeredQuestionOrders: Set<Int> {
|
||||
var orders = confirmedAnsweredOrders
|
||||
for answer in desiredAnswers.values {
|
||||
if answer.selectedOptionIDs.isEmpty { orders.remove(answer.order) }
|
||||
else { orders.insert(answer.order) }
|
||||
}
|
||||
return orders
|
||||
}
|
||||
private var confirmedAnsweredOrders: Set<Int> = []
|
||||
/// 最近确认的草稿版本,未加载前为零。
|
||||
private(set) var draftRevision = 0
|
||||
/// 前台加载或交卷期间暂停编辑;后台草稿写入独立协调。
|
||||
private(set) var isBusy = false
|
||||
/// 最近失败的展示文案,业务分支不依赖文案。
|
||||
private(set) var errorMessage: String?
|
||||
/// 已提交或恢复的成绩,可直接进入成绩页面。
|
||||
private(set) var submittedAttempt: TrainingAttemptSummary?
|
||||
/// 首次交卷返回的成绩及资格,成绩首屏可复用而无需等待额外请求。
|
||||
private(set) var submittedResult: TrainingAttemptDetail?
|
||||
/// 账号不支持培训或任务无访问权限时返回培训中心,身份变化时退出到根页面。
|
||||
private(set) var shouldReturnToCenter = false
|
||||
|
||||
private let pageSize: Int
|
||||
private let pendingStore: TrainingPendingSubmissionStore
|
||||
private let draftStore: TrainingDraftStore
|
||||
private let debounceNanoseconds: UInt64
|
||||
private var desiredAnswers: [String: TrainingDraftLocalAnswer] = [:]
|
||||
private var desiredPosition: Int?
|
||||
private var draftGeneration: String?
|
||||
private var restoredPaperID: String?
|
||||
private var debounceTask: Task<Void, Never>?
|
||||
private var writerTask: Task<Bool, Never>?
|
||||
private var isReadingDraft = false
|
||||
private var draftReadWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
private var saveFailure: String?
|
||||
/// 后台草稿请求状态变化;页面主动读取快照,不承担前台导航操作。
|
||||
var onDraftSaveStateChange: (@MainActor () -> Void)?
|
||||
/// 后台请求不锁住已加载题目的编辑。
|
||||
private(set) var isSaving = false
|
||||
/// 版本冲突必须由用户明确确认,不能悄悄覆盖其它设备的答案。
|
||||
private(set) var hasDraftConflict = false
|
||||
/// 有待提交的本机意图或尚未确认的原请求。
|
||||
var hasUnsavedChanges: Bool { !desiredAnswers.isEmpty || desiredPosition != nil || pendingMutation != nil }
|
||||
/// 底部轻量保存状态,不使用全局遮罩。
|
||||
var draftSaveMessage: String {
|
||||
if hasDraftConflict { return "答案已在其他设备变更,重试保存将应用本机未保存选择" }
|
||||
if let saveFailure { return "保存失败,本机选择已保留:" + saveFailure }
|
||||
return isSaving || hasUnsavedChanges ? "正在保存答案…" : "答案已保存,可稍后继续"
|
||||
}
|
||||
private let currentContext: @MainActor @Sendable () -> TrainingContext?
|
||||
private var context: TrainingContext?
|
||||
private var questionCache: [Int: TrainingQuestionItem] = [:]
|
||||
private var answerCache: TrainingAnswers = [:]
|
||||
private var loadedDraftIndices: Set<Int> = []
|
||||
private var pendingSubmission: TrainingPendingSubmission?
|
||||
private var pendingMutation: DraftMutation?
|
||||
private var initialResetRequested = false
|
||||
private var needsDraftRefresh = false
|
||||
private var recoveryStorageFailed = false
|
||||
private var identityIsValid = true
|
||||
|
||||
/// 未确认的草稿写入保持原请求 ID、版本和内容,不能被新的选择替换。
|
||||
private enum DraftMutation {
|
||||
case save(TrainingDraftSaveRequest)
|
||||
case reset(TrainingDraftResetRequest)
|
||||
}
|
||||
|
||||
/// 注入身份与持久化域,测试不访问全局登录态或网络。
|
||||
init(taskID: String, context: TrainingContext? = nil, pageSize: Int = 10,
|
||||
pendingStore: TrainingPendingSubmissionStore = TrainingPendingSubmissionStore(),
|
||||
draftStore: TrainingDraftStore? = nil, debounceNanoseconds: UInt64 = 300_000_000,
|
||||
currentContext: @escaping @MainActor @Sendable () -> TrainingContext? = { TrainingPendingSubmissionStore.currentContext() }) {
|
||||
self.taskID = taskID
|
||||
self.context = context
|
||||
self.pageSize = min(20, max(1, pageSize))
|
||||
self.pendingStore = pendingStore
|
||||
self.draftStore = draftStore ?? pendingStore.makeDraftStore()
|
||||
self.debounceNanoseconds = debounceNanoseconds
|
||||
self.currentContext = currentContext
|
||||
}
|
||||
|
||||
deinit { debounceTask?.cancel() }
|
||||
|
||||
/// 已知总题数,无需获取全部题目正文。
|
||||
var questionCount: Int { paper?.questionCount ?? 0 }
|
||||
/// 全局已答数量,不把未下载的答案当成漏答。
|
||||
var answeredCount: Int { answeredQuestionOrders.count }
|
||||
/// 当前已加载的题目。
|
||||
var currentQuestion: TrainingQuestionItem? { questionCache[currentIndex] }
|
||||
/// 当前题的本机期望选择,未修改时使用已确认答案。
|
||||
var currentSelectedIDs: Set<String> { currentQuestion.map { Set(desiredAnswers[$0.id]?.selectedOptionIDs ?? Array(answerCache[$0.id] ?? [])) } ?? [] }
|
||||
/// 第一处真正漏答的题位。
|
||||
var firstUnansweredIndex: Int? {
|
||||
guard questionCount > 0 else { return nil }
|
||||
return (1...questionCount).first { !answeredQuestionOrders.contains($0) }.map { $0 - 1 }
|
||||
}
|
||||
/// 存在未确认交卷时暂停编辑,直到恢复同一次结果。
|
||||
var hasPendingSubmission: Bool { pendingSubmission != nil }
|
||||
/// 页面所属账号、景区或店铺已变化,不能继续显示原身份的数据。
|
||||
var isIdentityInvalid: Bool { !identityIsValid }
|
||||
/// 存在需要用户明确重试或确认的草稿操作。
|
||||
var hasPendingMutation: Bool { saveFailure != nil || hasDraftConflict || isResetPending }
|
||||
private var isResetPending: Bool { if case .reset? = pendingMutation { return true }; return false }
|
||||
/// 当前题正文和对应草稿范围均成功读取后,才可展示为可编辑答案。
|
||||
var isCurrentPageReady: Bool { currentQuestion != nil && loadedDraftIndices.contains(currentIndex) && !needsDraftRefresh }
|
||||
/// 页读取或冲突后的恢复失败时,沿当前题位重试读取,保留其它页缓存。
|
||||
var canRetryCurrentPage: Bool {
|
||||
!isBusy && identityIsValid && !hasPendingSubmission && !isResetPending && !recoveryStorageFailed
|
||||
&& !shouldReturnToCenter && submittedAttempt == nil && paper != nil && !isCurrentPageReady
|
||||
&& progress?.canStartExam == true && progress?.learnerStatus == .pendingExam
|
||||
}
|
||||
/// 权威资格及当前页就绪时可编辑,后台保存不会阻断本机选择。
|
||||
var canEdit: Bool {
|
||||
!isBusy && identityIsValid && !hasPendingSubmission && !isResetPending && !needsDraftRefresh && !recoveryStorageFailed
|
||||
&& submittedAttempt == nil && progress?.canStartExam == true && progress?.learnerStatus == .pendingExam
|
||||
&& !shouldReturnToCenter && paper != nil && isCurrentPageReady
|
||||
}
|
||||
|
||||
/// 返回已提交页面前再次核对身份,避免把缓存成绩显示给切换后的账号。
|
||||
func validateIdentity() async {
|
||||
do { try await authorize() }
|
||||
catch { report(error) }
|
||||
}
|
||||
|
||||
/// 恢复待确认提交优先于考试资格校验;正常加载只取恢复题位所在的一页。
|
||||
func load(service: any TrainingDataServing, resetDraft: Bool = false) async {
|
||||
guard !isBusy else { return }
|
||||
isBusy = true
|
||||
isReadingDraft = true
|
||||
debounceTask?.cancel()
|
||||
debounceTask = nil
|
||||
errorMessage = nil
|
||||
defer {
|
||||
isBusy = false
|
||||
finishDraftRead(service: service)
|
||||
}
|
||||
do {
|
||||
try await authorize()
|
||||
guard let context else { throw TrainingRemoteError.identityChanged }
|
||||
do {
|
||||
pendingSubmission = try pendingStore.load(taskID: taskID, context: context)
|
||||
recoveryStorageFailed = false
|
||||
} catch {
|
||||
recoveryStorageFailed = true
|
||||
throw error
|
||||
}
|
||||
if pendingSubmission != nil {
|
||||
_ = try await recoverSubmission(service: service)
|
||||
return
|
||||
}
|
||||
if let writerTask { _ = await writerTask.value }
|
||||
let detail = try await service.task(id: taskID)
|
||||
try await authorize()
|
||||
let latestProgress = try await service.progress(taskID: taskID)
|
||||
try await authorize()
|
||||
task = detail.summary
|
||||
progress = latestProgress
|
||||
try requireExamAllowed()
|
||||
guard let paperID = task?.paperSnapshotID else { throw TrainingError.invalidPaper }
|
||||
let loadedPaper = try await service.paper(id: paperID, taskID: taskID)
|
||||
try await authorize()
|
||||
guard loadedPaper.id == paperID, (1...500).contains(loadedPaper.questionCount),
|
||||
loadedPaper.scoring == TrainingTask.equalPercentageScoring else { throw TrainingError.invalidPaper }
|
||||
if paper?.id != loadedPaper.id { questionCache = [:]; answerCache = [:]; loadedDraftIndices = [] }
|
||||
paper = loadedPaper
|
||||
try restoreDraftIfNeeded()
|
||||
// 已冻结请求先沿原键确认;明确重考也不能越过未知写入。
|
||||
if pendingMutation != nil, !hasDraftConflict {
|
||||
saveFailure = nil
|
||||
_ = await flushDraftNow(service: service)
|
||||
guard identityIsValid, !shouldReturnToCenter, !isResetPending else { return }
|
||||
}
|
||||
let metadata = try await service.draft(taskID: taskID, offset: 0, limit: 0)
|
||||
try await authorize()
|
||||
try applyMetadata(metadata)
|
||||
let position = desiredPosition ?? metadata.lastQuestionOrder
|
||||
currentIndex = (1...questionCount).contains(position) ? position - 1 : 0
|
||||
if resetDraft, !initialResetRequested {
|
||||
guard !hasUnsavedChanges, !hasDraftConflict else {
|
||||
saveFailure = "请先确认上次未保存答案,再重新发起重考"
|
||||
notifyDraftState()
|
||||
return
|
||||
}
|
||||
initialResetRequested = true
|
||||
pendingMutation = .reset(TrainingDraftResetRequest(requestID: UUID().uuidString, paperSnapshotID: paperID, baseRevision: draftRevision))
|
||||
try persistDraft()
|
||||
guard await flushDraftNow(service: service) else { return }
|
||||
} else {
|
||||
try await loadCurrentPage(service: service)
|
||||
}
|
||||
try persistDraft()
|
||||
if hasUnsavedChanges, !hasDraftConflict, saveFailure == nil { scheduleSave(service: service) }
|
||||
} catch {
|
||||
if error is TrainingDraftStorageError { reportSaveFailure(error) }
|
||||
else { report(error) }
|
||||
}
|
||||
}
|
||||
|
||||
/// 已缓存题目立即切换;位置变更并入后台串行草稿,不等待 ACK。
|
||||
@discardableResult
|
||||
func goToCachedQuestion(_ index: Int, service: any TrainingDataServing) -> Bool {
|
||||
guard canEdit, (0..<questionCount).contains(index), questionCache[index] != nil,
|
||||
loadedDraftIndices.contains(index) else { return false }
|
||||
currentIndex = index
|
||||
desiredPosition = index + 1
|
||||
queueDraft(service: service)
|
||||
return true
|
||||
}
|
||||
|
||||
/// 未缓存题按需加载,读取完成后继续本机选择;后台保存不会锁住缓存导航。
|
||||
func goToQuestion(_ index: Int, service: any TrainingDataServing) async {
|
||||
guard canEdit, (0..<questionCount).contains(index) else { return }
|
||||
if goToCachedQuestion(index, service: service) { return }
|
||||
isBusy = true
|
||||
isReadingDraft = true
|
||||
debounceTask?.cancel()
|
||||
debounceTask = nil
|
||||
errorMessage = nil
|
||||
defer {
|
||||
isBusy = false
|
||||
finishDraftRead(service: service)
|
||||
}
|
||||
do {
|
||||
try await authorize()
|
||||
if let writerTask { _ = await writerTask.value }
|
||||
currentIndex = index
|
||||
try await loadCurrentPage(service: service)
|
||||
desiredPosition = index + 1
|
||||
queueDraft(service: service)
|
||||
} catch { report(error) }
|
||||
}
|
||||
|
||||
/// 计算即时选择;重复单选是无操作,不创建请求或重置防抖。
|
||||
func selectionPreview(optionID: String) -> Set<String>? {
|
||||
guard canEdit, let question = currentQuestion,
|
||||
question.options.contains(where: { $0.id == optionID }) else { return nil }
|
||||
var selected = currentSelectedIDs
|
||||
if question.type == .single {
|
||||
guard selected != [optionID] else { return nil }
|
||||
selected = [optionID]
|
||||
} else if selected.contains(optionID) { selected.remove(optionID) }
|
||||
else { selected.insert(optionID) }
|
||||
return selected
|
||||
}
|
||||
|
||||
/// 同步更新并持久保存期望选择,允许上一请求未返回时继续改选。
|
||||
@discardableResult
|
||||
func selectLocally(optionID: String, service: any TrainingDataServing) -> Bool {
|
||||
guard let selected = selectionPreview(optionID: optionID), let question = currentQuestion else { return false }
|
||||
desiredAnswers[question.id] = TrainingDraftLocalAnswer(questionID: question.id, order: question.order,
|
||||
selectedOptionIDs: selected.sorted())
|
||||
desiredPosition = question.order
|
||||
errorMessage = nil
|
||||
// 尚未发出且已回到 ACK 选择的变化无需发送。
|
||||
if pendingMutation == nil, selected == (answerCache[question.id] ?? []) { desiredAnswers.removeValue(forKey: question.id) }
|
||||
queueDraft(service: service)
|
||||
return true
|
||||
}
|
||||
|
||||
/// 兼容调用方的异步入口,仅排入本机草稿;需要确认保存时显式 flushDraft。
|
||||
func select(optionID: String, service: any TrainingDataServing) async {
|
||||
_ = selectLocally(optionID: optionID, service: service)
|
||||
}
|
||||
|
||||
/// 立即排空所有草稿,等待在飞请求后使用最新 ACK 版本,不并发提交同一版本。
|
||||
@discardableResult
|
||||
func flushDraft(service: any TrainingDataServing) async -> Bool {
|
||||
if isReadingDraft {
|
||||
await withCheckedContinuation { draftReadWaiters.append($0) }
|
||||
}
|
||||
return await flushDraftNow(service: service)
|
||||
}
|
||||
|
||||
private func flushDraftNow(service: any TrainingDataServing) async -> Bool {
|
||||
debounceTask?.cancel()
|
||||
debounceTask = nil
|
||||
while true {
|
||||
if let writerTask {
|
||||
guard await writerTask.value else { return false }
|
||||
continue
|
||||
}
|
||||
guard !hasDraftConflict, saveFailure == nil, !recoveryStorageFailed else { return false }
|
||||
guard hasUnsavedChanges else { return true }
|
||||
let task = Task { @MainActor in await self.drainDraft(service: service) }
|
||||
writerTask = task
|
||||
guard await task.value else { return false }
|
||||
}
|
||||
}
|
||||
|
||||
/// 保存失败后明确重试冻结的原请求,不能更换原幂等键和 payload。
|
||||
func retryMutation(service: any TrainingDataServing) async {
|
||||
guard !isBusy, !hasPendingSubmission, !hasDraftConflict else { return }
|
||||
if recoveryStorageFailed {
|
||||
do { try persistDraft(); recoveryStorageFailed = false }
|
||||
catch { reportSaveFailure(error); notifyDraftState(); return }
|
||||
}
|
||||
saveFailure = nil
|
||||
errorMessage = nil
|
||||
if await flushDraft(service: service), currentQuestion == nil { await load(service: service) }
|
||||
}
|
||||
|
||||
/// 用户明确选择本机或服务端答案后才结束版本冲突暂停。
|
||||
func resolveDraftConflict(useLocalAnswers: Bool, service: any TrainingDataServing) async {
|
||||
guard !isBusy, hasDraftConflict, !hasPendingSubmission else { return }
|
||||
do {
|
||||
try await authorize()
|
||||
try await refreshDraft(service: service)
|
||||
if !useLocalAnswers { desiredAnswers = [:]; desiredPosition = nil }
|
||||
hasDraftConflict = false
|
||||
saveFailure = nil
|
||||
errorMessage = nil
|
||||
try persistDraft()
|
||||
_ = await flushDraft(service: service)
|
||||
} catch { reportSaveFailure(error) }
|
||||
notifyDraftState()
|
||||
}
|
||||
|
||||
/// 仅重读当前未就绪题位;已确认的其它页不会因一次网络失败被清空。
|
||||
func retryCurrentPage(service: any TrainingDataServing) async {
|
||||
guard canRetryCurrentPage else { return }
|
||||
isBusy = true
|
||||
isReadingDraft = true
|
||||
debounceTask?.cancel()
|
||||
debounceTask = nil
|
||||
errorMessage = nil
|
||||
defer {
|
||||
isBusy = false
|
||||
finishDraftRead(service: service)
|
||||
}
|
||||
do {
|
||||
try await authorize()
|
||||
if let writerTask { _ = await writerTask.value }
|
||||
if needsDraftRefresh { try await refreshDraft(service: service) }
|
||||
else { try await loadCurrentPage(service: service) }
|
||||
} catch { report(error) }
|
||||
}
|
||||
|
||||
/// 持久保存交卷请求后提交;未知结果先查原键,再重试原版本。
|
||||
func submit(service: any TrainingDataServing) async -> TrainingAttemptSummary? {
|
||||
guard !isBusy, !isResetPending, !recoveryStorageFailed else { return nil }
|
||||
let wasEditable = canEdit
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await authorize()
|
||||
if pendingSubmission != nil { return try await recoverSubmission(service: service) }
|
||||
guard let context else { throw TrainingRemoteError.identityChanged }
|
||||
if let persisted = try pendingStore.load(taskID: taskID, context: context) {
|
||||
pendingSubmission = persisted
|
||||
return try await recoverSubmission(service: service)
|
||||
}
|
||||
guard wasEditable, firstUnansweredIndex == nil else {
|
||||
errorMessage = "还有 \(questionCount - answeredCount) 道题未作答"
|
||||
return nil
|
||||
}
|
||||
try requireExamAllowed()
|
||||
guard await flushDraft(service: service), !hasUnsavedChanges else { return nil }
|
||||
try await authorize()
|
||||
guard let paper else { throw TrainingError.invalidPaper }
|
||||
let request = TrainingSubmissionRequest(submissionID: UUID().uuidString, paperSnapshotID: paper.id, draftRevision: draftRevision)
|
||||
let pending = TrainingPendingSubmission(taskID: taskID, request: request, context: context)
|
||||
do { try pendingStore.save(pending) }
|
||||
catch TrainingPendingSubmissionError.alreadyPending {
|
||||
pendingSubmission = try pendingStore.load(taskID: taskID, context: context)
|
||||
return try await recoverSubmission(service: service)
|
||||
}
|
||||
pendingSubmission = pending
|
||||
return try await sendSubmission(pending, service: service)
|
||||
} catch { report(error); return nil }
|
||||
}
|
||||
|
||||
private func report(_ error: Error) {
|
||||
errorMessage = error.localizedDescription
|
||||
switch error {
|
||||
case TrainingRemoteError.identityChanged:
|
||||
identityIsValid = false
|
||||
shouldReturnToCenter = true
|
||||
task = nil
|
||||
progress = nil
|
||||
paper = nil
|
||||
questionCache = [:]
|
||||
answerCache = [:]
|
||||
loadedDraftIndices = []
|
||||
confirmedAnsweredOrders = []
|
||||
desiredAnswers = [:]
|
||||
desiredPosition = nil
|
||||
debounceTask?.cancel()
|
||||
draftRevision = 0
|
||||
currentIndex = 0
|
||||
submittedAttempt = nil
|
||||
submittedResult = nil
|
||||
// 保留原身份的未知请求,不能因切换账号而删除或换键重试。
|
||||
case TrainingRemoteError.forbidden, TrainingRemoteError.accountInvalid: shouldReturnToCenter = true
|
||||
default: break
|
||||
}
|
||||
}
|
||||
|
||||
private func authorize() async throws {
|
||||
guard let actual = await currentContext() else { identityIsValid = false; throw TrainingRemoteError.identityChanged }
|
||||
if context == nil { context = actual }
|
||||
guard actual == context else { identityIsValid = false; throw TrainingRemoteError.identityChanged }
|
||||
identityIsValid = true
|
||||
}
|
||||
|
||||
private func requireExamAllowed() throws {
|
||||
guard task?.id == taskID, progress?.taskID == taskID else { throw TrainingError.invalidPaper }
|
||||
guard task?.mode == .exam, task?.learnerStatus == .pendingExam,
|
||||
progress?.learnerStatus == .pendingExam, progress?.completedAt == nil,
|
||||
progress?.canStartExam == true, progress?.readingCompleted == true else {
|
||||
throw TrainingRemoteError.examNotAllowed("当前任务暂不能考试,请返回课程确认学习进度和任务状态")
|
||||
}
|
||||
}
|
||||
|
||||
private func applyMetadata(_ value: TrainingDraftPage) throws {
|
||||
let orders = Set(value.answeredQuestionOrders)
|
||||
guard value.taskID == taskID, value.paperSnapshotID == paper?.id, value.total == questionCount,
|
||||
value.draftRevision > 0, orders.count == value.answeredCount,
|
||||
orders.allSatisfy({ (1...questionCount).contains($0) }) else { throw TrainingError.invalidAnswers }
|
||||
// 迟到 GET 不回退已确认版本;本机 overlay 与服务端缓存分别管理。
|
||||
guard value.draftRevision >= draftRevision else { return }
|
||||
if value.draftRevision > draftRevision, !desiredAnswers.isEmpty, pendingMutation == nil {
|
||||
hasDraftConflict = true
|
||||
}
|
||||
if value.draftRevision != draftRevision { answerCache = [:]; loadedDraftIndices = [] }
|
||||
draftRevision = value.draftRevision
|
||||
confirmedAnsweredOrders = orders
|
||||
}
|
||||
|
||||
private func loadCurrentPage(service: any TrainingDataServing) async throws {
|
||||
guard let paper else { throw TrainingError.invalidPaper }
|
||||
let offset = currentIndex / pageSize * pageSize
|
||||
if questionCache[currentIndex] == nil {
|
||||
try await fetchQuestions(offset: offset, paperID: paper.id, service: service)
|
||||
// 大小预算允许后端缩短页;远处题号直接请求目标位置,避免遍历此前的页。
|
||||
if questionCache[currentIndex] == nil, currentIndex != offset {
|
||||
try await fetchQuestions(offset: currentIndex, paperID: paper.id, service: service)
|
||||
}
|
||||
guard currentQuestion != nil else { throw TrainingError.invalidPaper }
|
||||
}
|
||||
if !loadedDraftIndices.contains(currentIndex) {
|
||||
try await fetchDraft(offset: offset, service: service)
|
||||
if !loadedDraftIndices.contains(currentIndex), currentIndex != offset {
|
||||
try await fetchDraft(offset: currentIndex, service: service)
|
||||
}
|
||||
guard loadedDraftIndices.contains(currentIndex) else { throw TrainingError.invalidAnswers }
|
||||
}
|
||||
if let question = currentQuestion {
|
||||
let selected = Set(desiredAnswers[question.id]?.selectedOptionIDs ?? Array(answerCache[question.id] ?? []))
|
||||
guard selected.isSubset(of: Set(question.options.map(\.id))),
|
||||
question.type != .single || selected.count <= 1 else { throw TrainingError.invalidAnswers }
|
||||
}
|
||||
needsDraftRefresh = false
|
||||
}
|
||||
|
||||
private func fetchQuestions(offset: Int, paperID: String, service: any TrainingDataServing) async throws {
|
||||
let page = try await service.questions(paperID: paperID, taskID: taskID, offset: offset, limit: pageSize)
|
||||
try await authorize()
|
||||
let end = min(questionCount, offset + pageSize)
|
||||
guard page.paperSnapshotID == paperID, page.total == questionCount, page.offset == offset,
|
||||
!page.items.isEmpty, page.items.count <= end - offset,
|
||||
Set(page.items.map(\.order)).count == page.items.count,
|
||||
Set(page.items.map(\.id)).count == page.items.count else { throw TrainingError.invalidPaper }
|
||||
for question in page.items {
|
||||
guard (offset + 1...end).contains(question.order), !question.id.isEmpty,
|
||||
(2...6).contains(question.options.count), Set(question.options.map(\.id)).count == question.options.count,
|
||||
!questionCache.values.contains(where: { $0.id == question.id && $0.order != question.order }) else {
|
||||
throw TrainingError.invalidPaper
|
||||
}
|
||||
questionCache[question.order - 1] = question
|
||||
}
|
||||
}
|
||||
|
||||
private func fetchDraft(offset: Int, service: any TrainingDataServing) async throws {
|
||||
var page = try await service.draft(taskID: taskID, offset: offset, limit: pageSize)
|
||||
try await authorize()
|
||||
if page.draftRevision < draftRevision {
|
||||
page = try await service.draft(taskID: taskID, offset: offset, limit: pageSize)
|
||||
try await authorize()
|
||||
}
|
||||
guard page.draftRevision >= draftRevision else { throw TrainingError.invalidAnswers }
|
||||
try applyMetadata(page)
|
||||
let requestedEnd = min(questionCount, offset + pageSize)
|
||||
let coveredEnd = page.nextOffset ?? requestedEnd
|
||||
guard page.offset == offset, coveredEnd > offset, coveredEnd <= requestedEnd,
|
||||
Set(page.items.map(\.questionID)).count == page.items.count,
|
||||
Set(page.items.map(\.order)).count == page.items.count else { throw TrainingError.invalidAnswers }
|
||||
for index in offset..<coveredEnd {
|
||||
if let question = questionCache[index] { answerCache[question.id] = [] }
|
||||
}
|
||||
for answer in page.items {
|
||||
guard (offset + 1...coveredEnd).contains(answer.order), !answer.questionID.isEmpty,
|
||||
Set(answer.selectedOptionIDs).count == answer.selectedOptionIDs.count else { throw TrainingError.invalidAnswers }
|
||||
if let question = questionCache[answer.order - 1] {
|
||||
guard question.id == answer.questionID,
|
||||
Set(answer.selectedOptionIDs).isSubset(of: Set(question.options.map(\.id))),
|
||||
question.type != .single || answer.selectedOptionIDs.count <= 1 else { throw TrainingError.invalidAnswers }
|
||||
}
|
||||
answerCache[answer.questionID] = Set(answer.selectedOptionIDs)
|
||||
}
|
||||
loadedDraftIndices.formUnion(offset..<coveredEnd)
|
||||
}
|
||||
|
||||
private func refreshDraft(service: any TrainingDataServing) async throws {
|
||||
needsDraftRefresh = true
|
||||
let metadata = try await service.draft(taskID: taskID, offset: 0, limit: 0)
|
||||
try await authorize()
|
||||
answerCache = [:]
|
||||
loadedDraftIndices = []
|
||||
try applyMetadata(metadata)
|
||||
try await loadCurrentPage(service: service)
|
||||
}
|
||||
|
||||
private func finishDraftRead(service: any TrainingDataServing) {
|
||||
isReadingDraft = false
|
||||
let waiters = draftReadWaiters
|
||||
draftReadWaiters = []
|
||||
for waiter in waiters { waiter.resume() }
|
||||
if hasUnsavedChanges { scheduleSave(service: service) }
|
||||
}
|
||||
|
||||
private func notifyDraftState() {
|
||||
Task { @MainActor [weak self] in self?.onDraftSaveStateChange?() }
|
||||
}
|
||||
|
||||
private func queueDraft(service: any TrainingDataServing) {
|
||||
do { try persistDraft() }
|
||||
catch { reportSaveFailure(error) }
|
||||
notifyDraftState()
|
||||
scheduleSave(service: service)
|
||||
}
|
||||
|
||||
private func scheduleSave(service: any TrainingDataServing) {
|
||||
debounceTask?.cancel()
|
||||
guard saveFailure == nil, !hasDraftConflict, !recoveryStorageFailed, !isReadingDraft,
|
||||
identityIsValid, !shouldReturnToCenter, !hasPendingSubmission, submittedAttempt == nil else { return }
|
||||
let delay = debounceNanoseconds
|
||||
debounceTask = Task { @MainActor [weak self] in
|
||||
do { try await Task.sleep(nanoseconds: delay) }
|
||||
catch { return }
|
||||
guard !Task.isCancelled, let self, !self.isReadingDraft else { return }
|
||||
self.debounceTask = nil
|
||||
_ = await self.flushDraft(service: service)
|
||||
}
|
||||
}
|
||||
|
||||
private func restoreDraftIfNeeded() throws {
|
||||
guard let context, let paper else { throw TrainingError.invalidPaper }
|
||||
guard restoredPaperID != paper.id else { return }
|
||||
desiredAnswers = [:]
|
||||
desiredPosition = nil
|
||||
pendingMutation = nil
|
||||
draftGeneration = nil
|
||||
hasDraftConflict = false
|
||||
if let record = try draftStore.load(taskID: taskID, paperSnapshotID: paper.id, context: context) {
|
||||
draftGeneration = record.generation
|
||||
draftRevision = max(draftRevision, record.revision)
|
||||
desiredAnswers = Dictionary(uniqueKeysWithValues: record.answers.map { ($0.questionID, $0) })
|
||||
desiredPosition = record.lastQuestionOrder
|
||||
if let order = record.lastQuestionOrder, (1...questionCount).contains(order) { currentIndex = order - 1 }
|
||||
hasDraftConflict = record.hasConflict
|
||||
if let save = record.pendingSave { pendingMutation = .save(save) }
|
||||
if let reset = record.pendingReset {
|
||||
pendingMutation = .reset(reset)
|
||||
initialResetRequested = true
|
||||
}
|
||||
}
|
||||
restoredPaperID = paper.id
|
||||
try persistDraft()
|
||||
}
|
||||
|
||||
private func persistDraft() throws {
|
||||
guard let context, let paper, restoredPaperID == paper.id else { return }
|
||||
var record = TrainingDraftRecord(taskID: taskID, paperSnapshotID: paper.id, context: context,
|
||||
revision: max(1, draftRevision), answers: desiredAnswers.values.sorted { $0.order < $1.order },
|
||||
lastQuestionOrder: desiredPosition, hasConflict: hasDraftConflict)
|
||||
if case .save(let request)? = pendingMutation { record.pendingSave = request }
|
||||
if case .reset(let request)? = pendingMutation { record.pendingReset = request }
|
||||
draftGeneration = try draftStore.save(record, replacing: draftGeneration)
|
||||
}
|
||||
|
||||
private func reportSaveFailure(_ error: Error) {
|
||||
saveFailure = error.localizedDescription
|
||||
if error is TrainingDraftStorageError { recoveryStorageFailed = true }
|
||||
report(error)
|
||||
}
|
||||
|
||||
private func drainDraft(service: any TrainingDataServing) async -> Bool {
|
||||
isSaving = true
|
||||
notifyDraftState()
|
||||
defer { isSaving = false; writerTask = nil; notifyDraftState() }
|
||||
do {
|
||||
while hasUnsavedChanges {
|
||||
try await authorize()
|
||||
guard !hasDraftConflict, let paper else { return false }
|
||||
if pendingMutation == nil {
|
||||
// 一个任务只有一个 writer;发送后 payload 和幂等键不再被本机后续点击改写。
|
||||
let changes = desiredAnswers.values.sorted { $0.order < $1.order }.prefix(20).map {
|
||||
TrainingDraftChange(questionID: $0.questionID, selectedOptionIDs: $0.selectedOptionIDs)
|
||||
}
|
||||
pendingMutation = .save(TrainingDraftSaveRequest(requestID: UUID().uuidString,
|
||||
paperSnapshotID: paper.id, baseRevision: draftRevision,
|
||||
lastQuestionOrder: desiredPosition, changes: changes))
|
||||
}
|
||||
try persistDraft()
|
||||
guard let mutation = pendingMutation else { return true }
|
||||
do {
|
||||
let confirmation: TrainingDraftConfirmation
|
||||
switch mutation {
|
||||
case .save(let request): confirmation = try await service.saveDraft(taskID: taskID, request: request)
|
||||
case .reset(let request): confirmation = try await service.resetDraft(taskID: taskID, request: request)
|
||||
}
|
||||
try await authorize()
|
||||
let base: Int
|
||||
switch mutation { case .save(let value): base = value.baseRevision; case .reset(let value): base = value.baseRevision }
|
||||
guard confirmation.draftRevision >= base, (0...questionCount).contains(confirmation.answeredCount) else {
|
||||
throw TrainingError.invalidAnswers
|
||||
}
|
||||
let staleAcknowledgement = confirmation.draftRevision < draftRevision
|
||||
pendingMutation = nil
|
||||
if staleAcknowledgement, !desiredAnswers.isEmpty { hasDraftConflict = true }
|
||||
draftRevision = max(draftRevision, confirmation.draftRevision)
|
||||
switch mutation {
|
||||
case .save(let request):
|
||||
for change in request.changes {
|
||||
let sent = Set(change.selectedOptionIDs)
|
||||
answerCache[change.questionID] = sent
|
||||
if let answer = desiredAnswers[change.questionID] {
|
||||
if sent.isEmpty { confirmedAnsweredOrders.remove(answer.order) }
|
||||
else { confirmedAnsweredOrders.insert(answer.order) }
|
||||
// 迟到 ACK 只确认它发送的版本,不能覆盖期间产生的更新选择。
|
||||
if !staleAcknowledgement, answer.selectedOptionIDs == change.selectedOptionIDs {
|
||||
desiredAnswers.removeValue(forKey: change.questionID)
|
||||
}
|
||||
}
|
||||
}
|
||||
if desiredPosition == request.lastQuestionOrder { desiredPosition = nil }
|
||||
try persistDraft()
|
||||
if staleAcknowledgement || confirmedAnsweredOrders.count != confirmation.answeredCount {
|
||||
try await refreshDraft(service: service)
|
||||
}
|
||||
case .reset:
|
||||
currentIndex = 0
|
||||
desiredAnswers = [:]
|
||||
desiredPosition = nil
|
||||
try persistDraft()
|
||||
try await refreshDraft(service: service)
|
||||
}
|
||||
saveFailure = nil
|
||||
errorMessage = nil
|
||||
try persistDraft()
|
||||
notifyDraftState()
|
||||
} catch {
|
||||
if case TrainingRemoteError.draftRevisionConflict = error {
|
||||
// 明确拒绝才解除原请求;先取权威版本,保留全部本机意图并等待用户确认。
|
||||
pendingMutation = nil
|
||||
hasDraftConflict = true
|
||||
try persistDraft()
|
||||
do { try await refreshDraft(service: service); try persistDraft() }
|
||||
catch { reportSaveFailure(error) }
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
reportSaveFailure(error)
|
||||
notifyDraftState()
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
private func recoverSubmission(service: any TrainingDataServing) async throws -> TrainingAttemptSummary? {
|
||||
guard let pending = pendingSubmission else { return nil }
|
||||
let page = try await service.attempts(taskID: taskID, submissionID: pending.request.submissionID, cursor: nil, limit: 1)
|
||||
try await authorize()
|
||||
guard page.items.count <= 1 else { throw TrainingError.invalidAnswers }
|
||||
if let attempt = page.items.first {
|
||||
return try finishSubmission(pending, attempt: attempt, serverTime: page.serverTime ?? attempt.submittedAt)
|
||||
}
|
||||
return try await sendSubmission(pending, service: service)
|
||||
}
|
||||
|
||||
private func sendSubmission(_ pending: TrainingPendingSubmission, service: any TrainingDataServing) async throws -> TrainingAttemptSummary? {
|
||||
do {
|
||||
let result = try await service.submit(taskID: taskID, request: pending.request)
|
||||
try await authorize()
|
||||
draftRevision = max(draftRevision, result.draftRevision)
|
||||
let attempt = try finishSubmission(pending, attempt: result.attempt, serverTime: result.serverTime)
|
||||
submittedResult = TrainingAttemptDetail(attempt: result.attempt, taskState: result.taskState, serverTime: result.serverTime)
|
||||
return attempt
|
||||
} catch {
|
||||
if let remote = error as? TrainingRemoteError, remote.code != nil {
|
||||
switch remote {
|
||||
case .idempotencyConflict, .forbidden, .accountInvalid:
|
||||
// 权限拒绝无法证明原请求未成功,保留恢复键。
|
||||
break
|
||||
default:
|
||||
try await authorize()
|
||||
try pendingStore.remove(pending)
|
||||
pendingSubmission = nil
|
||||
needsDraftRefresh = true
|
||||
if let latest = try? await service.progress(taskID: taskID) {
|
||||
try await authorize()
|
||||
progress = latest
|
||||
if latest.canStartExam { try? await refreshDraft(service: service) }
|
||||
}
|
||||
}
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
private func finishSubmission(_ pending: TrainingPendingSubmission, attempt: TrainingAttemptSummary, serverTime: Date) throws -> TrainingAttemptSummary {
|
||||
guard attempt.taskID == taskID, attempt.paperSnapshotID == pending.request.paperSnapshotID else { throw TrainingError.invalidAnswers }
|
||||
try pendingStore.remove(pending)
|
||||
pendingSubmission = nil
|
||||
desiredAnswers = [:]
|
||||
desiredPosition = nil
|
||||
pendingMutation = nil
|
||||
hasDraftConflict = false
|
||||
try? persistDraft()
|
||||
submittedAttempt = attempt
|
||||
let state = TrainingTaskState(learnerStatus: attempt.passed ? .completed : .pendingExam,
|
||||
completedAt: attempt.passed ? attempt.submittedAt : nil, canRetry: false, blockReason: attempt.passed ? "completed" : nil)
|
||||
submittedResult = TrainingAttemptDetail(attempt: attempt, taskState: state, serverTime: serverTime)
|
||||
return attempt
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,248 @@
|
||||
import Foundation
|
||||
|
||||
/// 培训列表只保存摘要和服务端游标,不聚合课程、试卷或解析。
|
||||
final class TrainingRemoteCenterViewModel {
|
||||
/// 当前页面入口。
|
||||
var tab: TrainingCenterTab = .home
|
||||
/// 服务端任务状态筛选。
|
||||
var filter: TrainingLearnerStatus = .pendingExam
|
||||
/// 服务端同时搜索任务名和课程名。
|
||||
var keyword = ""
|
||||
/// 当前任务摘要页。
|
||||
private(set) var tasks: [TrainingTaskSummary] = []
|
||||
/// 当前成绩摘要页。
|
||||
private(set) var records: [TrainingAttemptSummary] = []
|
||||
/// 不受分页和关键词影响的概览。
|
||||
private(set) var summary: TrainingSummary?
|
||||
/// 首次加载或刷新状态。
|
||||
private(set) var isLoading = false
|
||||
/// 翻页状态,避免重复消费同一游标。
|
||||
private(set) var isLoadingMore = false
|
||||
/// 最近失败说明。
|
||||
private(set) var errorMessage: String?
|
||||
/// 是否仍有下一页。
|
||||
private(set) var hasMore = false
|
||||
/// 进入时的身份已失效,页面应关闭而不是展示旧作用域统计。
|
||||
private(set) var isIdentityInvalid = false
|
||||
private var nextCursor: String?
|
||||
private var generation = UUID()
|
||||
|
||||
/// 概览中的待完成数量。
|
||||
var pendingCount: Int { summary?.pendingCount ?? 0 }
|
||||
/// 概览中的已完成数量。
|
||||
var completedCount: Int { summary?.completedCount ?? 0 }
|
||||
/// 最近成绩只来自概览接口,不遍历历史。
|
||||
var latestScore: String { summary?.latestAttempt.map { TrainingScore.text($0.scoreHundredths) } ?? "—" }
|
||||
|
||||
/// 切换入口时保留筛选状态,清除搜索和旧游标。
|
||||
func selectTab(_ tab: TrainingCenterTab) {
|
||||
self.tab = tab
|
||||
keyword = ""
|
||||
generation = UUID()
|
||||
nextCursor = nil
|
||||
hasMore = false
|
||||
}
|
||||
|
||||
/// 搜索文本变化立即失效游标与旧请求,网络首屏可以稍后防抖执行。
|
||||
func setKeyword(_ value: String) {
|
||||
keyword = value
|
||||
generation = UUID()
|
||||
nextCursor = nil
|
||||
hasMore = false
|
||||
isLoading = false
|
||||
isLoadingMore = false
|
||||
}
|
||||
|
||||
/// 页面并行读取概览和当前摘要页,保留顶部统计而不遍历其他资源。
|
||||
func load(service: any TrainingDataServing) async {
|
||||
let requestID = UUID()
|
||||
generation = requestID
|
||||
isLoading = true
|
||||
isLoadingMore = false
|
||||
errorMessage = nil
|
||||
hasMore = false
|
||||
nextCursor = nil
|
||||
let requestedTab = tab
|
||||
let requestedFilter = filter
|
||||
let query = keyword.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
defer { if generation == requestID { isLoading = false } }
|
||||
do {
|
||||
async let overview = service.summary()
|
||||
switch requestedTab {
|
||||
case .home:
|
||||
async let page = service.tasks(status: .pendingExam, keyword: "", cursor: nil, limit: 3)
|
||||
let (loadedSummary, loadedPage) = try await (overview, page)
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
summary = loadedSummary
|
||||
tasks = loadedPage.items
|
||||
records = []
|
||||
case .tasks:
|
||||
let page = try await service.tasks(status: requestedFilter, keyword: query, cursor: nil, limit: 20)
|
||||
let loadedSummary = try await overview
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
summary = loadedSummary
|
||||
tasks = page.items
|
||||
records = []
|
||||
nextCursor = page.hasMore ? page.nextCursor : nil
|
||||
hasMore = nextCursor != nil
|
||||
case .records:
|
||||
let page = try await service.attempts(taskID: nil, submissionID: nil, cursor: nil, limit: 20)
|
||||
let loadedSummary = try await overview
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
summary = loadedSummary
|
||||
records = page.items
|
||||
tasks = []
|
||||
nextCursor = page.hasMore ? page.nextCursor : nil
|
||||
hasMore = nextCursor != nil
|
||||
}
|
||||
} catch {
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
tasks = []
|
||||
records = []
|
||||
summary = nil
|
||||
isIdentityInvalid = error as? TrainingRemoteError == .identityChanged
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// 用户主动加载下一页,不提前遍历全部任务或成绩。
|
||||
func loadMore(service: any TrainingDataServing) async {
|
||||
guard !isLoading, !isLoadingMore, let cursor = nextCursor, tab != .home else { return }
|
||||
isLoadingMore = true
|
||||
errorMessage = nil
|
||||
let requestID = generation
|
||||
defer { if generation == requestID { isLoadingMore = false } }
|
||||
do {
|
||||
if tab == .tasks {
|
||||
let page = try await service.tasks(status: filter, keyword: keyword.trimmingCharacters(in: .whitespacesAndNewlines), cursor: cursor, limit: 20)
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
let existing = Set(tasks.map(\.id))
|
||||
tasks += page.items.filter { !existing.contains($0.id) }
|
||||
nextCursor = page.hasMore && page.nextCursor != cursor ? page.nextCursor : nil
|
||||
} else {
|
||||
let page = try await service.attempts(taskID: nil, submissionID: nil, cursor: cursor, limit: 20)
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
let existing = Set(records.map(\.id))
|
||||
records += page.items.filter { !existing.contains($0.id) }
|
||||
nextCursor = page.hasMore && page.nextCursor != cursor ? page.nextCursor : nil
|
||||
}
|
||||
hasMore = nextCursor != nil
|
||||
} catch {
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
if error as? TrainingRemoteError == .identityChanged {
|
||||
tasks = []; records = []; summary = nil; nextCursor = nil; hasMore = false
|
||||
isIdentityInvalid = true
|
||||
}
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 成绩首屏只读单次摘要,解析由展开或翻页动作触发。
|
||||
final class TrainingRemoteResultViewModel {
|
||||
/// 服务端成绩主键。
|
||||
let attemptID: String
|
||||
/// 当前摘要与最新操作资格。
|
||||
private(set) var detail: TrainingAttemptDetail?
|
||||
/// 已按需读取的解析页。
|
||||
private(set) var reviews: [TrainingReviewItem] = []
|
||||
/// 摘要加载状态。
|
||||
private(set) var isLoading = false
|
||||
/// 解析分页状态。
|
||||
private(set) var isLoadingReviews = false
|
||||
/// 是否已成功加载解析首屏。
|
||||
private(set) var hasLoadedReviews = false
|
||||
/// 解析是否仍可继续翻页。
|
||||
private(set) var hasMoreReviews = false
|
||||
/// 摘要失败信息。
|
||||
private(set) var errorMessage: String?
|
||||
/// 解析失败信息,不替换已成功显示的成绩。
|
||||
private(set) var reviewErrorMessage: String?
|
||||
/// 登录身份变化后清空成绩与解析,页面应退出旧身份作用域。
|
||||
private(set) var isIdentityInvalid = false
|
||||
/// 非店铺账号或任务权限撤回时退出该次成绩。
|
||||
private(set) var isAccessRevoked = false
|
||||
private var reviewCursor: String?
|
||||
private var generation = UUID()
|
||||
|
||||
/// 通过成绩 ID 定位,不读取任务的所有历史。
|
||||
init(attemptID: String, initialDetail: TrainingAttemptDetail? = nil) {
|
||||
self.attemptID = attemptID
|
||||
self.detail = initialDetail
|
||||
}
|
||||
|
||||
/// 返回页面时更新操作资格,但保留已读取的冻结解析。
|
||||
func load(service: any TrainingDataServing) async {
|
||||
let requestID = UUID()
|
||||
generation = requestID
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
defer { if generation == requestID { isLoading = false } }
|
||||
do {
|
||||
let loaded = try await service.attempt(id: attemptID)
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
detail = loaded
|
||||
if !loaded.attempt.reviewAvailable {
|
||||
reviews = []
|
||||
hasLoadedReviews = false
|
||||
hasMoreReviews = false
|
||||
reviewCursor = nil
|
||||
reviewErrorMessage = nil
|
||||
}
|
||||
} catch {
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
detail = nil
|
||||
reviews = []
|
||||
hasLoadedReviews = false
|
||||
hasMoreReviews = false
|
||||
isIdentityInvalid = error as? TrainingRemoteError == .identityChanged
|
||||
isAccessRevoked = [150100, 150101].contains((error as? TrainingRemoteError)?.code ?? 0)
|
||||
errorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
|
||||
/// 初次展开只取第一页,再次展开复用已有解析。
|
||||
func loadReviews(service: any TrainingDataServing, nextPage: Bool = false) async {
|
||||
guard !isLoadingReviews, detail?.attempt.reviewAvailable == true else { return }
|
||||
if nextPage { guard hasMoreReviews, reviewCursor != nil else { return } }
|
||||
else if hasLoadedReviews { return }
|
||||
let cursor = nextPage ? reviewCursor : nil
|
||||
let requestID = generation
|
||||
isLoadingReviews = true
|
||||
reviewErrorMessage = nil
|
||||
defer { isLoadingReviews = false }
|
||||
do {
|
||||
let page = try await service.reviews(attemptID: attemptID, cursor: cursor, limit: 10)
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
let existing = Set(reviews.map(\.id))
|
||||
reviews += page.items.filter { !existing.contains($0.id) }
|
||||
hasLoadedReviews = true
|
||||
reviewCursor = page.hasMore && page.nextCursor != cursor ? page.nextCursor : nil
|
||||
hasMoreReviews = reviewCursor != nil
|
||||
} catch {
|
||||
guard generation == requestID, !Task.isCancelled else { return }
|
||||
isAccessRevoked = [150100, 150101].contains((error as? TrainingRemoteError)?.code ?? 0)
|
||||
if error as? TrainingRemoteError == .identityChanged || isAccessRevoked {
|
||||
detail = nil
|
||||
reviews = []
|
||||
hasLoadedReviews = false
|
||||
hasMoreReviews = false
|
||||
reviewCursor = nil
|
||||
isIdentityInvalid = error as? TrainingRemoteError == .identityChanged
|
||||
}
|
||||
reviewErrorMessage = error.localizedDescription
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 服务端百分之一分的整数使用最多两位小数展示。
|
||||
enum TrainingScore {
|
||||
/// 不自行判分,只格式化已确认的成绩。
|
||||
static func text(_ hundredths: Int) -> String {
|
||||
let whole = hundredths / 100
|
||||
let fraction = hundredths % 100
|
||||
guard fraction != 0 else { return String(whole) }
|
||||
let digits = String(format: "%02d", fraction)
|
||||
return "\(whole).\(fraction.isMultiple(of: 10) ? String(digits.prefix(1)) : digits)"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,500 @@
|
||||
import Foundation
|
||||
|
||||
/// 正式课程按需读取与有效前台读时;页面在操作完成后主动读取状态并刷新。
|
||||
final class TrainingRemoteReadingViewModel {
|
||||
/// 当前本人任务标识。
|
||||
let taskID: String
|
||||
/// 已加载的轻量任务规则与快照引用。
|
||||
private(set) var task: TrainingTaskDetail?
|
||||
/// 已加载的课程元信息,不包含全部正文。
|
||||
private(set) var course: TrainingCourseInfo?
|
||||
/// 用户已请求的附件元信息,不包含文件内容。
|
||||
private(set) var attachments: [TrainingAttachmentInfo] = []
|
||||
/// 当前选中文档,授权或预览失败时仍保留,供用户重试。
|
||||
private(set) var currentAttachment: TrainingAttachmentInfo?
|
||||
/// 当前文档经任务授权的访问地址,不附带 App Token。
|
||||
private(set) var currentAttachmentLink: TrainingAttachmentLink?
|
||||
/// 每次选择或重试生成新票据,拒绝同一个附件的旧下载或渲染回调。
|
||||
private(set) var attachmentPreviewID: UUID?
|
||||
/// 只有当前附件已成功渲染后才可累计有效阅读。
|
||||
private(set) var isAttachmentRendered = false
|
||||
/// 当前附件授权或预览错误,不被进度刷新清除。
|
||||
private(set) var attachmentErrorMessage: String?
|
||||
/// 仅用于附件分页的提示,不阻挡当前已经显示的文档或有效阅读。
|
||||
private(set) var attachmentListErrorMessage: String?
|
||||
/// 最新后端确认的学习进度与资格。
|
||||
private(set) var progress: TrainingProgressSnapshot?
|
||||
/// 首次加载或切换附件期间阻止重复内容操作。
|
||||
private(set) var isLoading = false
|
||||
/// 附件目录下一页正在加载。
|
||||
private(set) var isLoadingAttachments = false
|
||||
/// 附件链接正在授权。
|
||||
private(set) var isAuthorizingAttachment = false
|
||||
/// 附件目录是否还有用户可主动读取的页面。
|
||||
private(set) var hasMoreAttachments = false
|
||||
/// 已经读取过附件第一页,避免反复取相同元信息。
|
||||
private(set) var hasLoadedAttachments = false
|
||||
/// 是否正在累计本次会话的可见读时。
|
||||
private(set) var isReading = false
|
||||
/// 当前会话本地累计秒数;新会话始终从零开始。
|
||||
private(set) var activeSecondsTotal = 0
|
||||
/// 最近一次阅读保存失败,可用原请求安全重试。
|
||||
private(set) var readingErrorMessage: String?
|
||||
/// 会话恢复提示,与当前操作资格分开展示。
|
||||
private(set) var readingNotice: String?
|
||||
/// 身份已经切换,所有迟到结果都应被丢弃。
|
||||
private(set) var isInvalidated = false
|
||||
|
||||
private let service: any TrainingDataServing
|
||||
private let validateIdentity: @MainActor @Sendable () -> Bool
|
||||
private let now: @Sendable () -> Date
|
||||
private var generation = 0
|
||||
private var attachmentCursor: String?
|
||||
private var contentErrorMessage: String?
|
||||
private var session: TrainingStudySession?
|
||||
private var sessionRequestID: String?
|
||||
private var acceptedActiveSecondsTotal = 0
|
||||
private var nextSequence = 1
|
||||
private var pendingHeartbeat: PendingHeartbeat?
|
||||
private var finalRequested = false
|
||||
private var wantsReading = false
|
||||
private var isSessionBusy = false
|
||||
private var sessionWaiters: [CheckedContinuation<Void, Never>] = []
|
||||
private var readingClock = TrainingReadingClock()
|
||||
private var lastVisibleUptime: TimeInterval = 0
|
||||
|
||||
/// 一次冻结的幂等心跳;重试时序号、累计秒数与 final 均不能变更。
|
||||
private struct PendingHeartbeat {
|
||||
let sessionID: String
|
||||
let sequence: Int
|
||||
let activeSecondsTotal: Int
|
||||
let final: Bool
|
||||
}
|
||||
|
||||
/// 注入正式数据源、身份校验与时钟,不让 ViewModel 依赖 UIKit 或共享登录视图。
|
||||
init(
|
||||
taskID: String,
|
||||
service: any TrainingDataServing,
|
||||
now: @escaping @Sendable () -> Date = { Date() },
|
||||
validateIdentity: @escaping @MainActor @Sendable () -> Bool = { true }
|
||||
) {
|
||||
self.taskID = taskID
|
||||
self.service = service
|
||||
self.now = now
|
||||
self.validateIdentity = validateIdentity
|
||||
}
|
||||
|
||||
/// 页面展示的内容或保存错误,不用中文文案判断恢复分支。
|
||||
var errorMessage: String? { readingErrorMessage ?? attachmentErrorMessage ?? contentErrorMessage }
|
||||
|
||||
/// 当前附件标识,预览失败时用于重试同一份文档。
|
||||
var currentAttachmentID: String? { currentAttachment?.id }
|
||||
|
||||
/// 显示未确认读时的倒计时,但只有服务器确认后才允许开始考试。
|
||||
var remainingSeconds: Int {
|
||||
guard let progress else { return task?.requiredReadingSeconds ?? 0 }
|
||||
let unconfirmed = max(0, activeSecondsTotal - acceptedActiveSecondsTotal)
|
||||
return max(0, progress.requiredReadingSeconds - progress.readingSeconds - unconfirmed)
|
||||
}
|
||||
|
||||
/// 当前后端是否允许继续有效学习,完成或只读任务不建立新会话。
|
||||
var canStudy: Bool {
|
||||
task?.summary.learnerStatus == .pendingExam && progress?.learnerStatus == .pendingExam
|
||||
&& progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated
|
||||
}
|
||||
|
||||
/// 上一次请求结束后才允许发送下一次心跳;保存失败交由用户重试。
|
||||
var needsReadingFlush: Bool {
|
||||
guard !isInvalidated, !isSessionBusy, readingErrorMessage == nil, let session else { return false }
|
||||
return finalRequested || activeSecondsTotal - acceptedActiveSecondsTotal >= max(1, session.heartbeatIntervalSeconds)
|
||||
}
|
||||
|
||||
/// 首次只读课程元信息、附件第一页与进度,并为首个附件授权;不请求小节标题或 HTML。
|
||||
func load() async {
|
||||
guard !isLoading, !isInvalidated else { return }
|
||||
let epoch = generation
|
||||
isLoading = true
|
||||
contentErrorMessage = nil
|
||||
attachmentErrorMessage = nil
|
||||
attachmentListErrorMessage = nil
|
||||
resetAttachmentPreview()
|
||||
pauseReading()
|
||||
defer { if generation == epoch { isLoading = false } }
|
||||
await flush(final: true)
|
||||
guard generation == epoch, !isInvalidated, !Task.isCancelled else { return }
|
||||
do {
|
||||
let detail = try await service.task(id: taskID)
|
||||
try await checkIdentity(epoch)
|
||||
guard detail.summary.learning.canViewCourse else {
|
||||
throw TrainingRemoteError.forbidden("当前任务不能查看课程")
|
||||
}
|
||||
let courseID = detail.summary.courseSnapshotID
|
||||
async let metadata = service.course(id: courseID, taskID: taskID)
|
||||
async let documents = service.attachments(courseID: courseID, taskID: taskID, cursor: nil, limit: 20)
|
||||
async let savedProgress = service.progress(taskID: taskID)
|
||||
let (info, page, saved) = try await (metadata, documents, savedProgress)
|
||||
try await checkIdentity(epoch)
|
||||
guard saved.canViewCourse else { throw TrainingRemoteError.forbidden("当前任务不能查看课程") }
|
||||
task = detail
|
||||
course = info
|
||||
attachments = page.items
|
||||
attachmentCursor = page.nextCursor
|
||||
hasMoreAttachments = page.hasMore
|
||||
hasLoadedAttachments = true
|
||||
progress = saved
|
||||
if let first = attachments.first {
|
||||
await prepareAttachment(first, epoch: epoch)
|
||||
}
|
||||
} catch { saveContentError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 返回已缓存课程时只刷新本人资格与进度,保留文档和预览错误。
|
||||
func refreshProgress() async {
|
||||
let epoch = generation
|
||||
guard !isInvalidated else { return }
|
||||
do {
|
||||
let value = try await service.progress(taskID: taskID)
|
||||
try await checkIdentity(epoch)
|
||||
guard value.canViewCourse else { throw TrainingRemoteError.forbidden("当前任务不能查看课程") }
|
||||
progress = value
|
||||
if !value.canStudy || value.readingCompleted { pauseReading() }
|
||||
contentErrorMessage = nil
|
||||
} catch { saveContentError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 选择或重试附件时先关闭旧读时片段,再为选中的文档重新授权。
|
||||
func selectAttachment(id: String) async {
|
||||
guard !isLoading, !isInvalidated,
|
||||
let attachment = attachments.first(where: { $0.id == id }) else { return }
|
||||
let epoch = generation
|
||||
isLoading = true
|
||||
defer { if generation == epoch { isLoading = false } }
|
||||
resetAttachmentPreview()
|
||||
pauseReading()
|
||||
await flush(final: true)
|
||||
guard generation == epoch, !isInvalidated, !Task.isCancelled else { return }
|
||||
contentErrorMessage = nil
|
||||
await prepareAttachment(attachment, epoch: epoch)
|
||||
}
|
||||
|
||||
/// 当前文档真正展示完成才打开读时门禁;过期页面或旧下载回调不能恢复学习。
|
||||
@discardableResult
|
||||
func markAttachmentRendered(id: String, previewID: UUID) -> Bool {
|
||||
guard !isInvalidated, !isLoading, currentAttachmentID == id,
|
||||
attachmentPreviewID == previewID, currentAttachmentLink != nil,
|
||||
attachmentErrorMessage == nil else { return false }
|
||||
isAttachmentRendered = true
|
||||
return true
|
||||
}
|
||||
|
||||
/// 文档下载或渲染失败立即停止累计,页面随后通过已有保存管线关闭会话。
|
||||
func reportAttachmentFailure(id: String, previewID: UUID, message: String) {
|
||||
guard !isInvalidated, currentAttachmentID == id, attachmentPreviewID == previewID else { return }
|
||||
isAttachmentRendered = false
|
||||
attachmentErrorMessage = message
|
||||
pauseReading()
|
||||
}
|
||||
|
||||
/// 后续附件页仅由用户主动读取;已有第一页不重复获取。
|
||||
func loadAttachments(loadMore: Bool = false) async {
|
||||
guard !isLoading, !isLoadingAttachments, let course, !isInvalidated else { return }
|
||||
if hasLoadedAttachments && !loadMore { return }
|
||||
if loadMore && (!hasMoreAttachments || attachmentCursor == nil) { return }
|
||||
let epoch = generation
|
||||
isLoadingAttachments = true
|
||||
defer { if generation == epoch { isLoadingAttachments = false } }
|
||||
do {
|
||||
let page = try await service.attachments(courseID: course.id, taskID: taskID, cursor: loadMore ? attachmentCursor : nil, limit: 20)
|
||||
try await checkIdentity(epoch)
|
||||
let existing = Set(attachments.map(\.id))
|
||||
if !loadMore { attachments = page.items }
|
||||
else { attachments.append(contentsOf: page.items.filter { !existing.contains($0.id) }) }
|
||||
attachmentCursor = page.nextCursor
|
||||
hasMoreAttachments = page.hasMore
|
||||
hasLoadedAttachments = true
|
||||
attachmentListErrorMessage = nil
|
||||
} catch { saveAttachmentListError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 获取同一附件的有效 HTTP/HTTPS 授权地址,保持签名参数原样,不附 App Token。
|
||||
func authorizeAttachment(id: String) async -> TrainingAttachmentLink? {
|
||||
guard !isAuthorizingAttachment, let course, !isInvalidated else { return nil }
|
||||
let epoch = generation
|
||||
isAuthorizingAttachment = true
|
||||
defer { if generation == epoch { isAuthorizingAttachment = false } }
|
||||
do {
|
||||
let link = try await service.attachmentURL(courseID: course.id, attachmentID: id, taskID: taskID)
|
||||
try await checkIdentity(epoch)
|
||||
let scheme = link.url.scheme?.lowercased()
|
||||
guard link.id == id, scheme == "http" || scheme == "https", link.url.host?.isEmpty == false,
|
||||
link.url.user == nil, link.url.password == nil, link.expiresAt > now() else {
|
||||
throw TrainingRemoteError.paramInvalid("附件访问地址无效或已过期,请重试")
|
||||
}
|
||||
attachmentErrorMessage = nil
|
||||
return link
|
||||
} catch { saveAttachmentError(error, epoch: epoch); return nil }
|
||||
}
|
||||
|
||||
private func prepareAttachment(_ attachment: TrainingAttachmentInfo, epoch: Int) async {
|
||||
currentAttachment = attachment
|
||||
attachmentErrorMessage = nil
|
||||
let previewID = UUID()
|
||||
attachmentPreviewID = previewID
|
||||
let link = await authorizeAttachment(id: attachment.id)
|
||||
guard generation == epoch, !isInvalidated, !Task.isCancelled,
|
||||
attachmentPreviewID == previewID, currentAttachmentID == attachment.id else { return }
|
||||
currentAttachmentLink = link
|
||||
}
|
||||
|
||||
private func resetAttachmentPreview() {
|
||||
currentAttachment = nil
|
||||
currentAttachmentLink = nil
|
||||
attachmentPreviewID = nil
|
||||
isAttachmentRendered = false
|
||||
attachmentErrorMessage = nil
|
||||
}
|
||||
|
||||
/// 附件已渲染且前台可见时建立或恢复会话;正在阅读时重复调用不重启计时。
|
||||
func startReading(at uptime: TimeInterval) async {
|
||||
guard isAttachmentRendered, currentAttachmentLink != nil, canStudy else { return }
|
||||
lastVisibleUptime = uptime
|
||||
guard !isReading else { return }
|
||||
let epoch = generation
|
||||
wantsReading = true
|
||||
await waitForSessionOperation(epoch: epoch)
|
||||
guard generation == epoch, !isInvalidated, wantsReading, canStudy, isAttachmentRendered, !isReading else { return }
|
||||
isSessionBusy = true
|
||||
defer { finishSessionOperation(epoch: epoch) }
|
||||
do {
|
||||
try await checkIdentity(epoch)
|
||||
if pendingHeartbeat != nil || finalRequested {
|
||||
try await sendHeartbeats(epoch: epoch)
|
||||
}
|
||||
if session == nil && canStudy { try await createSession(epoch: epoch) }
|
||||
if wantsReading, session != nil, canStudy, isAttachmentRendered {
|
||||
readingErrorMessage = nil
|
||||
readingClock.resume(at: uptime)
|
||||
isReading = true
|
||||
} else if session != nil { try await sendHeartbeats(epoch: epoch) }
|
||||
} catch { await handleReadingError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 前台可见时每次最多记一秒;网络心跳进行中仍累计,到门槛时同步停止。
|
||||
@discardableResult
|
||||
func accumulateVisibleTime(at uptime: TimeInterval) -> Bool {
|
||||
lastVisibleUptime = uptime
|
||||
guard session != nil, isReading, wantsReading, canStudy, isAttachmentRendered, readingErrorMessage == nil,
|
||||
readingClock.takeSecond(at: uptime) else { return false }
|
||||
activeSecondsTotal += 1
|
||||
if remainingSeconds == 0 { pauseReading() }
|
||||
return true
|
||||
}
|
||||
|
||||
/// 累计可见读时并等待本次保存;持续刷新的页面可分别调用累计与保存方法。
|
||||
func recordVisibleTime(at uptime: TimeInterval) async {
|
||||
accumulateVisibleTime(at: uptime)
|
||||
if needsReadingFlush { await flush() }
|
||||
}
|
||||
|
||||
/// 页面隐藏、锁屏、文档切换或预览失败时同步停止计时,丢弃未满一秒片段。
|
||||
func pauseReading() {
|
||||
wantsReading = false
|
||||
finalRequested = true
|
||||
isReading = false
|
||||
readingClock.pause()
|
||||
}
|
||||
|
||||
/// 保存已累计片段;先重试冻结的旧请求,再用新序号发送最终关闭请求。
|
||||
func flush(final: Bool = false) async {
|
||||
if final { pauseReading() }
|
||||
let epoch = generation
|
||||
await waitForSessionOperation(epoch: epoch)
|
||||
guard generation == epoch, !isInvalidated, session != nil else { return }
|
||||
isSessionBusy = true
|
||||
defer { finishSessionOperation(epoch: epoch) }
|
||||
do {
|
||||
try await checkIdentity(epoch)
|
||||
try await sendHeartbeats(epoch: epoch)
|
||||
readingErrorMessage = nil
|
||||
} catch { await handleReadingError(error, epoch: epoch) }
|
||||
}
|
||||
|
||||
/// 身份切换使所有异步操作失效,清理旧账号内容和未确认片段。
|
||||
func invalidate() {
|
||||
generation += 1
|
||||
isInvalidated = true
|
||||
pauseReading()
|
||||
clearSession()
|
||||
task = nil
|
||||
course = nil
|
||||
attachments = []
|
||||
resetAttachmentPreview()
|
||||
attachmentListErrorMessage = nil
|
||||
progress = nil
|
||||
contentErrorMessage = nil
|
||||
readingErrorMessage = nil
|
||||
readingNotice = nil
|
||||
attachmentCursor = nil
|
||||
hasMoreAttachments = false
|
||||
hasLoadedAttachments = false
|
||||
isLoading = false
|
||||
isLoadingAttachments = false
|
||||
isAuthorizingAttachment = false
|
||||
isSessionBusy = false
|
||||
resumeSessionWaiters()
|
||||
}
|
||||
|
||||
private func createSession(epoch: Int) async throws {
|
||||
let requestID = sessionRequestID ?? UUID().uuidString
|
||||
sessionRequestID = requestID
|
||||
let value = try await service.startReading(taskID: taskID, requestID: requestID)
|
||||
try await checkIdentity(epoch)
|
||||
session = value
|
||||
progress = value.progress
|
||||
activeSecondsTotal = 0
|
||||
acceptedActiveSecondsTotal = 0
|
||||
nextSequence = 1
|
||||
finalRequested = !wantsReading || !canStudy
|
||||
}
|
||||
|
||||
private func sendHeartbeats(epoch: Int) async throws {
|
||||
while let session {
|
||||
if pendingHeartbeat == nil {
|
||||
guard finalRequested || activeSecondsTotal > acceptedActiveSecondsTotal else { return }
|
||||
pendingHeartbeat = PendingHeartbeat(sessionID: session.sessionID, sequence: nextSequence,
|
||||
activeSecondsTotal: activeSecondsTotal, final: finalRequested)
|
||||
}
|
||||
guard let pending = pendingHeartbeat else { return }
|
||||
let response = try await service.heartbeat(sessionID: pending.sessionID, sequence: pending.sequence,
|
||||
activeSecondsTotal: pending.activeSecondsTotal, final: pending.final)
|
||||
try await checkIdentity(epoch)
|
||||
guard response.sessionID == pending.sessionID, response.acceptedSequence == pending.sequence,
|
||||
response.acceptedActiveSecondsTotal >= acceptedActiveSecondsTotal,
|
||||
response.acceptedActiveSecondsTotal <= pending.activeSecondsTotal else {
|
||||
throw TrainingRemoteError.sessionConflict("学习上报确认与请求不一致")
|
||||
}
|
||||
progress = response.progress
|
||||
acceptedActiveSecondsTotal = response.acceptedActiveSecondsTotal
|
||||
nextSequence = pending.sequence + 1
|
||||
pendingHeartbeat = nil
|
||||
if response.sessionClosed || pending.final {
|
||||
clearSession()
|
||||
return
|
||||
}
|
||||
if response.progress.readingCompleted || !response.progress.canStudy { pauseReading() }
|
||||
if !finalRequested { return }
|
||||
}
|
||||
}
|
||||
|
||||
private func clearSession() {
|
||||
session = nil
|
||||
sessionRequestID = nil
|
||||
pendingHeartbeat = nil
|
||||
activeSecondsTotal = 0
|
||||
acceptedActiveSecondsTotal = 0
|
||||
nextSequence = 1
|
||||
finalRequested = false
|
||||
isReading = false
|
||||
readingClock.pause()
|
||||
}
|
||||
|
||||
private func waitForSessionOperation(epoch: Int) async {
|
||||
while isSessionBusy, generation == epoch, !isInvalidated {
|
||||
await withCheckedContinuation { sessionWaiters.append($0) }
|
||||
}
|
||||
}
|
||||
|
||||
private func finishSessionOperation(epoch: Int) {
|
||||
guard generation == epoch else { return }
|
||||
isSessionBusy = false
|
||||
resumeSessionWaiters()
|
||||
}
|
||||
|
||||
private func resumeSessionWaiters() {
|
||||
let waiters = sessionWaiters
|
||||
sessionWaiters = []
|
||||
waiters.forEach { $0.resume() }
|
||||
}
|
||||
|
||||
private func checkIdentity(_ epoch: Int) async throws {
|
||||
guard generation == epoch, !isInvalidated, !Task.isCancelled else { throw CancellationError() }
|
||||
guard await validateIdentity() else {
|
||||
invalidate()
|
||||
throw TrainingRemoteError.identityChanged
|
||||
}
|
||||
}
|
||||
|
||||
private func saveContentError(_ error: Error, epoch: Int) {
|
||||
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
|
||||
let mapped = TrainingRemoteError.map(error)
|
||||
let code = (mapped as? TrainingRemoteError)?.code
|
||||
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 {
|
||||
invalidate()
|
||||
return
|
||||
}
|
||||
contentErrorMessage = mapped.localizedDescription
|
||||
}
|
||||
|
||||
private func saveAttachmentError(_ error: Error, epoch: Int) {
|
||||
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
|
||||
let mapped = TrainingRemoteError.map(error)
|
||||
let code = (mapped as? TrainingRemoteError)?.code
|
||||
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 {
|
||||
invalidate()
|
||||
return
|
||||
}
|
||||
attachmentErrorMessage = mapped.localizedDescription
|
||||
}
|
||||
|
||||
private func saveAttachmentListError(_ error: Error, epoch: Int) {
|
||||
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
|
||||
let mapped = TrainingRemoteError.map(error)
|
||||
let code = (mapped as? TrainingRemoteError)?.code
|
||||
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 {
|
||||
invalidate()
|
||||
return
|
||||
}
|
||||
attachmentListErrorMessage = mapped.localizedDescription
|
||||
}
|
||||
|
||||
private func handleReadingError(_ error: Error, epoch: Int) async {
|
||||
guard generation == epoch, !isInvalidated, !(error is CancellationError) else { return }
|
||||
let mapped = TrainingRemoteError.map(error)
|
||||
let code = (mapped as? TrainingRemoteError)?.code
|
||||
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 {
|
||||
invalidate()
|
||||
return
|
||||
}
|
||||
isReading = false
|
||||
readingClock.pause()
|
||||
readingErrorMessage = mapped.localizedDescription
|
||||
guard code == 150104 || code == 150105 || code == 150102 else { return }
|
||||
do {
|
||||
let saved = try await service.progress(taskID: taskID)
|
||||
try await checkIdentity(epoch)
|
||||
let shouldResume = wantsReading && isAttachmentRendered && code != 150102
|
||||
clearSession()
|
||||
progress = saved
|
||||
wantsReading = shouldResume
|
||||
if code == 150104 || code == 150105 {
|
||||
readingErrorMessage = nil
|
||||
readingNotice = "学习会话已恢复,继续阅读即可"
|
||||
}
|
||||
if shouldResume, canStudy {
|
||||
try await createSession(epoch: epoch)
|
||||
if wantsReading, canStudy, isAttachmentRendered {
|
||||
readingClock.resume(at: lastVisibleUptime)
|
||||
isReading = true
|
||||
readingErrorMessage = nil
|
||||
readingNotice = "学习会话已恢复,继续阅读即可"
|
||||
} else if session != nil { try await sendHeartbeats(epoch: epoch) }
|
||||
}
|
||||
} catch {
|
||||
guard generation == epoch, !isInvalidated else { return }
|
||||
let mapped = TrainingRemoteError.map(error)
|
||||
let code = (mapped as? TrainingRemoteError)?.code
|
||||
if mapped as? TrainingRemoteError == .identityChanged || code == 150100 || code == 150101 { invalidate() }
|
||||
else { readingErrorMessage = mapped.localizedDescription }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import Foundation
|
||||
|
||||
/// 培训中心与小程序一致的三个入口。
|
||||
enum TrainingCenterTab: Int, CaseIterable {
|
||||
case home, tasks, records
|
||||
|
||||
/// 培训中心底部入口的展示名称。
|
||||
var title: String { switch self { case .home: "首页"; case .tasks: "任务"; case .records: "记录" } }
|
||||
}
|
||||
|
||||
/// 培训中心任务与历史记录状态,页面在加载完成后主动刷新。
|
||||
final class TrainingCenterViewModel {
|
||||
/// 最近成功加载的本人任务,加载失败时清空。
|
||||
private(set) var tasks: [TrainingTask] = []
|
||||
/// 正在加载任务时阻止重复请求。
|
||||
private(set) var isLoading = false
|
||||
/// 最近一次加载失败的页面提示。
|
||||
private(set) var errorMessage: String?
|
||||
/// 任务列表当前选择的学员完成状态。
|
||||
var filter: TrainingLearnerStatus = .pendingExam
|
||||
/// 当前培训中心入口,决定页面展示的数据范围。
|
||||
var tab: TrainingCenterTab = .home
|
||||
/// 按任务或课程名称筛选任务的搜索词。
|
||||
var keyword = ""
|
||||
/// 记录页当前展示的记录数量上限,由页面增加以加载更多。
|
||||
var recordLimit = 20
|
||||
|
||||
/// 本人全部任务中已完成的数量,不受搜索与筛选影响。
|
||||
var completedCount: Int { tasks.filter { $0.learnerStatus == .completed }.count }
|
||||
/// 本人全部任务中尚未完成的数量。
|
||||
var pendingCount: Int { tasks.count - completedCount }
|
||||
/// 合并各任务的考试记录,按提交时间从新到旧排列。
|
||||
var records: [(task: TrainingTask, attempt: TrainingAttempt)] {
|
||||
tasks.flatMap { task in task.progress.attempts.map { (task: task, attempt: $0) } }
|
||||
.sorted { $0.attempt.submittedAt > $1.attempt.submittedAt }
|
||||
}
|
||||
/// 最近一次考试的得分,无考试记录时显示占位符。
|
||||
var latestScore: String { records.first?.attempt.scoreText ?? "—" }
|
||||
|
||||
/// 当前筛选的任务列表。
|
||||
var filteredTasks: [TrainingTask] {
|
||||
let query = keyword.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return tasks.filter { $0.learnerStatus == filter && (query.isEmpty || $0.title.localizedCaseInsensitiveContains(query) || $0.course.title.localizedCaseInsensitiveContains(query)) }
|
||||
}
|
||||
|
||||
/// 首页展示前三项必读任务,任务页提供完整筛选与搜索。
|
||||
var visibleTasks: [TrainingTask] {
|
||||
tab == .home ? Array(tasks.filter { $0.learnerStatus == .pendingExam }.prefix(3)) : filteredTasks
|
||||
}
|
||||
|
||||
/// 切换入口时清除搜索,保留用户选择的任务状态。
|
||||
func selectTab(_ tab: TrainingCenterTab) { self.tab = tab; keyword = "" }
|
||||
|
||||
/// 加载失败时清除旧任务,防止切换身份后展示旧账号内容。
|
||||
func load(service: any TrainingServing) async {
|
||||
guard !isLoading else { return }
|
||||
isLoading = true
|
||||
errorMessage = nil
|
||||
defer { isLoading = false }
|
||||
do { tasks = try await service.listTasks() }
|
||||
catch { tasks = []; errorMessage = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
/// 连续课程阅读状态;计时只由前台可见页面驱动。
|
||||
final class TrainingReadingViewModel {
|
||||
/// 当前阅读页面对应的本人任务标识。
|
||||
let taskID: String
|
||||
/// 最近一次成功读取或保存的课程与学习进度。
|
||||
private(set) var task: TrainingTask?
|
||||
/// 加载课程或保存阅读秒数时阻止重复操作。
|
||||
private(set) var isBusy = false
|
||||
/// 最近一次加载或保存失败的页面提示。
|
||||
private(set) var errorMessage: String?
|
||||
|
||||
/// 指定当前本人任务。
|
||||
init(taskID: String) { self.taskID = taskID }
|
||||
|
||||
/// 剩余有效阅读秒数。
|
||||
var remainingSeconds: Int { max(0, TrainingTask.requiredReadingSeconds - (task?.progress.readingSeconds ?? 0)) }
|
||||
|
||||
/// 读取最新进度,不重置已经完成的课程。
|
||||
func load(service: any TrainingServing) async {
|
||||
guard !isBusy else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do { task = try await service.task(id: taskID) }
|
||||
catch { task = nil; errorMessage = error.localizedDescription }
|
||||
}
|
||||
|
||||
/// 每次只记一秒;失败保留上一次成功进度,并停止页面计时。
|
||||
func recordSecond(service: any TrainingServing) async {
|
||||
guard !isBusy, let task, !task.hasFinishedReading, task.learnerStatus != .completed else { return }
|
||||
isBusy = true
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
self.task = try await service.recordReadingSecond(taskID: taskID)
|
||||
errorMessage = nil
|
||||
} catch { errorMessage = error.localizedDescription }
|
||||
}
|
||||
}
|
||||
|
||||
/// 逐题答题、答题卡、自动草稿保存与幂等交卷状态。
|
||||
final class TrainingExamViewModel {
|
||||
/// 当前考试页面对应的本人任务标识。
|
||||
let taskID: String
|
||||
/// 已通过时间、阅读门槛和试卷校验的考试任务。
|
||||
private(set) var task: TrainingTask?
|
||||
/// 已成功保存的草稿选择,保存失败时保留原值。
|
||||
private(set) var answers: TrainingAnswers = [:]
|
||||
/// 当前展示题目在试卷中的索引。
|
||||
private(set) var currentIndex = 0
|
||||
/// 加载、保存草稿或交卷期间阻止重复操作和题目跳转。
|
||||
private(set) var isBusy = false
|
||||
/// 最近一次加载、保存或交卷失败的页面提示。
|
||||
private(set) var errorMessage: String?
|
||||
private var submissionID: String?
|
||||
|
||||
/// 指定任务,默认恢复草稿;重考从空白试卷开始。
|
||||
init(taskID: String) { self.taskID = taskID }
|
||||
|
||||
/// 当前题目,无效试卷时为空。
|
||||
var currentQuestion: TrainingQuestion? {
|
||||
guard let task, task.questions.indices.contains(currentIndex) else { return nil }
|
||||
return task.questions[currentIndex]
|
||||
}
|
||||
|
||||
/// 第一处漏答位置,用于交卷时定位。
|
||||
var firstUnansweredIndex: Int? {
|
||||
task?.questions.firstIndex { (answers[$0.id] ?? []).isEmpty }
|
||||
}
|
||||
|
||||
/// 当前作答数量。
|
||||
var answeredCount: Int { task?.questions.filter { !(answers[$0.id] ?? []).isEmpty }.count ?? 0 }
|
||||
|
||||
/// 进入考试时重新验证任务时间与学习完成状态。
|
||||
func load(service: any TrainingServing, now: Date = Date(), resetDraft: Bool = false) async {
|
||||
guard !isBusy else { return }
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
let loaded = try await service.task(id: taskID)
|
||||
if let reason = loaded.submissionBlockReason(now: now) { throw TrainingError.blocked(reason) }
|
||||
guard loaded.mode == .exam else { throw TrainingError.invalidPaper }
|
||||
guard loaded.hasFinishedReading else { throw TrainingError.readingRequired }
|
||||
let draft = resetDraft ? [:] : loaded.progress.draftAnswers
|
||||
try TrainingValidation.validateAnswers(draft, task: loaded, requireComplete: false)
|
||||
if resetDraft { try await service.saveDraft(taskID: taskID, answers: [:]) }
|
||||
task = loaded
|
||||
answers = draft
|
||||
currentIndex = min(currentIndex, loaded.questions.count - 1)
|
||||
} catch { task = nil; errorMessage = error.localizedDescription }
|
||||
}
|
||||
|
||||
/// 选择有效选项,保存成功后再更新页面,失败允许重试。
|
||||
func select(optionID: String, service: any TrainingServing) async {
|
||||
guard !isBusy, let question = currentQuestion,
|
||||
question.options.contains(where: { $0.id == optionID }) else { return }
|
||||
var changed = answers
|
||||
var selected = changed[question.id] ?? []
|
||||
if question.type == .single { selected = [optionID] }
|
||||
else if selected.contains(optionID) { selected.remove(optionID) }
|
||||
else { selected.insert(optionID) }
|
||||
changed[question.id] = selected
|
||||
isBusy = true
|
||||
defer { isBusy = false }
|
||||
do {
|
||||
try await service.saveDraft(taskID: taskID, answers: changed)
|
||||
answers = changed
|
||||
submissionID = nil
|
||||
errorMessage = nil
|
||||
} catch { errorMessage = error.localizedDescription }
|
||||
}
|
||||
|
||||
/// 上一题、下一题和答题卡使用同一个安全跳转方法。
|
||||
func goToQuestion(_ index: Int) {
|
||||
guard !isBusy, let task, task.questions.indices.contains(index) else { return }
|
||||
currentIndex = index
|
||||
}
|
||||
|
||||
/// 交卷失败重试沿用同一 submissionID,避免新增重复考试记录。
|
||||
func submit(service: any TrainingServing) async -> TrainingAttempt? {
|
||||
guard !isBusy, let task else { return nil }
|
||||
if let missing = firstUnansweredIndex {
|
||||
currentIndex = missing
|
||||
errorMessage = TrainingError.unanswered(task.questions.count - answeredCount).localizedDescription
|
||||
return nil
|
||||
}
|
||||
isBusy = true
|
||||
errorMessage = nil
|
||||
defer { isBusy = false }
|
||||
let id = submissionID ?? UUID().uuidString
|
||||
submissionID = id
|
||||
do { return try await service.submit(taskID: taskID, answers: answers, submissionID: id) }
|
||||
catch { errorMessage = error.localizedDescription; return nil }
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,17 @@
|
||||
<string>qqmap</string>
|
||||
<string>comgooglemaps</string>
|
||||
</array>
|
||||
<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>UIApplicationSceneManifest</key>
|
||||
<dict>
|
||||
<key>UIApplicationSupportsMultipleScenes</key>
|
||||
|
||||
@@ -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.
|
||||
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
|
||||
# isarray
|
||||
|
||||
`Array#isArray` for older browsers.
|
||||
|
||||
[](http://travis-ci.org/juliangruber/isarray)
|
||||
[](https://www.npmjs.org/package/isarray)
|
||||
|
||||
[
|
||||
](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 <julian@juliangruber.com>
|
||||
|
||||
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.
|
||||
+20
@@ -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
@@ -100,13 +100,29 @@ final class AllFunctionsViewController: BaseViewController {
|
||||
self?.applyViewModel(animated: self?.hasAppliedInitialSnapshot == true)
|
||||
}
|
||||
}
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(reloadFunctions),
|
||||
name: NotificationName.permissionItemsDidChange,
|
||||
object: AppStore.shared.permissions
|
||||
)
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(reloadFunctions),
|
||||
name: NotificationName.accountDidSwitch,
|
||||
object: nil
|
||||
)
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
viewModel.loadFunctions()
|
||||
}
|
||||
|
||||
@objc private func reloadFunctions() {
|
||||
Task { @MainActor [weak self] in self?.viewModel.loadFunctions() }
|
||||
}
|
||||
|
||||
override func viewDidDisappear(_ animated: Bool) {
|
||||
super.viewDidDisappear(animated)
|
||||
if isMovingFromParent, viewModel.didCustomize {
|
||||
|
||||
@@ -12,6 +12,7 @@ final class GlobalLoadingManager {
|
||||
static let shared = GlobalLoadingManager()
|
||||
|
||||
private var loadingCount = 0
|
||||
private var requestTokens: Set<UUID> = []
|
||||
private weak var hostWindow: UIWindow?
|
||||
private var overlayView: GlobalLoadingOverlayView?
|
||||
|
||||
@@ -19,13 +20,14 @@ final class GlobalLoadingManager {
|
||||
|
||||
/// 当前是否正在展示 Loading。
|
||||
var isShowing: Bool {
|
||||
loadingCount > 0
|
||||
loadingCount > 0 || !requestTokens.isEmpty
|
||||
}
|
||||
|
||||
/// 增加 Loading 引用计数并展示遮罩。
|
||||
func show() {
|
||||
let wasShowing = isShowing
|
||||
loadingCount += 1
|
||||
guard loadingCount == 1 else { return }
|
||||
guard !wasShowing else { return }
|
||||
attachOverlayIfNeeded()
|
||||
overlayView?.present()
|
||||
}
|
||||
@@ -34,18 +36,41 @@ final class GlobalLoadingManager {
|
||||
func hide() {
|
||||
guard loadingCount > 0 else { return }
|
||||
loadingCount -= 1
|
||||
guard loadingCount == 0 else { return }
|
||||
overlayView?.dismiss()
|
||||
overlayView?.removeFromSuperview()
|
||||
dismissOverlayIfIdle()
|
||||
}
|
||||
|
||||
/// 为一次请求持有 Loading;使用令牌避免迟到回调结束其它请求的展示。
|
||||
func beginRequest() -> UUID {
|
||||
let token = UUID()
|
||||
let wasShowing = isShowing
|
||||
requestTokens.insert(token)
|
||||
if !wasShowing {
|
||||
attachOverlayIfNeeded()
|
||||
overlayView?.present()
|
||||
}
|
||||
return token
|
||||
}
|
||||
|
||||
/// 仅结束仍有效的请求令牌,重复结束或 hideAll 后的旧令牌均无副作用。
|
||||
func endRequest(_ token: UUID) {
|
||||
guard requestTokens.remove(token) != nil else { return }
|
||||
dismissOverlayIfIdle()
|
||||
}
|
||||
|
||||
/// 强制关闭所有 Loading。
|
||||
func hideAll() {
|
||||
requestTokens = []
|
||||
loadingCount = 0
|
||||
overlayView?.dismiss()
|
||||
overlayView?.removeFromSuperview()
|
||||
}
|
||||
|
||||
private func dismissOverlayIfIdle() {
|
||||
guard !isShowing else { return }
|
||||
overlayView?.dismiss()
|
||||
overlayView?.removeFromSuperview()
|
||||
}
|
||||
|
||||
private func attachOverlayIfNeeded() {
|
||||
guard let window = keyWindow else { return }
|
||||
hostWindow = window
|
||||
|
||||
@@ -67,16 +67,20 @@ final class MainTabBarController: UITabBarController {
|
||||
|
||||
/// 响应推送点击,切换到目标 Tab 并打开对应业务页面。
|
||||
func openPushDestination(_ destination: PushDestination) {
|
||||
let targetTab = AppTab.home
|
||||
loadViewIfNeeded()
|
||||
let targetTab: AppTab = destination == .orders ? .orders : .home
|
||||
|
||||
let wasAlreadyOnOrders = targetTab == .orders && selectedViewController === tabNavigationControllers[.orders]
|
||||
selectTab(targetTab)
|
||||
guard let navigationController = tabNavigationControllers[targetTab] else { return }
|
||||
_ = navigationController.popToRootViewController(animated: false)
|
||||
|
||||
let controller: UIViewController?
|
||||
switch destination {
|
||||
case .paymentRecord:
|
||||
controller = PaymentCollectionRecordViewController()
|
||||
case .orders:
|
||||
(navigationController.viewControllers.first as? OrdersViewController)?.openFromOrderNotification()
|
||||
if wasAlreadyOnOrders { badgeViewModel.refreshPendingWriteOffCount() }
|
||||
controller = nil
|
||||
case .paymentDetails:
|
||||
controller = PaymentCollectionDetailsViewController()
|
||||
case .messageCenter:
|
||||
|
||||
@@ -338,7 +338,7 @@ final class OfflineCollectionRegistrationViewController: BaseViewController {
|
||||
}
|
||||
|
||||
@objc private func quickAmountTapped(_ sender: UIButton) {
|
||||
viewModel.updateAmount(OfflineCollectionMoney.apiAmount(sender.tag))
|
||||
viewModel.updateAmount(OfflineCollectionMoney.displayAmount(sender.tag))
|
||||
amountField.becomeFirstResponder()
|
||||
moveAmountCursorToEnd()
|
||||
}
|
||||
|
||||
@@ -8,17 +8,64 @@ import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 订单 Tab 根页面,按角色分流摄影师/景区管理员/店铺管理员。
|
||||
final class OrdersViewController: BaseViewController, UITableViewDataSource, UITableViewDelegate {
|
||||
final class OrdersViewController: BaseViewController, UITableViewDelegate {
|
||||
|
||||
private let orderAPI = NetworkServices.shared.orderAPI
|
||||
private let orderListViewModel = OrderListViewModel()
|
||||
private let depositViewModel = DepositOrderListViewModel()
|
||||
private let appStore: AppStore
|
||||
private let orderAPI: OrderAPI
|
||||
private let orderListViewModel: OrderListViewModel
|
||||
private let depositViewModel: DepositOrderListViewModel
|
||||
|
||||
/// 表格快照持有完整行数据,避免刷新清空 ViewModel 后仍按旧行号取值。
|
||||
private struct OrderRow: Hashable {
|
||||
/// 同一快照内按位置区分行,兼容接口返回重复订单号。
|
||||
let position: Int
|
||||
let content: Content
|
||||
|
||||
/// 摄影师和店铺订单的不可变展示数据。
|
||||
enum Content: Equatable {
|
||||
case photographer(OrderEntity, source: OrderSourceSelection?, readOnly: Bool, showSource: Bool)
|
||||
case deposit(StoreOrderItem)
|
||||
}
|
||||
|
||||
func hash(into hasher: inout Hasher) {
|
||||
hasher.combine(position)
|
||||
switch content {
|
||||
case .photographer(let order, _, _, _):
|
||||
hasher.combine(0)
|
||||
hasher.combine(order.orderNumber)
|
||||
case .deposit(let order):
|
||||
hasher.combine(1)
|
||||
hasher.combine(order.orderNumber)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private var dataSource: UITableViewDiffableDataSource<Int, OrderRow>?
|
||||
|
||||
/// 注入订单数据依赖;默认使用应用共享 API 和独立的页面 ViewModel。
|
||||
init(
|
||||
orderAPI: OrderAPI? = nil,
|
||||
orderListViewModel: OrderListViewModel? = nil,
|
||||
depositViewModel: DepositOrderListViewModel? = nil,
|
||||
appStore: AppStore = .shared
|
||||
) {
|
||||
self.appStore = appStore
|
||||
self.orderAPI = orderAPI ?? NetworkServices.shared.orderAPI
|
||||
self.orderListViewModel = orderListViewModel ?? OrderListViewModel(appStore: appStore)
|
||||
self.depositViewModel = depositViewModel ?? DepositOrderListViewModel(appStore: appStore)
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("init(coder:) has not been implemented")
|
||||
}
|
||||
|
||||
private let filterBar = OrderFilterBarView()
|
||||
private let listView = OrderListView()
|
||||
|
||||
private var hasInitialized = false
|
||||
private var isStoreMode: Bool { AppStore.shared.session.currentAppRole == .storeAdmin }
|
||||
private var isStoreMode: Bool { appStore.session.currentAppRole == .storeAdmin }
|
||||
private var pendingOrderSourceNumber: String?
|
||||
private weak var orderSourcePicker: OrderSourcePickerViewController?
|
||||
private var pendingGiftOrderNumber: String?
|
||||
@@ -32,10 +79,10 @@ final class OrdersViewController: BaseViewController, UITableViewDataSource, UIT
|
||||
override func setupUI() {
|
||||
view.addSubview(filterBar)
|
||||
view.addSubview(listView)
|
||||
listView.tableView.dataSource = self
|
||||
listView.tableView.delegate = self
|
||||
listView.tableView.register(OrderCardCell.self, forCellReuseIdentifier: OrderCardCell.reuseIdentifier)
|
||||
listView.tableView.register(DepositOrderCardCell.self, forCellReuseIdentifier: DepositOrderCardCell.reuseIdentifier)
|
||||
configureDataSource()
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
@@ -133,6 +180,21 @@ final class OrdersViewController: BaseViewController, UITableViewDataSource, UIT
|
||||
Task { await initializeList() }
|
||||
}
|
||||
|
||||
/// 从订单通知进入时恢复默认查询,并刷新已有或首次打开的列表。
|
||||
func openFromOrderNotification() {
|
||||
loadViewIfNeeded()
|
||||
hasInitialized = true
|
||||
if isStoreMode {
|
||||
depositViewModel.resetFiltersForOrderNotification()
|
||||
} else {
|
||||
orderListViewModel.resetFiltersForOrderNotification()
|
||||
}
|
||||
applyViewModel()
|
||||
Task { @MainActor [weak self] in
|
||||
await self?.initializeList()
|
||||
}
|
||||
}
|
||||
|
||||
private func initializeList() async {
|
||||
if isStoreMode {
|
||||
await depositViewModel.refreshOrderList(api: orderAPI)
|
||||
@@ -142,6 +204,7 @@ final class OrdersViewController: BaseViewController, UITableViewDataSource, UIT
|
||||
}
|
||||
|
||||
private func applyViewModel() {
|
||||
applyOrderSnapshot()
|
||||
if isStoreMode {
|
||||
filterBar.configure(
|
||||
isStoreMode: true,
|
||||
@@ -191,7 +254,6 @@ final class OrdersViewController: BaseViewController, UITableViewDataSource, UIT
|
||||
presentMultiVerifySheet()
|
||||
}
|
||||
}
|
||||
listView.tableView.reloadData()
|
||||
}
|
||||
|
||||
private func dateRangeText(start: Date?, end: Date?) -> String {
|
||||
@@ -314,32 +376,61 @@ final class OrdersViewController: BaseViewController, UITableViewDataSource, UIT
|
||||
|
||||
// MARK: - UITableView
|
||||
|
||||
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
|
||||
isStoreMode ? depositViewModel.orderList.count : orderListViewModel.orderList.count
|
||||
}
|
||||
|
||||
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
|
||||
if isStoreMode {
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: DepositOrderCardCell.reuseIdentifier, for: indexPath) as! DepositOrderCardCell
|
||||
let item = depositViewModel.orderList[indexPath.row]
|
||||
cell.configure(item: item, actions: makeDepositActions(for: item))
|
||||
listView.notifyLoadMoreIfNeeded(at: indexPath.row, shouldLoad: depositViewModel.shouldLoadMore(at: indexPath.row))
|
||||
private func configureDataSource() {
|
||||
dataSource = UITableViewDiffableDataSource<Int, OrderRow>(tableView: listView.tableView) { [weak self] tableView, _, row in
|
||||
guard let self else { return nil }
|
||||
switch row.content {
|
||||
case .deposit(let item):
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: DepositOrderCardCell.reuseIdentifier) as! DepositOrderCardCell
|
||||
cell.configure(item: item, actions: self.makeDepositActions(for: item))
|
||||
return cell
|
||||
}
|
||||
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: OrderCardCell.reuseIdentifier, for: indexPath) as! OrderCardCell
|
||||
let order = orderListViewModel.orderList[indexPath.row]
|
||||
let source = orderListViewModel.orderSourceSelection(for: order)
|
||||
case .photographer(let order, let source, let readOnly, let showSource):
|
||||
let cell = tableView.dequeueReusableCell(withIdentifier: OrderCardCell.reuseIdentifier) as! OrderCardCell
|
||||
cell.configure(
|
||||
order: order,
|
||||
hideWriteActions: orderListViewModel.isScenicAdminReadOnly,
|
||||
actions: makeOrderActions(for: order),
|
||||
showOrderSource: orderListViewModel.shouldShowOrderSource(for: order),
|
||||
hideWriteActions: readOnly,
|
||||
actions: self.makeOrderActions(for: order),
|
||||
showOrderSource: showSource,
|
||||
sourceSelection: source
|
||||
)
|
||||
listView.notifyLoadMoreIfNeeded(at: indexPath.row, shouldLoad: orderListViewModel.shouldLoadMore(at: indexPath.row))
|
||||
return cell
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func applyOrderSnapshot() {
|
||||
let rows: [OrderRow]
|
||||
if isStoreMode {
|
||||
rows = depositViewModel.orderList.enumerated().map {
|
||||
OrderRow(position: $0.offset, content: .deposit($0.element))
|
||||
}
|
||||
} else {
|
||||
rows = orderListViewModel.orderList.enumerated().map { index, order in
|
||||
OrderRow(position: index, content: .photographer(
|
||||
order,
|
||||
source: orderListViewModel.orderSourceSelection(for: order),
|
||||
readOnly: orderListViewModel.isScenicAdminReadOnly,
|
||||
showSource: orderListViewModel.shouldShowOrderSource(for: order)
|
||||
))
|
||||
}
|
||||
}
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, OrderRow>()
|
||||
snapshot.appendSections([0])
|
||||
snapshot.appendItems(rows)
|
||||
dataSource?.apply(snapshot, animatingDifferences: true)
|
||||
}
|
||||
|
||||
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
|
||||
guard let row = dataSource?.itemIdentifier(for: indexPath) else { return }
|
||||
let shouldLoad: Bool
|
||||
switch row.content {
|
||||
case .deposit:
|
||||
shouldLoad = isStoreMode && depositViewModel.shouldLoadMore(at: row.position)
|
||||
case .photographer:
|
||||
shouldLoad = !isStoreMode && orderListViewModel.shouldLoadMore(at: row.position)
|
||||
}
|
||||
listView.notifyLoadMoreIfNeeded(at: row.position, shouldLoad: shouldLoad)
|
||||
}
|
||||
|
||||
private func makeOrderActions(for order: OrderEntity) -> OrderCardActions {
|
||||
var actions = OrderCardActions()
|
||||
|
||||
@@ -101,15 +101,16 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
}
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = viewModel.usesNalatiBranding ? nil : "收款详情"
|
||||
title = viewModel.usesBranding ? nil : "收款详情"
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
let usesBranding = viewModel.usesNalatiBranding
|
||||
let usesBranding = viewModel.usesBranding
|
||||
view.backgroundColor = usesBranding ? .clear : AppColor.pageBackground
|
||||
scrollView.showsVerticalScrollIndicator = !usesBranding
|
||||
scrollView.isScrollEnabled = true
|
||||
scrollView.alwaysBounceVertical = true
|
||||
scrollView.contentInsetAdjustmentBehavior = .always
|
||||
|
||||
contentStack.axis = .vertical
|
||||
contentStack.spacing = usesBranding ? brandSectionSpacing : AppSpacing.md
|
||||
@@ -187,7 +188,7 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
configureBrandHeader()
|
||||
backgroundImageView.contentMode = .scaleAspectFill
|
||||
backgroundImageView.clipsToBounds = true
|
||||
backgroundImageView.image = UIImage(named: "payment_nalati_background")
|
||||
backgroundImageView.image = UIImage(named: viewModel.brandBackgroundAssetName)
|
||||
view.addSubview(backgroundImageView)
|
||||
}
|
||||
|
||||
@@ -320,30 +321,24 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
if viewModel.usesNalatiBranding {
|
||||
if viewModel.usesBranding {
|
||||
backgroundImageView.snp.makeConstraints { make in
|
||||
make.edges.equalToSuperview()
|
||||
}
|
||||
}
|
||||
scrollView.snp.makeConstraints { make in
|
||||
if viewModel.usesNalatiBranding {
|
||||
make.leading.trailing.equalToSuperview()
|
||||
make.top.equalTo(view.safeAreaLayoutGuide.snp.top).offset(-44)
|
||||
make.bottom.equalTo(view.safeAreaLayoutGuide)
|
||||
} else {
|
||||
make.edges.equalTo(view.safeAreaLayoutGuide)
|
||||
}
|
||||
make.edges.equalToSuperview()
|
||||
}
|
||||
contentContainerView.snp.makeConstraints { make in
|
||||
make.edges.equalToSuperview()
|
||||
make.width.equalTo(scrollView.snp.width)
|
||||
if viewModel.usesNalatiBranding {
|
||||
make.edges.equalTo(scrollView.contentLayoutGuide)
|
||||
make.width.equalTo(scrollView.frameLayoutGuide)
|
||||
if viewModel.usesBranding {
|
||||
make.height.greaterThanOrEqualTo(scrollView.snp.height)
|
||||
}
|
||||
}
|
||||
contentStack.snp.makeConstraints { make in
|
||||
make.width.equalTo(scrollView.snp.width).offset(-AppSpacing.screenHorizontalInset * 2)
|
||||
if viewModel.usesNalatiBranding {
|
||||
if viewModel.usesBranding {
|
||||
make.centerX.equalToSuperview()
|
||||
make.top.bottom.equalToSuperview().inset(AppSpacing.screenHorizontalInset)
|
||||
} else {
|
||||
@@ -403,7 +398,7 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
}
|
||||
|
||||
override var preferredStatusBarStyle: UIStatusBarStyle {
|
||||
viewModel.usesNalatiBranding ? .darkContent : .default
|
||||
viewModel.usesBranding ? .darkContent : .default
|
||||
}
|
||||
|
||||
private func loadData() async {
|
||||
@@ -426,7 +421,7 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
if viewModel.isPayCodeLoading {
|
||||
qrImageView.isHidden = true
|
||||
qrContainerView.isHidden = true
|
||||
qrPlaceholderView.backgroundColor = viewModel.usesNalatiBranding
|
||||
qrPlaceholderView.backgroundColor = viewModel.usesBranding
|
||||
? .white
|
||||
: AppColor.inputBackground
|
||||
qrPlaceholderView.isHidden = false
|
||||
@@ -437,7 +432,7 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
} else if let image = viewModel.qrImage {
|
||||
qrImageView.image = image
|
||||
qrImageView.isHidden = false
|
||||
qrContainerView.isHidden = !viewModel.usesNalatiBranding
|
||||
qrContainerView.isHidden = !viewModel.usesBranding
|
||||
qrPlaceholderView.isHidden = true
|
||||
qrLoadingIndicator.stopAnimating()
|
||||
setActionRowAvailable(true)
|
||||
@@ -527,7 +522,7 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
brandHeaderStack.alignment = .center
|
||||
brandHeaderStack.spacing = brandScreenHeight <= 700 ? 6 : 8
|
||||
|
||||
brandLogoImageView.image = UIImage(named: "payment_nalati_logo")
|
||||
brandLogoImageView.image = UIImage(named: viewModel.brandLogoAssetName)
|
||||
brandLogoImageView.contentMode = .scaleAspectFit
|
||||
brandLogoImageView.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
|
||||
|
||||
@@ -537,7 +532,7 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
)
|
||||
brandTitleLabel.textColor = UIColor(hex: 0x102D54)
|
||||
brandTitleLabel.textAlignment = .center
|
||||
brandTitleLabel.numberOfLines = 1
|
||||
brandTitleLabel.numberOfLines = viewModel.brandTitleNumberOfLines
|
||||
brandTitleLabel.adjustsFontSizeToFitWidth = true
|
||||
brandTitleLabel.minimumScaleFactor = 0.8
|
||||
|
||||
@@ -604,7 +599,7 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
|
||||
@MainActor
|
||||
private func applyBrandConfigIfNeeded() {
|
||||
guard viewModel.usesNalatiBranding else { return }
|
||||
guard viewModel.usesBranding else { return }
|
||||
let config = viewModel.payPageConfig
|
||||
brandTitleLabel.text = config.title
|
||||
brandSubtitleLabel.text = config.subtitle
|
||||
@@ -615,13 +610,13 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
setBrandImage(
|
||||
backgroundImageView,
|
||||
urlString: config.background,
|
||||
fallbackName: "payment_nalati_background",
|
||||
fallbackName: viewModel.brandBackgroundAssetName,
|
||||
forceRefresh: forceRefresh
|
||||
)
|
||||
setBrandImage(
|
||||
brandLogoImageView,
|
||||
urlString: config.logo,
|
||||
fallbackName: "payment_nalati_logo",
|
||||
fallbackName: viewModel.brandLogoAssetName,
|
||||
forceRefresh: forceRefresh
|
||||
)
|
||||
appliedBrandConfig = config
|
||||
@@ -639,6 +634,7 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
guard let url = URL(string: trimmed),
|
||||
url.scheme?.lowercased() == "https",
|
||||
url.host != nil else {
|
||||
imageView.kf.cancelDownloadTask()
|
||||
imageView.image = fallback
|
||||
return
|
||||
}
|
||||
@@ -655,7 +651,7 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
}
|
||||
|
||||
private func applyBrandNavigationAppearanceIfNeeded() {
|
||||
guard viewModel.usesNalatiBranding, let navigationBar = navigationController?.navigationBar else { return }
|
||||
guard viewModel.usesBranding, let navigationBar = navigationController?.navigationBar else { return }
|
||||
previousStandardAppearance = navigationBar.standardAppearance
|
||||
previousScrollEdgeAppearance = navigationBar.scrollEdgeAppearance
|
||||
previousCompactAppearance = navigationBar.compactAppearance
|
||||
@@ -677,7 +673,7 @@ final class PaymentCollectionDetailsViewController: BaseViewController {
|
||||
}
|
||||
|
||||
private func restoreNavigationAppearanceIfNeeded() {
|
||||
guard viewModel.usesNalatiBranding, let navigationBar = navigationController?.navigationBar else { return }
|
||||
guard viewModel.usesBranding, let navigationBar = navigationController?.navigationBar else { return }
|
||||
if let previousStandardAppearance {
|
||||
navigationBar.standardAppearance = previousStandardAppearance
|
||||
}
|
||||
|
||||
@@ -30,6 +30,7 @@ final class ProfileViewController: BaseViewController {
|
||||
private let realNameRow = ProfileInfoRowView(title: "认证状态")
|
||||
private let statusRow = ProfileInfoRowView(title: "账号状态")
|
||||
private let scenicRow = ProfileInfoRowView(title: "当前景区")
|
||||
private let trainingRow = ProfileInfoRowView(title: "培训中心")
|
||||
private let settingRow = ProfileInfoRowView(title: "设置中心")
|
||||
private let logoutButton = UIButton(type: .system)
|
||||
private var hasLoadedProfileOnce = false
|
||||
@@ -92,6 +93,7 @@ final class ProfileViewController: BaseViewController {
|
||||
withdrawalRow.addTarget(self, action: #selector(withdrawalTapped), for: .touchUpInside)
|
||||
realNameRow.addTarget(self, action: #selector(realNameTapped), for: .touchUpInside)
|
||||
settingRow.addTarget(self, action: #selector(settingTapped), for: .touchUpInside)
|
||||
trainingRow.addTarget(self, action: #selector(trainingTapped), for: .touchUpInside)
|
||||
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
@@ -105,10 +107,17 @@ final class ProfileViewController: BaseViewController {
|
||||
name: NotificationName.userProfileDidUpdate,
|
||||
object: nil
|
||||
)
|
||||
NotificationCenter.default.addObserver(
|
||||
self,
|
||||
selector: #selector(handlePermissionItemsDidChange),
|
||||
name: NotificationName.permissionItemsDidChange,
|
||||
object: AppStore.shared.permissions
|
||||
)
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
applyViewModel()
|
||||
let showLoading = !hasLoadedProfileOnce && !viewModel.hasCachedBasicInfo
|
||||
Task {
|
||||
await reloadProfile(showGlobalLoading: showLoading)
|
||||
@@ -183,7 +192,7 @@ final class ProfileViewController: BaseViewController {
|
||||
[
|
||||
nameRow, accountRow, phoneRow, withdrawalRow,
|
||||
passwordRow, realNameRow, statusRow, scenicRow,
|
||||
settingRow
|
||||
trainingRow, settingRow
|
||||
].forEach { infoCard.addArrangedSubview($0) }
|
||||
|
||||
nameRow.isUserInteractionEnabled = false
|
||||
@@ -202,6 +211,8 @@ final class ProfileViewController: BaseViewController {
|
||||
}
|
||||
|
||||
private func applyViewModel() {
|
||||
trainingRow.isHidden = !viewModel.showsTrainingEntry
|
||||
trainingRow.configure(value: "学习课程与答题", accessory: .chevron)
|
||||
nicknameField.text = viewModel.displayNickname
|
||||
uidLabel.text = "UID:\(viewModel.displayUID)"
|
||||
avatarImageView.loadRemoteImage(urlString: viewModel.displayAvatarURL)
|
||||
@@ -289,9 +300,14 @@ final class ProfileViewController: BaseViewController {
|
||||
}
|
||||
|
||||
@objc private func handleAccountDidSwitch() {
|
||||
applyViewModel()
|
||||
Task { await reloadProfile(showGlobalLoading: true) }
|
||||
}
|
||||
|
||||
@objc private func handlePermissionItemsDidChange() {
|
||||
Task { @MainActor [weak self] in self?.applyViewModel() }
|
||||
}
|
||||
|
||||
@objc private func handleProfileDidUpdate() {
|
||||
viewModel.applyLocalProfileUpdate()
|
||||
applyViewModel()
|
||||
@@ -353,6 +369,10 @@ final class ProfileViewController: BaseViewController {
|
||||
navigationController?.pushViewController(SettingViewController(), animated: true)
|
||||
}
|
||||
|
||||
@objc private func trainingTapped() {
|
||||
HomeRouteHandler.open(uri: "/training", from: self, storeItem: nil)
|
||||
}
|
||||
|
||||
@objc private func logoutTapped() {
|
||||
let alert = UIAlertController(title: "确定退出登录?", message: "退出后将需要重新登录", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "取消", style: .cancel))
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import AVFoundation
|
||||
|
||||
/// 扫码采集会话的配置与运行接口,便于独立验证生命周期顺序。
|
||||
protocol QRCodeCaptureSession: AnyObject {
|
||||
/// 当前是否正在采集。
|
||||
var isRunning: Bool { get }
|
||||
/// 开始批量配置。
|
||||
func beginConfiguration()
|
||||
/// 提交批量配置。
|
||||
func commitConfiguration()
|
||||
/// 启动采集。
|
||||
func startRunning()
|
||||
/// 停止采集。
|
||||
func stopRunning()
|
||||
}
|
||||
|
||||
extension AVCaptureSession: QRCodeCaptureSession {}
|
||||
|
||||
/// 在同一串行队列中配置和启停相机,避免配置提交与启动交叉执行。
|
||||
final class QRCodeCaptureSessionController {
|
||||
private let session: QRCodeCaptureSession
|
||||
private let queue: DispatchQueue
|
||||
private var isConfigured = false
|
||||
|
||||
/// 创建会话生命周期控制器;队列必须为串行队列。
|
||||
init(session: QRCodeCaptureSession,
|
||||
queue: DispatchQueue = DispatchQueue(label: "com.zhifly.suixinkan.qr-capture")) {
|
||||
self.session = session
|
||||
self.queue = queue
|
||||
}
|
||||
|
||||
/// 在配置事务内添加输入输出,提交完成后在主线程通知结果。
|
||||
func configure(_ configuration: @escaping () -> Bool, completion: @escaping (Bool) -> Void) {
|
||||
queue.async { [self] in
|
||||
if !isConfigured {
|
||||
session.beginConfiguration()
|
||||
isConfigured = configuration()
|
||||
session.commitConfiguration()
|
||||
}
|
||||
let succeeded = isConfigured
|
||||
DispatchQueue.main.async { completion(succeeded) }
|
||||
}
|
||||
}
|
||||
|
||||
/// 按提交顺序更新运行状态,运行状态的读取也限定在会话队列内。
|
||||
func setRunning(_ shouldRun: Bool) {
|
||||
queue.async { [self] in
|
||||
if shouldRun {
|
||||
guard isConfigured, !session.isRunning else { return }
|
||||
session.startRunning()
|
||||
} else if session.isRunning {
|
||||
session.stopRunning()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,11 +10,15 @@ import UIKit
|
||||
/// AVFoundation 二维码扫描页。
|
||||
final class QRCodeScannerViewController: BaseViewController, AVCaptureMetadataOutputObjectsDelegate {
|
||||
|
||||
/// 识别到有效二维码后返回内容,每次展示仅回调一次。
|
||||
var onScanResult: ((String) -> Void)?
|
||||
|
||||
private let captureSession = AVCaptureSession()
|
||||
private lazy var captureController = QRCodeCaptureSessionController(session: captureSession)
|
||||
private var previewLayer: AVCaptureVideoPreviewLayer?
|
||||
private var isCameraConfigured = false
|
||||
private var isCameraConfiguring = false
|
||||
private var isScannerVisible = false
|
||||
private var hasHandledResult = false
|
||||
|
||||
private let maskView = UIView()
|
||||
@@ -63,6 +67,7 @@ final class QRCodeScannerViewController: BaseViewController, AVCaptureMetadataOu
|
||||
|
||||
override func viewDidAppear(_ animated: Bool) {
|
||||
super.viewDidAppear(animated)
|
||||
isScannerVisible = true
|
||||
updatePreviewLayout()
|
||||
startCaptureSessionIfNeeded()
|
||||
}
|
||||
@@ -75,6 +80,7 @@ final class QRCodeScannerViewController: BaseViewController, AVCaptureMetadataOu
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
isScannerVisible = false
|
||||
stopCaptureSession()
|
||||
}
|
||||
|
||||
@@ -105,32 +111,44 @@ final class QRCodeScannerViewController: BaseViewController, AVCaptureMetadataOu
|
||||
return
|
||||
}
|
||||
|
||||
guard let device = AVCaptureDevice.default(for: .video),
|
||||
let input = try? AVCaptureDeviceInput(device: device) else {
|
||||
showToast("无法打开相机")
|
||||
return
|
||||
}
|
||||
|
||||
captureSession.beginConfiguration()
|
||||
defer { captureSession.commitConfiguration() }
|
||||
|
||||
guard captureSession.canAddInput(input) else { return }
|
||||
guard !isCameraConfiguring else { return }
|
||||
isCameraConfiguring = true
|
||||
captureController.configure({ [weak self, captureSession] in
|
||||
guard let self,
|
||||
let device = AVCaptureDevice.default(for: .video),
|
||||
let input = try? AVCaptureDeviceInput(device: device),
|
||||
captureSession.canAddInput(input) else { return false }
|
||||
captureSession.addInput(input)
|
||||
|
||||
let output = AVCaptureMetadataOutput()
|
||||
guard captureSession.canAddOutput(output) else { return }
|
||||
guard captureSession.canAddOutput(output) else {
|
||||
captureSession.removeInput(input)
|
||||
return false
|
||||
}
|
||||
captureSession.addOutput(output)
|
||||
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
|
||||
guard output.availableMetadataObjectTypes.contains(.qr) else {
|
||||
captureSession.removeOutput(output)
|
||||
captureSession.removeInput(input)
|
||||
return false
|
||||
}
|
||||
output.setMetadataObjectsDelegate(self, queue: .main)
|
||||
output.metadataObjectTypes = [.qr]
|
||||
|
||||
let layer = AVCaptureVideoPreviewLayer(session: captureSession)
|
||||
return true
|
||||
}, completion: { [weak self] succeeded in
|
||||
guard let self else { return }
|
||||
self.isCameraConfiguring = false
|
||||
guard succeeded else {
|
||||
self.showToast("无法打开相机")
|
||||
return
|
||||
}
|
||||
let layer = AVCaptureVideoPreviewLayer(session: self.captureSession)
|
||||
layer.videoGravity = .resizeAspectFill
|
||||
view.layer.insertSublayer(layer, at: 0)
|
||||
previewLayer = layer
|
||||
isCameraConfigured = true
|
||||
|
||||
updatePreviewLayout()
|
||||
startCaptureSessionIfNeeded()
|
||||
self.view.layer.insertSublayer(layer, at: 0)
|
||||
self.previewLayer = layer
|
||||
self.isCameraConfigured = true
|
||||
self.updatePreviewLayout()
|
||||
self.startCaptureSessionIfNeeded()
|
||||
})
|
||||
}
|
||||
|
||||
private func updatePreviewLayout() {
|
||||
@@ -138,17 +156,12 @@ final class QRCodeScannerViewController: BaseViewController, AVCaptureMetadataOu
|
||||
}
|
||||
|
||||
private func startCaptureSessionIfNeeded() {
|
||||
guard isCameraConfigured, !captureSession.isRunning else { return }
|
||||
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
||||
self?.captureSession.startRunning()
|
||||
}
|
||||
guard isScannerVisible, isCameraConfigured, !hasHandledResult else { return }
|
||||
captureController.setRunning(true)
|
||||
}
|
||||
|
||||
private func stopCaptureSession() {
|
||||
guard captureSession.isRunning else { return }
|
||||
DispatchQueue.global(qos: .userInitiated).async { [weak self] in
|
||||
self?.captureSession.stopRunning()
|
||||
}
|
||||
captureController.setRunning(false)
|
||||
}
|
||||
|
||||
private func updateMask() {
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 培训首页、完整任务列表和考试记录共用一个页面,与小程序入口保持一致。
|
||||
@MainActor
|
||||
final class TrainingCenterViewController: TrainingBaseViewController {
|
||||
/// 差异化列表中的任务与考试记录标识。
|
||||
private enum Item: Hashable { case task(String), attempt(String) }
|
||||
private var reloadTask: Task<Void, Never>?
|
||||
private var reloadLoadingToken: UUID?
|
||||
private var moreTask: Task<Void, Never>?
|
||||
private var moreLoadingToken: UUID?
|
||||
private var searchTask: Task<Void, Never>?
|
||||
private let service: any TrainingDataServing
|
||||
private let viewModel = TrainingRemoteCenterViewModel()
|
||||
private let tableView = UITableView(frame: .zero, style: .plain)
|
||||
private let refreshControl = UIRefreshControl()
|
||||
private let header = UIStackView()
|
||||
private let hero = UIStackView()
|
||||
private let greetingLabel = TrainingUI.text(size: 14, color: .white)
|
||||
private let titleLabel = TrainingUI.text("我的培训中心", size: 18, weight: .bold, color: .white)
|
||||
private var statLabels: [UILabel] = []
|
||||
private let headingLabel = TrainingUI.text(size: 15.5, weight: .semibold)
|
||||
private let viewAllButton = TrainingUI.button("查看全部", plain: true)
|
||||
private let filters = UIStackView()
|
||||
private var filterButtons: [UIButton] = []
|
||||
private let searchField = UITextField()
|
||||
private let tabBar = UIStackView()
|
||||
private let tabBackground = UIView()
|
||||
private var tabButtons: [UIButton] = []
|
||||
private let footer = UIStackView()
|
||||
private let stateLabel = TrainingUI.text(size: 14, color: TrainingUI.muted)
|
||||
private let retryButton = TrainingUI.button("重新加载", secondary: true)
|
||||
private let moreButton = TrainingUI.button("加载更多记录", plain: true)
|
||||
private var dataSource: UITableViewDiffableDataSource<Int, Item>!
|
||||
|
||||
/// 默认使用当前登录身份连接环境配置中的培训接口。
|
||||
init(service: (any TrainingDataServing)? = nil, showsHistory: Bool = false) {
|
||||
self.service = service ?? TrainingRemoteServiceFactory.production()
|
||||
viewModel.tab = showsHistory ? .records : .home
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func setupNavigationBar() {
|
||||
TrainingUI.navigation(self, title: "培训中心")
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = TrainingUI.background
|
||||
header.axis = .vertical
|
||||
header.spacing = 0
|
||||
hero.axis = .vertical
|
||||
hero.spacing = 8
|
||||
hero.backgroundColor = UIColor(red: 45/255, green: 128/255, blue: 250/255, alpha: 1)
|
||||
hero.layer.cornerRadius = 14
|
||||
hero.isLayoutMarginsRelativeArrangement = true
|
||||
hero.layoutMargins = UIEdgeInsets(top: 19, left: 17, bottom: 18, right: 17)
|
||||
hero.addArrangedSubview(greetingLabel)
|
||||
hero.addArrangedSubview(titleLabel)
|
||||
let stats = UIStackView()
|
||||
stats.distribution = .fillEqually
|
||||
stats.alignment = .fill
|
||||
for caption in ["待考试", "已完成", "最近得分"] {
|
||||
let value = TrainingUI.text("—", size: 23, weight: .bold, color: .white)
|
||||
value.textAlignment = .center
|
||||
statLabels.append(value)
|
||||
let name = TrainingUI.text(caption, size: 12.5, color: .white)
|
||||
name.textAlignment = .center
|
||||
let column = UIStackView(arrangedSubviews: [value, name])
|
||||
column.axis = .vertical
|
||||
column.spacing = 6
|
||||
stats.addArrangedSubview(column)
|
||||
if statLabels.count > 1 {
|
||||
let line = UIView()
|
||||
line.backgroundColor = UIColor.white.withAlphaComponent(0.4)
|
||||
column.addSubview(line)
|
||||
line.snp.makeConstraints { $0.leading.top.bottom.equalToSuperview(); $0.width.equalTo(1) }
|
||||
}
|
||||
}
|
||||
hero.setCustomSpacing(18, after: titleLabel)
|
||||
hero.addArrangedSubview(stats)
|
||||
let heroContainer = UIStackView(arrangedSubviews: [hero])
|
||||
heroContainer.axis = .vertical
|
||||
heroContainer.isLayoutMarginsRelativeArrangement = true
|
||||
heroContainer.layoutMargins = UIEdgeInsets(top: 12, left: 13, bottom: 12, right: 13)
|
||||
header.addArrangedSubview(heroContainer)
|
||||
let body = UIStackView()
|
||||
body.axis = .vertical
|
||||
body.spacing = 11
|
||||
body.isLayoutMarginsRelativeArrangement = true
|
||||
body.layoutMargins = UIEdgeInsets(top: 14, left: 13, bottom: 10, right: 13)
|
||||
let heading = UIStackView(arrangedSubviews: [headingLabel, viewAllButton])
|
||||
heading.alignment = .center
|
||||
heading.spacing = 8
|
||||
headingLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
|
||||
viewAllButton.setContentHuggingPriority(.required, for: .horizontal)
|
||||
body.addArrangedSubview(heading)
|
||||
filters.distribution = .fillEqually
|
||||
filters.spacing = 9
|
||||
for (index, state) in TrainingLearnerStatus.allCases.enumerated() {
|
||||
let button = TrainingUI.button(state.title, secondary: true)
|
||||
var configuration = button.configuration
|
||||
configuration?.contentInsets = NSDirectionalEdgeInsets(top: 12, leading: 6, bottom: 12, trailing: 6)
|
||||
configuration?.titleAlignment = .center
|
||||
configuration?.titleLineBreakMode = .byWordWrapping
|
||||
button.configuration = configuration
|
||||
button.tag = index
|
||||
button.accessibilityIdentifier = "training.filter.\(button.tag)"
|
||||
button.addTarget(self, action: #selector(filterTapped(_:)), for: .touchUpInside)
|
||||
filterButtons.append(button)
|
||||
filters.addArrangedSubview(button)
|
||||
}
|
||||
body.addArrangedSubview(filters)
|
||||
searchField.font = .systemFont(ofSize: 13)
|
||||
searchField.backgroundColor = .white
|
||||
searchField.layer.cornerRadius = 8
|
||||
searchField.placeholder = "搜索任务或课程名称"
|
||||
searchField.clearButtonMode = .whileEditing
|
||||
searchField.returnKeyType = .search
|
||||
searchField.accessibilityIdentifier = "training.search"
|
||||
searchField.leftView = UIView(frame: CGRect(x: 0, y: 0, width: 12, height: 1))
|
||||
searchField.leftViewMode = .always
|
||||
searchField.snp.makeConstraints { $0.height.equalTo(44) }
|
||||
body.addArrangedSubview(searchField)
|
||||
header.addArrangedSubview(body)
|
||||
tableView.backgroundColor = .clear
|
||||
tableView.separatorStyle = .none
|
||||
tableView.rowHeight = UITableView.automaticDimension
|
||||
tableView.estimatedRowHeight = 250
|
||||
tableView.delegate = self
|
||||
tableView.keyboardDismissMode = .onDrag
|
||||
tableView.refreshControl = refreshControl
|
||||
tableView.register(TrainingTaskCell.self, forCellReuseIdentifier: TrainingTaskCell.reuseIdentifier)
|
||||
tableView.register(TrainingRecordCell.self, forCellReuseIdentifier: TrainingRecordCell.reuseIdentifier)
|
||||
tableView.tableHeaderView = header
|
||||
footer.axis = .vertical
|
||||
footer.spacing = 12
|
||||
footer.isLayoutMarginsRelativeArrangement = true
|
||||
footer.layoutMargins = UIEdgeInsets(top: 24, left: 26, bottom: 24, right: 26)
|
||||
stateLabel.textAlignment = .center
|
||||
[stateLabel, retryButton, moreButton].forEach(footer.addArrangedSubview)
|
||||
tableView.tableFooterView = footer
|
||||
tabBackground.backgroundColor = .white
|
||||
let line = UIView()
|
||||
line.backgroundColor = TrainingUI.border
|
||||
tabBackground.addSubview(line)
|
||||
line.snp.makeConstraints { $0.top.leading.trailing.equalToSuperview(); $0.height.equalTo(1) }
|
||||
tabBar.distribution = .fillEqually
|
||||
for tab in TrainingCenterTab.allCases {
|
||||
let button = TrainingUI.button(tab.title, plain: true)
|
||||
button.tag = tab.rawValue
|
||||
button.accessibilityIdentifier = "training.tab.\(tab.rawValue)"
|
||||
button.addTarget(self, action: #selector(tabTapped(_:)), for: .touchUpInside)
|
||||
tabButtons.append(button)
|
||||
tabBar.addArrangedSubview(button)
|
||||
}
|
||||
view.addSubview(tableView)
|
||||
view.addSubview(tabBackground)
|
||||
tabBackground.addSubview(tabBar)
|
||||
configureDataSource()
|
||||
applyState()
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
tabBackground.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() }
|
||||
tabBar.snp.makeConstraints {
|
||||
$0.leading.trailing.equalToSuperview().inset(12)
|
||||
$0.top.equalToSuperview().offset(7)
|
||||
$0.bottom.equalTo(view.safeAreaLayoutGuide).offset(-7)
|
||||
}
|
||||
tableView.snp.makeConstraints {
|
||||
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
|
||||
$0.bottom.equalTo(tabBackground.snp.top)
|
||||
}
|
||||
}
|
||||
|
||||
override func viewDidLayoutSubviews() {
|
||||
super.viewDidLayoutSubviews()
|
||||
sizeTableSupplementaryViews()
|
||||
}
|
||||
|
||||
private func sizeTableSupplementaryViews() {
|
||||
let width = tableView.bounds.width
|
||||
guard width > 0 else { return }
|
||||
for stack in [header, footer] {
|
||||
let height = stack.systemLayoutSizeFitting(CGSize(width: width, height: 0), withHorizontalFittingPriority: .required, verticalFittingPriority: .fittingSizeLevel).height
|
||||
if abs(stack.frame.height - height) > 0.5 || stack.frame.width != width {
|
||||
stack.frame = CGRect(x: 0, y: 0, width: width, height: height)
|
||||
if stack === header { tableView.tableHeaderView = header } else { tableView.tableFooterView = footer }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override func bindActions() {
|
||||
retryButton.accessibilityIdentifier = "training.center.retry"
|
||||
moreButton.accessibilityIdentifier = "training.center.more"
|
||||
refreshControl.addTarget(self, action: #selector(reloadTapped), for: .valueChanged)
|
||||
retryButton.addTarget(self, action: #selector(reloadTapped), for: .touchUpInside)
|
||||
viewAllButton.addTarget(self, action: #selector(viewAllTapped), for: .touchUpInside)
|
||||
searchField.addTarget(self, action: #selector(searchChanged), for: .editingChanged)
|
||||
moreButton.addTarget(self, action: #selector(moreTapped), for: .touchUpInside)
|
||||
}
|
||||
|
||||
override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated); reloadTapped() }
|
||||
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
|
||||
|
||||
private func configureDataSource() {
|
||||
dataSource = UITableViewDiffableDataSource<Int, Item>(tableView: tableView) { [weak self] table, indexPath, item in
|
||||
guard let self else { return nil }
|
||||
switch item {
|
||||
case .task(let id):
|
||||
guard let task = self.viewModel.tasks.first(where: { $0.id == id }), let cell = table.dequeueReusableCell(withIdentifier: TrainingTaskCell.reuseIdentifier, for: indexPath) as? TrainingTaskCell else { return nil }
|
||||
cell.configure(task: task)
|
||||
cell.onAction = { [weak self] in self?.openTask(task, directAction: true) }
|
||||
return cell
|
||||
case .attempt(let attemptID):
|
||||
guard let attempt = self.viewModel.records.first(where: { $0.id == attemptID }), let cell = table.dequeueReusableCell(withIdentifier: TrainingRecordCell.reuseIdentifier, for: indexPath) as? TrainingRecordCell else { return nil }
|
||||
cell.configure(attempt: attempt)
|
||||
return cell
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func applyState(completion: (() -> Void)? = nil) {
|
||||
let session = AppStore.shared.session
|
||||
let name = [session.realName, session.userName].first { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } ?? "当前学员"
|
||||
greetingLabel.text = "你好,\(name)"
|
||||
let context = session.currentScenicName.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
titleLabel.text = context.isEmpty ? "我的培训中心" : "\(context) · 培训中心"
|
||||
for (label, value) in zip(statLabels, [String(viewModel.pendingCount), String(viewModel.completedCount), viewModel.latestScore]) { label.text = value }
|
||||
headingLabel.text = switch viewModel.tab { case .home: "新政策与必读内容"; case .tasks: "我的学习任务"; case .records: "考试记录" }
|
||||
viewAllButton.isHidden = viewModel.tab != .home
|
||||
filters.isHidden = viewModel.tab != .tasks
|
||||
searchField.isHidden = viewModel.tab != .tasks
|
||||
for (index, button) in filterButtons.enumerated() {
|
||||
let state = TrainingLearnerStatus.allCases[index]
|
||||
let selected = state == viewModel.filter
|
||||
var configuration = button.configuration
|
||||
configuration?.title = switch state {
|
||||
case .pendingExam: "待考试 \(viewModel.pendingCount)"
|
||||
case .completed: "已完成 \(viewModel.completedCount)"
|
||||
case .ended: state.title
|
||||
}
|
||||
configuration?.background.backgroundColor = selected ? TrainingUI.primary.withAlphaComponent(0.09) : .white
|
||||
configuration?.baseForegroundColor = selected ? TrainingUI.primary : TrainingUI.muted
|
||||
button.configuration = configuration
|
||||
button.accessibilityTraits = selected ? [.button, .selected] : .button
|
||||
}
|
||||
for (index, button) in tabButtons.enumerated() {
|
||||
var configuration = button.configuration
|
||||
configuration?.baseForegroundColor = index == viewModel.tab.rawValue ? TrainingUI.primary : TrainingUI.muted
|
||||
button.configuration = configuration
|
||||
button.accessibilityTraits = index == viewModel.tab.rawValue ? [.button, .selected] : .button
|
||||
}
|
||||
let items: [Item] = viewModel.tab == .records ? viewModel.records.map { .attempt($0.id) } : viewModel.tasks.map { .task($0.id) }
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
|
||||
snapshot.appendSections([0])
|
||||
snapshot.appendItems(items)
|
||||
snapshot.reconfigureItems(items.filter { dataSource.snapshot().indexOfItem($0) != nil })
|
||||
dataSource.apply(snapshot, animatingDifferences: true, completion: completion)
|
||||
stateLabel.text = viewModel.errorMessage ?? (viewModel.isLoading ? "正在加载培训任务…" : viewModel.tab == .records ? "暂无考试记录\n交卷后可在此查看成绩和解析" : "暂无符合条件的任务\n景区分配给当前账号的任务会显示在这里")
|
||||
stateLabel.isHidden = !items.isEmpty
|
||||
retryButton.isHidden = viewModel.errorMessage == nil
|
||||
retryButton.isEnabled = !viewModel.isLoading
|
||||
moreButton.isHidden = !viewModel.hasMore
|
||||
moreButton.isEnabled = !viewModel.isLoadingMore
|
||||
var moreConfiguration = moreButton.configuration
|
||||
moreConfiguration?.title = viewModel.isLoadingMore ? "正在加载…" : "加载更多"
|
||||
moreButton.configuration = moreConfiguration
|
||||
if !viewModel.isLoading { refreshControl.endRefreshing() }
|
||||
sizeTableSupplementaryViews()
|
||||
}
|
||||
|
||||
/// 页面出现和下拉刷新都读取最新本人任务。
|
||||
func reload() async {
|
||||
await viewModel.load(service: service)
|
||||
guard !Task.isCancelled else { return }
|
||||
if viewModel.isIdentityInvalid { navigationController?.popToRootViewController(animated: false); return }
|
||||
await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in
|
||||
applyState { continuation.resume() }
|
||||
}
|
||||
}
|
||||
|
||||
/// 在同一页面切换入口,返回课程时保留筛选上下文。
|
||||
func selectTab(_ tab: TrainingCenterTab) {
|
||||
view.endEditing(true)
|
||||
viewModel.selectTab(tab)
|
||||
searchField.text = ""
|
||||
reloadTapped()
|
||||
tableView.setContentOffset(.zero, animated: false)
|
||||
}
|
||||
|
||||
@objc private func reloadTapped() {
|
||||
scheduleReload(showsLoading: true)
|
||||
}
|
||||
|
||||
private func releaseReloadLoading() {
|
||||
if let token = reloadLoadingToken { endRequestLoading(token) }
|
||||
reloadLoadingToken = nil
|
||||
}
|
||||
|
||||
private func releaseMoreLoading() {
|
||||
if let token = moreLoadingToken { endRequestLoading(token) }
|
||||
moreLoadingToken = nil
|
||||
}
|
||||
|
||||
private func scheduleReload(showsLoading: Bool) {
|
||||
if showsLoading {
|
||||
searchTask?.cancel()
|
||||
searchTask = nil
|
||||
}
|
||||
reloadTask?.cancel()
|
||||
releaseReloadLoading()
|
||||
moreTask?.cancel()
|
||||
moreTask = nil
|
||||
releaseMoreLoading()
|
||||
let token = showsLoading ? beginRequestLoading() : nil
|
||||
reloadLoadingToken = token
|
||||
reloadTask = Task { @MainActor in
|
||||
defer {
|
||||
if let token { endRequestLoading(token) }
|
||||
if reloadLoadingToken == token { reloadLoadingToken = nil }
|
||||
}
|
||||
await reload()
|
||||
}
|
||||
}
|
||||
@objc private func tabTapped(_ button: UIButton) { if let tab = TrainingCenterTab(rawValue: button.tag) { selectTab(tab) } }
|
||||
@objc private func filterTapped(_ button: UIButton) {
|
||||
guard TrainingLearnerStatus.allCases.indices.contains(button.tag) else { return }
|
||||
viewModel.filter = TrainingLearnerStatus.allCases[button.tag]
|
||||
reloadTapped()
|
||||
}
|
||||
@objc private func searchChanged() {
|
||||
viewModel.setKeyword(searchField.text ?? "")
|
||||
reloadTask?.cancel()
|
||||
releaseReloadLoading()
|
||||
moreTask?.cancel()
|
||||
moreTask = nil
|
||||
releaseMoreLoading()
|
||||
searchTask?.cancel()
|
||||
moreButton.isHidden = true
|
||||
searchTask = Task { @MainActor [weak self] in
|
||||
do { try await Task.sleep(for: .milliseconds(300)) } catch { return }
|
||||
self?.scheduleReload(showsLoading: false)
|
||||
}
|
||||
}
|
||||
@objc private func moreTapped() {
|
||||
guard moreTask == nil, viewModel.hasMore, !viewModel.isLoading, !viewModel.isLoadingMore else { return }
|
||||
let token = beginRequestLoading()
|
||||
moreLoadingToken = token
|
||||
moreTask = Task { @MainActor in
|
||||
defer {
|
||||
endRequestLoading(token)
|
||||
if moreLoadingToken == token {
|
||||
moreLoadingToken = nil
|
||||
moreTask = nil
|
||||
}
|
||||
}
|
||||
await viewModel.loadMore(service: service)
|
||||
if viewModel.isIdentityInvalid { navigationController?.popToRootViewController(animated: false); return }
|
||||
applyState()
|
||||
}
|
||||
}
|
||||
@objc private func viewAllTapped() { viewModel.filter = .pendingExam; selectTab(.tasks) }
|
||||
|
||||
private func openTask(_ task: TrainingTaskSummary, directAction: Bool) {
|
||||
let controller: UIViewController = directAction && task.learnerStatus == .pendingExam && task.learning.canStartExam ? TrainingExamViewController(taskID: task.id, service: service) : TrainingCourseViewController(taskID: task.id, service: service)
|
||||
navigationController?.pushViewController(controller, animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
extension TrainingCenterViewController: UITableViewDelegate {
|
||||
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
|
||||
tableView.deselectRow(at: indexPath, animated: true)
|
||||
guard let item = dataSource.itemIdentifier(for: indexPath) else { return }
|
||||
switch item {
|
||||
case .task(let id): if let task = viewModel.tasks.first(where: { $0.id == id }) { openTask(task, directAction: false) }
|
||||
case .attempt(let attemptID): if let attempt = viewModel.records.first(where: { $0.id == attemptID }) { navigationController?.pushViewController(TrainingResultViewController(taskID: attempt.taskID, attemptID: attempt.id, service: service), animated: true) }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,525 @@
|
||||
import SafariServices
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 原生课程信息与附件文件预览,并上报服务端确认的有效前台读时。
|
||||
@MainActor
|
||||
final class TrainingCourseViewController: TrainingBaseViewController {
|
||||
private let service: any TrainingDataServing
|
||||
private let viewModel: TrainingRemoteReadingViewModel
|
||||
private let validateIdentity: @MainActor @Sendable () -> Bool
|
||||
private let documentLoader: any TrainingDocumentLoading
|
||||
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 previewView = TrainingDocumentPreviewView()
|
||||
private var previewHeightConstraint: Constraint?
|
||||
private var localDocument: TrainingLocalDocument?
|
||||
private let stepView = TrainingStepView(currentStep: .learning)
|
||||
private let bottomStack = UIStackView()
|
||||
private let noticeLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
|
||||
private let actionButton = TrainingUI.button("正在加载课程…")
|
||||
private var readingTimer: Timer?
|
||||
private var contentTask: Task<Void, Never>?
|
||||
private var readingTask: Task<Void, Never>?
|
||||
private var closingTask: Task<Void, Never>?
|
||||
private var closingGeneration = 0
|
||||
private var appIsActive = UIApplication.shared.applicationState == .active
|
||||
private var isOpeningExternalLink = false
|
||||
private var contentIsReady = false
|
||||
private var contentLoadFailed = false
|
||||
private var pageIsVisible = false
|
||||
private var userRequestID: UUID?
|
||||
|
||||
/// 用户操作独占的请求票据;缓存复用仍防重复操作,但不展示全局进度。
|
||||
private struct UserRequest {
|
||||
let id: UUID
|
||||
let loadingToken: UUID?
|
||||
}
|
||||
|
||||
/// 当前任务标识,成绩页可复用已有课程页面。
|
||||
var taskID: String { viewModel.taskID }
|
||||
|
||||
/// 使用正式接口与独立文件下载器读取课程附件,支持测试注入本地文件。
|
||||
init(taskID: String, service: any TrainingDataServing, documentLoader: any TrainingDocumentLoading = TrainingDocumentLoader()) {
|
||||
self.service = service
|
||||
self.documentLoader = documentLoader
|
||||
let session = AppStore.shared.session
|
||||
let scope = session.accountCachePrefix
|
||||
let scenicID = session.currentScenicId
|
||||
let storeID = session.currentStoreId
|
||||
let token = session.token
|
||||
let validate: @MainActor @Sendable () -> Bool = {
|
||||
let current = AppStore.shared.session
|
||||
return current.accountCachePrefix == scope && current.currentScenicId == scenicID
|
||||
&& current.currentStoreId == storeID && current.token == token
|
||||
}
|
||||
validateIdentity = validate
|
||||
viewModel = TrainingRemoteReadingViewModel(taskID: taskID, service: service, validateIdentity: validate)
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func setupNavigationBar() { TrainingUI.navigation(self, title: "课程学习") }
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = TrainingUI.background
|
||||
scrollView.delegate = self
|
||||
scrollView.accessibilityIdentifier = "training.reading.scroll"
|
||||
scrollView.alwaysBounceVertical = true
|
||||
contentStack.axis = .vertical
|
||||
contentStack.spacing = 14
|
||||
metadataStack.axis = .vertical
|
||||
metadataStack.spacing = 8
|
||||
metadataStack.isHidden = true
|
||||
[taskTitleLabel, courseNameLabel, examInfoLabel, introductionLabel].forEach(metadataStack.addArrangedSubview)
|
||||
taskTitleLabel.accessibilityIdentifier = "training.reading.taskTitle"
|
||||
courseNameLabel.accessibilityIdentifier = "training.reading.courseName"
|
||||
examInfoLabel.accessibilityIdentifier = "training.reading.examInfo"
|
||||
introductionLabel.accessibilityIdentifier = "training.reading.introduction"
|
||||
contentStack.addArrangedSubview(metadataStack)
|
||||
contentStack.addArrangedSubview(previewView)
|
||||
stepView.isHidden = true
|
||||
bottomStack.axis = .vertical
|
||||
bottomStack.spacing = 8
|
||||
bottomStack.layoutMargins = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12)
|
||||
bottomStack.isLayoutMarginsRelativeArrangement = true
|
||||
bottomStack.backgroundColor = AppColor.cardBackground
|
||||
bottomStack.addArrangedSubview(noticeLabel)
|
||||
bottomStack.addArrangedSubview(actionButton)
|
||||
actionButton.accessibilityIdentifier = "training.reading.action"
|
||||
view.addSubview(stepView)
|
||||
view.addSubview(scrollView)
|
||||
scrollView.addSubview(contentStack)
|
||||
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()
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
stepView.snp.makeConstraints {
|
||||
$0.top.equalTo(view.safeAreaLayoutGuide).offset(8)
|
||||
$0.leading.trailing.equalToSuperview().inset(13)
|
||||
}
|
||||
scrollView.snp.makeConstraints {
|
||||
$0.top.equalTo(stepView.snp.bottom).offset(8)
|
||||
$0.leading.trailing.equalTo(view.safeAreaLayoutGuide)
|
||||
$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) }
|
||||
}
|
||||
|
||||
override func bindActions() {
|
||||
actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange, NotificationName.userDidLogout] {
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(identityChanged), name: name, object: nil)
|
||||
}
|
||||
}
|
||||
|
||||
override func viewDidAppear(_ animated: Bool) {
|
||||
super.viewDidAppear(animated)
|
||||
pageIsVisible = true
|
||||
let previousContent = contentTask
|
||||
contentTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await previousContent?.value
|
||||
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self,
|
||||
userRequestID == nil else { return }
|
||||
if viewModel.task == nil { loadCourse() }
|
||||
else if localDocument == nil, let id = viewModel.currentAttachmentID { selectAttachment(id) }
|
||||
else {
|
||||
await viewModel.refreshProgress()
|
||||
applyState()
|
||||
resumeReading()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
pageIsVisible = false
|
||||
contentTask?.cancel()
|
||||
pauseReading()
|
||||
}
|
||||
|
||||
override func onSessionDidExpire() { identityChanged() }
|
||||
|
||||
private var isContentVisible: Bool {
|
||||
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
|
||||
}
|
||||
|
||||
private func loadCourse() {
|
||||
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()
|
||||
contentIsReady = false
|
||||
contentLoadFailed = false
|
||||
previewView.showStatus("正在加载附件…")
|
||||
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
|
||||
}
|
||||
|
||||
private func applyState() {
|
||||
guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return }
|
||||
if let task = viewModel.task?.summary {
|
||||
stepView.configure(mode: task.mode)
|
||||
stepView.isHidden = false
|
||||
}
|
||||
let canInteract = userRequestID == nil
|
||||
actionButton.isUserInteractionEnabled = canInteract
|
||||
guard canInteract else { return }
|
||||
if contentLoadFailed || viewModel.attachmentErrorMessage != nil || viewModel.task == nil {
|
||||
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 viewModel.progress?.learnerStatus == .ended {
|
||||
noticeLabel.text = "任务已结束,仅可回顾课程内容"
|
||||
setActionTitle("返回培训中心")
|
||||
actionButton.isEnabled = true
|
||||
readingTimer?.invalidate()
|
||||
readingTimer = nil
|
||||
return
|
||||
}
|
||||
if let progress = viewModel.progress, progress.readingCompleted {
|
||||
noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成"
|
||||
if viewModel.task?.summary.mode == .exam && viewModel.task?.summary.learnerStatus == .pendingExam
|
||||
&& progress.learnerStatus == .pendingExam && progress.canStartExam { setActionTitle("开始考试") }
|
||||
else { setActionTitle("返回培训中心") }
|
||||
actionButton.isEnabled = true
|
||||
readingTimer?.invalidate()
|
||||
readingTimer = nil
|
||||
return
|
||||
}
|
||||
if !contentIsReady {
|
||||
noticeLabel.text = "正在打开课程附件…"
|
||||
setActionTitle("正在加载附件…")
|
||||
actionButton.isEnabled = false
|
||||
return
|
||||
}
|
||||
if !viewModel.canStudy {
|
||||
readingTimer?.invalidate()
|
||||
readingTimer = nil
|
||||
noticeLabel.text = viewModel.readingErrorMessage ?? "当前任务可回顾课程,不能继续提交学习记录"
|
||||
setActionTitle("返回培训中心")
|
||||
actionButton.isEnabled = true
|
||||
} else if let error = viewModel.errorMessage {
|
||||
readingTimer?.invalidate()
|
||||
readingTimer = nil
|
||||
noticeLabel.text = error
|
||||
setActionTitle(viewModel.readingErrorMessage != nil ? "重试保存并继续学习" : "重新加载课程")
|
||||
actionButton.isEnabled = true
|
||||
} else {
|
||||
let action = viewModel.task?.summary.mode == .exam ? "开始考试" : "完成学习"
|
||||
noticeLabel.text = viewModel.readingNotice ?? (viewModel.remainingSeconds == 0 ? "正在确认学习进度…" : "请在前台阅读课程内容,倒计时结束后等待保存确认")
|
||||
setActionTitle("\(action)(\(viewModel.remainingSeconds)s)")
|
||||
actionButton.isEnabled = false
|
||||
}
|
||||
}
|
||||
|
||||
private func setActionTitle(_ title: String) {
|
||||
var configuration = actionButton.configuration
|
||||
configuration?.title = title
|
||||
actionButton.configuration = configuration
|
||||
}
|
||||
|
||||
private func beginUserRequest(showsLoading: Bool) -> UserRequest? {
|
||||
guard userRequestID == nil, !viewModel.isInvalidated else { return nil }
|
||||
let request = UserRequest(id: UUID(), loadingToken: showsLoading ? beginRequestLoading() : nil)
|
||||
userRequestID = request.id
|
||||
applyState()
|
||||
return request
|
||||
}
|
||||
|
||||
private func endUserRequest(_ request: UserRequest) {
|
||||
if let token = request.loadingToken { endRequestLoading(token) }
|
||||
guard userRequestID == request.id else { return }
|
||||
userRequestID = nil
|
||||
applyState()
|
||||
}
|
||||
|
||||
private func performUserRequest<Value>(_ request: UserRequest, operation: () async -> Value) async -> Value {
|
||||
defer { endUserRequest(request) }
|
||||
return await operation()
|
||||
}
|
||||
|
||||
@objc private func pauseReading() {
|
||||
readingTimer?.invalidate()
|
||||
readingTimer = nil
|
||||
viewModel.pauseReading()
|
||||
let previousClose = closingTask
|
||||
closingGeneration += 1
|
||||
let epoch = closingGeneration
|
||||
closingTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await previousClose?.value
|
||||
await viewModel.flush()
|
||||
if closingGeneration == epoch { closingTask = nil }
|
||||
applyState()
|
||||
resumeReading()
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func appWillResignActive() { appIsActive = false; pauseReading() }
|
||||
|
||||
@objc private func appDidBecomeActive() { appIsActive = true; resumeReading() }
|
||||
|
||||
private func resumeReading(retrying: Bool = false) {
|
||||
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil) else { return }
|
||||
if viewModel.isReading {
|
||||
installReadingTimer()
|
||||
return
|
||||
}
|
||||
guard readingTask == nil else { return }
|
||||
let request = retrying ? beginUserRequest(showsLoading: true) : nil
|
||||
guard !retrying || request != nil else { return }
|
||||
let pendingClose = closingTask
|
||||
readingTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
defer { if let request { endUserRequest(request) } }
|
||||
await pendingClose?.value
|
||||
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), !Task.isCancelled else {
|
||||
readingTask = nil
|
||||
return
|
||||
}
|
||||
await viewModel.startReading(at: ProcessInfo.processInfo.systemUptime)
|
||||
readingTask = nil
|
||||
applyState()
|
||||
if isContentVisible && viewModel.isReading { installReadingTimer() }
|
||||
}
|
||||
}
|
||||
|
||||
private func installReadingTimer() {
|
||||
guard readingTimer == nil else { return }
|
||||
let timer = Timer(timeInterval: 0.25, repeats: true) { [weak self] _ in
|
||||
Task { @MainActor in self?.readingTick() }
|
||||
}
|
||||
readingTimer = timer
|
||||
RunLoop.main.add(timer, forMode: .common)
|
||||
}
|
||||
|
||||
private func readingTick() {
|
||||
guard isContentVisible else { return }
|
||||
if viewModel.accumulateVisibleTime(at: ProcessInfo.processInfo.systemUptime) { applyState() }
|
||||
guard readingTask == nil, viewModel.needsReadingFlush else { return }
|
||||
readingTask = Task { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
await viewModel.flush()
|
||||
readingTask = nil
|
||||
applyState()
|
||||
if isContentVisible, viewModel.canStudy, !viewModel.isReading, viewModel.remainingSeconds > 0 { resumeReading() }
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func identityChanged() {
|
||||
readingTimer?.invalidate()
|
||||
readingTimer = nil
|
||||
contentTask?.cancel()
|
||||
readingTask?.cancel()
|
||||
closingTask?.cancel()
|
||||
previewView.showStatus("")
|
||||
localDocument?.removeTemporaryFile()
|
||||
localDocument = nil
|
||||
viewModel.invalidate()
|
||||
leaveUnavailableCourse()
|
||||
}
|
||||
|
||||
@objc private func actionTapped() {
|
||||
guard userRequestID == nil else { return }
|
||||
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()
|
||||
if viewModel.task?.summary.mode == .exam && viewModel.task?.summary.learnerStatus == .pendingExam
|
||||
&& progress.learnerStatus == .pendingExam && progress.canStartExam {
|
||||
navigationController?.pushViewController(TrainingExamViewController(taskID: taskID, service: service), animated: true)
|
||||
} else { returnToCenter() }
|
||||
} else if !viewModel.canStudy { returnToCenter() }
|
||||
else if viewModel.readingErrorMessage != nil { resumeReading(retrying: true) }
|
||||
else if viewModel.errorMessage != nil { 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() {
|
||||
if let center = navigationController?.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
|
||||
navigationController?.popToViewController(center, animated: true)
|
||||
} else { navigationController?.popToRootViewController(animated: true) }
|
||||
}
|
||||
|
||||
private func leaveUnavailableCourse() {
|
||||
readingTimer?.invalidate()
|
||||
readingTimer = nil
|
||||
previewView.showStatus("")
|
||||
localDocument?.removeTemporaryFile()
|
||||
localDocument = nil
|
||||
if let presentedViewController {
|
||||
presentedViewController.dismiss(animated: false) { [weak self] in self?.returnToCenter() }
|
||||
} else { returnToCenter() }
|
||||
}
|
||||
|
||||
deinit { localDocument?.removeTemporaryFile() }
|
||||
|
||||
private func finishExternalLinkPresentation() {
|
||||
isOpeningExternalLink = false
|
||||
resumeReading()
|
||||
}
|
||||
}
|
||||
|
||||
extension TrainingCourseViewController: UIScrollViewDelegate {
|
||||
/// 原生课程信息滚动到覆盖整个预览区时暂停,文件再次可见时才恢复。
|
||||
func scrollViewDidScroll(_ scrollView: UIScrollView) {
|
||||
previewView.notifyIfRenderedAndVisible()
|
||||
if isContentVisible { resumeReading() }
|
||||
else if viewModel.isReading { pauseReading() }
|
||||
}
|
||||
}
|
||||
|
||||
extension TrainingCourseViewController: SFSafariViewControllerDelegate {
|
||||
/// 关闭外部链接后,仅在正文重新可见时建立新的阅读片段。
|
||||
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
|
||||
controller.dismiss(animated: true) { [weak self] in self?.finishExternalLinkPresentation() }
|
||||
}
|
||||
}
|
||||
@@ -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,468 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 按需分页的原生考试页,增量保存草稿并持久恢复未知交卷结果。
|
||||
@MainActor
|
||||
final class TrainingExamViewController: TrainingBaseViewController {
|
||||
private let service: any TrainingDataServing
|
||||
private let viewModel: TrainingRemoteExamViewModel
|
||||
private let resetDraft: Bool
|
||||
private var openedResult = false
|
||||
private var navigationIsScheduled = false
|
||||
private var hasAppeared = false
|
||||
private var isPerformingOperation = false
|
||||
private var requestLoadingToken: UUID?
|
||||
private var needsReloadOnReturn = false
|
||||
private var renderedQuestion: TrainingQuestionItem?
|
||||
private var optionButtons: [String: UIButton] = [:]
|
||||
private let scrollView = UIScrollView()
|
||||
private let pageStack = UIStackView()
|
||||
private let stepView = TrainingStepView(currentStep: .exam)
|
||||
private let contentStack = TrainingUI.card()
|
||||
private let positionLabel = TrainingUI.label(style: .subheadline, color: AppColor.primary)
|
||||
private let questionLabel = TrainingUI.label(style: .title3)
|
||||
private let hintLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
|
||||
private let optionStack = UIStackView()
|
||||
private let navigationStack = UIStackView()
|
||||
private let previousButton = AppButton(title: "上一题", style: .secondary)
|
||||
private let nextButton = AppButton(title: "下一题", style: .secondary)
|
||||
private let bottomStack = UIStackView()
|
||||
private let statusLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
|
||||
private let submitButton = AppButton(title: "交卷")
|
||||
|
||||
/// 用户明确重考才传 resetDraft;默认恢复已有草稿和未确认提交。
|
||||
init(taskID: String, service: any TrainingDataServing, resetDraft: Bool = false, viewModel: TrainingRemoteExamViewModel? = nil) {
|
||||
self.service = service
|
||||
self.viewModel = viewModel ?? TrainingRemoteExamViewModel(taskID: taskID, context: TrainingPendingSubmissionStore.currentContext())
|
||||
self.resetDraft = resetDraft
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func setupNavigationBar() {
|
||||
title = "培训答题"
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "答题卡", style: .plain, target: self, action: #selector(answerCardTapped))
|
||||
}
|
||||
|
||||
override func setupUI() {
|
||||
scrollView.alwaysBounceVertical = true
|
||||
pageStack.axis = .vertical
|
||||
pageStack.spacing = 16
|
||||
pageStack.addArrangedSubview(stepView)
|
||||
pageStack.addArrangedSubview(contentStack)
|
||||
optionStack.axis = .vertical
|
||||
optionStack.spacing = 12
|
||||
navigationStack.axis = .horizontal
|
||||
navigationStack.spacing = 12
|
||||
navigationStack.distribution = .fillEqually
|
||||
navigationStack.addArrangedSubview(previousButton)
|
||||
navigationStack.addArrangedSubview(nextButton)
|
||||
previousButton.accessibilityIdentifier = "training.exam.previous"
|
||||
nextButton.accessibilityIdentifier = "training.exam.next"
|
||||
[positionLabel, questionLabel, hintLabel, optionStack, navigationStack].forEach(contentStack.addArrangedSubview)
|
||||
bottomStack.axis = .vertical
|
||||
bottomStack.spacing = 8
|
||||
bottomStack.backgroundColor = AppColor.cardBackground
|
||||
bottomStack.layoutMargins = UIEdgeInsets(top: 12, left: 20, bottom: 12, right: 20)
|
||||
bottomStack.isLayoutMarginsRelativeArrangement = true
|
||||
bottomStack.addArrangedSubview(statusLabel)
|
||||
bottomStack.addArrangedSubview(submitButton)
|
||||
submitButton.accessibilityIdentifier = "training.exam.submit"
|
||||
scrollView.addSubview(pageStack)
|
||||
view.addSubview(scrollView)
|
||||
view.addSubview(bottomStack)
|
||||
applyState()
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
scrollView.snp.makeConstraints {
|
||||
$0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide)
|
||||
$0.bottom.equalTo(bottomStack.snp.top)
|
||||
}
|
||||
pageStack.snp.makeConstraints {
|
||||
$0.edges.equalTo(scrollView.contentLayoutGuide).inset(16)
|
||||
$0.width.equalTo(scrollView.frameLayoutGuide).offset(-32)
|
||||
}
|
||||
bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
|
||||
}
|
||||
|
||||
override func bindActions() {
|
||||
previousButton.addTarget(self, action: #selector(previousTapped), for: .touchUpInside)
|
||||
nextButton.addTarget(self, action: #selector(nextTapped), for: .touchUpInside)
|
||||
submitButton.addTarget(self, action: #selector(submitTapped), for: .touchUpInside)
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
viewModel.onDraftSaveStateChange = { [weak self] in
|
||||
guard let self, !self.isPerformingOperation else { return }
|
||||
self.applyState()
|
||||
self.scheduleNavigationIfNeeded()
|
||||
}
|
||||
loadExam()
|
||||
}
|
||||
|
||||
override func viewDidAppear(_ animated: Bool) {
|
||||
super.viewDidAppear(animated)
|
||||
let returning = hasAppeared
|
||||
let shouldReload = needsReloadOnReturn
|
||||
needsReloadOnReturn = false
|
||||
hasAppeared = true
|
||||
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
||||
if viewModel.submittedAttempt != nil || viewModel.shouldReturnToCenter {
|
||||
beginOperation(message: "正在确认考试状态…", showsLoading: false)
|
||||
Task { @MainActor in await viewModel.validateIdentity(); finishOperation() }
|
||||
return
|
||||
}
|
||||
if returning, shouldReload { loadExam() }
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
// 自有答题卡和确认弹窗关闭后继续当前题,真实导航返回才刷新考试资格。
|
||||
if navigationController?.topViewController !== self {
|
||||
needsReloadOnReturn = true
|
||||
Task { @MainActor in _ = await viewModel.flushDraft(service: service) }
|
||||
}
|
||||
}
|
||||
|
||||
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
|
||||
|
||||
private func loadExam() {
|
||||
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
||||
beginOperation(message: "正在加载试卷…")
|
||||
Task { @MainActor in
|
||||
await viewModel.load(service: service, resetDraft: resetDraft)
|
||||
finishOperation()
|
||||
}
|
||||
}
|
||||
|
||||
private func applyState() {
|
||||
setOperationInteractionEnabled(true)
|
||||
let pendingTitle = viewModel.hasPendingSubmission ? "恢复交卷结果"
|
||||
: viewModel.hasDraftConflict ? "确认本机答案" : viewModel.hasPendingMutation ? "重试保存" : viewModel.canRetryCurrentPage ? "重试加载本题" : nil
|
||||
guard let question = viewModel.currentQuestion else {
|
||||
clearOptions()
|
||||
positionLabel.text = ""
|
||||
questionLabel.text = viewModel.errorMessage ?? (viewModel.hasPendingSubmission ? "正在确认上次交卷结果…" : "正在加载试卷…")
|
||||
hintLabel.text = ""
|
||||
statusLabel.text = viewModel.hasPendingSubmission ? "上次提交尚未确认,恢复结果后再继续操作" : ""
|
||||
navigationStack.isHidden = true
|
||||
submitButton.setTitle(pendingTitle ?? "重新加载", for: .normal)
|
||||
submitButton.isEnabled = !viewModel.isBusy && (viewModel.errorMessage != nil || pendingTitle != nil)
|
||||
navigationItem.rightBarButtonItem?.isEnabled = false
|
||||
return
|
||||
}
|
||||
navigationStack.isHidden = false
|
||||
navigationItem.rightBarButtonItem?.isEnabled = viewModel.canEdit
|
||||
positionLabel.text = "第 \(viewModel.currentIndex + 1) / \(viewModel.questionCount) 题 · \(question.type == .single ? "单选题" : "多选题")"
|
||||
questionLabel.text = question.stem
|
||||
hintLabel.text = question.type == .single ? "请选择一个答案" : "请选择所有正确答案,少选、多选、错选均不得分"
|
||||
renderOptions(for: question)
|
||||
updateOptionSelection(viewModel.currentSelectedIDs)
|
||||
for button in optionButtons.values { button.isEnabled = viewModel.canEdit }
|
||||
previousButton.isEnabled = viewModel.canEdit && viewModel.currentIndex > 0
|
||||
nextButton.isEnabled = viewModel.canEdit && viewModel.currentIndex < viewModel.questionCount - 1
|
||||
let saveState = viewModel.draftSaveMessage
|
||||
statusLabel.text = viewModel.hasPendingMutation || viewModel.errorMessage == nil
|
||||
? "已答 \(viewModel.answeredCount)/\(viewModel.questionCount) · \(saveState)" : viewModel.errorMessage
|
||||
statusLabel.textColor = viewModel.hasPendingMutation || viewModel.errorMessage != nil ? AppColor.danger : AppColor.textSecondary
|
||||
submitButton.setTitle(pendingTitle ?? (viewModel.isBusy ? "正在保存…" : "交卷"), for: .normal)
|
||||
submitButton.isEnabled = !viewModel.isBusy && (pendingTitle != nil || viewModel.canEdit)
|
||||
}
|
||||
|
||||
private func clearOptions() {
|
||||
for child in optionStack.arrangedSubviews { optionStack.removeArrangedSubview(child); child.removeFromSuperview() }
|
||||
optionButtons = [:]
|
||||
renderedQuestion = nil
|
||||
}
|
||||
|
||||
private func renderOptions(for question: TrainingQuestionItem) {
|
||||
guard renderedQuestion != question else { return }
|
||||
clearOptions()
|
||||
renderedQuestion = question
|
||||
for (index, option) in question.options.enumerated() {
|
||||
let button = UIButton(type: .system)
|
||||
var configuration = UIButton.Configuration.filled()
|
||||
configuration.title = "\(TrainingQuestion.optionLetter(index)).\(option.text)"
|
||||
configuration.contentInsets = NSDirectionalEdgeInsets(top: 18, leading: 16, bottom: 18, trailing: 16)
|
||||
configuration.imagePadding = 12
|
||||
configuration.titleAlignment = .leading
|
||||
configuration.cornerStyle = .medium
|
||||
button.configuration = configuration
|
||||
button.contentHorizontalAlignment = .leading
|
||||
button.titleLabel?.numberOfLines = 0
|
||||
button.titleLabel?.lineBreakMode = .byWordWrapping
|
||||
button.accessibilityIdentifier = "training.option.\(option.id)"
|
||||
button.addAction(UIAction { [weak self] _ in self?.selectOption(option.id) }, for: .touchUpInside)
|
||||
optionButtons[option.id] = button
|
||||
optionStack.addArrangedSubview(button)
|
||||
button.snp.makeConstraints { $0.height.greaterThanOrEqualTo(56) }
|
||||
}
|
||||
}
|
||||
|
||||
private func updateOptionSelection(_ selectedIDs: Set<String>) {
|
||||
UIView.performWithoutAnimation {
|
||||
for (id, button) in optionButtons {
|
||||
let selected = selectedIDs.contains(id)
|
||||
var configuration = button.configuration
|
||||
configuration?.baseBackgroundColor = selected ? AppColor.primaryLight : AppColor.pageBackgroundSoft
|
||||
configuration?.baseForegroundColor = selected ? AppColor.primary : AppColor.textPrimary
|
||||
configuration?.image = UIImage(systemName: selected ? "checkmark.circle.fill" : "circle")
|
||||
button.configuration = configuration
|
||||
button.accessibilityTraits = selected ? [.button, .selected] : .button
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func setOperationInteractionEnabled(_ enabled: Bool) {
|
||||
// 网络操作只暂停动作,保留已启用控件的颜色和透明度。
|
||||
let buttons: [UIButton] = Array(optionButtons.values) + [previousButton, nextButton, submitButton]
|
||||
for button in buttons { button.isUserInteractionEnabled = enabled }
|
||||
}
|
||||
|
||||
private func beginOperation(message: String, showsLoading: Bool = true) {
|
||||
isPerformingOperation = true
|
||||
if showsLoading { requestLoadingToken = beginRequestLoading() }
|
||||
setOperationInteractionEnabled(false)
|
||||
statusLabel.text = message
|
||||
statusLabel.textColor = AppColor.textSecondary
|
||||
}
|
||||
|
||||
private func finishOperation() {
|
||||
if let requestLoadingToken {
|
||||
endRequestLoading(requestLoadingToken)
|
||||
self.requestLoadingToken = nil
|
||||
}
|
||||
isPerformingOperation = false
|
||||
applyState()
|
||||
scheduleNavigationIfNeeded()
|
||||
}
|
||||
|
||||
private func scheduleNavigationIfNeeded() {
|
||||
guard !openedResult, !navigationIsScheduled,
|
||||
viewModel.shouldReturnToCenter || viewModel.submittedAttempt != nil,
|
||||
let navigationController, navigationController.topViewController === self else { return }
|
||||
navigationIsScheduled = true
|
||||
let complete: @MainActor @Sendable () -> Void = { [weak self, weak navigationController] in
|
||||
guard let self else { return }
|
||||
self.navigationIsScheduled = false
|
||||
guard let navigationController, navigationController.topViewController === self else { return }
|
||||
// 返回页面的原 pop 必须先结束,否则新的成绩栈会被 UIKit 恢复成旧考试栈。
|
||||
if navigationController.transitionCoordinator != nil { self.scheduleNavigationIfNeeded(); return }
|
||||
if self.viewModel.shouldReturnToCenter { self.returnToCenter() }
|
||||
else if let attempt = self.viewModel.submittedAttempt { self.openResult(attempt) }
|
||||
}
|
||||
if let coordinator = navigationController.transitionCoordinator {
|
||||
let registered = coordinator.animate(alongsideTransition: nil) { _ in
|
||||
DispatchQueue.main.async(execute: complete)
|
||||
}
|
||||
if !registered { DispatchQueue.main.async(execute: complete) }
|
||||
} else { DispatchQueue.main.async(execute: complete) }
|
||||
}
|
||||
|
||||
private func returnToCenter() {
|
||||
guard let navigationController, navigationController.topViewController === self else { return }
|
||||
if viewModel.isIdentityInvalid {
|
||||
navigationController.popToRootViewController(animated: false)
|
||||
return
|
||||
}
|
||||
if let center = navigationController.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
|
||||
navigationController.popToViewController(center, animated: true)
|
||||
} else { navigationController.popToRootViewController(animated: true) }
|
||||
}
|
||||
|
||||
private func selectOption(_ id: String) {
|
||||
guard !isPerformingOperation, viewModel.selectLocally(optionID: id, service: service) else { return }
|
||||
// desired 已同步更新;连续多选不等待 Task 或网络,保留同题按钮实例。
|
||||
applyState()
|
||||
}
|
||||
|
||||
private func goToQuestion(_ index: Int) {
|
||||
guard !isPerformingOperation, viewModel.canEdit,
|
||||
(0..<viewModel.questionCount).contains(index), index != viewModel.currentIndex else { return }
|
||||
if viewModel.goToCachedQuestion(index, service: service) {
|
||||
applyState()
|
||||
scrollView.setContentOffset(.zero, animated: false)
|
||||
UIAccessibility.post(notification: .screenChanged, argument: questionLabel)
|
||||
return
|
||||
}
|
||||
beginOperation(message: "正在加载题目…")
|
||||
Task { @MainActor in
|
||||
await viewModel.goToQuestion(index, service: service)
|
||||
finishOperation()
|
||||
scrollView.setContentOffset(.zero, animated: false)
|
||||
UIAccessibility.post(notification: .screenChanged, argument: questionLabel)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func previousTapped() { goToQuestion(viewModel.currentIndex - 1) }
|
||||
@objc private func nextTapped() { goToQuestion(viewModel.currentIndex + 1) }
|
||||
|
||||
@objc private func answerCardTapped() {
|
||||
guard !isPerformingOperation, viewModel.canEdit, presentedViewController == nil else { return }
|
||||
let controller = TrainingAnswerCardViewController(questionCount: viewModel.questionCount,
|
||||
answeredOrders: viewModel.answeredQuestionOrders, currentIndex: viewModel.currentIndex)
|
||||
controller.onSelect = { [weak self] index in self?.goToQuestion(index) }
|
||||
let navigation = UINavigationController(rootViewController: controller)
|
||||
if let sheet = navigation.sheetPresentationController { sheet.detents = [.medium(), .large()]; sheet.prefersGrabberVisible = true }
|
||||
present(navigation, animated: true)
|
||||
}
|
||||
|
||||
@objc private func submitTapped() {
|
||||
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
||||
if viewModel.hasDraftConflict { confirmDraftConflict(); return }
|
||||
if viewModel.hasPendingMutation {
|
||||
Task { @MainActor in await viewModel.retryMutation(service: service); applyState() }
|
||||
return
|
||||
}
|
||||
if viewModel.hasPendingSubmission { performSubmit(); return }
|
||||
if viewModel.canRetryCurrentPage {
|
||||
beginOperation(message: "正在加载题目…")
|
||||
Task { @MainActor in await viewModel.retryCurrentPage(service: service); finishOperation() }
|
||||
return
|
||||
}
|
||||
guard viewModel.currentQuestion != nil else { loadExam(); return }
|
||||
guard viewModel.canEdit else { return }
|
||||
if let missing = viewModel.firstUnansweredIndex {
|
||||
goToQuestion(missing)
|
||||
showToast("还有 \(viewModel.questionCount - viewModel.answeredCount) 道题未作答,已定位到第一道")
|
||||
return
|
||||
}
|
||||
guard presentedViewController == nil else { return }
|
||||
let alert = UIAlertController(title: "确认交卷?", message: "已完成 \(viewModel.questionCount) 道题,提交后将生成本次考试记录。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "继续检查", style: .cancel))
|
||||
alert.addAction(UIAlertAction(title: "交卷", style: .default) { [weak self] _ in self?.performSubmit() })
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
private func confirmDraftConflict() {
|
||||
guard presentedViewController == nil else { return }
|
||||
let alert = UIAlertController(title: "答案已在其他设备变更", message: "本机尚未保存的选择已保留。应用本机选择会更新对应题目的答案,也可以使用其他设备已保存的答案。", preferredStyle: .alert)
|
||||
alert.addAction(UIAlertAction(title: "继续检查", style: .cancel))
|
||||
for (title, useLocal) in [("使用已保存答案", false), ("应用本机选择", true)] {
|
||||
alert.addAction(UIAlertAction(title: title, style: .default) { [weak self] _ in
|
||||
guard let self else { return }
|
||||
self.beginOperation(message: "正在确认草稿…", showsLoading: false)
|
||||
Task { @MainActor in
|
||||
await self.viewModel.resolveDraftConflict(useLocalAnswers: useLocal, service: self.service)
|
||||
self.finishOperation()
|
||||
}
|
||||
})
|
||||
}
|
||||
present(alert, animated: true)
|
||||
}
|
||||
|
||||
private func performSubmit() {
|
||||
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
||||
beginOperation(message: "正在提交并确认成绩…")
|
||||
Task { @MainActor in
|
||||
_ = await viewModel.submit(service: service)
|
||||
finishOperation()
|
||||
}
|
||||
}
|
||||
|
||||
private func openResult(_ attempt: TrainingAttemptSummary) {
|
||||
guard !openedResult, let navigationController, navigationController.topViewController === self else { return }
|
||||
openedResult = true
|
||||
let result = TrainingResultViewController(taskID: viewModel.taskID, attemptID: attempt.id, service: service, initialDetail: viewModel.submittedResult)
|
||||
navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [result], animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// 可滚动的网格答题卡,支持最多 500 道题。
|
||||
@MainActor
|
||||
final class TrainingAnswerCardViewController: UIViewController {
|
||||
private let questionCount: Int
|
||||
private let answeredOrders: Set<Int>
|
||||
private let currentIndex: Int
|
||||
private let collectionView: UICollectionView
|
||||
private var dataSource: UICollectionViewDiffableDataSource<Int, Int>!
|
||||
/// 关闭答题卡后将用户选择的题目位置返回考试页面。
|
||||
var onSelect: ((Int) -> Void)?
|
||||
|
||||
/// 使用总题数和已答题号展示答题卡,无需下载题目或全部答案。
|
||||
init(questionCount: Int, answeredOrders: Set<Int>, currentIndex: Int) {
|
||||
self.questionCount = min(500, max(0, questionCount))
|
||||
self.answeredOrders = answeredOrders
|
||||
self.currentIndex = currentIndex
|
||||
collectionView = UICollectionView(frame: .zero, collectionViewLayout: Self.makeLayout())
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
/// 保留演示渲染测试的初始化入口,将本地试卷转换成轻量题号状态。
|
||||
convenience init(task: TrainingTask, answers: TrainingAnswers, currentIndex: Int) {
|
||||
let orders = Set(task.questions.enumerated().compactMap { index, question in
|
||||
(answers[question.id] ?? []).isEmpty ? nil : index + 1
|
||||
})
|
||||
self.init(questionCount: task.questions.count, answeredOrders: orders, currentIndex: currentIndex)
|
||||
}
|
||||
|
||||
/// 保持原有五列、52 点行高与 12 点间距,随可用宽度自动计算列宽。
|
||||
private static func makeLayout() -> UICollectionViewCompositionalLayout {
|
||||
UICollectionViewCompositionalLayout { _, environment in
|
||||
let columns = 5
|
||||
let spacing: CGFloat = 12
|
||||
let inset: CGFloat = 20
|
||||
let availableWidth = environment.container.effectiveContentSize.width - inset * 2
|
||||
let itemWidth = max(0, floor((availableWidth - spacing * CGFloat(columns - 1)) / CGFloat(columns)))
|
||||
let itemSize = NSCollectionLayoutSize(widthDimension: .absolute(itemWidth), heightDimension: .absolute(52))
|
||||
let item = NSCollectionLayoutItem(layoutSize: itemSize)
|
||||
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1), heightDimension: .absolute(52))
|
||||
let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, repeatingSubitem: item, count: columns)
|
||||
group.interItemSpacing = .fixed(spacing)
|
||||
let section = NSCollectionLayoutSection(group: group)
|
||||
section.interGroupSpacing = spacing
|
||||
section.contentInsets = NSDirectionalEdgeInsets(top: inset, leading: inset, bottom: inset, trailing: inset)
|
||||
return section
|
||||
}
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
title = "答题卡 · 蓝色为已答"
|
||||
navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak self] _ in self?.dismiss(animated: true) })
|
||||
collectionView.backgroundColor = AppColor.pageBackgroundSoft
|
||||
collectionView.delegate = self
|
||||
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "question")
|
||||
view.addSubview(collectionView)
|
||||
collectionView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
|
||||
dataSource = UICollectionViewDiffableDataSource<Int, Int>(collectionView: collectionView) { [weak self] collection, indexPath, index in
|
||||
guard let self else { return nil }
|
||||
let cell = collection.dequeueReusableCell(withReuseIdentifier: "question", for: indexPath)
|
||||
let answered = self.answeredOrders.contains(index + 1)
|
||||
var content = UIListContentConfiguration.cell()
|
||||
content.text = "\(index + 1)"
|
||||
content.textProperties.alignment = .center
|
||||
content.textProperties.color = answered ? AppColor.primary : AppColor.textSecondary
|
||||
content.directionalLayoutMargins = .zero
|
||||
cell.contentConfiguration = content
|
||||
cell.backgroundColor = answered ? AppColor.primaryLight : AppColor.cardBackground
|
||||
cell.layer.cornerRadius = 10
|
||||
cell.layer.borderWidth = index == self.currentIndex ? 2 : 0
|
||||
cell.layer.borderColor = AppColor.primary.cgColor
|
||||
cell.isAccessibilityElement = true
|
||||
cell.accessibilityLabel = "第 \(index + 1) 题,\(answered ? "已答" : "未答")\(index == self.currentIndex ? ",当前题" : "")"
|
||||
cell.accessibilityTraits = .button
|
||||
return cell
|
||||
}
|
||||
var snapshot = NSDiffableDataSourceSnapshot<Int, Int>()
|
||||
snapshot.appendSections([0])
|
||||
snapshot.appendItems(Array(0..<questionCount))
|
||||
dataSource.apply(snapshot, animatingDifferences: true)
|
||||
}
|
||||
}
|
||||
|
||||
extension TrainingAnswerCardViewController: UICollectionViewDelegate {
|
||||
/// 选中题号后关闭答题卡并通知考试页面跳转。
|
||||
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
|
||||
guard let index = dataSource.itemIdentifier(for: indexPath) else { return }
|
||||
let selection = onSelect
|
||||
dismiss(animated: true) { selection?(index) }
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 成绩概览、可展开解析和返回学习入口,历史记录只按最新任务状态提供重考。
|
||||
@MainActor
|
||||
final class TrainingResultViewController: TrainingBaseViewController {
|
||||
private let taskID: String
|
||||
private let attemptID: String
|
||||
private let service: any TrainingDataServing
|
||||
private let documentLoader: any TrainingDocumentLoading
|
||||
private let viewModel: TrainingRemoteResultViewModel
|
||||
private let validateIdentity: () -> Bool
|
||||
private var loadFailed = false
|
||||
private var showsDetails = false
|
||||
private var usesInitialDetail: Bool
|
||||
private var resultLoadTask: Task<Void, Never>?
|
||||
private var isRequestInFlight = false
|
||||
private var requestLoadingToken: UUID?
|
||||
private let scrollView = UIScrollView()
|
||||
private let contentStack = UIStackView()
|
||||
private let footer = UIView()
|
||||
private let actionButton = TrainingUI.button("完成,返回培训中心")
|
||||
|
||||
/// 使用记录 ID 读取最新本人任务,禁止通过后从旧失败记录继续重考。
|
||||
init(taskID: String, attemptID: String, service: any TrainingDataServing, initialDetail: TrainingAttemptDetail? = nil,
|
||||
documentLoader: any TrainingDocumentLoading = TrainingDocumentLoader()) {
|
||||
self.taskID = taskID
|
||||
self.attemptID = attemptID
|
||||
self.service = service
|
||||
self.documentLoader = documentLoader
|
||||
let session = AppStore.shared.session
|
||||
let scope = session.accountCachePrefix
|
||||
let token = session.token
|
||||
let scenicID = session.currentScenicId
|
||||
let storeID = session.currentStoreId
|
||||
validateIdentity = {
|
||||
let current = AppStore.shared.session
|
||||
return current.accountCachePrefix == scope && current.token == token
|
||||
&& current.currentScenicId == scenicID && current.currentStoreId == storeID
|
||||
}
|
||||
viewModel = TrainingRemoteResultViewModel(attemptID: attemptID, initialDetail: initialDetail)
|
||||
usesInitialDetail = initialDetail != nil
|
||||
super.init(nibName: nil, bundle: nil)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
override func setupNavigationBar() { TrainingUI.navigation(self, title: "考试结果") }
|
||||
|
||||
override func setupUI() {
|
||||
view.backgroundColor = TrainingUI.background
|
||||
contentStack.axis = .vertical
|
||||
contentStack.spacing = 12
|
||||
scrollView.addSubview(contentStack)
|
||||
view.addSubview(scrollView)
|
||||
footer.backgroundColor = .white
|
||||
let line = UIView()
|
||||
line.backgroundColor = TrainingUI.border
|
||||
footer.addSubview(line)
|
||||
line.snp.makeConstraints { $0.leading.trailing.top.equalToSuperview(); $0.height.equalTo(1) }
|
||||
footer.addSubview(actionButton)
|
||||
view.addSubview(footer)
|
||||
actionButton.accessibilityIdentifier = "training.result.action"
|
||||
}
|
||||
|
||||
override func setupConstraints() {
|
||||
footer.snp.makeConstraints { $0.leading.trailing.bottom.equalToSuperview() }
|
||||
actionButton.snp.makeConstraints {
|
||||
$0.leading.trailing.equalToSuperview().inset(12)
|
||||
$0.top.equalToSuperview().offset(10)
|
||||
$0.bottom.equalTo(view.safeAreaLayoutGuide).offset(-10)
|
||||
}
|
||||
scrollView.snp.makeConstraints { $0.top.leading.trailing.equalTo(view.safeAreaLayoutGuide); $0.bottom.equalTo(footer.snp.top) }
|
||||
contentStack.snp.makeConstraints {
|
||||
$0.edges.equalTo(scrollView.contentLayoutGuide).inset(UIEdgeInsets(top: 14, left: 13, bottom: 20, right: 13))
|
||||
$0.width.equalTo(scrollView.frameLayoutGuide).offset(-26)
|
||||
}
|
||||
}
|
||||
|
||||
override func bindActions() { actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside) }
|
||||
override func viewWillAppear(_ animated: Bool) {
|
||||
super.viewWillAppear(animated)
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
if usesInitialDetail, let detail = viewModel.detail {
|
||||
usesInitialDetail = false
|
||||
render(detail: detail)
|
||||
} else { loadResult() }
|
||||
}
|
||||
override func onSessionDidExpire() { navigationController?.popToRootViewController(animated: true) }
|
||||
|
||||
private func loadResult() { Task { @MainActor in await reload() } }
|
||||
|
||||
/// 页面出现时只刷新该次成绩,解析在用户展开后加载。
|
||||
func reload() async {
|
||||
if let resultLoadTask { await resultLoadTask.value; return }
|
||||
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews,
|
||||
!Task.isCancelled else { return }
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
let token = beginResultRequest()
|
||||
let task = Task<Void, Never> { @MainActor [weak self] in
|
||||
guard let self else { return }
|
||||
defer { finishResultRequest(token) }
|
||||
await performReload()
|
||||
}
|
||||
resultLoadTask = task
|
||||
await task.value
|
||||
resultLoadTask = nil
|
||||
}
|
||||
|
||||
private func performReload() async {
|
||||
await viewModel.load(service: service)
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
if let detail = viewModel.detail {
|
||||
loadFailed = false
|
||||
render(detail: detail)
|
||||
} else {
|
||||
loadFailed = true
|
||||
clearContent()
|
||||
contentStack.addArrangedSubview(TrainingUI.text(viewModel.errorMessage ?? "成绩加载失败", color: TrainingUI.muted))
|
||||
setActionTitle("重新加载")
|
||||
}
|
||||
}
|
||||
|
||||
/// 同步锁定请求动作,Loading 令牌只属于这一次真正发出的请求。
|
||||
private func beginResultRequest() -> UUID {
|
||||
isRequestInFlight = true
|
||||
contentStack.isUserInteractionEnabled = false
|
||||
actionButton.isUserInteractionEnabled = false
|
||||
let token = beginRequestLoading()
|
||||
requestLoadingToken = token
|
||||
return token
|
||||
}
|
||||
|
||||
/// 成功、失败和取消均释放原令牌,保持按钮正常外观。
|
||||
private func finishResultRequest(_ token: UUID) {
|
||||
endRequestLoading(token)
|
||||
guard requestLoadingToken == token else { return }
|
||||
requestLoadingToken = nil
|
||||
isRequestInFlight = false
|
||||
contentStack.isUserInteractionEnabled = true
|
||||
actionButton.isUserInteractionEnabled = true
|
||||
}
|
||||
|
||||
/// 导航前主动释放本页请求;离页后的旧 defer 可以安全再次结束同一令牌。
|
||||
private func finishCurrentRequestBeforeNavigation() {
|
||||
if let token = requestLoadingToken { finishResultRequest(token) }
|
||||
}
|
||||
|
||||
private func clearContent() {
|
||||
for child in contentStack.arrangedSubviews { contentStack.removeArrangedSubview(child); child.removeFromSuperview() }
|
||||
}
|
||||
|
||||
private func leaveInaccessibleTaskIfNeeded() -> Bool {
|
||||
let identityChanged = !validateIdentity() || viewModel.isIdentityInvalid
|
||||
guard identityChanged || viewModel.isAccessRevoked else { return false }
|
||||
finishCurrentRequestBeforeNavigation()
|
||||
clearContent()
|
||||
if !identityChanged,
|
||||
let center = navigationController?.viewControllers.first(where: { $0 is TrainingCenterViewController }) {
|
||||
navigationController?.popToViewController(center, animated: true)
|
||||
} else { navigationController?.popToRootViewController(animated: false) }
|
||||
return true
|
||||
}
|
||||
|
||||
private func setActionTitle(_ title: String) { var configuration = actionButton.configuration; configuration?.title = title; actionButton.configuration = configuration }
|
||||
|
||||
private func render(detail: TrainingAttemptDetail) {
|
||||
let attempt = detail.attempt
|
||||
clearContent()
|
||||
let summary = UIStackView()
|
||||
summary.axis = .vertical
|
||||
summary.spacing = 11
|
||||
summary.alignment = .center
|
||||
summary.backgroundColor = .white
|
||||
summary.layer.cornerRadius = 11
|
||||
summary.layer.borderWidth = 1
|
||||
summary.layer.borderColor = TrainingUI.border.cgColor
|
||||
summary.isLayoutMarginsRelativeArrangement = true
|
||||
summary.layoutMargins = UIEdgeInsets(top: 25, left: 12, bottom: 25, right: 12)
|
||||
let symbol = UIImageView(image: UIImage(systemName: attempt.passed ? "checkmark.circle.fill" : "info.circle.fill"))
|
||||
symbol.tintColor = attempt.passed ? TrainingUI.success : UIColor(red: 237/255, green: 140/255, blue: 36/255, alpha: 1)
|
||||
symbol.contentMode = .scaleAspectFit
|
||||
symbol.snp.makeConstraints { $0.size.equalTo(54) }
|
||||
summary.addArrangedSubview(symbol)
|
||||
let title = TrainingUI.text(attempt.passed ? "考试通过,学习任务已完成" : "本次未通过,再接再厉", size: 16.5, weight: .bold)
|
||||
title.textAlignment = .center
|
||||
summary.addArrangedSubview(title)
|
||||
let score = UIStackView(arrangedSubviews: [TrainingUI.text(attempt.scoreText, size: 46, weight: .bold, color: TrainingUI.primary), TrainingUI.text("/ 100 分", size: 13, color: TrainingUI.muted)])
|
||||
score.alignment = .firstBaseline
|
||||
score.spacing = 6
|
||||
score.snp.makeConstraints { $0.height.greaterThanOrEqualTo(69) }
|
||||
summary.addArrangedSubview(score)
|
||||
let dateLabel = TrainingUI.text("\(attempt.passScore) 分及格 · \(TrainingUI.date(attempt.submittedAt))", size: 12.5, color: TrainingUI.muted)
|
||||
dateLabel.textAlignment = .center
|
||||
summary.addArrangedSubview(dateLabel)
|
||||
contentStack.addArrangedSubview(summary)
|
||||
let counts = TrainingUI.card()
|
||||
let row = UIStackView(arrangedSubviews: [TrainingUI.text("答对 \(attempt.correctCount) 题"), TrainingUI.text("答错 \(attempt.questionCount - attempt.correctCount) 题")])
|
||||
row.distribution = .fillEqually
|
||||
for label in row.arrangedSubviews.compactMap({ $0 as? UILabel }) { label.textAlignment = .center }
|
||||
counts.addArrangedSubview(row)
|
||||
contentStack.addArrangedSubview(counts)
|
||||
let details = TrainingUI.button(showsDetails ? "收起答案解析" : "查看答案解析", secondary: true)
|
||||
details.accessibilityIdentifier = "training.result.details"
|
||||
details.addTarget(self, action: #selector(toggleDetails), for: .touchUpInside)
|
||||
details.isEnabled = attempt.reviewAvailable
|
||||
contentStack.addArrangedSubview(details)
|
||||
let learning = TrainingUI.button("返回学习", plain: true)
|
||||
learning.accessibilityIdentifier = "training.result.learning"
|
||||
learning.addTarget(self, action: #selector(returnToLearning), for: .touchUpInside)
|
||||
contentStack.addArrangedSubview(learning)
|
||||
if showsDetails && attempt.reviewAvailable {
|
||||
for review in viewModel.reviews {
|
||||
let card = TrainingUI.card()
|
||||
let top = UIStackView(arrangedSubviews: [TrainingUI.text("第 \(review.order) 题", size: 12.5, color: TrainingUI.muted), TrainingUI.text(review.isCorrect ? "回答正确" : "回答错误", size: 12, color: review.isCorrect ? TrainingUI.success : .systemRed)])
|
||||
top.distribution = .equalSpacing
|
||||
card.addArrangedSubview(top)
|
||||
card.addArrangedSubview(TrainingUI.text(review.stem, size: 15.5, weight: .semibold))
|
||||
for (optionIndex, option) in review.options.enumerated() {
|
||||
card.addArrangedSubview(TrainingUI.text("\(TrainingQuestion.optionLetter(optionIndex)). \(option.text)", size: 13.5, color: UIColor(red: 92/255, green: 108/255, blue: 132/255, alpha: 1)))
|
||||
}
|
||||
func letters(_ ids: Set<String>) -> String {
|
||||
let values = review.options.enumerated().compactMap { ids.contains($0.element.id) ? TrainingQuestion.optionLetter($0.offset) : nil }
|
||||
return values.isEmpty ? "未作答" : values.joined(separator: "、")
|
||||
}
|
||||
card.addArrangedSubview(TrainingUI.text("你的答案:\(letters(Set(review.selectedOptionIDs))) · 正确答案:\(letters(Set(review.correctOptionIDs)))", size: 12.5, color: TrainingUI.muted))
|
||||
card.addArrangedSubview(TrainingUI.notice(review.explanation.isEmpty ? "暂无解析" : review.explanation))
|
||||
contentStack.addArrangedSubview(card)
|
||||
}
|
||||
}
|
||||
if showsDetails && attempt.reviewAvailable {
|
||||
if let error = viewModel.reviewErrorMessage { contentStack.addArrangedSubview(TrainingUI.notice(error)) }
|
||||
if viewModel.isLoadingReviews { contentStack.addArrangedSubview(TrainingUI.text("正在加载解析…", color: TrainingUI.muted)) }
|
||||
if viewModel.hasMoreReviews || viewModel.reviewErrorMessage != nil {
|
||||
let more = TrainingUI.button(viewModel.reviewErrorMessage != nil ? "重试加载解析" : "加载更多解析", plain: true)
|
||||
more.accessibilityIdentifier = "training.result.reviews.more"
|
||||
more.addTarget(self, action: #selector(moreReviewsTapped), for: .touchUpInside)
|
||||
contentStack.addArrangedSubview(more)
|
||||
}
|
||||
}
|
||||
let canRetry = !attempt.passed && detail.taskState.learnerStatus == .pendingExam && detail.taskState.canRetry
|
||||
contentStack.addArrangedSubview(TrainingUI.text(canRetry ? "截止前可不限次数重考,每次成绩都会保留。" : "本次记录只读,可回顾课程内容和答案解析。", size: 12, color: TrainingUI.muted))
|
||||
setActionTitle(canRetry ? "再考一次" : "完成,返回培训中心")
|
||||
}
|
||||
|
||||
@objc private func toggleDetails() {
|
||||
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return }
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
guard let detail = viewModel.detail, detail.attempt.reviewAvailable else { return }
|
||||
showsDetails.toggle()
|
||||
render(detail: detail)
|
||||
guard showsDetails, !viewModel.hasLoadedReviews else { return }
|
||||
loadReviewPage(nextPage: false)
|
||||
}
|
||||
|
||||
@objc private func moreReviewsTapped() {
|
||||
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return }
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
loadReviewPage(nextPage: viewModel.hasLoadedReviews)
|
||||
}
|
||||
|
||||
/// 首次展开、翻页和失败重试才持有 Loading,已缓存解析切换不发请求。
|
||||
private func loadReviewPage(nextPage: Bool) {
|
||||
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews,
|
||||
viewModel.detail?.attempt.reviewAvailable == true else { return }
|
||||
if nextPage { guard viewModel.hasMoreReviews else { return } }
|
||||
else { guard !viewModel.hasLoadedReviews else { return } }
|
||||
let token = beginResultRequest()
|
||||
Task { @MainActor in
|
||||
defer { finishResultRequest(token) }
|
||||
await viewModel.loadReviews(service: service, nextPage: nextPage)
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
if let current = viewModel.detail { render(detail: current) }
|
||||
}
|
||||
}
|
||||
|
||||
/// 无论是否通过都能返回本次课程,优先复用导航栈中的课程页面。
|
||||
@objc private func returnToLearning() {
|
||||
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return }
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
guard viewModel.detail != nil, let navigationController else { return }
|
||||
finishCurrentRequestBeforeNavigation()
|
||||
if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) {
|
||||
navigationController.popToViewController(course, animated: true)
|
||||
} else {
|
||||
navigationController.pushViewController(TrainingCourseViewController(taskID: taskID, service: service, documentLoader: documentLoader), animated: true)
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func actionTapped() {
|
||||
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return }
|
||||
if leaveInaccessibleTaskIfNeeded() { return }
|
||||
if loadFailed { loadResult(); return }
|
||||
guard let detail = viewModel.detail, let navigationController else { return }
|
||||
finishCurrentRequestBeforeNavigation()
|
||||
if !detail.attempt.passed, detail.taskState.learnerStatus == .pendingExam, detail.taskState.canRetry {
|
||||
navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [TrainingExamViewController(taskID: taskID, service: service, resetDraft: true)], animated: true)
|
||||
} else if let center = navigationController.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
|
||||
navigationController.popToViewController(center, animated: true)
|
||||
} else { navigationController.setViewControllers([TrainingCenterViewController(service: service)], animated: true) }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 学习与考试共用的进度提示,两项等宽居中,仅突出当前步骤。
|
||||
@MainActor
|
||||
final class TrainingStepView: UIView {
|
||||
/// 当前页面对应的学习流程阶段。
|
||||
enum Step {
|
||||
case learning
|
||||
case exam
|
||||
}
|
||||
|
||||
private let learningLabel: UILabel
|
||||
private let nextLabel: UILabel
|
||||
|
||||
/// 创建只读步骤栏,任务模式可在课程详情返回后更新。
|
||||
init(currentStep: Step, mode: TrainingMode = .exam) {
|
||||
learningLabel = TrainingUI.text("1 课程学习", size: 13,
|
||||
weight: currentStep == .learning ? .semibold : .regular,
|
||||
color: currentStep == .learning ? TrainingUI.primary : TrainingUI.muted)
|
||||
nextLabel = TrainingUI.text(size: 13,
|
||||
weight: currentStep == .exam ? .semibold : .regular,
|
||||
color: currentStep == .exam ? TrainingUI.primary : TrainingUI.muted)
|
||||
super.init(frame: .zero)
|
||||
backgroundColor = UIColor(red: 237/255, green: 241/255, blue: 247/255, alpha: 1)
|
||||
layer.cornerRadius = 8
|
||||
accessibilityIdentifier = "training.steps"
|
||||
learningLabel.accessibilityIdentifier = "training.steps.learning"
|
||||
nextLabel.accessibilityIdentifier = "training.steps.next"
|
||||
for label in [learningLabel, nextLabel] { label.textAlignment = .center }
|
||||
let currentLabel = currentStep == .learning ? learningLabel : nextLabel
|
||||
currentLabel.accessibilityTraits.insert(.selected)
|
||||
currentLabel.accessibilityValue = "当前步骤"
|
||||
let stack = UIStackView(arrangedSubviews: [learningLabel, nextLabel])
|
||||
stack.axis = .horizontal
|
||||
stack.alignment = .center
|
||||
stack.distribution = .fillEqually
|
||||
addSubview(stack)
|
||||
stack.snp.makeConstraints {
|
||||
$0.edges.equalToSuperview().inset(UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12))
|
||||
}
|
||||
snp.makeConstraints { $0.height.greaterThanOrEqualTo(44) }
|
||||
configure(mode: mode)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 仅学习任务展示完成学习,考试任务展示在线考试。
|
||||
func configure(mode: TrainingMode) {
|
||||
nextLabel.text = mode == .exam ? "2 在线考试" : "完成学习"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
import SnapKit
|
||||
import UIKit
|
||||
|
||||
/// 与小程序培训页面一致的色彩、字体和内容间距。
|
||||
@MainActor
|
||||
enum TrainingUI {
|
||||
static let primary = UIColor(red: 35/255, green: 121/255, blue: 1, alpha: 1)
|
||||
static let background = UIColor(red: 245/255, green: 248/255, blue: 252/255, alpha: 1)
|
||||
static let textColor = UIColor(red: 23/255, green: 32/255, blue: 51/255, alpha: 1)
|
||||
static let muted = UIColor(red: 132/255, green: 145/255, blue: 166/255, alpha: 1)
|
||||
static let border = UIColor(red: 227/255, green: 235/255, blue: 245/255, alpha: 1)
|
||||
static let hintColor = UIColor(red: 189/255, green: 121/255, blue: 24/255, alpha: 1)
|
||||
static let hintBackground = UIColor(red: 1, green: 246/255, blue: 233/255, alpha: 1)
|
||||
static let success = UIColor(red: 21/255, green: 151/255, blue: 108/255, alpha: 1)
|
||||
|
||||
/// 创建支持系统字体缩放的标签。
|
||||
static func text(_ value: String = "", size: CGFloat = 14, weight: UIFont.Weight = .regular, color: UIColor = textColor) -> UILabel {
|
||||
let label = UILabel()
|
||||
label.text = value
|
||||
label.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: .systemFont(ofSize: size, weight: weight))
|
||||
label.adjustsFontForContentSizeCategory = true
|
||||
label.textColor = color
|
||||
label.numberOfLines = 0
|
||||
return label
|
||||
}
|
||||
|
||||
/// 为答题等现有页面保留语义字体入口。
|
||||
static func label(_ text: String = "", style: UIFont.TextStyle = .body, color: UIColor = textColor) -> UILabel {
|
||||
let label = self.text(text, color: color)
|
||||
label.font = .preferredFont(forTextStyle: style)
|
||||
return label
|
||||
}
|
||||
|
||||
/// 白色内容卡片使用细边框和统一内边距。
|
||||
static func card() -> UIStackView {
|
||||
let stack = UIStackView()
|
||||
stack.axis = .vertical
|
||||
stack.spacing = 10
|
||||
stack.backgroundColor = .white
|
||||
stack.layer.cornerRadius = 11
|
||||
stack.layer.borderWidth = 1
|
||||
stack.layer.borderColor = border.cgColor
|
||||
stack.layoutMargins = UIEdgeInsets(top: 14, left: 14, bottom: 14, right: 14)
|
||||
stack.isLayoutMarginsRelativeArrangement = true
|
||||
return stack
|
||||
}
|
||||
|
||||
/// 提示内容在浅橙背景中展示。
|
||||
static func notice(_ value: String, demo: Bool = false) -> UIStackView {
|
||||
let box = UIStackView(arrangedSubviews: [text(value, size: demo ? 11 : 12, color: hintColor)])
|
||||
box.axis = .vertical
|
||||
box.backgroundColor = hintBackground
|
||||
box.layer.cornerRadius = 6
|
||||
box.isLayoutMarginsRelativeArrangement = true
|
||||
box.layoutMargins = UIEdgeInsets(top: 9, left: 10, bottom: 9, right: 10)
|
||||
return box
|
||||
}
|
||||
|
||||
/// 明确标识本机演示边界。
|
||||
static func demoNotice() -> UIStackView {
|
||||
notice("开发演示 · 记录仅保存在本机,未同步景区后台", demo: true)
|
||||
}
|
||||
|
||||
/// 使用本地时区展示任务截止和考试时间。
|
||||
static func date(_ date: Date) -> String {
|
||||
let formatter = DateFormatter()
|
||||
formatter.locale = Locale(identifier: "zh_CN")
|
||||
formatter.dateFormat = "MM-dd HH:mm"
|
||||
return formatter.string(from: date)
|
||||
}
|
||||
|
||||
/// 培训专用按钮,文字缩放时高度随内容增加。
|
||||
static func button(_ title: String, secondary: Bool = false, plain: Bool = false, pill: Bool = false) -> UIButton {
|
||||
let button = UIButton(type: .system)
|
||||
var configuration = UIButton.Configuration.plain()
|
||||
configuration.title = title
|
||||
configuration.baseForegroundColor = plain || secondary ? primary : .white
|
||||
configuration.background.backgroundColor = plain ? .clear : secondary ? primary.withAlphaComponent(0.08) : primary
|
||||
configuration.background.cornerRadius = pill ? 24 : 11
|
||||
configuration.contentInsets = NSDirectionalEdgeInsets(top: plain ? 10 : 12, leading: 14, bottom: plain ? 10 : 12, trailing: 14)
|
||||
configuration.titleTextAttributesTransformer = UIConfigurationTextAttributesTransformer { incoming in
|
||||
var output = incoming
|
||||
output.font = UIFontMetrics(forTextStyle: .body).scaledFont(for: .systemFont(ofSize: 14, weight: plain ? .regular : .semibold))
|
||||
return output
|
||||
}
|
||||
button.configuration = configuration
|
||||
if !plain, !secondary {
|
||||
button.configurationUpdateHandler = { button in
|
||||
var updated = button.configuration
|
||||
updated?.background.backgroundColor = button.isEnabled ? primary : border
|
||||
updated?.baseForegroundColor = button.isEnabled ? .white : muted
|
||||
button.configuration = updated
|
||||
}
|
||||
}
|
||||
button.titleLabel?.adjustsFontForContentSizeCategory = true
|
||||
button.snp.makeConstraints { $0.height.greaterThanOrEqualTo(44) }
|
||||
return button
|
||||
}
|
||||
|
||||
/// 导航栏保持普通白色背景,入口使用文本与箭头。
|
||||
static func navigation(_ controller: UIViewController, title: String) {
|
||||
controller.title = title
|
||||
let appearance = UINavigationBarAppearance()
|
||||
appearance.configureWithOpaqueBackground()
|
||||
appearance.backgroundColor = .white
|
||||
appearance.shadowColor = .clear
|
||||
appearance.titleTextAttributes = [.font: UIFont.systemFont(ofSize: 17, weight: .medium), .foregroundColor: textColor]
|
||||
controller.navigationItem.standardAppearance = appearance
|
||||
controller.navigationItem.scrollEdgeAppearance = appearance
|
||||
controller.navigationItem.compactAppearance = appearance
|
||||
controller.navigationItem.backButtonDisplayMode = .minimal
|
||||
let back = UIButton(type: .system)
|
||||
back.tintColor = textColor
|
||||
back.setImage(UIImage(systemName: "chevron.left", withConfiguration: UIImage.SymbolConfiguration(pointSize: 20, weight: .medium)), for: .normal)
|
||||
back.accessibilityLabel = "返回"
|
||||
back.snp.makeConstraints { $0.size.equalTo(44) }
|
||||
back.addAction(UIAction { [weak controller] _ in controller?.navigationController?.popViewController(animated: true) }, for: .touchUpInside)
|
||||
let item = UIBarButtonItem(customView: back)
|
||||
if #available(iOS 26.0, *) { item.hidesSharedBackground = true }
|
||||
controller.navigationItem.leftBarButtonItem = item
|
||||
}
|
||||
}
|
||||
|
||||
/// 任务卡显示截止、考试信息、提示、进度条和对应的操作入口。
|
||||
@MainActor
|
||||
final class TrainingTaskCell: UITableViewCell {
|
||||
static let reuseIdentifier = "TrainingTaskCell"
|
||||
private let stack = TrainingUI.card()
|
||||
private let deadlineLabel = TrainingUI.text(size: 11.5, color: .systemRed)
|
||||
private let statusLabel = TrainingUI.text(size: 11, color: TrainingUI.primary)
|
||||
private let titleLabel = TrainingUI.text(size: 15.5, weight: .semibold)
|
||||
private let publisherLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
|
||||
private let metaLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
|
||||
private let hintLabel = TrainingUI.text(size: 12, color: TrainingUI.hintColor)
|
||||
private let progressView = UIProgressView(progressViewStyle: .bar)
|
||||
private let progressLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
|
||||
private let actionButton = TrainingUI.button("去学习", pill: true)
|
||||
private let footer = UIStackView()
|
||||
var onAction: (() -> Void)?
|
||||
|
||||
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
|
||||
super.init(style: style, reuseIdentifier: reuseIdentifier)
|
||||
backgroundColor = .clear
|
||||
selectionStyle = .none
|
||||
contentView.addSubview(stack)
|
||||
let deadline = UIStackView(arrangedSubviews: [deadlineLabel])
|
||||
deadline.backgroundColor = UIColor.systemRed.withAlphaComponent(0.06)
|
||||
deadline.layer.cornerRadius = 12
|
||||
deadline.isLayoutMarginsRelativeArrangement = true
|
||||
deadline.layoutMargins = UIEdgeInsets(top: 4, left: 8, bottom: 4, right: 8)
|
||||
let top = UIStackView(arrangedSubviews: [deadline, UIView(), statusLabel])
|
||||
top.alignment = .center
|
||||
top.spacing = 8
|
||||
statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
let hint = UIStackView(arrangedSubviews: [hintLabel])
|
||||
hint.backgroundColor = TrainingUI.hintBackground
|
||||
hint.layer.cornerRadius = 6
|
||||
hint.isLayoutMarginsRelativeArrangement = true
|
||||
hint.layoutMargins = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
|
||||
progressView.progressTintColor = TrainingUI.primary
|
||||
progressView.trackTintColor = TrainingUI.border
|
||||
progressView.layer.cornerRadius = 3
|
||||
progressView.clipsToBounds = true
|
||||
progressView.snp.makeConstraints { $0.height.equalTo(6) }
|
||||
footer.spacing = 12
|
||||
footer.alignment = .center
|
||||
footer.addArrangedSubview(progressLabel)
|
||||
footer.addArrangedSubview(actionButton)
|
||||
progressLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
|
||||
actionButton.setContentHuggingPriority(.defaultHigh, for: .horizontal)
|
||||
actionButton.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
actionButton.snp.makeConstraints { $0.width.greaterThanOrEqualTo(140).priority(750) }
|
||||
[top, titleLabel, publisherLabel, metaLabel, hint, progressView, footer].forEach(stack.addArrangedSubview)
|
||||
stack.setCustomSpacing(14, after: top)
|
||||
stack.setCustomSpacing(14, after: metaLabel)
|
||||
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 13, bottom: 10, right: 13)) }
|
||||
actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside)
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 每个任务始终可回顾课程,只有已读完且有效时直接进入考试。
|
||||
func configure(task: TrainingTask) {
|
||||
let presentation = TrainingTaskPresentation(task: task)
|
||||
titleLabel.text = task.title
|
||||
deadlineLabel.text = "截止时间:\(TrainingUI.date(task.endAt))"
|
||||
statusLabel.text = task.learnerStatus.title
|
||||
statusLabel.textColor = task.learnerStatus == .completed ? TrainingUI.success : TrainingUI.primary
|
||||
publisherLabel.text = "发布人:\(task.publisherText)"
|
||||
metaLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.questions.count) 题 · \(task.passScore) 分及格" : "仅学习"
|
||||
hintLabel.text = presentation.hint
|
||||
progressView.progress = Float(presentation.progressPercent) / 100
|
||||
progressLabel.text = "学习进度 \(presentation.progressPercent)%"
|
||||
var configuration = actionButton.configuration
|
||||
configuration?.title = presentation.actionTitle
|
||||
actionButton.configuration = configuration
|
||||
actionButton.accessibilityIdentifier = "training.task.action.\(task.id)"
|
||||
footer.axis = traitCollection.preferredContentSizeCategory.isAccessibilityCategory ? .vertical : .horizontal
|
||||
}
|
||||
|
||||
/// 正式任务卡只展示摘要和服务端资格,不由本地时钟推断是否可交卷。
|
||||
func configure(task: TrainingTaskSummary) {
|
||||
titleLabel.text = task.title
|
||||
deadlineLabel.text = task.endAt.map { "截止时间:\(TrainingUI.date($0))" } ?? "未设置截止时间"
|
||||
statusLabel.text = task.learnerStatus.title
|
||||
statusLabel.textColor = switch task.learnerStatus { case .pendingExam: TrainingUI.primary; case .completed: TrainingUI.success; case .ended: TrainingUI.muted }
|
||||
let publisher = task.publisherName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
|
||||
publisherLabel.text = "发布人:\(publisher.isEmpty ? "未记录" : publisher)"
|
||||
metaLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格" : "仅学习"
|
||||
let completed = task.learnerStatus == .completed
|
||||
let ended = task.learnerStatus == .ended
|
||||
hintLabel.text = ended ? "任务已结束,仅可回顾课程内容" : completed ? "已完成本次学习任务" : task.learning.canStartExam ? "课程已学完,可以开始考试" : task.learning.canStudy ? "请阅读课程,完成学习要求" : "任务暂不可提交,可回顾课程内容"
|
||||
let progress = min(100, max(0, task.learning.progressPercent))
|
||||
progressView.progress = Float(progress) / 100
|
||||
progressLabel.text = "学习进度 \(progress)%"
|
||||
var configuration = actionButton.configuration
|
||||
configuration?.title = ended || completed ? "回顾学习" : task.learning.canStartExam ? (task.learning.hasDraft ? "继续答题" : "开始考试") : task.learning.canStudy ? "去学习" : "查看课程"
|
||||
actionButton.configuration = configuration
|
||||
actionButton.isEnabled = task.learning.canViewCourse || (!ended && task.learning.canStartExam)
|
||||
actionButton.accessibilityIdentifier = "training.task.action.\(task.id)"
|
||||
footer.axis = traitCollection.preferredContentSizeCategory.isAccessibilityCategory ? .vertical : .horizontal
|
||||
}
|
||||
|
||||
@objc private func actionTapped() { onAction?() }
|
||||
}
|
||||
|
||||
/// 考试记录沿用小程序的标题、蓝色得分和通过状态卡片。
|
||||
@MainActor
|
||||
final class TrainingRecordCell: UITableViewCell {
|
||||
static let reuseIdentifier = "TrainingRecordCell"
|
||||
private let stack = TrainingUI.card()
|
||||
private let titleLabel = TrainingUI.text(weight: .semibold)
|
||||
private let scoreLabel = TrainingUI.text(weight: .semibold, color: TrainingUI.primary)
|
||||
private let detailLabel = TrainingUI.text(size: 11.5, color: TrainingUI.muted)
|
||||
private let statusLabel = TrainingUI.text(size: 11.5)
|
||||
|
||||
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
|
||||
super.init(style: style, reuseIdentifier: reuseIdentifier)
|
||||
backgroundColor = .clear
|
||||
selectionStyle = .none
|
||||
let top = UIStackView(arrangedSubviews: [titleLabel, scoreLabel])
|
||||
top.spacing = 12
|
||||
top.alignment = .top
|
||||
scoreLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
scoreLabel.setContentHuggingPriority(.required, for: .horizontal)
|
||||
titleLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
|
||||
let bottom = UIStackView(arrangedSubviews: [detailLabel, statusLabel])
|
||||
bottom.spacing = 12
|
||||
bottom.alignment = .top
|
||||
statusLabel.setContentCompressionResistancePriority(.required, for: .horizontal)
|
||||
statusLabel.setContentHuggingPriority(.required, for: .horizontal)
|
||||
detailLabel.setContentHuggingPriority(.defaultLow, for: .horizontal)
|
||||
stack.addArrangedSubview(top)
|
||||
stack.addArrangedSubview(bottom)
|
||||
contentView.addSubview(stack)
|
||||
stack.snp.makeConstraints { $0.edges.equalToSuperview().inset(UIEdgeInsets(top: 0, left: 13, bottom: 10, right: 13)) }
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
|
||||
|
||||
/// 展示已提交记录,点击后进入该次成绩。
|
||||
func configure(task: TrainingTask, attempt: TrainingAttempt) {
|
||||
titleLabel.text = task.title
|
||||
scoreLabel.text = "\(attempt.scoreText) 分"
|
||||
detailLabel.text = "\(TrainingUI.date(attempt.submittedAt)) · 答对 \(attempt.correctCount) / \(attempt.questionCount) 题"
|
||||
statusLabel.text = attempt.passed ? "已通过" : "未通过"
|
||||
statusLabel.textColor = attempt.passed ? TrainingUI.success : .systemRed
|
||||
}
|
||||
|
||||
/// 正式历史列表使用成绩摘要,不读取任务或完整解析。
|
||||
func configure(attempt: TrainingAttemptSummary) {
|
||||
titleLabel.text = attempt.taskTitle
|
||||
scoreLabel.text = "\(attempt.scoreText) 分"
|
||||
detailLabel.text = "\(TrainingUI.date(attempt.submittedAt)) · 答对 \(attempt.correctCount) / \(attempt.questionCount) 题"
|
||||
statusLabel.text = attempt.passed ? "已通过" : "未通过"
|
||||
statusLabel.textColor = attempt.passed ? TrainingUI.success : .systemRed
|
||||
}
|
||||
}
|
||||
|
||||
/// 培训页面在账号或景区切换时立即关闭,停止展示旧身份记录。
|
||||
@MainActor
|
||||
class TrainingBaseViewController: BaseViewController {
|
||||
private var requestLoadingTokens: Set<UUID> = []
|
||||
|
||||
/// 展示本页面请求持有的 App 通用 Loading,在完成或离开页面时释放。
|
||||
func beginRequestLoading() -> UUID {
|
||||
let token = GlobalLoadingManager.shared.beginRequest()
|
||||
requestLoadingTokens.insert(token)
|
||||
return token
|
||||
}
|
||||
|
||||
/// 只释放本页面持有的令牌,迟到请求不能关闭其它页面的 Loading。
|
||||
func endRequestLoading(_ token: UUID) {
|
||||
guard requestLoadingTokens.remove(token) != nil else { return }
|
||||
GlobalLoadingManager.shared.endRequest(token)
|
||||
}
|
||||
|
||||
override func viewWillDisappear(_ animated: Bool) {
|
||||
super.viewWillDisappear(animated)
|
||||
endOwnedRequestLoading()
|
||||
}
|
||||
|
||||
override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange, NotificationName.userDidLogout] {
|
||||
NotificationCenter.default.addObserver(self, selector: #selector(contextChanged), name: name, object: nil)
|
||||
}
|
||||
}
|
||||
|
||||
private func endOwnedRequestLoading() {
|
||||
for token in requestLoadingTokens { GlobalLoadingManager.shared.endRequest(token) }
|
||||
requestLoadingTokens = []
|
||||
}
|
||||
|
||||
@objc private func contextChanged() {
|
||||
endOwnedRequestLoading()
|
||||
navigationController?.popToRootViewController(animated: false)
|
||||
}
|
||||
}
|
||||
@@ -40,6 +40,45 @@ final class APIClientTests: XCTestCase {
|
||||
XCTAssertEqual(session.requests[0].value(forHTTPHeaderField: "token"), "test-token-abc")
|
||||
}
|
||||
|
||||
func testQueryPreservesOpaqueCursorWithPlusAndDoesNotEncodePercentTwice() async throws {
|
||||
let responseData = try TestJSON.envelope(data: AppConfigResponse(enableRegister: false))
|
||||
let session = MockURLSession(responses: [responseData])
|
||||
let client = APIClient(environment: .testing, session: session)
|
||||
let cursor = "base64+part/with=padding 中文"
|
||||
let literalPercent = "%2B already encoded text"
|
||||
|
||||
let _: AppConfigResponse = try await client.send(APIRequest(
|
||||
method: .get,
|
||||
path: "/api/app/config",
|
||||
queryItems: [
|
||||
URLQueryItem(name: "cursor", value: cursor),
|
||||
URLQueryItem(name: "literal", value: literalPercent),
|
||||
]
|
||||
))
|
||||
|
||||
let url = try XCTUnwrap(session.requests.first?.url)
|
||||
let components = try XCTUnwrap(URLComponents(url: url, resolvingAgainstBaseURL: false))
|
||||
let encodedQuery = try XCTUnwrap(components.percentEncodedQuery)
|
||||
XCTAssertFalse(encodedQuery.contains("+"))
|
||||
XCTAssertTrue(encodedQuery.contains("base64%2Bpart"))
|
||||
XCTAssertTrue(encodedQuery.contains("part/with%3Dpadding"), "保留原有斜线编码语义,等号仍作为值编码")
|
||||
XCTAssertTrue(encodedQuery.contains("%20"))
|
||||
XCTAssertTrue(encodedQuery.contains("%E4%B8%AD%E6%96%87"))
|
||||
XCTAssertTrue(encodedQuery.contains("literal=%252B%20"), "请求值中的字面百分号只编码一次")
|
||||
XCTAssertFalse(encodedQuery.contains("base64%252B"), "修正生成的 %2B 不能再次编码为 %252B")
|
||||
|
||||
// 模拟 PHP/Laravel 常见的 form-query 解析,区别于 URLComponents 对 + 的保留行为。
|
||||
let decodedPairs = encodedQuery.split(separator: "&").map { pair -> (String, String) in
|
||||
let parts = pair.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false)
|
||||
let name = String(parts[0]).replacingOccurrences(of: "+", with: " ").removingPercentEncoding ?? ""
|
||||
let value = String(parts[1]).replacingOccurrences(of: "+", with: " ").removingPercentEncoding ?? ""
|
||||
return (name, value)
|
||||
}
|
||||
let decoded = Dictionary(uniqueKeysWithValues: decodedPairs)
|
||||
XCTAssertEqual(decoded["cursor"], cursor, "加号、空格、斜线、等号和中文均须原样到达后端")
|
||||
XCTAssertEqual(decoded["literal"], literalPercent)
|
||||
}
|
||||
|
||||
func testSendThrowsServerCodeErrorForBusinessFailure() async throws {
|
||||
let responseData = try TestJSON.errorEnvelope(code: 100001, msg: "密码错误")
|
||||
let session = MockURLSession(responses: [responseData])
|
||||
@@ -97,6 +136,49 @@ final class APIClientTests: XCTestCase {
|
||||
await fulfillment(of: [expectation], timeout: 1)
|
||||
}
|
||||
|
||||
func testExpiredResponseFromReplacedTokenDoesNotExpireNewSession() async throws {
|
||||
let center = NotificationCenter()
|
||||
let expired = XCTNSNotificationExpectation(name: NotificationName.sessionDidExpire, object: nil, notificationCenter: center)
|
||||
expired.isInverted = true
|
||||
let token = APIClientTestTokenState("old-token")
|
||||
let session = APIClientExpiredResponseSession(
|
||||
response: try TestJSON.errorEnvelope(code: 100060, msg: "旧 Token 已失效"),
|
||||
beforeResponse: { token.value = "new-token" }
|
||||
)
|
||||
let client = APIClient(environment: .testing, session: session, notificationCenter: center)
|
||||
client.bindAuthTokenProvider { token.value }
|
||||
|
||||
do {
|
||||
let _: AppConfigResponse = try await client.send(APIRequest(method: .get, path: "/api/app/config"))
|
||||
XCTFail("旧请求仍须向调用者返回原始失败")
|
||||
} catch let APIError.serverCode(code, _) {
|
||||
XCTAssertEqual(code, 100060)
|
||||
}
|
||||
|
||||
let sentToken = await session.requestToken
|
||||
XCTAssertEqual(sentToken, "old-token")
|
||||
XCTAssertEqual(token.value, "new-token")
|
||||
await fulfillment(of: [expired], timeout: 0.1)
|
||||
}
|
||||
|
||||
func testExpiredResponseForCurrentTokenStillExpiresSession() async throws {
|
||||
let center = NotificationCenter()
|
||||
let expired = XCTNSNotificationExpectation(name: NotificationName.sessionDidExpire, object: nil, notificationCenter: center)
|
||||
let token = APIClientTestTokenState("current-token")
|
||||
let session = APIClientExpiredResponseSession(
|
||||
response: try TestJSON.errorEnvelope(code: 180024, msg: "Token 已失效"),
|
||||
beforeResponse: { token.value = "current-token" }
|
||||
)
|
||||
let client = APIClient(environment: .testing, session: session, notificationCenter: center)
|
||||
client.bindAuthTokenProvider { token.value }
|
||||
|
||||
_ = try? await client.send(APIRequest<AppConfigResponse>(method: .get, path: "/api/app/config"))
|
||||
|
||||
let sentToken = await session.requestToken
|
||||
XCTAssertEqual(sentToken, "current-token")
|
||||
await fulfillment(of: [expired], timeout: 1)
|
||||
}
|
||||
|
||||
func testMultipartUploadBuildsAndroidCompatibleRequest() async throws {
|
||||
let session = MockURLSession(responses: [try TestJSON.envelope(data: EmptyPayload())])
|
||||
let client = APIClient(
|
||||
@@ -152,3 +234,28 @@ final class APIClientTests: XCTestCase {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 网络等待期间可以切换的主 Actor 凭证,避免并发测试修改捕获变量。
|
||||
@MainActor
|
||||
private final class APIClientTestTokenState {
|
||||
var value: String
|
||||
init(_ value: String) { self.value = value }
|
||||
}
|
||||
|
||||
/// 在请求已发出、响应返回前切换会话,模拟真实账号切换时的迟到失败。
|
||||
private actor APIClientExpiredResponseSession: URLSessionProtocol {
|
||||
private let response: Data
|
||||
private let beforeResponse: @MainActor @Sendable () -> Void
|
||||
private(set) var requestToken: String?
|
||||
|
||||
init(response: Data, beforeResponse: @escaping @MainActor @Sendable () -> Void) {
|
||||
self.response = response
|
||||
self.beforeResponse = beforeResponse
|
||||
}
|
||||
|
||||
func data(for request: URLRequest) async throws -> (Data, URLResponse) {
|
||||
requestToken = request.value(forHTTPHeaderField: "token")
|
||||
await beforeResponse()
|
||||
return (response, HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -144,6 +144,78 @@ final class AllFunctionsViewModelTests: XCTestCase {
|
||||
|
||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["location_report", "report_photographer"])
|
||||
}
|
||||
|
||||
/// 培训权限不额外按账号类型过滤,并按持久化配置区分常用和更多。
|
||||
func testTrainingPermissionFollowsSavedGroupingForStoreAndScenicAccounts() throws {
|
||||
for accountType in [AppAccountType.storeUser, .scenicUser] {
|
||||
appStore.session.accountType = accountType
|
||||
appStore.session.roleCode = accountType == .storeUser ? AppRoleCode.storeAdmin.rawValue : AppRoleCode.photographer.rawValue
|
||||
appStore.permissions.savePermissionItems([
|
||||
HomePermissionItem(id: "wallet", name: "钱包", uri: "wallet"),
|
||||
HomePermissionItem(id: "training", name: "培训", uri: "training"),
|
||||
])
|
||||
menuStore.saveCommonURIs(["wallet"], accountScope: appStore.session.accountCachePrefix,
|
||||
roleCode: appStore.session.roleCode)
|
||||
let viewModel = AllFunctionsViewModel(appStore: appStore, commonMenuStore: menuStore)
|
||||
viewModel.loadFunctions()
|
||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet"])
|
||||
XCTAssertEqual(viewModel.moreMenus.map(\.uri), ["/training"])
|
||||
|
||||
let training = try XCTUnwrap(viewModel.moreMenus.first)
|
||||
viewModel.addToCommon(training)
|
||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "/training"])
|
||||
viewModel.removeFromCommon(training)
|
||||
viewModel.loadFunctions()
|
||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet"])
|
||||
XCTAssertEqual(viewModel.moreMenus.map(\.uri), ["/training"])
|
||||
}
|
||||
}
|
||||
|
||||
/// 撤回兼容的两种权限后隐藏旧记录,格式近似的 URI 不能授权培训。
|
||||
func testTrainingPermissionWithdrawalAndUnrecognizedURIsCannotExposeSavedEntry() {
|
||||
appStore.session.accountType = .storeUser
|
||||
appStore.session.roleCode = AppRoleCode.storeAdmin.rawValue
|
||||
menuStore.saveCommonURIs(["wallet", "/training"], accountScope: appStore.session.accountCachePrefix,
|
||||
roleCode: appStore.session.roleCode)
|
||||
appStore.permissions.savePermissionItems([
|
||||
HomePermissionItem(id: "wallet", name: "钱包", uri: "wallet"),
|
||||
HomePermissionItem(id: "training", name: "培训", uri: "/training"),
|
||||
])
|
||||
let viewModel = AllFunctionsViewModel(appStore: appStore, commonMenuStore: menuStore)
|
||||
viewModel.loadFunctions()
|
||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "/training"])
|
||||
|
||||
for trainingURI in [nil, "Training", " training", "training/", "/training/"] as [String?] {
|
||||
var permissions = [HomePermissionItem(id: "wallet", name: "钱包", uri: "wallet")]
|
||||
if let trainingURI { permissions.append(HomePermissionItem(id: "training", name: "培训", uri: trainingURI)) }
|
||||
appStore.permissions.savePermissionItems(permissions)
|
||||
viewModel.loadFunctions()
|
||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet"])
|
||||
XCTAssertTrue(viewModel.moreMenus.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
/// 在飞权限撤回后,迟到的列表快照不能把入口重新加入常用或更多。
|
||||
func testRevokedTrainingCannotBeMovedUsingStaleSnapshot() throws {
|
||||
let wallet = HomePermissionItem(id: "wallet", name: "钱包", uri: "wallet")
|
||||
let training = HomePermissionItem(id: "training", name: "培训", uri: "/training")
|
||||
for startsInCommon in [false, true] {
|
||||
appStore.permissions.savePermissionItems([wallet, training])
|
||||
menuStore.saveCommonURIs(startsInCommon ? ["wallet", "/training"] : ["wallet"],
|
||||
accountScope: appStore.session.accountCachePrefix, roleCode: appStore.session.roleCode)
|
||||
let viewModel = AllFunctionsViewModel(appStore: appStore, commonMenuStore: menuStore)
|
||||
viewModel.loadFunctions()
|
||||
let stale = try XCTUnwrap((viewModel.commonMenus + viewModel.moreMenus).first { $0.uri == "/training" })
|
||||
appStore.permissions.savePermissionItems([wallet])
|
||||
|
||||
if startsInCommon { viewModel.removeFromCommon(stale) }
|
||||
else { viewModel.addToCommon(stale) }
|
||||
|
||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet"])
|
||||
XCTAssertTrue(viewModel.moreMenus.isEmpty)
|
||||
XCTAssertFalse(viewModel.didCustomize)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 全部功能菜单卡片交互语义测试。
|
||||
|
||||
@@ -126,6 +126,34 @@ final class AppStoreModuleTests: XCTestCase {
|
||||
XCTAssertFalse(appStore.scenicQueue.useOfflineTTS)
|
||||
}
|
||||
|
||||
/// 权限通知归属于实际写入的 store,观察者可在收到时立即读到持久化快照。
|
||||
func testPermissionChangesNotifyMatchingStoreAfterPersistence() {
|
||||
selectAccount(userId: "permissions", type: .storeUser)
|
||||
let items = [HomePermissionItem(id: "training", name: "培训", uri: "/training")]
|
||||
let granted = expectation(description: "实际写入的权限 store 通知")
|
||||
let grantedObserver = NotificationCenter.default.addObserver(forName: NotificationName.permissionItemsDidChange,
|
||||
object: appStore.permissions, queue: nil) { notification in
|
||||
XCTAssertEqual((notification.object as? AppPermissionStore)?.permissionItems(), items)
|
||||
granted.fulfill()
|
||||
}
|
||||
granted.assertForOverFulfill = true
|
||||
let otherStore = AppStore(defaults: defaults)
|
||||
otherStore.permissions.savePermissionItems(items)
|
||||
appStore.permissions.savePermissionItems(items)
|
||||
wait(for: [granted], timeout: 1)
|
||||
NotificationCenter.default.removeObserver(grantedObserver)
|
||||
|
||||
let revoked = expectation(description: "撤回权限已持久化后通知")
|
||||
let revokedObserver = NotificationCenter.default.addObserver(forName: NotificationName.permissionItemsDidChange,
|
||||
object: appStore.permissions, queue: nil) { notification in
|
||||
XCTAssertEqual((notification.object as? AppPermissionStore)?.permissionItems(), [])
|
||||
revoked.fulfill()
|
||||
}
|
||||
defer { NotificationCenter.default.removeObserver(revokedObserver) }
|
||||
appStore.permissions.savePermissionItems([])
|
||||
wait(for: [revoked], timeout: 1)
|
||||
}
|
||||
|
||||
func testStoreAndQueueCachesAreIsolatedByScenicAndSpot() {
|
||||
selectAccount(userId: "1001", type: .scenicUser, scenicId: 22)
|
||||
appStore.session.currentStoreId = 220
|
||||
|
||||
@@ -24,6 +24,19 @@ final class DepositOrderListViewModelTests: XCTestCase {
|
||||
super.tearDown()
|
||||
}
|
||||
|
||||
func testOrderNotificationResetsFilters() {
|
||||
let viewModel = DepositOrderListViewModel()
|
||||
viewModel.onSearchTextChange("123", api: OrderAPI(client: APIClient(environment: .testing, session: MockURLSession(results: []))))
|
||||
viewModel.onFilterChange(tab: 18)
|
||||
viewModel.onDateRangeSelected(start: Date(), end: Date())
|
||||
viewModel.resetFiltersForOrderNotification()
|
||||
XCTAssertEqual(viewModel.searchText, "")
|
||||
XCTAssertEqual(viewModel.tabIndex, 0)
|
||||
XCTAssertEqual(viewModel.filterLabel, "全部")
|
||||
XCTAssertNil(viewModel.startTime)
|
||||
XCTAssertNil(viewModel.endTime)
|
||||
}
|
||||
|
||||
func testStoreFilterMapsPaidStatusToAPI20() {
|
||||
XCTAssertEqual(DepositOrderListViewModel.apiOrderStatus(forTabIndex: 18), 20)
|
||||
XCTAssertEqual(DepositOrderListViewModel.apiOrderStatus(forTabIndex: 30), 30)
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
Not a ZIP document
|
||||
@@ -0,0 +1,2 @@
|
||||
培训课程 GB18030
|
||||
中文内容正常显示。
|
||||
Binary file not shown.
@@ -0,0 +1,18 @@
|
||||
# 培训课程
|
||||
|
||||
这是 **Markdown** 附件内容。
|
||||
|
||||
- 服务规范
|
||||
- 现场安全
|
||||
|
||||
| 项目 | 要求 |
|
||||
|---|---|
|
||||
| 阅读 | 完整阅读 |
|
||||
|
||||
[外部资料](https://example.com/training)
|
||||
|
||||

|
||||
|
||||
<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>
|
||||
第二段正文。
|
||||
Binary file not shown.
@@ -51,4 +51,48 @@ final class GlobalLoadingManagerTests: XCTestCase {
|
||||
manager.hide()
|
||||
XCTAssertFalse(manager.isShowing)
|
||||
}
|
||||
|
||||
/// 清理旧请求后,旧响应的释放不能关闭新请求或普通 show 持有的 Loading。
|
||||
func testStaleRequestTokenDoesNotHideNewLoading() {
|
||||
let manager = GlobalLoadingManager.shared
|
||||
let previous = manager.beginRequest()
|
||||
manager.hideAll()
|
||||
let current = manager.beginRequest()
|
||||
manager.endRequest(previous)
|
||||
XCTAssertTrue(manager.isShowing)
|
||||
manager.endRequest(current)
|
||||
XCTAssertFalse(manager.isShowing)
|
||||
manager.show()
|
||||
manager.endRequest(current)
|
||||
XCTAssertTrue(manager.isShowing)
|
||||
manager.hide()
|
||||
XCTAssertFalse(manager.isShowing)
|
||||
}
|
||||
|
||||
/// 请求令牌与已有 show/hide 引用计数可以共存,重复结束不影响其它持有者。
|
||||
func testRequestTokensRespectOtherLoadingOwners() {
|
||||
let manager = GlobalLoadingManager.shared
|
||||
manager.show()
|
||||
let first = manager.beginRequest()
|
||||
let second = manager.beginRequest()
|
||||
manager.endRequest(first)
|
||||
manager.endRequest(first)
|
||||
XCTAssertTrue(manager.isShowing)
|
||||
manager.hide()
|
||||
XCTAssertTrue(manager.isShowing)
|
||||
manager.endRequest(second)
|
||||
XCTAssertFalse(manager.isShowing)
|
||||
}
|
||||
|
||||
/// 旧普通请求在全局清理后的迟到 hide 不能抵消新培训请求的独立票据。
|
||||
func testLateLegacyHideCannotEndRequestToken() {
|
||||
let manager = GlobalLoadingManager.shared
|
||||
manager.show()
|
||||
manager.hideAll()
|
||||
let current = manager.beginRequest()
|
||||
manager.hide()
|
||||
XCTAssertTrue(manager.isShowing)
|
||||
manager.endRequest(current)
|
||||
XCTAssertFalse(manager.isShowing)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,4 +103,56 @@ final class HomeCommonMenuStoreTests: XCTestCase {
|
||||
XCTAssertEqual(HomeMenuCatalog.item(for: "/scenic-queue")?.iconName, "person.3.fill")
|
||||
XCTAssertEqual(HomeMenuItem.moreFunctions.iconName, "ellipsis")
|
||||
}
|
||||
|
||||
/// 同时下发两种培训权限时保留第一条的位置与文案,不改变其它菜单重复行为。
|
||||
func testTrainingPermissionAliasesShareCatalogEntryAndKeepFirstPosition() {
|
||||
for aliases in [["training", "/training"], ["/training", "training"]] {
|
||||
let permissions = [
|
||||
HomePermissionItem(id: "cloud", name: "云盘", uri: "cloud_management"),
|
||||
HomePermissionItem(id: "training-first", name: "首次培训", uri: aliases[0]),
|
||||
HomePermissionItem(id: "wallet", name: "钱包", uri: "wallet"),
|
||||
HomePermissionItem(id: "training-second", name: "重复培训", uri: aliases[1]),
|
||||
HomePermissionItem(id: "wallet-again", name: "钱包重复", uri: "wallet"),
|
||||
]
|
||||
let menus = HomeMenuCatalog.visibleMenus(from: permissions)
|
||||
XCTAssertEqual(menus.map(\.uri), ["cloud_management", "/training", "wallet", "wallet"])
|
||||
XCTAssertEqual(menus[1].serverName, "首次培训")
|
||||
}
|
||||
XCTAssertEqual(HomeMenuCatalog.item(for: "training"), HomeMenuCatalog.item(for: "/training"))
|
||||
for invalid in ["Training", " training", "training/", "/training/"] {
|
||||
XCTAssertNil(HomeMenuCatalog.item(for: invalid))
|
||||
}
|
||||
}
|
||||
|
||||
/// 培训双形式在取默认前四项之前合并,未知项与其它重复项仍保留原语义。
|
||||
func testDefaultCommonURIsCanonicalizeTrainingBeforeTakingFirstFour() {
|
||||
let uris = ["training", "/training", "wallet", "cloud_management", "task_management", "system_settings"]
|
||||
let permissions = uris.enumerated().map { HomePermissionItem(id: "\($0.offset)", name: "菜单", uri: $0.element) }
|
||||
XCTAssertEqual(HomeCommonMenuStore.defaultCommonURIs(from: permissions), ["/training", "wallet", "cloud_management", "task_management"])
|
||||
XCTAssertEqual(HomeMenuCatalog.canonicalURIs(["unknown", "wallet", "wallet", "training", "/training"]),
|
||||
["unknown", "wallet", "wallet", "/training"])
|
||||
}
|
||||
|
||||
/// 兼容两种历史常用配置,读取时迁移并去重;分组始终使用内部 URI。
|
||||
func testSavedTrainingAliasesMigrateAndGroupWithEitherPermissionForm() {
|
||||
let key = "scenic_user_u1_role_photographer_common_uris"
|
||||
for saved in [["training"], ["/training"], ["training", "/training"], ["/training", "training"]] {
|
||||
defaults.set(["wallet"] + saved, forKey: key)
|
||||
XCTAssertEqual(store.savedCommonURIs(accountScope: "scenic_user_u1", roleCode: "photographer"), ["wallet", "/training"])
|
||||
XCTAssertEqual(defaults.stringArray(forKey: key), ["wallet", "/training"])
|
||||
for permissionURI in ["training", "/training"] {
|
||||
let menus = HomeMenuCatalog.visibleMenus(from: [
|
||||
HomePermissionItem(id: "wallet", name: "钱包", uri: "wallet"),
|
||||
HomePermissionItem(id: "training", name: "培训", uri: permissionURI),
|
||||
])
|
||||
let split = HomeCommonMenuStore.splitMenus(from: menus, commonURIs: ["wallet"] + saved)
|
||||
XCTAssertEqual(split.common.map(\.uri), ["wallet", "/training"])
|
||||
XCTAssertTrue(split.more.isEmpty)
|
||||
let common = store.commonMenus(from: menus, permissions: [], accountScope: "scenic_user_u1", roleCode: "photographer")
|
||||
XCTAssertEqual(common.map(\.uri), ["wallet", "/training"])
|
||||
}
|
||||
}
|
||||
store.saveCommonURIs(["training", "wallet", "/training"], accountScope: "scenic_user_u1", roleCode: "photographer")
|
||||
XCTAssertEqual(defaults.stringArray(forKey: key), ["/training", "wallet"])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -200,7 +200,7 @@ final class HomeViewModelTests: XCTestCase {
|
||||
|
||||
XCTAssertFalse(viewModel.showPermissionDialog)
|
||||
XCTAssertTrue(viewModel.isMinimalTopRole)
|
||||
XCTAssertEqual(viewModel.commonMenus.count, 2)
|
||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "cloud_management"])
|
||||
XCTAssertEqual(viewModel.storeItem?.name, "测试门店")
|
||||
}
|
||||
|
||||
@@ -231,6 +231,68 @@ final class HomeViewModelTests: XCTestCase {
|
||||
XCTAssertEqual(session.requests.count, 1)
|
||||
}
|
||||
|
||||
/// 账号类型和本地旧配置均不能替代后台下发的两种培训权限 URI。
|
||||
func testTrainingEntryRequiresRecognizedPermissionEvenForStoreAccountAndSavedMenu() {
|
||||
let menuStore = HomeCommonMenuStore(defaults: defaults)
|
||||
appStore.session.accountType = .storeUser
|
||||
appStore.session.roleCode = AppRoleCode.storeAdmin.rawValue
|
||||
menuStore.saveCommonURIs(["wallet", "/training"], accountScope: appStore.session.accountCachePrefix,
|
||||
roleCode: appStore.session.roleCode)
|
||||
let viewModel = HomeViewModel(appStore: appStore, commonMenuStore: menuStore)
|
||||
|
||||
for trainingURI in [nil, "Training", " training", "training/", "/training/"] as [String?] {
|
||||
var permissions = [HomePermissionItem(id: "wallet", name: "钱包", uri: "wallet")]
|
||||
if let trainingURI { permissions.append(HomePermissionItem(id: "training", name: "培训", uri: trainingURI)) }
|
||||
appStore.permissions.savePermissionItems(permissions)
|
||||
viewModel.rebuildCommonMenus()
|
||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet"])
|
||||
}
|
||||
XCTAssertEqual(menuStore.savedCommonURIs(accountScope: appStore.session.accountCachePrefix,
|
||||
roleCode: appStore.session.roleCode), ["wallet", "/training"])
|
||||
}
|
||||
|
||||
/// 菜单可见性只由权限控制;权限撤回后本地已保存的入口立即隐藏。
|
||||
func testTrainingPermissionIsVisibleForStoreAndScenicAccountsUntilWithdrawn() {
|
||||
let menuStore = HomeCommonMenuStore(defaults: defaults)
|
||||
let viewModel = HomeViewModel(appStore: appStore, commonMenuStore: menuStore)
|
||||
for accountType in [AppAccountType.storeUser, .scenicUser] {
|
||||
appStore.session.accountType = accountType
|
||||
appStore.session.roleCode = accountType == .storeUser ? AppRoleCode.storeAdmin.rawValue : AppRoleCode.photographer.rawValue
|
||||
for trainingURI in ["training", "/training"] {
|
||||
appStore.permissions.savePermissionItems([
|
||||
HomePermissionItem(id: "wallet", name: "钱包", uri: "wallet"),
|
||||
HomePermissionItem(id: "training", name: "培训", uri: trainingURI),
|
||||
])
|
||||
viewModel.rebuildCommonMenus()
|
||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet", "/training"])
|
||||
|
||||
appStore.permissions.savePermissionItems([HomePermissionItem(id: "wallet", name: "钱包", uri: "wallet")])
|
||||
viewModel.rebuildCommonMenus()
|
||||
XCTAssertEqual(viewModel.commonMenus.map(\.uri), ["wallet"])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 用户从全部功能移出培训后,首页继续尊重保存的常用分组。
|
||||
func testRemovingTrainingFromCommonMenusDoesNotForceItBackOnHome() throws {
|
||||
appStore.session.accountType = .storeUser
|
||||
appStore.session.roleCode = AppRoleCode.storeAdmin.rawValue
|
||||
appStore.permissions.savePermissionItems([
|
||||
HomePermissionItem(id: "wallet", name: "钱包", uri: "wallet"),
|
||||
HomePermissionItem(id: "training", name: "培训", uri: "/training"),
|
||||
])
|
||||
let menuStore = HomeCommonMenuStore(defaults: defaults)
|
||||
let functions = AllFunctionsViewModel(appStore: appStore, commonMenuStore: menuStore)
|
||||
functions.loadFunctions()
|
||||
functions.removeFromCommon(try XCTUnwrap(functions.commonMenus.first { $0.uri == "/training" }))
|
||||
let home = HomeViewModel(appStore: appStore, commonMenuStore: menuStore)
|
||||
|
||||
home.rebuildCommonMenus()
|
||||
|
||||
XCTAssertEqual(home.commonMenus.map(\.uri), ["wallet"])
|
||||
XCTAssertEqual(functions.moreMenus.map(\.uri), ["/training"])
|
||||
}
|
||||
|
||||
func testUnreadMessageStatusUsesCountEndpointAndUpdatesBadgeState() async {
|
||||
let api = HomeMessageCenterAPIMock()
|
||||
api.unreadCountResponses = [
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user