Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Cannot retrieve contributors at this time

file 1333 lines (1072 sloc) 48.552 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 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 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333
//
// ZSyncTouchHandler.m
// SampleTouch
//
// Created by Marcus S. Zarra on 11/11/09.
// Copyright 2009 Zarra Studios, LLC. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.

#import "Reachability.h"
#import "ServerBrowser.h"
#import "ZSyncShared.h"
#import "ZSyncTouchHandler.h"

#define zsUUIDStringLength 55

#pragma mark -

@interface ZSyncTouchHandler ()

- (void)beginSyncWithService:(NSNetService *)service;
- (void)beginDeregistrationWithService:(NSNetService *)service;
- (void)beginLatentDeregistrationWithService:(NSNetService *)service;
- (void)requestDeregistrationUsingConnection:(BLIPConnection *)conn;
- (void)requestLatentDeregistrationUsingConnection:(BLIPConnection *)conn;
- (void)uploadDataToServerUsingConnection:(BLIPConnection *)conn;
- (void)sendPairingRequestToServerUsingConnection:(BLIPConnection *)conn;
- (void)completeSyncFromConnection:(BLIPConnection *)conn;
- (void)startServerSearch;
- (void)handleServerActionWithService:(NSNetService *)service;
- (NSString *)generatePairingCode;
- (NSString *)syncGUID;
- (NSString *)schemaID;
- (void)processLatentDeregisterResponse:(BLIPResponse *)response fromConnection:(BLIPConnection *)conn;
- (void)processDeregisterResponse:(BLIPResponse *)response fromConnection:(BLIPConnection *)conn;
- (void)processFileReceivedResponse:(BLIPResponse *)response fromConnection:(BLIPConnection *)conn;
- (void)processSchemaUnsupportedResponse:(BLIPResponse *)response fromConnection:(BLIPConnection *)conn;
- (void)processSchemaSupportedResponse:(BLIPResponse *)response fromConnection:(BLIPConnection *)conn;
- (void)processAuthenticationFailedRequest:(BLIPRequest *)request fromConnection:(BLIPConnection *)conn;
- (void)processAuthenticatePairingRequest:(BLIPRequest *)request fromConnection:(BLIPConnection *)conn;
- (void)processCompleteSyncRequest:(BLIPRequest *)request fromConnection:(BLIPConnection *)conn;
- (void)processStoreUploadRequest:(BLIPRequest *)request fromConnection:(BLIPConnection *)conn;
- (void)processCancelPairingRequest:(BLIPRequest *)request fromConnection:(BLIPConnection *)conn;

@property (nonatomic, assign) id delegate;
@property (nonatomic, retain) NSPersistentStoreCoordinator *persistentStoreCoordinator;

@end

#pragma mark -

@implementation ZSyncTouchHandler

#pragma mark -
#pragma mark Class methods

+ (id)shared;
{
  static ZSyncTouchHandler *sharedTouchHandler;
  if (sharedTouchHandler) {
    return sharedTouchHandler;
  }

  @synchronized(sharedTouchHandler)
  {
    sharedTouchHandler = [[ZSyncTouchHandler alloc] init];
    [[NSNotificationCenter defaultCenter] addObserver:sharedTouchHandler
                         selector:@selector(applicationWillTerminate:)
                           name:UIApplicationWillTerminateNotification
                           object:nil];

    // Initialize our lock objects
    [sharedTouchHandler lock];
    [sharedTouchHandler serviceResolutionLock];
  }

  return sharedTouchHandler;
}

#pragma mark -
#pragma mark Public methods

- (void)registerDelegate:(id<ZSyncDelegate>)zsyncDelegate withPersistentStoreCoordinator:(NSPersistentStoreCoordinator *)coordinator;
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  [self setDelegate:zsyncDelegate];
  [self setPersistentStoreCoordinator:coordinator];
}

- (void)requestSync
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  ZAssert([self serverAction] == ZSyncServerActionNoActivity, @"Attempt to sync while another action is active");
  if ([self serverAction] != ZSyncServerActionNoActivity) {
    if ([[self delegate] respondsToSelector:@selector(zSync:errorOccurred:)]) {
      NSString *errorString = [NSString stringWithFormat:@"Another activity in progress: %i", [self serverAction]];
      NSDictionary *dict = [NSDictionary dictionaryWithObject:errorString forKey:NSLocalizedDescriptionKey];
      NSError *error = [NSError errorWithDomain:zsErrorDomain code:zsErrorAnotherActivityInProgress userInfo:dict];
      [[self delegate] zSync:self errorOccurred:error];
      return;
    }
  }

  [self setServerAction:ZSyncServerActionSync];
  [self startServerSearch];
}

- (void)stopRequestingSync
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  [[self serviceBrowser] setDelegate:nil];
  [[self serviceBrowser] stop];
  [[self resolvedServices] removeAllObjects];
  [self setRegisteredService:nil];
  [self setServerAction:ZSyncServerActionNoActivity];
}

- (void)requestPairing:(ZSyncService *)server
{
  DLog(@"%s", __PRETTY_FUNCTION__);

  [self setServerAction:ZSyncServerActionSync];

  NSNetService *service = [server service];

  BLIPConnection *conn = [[BLIPConnection alloc] initToNetService:service];
  [[self openConnections] addObject:conn];
  [conn setDelegate:self];
  [conn open];
  [conn release], conn = nil;
}

