ChatMessageModel.m 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  1. //
  2. // ChatMessageModel.m
  3. // AIIM
  4. //
  5. // Created by qitewei on 2025/5/14.
  6. //
  7. #import "ChatMessageModel.h"
  8. #import "CryptoAES.h"
  9. #import "ChatsStore.h"
  10. #import "AVFoundation/AVFoundation.h"
  11. #import "FileNetApi.h"
  12. #import <SDWebImage/SDImageCache.h>
  13. @implementation ChatMessageModel
  14. + (instancetype)modelWithDictionary:(NSDictionary *)dict {
  15. ChatMessageModel *model = [[ChatMessageModel alloc] init];
  16. [model setupWithDictionary:dict];
  17. return model;
  18. }
  19. - (void)setupWithDictionary:(NSDictionary *)dict {
  20. NSMutableDictionary * mutableDict = [NSMutableDictionary dictionaryWithDictionary:dict];
  21. [mutableDict jk_each:^(id k, id v) {
  22. if ([v isKindOfClass:[NSNull class]]) {
  23. [mutableDict setObject:@"" forKey:k];
  24. }
  25. }];
  26. //原消息
  27. self.formerMessage = dict;
  28. self.chatId = mutableDict[@"chatId"];
  29. // 消息类型
  30. NSInteger type = [mutableDict[@"messageType"] integerValue];
  31. self.messageType = (ChatMessageType)type;
  32. self.type = [mutableDict[@"type"] integerValue];
  33. self.nickName = mutableDict[@"fromName"]?:@"";
  34. self.avatar = mutableDict[@"fromAvatar"]?:@"";
  35. // 通用内容
  36. // self.content = mutableDict[@"content"] ?: @"";//本地明文存储
  37. self.content =[CryptoAES.shareInstance decryptDataL:mutableDict[@"content"] ?: @""];//本地加密存储
  38. self.msgId = mutableDict[@"id"];
  39. self.fromId = mutableDict[@"fromId"];
  40. // 发送方标识
  41. NSDictionary *userinfo = [UDManager.shareInstance getDDManager:dkuserinfo];
  42. NSString *userId = userinfo[@"id"];
  43. if([self.fromId isEqualToString:userId]){
  44. self.isSender=true;
  45. }
  46. else{
  47. self.isSender=false;
  48. }
  49. // 处理媒体尺寸
  50. CGFloat width = [mutableDict[@"width"] floatValue];
  51. CGFloat height = [mutableDict[@"height"] floatValue];
  52. if (width > 0 && height > 0) {
  53. self.mediaSize = CGSizeMake(width, height);
  54. } else {
  55. // 默认尺寸
  56. self.mediaSize = CGSizeMake(200, 150);
  57. }
  58. self.placeholderImage = kImageMake(@"pictrue_placeholder");
  59. // 文件消息
  60. NSDictionary * extend = [mutableDict[@"extend"] isKindOfClass:NSDictionary.class]?mutableDict[@"extend"]:@{};
  61. self.fileName = extend[@"fileName"] ?: @"未知文件";
  62. self.fileSize = extend[@"size"] ?: @"0KB";
  63. self.url = extend[@"url"] ?: @"";
  64. // NSCharacterSet *allowedCharacters = [NSCharacterSet URLQueryAllowedCharacterSet];
  65. // self.url = [self.url stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
  66. self.localurl = extend[@"localurl"] ?: @"";
  67. self.quoteMessage = ![extend jk_hasKey:@"quoteMessage"] ?NULL: [ChatMessageModel modelWithDictionary:extend[@"quoteMessage"]];
  68. // 语音消息
  69. NSInteger duration = [extend[@"time"] integerValue];
  70. if (duration<=60) {
  71. self.voiceDuration = duration;
  72. }else{
  73. self.voiceDuration = duration/1000;
  74. }
  75. self.voiceWidth = [self voiceBubbleWidth];
  76. //文件传输成功或失败
  77. self.fileError = [extend[@"fileError"] integerValue];
  78. //合并转发
  79. self.forwardMsgArray = extend[@"messageList"] ?:@[];
  80. // 通话记录
  81. self.callDuration = [mutableDict[@"duration"] integerValue];
  82. self.isCallSuccess = [mutableDict[@"result"] boolValue];
  83. self.isVideo = [mutableDict[@"video"] boolValue];
  84. //@相关
  85. self.atAll = extend[@"atAll"]?[extend[@"atAll"] boolValue]:NO;
  86. self.atUserIds = extend[@"atUserIds"]?:@[];
  87. // 时间戳(如果需要)
  88. self.timestamp = [mutableDict[@"timestamp"] longLongValue];
  89. self.localtime = [mutableDict[@"localtime"] longLongValue];
  90. self.formatterTime = [self timeF:self.timestamp];
  91. // 其他自定义字段...
  92. self.readStatus = [self getReadStatus];
  93. BOOL contain = [[NSFileManager defaultManager] fileExistsAtPath:self.localurl];
  94. NSString *localPath = [self checkHasLocalPath];
  95. if (!contain && localPath.length) {
  96. self.localurl = localPath;
  97. }
  98. }
  99. - (void)exchangeModelWithModel:(ChatMessageModel *)model{
  100. self.msgId = model.msgId;
  101. self.formerMessage = model.formerMessage;
  102. if(self.messageType!=model.messageType){
  103. self.cellHeight=0;
  104. }
  105. self.messageType = model.messageType;
  106. self.type = model.type;
  107. self.isSender = model.isSender;
  108. self.content = model.content;
  109. self.msgId = model.msgId;
  110. self.mediaSize = model.mediaSize;
  111. self.placeholderImage = model.placeholderImage;
  112. self.fileName = model.fileName;
  113. self.fileSize = model.fileSize;
  114. self.url = model.url;
  115. self.localurl = model.localurl;
  116. //文件传输成功或失败
  117. self.fileError = model.fileError;
  118. // 通话记录
  119. self.callDuration = model.callDuration;
  120. self.isCallSuccess = model.isCallSuccess;
  121. self.isVideo = model.isVideo;
  122. self.avatar = model.avatar;
  123. self.nickName = model.nickName;
  124. //@相关
  125. self.atAll = model.atAll;
  126. self.atUserIds = model.atUserIds;
  127. // 时间戳(如果需要)
  128. self.timestamp = model.timestamp;
  129. self.localtime = model.localtime;
  130. self.formatterTime = model.formatterTime;
  131. // // 其他自定义字段...
  132. // 其他自定义字段...
  133. self.readStatus = [self getReadStatus];
  134. }
  135. -(NSString *)timeF:(NSInteger)time{
  136. //NSLog(@"time:%ld",(long)time);
  137. // 创建日期格式器
  138. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  139. [formatter setDateFormat:@"dd"]; // 设置你想要的日期格式
  140. long long timestamp =(long)time/1000; // 例如:2021-10-01 00:00:00 UTC
  141. // 转换为NSDate
  142. NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
  143. NSString *dateString = [formatter stringFromDate:date];
  144. NSDate *now = [NSDate date];
  145. NSTimeInterval trt = [now timeIntervalSince1970];
  146. date = [NSDate dateWithTimeIntervalSince1970:trt];
  147. NSString *tdateString = [formatter stringFromDate:date];
  148. NSInteger shijiancha = trt-timestamp;
  149. if(shijiancha<60){
  150. return NSLocalizedString(@"time-oneminint", @"");
  151. }
  152. if(shijiancha>24*3600||dateString.intValue!=tdateString.intValue){
  153. // 假设这是你的时间戳(以秒为单位)
  154. long long timestamp =(long)time/1000; // 例如:2021-10-01 00:00:00 UTC
  155. // 转换为NSDate
  156. NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
  157. // 创建日期格式器
  158. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  159. [formatter setDateFormat:@"yyyy-MM-dd HH:mm"]; // 设置你想要的日期格式
  160. // 转换为字符串
  161. NSString *dateString = [formatter stringFromDate:date];
  162. return dateString;
  163. }
  164. else{
  165. NSInteger xiaoshi = shijiancha/3600;
  166. NSInteger fenzhong = shijiancha/60;
  167. if(xiaoshi>0){
  168. // 假设这是你的时间戳(以秒为单位)
  169. long long timestamp =(long)time/1000; // 例如:2021-10-01 00:00:00 UTC
  170. // 转换为NSDate
  171. NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
  172. // 创建日期格式器
  173. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  174. [formatter setDateFormat:@"HH:mm"]; // 设置你想要的日期格式
  175. // 转换为字符串
  176. NSString *dateString = [formatter stringFromDate:date];
  177. return dateString;
  178. }
  179. else{
  180. return [NSString stringWithFormat:@"%ld%@",(long)fenzhong,NSLocalizedString(@"time-outmin", @"")];
  181. }
  182. }
  183. return @"";
  184. }
  185. - (NSString *)getReadStatus{
  186. if(self.isSent){
  187. //判断已读未读
  188. if(self.timestamp>ChatsStore.shareInstance.lastreadTime){
  189. return @"未读";
  190. }
  191. else{
  192. return @"已读";
  193. }
  194. }
  195. return @"";
  196. }
  197. - (void)generateThumbnailWithCompletion:(void(^)(UIImage *thumbnail))completion {
  198. // 如果内存中已有缩略图,直接返回
  199. if (self.videoThumbnailImage) {
  200. if (completion) completion(self.videoThumbnailImage);
  201. return;
  202. }
  203. // 生成缓存 key,优先使用 msgId,如果没有则使用 URL 的 hash
  204. NSString *cacheKey = nil;
  205. if (self.msgId.length > 0) {
  206. cacheKey = [NSString stringWithFormat:@"video_thumbnail_%@", self.msgId];
  207. } else if (self.url.length > 0) {
  208. cacheKey = [NSString stringWithFormat:@"video_thumbnail_%lu", (unsigned long)[self.url hash]];
  209. }
  210. // 从 SDWebImage 缓存中查找
  211. if (cacheKey) {
  212. SDImageCache *imageCache = [SDImageCache sharedImageCache];
  213. UIImage *cachedImage = [imageCache imageFromCacheForKey:cacheKey];
  214. if (cachedImage) {
  215. NSLog(@"从缓存加载缩略图: %@", cacheKey);
  216. self.videoThumbnailImage = cachedImage;
  217. if (completion) completion(cachedImage);
  218. return;
  219. }
  220. }
  221. // 没有缓存,需要生成缩略图
  222. NSURL *videoURL = nil;
  223. if (self.localurl.length != 0 && [[NSFileManager defaultManager] fileExistsAtPath:self.localurl]) {
  224. // 从本地文件生成缩略图
  225. NSLog(@"generateThumbnailWithCompletion localurl:%@",self.localurl);
  226. videoURL = [NSURL fileURLWithPath:self.localurl];
  227. NSString *finalCacheKey = cacheKey;
  228. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  229. AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
  230. AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
  231. generator.appliesPreferredTrackTransform = YES;
  232. CMTime acttime;
  233. NSError *error = nil;
  234. CGImageRef imageRef = [generator copyCGImageAtTime:CMTimeMake(0, 600) actualTime:&acttime error:&error];
  235. NSLog(@"error:%@",error);
  236. if (!error && imageRef) {
  237. UIImage *thumbnail = [[UIImage alloc] initWithCGImage:imageRef];
  238. CGImageRelease(imageRef);
  239. // 缓存到内存
  240. self.videoThumbnailImage = thumbnail;
  241. // 使用 SDWebImage 缓存到磁盘和内存
  242. if (finalCacheKey) {
  243. SDImageCache *imageCache = [SDImageCache sharedImageCache];
  244. [imageCache storeImage:thumbnail forKey:finalCacheKey completion:^{
  245. NSLog(@"缩略图已缓存: %@", finalCacheKey);
  246. }];
  247. }
  248. if (completion){
  249. completion(thumbnail);
  250. }
  251. } else {
  252. if (completion) completion(nil);
  253. }
  254. });
  255. } else {
  256. // 从远程 URL 生成缩略图
  257. NSLog(@"generateThumbnailWithCompletion url");
  258. if (self.url.length == 0){
  259. if (completion) completion(nil);
  260. return;
  261. }
  262. NSDictionary *options = @{AVURLAssetAllowsCellularAccessKey: @YES,
  263. AVURLAssetPreferPreciseDurationAndTimingKey: @YES};
  264. AVURLAsset *asset = [AVURLAsset URLAssetWithURL:getURL(self.url) options:options];
  265. // 创建图像生成器
  266. AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
  267. generator.appliesPreferredTrackTransform = YES; // 应用视频的方向
  268. generator.maximumSize = CGSizeMake(320, 0); // 设置最大尺寸,保持宽高比
  269. NSString *finalCacheKey = cacheKey;
  270. // 异步生成缩略图
  271. [generator generateCGImagesAsynchronouslyForTimes:@[[NSValue valueWithCMTime:kCMTimeZero]]
  272. completionHandler:^(CMTime requestedTime, CGImageRef image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) {
  273. __block UIImage *thumbnail = nil;
  274. // 处理生成结果
  275. if (result == AVAssetImageGeneratorSucceeded && image) {
  276. // 创建UIImage
  277. thumbnail = [UIImage imageWithCGImage:image];
  278. self.videoThumbnailImage = thumbnail;
  279. // 使用 SDWebImage 缓存到磁盘和内存
  280. if (finalCacheKey) {
  281. SDImageCache *imageCache = [SDImageCache sharedImageCache];
  282. [imageCache storeImage:thumbnail forKey:finalCacheKey completion:^{
  283. NSLog(@"缩略图已缓存: %@", finalCacheKey);
  284. }];
  285. }
  286. }
  287. dispatch_async(dispatch_get_main_queue(), ^{
  288. if (completion) completion(thumbnail);
  289. });
  290. }];
  291. }
  292. }
  293. //下载视频文件
  294. -(void)downloadFileIfNeed:(void(^)(NSInteger persent))loading{
  295. if ([[NSFileManager defaultManager] fileExistsAtPath:self.localurl]){
  296. self.customFileSize = [self getFileSize];
  297. if (loading) {
  298. loading(100);
  299. }
  300. NSLog(@"downloadFileIfNeed 0: %@", self.localurl);
  301. return;
  302. }
  303. NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
  304. NSURL *tempUrl = [NSURL URLWithString:self.url];
  305. NSString *fileName = tempUrl.lastPathComponent;
  306. NSString *fileExtension = [fileName pathExtension];
  307. NSString *newfileName = [NSString stringWithFormat:@"%@.%@", self.msgId,fileExtension];
  308. documentsDirectoryURL = [documentsDirectoryURL URLByAppendingPathComponent:newfileName];
  309. if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectoryURL.path]){
  310. NSLog(@"downloadFileIfNeed 1: %@", documentsDirectoryURL.path);
  311. NSMutableDictionary *mutableDict = [self.formerMessage mutableCopy];
  312. NSMutableDictionary *extend = [self.formerMessage[@"extend"] mutableCopy];
  313. [extend setObject:documentsDirectoryURL.path forKey:@"localurl"];
  314. [mutableDict setObject:extend forKey:@"extend"];
  315. self.localurl = documentsDirectoryURL.path;
  316. NSDictionary *NewMsg = [mutableDict copy];
  317. [ChatsStore.shareInstance reciveMsg:NewMsg];
  318. self.customFileSize = [self getFileSize];
  319. if (loading) {
  320. loading(100);
  321. }
  322. return;
  323. }
  324. if (![self.url hasPrefix:@"http"]) {
  325. NSLog(@"文件URL异常:%@", self.formerMessage);
  326. return;
  327. }
  328. [FileNetApi downLoadWToken:getURL(self.url) thrid:self.msgId succ:^(int code, NSDictionary * res) {
  329. if(res!=nil){
  330. NSMutableDictionary *mutableDict = [self.formerMessage mutableCopy];
  331. NSMutableDictionary *extend = [self.formerMessage[@"extend"] mutableCopy];
  332. [extend setObject:res[@"filePath"] forKey:@"localurl"];
  333. [mutableDict setObject:extend forKey:@"extend"];
  334. self.localurl = res[@"filePath"];
  335. NSDictionary *NewMsg = [mutableDict copy];
  336. [ChatsStore.shareInstance reciveMsg:NewMsg];
  337. self.customFileSize = [self getFileSize];
  338. if (loading) {
  339. loading(100);
  340. }
  341. }
  342. else{
  343. if (code>=0&&code<200) {
  344. if (loading) {
  345. loading(code);
  346. }
  347. }
  348. }
  349. } fail:^(NSError * _Nonnull error) {
  350. NSLog(@"downLoadWToken error:%@",error);
  351. }];
  352. }
  353. // 根据语音时长计算气泡宽度
  354. - (CGFloat)voiceBubbleWidth {
  355. // 基础宽度
  356. CGFloat minWidth = 60.0f;
  357. CGFloat maxWidth = 200.0f;
  358. // 最大限制时长(如60秒)
  359. NSInteger maxDuration = 60;
  360. NSInteger duration = MIN(self.voiceDuration, maxDuration);
  361. // 线性增长计算
  362. CGFloat width = minWidth + (maxWidth - minWidth) * (duration / (CGFloat)maxDuration);
  363. return width;
  364. }
  365. #pragma mark - 消息状态管理
  366. - (NSString *)getFileSize {
  367. NSString *filePath = self.localurl;
  368. NSFileManager *fileManager = [NSFileManager defaultManager];
  369. // 获取文件属性
  370. NSError *error = nil;
  371. NSDictionary *attributes = [fileManager attributesOfItemAtPath:filePath error:&error];
  372. NSString *string = @"0KB";
  373. if (error) {
  374. NSLog(@"获取文件属性失败: %@", error);
  375. } else {
  376. // 获取文件大小(单位:字节)
  377. unsigned long long fileSize = [attributes fileSize];
  378. NSLog(@"文件大小: %llu 字节", fileSize);
  379. // 可选:转换为 KB、MB
  380. double fileSizeKB = fileSize / 1024.0;
  381. double fileSizeMB = fileSizeKB / 1024.0;
  382. NSLog(@"文件大小: %.2f KB (%.2f MB)", fileSizeKB, fileSizeMB);
  383. string = [NSString stringWithFormat:@"%.2fMB", fileSizeMB];
  384. }
  385. return string;
  386. }
  387. - (NSString *)customFileSize {
  388. if (!_customFileSize) {
  389. _customFileSize = [self getFileSize];
  390. }
  391. return _customFileSize;
  392. }
  393. - (NSString *)checkHasLocalPath {
  394. if ([[NSFileManager defaultManager] fileExistsAtPath:self.localurl]){
  395. self.customFileSize = [self getFileSize];
  396. NSLog(@"checkHasLocalPath 0: %@", self.localurl);
  397. return self.localurl;
  398. }
  399. NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
  400. NSURL *tempUrl = [NSURL URLWithString:self.url];
  401. NSString *fileName = tempUrl.lastPathComponent;
  402. NSString *fileExtension = [fileName pathExtension];
  403. NSString *newfileName = [NSString stringWithFormat:@"%@.%@", self.msgId,fileExtension];
  404. NSString *path = [documentsDirectoryURL URLByAppendingPathComponent:newfileName].path;
  405. if ([[NSFileManager defaultManager] fileExistsAtPath:path]){
  406. NSLog(@"checkHasLocalPath 0: %@", path);
  407. return path;
  408. }
  409. return nil;
  410. }
  411. - (BOOL)isUploadFile {
  412. return self.messageType == ChatMessageTypeFile ||
  413. self.messageType == ChatMessageTypeVoice ||
  414. self.messageType == ChatMessageTypeImage ||
  415. self.messageType == ChatMessageTypeVideo;
  416. }
  417. - (BOOL)isSent {
  418. return ![self.msgId isEqualToString:[NSString stringWithFormat:@"%ld", self.localtime]];
  419. }
  420. - (BOOL)checkIsSendFail {
  421. // NSDate *now = [NSDate date];
  422. // NSTimeInterval trt = [now timeIntervalSince1970];
  423. // NSInteger time = trt*1000;
  424. // NSInteger outTime =time-self.localtime;
  425. // if(outTime>33000){
  426. // return YES;
  427. // }
  428. return NO;
  429. }
  430. @end