123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272 |
- //
- // TSGeneratePTPOperation.swift
- // AIRingtone
- //
- // Created by 100Years on 2025/3/24.
- //
- import Combine
- import Alamofire
- import ObjectMapper
- import Kingfisher
- class TSGeneratePTPOperationQueue: TSGenerateBaseOperationQueue {
- static let shared:TSGeneratePTPOperationQueue = TSGeneratePTPOperationQueue()
- func creatOperation(uuid: String) -> TSGeneratePTPOperation {
- let operation = super.creatOperation(uuid: uuid, type: TSGeneratePTPOperation.self)
- handleStateDatauPblished(uuid: uuid, generateOperation: operation as! TSGenerateBaseOperation, notificationName: .kGeneratePTPOperationChanged)
- return operation as! TSGeneratePTPOperation
- }
-
- override func getUUIDData(uuid:String)->(TSProgressState,TSActionInfoModel?){
- if let PosterOperation = TSGeneratePTPOperationQueue.shared.findOperation(uuid: uuid) as? TSGeneratePTPOperation {
- dePrint("TSBaseOperation stateDatauPblished 发送 = \(PosterOperation.stateDatauPblished)")
- return (PosterOperation.stateDatauPblished.0,PosterOperation.currentActionInfoModel)
- }
- return (.none,TSActionInfoModel())
- }
-
- }
- class TSGeneratePTPOperation: TSGenerateBaseOperation , @unchecked Sendable{
-
- //是否展示成功后的 View 提醒
- public var isShowSuccessView:Bool = false
-
- override var actionInfoDict:[String:Any]{
- return [
- "actionType":"image_create",
- "comments": "Success",
- "costTime":9,
- "createdTimestamp":1742183242,
- "id":2449,
- "percent":1,
- "request":"{\"prompt\": \"Traditional Chinese ink painting style phoenix soaring through misty mountain peaks, dynamic black brushstrokes with crimson accents on rice paper texture, Googie architecture space station, 1950s atomic age aesthetic, curved aluminum panels, starburst patterns, glass dome observatory --edge_threshold 0.5 --atomic_age_style 0.8 --chrome_reflection 1.2\", \"width\": 800, \"height\": 1440, \"countryCode\": \"FR\"}",
- "response": "{\"resultUrl\": \"https://be-aigc.s3-accelerate.amazonaws.com/4c946f78-b1e7-4ffe-ba18-fff26b10178c.png\"}",
- "status":"success"
- ]
- }
- override func replaceSaveInfoModel(model:TSActionInfoModel){
- model.uuid = uuid
- model.request.imageUrlTimestamp = currentActionInfoModel.request.imageUrlTimestamp
- if isSaveDB {
- TSRMShared.ptpDBHistory.updateData(model,id: currentActionInfoModel.id)
- }
- currentActionInfoModel = model
- dePrint("model actionStatus 发出=\(model.actionStatus)")
- currentActionInfoModelChanged?(currentActionInfoModel)
- }
- // override func handleGenerateSuccess() {
- // kPurchaseDefault.useOnceForFree(type: .picToPic)
- //
- // if isShowSuccessView == false {
- // return
- // }
- //
- // guard let window = WindowHelper.getKeyWindow() else {
- // debugPrint("getKeyWindow nil")
- // return
- // }
- //
- // guard let rootVC = WindowHelper.topViewController() else {
- // debugPrint("handleGenerateSuccess topViewController nil")
- // return
- // }
- //
- // let copyModel = self.currentActionInfoModel.copy()
- // if let rootVC = WindowHelper.getCurrentViewController() ,let cyModel = copyModel as? TSActionInfoModel {
- // kSaveSuccesswShared.show(atView: rootVC.view,text: "Successfully generated".localized,deadline: 5.0,bottom: kSaveSuccesswShared.getBottom(topY: k_Nav_Height+10)) {
- // let gennerateVC = TSPTPGeneratorVC(generateStyleModel: TSGenerateOnlineStyleModel(),infoModel: cyModel) { model in }
- // gennerateVC.modalPresentationStyle = .overFullScreen
- // gennerateVC.modalTransitionStyle = .crossDissolve
- // rootVC.present(gennerateVC, animated: true)
- // }
- // }else{
- // debugPrint("copyModel as? TSActionInfoModel error")
- // }
- // }
-
- override func handleGenerateSuccess() {
- kPurchaseDefault.useOnceForFree(type: .picToPic)
- Self.saveCurrentActionInfoModel = self.currentActionInfoModel
- if isShowSuccessView == false {
- return
- }
-
- guard let _ = WindowHelper.getKeyWindow() else {
- debugPrint("getKeyWindow nil")
- return
- }
-
- guard let _ = WindowHelper.topViewController() else {
- debugPrint("handleGenerateSuccess topViewController nil")
- return
- }
-
- if let rootVC = WindowHelper.getCurrentViewController() ,let cyModel = Self.saveCurrentActionInfoModel {
- kSaveSuccesswShared.show(atView: rootVC.view,text: "Successfully generated".localized,deadline: 5.0,bottom: kSaveSuccesswShared.getBottom(topY: k_Nav_Height+10)) {
- let gennerateVC = TSPTPGeneratorVC(generateStyleModel: TSGenerateOnlineStyleModel(),infoModel: cyModel) { model in }
- gennerateVC.modalPresentationStyle = .overFullScreen
- gennerateVC.modalTransitionStyle = .crossDissolve
- rootVC.present(gennerateVC, animated: true)
- }
- }else{
- debugPrint("copyModel as? TSActionInfoModel error")
- }
- }
- /**
- 1.用户上传图片
- 2.调用生成接口
- 3.后台返回查询 id,根据 id 不断查询进度和结果.(此时才允许进度后台)
-
- 利用3后台返回的TSActionRequestModel中存着关键的请求接口数据,请求数据
-
- */
-
- private var uploadRequest:Request?
- private var creatRequest:Request?
-
- private func createActionInfoModel(generateStyleModel:TSGenerateOnlineStyleModel) -> TSActionInfoModel? {
- guard let upLoadImageUrl = generateStyleModel.upLoadImageUrl else { return nil }
- let infoModel = TSActionInfoModel()
- infoModel.id = Date.timestampInt
- infoModel.request = TSActionRequestModel()
- infoModel.request.imageUrl = upLoadImageUrl
- infoModel.request.imageUrlTimestamp = Date.timestampInt
-
- infoModel.request.prompt = ""
- infoModel.request.promptSort = generateStyleModel.inputText
- infoModel.request.style = generateStyleModel.styleId
- infoModel.request.advance = false
-
- return infoModel
- }
-
- func uploadImage(generateStyleModel:TSGenerateOnlineStyleModel,complete:@escaping (TSActionInfoModel?)->Void) {
-
- guard let upLoadImage = generateStyleModel.upLoadImage else { return }
- if let imageUrl = generateStyleModel.upLoadImageUrl,imageUrl.contains("http") {
- complete(createActionInfoModel(generateStyleModel: generateStyleModel))
- return
- }
-
- stopNetwork = false
- stateDatauPblished = (.start,currentActionInfoModel)
-
- stateDatauPblished = (.progressString(uploadingPhoto(progress: 0.0)),currentActionInfoModel)
- uploadRequest = TSNetworkShared.uploadImage(upLoadImage: upLoadImage, maxKb: imageMaxKb) { [weak self] progress in
- guard let self = self else { return }
- if generatingProgress == 0 {
- stateDatauPblished = (.progressString(uploadingPhoto(progress: progress)),currentActionInfoModel)
- }
- } completion: { [weak self] data, error in
- guard let self = self else { return }
- if let error = error {
- generateStyleModel.upLoadImageUrl = nil
- self.stateDatauPblished = (.failed(error.localizedDescription),currentActionInfoModel)
- complete(nil)
- }else{
- if let string = data as? String {
- generateStyleModel.upLoadImageUrl = string
- if let url = URL(string: string){//上传成功后,就将图片缓存到本地
- ImageCache.default.store(upLoadImage, forKey: url.cacheKey)
- }
-
- complete(createActionInfoModel(generateStyleModel: generateStyleModel))
- }else{
- complete(nil)
- }
- }
- }
- }
-
- func creatImage(oldModel:TSActionInfoModel) {
-
- initializeActionInfoModel(oldModel: oldModel)
- if oldModel.upImageURLExpired { return }
- generatingProgress = 0
- stopNetwork = false
- stateDatauPblished = (.start,currentActionInfoModel)
-
-
- currentActionInfoModel.status = "running"
- currentActionInfoModel.actionStatus = .running
- currentActionInfoModel.percent = 0
- replaceSaveInfoModel(model: currentActionInfoModel)
-
- stateDatauPblished = (.progressString(generating(progress: 0.0)),currentActionInfoModel)
-
-
- let request = currentActionInfoModel.request
- var prompt = request.prompt
- let promptSort = request.promptSort
-
- if promptSort.count>0{
- if prompt.count > 0 {
- prompt = prompt + ", " + promptSort
- }else {
- prompt = promptSort
- }
- }
-
- creatRequest = TSNetworkShared.post(urlType: .imageRewriteV2,parameters:
- ["prompt":prompt,
- "imageUrl":request.imageUrl,
- "styleId":request.style,
- "device":getUserInfoJsonString(),
- ]) { [weak self] data,error in
- guard let self = self else { return }
-
- if let dataDict = kNetWorkCodeSuccess(data: data),
- let actionId = dataDict["actionId"] as? Int{
- if stopNetwork == false {
- self.stateDatauPblished = (.pending,currentActionInfoModel) //通知首页进行更新
- self.stateDatauPblished = (.backstage(true),currentActionInfoModel) //通知允许进入后台生成
- self.getActionInfo(action_id:actionId)
- }
- }else{
- handleFailInfoModel(errorString: error?.localizedDescription ?? "")
- }
- }
- }
- override func generating(progress: Float) -> String {
- let progress = Float(progress)*(0.9) // 预留 10% 进度给图片下载
- //Generating 0%-100%
- var progressInt = Int(progress*100)
- if progressInt > 99 {
- progressInt = 99
- }
-
- generatingProgress = progressInt
- return "Generating".localized + " \(progressInt)%"
- }
- var imageMaxKb:Int{
- return 10*1024
- }
-
- func uploadingPhoto(progress:Float) -> String {
- //Uploading Photo 0%-100%
- var progressInt = Int(progress*100)
- if progressInt > 99 {
- progressInt = 99
- }
- return "Uploading Photo".localized + " \(progressInt)%"
- }
-
-
- override func cancelCleanContent() {
- super.cancelCleanContent()
- debugPrint("cancelCleanContent")
- uploadRequest?.cancel()
- creatRequest?.cancel()
- }
- }
|