- (void)cancelPairing;
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  if ([[self openConnections] count] == 0) {
    return;
  }

  BLIPConnection *openConnection = nil;
  for (BLIPConnection *conn in [self openConnections]) {
    if ([conn status] == kTCP_Open) {
      openConnection = conn;
      break;
    }
  }

  if (!openConnection) {
    return;
  }

  DLog(@"sending a pairing cancel");
  NSMutableDictionary *requestPropertiesDictionary = [NSMutableDictionary dictionary];
  [requestPropertiesDictionary setValue:zsActID(zsActionCancelPairing) forKey:zsAction];
  [requestPropertiesDictionary setValue:[[UIDevice currentDevice] uniqueIdentifier] forKey:zsDeviceGUID];
  [requestPropertiesDictionary setValue:[self schemaID] forKey:zsSchemaIdentifier];

  BLIPRequest *request = [BLIPRequest requestWithBody:nil properties:requestPropertiesDictionary];
  [openConnection sendRequest:request];
}

- (void)disconnectPairing;
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  [[NSUserDefaults standardUserDefaults] removeObjectForKey:zsServerName];
  [[NSUserDefaults standardUserDefaults] removeObjectForKey:zsServerUUID];

  for (BLIPConnection *conn in [self openConnections]) {
    [conn setDelegate:nil];
    [conn close];
  }

  [[self openConnections] removeAllObjects];

  [self setRegisteredService:nil];

  [self setServerAction:ZSyncServerActionNoActivity];
}

- (void)deregister
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  DLog(@"deregister request received");

  ZAssert([self serverAction] == ZSyncServerActionNoActivity, @"Attempt to sync while another action is active");

  if ([self serverAction] != ZSyncServerActionNoActivity) {
    if ([[self delegate] respondsToSelector:@selector(zSync:errorOccurred:)]) {
      NSString *errorString = [NSString stringWithFormat:@"Another activity in progress: %i", [self serverAction]];
      NSDictionary *dict = [NSDictionary dictionaryWithObject:errorString forKey:NSLocalizedDescriptionKey];
      NSError *error = [NSError errorWithDomain:zsErrorDomain code:zsErrorAnotherActivityInProgress userInfo:dict];
      [[self delegate] zSync:self errorOccurred:error];
      return;
    }
  }

  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];
      NSError *error = [NSError errorWithDomain:zsErrorDomain code:zsErrorNoSyncClientRegistered userInfo:dict];
      [[self delegate] zSync:self errorOccurred:error];
      return;
    }
  }

  [self setServerAction:ZSyncServerActionDeregister];
  DLog(@"searching for server");
  [self startServerSearch];
}

- (NSString *)serverName
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  return [[NSUserDefaults standardUserDefaults] valueForKey:zsServerName];
}

#pragma mark -
#pragma mark Notification and other callback methods

- (void)applicationWillTerminate:(NSNotification *)notification
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  DLog(@"closing connection");
  for (BLIPConnection *conn in [self openConnections]) {
    [conn setDelegate:nil];
    [conn close];
  }

  [[self openConnections] removeAllObjects];

  if ([self serviceBrowser]) {
    [[self serviceBrowser] setDelegate:nil];
    [[self serviceBrowser] stop];
    [self setServiceBrowser:nil];
  }

  if ([self registeredService]) {
    [[self registeredService] stopMonitoring];
  }
}

- (void)networkTimeout:(NSTimer *)timer
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  DLog(@"timeout on local network");

  if ([self serverAction] == ZSyncServerActionDeregister) {
    DLog(@"[self serverAction] == ZSyncServerActionDeregister");
    NSMutableArray *deregisteredServers = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:zsDeregisteredServersKey]];
    if (!deregisteredServers) {
      deregisteredServers = [[NSMutableArray alloc] init];
    }

    NSString *registeredServerUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID];
    if (registeredServerUUID) {
      [deregisteredServers addObject:registeredServerUUID];
      [[NSUserDefaults standardUserDefaults] setObject:deregisteredServers forKey:zsDeregisteredServersKey];
    }

    [[NSUserDefaults standardUserDefaults] removeObjectForKey:zsServerUUID];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:zsServerName];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [deregisteredServers release], deregisteredServers = nil;

    networkTimer = nil;
    [self setServerAction:ZSyncServerActionNoActivity];
    if ([[self delegate] respondsToSelector:@selector(zSyncDeregisterComplete:)]) {
      [[self delegate] zSyncDeregisterComplete:self];
    }
    [[timer userInfo] stopNotifer];

    return;
  }

  NSString *serverUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID];
  if (serverUUID) {
    [[self serviceBrowser] setDelegate:nil];
    [[self serviceBrowser] stop];
    [self setServiceBrowser:nil];
  }

  networkTimer = nil;
  [self setServerAction:ZSyncServerActionNoActivity];
  if ([[self delegate] respondsToSelector:@selector(zSyncServerUnavailable:)]) {
    [[self delegate] zSyncServerUnavailable:self];
  }

  [[timer userInfo] stopNotifer];
}

