#238: Migration code

This commit is contained in:
Patrick Santana 2012-10-16 10:42:15 +02:00
parent 01116aa515
commit ff1a6eecea
15 changed files with 969 additions and 2 deletions

View file

@ -77,4 +77,9 @@ extern NSString * const kSyncShowUploadedPhotos;
#define NSLog(__FORMAT__, ...) TFLog((@"%s [Line %d] " __FORMAT__), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__) #define NSLog(__FORMAT__, ...) TFLog((@"%s [Line %d] " __FORMAT__), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
// Facebook
extern NSString * const kFacebookUserConnected;
extern NSString * const kFacebookUserConnectedEmail;
extern NSString * const kFacebookUserConnectedUsername;
@end @end

View file

@ -94,5 +94,11 @@ NSString * const kValidateNotAllowedLocation=@"validate_not_allowed_location";
*/ */
NSString * const kSyncShowUploadedPhotos=@"sync_show_uploaded_photos"; NSString * const kSyncShowUploadedPhotos=@"sync_show_uploaded_photos";
/*
* Facebook
*/
NSString * const kFacebookUserConnected=@"facebook_user_connected";
NSString * const kFacebookUserConnectedEmail=@"facebook_user_connected_email";
NSString * const kFacebookUserConnectedUsername=@"facebook_user_connected_username";
@end @end

View file

@ -0,0 +1,53 @@
//
// CoreDataTableViewController.h
//
// Created for Stanford CS193p Fall 2011.
// Copyright 2011 Stanford University. All rights reserved.
//
// This class mostly just copies the code from NSFetchedResultsController's documentation page
// into a subclass of UITableViewController.
//
// Just subclass this and set the fetchedResultsController.
// The only UITableViewDataSource method you'll HAVE to implement is tableView:cellForRowAtIndexPath:.
// And you can use the NSFetchedResultsController method objectAtIndexPath: to do it.
//
// Remember that once you create an NSFetchedResultsController, you CANNOT modify its @propertys.
// If you want new fetch parameters (predicate, sorting, etc.),
// create a NEW NSFetchedResultsController and set this class's fetchedResultsController @property again.
//
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
@interface CoreDataTableViewController : UITableViewController <NSFetchedResultsControllerDelegate>
// The controller (this class fetches nothing if this is not set).
@property (strong, nonatomic) NSFetchedResultsController *fetchedResultsController;
// Causes the fetchedResultsController to refetch the data.
// You almost certainly never need to call this.
// The NSFetchedResultsController class observes the context
// (so if the objects in the context change, you do not need to call performFetch
// since the NSFetchedResultsController will notice and update the table automatically).
// This will also automatically be called if you change the fetchedResultsController @property.
- (void)performFetch;
// Turn this on before making any changes in the managed object context that
// are a one-for-one result of the user manipulating rows directly in the table view.
// Such changes cause the context to report them (after a brief delay),
// and normally our fetchedResultsController would then try to update the table,
// but that is unnecessary because the changes were made in the table already (by the user)
// so the fetchedResultsController has nothing to do and needs to ignore those reports.
// Turn this back off after the user has finished the change.
// Note that the effect of setting this to NO actually gets delayed slightly
// so as to ignore previously-posted, but not-yet-processed context-changed notifications,
// therefore it is fine to set this to YES at the beginning of, e.g., tableView:moveRowAtIndexPath:toIndexPath:,
// and then set it back to NO at the end of your implementation of that method.
// It is not necessary (in fact, not desirable) to set this during row deletion or insertion
// (but definitely for row moves).
@property (nonatomic) BOOL suspendAutomaticTrackingOfChangesInManagedObjectContext;
// Set to YES to get some debugging output in the console.
@property BOOL debug;
@end

View file

