Commit e75e7749 by AppWaiBao

增加个推测试项目

parent bd0060e6
No preview for this file type
......@@ -28,16 +28,19 @@
D2BEE04858462B762CEC62FE /* AppConfig.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0761BDCFBF32BFC26470CEEB /* AppConfig.swift */; };
D8D1985C4269CD1AFF7F434D /* LoginView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D2904EB8426ED6563BA3276B /* LoginView.swift */; };
DAB50B4A799F32ECC81C4FD9 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = BE926DF3C407DF9E394E644C /* SettingsView.swift */; };
DB588BA5E2EC5F7CFC9AA8DB /* Pods_KFWDispatch.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 0248699672554D1BDA7E711F /* Pods_KFWDispatch.framework */; };
E2288D05A8BFC3E165CBECA1 /* AbnormalMonitor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 32BF94F0CDF6C80B96FFB6B8 /* AbnormalMonitor.swift */; };
FD1E30B82EF4DBFA468B87FA /* ring_fen_pei.mp3 in Resources */ = {isa = PBXBuildFile; fileRef = 0E50881C94F07014CB48207F /* ring_fen_pei.mp3 */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
0248699672554D1BDA7E711F /* Pods_KFWDispatch.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_KFWDispatch.framework; sourceTree = BUILT_PRODUCTS_DIR; };
0761BDCFBF32BFC26470CEEB /* AppConfig.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppConfig.swift; sourceTree = "<group>"; };
0E50881C94F07014CB48207F /* ring_fen_pei.mp3 */ = {isa = PBXFileReference; lastKnownFileType = audio.mp3; path = ring_fen_pei.mp3; sourceTree = "<group>"; };
0F8B7588EA941FA414E30B1E /* KFWDispatch.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = KFWDispatch.entitlements; sourceTree = "<group>"; };
1133F4DE113F617AA5C54DA6 /* KFWDispatchApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = KFWDispatchApp.swift; sourceTree = "<group>"; };
17AC1B79754D38F52052A046 /* KFWDispatch.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = KFWDispatch.app; sourceTree = BUILT_PRODUCTS_DIR; };
16DD1CFEFF8F250802A569D8 /* Pods-KFWDispatch.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-KFWDispatch.release.xcconfig"; path = "Target Support Files/Pods-KFWDispatch/Pods-KFWDispatch.release.xcconfig"; sourceTree = "<group>"; };
17AC1B79754D38F52052A046 /* KFWDispatch.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = KFWDispatch.app; sourceTree = BUILT_PRODUCTS_DIR; };
1ED5E6DFCC58E177378CA9A1 /* KFWDispatch-Release.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = "KFWDispatch-Release.entitlements"; sourceTree = "<group>"; };
2A9C73C6586171C2319D2B51 /* Components.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Components.swift; sourceTree = "<group>"; };
32BF94F0CDF6C80B96FFB6B8 /* AbnormalMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AbnormalMonitor.swift; sourceTree = "<group>"; };
......@@ -53,6 +56,7 @@
BBEB46791AA27DAF161E2A9F /* WebViewContainer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WebViewContainer.swift; sourceTree = "<group>"; };
BC633B5061BBA897508F4AB4 /* Network.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Network.swift; sourceTree = "<group>"; };
BE926DF3C407DF9E394E644C /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };
C5B6E225FA0881844AF276F1 /* Pods-KFWDispatch.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-KFWDispatch.debug.xcconfig"; path = "Target Support Files/Pods-KFWDispatch/Pods-KFWDispatch.debug.xcconfig"; sourceTree = "<group>"; };
CDF2BFCDD4BEA95A1C215EA1 /* AuthAPI.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AuthAPI.swift; sourceTree = "<group>"; };
CF684E82665B7846CFFF8638 /* ring_bobao.mp3 */ = {isa = PBXFileReference; lastKnownFileType = audio.mp3; path = ring_bobao.mp3; sourceTree = "<group>"; };
D02C9055BFA6100AE738B51B /* LoginViewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoginViewModel.swift; sourceTree = "<group>"; };
......@@ -61,6 +65,17 @@
FA3E18F8F1C71324CAE87CDD /* AbnormalFloatView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AbnormalFloatView.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
FF2C3752CCCA70363F217AF3 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
DB588BA5E2EC5F7CFC9AA8DB /* Pods_KFWDispatch.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
0473B5E0D0E313844D48931A /* Resources */ = {
isa = PBXGroup;
......@@ -84,6 +99,15 @@
path = Login;
sourceTree = "<group>";
};
3B26A9904CD21A2866BC71E4 /* Pods */ = {
isa = PBXGroup;
children = (
C5B6E225FA0881844AF276F1 /* Pods-KFWDispatch.debug.xcconfig */,
16DD1CFEFF8F250802A569D8 /* Pods-KFWDispatch.release.xcconfig */,
);
path = Pods;
sourceTree = "<group>";
};
52481169F1F7C376F93526B5 /* Push */ = {
isa = PBXGroup;
children = (
......@@ -126,6 +150,8 @@
children = (
DE47E0A13A703E01EB3ACDC9 /* KFWDispatch */,
AD3C3E4B8A230984A59FE070 /* Products */,
3B26A9904CD21A2866BC71E4 /* Pods */,
A786809923D48BFEEAA438C5 /* Frameworks */,
);
sourceTree = "<group>";
};
......@@ -141,6 +167,14 @@
path = UI;
sourceTree = "<group>";
};
A786809923D48BFEEAA438C5 /* Frameworks */ = {
isa = PBXGroup;
children = (
0248699672554D1BDA7E711F /* Pods_KFWDispatch.framework */,
);
name = Frameworks;
sourceTree = "<group>";
};
AD3C3E4B8A230984A59FE070 /* Products */ = {
isa = PBXGroup;
children = (
......@@ -221,16 +255,16 @@
isa = PBXNativeTarget;
buildConfigurationList = 0D299E3365FD39311EEC9DBA /* Build configuration list for PBXNativeTarget "KFWDispatch" */;
buildPhases = (
2AE2E22EA61F69540B7FF7FF /* [CP] Check Pods Manifest.lock */,
014F2FC37684FE21E9409E0D /* Sources */,
B5AEC4AFBD32091AE8BA90CE /* Resources */,
FF2C3752CCCA70363F217AF3 /* Frameworks */,
);
buildRules = (
);
dependencies = (
);
name = KFWDispatch;
packageProductDependencies = (
);
productName = KFWDispatch;
productReference = 17AC1B79754D38F52052A046 /* KFWDispatch.app */;
productType = "com.apple.product-type.application";
......@@ -283,6 +317,31 @@
};
/* End PBXResourcesBuildPhase section */
/* Begin PBXShellScriptBuildPhase section */
2AE2E22EA61F69540B7FF7FF /* [CP] Check Pods Manifest.lock */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
);
inputPaths = (
"${PODS_PODFILE_DIR_PATH}/Podfile.lock",
"${PODS_ROOT}/Manifest.lock",
);
name = "[CP] Check Pods Manifest.lock";
outputFileListPaths = (
);
outputPaths = (
"$(DERIVED_FILE_DIR)/Pods-KFWDispatch-checkManifestLockResult.txt",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
showEnvVarsInLog = 0;
};
/* End PBXShellScriptBuildPhase section */
/* Begin PBXSourcesBuildPhase section */
014F2FC37684FE21E9409E0D /* Sources */ = {
isa = PBXSourcesBuildPhase;
......@@ -434,13 +493,14 @@
};
C277D13873DFF016AD9FFC40 /* Debug */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = C5B6E225FA0881844AF276F1 /* Pods-KFWDispatch.debug.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = KFWDispatch/Resources/KFWDispatch.entitlements;
CODE_SIGN_IDENTITY = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 3;
DEVELOPMENT_TEAM = S3SN9ALHA9;
INFOPLIST_FILE = KFWDispatch/Resources/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.6;
......@@ -458,13 +518,14 @@
};
C73083744B6A8D947BC18643 /* Release */ = {
isa = XCBuildConfiguration;
baseConfigurationReference = 16DD1CFEFF8F250802A569D8 /* Pods-KFWDispatch.release.xcconfig */;
buildSettings = {
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
CODE_SIGN_ENTITLEMENTS = "KFWDispatch/Resources/KFWDispatch-Release.entitlements";
CODE_SIGN_IDENTITY = "iPhone Developer";
CODE_SIGN_STYLE = Automatic;
CURRENT_PROJECT_VERSION = 1;
CURRENT_PROJECT_VERSION = 3;
DEVELOPMENT_TEAM = S3SN9ALHA9;
INFOPLIST_FILE = KFWDispatch/Resources/Info.plist;
IPHONEOS_DEPLOYMENT_TARGET = 15.6;
......
<?xml version="1.0" encoding="UTF-8"?>
<Bucket
uuid = "99459E49-7451-405A-A74B-8AFDE5E1C76B"
type = "0"
version = "2.0">
<Breakpoints>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
uuid = "C0C2DB48-831A-4DDA-9761-53A3A3FA3213"
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "KFWDispatch/Network/AuthAPI.swift"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "28"
endingLineNumber = "28"
landmarkName = "login(mobile:password:)"
landmarkType = "7">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
uuid = "7496AE45-3B70-4CC3-9A43-C169169EF7FB"
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "KFWDispatch/Network/AuthAPI.swift"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "31"
endingLineNumber = "31"
landmarkName = "login(mobile:password:)"
landmarkType = "7">
</BreakpointContent>
</BreakpointProxy>
<BreakpointProxy
BreakpointExtensionID = "Xcode.Breakpoint.FileBreakpoint">
<BreakpointContent
uuid = "8291EB3E-0B3F-4AF9-B585-189E8C3A4C14"
shouldBeEnabled = "Yes"
ignoreCount = "0"
continueAfterRunningActions = "No"
filePath = "KFWDispatch/Network/AuthAPI.swift"
startingColumnNumber = "9223372036854775807"
endingColumnNumber = "9223372036854775807"
startingLineNumber = "24"
endingLineNumber = "24"
landmarkName = "login(mobile:password:)"
landmarkType = "7">
</BreakpointContent>
</BreakpointProxy>
</Breakpoints>
</Bucket>
import SwiftUI
/// 环境(对应安卓 configs.gradle 的 serverType)
enum AppEnvironment: String, CaseIterable {
/// 线上(正式环境)
case production
/// api4(测试/4 环境)
case api4
var hostURL: String {
switch self {
case .production: return "https://appmis.kfw.net/"
case .api4: return "https://appmis4.kfw.net/"
}
}
var displayName: String {
switch self {
case .production: return "线上"
case .api4: return "api4"
}
}
}
/// App 全局配置(对应安卓 AppConfig / configs.gradle)
enum AppConfig {
/// 包名(运行时自动读取,此处仅为兜底)
......@@ -15,12 +37,31 @@ enum AppConfig {
Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "1"
}
/// 服务器主机地址(对应安卓 configs.gradle 的 HOST_URL)
/// 注:当前后端只开放了 HTTPS,若需真机联调可临时改为 https://appmis4.kfw.net/
static let hostURL = "https://appmis4.kfw.net/"
private static let environmentKey = "kfw_environment"
/// 当前环境(可运行时切换,持久化到 UserDefaults;默认 api4 环境)
static var environment: AppEnvironment {
get {
if let raw = UserDefaults.standard.string(forKey: environmentKey),
let env = AppEnvironment(rawValue: raw) {
return env
}
return .api4
}
set {
UserDefaults.standard.set(newValue.rawValue, forKey: environmentKey)
}
}
/// 服务器主机地址(跟随当前环境)
static var hostURL: String {
environment.hostURL
}
/// 首页 H5 地址(对应安卓 HomeActivity 中硬编码的 url)
static let homeURL = "https://appmis4.kfw.net/index"
/// 首页 H5 地址(对应安卓 HomeActivity 的 url = HOST_URL + "index")
static var homeURL: String {
hostURL + "index"
}
/// 是否调试模式
static var isDebug: Bool {
......
......@@ -7,6 +7,7 @@ struct KFWDispatchApp: App {
var body: some Scene {
WindowGroup {
RootView()
.preferredColorScheme(.light) // 强制浅色,防止深色模式白底白字
}
}
}
......@@ -28,6 +28,9 @@ enum AuthAPI {
guard let login = res.data.data else {
throw APIError.business(code: res.data.code, message: "登录返回数据为空")
}
// 打印登录接口解析后的返回数据
NSLog("[KFWDispatch][登录返回] mobile=%@ userId=%d role=%d roleDesc=%@ groupId=%d",
login.mobile, login.userId, login.role, login.roleDesc, login.groupId)
return (login, res.cookie)
}
......
......@@ -31,8 +31,26 @@ struct HttpData<T: Decodable>: Decodable {
case data = "data"
}
/// 自定义解码:data 字段解析失败(如 `{}` 空对象、字段缺失)时容错为 nil,
/// 不阻断 code/msg/error 的读取,保证业务错误消息能透传出来。
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
code = try container.decode(String.self, forKey: .code)
msg = try container.decodeIfPresent(String.self, forKey: .msg)
error = try container.decodeIfPresent(String.self, forKey: .error)
// data 可能缺失、为 null、为空对象 `{}`,解析失败时不抛错,仅置 nil
data = try? container.decodeIfPresent(T.self, forKey: .data)
}
var isSuccess: Bool { code == "0000" }
var isTokenFailure: Bool { code == "2002" || code == "2100" }
/// 业务错误消息:优先取 resperr(安卓用 getError),为空再取 respmsg
var errorMessage: String {
if let error = error, !error.isEmpty { return error }
if let msg = msg, !msg.isEmpty { return msg }
return "请求失败"
}
}
/// 空数据占位(用于无 data 的接口,如退出登录)
......@@ -71,11 +89,29 @@ enum APIClient {
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
}
// 打印请求
NSLog("[KFWDispatch][请求] %@ %@", method, url.absoluteString)
if let body = body,
let json = try? JSONSerialization.data(withJSONObject: body),
let text = String(data: json, encoding: .utf8) {
NSLog("[KFWDispatch][请求体] %@", text)
}
let (data, response) = try await Self.session.data(for: request)
let http = response as? HTTPURLResponse
// 非 2xx 状态码:给出友好错误(如 403 通常是被 WAF/风控拦截)
// 打印响应状态码 + 原始响应体(后端返回的数据)
let rawText = String(data: data, encoding: .utf8) ?? ""
NSLog("[KFWDispatch][响应] status=%ld body=%@", http?.statusCode ?? -1, rawText)
// 非 2xx 状态码:优先透传后端 body 里的错误消息
if let status = http?.statusCode, !(200..<300).contains(status) {
if let dict = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {
let msg = (dict["respmsg"] as? String) ?? (dict["resperr"] as? String) ?? ""
if !msg.isEmpty {
throw APIError.business(code: "\(status)", message: msg)
}
}
if status == 403 {
throw APIError.business(code: "\(status)", message: "请求被服务器拒绝(403),可能触发安全风控,请稍后重试")
}
......@@ -97,7 +133,7 @@ enum APIClient {
throw APIError.tokenInvalid
}
if !result.isSuccess {
throw APIError.business(code: result.code, message: result.msg ?? result.error ?? "请求失败")
throw APIError.business(code: result.code, message: result.errorMessage)
}
return (result, setCookie)
}
......
import UIKit
import UserNotifications
import AVFoundation
#if canImport(GTSDK)
//#if canImport(GTSDK)
import GTSDK
#endif
//#endif
/// 对应安卓 GTPushService + PushMessageNotifier + KRingtoneManager。
/// 别名绑定保持和安卓一样:bindGtAlias() 整段是注释,不按 userId 绑定。
......@@ -73,25 +73,52 @@ final class PushService: NSObject {
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)
UNUserNotificationCenter.current().add(request)
}
/// 对应安卓 KRingtoneManager.playRingtone(KMessage):MS_003 用作废铃声,其余用分配铃声
private let ringtoneQueue = DispatchQueue(
label: "com.kfw.ringtone",
qos: .userInitiated
)
/// 对应安卓 KRingtoneManager.playRingtone(KMessage)
/// MS_003 使用作废铃声,其余使用分配铃声
private func playRingtone(code: String?) {
let name = code == "MS_003" ? "ring_zuo_fei" : "ring_fen_pei"
guard let url = Bundle.main.url(forResource: name, withExtension: "mp3") else { return }
do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(.playback, mode: .default)
try session.setActive(true)
player?.stop()
player = try AVAudioPlayer(contentsOf: url)
player?.play()
} catch {
player = nil
ringtoneQueue.async { [weak self] in
guard let self else { return }
let name = code == "MS_003" ? "ring_zuo_fei" : "ring_fen_pei"
guard let url = Bundle.main.url(
forResource: name,
withExtension: "mp3"
) else {
NSLog("[GT_PUSH] 铃声文件不存在: %@", name)
return
}
do {
let session = AVAudioSession.sharedInstance()
try session.setCategory(.playback, mode: .default)
try session.setActive(true)
self.player?.stop()
let newPlayer = try AVAudioPlayer(contentsOf: url)
newPlayer.prepareToPlay()
self.player = newPlayer
if !newPlayer.play() {
NSLog("[GT_PUSH] 铃声启动失败: %@", name)
}
} catch {
NSLog("[GT_PUSH] 铃声播放失败: %@", "\(error)")
self.player = nil
}
}
}
}
#if canImport(GTSDK)
//#if canImport(GTSDK)
extension PushService: GeTuiSdkDelegate {
func geTuiSdkDidRegisterClient(_ clientId: String) {
NSLog("个推 cid = \(clientId)")
......@@ -139,7 +166,7 @@ extension PushService: GeTuiSdkDelegate {
completionHandler?(.noData)
}
}
#endif
//#endif
/// 对应安卓 KMessage
struct KMessage: Decodable {
......
......@@ -4,6 +4,14 @@
"filename" : "icon_right.png",
"idiom" : "universal",
"scale" : "1x"
},
{
"idiom" : "universal",
"scale" : "2x"
},
{
"idiom" : "universal",
"scale" : "3x"
}
],
"info" : {
......
......@@ -19,7 +19,7 @@
<key>CFBundleShortVersionString</key>
<string>1.0.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<string>2</string>
<key>ITSAppUsesNonExemptEncryption</key>
<false/>
<key>NSAppTransportSecurity</key>
......@@ -37,5 +37,7 @@
<array>
<string>UIInterfaceOrientationPortrait</string>
</array>
<key>UIUserInterfaceStyle</key>
<string>Light</string>
</dict>
</plist>
import SwiftUI
import WebKit
/// 异常订单监控设置页(对应安卓 AbnormalSettingActivity,H5 gotoSetting 的目标页)
struct AbnormalSettingView: View {
......@@ -9,6 +10,7 @@ struct AbnormalSettingView: View {
@State private var showLogoutConfirm = false
@State private var toastMessage: String?
@State private var showEnvSwitcher = false
private var roleText: String {
let value = UserCache.shared.roleDesc
......@@ -50,7 +52,16 @@ struct AbnormalSettingView: View {
}
.buttonStyle(CapsuleButtonStyle())
.padding(.horizontal, 50)
.padding(.bottom, 30)
// 隐藏的环境切换入口:连点「退出登录」下方这块区域超过 5 次触发
Color.clear
.frame(height: 200)
.contentShape(Rectangle())
.onTapGesture(count: 5) {
showEnvSwitcher = true
}
Spacer().frame(height: 20)
}
}
}
......@@ -67,10 +78,36 @@ struct AbnormalSettingView: View {
Button("退出登录", role: .destructive) { logout() }
Button("取消", role: .cancel) {}
}
.confirmationDialog(
"切换环境(当前:\(AppConfig.environment.displayName))",
isPresented: $showEnvSwitcher,
titleVisibility: .visible
) {
ForEach(AppEnvironment.allCases, id: \.self) { env in
Button(env.displayName + (env == AppConfig.environment ? "(当前)" : "")) {
switchEnvironment(to: env)
}
}
Button("取消", role: .cancel) {}
}
}
.navigationViewStyle(.stack)
}
/// 切换环境:保存 → 清登录态和 H5 缓存 → 回登录页重新登录(等效重启)
private func switchEnvironment(to env: AppEnvironment) {
guard env != AppConfig.environment else { return }
AppConfig.environment = env
CommonSDCache.shared.cookie = ""
// 清 H5 的 Cookie 与缓存,避免旧环境会话串扰
WKWebsiteDataStore.default().removeData(
ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(),
modifiedSince: .distantPast
) {}
SessionManager.shared.logout()
dismiss()
}
private func toggleRow(_ title: String, isOn: Binding<Bool>) -> some View {
HStack(spacing: 0) {
Text(title)
......
import SwiftUI
import WebKit
/// 登录页(1:1 对应安卓 LoginActivity + login_activity.xml)
struct LoginView: View {
@StateObject private var viewModel = LoginViewModel()
@FocusState private var focusedField: Field?
@State private var showEnvSwitcher = false
private enum Field { case phone, password }
......@@ -78,6 +80,14 @@ struct LoginView: View {
}
.padding(.top, 20)
}
// 底部隐藏环境切换入口:连点 5 下触发
Color.clear
.frame(height: 50)
.contentShape(Rectangle())
.onTapGesture(count: 5) {
showEnvSwitcher = true
}
}
.background(Color.white)
.navigationBarHidden(true)
......@@ -86,6 +96,18 @@ struct LoginView: View {
} message: {
Text(viewModel.errorMessage ?? "")
}
.confirmationDialog(
"切换环境(当前:\(AppConfig.environment.displayName))",
isPresented: $showEnvSwitcher,
titleVisibility: .visible
) {
ForEach(AppEnvironment.allCases, id: \.self) { env in
Button(env.displayName + (env == AppConfig.environment ? "(当前)" : "")) {
switchEnvironment(to: env)
}
}
Button("取消", role: .cancel) {}
}
}
.navigationViewStyle(.stack)
.onAppear {
......@@ -100,4 +122,15 @@ struct LoginView: View {
#endif
}
}
/// 切换环境:保存 → 清登录态和 H5 缓存(重启走新环境)
private func switchEnvironment(to env: AppEnvironment) {
guard env != AppConfig.environment else { return }
AppConfig.environment = env
CommonSDCache.shared.cookie = ""
WKWebsiteDataStore.default().removeData(
ofTypes: WKWebsiteDataStore.allWebsiteDataTypes(),
modifiedSince: .distantPast
) {}
}
}
......@@ -42,7 +42,9 @@ targets:
properties:
CFBundleDisplayName: 快服务调度端
CFBundleShortVersionString: "1.0.0"
CFBundleVersion: "1"
CFBundleVersion: "2"
# 锁定浅色外观,避免深色模式下输入框文字与白色背景同色导致看不清
UIUserInterfaceStyle: Light
UILaunchScreen: {}
UISupportedInterfaceOrientations:
- UIInterfaceOrientationPortrait
......
# 在个推开发者中心 > 消息推送 > 配置管理 > 应用配置中查看
# 在个推开发者中心 > 消息推送 > 配置管理 > 应用配置中查看
GETUI_APP_ID=wNIKbIYrHV8bOJDaAaiI07
GETUI_APP_KEY=u1QjJm3cIg65wGXiJL1sE3
GETUI_MASTER_SECRET=EVTBtQ4s3bAM5uiDpsYOZ2
# 在 iOS GeTuiSdkDidRegisterClient 回调中获得
GETUI_TEST_CID=129c6b6879e8e4cc87d276ff861f19dd
# 默认端口:8765
PORT=8765
.env
.env
__pycache__/
*.pyc
.DS_Store
# KMessage iOS 本地测试推送后端
# KMessage iOS 本地测试推送后端
这是一个可在 Mac 上直接运行、没有外部 Python 依赖的单设备测试工具,使用个推 REST API V2。
## 运行
```bash
cd getui-ios-push-test-v2
cp .env.example .env
open -e .env
python3 server.py
```
`.env` 填写:`GETUI_APP_ID`、`GETUI_APP_KEY`、`GETUI_MASTER_SECRET`、可选 `GETUI_TEST_CID`。**MasterSecret 是后端密钥,不是 iOS 客户端使用的 AppSecret。不要提交到 Git,也不要发给其他人。**
浏览器打开 `http://127.0.0.1:8765`。如果端口已被占用,检查是否已在浏览器打开;或执行 `PORT=8766 python3 server.py`,访问 `http://127.0.0.1:8766`。仅监听 Mac 本机 `127.0.0.1`,请勿公网暴露。
## 消息格式
后端生成的在线透传 `push_message.transmission` 与离线 APNs `push_channel.ios.payload` 都是 **同一份字符串形式的 JSON**,与 Android KMessage 字段一致:
```json
{
"msg_id": 10001,
"code": "MS_001",
"r_url": "",
"time": 1795417200000,
"detail": {},
"play_type": "local"
}
```
- `MS_001` 骑士接单;`MS_002` 订单释放;`MS_003` 订单取消;`MS_004` 完成订单。
- `msg_id` 是符合 Java `int` 范围的正整数,默认由后端随机生成;`time` 为发送时的当前毫秒时间戳。
- `detail` **必须根据你们真实的 `MessageDetail.java` 填写**;这里 `{}` 仅用于连通性测试,不能证明业务解析与订单跳转可用。
- `play_type="local"` 会使 Android `isLocal()` 返回 true,进而尝试播放本地铃声;iOS 端是否播放要看 iOS 自己的实现。
- 默认标题为“订单提醒”,不再包含平台此前拦截的敏感词“个推”。如果再遇到 `20001` 的敏感词报错,检查标题、正文及业务字段。
## 接收验证
iOS 端 `GeTuiSdkDelegate` 可打印以下两类回调(**添加到已存在且已作为 SDK delegate 的类中,不要重复设置代理或重复调用 completionHandler**):
```objc
// 在线个推透传
- (void)GeTuiSdkDidReceiveSlience:(NSDictionary *)userInfo
fromGetui:(BOOL)fromGetui
offLine:(BOOL)offLine
appId:(NSString *)appId
taskId:(NSString *)taskId
msgId:(NSString *)msgId
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(@"[GT_PUSH] 透传 offLine=%d fromGetui=%d userInfo=%@", offLine, fromGetui, userInfo);
if (completionHandler) completionHandler(UIBackgroundFetchResultNoData);
}
// APNs 通知(包括点击)
- (void)GeTuiSdkDidReceiveNotification:(NSDictionary *)userInfo
notificationCenter:(UNUserNotificationCenter *)center
response:(UNNotificationResponse *)response
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
NSLog(@"[GT_PUSH] APNs response=%@ userInfo=%@", response, userInfo);
if (completionHandler) completionHandler(UIBackgroundFetchResultNoData);
}
```
`userInfo` 是字典,业务 JSON 通常位于 SDK 传回的 `payload` 字段,具体根据你当前 SDK 版本和实际日志解析,不要直接把整个 `userInfo` 当成 KMessage。测试前台时注意 iOS 个推透传通常不自动弹系统横幅;测试后台/锁屏是否收到通知请看手机系统通知界面。后台收到 APNs 不意味着一定执行业务代码:通知点击、应用启动或后续透传到达才是业务处理的常见时机。
### Curl
```bash
curl -sS -X POST http://127.0.0.1:8765/api/send \
-H 'Content-Type: application/json' \
-d '{"cid":"替换为手机CID","title":"订单提醒","body":"骑士接单事件测试","code":"MS_001","play_type":"local","detail":{}}'
```
## 本地测试
```bash
python3 -m unittest discover -s tests -v
```
**API `code=0` 表示个推平台接受推送请求,并不能保证消息最终送达设备。** 建议结合手机通知、Xcode 日志以及开发者中心的送达记录排查。APNs 证书/密钥需已配置在**对应的个推应用**,并与 Bundle ID 和 Debug/TestFlight 环境匹配。不要把 APNs Token 当做个推 CID。
**参考官方文档:**
- https://docs.getui.com/getui/server/rest_v2/common_args/
- https://docs.getui.com/getui/server/rest_v2/push/
- https://docs.getui.com/getui/scene/push/
- https://docs.getui.com/getui/mobile/ios/api/
"""GeTui REST V2 testing client. Python stdlib only; sends KMessage-compatible data."""
"""GeTui REST V2 testing client. Python stdlib only; sends KMessage-compatible data."""
from __future__ import annotations
import hashlib
import json
import secrets
import time
import uuid
from urllib import error, request
MESSAGE_CODES = {
"MS_001": "骑士接单",
"MS_002": "订单释放",
"MS_003": "订单取消",
"MS_004": "完成订单",
}
class GeTuiError(Exception):
pass
def make_kmessage(
code: str = "MS_001", *, msg_id: int | None = None, report_url: str = "",
timestamp: int | None = None, detail: dict | None = None,
play_type: str = "local",
) -> dict:
"""Match Java's @SerializedName fields. Detail shape must come from MessageDetail.java."""
if code not in MESSAGE_CODES:
raise ValueError(f"code 必须是 {', '.join(MESSAGE_CODES)} 之一")
if msg_id is None:
msg_id = secrets.randbelow(2_000_000_000) + 1 # safe within Java signed int
if isinstance(msg_id, bool) or not isinstance(msg_id, int) or not (1 <= msg_id <= 2_147_483_647):
raise ValueError("msg_id 必须是 1 到 2147483647 之间的整数")
if timestamp is None:
timestamp = int(time.time() * 1000)
if isinstance(timestamp, bool) or not isinstance(timestamp, int) or timestamp <= 0:
raise ValueError("time 必须是正整数毫秒时间戳")
if not isinstance(report_url, str) or len(report_url) > 1000:
raise ValueError("r_url 必须是长度不超过 1000 的字符串")
if detail is None:
detail = {}
if not isinstance(detail, dict):
raise ValueError("detail 必须是 JSON 对象")
if play_type not in ("local", "remote"):
raise ValueError("play_type 只能是 local 或 remote")
return {
"msg_id": msg_id,
"code": code,
"r_url": report_url,
"time": timestamp,
"detail": detail,
"play_type": play_type,
}
class GeTuiClient:
def __init__(self, app_id: str, app_key: str, master_secret: str, timeout: int = 15):
self.app_id = app_id.strip()
self.app_key = app_key.strip()
self.master_secret = master_secret.strip()
if not all((self.app_id, self.app_key, self.master_secret)):
raise ValueError("请先在 .env 配置 GETUI_APP_ID、GETUI_APP_KEY、GETUI_MASTER_SECRET")
self.base_url = f"https://restapi.getui.com/v2/{self.app_id}"
self.timeout = timeout
self._token = None
self._expire_ms = 0
def _post(self, path: str, payload: dict, token: str | None = None) -> dict:
headers = {"Content-Type": "application/json;charset=UTF-8"}
if token:
headers["token"] = token
req = request.Request(
self.base_url + path,
data=json.dumps(payload, ensure_ascii=False).encode("utf-8"),
headers=headers,
method="POST",
)
try:
with request.urlopen(req, timeout=self.timeout) as response:
content = response.read().decode("utf-8")
except error.HTTPError as exc:
details = exc.read(2000).decode("utf-8", errors="replace")
try:
response = json.loads(details)
message = response.get("msg", details)
if "sensitive word" in str(message):
raise GeTuiError(f"平台敏感词过滤:{message}。检查标题、正文及 detail 内容。") from exc
raise GeTuiError(f"GeTui HTTP {exc.code}, code={response.get('code')}: {message}") from exc
except (ValueError, TypeError):
raise GeTuiError(f"GeTui HTTP {exc.code}: {details[:400]}") from exc
except (error.URLError, TimeoutError) as exc:
raise GeTuiError(f"连接 GeTui 失败:{exc}") from exc
try:
result = json.loads(content)
if not isinstance(result, dict):
raise ValueError("not object")
return result
except (ValueError, TypeError) as exc:
raise GeTuiError(f"个推返回非 JSON 对象:{content[:400]}") from exc
def get_token(self, force_refresh: bool = False) -> str:
now_ms = int(time.time() * 1000)
if not force_refresh and self._token and now_ms < self._expire_ms - 60000:
return self._token
timestamp = str(now_ms)
sign = hashlib.sha256((self.app_key + timestamp + self.master_secret).encode("utf-8")).hexdigest()
result = self._post("/auth", {"sign": sign, "timestamp": timestamp, "appkey": self.app_key})
if result.get("code") != 0:
raise GeTuiError(f"个推鉴权失败:{result.get('code')} {result.get('msg', '')}")
data = result.get("data") or {}
token = data.get("token")
if not token:
raise GeTuiError("个推鉴权没有返回 token")
self._token = str(token)
self._expire_ms = int(data.get("expire_time") or 0)
return self._token
@staticmethod
def build_push_body(cid: str, title: str, body: str, message: dict) -> dict:
if not isinstance(cid, str) or not cid.strip():
raise ValueError("CID 不能为空")
if not isinstance(title, str) or not title.strip() or len(title) > 50:
raise ValueError("标题长度需为 1-50 字")
if not isinstance(body, str) or not body.strip() or len(body) > 256:
raise ValueError("正文长度需为 1-256 字")
if not isinstance(message, dict):
raise ValueError("业务消息必须是 JSON 对象")
# Explicit validation; never alter identifiers or business data silently.
message = make_kmessage(
code=message.get("code"),
msg_id=message.get("msg_id"),
report_url=message.get("r_url", ""),
timestamp=message.get("time"),
detail=message.get("detail"),
play_type=message.get("play_type", "local"),
)
payload = json.dumps(message, ensure_ascii=False, separators=(",", ":"))
if len(payload.encode("utf-8")) > 3000:
raise ValueError("业务消息体过大,请减少 detail 字段(限制 3000 字节)")
return {
"request_id": uuid.uuid4().hex,
"settings": {"ttl": 7200000},
"audience": {"cid": [cid.strip()]},
"push_message": {"transmission": payload},
"push_channel": {
"ios": {
"type": "notify",
"payload": payload,
"aps": {
"alert": {"title": title.strip(), "body": body.strip()},
"content-available": 0,
"sound": "default",
},
}
},
}
def push_to_cid(self, cid: str, title: str, body: str, message: dict) -> dict:
payload = self.build_push_body(cid, title, body, message)
for attempt in range(2):
response = self._post("/push/single/cid", payload, self.get_token())
if response.get("code") == 10001 and attempt == 0:
self.get_token(force_refresh=True)
continue
if response.get("code") != 0:
raise GeTuiError(f"个推拒绝请求:{response.get('code')} {response.get('msg', '')}")
return {
"request_id": payload["request_id"],
"getui_result": response,
"message": json.loads(payload["push_message"]["transmission"]),
}
raise GeTuiError("token 重试失败")
<!doctype html>
<!doctype html>
<html lang="zh-CN">
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>KMessage 推送调试</title>
<style>
:root{font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;background:#f4f6f9;color:#162236}
main{max-width:750px;margin:36px auto;padding:0 16px}.card{background:#fff;border-radius:15px;padding:26px;box-shadow:0 5px 25px #172b4d10}
h1{font-size:24px;margin:0 0 8px}p{line-height:1.6;color:#55677b;font-size:14px}
label{display:block;font-size:14px;font-weight:600;margin:15px 0 6px}
input,select,textarea{box-sizing:border-box;width:100%;border:1px solid #c8d3df;border-radius:8px;padding:10px 12px;font:inherit;background:white;color:#162236}
textarea{resize:vertical;min-height:85px}textarea.json{min-height:150px;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px}
.grid{display:grid;grid-template-columns:1fr 1fr;gap:0 16px}button{padding:13px;border:0;border-radius:8px;background:#1464d4;color:white;cursor:pointer;width:100%;font-weight:650;font-size:15px;margin-top:20px}button:disabled{opacity:.5;cursor:wait}
pre{background:#0b1829;color:#e1eeff;white-space:pre-wrap;overflow-wrap:anywhere;padding:16px;border-radius:8px;font-size:12px;max-height:420px;overflow-y:auto}.status{background:#f3f6fc;border-radius:8px;padding:12px;font-size:13px}.small{font-size:12px}
@media(max-width:600px){.grid{grid-template-columns:1fr}}
</style></head>
<body><main><div class="card"><h1>KMessage iOS 推送测试</h1>
<p>发送与安卓 <code>KMessage</code> 相同字段的 JSON。在线走个推透传,后台或锁屏走 APNs 系统通知。默认标题避开“个推”敏感词。</p>
<div id="health" class="status">正在读取本地服务状态……</div>
<form id="form">
<label for="cid">目标 iPhone CID(不是 APNs Token)</label><input id="cid" required placeholder="GeTuiSdkDidRegisterClient 返回的 CID">
<div class="grid"><div><label for="title">系统通知标题</label><input id="title" value="订单提醒" maxlength="50" required></div>
<div><label for="code">业务消息类型 code</label><select id="code"><option value="MS_001">MS_001 · 骑士接单</option><option value="MS_002">MS_002 · 订单释放</option><option value="MS_003">MS_003 · 订单取消</option><option value="MS_004">MS_004 · 完成订单</option></select></div></div>
<label for="body">系统通知正文</label><textarea id="body" maxlength="256" required>您有一条订单消息</textarea>
<div class="grid"><div><label for="msg_id">msg_id(可空,后端生成)</label><input id="msg_id" inputmode="numeric" placeholder="留空自动生成"></div>
<div><label for="play_type">play_type</label><select id="play_type"><option value="local">local · 安卓端触发本地铃声逻辑</option><option value="remote">remote · 不触发安卓本地铃声逻辑</option></select></div></div>
<label for="r_url">r_url(可空)</label><input id="r_url" placeholder="业务回执地址(如有)">
<label for="detail">detail(JSON 对象;先填真实 MessageDetail 字段)</label><textarea id="detail" class="json" spellcheck="false">{}</textarea>
<p class="small">完整 KMessage 的 time 为后端生成的当前毫秒时间戳。业务字段放在 detail 中;避免随便造生产订单数据。</p>
<button id="send" type="submit">发送到这个 CID</button>
</form>
<p class="small">测试建议:先让 App 在前台,检查透传回调;再把 App 切到后台/锁屏,检查系统通知。请求成功 ≠ 设备一定送达。</p>
<label>请求结果</label><pre id="out">尚未发送</pre>
</div></main>
<script>
(async()=>{let el=document.getElementById('health');try{let r=await fetch('/api/health');let j=await r.json();el.textContent=j.configured?'✓ 后端运行中,应用密钥已配置':'⚠ 后端运行中,请先填写 .env 的三个密钥';if(j.default_cid)document.getElementById('cid').value=j.default_cid;}catch(e){el.textContent='服务无法连接:'+e.message}})();
document.getElementById('form').addEventListener('submit',async (e)=>{e.preventDefault();let btn=document.getElementById('send'),out=document.getElementById('out');let val=id=>document.getElementById(id).value.trim();btn.disabled=true;out.textContent='正在调用接口……';try{let detail=JSON.parse(val('detail')||'{}');if(!detail||Array.isArray(detail)||typeof detail!=='object')throw Error('detail 必须是 JSON 对象');let data={cid:val('cid'),title:val('title'),body:val('body'),code:val('code'),play_type:val('play_type'),r_url:val('r_url'),detail};if(val('msg_id')){if(!/^\d+$/.test(val('msg_id')))throw Error('msg_id 必须是整数');data.msg_id=Number(val('msg_id'));}let response=await fetch('/api/send',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify(data)});let result=await response.json();out.textContent=(response.ok?'平台已接收(请看手机是否到达)\n':'请求失败\n')+JSON.stringify(result,null,2);}catch(err){out.textContent='输入或网络错误:'+err.message;}finally{btn.disabled=false}});
</script></body></html>
"""Local-only GeTui KMessage test server. No third-party dependencies."""
"""Local-only GeTui KMessage test server. No third-party dependencies."""
from __future__ import annotations
import json
import os
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from getui_client import GeTuiClient, GeTuiError, make_kmessage
ROOT = Path(__file__).resolve().parent
def load_dotenv():
env_path = ROOT / ".env"
if not env_path.exists():
return
for raw in env_path.read_text(encoding="utf-8").splitlines():
line = raw.strip()
if not line or line.startswith("#") or "=" not in line:
continue
key, val = line.split("=", 1)
val = val.strip()
if (val.startswith('"') and val.endswith('"')) or (val.startswith("'") and val.endswith("'")):
val = val[1:-1]
os.environ.setdefault(key.strip(), val)
load_dotenv()
CLIENT = None
def get_client():
global CLIENT
if CLIENT is None:
CLIENT = GeTuiClient(
os.getenv("GETUI_APP_ID", ""),
os.getenv("GETUI_APP_KEY", ""),
os.getenv("GETUI_MASTER_SECRET", ""),
)
return CLIENT
class Handler(BaseHTTPRequestHandler):
def reply_json(self, status: int, result: dict):
raw = json.dumps(result, ensure_ascii=False).encode("utf-8")
self.send_response(status)
self.send_header("Content-Type", "application/json; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(raw)
def do_GET(self):
if self.path == "/":
raw = (ROOT / "index.html").read_bytes()
self.send_response(200)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(raw)))
self.send_header("Cache-Control", "no-store")
self.end_headers()
self.wfile.write(raw)
elif self.path == "/api/health":
ready = all(os.getenv(k, "").strip() for k in (
"GETUI_APP_ID", "GETUI_APP_KEY", "GETUI_MASTER_SECRET"
))
self.reply_json(200, {
"ok": True, "configured": ready,
"default_cid": os.getenv("GETUI_TEST_CID", ""),
})
else:
self.reply_json(404, {"ok": False, "error": "Not found"})
def do_POST(self):
if self.path != "/api/send":
self.reply_json(404, {"ok": False, "error": "Not found"})
return
try:
length = int(self.headers.get("Content-Length", "0"))
if not (1 <= length <= 8192):
raise ValueError("请求体大小应为 1-8192 字节")
data = json.loads(self.rfile.read(length))
if not isinstance(data, dict):
raise ValueError("请求体必须是 JSON 对象")
cid = data.get("cid") or os.getenv("GETUI_TEST_CID", "")
title = data.get("title", "订单提醒")
body = data.get("body", "您有一条待处理的订单消息")
detail = data.get("detail", {})
if isinstance(detail, str):
detail = json.loads(detail)
msg = make_kmessage(
code=data.get("code", "MS_001"),
msg_id=data.get("msg_id"),
report_url=data.get("r_url", ""),
timestamp=data.get("time"),
detail=detail,
play_type=data.get("play_type", "local"),
)
result = get_client().push_to_cid(cid, title, body, msg)
self.reply_json(200, {
"ok": True,
"note": "个推 API 已接受请求,不代表 APNs 已送达设备",
**result,
})
except (ValueError, TypeError, json.JSONDecodeError) as exc:
self.reply_json(400, {"ok": False, "error": str(exc)})
except GeTuiError as exc:
self.reply_json(502, {"ok": False, "error": str(exc)})
except Exception as exc:
print(f"[ERROR] unexpected {type(exc).__name__}: {exc}", flush=True)
self.reply_json(500, {"ok": False, "error": "服务器错误,请查看终端日志"})
def main():
port = int(os.getenv("PORT", "8765"))
try:
server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
except OSError as exc:
if getattr(exc, "errno", None) == 48:
raise SystemExit(f"端口 {port} 已被占用。可直接访问 http://127.0.0.1:{port} ,或用 PORT=8766 python3 server.py 启动") from exc
raise
print(f"KMessage 推送测试服务:http://127.0.0.1:{port}", flush=True)
print("只监听本机,按 Ctrl+C 结束。", flush=True)
try:
server.serve_forever()
except KeyboardInterrupt:
pass
finally:
server.server_close()
if __name__ == "__main__":
main()
import json
import json
import unittest
from getui_client import GeTuiClient, make_kmessage
class MessageTest(unittest.TestCase):
def test_kmessage_shape(self):
msg = make_kmessage("MS_001", msg_id=10001, timestamp=1795417200000)
self.assertEqual(set(msg), {"msg_id", "code", "r_url", "time", "detail", "play_type"})
self.assertEqual(msg["code"], "MS_001")
self.assertEqual(msg["play_type"], "local")
def test_four_codes(self):
for code in ["MS_001", "MS_002", "MS_003", "MS_004"]:
self.assertEqual(make_kmessage(code)["code"], code)
def test_invalid_code(self):
with self.assertRaises(ValueError):
make_kmessage("MS_999")
def test_invalid_detail(self):
with self.assertRaises(ValueError):
make_kmessage("MS_001", detail=[1])
def test_signed_java_int_limit(self):
with self.assertRaises(ValueError):
make_kmessage("MS_001", msg_id=2147483648)
def test_same_payload_for_online_offline(self):
msg = make_kmessage("MS_001", msg_id=10, detail={"orderId": "test-order"})
payload = GeTuiClient.build_push_body("test-cid", "订单提醒", "骑士接单", msg)
online = payload["push_message"]["transmission"]
offline = payload["push_channel"]["ios"]["payload"]
self.assertEqual(online, offline)
self.assertEqual(json.loads(online), msg)
self.assertNotIn("个推", payload["push_channel"]["ios"]["aps"]["alert"]["title"])
def test_missing_cid(self):
with self.assertRaises(ValueError):
GeTuiClient.build_push_body("", "订单提醒", "正文", make_kmessage())
if __name__ == "__main__":
unittest.main()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment