TSDBHistoryManager.swift 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. //
  2. // TSDBHistoryManager.swift
  3. // AIEmoji
  4. //
  5. // Created by 100Years on 2025/4/25.
  6. //
  7. import RealmSwift
  8. import ObjectMapper
  9. // 1. 定义历史记录类型枚举
  10. enum TSDBHistoryType: String,CaseIterable {
  11. case ptp = "photoToPhotoHistoryListString" //图生图
  12. case ttp = "textPicHistoryListString" //文生图
  13. case ttEnmoji = "enmojiHistoryListString" //文生表情
  14. case pretty = "kTSAIPhotoPrettyHistoryListString" //美容
  15. case oldAge = "kTSChangeOldAgeHistoryListString" //变老
  16. case babyAge = "kTSChangeBabyAgeHistoryListString" //变年轻
  17. case oldPhoto = "kTSChangeOldPhotoHistoryListString" //旧照片修复
  18. case openEyes = "kTSAIEyeOpenHistoryListString" //睁眼
  19. case photoLive = "kTSAIPhotoLiveHistoryListString" //活照片
  20. case photoExpand = "kTSAIPhotoExpandHistoryListString" //照片扩展
  21. case photoQuality = "kTSAIPhotoQualityHistoryListString" //照片变高清
  22. }
  23. //MARK: TSDBAIChatList - 用于存储会话及消息列表
  24. class TSDBHistory: Object {
  25. @Persisted(primaryKey: true) var primaryKey: String = ""
  26. @Persisted var listModels = List<TSDBActionInfoModel>()
  27. var type: TSDBHistoryType {
  28. get { TSDBHistoryType(rawValue: primaryKey) ?? .ptp }
  29. set { primaryKey = newValue.rawValue }
  30. }
  31. convenience init(type: TSDBHistoryType) {
  32. self.init()
  33. self.primaryKey = type.rawValue
  34. }
  35. func getModelList() -> [TSActionInfoModel] {
  36. var msgModel:[TSActionInfoModel] = []
  37. for msgDBModel in listModels {
  38. msgModel.append(msgDBModel.getModel())
  39. }
  40. return msgModel
  41. }
  42. func getModelList(completion:@escaping ([TSActionInfoModel])->Void){
  43. let frozenList = self.listModels.freeze()
  44. DispatchQueue.global(qos: .userInitiated).async {
  45. var msgModel:[TSActionInfoModel] = []
  46. for msgDBModel in frozenList {
  47. msgModel.append(msgDBModel.getModel())
  48. }
  49. DispatchQueue.main.async {
  50. completion(msgModel)
  51. }
  52. }
  53. }
  54. func getModelList(count:Int) -> [TSActionInfoModel] {
  55. let listModels = Array(listModels.prefix(count))
  56. var msgModel:[TSActionInfoModel] = []
  57. for msgDBModel in listModels {
  58. msgModel.append(msgDBModel.getModel())
  59. }
  60. return msgModel
  61. }
  62. func delete() {
  63. TSRMShared.delete(self)
  64. }
  65. func deleteListModel(id:Int) {
  66. TSRMShared.writeThread {
  67. if let index = listModels.firstIndex(where: { $0.id == id }) {
  68. listModels.remove(at: index)
  69. debugPrint("listModels.remove(at: \(index))")
  70. }
  71. }
  72. }
  73. static func deleteAll() {
  74. do {
  75. let realm = try Realm()
  76. try realm.write {
  77. let allPersons = realm.objects(TSDBHistory.self)
  78. realm.delete(allPersons)
  79. }
  80. } catch {
  81. debugPrint("删除 TSDBPTPHistory 模型数据时出错: \(error)")
  82. }
  83. }
  84. func updateData(_ actionInfoModel:TSActionInfoModel,id:Int? = nil){
  85. let dbModel = TSDBActionInfoModel.createDBModel(actionInfoModel: actionInfoModel)
  86. var replaceID = dbModel.id
  87. if let id = id {
  88. replaceID = id
  89. }
  90. let frozenList = self.listModels.freeze()
  91. if let index = frozenList.firstIndex(where: { $0.id == replaceID }) {
  92. TSRMShared.writeThread {
  93. listModels[index] = dbModel// 如果找到,替换该元素
  94. }
  95. } else {
  96. print("Thread.current insert1=\(Thread.current)")
  97. TSRMShared.writeThread {
  98. listModels.insert(dbModel, at: 0)// 如果没有找到,添加到末尾
  99. print("Thread.current insert2=\(Thread.current)")
  100. }
  101. }
  102. }
  103. func updateDatas(_ actionInfoModels:[TSActionInfoModel]){
  104. for actionInfoModel in actionInfoModels {
  105. updateData(actionInfoModel)
  106. }
  107. }
  108. func addDatas(_ actionInfoModels:[TSActionInfoModel]){
  109. for actionInfoModel in actionInfoModels {
  110. let dbModel = TSDBActionInfoModel.createDBModel(actionInfoModel: actionInfoModel)
  111. TSRMShared.writeThread {
  112. listModels.append(dbModel)
  113. }
  114. }
  115. }
  116. }
  117. extension TSDBHistory {
  118. //是否需要迁移历史记录
  119. static var isMigrationUserDefaultsHistory:Bool{
  120. for type in TSDBHistoryType.allCases {
  121. if let _ = UserDefaults.standard.string(forKey: type.rawValue){
  122. debugPrint("需要迁移\(type.rawValue)")
  123. return true
  124. }
  125. }
  126. return false
  127. }
  128. static func migrationUserDefaultsHistory(complete:@escaping ()->Void){
  129. DispatchQueue.global(qos: .userInitiated).async {
  130. for type in TSDBHistoryType.allCases {
  131. if let historyString = UserDefaults.standard.string(forKey: type.rawValue){
  132. if let models = Mapper<TSActionInfoModel>().mapArray(JSONString: historyString) {
  133. debugPrint("TSDBHistory 需要迁移\(type.rawValue)\(models.count)条")
  134. let dbHistory = TSRMShared.getDBHistory(type:type)
  135. dbHistory.addDatas(models)
  136. debugPrint("TSDBHistory 迁移完毕\(type.rawValue)")
  137. UserDefaults.standard.set(nil, forKey: type.rawValue)
  138. UserDefaults.standard.synchronize()
  139. }
  140. }
  141. }
  142. DispatchQueue.main.async {
  143. complete()
  144. }
  145. }
  146. }
  147. }
  148. extension TSRealmManager {
  149. func getDBHistory(type:TSDBHistoryType) -> TSDBHistory {
  150. let predicate = NSPredicate(format: "primaryKey == %@",type.rawValue)
  151. let historys = TSRMShared.realm.objects(TSDBHistory.self).filter(predicate)
  152. if let history = historys.first {
  153. return history
  154. }else {
  155. let dbHistory = TSDBHistory(type: type)
  156. TSRMShared.update(dbHistory)
  157. return dbHistory
  158. }
  159. }
  160. func createExampleModel(id:Int,imageName:String)->TSActionInfoModel{
  161. let model = TSActionInfoModel()
  162. model.id = id
  163. model.modelType = .example
  164. model.request.prompt = "Example"
  165. model.request.promptSort = "Example"
  166. model.request.width = 330
  167. model.request.height = 440
  168. model.response.resultUrl = imageName
  169. model.status = "success"
  170. return model
  171. }
  172. //测试 5万条数据
  173. func textPtpDBHistory(){
  174. DispatchQueue.global(qos: .userInteractive).async {
  175. let id = Date.timestampInt
  176. var array:[TSDBActionInfoModel] = []
  177. debugPrint("创建 5万条数据 前")
  178. for i in 0...50 {
  179. let dbModel = TSDBActionInfoModel.createDBModel(actionInfoModel: self.createExampleModel(id:id+i, imageName: "ptp_example_image0"))
  180. array.append(dbModel)
  181. }
  182. debugPrint("创建 5万条数据 后")
  183. TSRMShared.writeThread {
  184. debugPrint("写入 5万条数据")
  185. // TSRMShared.photoExpandDBHistory.listModels.append(objectsIn: array)
  186. TSRMShared.ptpDBHistory.listModels.append(objectsIn: array)
  187. debugPrint("写完 5万条数据")
  188. }
  189. }
  190. }
  191. //图生图
  192. var ptpDBHistory:TSDBHistory {
  193. let ptpHistory = getDBHistory(type: TSDBHistoryType.ptp)
  194. if ptpHistory.listModels.count == 0,UserDefaults.standard.string(forKey: "insertPTPExampleData") == nil {
  195. let id = Date.timestampInt
  196. ptpHistory.updateDatas([
  197. createExampleModel(id:id, imageName: "ptp_example_image0"),
  198. createExampleModel(id:id+1, imageName: "ptp_example_image1")
  199. ])
  200. UserDefaults.standard.set("1", forKey: "insertPTPExampleData")
  201. UserDefaults.standard.synchronize()
  202. }
  203. return ptpHistory
  204. }
  205. //文生图
  206. var ttpDBHistory:TSDBHistory {
  207. return getDBHistory(type: TSDBHistoryType.ttp)
  208. }
  209. //文生表情
  210. var ttEnmojiDBHistory:TSDBHistory {
  211. return getDBHistory(type: TSDBHistoryType.ttEnmoji)
  212. }
  213. //美容
  214. var oldAgeDBHistory:TSDBHistory {
  215. return getDBHistory(type: TSDBHistoryType.oldAge)
  216. }
  217. //变老
  218. var prettyDBHistory:TSDBHistory {
  219. return getDBHistory(type: TSDBHistoryType.pretty)
  220. }
  221. //变年轻
  222. var babyAgeDBHistory:TSDBHistory {
  223. return getDBHistory(type: TSDBHistoryType.babyAge)
  224. }
  225. //老照片修复
  226. var oldPhotoDBHistory:TSDBHistory {
  227. return getDBHistory(type: TSDBHistoryType.oldPhoto)
  228. }
  229. //睁眼
  230. var openEyesDBHistory:TSDBHistory {
  231. return getDBHistory(type: TSDBHistoryType.openEyes)
  232. }
  233. //活照片
  234. var photoLiveDBHistory:TSDBHistory {
  235. return getDBHistory(type: TSDBHistoryType.photoLive)
  236. }
  237. //扩图
  238. var photoExpandDBHistory:TSDBHistory {
  239. return getDBHistory(type: TSDBHistoryType.photoExpand)
  240. }
  241. //变高清图
  242. var photoQualityDBHistory:TSDBHistory {
  243. return getDBHistory(type: TSDBHistoryType.photoQuality)
  244. }
  245. }