- (void)reachabilityChanged:(NSNotification *)notification
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  Reachability *reachability = [notification object];
  if ([reachability currentReachabilityStatus] == NotReachable) {
    return;
  }

  DLog(@"local network now available");
  [reachability stopNotifer];
  [networkTimer invalidate], networkTimer = nil;
  NSString *serverUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID];
  if (serverUUID) {
    networkTimer = [NSTimer scheduledTimerWithTimeInterval:15.0
                            target:self
                            selector:@selector(networkTimeout:)
                            userInfo:nil
                             repeats:NO];
  }

  if ([self registeredService]) {
    [self handleServerActionWithService:[self registeredService]];
  } else {
    NSString *serverUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID];
    if (serverUUID) {
      networkTimer = [NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(networkTimeout:) userInfo:reachability repeats:NO];
    }

    [[self serviceBrowser] start];
  }
}

#pragma mark -
#pragma mark Local methods

- (void)handleServerActionWithService:(NSNetService *)service
{
  if ([self serverAction] == ZSyncServerActionSync) {
    [self beginSyncWithService:service];
  } else if ([self serverAction] == ZSyncServerActionDeregister) {
    [self beginDeregistrationWithService:service];
  }
}

- (NSString *)cachePath
{
  DLog(@"%s", __PRETTY_FUNCTION__);

  NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  NSString *filePath = [paths objectAtIndex:0];

  return filePath;
}

- (void)startServerSearch
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  DLog(@"Resetting the service browser");
  [[self serviceBrowser] setDelegate:nil];
  [[self serviceBrowser] stop];
  [self setServiceBrowser:nil];

  Reachability *reachability = [Reachability reachabilityForLocalWiFi];
  if ([reachability currentReachabilityStatus] == NotReachable) {
    DLog(@"local network not available");
    // Subscribe to changes in reachability
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
    [reachability startNotifer];
    networkTimer = [NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(networkTimeout:) userInfo:reachability repeats:NO];

    return;
  } else if ([self registeredService]) {
    [self handleServerActionWithService:[self registeredService]];
  } else {
    NSString *serverUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID];
    if (serverUUID) {
      networkTimer = [NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(networkTimeout:) userInfo:reachability repeats:NO];
    }

    [[self serviceBrowser] start];
  }
}

- (void)beginSyncWithService:(NSNetService *)service
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  BLIPConnection *conn = [[BLIPConnection alloc] initToNetService:service];
  [[self openConnections] addObject:conn];
  [conn setDelegate:self];
  [conn open];
  [conn release], conn = nil;
}

- (void)beginDeregistrationWithService:(NSNetService *)service
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  BLIPConnection *conn = [[BLIPConnection alloc] initToNetService:service];
  [[self openConnections] addObject:conn];
  [conn setDelegate:self];
  [conn open];
  [conn release], conn = nil;
}

- (void)beginLatentDeregistrationWithService:(NSNetService *)service
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  BLIPConnection *conn = [[BLIPConnection alloc] initToNetService:service];
  [[self openConnections] addObject:conn];
  [conn setDelegate:self];
  [conn open];
  [conn release], conn = nil;
}

- (BOOL)switchStore:(NSPersistentStore *)persistentStore withReplacement:(NSDictionary *)replacement error:(NSError **)error
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  NSDictionary *storeOptions = [[[persistentStore options] copy] autorelease];
  NSFileManager *fileManager = [NSFileManager defaultManager];

  NSString *newFileTempPath = [replacement valueForKey:zsTempFilePath];
  NSString *originalFilePath = [[persistentStore URL] path];
  NSString *originalFileTempPath = [originalFilePath stringByAppendingPathExtension:@"zsync_"];

  if (![[self persistentStoreCoordinator] removePersistentStore:persistentStore error:error]) {
    return NO;
  }

  if ([fileManager fileExistsAtPath:originalFileTempPath]) {
    DLog(@"deleting stored file");
    if (![fileManager removeItemAtPath:originalFileTempPath error:error]) {
      return NO;
    }
  }

  if ([fileManager fileExistsAtPath:originalFilePath]) {
    if (![fileManager moveItemAtPath:originalFilePath toPath:originalFileTempPath error:error]) {
      return NO;
    }
  }

  if (![fileManager moveItemAtPath:newFileTempPath toPath:originalFilePath error:error]) {
    return NO;
  }

  NSURL *fileURL = [NSURL fileURLWithPath:originalFilePath];
  if (![[self persistentStoreCoordinator] addPersistentStoreWithType:[replacement valueForKey:zsStoreType] configuration:[replacement valueForKey:zsStoreConfiguration] URL:fileURL options:storeOptions error:error]) {
    return NO;
  }

  DLog(@"store switched");
  return YES;
}

