KMAIRequestServerManager.swift 43 KB

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