KMAIRequestServerManager.swift 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  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 = (dataDic as! NSDictionary)["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. if(KMMemberInfo.shared.isLogin == true) {
  464. KMUserInfoViewController.refreshTokenUserInfo {[weak self] success, resDic in
  465. if(success == true) {
  466. self?.aiMemberTranslationTextTransReq(q: q, from: from, to: to, complete: complete)
  467. } else {
  468. let code = resDic?.code ?? 200
  469. if(code == 304) {
  470. KMLoginWindowsController.shared.showWindow(nil)
  471. }
  472. }
  473. }
  474. }
  475. }
  476. func aiMemberTranslationTextTransReq(q: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
  477. let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/v1/translate/textTrans"
  478. let token: String = KMMemberInfo.shared.access_token
  479. var escapedString = q
  480. escapedString = String(data: escapedString.data(using: .utf8)!, encoding: .utf8)!
  481. let paraDict = ["text":escapedString,
  482. "from":from,
  483. "to":to,
  484. "uuid":uuid(),
  485. "platform": platform(),
  486. "app_name": app_name()]
  487. var postData = try! JSONSerialization.data(withJSONObject: paraDict)
  488. KMAIRequestServer.requestServer.aiMemberRewriting(urlString: urlString, params: paraDict) { formData in
  489. } requestSerializer: { requestSerializer in
  490. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  491. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  492. } completion: { task, responseObject, error in
  493. if responseObject is KMMemberCenterResult {
  494. let resultObjct = responseObject as! KMMemberCenterResult
  495. let code = resultObjct.code
  496. let message: String = resultObjct.msg ?? ""
  497. if code == 200 {
  498. complete(ResultWrapper(success: true, content: message))
  499. } else {
  500. complete(ResultWrapper(success: false, content: message))
  501. }
  502. } else {
  503. complete(ResultWrapper(success: false, content: "unknown error"))
  504. }
  505. }
  506. }
  507. /**
  508. @abstract重写 & 纠错
  509. @param content 内容
  510. @param state 类型
  511. */
  512. private func aiRewriting(content: String, state: KMAIRewritingState, complete: @escaping KMRequestServerComplete) {
  513. let aiInfo: AIInfo = AIInfoManager.default().aiInfo
  514. if aiInfo.totalToken - aiInfo.usedTimes > 1 {
  515. var urlString = AIInfoConfig().aiActionURL + "/api/AI/rewrite"
  516. if state == .correctTypos {
  517. urlString = AIInfoConfig().aiActionURL + "/api/AI/correctTypos"
  518. }
  519. let params: [String: Any] = ["content": content,
  520. "uuid": uuid(),
  521. "platform": platform(),
  522. "app_name": app_name()]
  523. KMAIRequestServer.requestServer.aiRewriting(urlString: urlString, params: params) { formData in
  524. } requestSerializer: { requestSerializer in
  525. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  526. } completion: { task, responseObject, error in
  527. if responseObject != nil {
  528. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  529. let code: String = responseObject!["code"] as? String ?? "06005"
  530. let message: String = responseObject!["message"] as? String ?? "unknown error"
  531. if Int(code)! == 200 {
  532. complete(ResultWrapper(success: true, content: data["content"] as! String))
  533. } else {
  534. complete(ResultWrapper(success: false, content: message))
  535. }
  536. } else {
  537. complete(ResultWrapper(success: false, content: "unknown error"))
  538. }
  539. }
  540. } else {
  541. if(KMMemberInfo.shared.isLogin == true) {
  542. KMUserInfoViewController.refreshTokenUserInfo {[weak self] success, resDic in
  543. if(success == true) {
  544. self?.aiMemberRewriting(content: content, state: state, complete: complete)
  545. } else {
  546. let code = resDic?.code ?? 200
  547. if(code == 304) {
  548. KMLoginWindowsController.shared.showWindow(nil)
  549. }
  550. }
  551. }
  552. }
  553. }
  554. }
  555. func aiMemberRewriting(content: String, state: KMAIRewritingState, complete: @escaping KMRequestServerComplete) {
  556. let token: String = KMMemberInfo.shared.access_token
  557. if token == "" {
  558. return
  559. }
  560. var urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/rewrite"
  561. if state == .correctTypos {
  562. urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/correct-typos"
  563. }
  564. let params: [String: Any] = ["content": content]
  565. KMAIRequestServer.requestServer.aiMemberRewriting(urlString: urlString, params: params) { formData in
  566. } requestSerializer: { requestSerializer in
  567. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  568. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  569. } completion: { task, responseObject, error in
  570. if responseObject is KMMemberCenterResult {
  571. let resultObjct = responseObject as! KMMemberCenterResult
  572. let code = resultObjct.code
  573. let message: String = resultObjct.msg ?? ""
  574. if code == 200 {
  575. complete(ResultWrapper(success: true, content: message))
  576. } else {
  577. complete(ResultWrapper(success: false, content: message))
  578. }
  579. } else {
  580. complete(ResultWrapper(success: false, content: "unknown error"))
  581. }
  582. }
  583. }
  584. /**
  585. @abstract 提取摘要
  586. @param file 文件路径
  587. */
  588. private func extractSummaryFile(file: String, complete: @escaping KMRequestServerComplete) {
  589. let infoDictionary = Bundle .main.infoDictionary!
  590. let urlString = AIInfoConfig().aiActionURL + "/api/AI/extractSummaryFile"
  591. let fileData = FileManager.default.contents(atPath: file)
  592. let params: [String: Any] = ["file": fileData,
  593. "uuid": uuid(),
  594. "platform": platform(),
  595. "app_name": app_name()]
  596. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  597. let fileURL = URL(fileURLWithPath: file)
  598. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  599. } requestSerializer: { requestSerializer in
  600. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  601. } completion: { task, responseObject, error in
  602. if responseObject != nil {
  603. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  604. let code: Int = responseObject!["code"] as? Int ?? 06005
  605. let message: String = responseObject!["message"] as? String ?? "unknown error"
  606. let error = NSError(domain: message, code: code)
  607. if code == 200 {
  608. complete(ResultWrapper(success: true, content: data["summary"] as! String))
  609. } else {
  610. complete(ResultWrapper(success: false, content: message))
  611. }
  612. } else {
  613. let error = NSError(domain: "unknown error", code: 404)
  614. complete(ResultWrapper(success: false, content: "unknown error"))
  615. }
  616. }
  617. }
  618. private func memberExtractSummaryFile(file: String, complete: @escaping KMRequestServerComplete) {
  619. let token: String = KMMemberInfo.shared.access_token
  620. if token == "" {
  621. return
  622. }
  623. let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/extract-file-summary"
  624. let fileData = FileManager.default.contents(atPath: file)
  625. let params: [String: Any] = ["file": fileData]
  626. KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
  627. let fileURL = URL(fileURLWithPath: file)
  628. try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
  629. } requestSerializer: { requestSerializer in
  630. requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  631. requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  632. } completion: { task, responseObject, error in
  633. if responseObject != nil {
  634. let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
  635. let code: Int = responseObject!["code"] as? Int ?? 06005
  636. let message: String = responseObject!["message"] as? String ?? "unknown error"
  637. let error = NSError(domain: message, code: code)
  638. if code == 200 {
  639. complete(ResultWrapper(success: true, content: data["summary"] as! String))
  640. } else {
  641. complete(ResultWrapper(success: false, content: message))
  642. }
  643. } else {
  644. let error = NSError(domain: "unknown error", code: 404)
  645. complete(ResultWrapper(success: false, content: "unknown error"))
  646. }
  647. }
  648. }
  649. }
  650. //typealias KMHttpRequestServerComplete = (_ task: URLSessionDataTask?, _ responseObject: AnyObject?, _ error: NSError?) -> Void
  651. class KMAIRequestServer {
  652. var sessionManager: AFHTTPSessionManager!
  653. static let requestServer = KMAIRequestServer()
  654. var task: URLSessionTask?
  655. init() {
  656. let configuration: URLSessionConfiguration = URLSessionConfiguration.default
  657. sessionManager = AFHTTPSessionManager.init(sessionConfiguration: configuration)
  658. sessionManager.securityPolicy = AFSecurityPolicy.default()
  659. }
  660. /**
  661. 上传文件
  662. - 翻译
  663. - 摘要提取
  664. */
  665. func uploadFile(urlString: String,
  666. params: Dictionary<String, Any>?,
  667. body: ((_ formData:AFMultipartFormData) -> Void)?,
  668. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  669. completion: KMHttpRequestServerComplete?) -> Void {
  670. sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
  671. sessionManager.requestSerializer.timeoutInterval = 60
  672. sessionManager.responseSerializer = AFJSONResponseSerializer()
  673. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  674. if (requestSerializer != nil) {
  675. requestSerializer!(sessionManager.requestSerializer);
  676. }
  677. if (body != nil) {
  678. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  679. body!(formData)
  680. } progress: { progress in
  681. } success: { task, responseObject in
  682. let responseObject = responseObject as AnyObject
  683. if (completion != nil) {
  684. completion!(task,responseObject,nil);
  685. }
  686. } failure: { task, error in
  687. if (completion != nil) {
  688. completion!(task, nil, error as NSError);
  689. }
  690. }
  691. } else {
  692. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  693. } success: { task, responseObject in
  694. if (completion != nil) {
  695. let responseObject = responseObject as AnyObject
  696. completion!(task,responseObject,nil);
  697. }
  698. } failure: { task, error in
  699. if (completion != nil) {
  700. completion!(task, nil, error as NSError);
  701. }
  702. }
  703. }
  704. }
  705. /**
  706. 文件翻译
  707. */
  708. func aiFileTranslateHandle(urlString: String,
  709. params: Dictionary<String, Any>?,
  710. body: ((_ formData:AFMultipartFormData) -> Void)?,
  711. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  712. completion: KMHttpRequestServerComplete?) -> Void {
  713. sessionManager.requestSerializer = AFJSONRequestSerializer()
  714. sessionManager.responseSerializer = AFJSONResponseSerializer()
  715. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  716. if (requestSerializer != nil) {
  717. requestSerializer!(sessionManager.requestSerializer);
  718. }
  719. if (body != nil) {
  720. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  721. body!(formData)
  722. } progress: { progress in
  723. } success: { task, responseObject in
  724. let responseObject = responseObject as AnyObject
  725. if (completion != nil) {
  726. completion!(task,responseObject,nil);
  727. }
  728. } failure: { task, error in
  729. if (completion != nil) {
  730. completion!(task, nil, error as NSError);
  731. }
  732. }
  733. } else {
  734. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  735. } success: { task, responseObject in
  736. if (completion != nil) {
  737. let responseObject = responseObject as AnyObject
  738. completion!(task,responseObject,nil);
  739. }
  740. } failure: { task, error in
  741. if (completion != nil) {
  742. completion!(task, nil, error as NSError);
  743. }
  744. }
  745. }
  746. }
  747. /**
  748. 重写
  749. */
  750. func aiRewriting(urlString: String,
  751. params: Dictionary<String, Any>?,
  752. body: ((_ formData:AFMultipartFormData) -> Void)?,
  753. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  754. completion: KMHttpRequestServerComplete?) -> Void {
  755. sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
  756. sessionManager.requestSerializer.timeoutInterval = 60
  757. sessionManager.responseSerializer = AFJSONResponseSerializer()
  758. sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
  759. if (requestSerializer != nil) {
  760. requestSerializer!(sessionManager.requestSerializer);
  761. }
  762. if (body != nil) {
  763. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
  764. body!(formData)
  765. } progress: { progress in
  766. } success: { task, responseObject in
  767. let responseObject = responseObject as AnyObject
  768. if (completion != nil) {
  769. completion!(task,responseObject,nil);
  770. }
  771. } failure: { task, error in
  772. if (completion != nil) {
  773. completion!(task, nil, error as NSError);
  774. }
  775. }
  776. } else {
  777. self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
  778. } success: { task, responseObject in
  779. if (completion != nil) {
  780. let responseObject = responseObject as AnyObject
  781. completion!(task,responseObject,nil);
  782. }
  783. } failure: { task, error in
  784. if (completion != nil) {
  785. completion!(task, nil, error as NSError);
  786. }
  787. }
  788. }
  789. }
  790. func aiMemberRewriting(urlString: String,
  791. params: Dictionary<String, Any>?,
  792. body: ((_ formData:AFMultipartFormData) -> Void)?,
  793. requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
  794. completion: KMHttpRequestServerComplete?) -> Void {
  795. let token: String = KMMemberInfo.shared.access_token
  796. let urlString = urlString
  797. let paraDict: [String: Any] = params!
  798. let postData = try! JSONSerialization.data(withJSONObject: paraDict)
  799. var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
  800. request.addValue("application/json", forHTTPHeaderField: "Content-Type")
  801. request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
  802. request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization")
  803. request.httpMethod = "POST"
  804. request.httpBody = postData
  805. let task = URLSession.shared.dataTask(with: request) { data, response, error in
  806. guard let data = data else {
  807. print(String(describing: error))
  808. return
  809. }
  810. let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
  811. if jsonObject != nil {
  812. let codeStr: String = jsonObject!["code"] as? String ?? ""
  813. var code: Int = 0
  814. if let numCode = Int(codeStr) {
  815. code = numCode
  816. }
  817. var result_bool: Bool = true
  818. var message: String = ""
  819. if let string = jsonObject!["data"] {
  820. let dataDic = jsonObject!["data"] as? NSDictionary ?? [:]
  821. if let dataStr = dataDic["content"] {
  822. message = dataStr as! String
  823. result_bool = true
  824. }
  825. }
  826. let result = KMMemberCenterResult(code: code, msg: message, result: result_bool)
  827. if code == 200 {
  828. if (completion != nil) {
  829. completion!(nil, result, nil);
  830. }
  831. } else {
  832. if (completion != nil) {
  833. completion!(nil, nil, error as? NSError);
  834. }
  835. }
  836. } else {
  837. if (completion != nil) {
  838. completion!(nil, nil, error as? NSError);
  839. }
  840. }
  841. }
  842. task.resume()
  843. }
  844. }