- (void)completeSyncFromConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  [[self persistentStoreCoordinator] lock];

  // First we need to verify that we received every file. Otherwise we fail
  for (NSPersistentStore *store in [[self persistentStoreCoordinator] persistentStores]) {
    if ([[self receivedFileLookupDictionary] objectForKey:[store identifier]]) {
      continue;
    }

    DLog(@"Store ID: %@\n%@", [store identifier], [[self receivedFileLookupDictionary] allKeys]);
    // Fail
    if ([[self delegate] respondsToSelector:@selector(zSync:errorOccurred:)]) {
      // Flush the temp files
      for (NSDictionary *fileDict in [[self receivedFileLookupDictionary] allValues]) {
        NSError *error = nil;
        [[NSFileManager defaultManager] removeItemAtPath:[fileDict valueForKey:zsTempFilePath] error:&error];

        // We want to explode on this failure in dev but in prod just note it
        ZAssert(error == nil, @"Error deleting temp file: %@", [error localizedDescription]);
      }
      NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[store identifier] forKey:zsStoreIdentifier];
      NSError *error = [NSError errorWithDomain:zsErrorDomain code:zsErrorFailedToReceiveAllFiles userInfo:userInfo];
      [[self delegate] zSync:self errorOccurred:error];
      [self setReceivedFileLookupDictionary:nil];
    }
    [[self persistentStoreCoordinator] unlock];
    return;
  }

  // We have all of the files now we need to swap them out.
  for (NSPersistentStore *persistentStore in [[self persistentStoreCoordinator] persistentStores]) {
    NSDictionary *replacement = [[self receivedFileLookupDictionary] valueForKey:[persistentStore identifier]];

    ZAssert(replacement != nil, @"Missing the replacement file for %@\n%@", [persistentStore identifier], [[self receivedFileLookupDictionary] allKeys]);

    NSError *error = nil;
    if ([self switchStore:persistentStore withReplacement:replacement error:&error]) {
      continue;
    }

    ZAssert(error == nil, @"Error switching stores: %@\n%@", [error localizedDescription], [error userInfo]);

    // TODO: We failed in the migration and need to roll back
  }

  [self setReceivedFileLookupDictionary:nil];

  [conn setDelegate:nil];
  [conn close];
  [[self openConnections] removeObject:conn];

  if ([[self delegate] respondsToSelector:@selector(zSyncFinished:)]) {
    [[self delegate] zSyncFinished:self];
  }

  [[self persistentStoreCoordinator] unlock];

  [self setServerAction:ZSyncServerActionNoActivity];
}

/*
* We want to start looking for desktops to sync with here. Once started
* We want to maintain a list of computers found and also send out a notification
* for every server that we discover
*/
- (void)startBrowser;
{
  DLog(@"%s", __PRETTY_FUNCTION__);

  [[self serviceBrowser] start];
}

- (void)sendUploadComplete
{
  DLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)uploadDataToServerUsingConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  [[self serviceBrowser] setDelegate:nil];
  [[self serviceBrowser] stop];
  [self setServiceBrowser:nil];

  [[self delegate] zSyncStarted:self];

  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]);

    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:[self syncGUID] forKey:zsSyncGUID];
    [requestPropertiesDictionary setValue:[self schemaID] forKey:zsSchemaIdentifier];
    if (![[persistentStore configurationName] isEqualToString:@"PF_DEFAULT_CONFIGURATION_NAME"]) {
      [requestPropertiesDictionary setValue:[persistentStore configurationName] forKey:zsStoreConfiguration];
    }
    [requestPropertiesDictionary setValue:[persistentStore type] forKey:zsStoreType];
    [requestPropertiesDictionary setValue:zsActID(zsActionStoreUpload) forKey:zsAction];

    BLIPRequest *request = [BLIPRequest requestWithBody:persistentStoreData properties:requestPropertiesDictionary];
    // TODO: Compression is not working. Need to find out why
    [request setCompressed:YES];
    [conn sendRequest:request];

    [persistentStoreData release], persistentStoreData = nil;
    [requestPropertiesDictionary release], requestPropertiesDictionary = nil;
    DLog(@"file uploaded");

    [[self storeFileIdentifiers] addObject:[persistentStore identifier]];
  }
  DLog(@"finished");
}

- (void)sendPairingRequestToServerUsingConnection:(BLIPConnection *)conn
{
  [self setPasscode:[self generatePairingCode]];

  NSMutableDictionary *requestPropertiesDictionary = [[NSMutableDictionary alloc] init];
  [requestPropertiesDictionary setValue:zsActID(zsActionRequestPairing) 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:[self schemaID] forKey:zsSchemaIdentifier];

  NSData *data = [[self passcode] dataUsingEncoding:NSUTF8StringEncoding];
  BLIPRequest *request = [conn requestWithBody:data properties:requestPropertiesDictionary];
  [request send];

  [requestPropertiesDictionary release], requestPropertiesDictionary = nil;

  [[self delegate] zSyncHandler:self displayPairingCode:[self passcode]];
}

- (NSString *)generatePairingCode
{
  DLog(@"%s", __PRETTY_FUNCTION__);

  NSMutableString *string = [NSMutableString string];
  [string appendFormat:@"%i", (arc4random() % 10)];
  [string appendFormat:@"%i", (arc4random() % 10)];
  [string appendFormat:@"%i", (arc4random() % 10)];
  [string appendFormat:@"%i", (arc4random() % 10)];

  return string;
}

- (void)requestDeregistrationUsingConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  DLog(@"issuing deregister command");

  NSMutableDictionary *requestPropertiesDictionary = [NSMutableDictionary dictionary];
  [requestPropertiesDictionary setValue:zsActID(zsActionDeregisterClient) forKey:zsAction];
  [requestPropertiesDictionary setValue:[self schemaID] forKey:zsSchemaIdentifier];

  NSData *body = [[self syncGUID] dataUsingEncoding:NSUTF8StringEncoding];

  BLIPRequest *request = [BLIPRequest requestWithBody:body properties:requestPropertiesDictionary];
  [conn sendRequest:request];
}

- (void)requestLatentDeregistrationUsingConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
  [dictionary setValue:zsActID(zsActionLatentDeregisterClient) forKey:zsAction];
  [dictionary setValue:[self schemaID] forKey:zsSchemaIdentifier];

  NSData *body = [[self syncGUID] dataUsingEncoding:NSUTF8StringEncoding];

  BLIPRequest *request = [BLIPRequest requestWithBody:body properties:dictionary];
  [conn sendRequest:request];
}

- (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];
}

- (void)processLatentDeregisterResponse:(BLIPResponse *)response fromConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);

  NSString *registeredServerUUID = [response valueOfProperty:zsServerUUID];
  DLog(@"%s registeredServerUUID %@", __PRETTY_FUNCTION__, registeredServerUUID);

  // TODO: Compare version numbers
  ZAssert(registeredServerUUID != nil, @"Body string is nil in request\n%@", [[response properties] allProperties]);

  NSMutableArray *deregisteredServers = [[NSMutableArray alloc] initWithArray:[[NSUserDefaults standardUserDefaults] arrayForKey:zsDeregisteredServersKey]];

  if (registeredServerUUID) {
    [deregisteredServers removeObject:registeredServerUUID];
    [[NSUserDefaults standardUserDefaults] setObject:deregisteredServers forKey:zsDeregisteredServersKey];
  }

  [[NSUserDefaults standardUserDefaults] synchronize];

  [deregisteredServers release], deregisteredServers = nil;

  [self setServerAction:ZSyncServerActionNoActivity];
  [conn setDelegate:nil];
  [conn close];
  [[self openConnections] removeObject:conn];
}

- (void)processDeregisterResponse:(BLIPResponse *)response fromConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);

  if ([[self delegate] respondsToSelector:@selector(zSyncDeregisterComplete:)]) {
    [[self delegate] zSyncDeregisterComplete:self];
  }

  [self setServerAction:ZSyncServerActionNoActivity];
  [conn setDelegate:nil];
  [conn close];
  [[self openConnections] removeObject:conn];

  [self setRegisteredService:nil];
}

- (void)processFileReceivedResponse:(BLIPResponse *)response fromConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);

  ZAssert([self storeFileIdentifiers] != nil, @"zsActionFileReceived with a nil storeFileIdentifiers");

  [[self storeFileIdentifiers] removeObject:[[response properties] valueOfProperty:zsStoreIdentifier]];

  if ([[self storeFileIdentifiers] count] == 0) {
    DLog(@"sending upload complete");

    NSMutableDictionary *requestPropertiesDictionary = [[NSMutableDictionary alloc] init];
    [requestPropertiesDictionary setValue:zsActID(zsActionPerformSync) forKey:zsAction];
    [requestPropertiesDictionary setValue:[self schemaID] forKey:zsSchemaIdentifier];

    BLIPRequest *request = [BLIPRequest requestWithBody:nil properties:requestPropertiesDictionary];
    [request setNoReply:YES];
    [conn sendRequest:request];

    [requestPropertiesDictionary release], requestPropertiesDictionary = nil;

    [self setStoreFileIdentifiers:nil];
  }
}

- (void)processSchemaUnsupportedResponse:(BLIPResponse *)response fromConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);

  if ([[self delegate] respondsToSelector:@selector(zSync:serverVersionUnsupported:)]) {
    NSDictionary *userInfo = [NSDictionary dictionaryWithObject:[response bodyString] forKey:NSLocalizedDescriptionKey];
    NSError *error = [NSError errorWithDomain:zsErrorDomain code:[[response valueOfProperty:zsErrorCode] integerValue] userInfo:userInfo];

    [[self delegate] zSync:self serverVersionUnsupported:error];
  }

  [self setServerAction:ZSyncServerActionNoActivity];
  [conn setDelegate:nil];
  [conn close];
  [[self openConnections] removeObject:conn];
  [self setRegisteredService:nil];
}

- (void)processSchemaSupportedResponse:(BLIPResponse *)response fromConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);

  switch ([self serverAction]) {
    case ZSyncServerActionSync:
      if ([[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID]) {
        // Start a sync by pushing the data file to the server
        [self uploadDataToServerUsingConnection:conn];
      } else {
        // We are not paired so we need to request a pairing session
        [self sendPairingRequestToServerUsingConnection:conn];
      }
      break;
    case ZSyncServerActionDeregister:
      [self requestDeregistrationUsingConnection:conn];
      break;
    case ZSyncServerActionLatentDeregistration:
      [self requestLatentDeregistrationUsingConnection:conn];
      break;
    default:
      ALog(@"Unknown server action: %i", [self serverAction]);
  }
}

- (void)processAuthenticationFailedRequest:(BLIPRequest *)request fromConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);

  /*
* The pairing code was not entered correctly so we reset back to a default state
* so that the user can start all over again.
*/
  [conn setDelegate:nil];
  [conn close];
  [[self openConnections] removeObject:conn];

  if ([[self delegate] respondsToSelector:@selector(zSyncPairingCodeRejected:)]) {
    [[self delegate] zSyncPairingCodeRejected:self];
  }

  [self setServerAction:ZSyncServerActionNoActivity];
  [[NSUserDefaults standardUserDefaults] removeObjectForKey:zsServerUUID];
  [[NSUserDefaults standardUserDefaults] removeObjectForKey:zsServerName];
}

