-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathBFDataManager.m
507 lines (392 loc) · 17.5 KB
/
BFDataManager.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
//
// BFDataManager.m
// Briefs
//
// Created by Rob Rhyne on 9/23/09.
// Copyright Digital Arch Design, 2009. See LICENSE file for details.
//
#import "BFDataManager.h"
#import "SynthesizeSingleton.h"
#import "BFBriefCellController.h"
#import "BFBriefcastCellController.h"
#import "BFBriefcast+CoreDataAdditions.h"
#import "NSDictionary+BFAdditions.h"
#import "BFBriefInfo.h"
#import "BFArrayBriefDataSource.h"
#define kBFDataManagerStoreLocation @"Briefs.sqlite"
@interface BFDataManager (PrivateMethods)
- (BriefRef *)addBriefAtPath:(NSString *)path fromURL:(NSString *)url;
@end
@implementation BFDataManager
SYNTHESIZE_SINGLETON_FOR_CLASS(BFDataManager);
///////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Initialization
- (NSString *)documentDirectory
{
return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
- (NSString *)locationOfDataStore
{
return [[self documentDirectory] stringByAppendingPathComponent:kBFDataManagerStoreLocation];
}
- (void)load
{
// Manually Installed Briefs
// =====================================
// look for manually installed Briefs
// and copy them into the documents
// directory with the rest of the briefs
// TODO: Make this run on first load only.
NSString *bundleDirectory = [[NSBundle mainBundle] resourcePath];
NSDirectoryEnumerator *enumerator = [[NSFileManager defaultManager] enumeratorAtPath:bundleDirectory];
NSString *next;
while (next = [enumerator nextObject]) {
// Only move briefs
if ([[next pathExtension] isEqualToString:@"brieflist"]) {
NSString *newPath = [[self documentDirectory] stringByAppendingPathComponent:next];
NSString *oldPath = [bundleDirectory stringByAppendingPathComponent:next];
NSError *error = [[NSError alloc] init];
// check if already installed,
// do not add it to the datastore if it already exists.
if (![[NSFileManager defaultManager] fileExistsAtPath:newPath isDirectory:NO]) {
// copy the brief
if([[NSFileManager defaultManager] copyItemAtPath:oldPath toPath:newPath error:&error]) {
// if copy was successful, then add it to the database
BriefRef *briefRef = [self addBriefAtPath:next fromURL:kBFLocallyStoredBriefURLString];
[briefRef setBriefcast:[self localBriefcastRefMarker]];
// Save the context
if (![managedObjectContext save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
}
else
// If not, throw an error, dude.
NSLog(@"ERROR! - %@", error);
}
[error release];
}
}
}
- (void)save
{
// TODO: Handle the error appropriately.
NSError *error = nil;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
}
}
- (void)dealloc
{
[managedObjectContext release];
[managedObjectModel release];
[persistentStoreCoordinator release];
[super dealloc];
}
///////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Core Data stack
/**
Returns the managed object context for the application.
If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
*/
- (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext != nil) {
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
if (coordinator != nil) {
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator: coordinator];
}
return managedObjectContext;
}
/**
Returns the managed object model for the application.
If the model doesn't already exist, it is created by merging all of the models found in the application bundle.
*/
- (NSManagedObjectModel *)managedObjectModel
{
if (managedObjectModel != nil) {
return managedObjectModel;
}
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:nil] retain];
return managedObjectModel;
}
/**
Returns the persistent store coordinator for the application.
If the coordinator doesn't already exist, it is created and the application's store added to it.
*/
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
if (persistentStoreCoordinator != nil) {
return persistentStoreCoordinator;
}
NSURL *storeUrl = [NSURL fileURLWithPath:[self locationOfDataStore]];
NSError *error = nil;
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
if (![persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeUrl options:nil error:&error]) {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
Typical reasons for an error here include:
* The persistent store is not accessible
* The schema for the persistent store is incompatible with current managed object model
Check the error message to determine what the actual problem was.
*/
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
}
return persistentStoreCoordinator;
}
///////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Add / Insert API
- (void)addBriefcastInformation:(BFBriefcast *)briefcast
{
// Create and configure a new instance of the Event entity
[briefcast insertIntoManagedContext:[self managedObjectContext]];
// Save the context
NSError *error;
if (![[self managedObjectContext] save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
}
- (BriefRef *)addBriefAtPath:(NSString *)path usingData:(NSData *)data fromURL:(NSString *)url
{
NSString *destination = [[self documentDirectory] stringByAppendingPathComponent:path];
// check to see if the brief already exists
// if it doesn't, add it the regular way
BriefRef *brief = [self findBriefUsingURL:url];
if (brief == nil) {
// check to see if a file exists at that path
// if so, alter the incoming file path to avoid
// overwriting data
if ([[NSFileManager defaultManager] fileExistsAtPath:destination isDirectory:NO]) {
// Meh. This is ugly. Desperately needs refactoring.
NSString *alteredURL = [[[url stringByReplacingOccurrencesOfString:@".brieflist" withString:@""]
stringByReplacingOccurrencesOfString:@"http://" withString:@""]
stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
path = [NSString stringWithFormat:@"(%@)%@", alteredURL, path];
NSString *newDestination = [[self documentDirectory] stringByAppendingPathComponent:path];
[data writeToFile:newDestination atomically:YES];
}
else [data writeToFile:destination atomically:YES];
return [self addBriefAtPath:path fromURL:url];
}
// else, get the reference and update it's download date
else {
return [self updateBrief:brief usingData:data];
}
}
- (BriefRef *)addBriefAtPath:(NSString *)path fromURL:(NSString *)url
{
// NOTE: This signature is only called by self, when the
// brief is already stored on the file system.
// (i.e., only internally by the data manager)
NSString *destination = [[self documentDirectory] stringByAppendingPathComponent:path];
NSDictionary *dictionary = [NSDictionary dictionaryWithContentsOfFile:destination];
BFBriefInfo *info = [BFBriefInfo infoForBriefData:dictionary atPath:path];
BriefRef *newRef = [info insertIntoManagedContext:[self managedObjectContext]];
[newRef setDateLastDownloaded:[NSDate date]];
[newRef setFromURL:url];
// Save the context
NSError *error;
if (![[self managedObjectContext] save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
return newRef;
}
- (BriefRef *)updateBrief:(BriefRef *)brief usingData:(NSData *)data
{
// update the brief meta data
BFBriefInfo *info = [BFBriefInfo infoForBriefData:[NSDictionary dictionaryFromData:data] atPath:brief.filePath];
brief = [info mergeInfoIntoBrief:brief];
[brief setDateLastDownloaded:[NSDate date]];
[self save];
// write the new file
NSString *destination = [[self documentDirectory] stringByAppendingPathComponent:brief.filePath];
[data writeToFile:destination atomically:YES];
return brief;
}
///////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark Remove API
- (void)removeBrief:(BriefRef *)brief
{
NSError *error;
// Remove the brief's binary file
NSString *pathToBrief = [[self documentDirectory] stringByAppendingPathComponent:[brief filePath]];
if ([[NSFileManager defaultManager] fileExistsAtPath:pathToBrief isDirectory:NO]) {
if (![[NSFileManager defaultManager] removeItemAtPath:pathToBrief error:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
}
// Remove it from the database
[[self managedObjectContext] deleteObject:brief];
if (![[self managedObjectContext] save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
}
- (void)removeBriefcast:(BriefcastRef *)briefcast
{
// cycle through existing briefs and delete
// TODO: this should be an archive operation
for (BriefRef *brief in [briefcast briefs]) {
[self removeBrief:brief];
}
// delete the reference to the briefcast
[[self managedObjectContext] deleteObject:briefcast];
NSError *error;
if (![[self managedObjectContext] save:&error]) {
// Handle the error.
}
}
///////////////////////////////////////////////////////////////////////////////
#pragma mark -
#pragma mark High-Level API
- (NSArray *)allBriefcastsSortedAs:(BFDataManagerSortType)typeOfSort
{
return [self briefcastsSortedAs:typeOfSort limitTo:-1];
}
- (NSArray *)briefcastsSortedAs:(BFDataManagerSortType)typeOfSort limitTo:(int)limit
{
// Build predicate to locate marker
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"fromURL <> %@", kBFLocallyStoredBriefURLString];
// TODO: implement sorting types
// defaults to lasted opened for now
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"dateLastOpened" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sort, nil];
[sort release];
NSMutableArray *arrayOfBriefcasts = [NSMutableArray array];
// Fetch Data from the database
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"BriefcastRef" inManagedObjectContext:[self managedObjectContext]];
[request setEntity:entity];
[request setPredicate:predicate];
[request setSortDescriptors:sortDescriptors];
// handle limit
if (limit > 0) [request setFetchLimit:limit];
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Boom! Handle the error.
NSLog(@"There was a problem retrieving the listing of Briefcasts");
[request release];
return nil;
}
for (BriefcastRef *ref in mutableFetchResults) {
[arrayOfBriefcasts addObject:ref];
}
[mutableFetchResults release];
[request release];
return arrayOfBriefcasts;
}
- (NSArray *)briefsFromBriefcast:(BriefcastRef *)briefcast sortedAs:(BFDataManagerSortType)typeOfSort
{
// TODO: implement sorting types
return [[briefcast briefs] allObjects];
}
- (id<BFBriefDataSource>)allBriefsSortedAs:(BFDataManagerSortType)typeOfSort;
{
return [self briefsSortedAs:typeOfSort limitTo:-1];
}
- (id<BFBriefDataSource>)briefsSortedAs:(BFDataManagerSortType)typeOfSort limitTo:(int)limit
{
NSMutableArray *arrayOfBriefs = [NSMutableArray array];
// TODO: implement sorting types
// defaults to lasted opened for now
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"dateLastOpened" ascending:NO];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sort, nil];
[sort release];
// Fetch Data from the database
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"BriefRef" inManagedObjectContext:[self managedObjectContext]];
[request setEntity:entity];
[request setSortDescriptors:sortDescriptors];
// handle limit
if (limit > 0) [request setFetchLimit:limit];
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Boom! Handle the error.
NSLog(@"There was a problem retrieving the listing of Briefs");
[request release];
return nil;
}
for (BriefRef *ref in mutableFetchResults) {
[arrayOfBriefs addObject:ref];
}
[mutableFetchResults release];
[request release];
return [[[BFArrayBriefDataSource alloc] initWithArray:arrayOfBriefs] autorelease];
}
- (BriefcastRef *)localBriefcastRefMarker
{
BriefcastRef *refToReturn;
// Build predicate to locate marker
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"fromURL == %@", kBFLocallyStoredBriefURLString];
// Fetch Data from the database
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"BriefcastRef" inManagedObjectContext:[self managedObjectContext]];
[request setEntity:entity];
[request setPredicate:predicate];
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil || [mutableFetchResults count] <= 0) {
// Marker does not exist
BriefcastRef *ref = (BriefcastRef *) [NSEntityDescription insertNewObjectForEntityForName:@"BriefcastRef"
inManagedObjectContext:[self managedObjectContext]];
[ref setFromURL:kBFLocallyStoredBriefURLString];
[ref setTitle:@"Local Briefs"];
[ref setDesc:@"This contains briefs that did not originate from a briefcast and are stored locally on the device."];
// Save the context
NSError *error;
if (![[self managedObjectContext] save:&error]) {
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
refToReturn = ref;
}
else refToReturn = (BriefcastRef *) [mutableFetchResults objectAtIndex:0];
[request release];
[mutableFetchResults release];
return refToReturn;
}
- (BriefRef *)findBriefUsingURL:(NSString *)url
{
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"fromURL == %@", url];
// Fetch Data from the database
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"BriefRef" inManagedObjectContext:[self managedObjectContext]];
[request setEntity:entity];
[request setPredicate:predicate];
NSError *error;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil || [mutableFetchResults count] <= 0) {
if (mutableFetchResults) [mutableFetchResults release];
[request release];
return nil;
}
BriefRef *refToReturn = (BriefRef *) [mutableFetchResults objectAtIndex:0];
[request release];
[mutableFetchResults release];
return refToReturn;
}
- (NSDate *)briefFromURLWasInstalledOnDate:(NSString *)url
{
BriefRef *ref = [self findBriefUsingURL:url];
if (ref == nil) {
return nil;
}
else return [ref dateLastDownloaded];
}
///////////////////////////////////////////////////////////////////////////////
@end