123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291 |
- //
- // TSDBHistoryManager.swift
- // AIEmoji
- //
- // Created by 100Years on 2025/4/25.
- //
- import RealmSwift
- import ObjectMapper
- // 1. 定义历史记录类型枚举
- enum TSDBHistoryType: String,CaseIterable {
- case ptp = "photoToPhotoHistoryListString" //图生图
- case ttp = "textPicHistoryListString" //文生图
- case ttEnmoji = "enmojiHistoryListString" //文生表情
- case pretty = "kTSAIPhotoPrettyHistoryListString" //美容
- case oldAge = "kTSChangeOldAgeHistoryListString" //变老
- case babyAge = "kTSChangeBabyAgeHistoryListString" //变年轻
- case oldPhoto = "kTSChangeOldPhotoHistoryListString" //旧照片修复
- case openEyes = "kTSAIEyeOpenHistoryListString" //睁眼
- case photoLive = "kTSAIPhotoLiveHistoryListString" //活照片
- case photoExpand = "kTSAIPhotoExpandHistoryListString" //照片扩展
- case photoQuality = "kTSAIPhotoQualityHistoryListString" //照片变高清
-
- }
- //MARK: TSDBAIChatList - 用于存储会话及消息列表
- class TSDBHistory: Object {
- @Persisted(primaryKey: true) var primaryKey: String = ""
- @Persisted var listModels = List<TSDBActionInfoModel>()
-
- var type: TSDBHistoryType {
- get { TSDBHistoryType(rawValue: primaryKey) ?? .ptp }
- set { primaryKey = newValue.rawValue }
- }
-
- convenience init(type: TSDBHistoryType) {
- self.init()
- self.primaryKey = type.rawValue
- }
-
- func getModelList() -> [TSActionInfoModel] {
- var msgModel:[TSActionInfoModel] = []
- for msgDBModel in listModels {
- msgModel.append(msgDBModel.getModel())
- }
- return msgModel
- }
-
-
- func getModelList(completion:@escaping ([TSActionInfoModel])->Void){
- let frozenList = self.listModels.freeze()
- DispatchQueue.global(qos: .userInitiated).async {
- var msgModel:[TSActionInfoModel] = []
- for msgDBModel in frozenList {
- msgModel.append(msgDBModel.getModel())
- }
- DispatchQueue.main.async {
- completion(msgModel)
- }
- }
- }
-
- func getModelList(count:Int) -> [TSActionInfoModel] {
- let listModels = Array(listModels.prefix(count))
- var msgModel:[TSActionInfoModel] = []
- for msgDBModel in listModels {
- msgModel.append(msgDBModel.getModel())
- }
- return msgModel
- }
-
- func delete() {
- TSRMShared.delete(self)
- }
-
- func deleteListModel(id:Int) {
- TSRMShared.writeThread {
- if let index = listModels.firstIndex(where: { $0.id == id }) {
- listModels.remove(at: index)
- debugPrint("listModels.remove(at: \(index))")
- }
- }
- }
-
- static func deleteAll() {
- do {
- let realm = try Realm()
- try realm.write {
- let allPersons = realm.objects(TSDBHistory.self)
- realm.delete(allPersons)
- }
- } catch {
- debugPrint("删除 TSDBPTPHistory 模型数据时出错: \(error)")
- }
- }
-
- func updateData(_ actionInfoModel:TSActionInfoModel,id:Int? = nil){
- let dbModel = TSDBActionInfoModel.createDBModel(actionInfoModel: actionInfoModel)
- var replaceID = dbModel.id
- if let id = id {
- replaceID = id
- }
-
- let frozenList = self.listModels.freeze()
- if let index = frozenList.firstIndex(where: { $0.id == replaceID }) {
- TSRMShared.writeThread {
- listModels[index] = dbModel// 如果找到,替换该元素
- }
- } else {
- print("Thread.current insert1=\(Thread.current)")
- TSRMShared.writeThread {
- listModels.insert(dbModel, at: 0)// 如果没有找到,添加到末尾
- print("Thread.current insert2=\(Thread.current)")
- }
- }
- }
-
- func updateDatas(_ actionInfoModels:[TSActionInfoModel]){
- for actionInfoModel in actionInfoModels {
- updateData(actionInfoModel)
- }
- }
-
- func addDatas(_ actionInfoModels:[TSActionInfoModel]){
- for actionInfoModel in actionInfoModels {
- let dbModel = TSDBActionInfoModel.createDBModel(actionInfoModel: actionInfoModel)
- TSRMShared.writeThread {
- listModels.append(dbModel)
- }
- }
- }
- }
- extension TSDBHistory {
- //是否需要迁移历史记录
- static var isMigrationUserDefaultsHistory:Bool{
- for type in TSDBHistoryType.allCases {
- if let _ = UserDefaults.standard.string(forKey: type.rawValue){
- debugPrint("需要迁移\(type.rawValue)")
- return true
- }
- }
- return false
- }
- static func migrationUserDefaultsHistory(complete:@escaping ()->Void){
- DispatchQueue.global(qos: .userInitiated).async {
- for type in TSDBHistoryType.allCases {
- if let historyString = UserDefaults.standard.string(forKey: type.rawValue){
- if let models = Mapper<TSActionInfoModel>().mapArray(JSONString: historyString) {
- debugPrint("TSDBHistory 需要迁移\(type.rawValue)\(models.count)条")
- let dbHistory = TSRMShared.getDBHistory(type:type)
- dbHistory.addDatas(models)
- debugPrint("TSDBHistory 迁移完毕\(type.rawValue)")
- UserDefaults.standard.set(nil, forKey: type.rawValue)
- UserDefaults.standard.synchronize()
- }
- }
- }
- DispatchQueue.main.async {
- complete()
- }
- }
- }
- }
- extension TSRealmManager {
- func getDBHistory(type:TSDBHistoryType) -> TSDBHistory {
- let predicate = NSPredicate(format: "primaryKey == %@",type.rawValue)
- let historys = TSRMShared.realm.objects(TSDBHistory.self).filter(predicate)
- if let history = historys.first {
- return history
- }else {
- let dbHistory = TSDBHistory(type: type)
- TSRMShared.update(dbHistory)
- return dbHistory
- }
- }
-
- func createExampleModel(id:Int,imageName:String)->TSActionInfoModel{
- let model = TSActionInfoModel()
- model.id = id
- model.modelType = .example
- model.request.prompt = "Example"
- model.request.promptSort = "Example"
- model.request.width = 330
- model.request.height = 440
- model.response.resultUrl = imageName
- model.status = "success"
- return model
- }
-
- //测试 5万条数据
- func textPtpDBHistory(){
- DispatchQueue.global(qos: .userInteractive).async {
- let id = Date.timestampInt
- var array:[TSDBActionInfoModel] = []
- debugPrint("创建 5万条数据 前")
- for i in 0...50 {
- let dbModel = TSDBActionInfoModel.createDBModel(actionInfoModel: self.createExampleModel(id:id+i, imageName: "ptp_example_image0"))
- array.append(dbModel)
- }
- debugPrint("创建 5万条数据 后")
-
- TSRMShared.writeThread {
- debugPrint("写入 5万条数据")
- // TSRMShared.photoExpandDBHistory.listModels.append(objectsIn: array)
- TSRMShared.ptpDBHistory.listModels.append(objectsIn: array)
- debugPrint("写完 5万条数据")
- }
- }
- }
-
- //图生图
- var ptpDBHistory:TSDBHistory {
- let ptpHistory = getDBHistory(type: TSDBHistoryType.ptp)
-
- if ptpHistory.listModels.count == 0,UserDefaults.standard.string(forKey: "insertPTPExampleData") == nil {
- let id = Date.timestampInt
- ptpHistory.updateDatas([
- createExampleModel(id:id, imageName: "ptp_example_image0"),
- createExampleModel(id:id+1, imageName: "ptp_example_image1")
- ])
- UserDefaults.standard.set("1", forKey: "insertPTPExampleData")
- UserDefaults.standard.synchronize()
- }
-
- return ptpHistory
- }
-
- //文生图
- var ttpDBHistory:TSDBHistory {
- return getDBHistory(type: TSDBHistoryType.ttp)
- }
- //文生表情
- var ttEnmojiDBHistory:TSDBHistory {
- return getDBHistory(type: TSDBHistoryType.ttEnmoji)
- }
- //美容
- var oldAgeDBHistory:TSDBHistory {
- return getDBHistory(type: TSDBHistoryType.oldAge)
- }
-
- //变老
- var prettyDBHistory:TSDBHistory {
- return getDBHistory(type: TSDBHistoryType.pretty)
- }
-
- //变年轻
- var babyAgeDBHistory:TSDBHistory {
- return getDBHistory(type: TSDBHistoryType.babyAge)
- }
-
- //老照片修复
- var oldPhotoDBHistory:TSDBHistory {
- return getDBHistory(type: TSDBHistoryType.oldPhoto)
- }
-
- //睁眼
- var openEyesDBHistory:TSDBHistory {
- return getDBHistory(type: TSDBHistoryType.openEyes)
- }
-
- //活照片
- var photoLiveDBHistory:TSDBHistory {
- return getDBHistory(type: TSDBHistoryType.photoLive)
- }
-
- //扩图
- var photoExpandDBHistory:TSDBHistory {
- return getDBHistory(type: TSDBHistoryType.photoExpand)
- }
-
- //变高清图
- var photoQualityDBHistory:TSDBHistory {
- return getDBHistory(type: TSDBHistoryType.photoQuality)
- }
- }
|