CNLiveBusinessTools.m 42.9 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072
//
//  CNLiveBusinessTools.m
//  CNLiveBusinessTools
//
//  Created by 张旭 on 2020/4/14.
//

#import "CNLiveBusinessTools.h"
#import <Photos/Photos.h>
#import <CNLiveEnvironment/CNLiveEnvironment.h>
#import <CNLiveUserManagement/CNUserInfoManager.h>
#import "CommonCrypto/CommonDigest.h"
#import <CNLiveBaseKit/CNLiveBaseKit.h>
#import "CNEmojiTextAttachment.h"
#import <QMUIKit/QMUIEmotionView.h>
#import "CNLiveQQEmotionManager.h"
#import <YYKit/YYKit.h>
@implementation CNLiveBusinessTools

+ (NSString *)cnStatWithType:(CNStatType)statType type:(NSString *)type userId:(NSString *)userId programId:(NSString *)programId title:(NSString *)title {
    
    NSString *statStr = @"";
    switch (statType) {
        case CNStatTypeContentCount:
            statStr = @"count";
            break;
        case CNStatTypeContentDuration:
            statStr = @"duration";
            break;
        case CNStatTypeShareCount:
            statStr = @"share";
            break;
        default:
            break;
    }
    NSString *channelTypeStr = type?type:@"";
    NSString *uIdStr = userId?userId:@"";
    NSString *proIdStr = programId?programId:@"";
    NSString *titleStr = title?title:@"";
    
    NSString *eventStr = [NSString stringWithFormat:@"type__%@-channel__%@-sid__%@-uid__%@-pid__%@-title__%@-data_",statStr,channelTypeStr,uIdStr,[self getUidForStat:[NSDate date]],proIdStr,titleStr];
    NSLog(@"event:%@",eventStr);
    return eventStr;
}

