KMRequestServerManager.swift 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965
  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. class KMRequestServerManager: NSObject {
  168. static let manager = KMRequestServerManager()
  169. var loginAlert: NSAlert? = nil
  170. }
  171. //MARK: - 会员
  172. extension KMRequestServerManager {
  173. /**
  174. @abstract 获取验证码
  175. @param verifyCodeType 验证入口类型
  176. @param email 邮箱
  177. */
  178. func getVerifyCode(verifyCodeType: KMVerifyCodeType, email: String, complete: @escaping KMRequestServerComplete) {
  179. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/getVerifyCode"
  180. let params: [String: Any] = ["action": verifyCodeType.rawValue,
  181. "appId": "16",
  182. "receiver": email,
  183. "type": "0"]
  184. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: params) { requestSerializer in
  185. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  186. } completion: { [unowned self] (task, responseObject, error) in
  187. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  188. if result.code == 200 {
  189. complete(true, result)
  190. } else {
  191. complete(false, result)
  192. }
  193. }
  194. }
  195. /**
  196. @abstract 注册
  197. @param userName 用户账号(邮箱)
  198. @param verifyCode 验证码
  199. */
  200. func register(userName: String, password: String, verifyCode: String, complete: @escaping (_ success: Bool, _ requestData: KMLightMemberToken?, _ result: Result) -> Void) {
  201. let uuid: String = GetHardwareUUID() ?? ""
  202. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/emailRegister"
  203. let params: [String: Any] = ["appId": "16",
  204. "deviceSign": uuid,
  205. "password": password,
  206. "platformType": "0",
  207. "username": userName,
  208. "verifyCode": verifyCode,
  209. "model": "Mac"]
  210. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  211. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  212. } completion: { [unowned self] task, responseObject, error in
  213. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  214. if result.code == 200 {
  215. //解析数据
  216. KMLightMemberToken.parseData(data: result.result) { data in
  217. //登录成功
  218. KMLightMemberManager.manager.logIn()
  219. complete(true, data, result)
  220. }
  221. } else {
  222. complete(false, nil, result)
  223. }
  224. }
  225. }
  226. /**
  227. @abstract 注销
  228. @param verifyCode 验证码
  229. */
  230. func logOff(verifyCode: String, complete: @escaping KMRequestServerComplete) {
  231. let token: String = KMLightMemberManager.manager.token.access_token
  232. if token == "" {
  233. return
  234. }
  235. var urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/user/logOffForUser"
  236. // let params = ["code":verifyCode]
  237. urlString = urlString + (NSString(format: "?code=%@&appId=%@", verifyCode, "16") as String)
  238. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: nil) { requestSerializer in
  239. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  240. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  241. } completion: { [unowned self] (task, responseObject, error) in
  242. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  243. if result.code == 200 {
  244. //登出
  245. KMLightMemberCache.cache.clean()
  246. KMLightMemberManager.manager.logOut()
  247. complete(true, result)
  248. } else {
  249. complete(false, result)
  250. }
  251. }
  252. }
  253. /**
  254. @abstract 登录
  255. @param email 邮箱
  256. @param password 密码
  257. */
  258. func login(email: String, password: String, complete: @escaping (_ success: Bool, _ requestData: KMLightMemberToken?, _ result: Result?) -> Void) {
  259. var urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/emailLogin"
  260. let uuid: String = GetHardwareUUID() ?? ""
  261. // let params: [String: String] = ["appId": "16",
  262. // "deviceSign": uuid,
  263. // "email": email,
  264. // "password": password,
  265. // "platformType": "0"]
  266. urlString = urlString + (NSString(format: "?appId=16&deviceSign=%@&email=%@&password=%@&platformType=0&model=%@", uuid, email, password, "Mac") as String)
  267. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: nil) { requestSerializer in
  268. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  269. } completion: { [unowned self] (task, responseObject, error) in
  270. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  271. if result.code == 200 {
  272. //解析数据
  273. KMLightMemberToken.parseData(data: result.result) { data in
  274. //登录成功
  275. KMLightMemberManager.manager.logIn()
  276. complete(true, data, nil)
  277. }
  278. } else {
  279. complete(false, nil, result)
  280. }
  281. }
  282. }
  283. /**
  284. @abstract 登出
  285. */
  286. func logout(complete: @escaping KMRequestServerComplete) {
  287. let token: String = KMLightMemberManager.manager.token.access_token
  288. if token == "" {
  289. return
  290. }
  291. let uuid: String = GetHardwareUUID() ?? ""
  292. var urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/user/logout"
  293. // let params: [String: Any] = ["deviceSign": uuid,
  294. // "appId": "16"]
  295. urlString = urlString + (NSString(format: "?appId=16&deviceSign=%@", uuid) as String)
  296. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: nil) { requestSerializer in
  297. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  298. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  299. } completion: { [unowned self] (task, responseObject, error) in
  300. //登出成功
  301. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  302. if result.code == 200 {
  303. //登出
  304. KMLightMemberManager.manager.logOut()
  305. complete(true, result)
  306. } else {
  307. complete(false, result)
  308. }
  309. }
  310. }
  311. /**
  312. @abstract 修改密码
  313. @param url 源文件url
  314. @param data 数据
  315. @retrun document
  316. */
  317. func resetPassword(account: String, firstPassword: String, secondPassword: String, verifyCode: String, complete: @escaping KMRequestServerComplete) {
  318. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/resetPassword"
  319. let params: [String: Any] = ["account": account,
  320. "appId": "16",
  321. "firstPassword": firstPassword,
  322. "platformType": "0",
  323. "secondPassword": secondPassword,
  324. "verifyCode": verifyCode]
  325. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  326. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  327. } completion: { [unowned self] (task, responseObject, error) in
  328. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  329. if result.code == 200 {
  330. complete(true, result)
  331. } else {
  332. complete(false, result)
  333. }
  334. }
  335. }
  336. /**
  337. @abstract 获取用户信息
  338. */
  339. func getUserInfo(complete: @escaping (_ success: Bool, _ data: KMLightMemberUserInfo?, _ result: Result?, _ isLocal: Bool) -> Void) {
  340. let token: String = KMLightMemberManager.manager.token.access_token
  341. if token == "" {
  342. complete(false , nil, Result(message: "token 不存在", code: 304), false)
  343. return
  344. }
  345. //先拿缓存数据 再请求新数据
  346. let cacheData = KMLightMemberCache.cache.readData()
  347. if cacheData.count != 0 {
  348. KMLightMemberUserInfo.parseData(data: cacheData, needSave: false) { data in
  349. complete(true ,data, nil, true)
  350. }
  351. }
  352. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/user/me"
  353. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: nil) { requestSerializer in
  354. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  355. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  356. } completion: { [unowned self] (task, responseObject, error) in
  357. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  358. if result.code == 200 {
  359. //解析数据
  360. KMLightMemberUserInfo.parseData(data: responseObject as! NSDictionary) { data in
  361. KMLightMemberManager.manager.reloadUserInfo()
  362. complete(true, data, nil, false)
  363. }
  364. } else {
  365. complete(false, nil, result, false)
  366. }
  367. }
  368. }
  369. func getUserInfo2() async throws -> (Bool, Result) {
  370. let token: String = KMLightMemberManager.manager.token.access_token
  371. if token == "" {
  372. return (false, Result())
  373. }
  374. if #available(macOS 10.15, *) {
  375. return try await withCheckedThrowingContinuation { continuation in
  376. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/user/me"
  377. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: nil) { requestSerializer in
  378. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  379. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  380. } completion: { [unowned self] (task, responseObject, error) in
  381. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  382. DispatchQueue.main.async {
  383. if result.code == 200 {
  384. //解析数据
  385. KMLightMemberUserInfo.parseData(data: responseObject as! NSDictionary) { data in
  386. KMLightMemberManager.manager.reloadUserInfo()
  387. continuation.resume(returning: (true, result))
  388. }
  389. } else {
  390. continuation.resume(returning: (false, result))
  391. }
  392. }
  393. }
  394. }
  395. } else {
  396. // Fallback on earlier versions
  397. return (true, Result())
  398. }
  399. }
  400. /**
  401. @abstract 验证码验证是否正确
  402. @param account 用户账号(邮箱)
  403. @param verifyCode 验证码
  404. @retrun verifyCodeType 验证码入口类型
  405. */
  406. func verificationCode(account: String, verifyCode: String, verifyCodeType: KMVerifyCodeType, complete: @escaping KMRequestServerComplete) {
  407. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/isEmailCodeValid"
  408. let params: [String: Any] = ["account": account,
  409. "code": verifyCode,
  410. "type": verifyCodeType.rawValue,
  411. "appId": "16"]
  412. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: params) { requestSerializer in
  413. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  414. } completion: { [unowned self] (task, responseObject, error) in
  415. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  416. if result.code == 200 {
  417. complete(true, result)
  418. } else {
  419. complete(false, result)
  420. }
  421. }
  422. }
  423. /**
  424. @abstract 邮箱验证
  425. @param account 用户账号(邮箱)
  426. @param verifyCodeType 验证码
  427. @retrun verifyCodeType 验证码入口类型
  428. */
  429. func verificationEmail(userName: String, verifyEmailType: KMVerifyEmailType, complete: @escaping KMRequestServerComplete) {
  430. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/validUser"
  431. let params: [String: Any] = ["appId": "16",
  432. "username": userName,
  433. "platformType": "0",
  434. "validType": verifyEmailType.rawValue]
  435. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  436. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  437. } completion: { [unowned self] (task, responseObject, error) in
  438. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  439. if result.code == 200 {
  440. complete(true, result)
  441. } else {
  442. complete(false, result)
  443. }
  444. }
  445. }
  446. }
  447. //MARK: - 订阅
  448. extension KMRequestServerManager {
  449. //创建订单
  450. func createOrder(productId: String, userId: String, complete: @escaping (_ success: Bool, _ orderId: String?, _ result: Result?) -> Void) {
  451. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-website/pay/appStoreCreateOrder"
  452. let params: [String: Any] = ["productId": productId,
  453. "paymentMethod": "APPLE_PAY",
  454. "userId": userId,
  455. "appId": "16"]
  456. let token: String = KMLightMemberManager.manager.token.access_token
  457. if token == "" {
  458. complete(false, "", Result())
  459. return
  460. }
  461. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  462. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  463. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  464. } completion: { [unowned self] (task, responseObject, error) in
  465. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  466. if result.code == 200 {
  467. complete(true, result.result["id"] as! String, result)
  468. } else {
  469. complete(false, "", result)
  470. }
  471. }
  472. }
  473. //
  474. func restore(productId: String, userId: String, complete: @escaping (_ success: Bool, _ orderId: String?, _ result: Result?) -> Void) {
  475. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-website/pay/appStoreCreateOrder"
  476. let params: [String: Any] = ["productId": productId,
  477. "paymentMethod": "APPLE_PAY",
  478. "userId": userId,
  479. "appId": "16"]
  480. let token: String = KMLightMemberManager.manager.token.access_token
  481. if token == "" {
  482. complete(false, "", Result())
  483. return
  484. }
  485. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  486. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  487. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  488. } completion: { [unowned self] (task, responseObject, error) in
  489. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  490. if result.code == 200 {
  491. complete(true, result.result["id"] as! String, result)
  492. } else {
  493. complete(false, "", result)
  494. }
  495. }
  496. }
  497. func parseVerification(applePayProductId: String, orderId: String, receipt: String, restore: Int = 0, complete: @escaping KMRequestServerComplete) {
  498. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-website/pay/appStoreOrderSucceed"
  499. let params: [String: Any] = ["applePayProductId": applePayProductId,
  500. "orderId": orderId,
  501. "receipt": receipt,
  502. "restore": restore]
  503. KMPrint("二次验证上传数据:\(params)")
  504. let token: String = KMLightMemberManager.manager.token.access_token
  505. if token == "" {
  506. complete(false, Result())
  507. return
  508. }
  509. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  510. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  511. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  512. } completion: { [unowned self] (task, responseObject, error) in
  513. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  514. if result.code == 200 {
  515. complete(true, result)
  516. } else {
  517. complete(false, result)
  518. }
  519. }
  520. }
  521. func checkDeviceStatus(complete: @escaping KMRequestServerComplete) {
  522. var urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/checkDeviceStatus"
  523. let uuid: String = GetHardwareUUID() ?? ""
  524. // let params: [String: Any] = ["appId": "16",
  525. // "deviceSign": uuid]
  526. urlString = urlString + (NSString(format: "?appId=16&deviceSign=%@", uuid) as String)
  527. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: nil) { requestSerializer in
  528. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  529. } completion: { [unowned self] (task, responseObject, error) in
  530. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  531. if result.code == 200 {
  532. complete(true, result)
  533. } else {
  534. complete(false, result)
  535. }
  536. }
  537. }
  538. func appStoreEquityVerification(applePayProductId: String, receipt: String, complete: @escaping KMRequestServerComplete) {
  539. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-website/pay/appStoreEquityVerification"
  540. let params: [String: Any] = ["applePayProductId": applePayProductId,
  541. "paymentMethod": "APPLE_PAY",
  542. "receipt": receipt
  543. ]
  544. KMPrint("票据信息上传数据:\(params)")
  545. var token: String = KMLightMemberManager.manager.token.access_token
  546. if token == "" {
  547. complete(false, Result())
  548. return
  549. }
  550. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  551. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  552. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  553. } completion: { [unowned self] (task, responseObject, error) in
  554. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  555. if result.code == 200 {
  556. complete(true, result)
  557. } else {
  558. complete(false, result)
  559. }
  560. }
  561. }
  562. func appStoreBuyComplete(applePayProductId: String, receipt: String, isPurchase: Bool = false, complete: @escaping KMRequestServerComplete) {
  563. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-website/pay/appStoreBuyComplete"
  564. let userId = KMLightMemberManager.manager.info.id
  565. let params: [String: Any] = ["applePayProductId": applePayProductId,
  566. "paymentMethod": "APPLE_PAY",
  567. "receipt": receipt,
  568. "appId": "16",
  569. "productId": "21",
  570. "userId": userId
  571. ]
  572. KMPrint("票据信息上传数据:\(params)")
  573. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  574. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  575. } completion: { [unowned self] (task, responseObject, error) in
  576. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  577. if result.code == 200 {
  578. complete(true, result)
  579. } else {
  580. complete(false, result)
  581. }
  582. }
  583. }
  584. }
  585. //MARK: - AI
  586. extension KMRequestServerManager {
  587. /**
  588. @abstract 翻译上传
  589. @param file 文件路径
  590. @param version 版本号
  591. */
  592. func aiTranslationFileUpload(file: String, version: String, complete: @escaping KMRequestServerComplete) {
  593. let infoDictionary = Bundle .main.infoDictionary!
  594. let userInfo = KMLightMemberCache.cache.readData(type: .info)
  595. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  596. let urlString = KMAIServerConfig().aiTranslationURL + "/v1/translate/fileUpload"
  597. let fileData = FileManager.default.contents(atPath: file)
  598. let params: [String: Any] = ["file": fileData,
  599. "projectId": "2",
  600. "version": version,
  601. "userId": userInfo["id"] as Any]
  602. KMRequestServer.requestServer.aiTranslation(urlString: urlString, params: params) { formData in
  603. let fileURL = URL(fileURLWithPath: file)
  604. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  605. } requestSerializer: { requestSerializer in
  606. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  607. } completion: { task, responseObject, error in
  608. if responseObject != nil {
  609. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  610. let code: String = responseObject!["code"] as? String ?? "06005"
  611. let message: String = responseObject!["msg"] as? String ?? "unknown error"
  612. let error = NSError(domain: message, code: Int(code)!)
  613. let result = Result(result: data,message: message,code: Int(code)!, error: error)
  614. if result.code == 200 {
  615. complete(true, result)
  616. } else {
  617. complete(false, result)
  618. }
  619. } else {
  620. let error = NSError(domain: "unknown error", code: 404)
  621. let result = Result(result: [:],message: "unknown error",code: 404, error: error)
  622. complete(false, result)
  623. }
  624. }
  625. }
  626. /**
  627. @abstract 文件翻译
  628. @param fileKey 文件Key
  629. @param from 初始语言
  630. @param to 结束语言
  631. @param version 应用版本
  632. */
  633. func aiTranslationFileTranslateHandle(fileKey: String, from: String, to: String, version: String, complete: @escaping KMRequestServerComplete) {
  634. let infoDictionary = Bundle .main.infoDictionary!
  635. let userInfo = KMLightMemberCache.cache.readData(type: .info)
  636. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  637. let urlString = KMAIServerConfig().aiTranslationURL + "/v1/translate/fileTranslateHandle"
  638. if userInfo.count > 0 {
  639. var semaphore = DispatchSemaphore (value: 0)
  640. 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)
  641. let postData = parameters.data(using: .utf8)
  642. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  643. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  644. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  645. request.httpMethod = "POST"
  646. request.httpBody = postData
  647. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  648. guard let data = data else {
  649. KMPrint(String(describing: error))
  650. semaphore.signal()
  651. return
  652. }
  653. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  654. if jsonObject != nil {
  655. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  656. let code: String = jsonObject!["code"] as? String ?? "06005"
  657. let message: String = jsonObject!["msg"] as? String ?? "unknown error"
  658. let error = NSError(domain: message, code: Int(code)!)
  659. let result = Result(result: data1,message: message,code: Int(code)!, error: error)
  660. if result.code == 200 {
  661. complete(true, result)
  662. } else {
  663. complete(false, result)
  664. }
  665. } else {
  666. let error = NSError(domain: "unknown error", code: 404)
  667. let result = Result(result: [:],message: "unknown error",code: 404, error: error)
  668. complete(false, result)
  669. }
  670. semaphore.signal()
  671. }
  672. task.resume()
  673. semaphore.wait()
  674. }
  675. }
  676. /**
  677. @abstract 内容翻译
  678. @param q 选中
  679. @param from 初始语言
  680. @param to 结束语言
  681. @param version 应用版本
  682. */
  683. func aiTranslationTextTrans(q: String, from: String, to: String, version: String, complete: @escaping KMRequestServerComplete) {
  684. let infoDictionary = Bundle .main.infoDictionary!
  685. let userInfo = KMLightMemberCache.cache.readData(type: .info)
  686. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  687. let urlString = KMAIServerConfig().aiTranslationURL + "/v1/translate/textTrans"
  688. if userInfo.count > 0 {
  689. var semaphore = DispatchSemaphore (value: 0)
  690. var escapedString = q
  691. if q.contains("\n") || q.contains("\r") {
  692. escapedString = q.replacingOccurrences(of: "\n", with: "\\n")
  693. escapedString = escapedString.replacingOccurrences(of: "\r", with: "\\r")
  694. } else if q.contains("\u{2028}") {
  695. }
  696. escapedString = String(data: escapedString.data(using: .utf8)!, encoding: .utf8)!
  697. // let escapedString = String(data: q.data(using: .utf8)!, encoding: .utf8)!
  698. 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)
  699. let postData = parameters.data(using: .utf8)
  700. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  701. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  702. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  703. request.httpMethod = "POST"
  704. request.httpBody = postData
  705. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  706. guard let data = data else {
  707. KMPrint(String(describing: error))
  708. semaphore.signal()
  709. return
  710. }
  711. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  712. if jsonObject != nil {
  713. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  714. let code: String = jsonObject!["code"] as? String ?? "06005"
  715. let message: String = jsonObject!["msg"] as? String ?? "unknown error"
  716. let error = NSError(domain: message, code: Int(code)!)
  717. let result = Result(result: data1,message: message,code: Int(code)!, error: error)
  718. if result.code == 200 {
  719. complete(true, result)
  720. } else {
  721. complete(false, result)
  722. }
  723. } else {
  724. let error = NSError(domain: "unknown error", code: 404)
  725. let result = Result(result: [:],message: "unknown error",code: 404, error: error)
  726. complete(false, result)
  727. }
  728. semaphore.signal()
  729. }
  730. task.resume()
  731. semaphore.wait()
  732. }
  733. }
  734. /**
  735. @abstract重写 & 纠错
  736. @param content 内容
  737. @param version 版本号
  738. */
  739. func aiRewriting(content: String, version: String, state: KMAIRewritingState, complete: @escaping KMRequestServerComplete) {
  740. let userInfo = KMLightMemberCache.cache.readData(type: .info)
  741. var urlString = KMAIServerConfig().aiRewritingURL + "/api/rewrite"
  742. // if state == .AIErrorCorrection {
  743. // urlString = KMAIServerConfig().aiRewritingURL + "/api/correct-typos"
  744. // }
  745. let params: [String: Any] = ["project_id": 2,
  746. "content": content,
  747. "version": version,
  748. "user_id": userInfo["id"] as Any]
  749. KMRequestServer.requestServer.aiRewriting(urlString: urlString, params: params) { formData in
  750. } requestSerializer: { requestSerializer in
  751. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  752. } completion: { task, responseObject, error in
  753. if responseObject != nil {
  754. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  755. let code: String = responseObject!["code"] as? String ?? "06005"
  756. let message: String = responseObject!["message"] as? String ?? "unknown error"
  757. let error = NSError(domain: message, code: Int(code)!)
  758. let result = Result(result: data,message: message,code: Int(code)!, error: error)
  759. if result.code == 200 {
  760. complete(true, result)
  761. } else {
  762. complete(false, result)
  763. }
  764. } else {
  765. let error = NSError(domain: "unknown error", code: 404)
  766. let result = Result(result: [:],message: "unknown error",code: 404, error: error)
  767. complete(false, result)
  768. }
  769. }
  770. }
  771. }
  772. //MARK: - 数据处理
  773. extension KMRequestServerManager {
  774. func dealData(responseObject: NSDictionary?, error: NSError?) -> Result {
  775. var dic: NSDictionary = [:]
  776. if (error == nil && responseObject != nil) {
  777. dic = responseObject!
  778. } else {
  779. var info = responseObject
  780. if (error != nil) {
  781. let data = error!.userInfo["com.alamofire.serialization.response.error.data"]
  782. if (data != nil) {
  783. info = try?JSONSerialization.jsonObject(with: data as? Data ?? Data(), options: JSONSerialization.ReadingOptions.mutableLeaves) as? NSDictionary
  784. }
  785. dic = info ?? [:]
  786. }
  787. }
  788. let result: NSDictionary = dic["result"] as? NSDictionary ?? [:]
  789. var code: Int = dic["code"] as? Int ?? 0
  790. let message: String = dic["msg"] as? String ?? "unknown error"
  791. let error = NSError(domain: message, code: code)
  792. if result.count == 0 && responseObject != nil && code == 0 {
  793. code = 200
  794. }
  795. if code == 318 {
  796. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.1, execute: {
  797. let alert = NSAlert()
  798. alert.messageText = NSLocalizedString("Unable to Log in", comment: "")
  799. 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: "")
  800. alert.addButton(withTitle: NSLocalizedString("Contact Us", comment: ""))
  801. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  802. var window = NSWindow.currentWindow()
  803. if window != nil {
  804. alert.beginSheetModal(for: window) { result in
  805. if (result == .alertFirstButtonReturn) {
  806. // KMMailHelper.newEmail(withContacts: "support@pdfreaderpro.com", andSubjects: "")
  807. // NSWorkspace.shared.launchApplication("Mailto:support@pdfreaderpro.com")
  808. // NSWorkspace.shared.open(URL(string: "mailto:support@pdfreaderpro.com")!)
  809. NSWorkspace.shared.open(URL(string: "https://www.pdfreaderpro.com/contact")!)
  810. // let service = NSSharingService(named: NSSharingService.Name.composeEmail)
  811. // service?.recipients = ["support@pdfreaderpro.com"]
  812. // service?.subject = "Test Mail"
  813. // service?.perform(withItems: ["Test Mail body"])
  814. } else if result == .alertSecondButtonReturn {
  815. return
  816. }
  817. }
  818. }
  819. })
  820. }
  821. if code == 304 {
  822. self.checkDeviceStatus { success, result in
  823. }
  824. }
  825. if code == 330 {
  826. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: { [unowned self] in
  827. if loginAlert == nil {
  828. loginAlert = NSAlert()
  829. loginAlert?.messageText = NSLocalizedString("Please Log in again", comment: "")
  830. 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: "")
  831. loginAlert?.addButton(withTitle: NSLocalizedString("Change Password", comment: ""))
  832. loginAlert?.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  833. var window = NSWindow.currentWindow()
  834. if window != nil {
  835. loginAlert?.beginSheetModal(for: window) { result in
  836. if (result == .alertFirstButtonReturn) {
  837. if KMLoginWindowController.fetchSampleController() == nil {
  838. KMLoginWindowController.show(window: window)
  839. }
  840. } else if result == .alertSecondButtonReturn {
  841. self.loginAlert = nil
  842. return
  843. }
  844. self.loginAlert = nil
  845. }
  846. } else {
  847. self.loginAlert = nil
  848. }
  849. }
  850. })
  851. }
  852. if code == 343 {
  853. DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2, execute: { [unowned self] in
  854. var window = NSWindow.currentWindow()
  855. let _ = KMAccountExceptionWindowController.show(window: window)
  856. KMLightMemberManager.manager.logOut()
  857. })
  858. }
  859. // if code == 500 {
  860. // let alert = NSAlert()
  861. // alert.messageText = NSLocalizedString(message, comment: "")
  862. // alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  863. // if NSApp.mainWindow != nil {
  864. // alert.beginSheetModal(for: NSApp.mainWindow!)
  865. // } else {
  866. // alert.runModal()
  867. // }
  868. // }
  869. KMPrint(dic)
  870. return Result(result: result,message: message,code: code, error: error)
  871. }
  872. }
  873. extension NSWindow {
  874. static func currentWindow() -> NSWindow {
  875. var window = NSApp.mainWindow
  876. if NSApp.mainWindow?.sheets.first != nil {
  877. window = NSApp.mainWindow?.sheets.first
  878. }
  879. if window == nil {
  880. window = NSApplication.shared.windows.first
  881. }
  882. return window ?? NSWindow()
  883. }
  884. }