@ -0,0 +1,177 @@
//
// CoreDataTableViewController.m
//
// Created for Stanford CS193p Fall 2011.
// Copyright 2011 Stanford University. All rights reserved.
//
#import "CoreDataTableViewController.h"
@interface CoreDataTableViewController()
@property (nonatomic) BOOL beganUpdates;
@end
@implementation CoreDataTableViewController
#pragma mark - Properties
@synthesize fetchedResultsController = _fetchedResultsController;
@synthesize suspendAutomaticTrackingOfChangesInManagedObjectContext = _suspendAutomaticTrackingOfChangesInManagedObjectContext;
@synthesize debug = _debug;
@synthesize beganUpdates = _beganUpdates;
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return YES;
}
#pragma mark - Fetching
- (void)performFetch
{
if (self.fetchedResultsController) {
if (self.fetchedResultsController.fetchRequest.predicate) {
if (self.debug) NSLog(@"[%@ %@] fetching %@ with predicate: %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), self.fetchedResultsController.fetchRequest.entityName, self.fetchedResultsController.fetchRequest.predicate);
} else {
if (self.debug) NSLog(@"[%@ %@] fetching all %@ (i.e., no predicate)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), self.fetchedResultsController.fetchRequest.entityName);
}
NSError *error = nil;
[self.fetchedResultsController performFetch:&error];
if (error) NSLog(@"[%@ %@] %@ (%@)", NSStringFromClass([self class]), NSStringFromSelector(_cmd), [error localizedDescription], [error localizedFailureReason]);
} else {
if (self.debug) NSLog(@"[%@ %@] no NSFetchedResultsController (yet?)", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
}
[self.tableView reloadData];
}
- (void)setFetchedResultsController:(NSFetchedResultsController *)newfrc
{
NSFetchedResultsController *oldfrc = _fetchedResultsController;
if (newfrc != oldfrc) {
_fetchedResultsController = newfrc;
newfrc.delegate = self;
if ((!self.title || [self.title isEqualToString:oldfrc.fetchRequest.entity.name]) && (!self.navigationController || !self.navigationItem.title)) {
self.title = newfrc.fetchRequest.entity.name;
}
if (newfrc) {
if (self.debug) NSLog(@"[%@ %@] %@", NSStringFromClass([self class]), NSStringFromSelector(_cmd), oldfrc ? @"updated" : @"set");
[self performFetch];
} else {
if (self.debug) NSLog(@"[%@ %@] reset to nil", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
[self.tableView reloadData];
}
}
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [[[self.fetchedResultsController sections] objectAtIndex:section] numberOfObjects];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [[[self.fetchedResultsController sections] objectAtIndex:section] name];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index
{
return [self.fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
return [self.fetchedResultsController sectionIndexTitles];
}
#pragma mark - NSFetchedResultsControllerDelegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
if (!self.suspendAutomaticTrackingOfChangesInManagedObjectContext) {
[self.tableView beginUpdates];
self.beganUpdates = YES;
}
}
- (void)controller:(NSFetchedResultsController *)controller
didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex
forChangeType:(NSFetchedResultsChangeType)type
{
if (!self.suspendAutomaticTrackingOfChangesInManagedObjectContext)
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
}
- (void)controller:(NSFetchedResultsController *)controller
didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath
forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath
{
if (!self.suspendAutomaticTrackingOfChangesInManagedObjectContext)
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeMove:
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
if (self.beganUpdates) {
self.beganUpdates = NO;
[self.tableView endUpdates];
}
}
- (void)endSuspensionOfUpdatesDueToContextChanges
{
_suspendAutomaticTrackingOfChangesInManagedObjectContext = NO;
}
- (void)setSuspendAutomaticTrackingOfChangesInManagedObjectContext:(BOOL)suspend
{
if (suspend) {
_suspendAutomaticTrackingOfChangesInManagedObjectContext = YES;
} else {
[self performSelector:@selector(endSuspensionOfUpdatesDueToContextChanges) withObject:0 afterDelay:0];
}
}
@end

View file

@ -0,0 +1,40 @@
//
// CoreLocationController.h
// OpenPhoto
//
// Created by Patrick Santana on 02/11/11.
// Copyright 2012 OpenPhoto
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import <CoreLocation/CoreLocation.h>
@protocol CoreLocationControllerDelegate
@required
- (void)locationUpdate:(CLLocation *)location;
- (void)locationError:(NSError *)error;
@end
@interface CoreLocationController : NSObject <CLLocationManagerDelegate> {
CLLocationManager *locMgr;
id delegate;
}
@property (nonatomic, strong) CLLocationManager *locMgr;
@property (nonatomic, assign) id delegate;
@end

View file

@ -0,0 +1,51 @@
//
// CoreLocationController.m
// OpenPhoto
//
// Created by Patrick Santana on 02/11/11.
// Copyright 2012 OpenPhoto
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#import "CoreLocationController.h"
@implementation CoreLocationController
@synthesize locMgr=_locMgr;
@synthesize delegate=_delegate;
- (id)init {
self = [super init];
if(self != nil) {
self.locMgr = [[CLLocationManager alloc] init];
self.locMgr.delegate = self;
}
return self;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
if([self.delegate conformsToProtocol:@protocol(CoreLocationControllerDelegate)]) {
[self.delegate locationUpdate:newLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
if([self.delegate conformsToProtocol:@protocol(CoreLocationControllerDelegate)]) {
[self.delegate locationError:error];
}
}
@end

View file

@ -1,4 +1,37 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?> <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model name="Test1.xcdatamodel" userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="1" systemVersion="11A491" minimumToolsVersion="Automatic" macOSVersion="Automatic" iOSVersion="Automatic"> <model name="" userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="1811" systemVersion="12C60" minimumToolsVersion="Automatic" macOSVersion="Automatic" iOSVersion="Automatic">
<elements/> <entity name="Synced" representedClassName="Synced" syncable="YES">
<attribute name="fileHash" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="filePath" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="status" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="userUrl" optional="YES" attributeType="String" syncable="YES"/>
</entity>
<entity name="Timeline" representedClassName="Timeline" syncable="YES">
<attribute name="date" optional="YES" attributeType="Date" syncable="YES"/>
<attribute name="dateUploaded" optional="YES" attributeType="Date" syncable="YES"/>
<attribute name="facebook" optional="YES" attributeType="Boolean" syncable="YES"/>
<attribute name="fileName" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="key" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="latitude" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="longitude" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="permission" optional="YES" attributeType="Boolean" syncable="YES"/>
<attribute name="photoDataTempUrl" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="photoDataThumb" optional="YES" attributeType="Binary" syncable="YES"/>
<attribute name="photoPageUrl" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="photoToUpload" optional="YES" attributeType="Boolean" syncable="YES"/>
<attribute name="photoUploadMultiplesUrl" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="photoUploadProgress" optional="YES" attributeType="Float" defaultValueString="0.0" syncable="YES"/>
<attribute name="photoUploadResponse" optional="YES" attributeType="Binary" syncable="YES"/>
<attribute name="photoUrl" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="status" optional="YES" attributeType="String" indexed="YES" syncable="YES"/>
<attribute name="syncedUrl" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="tags" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="title" optional="YES" attributeType="String" syncable="YES"/>
<attribute name="twitter" optional="YES" attributeType="Boolean" syncable="YES"/>
<attribute name="userUrl" optional="YES" attributeType="String" syncable="YES"/>
</entity>
<elements>
<element name="Synced" positionX="160" positionY="192" width="128" height="105"/>
<element name="Timeline" positionX="160" positionY="192" width="128" height="375"/>
</elements>
</model> </model>

30
Photo/Synced+Photo.h Normal file
View file

@ -0,0 +1,30 @@
//
// SyncPhotos.h
// Photo
//
// Created by Patrick Santana on 21/05/12.
// Copyright 2012 Photo
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "Synced.h"
@interface Synced (Photo)
// constant
extern NSString * const kSyncedStatusTypeUploaded;
+ (NSMutableArray *) getPathsInManagedObjectContext:(NSManagedObjectContext *)context;
+ (void) deleteAllSyncedPhotosInManagedObjectContext:(NSManagedObjectContext *)context;
@end

78
Photo/Synced+Photo.m Normal file
View file

@ -0,0 +1,78 @@
//
// Synced+Photo.m
// Photo
//
// Created by Patrick Santana on 21/05/12.
// Copyright 2012 Photo
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "Synced+Photo.h"
@implementation Synced (Photo)
//
// Constast for sync uploaded
//
NSString * const kSyncedStatusTypeUploaded = @"Uploaded";
+ (NSMutableArray *) getPathsInManagedObjectContext:(NSManagedObjectContext *)context
{
NSMutableArray *array = [NSMutableArray array];
// get all syncs and put in the dictionary
// with all paths
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Synced"];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (error){
NSLog(@"Error to get all paths from Synced on managed object context = %@",[error localizedDescription]);
return nil;
}
for (Synced *model in matches) {
[array addObject:model.filePath];
}
return array;
}
+ (void) deleteAllSyncedPhotosInManagedObjectContext:(NSManagedObjectContext *)context
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"Synced" inManagedObjectContext:context]];
[fetchRequest setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError *error = nil;
NSArray *photos = [context executeFetchRequest:fetchRequest error:&error];
if (error){
NSLog(@"Error getting timeline to delete all from managed object context = %@",[error localizedDescription]);
}
for (NSManagedObject *photo in photos) {
[context deleteObject:photo];
}
NSError *saveError = nil;
if (![context save:&saveError]){
NSLog(@"Error delete all photos from managed object context = %@",[error localizedDescription]);
}
// now we can release the object
[fetchRequest release];
}
@end

20
Photo/Synced.h Normal file
View file

@ -0,0 +1,20 @@
//
// Synced.h
// Photo
//
// Created by Patrick Santana on 15/10/12.
// Copyright (c) 2012 Photo Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface Synced : NSManagedObject
@property (nonatomic, retain) NSString * fileHash;
@property (nonatomic, retain) NSString * filePath;
@property (nonatomic, retain) NSString * status;
@property (nonatomic, retain) NSString * userUrl;
@end

19
Photo/Synced.m Normal file
View file

@ -0,0 +1,19 @@
//
// Synced.m
// Photo
//
// Created by Patrick Santana on 15/10/12.
// Copyright (c) 2012 Photo Project. All rights reserved.
//
#import "Synced.h"
@implementation Synced
@dynamic fileHash;
@dynamic filePath;
@dynamic status;
@dynamic userUrl;
@end

54
Photo/Timeline+Photo.h Normal file
View file

@ -0,0 +1,54 @@
//
// NewestPhotos+Photo.h
// Photo
//
// Created by Patrick Santana on 22/03/12.
// Copyright 2012 Photo
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "Timeline.h"
#import "SHA1.h"
// constant
extern NSString * const kUploadStatusTypeCreating; // this is used while we are creating all UPLOAD entries. After all of them are finish, we changed to CREATED
extern NSString * const kUploadStatusTypeCreated;
extern NSString * const kUploadStatusTypeFailed;
extern NSString * const kUploadStatusTypeDuplicated;
extern NSString * const kUploadStatusTypeUploading;
extern NSString * const kUploadStatusTypeUploadFinished;
// images already in the server
extern NSString * const kUploadStatusTypeUploaded;
@interface Timeline (Photo)
+ (NSArray *) getNewestPhotosInManagedObjectContext:(NSManagedObjectContext *)context;
+ (void) insertIntoCoreData:(NSArray *) rawNewestPhotos InManagedObjectContext:(NSManagedObjectContext *)context;
// From upload
+ (NSArray *) getUploadsInManagedObjectContext:(NSManagedObjectContext *)context;
+ (NSArray *) getUploadsNotUploadedInManagedObjectContext:(NSManagedObjectContext *)context;
+ (void) deleteAllTimelineInManagedObjectContext:(NSManagedObjectContext *)context;
+ (int) howEntitiesTimelineInManagedObjectContext:(NSManagedObjectContext *)context type:(NSString*) type;
+ (NSArray *) getNextWaitingToUploadInManagedObjectContext:(NSManagedObjectContext *)context qtd:(int) quantity;
+ (void) deleteEntitiesInManagedObjectContext:(NSManagedObjectContext *)context state:(NSString*) state;
+ (void) resetEntitiesOnStateUploadingInManagedObjectContext:(NSManagedObjectContext *)context;
+ (void) setUploadsStatusToCreatedInManagedObjectContext:(NSManagedObjectContext *)context;
- (NSDictionary *) toDictionary;
@end

326
Photo/Timeline+Photo.m Normal file
View file

@ -0,0 +1,326 @@
//
// NewestPhotos+Photo.m
// Photo
//
// Created by Patrick Santana on 22/03/12.
// Copyright 2012 Photo
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#import "Timeline+Photo.h"
@implementation Timeline (Photo)
//
// Constast for Upload Status
//
NSString * const kUploadStatusTypeCreating = @"Creating";
NSString * const kUploadStatusTypeCreated = @"Created";
NSString * const kUploadStatusTypeFailed = @"Failed";
NSString * const kUploadStatusTypeUploaded = @"Uploaded";
NSString * const kUploadStatusTypeDuplicated = @"Duplicated";
NSString * const kUploadStatusTypeUploading = @"Uploading";
NSString * const kUploadStatusTypeUploadFinished =@"A_UploadFinished";
+ (NSArray *) getUploadsInManagedObjectContext:(NSManagedObjectContext *) context
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Timeline"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (error){
NSLog(@"Error to get all uploads on managed object context = %@",[error localizedDescription]);
}
NSMutableArray *result = [[NSMutableArray alloc] init];
for (Timeline *model in matches) {
[result addObject:model];
}
// return an array of Uploads
return [result autorelease];
}
+ (NSArray *) getUploadsNotUploadedInManagedObjectContext:(NSManagedObjectContext *)context
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Timeline"];
// status not Uploaded
request.predicate= [NSPredicate predicateWithFormat:@"status != %@", kUploadStatusTypeUploaded];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (error){
NSLog(@"Error to get all uploads on managed object context = %@",[error localizedDescription]);
}
return matches;
}
+ (int) howEntitiesTimelineInManagedObjectContext:(NSManagedObjectContext *)context type:(NSString*) type
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Timeline"];
request.predicate= [NSPredicate predicateWithFormat:@"status == %@", type];
[request setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError *error = nil;
NSArray *result = [context executeFetchRequest:request error:&error];
if (error){
NSLog(@"Error to get how many uploading = %@",[error localizedDescription]);
}
return [result count];
}
+ (void) resetEntitiesOnStateUploadingInManagedObjectContext:(NSManagedObjectContext *)context{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Timeline"];
request.predicate= [NSPredicate predicateWithFormat:@"status == %@", kUploadStatusTypeUploading];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (error){
NSLog(@"Error to get how many uploading = %@",[error localizedDescription]);
}
for (Timeline *model in matches) {
model.status = kUploadStatusTypeFailed;
}
}
+ (NSArray *) getNewestPhotosInManagedObjectContext:(NSManagedObjectContext *)context
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Timeline"];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"dateUploaded" ascending:NO];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (error){
NSLog(@"Error to get all newest photos on managed object context = %@",[error localizedDescription]);
}
return matches;
}
+ (void) deleteAllTimelineInManagedObjectContext:(NSManagedObjectContext *)context
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"Timeline" inManagedObjectContext:context]];
[fetchRequest setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError *error = nil;
NSArray *photos = [context executeFetchRequest:fetchRequest error:&error];
if (error){
NSLog(@"Error getting timeline to delete all from managed object context = %@",[error localizedDescription]);
}
for (NSManagedObject *photo in photos) {
[context deleteObject:photo];
}
NSError *saveError = nil;
if (![context save:&saveError]){
NSLog(@"Error delete all newest photos from managed object context = %@",[saveError localizedDescription]);
}
// now we can release the object
[fetchRequest release];
}
+ (void) insertIntoCoreData:(NSArray *) rawNewestPhotos InManagedObjectContext:(NSManagedObjectContext *)context
{
if ([rawNewestPhotos count]>0){
BOOL checkTotalRows = YES;
for (NSDictionary *raw in rawNewestPhotos){
// check if object exists
if (checkTotalRows){
if ([[raw objectForKey:@"totalRows"] intValue] == 0){
return;
}else{
checkTotalRows = NO;
}
}
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Timeline"];
request.predicate= [NSPredicate predicateWithFormat:@"key==%@",[NSString stringWithFormat:@"%@",[raw objectForKey:@"id"]]];
[request setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (error){
NSLog(@"Error getting a newest photo on managed object context = %@",[error localizedDescription]);
}
if (!matches || [matches count] > 0){
#ifdef DEVELOPMENT_ENABLED
NSLog(@"Object already exist");
#endif
}else {
Timeline *photo = [NSEntityDescription insertNewObjectForEntityForName:@"Timeline"
inManagedObjectContext:context];
// get details URL
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)] == YES && [[UIScreen mainScreen] scale] == 2.00) {
// retina display
photo.photoUrl = [NSString stringWithFormat:@"%@",[raw objectForKey:@"path610x530xCR"]];
}else{
// not retina display
photo.photoUrl = [NSString stringWithFormat:@"%@",[raw objectForKey:@"path305x265xCR"]];
}
NSString *title = [raw objectForKey:@"title"];
if ([title class] == [NSNull class] || [title isEqualToString:@""])
photo.title = [NSString stringWithFormat:@"%@",[raw objectForKey:@"filenameOriginal"]];
else
photo.title = title;
NSArray *tagsResult = [raw objectForKey:@"tags"];
NSMutableString *tags = [NSMutableString string];
if ([tagsResult class] != [NSNull class]) {
int i = 1;
for (NSString *tagDetails in tagsResult){
[tags appendString:[tagDetails stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
if ( i < [tagsResult count])
[tags appendString:@", "];
i++;
}}
photo.tags=tags;
photo.key=[NSString stringWithFormat:@"%@",[raw objectForKey:@"id"]];
// get the date taken since 1970
double d = [[raw objectForKey:@"dateTaken"] doubleValue];
NSTimeInterval date = d;
photo.date = [NSDate dateWithTimeIntervalSince1970:date];
// permission
if ([[raw objectForKey:@"permission"] isEqualToString:@"1"])
photo.permission = [NSNumber numberWithBool:YES];
else
photo.permission = [NSNumber numberWithBool:NO];
// latitude
NSString *latitude = [raw objectForKey:@"latitude"];
if ([latitude class] != [NSNull class] && ![latitude isEqualToString:@""])
photo.latitude = latitude;
// longitude
NSString *longitude = [raw objectForKey:@"longitude"];
if ([longitude class] != [NSNull class] && ![longitude isEqualToString:@""])
photo.longitude = longitude;
// get the date since 1970
double dUpload = [[raw objectForKey:@"dateUploaded"] doubleValue];
NSTimeInterval dateUpload = dUpload;
photo.dateUploaded = [NSDate dateWithTimeIntervalSince1970:dateUpload];
// page url
photo.photoPageUrl = [raw objectForKey:@"url"];
// status
photo.status = kUploadStatusTypeUploaded;
}
}
// save context
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Couldn't save: %@", [error localizedDescription]);
}
}
}
+ (NSArray *) getNextWaitingToUploadInManagedObjectContext:(NSManagedObjectContext *)context qtd:(int) quantity
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Timeline"];
// status not Uploaded
request.predicate= [NSPredicate predicateWithFormat:@"status == %@", kUploadStatusTypeCreated];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"dateUploaded" ascending:NO];
request.sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
// set max to return
[request setFetchLimit:quantity];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (error){
NSLog(@"Error to get all uploads on managed object context = %@",[error localizedDescription]);
}
return matches;
}
+ (void) deleteEntitiesInManagedObjectContext:(NSManagedObjectContext *)context state:(NSString*) state
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"Timeline" inManagedObjectContext:context]];
fetchRequest.predicate= [NSPredicate predicateWithFormat:@"status == %@", state];
[fetchRequest setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError *error = nil;
NSArray *photos = [context executeFetchRequest:fetchRequest error:&error];
if (error){
NSLog(@"Error getting timeline to delete all from managed object context = %@",[error localizedDescription]);
}
for (NSManagedObject *photo in photos) {
[context deleteObject:photo];
}
// now we can release the object
[fetchRequest release];
}
+ (void) setUploadsStatusToCreatedInManagedObjectContext:(NSManagedObjectContext *)context
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Timeline"];
request.predicate= [NSPredicate predicateWithFormat:@"status == %@", kUploadStatusTypeCreating];
NSError *error = nil;
NSArray *matches = [context executeFetchRequest:request error:&error];
if (error){
NSLog(@"Error to get how many uploading = %@",[error localizedDescription]);
}
for (Timeline *model in matches) {
model.status = kUploadStatusTypeCreated;
}
}
- (NSDictionary *) toDictionary
{
NSArray *keys = [NSArray arrayWithObjects: @"date", @"facebook", @"permission", @"status", @"title", @"twitter", @"image", @"fileName",@"tags", nil];
NSArray *objects = [NSArray arrayWithObjects:self.date,self.facebook,self.permission,self.status,self.title,self.twitter,self.photoDataTempUrl,self.fileName,self.tags, nil];
return [NSDictionary dictionaryWithObjects:objects forKeys:keys];
}
@end