- (void)processAuthenticatePairingRequest:(BLIPRequest *)request fromConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);

  if ([[request bodyString] isEqualToString:[self passcode]]) {
    [[NSUserDefaults standardUserDefaults] setValue:[request valueOfProperty:zsServerUUID] forKey:zsServerUUID];
    [self performSelector:@selector(uploadDataToServerUsingConnection:) withObject:conn afterDelay:0.1];
  }

  [[self delegate] zSyncPairingCodeCompleted:self];
}

- (void)processCompleteSyncRequest:(BLIPRequest *)request fromConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);

  [self performSelector:@selector(completeSyncFromConnection:) withObject:conn afterDelay:0.01];
}

- (void)processStoreUploadRequest:(BLIPRequest *)request fromConnection:(BLIPConnection *)conn
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  ZAssert([request complete], @"Message is incomplete");

  DLog(@"file received");

  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];

  NSMutableDictionary *fileDict = [[NSMutableDictionary alloc] init];
  [fileDict setValue:[request valueOfProperty:zsStoreIdentifier] forKey:zsStoreIdentifier];
  if (![[request valueOfProperty:zsStoreConfiguration] isEqualToString:@"PF_DEFAULT_CONFIGURATION_NAME"]) {
    [fileDict setValue:[request valueOfProperty:zsStoreConfiguration] forKey:zsStoreConfiguration];
  }
  [fileDict setValue:[request valueOfProperty:zsStoreType] forKey:zsStoreType];
  [fileDict setValue:tempPath forKey:zsTempFilePath];

  [[self receivedFileLookupDictionary] setValue:fileDict forKey:[request valueOfProperty:zsStoreIdentifier]];
  [fileDict release], fileDict = nil;

  BLIPResponse *response = [request response];
  [response setValue:zsActID(zsActionFileReceived) ofProperty:zsAction];
  [response setValue:[request valueOfProperty:zsStoreIdentifier] ofProperty:zsStoreIdentifier];
  [response send];
}

- (void)processCancelPairingRequest:(BLIPRequest *)request fromConnection:(BLIPConnection *)conn
{
  DLog(@"%s zsActionCancelPairing", __PRETTY_FUNCTION__);
  [conn setDelegate:nil];
  [conn close];
  [[self openConnections] removeObject:conn];
  // [self setConnection:nil];
  if ([[self delegate] respondsToSelector:@selector(zSyncPairingCodeCancelled:)]) {
    [[self delegate] zSyncPairingCodeCancelled:self];
  }

  [self setServerAction:ZSyncServerActionNoActivity];
  [[NSUserDefaults standardUserDefaults] removeObjectForKey:zsServerUUID];
  [[NSUserDefaults standardUserDefaults] removeObjectForKey:zsServerName];

  [self setRegisteredService:nil];
}

#pragma mark -
#pragma mark Overridden getters/setter

- (ServerBrowser *)serviceBrowser
{
  if (!_serviceBrowser) {
    _serviceBrowser = [[ServerBrowser alloc] init];
    _serviceBrowser.delegate = self;
  }

  return _serviceBrowser;
}

- (NSMutableArray *)availableServers
{
  if (!availableServers) {
    availableServers = [[NSMutableArray alloc] init];
  }

  return availableServers;
}

- (NSMutableArray *)discoveredServers
{
  if (!discoveredServers) {
    discoveredServers = [[NSMutableArray alloc] init];
  }

  return discoveredServers;
}

- (NSMutableArray *)openConnections
{
  if (!openConnections) {
    openConnections = [[NSMutableArray alloc] init];
  }

  return openConnections;
}

- (NSLock *)lock
{
  if (!lock) {
    lock = [[NSLock alloc] init];
  }

  return lock;
}

- (NSLock *)serviceResolutionLock
{
  if (!serviceResolutionLock) {
    serviceResolutionLock = [[NSLock alloc] init];
  }

  return serviceResolutionLock;
}

- (NSMutableDictionary *)receivedFileLookupDictionary
{
  if (!receivedFileLookupDictionary) {
    receivedFileLookupDictionary = [[NSMutableDictionary alloc] init];
  }

  return receivedFileLookupDictionary;
}

- (NSMutableArray *)storeFileIdentifiers
{
  if (!storeFileIdentifiers) {
    storeFileIdentifiers = [[NSMutableArray alloc] init];
  }

  return storeFileIdentifiers;
}

#pragma mark -
#pragma mark ServerBrowserDelegate methods

- (void)updateServerList
{
  [serviceResolutionLock lock];
  DLog(@"%s", __PRETTY_FUNCTION__);
  [networkTimer invalidate], networkTimer = nil;

  for (NSNetService *service in [self discoveredServers]) {
    [service setDelegate:nil];
    [service stop];
  }

  [[self discoveredServers] removeAllObjects];
  [[self availableServers] removeAllObjects];

  [[self discoveredServers] addObjectsFromArray:[[self serviceBrowser] servers]];
  for (NSNetService *service in [self discoveredServers]) {
    [service setDelegate:self];
    [service resolveWithTimeout:15.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:15.0
                              target:self
                              selector:@selector(networkTimeout:)
                              userInfo:nil
                               repeats:NO];
    }
  }

  [serviceResolutionLock unlock];
}

