KMAIRequestServerManager.swift 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968
  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 > 0 {
  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. complete(ResultWrapper(success: false, content: "unknown error"))
  271. if(KMMemberInfo.shared.isLogin == true) {
  272. KMUserInfoViewController.refreshTokenUserInfo {[weak self] success, resDic in
  273. if(success == true) {
  274. } else {
  275. let code = resDic?.code ?? 200
  276. if(code == 304) {
  277. KMLoginWindowsController.shared.showWindow(nil)
  278. }
  279. }
  280. }
  281. } else {
  282. KMLoginWindowsController.shared.showWindow(nil)
  283. }
  284. return
  285. }
  286. let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/v1/translate/fileUpload"
  287. let fileData = FileManager.default.contents(atPath: file)
  288. let params: [String: Any] = ["file" : fileData,
  289. "calculate" : "1"]
  290. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  291. let fileURL = URL(fileURLWithPath: file)
  292. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  293. } requestSerializer: { requestSerializer in
  294. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  295. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  296. } completion: { task, responseObject, error in
  297. if responseObject != nil {
  298. let data: NSDictionary = responseObject as? NSDictionary ?? [:]
  299. if data.count > 0 {
  300. let code: String = data["code"] as? String ?? "06005"
  301. if Int(code)! == 200, let dataDic = data["data"] {
  302. let wrapper = ResultWrapper(success: true, resultData: dataDic as! NSDictionary)
  303. if let value = (dataDic as! NSDictionary)["fileKey"] {
  304. wrapper.content = value as! String
  305. }
  306. complete(wrapper)
  307. } else {
  308. let wrapper = ResultWrapper(success: false, resultData: data)
  309. if let value = data["msg"] {
  310. wrapper.content = value as! String
  311. }
  312. complete(wrapper)
  313. }
  314. } else {
  315. let error = NSError(domain: "unknown error", code: 404)
  316. complete(ResultWrapper(success: false, content: "unknown error"))
  317. }
  318. } else {
  319. let error = NSError(domain: "unknown error", code: 404)
  320. complete(ResultWrapper(success: false, content: "unknown error"))
  321. }
  322. }
  323. }
  324. /**
  325. @abstract 文件翻译
  326. @param fileKey 文件Key
  327. @param from 初始语言
  328. @param to 结束语言
  329. */
  330. func aiTranslationFileTranslateHandle(fileKey: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  331. let aiInfo: AIInfo = AIInfoManager.default().aiInfo
  332. if aiInfo.totalToken - aiInfo.usedTimes > 1 {
  333. let infoDictionary = Bundle .main.infoDictionary!
  334. let urlString = AIInfoConfig().aiActionURL + "/api/AI/fileTranslate"
  335. let paraDict = ["fileKey": fileKey,
  336. "from": languageAbbreviation(from),
  337. "to": languageAbbreviation(to),
  338. "uuid": uuid(),
  339. "platform": platform(),
  340. "app_name": app_name()]
  341. var postData = try! JSONSerialization.data(withJSONObject: paraDict)
  342. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  343. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  344. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  345. request.httpMethod = "POST"
  346. request.httpBody = postData
  347. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  348. guard let data = data else {
  349. print(String(describing: error))
  350. return
  351. }
  352. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  353. if jsonObject != nil {
  354. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  355. let code: String = jsonObject!["code"] as? String ?? "06005"
  356. let message: String = jsonObject!["message"] as? String ?? "unknown error"
  357. let error = NSError(domain: message, code: Int(code)!)
  358. if Int(code)! == 200 {
  359. let fileUrl = data1["fileUrl"]
  360. let downFileUrl = data1["downFileUrl"]
  361. let ossDownUrl = data1["ossDownUrl"]
  362. let fileName = data1["fileName"]
  363. let downFileName = data1["downFileName"]
  364. let fromStr = data1["from"]
  365. let toStr = data1["to"]
  366. self.downFileName = downFileName as! String
  367. complete(ResultWrapper(success: true, content: ossDownUrl as! String))
  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. } else {
  377. memberAITranslationFileTranslateHandle(fileKey: fileKey, from: from, to: to, complete: complete)
  378. }
  379. }
  380. func memberAITranslationFileTranslateHandle(fileKey: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  381. let token: String = KMMemberInfo.shared.access_token
  382. let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/v1/translate/fileTranslateHandle"
  383. let paraDict = ["fileKey": fileKey,
  384. "from": languageAbbreviation(from),
  385. "to": languageAbbreviation(to)]
  386. let postData = try! JSONSerialization.data(withJSONObject: paraDict)
  387. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  388. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  389. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  390. request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  391. request.httpMethod = "POST"
  392. request.httpBody = postData
  393. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  394. guard let data = data else {
  395. print(String(describing: error))
  396. return
  397. }
  398. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  399. if jsonObject != nil {
  400. let codeStr: String = jsonObject!["code"] as! String
  401. var code: Int = 0
  402. if let numCode = Int(codeStr) {
  403. code = numCode
  404. }
  405. var result_bool: Bool = true
  406. var message: String = ""
  407. if let value = jsonObject!["message"]{
  408. message = value as! String
  409. }
  410. let result = KMMemberCenterResult(code: code, msg: message, result: result_bool)
  411. if code == 200 {
  412. if jsonObject!["data"] != nil {
  413. let dataDic = jsonObject!["data"] as? NSDictionary ?? [:]
  414. let fileUrl = dataDic["fileUrl"]
  415. let downFileUrl = dataDic["downFileUrl"]
  416. let ossDownUrl = dataDic["ossDownUrl"]
  417. let fileName = dataDic["fileName"]
  418. let downFileName = dataDic["downFileName"]
  419. let fromStr = dataDic["from"]
  420. let toStr = dataDic["to"]
  421. self.downFileName = downFileName as! String
  422. complete(ResultWrapper(success: true, content: ossDownUrl as! String))
  423. }
  424. } else {
  425. complete(ResultWrapper(success: false, content: message))
  426. }
  427. } else {
  428. complete(ResultWrapper(success: false, content: ""))
  429. }
  430. }
  431. task.resume()
  432. }
  433. /**
  434. @abstract 内容翻译
  435. @param q 选中
  436. @param from 初始语言
  437. @param to 结束语言
  438. */
  439. private func aiTranslationTextTrans(q: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  440. let infoDictionary = Bundle .main.infoDictionary!
  441. let urlString = AIInfoConfig().aiActionURL + "/api/AI/textTranslate"
  442. var escapedString = q
  443. escapedString = String(data: escapedString.data(using: .utf8)!, encoding: .utf8)!
  444. let paraDict = ["text":escapedString,
  445. "from":from,
  446. "to":to,
  447. "uuid":uuid(),
  448. "platform": platform(),
  449. "app_name": app_name()]
  450. var postData = try! JSONSerialization.data(withJSONObject: paraDict)
  451. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  452. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  453. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  454. request.httpMethod = "POST"
  455. request.httpBody = postData
  456. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  457. guard let data = data else {
  458. print(String(describing: error))
  459. return
  460. }
  461. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  462. if jsonObject != nil {
  463. let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
  464. let code: String = jsonObject!["code"] as? String ?? "06005"
  465. let message: String = jsonObject!["message"] as? String ?? "unknown error"
  466. let error = NSError(domain: message, code: Int(code)!)
  467. if Int(code)! == 200 {
  468. var resultStr = data1["dst"] as! String
  469. complete(ResultWrapper(success: true, content: resultStr))
  470. } else {
  471. complete(ResultWrapper(success: false, content: message))
  472. }
  473. } else {
  474. complete(ResultWrapper(success: false, content: "unknown error"))
  475. }
  476. }
  477. task.resume()
  478. }
  479. private func aiMemberTranslationTextTrans(q: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  480. if(KMMemberInfo.shared.isLogin == true) {
  481. KMUserInfoViewController.refreshTokenUserInfo {[weak self] success, resDic in
  482. if(success == true) {
  483. self?.aiMemberTranslationTextTransReq(q: q, from: from, to: to, complete: complete)
  484. } else {
  485. let code = resDic?.code ?? 200
  486. if(code == 304) {
  487. KMLoginWindowsController.shared.showWindow(nil)
  488. }
  489. }
  490. }
  491. }
  492. }
  493. func aiMemberTranslationTextTransReq(q: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  494. let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/v1/translate/textTrans"
  495. let token: String = KMMemberInfo.shared.access_token
  496. var escapedString = q
  497. escapedString = String(data: escapedString.data(using: .utf8)!, encoding: .utf8)!
  498. let paraDict = ["text":escapedString,
  499. "from":from,
  500. "to":to,
  501. "uuid":uuid(),
  502. "platform": platform(),
  503. "app_name": app_name()]
  504. var postData = try! JSONSerialization.data(withJSONObject: paraDict)
  505. KMAIRequestServer.requestServer.aiMemberRewriting(urlString: urlString, params: paraDict) { formData in
  506. } requestSerializer: { requestSerializer in
  507. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  508. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  509. } completion: { task, responseObject, error in
  510. if responseObject is KMMemberCenterResult {
  511. let resultObjct = responseObject as! KMMemberCenterResult
  512. let code = resultObjct.code
  513. let message: String = resultObjct.msg ?? ""
  514. if code == 200 {
  515. complete(ResultWrapper(success: true, content: message))
  516. } else {
  517. complete(ResultWrapper(success: false, content: message))
  518. }
  519. } else {
  520. complete(ResultWrapper(success: false, content: "unknown error"))
  521. }
  522. }
  523. }
  524. /**
  525. @abstract重写 & 纠错
  526. @param content 内容
  527. @param state 类型
  528. */
  529. private func aiRewriting(content: String, state: KMAIRewritingState, complete: @escaping KMRequestServerComplete) {
  530. let aiInfo: AIInfo = AIInfoManager.default().aiInfo
  531. if aiInfo.totalToken - aiInfo.usedTimes > 0 {
  532. var urlString = AIInfoConfig().aiActionURL + "/api/AI/rewrite"
  533. if state == .correctTypos {
  534. urlString = AIInfoConfig().aiActionURL + "/api/AI/correctTypos"
  535. }
  536. let params: [String: Any] = ["content": content,
  537. "uuid": uuid(),
  538. "platform": platform(),
  539. "app_name": app_name()]
  540. KMAIRequestServer.requestServer.aiRewriting(urlString: urlString, params: params) { formData in
  541. } requestSerializer: { requestSerializer in
  542. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  543. } completion: { task, responseObject, error in
  544. if responseObject != nil {
  545. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  546. let code: String = responseObject!["code"] as? String ?? "06005"
  547. let message: String = responseObject!["message"] as? String ?? "unknown error"
  548. if Int(code)! == 200 {
  549. complete(ResultWrapper(success: true, content: data["content"] as! String))
  550. } else {
  551. complete(ResultWrapper(success: false, content: message))
  552. }
  553. } else {
  554. complete(ResultWrapper(success: false, content: "unknown error"))
  555. }
  556. }
  557. } else {
  558. if(KMMemberInfo.shared.isLogin == true) {
  559. KMUserInfoViewController.refreshTokenUserInfo {[weak self] success, resDic in
  560. if(success == true) {
  561. self?.aiMemberRewriting(content: content, state: state, complete: complete)
  562. } else {
  563. let code = resDic?.code ?? 200
  564. if(code == 304) {
  565. KMLoginWindowsController.shared.showWindow(nil)
  566. }
  567. }
  568. }
  569. }
  570. }
  571. }
  572. func aiMemberRewriting(content: String, state: KMAIRewritingState, complete: @escaping KMRequestServerComplete) {
  573. let token: String = KMMemberInfo.shared.access_token
  574. if token == "" {
  575. complete(ResultWrapper(success: false, content: "unknown error"))
  576. }
  577. var urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/rewrite"
  578. if state == .correctTypos {
  579. urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/correct-typos"
  580. }
  581. let params: [String: Any] = ["content": content]
  582. KMAIRequestServer.requestServer.aiMemberRewriting(urlString: urlString, params: params) { formData in
  583. } requestSerializer: { requestSerializer in
  584. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  585. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  586. } completion: { task, responseObject, error in
  587. if responseObject is KMMemberCenterResult {
  588. let resultObjct = responseObject as! KMMemberCenterResult
  589. let code = resultObjct.code
  590. let message: String = resultObjct.msg ?? ""
  591. if code == 200 {
  592. complete(ResultWrapper(success: true, content: message))
  593. } else {
  594. complete(ResultWrapper(success: false, content: message))
  595. }
  596. } else {
  597. complete(ResultWrapper(success: false, content: "unknown error"))
  598. }
  599. }
  600. }
  601. /**
  602. @abstract 提取摘要
  603. @param file 文件路径
  604. */
  605. private func extractSummaryFile(file: String, complete: @escaping KMRequestServerComplete) {
  606. let infoDictionary = Bundle .main.infoDictionary!
  607. let urlString = AIInfoConfig().aiActionURL + "/api/AI/extractSummaryFile"
  608. let fileData = FileManager.default.contents(atPath: file)
  609. let params: [String: Any] = ["file": fileData,
  610. "uuid": uuid(),
  611. "platform": platform(),
  612. "app_name": app_name()]
  613. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  614. let fileURL = URL(fileURLWithPath: file)
  615. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  616. } requestSerializer: { requestSerializer in
  617. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  618. } completion: { task, responseObject, error in
  619. if responseObject != nil {
  620. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  621. let code: Int = responseObject!["code"] as? Int ?? 06005
  622. let message: String = responseObject!["message"] as? String ?? "unknown error"
  623. let error = NSError(domain: message, code: code)
  624. if code == 200 {
  625. complete(ResultWrapper(success: true, content: data["summary"] as! String))
  626. } else {
  627. complete(ResultWrapper(success: false, content: message))
  628. }
  629. } else {
  630. let error = NSError(domain: "unknown error", code: 404)
  631. complete(ResultWrapper(success: false, content: "unknown error"))
  632. }
  633. }
  634. }
  635. private func memberExtractSummaryFile(file: String, complete: @escaping KMRequestServerComplete) {
  636. let token: String = KMMemberInfo.shared.access_token
  637. if token == "" {
  638. return
  639. }
  640. let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/extract-file-summary"
  641. let fileData = FileManager.default.contents(atPath: file)
  642. let params: [String: Any] = ["file": fileData]
  643. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  644. let fileURL = URL(fileURLWithPath: file)
  645. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  646. } requestSerializer: { requestSerializer in
  647. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  648. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  649. } completion: { task, responseObject, error in
  650. if responseObject != nil {
  651. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  652. let code: Int = responseObject!["code"] as? Int ?? 06005
  653. let message: String = responseObject!["message"] as? String ?? "unknown error"
  654. let error = NSError(domain: message, code: code)
  655. if code == 200 {
  656. complete(ResultWrapper(success: true, content: data["summary"] as! String))
  657. } else {
  658. complete(ResultWrapper(success: false, content: message))
  659. }
  660. } else {
  661. let error = NSError(domain: "unknown error", code: 404)
  662. complete(ResultWrapper(success: false, content: "unknown error"))
  663. }
  664. }
  665. }
  666. }
  667. //typealias KMHttpRequestServerComplete = (_ task: URLSessionDataTask?, _ responseObject: AnyObject?, _ error: NSError?) -> Void
  668. class KMAIRequestServer {
  669. var sessionManager: AFHTTPSessionManager!
  670. static let requestServer = KMAIRequestServer()
  671. var task: URLSessionTask?
  672. init() {
  673. let configuration: URLSessionConfiguration = URLSessionConfiguration.default
  674. sessionManager = AFHTTPSessionManager.init(sessionConfiguration: configuration)
  675. sessionManager.securityPolicy = AFSecurityPolicy.default()
  676. }
  677. /**
  678. 上传文件
  679. - 翻译
  680. - 摘要提取
  681. */
  682. func uploadFile(urlString: String,
  683. params: Dictionary<String, Any>?,
  684. body: ((_ formData:AFMultipartFormData) -> Void)?,
  685. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  686. completion: KMHttpRequestServerComplete?) -> Void {
  687. sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
  688. sessionManager.requestSerializer.timeoutInterval = 60
  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 aiFileTranslateHandle(urlString: String,
  726. params: Dictionary<String, Any>?,
  727. body: ((_ formData:AFMultipartFormData) -> Void)?,
  728. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  729. completion: KMHttpRequestServerComplete?) -> Void {
  730. sessionManager.requestSerializer = AFJSONRequestSerializer()
  731. sessionManager.responseSerializer = AFJSONResponseSerializer()
  732. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  733. if (requestSerializer != nil) {
  734. requestSerializer!(sessionManager.requestSerializer);
  735. }
  736. if (body != nil) {
  737. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  738. body!(formData)
  739. } progress: { progress in
  740. } success: { task, responseObject in
  741. let responseObject = responseObject as AnyObject
  742. if (completion != nil) {
  743. completion!(task,responseObject,nil);
  744. }
  745. } failure: { task, error in
  746. if (completion != nil) {
  747. completion!(task, nil, error as NSError);
  748. }
  749. }
  750. } else {
  751. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  752. } success: { task, responseObject in
  753. if (completion != nil) {
  754. let responseObject = responseObject as AnyObject
  755. completion!(task,responseObject,nil);
  756. }
  757. } failure: { task, error in
  758. if (completion != nil) {
  759. completion!(task, nil, error as NSError);
  760. }
  761. }
  762. }
  763. }
  764. /**
  765. 重写
  766. */
  767. func aiRewriting(urlString: String,
  768. params: Dictionary<String, Any>?,
  769. body: ((_ formData:AFMultipartFormData) -> Void)?,
  770. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  771. completion: KMHttpRequestServerComplete?) -> Void {
  772. sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
  773. sessionManager.requestSerializer.timeoutInterval = 60
  774. sessionManager.responseSerializer = AFJSONResponseSerializer()
  775. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  776. if (requestSerializer != nil) {
  777. requestSerializer!(sessionManager.requestSerializer);
  778. }
  779. if (body != nil) {
  780. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  781. body!(formData)
  782. } progress: { progress in
  783. } success: { task, responseObject in
  784. let responseObject = responseObject as AnyObject
  785. if (completion != nil) {
  786. completion!(task,responseObject,nil);
  787. }
  788. } failure: { task, error in
  789. if (completion != nil) {
  790. completion!(task, nil, error as NSError);
  791. }
  792. }
  793. } else {
  794. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  795. } success: { task, responseObject in
  796. if (completion != nil) {
  797. let responseObject = responseObject as AnyObject
  798. completion!(task,responseObject,nil);
  799. }
  800. } failure: { task, error in
  801. if (completion != nil) {
  802. completion!(task, nil, error as NSError);
  803. }
  804. }
  805. }
  806. }
  807. func aiMemberRewriting(urlString: String,
  808. params: Dictionary<String, Any>?,
  809. body: ((_ formData:AFMultipartFormData) -> Void)?,
  810. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  811. completion: KMHttpRequestServerComplete?) -> Void {
  812. let token: String = KMMemberInfo.shared.access_token
  813. let urlString = urlString
  814. let paraDict: [String: Any] = params!
  815. let postData = try! JSONSerialization.data(withJSONObject: paraDict)
  816. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  817. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  818. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  819. request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  820. request.httpMethod = "POST"
  821. request.httpBody = postData
  822. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  823. guard let data = data else {
  824. print(String(describing: error))
  825. return
  826. }
  827. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  828. if jsonObject != nil {
  829. let codeStr: String = jsonObject!["code"] as? String ?? ""
  830. var code: Int = 0
  831. if let numCode = Int(codeStr) {
  832. code = numCode
  833. }
  834. var result_bool: Bool = true
  835. var message: String = ""
  836. if let value = jsonObject!["message"]{
  837. message = value as! String
  838. }
  839. if let string = jsonObject!["data"] {
  840. let dataDic = jsonObject!["data"] as? NSDictionary ?? [:]
  841. if let dataStr = dataDic["content"] {
  842. message = dataStr as! String
  843. result_bool = true
  844. }
  845. }
  846. let result = KMMemberCenterResult(code: code, msg: message, result: result_bool)
  847. if code == 200 {
  848. if (completion != nil) {
  849. completion!(nil, result, nil);
  850. }
  851. } else {
  852. if (completion != nil) {
  853. completion!(nil, result, error as? NSError);
  854. }
  855. }
  856. } else {
  857. if (completion != nil) {
  858. completion!(nil, nil, error as? NSError);
  859. }
  860. }
  861. }
  862. task.resume()
  863. }
  864. }