From 24c07ae318d9b51796c9740edd15e7b1478b080a Mon Sep 17 00:00:00 2001 From: Saeed Date: Sun, 26 Oct 2014 13:41:36 +0330 Subject: [PATCH] #85 impl --- Classes/WADocumentDownloader.h | 10 +- Classes/WADocumentDownloader.m | 214 ++++++++++++------ Classes/WADownloadingView.m | 4 +- Classes/WAGridCell.xib | 16 +- Classes/WAGridView.m | 2 +- Classes/WAModuleViewController.m | 2 +- ...esDownloader.h => WAResourcesDownloader.h} | 2 +- ...esDownloader.m => WAResourcesDownloader.m} | 54 +++-- Classes/WASQLiteParser.m | 2 +- Classes/WAUtilities.h | 1 + Classes/WAUtilities.m | 24 +- Librelio.xcodeproj/project.pbxproj | 16 +- Wind/Tabs.plist | 2 +- 13 files changed, 229 insertions(+), 120 deletions(-) rename Classes/{WAMissingResourcesDownloader.h => WAResourcesDownloader.h} (73%) rename Classes/{WAMissingResourcesDownloader.m => WAResourcesDownloader.m} (78%) diff --git a/Classes/WADocumentDownloader.h b/Classes/WADocumentDownloader.h index bc8959d..30cfa4e 100644 --- a/Classes/WADocumentDownloader.h +++ b/Classes/WADocumentDownloader.h @@ -30,8 +30,9 @@ typedef enum { NSMutableArray * mutableResourcesArray; NSArray * oldResourcesArray; NSString *currentMessage; - CGFloat currentProgress; - + CGFloat currentProgress; + + NSDate *processStartTime; } @property (nonatomic, retain) NSString *urlString; @@ -45,6 +46,7 @@ typedef enum { @property (nonatomic,retain) NSArray * oldResourcesArray; @property (nonatomic,retain) NSString *currentMessage; @property (nonatomic,assign) CGFloat currentProgress; +@property (nonatomic,retain) NSDate *processStartTime; - (AuthenticationType) getAuthenticationType; - (void) downloadMainFile; @@ -53,12 +55,12 @@ typedef enum { - (void) didDownloadAllResources; - (void) notifyDownloadFinished; - (void)didReceiveNotModifiedHeaderForConnection:(NSURLConnection *)connection ; -- (void) deleteUnusedOldResources; +- (void) deleteUnusedOldResources:(NSArray*)resources; - (void) launchConnectionWithUrlString:completeUrl; - (void) didEndDrawPageOperationWithNotification:(NSNotification *) notification; - +- (void)endSavingCurrentFile; @end diff --git a/Classes/WADocumentDownloader.m b/Classes/WADocumentDownloader.m index 090e655..dd88710 100644 --- a/Classes/WADocumentDownloader.m +++ b/Classes/WADocumentDownloader.m @@ -15,9 +15,14 @@ #import "NSBundle+WAAdditions.h" #import "NSDate+WAAdditions.h" -@implementation WADocumentDownloader +@implementation WADocumentDownloader +{ + NSDate *responseLastModified; + NSString *currentHandlePath; + BOOL downloadResources; +} -@synthesize parser,currentUrlString,receivedData,handle,filesize,nnewResourcesArray,mutableResourcesArray,oldResourcesArray, currentMessage,currentProgress; +@synthesize parser,currentUrlString,receivedData,handle,filesize,nnewResourcesArray,mutableResourcesArray,oldResourcesArray, currentMessage,currentProgress,processStartTime; - (NSString *) urlString @@ -34,15 +39,14 @@ - (void) setUrlString: (NSString *) theString - //SLog(@"WADocumentDownloader (or subclass launched for Url:%@",theString); - + //NSLog(@"WADocumentDownloader (or subclass launched for Url:%@",theString); + processStartTime = [[[NSDate alloc] initWithTimeInterval:0 sinceDate:[NSDate date]] retain]; + [self downloadMainFile]; //Add observer [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didEndDrawPageOperationWithNotification:) name:@"didEndDrawPageOperation" object:nil]; - - } - (void)dealloc { @@ -55,35 +59,65 @@ - (void)dealloc { [filesize release]; [urlString release]; [receivedData release]; - [handle release]; - [nnewResourcesArray release]; + if(handle != nil) + [handle release]; + if(processStartTime != nil) + [processStartTime release]; + [currentHandlePath release]; + if(nnewResourcesArray) + { + [self releaseArrayObjects:nnewResourcesArray]; + [nnewResourcesArray release]; + } [mutableResourcesArray release]; [oldResourcesArray release]; [currentMessage release]; [super dealloc]; } +- (void)releaseArrayObjects:(NSArray*)arr +{ + for(id obj in arr) + [obj release]; +} + - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { - //SLog(@"Connection started, received %i headers with dic: %@",[[response allHeaderFields]count],[[response allHeaderFields]description]); - [receivedData setLength:0]; + //NSLog(@"Connection started, statusCode %d, received %d headers with dic: %@",(int)[response statusCode], (int)[[response allHeaderFields]count],[[response allHeaderFields]description]); + NSDictionary *headers = [response allHeaderFields]; + NSString *responseLastModifiedStr = [headers objectForKey:@"Last-Modified"]; + if(responseLastModified != nil) + [responseLastModified release]; + if([responseLastModifiedStr isKindOfClass:[NSString class]]) + responseLastModified = [[NSDate dateWithHeaderString:responseLastModifiedStr] retain]; + if(![responseLastModified isKindOfClass:[NSDate class]]) + responseLastModified = [[[NSDate alloc] initWithTimeInterval:0 sinceDate:[NSDate date]] retain]; + + [receivedData setLength:0]; filesize = [[NSNumber numberWithLong: [response expectedContentLength] ] retain]; - //Hack for version 4.3 in PdfBrowser - if (![response respondsToSelector:@selector(statusCode)]) return; + NSInteger statusCode; + //Hack for version 4.3 in PdfBrowser + if (![response respondsToSelector:@selector(statusCode)]) + statusCode = 200; + else + statusCode = [response statusCode]; //SLog(@"Did respond to selector"); //Trigger error if one of the following statusCodes is returned - if (([response statusCode]==304)||([response statusCode]==401)||([response statusCode]==402)||([response statusCode]==403)||([response statusCode]==461)||([response statusCode]==462)||([response statusCode]==463)){ - //SLog(@"Connection error %i",[response statusCode]); - NSDictionary * userDic = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%li",(long)[response statusCode]] forKey:@"SSErrorHTTPStatusCodeKey"]; + if ((statusCode==304)||(statusCode==401)||(statusCode==402)||(statusCode==403)||(statusCode==461)||(statusCode==462)||(statusCode==463)){ + //SLog(@"Connection error %i",statusCode); + NSDictionary * userDic = [NSDictionary dictionaryWithObject:[NSString stringWithFormat:@"%li",(long)statusCode] forKey:@"SSErrorHTTPStatusCodeKey"]; NSError * error = [NSError errorWithDomain:@"Librelio" code:2 userInfo:userDic]; [self connection:connection didFailWithError:error]; } - + else + { + handle = [[NSFileHandle fileHandleForWritingAtPath:currentHandlePath] retain]; + } @@ -95,7 +129,7 @@ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data NSNumber* curLength = [NSNumber numberWithLong:[receivedData length] ]; currentProgress = ([curLength floatValue]+[handle offsetInFile]) / [filesize floatValue] ; - //SLog(@"Downloaded %f ",currentProgress); + //NSLog(@"Downloaded %f ",currentProgress); //progressView.progress = progress; if( receivedData.length > 1000000 && handle!=nil ) { @@ -109,7 +143,7 @@ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { - //SLog(@"Download error for connection %@:%@",connection,error); + //NSLog(@"Download error for connection %@:%@",connection,error); NSDictionary * userInfo = error.userInfo; NSString * httpStatus = [NSString stringWithFormat:@"%@",[userInfo objectForKey:@"SSErrorHTTPStatusCodeKey"]]; //SLog(@"Status %@",httpStatus); @@ -188,10 +222,8 @@ - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)err - (void)connectionDidFinishLoading:(NSURLConnection *)connection { - //SLog(@"Did finish loading %@",connection); - [handle writeData:self.receivedData]; - - + //NSLog(@"Did finish loading %@",connection); + [self endSavingCurrentFile]; //Remove from queue @@ -203,6 +235,13 @@ - (void)connectionDidFinishLoading:(NSURLConnection *)connection } +- (void)endSavingCurrentFile +{ + if(handle != nil && [self.receivedData isKindOfClass:[NSData class]] && [self.receivedData length] > 0) + [handle writeData:self.receivedData]; + + [self setDateForFileAtPath:currentHandlePath created:responseLastModified modified:[NSDate date]]; +} @@ -220,7 +259,8 @@ - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallen //Try to get file after approval by Apple or Password check [self launchConnectionWithUrlString:completeUrl]; //Initialize handle and receivedData - [handle release]; + if(handle != nil) + [handle release]; NSString *tempUrlString = [NSString stringWithFormat:@"TempWa/%@", currentUrlString]; [WAUtilities storeFileWithUrlString:tempUrlString withData:nil]; NSString * path = [[NSBundle mainBundle] pathOfFileWithUrl:tempUrlString]; @@ -248,24 +288,33 @@ - (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallen - (void)didReceiveNotModifiedHeaderForConnection:(NSURLConnection *)connection { - //SLog(@"Not modified"); - [[[WAFileDownloadsManager sharedManager] downloadQueue] removeObjectIdenticalTo:connection]; + //NSLog(@"Not modified %@", connection); + + //Copy existing file into cache dir + NSString *filePath = [[NSBundle mainBundle] pathOfFileWithUrl:[currentUrlString noArgsPartOfUrlString]]; + NSString *dirPath = [WAUtilities cacheFolderPath]; + NSString *tmpFilePath = [NSString stringWithFormat:@"%@/TempWa/%@",dirPath,[currentUrlString noArgsPartOfUrlString]]; + NSError *error = nil; + [[NSFileManager defaultManager] removeItemAtPath:tmpFilePath error:nil]; + [[NSFileManager defaultManager] copyItemAtPath:filePath toPath:tmpFilePath error:&error]; + if(error != nil) + { + NSLog(@"Couldn't copy file to cache: %@", error); + } + /* + //[[[WAFileDownloadsManager sharedManager] downloadQueue] removeObjectIdenticalTo:connection]; if ([currentUrlString isEqual:urlString]){ //We were downloading the main resource, no need to go further - [[NSNotificationCenter defaultCenter] postNotificationName:@"didSucceedIssueDownload" object:urlString]; + //[[NSNotificationCenter defaultCenter] postNotificationName:@"didSucceedIssueDownload" object:urlString]; //Update modification date of local file; this will avoid unnecessary queries to distant server until expiration of cache - NSString* path = [[NSBundle mainBundle] pathOfFileWithUrl:[urlString noArgsPartOfUrlString]]; - NSDictionary * dateAttDic = [NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate]; - NSError *error = nil; - [[NSFileManager defaultManager] setAttributes:dateAttDic ofItemAtPath:path error:&error]; + //[self setDateForFileAtPath:currentHandlePath created:responseLastModified modified:[NSDate date]]; + //[[[WADocumentDownloadsManager sharedManager] issuesQueue] removeObjectIdenticalTo:self];//This will release this instance if not owned by a download view - [[[WADocumentDownloadsManager sharedManager] issuesQueue] removeObjectIdenticalTo:self];//This will release this instance if not owned by a download view - - + //[self didDownloadMainFile]; } else { //Delete the content of the file so that we do not keep a corrupted file @@ -273,7 +322,7 @@ - (void)didReceiveNotModifiedHeaderForConnection:(NSURLConnection *)connection { //We were downloading a resource, let's be tolerant and move to the next one //[self downloadNextResource];NOT NEEDED,connexiondidfinishloading will be called, produces bug } - + */ } @@ -292,7 +341,8 @@ - (void) downloadMainFile{ [WAUtilities storeFileWithUrlString:tempUrlString withData:nil]; NSString * path = [[NSBundle mainBundle] pathOfFileWithUrl:tempUrlString]; //SLog(@"pathOfFileWithUrl:%@",path); - handle = [[NSFileHandle fileHandleForWritingAtPath:path] retain]; + currentHandlePath = [path retain]; + handle = nil; receivedData = [[NSMutableData alloc]init]; [self launchConnectionWithUrlString:completeUrl]; @@ -307,7 +357,7 @@ - (void) didDownloadMainFile{ parser = (NSObject *)[[theClass alloc] init]; parser.urlString = tempUrlString; - //SLog(@"parser count data:%i for Url:%@",[parser countData],tempUrlString); + //NSLog(@"parser count data:%i for Url:%@",[parser countData],tempUrlString); if (!([parser countData]>0)){ //SLog(@"File corrupted: %@",tempUrlString); //The file is corrupted, let us notify an error @@ -333,6 +383,9 @@ - (void) didDownloadMainFile{ for (NSString * relativeResourceUrl in resourcesArray){ NSString *absUrl ; + NSRange tmpRange = [relativeResourceUrl rangeOfString:@"/TempWa/"]; + if(tmpRange.location == 0) + relativeResourceUrl = [relativeResourceUrl substringFromIndex:tmpRange.length]; if (forcedUrl){ if ([relativeResourceUrl valueOfParameterInUrlStringforKey:@"waurl"]){ //If the waurl argument is already included in the resources url, no need to change it @@ -355,22 +408,23 @@ - (void) didDownloadMainFile{ - if (![tempArray containsObject:absUrl]) [tempArray addObject:absUrl]; + if (![tempArray containsObject:absUrl]) [tempArray addObject:[absUrl retain]]; } nnewResourcesArray = [[NSArray alloc]initWithArray:tempArray]; - //SLog(@"nnewResourcesArray:%@",nnewResourcesArray); if (nnewResourcesArray&&[parser shouldCompleteDownloadResources]){ mutableResourcesArray = [[NSMutableArray alloc ]initWithArray: nnewResourcesArray]; //SLog(@"MutableRessources:%@",nnewResourcesArray); + downloadResources = YES; [self downloadNextResource];//Start looping in newResourcesArray } else { //SLog(@"Launch didDownloadAllResources from didDownloadMainFile"); currentUrlString = nil;//This is important because there is a test in didEndDrawPageOperationWithNotification + downloadResources = NO; [[[WADocumentDownloadsManager sharedManager] issuesQueue] removeObjectIdenticalTo:self];//Remove self from issuesQueue now, because WAMissingResourecesDwnloader may need to add itself again immediately after [self didDownloadAllResources];//No resources to download now } @@ -383,14 +437,19 @@ - (void) downloadNextResource{ NSString * nextUrlString = [mutableResourcesArray lastObject]; //Open new handle - [handle release]; + if(handle != nil) + { + [handle release]; + handle = nil; // clear handle variable for next request + } NSString *tempUrlString = [NSString stringWithFormat:@"TempWa/%@", nextUrlString]; //Create empty file [WAUtilities storeFileWithUrlString:tempUrlString withData:nil]; + NSString * path = [[NSBundle mainBundle] pathOfFileWithUrl:tempUrlString]; //SLog(@"handle path:%@",path); - handle = [[NSFileHandle fileHandleForWritingAtPath:path] retain]; - + [currentHandlePath release]; + currentHandlePath = [path retain]; [currentUrlString release]; currentUrlString = [[NSString alloc]initWithString: nextUrlString]; @@ -438,6 +497,7 @@ - (void) didDownloadAllResources{ //SLog(@"Will move main %@ to %@",[NSString stringWithFormat:@"%@/TempWa/%@",dirPath,[urlString noArgsPartOfUrlString]], urlString); [WAUtilities storeFileWithUrlString:urlString withFileAtPath:[NSString stringWithFormat:@"%@/TempWa/%@",dirPath,[urlString noArgsPartOfUrlString]]];//Move the main file + //Store generated cache files NSString * cacheDirUrlString = [urlString urlOfCacheFileWithName:@""]; cacheDirUrlString = [cacheDirUrlString substringToIndex:[cacheDirUrlString length]-1];//Remove final "/" @@ -445,20 +505,35 @@ - (void) didDownloadAllResources{ NSString * tempCacheDirUrlString = [[NSString stringWithFormat:@"TempWa/%@", urlString] urlOfCacheFileWithName:@""]; //SLog(@"Will move cache %@ to %@",[NSString stringWithFormat:@"%@/%@",dirPath,tempCacheDirUrlString], tempCacheDirUrlString); [WAUtilities storeFileWithUrlString:cacheDirUrlString withFileAtPath:[NSString stringWithFormat:@"%@/%@",dirPath,tempCacheDirUrlString]];//Move the cache dir - - //Loop through resources - for (NSString * loopedUrlString in nnewResourcesArray){ - loopedUrlString = [loopedUrlString noArgsPartOfUrlString];//Remove the args - NSString *tempUrlString = [NSString stringWithFormat:@"%@/TempWa/%@", dirPath,loopedUrlString]; - //SLog(@"Will move %@ to %@",tempUrlString, loopedUrlString); - [WAUtilities storeFileWithUrlString:loopedUrlString withFileAtPath:tempUrlString]; + if(downloadResources == YES) + { + //Loop through resources + for (NSString * loopedUrlString in nnewResourcesArray){ + loopedUrlString = [loopedUrlString noArgsPartOfUrlString];//Remove the args + NSString *tempUrlString = [NSString stringWithFormat:@"%@/TempWa/%@", dirPath,loopedUrlString]; + //SLog(@"Will move %@ to %@",tempUrlString, loopedUrlString); + [WAUtilities storeFileWithUrlString:loopedUrlString withFileAtPath:tempUrlString]; + } } //Store plist with metadata and list of resources for this download NSString * mainFilePath = [[NSBundle mainBundle] pathOfFileWithUrl:urlString]; NSString * plistPath = [WAUtilities urlByChangingExtensionOfUrlString:mainFilePath toSuffix:@"_metadata.plist"]; + + //Update metadata plist + NSMutableDictionary * prevMetaDic = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; + + if(downloadResources == YES && [[prevMetaDic objectForKey:@"Resources"] isKindOfClass:[NSArray class]]) + [self deleteUnusedOldResources:[prevMetaDic objectForKey:@"Resources"]]; // deletes useless resources from previous download operation + NSMutableDictionary * metaDic = [NSMutableDictionary dictionary]; - if (nnewResourcesArray) [metaDic setObject:nnewResourcesArray forKey:@"Resources"]; + if(downloadResources && nnewResourcesArray) + { + [metaDic setObject:nnewResourcesArray forKey:@"Resources"]; + [metaDic setObject:@"YES" forKey:@"DownloadComplete"]; + } + else if(downloadResources == NO && [[prevMetaDic objectForKey:@"Resources"] isKindOfClass:[NSArray class]]) + [metaDic setObject:[prevMetaDic objectForKey:@"Resources"] forKey:@"Resources"]; [metaDic setObject:[NSDate date] forKey:@"DownloadDate"]; [metaDic setObject:urlString forKey:@"FileUrl"]; @@ -531,28 +606,33 @@ - (void) didEndDrawPageOperationWithNotification:(NSNotification *) notification -- (void) deleteUnusedOldResources{ - //TODO: complete +- (void) deleteUnusedOldResources:(NSArray*)resources +{ + // remove old files if not exist anymore + for(NSString *oldFileUrlString in resources) + { + NSDate *modDate = [WAUtilities dateOfFileWithUrlString:oldFileUrlString]; + if([modDate isKindOfClass:[NSDate class]] && [processStartTime compare:modDate] == NSOrderedDescending) + { + NSString *path = [[NSBundle mainBundle] pathOfFileWithUrl:[oldFileUrlString noArgsPartOfUrlString]]; + [[NSFileManager defaultManager] removeItemAtPath:path error:nil]; + } + } } #pragma mark - #pragma mark Helper methods - (void) launchConnectionWithUrlString:completeUrl{ - + NSMutableURLRequest * urlRequest =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:completeUrl]]; - - //Prevent download if local file is more recent than remote (except if - - NSDate * last = [WAUtilities dateOfFileWithUrlString:[currentUrlString noArgsPartOfUrlString]]; + urlRequest.cachePolicy = NSURLRequestReloadIgnoringCacheData; + //Prevent download if local file is more recent than remote (except if + NSDate * last = [WAUtilities creationDateOfFileWithUrlString:[currentUrlString noArgsPartOfUrlString]]; //NSDate * last = nil; - if (last){ - //SLog(@"Will set If-Modified-Since to %@",[last headerString]); [urlRequest setValue:[last headerString] forHTTPHeaderField:@"If-Modified-Since"]; // conditonal load } - - - + //NSLog(@"request: %@\nModDate: %@ %@", completeUrl, [last headerString], [currentUrlString noArgsPartOfUrlString]); NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; //SLog(@"will launch connection for %@ with connexion %@",completeUrl,conn); @@ -571,7 +651,15 @@ - (AuthenticationType) getAuthenticationType{ else return AuthenticationTypeAppStore; } - - +- (void)setDateForFileAtPath:(NSString*)path created:(NSDate*)creationDate modified:(NSDate*)modifiedDate +{ + NSDictionary * modDateAttDic = [NSDictionary dictionaryWithObject:modifiedDate forKey:NSFileModificationDate]; + NSDictionary * dateAttDic = [NSDictionary dictionaryWithObject:creationDate forKey:NSFileCreationDate]; + + NSError *error = nil; + + [[NSFileManager defaultManager] setAttributes:modDateAttDic ofItemAtPath:path error:&error]; + [[NSFileManager defaultManager] setAttributes:dateAttDic ofItemAtPath:path error:&error]; +} @end diff --git a/Classes/WADownloadingView.m b/Classes/WADownloadingView.m index 199d8e9..2219b97 100644 --- a/Classes/WADownloadingView.m +++ b/Classes/WADownloadingView.m @@ -7,7 +7,7 @@ #import "WADocumentDownloadsManager.h" #import "WADocumentDownloader.h" #import "WANewsstandIssueDownloader.h" -#import "WAMissingResourcesDownloader.h" +#import "WAResourcesDownloader.h" #import "WAPDFParser.h" #import "NSString+WAURLString.h" #import "NSBundle+WAAdditions.h" @@ -166,7 +166,7 @@ - (void) startDownloadWithoutNewsstand{ [issue release]; } else { - WAMissingResourcesDownloader * issue = [[WAMissingResourcesDownloader alloc]init]; + WAResourcesDownloader * issue = [[WAResourcesDownloader alloc]init]; [[[WADocumentDownloadsManager sharedManager] issuesQueue]addObject:issue]; issue.urlString = urlString; [issue release]; diff --git a/Classes/WAGridCell.xib b/Classes/WAGridCell.xib index ab18fc9..eb83c24 100644 --- a/Classes/WAGridCell.xib +++ b/Classes/WAGridCell.xib @@ -1,8 +1,7 @@ - + - - + @@ -16,7 +15,7 @@ - + @@ -78,9 +77,16 @@ + + - \ No newline at end of file + + + + + + diff --git a/Classes/WAGridView.m b/Classes/WAGridView.m index 9ccaab1..c66ed5a 100755 --- a/Classes/WAGridView.m +++ b/Classes/WAGridView.m @@ -273,7 +273,7 @@ - (void) moduleViewDidAppear{ //SLog(@"grid moduleview did appear, should check update"); //Check wether an update of the source data is needed WAModuleViewController * moduleViewController = (WAModuleViewController *) [self traverseResponderChainForUIViewController]; - [moduleViewController checkUpdateIfNeeded]; + //[moduleViewController checkUpdateIfNeeded]; //Update the table [self initParser]; diff --git a/Classes/WAModuleViewController.m b/Classes/WAModuleViewController.m index 0d6d387..b118517 100644 --- a/Classes/WAModuleViewController.m +++ b/Classes/WAModuleViewController.m @@ -12,7 +12,7 @@ #import "WAUtilities.h" #import "WADownloadingView.h" #import "WADocumentDownloadsManager.h" -#import "WAMissingResourcesDownloader.h" +#import "WAResourcesDownloader.h" #import "WABarButtonItemWithLink.h" diff --git a/Classes/WAMissingResourcesDownloader.h b/Classes/WAResourcesDownloader.h similarity index 73% rename from Classes/WAMissingResourcesDownloader.h rename to Classes/WAResourcesDownloader.h index 323b10f..27ed94b 100644 --- a/Classes/WAMissingResourcesDownloader.h +++ b/Classes/WAResourcesDownloader.h @@ -11,6 +11,6 @@ Downloads missing resources, for a document already downloaded */ -@interface WAMissingResourcesDownloader : WADocumentDownloader +@interface WAResourcesDownloader : WADocumentDownloader @end diff --git a/Classes/WAMissingResourcesDownloader.m b/Classes/WAResourcesDownloader.m similarity index 78% rename from Classes/WAMissingResourcesDownloader.m rename to Classes/WAResourcesDownloader.m index c972e86..7a26a08 100644 --- a/Classes/WAMissingResourcesDownloader.m +++ b/Classes/WAResourcesDownloader.m @@ -5,21 +5,22 @@ // Copyright (c) 2011 WidgetAvenue - Librelio. All rights reserved. // -#import "WAMissingResourcesDownloader.h" +#import "WAResourcesDownloader.h" #import "NSString+WAURLString.h" #import "NSBundle+WAAdditions.h" #import "WADocumentDownloadsManager.h" -@implementation WAMissingResourcesDownloader +@implementation WAResourcesDownloader - (void) setUrlString: (NSString *) theString { - //SLog(@"WAMissingResourcesDownloader launched for Url:%@",theString); + //NSLog(@"WAResourcesDownloader launched for Url:%@",theString); urlString = [[NSString alloc]initWithString: theString]; [self didDownloadMainFile]; //No need to download main file - + processStartTime = [[[NSDate alloc] initWithTimeInterval:0 sinceDate:[NSDate date]] retain]; + } @@ -68,18 +69,18 @@ - (void) didDownloadMainFile{ //If the resource is not present on the device, add it to the download queue - if ((![tempArray containsObject:absUrl])&&(![[NSBundle mainBundle]pathOfFileWithUrl:absUrl])) [tempArray addObject:absUrl]; + if (![tempArray containsObject:absUrl]) [tempArray addObject:[absUrl retain]]; } - nnewResourcesArray = [[NSArray alloc]initWithArray:tempArray]; - if ([nnewResourcesArray count]){ - mutableResourcesArray = [[NSMutableArray alloc ]initWithArray: nnewResourcesArray]; + self.nnewResourcesArray = [[NSArray alloc]initWithArray:tempArray]; + if ([self.nnewResourcesArray count]){ + self.mutableResourcesArray = [[NSMutableArray alloc ]initWithArray: self.nnewResourcesArray]; //SLog(@"Missing resources:%@",nnewResourcesArray); - receivedData = [[NSMutableData alloc]init]; + self.receivedData = [[NSMutableData alloc]init]; [self downloadNextResource];//Start looping in newResourcesArray @@ -111,17 +112,14 @@ - (void) didDownloadAllResources{ NSString * mainFilePath = [[NSBundle mainBundle] pathOfFileWithUrl:urlString]; NSString * plistPath = [WAUtilities urlByChangingExtensionOfUrlString:mainFilePath toSuffix:@"_metadata.plist"]; - if (nnewResourcesArray){ - NSMutableDictionary * metaDic = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; - NSArray * concatArray = [nnewResourcesArray arrayByAddingObjectsFromArray:[metaDic objectForKey:@"Resources"]]; - [metaDic setObject:concatArray forKey:@"Resources"]; - - [metaDic writeToFile:plistPath atomically:YES]; - - - } + NSMutableDictionary * metaDic = [NSMutableDictionary dictionaryWithContentsOfFile:plistPath]; + if([[metaDic objectForKey:@"Resources"] isKindOfClass:[NSArray class]]) + [self deleteUnusedOldResources:[metaDic objectForKey:@"Resources"]]; - + if(self.nnewResourcesArray) + [metaDic setObject:self.nnewResourcesArray forKey:@"Resources"]; + [metaDic setObject:@"YES" forKey:@"DownloadComplete"]; + [metaDic writeToFile:plistPath atomically:YES]; //SLog(@"sharedManager before remove:%@",[[WADocumentDownloadsManager sharedManager]issuesQueue]); @@ -139,26 +137,26 @@ - (void) didDownloadAllResources{ - (void)connectionDidFinishLoading:(NSURLConnection *)connection { - - [handle writeData:self.receivedData]; + //NSLog(@"Did finish loading %@",connection); + [self endSavingCurrentFile]; //Move the file from TempWA directory to relevant place NSString * dirPath = [WAUtilities cacheFolderPath]; NSString *tempUrlString = [NSString stringWithFormat:@"%@/TempWa/%@", dirPath,[currentUrlString noArgsPartOfUrlString]]; - //SLog(@"Will move %@ to %@",tempUrlString, currentUrlString); + //NSLog(@"Will move %@ to %@",tempUrlString, curUrlString); [WAUtilities storeFileWithUrlString:currentUrlString withFileAtPath:tempUrlString]; - + //SLog(@"Will send didSucceedResourceDownload notification for connection %@",connection); [[NSNotificationCenter defaultCenter] postNotificationName:@"didSucceedResourceDownload" object:urlString]; - + [currentUrlString release]; + + //Continue with other downloads + if ([currentUrlString isEqual:urlString]) [self didDownloadMainFile]; + else [self downloadNextResource]; - //Continue with other downloads - if ([currentUrlString isEqual:urlString]) [self didDownloadMainFile]; - else [self downloadNextResource]; - } diff --git a/Classes/WASQLiteParser.m b/Classes/WASQLiteParser.m index 4ce95e4..475789a 100644 --- a/Classes/WASQLiteParser.m +++ b/Classes/WASQLiteParser.m @@ -2,7 +2,7 @@ #import "NSString+WAURLString.h" #import "NSBundle+WAAdditions.m" #import "WADocumentDownloadsManager.h" -#import "WAMissingResourcesDownloader.h" +#import "WAResourcesDownloader.h" diff --git a/Classes/WAUtilities.h b/Classes/WAUtilities.h index b07dd70..81bfa34 100644 --- a/Classes/WAUtilities.h +++ b/Classes/WAUtilities.h @@ -18,6 +18,7 @@ + (NSString *)cacheFolderPath; + (NSString *) hashPartOfUrlString:(NSString*)urlString; //Returns the part after the # sign + (NSDate *) dateOfFileWithUrlString:(NSString*)name; ++ (NSDate *) creationDateOfFileWithUrlString:(NSString*)urlString; + (NSString*)directoryUrlOfUrlString:(NSString*)urlString;//Returns the Url of the directory + (NSString*) absoluteUrlOfRelativeUrl:(NSString*)relativeUrl relativeToUrl:(NSString*)baseUrl; + (NSString*) urlByChangingExtensionOfUrlString:(NSString*)urlString toSuffix:(NSString*)newExtension; diff --git a/Classes/WAUtilities.m b/Classes/WAUtilities.m index cce0c8d..b1b02d1 100644 --- a/Classes/WAUtilities.m +++ b/Classes/WAUtilities.m @@ -107,6 +107,18 @@ + (NSDate *) dateOfFileWithUrlString:(NSString*)urlString{ } ++ (NSDate*) creationDateOfFileWithUrlString:(NSString*)urlString{ + NSString * tempPath = [[NSBundle mainBundle] pathOfFileWithUrl:urlString]; + //SLog(@"finding date of file %@",tempPath); + NSDate * ret = nil;//Return nil by default + //Check if the file is in the app bundle, or the cache directory; if it is in the cache bundle, the date does not mean anything, so we return nil; + if (tempPath &&[tempPath hasPrefix:[self cacheFolderPath]]){ + ret = [[[NSFileManager defaultManager] attributesOfItemAtPath:tempPath error:NULL] objectForKey:NSFileCreationDate] ; + } + + return ret; +} + @@ -176,7 +188,8 @@ + (void) storeFileWithUrlString:(NSString*)urlString withData:(NSData *) data{ + (void) storeFileWithUrlString:(NSString*)urlString withFileAtPath:(NSString*)tempFilePath{ NSString *newFilePath = [urlString pathOfStorageForUrlString]; NSString* dirPath=[self directoryUrlOfUrlString:newFilePath]; - if (![[NSFileManager defaultManager] fileExistsAtPath:dirPath]) { + + if (![[NSFileManager defaultManager] fileExistsAtPath:dirPath]) { //Directory does not exist, must be created [[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:NULL]; @@ -189,15 +202,15 @@ + (void) storeFileWithUrlString:(NSString*)urlString withFileAtPath:(NSString*)t if (([attDic fileSize]==0)&&([attDic fileType]==NSFileTypeRegular)){ //If this is a file (not a directory) and the size is zero, delete it, [[NSFileManager defaultManager]removeItemAtPath:tempFilePath error:nil]; - //SLog(@"Deleted empty file"); + //NSLog(@"Deleted empty file"); } else{ //Move the file or directory [[NSFileManager defaultManager] removeItemAtPath:newFilePath error:&error2];//Remove existing file at filePath, if there is one //if (error2) SLog(@"Error:%@ when removing file at path:%@",[error2 localizedDescription],newFilePath); [[NSFileManager defaultManager] moveItemAtPath:tempFilePath toPath:newFilePath error:&error]; - //if (error) SLog(@"Error:%@ with file at path:%@",error,tempFilePath); - //else SLog(@"moved from %@ to %@",tempFilePath,newFilePath); + //if (error) NSLog(@"Error:%@ with file at path:%@",error,tempFilePath); + //else NSLog(@"moved from %@ to %@",tempFilePath,newFilePath); } @@ -281,7 +294,7 @@ + (BOOL) featuresInApps{ + (BOOL) isCheckUpdateNeededForUrlString:(NSString*)urlString{ - //SLog(@"Checking update needed? for url:%@",urlString); + // NSLog(@"Checking update needed? for url:%@ isLocalUrl: %d",urlString, (int)[urlString isLocalUrl]); if ([urlString isLocalUrl]) { NSString * path = [[NSBundle mainBundle] pathOfFileWithUrl:urlString]; if (!path) { @@ -296,6 +309,7 @@ + (BOOL) isCheckUpdateNeededForUrlString:(NSString*)urlString{ NSDate * fileModifDate = [self dateOfFileWithUrlString:urlString]; NSDate * nextCheckDate = [fileModifDate dateByAddingTimeInterval:60*mn];//waupdate parameter is in minutes NSDate * nowDate = [NSDate date]; + //NSLog(@"path: %@ compare: nextCheckDate: %@ now: %@", path, nextCheckDate, nowDate); if (![path hasPrefix:[self cacheFolderPath]]){ //SLog(@"Document in app bunde, update needed"); return YES; //The document is in the app bundle, we should check if an update is needed diff --git a/Librelio.xcodeproj/project.pbxproj b/Librelio.xcodeproj/project.pbxproj index 49be7ca..4700ec6 100644 --- a/Librelio.xcodeproj/project.pbxproj +++ b/Librelio.xcodeproj/project.pbxproj @@ -152,7 +152,7 @@ 149086F917E375D700943DD2 /* WASQLiteParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 147B34D9146C13BA0002CC17 /* WASQLiteParser.m */; }; 149086FA17E375D700943DD2 /* WANewsstandIssueDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 147B3531146E78930002CC17 /* WANewsstandIssueDownloader.m */; }; 149086FB17E375D700943DD2 /* NSDate+WAAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 14897FF9146FB37F00C6A5C6 /* NSDate+WAAdditions.m */; }; - 149086FC17E375D700943DD2 /* WAMissingResourcesDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 14DD776C14A4F938004E06E5 /* WAMissingResourcesDownloader.m */; }; + 149086FC17E375D700943DD2 /* WAResourcesDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 14DD776C14A4F938004E06E5 /* WAResourcesDownloader.m */; }; 149086FD17E375D700943DD2 /* WAZoomImage.m in Sources */ = {isa = PBXBuildFile; fileRef = 14DD77A014A60D64004E06E5 /* WAZoomImage.m */; }; 149086FE17E375D700943DD2 /* WAAddressAnnotation.m in Sources */ = {isa = PBXBuildFile; fileRef = 14D37B6114B6DEAA00BA49C0 /* WAAddressAnnotation.m */; }; 149086FF17E375D700943DD2 /* WASplashWebViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 1424381314BC36BE005ABB4A /* WASplashWebViewController.m */; }; @@ -291,7 +291,7 @@ 14DB11DB164BEDC3001FE76B /* WASQLiteParser.m in Sources */ = {isa = PBXBuildFile; fileRef = 147B34D9146C13BA0002CC17 /* WASQLiteParser.m */; }; 14DB11DC164BEDC3001FE76B /* WANewsstandIssueDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 147B3531146E78930002CC17 /* WANewsstandIssueDownloader.m */; }; 14DB11DD164BEDC3001FE76B /* NSDate+WAAdditions.m in Sources */ = {isa = PBXBuildFile; fileRef = 14897FF9146FB37F00C6A5C6 /* NSDate+WAAdditions.m */; }; - 14DB11DE164BEDC3001FE76B /* WAMissingResourcesDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 14DD776C14A4F938004E06E5 /* WAMissingResourcesDownloader.m */; }; + 14DB11DE164BEDC3001FE76B /* WAResourcesDownloader.m in Sources */ = {isa = PBXBuildFile; fileRef = 14DD776C14A4F938004E06E5 /* WAResourcesDownloader.m */; }; 14DB11DF164BEDC3001FE76B /* WAZoomImage.m in Sources */ = {isa = PBXBuildFile; fileRef = 14DD77A014A60D64004E06E5 /* WAZoomImage.m */; }; 14DB11E0164BEDC3001FE76B /* WAAddressAnnotation.m in Sources */ = {isa = PBXBuildFile; fileRef = 14D37B6114B6DEAA00BA49C0 /* WAAddressAnnotation.m */; }; 14DB11E1164BEDC3001FE76B /* WASplashWebViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 1424381314BC36BE005ABB4A /* WASplashWebViewController.m */; }; @@ -586,8 +586,8 @@ 14DB137F164C52C4001FE76B /* Tabs.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Tabs.plist; sourceTree = ""; }; 14DB1380164C52C4001FE76B /* wind-generic.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = "wind-generic.png"; sourceTree = ""; }; 14DB1381164C52C4001FE76B /* wind_355.png */ = {isa = PBXFileReference; lastKnownFileType = image.png; path = wind_355.png; sourceTree = ""; }; - 14DD776B14A4F937004E06E5 /* WAMissingResourcesDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WAMissingResourcesDownloader.h; sourceTree = ""; }; - 14DD776C14A4F938004E06E5 /* WAMissingResourcesDownloader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WAMissingResourcesDownloader.m; sourceTree = ""; }; + 14DD776B14A4F937004E06E5 /* WAResourcesDownloader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WAResourcesDownloader.h; sourceTree = ""; }; + 14DD776C14A4F938004E06E5 /* WAResourcesDownloader.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WAResourcesDownloader.m; sourceTree = ""; }; 14DD779F14A60D64004E06E5 /* WAZoomImage.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WAZoomImage.h; sourceTree = ""; }; 14DD77A014A60D64004E06E5 /* WAZoomImage.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = WAZoomImage.m; sourceTree = ""; }; 14DF9B22145D4FE10031C52F /* NSString+WAURLString.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSString+WAURLString.h"; sourceTree = ""; }; @@ -829,8 +829,8 @@ 14A1DC0B14629D48005366C7 /* WADocumentDownloader.m */, 147B3530146E78920002CC17 /* WANewsstandIssueDownloader.h */, 147B3531146E78930002CC17 /* WANewsstandIssueDownloader.m */, - 14DD776B14A4F937004E06E5 /* WAMissingResourcesDownloader.h */, - 14DD776C14A4F938004E06E5 /* WAMissingResourcesDownloader.m */, + 14DD776B14A4F937004E06E5 /* WAResourcesDownloader.h */, + 14DD776C14A4F938004E06E5 /* WAResourcesDownloader.m */, ); name = Downloader; sourceTree = ""; @@ -1721,7 +1721,7 @@ 149086F917E375D700943DD2 /* WASQLiteParser.m in Sources */, 149086FA17E375D700943DD2 /* WANewsstandIssueDownloader.m in Sources */, 149086FB17E375D700943DD2 /* NSDate+WAAdditions.m in Sources */, - 149086FC17E375D700943DD2 /* WAMissingResourcesDownloader.m in Sources */, + 149086FC17E375D700943DD2 /* WAResourcesDownloader.m in Sources */, 149086FD17E375D700943DD2 /* WAZoomImage.m in Sources */, 149086FE17E375D700943DD2 /* WAAddressAnnotation.m in Sources */, 149086FF17E375D700943DD2 /* WASplashWebViewController.m in Sources */, @@ -1811,7 +1811,7 @@ 14DB11DB164BEDC3001FE76B /* WASQLiteParser.m in Sources */, 14DB11DC164BEDC3001FE76B /* WANewsstandIssueDownloader.m in Sources */, 14DB11DD164BEDC3001FE76B /* NSDate+WAAdditions.m in Sources */, - 14DB11DE164BEDC3001FE76B /* WAMissingResourcesDownloader.m in Sources */, + 14DB11DE164BEDC3001FE76B /* WAResourcesDownloader.m in Sources */, 14DB11DF164BEDC3001FE76B /* WAZoomImage.m in Sources */, 14DB11E0164BEDC3001FE76B /* WAAddressAnnotation.m in Sources */, 14DB11E1164BEDC3001FE76B /* WASplashWebViewController.m in Sources */, diff --git a/Wind/Tabs.plist b/Wind/Tabs.plist index 8317f96..fc315b7 100644 --- a/Wind/Tabs.plist +++ b/Wind/Tabs.plist @@ -4,7 +4,7 @@ FileName - Magazines.plist?waupdate=300000 + Magazines.plist?waupdate=30 Icon download.png Title