38
Photo/Timeline.h Normal file
View file

@ -0,0 +1,38 @@
//
// Timeline.h
// Photo
//
// Created by Patrick Santana on 15/10/12.
// Copyright (c) 2012 Photo Project. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <CoreData/CoreData.h>
@interface Timeline : NSManagedObject
@property (nonatomic, retain) NSDate * date;
@property (nonatomic, retain) NSDate * dateUploaded;
@property (nonatomic, retain) NSNumber * facebook;
@property (nonatomic, retain) NSString * fileName;
@property (nonatomic, retain) NSString * key;
@property (nonatomic, retain) NSString * latitude;
@property (nonatomic, retain) NSString * longitude;
@property (nonatomic, retain) NSNumber * permission;
@property (nonatomic, retain) NSString * photoDataTempUrl;
@property (nonatomic, retain) NSData * photoDataThumb;
@property (nonatomic, retain) NSNumber * photoToUpload;
@property (nonatomic, retain) NSString * photoPageUrl;
@property (nonatomic, retain) NSString * photoUploadMultiplesUrl;
@property (nonatomic, retain) NSNumber * photoUploadProgress;
@property (nonatomic, retain) NSData * photoUploadResponse;
@property (nonatomic, retain) NSString * photoUrl;
@property (nonatomic, retain) NSString * status;
@property (nonatomic, retain) NSString * syncedUrl;
@property (nonatomic, retain) NSString * tags;
@property (nonatomic, retain) NSString * title;
@property (nonatomic, retain) NSNumber * twitter;
@property (nonatomic, retain) NSString * userUrl;
@end

37
Photo/Timeline.m Normal file
View file

@ -0,0 +1,37 @@
//
// Timeline.m
// Photo
//
// Created by Patrick Santana on 15/10/12.
// Copyright (c) 2012 Photo Project. All rights reserved.
//
#import "Timeline.h"
@implementation Timeline
@dynamic date;
@dynamic dateUploaded;
@dynamic facebook;
@dynamic fileName;
@dynamic key;
@dynamic latitude;
@dynamic longitude;
@dynamic permission;
@dynamic photoDataTempUrl;
@dynamic photoDataThumb;
@dynamic photoToUpload;
@dynamic photoPageUrl;
@dynamic photoUploadMultiplesUrl;
@dynamic photoUploadProgress;
@dynamic photoUploadResponse;
@dynamic photoUrl;
@dynamic status;
@dynamic syncedUrl;
@dynamic tags;
@dynamic title;
@dynamic twitter;
@dynamic userUrl;
@end