+ (NSString *)getUidForStat:(NSDate *)date {
    
    NSString *uid = @"";
    NSString *uidKey = @"kCNLiveUserDefaultsUIDKey";
    NSUserDefaults *defauts = [NSUserDefaults standardUserDefaults];
    if ([defauts objectForKey:uidKey]) {
        uid = [[defauts objectForKey:uidKey] copy];
        return uid;
    }
    else {
        
        NSInteger time = [[NSDate date] timeIntervalSince1970];
        NSString *timeString = [NSString stringWithFormat:@"%ld", (long)time];
        NSString *stamp = timeString;
        stamp = [stamp stringByReplacingOccurrencesOfString:@"." withString:@""];
        NSString *idfv = [[[[UIDevice currentDevice] identifierForVendor] UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
        uid = [NSString stringWithFormat:@"%@_%@", idfv, stamp];
        [defauts setObject:uid forKey:uidKey];
        [defauts synchronize];
        return uid;
    }
}

+ (NSString *)uuid{
    NSString *uid = @"";
    NSString *uidKey = @"kCNLiveUserDefaultsUIDKey";
    NSUserDefaults *defauts = [NSUserDefaults standardUserDefaults];
    if ([defauts objectForKey:uidKey]) {
        uid = [[defauts objectForKey:uidKey] copy];
        return uid;
    } else {
        NSInteger time = [[NSDate date] timeIntervalSince1970];
        NSString *timeString = [NSString stringWithFormat:@"%ld", (long)time];
        NSString *stamp = timeString;
        stamp = [stamp stringByReplacingOccurrencesOfString:@"." withString:@""];
        NSString *idfv = [[[[UIDevice currentDevice] identifierForVendor] UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
        uid = [NSString stringWithFormat:@"%@_%@", idfv, stamp];
        [defauts setObject:uid forKey:uidKey];
        [defauts synchronize];
        return uid;
    }
}


+ (NSString *)tingyunUUID{
    NSString *uid = @"";
    NSUserDefaults *defauts = [NSUserDefaults standardUserDefaults];
    if ([defauts objectForKey:@"kCNLiveUserDefaultsTingYunUIDKey"]) {
        uid = [[defauts objectForKey:@"kCNLiveUserDefaultsTingYunUIDKey"] copy];
        return uid;
    } else {
        NSString *idfv = [[[[UIDevice currentDevice] identifierForVendor] UUIDString] stringByReplacingOccurrencesOfString:@"-" withString:@""];
        [defauts setObject:idfv forKey:@"kCNLiveUserDefaultsTingYunUIDKey"];
        [defauts synchronize];
    }
    return uid;
}

+ (NSString *)cnStatWithType:(CNStatType)statType type:(NSString *)type userId:(NSString *)userId programId:(NSString *)programId title:(NSString *)title shareToType:(NSString *)shareToType
{
    NSString *statStr = @"";
    switch (statType) {
        case CNStatTypeContentCount:
            statStr = @"count";
            break;
        case CNStatTypeContentDuration:
            statStr = @"duration";
            break;
        case CNStatTypeShareCount:
            statStr = @"share";
            break;
        default:
            break;
    }
    NSString *channelTypeStr = type?type:@"";
    NSString *uIdStr = userId?userId:@"";
    NSString *proIdStr = programId?programId:@"";
    NSString *titleStr = title?title:@"";
    NSString *shareToTypeStr = shareToType?shareToType:@"";
    
    NSString *eventStr = [NSString stringWithFormat:@"type__%@-channel__%@-sid__%@-uid__%@-pid__%@-title__%@-to__%@-data_",statStr,channelTypeStr,uIdStr,[self getUidForStat:[NSDate date]],proIdStr,titleStr,shareToTypeStr];
    NSLog(@"event:%@",eventStr);
    return eventStr;
}
+ (BOOL)isGif:(id)asset {
    
    if ([asset isKindOfClass:[PHAsset class]]) {
        PHAsset *phAsset = (PHAsset *)asset;
        if (phAsset.mediaType == PHAssetMediaTypeImage) {
            // Gif
            if ([[phAsset valueForKey:@"filename"] hasSuffix:@"GIF"]) {
                return YES;
            }
        }
    }
    return NO;
}
+ (BOOL)isGifWithImageData: (NSData *)data {
    if ([[self contentTypeWithImageData:data] isEqualToString:@"gif"]) {
        return YES;
    }
    return NO;
}
+ (NSString *)contentTypeWithImageData: (NSData *)data {
    
    uint8_t c;
    
    [data getBytes:&c length:1];
    
    switch (c) {
            
        case 0xFF:
            
            return @"jpeg";
            
        case 0x89:
            
            return @"png";
            
        case 0x47:
            
            return @"gif";
            
        case 0x49:
            
        case 0x4D:
            
            return @"tiff";
            
        case 0x52:
            
            if ([data length] < 12) {
                
                return nil;
                
            }
            
            NSString *testString = [[NSString alloc] initWithData:[data subdataWithRange:NSMakeRange(0, 12)] encoding:NSASCIIStringEncoding];
            
            if ([testString hasPrefix:@"RIFF"] && [testString hasSuffix:@"WEBP"]) {
                
                return @"webp";
                
            }
            
            return nil;
            
    }
    
    return nil;
}

+ (NSDictionary *)fileTypeDic
{
    NSDictionary *dic =
    @{
      @".3gp" : @"video/3gpp",
      @".apk" : @"application/vnd.android.package-archive",
      @".asf" : @"video/x-ms-asf",
      @".avi" : @"video/x-msvideo",
      @".bin" : @"application/octet-stream",
      @".bmp" : @"image/bmp",
      @".c" : @"text/plain",
      @".class" : @"application/octet-stream",
      @".conf" : @"text/plain",
      @".cpp" : @"text/plain",
      @".doc" : @"application/msword",
      @".docx" : @"application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      @".xls" : @"application/vnd.ms-excel",
      @".xlsx" : @"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
      @".exe" : @"application/octet-stream",
      @".gif" : @"image/gif",
      @".gtar" : @"application/x-gtar",
      @".gz" : @"application/x-gzip",
      @".h" : @"text/plain",
      @".htm" : @"text/html",
      @".html" : @"text/html",
      @".jar" : @"application/java-archive",
      @".java" : @"text/plain",
      @".jpeg" : @"image/jpeg",
      @".jpg" : @"image/jpeg",
      @".js" : @"application/x-javascript",
      @".log" : @"text/plain",
      @".m3u" : @"audio/x-mpegurl",
      @".m4a" : @"audio/mp4a-latm",
      @".m4b" : @"audio/mp4a-latm",
      @".m4p" : @"audio/mp4a-latm",
      @".m4u" : @"video/vnd.mpegurl",
      @".m4v" : @"video/x-m4v",
      @".mov" : @"video/quicktime",
      @".mp2" : @"audio/x-mpeg",
      @".mp3" : @"audio/x-mpeg",
      @".mp4" : @"video/mp4",
      @".mpc" : @"application/vnd.mpohun.certificate",
      @".mpe" : @"video/mpeg",
      @".mpeg" : @"video/mpeg",
      @".mpg" : @"video/mpeg",
      @".mpg4" : @"video/mp4",
      @".mpga" : @"audio/mpeg",
      @".msg" : @"application/vnd.ms-outlook",
      @".ogg" : @"audio/ogg",
      @".pdf" : @"application/pdf",
      @".png" : @"image/png",
      @".pps" : @"application/vnd.ms-powerpoint",
      @".ppt" : @"application/vnd.ms-powerpoint",
      @".pptx" : @"application/vnd.openxmlformats-officedocument.presentationml.presentation",
      @".prop" : @"text/plain",
      @".rc" : @"text/plain",
      @".rmvb" : @"audio/x-pn-realaudio",
      @".rtf" : @"application/rtf",
      @".sh" : @"text/plain",
      @".tar" : @"application/x-tar",
      @".tgz" : @"application/x-compressed",
      @".txt" : @"text/plain",
      @".wav" : @"audio/x-wav",
      @".wma" : @"audio/x-ms-wma",
      @".wmv" : @"audio/x-ms-wmv",
      @".wps" : @"application/vnd.ms-works",
      @".xml" : @"text/plain",
      @".z" : @"application/x-compress",
      @".h"   : @"text/h-text",
      @".m"   : @"text/m-text",
      @".json": @"text/json-text",
      @".key" : @"application/vnd.ms-powerpoint",
      @".numbers" : @"application/vnd.ms-excel",
      @".pages" : @"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      };
    
    return dic;
}
+ (CNFileType)isReadedFileByType:(NSString *)suffixType
{
    suffixType = [NSString stringWithFormat:@"%@",[suffixType lowercaseString]];
    if ([[CNLiveBusinessTools fileTypeDic] objectForKey:[NSString stringWithFormat:@".%@",suffixType]]) {
        return CNFileTypeReadAndLook;
    }
    else if ([[CNLiveBusinessTools onlyReadFileType] objectForKey:[NSString stringWithFormat:@".%@",suffixType]])
    {
        return CNFileTypeOnlyRead;
    }
    else
        return CNFileTypeUnkown;
}
// 文件知道其类型,但是无法预览
+ (NSDictionary *)onlyReadFileType
{
    NSDictionary *dic = @{
                          @".zip" : @"application/x-zip-compressed",
                          
                          };
    return dic;
}

+ (NSString *)getSpid
{
    NSString *spId = @"";
    NSArray *array = [AppId componentsSeparatedByString:@"_"];
    spId = [array firstObject];
    return spId;
}
+ (NSString *)getSidIdfv
{
    NSString *idfv = [self tingyunUUID];
    NSString *uid = @"";
    if ([CNUserShareManager isLogin]) {
        uid = CNUserShareModel.uid;
    }
    NSString *sidIdfv = [NSString stringWithFormat:@"%@%@",uid,idfv];
    //    NSLog(@"sidIdfv:%@",sidIdfv);
    return sidIdfv;
}



+ (NSMutableDictionary *)encryptionSignWithParameter:(NSMutableDictionary *)parameter encryptionKey:(NSString *)encryptionKey
{
    NSMutableDictionary *muDic = [NSMutableDictionary dictionaryWithDictionary:parameter];
    NSArray *allKeys = [muDic allKeys];
    BOOL isContainAppId = NO;
    BOOL isContainPlat = NO;
    BOOL isPlatform_id = NO;
    BOOL isTimestamp = NO;
    BOOL isVer = NO;
    BOOL isUUID = NO;
    BOOL isSign = NO;
    BOOL isLoginId = NO;
    for (NSString *key in allKeys) {
        if ([key isEqualToString:@"appId"]){
            isContainAppId = YES;
        }else if ([key isEqualToString:@"plat"]) {
            isContainPlat = YES;
        }else if ([key isEqualToString:@"platform_id"]) {
            isPlatform_id = YES;
        }else if ([key isEqualToString:@"timestamp"]) {
            isTimestamp = YES;
        }else if ([key isEqualToString:@"ver"]) {
            isVer = YES;
        }else if ([key isEqualToString:@"uuid"]) {
            isUUID = YES;
        }else if ([key isEqualToString:@"sign"]){
            isSign = YES;
        }else if ([key isEqualToString:@"loginSid"]) {
            isLoginId = YES;
        }
        if (isContainAppId && isContainPlat && isPlatform_id && isTimestamp && isVer && isUUID && isLoginId) {
            break;
        }
    }
    if (!isContainAppId) {
        [muDic setObject:AppId forKey:@"appId"];
    }
    if (!isContainPlat) {
        [muDic setObject:@"i" forKey:@"plat"];
    }
    if (!isPlatform_id) {
        [muDic setObject:[self getBundleID] forKey:@"platform_id"];
    }
    if (!isTimestamp) {
        [muDic setObject:[NSString stringWithFormat:@"%zd",[self getNowTimestamp]] forKey:@"timestamp"];
    }
    if (!isVer) {
        [muDic setObject:AppVersion forKey:@"ver"];
    }
    if (!isUUID) {
        [muDic setObject:[CNLiveBusinessTools uuid] forKey:@"uuid"];
    }
    if (!isLoginId) {
        [muDic setObject:CNUserShareModel.uid.length == 0 ? @"" : CNUserShareModel.uid forKey:@"loginSid"];
    }
    
    NSMutableDictionary *startPara = [NSMutableDictionary dictionaryWithDictionary:muDic];
    if (!isSign) {
        NSString *string = [NSString stringWithFormat:@"%@&key=%@",[self signvalue:muDic],encryptionKey];
        NSString *signString = [[self sha1:string] uppercaseString];
        [startPara setObject:signString forKey:@"sign"];
    }
    return startPara;
}

+ (NSInteger)getNowTimestamp{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    //设置时区,这个对于时间的处理有时很重要
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [formatter setTimeZone:timeZone];
    NSDate *datenow = [NSDate date];//现在时间
    //    NSLog(@"设备当前的时间:%@",[formatter stringFromDate:datenow]);
    //时间转时间戳的方法:
    NSInteger timeSp = [[NSNumber numberWithDouble:[datenow timeIntervalSince1970]] integerValue];
    //    NSLog(@"设备当前的10位时间戳:%ld",(long)timeSp); //时间戳的值
    return timeSp;
}

+ (NSString *)signvalue:(NSDictionary*)parameter
{
    //对所有传入参数按照字段名的 ASCII 码从小到大排序
    NSArray *keyArr=[parameter allKeys];
    NSArray *arr = [keyArr sortedArrayUsingSelector:@selector(compare:)];
    
    NSMutableString *string1 = [[NSMutableString alloc]init];
    for (int i=0; i<arr.count; i++) {
        
        NSString *parameterString = parameter[[arr objectAtIndex:i]];
        if (parameterString.length > 0) {
            [string1 appendString:[NSString stringWithFormat:@"%@=%@&",[arr objectAtIndex:i],parameter[[arr objectAtIndex:i]]]];
        }
    }
    
    if (string1.length > 0) {
        [string1 deleteCharactersInRange:NSMakeRange(string1.length-1, 1)];
    }
    
    return string1;
}

+ (NSString*)sha1:(NSString *)string
{
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    
    CC_SHA1(data.bytes, (int)data.length, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    
    while ([[output substringToIndex:1] isEqualToString:@"0"]) {
        output = [[NSMutableString alloc] initWithString:[output substringFromIndex:1]];
    }
    
    return output;
}

//获取BundleID
+ (NSString*)getBundleID
{
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    
}


/**
 GIF表情存放位置
 @return 地址
 */
+ (NSString *)newChatGifFacePath{
    
    // NSHomeDirectory():应用程序目录, 在Documents文件夹下创建
    NSString *tempName = [NSString stringWithFormat:@"Documents/%@/GifFace/Cache", CNUserShareModel.uid];
    
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:tempName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    if ( !(isDir == YES && existed == YES) ) {
        
        // 在 tmp 目录下创建一个 temp 目录
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return filePath;
    
}
/**
 @param userId 单聊为对方ID,群聊为群聊 ID,图片和视频存放位置
 @return 地址
 */
+ (NSString *)newChatFilePathByUserId:(NSString *)userId{
    
    // NSHomeDirectory():应用程序目录, 在Documents文件夹下创建
    NSString *tempName = [NSString stringWithFormat:@"Documents/%@/%@/imageorvideo", CNUserShareModel.uid, userId];
    
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:tempName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    if ( !(isDir == YES && existed == YES) ) {
        
        // 在 tmp 目录下创建一个 temp 目录
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return filePath;
    
}

+ (nullable NSString *)chatFileWithCachePathByUserId:(NSString *_Nonnull)userId{
    // NSHomeDirectory():应用程序目录, @"tmp/temp":在tmp文件夹下创建temp 文件夹
    //    NSString *tempName = [NSString stringWithFormat:@"cache/%@/%@", CNUserShareModel.uid, userId];
    
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0]; //stringByAppendingPathComponent:tempName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    if ( !(isDir == YES && existed == YES) ) {
        
        // 在 tmp 目录下创建一个 temp 目录
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return filePath;
}

//用户ID
+ (nullable NSString *)chatFilePathByUserId:(NSString *_Nonnull)userId{
    
    // NSHomeDirectory():应用程序目录, @"tmp/temp":在tmp文件夹下创建temp 文件夹
    NSString *tempName = [NSString stringWithFormat:@"%@/",userId];
    
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:tempName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    if ( !(isDir == YES && existed == YES) ) {
        
        // 在 temp 目录下创建一临时文件
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return filePath;
    
}

/**
 @param userId 单聊为对方ID,群聊为群聊 ID
 @return 返回聊天发送的文件 所保存的文件夹地址
 */
+ (NSString *)getChatFilesPathByUserId:(NSString *)userId{
    NSString *tempName = [NSString stringWithFormat:@"Documents/%@/%@/file", CNUserShareModel.uid, userId];
    
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:tempName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    if ( !(isDir == YES && existed == YES) ) {
        
        // 在 Documents 目录下创建
        
        if ([fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]) {
            NSLog(@"创建聊天文件路径成功");
        }
        else
        {
            NSLog(@"聊天文件路径已经创建过");
        }
    }
    return filePath;
}
/// 获取聊天文件路径
/// @param userId 会话id
/// @param msgId 消息id
+ (NSString *)getChatFilesPathByUserId:(NSString *)userId msgId:(NSString *)msgId
{
    NSString *tempName = [NSString stringWithFormat:@"Documents/%@/%@/file/%@", CNUserShareModel.uid, userId,msgId];
    
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:tempName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    if ( !(isDir == YES && existed == YES) ) {
        
        // 在 Documents 目录下创建
        
        if ([fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]) {
            NSLog(@"创建聊天文件路径成功");
        }
        else
        {
            NSLog(@"聊天文件路径已经创建过");
        }
    }
    return filePath;
}

/// 某一个 聊天图片 文件地址
/// @param conversationId 会话id
/// @param read 是否是读文件
/// @param isThumb 是否是缩略图
/// @param imageElem_path_lastPathComponent 自己发送时的图片上传地址名字 ,只在读文件的时候才需要用到
+ (NSString *)chatImagePathByConversationId:(NSString *)conversationId imageName:(NSString *)imageName isRead:(BOOL)read isThumb:(BOOL)isThumb imageElem_path_lastPathComponent:(NSString *)imageElem_path_lastPathComponent;
{
    #pragma mark 备注:自己发送的图片 imageElem.path 才有值,但是删除APP再次下载imageElem.path无值,收到别人的图片self.path无值

    NSFileManager *fileMgr = [NSFileManager defaultManager];
    if (read) {

        //读本地图片文件, 包含兼容老版本逻辑
        
        if (!isThumb) {
            //原图地址
            NSString *tempStr = @"";
            //path1 为本地image文件下的图片本地地址
            NSString *path1 = [[CNLiveBusinessTools getChatImageFile:conversationId] stringByAppendingPathComponent:imageName];
            //path2 为自己发送时传给 IM 的本地临时 image_video_temp 文件下的图片地址
            NSString *path2 = [CNLiveBusinessTools chatImageAndVideoUploadIMCachePath:imageElem_path_lastPathComponent];
            //path3 为老版本存的图片地址
            NSString *path3 = [[CNLiveBusinessTools chatFileWithCachePathByUserId:conversationId] stringByAppendingPathComponent:imageName];
            //path4 为老版本自己发送时传给 IM 的本地图片地址
               NSString *path4 = [[CNLiveBusinessTools chatFileWithCachePathByUserId:conversationId] stringByAppendingPathComponent:imageElem_path_lastPathComponent];
            
            if ([fileMgr fileExistsAtPath:path1])
            {
                //自己下载的图片 本地地址
                tempStr = path1;
            }
            else if ([fileMgr fileExistsAtPath:path2] && ![NSString isEmpty:imageElem_path_lastPathComponent]) {
                // 自己发送时传给 IM 的本地图片地址
                tempStr = path2;
            }
            else if ([fileMgr fileExistsAtPath:path3])
            {
                //老版本存的图片地址
                tempStr = path3;
            }
            else if ([fileMgr fileExistsAtPath:path4] && ![NSString isEmpty:imageElem_path_lastPathComponent])
            {
                //为老版本自己发送时传给 IM 的本地图片地址
                tempStr = path4;
            }
            return tempStr;
        }
        else
        {
            //缩略图地址
            #pragma mark 本地缩略图地址
            NSString *thumbStr = @"";
            
            //thumPath1 为本地Image文件夹下的缩略图地址
            NSString *thumPath1 = [[CNLiveBusinessTools getChatImageFile:conversationId] stringByAppendingPathComponent:imageName];
            
            //thumPath2 为自己发送消息时本地临时文件夹下image_video_temp的缩略图地址
            NSString *thumPath2 = [CNLiveBusinessTools chatImageAndVideoUploadIMCachePath:[NSString stringWithFormat:@"%@_thumb",imageElem_path_lastPathComponent]];
            
            //thumbPath3 为老版本存的缩略图 地址
            NSString *thumbPath3 = [[CNLiveBusinessTools chatFileWithCachePathByUserId:conversationId] stringByAppendingPathComponent:imageName];
            //thumbPath4 为老版本自己发送时传给 IM 的本地图片地址
            NSString *thumPath4 = [[CNLiveBusinessTools chatFileWithCachePathByUserId:conversationId] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_thumb",imageElem_path_lastPathComponent]];
            
            if ([fileMgr fileExistsAtPath:thumPath1])
            {
                //为本地Image文件夹下的缩略图地址
                thumbStr = thumPath1;
            }
            else if ([fileMgr fileExistsAtPath:thumPath2] && ![NSString isEmpty:imageElem_path_lastPathComponent]) {
                // 为自己发送消息时本地临时文件夹下image_video_temp的缩略图地址
                thumbStr = thumPath2;
            }
            else if ([fileMgr fileExistsAtPath:thumbPath3])
            {
                //老版本存的缩略图 地址
                thumbStr = thumbPath3;
            }
            else if ([fileMgr fileExistsAtPath:thumPath4] && ![NSString isEmpty:imageElem_path_lastPathComponent])
            {
                //为老版本自己发送时传给 IM 的本地图片地址
                thumbStr = thumPath4;
            }
            return thumbStr;
        }
        
        
    }
    else
    {
        //存文件
        NSString *path = [[CNLiveBusinessTools getChatImageFile:conversationId] stringByAppendingPathComponent:imageName];
        return path;
    }
    
}
/// 获取本地聊天图片 文件夹路径
/// @param conversationId 会话id
+ (NSString *)getChatImageFile:(NSString *)conversationId
{
    // NSHomeDirectory():应用程序目录, 在Documents文件夹下创建
    NSString *tempName = [NSString stringWithFormat:@"Documents/%@/%@/Image", CNUserShareModel.uid, conversationId];
    
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:tempName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    if ( !(isDir == YES && existed == YES) ) {
        
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return filePath;
}

/// 某一个聊天视频或视频封面图 文件地址
/// @param conversationId 会话id
/// @param fileName 文件名字
/// @param read 是否是读文件
/// @param isSnapshot 是否是视频封面图
/// @param videoElem_path_lastPathComponent 自己发送时的视频名字 ,只在读文件的时候才需要用到
/// @param snapshotPath_lastPathComponent 自己发送时的视频封面图名字,只在读文件的时候才需要用到
+ (NSString *)chatVideoPathByConversationId:(NSString *)conversationId fileName:(NSString *)fileName isRead:(BOOL)read isSnapshot:(BOOL)isSnapshot videoElem_path_lastPathComponent:(NSString *)videoElem_path_lastPathComponent snapshotPath_lastPathComponent:(NSString *)snapshotPath_lastPathComponent
{
    NSFileManager *fileMgr = [NSFileManager defaultManager];

    if (read) {
        //读文件
        
        if (!isSnapshot) {
            //视频地址
            
            NSString *videoPath = @"";
           
            //path1 为Video文件夹下视频本地地址
            NSString *path1 = [[CNLiveBusinessTools getChatVideoFile:conversationId] stringByAppendingPathComponent:fileName];
            //path2 为自己发送时的本地image_video_temp文件夹下的视频地址
            NSString *path2 = [CNLiveBusinessTools chatImageAndVideoUploadIMCachePath:videoElem_path_lastPathComponent];
            //path3 为老版本已经下载的视频本地地址
            NSString *path3 = [[CNLiveBusinessTools chatFileWithCachePathByUserId:conversationId] stringByAppendingPathComponent:fileName];
            //path4 为老版本自己发送的视频本地地址
            NSString *path4 = [[CNLiveBusinessTools newChatFilePathByUserId:conversationId] stringByAppendingPathComponent:videoElem_path_lastPathComponent];

           
            if ([fileMgr fileExistsAtPath:path1 isDirectory:nil])
            {
                //自己下载的视频本地地址
                videoPath = path1;
            }
            else if ([fileMgr fileExistsAtPath:path2 isDirectory:nil] && ![NSString isEmpty:videoElem_path_lastPathComponent]) {
                //自己发送时的本地视频地址
                videoPath = path2;
            }
            else if ([fileMgr fileExistsAtPath:path3 isDirectory:nil])
            {
                //老版本下载的视频本地地址
                videoPath = path3;
            }
            else if ([fileMgr fileExistsAtPath:path4 isDirectory:nil] && ![NSString isEmpty:videoElem_path_lastPathComponent])
            {
                //为老版本自己发送的视频本地地址
                videoPath = path4;
            }
            
            return videoPath;
        }
        else
        {
            //视频封面图地址
            NSString *snapshotPath = @"";
            
            //snapshotPath1 为Video文件下的视频封面图 本地地址
            NSString *snapshotPath1 = [[CNLiveBusinessTools getChatVideoFile:conversationId] stringByAppendingPathComponent:fileName];
            //snapshotPath2 为自己发送消息时image_video_temp文件夹下本地视频封面图地址
            NSString *snapshotPath2 = [CNLiveBusinessTools chatImageAndVideoUploadIMCachePath:snapshotPath_lastPathComponent];
            //snapshotPath3 为老版本存的视频图 地址
            NSString *snapshotPath3 = [[CNLiveBusinessTools chatFileWithCachePathByUserId:conversationId] stringByAppendingPathComponent:fileName];
            //snapshotPath4 为老版本自己发送的视频封面图地址
            NSString *snapshotPath4 = [[CNLiveBusinessTools chatFileWithCachePathByUserId:conversationId] stringByAppendingPathComponent:snapshotPath_lastPathComponent];

            if ([PathUtility isExistFile:snapshotPath1])
            {
                //自己下载的视频图 本地地址
                snapshotPath = snapshotPath1;
            }
            if ([PathUtility isExistFile:snapshotPath2] && ![NSString isEmpty:snapshotPath_lastPathComponent]) {
                // 自己发送消息时本地视频图地址
                snapshotPath = snapshotPath2;
            }
            else if ([PathUtility isExistFile:snapshotPath3])
            {
                //老版本存的视频图 地址
                snapshotPath = snapshotPath3;
            }
            else if ([PathUtility isExistFile:snapshotPath4] && ![NSString isEmpty:snapshotPath_lastPathComponent])
            {
                // 为老版本自己发送的视频封面图地址
                snapshotPath = snapshotPath4;
            }
            
            return snapshotPath;
        }
        
    }
    else
    {
        //存文件
        NSString *filePath = [[CNLiveBusinessTools getChatVideoFile:conversationId] stringByAppendingPathComponent:fileName];
        return filePath;
    }
}
/// 获取本地聊天视频 文件夹路径
/// @param conversationId 会话id
+ (NSString *)getChatVideoFile:(NSString *)conversationId
{
    // NSHomeDirectory():应用程序目录, 在Documents文件夹下创建
    NSString *tempName = [NSString stringWithFormat:@"Documents/%@/%@/Video", CNUserShareModel.uid, conversationId];
    
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:tempName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    if ( !(isDir == YES && existed == YES) ) {
        
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return filePath;
}
/// 发送图片或视频消息时上传给IM的文件路径,发送消息成功后或者失败后会把这个图片或视频文件拷贝到对应的 image 或者video 文件夹下
/// @param fileName 临时图片或视频名字
+ (NSString *)chatImageAndVideoUploadIMCachePath:(NSString *)fileName;
{
    NSString *filePath = [CNLiveBusinessTools getChatImageAndVideoUploadIMCacheDirectory];
    filePath = [filePath stringByAppendingPathComponent:fileName];
    return filePath;
}
//获取 临时发送图片或视频保存的文件夹地址
+ (NSString *)getChatImageAndVideoUploadIMCacheDirectory;
{
    NSString *temp = [NSString stringWithFormat:@"Documents/%@/image_video_temp", CNUserShareModel.uid];
    
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:temp];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    if ( !(isDir == YES && existed == YES) ) {
        
        // 在 Documents 目录下创建一个 image_video_temp 目录
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return filePath;
}
/// 删除聊天 图片 和 视频 上传时的临时文件
+ (BOOL )deleteChatImageAndVideoUploadImCache
{
    NSString *temp = [NSString stringWithFormat:@"Documents/%@/image_video_temp", CNUserShareModel.uid];
    
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:temp];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    if (existed) {
        BOOL suceess = [fileManager removeItemAtPath:filePath error:nil];
        return suceess;
    }
    return YES;
}
/**
 0
 @param userId 单聊为对方ID,群聊为群聊 ID ,语音文件保存路径
 */
+ (NSString *)audioChatFilePathByUserId:(NSString *)userId{
    NSString *tempName = [NSString stringWithFormat:@"Documents/%@/%@/audio", CNUserShareModel.uid, userId];
    
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:tempName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    if ( !(isDir == YES && existed == YES) ) {
        
        // 在 Documents 目录下创建
        
        if ([fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]) {
            NSLog(@"创建语音文件成功");
        }
        else
        {
            NSLog(@"语音文件已经存在");
        }
    }
    return filePath;
}

/**
 聊天背景图图片地址
 
 @return file
 */
+ (NSString *)chatBackgroupImagefilePath{
    
    // NSHomeDirectory():应用程序目录, 在Documents文件夹下创建
    NSString *tempName = [NSString stringWithFormat:@"Documents/%@/chatBackgroupImage", CNUserShareModel.uid];
    
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:tempName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL isDir = NO;
    
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL existed = [fileManager fileExistsAtPath:filePath isDirectory:&isDir];
    
    if ( !(isDir == YES && existed == YES) ) {
        
        // 在 tmp 目录下创建一个 temp 目录
        [fileManager createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return filePath;
    
}

+ (NSMutableAttributedString *)replaceQQemojiWithCustomText:(NSString *)text
{
    if (text == nil || [text isEqualToString:@""]) return  [[NSMutableAttributedString alloc] initWithString:@""];
    //过滤未知字符
    text = [NSString filterUnknownChara:text];
    
    //利用正则 取出 [开头 ]结尾 的数组,内容通配 ,再次forin QQEmojiArr,得到真正的表情个数,再替换删除
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    
    NSString *zhengze = @"\\[(.*?)\\]";
    NSError *error;
    NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error];
    if (!re) {
        NSLog(@"正则表达式匹配错误%@",[error localizedDescription]);
    }
    NSArray * arr = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];
    if (!arr.count) {//说明字符串中没有表情通配符,是普通的文本
        
    }else{//有表情通配符
        //如果有多个表情图,必须从后往前替换,因为替换后Range就不准确了
        NSArray<QMUIEmotion *> *emojiArr = [CNLiveQQEmotionManager emotionsForQQ];
        for (int i = (int)arr.count - 1; i >= 0; i --) {
            //NSTextCheckingResult里面包含range
            NSTextCheckingResult * result = arr[i];
            
            for (int j = 0; j < emojiArr.count; j ++) {
                if ([[text substringWithRange:result.range] isEqualToString:emojiArr[j].displayName]) {
                    @try {
                        if (![NSThread isMainThread]) {
                            dispatch_sync(dispatch_get_main_queue(), ^{
                                YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithImage:emojiArr[j].image];
                                imageView.width = 24*RATIO;
                                imageView.height = 24*RATIO;
                                NSMutableAttributedString *attachText = [NSMutableAttributedString attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.size alignToFont:UIFontCNMake(contentLabelFontSize) alignment:YYTextVerticalAlignmentCenter];
                                [attStr replaceCharactersInRange:result.range withAttributedString:attachText];
                            });
                        }else{
                            YYAnimatedImageView *imageView = [[YYAnimatedImageView alloc] initWithImage:emojiArr[j].image];
                            imageView.width = 24*RATIO;
                            imageView.height = 24*RATIO;
                            NSMutableAttributedString *attachText = [NSMutableAttributedString attachmentStringWithContent:imageView contentMode:UIViewContentModeCenter attachmentSize:imageView.size alignToFont:UIFontCNMake(contentLabelFontSize) alignment:YYTextVerticalAlignmentCenter];
                            
                            [attStr replaceCharactersInRange:result.range withAttributedString:attachText];
                        }
                    } @catch (NSException *exception) {
                        NSLog(@"获取的异常为=>%@",exception.reason);
                    }
                }
            }
        }
    }
    return attStr;
}

////static NSString *const kUserPattern = @"\\@\\w+"; // "@用户名"过滤
////static NSString *const kTopicPattern = @"\\#\\w+\\#"; // "##"微博话题过滤
////static NSString *const kEmotionPattern = @"\\[\\w+\\]"; // "[]"表情字段过滤
//static NSString *const kUrlPattern = @"(((ht|f)tp(s?))\\://)?(www.|[a-zA-Z].)[a-zA-Z0-9\\-\\.]+\\.(com|edu|gov|mil|net|org|biz|info|name|museum|us|ca|uk)(\\:[0-9]+)*(/($|[a-zA-Z0-9\\.\\,\\;\\?\\'\\\\\\+&%\\$#\\=~_\\-]+))*"; // URL 过滤
+ (NSMutableAttributedString *)replaceNativeQQemojiWithCustomText:(NSString *)text
{
    if (text == nil || [text isEqualToString:@""]) return  [[NSMutableAttributedString alloc] initWithString:@""];
    //    过滤未知字符
    text = [NSString filterUnknownChara:text];
    //利用正则 取出 [开头 ]结尾 的数组,内容通配 ,再次forin QQEmojiArr,得到真正的表情个数,再替换删除
    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:text];
    NSString *zhengze = @"\\[(.*?)\\]";
    NSError *error;
    NSRegularExpression *re = [NSRegularExpression regularExpressionWithPattern:zhengze options:NSRegularExpressionCaseInsensitive error:&error];
    if (!re) {
        NSLog(@"正则表达式匹配错误%@",[error localizedDescription]);
    }
    NSArray * arr = [re matchesInString:text options:0 range:NSMakeRange(0, text.length)];
    if (!arr.count) {//说明字符串中没有表情通配符,是普通的文本
        
    }else
    {//有表情通配符
        //如果有多个表情图,必须从后往前替换,因为替换后Range就不准确了
        NSArray<QMUIEmotion *> *emojiArr = [CNLiveQQEmotionManager emotionsForQQ];
        for (int i = (int)arr.count - 1; i >= 0; i --) {
            //NSTextCheckingResult里面包含range
            NSTextCheckingResult * result = arr[i];
            
            if ([[[text substringWithRange:result.range] substringToIndex:1] isEqualToString:@"["]) {
                //可能自定义表情
                for (int j = 0; j < emojiArr.count; j ++) {
                    if ([[text substringWithRange:result.range] isEqualToString:emojiArr[j].displayName]) {
                        
                        NSString *emojiText = [text substringWithRange:result.range];
                        
                        CNEmojiTextAttachment *textAttachment = [[CNEmojiTextAttachment alloc]init];
                        textAttachment.image = emojiArr[j].image;
                        textAttachment.bounds = CGRectMake(0, -4.7, 20*RATIO, 20*RATIO);
                        textAttachment.emojiText = emojiText;
                        
                        NSAttributedString *imageStr = [NSAttributedString attributedStringWithAttachment:textAttachment];
                        [attStr replaceCharactersInRange:result.range withAttributedString:imageStr];
                        NSLog(@"\n11111:text%@,range:%@",text,NSStringFromRange(result.range));
                    }
                }
            }else
            {//目前只有 暂时没有判断是否是url办法 表情和url
                //url
                NSString *urlStr = [text substringWithRange:result.range];
                NSMutableAttributedString *urlAttStr = [[NSMutableAttributedString alloc] initWithString:urlStr attributes:@{NSFontAttributeName:UIFontMake(contentLabelFontSize)}];
                [urlAttStr addAttribute:NSLinkAttributeName value:[NSURL URLWithString:urlStr] range:NSMakeRange(0, urlStr.length)];
                [attStr replaceCharactersInRange:result.range withAttributedString:urlAttStr];
            }
        }
    }
    return attStr;
}

@end