KMAIRequestServerManager.swift 29 KB

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