JLChen
2021-04-30 a5247b61d585627a1a7b1e1f35f34de9f0af9fba
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
//
//  Copyright © 2019 Zhejiang Dahua Technology Co.,Ltd. All rights reserved.
//
 
#import <LCBaseModule/DHClientEventLogHelper.h>
#import <LCBaseModule/UIDevice+IPhoneModel.h>
#import <LCBaseModule/DHFileManager.h>
#import <LCBaseModule/NSString+SHA256.h>
#import <LCBaseModule/NSData+SHA256.h>
#import <LCBaseModule/NSObject+JSON.h>
#import <LCBaseModule/DHUserManager.h>
#import <LCBaseModule/NSString+LeChange.h>
 
#import <LCBaseModule/LCUserInfo.h>
#import <LCBaseModule/LCError.h>
 
static NSInteger upperId = 0;
 
@interface DHClientEventLogHelper ()
 
@property (nonatomic, strong) NSMutableArray<LCUserEventLogReport *> *logArray;
@property (nonatomic, strong) NSLock *lock;
@property (nonatomic, copy) NSString *cacheFileName;
@property (nonatomic, assign) BOOL isUploading;
@end
 
@implementation DHClientEventLogHelper
 
+ (DHClientEventLogHelper *)shareInstance
{
    static dispatch_once_t onceToken;
    static DHClientEventLogHelper *manager = nil;
    dispatch_once(&onceToken, ^{
        if (manager == nil) {
            manager = [[self alloc] init];
        }
    });
    
    return manager;
}
 
- (instancetype)init {
    self = [super init];
    if (self) {
 
        self.lock = [[NSLock alloc] init];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];
    }
    return self;
}
 
- (void)uploadLogs:(NSArray *)logs success:(void(^)(void))success{
    
    if (logs.count <= 0) {
        return;
    }
    
    if (self.isUploading == false) {
        self.isUploading = true;
        //需要完善上报处理
//        NSArray *copyArray = [logs copy];
//        [LCCommonInterface saas_clientEventLog:copyArray success:^{
//            self.isUploading = false;
//            NSLog(@"💚💚💚💚log upload success");
//            [self.lock lock];
//            [self.logArray removeObjectsInArray:copyArray];
//            [self.lock unlock];
//            if (success) {
//                success();
//            }
//        } failure:^(LCError *error) {
//            self.isUploading = false;
//            NSLog(@"💚💚💚💚log upload fail");
//            NSLog(@"💚💚💚💚 error = %@",error);
//        }];
    }
}
 
- (void)addClientEventLog:(NSString *)name conent:(NSDictionary *)contentDic {
    //打开调试模式才开始上报
    if ([DHUserManager shareInstance].openDebugMode == false) {
        return;
    }
    NSString *encodeStr = [[contentDic dh_jsonString] lc_base64String];
 
    LCUserEventLogReport *log = [LCUserEventLogReport new];
    log._id = name;
    log.content = encodeStr;
    
    [self.lock lock];
    [self.logArray addObject:log];
    [self.lock unlock];
    
    // 日志多余10条,上传
    if (self.logArray.count >= 10) {
        NSLog(@"%s: upload client log", __func__);
        [self.lock lock];
        NSArray *uploadArray = nil;
        if (self.logArray.count >= 10) {
            uploadArray = [self.logArray subarrayWithRange:NSMakeRange(0, 10)];
        }
        [self.lock unlock];
        [self uploadLogs:uploadArray success:nil];
    }
}
 
- (void)addClientEventLogForJson:(NSString *)json {
    
    if (json == nil || [json length] <= 0) {
        return;
    }
    //打开调试模式才开始上报
    if ([DHUserManager shareInstance].openDebugMode == false) {
        return;
    }
    NSDictionary *jsonDic = [json dh_jsonDictionary];
    NSString *type = jsonDic[@"type"];
    if (type && [jsonDic isKindOfClass:[NSDictionary class]]) {
        [self addClientEventLog:type conent:jsonDic];
    }
}
 
- (NSString *)getRequestId {
    NSString *mac = [UIDevice dh_getMacAddress];
    //补充实际的userId
    NSInteger userId = 0;
    NSString *currentTime = [self getCurrentSystemTimeMillis];
    NSString *requestId = [NSString stringWithFormat:@"%@%ld%@%@%ld",@"public-cloud-request",(long)userId, mac, currentTime, (long)upperId++];
    // 需要经过加密
    NSData *decryptData = [requestId lc_MD5Data];
    return [decryptData lc_convertToHexString];
}
 
// 获取当期时间的时间戳  毫秒级别
- (NSString *)getCurrentSystemTimeMillis {
    NSDate *datenow = [NSDate date];
    NSString *timeSp = [NSString stringWithFormat:@"%.lf", (double)[datenow timeIntervalSince1970]*1000];
    
    return timeSp;
}
 
#pragma mark - 缓存
 
- (void)applicationWillTerminate:(NSNotification *)noti {
    
    // 缓存日志
    [self archiveLogsToFile];
}
 
- (void)uploadCacheLog {
    
    //打开调试模式才开始上报
    if ([DHUserManager shareInstance].openDebugMode == false) {
        return;
    }
    NSString *cacheFilePath = [self cacheFilePathForCacheName:self.cacheFileName];
    if ([[NSFileManager defaultManager] fileExistsAtPath:cacheFilePath] == YES) {
        NSArray *logs = [NSKeyedUnarchiver unarchiveObjectWithFile:cacheFilePath];
        if (logs) {
            [self uploadLogs:logs success:^{
                NSError *error;
                [[NSFileManager defaultManager] removeItemAtPath:cacheFilePath error:&error];
            }];
        }
    }
}
 
- (void)archiveLogsToFile {
    
    //打开调试模式才进行归档
    if ([DHUserManager shareInstance].openDebugMode == false) {
        return;
    }
    if (self.logArray.count > 0) {
        NSString *cacheFilePath = [self cacheFilePathForCacheName:self.cacheFileName];
        [NSKeyedArchiver archiveRootObject:self.logArray toFile:cacheFilePath];
    }
}
 
// 缓存文件的位置
- (NSString *)cacheFilePathForCacheName:(NSString *)cacheName {
    
    if (cacheName == nil || cacheName.length == 0) {
        return nil;
    }
    NSString *folder = [[DHFileManager supportFolder] stringByAppendingPathComponent:@"cache/clientLog"];
    if ([[NSFileManager defaultManager] fileExistsAtPath:folder] == NO) {
        NSError *error;
        [[NSFileManager defaultManager] createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:nil error:&error];
    }
    NSString *fileName = [folder stringByAppendingPathComponent:cacheName];
    return fileName;
}
 
 
#pragma mark - 属性懒加载
 
- (NSMutableArray *)logArray {
    if (_logArray == nil) {
        _logArray = [NSMutableArray arrayWithCapacity:10];
    }
    return _logArray;
}
 
- (NSString *)cacheFileName {
    if (_cacheFileName == nil) {
        
        _cacheFileName = @"client_log";
    }
    return _cacheFileName;
}
 
@end