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 token: String = KMMemberInfo.shared.access_token
  214. if token == "" {
  215. return
  216. }
  217. let infoDictionary = Bundle .main.infoDictionary!
  218. let urlString = AIInfoConfig().aiActionURL + "/member-system-website/v1/translate/fileUpload"
  219. let fileData = FileManager.default.contents(atPath: file)
  220. let params: [String: Any] = ["file": fileData,
  221. "uuid": uuid(),
  222. "platform": platform(),
  223. "app_name": app_name(),
  224. "calculate":"1"]
  225. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  226. let fileURL = URL(fileURLWithPath: file)
  227. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  228. } requestSerializer: { requestSerializer in
  229. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  230. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  231. } completion: { task, responseObject, error in
  232. if responseObject != nil {
  233. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  234. var code: String = responseObject!["code"] as? String ?? "06005"
  235. if code == "06005" {
  236. let tempCode: Int = responseObject!["code"] as? Int ?? 0
  237. if tempCode == 501 {
  238. code = "501"
  239. }
  240. }
  241. let message: String = responseObject!["message"] as? String ?? "unknown error"
  242. let error = NSError(domain: message, code: Int(code)!)
  243. // let result = ResultWrapper(success: true, result: data, message: message, code: Int(code)!, error: error, state: .uploadTranslate)
  244. // if result.code == 200 {
  245. // result.success = true
  246. // complete(result)
  247. // } else {
  248. // result.success = false
  249. // complete(result)
  250. // }
  251. if Int(code)! == 200 {
  252. let wrapper = ResultWrapper(success: true, resultData: data)
  253. wrapper.content = data["fileKey"] as! String
  254. complete(wrapper)
  255. } else {
  256. let wrapper = ResultWrapper(success: false, resultData: data)
  257. if Int(code)! == 501 {
  258. wrapper.content = "501"
  259. } else {
  260. wrapper.content = message
  261. }
  262. complete(wrapper)
  263. }
  264. } else {
  265. // let error = NSError(domain: "unknown error", code: 404)
  266. // let result = ResultWrapper(success: false, result: [:], message: "unknown error", code: 404, error: error, state: .uploadTranslate)
  267. // complete(result)
  268. complete(ResultWrapper(success: false, content: "unknown error"))
  269. }
  270. }
  271. }
  272. /**
  273. @abstract 文件翻译
  274. @param fileKey 文件Key
  275. @param from 初始语言
  276. @param to 结束语言
  277. */
  278. func aiTranslationFileTranslateHandle(fileKey: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  279. let token: String = KMMemberInfo.shared.access_token
  280. if token == "" {
  281. return
  282. }
  283. let infoDictionary = Bundle .main.infoDictionary!
  284. let urlString = AIInfoConfig().aiActionURL + "/member-system-website/v1/translate/fileTranslateHandle"
  285. let paraDict = ["fileKey": fileKey,
  286. "from": languageAbbreviation(from),
  287. "to": languageAbbreviation(to),
  288. "uuid": uuid(),
  289. "platform": platform(),
  290. "app_name": app_name()]
  291. var postData = try! JSONSerialization.data(withJSONObject: paraDict)
  292. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  293. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  294. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  295. request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  296. request.httpMethod = "POST"
  297. request.httpBody = postData
  298. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  299. guard let data = data else {
  300. print(String(describing: error))
  301. return
  302. }
  303. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  304. if jsonObject != nil {
  305. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  306. let code: String = jsonObject!["code"] as? String ?? "06005"
  307. let message: String = jsonObject!["message"] as? String ?? "unknown error"
  308. let error = NSError(domain: message, code: Int(code)!)
  309. // let result = ResultWrapper(success: true, result: data1, message: message, code: Int(code)!, error: error, state: .fileTranslate)
  310. // if result.code == 200 {
  311. // result.success = true
  312. // complete(result)
  313. // } else {
  314. // result.success = false
  315. // complete(result)
  316. // }
  317. if Int(code)! == 200 {
  318. let fileUrl = data1["fileUrl"]
  319. let downFileUrl = data1["downFileUrl"]
  320. let ossDownUrl = data1["ossDownUrl"]
  321. let fileName = data1["fileName"]
  322. let downFileName = data1["downFileName"]
  323. let fromStr = data1["from"]
  324. let toStr = data1["to"]
  325. self.downFileName = downFileName as! String
  326. // self.downloadFile(filePath: ossDownUrl as! String, downFileName: downFileName as! String)
  327. complete(ResultWrapper(success: true, content: ossDownUrl as! String))
  328. } else {
  329. complete(ResultWrapper(success: false, content: message))
  330. }
  331. } else {
  332. // let error = NSError(domain: "unknown error", code: 404)
  333. // let result = ResultWrapper(success: false, result: [:], message: "unknown error", code: 404, error: error, state: .fileTranslate)
  334. // complete(result)
  335. complete(ResultWrapper(success: false, content: "unknown error"))
  336. }
  337. }
  338. task.resume()
  339. }
  340. /**
  341. @abstract 内容翻译
  342. @param q 选中
  343. @param from 初始语言
  344. @param to 结束语言
  345. */
  346. private func aiTranslationTextTrans(q: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  347. let token: String = KMMemberInfo.shared.access_token
  348. if token == "" {
  349. return
  350. }
  351. let infoDictionary = Bundle .main.infoDictionary!
  352. let urlString = AIInfoConfig().aiActionURL + "/member-system-website/v1/translate/textTrans"
  353. var escapedString = q
  354. escapedString = String(data: escapedString.data(using: .utf8)!, encoding: .utf8)!
  355. let paraDict = ["text":escapedString,
  356. "from":from,
  357. "to":to,
  358. "uuid":uuid(),
  359. "platform": platform(),
  360. "app_name": app_name()]
  361. var postData = try! JSONSerialization.data(withJSONObject: paraDict)
  362. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  363. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  364. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  365. request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  366. request.httpMethod = "POST"
  367. request.httpBody = postData
  368. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  369. guard let data = data else {
  370. print(String(describing: error))
  371. return
  372. }
  373. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  374. if jsonObject != nil {
  375. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  376. let code: String = jsonObject!["code"] as? String ?? "06005"
  377. let message: String = jsonObject!["message"] as? String ?? "unknown error"
  378. let error = NSError(domain: message, code: Int(code)!)
  379. if Int(code)! == 200 {
  380. var resultStr = data1["dst"] as! String
  381. complete(ResultWrapper(success: true, content: resultStr))
  382. } else {
  383. complete(ResultWrapper(success: false, content: message))
  384. }
  385. } else {
  386. complete(ResultWrapper(success: false, content: "unknown error"))
  387. }
  388. }
  389. task.resume()
  390. }
  391. /**
  392. @abstract重写 & 纠错
  393. @param content 内容
  394. @param state 类型
  395. */
  396. private func aiRewriting(content: String, state: KMAIRewritingState, complete: @escaping KMRequestServerComplete) {
  397. let token: String = KMMemberInfo.shared.access_token
  398. if token == "" {
  399. return
  400. }
  401. var urlString = AIInfoConfig().aiActionURL + "/member-system-website/api/rewrite"
  402. if state == .correctTypos {
  403. urlString = AIInfoConfig().aiActionURL + "/member-system-website/api/correct-typos"
  404. }
  405. let params: [String: Any] = ["content": content,
  406. "uuid": uuid(),
  407. "platform": platform(),
  408. "app_name": app_name()]
  409. KMAIRequestServer.requestServer.aiRewriting(urlString: urlString, params: params) { formData in
  410. } requestSerializer: { requestSerializer in
  411. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  412. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  413. } completion: { task, responseObject, error in
  414. if responseObject != nil {
  415. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  416. let code: String = responseObject!["code"] as? String ?? "06005"
  417. let message: String = responseObject!["message"] as? String ?? "unknown error"
  418. let error = NSError(domain: message, code: Int(code)!)
  419. if Int(code)! == 200 {
  420. complete(ResultWrapper(success: true, content: data["content"] as! String))
  421. } else {
  422. complete(ResultWrapper(success: false, content: message))
  423. }
  424. } else {
  425. complete(ResultWrapper(success: false, content: "unknown error"))
  426. }
  427. }
  428. }
  429. /**
  430. @abstract 提取摘要
  431. @param file 文件路径
  432. */
  433. private func extractSummaryFile(file: String, complete: @escaping KMRequestServerComplete) {
  434. let token: String = KMMemberInfo.shared.access_token
  435. if token == "" {
  436. return
  437. }
  438. let infoDictionary = Bundle .main.infoDictionary!
  439. let urlString = AIInfoConfig().aiActionURL + "/member-system-website/api/extract-file-summary"
  440. let fileData = FileManager.default.contents(atPath: file)
  441. let params: [String: Any] = ["file": fileData,
  442. "uuid": uuid(),
  443. "platform": platform(),
  444. "app_name": app_name()]
  445. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  446. let fileURL = URL(fileURLWithPath: file)
  447. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  448. } requestSerializer: { requestSerializer in
  449. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  450. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  451. } completion: { task, responseObject, error in
  452. if responseObject != nil {
  453. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  454. let code: Int = responseObject!["code"] as? Int ?? 06005
  455. let message: String = responseObject!["message"] as? String ?? "unknown error"
  456. let error = NSError(domain: message, code: code)
  457. if code == 200 {
  458. complete(ResultWrapper(success: true, content: data["summary"] as! String))
  459. } else {
  460. complete(ResultWrapper(success: false, content: message))
  461. }
  462. } else {
  463. let error = NSError(domain: "unknown error", code: 404)
  464. complete(ResultWrapper(success: false, content: "unknown error"))
  465. }
  466. }
  467. }
  468. }
  469. //typealias KMHttpRequestServerComplete = (_ task: URLSessionDataTask?, _ responseObject: AnyObject?, _ error: NSError?) -> Void
  470. class KMAIRequestServer {
  471. var sessionManager: AFHTTPSessionManager!
  472. static let requestServer = KMAIRequestServer()
  473. var task: URLSessionTask?
  474. init() {
  475. let configuration: URLSessionConfiguration = URLSessionConfiguration.default
  476. sessionManager = AFHTTPSessionManager.init(sessionConfiguration: configuration)
  477. sessionManager.securityPolicy = AFSecurityPolicy.default()
  478. }
  479. /**
  480. 上传文件
  481. - 翻译
  482. - 摘要提取
  483. */
  484. func uploadFile(urlString: String,
  485. params: Dictionary<String, Any>?,
  486. body: ((_ formData:AFMultipartFormData) -> Void)?,
  487. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  488. completion: KMHttpRequestServerComplete?) -> Void {
  489. sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
  490. sessionManager.requestSerializer.timeoutInterval = 60
  491. sessionManager.responseSerializer = AFJSONResponseSerializer()
  492. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  493. if (requestSerializer != nil) {
  494. requestSerializer!(sessionManager.requestSerializer);
  495. }
  496. if (body != nil) {
  497. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  498. body!(formData)
  499. } progress: { progress in
  500. } success: { task, responseObject in
  501. let responseObject = responseObject as AnyObject
  502. if (completion != nil) {
  503. completion!(task,responseObject,nil);
  504. }
  505. } failure: { task, error in
  506. if (completion != nil) {
  507. completion!(task, nil, error as NSError);
  508. }
  509. }
  510. } else {
  511. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  512. } success: { task, responseObject in
  513. if (completion != nil) {
  514. let responseObject = responseObject as AnyObject
  515. completion!(task,responseObject,nil);
  516. }
  517. } failure: { task, error in
  518. if (completion != nil) {
  519. completion!(task, nil, error as NSError);
  520. }
  521. }
  522. }
  523. }
  524. /**
  525. 文件翻译
  526. */
  527. func aiFileTranslateHandle(urlString: String,
  528. params: Dictionary<String, Any>?,
  529. body: ((_ formData:AFMultipartFormData) -> Void)?,
  530. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  531. completion: KMHttpRequestServerComplete?) -> Void {
  532. sessionManager.requestSerializer = AFJSONRequestSerializer()
  533. sessionManager.responseSerializer = AFJSONResponseSerializer()
  534. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  535. if (requestSerializer != nil) {
  536. requestSerializer!(sessionManager.requestSerializer);
  537. }
  538. if (body != nil) {
  539. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  540. body!(formData)
  541. } progress: { progress in
  542. } success: { task, responseObject in
  543. let responseObject = responseObject as AnyObject
  544. if (completion != nil) {
  545. completion!(task,responseObject,nil);
  546. }
  547. } failure: { task, error in
  548. if (completion != nil) {
  549. completion!(task, nil, error as NSError);
  550. }
  551. }
  552. } else {
  553. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  554. } success: { task, responseObject in
  555. if (completion != nil) {
  556. let responseObject = responseObject as AnyObject
  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. }
  565. }
  566. /**
  567. 重写
  568. */
  569. func aiRewriting(urlString: String,
  570. params: Dictionary<String, Any>?,
  571. body: ((_ formData:AFMultipartFormData) -> Void)?,
  572. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  573. completion: KMHttpRequestServerComplete?) -> Void {
  574. sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
  575. sessionManager.requestSerializer.timeoutInterval = 60
  576. sessionManager.responseSerializer = AFJSONResponseSerializer()
  577. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  578. if (requestSerializer != nil) {
  579. requestSerializer!(sessionManager.requestSerializer);
  580. }
  581. if (body != nil) {
  582. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  583. body!(formData)
  584. } progress: { progress in
  585. } success: { task, responseObject in
  586. let responseObject = responseObject as AnyObject
  587. if (completion != nil) {
  588. completion!(task,responseObject,nil);
  589. }
  590. } failure: { task, error in
  591. if (completion != nil) {
  592. completion!(task, nil, error as NSError);
  593. }
  594. }
  595. } else {
  596. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  597. } success: { task, responseObject in
  598. if (completion != nil) {
  599. let responseObject = responseObject as AnyObject
  600. completion!(task,responseObject,nil);
  601. }
  602. } failure: { task, error in
  603. if (completion != nil) {
  604. completion!(task, nil, error as NSError);
  605. }
  606. }
  607. }
  608. }
  609. }