Skip to content
This repository
tree: 4430b9c381
Fetching contributors…

Cannot retrieve contributors at this time

file 172 lines (150 sloc) 6.88 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172
//
// ReportImportOperation.m
// AppSales
//
// Created by Ole Zorn on 09.07.11.
// Copyright 2011 omz:software. All rights reserved.
//

#import "ReportImportOperation.h"
#import "ASAccount.h"
#import "Report.h"
#import "NSData+Compression.h"

@implementation ReportImportOperation

@synthesize importDirectory, deleteOriginalFilesAfterImport;

+ (BOOL)filesAvailableToImport
{
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSFileManager *fm = [[[NSFileManager alloc] init] autorelease];
NSArray *filenames = [fm contentsOfDirectoryAtPath:docPath error:NULL];
for (NSString *filename in filenames) {
if ([[filename pathExtension] isEqualToString:@"txt"]) {
return YES;
}
}
return NO;
}

- (id)initWithAccount:(ASAccount *)account
{
self = [super init];
if (self) {
_account = [account retain];
accountObjectID = [[account objectID] copy];
psc = [[[account managedObjectContext] persistentStoreCoordinator] retain];
}
return self;
}

- (void)main
{
NSAutoreleasePool *pool = [NSAutoreleasePool new];

dispatch_async(dispatch_get_main_queue(), ^ {
_account.downloadStatus = NSLocalizedString(@"Starting import", nil);
_account.downloadProgress = 0.0;
});

NSManagedObjectContext *moc = [[[NSManagedObjectContext alloc] init] autorelease];
[moc setPersistentStoreCoordinator:psc];
[moc setMergePolicy:NSMergeByPropertyObjectTrumpMergePolicy];

ASAccount *account = (ASAccount *)[moc objectWithID:accountObjectID];
NSInteger numberOfReportsImported = 0;
NSInteger i = 0;

NSFetchRequest *existingDailyReportsRequest = [[[NSFetchRequest alloc] init] autorelease];
[existingDailyReportsRequest setEntity:[NSEntityDescription entityForName:@"DailyReport" inManagedObjectContext:moc]];
[existingDailyReportsRequest setPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
[existingDailyReportsRequest setPropertiesToFetch:[NSArray arrayWithObject:@"startDate"]];
[existingDailyReportsRequest setResultType:NSDictionaryResultType];
NSArray *existingDailyReportDates = [[moc executeFetchRequest:existingDailyReportsRequest error:NULL] valueForKey:@"startDate"];
NSMutableSet *existingDailyReportDatesSet = [NSMutableSet setWithArray:existingDailyReportDates];

NSFetchRequest *existingWeeklyReportsRequest = [[[NSFetchRequest alloc] init] autorelease];
[existingWeeklyReportsRequest setEntity:[NSEntityDescription entityForName:@"WeeklyReport" inManagedObjectContext:moc]];
[existingWeeklyReportsRequest setPredicate:[NSPredicate predicateWithFormat:@"account == %@", account]];
[existingWeeklyReportsRequest setPropertiesToFetch:[NSArray arrayWithObject:@"startDate"]];
[existingWeeklyReportsRequest setResultType:NSDictionaryResultType];
NSArray *existingWeeklyReportDates = [[moc executeFetchRequest:existingWeeklyReportsRequest error:NULL] valueForKey:@"startDate"];
NSMutableSet *existingWeeklyReportDatesSet = [NSMutableSet setWithArray:existingWeeklyReportDates];

NSString *docPath = nil;
if (self.importDirectory) {
docPath = [[self.importDirectory retain] autorelease];
} else {
docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
}
NSFileManager *fm = [[[NSFileManager alloc] init] autorelease];
NSArray *fileNames = [fm contentsOfDirectoryAtPath:docPath error:NULL];

dispatch_async(dispatch_get_main_queue(), ^ {
_account.downloadStatus = [NSString stringWithFormat:NSLocalizedString(@"Processing files (0/%i)...", nil), [fileNames count]];
_account.downloadProgress = 0.0;
});

for (NSString *fileName in fileNames) {
NSAutoreleasePool *innerPool = [NSAutoreleasePool new];
if (![[fileName pathExtension] isEqualToString:@"txt"] && ![fileName hasSuffix:@"txt.gz"]) {
[innerPool release];
continue;
}
NSString *fullPath = [docPath stringByAppendingPathComponent:fileName];
NSString *reportCSV = nil;
if ([[fullPath pathExtension] isEqualToString:@"gz"]) {
NSData *gzData = [[[NSData alloc] initWithContentsOfFile:fullPath] autorelease];
NSData *inflatedData = [gzData gzipInflate];
reportCSV = [[[NSString alloc] initWithData:inflatedData encoding:NSUTF8StringEncoding] autorelease];
if (!reportCSV) reportCSV = [[[NSString alloc] initWithData:inflatedData encoding:NSISOLatin1StringEncoding] autorelease];
} else {
reportCSV = [[[NSString alloc] initWithContentsOfFile:fullPath encoding:NSUTF8StringEncoding error:NULL] autorelease];
if (!reportCSV) reportCSV = [[[NSString alloc] initWithContentsOfFile:fullPath encoding:NSISOLatin1StringEncoding error:NULL] autorelease];
}

NSDictionary *reportInfo = [Report infoForReportCSV:reportCSV];
if (reportInfo) {
NSDate *reportDate = [reportInfo objectForKey:kReportInfoDate];
NSMutableSet *existingDates = nil;
if ([[reportInfo objectForKey:kReportInfoClass] isEqualToString:kReportInfoClassDaily]) {
existingDates = existingDailyReportDatesSet;
} else if ([[reportInfo objectForKey:kReportInfoClass] isEqualToString:kReportInfoClassWeekly]) {
existingDates = existingWeeklyReportDatesSet;
}
if (![existingDates containsObject:reportDate]) {
Report *report = [Report insertNewReportWithCSV:reportCSV inAccount:account];
if (report) {
[existingDates addObject:reportDate];
NSManagedObject *originalReport = [NSEntityDescription insertNewObjectForEntityForName:@"ReportCSV" inManagedObjectContext:moc];
[originalReport setValue:reportCSV forKey:@"content"];
[originalReport setValue:report forKey:@"report"];
[originalReport setValue:fileName forKey:@"filename"];

[report generateCache];

numberOfReportsImported++;
[psc lock];
NSError *saveError = nil;
[moc save:&saveError];
if (saveError) {
NSLog(@"Could not save context: %@", saveError);
}
[psc unlock];
if (i % 10 == 0) {
//Reset the context periodically to avoid excessive memory growth:
[moc reset];
account = (ASAccount *)[moc objectWithID:accountObjectID];
}
if (!saveError && deleteOriginalFilesAfterImport) {
[fm removeItemAtPath:fullPath error:NULL];
}
}
}
}

dispatch_async(dispatch_get_main_queue(), ^ {
float progress = (float)i / (float)[fileNames count];
_account.downloadStatus = [NSString stringWithFormat:NSLocalizedString(@"Processing files (%i/%i)...", nil), i, [fileNames count]];
_account.downloadProgress = progress;
});

[innerPool release];
i++;
}

dispatch_async(dispatch_get_main_queue(), ^ {
_account.downloadStatus = [NSString stringWithFormat:NSLocalizedString(@"Finished (%i imported)", nil), numberOfReportsImported];
_account.downloadProgress = 1.0;
});
[pool release];
}

- (void)dealloc
{
[_account release];
[psc release];
[accountObjectID release];
[super dealloc];
}

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