TSGenerateBaseOperation.swift 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202
  1. //
  2. // TSGenerateBaseOperation.swift
  3. // AIRingtone
  4. //
  5. // Created by 100Years on 2025/3/24.
  6. //
  7. import Combine
  8. import Alamofire
  9. class TSGenerateBaseOperationQueue: TSBaseOperationQueue {
  10. // 存储每个操作的 AnyCancellable
  11. var stateables: [String: AnyCancellable] = [:]
  12. var generateOperationStateChanged:((String)->Void)?
  13. override func cancelOperations(uuid: String) {
  14. super.cancelOperations(uuid: uuid)
  15. stateables.removeValue(forKey: uuid)
  16. }
  17. func handleStateDatauPblished(uuid:String,generateOperation: TSGenerateBaseOperation,notificationName:Notification.Name) {
  18. stateables[uuid] = generateOperation.$stateDatauPblished.sink { [weak self] state in
  19. guard let self = self else { return }
  20. DispatchQueue.main.async {
  21. self.generateOperationStateChanged?(uuid)
  22. let uuidData = self.getUUIDData(uuid: uuid)
  23. NotificationCenter.default.post(
  24. name: notificationName,
  25. object: nil,
  26. userInfo: [
  27. "uuid": uuid,
  28. "count":self.queue.maxConcurrentOperationCount,
  29. "state":uuidData.0,
  30. "actionInfo":uuidData.1,
  31. ])
  32. }
  33. }
  34. }
  35. func getUUIDData(uuid:String)->(TSProgressState,TSActionInfoModel?){
  36. return (.none,TSActionInfoModel())
  37. }
  38. }
  39. class TSGenerateBaseOperation: TSBaseOperation , @unchecked Sendable{
  40. var actionInfoDict:[String:Any]{
  41. return [:]
  42. }
  43. @Published var stateDatauPblished:(TSProgressState,TSActionInfoModel?) = (TSProgressState.none,nil){
  44. didSet{
  45. dePrint("TSBaseOperation stateDatauPblished didSet = \(stateDatauPblished)")
  46. if case .start = stateDatauPblished.0 {
  47. start()
  48. }else if stateDatauPblished.0.isResult {
  49. DispatchQueue.main.asyncAfter(deadline: .now()+0.3){//稍微延迟,让通知报成功状态发送出去
  50. self.finished()
  51. }
  52. }
  53. }
  54. }
  55. var queryRequest:Request?
  56. var stopNetwork = false
  57. var generatingProgress = 0
  58. var action_id:Int = 0
  59. var isSaveDB:Bool = false //是否保存到数据库
  60. var currentActionInfoModelChanged:((TSActionInfoModel)->Void)?
  61. @Published var currentActionInfoModel: TSActionInfoModel = TSActionInfoModel()
  62. func initializeActionInfoModel(oldModel:TSActionInfoModel) {
  63. currentActionInfoModel = oldModel
  64. replaceSaveInfoModel(model: currentActionInfoModel)
  65. stateDatauPblished = (.start,currentActionInfoModel)
  66. }
  67. func replaceSaveInfoModel(model:TSActionInfoModel){ }
  68. func handleGenerateSuccess(){
  69. }
  70. func handleFailInfoModel(errorString:String?){
  71. self.currentActionInfoModel.actionStatus = .failed
  72. self.currentActionInfoModel.status = "failed"
  73. generatingProgress = 0
  74. self.replaceSaveInfoModel(model: self.currentActionInfoModel)
  75. self.stateDatauPblished = (.failed(errorString ?? ""),self.currentActionInfoModel)
  76. }
  77. func getActionInfo(oldModel:TSActionInfoModel) {
  78. currentActionInfoModel = oldModel
  79. self.getActionInfo(action_id:oldModel.id)
  80. }
  81. func getActionInfo(action_id:Int){
  82. self.action_id = action_id
  83. queryRequest = TSNetworkShared.get(urlType: .actionInfo,parameters: ["action_id":action_id]) { [weak self] data,error in
  84. guard let self = self else { return }
  85. if stopNetwork == true {
  86. return
  87. }
  88. if let result = kNetWorkResultSuccess(data: data) {
  89. if let genmojiModel = TSActionInfoModel(JSON: result) {
  90. if genmojiModel.actionStatus != .success {
  91. self.replaceSaveInfoModel(model: genmojiModel)
  92. }
  93. switch genmojiModel.actionStatus {
  94. case .success:
  95. let successBlock = { [weak self] in
  96. guard let self = self else { return }
  97. self.replaceSaveInfoModel(model: genmojiModel)
  98. dePrint("successBlock genmojiModel=\(genmojiModel.toJSONString())")
  99. self.stateDatauPblished = (.success(nil),genmojiModel)
  100. generatingProgress = 0
  101. self.handleGenerateSuccess()
  102. }
  103. if let url = URL(string:genmojiModel.response.resultUrl) {
  104. UIImageView.downloadImageWithProgress(urlString: genmojiModel.response.resultUrl) { [weak self] progress in
  105. guard let self = self else { return }
  106. let progressInt = Int(progress*10.0)
  107. let progressString = "Generating".localized + " \(90 + progressInt)%"
  108. stateDatauPblished = (.progressString(progressString),currentActionInfoModel)
  109. dePrint("生成后图片下载进度 \(progress)")
  110. } completion: { image in
  111. successBlock()
  112. }
  113. }else{
  114. successBlock()
  115. }
  116. case .failed:
  117. handleFailInfoModel(errorString: kNetWorkMessage(data: data) ?? "")
  118. default:
  119. stateDatauPblished = (.progressString(generating(progress: genmojiModel.percent)),currentActionInfoModel)
  120. if stopNetwork == false {
  121. kDelayOnMainThread(2.0) {
  122. self.getActionInfo(action_id: action_id)
  123. }
  124. }
  125. }
  126. return
  127. }
  128. }
  129. handleFailInfoModel(errorString: error?.localizedDescription)
  130. }
  131. }
  132. func generating(progress:Float) -> String {
  133. //Generating 0%-100%
  134. var progressInt = Int(progress*100)
  135. if generatingProgress >= progressInt{
  136. return getGeneratingProgressText()
  137. }
  138. if progressInt > 99 {
  139. progressInt = 99
  140. }
  141. generatingProgress = progressInt
  142. return getGeneratingProgressText()
  143. }
  144. func getGeneratingProgressText()->String{
  145. return "Working on your ringtone \(generatingProgress)%..."
  146. }
  147. override func cancelCleanContent() {
  148. debugPrint("cancelCleanContent")
  149. stopNetwork = true
  150. queryRequest?.cancel()
  151. }
  152. }
  153. var kRandomBoolLastResult:Bool = true
  154. func kRandomBool() -> Bool {
  155. if !kRandomBoolLastResult {
  156. // 如果上一次是 false,这次必须返回 true
  157. kRandomBoolLastResult = true
  158. return true
  159. } else {
  160. // 如果上一次是 true,随机返回 true 或 false
  161. let randomResult = Bool.random()
  162. kRandomBoolLastResult = randomResult
  163. return randomResult
  164. }
  165. }