-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonCache.m
519 lines (350 loc) · 14.9 KB
/
JsonCache.m
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
/*
``The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in
compliance with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/
The Initial Developer of the Original Code is Hollrr, LLC.
Portions created by the Initial Developer are Copyright (C) 2011
the Initial Developer. All Rights Reserved.
Contributor(s):
Dustin Dettmer <[email protected]>
*/
#import "JsonCache.h"
#import "CachedRequest.h"
#import "JsonLoader.h"
#import <CoreData/CoreData.h>
#import "CJSONDeserializer.h"
@interface JsonCache ()
@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
@property (nonatomic, retain) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (nonatomic, retain) NSManagedObjectModel *managedObjectModel;
- (void)saveContext;
- (void)saveContext:(BOOL)cleanupExpired;
- (CachedRequest*)getCachedRequestForUrl:(NSURL*)url;
- (CachedRequest*)getCachedRequestForUrlString:(NSString*)urlString;
@end
@implementation JsonCache
@synthesize managedObjectContext;
@synthesize persistentStoreCoordinator;
@synthesize managedObjectModel;
- (NSURL *)applicationDocumentsDirectory {
return [[[NSFileManager defaultManager]
URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]
lastObject];
}
- (NSManagedObjectContext*)managedObjectContext {
if(!managedObjectContext) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
managedObjectContext.persistentStoreCoordinator = self.persistentStoreCoordinator;
}
return managedObjectContext;
}
- (NSPersistentStoreCoordinator*)persistentStoreCoordinator {
if(!persistentStoreCoordinator) {
NSURL *storeURL = [[self applicationDocumentsDirectory]
URLByAppendingPathComponent:@"JsonCache.sqlite"];
persistentStoreCoordinator =
[[NSPersistentStoreCoordinator alloc]
initWithManagedObjectModel:self.managedObjectModel];
NSError *error = nil;
// check if we actually need to migrate (for debug purposes)
NSDictionary *sourceMetadata =
[NSPersistentStoreCoordinator metadataForPersistentStoreOfType:NSSQLiteStoreType
URL:storeURL
error:&error];
if (sourceMetadata == nil) {
// deal with error
NSLog(@"JsonCache: sourceMetadata == nil, cannot check if JSON cache needs to be migrated");
}
else {
NSManagedObjectModel *destinationModel = [persistentStoreCoordinator managedObjectModel];
BOOL pscCompatibile = [destinationModel
isConfiguration:nil
compatibleWithStoreMetadata:sourceMetadata];
if (pscCompatibile) {
NSLog(@"JsonCache: existing JSON cache is compatible , no need to migrate");
// no need to migrate
}
else {
NSLog(@"JsonCache: existing JSON cache is not compatible, need to migrate");
}
}
NSDictionary *options =
[NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption,
[NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption,
nil];
if (![persistentStoreCoordinator
addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storeURL
options:options error:&error]) {
NSLog(@"persistentStoreCoordinator addPersistentStoreWithType error %@, %@", error, [error userInfo]);
NSLog(@"persistentStoreCoordinator store: %@ ", storeURL);
// try to delete the store and try again
error = nil;
NSFileManager *fileMgr = [NSFileManager defaultManager];
[fileMgr removeItemAtURL:storeURL error:&error];
if(error) {
NSLog(@"could not delete store at %@", storeURL);
}
else {
NSLog(@"deleted store at %@", storeURL);
}
if ([fileMgr fileExistsAtPath:[storeURL path]]) {
NSLog(@"store at %@ is still there! deleting didnt work", storeURL);
}
else {
NSLog(@"store at %@ is gone - deleting worked", storeURL);
}
if (![persistentStoreCoordinator
addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil URL:storeURL
options:options error:&error]) {
NSLog(@"persistentStoreCoordinator addPersistentStoreWithType failed again! store: %@ ", storeURL);
NSLog(@"persistentStoreCoordinator addPersistentStoreWithType error %@, %@", error, [error userInfo]);
NSLog(@"calling recursively as last act of desperation");
persistentStoreCoordinator = nil;
return [self persistentStoreCoordinator];
}
else {
NSLog(@"persistentStoreCoordinator addPersistentStoreWithType apparently worked second attempt");
}
}
else {
NSLog(@"persistentStoreCoordinator addPersistentStoreWithType succeeded");
}
}
return persistentStoreCoordinator;
}
- (NSManagedObjectModel*)managedObjectModel {
if(!managedObjectModel)
managedObjectModel = [[NSManagedObjectModel alloc]
initWithContentsOfURL:
[[NSBundle mainBundle]
URLForResource:@"JsonCache"
withExtension:@"momd"]];
return managedObjectModel;
}
- (void)cleanupExpired {
NSManagedObjectContext *moc = self.managedObjectContext;
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
request.entity =
[NSEntityDescription entityForName:@"CachedRequest"
inManagedObjectContext:moc];
request.resultType = NSDictionaryResultType;
NSMutableArray *ary =
[NSMutableArray arrayWithObjects:@"timestamp", @"url", nil];
NSDictionary *props = request.entity.propertiesByName;
// This is here because migration is not working. So instead of
// crashing, we disable the perma functionality.
if([props objectForKey:@"perma"])
[ary addObject:@"perma"];
request.propertiesToFetch = ary;
NSArray *array = [moc executeFetchRequest:request error:nil];
for(NSDictionary *cachedRequest in array) {
NSDate *date = [cachedRequest objectForKey:@"timestamp"];
NSNumber *expire = [cachedRequest objectForKey:@"expire"];
if(-[date timeIntervalSinceNow] > [expire intValue]) {
if (![[cachedRequest objectForKey:@"perma"] boolValue]) {
id obj = [self getCachedRequestForUrlString:[cachedRequest objectForKey:@"url"]];
if(obj)
[self.managedObjectContext deleteObject:obj];
NSLog(@"Deleting expired cached json for url: %@", [cachedRequest objectForKey:@"url"]);
}
else {
NSLog(@"url is permacached, not touching it: %@", [cachedRequest objectForKey:@"url"]);
}
}
}
}
- (void)clearCache {
NSManagedObjectContext *moc = self.managedObjectContext;
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
request.entity =
[NSEntityDescription entityForName:@"CachedRequest"
inManagedObjectContext:moc];
request.resultType = NSDictionaryResultType;
request.propertiesToFetch =
[NSArray arrayWithObjects:@"timestamp", @"url", nil];
NSArray *array = [moc executeFetchRequest:request error:nil];
for(NSDictionary *cachedRequest in array) {
id obj = [self getCachedRequestForUrlString:[cachedRequest objectForKey:@"url"]];
if(obj)
[self.managedObjectContext deleteObject:obj];
}
[self saveContext:FALSE];
}
- (void)saveContext {
[self saveContext:TRUE];
}
- (void)saveContext:(BOOL)cleanupExpired {
if (cleanupExpired) {
[self cleanupExpired];
}
NSError *error = nil;
if (self.managedObjectContext && [managedObjectContext hasChanges]
&& ![managedObjectContext save:&error]) {
NSLog(@"managedObjectContext save error %@, %@",
error, [error userInfo]);
abort();
}
}
+ (id)shared {
static JsonCache *jsonCache = nil;
if(!jsonCache)
jsonCache = [[JsonCache alloc] init];
return jsonCache;
}
- (void)saveAndQuit {
[self saveContext];
[self release];
}
- (CachedRequest*)getCachedRequestForUrl:(NSURL*)url {
return [self getCachedRequestForUrlString:[url absoluteString]];
}
- (CachedRequest*)getCachedRequestForUrlString:(NSString*)urlString {
NSManagedObjectContext *moc = self.managedObjectContext;
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
request.entity =
[NSEntityDescription entityForName:@"CachedRequest" inManagedObjectContext:moc];
request.predicate =
[NSPredicate predicateWithFormat:@"url = %@", urlString];
NSArray *array = [moc executeFetchRequest:request error:nil];
if (array == nil)
return nil;
return [array lastObject];
}
- (CachedRequest*)createCachedRequest {
return
[NSEntityDescription
insertNewObjectForEntityForName:@"CachedRequest"
inManagedObjectContext:self.managedObjectContext];
}
- (void)checkForSoftUpdate:(CachedRequest*)cachedRequest url:(NSURL*)url perma:(BOOL)perma {
if([[NSDate date] earlierDate:
[cachedRequest.timestamp dateByAddingTimeInterval:
[cachedRequest.expire intValue] / 2]] != cachedRequest.timestamp) {
NSLog(@"checkForSoftUpdate running: %@", url);
NSURLRequest *req = [NSURLRequest requestWithURL:url];
JsonLoader *updater =
[[JsonLoader alloc] initWithCacheBustingRequest:req delegate:nil perma:perma];
updater.releaseWhenDone = YES;
}
else {
NSLog(@"checkForSoftUpdate not running: %@", url);
}
}
- (BOOL)cachedDataHasExpired:(NSURL*)url {
CachedRequest *cachedRequest = [self getCachedRequestForUrl:url];
if(cachedRequest
&& [cachedRequest.timestamp timeIntervalSinceNow] >
[cachedRequest.expire intValue]) {
return YES;
}
return NO;
}
- (void)clearDataForUrl:(NSURL*)url {
CachedRequest *cachedRequest = [self getCachedRequestForUrl:url];
[self.managedObjectContext deleteObject:cachedRequest];
}
- (NSData*)cacheDataForUrl:(NSURL*)url checkForSoftUpdate:(BOOL)checkForSoftUpdate {
CachedRequest *cachedRequest = [self getCachedRequestForUrl:url];
if (checkForSoftUpdate) {
[self checkForSoftUpdate:cachedRequest url:url perma:[cachedRequest.perma boolValue]];
}
return cachedRequest.rawData;
}
- (NSData*)cacheDataForUrl:(NSURL*)url getAge:(NSTimeInterval*)age checkForSoftUpdate:(BOOL)checkForSoftUpdate {
@try {
NSLog(@"cacheDataForUrl called for: %@", url);
CachedRequest *cachedRequest = [self getCachedRequestForUrl:url];
if(cachedRequest) {
NSTimeInterval timeIntervalSinceNow = [cachedRequest.timestamp timeIntervalSinceNow];
int timeIntervalSinceNowInt = (int) timeIntervalSinceNow;
timeIntervalSinceNowInt = abs(timeIntervalSinceNowInt);
NSLog(@"cachedRequest.expire: %d", [cachedRequest.expire intValue]);
NSLog(@"cachedRequest.timestamp timeIntervalSinceNow: %d", timeIntervalSinceNowInt);
if([cachedRequest.expire intValue] == 0 ||
timeIntervalSinceNowInt >
[cachedRequest.expire intValue]) {
if (![cachedRequest.perma boolValue]) {
NSLog(@"cacheDataForUrl deleting stale cache content for: %@", url);
[self.managedObjectContext deleteObject:cachedRequest];
return nil;
}
else {
NSLog(@"url is permacached, going to use cached data even though it appears stale: %@", url);
}
}
else {
NSLog(@"cacheDataForUrl found valid cached content for: %@", url);
}
if(age)
*age = [cachedRequest.timestamp timeIntervalSinceNow];
}
else {
NSLog(@"cacheDataForUrl nothing in cache found for: %@", url);
}
if (checkForSoftUpdate) {
NSLog(@"checkForSoftUpdate: %@", url);
[self checkForSoftUpdate:cachedRequest url:url perma:[cachedRequest.perma boolValue]];
}
return cachedRequest.rawData;
}
@catch (NSException *exception) {
NSLog(@"Caught %@: %@ when trying to cache data for url: %@", [exception name], [exception reason], url);
return nil;
}
}
- (void)setCacheData:(NSData*)data forUrl:(NSURL*)url expire:(int)inSeconds perma:(BOOL)perma {
@try {
// make sure this is valid json before saving in cache
NSError *error = nil;
id deserialized = [[CJSONDeserializer deserializer] deserialize:data error:&error];
// NSString *tempDebug = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (error || !deserialized) {
NSLog(@"setCacheData not setting cache data because json invalid for url: %@", url);
return;
}
CachedRequest *cachedRequest = [self getCachedRequestForUrl:url];
if(!cachedRequest) {
cachedRequest = [self createCachedRequest];
}
cachedRequest.rawData = data;
cachedRequest.url = [url absoluteString];
cachedRequest.timestamp = [NSDate date];
cachedRequest.perma = [NSNumber numberWithBool:perma];
if(inSeconds != -1) {
cachedRequest.expire = [NSNumber numberWithInt:inSeconds];
}
}
@catch (NSException *exception) {
NSLog(@"Caught %@: %@ when trying to set cache data for url: %@", [exception name], [exception reason], url);
}
}
- (void)setCacheData:(NSData*)data forUrl:(NSURL*)url {
[self setCacheData:data forUrl:url expire:-1 perma:NO];
}
- (id)init {
if((self = [super init])) {
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(saveAndQuit)
name:UIApplicationWillTerminateNotification
object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(saveContext)
name:UIApplicationDidEnterBackgroundNotification
object:nil];
}
return self;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
self.managedObjectContext = nil;
self.persistentStoreCoordinator = nil;
self.managedObjectModel = nil;
[super dealloc];
}
@end