#pragma mark -
#pragma mark NSNetServiceDelegate methods

/* 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 *)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
{
  [serviceResolutionLock lock];

  DLog(@"%s", __PRETTY_FUNCTION__);
  DLog(@"%s description:%@", __PRETTY_FUNCTION__, [bonjourService description]);
  DLog(@"%s hostName:%@", __PRETTY_FUNCTION__, [bonjourService hostName]);
  DLog(@"%s name:%@", __PRETTY_FUNCTION__, [bonjourService name]);
  DLog(@"%s domain:%@", __PRETTY_FUNCTION__, [bonjourService domain]);
  DLog(@"%s addresses:%@", __PRETTY_FUNCTION__, [bonjourService addresses]);
  for (NSData *socketData in [bonjourService addresses]) {
    NSString *socketString = [[NSString alloc] initWithData:socketData encoding:NSASCIIStringEncoding];
    DLog(@"%s address:%@", __PRETTY_FUNCTION__, socketString);
    [socketString release], socketString = nil;
  }
  DLog(@"%s type:%@", __PRETTY_FUNCTION__, [bonjourService type]);
  NSString *incomingServerName = [bonjourService name];

  if ([bonjourService isEqual:[self registeredService]]) {
    DLog(@"%s We've already resolved our service, bailing out before we start a sync. Service Name:%@", __PRETTY_FUNCTION__, incomingServerName);
    [serviceResolutionLock unlock];
    return;
  }


  NSDictionary *txtRecordDictionary = [NSNetService dictionaryFromTXTRecordData:[bonjourService TXTRecordData]];
  if (!txtRecordDictionary) {
    DLog(@"The NSNetService named %@ did not contain a TXT record", incomingServerName);
    [serviceResolutionLock unlock];
    return;
  }

  NSData *incomingServerUUIDData = [txtRecordDictionary objectForKey:zsServerUUID];
  if (!incomingServerUUIDData) {
    DLog(@"The TXT record did not contain a server UUID.");
    [serviceResolutionLock unlock];
    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;
    [serviceResolutionLock unlock];
    return;
  }

  NSArray *deregisteredServers = [[NSUserDefaults standardUserDefaults] objectForKey:zsDeregisteredServersKey];
  if (deregisteredServers && [deregisteredServers containsObject:incomingServerUUID]) {
    [self setServerAction:ZSyncServerActionLatentDeregistration];
    [self beginLatentDeregistrationWithService:bonjourService];
  }

  NSString *registeredServerUUID = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerUUID];
  NSString *registeredServerName = [[NSUserDefaults standardUserDefaults] valueForKey:zsServerName];

  if (!registeredServerUUID) { // See if the server is in the deregistered list
    ZSyncService *zSyncService = [[ZSyncService alloc] init];
    [zSyncService setService:bonjourService];
    [zSyncService setName:incomingServerName];
    [zSyncService setUuid:incomingServerUUID];
    [[self availableServers] addObject:zSyncService];
    [zSyncService release], zSyncService = nil;

    [[self delegate] zSyncNoServerPaired:[self availableServers]];

    [incomingServerUUID release], incomingServerUUID = nil;

    [serviceResolutionLock unlock];
    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;
      [serviceResolutionLock unlock];
      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;
      [serviceResolutionLock unlock];
      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;

      [serviceResolutionLock unlock];
      return;
    }
  }

  [incomingServerUUID release], incomingServerUUID = nil;

  [networkTimer invalidate], networkTimer = nil;
  DLog(@"our server found");
  // Found our server, stop looking and start the sync
  [[self serviceBrowser] setDelegate:nil];
  [[self serviceBrowser] stop];

  [self setRegisteredService:bonjourService];

  [self handleServerActionWithService:bonjourService];

  [serviceResolutionLock unlock];

  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).
*/
- (void)netService:(NSNetService *)sender didNotResolve:(NSDictionary *)errorDict
{
  [serviceResolutionLock lock];

  DLog(@"%s", __PRETTY_FUNCTION__);
  [[self discoveredServers] removeObject:sender];

  // Did not find our registered server. Fail
  if ([[self discoveredServers] count] == 0) {
    [[self delegate] zSyncServerUnavailable:self];
    [self setServerAction:ZSyncServerActionNoActivity];
  }

  [serviceResolutionLock unlock];
}

/* Sent to the NSNetService instance's delegate when the instance's previously running publication or resolution request has stopped.
*/
- (void)netServiceDidStop:(NSNetService *)sender {}

/* Sent to the NSNetService instance's delegate when the instance is being monitored and the instance's TXT record has been updated. The new record is contained in the data parameter.
*/
- (void)netService:(NSNetService *)sender didUpdateTXTRecordData:(NSData *)data {}

#pragma mark -
#pragma mark BLIPConnectionDelegate methods

