Skip to content
Browse files

Possibly fixed a syncing issue where, after an indeterminate number o…

…f syncs, syncing would spin on and on forever
  • Loading branch information...
1 parent 4152341 commit edade0f85d627a009ecc8c46951b40ca339a78df Michael Fey committed Sep 23, 2010
View
266 Daemon/Classes/ZSyncDaemon.m
@@ -17,42 +17,44 @@ @implementation ZSyncDaemon
static int GetBSDProcessList(kinfo_proc **procList, size_t *procCount)
{
- int err;
- kinfo_proc * result;
- bool done;
- static const int name[] = { CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0 };
- size_t length;
-
- assert( procList != NULL);
+ int err;
+ kinfo_proc *result;
+ bool done;
+ static const int name[] = {
+ CTL_KERN, KERN_PROC, KERN_PROC_ALL, 0
+ };
+ size_t length;
+
+ assert(procList != NULL);
assert(*procList == NULL);
assert(procCount != NULL);
-
+
*procCount = 0;
-
+
result = NULL;
done = false;
do {
assert(result == NULL);
-
+
length = 0;
- err = sysctl( (int *) name, (sizeof(name) / sizeof(*name)) - 1,
- NULL, &length,
- NULL, 0);
+ err = sysctl( (int *)name, (sizeof(name) / sizeof(*name)) - 1,
+ NULL, &length,
+ NULL, 0);
if (err == -1) {
err = errno;
}
-
+
if (err == 0) {
result = malloc(length);
if (result == NULL) {
err = ENOMEM;
}
}
-
+
if (err == 0) {
- err = sysctl( (int *) name, (sizeof(name) / sizeof(*name)) - 1,
- result, &length,
- NULL, 0);
+ err = sysctl( (int *)name, (sizeof(name) / sizeof(*name)) - 1,
+ result, &length,
+ NULL, 0);
if (err == -1) {
err = errno;
}
@@ -65,8 +67,8 @@ static int GetBSDProcessList(kinfo_proc **procList, size_t *procCount)
err = 0;
}
}
- } while (err == 0 && ! done);
-
+ } while (err == 0 && !done);
+
if (err != 0 && result != NULL) {
free(result);
result = NULL;
@@ -75,41 +77,41 @@ static int GetBSDProcessList(kinfo_proc **procList, size_t *procCount)
if (err == 0) {
*procCount = length / sizeof(kinfo_proc);
}
-
+
assert( (err == 0) == (*procList != NULL) );
-
+
return err;
}
-+ (NSBundle*)myBundle
++ (NSBundle *)myBundle
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"ZSyncInstaller" ofType:@"bundle"];
return [NSBundle bundleWithPath:path];
}
-+ (NSBundle*)daemonBundle
++ (NSBundle *)daemonBundle
{
NSBundle *myBundle = [self myBundle];
NSString *path = [myBundle pathForResource:@"ZSyncDaemon" ofType:@"app"];
return [NSBundle bundleWithPath:path];
}
-+ (NSString*)basePath
++ (NSString *)basePath
{
- //Build our standard install path
+ // Build our standard install path
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : NSTemporaryDirectory();
basePath = [basePath stringByAppendingPathComponent:@"ZSyncDaemon"];
return basePath;
}
-+ (NSString*)applicationPath
++ (NSString *)applicationPath
{
NSString *basePath = [self basePath];
return [basePath stringByAppendingPathComponent:@"ZSyncDaemon.app"];
}
-+ (BOOL)checkBasePath:(NSString*)basePath error:(NSError**)error;
++ (BOOL)checkBasePath:(NSString *)basePath error:(NSError **)error;
{
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDirectory = NO;
@@ -119,13 +121,15 @@ + (BOOL)checkBasePath:(NSString*)basePath error:(NSError**)error;
if (!isDirectory) {
NSString *errorDesc = [NSString stringWithFormat:@"Unknown file at base installation path: %@", basePath];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
- if (error != NULL) *error = [NSError errorWithDomain:@"ZSync" code:1123 userInfo:dictionary];
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:@"ZSync" code:1123 userInfo:dictionary];
+ }
return NO;
}
return YES;
}
-+ (BOOL)checkApplicationPath:(NSString*)applicationPath error:(NSError**)error;
++ (BOOL)checkApplicationPath:(NSString *)applicationPath error:(NSError **)error;
{
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDirectory = NO;
@@ -135,13 +139,15 @@ + (BOOL)checkApplicationPath:(NSString*)applicationPath error:(NSError**)error;
if (!isDirectory) {
NSString *errorDesc = [NSString stringWithFormat:@"Unknown file at daemon application installation path: %@", applicationPath];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
- if (error != NULL) *error = [NSError errorWithDomain:@"ZSync" code:1124 userInfo:dictionary];
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:@"ZSync" code:1124 userInfo:dictionary];
+ }
return NO;
}
return YES;
}
-+ (BOOL)isDaemonInstalled:(NSError**)error;
++ (BOOL)isDaemonInstalled:(NSError **)error;
{
NSString *basePath = [self basePath];
if (![self checkBasePath:basePath error:error]) {
@@ -156,53 +162,61 @@ + (BOOL)isDaemonInstalled:(NSError**)error;
return [self checkApplicationPath:applicationPath error:error];
}
-+ (BOOL)installDaemon:(NSError**)error;
++ (BOOL)installDaemon:(NSError **)error;
{
NSString *basePath = [self basePath];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDirectory = NO;
-
+
if (![fileManager fileExistsAtPath:basePath isDirectory:&isDirectory]) {
if (![[NSFileManager defaultManager] createDirectoryAtPath:basePath withIntermediateDirectories:YES attributes:nil error:error]) {
return NO;
}
} else if (!isDirectory) {
NSString *errorDesc = [NSString stringWithFormat:@"Unknown file at base installation path: %@", basePath];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
- if (error != NULL) *error = [NSError errorWithDomain:@"ZSync" code:1123 userInfo:dictionary];
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:@"ZSync" code:1123 userInfo:dictionary];
+ }
return NO;
}
-
+
NSString *myBundlePath = [[self daemonBundle] bundlePath];
NSString *applicationPath = [self applicationPath];
-
- if (![fileManager copyItemAtPath:myBundlePath toPath:applicationPath error:error]) return NO;
-
+
+ if (![fileManager copyItemAtPath:myBundlePath toPath:applicationPath error:error]) {
+ return NO;
+ }
+
NSURL *itemURL = [NSURL fileURLWithPath:applicationPath];
-
+
LSSharedFileListRef loginListRef = LSSharedFileListCreate(NULL, kLSSharedFileListSessionLoginItems, NULL);
if (!loginListRef) {
NSString *errorDesc = @"Failed to retrieve login list for startup injection";
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
- if (error != NULL) *error = [NSError errorWithDomain:@"ZSync" code:1130 userInfo:dictionary];
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:@"ZSync" code:1130 userInfo:dictionary];
+ }
return NO;
}
-
+
LSSharedFileListItemRef loginItemRef = LSSharedFileListInsertItemURL(loginListRef, kLSSharedFileListItemLast, NULL, NULL, (CFURLRef)itemURL, NULL, NULL);
if (!loginItemRef) {
NSString *errorDesc = @"Failed to create login item for startup injection";
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
- if (error != NULL) *error = [NSError errorWithDomain:@"ZSync" code:1130 userInfo:dictionary];
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:@"ZSync" code:1130 userInfo:dictionary];
+ }
return NO;
}
-
+
CFRelease(loginItemRef);
CFRelease(loginListRef);
-
+
return YES;
}
-+ (BOOL)stopDaemon:(NSError**)error
++ (BOOL)stopDaemon:(NSError **)error
{
NSString *appName = [[[self daemonBundle] infoDictionary] objectForKey:@"CFBundleExecutable"];
NSString *command = [NSString stringWithFormat:@"tell application \"%@\" to quit", appName];
@@ -219,39 +233,43 @@ + (BOOL)stopDaemon:(NSError**)error
return YES;
}
-+ (BOOL)updateInstalledApplication:(NSError**)error;
++ (BOOL)updateInstalledApplication:(NSError **)error;
{
NSString *appName = [[[self myBundle] infoDictionary] objectForKey:@"CFBundleExecutable"];
-
- if ([self isDaemonRunning] && ![self stopDaemon:error]) return NO;
-
+
+ if ([self isDaemonRunning] && ![self stopDaemon:error]) {
+ return NO;
+ }
+
NSString *myBundlePath = [[self myBundle] bundlePath];
-
+
NSString *applicationPath = [self applicationPath];
NSString *basePath = [self basePath];
NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
- if (![workspace performFileOperation:NSWorkspaceRecycleOperation
- source:basePath
- destination:@""
- files:[NSArray arrayWithObject:appName]
- tag:NULL]) {
+ if (![workspace performFileOperation:NSWorkspaceRecycleOperation
+ source:basePath
+ destination:@""
+ files:[NSArray arrayWithObject:appName]
+ tag:NULL]) {
NSString *errorDesc = [NSString stringWithFormat:@"Failed to move old app version to the trash"];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
- if (error != NULL) *error = [NSError errorWithDomain:@"ZSync" code:1126 userInfo:dictionary];
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:@"ZSync" code:1126 userInfo:dictionary];
+ }
return NO;
}
-
+
NSFileManager *fileManager = [NSFileManager defaultManager];
return [fileManager copyItemAtPath:myBundlePath toPath:applicationPath error:error];
}
-+ (NSString*)pluginPath
++ (NSString *)pluginPath
{
NSString *basePath = [self basePath];
return [basePath stringByAppendingPathComponent:@"Plugins"];
}
-+ (BOOL)isPluginInstalled:(NSString*)path error:(NSError**)error
++ (BOOL)isPluginInstalled:(NSString *)path error:(NSError **)error
{
NSString *pluginPath = [self pluginPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
@@ -262,92 +280,104 @@ + (BOOL)isPluginInstalled:(NSString*)path error:(NSError**)error
if (!isDirectory) {
NSString *errorDesc = [NSString stringWithFormat:@"Unknown file at plugin installation path: %@", pluginPath];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
- if (error != NULL) *error = [NSError errorWithDomain:@"ZSync" code:1123 userInfo:dictionary];
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:@"ZSync" code:1123 userInfo:dictionary];
+ }
return NO;
}
-
+
NSString *finalPath = [pluginPath stringByAppendingPathComponent:[path lastPathComponent]];
if (![fileManager fileExistsAtPath:finalPath isDirectory:&isDirectory]) {
return NO;
}
return YES;
}
-+ (BOOL)installPluginAtPath:(NSString*)path intoDaemonWithError:(NSError**)error;
++ (BOOL)installPluginAtPath:(NSString *)path intoDaemonWithError:(NSError **)error;
{
if (![[path pathExtension] isEqualToString:@"zsyncPlugin"]) {
NSString *errorDesc = [NSString stringWithFormat:@"url is not a valid ZSync plugin: %@", path];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
- if (error != NULL) *error = [NSError errorWithDomain:@"ZSync" code:1125 userInfo:dictionary];
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:@"ZSync" code:1125 userInfo:dictionary];
+ }
return NO;
}
-
+
BOOL isDaemonInstalled = [self isDaemonInstalled:error];
-
+
if (!isDaemonInstalled && *error) {
return NO;
}
-
+
if (!isDaemonInstalled) {
- if (![self installDaemon:error]) return NO;
+ if (![self installDaemon:error]) {
+ return NO;
+ }
} else {
NSDictionary *infoDictionary = [[self daemonBundle] infoDictionary];
NSInteger currentVersionNumber = [[infoDictionary objectForKey:ZSyncVersionNumber] integerValue];
-
+
NSBundle *installed = [NSBundle bundleWithPath:[self applicationPath]];
NSInteger installedVersionNumber = [[[installed infoDictionary] objectForKey:ZSyncVersionNumber] integerValue];
-
- if (installedVersionNumber < currentVersionNumber && ![self updateInstalledApplication:error]) return NO;
+
+ if (installedVersionNumber < currentVersionNumber && ![self updateInstalledApplication:error]) {
+ return NO;
+ }
}
-
- //Is plugin already installed?
+
+ // Is plugin already installed?
if ([self isPluginInstalled:path error:error]) {
- if (![self isDaemonRunning]) [self startDaemon];
+ if (![self isDaemonRunning]) {
+ [self startDaemon];
+ }
return YES;
}
-
- //Shutdown the daemon to install the plugin
+
+ // Shutdown the daemon to install the plugin
if ([self isDaemonRunning] && ![self stopDaemon:error]) {
return NO;
}
-
- //Install the plugin
+
+ // Install the plugin
NSString *pluginPath = [self pluginPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isDirectory = NO;
-
+
if (![fileManager fileExistsAtPath:pluginPath isDirectory:&isDirectory]) {
if (![[NSFileManager defaultManager] createDirectoryAtPath:pluginPath withIntermediateDirectories:YES attributes:nil error:error]) {
return NO;
}
} else if (!isDirectory) {
NSString *errorDesc = [NSString stringWithFormat:@"Unknown file at base installation path: %@", pluginPath];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
- if (error != NULL) *error = [NSError errorWithDomain:@"ZSync" code:1123 userInfo:dictionary];
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:@"ZSync" code:1123 userInfo:dictionary];
+ }
return NO;
}
-
+
pluginPath = [pluginPath stringByAppendingPathComponent:[path lastPathComponent]];
if (![fileManager copyItemAtPath:path toPath:pluginPath error:error]) {
return NO;
}
-
- //Start the daemon back up
+
+ // Start the daemon back up
[self startDaemon];
-
+
return YES;
}
+ (BOOL)isDaemonRunning;
{
NSDictionary *infoDictionary = [[self daemonBundle] infoDictionary];
NSString *appName = [infoDictionary objectForKey:@"CFBundleExecutable"];
-
+
kinfo_proc *procList = NULL;
size_t procCount;
int err = GetBSDProcessList(&procList, &procCount);
NSAssert1(err == 0, @"Error fetching proc list: %i", err);
-
+
int index;
for (index = procCount - 1; index >= 0; --index) {
NSString *name = [[NSString alloc] initWithCString:procList[index].kp_proc.p_comm];
@@ -357,7 +387,7 @@ + (BOOL)isDaemonRunning;
}
[name release], name = nil;
}
-
+
return NO;
}
@@ -368,92 +398,106 @@ + (void)startDaemon;
[workspace launchApplication:appPath];
}
-+ (NSManagedObjectContext*)managedObjectContext:(NSError**)error
++ (NSManagedObjectContext *)managedObjectContext:(NSError **)error
{
NSBundle *appBundle = [NSBundle bundleWithPath:[self applicationPath]];
if (!appBundle) {
NSString *errorDesc = [NSString stringWithFormat:@"ZSyncDaemon is not installed: %@", [self applicationPath]];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
- if (error != NULL) *error = [NSError errorWithDomain:@"ZSync" code:1129 userInfo:dictionary];
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:@"ZSync" code:1129 userInfo:dictionary];
+ }
return nil;
}
NSString *path = [appBundle pathForResource:@"ZSyncModel" ofType:@"mom"];
NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:[NSURL fileURLWithPath:path]];
-
+
if (!model) {
NSString *errorDesc = [NSString stringWithFormat:@"Failed to find model at path: %@", path];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
- if (error != NULL) *error = [NSError errorWithDomain:@"ZSync" code:1127 userInfo:dictionary];
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:@"ZSync" code:1127 userInfo:dictionary];
+ }
[model release], model = nil;
return nil;
}
-
+
NSString *basePath = [ZSyncDaemon basePath];
if (![ZSyncDaemon checkBasePath:basePath error:error]) {
[model release], model = nil;
return nil;
}
-
+
NSString *filePath = [basePath stringByAppendingPathComponent:@"SyncHistory.sqlite"];
-
+
NSPersistentStoreCoordinator *psc = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
-
+
if (![psc addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:filePath] options:nil error:error]) {
[psc release], psc = nil;
[model release], model = nil;
return nil;
}
-
+
NSManagedObjectContext *moc = [[NSManagedObjectContext alloc] init];
[moc setPersistentStoreCoordinator:psc];
[psc release], psc = nil;
[model release], model = nil;
return [moc autorelease];
}
-+ (BOOL)deregisterDeviceForUUID:(NSString*)uuid error:(NSError**)error;
++ (BOOL)deregisterDeviceForUUID:(NSString *)uuid error:(NSError **)error;
{
NSArray *components = [uuid componentsSeparatedByString:@":"];
if ([components count] != 2) {
NSString *errorDesc = [NSString stringWithFormat:@"Invalid UUID: %@", uuid];
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:errorDesc forKey:NSLocalizedDescriptionKey];
- if (error != NULL) *error = [NSError errorWithDomain:@"ZSync" code:1128 userInfo:dictionary];
+ if (error != NULL) {
+ *error = [NSError errorWithDomain:@"ZSync" code:1128 userInfo:dictionary];
+ }
return NO;
}
NSManagedObjectContext *moc = [self managedObjectContext:error];
- if (!moc) return NO;
-
+ if (!moc) {
+ return NO;
+ }
+
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Application" inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:@"uuid == %@ && device.uuid == %@", [components objectAtIndex:1], [components objectAtIndex:0]]];
-
+
id result = [[moc executeFetchRequest:request error:error] lastObject];
[request release], request = nil;
- if (!result && error) return NO;
- if (!result) return YES;
-
+ if (!result && error) {
+ return NO;
+ }
+ if (!result) {
+ return YES;
+ }
+
ISyncClient *client = [[ISyncManager sharedManager] clientWithIdentifier:[components objectAtIndex:1]];
if (client) {
[[ISyncManager sharedManager] unregisterClient:client];
}
-
+
[moc deleteObject:result];
-
+
return [moc save:error];
}
-+ (NSArray*)devicesRegisteredForSchema:(NSString*)schema error:(NSError**)error;
++ (NSArray *)devicesRegisteredForSchema:(NSString *)schema error:(NSError **)error;
{
NSManagedObjectContext *moc = [self managedObjectContext:error];
- if (!moc) return nil;
-
+ if (!moc) {
+ return nil;
+ }
+
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Application" inManagedObjectContext:moc]];
[request setPredicate:[NSPredicate predicateWithFormat:@"schema == %@", schema]];
-
+
NSArray *applications = [moc executeFetchRequest:request error:error];
[request release], request = nil;
-
+
NSMutableArray *deviceArray = [NSMutableArray array];
for (NSManagedObject *applicationMO in applications) {
NSManagedObject *deviceMO = [applicationMO valueForKey:@"device"];
View
64 DesktopCode/ZSyncConnectionDelegate.m
@@ -46,7 +46,7 @@ - (NSManagedObjectModel *)managedObjectModel
NSArray *bundles = [NSArray arrayWithObject:pluginBundle];
managedObjectModel = [[NSManagedObjectModel mergedModelFromBundles:bundles] retain];
}
-
+
return managedObjectModel;
}
@@ -55,7 +55,7 @@ - (NSPersistentStoreCoordinator *)persistentStoreCoordinator
if (!persistentStoreCoordinator) {
persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
}
-
+
return persistentStoreCoordinator;
}
@@ -66,7 +66,7 @@ - (NSManagedObjectContext *)managedObjectContext
[managedObjectContext setPersistentStoreCoordinator:[self persistentStoreCoordinator]];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mocSaved:) name:NSManagedObjectContextDidSaveNotification object:managedObjectContext];
}
-
+
return managedObjectContext;
}
@@ -75,7 +75,7 @@ - (NSMutableArray *)storeFileIdentifiers
if (!storeFileIdentifiers) {
storeFileIdentifiers = [[NSMutableArray alloc] init];
}
-
+
return storeFileIdentifiers;
}
@@ -84,7 +84,7 @@ - (id)pairingCodeWindowController
if (!pairingCodeWindowController) {
pairingCodeWindowController = [[PairingCodeWindowController alloc] initWithDelegate:self];
}
-
+
return pairingCodeWindowController;
}
@@ -135,10 +135,10 @@ - (void)addPersistentStore:(BLIPRequest *)request
NSError *error = nil;
NSPersistentStore *persistentStore = nil;
persistentStore = [[self persistentStoreCoordinator] addPersistentStoreWithType:[request valueOfProperty:zsStoreType]
- configuration:[request valueOfProperty:zsStoreConfiguration]
- URL:[NSURL fileURLWithPath:filePath]
- options:nil
- error:&error];
+ configuration:[request valueOfProperty:zsStoreConfiguration]
+ URL:[NSURL fileURLWithPath:filePath]
+ options:nil
+ error:&error];
ZAssert(persistentStore != nil, @"Error loading persistent store: %@", [error localizedDescription]);
@@ -173,7 +173,7 @@ - (void)transferStoresToDevice
BLIPRequest *request = [BLIPRequest requestWithBody:data properties:requestPropertiesDictionary];
[request setCompressed:YES];
[[self connection] sendRequest:request];
-
+
[data release], data = nil;
[requestPropertiesDictionary release], requestPropertiesDictionary = nil;
@@ -339,10 +339,10 @@ - (void)registerSyncClient:(BLIPRequest *)request
[response send];
return;
}
-
+
NSString *deviceName = [request valueOfProperty:zsDeviceName];
NSString *deviceUUID = [request valueOfProperty:zsDeviceGUID];
-
+
NSManagedObject *device = [[ZSyncHandler shared] registerDevice:deviceUUID withName:deviceName];
[self setSyncApplication:[[ZSyncHandler shared] registerApplication:schemaIdentifier withClient:clientID withDevice:device]];
}
@@ -507,28 +507,26 @@ - (BOOL)connection:(BLIPConnection *)con receivedRequest:(BLIPRequest *)request
DLog(@"%s zsActionRequestPairing", __PRETTY_FUNCTION__);
[self setPairingCode:[request bodyString]];
[self showCodeWindow];
- [response setValue:zsActID(zsActionRequestPairing) ofProperty:zsAction];
- [response send];
return YES;
- case zsActionAuthenticatePairing:
- DLog(@"%s zsActionAuthenticatePairing", __PRETTY_FUNCTION__);
- ALog(@"Is this ever called?");
- if ([[self pairingCode] isEqualToString:[request bodyString]]) {
- DLog(@"%s passed '%@' '%@'", __PRETTY_FUNCTION__, [request bodyString], [self pairingCode]);
- // TODO: Register the unique ID of this service
- [response setValue:zsActID(zsActionAuthenticatePassed) ofProperty:zsAction];
- [response setValue:[[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID] ofProperty:zsServerUUID];
- [response setValue:[[ZSyncHandler shared] serverName] ofProperty:zsServerName];
- [response send];
- [[self pairingCodeWindowController] close];
- [self setPairingCodeWindowController:nil];
- } else {
- DLog(@"%s failed '%@' '%@'", __PRETTY_FUNCTION__, [request bodyString], [self pairingCode]);
- [response setValue:zsActID(zsActionAuthenticateFailed) ofProperty:zsAction];
- [response send];
- }
- return YES;
+// case zsActionAuthenticatePairing:
+// DLog(@"%s zsActionAuthenticatePairing", __PRETTY_FUNCTION__);
+// ALog(@"Is this ever called?");
+// if ([[self pairingCode] isEqualToString:[request bodyString]]) {
+// DLog(@"%s passed '%@' '%@'", __PRETTY_FUNCTION__, [request bodyString], [self pairingCode]);
+// // TODO: Register the unique ID of this service
+// [response setValue:zsActID(zsActionAuthenticatePassed) ofProperty:zsAction];
+// [response setValue:[[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID] ofProperty:zsServerUUID];
+// [response setValue:[[ZSyncHandler shared] serverName] ofProperty:zsServerName];
+// [response send];
+// [[self pairingCodeWindowController] close];
+// [self setPairingCodeWindowController:nil];
+// } else {
+// DLog(@"%s failed '%@' '%@'", __PRETTY_FUNCTION__, [request bodyString], [self pairingCode]);
+// [response setValue:zsActID(zsActionAuthenticateFailed) ofProperty:zsAction];
+// [response send];
+// }
+// return YES;
case zsActionVerifyPairing:
// TODO: This method should verify that the client is paired properly, responding accordingly
@@ -547,7 +545,7 @@ - (BOOL)connection:(BLIPConnection *)con receivedRequest:(BLIPRequest *)request
case zsActionCancelPairing:
DLog(@"%s zsActionCancelPairing", __PRETTY_FUNCTION__);
- [[self pairingCodeWindowController] close];
+ [[self pairingCodeWindowController] close];
return YES;
default:
View
28 DesktopCode/ZSyncHandler.m
@@ -176,37 +176,41 @@ - (NSManagedObject *)registerDevice:(NSString *)deviceUUID withName:(NSString *)
}
[device setValue:deviceName forKey:@"name"];
+
+ error = nil;
+ ZAssert([[self managedObjectContext] save:&error], @"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
+
return device;
}
- (NSManagedObject *)registerApplication:(NSString *)schema withClient:(NSString *)clientUUID withDevice:(NSManagedObject *)device;
{
DLog(@"%s", __PRETTY_FUNCTION__);
// Find any other clients registered for this device with this schema and remove them
- NSSet *clients = [[device valueForKey:@"applications"] filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"uuid != %@", clientUUID]];
- for (NSManagedObject *client in clients) {
- ISyncClient *syncClient = [[ISyncManager sharedManager] clientWithIdentifier:[client valueForKey:@"uuid"]];
+ NSSet *applications = [[device valueForKey:@"applications"] filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"uuid != %@", clientUUID]];
+ for (NSManagedObject *application in applications) {
+ ISyncClient *syncClient = [[ISyncManager sharedManager] clientWithIdentifier:[application valueForKey:@"uuid"]];
if (syncClient) {
[[ISyncManager sharedManager] unregisterClient:syncClient];
}
- [[self managedObjectContext] deleteObject:client];
+ [[self managedObjectContext] deleteObject:application];
}
- id client = [[[device valueForKey:@"applications"] filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"uuid == %@", clientUUID]] anyObject];
+ id application = [[[device valueForKey:@"applications"] filteredSetUsingPredicate:[NSPredicate predicateWithFormat:@"uuid == %@", clientUUID]] anyObject];
- if (client) {
- return client;
+ if (application) {
+ return application;
}
- client = [NSEntityDescription insertNewObjectForEntityForName:@"Application" inManagedObjectContext:[self managedObjectContext]];
- [client setValue:device forKey:@"device"];
- [client setValue:clientUUID forKey:@"uuid"];
- [client setValue:schema forKey:@"schema"];
+ application = [NSEntityDescription insertNewObjectForEntityForName:@"Application" inManagedObjectContext:[self managedObjectContext]];
+ [application setValue:device forKey:@"device"];
+ [application setValue:clientUUID forKey:@"uuid"];
+ [application setValue:schema forKey:@"schema"];
NSError *error = nil;
ZAssert([[self managedObjectContext] save:&error], @"Error saving context: %@\n%@", [error localizedDescription], [error userInfo]);
- return client;
+ return application;
}
- (NSBundle *)pluginForSchema:(NSString *)schema;
View
5 DeviceCode/ZSyncTouchHandler.h
@@ -158,7 +158,8 @@ typedef enum {
@property (nonatomic, assign) ZSyncServerAction serverAction;
@property (nonatomic, retain) ServerBrowser *serviceBrowser;
-@property (nonatomic, assign) BLIPConnection *connection;
+@property (nonatomic, retain) BLIPConnection *connection;
+//@property (nonatomic, assign) BLIPConnection *connection;
@property (nonatomic, assign) NSInteger majorVersionNumber;
@property (nonatomic, assign) NSInteger minorVersionNumber;
@property (nonatomic, copy) NSString *passcode;
@@ -179,7 +180,7 @@ typedef enum {
- (void)requestSync;
- (void)stopRequestingSync;
- (void)requestPairing:(ZSyncService *)server;
-- (void)authenticatePairing:(NSString *)code;
+//- (void)authenticatePairing:(NSString *)code;
- (void)cancelPairing;
- (void)disconnectPairing;
View
417 DeviceCode/ZSyncTouchHandler.m
@@ -40,6 +40,8 @@ @interface ZSyncTouchHandler ()
- (void)requestDeregistration;
- (void)uploadDataToServer;
- (void)startServerSearch;
+- (NSString *)syncGUID;
+- (NSString *)schemaID;
@property (nonatomic, assign) id delegate;
@property (nonatomic, retain) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@@ -88,6 +90,7 @@ - (void)requestSync
ZAssert([self serverAction] == ZSyncServerActionNoActivity, @"Attempt to sync while another action is active");
[self setServerAction:ZSyncServerActionSync];
+
if ([self connection]) {
[self uploadDataToServer];
} else {
@@ -107,37 +110,38 @@ - (void)requestPairing:(ZSyncService *)server
{
DLog(@"%s", __PRETTY_FUNCTION__);
- NSNetService *service = [server service];
[self setServerAction:ZSyncServerActionSync];
+ NSNetService *service = [server service];
+
BLIPConnection *conn = [[BLIPConnection alloc] initToNetService:service];
- [self setConnection:conn];
[conn setDelegate:self];
[conn open];
+ [self setConnection:conn];
[conn release], conn = nil;
}
-- (void)authenticatePairing:(NSString *)pairingCode;
-{
- DLog(@"%s", __PRETTY_FUNCTION__);
- if (![self connection]) {
- return;
- }
-
- // Start a pairing request
- DLog(@"sending a pairing code");
- NSString *schemaID = [[[NSBundle mainBundle] infoDictionary] objectForKey:zsSchemaIdentifier];
-
- NSMutableDictionary *requestPropertiesDictionary = [NSMutableDictionary dictionary];
- [requestPropertiesDictionary setValue:zsActID(zsActionAuthenticatePairing) forKey:zsAction];
- [requestPropertiesDictionary setValue:[[UIDevice currentDevice] uniqueIdentifier] forKey:zsDeviceGUID];
- [requestPropertiesDictionary setValue:schemaID forKey:zsSchemaIdentifier];
-
- NSData *pairingCodeData = [pairingCode dataUsingEncoding:NSUTF8StringEncoding];
-
- BLIPRequest *request = [BLIPRequest requestWithBody:pairingCodeData properties:requestPropertiesDictionary];
- [[self connection] sendRequest:request];
-}
+// - (void)authenticatePairing:(NSString *)pairingCode;
+// {
+// DLog(@"%s", __PRETTY_FUNCTION__);
+// if (![self connection]) {
+// return;
+// }
+//
+// // Start a pairing request
+// DLog(@"sending a pairing code");
+// NSString *schemaID = [[[NSBundle mainBundle] infoDictionary] objectForKey:zsSchemaIdentifier];
+//
+// NSMutableDictionary *requestPropertiesDictionary = [NSMutableDictionary dictionary];
+// [requestPropertiesDictionary setValue:zsActID(zsActionAuthenticatePairing) forKey:zsAction];
+// [requestPropertiesDictionary setValue:[[UIDevice currentDevice] uniqueIdentifier] forKey:zsDeviceGUID];
+// [requestPropertiesDictionary setValue:schemaID forKey:zsSchemaIdentifier];
+//
+// NSData *pairingCodeData = [pairingCode dataUsingEncoding:NSUTF8StringEncoding];
+//
+// BLIPRequest *request = [BLIPRequest requestWithBody:pairingCodeData properties:requestPropertiesDictionary];
+// [[self connection] sendRequest:request];
+// }
- (void)cancelPairing;
{
@@ -146,14 +150,11 @@ - (void)cancelPairing;
return;
}
- // Start a pairing request
DLog(@"sending a pairing cancel");
- NSString *schemaID = [[[NSBundle mainBundle] infoDictionary] objectForKey:zsSchemaIdentifier];
-
NSMutableDictionary *requestPropertiesDictionary = [NSMutableDictionary dictionary];
[requestPropertiesDictionary setValue:zsActID(zsActionCancelPairing) forKey:zsAction];
[requestPropertiesDictionary setValue:[[UIDevice currentDevice] uniqueIdentifier] forKey:zsDeviceGUID];
- [requestPropertiesDictionary setValue:schemaID forKey:zsSchemaIdentifier];
+ [requestPropertiesDictionary setValue:[self schemaID] forKey:zsSchemaIdentifier];
BLIPRequest *request = [BLIPRequest requestWithBody:nil properties:requestPropertiesDictionary];
[[self connection] sendRequest:request];
@@ -169,7 +170,7 @@ - (void)disconnectPairing;
[[self connection] close];
[self setConnection:nil];
}
-
+
[self setServerAction:ZSyncServerActionNoActivity];
}
@@ -188,7 +189,7 @@ - (void)deregister
}
}
- if (![[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID] || ![[NSUserDefaults standardUserDefaults] valueForKey:zsDeviceGUID]) {
+ if (![[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID]) {
if ([[self delegate] respondsToSelector:@selector(zSync:errorOccurred:)]) {
NSString *errorString = [NSString stringWithFormat:@"Client is not registered with a server", [self serverAction]];
NSDictionary *dict = [NSDictionary dictionaryWithObject:errorString forKey:NSLocalizedDescriptionKey];
@@ -223,6 +224,7 @@ - (void)applicationWillTerminate:(NSNotification *)notification
DLog(@"closing connection");
if ([self connection]) {
[[self connection] close];
+ [self setConnection:nil];
}
if ([self serviceBrowser]) {
@@ -271,6 +273,7 @@ - (void)networkTimeout:(NSTimer *)timer
if ([[self delegate] respondsToSelector:@selector(zSyncServerUnavailable:)]) {
[[self delegate] zSyncServerUnavailable:self];
}
+
[[timer userInfo] stopNotifer];
}
@@ -287,12 +290,13 @@ - (void)reachabilityChanged:(NSNotification *)notification
[networkTimer invalidate], networkTimer = nil;
NSString *serverUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID];
if (serverUUID) {
- networkTimer = [NSTimer scheduledTimerWithTimeInterval:10.0
+ networkTimer = [NSTimer scheduledTimerWithTimeInterval:15.0
target:self
selector:@selector(networkTimeout:)
userInfo:nil
repeats:NO];
}
+
[[self serviceBrowser] start];
}
@@ -302,6 +306,7 @@ - (void)reachabilityChanged:(NSNotification *)notification
- (NSString *)cachePath
{
DLog(@"%s", __PRETTY_FUNCTION__);
+
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filePath = [paths objectAtIndex:0];
@@ -318,9 +323,6 @@ - (void)startServerSearch
[self setServiceBrowser:nil];
}
-// _serviceBrowser = [[ServerBrowser alloc] init];
-// _serviceBrowser.delegate = self;
-
Reachability *reachability = [Reachability reachabilityForLocalWiFi];
if ([reachability currentReachabilityStatus] == NotReachable) {
DLog(@"local network not available");
@@ -331,7 +333,7 @@ - (void)startServerSearch
object:nil];
[reachability startNotifer];
- networkTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
+ networkTimer = [NSTimer scheduledTimerWithTimeInterval:15.0
target:self
selector:@selector(networkTimeout:)
userInfo:reachability
@@ -341,7 +343,7 @@ - (void)startServerSearch
} else {
NSString *serverUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID];
if (serverUUID) {
- networkTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
+ networkTimer = [NSTimer scheduledTimerWithTimeInterval:15.0
target:self
selector:@selector(networkTimeout:)
userInfo:reachability
@@ -371,7 +373,7 @@ - (void)receiveFile:(BLIPRequest *)request
NSString *tempFilename = [[NSProcessInfo processInfo] globallyUniqueString];
NSString *tempPath = [[self cachePath] stringByAppendingPathComponent:tempFilename];
DLog(@"file written to \n%@", tempPath);
-
+
DLog(@"request length: %i", [[request body] length]);
[[request body] writeToFile:tempPath atomically:YES];
@@ -392,18 +394,18 @@ - (void)receiveFile:(BLIPRequest *)request
[response send];
}
-- (BOOL)switchStore:(NSPersistentStore *)store withReplacement:(NSDictionary *)replacement error:(NSError **)error
+- (BOOL)switchStore:(NSPersistentStore *)persistentStore withReplacement:(NSDictionary *)replacement error:(NSError **)error
{
DLog(@"%s", __PRETTY_FUNCTION__);
- NSDictionary *storeOptions = [[[store options] copy] autorelease];
+ NSDictionary *storeOptions = [[[persistentStore options] copy] autorelease];
NSFileManager *fileManager = [NSFileManager defaultManager];
- NSPersistentStoreCoordinator *psc = [self persistentStoreCoordinator];
+// NSPersistentStoreCoordinator *psc = [self persistentStoreCoordinator];
NSString *newFileTempPath = [replacement valueForKey:zsTempFilePath];
- NSString *fileOriginalPath = [[store URL] path];
- NSString *originalFileTempPath = [fileOriginalPath stringByAppendingPathExtension:@"zsync_"];
+ NSString *originalFilePath = [[persistentStore URL] path];
+ NSString *originalFileTempPath = [originalFilePath stringByAppendingPathExtension:@"zsync_"];
- if (![psc removePersistentStore:store error:error]) {
+ if (![[self persistentStoreCoordinator] removePersistentStore:persistentStore error:error]) {
return NO;
}
@@ -414,18 +416,18 @@ - (BOOL)switchStore:(NSPersistentStore *)store withReplacement:(NSDictionary *)r
}
}
- if ([fileManager fileExistsAtPath:fileOriginalPath]) {
- if (![fileManager moveItemAtPath:fileOriginalPath toPath:originalFileTempPath error:error]) {
+ if ([fileManager fileExistsAtPath:originalFilePath]) {
+ if (![fileManager moveItemAtPath:originalFilePath toPath:originalFileTempPath error:error]) {
return NO;
}
}
- if (![fileManager moveItemAtPath:newFileTempPath toPath:fileOriginalPath error:error]) {
+ if (![fileManager moveItemAtPath:newFileTempPath toPath:originalFilePath error:error]) {
return NO;
}
- NSURL *fileURL = [NSURL fileURLWithPath:fileOriginalPath];
- if (![psc addPersistentStoreWithType:[replacement valueForKey:zsStoreType] configuration:[replacement valueForKey:zsStoreConfiguration] URL:fileURL options:storeOptions error:error]) {
+ NSURL *fileURL = [NSURL fileURLWithPath:originalFilePath];
+ if (![[self persistentStoreCoordinator] addPersistentStoreWithType:[replacement valueForKey:zsStoreType] configuration:[replacement valueForKey:zsStoreConfiguration] URL:fileURL options:storeOptions error:error]) {
return NO;
}
@@ -465,13 +467,13 @@ - (void)completeSync
}
// We have all of the files now we need to swap them out.
- for (NSPersistentStore *store in [[self persistentStoreCoordinator] persistentStores]) {
- NSDictionary *replacement = [[self receivedFileLookupDictionary] valueForKey:[store identifier]];
+ for (NSPersistentStore *persistentStore in [[self persistentStoreCoordinator] persistentStores]) {
+ NSDictionary *replacement = [[self receivedFileLookupDictionary] valueForKey:[persistentStore identifier]];
- ZAssert(replacement != nil, @"Missing the replacement file for %@\n%@", [store identifier], [[self receivedFileLookupDictionary] allKeys]);
+ ZAssert(replacement != nil, @"Missing the replacement file for %@\n%@", [persistentStore identifier], [[self receivedFileLookupDictionary] allKeys]);
NSError *error = nil;
- if ([self switchStore:store withReplacement:replacement error:&error]) {
+ if ([self switchStore:persistentStore withReplacement:replacement error:&error]) {
continue;
}
@@ -501,35 +503,28 @@ - (void)completeSync
*/
- (void)startBrowser;
{
+ DLog(@"%s", __PRETTY_FUNCTION__);
+
[[self serviceBrowser] start];
-// DLog(@"%s", __PRETTY_FUNCTION__);
-// if (_serviceBrowser) {
-// return;
-// }
-// _serviceBrowser = [[ServerBrowser alloc] init];
-// _serviceBrowser.delegate = self;
-// [_serviceBrowser start];
}
- (void)sendUploadComplete
{
DLog(@"%s", __PRETTY_FUNCTION__);
DLog(@"sending upload complete");
-
- NSString *schemaID = [[[NSBundle mainBundle] infoDictionary] objectForKey:zsSchemaIdentifier];
NSMutableDictionary *requestPropertiesDictionary = [[NSMutableDictionary alloc] init];
[requestPropertiesDictionary setValue:zsActID(zsActionPerformSync) forKey:zsAction];
- [requestPropertiesDictionary setValue:schemaID forKey:zsSchemaIdentifier];
-
+ [requestPropertiesDictionary setValue:[self schemaID] forKey:zsSchemaIdentifier];
+
BLIPRequest *request = [BLIPRequest requestWithBody:nil properties:requestPropertiesDictionary];
[request setNoReply:YES];
[[self connection] sendRequest:request];
[requestPropertiesDictionary release], requestPropertiesDictionary = nil;
}
-- (void)uploadDataToServer;
+- (void)uploadDataToServer
{
DLog(@"%s", __PRETTY_FUNCTION__);
[[self serviceBrowser] setDelegate:nil];
@@ -538,30 +533,20 @@ - (void)uploadDataToServer;
[[self delegate] zSyncStarted:self];
-// storeFileIdentifiers = [[NSMutableArray alloc] init];
-
NSAssert([self persistentStoreCoordinator] != nil, @"The persistent store coordinator was nil. Make sure you are calling registerDelegate:withPersistentStoreCoordinator: before trying to sync.");
for (NSPersistentStore *persistentStore in [[self persistentStoreCoordinator] persistentStores]) {
NSData *persistentStoreData = [[NSData alloc] initWithContentsOfMappedFile:[[persistentStore URL] path]];
DLog(@"url %@\nIdentifier: %@\nSize: %i", [persistentStore URL], [persistentStore identifier], [persistentStoreData length]);
- NSString *syncGUID = [[NSUserDefaults standardUserDefaults] stringForKey:zsSyncGUID];
- if (!syncGUID) {
- syncGUID = [[NSProcessInfo processInfo] globallyUniqueString];
- [[NSUserDefaults standardUserDefaults] setValue:syncGUID forKey:zsSyncGUID];
- }
-
- NSString *schemaID = [[[NSBundle mainBundle] infoDictionary] objectForKey:zsSchemaIdentifier];
-
NSMutableDictionary *requestPropertiesDictionary = [[NSMutableDictionary alloc] init];
[requestPropertiesDictionary setValue:zsActID([self majorVersionNumber]) forKey:zsSchemaMajorVersion];
[requestPropertiesDictionary setValue:zsActID([self minorVersionNumber]) forKey:zsSchemaMinorVersion];
[requestPropertiesDictionary setValue:[[UIDevice currentDevice] name] forKey:zsDeviceName];
[requestPropertiesDictionary setValue:[[UIDevice currentDevice] uniqueIdentifier] forKey:zsDeviceGUID];
[requestPropertiesDictionary setValue:[persistentStore identifier] forKey:zsStoreIdentifier];
- [requestPropertiesDictionary setValue:syncGUID forKey:zsSyncGUID];
- [requestPropertiesDictionary setValue:schemaID forKey:zsSchemaIdentifier];
+ [requestPropertiesDictionary setValue:[self syncGUID] forKey:zsSyncGUID];
+ [requestPropertiesDictionary setValue:[self schemaID] forKey:zsSchemaIdentifier];
if (![[persistentStore configurationName] isEqualToString:@"PF_DEFAULT_CONFIGURATION_NAME"]) {
[requestPropertiesDictionary setValue:[persistentStore configurationName] forKey:zsStoreConfiguration];
}
@@ -572,7 +557,7 @@ - (void)uploadDataToServer;
// TODO: Compression is not working. Need to find out why
[request setCompressed:YES];
[[self connection] sendRequest:request];
-
+
[persistentStoreData release], persistentStoreData = nil;
[requestPropertiesDictionary release], requestPropertiesDictionary = nil;
DLog(@"file uploaded");
@@ -582,28 +567,10 @@ - (void)uploadDataToServer;
DLog(@"finished");
}
-- (void)processTestFileTransfer:(BLIPRequest *)request
-{
- DLog(@"%s", __PRETTY_FUNCTION__);
- NSData *data = [request body];
- DLog(@"length %i", [data length]);
- NSString *path = [self cachePath];
- path = [path stringByAppendingPathComponent:@"test.jpg"];
-
- NSError *error = nil;
- if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
- DLog(@"deleting old file");
- [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
- ZAssert(error == nil, @"error removing test file: %@", [error localizedDescription]);
- }
-
- [data writeToFile:path atomically:YES];
- DLog(@"file written\n%@", path);
-}
-
- (NSString *)generatePairingCode
{
DLog(@"%s", __PRETTY_FUNCTION__);
+
NSMutableString *string = [NSMutableString string];
[string appendFormat:@"%i", (arc4random() % 10)];
[string appendFormat:@"%i", (arc4random() % 10)];
@@ -617,14 +584,12 @@ - (void)requestDeregistration;
{
DLog(@"%s", __PRETTY_FUNCTION__);
DLog(@"issuing deregister command");
- NSString *schemaID = [[[NSBundle mainBundle] infoDictionary] objectForKey:zsSchemaIdentifier];
NSMutableDictionary *requestPropertiesDictionary = [NSMutableDictionary dictionary];
[requestPropertiesDictionary setValue:zsActID(zsActionDeregisterClient) forKey:zsAction];
- [requestPropertiesDictionary setValue:schemaID forKey:zsSchemaIdentifier];
+ [requestPropertiesDictionary setValue:[self schemaID] forKey:zsSchemaIdentifier];
- NSString *syncUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsSyncGUID];
- NSData *body = [syncUUID dataUsingEncoding:NSUTF8StringEncoding];
+ NSData *body = [[self syncGUID] dataUsingEncoding:NSUTF8StringEncoding];
BLIPRequest *request = [BLIPRequest requestWithBody:body properties:requestPropertiesDictionary];
[[self connection] sendRequest:request];
@@ -633,14 +598,11 @@ - (void)requestDeregistration;
- (void)requestLatentDeregistration
{
DLog(@"%s", __PRETTY_FUNCTION__);
- NSString *schemaID = [[[NSBundle mainBundle] infoDictionary] objectForKey:zsSchemaIdentifier];
-
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setValue:zsActID(zsActionLatentDeregisterClient) forKey:zsAction];
- [dictionary setValue:schemaID forKey:zsSchemaIdentifier];
+ [dictionary setValue:[self schemaID] forKey:zsSchemaIdentifier];
- NSString *syncUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsSyncGUID];
- NSData *body = [syncUUID dataUsingEncoding:NSUTF8StringEncoding];
+ NSData *body = [[self syncGUID] dataUsingEncoding:NSUTF8StringEncoding];
BLIPRequest *request = [BLIPRequest requestWithBody:body properties:dictionary];
[[self connection] sendRequest:request];
@@ -651,7 +613,6 @@ - (void)connectionEstablished
DLog(@"%s", __PRETTY_FUNCTION__);
switch ([self serverAction]) {
case ZSyncServerActionLatentDeregistration:
- DLog(@"%s", __PRETTY_FUNCTION__);
[self requestLatentDeregistration];
break;
case ZSyncServerActionSync:
@@ -662,20 +623,18 @@ - (void)connectionEstablished
// We are not paired so we need to request a pairing session
[self setPasscode:[self generatePairingCode]];
- NSString *schemaID = [[[NSBundle mainBundle] infoDictionary] objectForKey:zsSchemaIdentifier];
-
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
[dict setValue:zsActID(zsActionRequestPairing) forKey:zsAction];
[dict setValue:zsActID([self majorVersionNumber]) forKey:zsSchemaMajorVersion];
[dict setValue:zsActID([self minorVersionNumber]) forKey:zsSchemaMinorVersion];
[dict setValue:[[UIDevice currentDevice] name] forKey:zsDeviceName];
[dict setValue:[[UIDevice currentDevice] uniqueIdentifier] forKey:zsDeviceGUID];
- [dict setValue:schemaID forKey:zsSchemaIdentifier];
-
+ [dict setValue:[self schemaID] forKey:zsSchemaIdentifier];
+
NSData *data = [[self passcode] dataUsingEncoding:NSUTF8StringEncoding];
BLIPRequest *request = [[self connection] requestWithBody:data properties:dict];
[request send];
-
+
[dict release], dict = nil;
[[self delegate] zSyncHandler:self displayPairingCode:[self passcode]];
@@ -689,6 +648,23 @@ - (void)connectionEstablished
}
}
+- (NSString *)syncGUID
+{
+ NSString *syncGUID = [[NSUserDefaults standardUserDefaults] stringForKey:zsSyncGUID];
+
+ if (!syncGUID) {
+ syncGUID = [[NSProcessInfo processInfo] globallyUniqueString];
+ [[NSUserDefaults standardUserDefaults] setValue:syncGUID forKey:zsSyncGUID];
+ }
+
+ return syncGUID;
+}
+
+- (NSString *)schemaID
+{
+ return [[[NSBundle mainBundle] infoDictionary] objectForKey:zsSchemaIdentifier];
+}
+
#pragma mark -
#pragma mark Overridden getters/setter
@@ -698,14 +674,12 @@ - (ServerBrowser *)serviceBrowser
_serviceBrowser = [[ServerBrowser alloc] init];
_serviceBrowser.delegate = self;
}
-
+
return _serviceBrowser;
}
-
- (NSMutableArray *)availableServers
{
- DLog(@"%s", __PRETTY_FUNCTION__);
if (!availableServers) {
availableServers = [[NSMutableArray alloc] init];
}
@@ -715,7 +689,6 @@ - (NSMutableArray *)availableServers
- (NSMutableArray *)discoveredServers
{
- DLog(@"%s", __PRETTY_FUNCTION__);
if (!discoveredServers) {
discoveredServers = [[NSMutableArray alloc] init];
}
@@ -725,7 +698,6 @@ - (NSMutableArray *)discoveredServers
- (NSObject *)lock
{
- DLog(@"%s", __PRETTY_FUNCTION__);
if (!lock) {
lock = [[NSObject alloc] init];
}
@@ -738,7 +710,7 @@ - (NSMutableDictionary *)receivedFileLookupDictionary
if (!receivedFileLookupDictionary) {
receivedFileLookupDictionary = [[NSMutableDictionary alloc] init];
}
-
+
return receivedFileLookupDictionary;
}
@@ -747,11 +719,25 @@ - (NSMutableArray *)storeFileIdentifiers
if (!storeFileIdentifiers) {
storeFileIdentifiers = [[NSMutableArray alloc] init];
}
-
+
return storeFileIdentifiers;
}
+- (void)setConnection:(BLIPConnection *)conn
+{
+ if ([conn isEqual:[self connection]]) {
+ return;
+ }
+ if ([self connection]) {
+ [[self connection] close];
+ [[self connection] setDelegate:nil];
+ }
+
+ BLIPConnection *tmp = [conn retain];
+ [_connection release], _connection = nil;
+ _connection = tmp;
+}
#pragma mark -
#pragma mark ServerBrowserDelegate methods
@@ -776,15 +762,15 @@ - (void)updateServerList
[service resolveWithTimeout:15.0];
}
- if (![self discoveredServers] || [[self discoveredServers] count] == 0) {
+ if ([[self discoveredServers] count] == 0) {
NSString *serverUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID];
if (!serverUUID) {
[[self delegate] zSyncNoServerPaired:[self availableServers]];
}
} else {
NSString *serverUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID];
if (serverUUID) {
- networkTimer = [NSTimer scheduledTimerWithTimeInterval:5.0
+ networkTimer = [NSTimer scheduledTimerWithTimeInterval:15.0
target:self
selector:@selector(networkTimeout:)
userInfo:nil
@@ -800,113 +786,102 @@ - (void)updateServerList
/* Sent to the NSNetService instance's delegate prior to resolving a service on the network. If for some reason the resolution cannot occur, the delegate will not receive this message, and an error will be delivered to the delegate via the delegate's -netService:didNotResolve: method.
*/
-- (void)netServiceWillResolve:(NSNetService *)sender {}
+- (void)netServiceWillResolve:(NSNetService *)bonjourService {}
/* Sent to the NSNetService instance's delegate when one or more addresses have been resolved for an NSNetService instance. Some NSNetService methods will return different results before and after a successful resolution. An NSNetService instance may get resolved more than once; truly robust clients may wish to resolve again after an error, or to resolve more than once.
*/
- (void)netServiceDidResolveAddress:(NSNetService *)bonjourService
{
DLog(@"%s", __PRETTY_FUNCTION__);
+
+ NSString *incomingServerName = [bonjourService name];
+
+ NSDictionary *txtRecordDictionary = [NSNetService dictionaryFromTXTRecordData:[bonjourService TXTRecordData]];
+ if (!txtRecordDictionary) {
+ DLog(@"The NSNetService named %@ did not contain a TXT record", incomingServerName);
+ return;
+ }
+
+ NSData *incomingServerUUIDData = [txtRecordDictionary objectForKey:zsServerUUID];
+ if (!incomingServerUUIDData) {
+ DLog(@"The TXT record did not contain a server UUID.");
+ return;
+ }
+
+ NSString *incomingServerUUID = [[NSString alloc] initWithData:incomingServerUUIDData encoding:NSUTF8StringEncoding];
+ if (!incomingServerUUID || [incomingServerUUID length] == 0) {
+ DLog(@"The TXT record UUID was zero length.");
+ [incomingServerUUID release], incomingServerUUID = nil;
+ return;
+ }
+
NSString *registeredServerUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID];
NSString *registeredServerName = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerName];
- @try {
- if (!registeredServerUUID) { // See if the server is in this list
- NSString *incomingServerName = [bonjourService name];
- NSDictionary *txtRecordDictionary = [NSNetService dictionaryFromTXTRecordData:[bonjourService TXTRecordData]];
- if (!txtRecordDictionary) {
- DLog(@"The NSNetService named %@ did not contain a TXT record", incomingServerName);
- return;
- }
+ if (!registeredServerUUID) { // See if the server is in the deregistered list
+ NSArray *deregisteredServers = [[NSUserDefaults standardUserDefaults] objectForKey:zsDeregisteredServersKey];
+ if (deregisteredServers && [deregisteredServers containsObject:incomingServerUUID]) {
+ [self setServerAction:ZSyncServerActionLatentDeregistration];
+ BLIPConnection *conn = [[BLIPConnection alloc] initToNetService:bonjourService];
+ [self setConnection:conn];
+ [conn setDelegate:self];
+ [conn open];
+ [conn release], conn = nil;
+ }
- NSData *serverUUIDData = [txtRecordDictionary objectForKey:zsServerUUID];
- if (!serverUUIDData) {
- DLog(@"The TXT record did not contain a server UUID.");
- return;
- }
+ ZSyncService *zSyncService = [[ZSyncService alloc] init];
+ [zSyncService setService:bonjourService];
+ [zSyncService setName:incomingServerName];
+ [zSyncService setUuid:incomingServerUUID];
+ [[self availableServers] addObject:zSyncService];
+ [zSyncService release], zSyncService = nil;
- NSString *incomingServerUUID = [[NSString alloc] initWithData:serverUUIDData encoding:NSUTF8StringEncoding];
- if (!incomingServerUUID || [incomingServerUUID length] == 0) {
- DLog(@"The TXT record UUID was zero length.");
- [incomingServerUUID release], incomingServerUUID = nil;
- return;
- }
+ [[self delegate] zSyncNoServerPaired:[self availableServers]];
- NSArray *deregisteredServers = [[NSUserDefaults standardUserDefaults] objectForKey:zsDeregisteredServersKey];
- if (deregisteredServers && [deregisteredServers containsObject:incomingServerUUID]) {
- [self setServerAction:ZSyncServerActionLatentDeregistration];
- BLIPConnection *conn = [[BLIPConnection alloc] initToNetService:bonjourService];
- [self setConnection:conn];
- [conn setDelegate:self];
- [conn open];
- [conn release], conn = nil;
- }
-
- ZSyncService *zSyncService = [[ZSyncService alloc] init];
- [zSyncService setService:bonjourService];
- [zSyncService setName:incomingServerName];
- [zSyncService setUuid:incomingServerUUID];
- [[self availableServers] addObject:zSyncService];
- [zSyncService release], zSyncService = nil;
+ [incomingServerUUID release], incomingServerUUID = nil;
- [[self delegate] zSyncNoServerPaired:[self availableServers]];
+ return;
+ }
+ if (![incomingServerUUID isEqualToString:registeredServerUUID]) {
+ NSData *incomingServerNameData = [txtRecordDictionary objectForKey:zsServerName];
+ if (!incomingServerNameData) {
+ DLog(@"TXT record did not contain server name data");
[incomingServerUUID release], incomingServerUUID = nil;
-
return;
}
- NSDictionary *txtRecordDictionary = [NSNetService dictionaryFromTXTRecordData:[bonjourService TXTRecordData]];
- if (!txtRecordDictionary) {
- DLog(@"Found a serverUUID, but the NSNetService named %@ did not contain a TXT record", [bonjourService name]);
+ NSString *incomingServerName = [[NSString alloc] initWithData:incomingServerNameData encoding:NSUTF8StringEncoding];
+ if (![incomingServerName isEqualToString:registeredServerName]) {
+ DLog(@"Incoming server name did not match registered server name, %@ != %@", incomingServerName, registeredServerName);
+ [incomingServerUUID release], incomingServerUUID = nil;
+ [incomingServerName release], incomingServerName = nil;
return;
}
- NSData *incomingServerUUIDData = [txtRecordDictionary objectForKey:zsServerUUID];
- if (!incomingServerUUIDData) {
- DLog(@"TXT record did not contain server UUID data");
+ if ([incomingServerUUID hasPrefix:registeredServerUUID]) {
+ DLog(@"Found an instance of an old UUID that we will upgrade");
+ [[NSUserDefaults standardUserDefaults] setValue:incomingServerUUID forKey:zsServerUUID];
+ [incomingServerUUID release], incomingServerUUID = nil;
+ [incomingServerName release], incomingServerName = nil;
+ } else {
+ DLog(@"Incoming server UUID did not have a prefix of the registered server UUID, %@ does not start with %@", incomingServerUUID, registeredServerUUID);
+ [incomingServerUUID release], incomingServerUUID = nil;
+ [incomingServerName release], incomingServerName = nil;
+
return;
}
+ }
- NSString *incomingServerUUID = [[NSString alloc] initWithData:incomingServerUUIDData encoding:NSUTF8StringEncoding];
- if (![incomingServerUUID isEqualToString:registeredServerUUID]) {
- NSData *incomingServerNameData = [txtRecordDictionary objectForKey:zsServerName];
- if (!incomingServerNameData) {
- DLog(@"TXT record did not contain server name data");
- [incomingServerUUID release], incomingServerUUID = nil;
- return;
- }
-
- NSString *incomingServerName = [[NSString alloc] initWithData:incomingServerNameData encoding:NSUTF8StringEncoding];
- if (![incomingServerName isEqualToString:registeredServerName]) {
- DLog(@"Incoming server name did not match registered server name, %@ != %@", incomingServerName, registeredServerName);
- [incomingServerUUID release], incomingServerUUID = nil;
- [incomingServerName release], incomingServerName = nil;
- return;
- }
-
- if ([incomingServerUUID hasPrefix:registeredServerUUID]) {
- DLog(@"Found an instance of an old UUID that we will upgrade");
- [[NSUserDefaults standardUserDefaults] setValue:incomingServerUUID forKey:zsServerUUID];
- [incomingServerUUID release], incomingServerUUID = nil;
- [incomingServerName release], incomingServerName = nil;
- } else {
- DLog(@"Incoming server UUID did not have a prefix of the registered server UUID, %@ does not start with %@", incomingServerUUID, registeredServerUUID);
- [incomingServerUUID release], incomingServerUUID = nil;
- [incomingServerName release], incomingServerName = nil;
-
- return;
- }
- }
+ [networkTimer invalidate], networkTimer = nil;
+ DLog(@"our server found");
+ // Found our server, stop looking and start the sync
+ [[self serviceBrowser] setDelegate:nil];
+ [[self serviceBrowser] stop];
- [networkTimer invalidate], networkTimer = nil;
- DLog(@"our server found");
- // Found our server, start the sync
- [self beginSyncWithService:bonjourService];
- return;
- } @finally {
- // Not sure what to put in here, we don't need to stop the service browser each time anymore...
- }
+ [self beginSyncWithService:bonjourService];
+
+ return;
}
/* Sent to the NSNetService instance's delegate when an error in resolving the instance occurs. The error dictionary will contain two key/value pairs representing the error domain and code (see the NSNetServicesError enumeration above for error code constants).
@@ -948,25 +923,17 @@ - (void)connectionDidOpen:(BLIPConnection *)conn
{
DLog(@"%s", __PRETTY_FUNCTION__);
DLog(@"%s entered", __PRETTY_FUNCTION__);
- // Start by confirming that the server still supports our schema and version
-
- NSString *schemaID = [[[NSBundle mainBundle] infoDictionary] objectForKey:zsSchemaIdentifier];
+ // Start by confirming that the server still supports our schema and version
NSMutableDictionary *requestPropertiesDictionary = [[NSMutableDictionary alloc] init];
[requestPropertiesDictionary setValue:zsActID(zsActionVerifySchema) forKey:zsAction];
[requestPropertiesDictionary setValue:zsActID([self majorVersionNumber]) forKey:zsSchemaMajorVersion];
[requestPropertiesDictionary setValue:zsActID([self minorVersionNumber]) forKey:zsSchemaMinorVersion];
[requestPropertiesDictionary setValue:[[UIDevice currentDevice] name] forKey:zsDeviceName];
[requestPropertiesDictionary setValue:[[UIDevice currentDevice] uniqueIdentifier] forKey:zsDeviceGUID];
- [requestPropertiesDictionary setValue:schemaID forKey:zsSchemaIdentifier];
-
- NSString *syncGUID = [[NSUserDefaults standardUserDefaults] stringForKey:zsSyncGUID];
- if (!syncGUID) {
- syncGUID = [[NSProcessInfo processInfo] globallyUniqueString];
- [[NSUserDefaults standardUserDefaults] setValue:syncGUID forKey:zsSyncGUID];
- }
+ [requestPropertiesDictionary setValue:[self schemaID] forKey:zsSchemaIdentifier];
- NSData *syncGUIDData = [syncGUID dataUsingEncoding:NSUTF8StringEncoding];
+ NSData *syncGUIDData = [[self syncGUID] dataUsingEncoding:NSUTF8StringEncoding];
BLIPRequest *request = [conn requestWithBody:syncGUIDData properties:requestPropertiesDictionary];
[request send];
@@ -1033,6 +1000,7 @@ - (void)connection:(BLIPConnection *)conn receivedResponse:(BLIPResponse *)respo
[self setServerAction:ZSyncServerActionNoActivity];
[[self connection] close];
[self setConnection:nil];
+
return;
case zsActionFileReceived:
@@ -1045,21 +1013,11 @@ - (void)connection:(BLIPConnection *)conn receivedResponse:(BLIPResponse *)respo
}
return;
- case zsActionRequestPairing:
- DLog(@"%s zsActionRequestPairing", __PRETTY_FUNCTION__);
- // Server has accepted the pairing request
- // Notify the delegate to present a pairing dialog
- if ([[self delegate] respondsToSelector:@selector(zSyncPairingRequestAccepted:)]) {
- // TODO: This does nothing currently, either remove or implement
- // [[self delegate] zSyncPairingRequestAccepted:self];
- }
- return;
-
- case zsActionAuthenticatePassed:
- DLog(@"%s zsActionAuthenticatePassed", __PRETTY_FUNCTION__);
- ALog(@"%s server UUID accepted: %@", [response valueOfProperty:zsServerUUID]);
- return;
-
+// case zsActionAuthenticatePassed:
+// DLog(@"%s zsActionAuthenticatePassed", __PRETTY_FUNCTION__);
+// ALog(@"%s server UUID accepted: %@", [response valueOfProperty:zsServerUUID]);
+// return;
+//
case zsActionSchemaUnsupported:
DLog(@"%s zsActionSchemaUnsupported", __PRETTY_FUNCTION__);
if ([[self delegate] respondsToSelector:@selector(zSync:serverVersionUnsupported:)]) {
@@ -1116,11 +1074,6 @@ - (BOOL)connection:(BLIPConnection *)conn receivedRequest:(BLIPRequest *)request
[[self delegate] zSyncPairingCodeCompleted:self];
return YES;
- case zsActionTestFileTransfer:
- DLog(@"%s zsActionTestFileTransfer", __PRETTY_FUNCTION__);
- [self processTestFileTransfer:request];
- return YES;
-
case zsActionCompleteSync:
DLog(@"%s zsActionCompleteSync", __PRETTY_FUNCTION__);
[self performSelector:@selector(completeSync) withObject:nil afterDelay:0.01];
View
2 SharedCode/ZSyncShared.h
@@ -2,7 +2,7 @@
#define DLog(...) NSLog(@"%s(%x) %@", __PRETTY_FUNCTION__, self, [NSString stringWithFormat:__VA_ARGS__])
#define ALog(...) [[NSAssertionHandler currentHandler] handleFailureInFunction:[NSString stringWithCString:__PRETTY_FUNCTION__ encoding:NSUTF8StringEncoding] file:[NSString stringWithCString:__FILE__ encoding:NSUTF8StringEncoding] lineNumber:__LINE__ description:__VA_ARGS__]
#else
- #define DLog(...) do {} while(0)
+ #define DLog(...) NSLog(@"%s(%x) %@", __PRETTY_FUNCTION__, self, [NSString stringWithFormat:__VA_ARGS__])
#ifndef NS_BLOCK_ASSERTIONS
#define NS_BLOCK_ASSERTIONS
#endif

0 comments on commit edade0f

Please sign in to comment.
Something went wrong with that request. Please try again.