forked from James-jinye/JSONModel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONCache.m
More file actions
470 lines (371 loc) · 16.2 KB
/
Copy pathJSONCache.m
File metadata and controls
470 lines (371 loc) · 16.2 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
//
// JSONCache.m
//
// @version 0.9.0
// @author Marin Todorov, http://www.touch-code-magazine.com
//
// Copyright (c) 2012 Marin Todorov, Underplot ltd.
// This code is distributed under the terms and conditions of the MIT license.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// The MIT License in plain English: http://www.touch-code-magazine.com/JSONModel/MITLicense
#import "JSONCache.h"
#import <CommonCrypto/CommonDigest.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h>
#import <netinet6/in6.h>
#pragma mark - constants
float kNeverRevalidate = FLT_MAX;
float kAlwaysRevalidate = 0.0f;
float kNeverExpire = FLT_MAX;
float kImmediatelyExpire = 0.0f;
#define kJSONCacheDirectory @"JSONCache"
#define kDefaultExpirationTimeInHours 1 //1 hour
#define kDefaultExpirationTimeInHoursWhenOffline 168 //1 week
#define kIfModifiedSinceHTTPHeaderName @"If-Modified-Since"
#define kETagHTTPHeaderName @"ETag"
#define kIfModifiedSinceHTTPHeaderNameXd @"X-If-Modified-Since"
#define kETagHTTPHeaderNameXd @"X-ETag"
BOOL JCFEqual(f1, f2) { return (fabs((f1) - (f2)) < FLT_EPSILON); }
static JSONCache* instance = nil;
#pragma mark - cache implementation
@implementation JSONCache
{
NSString* cacheDirectory;
NSFileManager* fm;
NSMutableDictionary* cacheFiles;
NSTimeInterval _expirationOnlineTimeInterval;
NSTimeInterval _expirationOfflineTimeInterval;
NSTimeInterval _revalidateFromServerTimeInterval;
NSTimeInterval _revalidateFromServerWithETagTimeInterval;
SCNetworkReachabilityRef reachabilityRef;
BOOL observingConnection;
}
#pragma mark - initializers
-(instancetype)init
{
NSAssert(NO, @"use [JSONCache sharedCache] instead");
return nil;
}
-(id)_initPrivate
{
self = [super init];
if (self!=nil) {
//do initial configuration
self.expirationTimeInHours = kDefaultExpirationTimeInHours;
self.expirationTimeInHoursWhenOffline = kDefaultExpirationTimeInHoursWhenOffline;
self.revalidateCacheFromServerAfterTimeInHours = kNeverRevalidate;
self.revalidateCacheViaETagAfterTimeInHours = kNeverRevalidate;
self.isUsingXdHTTPHeaderNames = YES;
_isOnline = YES;
cacheFiles = [[NSMutableDictionary alloc] initWithCapacity: 5];
}
return self;
}
+(instancetype)sharedCache
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
instance = [[[self class] alloc] _initPrivate];
});
return instance;
}
#pragma mark - load cached objects
-(void)loadCacheFromDisc
{
//setup the directories
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory , NSUserDomainMask, YES);
cacheDirectory = [[paths objectAtIndex:0] stringByAppendingPathComponent:kJSONCacheDirectory];
fm = [[NSFileManager alloc] init];
//create the cache directory
if (![fm fileExistsAtPath:cacheDirectory]) {
//empty cache
[fm createDirectoryAtPath:cacheDirectory withIntermediateDirectories:YES attributes:nil error:nil];
cacheFiles = [[NSMutableDictionary alloc] initWithCapacity:10];
} else {
//read the current cache folder
NSArray *directoryContents = [fm contentsOfDirectoryAtPath:cacheDirectory error:nil];
//read the current cache contents
for (NSString* fileName in directoryContents) {
NSLog(@"load cache file: %@", fileName);
NSString* fullFilePath = [cacheDirectory stringByAppendingPathComponent: fileName];
NSDate* modifiedDate = [[fm attributesOfItemAtPath:fullFilePath error:NULL] fileModificationDate];
JSONCacheFile* file = [[JSONCacheFile alloc] init];
file.modificationTime= [modifiedDate timeIntervalSinceReferenceDate];
file.fileName = fileName;
[cacheFiles setValue:file forKey:file.key];
}
//trim the cache
[self trimExpiredObjects];
}
if (cacheFiles.count>0 && observingConnection==NO) {
//observe connectivity changes
[self startConnectivityObserver];
NSLog(@"JSONCache.isOnline = %@", _isOnline?@"YES":@"NO" );
}
}
#pragma mark - manage cache objects
-(BOOL)addObject:(id)object forMethod:(NSString*)method andParams:(id)params
{
return [self addObject:object forMethod:method andParams:params etag:nil];
}
-(BOOL)addObject:(id)object forMethod:(NSString*)method andParams:(id)params etag:(NSString*)etag
{
//expire objects
[self trimExpiredObjects];
//add new objects
NSString* key = [self keyForMethod:method andParams:params];
//remove previous versions of the object
if (cacheFiles[key]) [self trimObjectForKey:key];
//store the file
NSData * data = [NSKeyedArchiver archivedDataWithRootObject:object];
//save the cache file
JSONCacheFile* file = [[JSONCacheFile alloc] initWithKey:key andEtag:etag];
NSString* filePath = [cacheDirectory stringByAppendingPathComponent: file.fileName];
BOOL success = [data writeToFile:filePath atomically:YES];
if (success) {
//save the object to the disc
[cacheFiles setValue: file forKey:key];
}
if (cacheFiles.count>0 && observingConnection==NO) {
//observe connectivity changes
[self startConnectivityObserver];
NSLog(@"JSONCache.isOnline = %@", _isOnline?@"YES":@"NO");
}
return success;
}
-(JSONCacheResponse*)objectForMethod:(NSString*)method andParams:(id)params
{
NSString* key = [self keyForMethod:method andParams:params];
JSONCacheFile* file = cacheFiles[key];
if (!file) return nil;
if ([self isObjectExpired: file]) {
//expired content
[self trimObjectForKey: key];
return nil;
}
NSString* filePath = [cacheDirectory stringByAppendingPathComponent:file.fileName];
NSData* data = [NSData dataWithContentsOfFile: filePath];
id object;
@try {
object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
} @catch (NSException* e) {
return nil;
}
JSONCacheResponse* response = [[JSONCacheResponse alloc] init];
response.object = object;
response.isOfflineVersion = !self.isOnline;
NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate] + 1;
if (self.isOnline && JCFEqual(self.revalidateCacheFromServerAfterTimeInHours, kNeverRevalidate)) {
//check for revalidation rules
NSTimeInterval expiration = _revalidateFromServerTimeInterval;
if (now > file.modificationTime + expiration) {
response.mustRevalidate = YES;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
NSDate* lastModificationDate = [NSDate dateWithTimeIntervalSinceReferenceDate:file.modificationTime];
[response.revalidateHeaders setValue: [dateFormatter stringFromDate: lastModificationDate]
forKey: self.isUsingXdHTTPHeaderNames? kIfModifiedSinceHTTPHeaderNameXd: kIfModifiedSinceHTTPHeaderName ];
}
}
if (self.isOnline && JCFEqual(self.revalidateCacheViaETagAfterTimeInHours,kNeverRevalidate)==NO ) {
//check for the revalidation rules
NSTimeInterval expiration = _revalidateFromServerWithETagTimeInterval;
if (now > file.modificationTime + expiration) {
response.mustRevalidate = YES;
if (file.etag != nil) {
[response.revalidateHeaders setValue: file.etag
forKey: self.isUsingXdHTTPHeaderNames? kETagHTTPHeaderNameXd: kETagHTTPHeaderName ];
}
}
}
NSLog(@"CASHED RESULT!!!");
return response;
}
-(NSString*)keyForMethod:(NSString*)method andParams:(id)params
{
if (params==nil) return method;
NSData* data = [NSJSONSerialization dataWithJSONObject: @{@"m":method,@"p":params}
options: kNilOptions error:NULL];
NSString* key = [[NSString alloc] initWithData:data encoding: NSUTF8StringEncoding];
return [self MD5:key];
}
-(void)trimExpiredObjects
{
NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate];
NSLog(@"trim expired objects...");
for (NSString* key in [cacheFiles allKeys]) {
JSONCacheFile* object = cacheFiles[key];
if (now > object.modificationTime + MAX(_expirationOnlineTimeInterval, _expirationOfflineTimeInterval)) {
//expired content - remove the file
NSLog(@"expired content for key %@", key);
NSLog(@"now: %.f %@", now, [NSDate dateWithTimeIntervalSinceReferenceDate: now]);
NSLog(@"object mod time: %.f %@", object.modificationTime, [NSDate dateWithTimeIntervalSinceReferenceDate:object.modificationTime]);
NSLog(@"expiration: %.f %@", object.modificationTime + MAX(_expirationOnlineTimeInterval, _expirationOfflineTimeInterval), [NSDate dateWithTimeIntervalSinceReferenceDate:object.modificationTime + MAX(_expirationOnlineTimeInterval, _expirationOfflineTimeInterval)]);
[self trimObjectForKey: key];
}
}
}
-(void)trimObjectForMethod:(NSString*)method andParams:(id)params
{
[self trimObjectForKey: [self keyForMethod:method andParams:params] ];
}
-(void)trimObjectForKey:(NSString*)key
{
NSLog(@"delete file: %@", key);
JSONCacheFile* file = cacheFiles[key];
NSString* filePath = [cacheDirectory stringByAppendingPathComponent: file.fileName];
[fm removeItemAtPath:filePath error:NULL];
[cacheFiles removeObjectForKey: key];
if (cacheFiles.count==0 && observingConnection==YES) {
//observe connectivity changes
[self stopConnectivityObserver];
}
}
-(void)purgeCache
{
for (NSString* key in [cacheFiles allKeys]) {
[self trimObjectForKey: key];
}
}
#pragma mark - connectivity methods
static void ReachabilityCallback(SCNetworkReachabilityRef target, SCNetworkReachabilityFlags flags, void *info)
{
#pragma unused (target, flags, info)
[instance updateConnectivity];
}
-(void)startConnectivityObserver
{
if (reachabilityRef==NULL) {
[self updateConnectivity];
}
SCNetworkReachabilityContext context = {0, (__bridge void *)(self), NULL, NULL, NULL};
if(SCNetworkReachabilitySetCallback(reachabilityRef, ReachabilityCallback, &context))
{
if(SCNetworkReachabilityScheduleWithRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode))
{
observingConnection = YES;
}
}
}
-(void)stopConnectivityObserver
{
if(reachabilityRef!= NULL)
{
SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityRef, CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
}
observingConnection = NO;
}
-(void)updateConnectivity
{
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
reachabilityRef = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
if(reachabilityRef != NULL) {
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(reachabilityRef, &flags)) {
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
{
_isOnline = NO;
return;
}
if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
_isOnline = YES;
return;
}
if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
{
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
{
_isOnline = YES;
return;
}
}
#if TARGET_OS_IPHONE
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
_isOnline = YES;
return;
}
#endif
}
}
_isOnline = NO;
}
#pragma mark - convenience methods
-(BOOL)isObjectExpired:(JSONCacheFile*)object
{
NSTimeInterval now = [[NSDate date] timeIntervalSinceReferenceDate];
NSTimeInterval expiration = 0;
if (self.isOnline==NO && JCFEqual(self.expirationTimeInHoursWhenOffline, kImmediatelyExpire) ) {
NSLog(@"expire %@ for Offline:offline disabled", object.key);
//it's always expired
return YES;
} else if (self.isOnline==YES && JCFEqual(self.expirationTimeInHoursWhenOffline, kImmediatelyExpire) ) {
//online cache expiration
NSLog(@"check expiration online with time: %.f", _expirationOnlineTimeInterval);
expiration = _expirationOnlineTimeInterval;
} else if (self.isOnline==YES && self.expirationTimeInHoursWhenOffline>kImmediatelyExpire) {
//offline expiration time
NSLog(@"check expiration offline with time: %.f", _expirationOfflineTimeInterval);
expiration = _expirationOfflineTimeInterval;
} else {
//just return the longer of the two exp. times
NSLog(@"check expiration combined with time: %.f", MAX(_expirationOfflineTimeInterval, _expirationOnlineTimeInterval));
expiration = MAX(_expirationOfflineTimeInterval, _expirationOnlineTimeInterval);
}
return (now > object.modificationTime + expiration);
}
//http://stackoverflow.com/questions/1524604/md5-algorithm-in-objective-c
-(NSString*)MD5:(NSString*)string
{
const char *cStr = [string UTF8String];
unsigned char result[16];
CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
}
-(NSString*)description
{
return [cacheFiles description];
}
#pragma mark - custom property getters
-(NSString*)etagHeaderName
{
return self.isUsingXdHTTPHeaderNames? kETagHTTPHeaderNameXd: kETagHTTPHeaderName;
}
#pragma mark - custom property setters
-(void)setExpirationTimeInHours:(float)hrs
{
_expirationTimeInHours = hrs;
_expirationOnlineTimeInterval = (JCFEqual(hrs,kNeverExpire))?kNeverExpire: hrs * 360;
}
-(void)setExpirationTimeInHoursWhenOffline:(float)hrs
{
_expirationTimeInHoursWhenOffline = hrs;
_expirationOfflineTimeInterval = (JCFEqual(hrs, kNeverExpire))?kNeverExpire: hrs * 360;
NSLog(@"exp. offline time: %.f", _expirationOfflineTimeInterval);
}
-(void)setRevalidateCacheFromServerAfterTimeInHours:(float)hrs
{
_revalidateCacheFromServerAfterTimeInHours = hrs;
_revalidateFromServerTimeInterval = (JCFEqual(hrs, kNeverRevalidate))?kNeverRevalidate: hrs * 360;
}
-(void)setRevalidateCacheViaETagAfterTimeInHours:(float)hrs
{
_revalidateCacheViaETagAfterTimeInHours = hrs;
_revalidateFromServerWithETagTimeInterval = (JCFEqual(hrs, kNeverRevalidate))?kNeverRevalidate: hrs * 360;
}
@end