/* Three possible states at this point: If we have a server UUID
* then we are ready to start a sync. If we do not have a server UUID
* then we need to start a pairing. If we do not have a server UUID but
* we have a previously deregistered server UUID then we need to tell
* that server it's been deregistered.
*/
- (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
  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:[self schemaID] forKey:zsSchemaIdentifier];

  NSData *syncGUIDData = [[self syncGUID] dataUsingEncoding:NSUTF8StringEncoding];
  BLIPRequest *request = [conn requestWithBody:syncGUIDData properties:requestPropertiesDictionary];
  [request send];

  [requestPropertiesDictionary release], requestPropertiesDictionary = nil;
  DLog(@"%s initial send complete", __PRETTY_FUNCTION__);
}

/* We had an error talking to the server. Push this error on to our delegate
* and close the connection
*/
- (void)connection:(TCPConnection *)conn failedToOpen:(NSError *)error
{
  DLog(@"%s error:%@", __PRETTY_FUNCTION__, [error localizedDescription]);
  [conn setDelegate:nil];
  [conn close];
  [[self openConnections] removeObject:conn];
  [[self delegate] zSync:self errorOccurred:error];
  [self setRegisteredService:nil];
}

- (void)connection:(BLIPConnection *)conn receivedResponse:(BLIPResponse *)response;
{
  if (![[response properties] valueOfProperty:zsAction]) {
    DLog(@"%s received empty response, ignoring", __PRETTY_FUNCTION__);
    return;
  }

  DLog(@"%s entered\n%@", __PRETTY_FUNCTION__, [[response properties] allProperties]);
  NSInteger action = [[[response properties] valueOfProperty:zsAction] integerValue];
  switch (action) {
    case zsActionLatentDeregisterClient:
      [self processLatentDeregisterResponse:response fromConnection:conn];
      return;

    case zsActionDeregisterClient:
      [self processDeregisterResponse:response fromConnection:conn];
      return;

    case zsActionFileReceived:
      [self processFileReceivedResponse:response fromConnection:conn];
      return;

    case zsActionSchemaUnsupported:
      [self processSchemaUnsupportedResponse:response fromConnection:conn];
      return;

    case zsActionSchemaSupported:
      [self processSchemaSupportedResponse:response fromConnection:conn];
      return;

    default:
      DLog(@"%s default case encountered", __PRETTY_FUNCTION__);
      ALog(@"%s Unknown response action received: %i", __PRETTY_FUNCTION__, action);
  }
}

- (BOOL)connection:(BLIPConnection *)conn receivedRequest:(BLIPRequest *)request
{
  NSInteger action = [[[request properties] valueOfProperty:zsAction] integerValue];
  switch (action) {
    case zsActionAuthenticateFailed:
      [self processAuthenticationFailedRequest:request fromConnection:conn];
      return YES;

    case zsActionAuthenticatePairing:
      [self processAuthenticatePairingRequest:request fromConnection:conn];
      return YES;

    case zsActionCompleteSync:
      [self processCompleteSyncRequest:request fromConnection:conn];
      return YES;

    case zsActionStoreUpload:
      [self processStoreUploadRequest:request fromConnection:conn];
      return YES;

    case zsActionCancelPairing:
      [self processCancelPairingRequest:request fromConnection:conn];
      return YES;

    default:
      DLog(@"%s default case encountered", __PRETTY_FUNCTION__);
      ALog(@"%s Unknown request action received: %i", __PRETTY_FUNCTION__, action);
      return NO;
  }
}

- (void)connectionDidClose:(TCPConnection *)conn;
{
  DLog(@"%s", __PRETTY_FUNCTION__);
  if (![[self openConnections] containsObject:conn]) {
    return;
  }

  // premature closing
  [[self openConnections] removeObject:conn];
  [self setServerAction:ZSyncServerActionNoActivity];

  [self setRegisteredService:nil];

  if (![[self delegate] respondsToSelector:@selector(zSync:errorOccurred:)]) {
    return;
  }

  NSDictionary *userInfo = [NSDictionary dictionaryWithObject:NSLocalizedString(@"Server Hung Up", @"Server Hung Up message text") forKey:NSLocalizedDescriptionKey];
  NSError *error = [NSError errorWithDomain:zsErrorDomain code:zsErrorServerHungUp userInfo:userInfo];
  [[self delegate] zSync:self errorOccurred:error];
}

#pragma mark -
#pragma mark Memory management and property declarations

@synthesize delegate = _delegate;

@synthesize serviceBrowser = _serviceBrowser;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;

@synthesize majorVersionNumber;
@synthesize minorVersionNumber;
@synthesize passcode;
@synthesize serverAction;
@synthesize availableServers;
@synthesize discoveredServers;
@synthesize resolvedServices;
@synthesize lock;
@synthesize serviceResolutionLock;
@synthesize storeFileIdentifiers;
@synthesize receivedFileLookupDictionary;
@synthesize openConnections;
@synthesize registeredService;

@end

#pragma mark -

@implementation ZSyncService

@synthesize name;
@synthesize uuid;
@synthesize service;

- (NSString *)description
{
  return [NSString stringWithFormat:@"[%@:%@]", [self name], [self uuid]];
}

- (NSUInteger)hash
{
  return [[self description] hash];
}

- (BOOL)isEqual:(id)object
{
  if (!object || ![object isKindOfClass:[ZSyncService class]]) {
    return NO;
  }

  if (![[object name] isEqualToString:[self name]]) {
    return NO;
  }

  if (![[object uuid] isEqualToString:[self uuid]]) {
    return NO;
  }

  return YES;
}

@end
Something went wrong with that request. Please try again.