KMAIRequestServerManager.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. //
  2. // KMAIRequestServerManager.swift
  3. // PDF Reader Pro Edition
  4. //
  5. // Created by wanjun on 2024/1/17.
  6. //
  7. import Cocoa
  8. import AFNetworking
  9. @objcMembers
  10. class ResultWrapper: NSObject {
  11. var success: Bool = false
  12. var result: NSDictionary = [:]
  13. var content: String = ""
  14. init(success: Bool, content: String) {
  15. self.success = success
  16. self.content = content
  17. self.result = NSDictionary.init()
  18. }
  19. init(success: Bool, resultData: NSDictionary) {
  20. self.success = success
  21. self.content = ""
  22. self.result = resultData
  23. }
  24. }
  25. @objc enum KMAIRewritingState : Int {
  26. case rewrite = 0 // 重写
  27. case correctTypos // 纠错
  28. case uploadTranslate // 翻译上传文件
  29. case fileTranslate // 翻译文件
  30. case textTranslate // 翻译文本
  31. case extractSummaryFile //摘要
  32. }
  33. @objc enum KMAIFileUploadState : Int {
  34. case Translation = 0
  35. case ExtractAbstract
  36. }
  37. //typealias KMRequestServerComplete = (_ success: Bool, _ result: Result?) -> Void
  38. @objcMembers class KMAIRequestServerManager: NSObject {
  39. static let defaultManager = KMAIRequestServerManager()
  40. typealias KMRequestServerComplete = (_ wrapper: ResultWrapper) -> Void
  41. private var downFileUrl: String = "" // 文件翻译
  42. var downFileName: String = "" // 文件翻译
  43. var fromLanguages: [String] = ["Automatic", "English", "Simplified Chinese", "Traditional Chinese", "Japanese", "Korean", "French", "Spanish", "Italian", "German", "Portuguese", "Russian", "Vietnamese", "Thai", "Arabic", "Greek", "Bulgarian", "Finnish", "Slovene", "Dutch", "Czech", "Swedish", "Polish", "Danish", "Romanian", "Hungarian"]
  44. var toLanguages: [String] = ["English", "Simplified Chinese", "Traditional Chinese", "Japanese", "Korean", "French", "Spanish", "Italian", "German", "Portuguese", "Russian", "Vietnamese", "Thai", "Arabic", "Greek", "Bulgarian", "Finnish", "Slovene", "Dutch", "Czech", "Swedish", "Polish", "Danish", "Romanian", "Hungarian"]
  45. // MARK: AI Action (public)
  46. func aiAction(content: String, state: KMAIRewritingState, from: String = "auto", to: String = "en", complete: @escaping KMRequestServerComplete) {
  47. if state == .rewrite || state == .correctTypos { //重写 && 纠错
  48. aiRewriting(content: content, state: state, complete: complete)
  49. } else if state == .uploadTranslate || state == .fileTranslate { // 上传文件 || 文件翻译
  50. aiTranslationFileUpload(file: content, complete: { [weak self] wrapper in
  51. let success: Bool = wrapper.success
  52. let fileKey = wrapper.content
  53. if success {
  54. let fileData = wrapper.result
  55. complete(wrapper)
  56. } else {
  57. complete(wrapper)
  58. }
  59. })
  60. } else if state == .textTranslate { // 文本翻译
  61. aiTranslationTextTrans(q: content, from: languageAbbreviation(from), to: languageAbbreviation(to), complete: complete)
  62. } else if state == .extractSummaryFile { // 提取摘要
  63. extractSummaryFile(file: content, complete: complete)
  64. }
  65. }
  66. // MARK: Private
  67. private func uuid() -> String {
  68. return GetHardwareUUID()!
  69. }
  70. private func platform() -> String {
  71. var platform = "DMG"
  72. #if VERSION_DMG
  73. platform = "DMG"
  74. #else
  75. platform = "AiStore"
  76. #endif
  77. return platform
  78. }
  79. private func app_name() -> String {
  80. var bundleID: String!
  81. bundleID = Bundle.main.object(forInfoDictionaryKey: "CFBundleIdentifier") as! String
  82. return bundleID;
  83. }
  84. func downloadFile(filePath: String, downFileName: String, toPath: String, complete: @escaping KMRequestServerComplete) {
  85. self.downFileUrl = ""
  86. guard let fileURL = URL(string: filePath) else {
  87. let alert = NSAlert()
  88. alert.alertStyle = .critical
  89. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  90. alert.runModal()
  91. return
  92. }
  93. var destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
  94. if URL(fileURLWithPath: toPath) != nil {
  95. destinationURL = URL(fileURLWithPath: toPath)
  96. }
  97. if FileManager.default.fileExists(atPath: destinationURL.path) {
  98. do {
  99. try FileManager.default.removeItem(at: destinationURL)
  100. print("删除旧文件成功")
  101. } catch {
  102. print("删除旧文件失败:\(error)")
  103. }
  104. }
  105. let sessionConfiguration = URLSessionConfiguration.default
  106. let session = URLSession(configuration: sessionConfiguration)
  107. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  108. if let error = error {
  109. let alert = NSAlert()
  110. alert.alertStyle = .critical
  111. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failed", comment: ""))
  112. alert.runModal()
  113. return
  114. }
  115. guard let tempLocalURL = tempLocalURL else {
  116. let alert = NSAlert()
  117. alert.alertStyle = .critical
  118. alert.messageText = NSLocalizedString("Invalid temporary directory", comment: "")
  119. alert.runModal()
  120. return
  121. }
  122. do {
  123. try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
  124. let wrapper = ResultWrapper(success: true, content: "")
  125. wrapper.content = destinationURL.path
  126. complete(wrapper)
  127. } catch {
  128. let alert = NSAlert()
  129. alert.alertStyle = .critical
  130. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Failed to save file", comment: ""))
  131. alert.runModal()
  132. }
  133. }
  134. self.downFileUrl = destinationURL.path
  135. downloadTask.resume()
  136. }
  137. private func languageAbbreviation(_ language: String) -> String {
  138. if language == "Automatic" || language == "auto" {
  139. return "auto"
  140. } else if language == "English" || language == "en" {
  141. return "en"
  142. } else if language == "Simplified Chinese" || language == "zh" {
  143. return "zh"
  144. } else if language == "Traditional Chinese" || language == "cht" {
  145. return "cht"
  146. } else if language == "Japanese" || language == "jp" {
  147. return "jp"
  148. } else if language == "Korean" || language == "kor" {
  149. return "kor"
  150. } else if language == "French" || language == "fra" {
  151. return "fra"
  152. } else if language == "Spanish" || language == "spa" {
  153. return "spa"
  154. } else if language == "Italian" || language == "it" {
  155. return "it"
  156. } else if language == "German" || language == "de" {
  157. return "de"
  158. } else if language == "Portuguese" || language == "pt" {
  159. return "pt"
  160. } else if language == "Russian" || language == "ru" {
  161. return "ru"
  162. } else if language == "Vietnamese" || language == "vie" {
  163. return "vie"
  164. } else if language == "Thai" || language == "th" {
  165. return "th"
  166. } else if language == "Arabic" || language == "ara" {
  167. return "ara"
  168. } else if language == "Greek" || language == "el" {
  169. return "el"
  170. } else if language == "Bulgarian" || language == "bul" {
  171. return "bul"
  172. } else if language == "Finnish" || language == "fin" {
  173. return "fin"
  174. } else if language == "Slovene" || language == "slo" {
  175. return "slo"
  176. } else if language == "Dutch" || language == "nl" {
  177. return "nl"
  178. } else if language == "Czech" || language == "cs" {
  179. return "cs"
  180. } else if language == "Swedish" || language == "swe" {
  181. return "swe"
  182. } else if language == "Polish" || language == "pl" {
  183. return "pl"
  184. } else if language == "Danish" || language == "dan" {
  185. return "dan"
  186. } else if language == "Romanian" || language == "rom" {
  187. return "rom"
  188. } else if language == "Hungarian" || language == "hu" {
  189. return "hu"
  190. }
  191. return "auto"
  192. }
  193. // MARK: AI Action (private)
  194. /**
  195. @abstract 翻译上传
  196. @param file 文件路径
  197. @param complete 上传完成回调
  198. */
  199. private func aiTranslationFileUpload(file: String, complete: @escaping KMRequestServerComplete) {
  200. let infoDictionary = Bundle .main.infoDictionary!
  201. let urlString = AIInfoConfig().aiActionURL + "/api/AI/uploadTranslate"
  202. let fileData = FileManager.default.contents(atPath: file)
  203. let params: [String: Any] = ["file": fileData,
  204. "uuid": uuid(),
  205. "platform": platform(),
  206. "app_name": app_name(),
  207. "calculate":"1"]
  208. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  209. let fileURL = URL(fileURLWithPath: file)
  210. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  211. } requestSerializer: { requestSerializer in
  212. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  213. } completion: { task, responseObject, error in
  214. if responseObject != nil {
  215. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  216. var code: String = responseObject!["code"] as? String ?? "06005"
  217. if code == "06005" {
  218. let tempCode: Int = responseObject!["code"] as? Int ?? 0
  219. if tempCode == 501 {
  220. code = "501"
  221. }
  222. }
  223. let message: String = responseObject!["message"] as? String ?? "unknown error"
  224. let error = NSError(domain: message, code: Int(code)!)
  225. if Int(code)! == 200 {
  226. let wrapper = ResultWrapper(success: true, resultData: data)
  227. wrapper.content = data["fileKey"] as! String
  228. complete(wrapper)
  229. } else {
  230. let wrapper = ResultWrapper(success: false, resultData: data)
  231. if Int(code)! == 501 {
  232. wrapper.content = "501"
  233. } else {
  234. wrapper.content = message
  235. }
  236. complete(wrapper)
  237. }
  238. } else {
  239. complete(ResultWrapper(success: false, content: "unknown error"))
  240. }
  241. }
  242. }
  243. /**
  244. @abstract 文件翻译
  245. @param fileKey 文件Key
  246. @param from 初始语言
  247. @param to 结束语言
  248. */
  249. func aiTranslationFileTranslateHandle(fileKey: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  250. let infoDictionary = Bundle .main.infoDictionary!
  251. let urlString = AIInfoConfig().aiActionURL + "/api/AI/fileTranslate"
  252. let paraDict = ["fileKey": fileKey,
  253. "from": languageAbbreviation(from),
  254. "to": languageAbbreviation(to),
  255. "uuid": uuid(),
  256. "platform": platform(),
  257. "app_name": app_name()]
  258. var postData = try! JSONSerialization.data(withJSONObject: paraDict)
  259. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  260. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  261. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  262. request.httpMethod = "POST"
  263. request.httpBody = postData
  264. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  265. guard let data = data else {
  266. print(String(describing: error))
  267. return
  268. }
  269. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  270. if jsonObject != nil {
  271. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  272. let code: String = jsonObject!["code"] as? String ?? "06005"
  273. let message: String = jsonObject!["message"] as? String ?? "unknown error"
  274. let error = NSError(domain: message, code: Int(code)!)
  275. if Int(code)! == 200 {
  276. let fileUrl = data1["fileUrl"]
  277. let downFileUrl = data1["downFileUrl"]
  278. let ossDownUrl = data1["ossDownUrl"]
  279. let fileName = data1["fileName"]
  280. let downFileName = data1["downFileName"]
  281. let fromStr = data1["from"]
  282. let toStr = data1["to"]
  283. self.downFileName = downFileName as! String
  284. complete(ResultWrapper(success: true, content: ossDownUrl as! String))
  285. } else {
  286. complete(ResultWrapper(success: false, content: message))
  287. }
  288. } else {
  289. complete(ResultWrapper(success: false, content: "unknown error"))
  290. }
  291. }
  292. task.resume()
  293. }
  294. /**
  295. @abstract 内容翻译
  296. @param q 选中
  297. @param from 初始语言
  298. @param to 结束语言
  299. */
  300. private func aiTranslationTextTrans(q: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  301. let infoDictionary = Bundle .main.infoDictionary!
  302. let urlString = AIInfoConfig().aiActionURL + "/api/AI/textTranslate"
  303. var escapedString = q
  304. escapedString = String(data: escapedString.data(using: .utf8)!, encoding: .utf8)!
  305. let paraDict = ["text":escapedString,
  306. "from":from,
  307. "to":to,
  308. "uuid":uuid(),
  309. "platform": platform(),
  310. "app_name": app_name()]
  311. var postData = try! JSONSerialization.data(withJSONObject: paraDict)
  312. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  313. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  314. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  315. request.httpMethod = "POST"
  316. request.httpBody = postData
  317. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  318. guard let data = data else {
  319. print(String(describing: error))
  320. return
  321. }
  322. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  323. if jsonObject != nil {
  324. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  325. let code: String = jsonObject!["code"] as? String ?? "06005"
  326. let message: String = jsonObject!["message"] as? String ?? "unknown error"
  327. let error = NSError(domain: message, code: Int(code)!)
  328. if Int(code)! == 200 {
  329. var resultStr = data1["dst"] as! String
  330. complete(ResultWrapper(success: true, content: resultStr))
  331. } else {
  332. complete(ResultWrapper(success: false, content: message))
  333. }
  334. } else {
  335. complete(ResultWrapper(success: false, content: "unknown error"))
  336. }
  337. }
  338. task.resume()
  339. }
  340. /**
  341. @abstract重写 & 纠错
  342. @param content 内容
  343. @param state 类型
  344. */
  345. private func aiRewriting(content: String, state: KMAIRewritingState, complete: @escaping KMRequestServerComplete) {
  346. let aiInfo: AIInfo = AIInfoManager.default().aiInfo
  347. if aiInfo.totalToken - aiInfo.usedTimes > 1 {
  348. var urlString = AIInfoConfig().aiActionURL + "/api/AI/rewrite"
  349. if state == .correctTypos {
  350. urlString = AIInfoConfig().aiActionURL + "/api/AI/correctTypos"
  351. }
  352. let params: [String: Any] = ["content": content,
  353. "uuid": uuid(),
  354. "platform": platform(),
  355. "app_name": app_name()]
  356. KMAIRequestServer.requestServer.aiRewriting(urlString: urlString, params: params) { formData in
  357. } requestSerializer: { requestSerializer in
  358. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  359. } completion: { task, responseObject, error in
  360. if responseObject != nil {
  361. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  362. let code: String = responseObject!["code"] as? String ?? "06005"
  363. let message: String = responseObject!["message"] as? String ?? "unknown error"
  364. if Int(code)! == 200 {
  365. complete(ResultWrapper(success: true, content: data["content"] as! String))
  366. } else {
  367. complete(ResultWrapper(success: false, content: message))
  368. }
  369. } else {
  370. complete(ResultWrapper(success: false, content: "unknown error"))
  371. }
  372. }
  373. } else {
  374. let token: String = KMMemberInfo.shared.access_token
  375. if token == "" {
  376. return
  377. }
  378. var urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/rewrite"
  379. if state == .correctTypos {
  380. urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/correct-typos"
  381. }
  382. let params: [String: Any] = ["content": content]
  383. KMAIRequestServer.requestServer.aiMemberRewriting(urlString: urlString, params: params) { formData in
  384. } requestSerializer: { requestSerializer in
  385. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  386. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  387. } completion: { task, responseObject, error in
  388. if responseObject is KMMemberCenterResult {
  389. let resultObjct = responseObject as! KMMemberCenterResult
  390. let code = resultObjct.code
  391. let message: String = resultObjct.msg ?? ""
  392. if code == 200 {
  393. complete(ResultWrapper(success: true, content: message))
  394. } else {
  395. complete(ResultWrapper(success: false, content: message))
  396. }
  397. } else {
  398. complete(ResultWrapper(success: false, content: "unknown error"))
  399. }
  400. }
  401. }
  402. }
  403. /**
  404. @abstract 提取摘要
  405. @param file 文件路径
  406. */
  407. private func extractSummaryFile(file: String, complete: @escaping KMRequestServerComplete) {
  408. let infoDictionary = Bundle .main.infoDictionary!
  409. let urlString = AIInfoConfig().aiActionURL + "/api/AI/extractSummaryFile"
  410. let fileData = FileManager.default.contents(atPath: file)
  411. let params: [String: Any] = ["file": fileData,
  412. "uuid": uuid(),
  413. "platform": platform(),
  414. "app_name": app_name()]
  415. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  416. let fileURL = URL(fileURLWithPath: file)
  417. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  418. } requestSerializer: { requestSerializer in
  419. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  420. } completion: { task, responseObject, error in
  421. if responseObject != nil {
  422. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  423. let code: Int = responseObject!["code"] as? Int ?? 06005
  424. let message: String = responseObject!["message"] as? String ?? "unknown error"
  425. let error = NSError(domain: message, code: code)
  426. if code == 200 {
  427. complete(ResultWrapper(success: true, content: data["summary"] as! String))
  428. } else {
  429. complete(ResultWrapper(success: false, content: message))
  430. }
  431. } else {
  432. let error = NSError(domain: "unknown error", code: 404)
  433. complete(ResultWrapper(success: false, content: "unknown error"))
  434. }
  435. }
  436. }
  437. }
  438. //typealias KMHttpRequestServerComplete = (_ task: URLSessionDataTask?, _ responseObject: AnyObject?, _ error: NSError?) -> Void
  439. class KMAIRequestServer {
  440. var sessionManager: AFHTTPSessionManager!
  441. static let requestServer = KMAIRequestServer()
  442. var task: URLSessionTask?
  443. init() {
  444. let configuration: URLSessionConfiguration = URLSessionConfiguration.default
  445. sessionManager = AFHTTPSessionManager.init(sessionConfiguration: configuration)
  446. sessionManager.securityPolicy = AFSecurityPolicy.default()
  447. }
  448. /**
  449. 上传文件
  450. - 翻译
  451. - 摘要提取
  452. */
  453. func uploadFile(urlString: String,
  454. params: Dictionary<String, Any>?,
  455. body: ((_ formData:AFMultipartFormData) -> Void)?,
  456. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  457. completion: KMHttpRequestServerComplete?) -> Void {
  458. sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
  459. sessionManager.requestSerializer.timeoutInterval = 60
  460. sessionManager.responseSerializer = AFJSONResponseSerializer()
  461. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  462. if (requestSerializer != nil) {
  463. requestSerializer!(sessionManager.requestSerializer);
  464. }
  465. if (body != nil) {
  466. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  467. body!(formData)
  468. } progress: { progress in
  469. } success: { task, responseObject in
  470. let responseObject = responseObject as AnyObject
  471. if (completion != nil) {
  472. completion!(task,responseObject,nil);
  473. }
  474. } failure: { task, error in
  475. if (completion != nil) {
  476. completion!(task, nil, error as NSError);
  477. }
  478. }
  479. } else {
  480. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  481. } success: { task, responseObject in
  482. if (completion != nil) {
  483. let responseObject = responseObject as AnyObject
  484. completion!(task,responseObject,nil);
  485. }
  486. } failure: { task, error in
  487. if (completion != nil) {
  488. completion!(task, nil, error as NSError);
  489. }
  490. }
  491. }
  492. }
  493. /**
  494. 文件翻译
  495. */
  496. func aiFileTranslateHandle(urlString: String,
  497. params: Dictionary<String, Any>?,
  498. body: ((_ formData:AFMultipartFormData) -> Void)?,
  499. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  500. completion: KMHttpRequestServerComplete?) -> Void {
  501. sessionManager.requestSerializer = AFJSONRequestSerializer()
  502. sessionManager.responseSerializer = AFJSONResponseSerializer()
  503. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  504. if (requestSerializer != nil) {
  505. requestSerializer!(sessionManager.requestSerializer);
  506. }
  507. if (body != nil) {
  508. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  509. body!(formData)
  510. } progress: { progress in
  511. } success: { task, responseObject in
  512. let responseObject = responseObject as AnyObject
  513. if (completion != nil) {
  514. completion!(task,responseObject,nil);
  515. }
  516. } failure: { task, error in
  517. if (completion != nil) {
  518. completion!(task, nil, error as NSError);
  519. }
  520. }
  521. } else {
  522. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  523. } success: { task, responseObject in
  524. if (completion != nil) {
  525. let responseObject = responseObject as AnyObject
  526. completion!(task,responseObject,nil);
  527. }
  528. } failure: { task, error in
  529. if (completion != nil) {
  530. completion!(task, nil, error as NSError);
  531. }
  532. }
  533. }
  534. }
  535. /**
  536. 重写
  537. */
  538. func aiRewriting(urlString: String,
  539. params: Dictionary<String, Any>?,
  540. body: ((_ formData:AFMultipartFormData) -> Void)?,
  541. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  542. completion: KMHttpRequestServerComplete?) -> Void {
  543. sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
  544. sessionManager.requestSerializer.timeoutInterval = 60
  545. sessionManager.responseSerializer = AFJSONResponseSerializer()
  546. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  547. if (requestSerializer != nil) {
  548. requestSerializer!(sessionManager.requestSerializer);
  549. }
  550. if (body != nil) {
  551. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  552. body!(formData)
  553. } progress: { progress in
  554. } success: { task, responseObject in
  555. let responseObject = responseObject as AnyObject
  556. if (completion != nil) {
  557. completion!(task,responseObject,nil);
  558. }
  559. } failure: { task, error in
  560. if (completion != nil) {
  561. completion!(task, nil, error as NSError);
  562. }
  563. }
  564. } else {
  565. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  566. } success: { task, responseObject in
  567. if (completion != nil) {
  568. let responseObject = responseObject as AnyObject
  569. completion!(task,responseObject,nil);
  570. }
  571. } failure: { task, error in
  572. if (completion != nil) {
  573. completion!(task, nil, error as NSError);
  574. }
  575. }
  576. }
  577. }
  578. func aiMemberRewriting(urlString: String,
  579. params: Dictionary<String, Any>?,
  580. body: ((_ formData:AFMultipartFormData) -> Void)?,
  581. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  582. completion: KMHttpRequestServerComplete?) -> Void {
  583. let token: String = KMMemberInfo.shared.access_token
  584. let urlString = urlString
  585. let paraDict: [String: Any] = params!
  586. let postData = try! JSONSerialization.data(withJSONObject: paraDict)
  587. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  588. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  589. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  590. request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  591. request.httpMethod = "POST"
  592. request.httpBody = postData
  593. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  594. guard let data = data else {
  595. print(String(describing: error))
  596. return
  597. }
  598. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  599. if jsonObject != nil {
  600. let codeStr: String = jsonObject!["code"] as! String
  601. var code: Int = 0
  602. if let numCode = Int(codeStr) {
  603. code = numCode
  604. }
  605. var result_bool: Bool = true
  606. var message: String = ""
  607. if let string = jsonObject!["data"] {
  608. let dataDic = jsonObject!["data"] as? NSDictionary ?? [:]
  609. if let dataStr = dataDic["content"] {
  610. message = dataStr as! String
  611. result_bool = true
  612. }
  613. }
  614. let result = KMMemberCenterResult(code: code, msg: message, result: result_bool)
  615. if code == 200 {
  616. if (completion != nil) {
  617. completion!(nil, result, nil);
  618. }
  619. } else {
  620. if (completion != nil) {
  621. completion!(nil, nil, error as? NSError);
  622. }
  623. }
  624. } else {
  625. if (completion != nil) {
  626. completion!(nil, nil, error as? NSError);
  627. }
  628. }
  629. }
  630. task.resume()
  631. }
  632. }