KMAIRequestServerManager.swift 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916
  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. let aiInfo: AIInfo = AIInfoManager.default().aiInfo
  51. if aiInfo.totalToken - aiInfo.usedTimes > 1 {
  52. aiTranslationFileUpload(file: content, complete: { [weak self] wrapper in
  53. let success: Bool = wrapper.success
  54. let fileKey = wrapper.content
  55. if success {
  56. let fileData = wrapper.result
  57. complete(wrapper)
  58. } else {
  59. complete(wrapper)
  60. }
  61. })
  62. } else {
  63. memberAITranslationFileUpload(file: content, complete: { [weak self] wrapper in
  64. let success: Bool = wrapper.success
  65. let fileKey = wrapper.content
  66. if success {
  67. let fileData = wrapper.result
  68. complete(wrapper)
  69. } else {
  70. complete(wrapper)
  71. }
  72. })
  73. }
  74. } else if state == .textTranslate { // 文本翻译
  75. let aiInfo: AIInfo = AIInfoManager.default().aiInfo
  76. if aiInfo.totalToken - aiInfo.usedTimes > 1 {
  77. aiTranslationTextTrans(q: content, from: languageAbbreviation(from), to: languageAbbreviation(to), complete: complete)
  78. } else {
  79. aiMemberTranslationTextTrans(q: content, from: languageAbbreviation(from), to: languageAbbreviation(to), complete: complete)
  80. }
  81. } else if state == .extractSummaryFile { // 提取摘要
  82. let aiInfo: AIInfo = AIInfoManager.default().aiInfo
  83. if aiInfo.totalToken - aiInfo.usedTimes > 1 {
  84. extractSummaryFile(file: content, complete: complete)
  85. } else {
  86. memberExtractSummaryFile(file: content, complete: complete)
  87. }
  88. }
  89. }
  90. // MARK: Private
  91. private func uuid() -> String {
  92. return GetHardwareUUID()!
  93. }
  94. private func platform() -> String {
  95. var platform = "DMG"
  96. #if VERSION_DMG
  97. platform = "DMG"
  98. #else
  99. platform = "AiStore"
  100. #endif
  101. return platform
  102. }
  103. private func app_name() -> String {
  104. var bundleID: String!
  105. bundleID = Bundle.main.object(forInfoDictionaryKey: "CFBundleIdentifier") as! String
  106. return bundleID;
  107. }
  108. func downloadFile(filePath: String, downFileName: String, toPath: String, complete: @escaping KMRequestServerComplete) {
  109. self.downFileUrl = ""
  110. guard let fileURL = URL(string: filePath) else {
  111. let alert = NSAlert()
  112. alert.alertStyle = .critical
  113. alert.messageText = NSLocalizedString("Invalid file link", comment: "")
  114. alert.runModal()
  115. return
  116. }
  117. var destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
  118. if URL(fileURLWithPath: toPath) != nil {
  119. destinationURL = URL(fileURLWithPath: toPath)
  120. }
  121. if FileManager.default.fileExists(atPath: destinationURL.path) {
  122. do {
  123. try FileManager.default.removeItem(at: destinationURL)
  124. print("删除旧文件成功")
  125. } catch {
  126. print("删除旧文件失败:\(error)")
  127. }
  128. }
  129. let sessionConfiguration = URLSessionConfiguration.default
  130. let session = URLSession(configuration: sessionConfiguration)
  131. let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
  132. if let error = error {
  133. let alert = NSAlert()
  134. alert.alertStyle = .critical
  135. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failed", comment: ""))
  136. alert.runModal()
  137. return
  138. }
  139. guard let tempLocalURL = tempLocalURL else {
  140. let alert = NSAlert()
  141. alert.alertStyle = .critical
  142. alert.messageText = NSLocalizedString("Invalid temporary directory", comment: "")
  143. alert.runModal()
  144. return
  145. }
  146. do {
  147. try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
  148. let wrapper = ResultWrapper(success: true, content: "")
  149. wrapper.content = destinationURL.path
  150. complete(wrapper)
  151. } catch {
  152. let alert = NSAlert()
  153. alert.alertStyle = .critical
  154. alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Failed to save file", comment: ""))
  155. alert.runModal()
  156. }
  157. }
  158. self.downFileUrl = destinationURL.path
  159. downloadTask.resume()
  160. }
  161. private func languageAbbreviation(_ language: String) -> String {
  162. if language == "Automatic" || language == "auto" {
  163. return "auto"
  164. } else if language == "English" || language == "en" {
  165. return "en"
  166. } else if language == "Simplified Chinese" || language == "zh" {
  167. return "zh"
  168. } else if language == "Traditional Chinese" || language == "cht" {
  169. return "cht"
  170. } else if language == "Japanese" || language == "jp" {
  171. return "jp"
  172. } else if language == "Korean" || language == "kor" {
  173. return "kor"
  174. } else if language == "French" || language == "fra" {
  175. return "fra"
  176. } else if language == "Spanish" || language == "spa" {
  177. return "spa"
  178. } else if language == "Italian" || language == "it" {
  179. return "it"
  180. } else if language == "German" || language == "de" {
  181. return "de"
  182. } else if language == "Portuguese" || language == "pt" {
  183. return "pt"
  184. } else if language == "Russian" || language == "ru" {
  185. return "ru"
  186. } else if language == "Vietnamese" || language == "vie" {
  187. return "vie"
  188. } else if language == "Thai" || language == "th" {
  189. return "th"
  190. } else if language == "Arabic" || language == "ara" {
  191. return "ara"
  192. } else if language == "Greek" || language == "el" {
  193. return "el"
  194. } else if language == "Bulgarian" || language == "bul" {
  195. return "bul"
  196. } else if language == "Finnish" || language == "fin" {
  197. return "fin"
  198. } else if language == "Slovene" || language == "slo" {
  199. return "slo"
  200. } else if language == "Dutch" || language == "nl" {
  201. return "nl"
  202. } else if language == "Czech" || language == "cs" {
  203. return "cs"
  204. } else if language == "Swedish" || language == "swe" {
  205. return "swe"
  206. } else if language == "Polish" || language == "pl" {
  207. return "pl"
  208. } else if language == "Danish" || language == "dan" {
  209. return "dan"
  210. } else if language == "Romanian" || language == "rom" {
  211. return "rom"
  212. } else if language == "Hungarian" || language == "hu" {
  213. return "hu"
  214. }
  215. return "auto"
  216. }
  217. // MARK: AI Action (private)
  218. /**
  219. @abstract 翻译上传
  220. @param file 文件路径
  221. @param complete 上传完成回调
  222. */
  223. private func aiTranslationFileUpload(file: String, complete: @escaping KMRequestServerComplete) {
  224. let infoDictionary = Bundle .main.infoDictionary!
  225. let urlString = AIInfoConfig().aiActionURL + "/api/AI/uploadTranslate"
  226. let fileData = FileManager.default.contents(atPath: file)
  227. let params: [String: Any] = ["file": fileData,
  228. "uuid": uuid(),
  229. "platform": platform(),
  230. "app_name": app_name(),
  231. "calculate":"1"]
  232. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  233. let fileURL = URL(fileURLWithPath: file)
  234. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  235. } requestSerializer: { requestSerializer in
  236. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  237. } completion: { task, responseObject, error in
  238. if responseObject != nil {
  239. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  240. var code: String = responseObject!["code"] as? String ?? "06005"
  241. if code == "06005" {
  242. let tempCode: Int = responseObject!["code"] as? Int ?? 0
  243. if tempCode == 501 {
  244. code = "501"
  245. }
  246. }
  247. let message: String = responseObject!["message"] as? String ?? "unknown error"
  248. let error = NSError(domain: message, code: Int(code)!)
  249. if Int(code)! == 200 {
  250. let wrapper = ResultWrapper(success: true, resultData: data)
  251. wrapper.content = data["fileKey"] as! String
  252. complete(wrapper)
  253. } else {
  254. let wrapper = ResultWrapper(success: false, resultData: data)
  255. if Int(code)! == 501 {
  256. wrapper.content = "501"
  257. } else {
  258. wrapper.content = message
  259. }
  260. complete(wrapper)
  261. }
  262. } else {
  263. complete(ResultWrapper(success: false, content: "unknown error"))
  264. }
  265. }
  266. }
  267. private func memberAITranslationFileUpload(file: String, complete: @escaping KMRequestServerComplete) {
  268. let token: String = KMMemberInfo.shared.access_token
  269. if token == "" {
  270. return
  271. }
  272. let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/v1/translate/fileUpload"
  273. let fileData = FileManager.default.contents(atPath: file)
  274. let params: [String: Any] = ["file" : fileData,
  275. "calculate" : "1"]
  276. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  277. let fileURL = URL(fileURLWithPath: file)
  278. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  279. } requestSerializer: { requestSerializer in
  280. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  281. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  282. } completion: { task, responseObject, error in
  283. if responseObject != nil {
  284. let data: NSDictionary = responseObject as? NSDictionary ?? [:]
  285. if data.count > 0 {
  286. let code: String = data["code"] as? String ?? "06005"
  287. if Int(code)! == 200, let dataDic = data["data"] {
  288. let wrapper = ResultWrapper(success: true, resultData: dataDic as! NSDictionary)
  289. if let value = data["fileKey"] {
  290. wrapper.content = value as! String
  291. }
  292. complete(wrapper)
  293. } else {
  294. let wrapper = ResultWrapper(success: false, resultData: data)
  295. if let value = data["msg"] {
  296. wrapper.content = value as! String
  297. }
  298. complete(wrapper)
  299. }
  300. } else {
  301. let error = NSError(domain: "unknown error", code: 404)
  302. complete(ResultWrapper(success: false, content: "unknown error"))
  303. }
  304. } else {
  305. let error = NSError(domain: "unknown error", code: 404)
  306. complete(ResultWrapper(success: false, content: "unknown error"))
  307. }
  308. }
  309. }
  310. /**
  311. @abstract 文件翻译
  312. @param fileKey 文件Key
  313. @param from 初始语言
  314. @param to 结束语言
  315. */
  316. func aiTranslationFileTranslateHandle(fileKey: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  317. let aiInfo: AIInfo = AIInfoManager.default().aiInfo
  318. if aiInfo.totalToken - aiInfo.usedTimes > 1 {
  319. let infoDictionary = Bundle .main.infoDictionary!
  320. let urlString = AIInfoConfig().aiActionURL + "/api/AI/fileTranslate"
  321. let paraDict = ["fileKey": fileKey,
  322. "from": languageAbbreviation(from),
  323. "to": languageAbbreviation(to),
  324. "uuid": uuid(),
  325. "platform": platform(),
  326. "app_name": app_name()]
  327. var postData = try! JSONSerialization.data(withJSONObject: paraDict)
  328. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  329. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  330. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  331. request.httpMethod = "POST"
  332. request.httpBody = postData
  333. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  334. guard let data = data else {
  335. print(String(describing: error))
  336. return
  337. }
  338. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  339. if jsonObject != nil {
  340. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  341. let code: String = jsonObject!["code"] as? String ?? "06005"
  342. let message: String = jsonObject!["message"] as? String ?? "unknown error"
  343. let error = NSError(domain: message, code: Int(code)!)
  344. if Int(code)! == 200 {
  345. let fileUrl = data1["fileUrl"]
  346. let downFileUrl = data1["downFileUrl"]
  347. let ossDownUrl = data1["ossDownUrl"]
  348. let fileName = data1["fileName"]
  349. let downFileName = data1["downFileName"]
  350. let fromStr = data1["from"]
  351. let toStr = data1["to"]
  352. self.downFileName = downFileName as! String
  353. complete(ResultWrapper(success: true, content: ossDownUrl as! String))
  354. } else {
  355. complete(ResultWrapper(success: false, content: message))
  356. }
  357. } else {
  358. complete(ResultWrapper(success: false, content: "unknown error"))
  359. }
  360. }
  361. task.resume()
  362. } else {
  363. memberAITranslationFileTranslateHandle(fileKey: fileKey, from: from, to: to, complete: complete)
  364. }
  365. }
  366. func memberAITranslationFileTranslateHandle(fileKey: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  367. let token: String = KMMemberInfo.shared.access_token
  368. let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/v1/translate/fileTranslateHandle"
  369. let paraDict = ["fileKey": fileKey,
  370. "from": languageAbbreviation(from),
  371. "to": languageAbbreviation(to)]
  372. let postData = try! JSONSerialization.data(withJSONObject: paraDict)
  373. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  374. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  375. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  376. request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  377. request.httpMethod = "POST"
  378. request.httpBody = postData
  379. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  380. guard let data = data else {
  381. print(String(describing: error))
  382. return
  383. }
  384. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  385. if jsonObject != nil {
  386. let codeStr: String = jsonObject!["code"] as! String
  387. var code: Int = 0
  388. if let numCode = Int(codeStr) {
  389. code = numCode
  390. }
  391. var result_bool: Bool = true
  392. var message: String = ""
  393. let result = KMMemberCenterResult(code: code, msg: message, result: result_bool)
  394. if code == 200 {
  395. if jsonObject!["data"] != nil {
  396. let dataDic = jsonObject!["data"] as? NSDictionary ?? [:]
  397. let fileUrl = dataDic["fileUrl"]
  398. let downFileUrl = dataDic["downFileUrl"]
  399. let ossDownUrl = dataDic["ossDownUrl"]
  400. let fileName = dataDic["fileName"]
  401. let downFileName = dataDic["downFileName"]
  402. let fromStr = dataDic["from"]
  403. let toStr = dataDic["to"]
  404. self.downFileName = downFileName as! String
  405. complete(ResultWrapper(success: true, content: ossDownUrl as! String))
  406. }
  407. } else {
  408. complete(ResultWrapper(success: false, content: ""))
  409. }
  410. } else {
  411. complete(ResultWrapper(success: false, content: ""))
  412. }
  413. }
  414. task.resume()
  415. }
  416. /**
  417. @abstract 内容翻译
  418. @param q 选中
  419. @param from 初始语言
  420. @param to 结束语言
  421. */
  422. private func aiTranslationTextTrans(q: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  423. let infoDictionary = Bundle .main.infoDictionary!
  424. let urlString = AIInfoConfig().aiActionURL + "/api/AI/textTranslate"
  425. var escapedString = q
  426. escapedString = String(data: escapedString.data(using: .utf8)!, encoding: .utf8)!
  427. let paraDict = ["text":escapedString,
  428. "from":from,
  429. "to":to,
  430. "uuid":uuid(),
  431. "platform": platform(),
  432. "app_name": app_name()]
  433. var postData = try! JSONSerialization.data(withJSONObject: paraDict)
  434. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  435. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  436. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  437. request.httpMethod = "POST"
  438. request.httpBody = postData
  439. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  440. guard let data = data else {
  441. print(String(describing: error))
  442. return
  443. }
  444. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  445. if jsonObject != nil {
  446. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  447. let code: String = jsonObject!["code"] as? String ?? "06005"
  448. let message: String = jsonObject!["message"] as? String ?? "unknown error"
  449. let error = NSError(domain: message, code: Int(code)!)
  450. if Int(code)! == 200 {
  451. var resultStr = data1["dst"] as! String
  452. complete(ResultWrapper(success: true, content: resultStr))
  453. } else {
  454. complete(ResultWrapper(success: false, content: message))
  455. }
  456. } else {
  457. complete(ResultWrapper(success: false, content: "unknown error"))
  458. }
  459. }
  460. task.resume()
  461. }
  462. private func aiMemberTranslationTextTrans(q: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  463. let token: String = KMMemberInfo.shared.access_token
  464. if token == "" {
  465. return
  466. }
  467. let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/v1/translate/textTrans"
  468. var escapedString = q
  469. escapedString = String(data: escapedString.data(using: .utf8)!, encoding: .utf8)!
  470. let paraDict = ["text":escapedString,
  471. "from":from,
  472. "to":to,
  473. "uuid":uuid(),
  474. "platform": platform(),
  475. "app_name": app_name()]
  476. var postData = try! JSONSerialization.data(withJSONObject: paraDict)
  477. KMAIRequestServer.requestServer.aiMemberRewriting(urlString: urlString, params: paraDict) { formData in
  478. } requestSerializer: { requestSerializer in
  479. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  480. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  481. } completion: { task, responseObject, error in
  482. if responseObject is KMMemberCenterResult {
  483. let resultObjct = responseObject as! KMMemberCenterResult
  484. let code = resultObjct.code
  485. let message: String = resultObjct.msg ?? ""
  486. if code == 200 {
  487. complete(ResultWrapper(success: true, content: message))
  488. } else {
  489. complete(ResultWrapper(success: false, content: message))
  490. }
  491. } else {
  492. complete(ResultWrapper(success: false, content: "unknown error"))
  493. }
  494. }
  495. }
  496. /**
  497. @abstract重写 & 纠错
  498. @param content 内容
  499. @param state 类型
  500. */
  501. private func aiRewriting(content: String, state: KMAIRewritingState, complete: @escaping KMRequestServerComplete) {
  502. let aiInfo: AIInfo = AIInfoManager.default().aiInfo
  503. if aiInfo.totalToken - aiInfo.usedTimes > 1 {
  504. var urlString = AIInfoConfig().aiActionURL + "/api/AI/rewrite"
  505. if state == .correctTypos {
  506. urlString = AIInfoConfig().aiActionURL + "/api/AI/correctTypos"
  507. }
  508. let params: [String: Any] = ["content": content,
  509. "uuid": uuid(),
  510. "platform": platform(),
  511. "app_name": app_name()]
  512. KMAIRequestServer.requestServer.aiRewriting(urlString: urlString, params: params) { formData in
  513. } requestSerializer: { requestSerializer in
  514. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  515. } completion: { task, responseObject, error in
  516. if responseObject != nil {
  517. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  518. let code: String = responseObject!["code"] as? String ?? "06005"
  519. let message: String = responseObject!["message"] as? String ?? "unknown error"
  520. if Int(code)! == 200 {
  521. complete(ResultWrapper(success: true, content: data["content"] as! String))
  522. } else {
  523. complete(ResultWrapper(success: false, content: message))
  524. }
  525. } else {
  526. complete(ResultWrapper(success: false, content: "unknown error"))
  527. }
  528. }
  529. } else {
  530. let token: String = KMMemberInfo.shared.access_token
  531. if token == "" {
  532. return
  533. }
  534. var urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/rewrite"
  535. if state == .correctTypos {
  536. urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/correct-typos"
  537. }
  538. let params: [String: Any] = ["content": content]
  539. KMAIRequestServer.requestServer.aiMemberRewriting(urlString: urlString, params: params) { formData in
  540. } requestSerializer: { requestSerializer in
  541. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  542. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  543. } completion: { task, responseObject, error in
  544. if responseObject is KMMemberCenterResult {
  545. let resultObjct = responseObject as! KMMemberCenterResult
  546. let code = resultObjct.code
  547. let message: String = resultObjct.msg ?? ""
  548. if code == 200 {
  549. complete(ResultWrapper(success: true, content: message))
  550. } else {
  551. complete(ResultWrapper(success: false, content: message))
  552. }
  553. } else {
  554. complete(ResultWrapper(success: false, content: "unknown error"))
  555. }
  556. }
  557. }
  558. }
  559. /**
  560. @abstract 提取摘要
  561. @param file 文件路径
  562. */
  563. private func extractSummaryFile(file: String, complete: @escaping KMRequestServerComplete) {
  564. let infoDictionary = Bundle .main.infoDictionary!
  565. let urlString = AIInfoConfig().aiActionURL + "/api/AI/extractSummaryFile"
  566. let fileData = FileManager.default.contents(atPath: file)
  567. let params: [String: Any] = ["file": fileData,
  568. "uuid": uuid(),
  569. "platform": platform(),
  570. "app_name": app_name()]
  571. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  572. let fileURL = URL(fileURLWithPath: file)
  573. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  574. } requestSerializer: { requestSerializer in
  575. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  576. } completion: { task, responseObject, error in
  577. if responseObject != nil {
  578. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  579. let code: Int = responseObject!["code"] as? Int ?? 06005
  580. let message: String = responseObject!["message"] as? String ?? "unknown error"
  581. let error = NSError(domain: message, code: code)
  582. if code == 200 {
  583. complete(ResultWrapper(success: true, content: data["summary"] as! String))
  584. } else {
  585. complete(ResultWrapper(success: false, content: message))
  586. }
  587. } else {
  588. let error = NSError(domain: "unknown error", code: 404)
  589. complete(ResultWrapper(success: false, content: "unknown error"))
  590. }
  591. }
  592. }
  593. private func memberExtractSummaryFile(file: String, complete: @escaping KMRequestServerComplete) {
  594. let token: String = KMMemberInfo.shared.access_token
  595. if token == "" {
  596. return
  597. }
  598. let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/extract-file-summary"
  599. let fileData = FileManager.default.contents(atPath: file)
  600. let params: [String: Any] = ["file": fileData]
  601. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  602. let fileURL = URL(fileURLWithPath: file)
  603. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  604. } requestSerializer: { requestSerializer in
  605. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  606. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  607. } completion: { task, responseObject, error in
  608. if responseObject != nil {
  609. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  610. let code: Int = responseObject!["code"] as? Int ?? 06005
  611. let message: String = responseObject!["message"] as? String ?? "unknown error"
  612. let error = NSError(domain: message, code: code)
  613. if code == 200 {
  614. complete(ResultWrapper(success: true, content: data["summary"] as! String))
  615. } else {
  616. complete(ResultWrapper(success: false, content: message))
  617. }
  618. } else {
  619. let error = NSError(domain: "unknown error", code: 404)
  620. complete(ResultWrapper(success: false, content: "unknown error"))
  621. }
  622. }
  623. }
  624. }
  625. //typealias KMHttpRequestServerComplete = (_ task: URLSessionDataTask?, _ responseObject: AnyObject?, _ error: NSError?) -> Void
  626. class KMAIRequestServer {
  627. var sessionManager: AFHTTPSessionManager!
  628. static let requestServer = KMAIRequestServer()
  629. var task: URLSessionTask?
  630. init() {
  631. let configuration: URLSessionConfiguration = URLSessionConfiguration.default
  632. sessionManager = AFHTTPSessionManager.init(sessionConfiguration: configuration)
  633. sessionManager.securityPolicy = AFSecurityPolicy.default()
  634. }
  635. /**
  636. 上传文件
  637. - 翻译
  638. - 摘要提取
  639. */
  640. func uploadFile(urlString: String,
  641. params: Dictionary<String, Any>?,
  642. body: ((_ formData:AFMultipartFormData) -> Void)?,
  643. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  644. completion: KMHttpRequestServerComplete?) -> Void {
  645. sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
  646. sessionManager.requestSerializer.timeoutInterval = 60
  647. sessionManager.responseSerializer = AFJSONResponseSerializer()
  648. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  649. if (requestSerializer != nil) {
  650. requestSerializer!(sessionManager.requestSerializer);
  651. }
  652. if (body != nil) {
  653. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  654. body!(formData)
  655. } progress: { progress in
  656. } success: { task, responseObject in
  657. let responseObject = responseObject as AnyObject
  658. if (completion != nil) {
  659. completion!(task,responseObject,nil);
  660. }
  661. } failure: { task, error in
  662. if (completion != nil) {
  663. completion!(task, nil, error as NSError);
  664. }
  665. }
  666. } else {
  667. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  668. } success: { task, responseObject in
  669. if (completion != nil) {
  670. let responseObject = responseObject as AnyObject
  671. completion!(task,responseObject,nil);
  672. }
  673. } failure: { task, error in
  674. if (completion != nil) {
  675. completion!(task, nil, error as NSError);
  676. }
  677. }
  678. }
  679. }
  680. /**
  681. 文件翻译
  682. */
  683. func aiFileTranslateHandle(urlString: String,
  684. params: Dictionary<String, Any>?,
  685. body: ((_ formData:AFMultipartFormData) -> Void)?,
  686. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  687. completion: KMHttpRequestServerComplete?) -> Void {
  688. sessionManager.requestSerializer = AFJSONRequestSerializer()
  689. sessionManager.responseSerializer = AFJSONResponseSerializer()
  690. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  691. if (requestSerializer != nil) {
  692. requestSerializer!(sessionManager.requestSerializer);
  693. }
  694. if (body != nil) {
  695. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  696. body!(formData)
  697. } progress: { progress in
  698. } success: { task, responseObject in
  699. let responseObject = responseObject as AnyObject
  700. if (completion != nil) {
  701. completion!(task,responseObject,nil);
  702. }
  703. } failure: { task, error in
  704. if (completion != nil) {
  705. completion!(task, nil, error as NSError);
  706. }
  707. }
  708. } else {
  709. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  710. } success: { task, responseObject in
  711. if (completion != nil) {
  712. let responseObject = responseObject as AnyObject
  713. completion!(task,responseObject,nil);
  714. }
  715. } failure: { task, error in
  716. if (completion != nil) {
  717. completion!(task, nil, error as NSError);
  718. }
  719. }
  720. }
  721. }
  722. /**
  723. 重写
  724. */
  725. func aiRewriting(urlString: String,
  726. params: Dictionary<String, Any>?,
  727. body: ((_ formData:AFMultipartFormData) -> Void)?,
  728. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  729. completion: KMHttpRequestServerComplete?) -> Void {
  730. sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
  731. sessionManager.requestSerializer.timeoutInterval = 60
  732. sessionManager.responseSerializer = AFJSONResponseSerializer()
  733. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  734. if (requestSerializer != nil) {
  735. requestSerializer!(sessionManager.requestSerializer);
  736. }
  737. if (body != nil) {
  738. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  739. body!(formData)
  740. } progress: { progress in
  741. } success: { task, responseObject in
  742. let responseObject = responseObject as AnyObject
  743. if (completion != nil) {
  744. completion!(task,responseObject,nil);
  745. }
  746. } failure: { task, error in
  747. if (completion != nil) {
  748. completion!(task, nil, error as NSError);
  749. }
  750. }
  751. } else {
  752. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  753. } success: { task, responseObject in
  754. if (completion != nil) {
  755. let responseObject = responseObject as AnyObject
  756. completion!(task,responseObject,nil);
  757. }
  758. } failure: { task, error in
  759. if (completion != nil) {
  760. completion!(task, nil, error as NSError);
  761. }
  762. }
  763. }
  764. }
  765. func aiMemberRewriting(urlString: String,
  766. params: Dictionary<String, Any>?,
  767. body: ((_ formData:AFMultipartFormData) -> Void)?,
  768. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  769. completion: KMHttpRequestServerComplete?) -> Void {
  770. let token: String = KMMemberInfo.shared.access_token
  771. let urlString = urlString
  772. let paraDict: [String: Any] = params!
  773. let postData = try! JSONSerialization.data(withJSONObject: paraDict)
  774. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  775. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  776. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  777. request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  778. request.httpMethod = "POST"
  779. request.httpBody = postData
  780. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  781. guard let data = data else {
  782. print(String(describing: error))
  783. return
  784. }
  785. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  786. if jsonObject != nil {
  787. let codeStr: String = jsonObject!["code"] as! String
  788. var code: Int = 0
  789. if let numCode = Int(codeStr) {
  790. code = numCode
  791. }
  792. var result_bool: Bool = true
  793. var message: String = ""
  794. if let string = jsonObject!["data"] {
  795. let dataDic = jsonObject!["data"] as? NSDictionary ?? [:]
  796. if let dataStr = dataDic["dst"] {
  797. message = dataStr as! String
  798. result_bool = true
  799. }
  800. }
  801. let result = KMMemberCenterResult(code: code, msg: message, result: result_bool)
  802. if code == 200 {
  803. if (completion != nil) {
  804. completion!(nil, result, nil);
  805. }
  806. } else {
  807. if (completion != nil) {
  808. completion!(nil, nil, error as? NSError);
  809. }
  810. }
  811. } else {
  812. if (completion != nil) {
  813. completion!(nil, nil, error as? NSError);
  814. }
  815. }
  816. }
  817. task.resume()
  818. }
  819. }