KMRequestServerManager.swift 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  1. //
  2. // KMRequestServerManager.swift
  3. // PDF Master
  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 EMAIL_VERIFY_CODE_KEY_ERROR2 = 700
  38. static func typeOfMessage(type: KMRequestServerErrorCodeType?) -> String {
  39. var result: String = ""
  40. switch type {
  41. case .EXCEPTION_MSG_IMAGE_CODE_ERROR:
  42. result = "Graphic verification code error"
  43. case .EXCEPTION_MSG_USER_NOT_FOUND:
  44. result = "Email address is not registered"
  45. case .EXCEPTION_MSG_TOKEN_IS_INVALID:
  46. result = "Invalid token or token has expired"
  47. case .EXCEPTION_MSG_DEVICE_NUM_MAX:
  48. result = "You have reached the maximum number of devices, please log out of other devices and log in again."
  49. case .EXCEPTION_MSG_USER_NOT_LOGIN:
  50. result = "User is not logged in. Please log in and try again."
  51. case .EXCEPTION_MSG_GET_CODE_FAIL:
  52. result = "Failed to obtain authorization code"
  53. case .EXCEPTION_MSG_GET_TOKEN_FAIL:
  54. result = "Failed to obtain token"
  55. case .EMAIL_VERIFY_CODE_KEY_ERROR:
  56. result = "Email code error"
  57. case .EMAIL_REGISTER_ERROR:
  58. result = "Register error"
  59. case .EXCEPTION_MSG_PASSWORD_ERROR:
  60. result = "Wrong password. You can check whether the letter is uppercase or lowercase."
  61. case .EXCEPTION_MSG_CODE_ACTION_ERROR:
  62. result = "Incorrect code"
  63. case .EXCEPTION_MSG_CODE_SEND_ERROR:
  64. result = "Code send error"
  65. case .EXCEPTION_MAIL_CODE_SEND_ERROR:
  66. result = "Mail send error"
  67. case .VERIFY_CODE_SEND_TOO_QUICKLY:
  68. result = "Enter an existing verification code" //result = "Too many codes sent, please try again later."
  69. case .EXCEPTION_MSG_EMAIL_EXIST:
  70. result = "This email is already registered, please log in."
  71. case .EXCEPTION_MSG_EMAIL_NOT_REGISTER:
  72. result = "This account is not registered, click Sign Up to create a new account."
  73. case .EXCEPTION_MSG_EMAIL_LOGOUT_ING:
  74. result = "Your account is currently being canceled and cannot be logged in. If you have any questions, please contact customer service."
  75. case .EXCEPTION_MSG_EMAIL_INVALID:
  76. result = "Please enter the correct email format"
  77. case .EXCEPTION_MSG_PASSWORD_NOT_INCONSISTENT:
  78. result = "Wrong password. You can check whether the letter is uppercase or lowercase." //result = "Passwords are different. Please re-enter them."
  79. case .EXCEPTION_MSG_PASSWORD_SIZE_MIN:
  80. result = "Password must be 6-24 characters" //result = "At least 6 characters"
  81. case .EXCEPTION_MSG_PASSWORD_SIZE_MAX:
  82. result = "Password must be 6-24 characters" //result = "Up to 24 characters"
  83. case .EXCEPTION_MSG_PLEASE_ADD_AUTH_CONFIG:
  84. result = "Please add auth config"
  85. case .EXCEPTION_MSG_USER_SUBSCRIPTION_IN_PROGRESS:
  86. result = "You are still in the subscription and cannot cancel account. Please click Cancel Account after the subscription period ends."
  87. case .EXCEPTION_MSG_USER_TRAIL_IN_PROGRESS:
  88. result = "You are still in the subscription and cannot cancel account. Please click Cancel Account after the trial expired."
  89. case .EXCEPTION_TIME_TRANSFER_ERROR:
  90. result = "Time conversion failure"
  91. case .EMAIL_VERIFY_CODE_KEY_ERROR2:
  92. result = "Email code error"
  93. case .EXCEPTION_MSG_PASSWORD_CONTAIN_EMRTY:
  94. result = "Spaces are not allowed in password" //result = "The password cannot contain Spaces"
  95. case .unknown:
  96. result = ""
  97. case .correct:
  98. result = ""
  99. default:
  100. result = "Network error"
  101. }
  102. return result
  103. }
  104. }
  105. enum KMVerifyCodeType: String, CaseIterable {
  106. case unknown = "" //
  107. case register = "user_register" // 注册
  108. case logOff = "user_log_off" //注销
  109. case resetPassword = "user_reset_password" //重置密码
  110. }
  111. enum KMVerifyEmailType: String, CaseIterable {
  112. case login = "1" // 登录
  113. case register = "2" //注册
  114. }
  115. struct Result {
  116. var result: NSDictionary = [:]
  117. var message: String = ""
  118. var code : Int = 200
  119. var error: NSError?
  120. }
  121. typealias KMRequestServerComplete = (_ success: Bool, _ result: Result?) -> Void
  122. class KMRequestServerManager: NSObject {
  123. static let manager = KMRequestServerManager()
  124. /**
  125. @abstract 获取验证码
  126. @param verifyCodeType 验证入口类型
  127. @param email 邮箱
  128. */
  129. func getVerifyCode(verifyCodeType: KMVerifyCodeType, email: String, complete: @escaping KMRequestServerComplete) {
  130. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/getVerifyCode"
  131. let params: [String: Any] = ["action": verifyCodeType.rawValue,
  132. "appId": "16",
  133. "receiver": email,
  134. "type": "0"]
  135. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: params) { requestSerializer in
  136. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  137. } completion: { [unowned self] (task, responseObject, error) in
  138. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  139. if result.code == 200 {
  140. complete(true, result)
  141. } else {
  142. complete(false, result)
  143. }
  144. }
  145. }
  146. /**
  147. @abstract 注册
  148. @param userName 用户账号(邮箱)
  149. @param verifyCode 验证码
  150. */
  151. func register(userName: String, password: String, verifyCode: String, complete: @escaping (_ success: Bool, _ requestData: KMLightMemberToken?, _ result: Result) -> Void) {
  152. let uuid: String = GetHardwareUUID() ?? ""
  153. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/emailRegister"
  154. let params: [String: Any] = ["appId": "16",
  155. "deviceSign": uuid,
  156. "password": password,
  157. "platformType": "0",
  158. "username": userName,
  159. "verifyCode": verifyCode,
  160. "model": "Mac"]
  161. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  162. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  163. } completion: { [unowned self] task, responseObject, error in
  164. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  165. if result.code == 200 {
  166. //解析数据
  167. KMLightMemberToken.parseData(data: result.result) { data in
  168. //登录成功
  169. KMLightMemberManager.manager.logIn()
  170. complete(true, data, result)
  171. }
  172. } else {
  173. complete(false, nil, result)
  174. }
  175. }
  176. }
  177. /**
  178. @abstract 注销
  179. @param verifyCode 验证码
  180. */
  181. func logOff(verifyCode: String, complete: @escaping KMRequestServerComplete) {
  182. let token: String = KMLightMemberManager.manager.token.access_token
  183. if token == "" {
  184. return
  185. }
  186. var urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/user/logOffForUser"
  187. // let params = ["code":verifyCode]
  188. urlString = urlString + (NSString(format: "?code=%@&appId=%@", verifyCode, "16") as String)
  189. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: nil) { requestSerializer in
  190. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  191. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  192. } completion: { [unowned self] (task, responseObject, error) in
  193. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  194. if result.code == 200 {
  195. //登出
  196. KMLightMemberCache.cache.clean()
  197. KMLightMemberManager.manager.logOut()
  198. complete(true, result)
  199. } else {
  200. complete(false, result)
  201. }
  202. }
  203. }
  204. /**
  205. @abstract 登录
  206. @param email 邮箱
  207. @param password 密码
  208. */
  209. func login(email: String, password: String, complete: @escaping (_ success: Bool, _ requestData: KMLightMemberToken?, _ result: Result?) -> Void) {
  210. var urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/emailLogin"
  211. let uuid: String = GetHardwareUUID() ?? ""
  212. // let params: [String: String] = ["appId": "16",
  213. // "deviceSign": uuid,
  214. // "email": email,
  215. // "password": password,
  216. // "platformType": "0"]
  217. urlString = urlString + (NSString(format: "?appId=16&deviceSign=%@&email=%@&password=%@&platformType=0&model=%@", uuid, email, password, "Mac") as String)
  218. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: nil) { requestSerializer in
  219. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  220. } completion: { [unowned self] (task, responseObject, error) in
  221. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  222. if result.code == 200 {
  223. //解析数据
  224. KMLightMemberToken.parseData(data: result.result) { data in
  225. //登录成功
  226. KMLightMemberManager.manager.logIn()
  227. complete(true, data, nil)
  228. }
  229. } else {
  230. complete(false, nil, result)
  231. }
  232. }
  233. }
  234. /**
  235. @abstract 登出
  236. */
  237. func logout(complete: @escaping KMRequestServerComplete) {
  238. let token: String = KMLightMemberManager.manager.token.access_token
  239. if token == "" {
  240. return
  241. }
  242. let uuid: String = GetHardwareUUID() ?? ""
  243. var urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/user/logout"
  244. // let params: [String: Any] = ["deviceSign": uuid,
  245. // "appId": "16"]
  246. urlString = urlString + (NSString(format: "?appId=16&deviceSign=%@", uuid) as String)
  247. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: nil) { requestSerializer in
  248. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  249. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  250. } completion: { [unowned self] (task, responseObject, error) in
  251. //登出成功
  252. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  253. if result.code == 200 {
  254. //登出
  255. KMLightMemberManager.manager.logOut()
  256. complete(true, result)
  257. } else {
  258. complete(false, result)
  259. }
  260. }
  261. }
  262. /**
  263. @abstract 修改密码
  264. @param url 源文件url
  265. @param data 数据
  266. @retrun document
  267. */
  268. func resetPassword(account: String, firstPassword: String, secondPassword: String, verifyCode: String, complete: @escaping KMRequestServerComplete) {
  269. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/resetPassword"
  270. let params: [String: Any] = ["account": account,
  271. "appId": "16",
  272. "firstPassword": firstPassword,
  273. "platformType": "0",
  274. "secondPassword": secondPassword,
  275. "verifyCode": verifyCode]
  276. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  277. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  278. } completion: { [unowned self] (task, responseObject, error) in
  279. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  280. if result.code == 200 {
  281. complete(true, result)
  282. } else {
  283. complete(false, result)
  284. }
  285. }
  286. }
  287. /**
  288. @abstract 获取用户信息
  289. */
  290. func getUserInfo(complete: @escaping (_ success: Bool, _ data: KMLightMemberUserInfo?, _ result: Result?, _ isLocal: Bool) -> Void) {
  291. let token: String = KMLightMemberManager.manager.token.access_token
  292. if token == "" {
  293. complete(false , nil, Result(message: "token 不存在", code: 304), false)
  294. return
  295. }
  296. //先拿缓存数据 再请求新数据
  297. let cacheData = KMLightMemberCache.cache.readData()
  298. if cacheData.count != 0 {
  299. KMLightMemberUserInfo.parseData(data: cacheData, needSave: false) { data in
  300. complete(true ,data, nil, true)
  301. }
  302. }
  303. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/user/me"
  304. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: nil) { requestSerializer in
  305. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  306. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  307. } completion: { [unowned self] (task, responseObject, error) in
  308. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  309. if result.code == 200 {
  310. //解析数据
  311. KMLightMemberUserInfo.parseData(data: responseObject as! NSDictionary) { data in
  312. KMLightMemberManager.manager.reloadUserInfo()
  313. complete(true, data, nil, false)
  314. }
  315. } else {
  316. complete(false, nil, result, false)
  317. }
  318. }
  319. }
  320. func getUserInfo2() async throws -> (Bool, Result) {
  321. let token: String = KMLightMemberManager.manager.token.access_token
  322. if token == "" {
  323. return (false, Result())
  324. }
  325. if #available(macOS 10.15, *) {
  326. return try await withCheckedThrowingContinuation { continuation in
  327. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/user/me"
  328. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: nil) { requestSerializer in
  329. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  330. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  331. } completion: { [unowned self] (task, responseObject, error) in
  332. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  333. DispatchQueue.main.async {
  334. if result.code == 200 {
  335. //解析数据
  336. KMLightMemberUserInfo.parseData(data: responseObject as! NSDictionary) { data in
  337. KMLightMemberManager.manager.reloadUserInfo()
  338. continuation.resume(returning: (true, result))
  339. }
  340. } else {
  341. continuation.resume(returning: (false, result))
  342. }
  343. }
  344. }
  345. }
  346. } else {
  347. // Fallback on earlier versions
  348. return (true, Result())
  349. }
  350. }
  351. /**
  352. @abstract 验证码验证是否正确
  353. @param account 用户账号(邮箱)
  354. @param verifyCode 验证码
  355. @retrun verifyCodeType 验证码入口类型
  356. */
  357. func verificationCode(account: String, verifyCode: String, verifyCodeType: KMVerifyCodeType, complete: @escaping KMRequestServerComplete) {
  358. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/isEmailCodeValid"
  359. let params: [String: Any] = ["account": account,
  360. "code": verifyCode,
  361. "type": verifyCodeType.rawValue,
  362. "appId": "16"]
  363. KMRequestServer.requestServer.request(urlString: urlString, method: .get, params: params) { requestSerializer in
  364. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  365. } completion: { [unowned self] (task, responseObject, error) in
  366. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  367. if result.code == 200 {
  368. complete(true, result)
  369. } else {
  370. complete(false, result)
  371. }
  372. }
  373. }
  374. /**
  375. @abstract 邮箱验证
  376. @param account 用户账号(邮箱)
  377. @param verifyCodeType 验证码
  378. @retrun verifyCodeType 验证码入口类型
  379. */
  380. func verificationEmail(userName: String, verifyEmailType: KMVerifyEmailType, complete: @escaping KMRequestServerComplete) {
  381. let urlString = KMLightMemberManager.manager.config.kServerURL + "/pdf-office-sso/auth/validUser"
  382. let params: [String: Any] = ["appId": "16",
  383. "username": userName,
  384. "platformType": "0",
  385. "validType": verifyEmailType.rawValue]
  386. KMRequestServer.requestServer.request(urlString: urlString, method: .post, params: params) { requestSerializer in
  387. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  388. } completion: { [unowned self] (task, responseObject, error) in
  389. let result = self.dealData(responseObject: responseObject as? NSDictionary, error: error)
  390. if result.code == 200 {
  391. complete(true, result)
  392. } else {
  393. complete(false, result)
  394. }
  395. }
  396. }
  397. func dealData(responseObject: NSDictionary?, error: NSError?) -> Result {
  398. var dic: NSDictionary = [:]
  399. if (error == nil && responseObject != nil) {
  400. dic = responseObject!
  401. } else {
  402. var info = responseObject
  403. if (error != nil) {
  404. let data = error!.userInfo["com.alamofire.serialization.response.error.data"]
  405. if (data != nil) {
  406. info = try?JSONSerialization.jsonObject(with: data as? Data ?? Data(), options: JSONSerialization.ReadingOptions.mutableLeaves) as? NSDictionary
  407. }
  408. dic = info ?? [:]
  409. }
  410. }
  411. let result: NSDictionary = dic["result"] as? NSDictionary ?? [:]
  412. var code: Int = dic["code"] as? Int ?? 0
  413. let message: String = dic["msg"] as? String ?? "unknown error"
  414. let error = NSError(domain: message, code: code)
  415. if result.count == 0 && responseObject != nil && code == 0 {
  416. code = 200
  417. }
  418. if code == 318 {
  419. let alert = NSAlert()
  420. alert.messageText = NSLocalizedString("Unable to Log in", comment: "")
  421. 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: "")
  422. alert.addButton(withTitle: NSLocalizedString("Contact Us", comment: ""))
  423. alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  424. var window = NSApp.mainWindow
  425. if NSApp.mainWindow?.sheets.first != nil {
  426. window = NSApp.mainWindow?.sheets.first
  427. }
  428. alert.beginSheetModal(for: window!) { result in
  429. if (result == .alertFirstButtonReturn) {
  430. // KMMailHelper.newEmail(withContacts: "support@pdfreaderpro.com", andSubjects: "")
  431. // NSWorkspace.shared.launchApplication("Mailto:support@pdfreaderpro.com")
  432. // NSWorkspace.shared.open(URL(string: "mailto:support@pdfreaderpro.com")!)
  433. NSWorkspace.shared.open(URL(string: "https://www.pdfreaderpro.com/contact")!)
  434. // let service = NSSharingService(named: NSSharingService.Name.composeEmail)
  435. // service?.recipients = ["support@pdfreaderpro.com"]
  436. // service?.subject = "Test Mail"
  437. // service?.perform(withItems: ["Test Mail body"])
  438. } else if result == .alertSecondButtonReturn {
  439. return
  440. }
  441. }
  442. }
  443. // if code == 500 {
  444. // let alert = NSAlert()
  445. // alert.messageText = NSLocalizedString(message, comment: "")
  446. // alert.addButton(withTitle: NSLocalizedString("Cancel", comment: ""))
  447. // if NSApp.mainWindow != nil {
  448. // alert.beginSheetModal(for: NSApp.mainWindow!)
  449. // } else {
  450. // alert.runModal()
  451. // }
  452. // }
  453. print(dic)
  454. return Result(result: result,message: message,code: code, error: error)
  455. }
  456. /**
  457. @abstract 翻译上传
  458. @param file 文件路径
  459. @param version 版本号
  460. */
  461. func aiTranslationFileUpload(file: String, version: String, complete: @escaping KMRequestServerComplete) {
  462. let infoDictionary = Bundle .main.infoDictionary!
  463. let userInfo = KMLightMemberCache.cache.readData(type: .info)
  464. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  465. let urlString = KMAIServerConfig().aiTranslationURL + "/v1/translate/fileUpload"
  466. let fileData = FileManager.default.contents(atPath: file)
  467. let params: [String: Any] = ["file": fileData,
  468. "projectId": "2",
  469. "version": version,
  470. "userId": userInfo["id"] as Any]
  471. KMRequestServer.requestServer.aiTranslation(urlString: urlString, params: params) { formData in
  472. let fileURL = URL(fileURLWithPath: file)
  473. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  474. } requestSerializer: { requestSerializer in
  475. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  476. } completion: { task, responseObject, error in
  477. if responseObject != nil {
  478. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  479. let code: String = responseObject!["code"] as? String ?? "06005"
  480. let message: String = responseObject!["msg"] as? String ?? "unknown error"
  481. let error = NSError(domain: message, code: Int(code)!)
  482. let result = Result(result: data,message: message,code: Int(code)!, error: error)
  483. if result.code == 200 {
  484. complete(true, result)
  485. } else {
  486. complete(false, result)
  487. }
  488. }
  489. }
  490. }
  491. /**
  492. @abstract 文件翻译
  493. @param fileKey 文件Key
  494. @param from 初始语言
  495. @param to 结束语言
  496. @param version 应用版本
  497. */
  498. func aiTranslationFileTranslateHandle(fileKey: String, from: String, to: String, version: String, complete: @escaping KMRequestServerComplete) {
  499. let infoDictionary = Bundle .main.infoDictionary!
  500. let userInfo = KMLightMemberCache.cache.readData(type: .info)
  501. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  502. let urlString = KMAIServerConfig().aiTranslationURL + "/v1/translate/fileTranslateHandle"
  503. var semaphore = DispatchSemaphore (value: 0)
  504. 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)
  505. let postData = parameters.data(using: .utf8)
  506. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  507. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  508. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  509. request.httpMethod = "POST"
  510. request.httpBody = postData
  511. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  512. guard let data = data else {
  513. print(String(describing: error))
  514. semaphore.signal()
  515. return
  516. }
  517. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  518. if jsonObject != nil {
  519. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  520. let code: String = jsonObject!["code"] as? String ?? "06005"
  521. let message: String = jsonObject!["msg"] as? String ?? "unknown error"
  522. let error = NSError(domain: message, code: Int(code)!)
  523. let result = Result(result: data1,message: message,code: Int(code)!, error: error)
  524. if result.code == 200 {
  525. complete(true, result)
  526. } else {
  527. complete(false, result)
  528. }
  529. }
  530. semaphore.signal()
  531. }
  532. task.resume()
  533. semaphore.wait()
  534. }
  535. /**
  536. @abstract 内容翻译
  537. @param q 选中
  538. @param from 初始语言
  539. @param to 结束语言
  540. @param version 应用版本
  541. */
  542. func aiTranslationTextTrans(q: String, from: String, to: String, version: String, complete: @escaping KMRequestServerComplete) {
  543. let infoDictionary = Bundle .main.infoDictionary!
  544. let userInfo = KMLightMemberCache.cache.readData(type: .info)
  545. let majorVersion = infoDictionary["CFBundleShortVersionString"]
  546. let urlString = KMAIServerConfig().aiTranslationURL + "/v1/translate/textTrans"
  547. var semaphore = DispatchSemaphore (value: 0)
  548. var escapedString = q
  549. if q.contains("\n") || q.contains("\r") {
  550. escapedString = q.replacingOccurrences(of: "\n", with: "\\n")
  551. escapedString = escapedString.replacingOccurrences(of: "\r", with: "\\r")
  552. } else if q.contains("\u{2028}") {
  553. }
  554. escapedString = String(data: escapedString.data(using: .utf8)!, encoding: .utf8)!
  555. // let escapedString = String(data: q.data(using: .utf8)!, encoding: .utf8)!
  556. 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)
  557. let postData = parameters.data(using: .utf8)
  558. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  559. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  560. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  561. request.httpMethod = "POST"
  562. request.httpBody = postData
  563. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  564. guard let data = data else {
  565. print(String(describing: error))
  566. semaphore.signal()
  567. return
  568. }
  569. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  570. if jsonObject != nil {
  571. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  572. let code: String = jsonObject!["code"] as? String ?? "06005"
  573. let message: String = jsonObject!["msg"] as? String ?? "unknown error"
  574. let error = NSError(domain: message, code: Int(code)!)
  575. let result = Result(result: data1,message: message,code: Int(code)!, error: error)
  576. if result.code == 200 {
  577. complete(true, result)
  578. } else {
  579. complete(false, result)
  580. }
  581. }
  582. semaphore.signal()
  583. }
  584. task.resume()
  585. semaphore.wait()
  586. }
  587. /**
  588. @abstract重写 & 纠错
  589. @param content 内容
  590. @param version 版本号
  591. */
  592. func aiRewriting(content: String, version: String, state: KMAIRewritingState, complete: @escaping KMRequestServerComplete) {
  593. let userInfo = KMLightMemberCache.cache.readData(type: .info)
  594. var urlString = KMAIServerConfig().aiRewritingURL + "/api/rewrite"
  595. if state == .AIErrorCorrection {
  596. urlString = KMAIServerConfig().aiRewritingURL + "/api/correct-typos"
  597. }
  598. let params: [String: Any] = ["project_id": 2,
  599. "content": content,
  600. "version": version,
  601. "user_id": userInfo["id"] as Any]
  602. KMRequestServer.requestServer.aiRewriting(urlString: urlString, params: params) { formData in
  603. } requestSerializer: { requestSerializer in
  604. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  605. } completion: { task, responseObject, error in
  606. if responseObject != nil {
  607. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  608. let code: String = responseObject!["code"] as? String ?? "06005"
  609. let message: String = responseObject!["message"] as? String ?? "unknown error"
  610. let error = NSError(domain: message, code: Int(code)!)
  611. let result = Result(result: data,message: message,code: Int(code)!, error: error)
  612. if result.code == 200 {
  613. complete(true, result)
  614. } else {
  615. complete(false, result)
  616. }
  617. }
  618. }
  619. }
  620. }