-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathServerSyncer.m
198 lines (163 loc) · 6.53 KB
/
ServerSyncer.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
//
// ServerSyncer.m
// App Scanner
//
// Created by Andrew Schenk on 9/16/10.
// Copyright 2010 Chimp Studios. All rights reserved.
//
#import "ServerSyncer.h"
#import "APIScannerAppDelegate.h"
#import "Pweep.h"
#import "JSON.h"
@implementation ServerSyncer
@synthesize cmdContext;
-(void)startSync
{
APIScannerAppDelegate *delegate = (APIScannerAppDelegate*)[[NSApplication sharedApplication] delegate];
[NSThread detachNewThreadSelector:@selector(triggerDataCheck:)
toTarget:self
withObject:delegate.threadedContext];
}
-(void)startCommandLineSync
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Pweep" inManagedObjectContext:cmdContext];
if (!entity) {
NSLog(@"entity is null.");
}
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"UpdatedAt" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
// Set up a pointer to hold an error, in case the fetch request fails.
NSError *error = nil;
NSArray *fetchResults = [cmdContext executeFetchRequest:request error:&error];
[request release];
if (fetchResults == nil) {
// Some amount of error handling here.
} else if ([fetchResults count] > 1) {
Pweep *latestUpdated = [fetchResults objectAtIndex:0];
if (latestUpdated.UpdatedAt) {
[self checkForNewData:[NSDictionary dictionaryWithObjectsAndKeys:latestUpdated.UpdatedAt, @"updatedAt", [NSNumber numberWithBool:YES], @"sync", nil]];
}
}
}
#pragma mark -
#pragma mark Data Check
-(void)triggerDataCheck:(NSManagedObjectContext*)context
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// We need to find the latest from the database
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Pweep" inManagedObjectContext:context]];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"UpdatedAt" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
// Set up a pointer to hold an error, in case the fetch request fails.
NSError *error = nil;
NSArray *fetchResults = [context executeFetchRequest:request error:&error];
[request release];
if (fetchResults == nil) {
// Some amount of error handling here.
} else if ([fetchResults count] > 1) {
Pweep *latestUpdated = [fetchResults objectAtIndex:0];
if (latestUpdated.UpdatedAt) {
[self performSelectorOnMainThread:@selector(checkForNewData:)
withObject:[NSDictionary dictionaryWithObjectsAndKeys:latestUpdated.UpdatedAt, @"updatedAt", [NSNumber numberWithBool:NO], @"sync", nil]
waitUntilDone:NO];
}
}
[pool release];
}
//-(void)checkForNewData:(NSDate*)lastUpdate synchronously:(BOOL)synchron
-(void)checkForNewData:(NSDictionary*)dict
{
// no community feedback in open source version.
}
#pragma mark -
#pragma mark NSURLConnection
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
[updateConnection release];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
if (!connData) {
connData = [[NSMutableData alloc] initWithCapacity:0];
[connData retain];
}
[connData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *jsonString = [[NSString alloc] initWithData:connData encoding:NSUTF8StringEncoding];
[self updateDatabaseWithJSON:jsonString];
//NSLog(@"jsonString -> %@", jsonString);
[jsonString release];
[connData release];
[updateConnection release];
}
-(void)updateDatabaseWithJSON:(NSString*)jsonString
{
SBJSON *json = [[SBJSON alloc] init];
APIScannerAppDelegate *delegate = (APIScannerAppDelegate*)[[NSApplication sharedApplication] delegate];
NSManagedObjectContext* useThisContext;
if (cmdContext) {
useThisContext = cmdContext;
} else {
useThisContext = delegate.managedObjectContext;
}
NSArray *pweeps = [json objectWithString:jsonString];
//NSLog(@"Found %i Pweeps...", [pweeps count]);
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
for(NSDictionary *dict in pweeps) {
NSDictionary *pweep = [dict objectForKey:@"pweep"];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Pweep" inManagedObjectContext:useThisContext]];
[request setPredicate:[NSPredicate predicateWithFormat:@"PweepID == %i", [[pweep objectForKey:@"id"] intValue]]];
NSError *fetchError = nil;
NSArray *results = [useThisContext executeFetchRequest:request error:&fetchError];
if ([results count] > 0) {
Pweep* oldPweep = [results objectAtIndex:0];
[oldPweep setLevel:[NSNumber numberWithInt:[[pweep objectForKey:@"level"] intValue]]];
[oldPweep setLevel_Weight:[NSNumber numberWithFloat:[[pweep objectForKey:@"level_weight"] floatValue]]];
[oldPweep setSDK_Version:[pweep objectForKey:@"sdk_version"]];
[oldPweep setUpdatedAt:[df dateFromString:[pweep objectForKey:@"updated_at"]]];
NSError *saveError = nil;
if (![useThisContext save:&saveError]) {
NSLog(@"Error with db save -> %@", [saveError localizedDescription]);
} else {
//NSLog(@"%@ added;", newStation.Name);
}
} else {
// this is a new pweep. Make an entry in the database for it.
Pweep *newPweep = (Pweep*)[NSEntityDescription insertNewObjectForEntityForName:@"Pweep"
inManagedObjectContext:useThisContext];
[newPweep setLevel:[NSNumber numberWithInt:[[pweep objectForKey:@"level"] intValue]]];
[newPweep setLevel_Weight:[NSNumber numberWithFloat:[[pweep objectForKey:@"level_weight"] floatValue]]];
[newPweep setSDK_Version:[pweep objectForKey:@"sdk_version"]];
[newPweep setSignature:[pweep objectForKey:@"signature"]];
[newPweep setPweepID:[NSNumber numberWithInt:[[pweep objectForKey:@"id"] intValue]]];
[newPweep setUpdatedAt:[df dateFromString:[pweep objectForKey:@"updated_at"]]];
NSError *saveError = nil;
if (![useThisContext save:&saveError]) {
NSLog(@"Error with db save -> %@", [saveError localizedDescription]);
} else {
//NSLog(@"%@ added;", newStation.Name);
}
//NSLog(@"pweep added to database");
}
}
//NSLog(@"finished updating database...");
}
-(void)dealloc
{
[cmdContext release];
[super dealloc];
}
@end