KMRequestServerManager.swift 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990
  1. //
  2. // KMRequestServerManager.swift
  3. // PDF Reader Pro
  4. //
  5. // Created by lizhe on 2023/2/22.
  6. //
  7. import Cocoa
  8. enum KMRequestServerErrorCodeType: Int, CaseIterable {
  9. case unknown = 0 //未知
  10. case correct = 200 //正确
  11. case EXCEPTION_MSG_IMAGE_CODE_ERROR = 301
  12. case EXCEPTION_MSG_USER_NOT_FOUND = 302
  13. case EXCEPTION_MSG_TOKEN_IS_INVALID = 304
  14. case EXCEPTION_MSG_DEVICE_NUM_MAX = 305
  15. case EXCEPTION_MSG_USER_NOT_LOGIN = 306
  16. case EXCEPTION_MSG_GET_CODE_FAIL = 307
  17. case EXCEPTION_MSG_GET_TOKEN_FAIL = 308
  18. case EMAIL_VERIFY_CODE_KEY_ERROR = 309
  19. case EMAIL_REGISTER_ERROR = 310
  20. case EXCEPTION_MSG_PASSWORD_ERROR = 311
  21. case EXCEPTION_MSG_CODE_ACTION_ERROR = 312
  22. case EXCEPTION_MSG_CODE_SEND_ERROR = 313
  23. case EXCEPTION_MAIL_CODE_SEND_ERROR = 314
  24. case VERIFY_CODE_SEND_TOO_QUICKLY = 315
  25. case EXCEPTION_MSG_EMAIL_EXIST = 316
  26. case EXCEPTION_MSG_EMAIL_NOT_REGISTER = 317
  27. case EXCEPTION_MSG_EMAIL_LOGOUT_ING = 318
  28. case EXCEPTION_MSG_EMAIL_INVALID = 319
  29. case EXCEPTION_MSG_PASSWORD_NOT_INCONSISTENT = 320
  30. case EXCEPTION_MSG_PASSWORD_SIZE_MIN = 321
  31. case EXCEPTION_MSG_PASSWORD_SIZE_MAX = 322
  32. case EXCEPTION_MSG_PLEASE_ADD_AUTH_CONFIG = 323
  33. case EXCEPTION_MSG_USER_SUBSCRIPTION_IN_PROGRESS = 324
  34. case EXCEPTION_MSG_USER_TRAIL_IN_PROGRESS = 325
  35. case EXCEPTION_TIME_TRANSFER_ERROR = 326
  36. case EXCEPTION_MSG_PASSWORD_CONTAIN_EMRTY = 327
  37. case EXCEPTION_MSG_CREATE_ORDER_PARAMETER = 328//,"支付方式异常"),
  38. case EXCEPTION_MSG_EVENT_IS_CURRENTLY_NOT_SUPPORTED = 329 //, "当前事件暂不支持"),
  39. case EXCEPTION_MSG_THE_ACCOUNT_IS_ALREADY_LOGGED_IN_ON_OTHER_DEVICES = 330//, "账号已在其他设备登录"),
  40. case EXCEPTION_MSG_ABNORMAL_USER_STATUS = 331 //,"当前邮箱已被停用或者处于注销中状态"),
  41. case EXCEPTION_MSG_APP_STORE_TICKET_VALIDATION_FAILED = 332 //"AppStore票据验证失败"),
  42. case EXCEPTION_MSG_APP_STORE_TICKET_VALIDATION_NEED_TO_RETRY = 333// "AppStore票据验证需要重试"),
  43. case EXCEPTION_MSG_REPEAT_SUBSCRIPTION = 334 //"用户已订阅该产品"
  44. case EXCEPTION_MSG_RESTORING_PURCHASES_IS_NOT_CURRENTLY_SUPPORTED = 335 //"恢复购买暂不支持"),
  45. case EXCEPTION_MSG_USER_TRANSACTION_CANCELED_OR_FAILED = 336 //"用户交易取消或失败")
  46. case EXCEPTION_MSG_CURRENT_ORDER_NOT_RECORDED = 337 //"当前订单未记录,请稍后重试"),
  47. case EXCEPTION_MSG_THE_SAME_USER = 338//"同一用户,无需处理"),
  48. case EXCEPTION_MSG_THIRD_PAY_ID_ILLEGAL = 339//"thirdPayId非法"),
  49. case EXCEPTION_MSG_ORDER_DOES_NOT_EXIST = 340// "订单不存在"),
  50. case EXCEPTION_MSG_THE_ORDER_STATUS_IS_ABNORMAL = 341// "订单状态异常"),
  51. case EXCEPTION_MSG_TRANSACTION_ID_REPEAT = 342 //"transactionId重复"),
  52. case EMAIL_VERIFY_CODE_KEY_ERROR2 = 700
  53. static func typeOfMessage(type: KMRequestServerErrorCodeType?) -> String {
  54. var result: String = ""
  55. switch type {
  56. case .EXCEPTION_MSG_IMAGE_CODE_ERROR:
  57. result = "Graphic verification code error"
  58. case .EXCEPTION_MSG_USER_NOT_FOUND:
  59. result = "Email address is not registered"
  60. case .EXCEPTION_MSG_TOKEN_IS_INVALID:
  61. result = "Invalid token or token has expired"
  62. case .EXCEPTION_MSG_DEVICE_NUM_MAX:
  63. result = "You have reached the maximum number of devices, please log out of other devices and log in again."
  64. case .EXCEPTION_MSG_USER_NOT_LOGIN:
  65. result = "User is not logged in. Please log in and try again."
  66. case .EXCEPTION_MSG_GET_CODE_FAIL:
  67. result = "Failed to obtain authorization code"
  68. case .EXCEPTION_MSG_GET_TOKEN_FAIL:
  69. result = "Failed to obtain token"
  70. case .EMAIL_VERIFY_CODE_KEY_ERROR:
  71. result = "Email code error"
  72. case .EMAIL_REGISTER_ERROR:
  73. result = "Register error"
  74. case .EXCEPTION_MSG_PASSWORD_ERROR:
  75. result = "Wrong password. You can check whether the letter is uppercase or lowercase."
  76. case .EXCEPTION_MSG_CODE_ACTION_ERROR:
  77. result = "Incorrect code"
  78. case .EXCEPTION_MSG_CODE_SEND_ERROR:
  79. result = "Code send error"
  80. case .EXCEPTION_MAIL_CODE_SEND_ERROR:
  81. result = "Mail send error"
  82. case .VERIFY_CODE_SEND_TOO_QUICKLY:
  83. result = "Enter an existing verification code" //result = "Too many codes sent, please try again later."
  84. case .EXCEPTION_MSG_EMAIL_EXIST:
  85. result = "This email is already registered, please log in."
  86. case .EXCEPTION_MSG_EMAIL_NOT_REGISTER:
  87. result = "This account is not registered, click Sign Up to create a new account."
  88. case .EXCEPTION_MSG_EMAIL_LOGOUT_ING:
  89. result = "Your account is currently being canceled and cannot be logged in. If you have any questions, please contact customer service."
  90. case .EXCEPTION_MSG_EMAIL_INVALID:
  91. result = "Please enter the correct email format"
  92. case .EXCEPTION_MSG_PASSWORD_NOT_INCONSISTENT:
  93. result = "Wrong password. You can check whether the letter is uppercase or lowercase." //result = "Passwords are different. Please re-enter them."
  94. case .EXCEPTION_MSG_PASSWORD_SIZE_MIN:
  95. result = "Password must be 6-24 characters" //result = "At least 6 characters"
  96. case .EXCEPTION_MSG_PASSWORD_SIZE_MAX:
  97. result = "Password must be 6-24 characters" //result = "Up to 24 characters"
  98. case .EXCEPTION_MSG_PLEASE_ADD_AUTH_CONFIG:
  99. result = "Please add auth config"
  100. case .EXCEPTION_MSG_USER_SUBSCRIPTION_IN_PROGRESS:
  101. result = "You are still in the subscription and cannot cancel account. Please click Cancel Account after the subscription period ends."
  102. case .EXCEPTION_MSG_USER_TRAIL_IN_PROGRESS:
  103. result = "You are still in the subscription and cannot cancel account. Please click Cancel Account after the trial expired."
  104. case .EXCEPTION_TIME_TRANSFER_ERROR:
  105. result = "Time conversion failure"
  106. case .EMAIL_VERIFY_CODE_KEY_ERROR2:
  107. result = "Email code error"
  108. case .EXCEPTION_MSG_PASSWORD_CONTAIN_EMRTY:
  109. result = "Spaces are not allowed in password" //result = "The password cannot contain Spaces"
  110. case .EXCEPTION_MSG_CREATE_ORDER_PARAMETER:
  111. result = "Abnormal payment method"
  112. case .EXCEPTION_MSG_EVENT_IS_CURRENTLY_NOT_SUPPORTED:
  113. result = "The current event is not supported"
  114. case .EXCEPTION_MSG_THE_ACCOUNT_IS_ALREADY_LOGGED_IN_ON_OTHER_DEVICES:
  115. result = "Your account has been logged into another device."
  116. case .EXCEPTION_MSG_ABNORMAL_USER_STATUS:
  117. result = "This email account is no longer available or canceled."
  118. case .EXCEPTION_MSG_APP_STORE_TICKET_VALIDATION_FAILED:
  119. result = "AppStore receipt verification failed."
  120. case .EXCEPTION_MSG_APP_STORE_TICKET_VALIDATION_NEED_TO_RETRY:
  121. result = "Please re-verify the receipt."
  122. case .EXCEPTION_MSG_REPEAT_SUBSCRIPTION:
  123. result = "Users have already subscribed to PDF Reader Pro."
  124. case .EXCEPTION_MSG_RESTORING_PURCHASES_IS_NOT_CURRENTLY_SUPPORTED:
  125. result = "Restoring purchases may not work due to the temporary problem with the App Store system."
  126. case .EXCEPTION_MSG_USER_TRANSACTION_CANCELED_OR_FAILED:
  127. result = "Payment Cancelled or Failed."
  128. case .EXCEPTION_MSG_CURRENT_ORDER_NOT_RECORDED:
  129. result = "The current order is not recorded, please try again later."
  130. case .EXCEPTION_MSG_THE_SAME_USER:
  131. result = "Same user, no processing required."
  132. case .EXCEPTION_MSG_THIRD_PAY_ID_ILLEGAL:
  133. result = "ThirdPayID illegal"
  134. case .EXCEPTION_MSG_ORDER_DOES_NOT_EXIST:
  135. result = "This order does not exist."
  136. case .EXCEPTION_MSG_THE_ORDER_STATUS_IS_ABNORMAL:
  137. result = "This order status is abnormal."
  138. case .EXCEPTION_MSG_TRANSACTION_ID_REPEAT:
  139. result = "Duplicate TransactionID"
  140. case .unknown:
  141. result = ""
  142. case .correct:
  143. result = ""
  144. default:
  145. result = "Network error"
  146. }
  147. return result
  148. }
  149. }
  150. enum KMVerifyCodeType: String, CaseIterable {
  151. case unknown = "" //
  152. case register = "user_register" // 注册
  153. case logOff = "user_log_off" //注销
  154. case resetPassword = "user_reset_password" //重置密码
  155. }
  156. enum KMVerifyEmailType: String, CaseIterable {
  157. case login = "1" // 登录
  158. case register = "2" //注册
  159. }
  160. struct Result {
  161. var result: NSDictionary = [:]
  162. var message: String = ""
  163. var code : Int = 200
  164. var error: NSError?
  165. }
  166. typealias KMRequestServerComplete = (_ success: Bool, _ result: Result?) -> Void
  167. typealias KMRequestServerDateComplete = (_ success: Bool, _ result: NSDictionary?) -> Void
  168. class KMRequestServerManager: NSObject {
  169. static let manager = KMRequestServerManager()
  170. var loginAlert: NSAlert? = nil
  171. }
  172. //MARK: - 会员
  173. extension KMRequestServerManager {
  174. /**
  175. @abstract 获取验证码
  176. @param verifyCodeType 验证入口类型
  177. @param email 邮箱
  178. */
  179. func getVerifyCode(verifyCodeType: KMVerifyCodeType, email: String, complete: @escaping KMRequestServerComplete) {
  180. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/getVerifyCode"
  181. let params: [String: Any] = ["action": verifyCodeType.rawValue,
  182. "appId": "16",
  183. "receiver": email,
  184. "type": "0"]
  185. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: params) { requestSerializer in
  186. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  187. } completion: { [unowned self] (task, responseObject, error) in
  188. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  189. if result.code == 200 {
  190. complete(true, result)
  191. } else {
  192. complete(false, result)
  193. }
  194. }
  195. }
  196. /**
  197. @abstract 注册
  198. @param userName 用户账号(邮箱)
  199. @param verifyCode 验证码
  200. */
  201. func register(userName: String, password: String, verifyCode: String, complete: @escaping (_ success: Bool, _ requestData: KMLightMemberToken?, _ result: Result) -> Void) {
  202. let uuid: String = GetHardwareUUID() ?? ""
  203. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/emailRegister"
  204. let params: [String: Any] = ["appId": "16",
  205. "deviceSign": uuid,
  206. "password": password,
  207. "platformType": "0",
  208. "username": userName,
  209. "verifyCode": verifyCode,
  210. "model": "Mac"]
  211. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  212. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  213. } completion: { [unowned self] task, responseObject, error in
  214. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  215. if result.code == 200 {
  216. //解析数据
  217. KMLightMemberToken.parseData(data: result.result) { data in
  218. //登录成功
  219. KMLightMemberManager.manager.logIn()
  220. complete(true, data, result)
  221. }
  222. } else {
  223. complete(false, nil, result)
  224. }
  225. }
  226. }
  227. /**
  228. @abstract 注销
  229. @param verifyCode 验证码
  230. */
  231. func logOff(verifyCode: String, complete: @escaping KMRequestServerComplete) {
  232. let token: String = KMLightMemberManager.manager.token.access_token
  233. if token == "" {
  234. return
  235. }
  236. var urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/user/logOffForUser"
  237. // let params = ["code":verifyCode]
  238. urlString = urlString + (NSString(format: "?code=%@&appId=%@", verifyCode, "16") as String)
  239. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: nil) { requestSerializer in
  240. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  241. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  242. } completion: { [unowned self] (task, responseObject, error) in
  243. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  244. if result.code == 200 {
  245. //登出
  246. KMLightMemberCache.cache.clean()
  247. KMLightMemberManager.manager.logOut()
  248. complete(true, result)
  249. } else {
  250. complete(false, result)
  251. }
  252. }
  253. }
  254. /**
  255. @abstract 登录
  256. @param email 邮箱
  257. @param password 密码
  258. */
  259. func login(email: String, password: String, complete: @escaping (_ success: Bool, _ requestData: KMLightMemberToken?, _ result: Result?) -> Void) {
  260. var urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/emailLogin"
  261. let uuid: String = GetHardwareUUID() ?? ""
  262. // let params: [String: String] = ["appId": "16",
  263. // "deviceSign": uuid,
  264. // "email": email,
  265. // "password": password,
  266. // "platformType": "0"]
  267. urlString = urlString + (NSString(format: "?appId=16&deviceSign=%@&email=%@&password=%@&platformType=0&model=%@", uuid, email, password, "Mac") as String)
  268. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: nil) { requestSerializer in
  269. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  270. } completion: { [unowned self] (task, responseObject, error) in
  271. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  272. if result.code == 200 {
  273. //解析数据
  274. KMLightMemberToken.parseData(data: result.result) { data in
  275. //登录成功
  276. KMLightMemberManager.manager.logIn()
  277. complete(true, data, nil)
  278. }
  279. } else {
  280. complete(false, nil, result)
  281. }
  282. }
  283. }
  284. /**
  285. @abstract 登出
  286. */
  287. func logout(complete: @escaping KMRequestServerComplete) {
  288. let token: String = KMLightMemberManager.manager.token.access_token
  289. if token == "" {
  290. return
  291. }
  292. let uuid: String = GetHardwareUUID() ?? ""
  293. var urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/user/logout"
  294. // let params: [String: Any] = ["deviceSign": uuid,
  295. // "appId": "16"]
  296. urlString = urlString + (NSString(format: "?appId=16&deviceSign=%@", uuid) as String)
  297. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: nil) { requestSerializer in
  298. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  299. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  300. } completion: { [unowned self] (task, responseObject, error) in
  301. //登出成功
  302. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  303. if result.code == 200 {
  304. //登出
  305. KMLightMemberManager.manager.logOut()
  306. complete(true, result)
  307. } else {
  308. complete(false, result)
  309. }
  310. }
  311. }
  312. /**
  313. @abstract 修改密码
  314. @param url 源文件url
  315. @param data 数据
  316. @retrun document
  317. */
  318. func resetPassword(account: String, firstPassword: String, secondPassword: String, verifyCode: String, complete: @escaping KMRequestServerComplete) {
  319. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/resetPassword"
  320. let params: [String: Any] = ["account": account,
  321. "appId": "16",
  322. "firstPassword": firstPassword,
  323. "platformType": "0",
  324. "secondPassword": secondPassword,
  325. "verifyCode": verifyCode]
  326. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  327. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  328. } completion: { [unowned self] (task, responseObject, error) in
  329. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  330. if result.code == 200 {
  331. complete(true, result)
  332. } else {
  333. complete(false, result)
  334. }
  335. }
  336. }
  337. /**
  338. @abstract 获取用户信息
  339. */
  340. func getUserInfo(complete: @escaping (_ success: Bool, _ data: KMLightMemberUserInfo?, _ result: Result?, _ isLocal: Bool) -> Void) {
  341. let token: String = KMLightMemberManager.manager.token.access_token
  342. if token == "" {
  343. complete(false , nil, Result(message: "token 不存在", code: 304), false)
  344. return
  345. }
  346. //先拿缓存数据 再请求新数据
  347. let cacheData = KMLightMemberCache.cache.readData()
  348. if cacheData.count != 0 {
  349. KMLightMemberUserInfo.parseData(data: cacheData, needSave: false) { data in
  350. complete(true ,data, nil, true)
  351. }
  352. }
  353. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/user/me"
  354. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: nil) { requestSerializer in
  355. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  356. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  357. } completion: { [unowned self] (task, responseObject, error) in
  358. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  359. if result.code == 200 {
  360. //解析数据
  361. KMLightMemberUserInfo.parseData(data: responseObject as! NSDictionary) { data in
  362. KMLightMemberManager.manager.reloadUserInfo()
  363. complete(true, data, nil, false)
  364. }
  365. } else {
  366. complete(false, nil, result, false)
  367. }
  368. }
  369. }
  370. func getUserInfo2() async throws -> (Bool, Result) {
  371. let token: String = KMLightMemberManager.manager.token.access_token
  372. if token == "" {
  373. return (false, Result())
  374. }
  375. if #available(macOS 10.15, *) {
  376. return try await withCheckedThrowingContinuation { continuation in
  377. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/user/me"
  378. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: nil) { requestSerializer in
  379. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  380. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  381. } completion: { [unowned self] (task, responseObject, error) in
  382. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  383. DispatchQueue.main.async {
  384. if result.code == 200 {
  385. //解析数据
  386. KMLightMemberUserInfo.parseData(data: responseObject as! NSDictionary) { data in
  387. KMLightMemberManager.manager.reloadUserInfo()
  388. continuation.resume(returning: (true, result))
  389. }
  390. } else {
  391. continuation.resume(returning: (false, result))
  392. }
  393. }
  394. }
  395. }
  396. } else {
  397. // Fallback on earlier versions
  398. return (true, Result())
  399. }
  400. }
  401. /**
  402. @abstract 验证码验证是否正确
  403. @param account 用户账号(邮箱)
  404. @param verifyCode 验证码
  405. @retrun verifyCodeType 验证码入口类型
  406. */
  407. func verificationCode(account: String, verifyCode: String, verifyCodeType: KMVerifyCodeType, complete: @escaping KMRequestServerComplete) {
  408. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/isEmailCodeValid"
  409. let params: [String: Any] = ["account": account,
  410. "code": verifyCode,
  411. "type": verifyCodeType.rawValue,
  412. "appId": "16"]
  413. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: params) { requestSerializer in
  414. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  415. } completion: { [unowned self] (task, responseObject, error) in
  416. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  417. if result.code == 200 {
  418. complete(true, result)
  419. } else {
  420. complete(false, result)
  421. }
  422. }
  423. }
  424. /**
  425. @abstract 邮箱验证
  426. @param account 用户账号(邮箱)
  427. @param verifyCodeType 验证码
  428. @retrun verifyCodeType 验证码入口类型
  429. */
  430. func verificationEmail(userName: String, verifyEmailType: KMVerifyEmailType, complete: @escaping KMRequestServerComplete) {
  431. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/validUser"
  432. let params: [String: Any] = ["appId": "16",
  433. "username": userName,
  434. "platformType": "0",
  435. "validType": verifyEmailType.rawValue]
  436. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  437. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  438. } completion: { [unowned self] (task, responseObject, error) in
  439. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  440. if result.code == 200 {
  441. complete(true, result)
  442. } else {
  443. complete(false, result)
  444. }
  445. }
  446. }
  447. func getDeviceRetensionCoupon(complete: @escaping KMRequestServerDateComplete) {
  448. let urlString = AIInfoConfig().aiActionURL + "api/devices/getRetensionCoupon"
  449. let params: [String:Any] = ["unique_sn": self.uuid(),
  450. "platform": "DMG"]
  451. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  452. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  453. } completion: { [unowned self] (task, responseObject, error) in
  454. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  455. if result.code == 200 && result.error != nil && result.message != "unknown error" {
  456. complete(true, responseObject as? NSDictionary)
  457. } else {
  458. complete(false, responseObject as? NSDictionary)
  459. }
  460. }
  461. }
  462. //MARK: Private Method
  463. private func uuid() -> String {
  464. return GetHardwareUUID()!
  465. }
  466. }
  467. //MARK: - 订阅
  468. extension KMRequestServerManager {
  469. //创建订单
  470. func createOrder(productId: String, userId: String, complete: @escaping (_ success: Bool, _ orderId: String?, _ result: Result?) -> Void) {
  471. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-website/pay/appStoreCreateOrder"
  472. let params: [String: Any] = ["productId": productId,
  473. "paymentMethod": "APPLE_PAY",
  474. "userId": userId,
  475. "appId": "16"]
  476. let token: String = KMLightMemberManager.manager.token.access_token
  477. if token == "" {
  478. complete(false, "", Result())
  479. return
  480. }
  481. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  482. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  483. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  484. } completion: { [unowned self] (task, responseObject, error) in
  485. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  486. if result.code == 200 {
  487. complete(true, result.result["id"] as! String, result)
  488. } else {
  489. complete(false, "", result)
  490. }
  491. }
  492. }
  493. //
  494. func restore(productId: String, userId: String, complete: @escaping (_ success: Bool, _ orderId: String?, _ result: Result?) -> Void) {
  495. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-website/pay/appStoreCreateOrder"
  496. let params: [String: Any] = ["productId": productId,
  497. "paymentMethod": "APPLE_PAY",
  498. "userId": userId,
  499. "appId": "16"]
  500. let token: String = KMLightMemberManager.manager.token.access_token
  501. if token == "" {
  502. complete(false, "", Result())
  503. return
  504. }
  505. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  506. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  507. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  508. } completion: { [unowned self] (task, responseObject, error) in
  509. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  510. if result.code == 200 {
  511. complete(true, result.result["id"] as! String, result)
  512. } else {
  513. complete(false, "", result)
  514. }
  515. }
  516. }
  517. func parseVerification(applePayProductId: String, orderId: String, receipt: String, restore: Int = 0, complete: @escaping KMRequestServerComplete) {
  518. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-website/pay/appStoreOrderSucceed"
  519. let params: [String: Any] = ["applePayProductId": applePayProductId,
  520. "orderId": orderId,
  521. "receipt": receipt,
  522. "restore": restore]
  523. KMPrint("二次验证上传数据:\(params)")
  524. let token: String = KMLightMemberManager.manager.token.access_token
  525. if token == "" {
  526. complete(false, Result())
  527. return
  528. }
  529. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  530. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  531. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  532. } completion: { [unowned self] (task, responseObject, error) in
  533. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  534. if result.code == 200 {
  535. complete(true, result)
  536. } else {
  537. complete(false, result)
  538. }
  539. }
  540. }
  541. func checkDeviceStatus(complete: @escaping KMRequestServerComplete) {
  542. var urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/checkDeviceStatus"
  543. let uuid: String = GetHardwareUUID() ?? ""
  544. // let params: [String: Any] = ["appId": "16",
  545. // "deviceSign": uuid]
  546. urlString = urlString + (NSString(format: "?appId=16&deviceSign=%@", uuid) as String)
  547. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: nil) { requestSerializer in
  548. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  549. } completion: { [unowned self] (task, responseObject, error) in
  550. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  551. if result.code == 200 {
  552. complete(true, result)
  553. } else {
  554. complete(false, result)
  555. }
  556. }
  557. }
  558. func appStoreEquityVerification(applePayProductId: String, receipt: String, complete: @escaping KMRequestServerComplete) {
  559. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-website/pay/appStoreEquityVerification"
  560. let params: [String: Any] = ["applePayProductId": applePayProductId,
  561. "paymentMethod": "APPLE_PAY",
  562. "receipt": receipt
  563. ]
  564. KMPrint("票据信息上传数据:\(params)")
  565. var token: String = KMLightMemberManager.manager.token.access_token
  566. if token == "" {
  567. complete(false, Result())
  568. return
  569. }
  570. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  571. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  572. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  573. } completion: { [unowned self] (task, responseObject, error) in
  574. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  575. if result.code == 200 {
  576. complete(true, result)
  577. } else {
  578. complete(false, result)
  579. }
  580. }
  581. }
  582. func appStoreBuyComplete(applePayProductId: String, receipt: String, isPurchase: Bool = false, complete: @escaping KMRequestServerComplete) {
  583. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-website/pay/appStoreBuyComplete"
  584. let userId = KMLightMemberManager.manager.info.id
  585. let params: [String: Any] = ["applePayProductId": applePayProductId,
  586. "paymentMethod": "APPLE_PAY",
  587. "receipt": receipt,
  588. "appId": "16",
  589. "productId": "21",
  590. "userId": userId
  591. ]
  592. KMPrint("票据信息上传数据:\(params)")
  593. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  594. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  595. } completion: { [unowned self] (task, responseObject, error) in
  596. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  597. if result.code == 200 {
  598. complete(true, result)
  599. } else {
  600. complete(false, result)
  601. }
  602. }
  603. }
  604. }
  605. //MARK: - AI
  606. extension KMRequestServerManager {
  607. /**
  608. @abstract 翻译上传
  609. @param file 文件路径
  610. @param version 版本号
  611. */
  612. func aiTranslationFileUpload(file: String, version: String, complete: @escaping KMRequestServerComplete) {
  613. let infoDictionary = Bundle .main.infoDictionary!
  614. let userInfo = KMLightMemberCache.cache.readData(type: .info)
  615. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  616. let urlString = KMAIServerConfig().aiTranslationURL + "/v1/translate/fileUpload"
  617. let fileData = FileManager.default.contents(atPath: file)
  618. let params: [String: Any] = ["file": fileData,
  619. "projectId": "2",
  620. "version": version,
  621. "userId": userInfo["id"] as Any]
  622. KMRequestServer.requestServer.aiTranslation(urlString: urlString, params: params) { formData in
  623. let fileURL = URL(fileURLWithPath: file)
  624. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  625. } requestSerializer: { requestSerializer in
  626. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  627. } completion: { task, responseObject, error in
  628. if responseObject != nil {
  629. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  630. let code: String = responseObject!["code"] as? String ?? "06005"
  631. let message: String = responseObject!["msg"] as? String ?? "unknown error"
  632. let error = NSError(domain: message, code: Int(code)!)
  633. let result = Result(result: data,message: message,code: Int(code)!, error: error)
  634. if result.code == 200 {
  635. complete(true, result)
  636. } else {
  637. complete(false, result)
  638. }
  639. } else {
  640. let error = NSError(domain: "unknown error", code: 404)
  641. let result = Result(result: [:],message: "unknown error",code: 404, error: error)
  642. complete(false, result)
  643. }
  644. }
  645. }
  646. /**
  647. @abstract 文件翻译
  648. @param fileKey 文件Key
  649. @param from 初始语言
  650. @param to 结束语言
  651. @param version 应用版本
  652. */
  653. func aiTranslationFileTranslateHandle(fileKey: String, from: String, to: String, version: String, complete: @escaping KMRequestServerComplete) {
  654. let infoDictionary = Bundle .main.infoDictionary!
  655. let userInfo = KMLightMemberCache.cache.readData(type: .info)
  656. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  657. let urlString = KMAIServerConfig().aiTranslationURL + "/v1/translate/fileTranslateHandle"
  658. if userInfo.count > 0 {
  659. var semaphore = DispatchSemaphore (value: 0)
  660. let parameters = String(format: "{\r\n \"fileKey\": \"%@\",\r\n \"from\": \"%@\",\r\n \"to\": \"%@\",\r\n \"version\": \"%@\",\r\n \"projectId\": \"2\",\r\n \"userId\": \"%@\"\r\n}", fileKey, from, to, version, userInfo["id"] as! String)
  661. let postData = parameters.data(using: .utf8)
  662. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  663. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  664. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  665. request.httpMethod = "POST"
  666. request.httpBody = postData
  667. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  668. guard let data = data else {
  669. KMPrint(String(describing: error))
  670. semaphore.signal()
  671. return
  672. }
  673. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  674. if jsonObject != nil {
  675. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  676. let code: String = jsonObject!["code"] as? String ?? "06005"
  677. let message: String = jsonObject!["msg"] as? String ?? "unknown error"
  678. let error = NSError(domain: message, code: Int(code)!)
  679. let result = Result(result: data1,message: message,code: Int(code)!, error: error)
  680. if result.code == 200 {
  681. complete(true, result)
  682. } else {
  683. complete(false, result)
  684. }
  685. } else {
  686. let error = NSError(domain: "unknown error", code: 404)
  687. let result = Result(result: [:],message: "unknown error",code: 404, error: error)
  688. complete(false, result)
  689. }
  690. semaphore.signal()
  691. }
  692. task.resume()
  693. semaphore.wait()
  694. }
  695. }
  696. /**
  697. @abstract 内容翻译
  698. @param q 选中
  699. @param from 初始语言
  700. @param to 结束语言
  701. @param version 应用版本
  702. */
  703. func aiTranslationTextTrans(q: String, from: String, to: String, version: String, complete: @escaping KMRequestServerComplete) {
  704. let infoDictionary = Bundle .main.infoDictionary!
  705. let userInfo = KMLightMemberCache.cache.readData(type: .info)
  706. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  707. let urlString = KMAIServerConfig().aiTranslationURL + "/v1/translate/textTrans"
  708. if userInfo.count > 0 {
  709. var semaphore = DispatchSemaphore (value: 0)
  710. var escapedString = q
  711. if q.contains("\n") || q.contains("\r") {
  712. escapedString = q.replacingOccurrences(of: "\n", with: "\\n")
  713. escapedString = escapedString.replacingOccurrences(of: "\r", with: "\\r")
  714. } else if q.contains("\u{2028}") {
  715. }
  716. escapedString = String(data: escapedString.data(using: .utf8)!, encoding: .utf8)!
  717. // let escapedString = String(data: q.data(using: .utf8)!, encoding: .utf8)!
  718. let parameters = String(format: "{\r\n \"q\": \"%@\",\r\n \"from\": \"%@\",\r\n \"to\": \"%@\",\r\n \"version\": \"%@\",\r\n \"projectId\": \"2\",\r\n \"userId\": \"%@\"\r\n}", escapedString, from, to, version, userInfo["id"] as! String)
  719. let postData = parameters.data(using: .utf8)
  720. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  721. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  722. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  723. request.httpMethod = "POST"
  724. request.httpBody = postData
  725. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  726. guard let data = data else {
  727. KMPrint(String(describing: error))
  728. semaphore.signal()
  729. return
  730. }
  731. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  732. if jsonObject != nil {
  733. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  734. let code: String = jsonObject!["code"] as? String ?? "06005"
  735. let message: String = jsonObject!["msg"] as? String ?? "unknown error"
  736. let error = NSError(domain: message, code: Int(code)!)
  737. let result = Result(result: data1,message: message,code: Int(code)!, error: error)
  738. if result.code == 200 {
  739. complete(true, result)
  740. } else {
  741. complete(false, result)
  742. }
  743. } else {
  744. let error = NSError(domain: "unknown error", code: 404)
  745. let result = Result(result: [:],message: "unknown error",code: 404, error: error)
  746. complete(false, result)
  747. }
  748. semaphore.signal()
  749. }
  750. task.resume()
  751. semaphore.wait()
  752. }
  753. }
  754. /**
  755. @abstract重写 & 纠错
  756. @param content 内容
  757. @param version 版本号
  758. */
  759. func aiRewriting(content: String, version: String, state: KMAIRewritingState, complete: @escaping KMRequestServerComplete) {
  760. let userInfo = KMLightMemberCache.cache.readData(type: .info)
  761. var urlString = KMAIServerConfig().aiRewritingURL + "/api/rewrite"
  762. // if state == .AIErrorCorrection {
  763. // urlString = KMAIServerConfig().aiRewritingURL + "/api/correct-typos"
  764. // }
  765. let params: [String: Any] = ["project_id": 2,
  766. "content": content,
  767. "version": version,
  768. "user_id": userInfo["id"] as Any]
  769. KMRequestServer.requestServer.aiRewriting(urlString: urlString, params: params) { formData in
  770. } requestSerializer: { requestSerializer in
  771. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  772. } completion: { task, responseObject, error in
  773. if responseObject != nil {
  774. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  775. let code: String = responseObject!["code"] as? String ?? "06005"
  776. let message: String = responseObject!["message"] as? String ?? "unknown error"
  777. let error = NSError(domain: message, code: Int(code)!)
  778. let result = Result(result: data,message: message,code: Int(code)!, error: error)
  779. if result.code == 200 {
  780. complete(true, result)
  781. } else {
  782. complete(false, result)
  783. }
  784. } else {
  785. let error = NSError(domain: "unknown error", code: 404)
  786. let result = Result(result: [:],message: "unknown error",code: 404, error: error)
  787. complete(false, result)
  788. }
  789. }
  790. }
  791. }
  792. //MARK: - 数据处理
  793. extension KMRequestServerManager {
  794. func dealData(responseObject: NSDictionary?, error: NSError?) -> Result {
  795. var dic: NSDictionary = [:]
  796. if (error == nil && responseObject != nil) {
  797. dic = responseObject!
  798. } else {
  799. var info = responseObject
  800. if (error != nil) {
  801. let data = error!.userInfo["com.alamofire.serialization.response.error.data"]
  802. if (data != nil) {
  803. info = try?JSONSerialization.jsonObject(with: data as? Data ?? Data(), options: JSONSerialization.ReadingOptions.mutableLeaves) as? NSDictionary
  804. }
  805. dic = info ?? [:]
  806. }
  807. }
  808. let result: NSDictionary = dic["result"] as? NSDictionary ?? [:]
  809. var code: Int = dic["code"] as? Int ?? 0
  810. let message: String = dic["msg"] as? String ?? "unknown error"
  811. let error = NSError(domain: message, code: code)
  812. if result.count == 0 && responseObject != nil && code == 0 {
  813. code = 200
  814. }
  815. if code == 318 {
  816. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
  817. let alert = NSAlert()
  818. alert.messageText = NSLocalizedString("Unable to Log in", comment: "")
  819. alert.informativeText = NSLocalizedString("Your account is currently being canceled and cannot be logged in. If you have any questions, please contact us at support@pdfreaderpro.com", comment: "")
  820. alert.addButton(withTitle: NSLocalizedString("Contact Us", comment: ""))
  821. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  822. var window = NSWindow.currentWindow()
  823. if window != nil {
  824. alert.beginSheetModal(for: window) { result in
  825. if (result == .alertFirstButtonReturn) {
  826. // KMMailHelper.newEmail(withContacts: "support@pdfreaderpro.com", andSubjects: "")
  827. // NSWorkspace.shared.launchApplication("Mailto:support@pdfreaderpro.com")
  828. // NSWorkspace.shared.open(URL(string: "mailto:support@pdfreaderpro.com")!)
  829. NSWorkspace.shared.open(URL(string: "https://www.pdfreaderpro.com/contact")!)
  830. // let service = NSSharingService(named: NSSharingService.Name.composeEmail)
  831. // service?.recipients = ["support@pdfreaderpro.com"]
  832. // service?.subject = "Test Mail"
  833. // service?.perform(withItems: ["Test Mail body"])
  834. } else if result == .alertSecondButtonReturn {
  835. return
  836. }
  837. }
  838. }
  839. })
  840. }
  841. if code == 304 {
  842. self.checkDeviceStatus { success, result in
  843. }
  844. }
  845. if code == 330 {
  846. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: { [unowned self] in
  847. if loginAlert == nil {
  848. loginAlert = NSAlert()
  849. loginAlert?.messageText = NSLocalizedString("Please Log in again", comment: "")
  850. loginAlert?.informativeText = NSLocalizedString("Your account has been logged into another device. If it was not done by you, please change your password as soon as possible.", comment: "")
  851. loginAlert?.addButton(withTitle: NSLocalizedString("Change Password", comment: ""))
  852. loginAlert?.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  853. var window = NSWindow.currentWindow()
  854. if window != nil {
  855. loginAlert?.beginSheetModal(for: window) { result in
  856. if (result == .alertFirstButtonReturn) {
  857. if KMLoginWindowController.fetchSampleController() == nil {
  858. KMLoginWindowController.show(window: window)
  859. }
  860. } else if result == .alertSecondButtonReturn {
  861. self.loginAlert = nil
  862. return
  863. }
  864. self.loginAlert = nil
  865. }
  866. } else {
  867. self.loginAlert = nil
  868. }
  869. }
  870. })
  871. }
  872. if code == 343 {
  873. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: { [unowned self] in
  874. var window = NSWindow.currentWindow()
  875. let _ = KMAccountExceptionWindowController.show(window: window)
  876. KMLightMemberManager.manager.logOut()
  877. })
  878. }
  879. // if code == 500 {
  880. // let alert = NSAlert()
  881. // alert.messageText = NSLocalizedString(message, comment: "")
  882. // alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  883. // if NSApp.mainWindow != nil {
  884. // alert.beginSheetModal(for: NSApp.mainWindow!)
  885. // } else {
  886. // alert.runModal()
  887. // }
  888. // }
  889. KMPrint(dic)
  890. return Result(result: result,message: message,code: code, error: error)
  891. }
  892. }
  893. extension NSWindow {
  894. static func currentWindow() -> NSWindow {
  895. var window = NSApp.mainWindow
  896. if NSApp.mainWindow?.sheets.first != nil {
  897. window = NSApp.mainWindow?.sheets.first
  898. }
  899. if window == nil {
  900. window = NSApplication.shared.windows.first
  901. }
  902. return window ?? NSWindow()
  903. }
  904. }