123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968 |
- //
- // KMAIRequestServerManager.swift
- // PDF Reader Pro Edition
- //
- // Created by wanjun on 2024/1/17.
- //
- import Cocoa
- import AFNetworking
- @objcMembers
- class ResultWrapper: NSObject {
- var success: Bool = false
- var result: NSDictionary = [:]
-
- var content: String = ""
-
- init(success: Bool, content: String) {
- self.success = success
- self.content = content
- self.result = NSDictionary.init()
- }
-
- init(success: Bool, resultData: NSDictionary) {
- self.success = success
- self.content = ""
- self.result = resultData
- }
- }
- @objc enum KMAIRewritingState : Int {
- case rewrite = 0 // 重写
- case correctTypos // 纠错
- case uploadTranslate // 翻译上传文件
- case fileTranslate // 翻译文件
- case textTranslate // 翻译文本
- case extractSummaryFile //摘要
- }
- @objc enum KMAIFileUploadState : Int {
- case Translation = 0
- case ExtractAbstract
- }
- //typealias KMRequestServerComplete = (_ success: Bool, _ result: Result?) -> Void
- @objcMembers class KMAIRequestServerManager: NSObject {
- static let defaultManager = KMAIRequestServerManager()
- typealias KMRequestServerComplete = (_ wrapper: ResultWrapper) -> Void
- private var downFileUrl: String = "" // 文件翻译
- var downFileName: String = "" // 文件翻译
-
- 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"]
- 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"]
-
- // MARK: AI Action (public)
-
- func aiAction(content: String, state: KMAIRewritingState, from: String = "auto", to: String = "en", complete: @escaping KMRequestServerComplete) {
- if state == .rewrite || state == .correctTypos { //重写 && 纠错
- aiRewriting(content: content, state: state, complete: complete)
- } else if state == .uploadTranslate || state == .fileTranslate { // 上传文件 || 文件翻译
- let aiInfo: AIInfo = AIInfoManager.default().aiInfo
- if aiInfo.totalToken - aiInfo.usedTimes > 1 {
- aiTranslationFileUpload(file: content, complete: { [weak self] wrapper in
- let success: Bool = wrapper.success
- let fileKey = wrapper.content
- if success {
- let fileData = wrapper.result
- complete(wrapper)
-
- } else {
- complete(wrapper)
- }
- })
- } else {
- memberAITranslationFileUpload(file: content, complete: { [weak self] wrapper in
- let success: Bool = wrapper.success
- let fileKey = wrapper.content
- if success {
- let fileData = wrapper.result
- complete(wrapper)
-
- } else {
- complete(wrapper)
- }
- })
- }
- } else if state == .textTranslate { // 文本翻译
- let aiInfo: AIInfo = AIInfoManager.default().aiInfo
- if aiInfo.totalToken - aiInfo.usedTimes > 1 {
- aiTranslationTextTrans(q: content, from: languageAbbreviation(from), to: languageAbbreviation(to), complete: complete)
- } else {
- aiMemberTranslationTextTrans(q: content, from: languageAbbreviation(from), to: languageAbbreviation(to), complete: complete)
- }
- } else if state == .extractSummaryFile { // 提取摘要
- let aiInfo: AIInfo = AIInfoManager.default().aiInfo
- if aiInfo.totalToken - aiInfo.usedTimes > 0 {
- extractSummaryFile(file: content, complete: complete)
- } else {
- memberExtractSummaryFile(file: content, complete: complete)
- }
- }
- }
-
- // MARK: Private
-
- private func uuid() -> String {
- return GetHardwareUUID()!
- }
-
- private func platform() -> String {
- var platform = "DMG"
- #if VERSION_DMG
- platform = "DMG"
- #else
- platform = "AiStore"
- #endif
- return platform
- }
-
- private func app_name() -> String {
- var bundleID: String!
- bundleID = Bundle.main.object(forInfoDictionaryKey: "CFBundleIdentifier") as! String
- return bundleID;
- }
-
- func downloadFile(filePath: String, downFileName: String, toPath: String, complete: @escaping KMRequestServerComplete) {
- self.downFileUrl = ""
- guard let fileURL = URL(string: filePath) else {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("Invalid file link", comment: "")
- alert.runModal()
- return
- }
- var destinationURL = FileManager.default.temporaryDirectory.appendingPathComponent(downFileName)
- if URL(fileURLWithPath: toPath) != nil {
- destinationURL = URL(fileURLWithPath: toPath)
- }
- if FileManager.default.fileExists(atPath: destinationURL.path) {
- do {
- try FileManager.default.removeItem(at: destinationURL)
- print("删除旧文件成功")
- } catch {
- print("删除旧文件失败:\(error)")
- }
- }
- let sessionConfiguration = URLSessionConfiguration.default
- let session = URLSession(configuration: sessionConfiguration)
- let downloadTask = session.downloadTask(with: fileURL) { (tempLocalURL, response, error) in
- if let error = error {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Download failed", comment: ""))
- alert.runModal()
-
- return
- }
- guard let tempLocalURL = tempLocalURL else {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = NSLocalizedString("Invalid temporary directory", comment: "")
- alert.runModal()
- return
- }
-
- do {
- try FileManager.default.moveItem(at: tempLocalURL, to: destinationURL)
-
- let wrapper = ResultWrapper(success: true, content: "")
- wrapper.content = destinationURL.path
- complete(wrapper)
- } catch {
- let alert = NSAlert()
- alert.alertStyle = .critical
- alert.messageText = String(format: "%@:\(error)", NSLocalizedString("Failed to save file", comment: ""))
- alert.runModal()
- }
- }
- self.downFileUrl = destinationURL.path
- downloadTask.resume()
- }
-
- private func languageAbbreviation(_ language: String) -> String {
- if language == "Automatic" || language == "auto" {
- return "auto"
- } else if language == "English" || language == "en" {
- return "en"
- } else if language == "Simplified Chinese" || language == "zh" {
- return "zh"
- } else if language == "Traditional Chinese" || language == "cht" {
- return "cht"
- } else if language == "Japanese" || language == "jp" {
- return "jp"
- } else if language == "Korean" || language == "kor" {
- return "kor"
- } else if language == "French" || language == "fra" {
- return "fra"
- } else if language == "Spanish" || language == "spa" {
- return "spa"
- } else if language == "Italian" || language == "it" {
- return "it"
- } else if language == "German" || language == "de" {
- return "de"
- } else if language == "Portuguese" || language == "pt" {
- return "pt"
- } else if language == "Russian" || language == "ru" {
- return "ru"
- } else if language == "Vietnamese" || language == "vie" {
- return "vie"
- } else if language == "Thai" || language == "th" {
- return "th"
- } else if language == "Arabic" || language == "ara" {
- return "ara"
- } else if language == "Greek" || language == "el" {
- return "el"
- } else if language == "Bulgarian" || language == "bul" {
- return "bul"
- } else if language == "Finnish" || language == "fin" {
- return "fin"
- } else if language == "Slovene" || language == "slo" {
- return "slo"
- } else if language == "Dutch" || language == "nl" {
- return "nl"
- } else if language == "Czech" || language == "cs" {
- return "cs"
- } else if language == "Swedish" || language == "swe" {
- return "swe"
- } else if language == "Polish" || language == "pl" {
- return "pl"
- } else if language == "Danish" || language == "dan" {
- return "dan"
- } else if language == "Romanian" || language == "rom" {
- return "rom"
- } else if language == "Hungarian" || language == "hu" {
- return "hu"
- }
- return "auto"
- }
-
- // MARK: AI Action (private)
-
- /**
- @abstract 翻译上传
- @param file 文件路径
- @param complete 上传完成回调
- */
- private func aiTranslationFileUpload(file: String, complete: @escaping KMRequestServerComplete) {
- let infoDictionary = Bundle .main.infoDictionary!
- let urlString = AIInfoConfig().aiActionURL + "/api/AI/uploadTranslate"
- let fileData = FileManager.default.contents(atPath: file)
- let params: [String: Any] = ["file": fileData,
- "uuid": uuid(),
- "platform": platform(),
- "app_name": app_name(),
- "calculate":"1"]
- KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
- let fileURL = URL(fileURLWithPath: file)
- try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
- } requestSerializer: { requestSerializer in
- requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
- } completion: { task, responseObject, error in
- if responseObject != nil {
- let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
- var code: String = responseObject!["code"] as? String ?? "06005"
- if code == "06005" {
- let tempCode: Int = responseObject!["code"] as? Int ?? 0
- if tempCode == 501 {
- code = "501"
- }
- }
-
- let message: String = responseObject!["message"] as? String ?? "unknown error"
- let error = NSError(domain: message, code: Int(code)!)
-
- if Int(code)! == 200 {
- let wrapper = ResultWrapper(success: true, resultData: data)
- wrapper.content = data["fileKey"] as! String
- complete(wrapper)
- } else {
- let wrapper = ResultWrapper(success: false, resultData: data)
- if Int(code)! == 501 {
- wrapper.content = "501"
- } else {
- wrapper.content = message
- }
- complete(wrapper)
- }
- } else {
- complete(ResultWrapper(success: false, content: "unknown error"))
- }
- }
- }
-
- private func memberAITranslationFileUpload(file: String, complete: @escaping KMRequestServerComplete) {
- let token: String = KMMemberInfo.shared.access_token
- if token == "" {
- complete(ResultWrapper(success: false, content: "unknown error"))
-
- if(KMMemberInfo.shared.isLogin == true) {
- KMUserInfoViewController.refreshTokenUserInfo {[weak self] success, resDic in
- if(success == true) {
-
- } else {
- let code = resDic?.code ?? 200
- if(code == 304) {
- KMLoginWindowsController.shared.showWindow(nil)
- }
- }
- }
- } else {
- KMLoginWindowsController.shared.showWindow(nil)
- }
-
- return
- }
-
- let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/v1/translate/fileUpload"
- let fileData = FileManager.default.contents(atPath: file)
- let params: [String: Any] = ["file" : fileData,
- "calculate" : "1"]
-
- KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
- let fileURL = URL(fileURLWithPath: file)
- try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
- } requestSerializer: { requestSerializer in
- requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
- requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
- } completion: { task, responseObject, error in
- if responseObject != nil {
- let data: NSDictionary = responseObject as? NSDictionary ?? [:]
- if data.count > 0 {
- let code: String = data["code"] as? String ?? "06005"
- if Int(code)! == 200, let dataDic = data["data"] {
- let wrapper = ResultWrapper(success: true, resultData: dataDic as! NSDictionary)
- if let value = (dataDic as! NSDictionary)["fileKey"] {
- wrapper.content = value as! String
- }
- complete(wrapper)
- } else {
- let wrapper = ResultWrapper(success: false, resultData: data)
- if let value = data["msg"] {
- wrapper.content = value as! String
- }
- complete(wrapper)
- }
- } else {
- let error = NSError(domain: "unknown error", code: 404)
- complete(ResultWrapper(success: false, content: "unknown error"))
- }
- } else {
- let error = NSError(domain: "unknown error", code: 404)
- complete(ResultWrapper(success: false, content: "unknown error"))
- }
- }
- }
-
- /**
- @abstract 文件翻译
- @param fileKey 文件Key
- @param from 初始语言
- @param to 结束语言
- */
- func aiTranslationFileTranslateHandle(fileKey: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
- let aiInfo: AIInfo = AIInfoManager.default().aiInfo
- if aiInfo.totalToken - aiInfo.usedTimes > 1 {
- let infoDictionary = Bundle .main.infoDictionary!
- let urlString = AIInfoConfig().aiActionURL + "/api/AI/fileTranslate"
-
- let paraDict = ["fileKey": fileKey,
- "from": languageAbbreviation(from),
- "to": languageAbbreviation(to),
- "uuid": uuid(),
- "platform": platform(),
- "app_name": app_name()]
- var postData = try! JSONSerialization.data(withJSONObject: paraDict)
-
-
- var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
- request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
-
- request.httpMethod = "POST"
- request.httpBody = postData
-
- let task = URLSession.shared.dataTask(with: request) { data, response, error in
- guard let data = data else {
- print(String(describing: error))
- return
- }
- let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
- if jsonObject != nil {
- let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
- let code: String = jsonObject!["code"] as? String ?? "06005"
- let message: String = jsonObject!["message"] as? String ?? "unknown error"
- let error = NSError(domain: message, code: Int(code)!)
-
- if Int(code)! == 200 {
- let fileUrl = data1["fileUrl"]
- let downFileUrl = data1["downFileUrl"]
- let ossDownUrl = data1["ossDownUrl"]
- let fileName = data1["fileName"]
- let downFileName = data1["downFileName"]
- let fromStr = data1["from"]
- let toStr = data1["to"]
-
- self.downFileName = downFileName as! String
- complete(ResultWrapper(success: true, content: ossDownUrl as! String))
- } else {
- complete(ResultWrapper(success: false, content: message))
- }
- } else {
- complete(ResultWrapper(success: false, content: "unknown error"))
- }
- }
- task.resume()
- } else {
- memberAITranslationFileTranslateHandle(fileKey: fileKey, from: from, to: to, complete: complete)
- }
- }
-
- func memberAITranslationFileTranslateHandle(fileKey: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
- let token: String = KMMemberInfo.shared.access_token
- let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/v1/translate/fileTranslateHandle"
- let paraDict = ["fileKey": fileKey,
- "from": languageAbbreviation(from),
- "to": languageAbbreviation(to)]
- let postData = try! JSONSerialization.data(withJSONObject: paraDict)
-
- var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
-
- request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
- request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization")
- request.httpMethod = "POST"
- request.httpBody = postData
-
- let task = URLSession.shared.dataTask(with: request) { data, response, error in
- guard let data = data else {
- print(String(describing: error))
- return
- }
- let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
- if jsonObject != nil {
- let codeStr: String = jsonObject!["code"] as! String
- var code: Int = 0
- if let numCode = Int(codeStr) {
- code = numCode
- }
- var result_bool: Bool = true
- var message: String = ""
- if let value = jsonObject!["message"]{
- message = value as! String
- }
-
- let result = KMMemberCenterResult(code: code, msg: message, result: result_bool)
- if code == 200 {
- if jsonObject!["data"] != nil {
- let dataDic = jsonObject!["data"] as? NSDictionary ?? [:]
-
- let fileUrl = dataDic["fileUrl"]
- let downFileUrl = dataDic["downFileUrl"]
- let ossDownUrl = dataDic["ossDownUrl"]
- let fileName = dataDic["fileName"]
- let downFileName = dataDic["downFileName"]
- let fromStr = dataDic["from"]
- let toStr = dataDic["to"]
-
- self.downFileName = downFileName as! String
- complete(ResultWrapper(success: true, content: ossDownUrl as! String))
- }
- } else {
- complete(ResultWrapper(success: false, content: message))
- }
- } else {
- complete(ResultWrapper(success: false, content: ""))
- }
- }
- task.resume()
- }
- /**
- @abstract 内容翻译
- @param q 选中
- @param from 初始语言
- @param to 结束语言
- */
- private func aiTranslationTextTrans(q: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
-
- let infoDictionary = Bundle .main.infoDictionary!
- let urlString = AIInfoConfig().aiActionURL + "/api/AI/textTranslate"
-
- var escapedString = q
- escapedString = String(data: escapedString.data(using: .utf8)!, encoding: .utf8)!
- let paraDict = ["text":escapedString,
- "from":from,
- "to":to,
- "uuid":uuid(),
- "platform": platform(),
- "app_name": app_name()]
- var postData = try! JSONSerialization.data(withJSONObject: paraDict)
- var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
- request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
- request.httpMethod = "POST"
- request.httpBody = postData
- let task = URLSession.shared.dataTask(with: request) { data, response, error in
- guard let data = data else {
- print(String(describing: error))
- return
- }
- let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
- if jsonObject != nil {
- let data1: NSDictionary = jsonObject!["data"] as? NSDictionary ?? [:]
- let code: String = jsonObject!["code"] as? String ?? "06005"
- let message: String = jsonObject!["message"] as? String ?? "unknown error"
- let error = NSError(domain: message, code: Int(code)!)
- if Int(code)! == 200 {
- var resultStr = data1["dst"] as! String
- complete(ResultWrapper(success: true, content: resultStr))
- } else {
- complete(ResultWrapper(success: false, content: message))
- }
- } else {
- complete(ResultWrapper(success: false, content: "unknown error"))
- }
- }
- task.resume()
- }
-
- private func aiMemberTranslationTextTrans(q: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
- if(KMMemberInfo.shared.isLogin == true) {
- KMUserInfoViewController.refreshTokenUserInfo {[weak self] success, resDic in
- if(success == true) {
- self?.aiMemberTranslationTextTransReq(q: q, from: from, to: to, complete: complete)
- } else {
- let code = resDic?.code ?? 200
- if(code == 304) {
- KMLoginWindowsController.shared.showWindow(nil)
- }
- }
- }
-
- }
- }
-
- func aiMemberTranslationTextTransReq(q: String, from: String, to: String, complete: @escaping KMRequestServerComplete) {
- let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/v1/translate/textTrans"
- let token: String = KMMemberInfo.shared.access_token
- var escapedString = q
- escapedString = String(data: escapedString.data(using: .utf8)!, encoding: .utf8)!
- let paraDict = ["text":escapedString,
- "from":from,
- "to":to,
- "uuid":uuid(),
- "platform": platform(),
- "app_name": app_name()]
- var postData = try! JSONSerialization.data(withJSONObject: paraDict)
-
- KMAIRequestServer.requestServer.aiMemberRewriting(urlString: urlString, params: paraDict) { formData in
-
- } requestSerializer: { requestSerializer in
- requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
- requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
- } completion: { task, responseObject, error in
- if responseObject is KMMemberCenterResult {
- let resultObjct = responseObject as! KMMemberCenterResult
- let code = resultObjct.code
- let message: String = resultObjct.msg ?? ""
- if code == 200 {
- complete(ResultWrapper(success: true, content: message))
- } else {
- complete(ResultWrapper(success: false, content: message))
- }
- } else {
- complete(ResultWrapper(success: false, content: "unknown error"))
- }
- }
- }
-
- /**
- @abstract重写 & 纠错
- @param content 内容
- @param state 类型
- */
- private func aiRewriting(content: String, state: KMAIRewritingState, complete: @escaping KMRequestServerComplete) {
- let aiInfo: AIInfo = AIInfoManager.default().aiInfo
-
- if aiInfo.totalToken - aiInfo.usedTimes > 0 {
- var urlString = AIInfoConfig().aiActionURL + "/api/AI/rewrite"
- if state == .correctTypos {
- urlString = AIInfoConfig().aiActionURL + "/api/AI/correctTypos"
- }
- let params: [String: Any] = ["content": content,
- "uuid": uuid(),
- "platform": platform(),
- "app_name": app_name()]
-
- KMAIRequestServer.requestServer.aiRewriting(urlString: urlString, params: params) { formData in
-
- } requestSerializer: { requestSerializer in
- requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
- } completion: { task, responseObject, error in
- if responseObject != nil {
- let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
- let code: String = responseObject!["code"] as? String ?? "06005"
- let message: String = responseObject!["message"] as? String ?? "unknown error"
-
- if Int(code)! == 200 {
- complete(ResultWrapper(success: true, content: data["content"] as! String))
- } else {
- complete(ResultWrapper(success: false, content: message))
- }
- } else {
- complete(ResultWrapper(success: false, content: "unknown error"))
- }
- }
- } else {
- if(KMMemberInfo.shared.isLogin == true) {
- KMUserInfoViewController.refreshTokenUserInfo {[weak self] success, resDic in
- if(success == true) {
- self?.aiMemberRewriting(content: content, state: state, complete: complete)
- } else {
- let code = resDic?.code ?? 200
- if(code == 304) {
- KMLoginWindowsController.shared.showWindow(nil)
- }
- }
- }
-
- }
- }
- }
-
- func aiMemberRewriting(content: String, state: KMAIRewritingState, complete: @escaping KMRequestServerComplete) {
- let token: String = KMMemberInfo.shared.access_token
- if token == "" {
- complete(ResultWrapper(success: false, content: "unknown error"))
- }
- var urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/rewrite"
- if state == .correctTypos {
- urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/correct-typos"
- }
- let params: [String: Any] = ["content": content]
-
- KMAIRequestServer.requestServer.aiMemberRewriting(urlString: urlString, params: params) { formData in
-
- } requestSerializer: { requestSerializer in
- requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
- requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
- } completion: { task, responseObject, error in
- if responseObject is KMMemberCenterResult {
- let resultObjct = responseObject as! KMMemberCenterResult
- let code = resultObjct.code
- let message: String = resultObjct.msg ?? ""
- if code == 200 {
- complete(ResultWrapper(success: true, content: message))
- } else {
- complete(ResultWrapper(success: false, content: message))
- }
- } else {
- complete(ResultWrapper(success: false, content: "unknown error"))
- }
- }
- }
-
- /**
- @abstract 提取摘要
- @param file 文件路径
- */
- private func extractSummaryFile(file: String, complete: @escaping KMRequestServerComplete) {
-
- let infoDictionary = Bundle .main.infoDictionary!
- let urlString = AIInfoConfig().aiActionURL + "/api/AI/extractSummaryFile"
- let fileData = FileManager.default.contents(atPath: file)
- let params: [String: Any] = ["file": fileData,
- "uuid": uuid(),
- "platform": platform(),
- "app_name": app_name()]
- KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
- let fileURL = URL(fileURLWithPath: file)
- try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
- } requestSerializer: { requestSerializer in
- requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
- } completion: { task, responseObject, error in
- if responseObject != nil {
- let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
- let code: Int = responseObject!["code"] as? Int ?? 06005
- let message: String = responseObject!["message"] as? String ?? "unknown error"
- let error = NSError(domain: message, code: code)
-
- if code == 200 {
- complete(ResultWrapper(success: true, content: data["summary"] as! String))
- } else {
- complete(ResultWrapper(success: false, content: message))
- }
- } else {
- let error = NSError(domain: "unknown error", code: 404)
- complete(ResultWrapper(success: false, content: "unknown error"))
- }
- }
- }
- private func memberExtractSummaryFile(file: String, complete: @escaping KMRequestServerComplete) {
- let token: String = KMMemberInfo.shared.access_token
- if token == "" {
- return
- }
- let urlString = AIInfoConfig().memberAIActionURL + "/member-system-website/api/extract-file-summary"
- let fileData = FileManager.default.contents(atPath: file)
- let params: [String: Any] = ["file": fileData]
-
- KMAIRequestServer.requestServer.uploadFile(urlString: urlString, params: params) { formData in
- let fileURL = URL(fileURLWithPath: file)
- try? formData.appendPart(withFileURL: fileURL, name: "file", fileName: fileURL.lastPathComponent, mimeType: "application/octet-stream")
- } requestSerializer: { requestSerializer in
- requestSerializer.setValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
- requestSerializer.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
- } completion: { task, responseObject, error in
- if responseObject != nil {
- let data: NSDictionary = responseObject!["data"] as? NSDictionary ?? [:]
- let code: Int = responseObject!["code"] as? Int ?? 06005
- let message: String = responseObject!["message"] as? String ?? "unknown error"
- let error = NSError(domain: message, code: code)
-
- if code == 200 {
- complete(ResultWrapper(success: true, content: data["summary"] as! String))
- } else {
- complete(ResultWrapper(success: false, content: message))
- }
- } else {
- let error = NSError(domain: "unknown error", code: 404)
- complete(ResultWrapper(success: false, content: "unknown error"))
- }
- }
- }
-
-
- }
- //typealias KMHttpRequestServerComplete = (_ task: URLSessionDataTask?, _ responseObject: AnyObject?, _ error: NSError?) -> Void
- class KMAIRequestServer {
- var sessionManager: AFHTTPSessionManager!
- static let requestServer = KMAIRequestServer()
- var task: URLSessionTask?
-
- init() {
- let configuration: URLSessionConfiguration = URLSessionConfiguration.default
- sessionManager = AFHTTPSessionManager.init(sessionConfiguration: configuration)
- sessionManager.securityPolicy = AFSecurityPolicy.default()
- }
-
- /**
- 上传文件
- - 翻译
- - 摘要提取
- */
- func uploadFile(urlString: String,
- params: Dictionary<String, Any>?,
- body: ((_ formData:AFMultipartFormData) -> Void)?,
- requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
- completion: KMHttpRequestServerComplete?) -> Void {
- sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
- sessionManager.requestSerializer.timeoutInterval = 60
- sessionManager.responseSerializer = AFJSONResponseSerializer()
- sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
- if (requestSerializer != nil) {
- requestSerializer!(sessionManager.requestSerializer);
- }
- if (body != nil) {
- self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
- body!(formData)
- } progress: { progress in
-
- } success: { task, responseObject in
- let responseObject = responseObject as AnyObject
- if (completion != nil) {
- completion!(task,responseObject,nil);
- }
- } failure: { task, error in
- if (completion != nil) {
- completion!(task, nil, error as NSError);
- }
- }
- } else {
- self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
-
- } success: { task, responseObject in
- if (completion != nil) {
- let responseObject = responseObject as AnyObject
- completion!(task,responseObject,nil);
- }
- } failure: { task, error in
- if (completion != nil) {
- completion!(task, nil, error as NSError);
- }
- }
- }
- }
-
- /**
- 文件翻译
- */
- func aiFileTranslateHandle(urlString: String,
- params: Dictionary<String, Any>?,
- body: ((_ formData:AFMultipartFormData) -> Void)?,
- requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
- completion: KMHttpRequestServerComplete?) -> Void {
- sessionManager.requestSerializer = AFJSONRequestSerializer()
- sessionManager.responseSerializer = AFJSONResponseSerializer()
- sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
- if (requestSerializer != nil) {
- requestSerializer!(sessionManager.requestSerializer);
- }
- if (body != nil) {
- self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
- body!(formData)
- } progress: { progress in
-
- } success: { task, responseObject in
- let responseObject = responseObject as AnyObject
- if (completion != nil) {
- completion!(task,responseObject,nil);
- }
- } failure: { task, error in
- if (completion != nil) {
- completion!(task, nil, error as NSError);
- }
- }
- } else {
- self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
-
- } success: { task, responseObject in
- if (completion != nil) {
- let responseObject = responseObject as AnyObject
- completion!(task,responseObject,nil);
- }
- } failure: { task, error in
- if (completion != nil) {
- completion!(task, nil, error as NSError);
- }
- }
- }
- }
-
- /**
- 重写
- */
- func aiRewriting(urlString: String,
- params: Dictionary<String, Any>?,
- body: ((_ formData:AFMultipartFormData) -> Void)?,
- requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
- completion: KMHttpRequestServerComplete?) -> Void {
- sessionManager.requestSerializer.setValue("multipart/form-data", forHTTPHeaderField: "Content-Type")
- sessionManager.requestSerializer.timeoutInterval = 60
- sessionManager.responseSerializer = AFJSONResponseSerializer()
- sessionManager.responseSerializer.acceptableContentTypes = ["application/json","text/html","text/json","text/javascript","text/plain","image/gif"]
- if (requestSerializer != nil) {
- requestSerializer!(sessionManager.requestSerializer);
- }
- if (body != nil) {
- self.task = sessionManager.post(urlString, parameters: params, headers: nil) { formData in
- body!(formData)
- } progress: { progress in
-
- } success: { task, responseObject in
- let responseObject = responseObject as AnyObject
- if (completion != nil) {
- completion!(task,responseObject,nil);
- }
- } failure: { task, error in
- if (completion != nil) {
- completion!(task, nil, error as NSError);
- }
- }
- } else {
- self.task = sessionManager.post(urlString, parameters: params, headers: nil) { progress in
-
- } success: { task, responseObject in
- if (completion != nil) {
- let responseObject = responseObject as AnyObject
- completion!(task,responseObject,nil);
- }
- } failure: { task, error in
- if (completion != nil) {
- completion!(task, nil, error as NSError);
- }
- }
- }
- }
-
- func aiMemberRewriting(urlString: String,
- params: Dictionary<String, Any>?,
- body: ((_ formData:AFMultipartFormData) -> Void)?,
- requestSerializer: ((_ requestSerializer:AFHTTPRequestSerializer) -> Void)?,
- completion: KMHttpRequestServerComplete?) -> Void {
-
- let token: String = KMMemberInfo.shared.access_token
-
- let urlString = urlString
- let paraDict: [String: Any] = params!
- let postData = try! JSONSerialization.data(withJSONObject: paraDict)
-
- var request = URLRequest(url: URL(string: urlString)!,timeoutInterval: Double.infinity)
- request.addValue("application/json", forHTTPHeaderField: "Content-Type")
-
- request.addValue("Apifox/1.0.0 (https://www.apifox.cn)", forHTTPHeaderField: "User-Agent")
- request.addValue("Bearer " + token, forHTTPHeaderField: "Authorization")
- request.httpMethod = "POST"
- request.httpBody = postData
-
- let task = URLSession.shared.dataTask(with: request) { data, response, error in
- guard let data = data else {
- print(String(describing: error))
- return
- }
- let jsonObject = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary ?? [:]
- if jsonObject != nil {
- let codeStr: String = jsonObject!["code"] as? String ?? ""
- var code: Int = 0
- if let numCode = Int(codeStr) {
- code = numCode
- }
- var result_bool: Bool = true
-
- var message: String = ""
- if let value = jsonObject!["message"]{
- message = value as! String
- }
- if let string = jsonObject!["data"] {
- let dataDic = jsonObject!["data"] as? NSDictionary ?? [:]
- if let dataStr = dataDic["content"] {
- message = dataStr as! String
- result_bool = true
- }
- }
- let result = KMMemberCenterResult(code: code, msg: message, result: result_bool)
- if code == 200 {
- if (completion != nil) {
- completion!(nil, result, nil);
- }
- } else {
- if (completion != nil) {
- completion!(nil, result, error as? NSError);
- }
- }
- } else {
- if (completion != nil) {
- completion!(nil, nil, error as? NSError);
- }
- }
- }
- task.resume()
-
- }
- }
|