ChatMessageModel.m 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  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 = 0;
  78. NSInteger fileError = [extend[@"fileError"] integerValue];
  79. if (fileError!=0) {
  80. self.fileError = fileError;
  81. }
  82. else{
  83. if(self.url.length>0){
  84. self.fileError = 0;
  85. }
  86. }
  87. //合并转发
  88. self.forwardMsgArray = extend[@"messageList"] ?:@[];
  89. // 通话记录
  90. self.callDuration = [mutableDict[@"duration"] integerValue];
  91. self.isCallSuccess = [mutableDict[@"result"] boolValue];
  92. self.isVideo = [mutableDict[@"video"] boolValue];
  93. //@相关
  94. self.atAll = extend[@"atAll"]?[extend[@"atAll"] boolValue]:NO;
  95. self.atUserIds = extend[@"atUserIds"]?:@[];
  96. // 时间戳(如果需要)
  97. self.timestamp = [mutableDict[@"timestamp"] longLongValue];
  98. self.localtime = [mutableDict[@"localtime"] longLongValue];
  99. self.formatterTime = [self timeF:self.timestamp];
  100. // 其他自定义字段...
  101. self.readStatus = [self getReadStatus];
  102. BOOL contain = [[NSFileManager defaultManager] fileExistsAtPath:self.localurl];
  103. NSString *localPath = [self checkHasLocalPath];
  104. if (!contain && localPath.length) {
  105. self.localurl = localPath;
  106. }
  107. }
  108. - (void)exchangeModelWithModel:(ChatMessageModel *)model{
  109. self.msgId = model.msgId;
  110. self.formerMessage = model.formerMessage;
  111. if(self.messageType!=model.messageType){
  112. self.cellHeight=0;
  113. }
  114. self.messageType = model.messageType;
  115. self.type = model.type;
  116. self.isSender = model.isSender;
  117. self.content = model.content;
  118. self.msgId = model.msgId;
  119. self.mediaSize = model.mediaSize;
  120. self.placeholderImage = model.placeholderImage;
  121. self.fileName = model.fileName;
  122. self.fileSize = model.fileSize;
  123. self.url = model.url;
  124. self.localurl = model.localurl;
  125. //文件传输成功或失败
  126. self.fileError = model.fileError;
  127. // 通话记录
  128. self.callDuration = model.callDuration;
  129. self.isCallSuccess = model.isCallSuccess;
  130. self.isVideo = model.isVideo;
  131. self.avatar = model.avatar;
  132. self.nickName = model.nickName;
  133. //@相关
  134. self.atAll = model.atAll;
  135. self.atUserIds = model.atUserIds;
  136. // 时间戳(如果需要)
  137. self.timestamp = model.timestamp;
  138. self.localtime = model.localtime;
  139. self.formatterTime = model.formatterTime;
  140. // // 其他自定义字段...
  141. // 其他自定义字段...
  142. self.readStatus = [self getReadStatus];
  143. }
  144. -(NSString *)timeF:(NSInteger)time{
  145. //NSLog(@"time:%ld",(long)time);
  146. // 创建日期格式器
  147. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  148. [formatter setDateFormat:@"dd"]; // 设置你想要的日期格式
  149. long long timestamp =(long)time/1000; // 例如:2021-10-01 00:00:00 UTC
  150. // 转换为NSDate
  151. NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
  152. NSString *dateString = [formatter stringFromDate:date];
  153. NSDate *now = [NSDate date];
  154. NSTimeInterval trt = [now timeIntervalSince1970];
  155. date = [NSDate dateWithTimeIntervalSince1970:trt];
  156. NSString *tdateString = [formatter stringFromDate:date];
  157. NSInteger shijiancha = trt-timestamp;
  158. if(shijiancha<60){
  159. return NSLocalizedString(@"time-oneminint", @"");
  160. }
  161. if(shijiancha>24*3600||dateString.intValue!=tdateString.intValue){
  162. // 假设这是你的时间戳(以秒为单位)
  163. long long timestamp =(long)time/1000; // 例如:2021-10-01 00:00:00 UTC
  164. // 转换为NSDate
  165. NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
  166. // 创建日期格式器
  167. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  168. [formatter setDateFormat:@"yyyy-MM-dd HH:mm"]; // 设置你想要的日期格式
  169. // 转换为字符串
  170. NSString *dateString = [formatter stringFromDate:date];
  171. return dateString;
  172. }
  173. else{
  174. NSInteger xiaoshi = shijiancha/3600;
  175. NSInteger fenzhong = shijiancha/60;
  176. if(xiaoshi>0){
  177. // 假设这是你的时间戳(以秒为单位)
  178. long long timestamp =(long)time/1000; // 例如:2021-10-01 00:00:00 UTC
  179. // 转换为NSDate
  180. NSDate *date = [NSDate dateWithTimeIntervalSince1970:timestamp];
  181. // 创建日期格式器
  182. NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
  183. [formatter setDateFormat:@"HH:mm"]; // 设置你想要的日期格式
  184. // 转换为字符串
  185. NSString *dateString = [formatter stringFromDate:date];
  186. return dateString;
  187. }
  188. else{
  189. return [NSString stringWithFormat:@"%ld%@",(long)fenzhong,NSLocalizedString(@"time-outmin", @"")];
  190. }
  191. }
  192. return @"";
  193. }
  194. - (NSString *)getReadStatus{
  195. NSString * readStatus;
  196. self.readstate = 0;
  197. if(self.timestamp == 0){
  198. return @"";
  199. }
  200. if(self.messageType==11||self.messageType==12){
  201. return @"";
  202. }
  203. if(self.type==0){
  204. if (self.localtime != 0 && self.localtime == self.timestamp) {
  205. NSDate *now = [NSDate date];
  206. NSTimeInterval trt = [now timeIntervalSince1970];
  207. NSInteger time = trt*1000;
  208. NSInteger outTime =time-self.localtime;
  209. if(outTime>33000){
  210. if(self.messageType==1||self.messageType==2||self.messageType==5){
  211. readStatus = @"正在发送";
  212. self.readstate = 3;
  213. }else{
  214. readStatus = @"发送失败";
  215. self.readstate = 4;
  216. }
  217. }else{
  218. readStatus = @"正在发送";
  219. self.readstate = 3;
  220. }
  221. }
  222. else{
  223. //判断已读未读
  224. if(self.timestamp>ChatsStore.shareInstance.lastreadTime){
  225. readStatus = @"未读";
  226. self.readstate = 1;
  227. }
  228. else{
  229. readStatus = @"已读";
  230. self.readstate = 2;
  231. }
  232. if(self.fileError==1){
  233. readStatus = @"發送失敗,點擊重發";
  234. self.readstate = 4;
  235. }
  236. }
  237. }else{
  238. return @"";
  239. }
  240. return readStatus;
  241. }
  242. - (void)generateThumbnailWithCompletion:(void(^)(UIImage *thumbnail))completion {
  243. // 如果内存中已有缩略图,直接返回
  244. if (self.videoThumbnailImage) {
  245. if (completion) completion(self.videoThumbnailImage);
  246. return;
  247. }
  248. // 生成缓存 key,优先使用 msgId,如果没有则使用 URL 的 hash
  249. NSString *cacheKey = nil;
  250. if (self.msgId.length > 0) {
  251. cacheKey = [NSString stringWithFormat:@"video_thumbnail_%@", self.msgId];
  252. } else if (self.url.length > 0) {
  253. cacheKey = [NSString stringWithFormat:@"video_thumbnail_%lu", (unsigned long)[self.url hash]];
  254. }
  255. // 从 SDWebImage 缓存中查找
  256. if (cacheKey) {
  257. SDImageCache *imageCache = [SDImageCache sharedImageCache];
  258. UIImage *cachedImage = [imageCache imageFromCacheForKey:cacheKey];
  259. if (cachedImage) {
  260. NSLog(@"从缓存加载缩略图: %@", cacheKey);
  261. self.videoThumbnailImage = cachedImage;
  262. if (completion) completion(cachedImage);
  263. return;
  264. }
  265. }
  266. // 没有缓存,需要生成缩略图
  267. NSURL *videoURL = nil;
  268. if (self.localurl.length != 0 && [[NSFileManager defaultManager] fileExistsAtPath:self.localurl]) {
  269. // 从本地文件生成缩略图
  270. NSLog(@"generateThumbnailWithCompletion localurl:%@",self.localurl);
  271. videoURL = [NSURL fileURLWithPath:self.localurl];
  272. NSString *finalCacheKey = cacheKey;
  273. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  274. AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
  275. AVAssetImageGenerator *generator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
  276. generator.appliesPreferredTrackTransform = YES;
  277. CMTime acttime;
  278. NSError *error = nil;
  279. CGImageRef imageRef = [generator copyCGImageAtTime:CMTimeMake(0, 600) actualTime:&acttime error:&error];
  280. NSLog(@"error:%@",error);
  281. if (!error && imageRef) {
  282. UIImage *thumbnail = [[UIImage alloc] initWithCGImage:imageRef];
  283. CGImageRelease(imageRef);
  284. // 缓存到内存
  285. self.videoThumbnailImage = thumbnail;
  286. // 使用 SDWebImage 缓存到磁盘和内存
  287. if (finalCacheKey) {
  288. SDImageCache *imageCache = [SDImageCache sharedImageCache];
  289. [imageCache storeImage:thumbnail forKey:finalCacheKey completion:^{
  290. NSLog(@"缩略图已缓存: %@", finalCacheKey);
  291. }];
  292. }
  293. if (completion){
  294. completion(thumbnail);
  295. }
  296. } else {
  297. if (completion) completion(nil);
  298. }
  299. });
  300. } else {
  301. // 从远程 URL 生成缩略图
  302. NSLog(@"generateThumbnailWithCompletion url");
  303. if (self.url.length == 0){
  304. if (completion) completion(nil);
  305. return;
  306. }
  307. NSDictionary *options = @{AVURLAssetAllowsCellularAccessKey: @YES,
  308. AVURLAssetPreferPreciseDurationAndTimingKey: @YES};
  309. AVURLAsset *asset = [AVURLAsset URLAssetWithURL:getURL(self.url) options:options];
  310. // 创建图像生成器
  311. AVAssetImageGenerator *generator = [AVAssetImageGenerator assetImageGeneratorWithAsset:asset];
  312. generator.appliesPreferredTrackTransform = YES; // 应用视频的方向
  313. generator.maximumSize = CGSizeMake(320, 0); // 设置最大尺寸,保持宽高比
  314. NSString *finalCacheKey = cacheKey;
  315. // 异步生成缩略图
  316. [generator generateCGImagesAsynchronouslyForTimes:@[[NSValue valueWithCMTime:kCMTimeZero]]
  317. completionHandler:^(CMTime requestedTime, CGImageRef image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError *error) {
  318. __block UIImage *thumbnail = nil;
  319. // 处理生成结果
  320. if (result == AVAssetImageGeneratorSucceeded && image) {
  321. // 创建UIImage
  322. thumbnail = [UIImage imageWithCGImage:image];
  323. self.videoThumbnailImage = thumbnail;
  324. // 使用 SDWebImage 缓存到磁盘和内存
  325. if (finalCacheKey) {
  326. SDImageCache *imageCache = [SDImageCache sharedImageCache];
  327. [imageCache storeImage:thumbnail forKey:finalCacheKey completion:^{
  328. NSLog(@"缩略图已缓存: %@", finalCacheKey);
  329. }];
  330. }
  331. }
  332. dispatch_async(dispatch_get_main_queue(), ^{
  333. if (completion) completion(thumbnail);
  334. });
  335. }];
  336. }
  337. }
  338. //下载视频文件
  339. -(void)downloadFileIfNeed:(void(^)(NSInteger persent))loading{
  340. NSString *localFileurl = [self.localurl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
  341. if (self.localurl.length != 0 && [[NSFileManager defaultManager] fileExistsAtPath:localFileurl]){
  342. self.customFileSize = [self getFileSize];
  343. if (loading) {
  344. loading(100);
  345. }
  346. NSLog(@"downloadFileIfNeed 0: %@", localFileurl);
  347. return;
  348. }
  349. NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
  350. NSURL *tempUrl = [NSURL URLWithString:self.url];
  351. NSString *fileName = tempUrl.lastPathComponent;
  352. NSString *fileExtension = [fileName pathExtension];
  353. NSString *newfileName = [NSString stringWithFormat:@"%@.%@", self.msgId,fileExtension];
  354. documentsDirectoryURL = [documentsDirectoryURL URLByAppendingPathComponent:newfileName];
  355. if ([[NSFileManager defaultManager] fileExistsAtPath:documentsDirectoryURL.path]){
  356. NSLog(@"downloadFileIfNeed 1: %@", documentsDirectoryURL.path);
  357. NSMutableDictionary *mutableDict = [self.formerMessage mutableCopy];
  358. NSMutableDictionary *extend = [self.formerMessage[@"extend"] mutableCopy];
  359. [extend setObject:documentsDirectoryURL.path forKey:@"localurl"];
  360. [mutableDict setObject:extend forKey:@"extend"];
  361. self.localurl = documentsDirectoryURL.path;
  362. NSDictionary *NewMsg = [mutableDict copy];
  363. [ChatsStore.shareInstance reciveMsg:NewMsg];
  364. self.customFileSize = [self getFileSize];
  365. if (loading) {
  366. loading(100);
  367. }
  368. return;
  369. }
  370. [FileNetApi downLoadWToken:getURL(self.url) thrid:self.msgId succ:^(int code, NSDictionary * res) {
  371. if(res!=nil){
  372. NSMutableDictionary *mutableDict = [self.formerMessage mutableCopy];
  373. NSMutableDictionary *extend = [self.formerMessage[@"extend"] mutableCopy];
  374. [extend setObject:res[@"filePath"] forKey:@"localurl"];
  375. [mutableDict setObject:extend forKey:@"extend"];
  376. self.localurl = res[@"filePath"];
  377. NSDictionary *NewMsg = [mutableDict copy];
  378. [ChatsStore.shareInstance reciveMsg:NewMsg];
  379. self.customFileSize = [self getFileSize];
  380. if (loading) {
  381. loading(100);
  382. }
  383. }
  384. else{
  385. if (code>=0&&code<200) {
  386. if (loading) {
  387. loading(code);
  388. }
  389. }
  390. }
  391. } fail:^(NSError * _Nonnull error) {
  392. NSLog(@"downLoadWToken error:%@",error);
  393. }];
  394. }
  395. -(void)setuploadPersent:(NSInteger)persent localtime:(NSInteger)localtime{
  396. if(self.uploadPersentChange && localtime==self.localtime){
  397. self.uploadPersentChange(persent,localtime);
  398. }
  399. }
  400. // 根据语音时长计算气泡宽度
  401. - (CGFloat)voiceBubbleWidth {
  402. // 基础宽度
  403. CGFloat minWidth = 60.0f;
  404. CGFloat maxWidth = 200.0f;
  405. // 最大限制时长(如60秒)
  406. NSInteger maxDuration = 60;
  407. NSInteger duration = MIN(self.voiceDuration, maxDuration);
  408. // 线性增长计算
  409. CGFloat width = minWidth + (maxWidth - minWidth) * (duration / (CGFloat)maxDuration);
  410. return width;
  411. }
  412. - (NSString *)getFileSize {
  413. NSString *filePath = self.localurl;
  414. NSFileManager *fileManager = [NSFileManager defaultManager];
  415. // 获取文件属性
  416. NSError *error = nil;
  417. NSDictionary *attributes = [fileManager attributesOfItemAtPath:filePath error:&error];
  418. NSString *string = @"0KB";
  419. if (error) {
  420. NSLog(@"获取文件属性失败: %@", error);
  421. } else {
  422. // 获取文件大小(单位:字节)
  423. unsigned long long fileSize = [attributes fileSize];
  424. NSLog(@"文件大小: %llu 字节", fileSize);
  425. // 可选:转换为 KB、MB
  426. double fileSizeKB = fileSize / 1024.0;
  427. double fileSizeMB = fileSizeKB / 1024.0;
  428. NSLog(@"文件大小: %.2f KB (%.2f MB)", fileSizeKB, fileSizeMB);
  429. string = [NSString stringWithFormat:@"%.2fMB", fileSizeMB];
  430. }
  431. return string;
  432. }
  433. - (NSString *)customFileSize {
  434. if (!_customFileSize) {
  435. _customFileSize = [self getFileSize];
  436. }
  437. return _customFileSize;
  438. }
  439. - (NSString *)checkHasLocalPath {
  440. NSString *localFileurl = [self.localurl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLPathAllowedCharacterSet]];
  441. if (self.localurl.length != 0 && [[NSFileManager defaultManager] fileExistsAtPath:localFileurl]){
  442. self.customFileSize = [self getFileSize];
  443. NSLog(@"checkHasLocalPath 0: %@", localFileurl);
  444. return localFileurl;
  445. }
  446. NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
  447. NSURL *tempUrl = [NSURL URLWithString:self.url];
  448. NSString *fileName = tempUrl.lastPathComponent;
  449. NSString *fileExtension = [fileName pathExtension];
  450. NSString *newfileName = [NSString stringWithFormat:@"%@.%@", self.msgId,fileExtension];
  451. NSString *path = [documentsDirectoryURL URLByAppendingPathComponent:newfileName].path;
  452. if ([[NSFileManager defaultManager] fileExistsAtPath:path]){
  453. NSLog(@"checkHasLocalPath 0: %@", path);
  454. return path;
  455. }
  456. return nil;
  457. }
  458. @end