Advertisement
mitchellmate

DataInputAdapter.m

Jun 28th, 2012
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //
  2. //  FBDataAdapter.m
  3. //  Yearbook
  4. //
  5. //  Created by Mitch Robertson on 9/06/10.
  6. //  Copyright 2010 __MyCompanyName__. All rights reserved.
  7. //
  8.  
  9. #import "DataInputAdapter.h"
  10. #import "DictionaryToObject.h"
  11. #import "lazyjobdirective.h"
  12. #import "guroo_image.h"
  13. #import "Ref.h"
  14. #import "SyncedDate.h"
  15.  
  16. @implementation DataInputAdapter
  17.  
  18. @synthesize managedObjectContext;
  19. @synthesize dataOutputAdapter;
  20. @synthesize preferences;
  21.  
  22. - (id)initWithManagedObjectContext:(NSManagedObjectContext *)managedObjectContext1 andPrefs:(Preferences *)prefs1 {
  23.     if (!(self = [self init])) return nil;
  24.     self.managedObjectContext = managedObjectContext1;
  25.     self.dataOutputAdapter = [[DataOutputAdapter alloc] initWithManagedObjectContext:managedObjectContext1];
  26.     self.preferences = prefs1;
  27.     return self;
  28. }
  29.  
  30. + (NSString *)getModifiedField:(NSString *)t {
  31.     if ([t isEqualToString:@"stream"]) {
  32.         return @"updated_time";
  33.     } else if ([t isEqualToString:@"album"]) {
  34.         return @"modified";
  35.     } else if ([t isEqualToString:@"note"]) {
  36.         return @"updated_time";
  37.     } else if ([t isEqualToString:@"thread"]) {
  38.         return @"updated_time";
  39.     } else if ([t isEqualToString:@"photo"]) {
  40.         return @"modified";
  41.     } else if ([t isEqualToString:@"guroo_friends"]) {
  42.         return @"profile_update_time";
  43.     }
  44.     if ([t isEqualToString:@"status"]) {
  45.         return @"updated_time";
  46.     }
  47.     return nil;
  48. }
  49.  
  50. - (void)commitTransaction {
  51.     NSError *error;
  52.     int insertedCount = [[managedObjectContext insertedObjects] count];
  53.     if (![managedObjectContext save:&error]) {
  54.         NSLog(@"ERROR SAVING STREAM:%@", [error localizedDescription]);
  55.     } else {
  56.         //NSLog(@"DataInputAdapter: inserted %i objects",insertedCount);
  57.     }
  58. }
  59.  
  60. - (BOOL)date:(NSDate *)d1 isGreaterThan:(NSDate *)d2 {
  61.     double d1doub = [d1 timeIntervalSince1970];
  62.     double d2doub = [d2 timeIntervalSince1970];
  63.     //NSLog(@"%0.f-%0.f = %0.f :: %@",d1doub,d2doub,(d1doub-d2doub),(d1doub>d2doub) ? @"YES" : @"NO");
  64.     return (d1doub > d2doub);
  65. }
  66.  
  67. - (BOOL)dateInField:(NSString *)fieldKey inDict:(NSDictionary *)obj isGreaterThan:(NSDate *)date {
  68.     NSDate *dictDate = [DictionaryToObject parseDate:[obj objectForKey:fieldKey]];
  69.     return [self date:dictDate isGreaterThan:date];
  70. }
  71.  
  72. // add entity returning a list of key/otherField pairs that have been modified
  73. - (NSMutableArray *)saveEntityType:(NSString *)t objs:(NSArray *)objs keyField:(NSString *)kf recordAuxField:(NSString *)otherField assocFeedIndex:(int)ft {
  74.     // list of new or modified keys
  75.     NSString *modifiedKey = [DataInputAdapter getModifiedField:t];
  76.     NSMutableArray *modifiedEntityKeys = [[NSMutableArray alloc] init];
  77.     BOOL contentToSave = NO;
  78.     int addCount = 0;
  79.     for (int i = 0; i < [objs count]; i++) {
  80.         NSDictionary *obj = [objs objectAtIndex:i];
  81.         NSString *idValue = [obj valueForKey:kf];
  82.         if ([idValue isKindOfClass:[NSNumber class]]) {
  83.             idValue = [((NSNumber *) idValue) stringValue];
  84.         }
  85.         NSManagedObject *mo = [self.dataOutputAdapter getDBRecordOnTable:t whereField:kf equals:idValue];
  86.         if (mo == nil) {
  87.             //NSLog(@"----------------------->ADD %@, id: %@",t,idValue);
  88.             addCount++;
  89.             mo = [NSEntityDescription
  90.                     insertNewObjectForEntityForName:t
  91.                              inManagedObjectContext:self.managedObjectContext];
  92.             mo = [DictionaryToObject populateManagedObject:mo ofType:t withResult:obj];
  93.             if (otherField == nil) {
  94.                 [modifiedEntityKeys addObject:idValue];
  95.             } else {
  96.                 Ref *ref = [[Ref alloc] init];
  97.                 ref.string1 = idValue;
  98.  
  99.                 NSArray *otherFields = [otherField componentsSeparatedByString:@","];
  100.                 ref.string2 = [obj valueForKey:[otherFields objectAtIndex:0]];
  101.                 if ([otherFields count] > 1) {
  102.                     ref.string3 = [obj valueForKey:[otherFields objectAtIndex:1]];
  103.                 }
  104.  
  105.                 [modifiedEntityKeys addObject:ref];
  106.             }
  107.             contentToSave = YES;
  108.         } else {
  109.             if (modifiedKey != nil) {
  110.                 // edit existing if needed
  111.                 NSDate *oldDate = ((NSDate *) objc_msgSend(mo, NSSelectorFromString(modifiedKey)));
  112.                 if ([self dateInField:modifiedKey inDict:obj isGreaterThan:oldDate] == YES) {
  113.                     //NSLog(@"----------------------->EDIT %@, id: %@",t,idValue);
  114.                     // EDIT existing
  115.                     mo = [DictionaryToObject populateManagedObject:mo ofType:t withResult:obj];
  116.                     if (otherField == nil) {
  117.                         [modifiedEntityKeys addObject:idValue];
  118.                     } else {
  119.                         Ref *ref = [[Ref alloc] init];
  120.                         ref.string1 = idValue;
  121.  
  122.                         NSArray *otherFields = [otherField componentsSeparatedByString:@","];
  123.                         ref.string2 = [obj valueForKey:[otherFields objectAtIndex:0]];
  124.                         if ([otherFields count] > 1) {
  125.                             ref.string3 = [obj valueForKey:[otherFields objectAtIndex:1]];
  126.                         }
  127.  
  128.                         [modifiedEntityKeys addObject:ref];
  129.                     }
  130.                     contentToSave = YES;
  131.                 }
  132.             }
  133.         }
  134.     }
  135.     if (contentToSave) {
  136.         if (ft != -1) {
  137.             [self.preferences addToTotalForFeed:ft amount:addCount];
  138.         }
  139.         [self commitTransaction];
  140.     }
  141.     return modifiedEntityKeys;
  142. }
  143.  
  144. // add entity returning a list of ids that have been modified
  145. - (NSMutableArray *)saveEntityType:(NSString *)t objs:(NSArray *)objs keyField:(NSString *)kf assocFeedIndex:(int)ft {
  146.     return [self saveEntityType:t objs:objs keyField:kf recordAuxField:nil assocFeedIndex:ft];
  147. }
  148.  
  149. - (void)saveChildEntityType:(NSString *)t objs:(NSArray *)objs parentRefField:(NSString *)prf {
  150.     BOOL contentToSave = NO;
  151.     // parent keys whose children have been deleted
  152.     NSMutableDictionary *deletedChildren = [[NSMutableDictionary alloc] init];
  153.  
  154.     NSArray *parentRefFields = [prf componentsSeparatedByString:@","];
  155.     prf = [parentRefFields objectAtIndex:0];
  156.  
  157.     for (int i = 0; i < [objs count]; i++) {
  158.         NSDictionary *obj = [objs objectAtIndex:i];
  159.         NSObject *parentIdVal = [obj valueForKey:prf];
  160.         if ((parentIdVal == [NSNull null] || parentIdVal == nil) && [parentRefFields count] > 1) {
  161.             prf = [parentRefFields objectAtIndex:1];
  162.             parentIdVal = [obj valueForKey:prf];
  163.         }
  164.         NSString *parentId = [parentIdVal isKindOfClass:[NSNumber class]] ? [((NSNumber *) parentIdVal) stringValue] : parentIdVal;
  165.         parentId = [DictionaryToObject extractID:parentId];
  166.  
  167.         // delete all children if haven't already
  168.         if ([deletedChildren valueForKey:parentId] == nil) {
  169.             // delete all children
  170.             NSMutableArray *oldChildren = [self.dataOutputAdapter getDBRecordsOnTable:t whereField:[parentRefFields count] > 1 ? [parentRefFields objectAtIndex:0] : prf equals:parentId];
  171.             //NSLog(@"DataInputAdapter: deleting %i old children before saving new ones",[oldChildren count]);
  172.             for (NSManagedObject *oldManagedObj in oldChildren) {
  173.                 [self.managedObjectContext deleteObject:oldManagedObj];
  174.                 contentToSave = YES;
  175.             }
  176.             [deletedChildren setValue:@"YES" forKey:parentId];
  177.         }
  178.  
  179.         NSManagedObject *mo = [NSEntityDescription
  180.                 insertNewObjectForEntityForName:t
  181.                          inManagedObjectContext:self.managedObjectContext];
  182.         mo = [DictionaryToObject populateManagedObject:mo ofType:t withResult:obj];
  183.         contentToSave = YES;
  184.     }
  185.     if (contentToSave) {
  186.         [self commitTransaction];
  187.     }
  188. }
  189.  
  190. // private
  191. - (void)saveLazyJobDirectivesFor:(NSMutableArray *)changed assocFeedType:(FeedType *)feedType {
  192.     NSString *feedTypeStr = [NSString stringWithFormat:@"%i", feedType];
  193.     NSMutableArray *all = [self.dataOutputAdapter getDBRecordsOnTable:
  194.             @"lazyjobdirective"                            whereField:@"feedType" equals:feedTypeStr];
  195.     NSMutableSet *seen = [[NSMutableSet alloc] init];
  196.     if (all != nil) {
  197.         // build up list of seen
  198.         for (lazyjobdirective *lazy in all) {
  199.             /*if ([lazy.completed isEqualToString:@"YES"]){
  200.                    [self.managedObjectContext deleteObject:lazy];
  201.                }else {*/
  202.             [seen addObject:lazy.itemUID];
  203.             //}
  204.         }
  205.     }
  206.  
  207.     for (NSObject *obj in changed) {
  208.         NSString *key = [obj isKindOfClass:[Ref class]] ? ((Ref *) obj).string1 : (NSString *) obj;
  209.         if (![seen containsObject:key]) {
  210.             lazyjobdirective *lazy = [NSEntityDescription
  211.                     insertNewObjectForEntityForName:@"lazyjobdirective"
  212.                              inManagedObjectContext:self.managedObjectContext];
  213.             lazy.completed = @"NO";
  214.             lazy.feedType = feedTypeStr;
  215.             lazy.itemUID = key;
  216.         }
  217.     }
  218. }
  219.  
  220. // LEVEL 1 Entities
  221. - (Ref *)saveProfileInfo:(NSDictionary *)userInfo {
  222.     NSString *idValue = [userInfo valueForKey:@"uid"];
  223.     NSManagedObject *mo = [self.dataOutputAdapter getDBRecordOnTable:@"user" whereField:@"uid" equals:idValue];
  224.     if (mo == nil) {
  225.         mo = [NSEntityDescription
  226.                 insertNewObjectForEntityForName:@"user"
  227.                          inManagedObjectContext:self.managedObjectContext];
  228.         mo = [DictionaryToObject populateManagedObject:mo ofType:@"user" withResult:userInfo];
  229.     } else {
  230.         // edit exisiting
  231.         mo = [DictionaryToObject populateManagedObject:mo ofType:@"user" withResult:userInfo];
  232.     }
  233.  
  234.     [self commitTransaction];
  235.  
  236.     // add fake friend
  237.     guroo_friends *profileFriend = (guroo_friends *) [self.dataOutputAdapter getDBRecordOnTable:@"guroo_friends" whereField:@"uid" equals:idValue];
  238.     Ref *ref = nil;
  239.     if (profileFriend == nil) {
  240.         // create new
  241.         profileFriend = (guroo_friends *) [NSEntityDescription
  242.                 insertNewObjectForEntityForName:@"guroo_friends"
  243.                          inManagedObjectContext:self.managedObjectContext];
  244.         profileFriend = [DictionaryToObject populateFriendObject:profileFriend withResult:userInfo];
  245.  
  246.         ref = [[Ref alloc] init];
  247.         ref.string1 = profileFriend.uid;
  248.         ref.string2 = @"pic_square";
  249.         ref.string3 = profileFriend.pic_square;
  250.     } else {
  251.         NSLog(@"pic_big=@%", profileFriend.pic_big);
  252.         NSLog(@"pic_square=@%", profileFriend.pic_square);
  253.         NSLog(@"uid=@%", profileFriend.uid);
  254.         NSLog(@"name=@%", profileFriend.name);
  255.         NSLog(@"status=@%", profileFriend.status);
  256.         NSLog(@"===================");
  257.         NSString *oldURL = profileFriend.pic_square;
  258.         NSString *newURL = [userInfo valueForKey:@"pic_square"];
  259.         if ((oldURL == nil && newURL != nil) || (oldURL != nil && newURL != nil && ![oldURL isEqualToString:newURL])) {
  260.             ref = [[Ref alloc] init];
  261.             ref.string1 = profileFriend.uid;
  262.             ref.string2 = @"pic_square";
  263.             ref.string3 = profileFriend.pic_square;
  264.         }
  265.  
  266.         // edit existing
  267.         profileFriend = [DictionaryToObject populateFriendObject:profileFriend withResult:userInfo];
  268.     }
  269.  
  270.     [self commitTransaction];
  271.  
  272.     return ref;
  273.  
  274. }
  275.  
  276. - (void)deleteObjects:(NSString *)objectType whereField:(NSString *)fieldKey equals:(NSString *)fieldValue {
  277.     NSArray *results = [self.dataOutputAdapter getDBRecordsOnTable:objectType whereField:fieldKey equals:fieldValue];
  278.     if (results != nil) {
  279.         for (NSManagedObject *obj in results) {
  280.             [self.managedObjectContext deleteObject:obj];
  281.         }
  282.         [self commitTransaction];
  283.     }
  284. }
  285.  
  286. - (BOOL)isNameForPerson:(NSString *)uid {
  287.     if (uid != nil) {
  288.         return [self.preferences getNameForUID:uid] != nil || [self.dataOutputAdapter getDBRecordOnTable:@"guroo_friends" whereField:@"uid" equals:uid] != nil;
  289.     } else {
  290.         return YES;
  291.     }
  292. }
  293.  
  294. - (NSString *)toString:(NSObject *)obj {
  295.     if (obj == nil) {
  296.         return @"";
  297.     }
  298.     if ([obj isKindOfClass:[NSNumber class]]) {
  299.         return [((NSNumber *) obj) stringValue];
  300.     }
  301.     return obj;
  302. }
  303.  
  304. - (NSMutableArray *)saveStatusResults:(NSArray *)objs {
  305.     // list of new or modified keys
  306.     NSString *modifiedKey = @"updated_time";
  307.     NSMutableArray *modifiedEntityKeys = [[NSMutableArray alloc] init];
  308.     BOOL contentToSave = NO;
  309.     int addCount = 0;
  310.     for (int i = 0; i < [objs count]; i++) {
  311.         NSDictionary *obj = [objs objectAtIndex:i];
  312.         NSString *idValue = [obj valueForKey:@"id"];
  313.         if ([idValue isKindOfClass:[NSNumber class]]) {
  314.             idValue = [((NSNumber *) idValue) stringValue];
  315.         }
  316.         NSManagedObject *mo = [self.dataOutputAdapter getDBRecordOnTable:@"status" whereField:@"status_id" equals:idValue];
  317.         if (mo == nil) {
  318.             //NSLog(@"----------------------->ADD %@, id: %@",t,idValue);
  319.             addCount++;
  320.             mo = [NSEntityDescription
  321.                     insertNewObjectForEntityForName:@"status"
  322.                              inManagedObjectContext:self.managedObjectContext];
  323.         } else {
  324.             // don't add again
  325.         }
  326.         mo = [DictionaryToObject populateManagedObject:mo ofType:@"status" withResult:obj graph:YES];
  327.         [modifiedEntityKeys addObject:idValue];
  328.         contentToSave = YES;
  329.         [self saveGraphComments:[obj objectForKey:@"comments"] forObjectID:idValue];
  330.         [self saveGraphLikes:[obj objectForKey:@"likes"] forObjectID:idValue];
  331.     }
  332.     if (contentToSave) {
  333.         [self.preferences addToTotalForFeed:STATUSUPDATES amount:addCount];
  334.         [self commitTransaction];
  335.     }
  336.     return modifiedEntityKeys;
  337. }
  338.  
  339. - (NSMutableArray *)saveStreamResults:(NSArray *)objs {
  340.     NSObject *paging = nil;
  341.     if (objs != nil && [objs isKindOfClass:[NSDictionary class]]) {
  342.         objs = [((NSDictionary *) objs) objectForKey:@"data"];
  343.     }
  344.  
  345.     // list of new or modified keys
  346.     NSString *modifiedKey = @"updated_time";
  347.     NSMutableArray *modifiedEntityKeys = [[NSMutableArray alloc] init];
  348.     BOOL contentToSave = NO;
  349.  
  350.     int addCount = 0;
  351.     for (int i = 0; i < [objs count]; i++) {
  352.         NSDictionary *obj = [objs objectAtIndex:i];
  353.         NSString *idValue = [obj valueForKey:@"id"];
  354.         /*for(NSString *aKey in obj){
  355.               NSLog(aKey);
  356.           }*/
  357.         NSString *type = [obj valueForKey:@"type"];
  358.         /*if (type != nil && [type isEqualToString:@"status"]){
  359.               continue;
  360.           }*/
  361.  
  362.         NSDictionary *from = [obj objectForKey:@"from"];
  363.         NSString *fromID = [from objectForKey:@"id"];
  364.         // filter out status updates
  365.         if ([type isEqualToString:@"status"] && [fromID isEqualToString:[self.preferences getLoggedInUserID]]) {
  366.             NSLog(@"IGNORED %@", [obj objectForKey:@"message"]);
  367.             continue;
  368.         }
  369.         if ([idValue isKindOfClass:[NSNumber class]]) {
  370.             idValue = [((NSNumber *) idValue) stringValue];
  371.         }
  372.         idValue = [DictionaryToObject extractID:idValue];
  373.         NSManagedObject *mo = [self.dataOutputAdapter getDBRecordOnTable:@"stream" whereField:@"post_id" equals:idValue];
  374.         if (mo == nil) {
  375.             //NSLog(@"----------------------->ADD %@, id: %@",t,idValue);
  376.             addCount++;
  377.             mo = [NSEntityDescription
  378.                     insertNewObjectForEntityForName:@"stream"
  379.                              inManagedObjectContext:self.managedObjectContext];
  380.         } else {
  381.             // don't add again
  382.         }
  383.         mo = [DictionaryToObject populateManagedObject:mo ofType:@"stream" withResult:obj graph:YES];
  384.         [modifiedEntityKeys addObject:idValue];
  385.         contentToSave = YES;
  386.         [self saveGraphComments:[obj objectForKey:@"comments"] forObjectID:idValue];
  387.         [self saveGraphLikes:[obj objectForKey:@"likes"] forObjectID:idValue];
  388.     }
  389.     if (contentToSave) {
  390.         [self.preferences addToTotalForFeed:WALLPOST amount:addCount];
  391.         [self commitTransaction];
  392.     }
  393.     return modifiedEntityKeys;
  394. }
  395.  
  396. - (NSMutableArray *)saveAlbumsList:(NSArray *)albums {
  397.     NSMutableArray *newOrModified = [self saveEntityType:@"album" objs:albums keyField:@"aid" recordAuxField:@"object_id,cover_pid" assocFeedIndex:ALBUM];
  398.     [self saveLazyJobDirectivesFor:newOrModified assocFeedType:ALBUM];
  399.     return newOrModified;
  400. }
  401.  
  402. - (NSMutableArray *)saveNoteResults:(NSArray *)noteResults {
  403.     return [self saveEntityType:@"note" objs:noteResults keyField:@"note_id" assocFeedIndex:NOTE];
  404. }
  405.  
  406. - (void)saveThreadResults:(NSArray *)threadResults {
  407.     NSMutableArray *newOrModified = [self saveEntityType:@"thread" objs:threadResults keyField:@"thread_id" assocFeedIndex:INBOX];
  408.     [self saveLazyJobDirectivesFor:newOrModified assocFeedType:INBOX];
  409. }
  410. /*
  411. -(NSMutableArray *) savePhotosList: (NSArray *) photos{
  412.     return [self saveEntityType:@"photo" objs:albums keyField:@"pid" recordAuxField:@"object_id" assocFeedIndex:PHOTO];
  413. }*/
  414.  
  415. // LEVEL 2 Entities
  416. - (void)saveComments:(NSArray *)comments {
  417.     [self saveChildEntityType:@"comment" objs:comments parentRefField:@"object_id"];
  418. }
  419.  
  420. - (void)saveStreamComments:(NSArray *)comments {
  421.     [self saveChildEntityType:@"comment" objs:comments parentRefField:@"object_id,post_id"];
  422. }
  423.  
  424. - (void)saveMessageResults:(NSArray *)messages {
  425.     [self saveChildEntityType:@"message" objs:messages parentRefField:@"thread_id"];
  426. }
  427.  
  428. - (void)saveLikeResults:(NSArray *)likes {
  429.     [self saveChildEntityType:@"like" objs:likes parentRefField:@"object_id"];
  430. }
  431.  
  432. - (void)savePhotoTagResults:(NSArray *)photoTags {
  433.     [self saveChildEntityType:@"photo_tag" objs:photoTags parentRefField:@"pid"];
  434. }
  435.  
  436. - (NSArray *)extractGraphData:(NSArray *)data {
  437.     if (data != nil && [data isKindOfClass:[NSDictionary class]]) {
  438.         return [((NSDictionary *) data) objectForKey:@"data"];
  439.     }
  440.     return data;
  441. }
  442.  
  443. - (int)saveGraphComments:(NSArray *)newComments forObjectID:(NSString *)objID {
  444.     newComments = [self extractGraphData:newComments];
  445.  
  446.     // delete old ones
  447.     NSArray *cms = [self.dataOutputAdapter getDBRecordsOnTable:@"comment" whereField:@"object_id" equals:objID];
  448.     if (cms != nil) {
  449.         for (NSManagedObject *comment in cms) {
  450.             [self.managedObjectContext deleteObject:comment];
  451.         }
  452.     }
  453.     comment *c;
  454.     NSDictionary *from;
  455.     NSString *commentID;
  456.     for (NSDictionary *dict in newComments) {
  457.         c = [NSEntityDescription
  458.                 insertNewObjectForEntityForName:@"comment"
  459.                          inManagedObjectContext:self.managedObjectContext];
  460.         from = [dict objectForKey:@"from"];
  461.         commentID = [dict valueForKey:@"id"];
  462.         c.text = [dict valueForKey:@"message"];
  463.         c.time = [DictionaryToObject parseDate:[dict valueForKey:@"created_time"]];
  464.         c.fromid = [DictionaryToObject parseString:[from valueForKey:@"id"]];
  465.         c.object_id = objID;
  466.         c.xid = [DictionaryToObject extractID:commentID];
  467.         if (![self isNameForPerson:c.fromid]) {
  468.             [self.preferences setNameForUID:[from valueForKey:@"name"] :c.fromid];
  469.         }
  470.     }
  471.     [self commitTransaction];
  472.     return newComments != nil ? [newComments count] : 0;
  473. }
  474.  
  475. - (int)saveGraphLikes:(NSArray *)newLikes forObjectID:(NSString *)objID {
  476.     newLikes = [self extractGraphData:newLikes];
  477.  
  478.     // delete old ones
  479.     NSArray *likes = [self.dataOutputAdapter getDBRecordsOnTable:@"like" whereField:@"object_id" equals:objID];
  480.     if (likes != nil) {
  481.         for (NSManagedObject *like in likes) {
  482.             [self.managedObjectContext deleteObject:like];
  483.         }
  484.     }
  485.     like *l;
  486.     for (NSDictionary *dict in newLikes) {
  487.         l = [NSEntityDescription
  488.                 insertNewObjectForEntityForName:@"like"
  489.                          inManagedObjectContext:self.managedObjectContext];
  490.         l.user_id = [dict valueForKey:@"id"];
  491.         l.object_id = objID;
  492.         if (![self isNameForPerson:[dict valueForKey:@"id"]]) {
  493.             [self.preferences setNameForUID:[dict valueForKey:@"name"] :[dict valueForKey:@"id"]];
  494.         }
  495.     }
  496.     [self commitTransaction];
  497.     return newLikes != nil ? [newLikes count] : 0;
  498. }
  499.  
  500. // exceptions
  501.  
  502. - (NSMutableArray *)saveFriendListResults:(NSArray *)friendListConnections {
  503.     BOOL contentToSave = NO;
  504.  
  505.     // delete old ones
  506.     NSMutableArray *oldFriends = [self.dataOutputAdapter getDBRecordsOnTable:@"guroo_friends"];
  507.     NSLog(@"DataInputAdapter: deleting %i old friends before saving %i ones", [oldFriends count], [friendListConnections count]);
  508.  
  509.     // while deleting, store all friend lists and their pic url for use later
  510.     NSMutableDictionary *oldFriendListPhotoDetails = [[NSMutableDictionary alloc] init];
  511.  
  512.     for (NSManagedObject *oldManagedObj in oldFriends) {
  513.         // save the pic_square against the uid - we will check later if the pic_square url has changed
  514.         [oldFriendListPhotoDetails setValue:((guroo_friends *) oldManagedObj).pic_square forKey:((guroo_friends *) oldManagedObj).uid];
  515.         [self.managedObjectContext deleteObject:oldManagedObj];
  516.     }
  517.  
  518.     int addCount = 0;
  519.  
  520.     NSMutableArray *newOrUpdatedPhotoRefs = [[NSMutableArray alloc] init];
  521.  
  522.     for (int i = 0; i < [friendListConnections count]; i++) {
  523.         addCount++;
  524.         contentToSave = YES;
  525.         guroo_friends *gf = (guroo_friends *) [NSEntityDescription
  526.                 insertNewObjectForEntityForName:@"guroo_friends"
  527.                          inManagedObjectContext:self.managedObjectContext];
  528.         gf = [DictionaryToObject populateFriendObject:gf withResult:[friendListConnections objectAtIndex:i]];
  529.         Ref *ref = [[Ref alloc] init];
  530.         NSString *oldURL = [oldFriendListPhotoDetails valueForKey:gf.uid];
  531.         NSString *newURL = gf.pic_square;
  532.         ref.string1 = gf.uid;
  533.         ref.string2 = @"pic_square";
  534.         ref.string3 = gf.pic_square;
  535.         if ((oldURL == nil && newURL != nil) || (oldURL != nil && newURL != nil && ![oldURL isEqualToString:newURL])) {
  536.             // brand new photo
  537.             [newOrUpdatedPhotoRefs addObject:ref];
  538.             //NSLog(@"DataInputAdapter: will download pic_square for '%@' with uid=%@",gf.name,gf.uid);
  539.         }
  540.     }
  541.  
  542.     for (Ref *updatedPhoto in newOrUpdatedPhotoRefs) {
  543.         NSManagedObject *oldPhoto = [self.dataOutputAdapter getDBRecordOnTable:@"guroo_image" whereField:@"pid" equals:updatedPhoto.string1 andOtherField:@"srcfield" equals:@"pic_big"];
  544.         if (oldPhoto != nil)
  545.             [self.managedObjectContext deleteObject:oldPhoto];
  546.     }
  547.  
  548.     if (contentToSave) {
  549.         if (addCount > 0) {
  550.             [self.preferences setTotalForFeed:FRIEND amount:addCount];
  551.         }
  552.         NSLog(@"DataInputAdapter: saving %i friends", [friendListConnections count]);
  553.         [self commitTransaction];
  554.     }
  555.     return newOrUpdatedPhotoRefs;
  556. }
  557.  
  558. - (void)savePhotoBinary:(UIImage *)image forURL:(NSString *)url andPID:(NSString *)pid fromField:(NSString *)srcfield {
  559.     if (image != nil && pid != nil) {
  560.         NSData *imageData = UIImagePNGRepresentation(image);
  561.         guroo_image *gi = (guroo_image *) [NSEntityDescription
  562.                 insertNewObjectForEntityForName:@"guroo_image"
  563.                          inManagedObjectContext:self.managedObjectContext];
  564.         gi.url = url;
  565.         gi.pid = pid;
  566.         gi.binary = imageData;
  567.         gi.srcfield = srcfield;
  568.         //NSLog(@"DataInputAdapter: saving photo for id %@,%@,%@",srcfield,pid,url);
  569.         [self commitTransaction];
  570.  
  571.         /*[NSThread detachNewThreadSelector:@selector(commitTransaction)
  572.                                    toTarget:self
  573.                                  withObject:nil];*/
  574.     }
  575. }
  576.  
  577. - (NSMutableArray *)saveAlbumCoverPhotos:(NSArray *)photos {
  578.  
  579.     NSMutableArray *modified = [[NSMutableArray alloc] init];
  580.  
  581.     BOOL contentToSave = NO;
  582.  
  583.     for (NSDictionary *photoObj in photos) {
  584.         NSString *pid = [photoObj valueForKey:@"pid"];
  585.         photo *photoDB = (photo *) [self.dataOutputAdapter getDBRecordOnTable:@"photo" whereField:@"pid" equals:pid];
  586.         if (photoDB == nil) {
  587.             // add new
  588.             photoDB = (photo *) [NSEntityDescription
  589.                     insertNewObjectForEntityForName:@"photo"
  590.                              inManagedObjectContext:self.managedObjectContext];
  591.  
  592.             // add modified reference
  593.             Ref *ref = [[Ref alloc] init];
  594.             ref.string1 = pid;
  595.             ref.string2 = @"src";
  596.             ref.string3 = [photoObj valueForKey:@"src"];
  597.             [modified addObject:ref];
  598.  
  599.             photoDB = [DictionaryToObject populatePhotoObject:photoDB withResult:photoObj];
  600.             contentToSave = YES;
  601.         } else {
  602.             // one already - check modified
  603.             NSDate *oldModified = photoDB.modified;
  604.             if ([self dateInField:@"modified" inDict:photoObj isGreaterThan:oldModified]) {
  605.  
  606.                 // add modified reference
  607.                 Ref *ref = [[Ref alloc] init];
  608.                 ref.string1 = pid;
  609.                 ref.string2 = @"src";
  610.                 ref.string3 = [photoObj valueForKey:@"src"];
  611.                 [modified addObject:ref];
  612.  
  613.                 photoDB = [DictionaryToObject populatePhotoObject:photoDB withResult:photoObj];
  614.                 contentToSave = YES;
  615.             }
  616.         }
  617.  
  618.     }
  619.     if (contentToSave == YES) {
  620.         [self commitTransaction];
  621.     }
  622.     return modified;
  623. }
  624.  
  625. - (NSArray *)savePhotos:(NSArray *)photos forAlbum:(NSString *)aid returnAllRefs:(BOOL)returnAllRefs {
  626.     BOOL contentToSave = NO;
  627.  
  628.     // delete old ones
  629.     NSMutableArray *oldPhotos = [self.dataOutputAdapter getDBRecordsOnTable:@"photo" whereField:@"aid" equals:aid];
  630.     NSLog(@"DataInputAdapter: deleting %i old photos before saving new ones", [oldPhotos count]);
  631.  
  632.     // TODO DELETE BIG VERSIONS OF PICTURES IF CHANGED
  633.  
  634.     // while deleting, store all photos and their modified date for use later
  635.     NSMutableDictionary *pidToModified = [[NSMutableDictionary alloc] init];
  636.  
  637.     for (NSManagedObject *oldManagedObj in oldPhotos) {
  638.         [pidToModified setObject:((photo *) oldManagedObj).modified forKey:((photo *) oldManagedObj).pid];
  639.         [self.managedObjectContext deleteObject:oldManagedObj];
  640.         contentToSave = NO;
  641.     }
  642.  
  643.     // tally up list of modified or new photos
  644.     NSMutableArray *modifiedOrNewPhotos = [[NSMutableArray alloc] init];
  645.  
  646.     // save new batch
  647.     NSDictionary *obj;
  648.     photo *p;
  649.     for (int i = 0; i < [photos count]; i++) {
  650.         obj = [photos objectAtIndex:i];
  651.         p = (photo *) [NSEntityDescription
  652.                 insertNewObjectForEntityForName:@"photo"
  653.                          inManagedObjectContext:self.managedObjectContext];
  654.         p = [DictionaryToObject populatePhotoObject:p withResult:obj];
  655.         NSDate *oldModified = ((NSDate *) [pidToModified objectForKey:p.pid]);
  656.         Ref *ref = [[Ref alloc] init];
  657.         ref.string1 = p.pid;
  658.         ref.string2 = @"src";
  659.         ref.string3 = p.src;
  660.         ref.string4 = p.object_id;
  661.         if (oldModified == nil || returnAllRefs) {
  662.             // brand new photo
  663.             [modifiedOrNewPhotos addObject:ref];
  664.         } else if ([self date:p.modified isGreaterThan:oldModified]) {
  665.             // updated photo
  666.             [modifiedOrNewPhotos addObject:ref];
  667.         }
  668.         contentToSave = YES;
  669.     }
  670.     if (contentToSave == YES) {
  671.         [self commitTransaction];
  672.     }
  673.     return modifiedOrNewPhotos;
  674. }
  675.  
  676. - (NSArray *)savePhotos:(NSArray *)photos forAlbum:(NSString *)aid {
  677.     return [self savePhotos:photos forAlbum:aid returnAllRefs:NO];
  678. }
  679.  
  680. - (void)saveOverallSyncDate {
  681.     SyncedDate *syncDate = ((SyncedDate *) [self.dataOutputAdapter getDBRecordOnTable:@"SyncedDate"
  682.                                                                            whereField:@"key" equals:@"overall"]);
  683.     if (syncDate == nil) {
  684.         syncDate = (SyncedDate *) [NSEntityDescription
  685.                 insertNewObjectForEntityForName:@"SyncedDate"
  686.                          inManagedObjectContext:self.managedObjectContext];
  687.     }
  688.     syncDate.date = [[NSDate alloc] init];
  689.     syncDate.key = @"overall";
  690.     [self commitTransaction];
  691. }
  692.  
  693. - (void)saveSyncDateForJob:(double)job {
  694.     SyncedDate *syncDate = ((SyncedDate *) [self.dataOutputAdapter getDBRecordOnTable:@"SyncedDate"
  695.                                                                            whereField:@"key" equals:[NSString stringWithFormat:@"%f", job]]);
  696.     if (syncDate == nil) {
  697.         syncDate = (SyncedDate *) [NSEntityDescription
  698.                 insertNewObjectForEntityForName:@"SyncedDate"
  699.                          inManagedObjectContext:self.managedObjectContext];
  700.     }
  701.     syncDate.date = [[NSDate alloc] init];
  702.     syncDate.key = [NSString stringWithFormat:@"%f", job];
  703.     [self commitTransaction];
  704. }
  705.  
  706. - (void)saveSyncDateForFeedType:(FeedType)feedType {
  707.     SyncedDate *syncDate = ((SyncedDate *) [self.dataOutputAdapter getDBRecordOnTable:@"SyncedDate"
  708.                                                                            whereField:@"key" equals:[NSString stringWithFormat:@"%i", feedType]]);
  709.     if (syncDate == nil) {
  710.         syncDate = (SyncedDate *) [NSEntityDescription
  711.                 insertNewObjectForEntityForName:@"SyncedDate"
  712.                          inManagedObjectContext:self.managedObjectContext];
  713.     }
  714.     syncDate.date = [[NSDate alloc] init];
  715.     syncDate.key = [NSString stringWithFormat:@"%i", feedType];
  716.     [self commitTransaction];
  717. }
  718.  
  719. - (void)saveStreamStartDate:(NSDate *)theDate {
  720.     SyncedDate *syncDate = ((SyncedDate *) [self.dataOutputAdapter getDBRecordOnTable:@"SyncedDate"
  721.                                                                            whereField:@"key" equals:@"streamstart"]);
  722.     if (syncDate == nil) {
  723.         syncDate = (SyncedDate *) [NSEntityDescription
  724.                 insertNewObjectForEntityForName:@"SyncedDate"
  725.                          inManagedObjectContext:self.managedObjectContext];
  726.     }
  727.     syncDate.date = theDate;
  728.     syncDate.key = @"streamstart";
  729.     [self commitTransaction];
  730. }
  731.  
  732.  
  733. @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement