KMAIRequestServerManager.swift 29 KB

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