Improve UUID translation in nodes
[pithos-macos] / pithos-macos / PithosAccount.m
index 0c4a01b..0250f15 100644 (file)
@@ -1,8 +1,8 @@
 //
-//  PithosNode.m
+//  PithosAccount.m
 //  pithos-macos
 //
-// Copyright 2011 GRNET S.A. All rights reserved.
+// Copyright 2012 GRNET S.A. All rights reserved.
 //
 // Redistribution and use in source and binary forms, with or
 // without modification, are permitted provided that the following
 // interpreted as representing official policies, either expressed
 // or implied, of GRNET S.A.
 
-#import "PithosNode.h"
+#import "PithosAccount.h"
+#import "PithosSyncDaemon.h"
+#import "ASIPithos.h"
+#import "ASIPithosRequest.h"
+#import "PithosAccountNode.h"
+#import "PithosSharingAccountsNode.h"
+#import "PithosUtilities.h"
+#import "pithos_macosAppDelegate.h"
 
-@implementation PithosNode
-@synthesize children;
+@interface PithosAccount (Internal)
+- (BOOL)urlIsValid:(NSString *)urlString;
+@end
+
+@implementation PithosAccount
+@synthesize uniqueName, active, name, clientVersion;
+@synthesize syncActive, syncDirectoryPath, syncAccountsDictionary, syncSkipHidden, syncLastCompleted, syncDaemon;
+@synthesize serverURL, versionResource, loginResource, publicResource, userCatalogResource;
+@synthesize authUser, authToken, storageURLPrefix, authURL, loginURLPrefix, publicURLPrefix, userCatalogURL, userCatalog;
+@synthesize pithos, accountNode, sharingAccountsNode;
 
 #pragma mark -
 #pragma mark Object Lifecycle
 
-- (void)dealloc {
-    [children release];
-    [super dealloc];
++ (id)pithosAccount {
+    PithosAccount *pithosAccount = [[self alloc] init];
+    pithosAccount.uniqueName = [NSString stringWithFormat:@"pithosAccount-%f", [NSDate timeIntervalSinceReferenceDate]];
+    pithosAccount.clientVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
+    pithosAccount.syncSkipHidden = YES;
+    return pithosAccount;
+}
+
+
+- (NSString *)description {
+    return [NSString stringWithFormat:@"uniqueName: %@, active: %d, name: %@, clientVersion: %@, syncActive: %d, syncDirectoryPath: %@, syncAccountsDictionary: %@, syncSkipHidden: %d, syncLastCompleted: %@, serverURL: %@, versionResource: %@, loginResource: %@, publicResource: %@, userCatalogResource: %@, authUser: %@, authToken: %@, storageURLPrefix: %@, authURL: %@, loginURLPrefix: %@, publicURLPrefix: %@, userCatalogResource: %@",
+            uniqueName, active, name, clientVersion, syncActive, syncDirectoryPath, syncAccountsDictionary, syncSkipHidden, syncLastCompleted, serverURL, versionResource, loginResource, publicResource, userCatalogResource, authUser, authToken, storageURLPrefix, authURL, loginURLPrefix, publicURLPrefix, userCatalogResource];
+}
+
+#pragma mark -
+#pragma mark Internal
+
+- (BOOL)urlIsValid:(NSString *)urlString {
+    if (urlString) {
+        NSURL *url = [NSURL URLWithString:urlString];
+        if (url && url.scheme && url.host)
+            return YES;
+    }
+    return NO;
 }
 
 #pragma mark -
 #pragma mark Properties
 
-- (NSArray *)children {
-    if (children == nil) {
-        children = [[NSArray alloc] init];
+- (NSString *)name {
+    if (![name length]) {
+        NSDictionary *pithosAccountsDictionary = [(pithos_macosAppDelegate *)[[NSApplication sharedApplication] delegate] pithosAccountsDictionary];
+        NSString *namePrefix = @"okeanos";
+        NSUInteger nameSuffix = 1;
+        name = @"okeanos";
+        NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
+        NSFileManager *fileManager = [NSFileManager defaultManager];
+        while ([pithosAccountsDictionary objectForKey:name] || 
+               [fileManager fileExistsAtPath:[documentsDirectoryPath stringByAppendingPathComponent:name]]) {
+            name = [NSString stringWithFormat:@"%@%ld", namePrefix, ++nameSuffix];
+        }
+    }
+    return name;
+}
+
+- (void)setName:(NSString *)aName {
+    NSMutableDictionary *pithosAccountsDictionary = [(pithos_macosAppDelegate *)[[NSApplication sharedApplication] delegate] pithosAccountsDictionary];
+    if (![self.name isEqualToString:aName] && [aName length] && ![pithosAccountsDictionary objectForKey:aName]) {
+        [pithosAccountsDictionary setObject:self forKey:aName];
+        [pithosAccountsDictionary removeObjectForKey:name];
+        name = aName;
+    }
+}
+
+- (BOOL)syncActive {
+    if (active)
+        return syncActive;
+    else
+        return NO;
+}
+
+- (void)setSyncActive:(BOOL)aSyncActive {
+    syncActive = aSyncActive;
+    if (syncDaemon && !self.syncActive)
+        [syncDaemon resetDaemon];
+}
+
+- (NSString *)syncDirectoryPath {
+    if (![syncDirectoryPath length]) {
+        syncDirectoryPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] 
+                              stringByAppendingPathComponent:self.name];
+    }
+    return syncDirectoryPath;
+}
+
+- (void)setSyncDirectoryPath:(NSString *)aSyncDirectoryPath {
+    if (![self.syncDirectoryPath isEqualToString:aSyncDirectoryPath] && [aSyncDirectoryPath length]) {
+        BOOL isDirectory;
+        if (![[NSFileManager defaultManager] fileExistsAtPath:aSyncDirectoryPath isDirectory:&isDirectory] || isDirectory) {
+            syncDirectoryPath = aSyncDirectoryPath;
+        } else {
+            return;
+        }
+
+        @synchronized(self) {
+            resetSyncDaemonLocalState = YES;
+            syncLastCompleted = nil;
+        }
+    }
+}
+
+- (NSMutableDictionary *)syncAccountsDictionary {
+    if (!syncAccountsDictionary) {
+        syncAccountsDictionary = [NSMutableDictionary dictionaryWithObject:[NSMutableDictionary dictionaryWithObject:[NSMutableSet set] 
+                                                                                                              forKey:@"pithos"]
+                                                                    forKey:@""];
+    }        
+    return syncAccountsDictionary;
+}
+
+- (void)setSyncAccountsDictionary:(NSMutableDictionary *)aSyncAccountsDictionary {
+    if (aSyncAccountsDictionary && ![self.syncAccountsDictionary isEqualToDictionary:aSyncAccountsDictionary]) {
+        syncAccountsDictionary = [[NSMutableDictionary alloc] initWithCapacity:[aSyncAccountsDictionary count]];
+        for (NSString *accountName in aSyncAccountsDictionary) {
+            NSDictionary *aSyncContainersDictionary = [aSyncAccountsDictionary objectForKey:accountName];
+            NSMutableDictionary *syncContainersDictionary = [NSMutableDictionary dictionary];
+            for (NSString *containerName in aSyncContainersDictionary) {
+                if (![accountName isEqualToString:@""] || ![[containerName lowercaseString] isEqualToString:@"shared with me"])
+                    [syncContainersDictionary setObject:[NSMutableSet setWithSet:[aSyncContainersDictionary objectForKey:containerName]] 
+                                                 forKey:containerName];
+            }
+            if ([syncContainersDictionary count])
+                [syncAccountsDictionary setObject:syncContainersDictionary forKey:accountName];
+        }
+        
+        @synchronized(self) {
+            resetSyncDaemonLocalState = YES;
+            syncLastCompleted = nil;
+        }
+    }
+}
+
+- (NSDate *)syncLastCompleted {
+    if (self.syncDaemon.lastCompletedSync && ![self.syncDaemon.lastCompletedSync isEqualToDate:syncLastCompleted]) {
+        syncLastCompleted = [self.syncDaemon.lastCompletedSync copy];
+    }
+    return syncLastCompleted;
+}
+
+- (PithosSyncDaemon *)syncDaemon {
+    @synchronized(self) {
+        if (self.syncActive && !syncDaemon)
+            syncDaemon = [[PithosSyncDaemon alloc] initWithDirectoryPath:self.syncDirectoryPath 
+                                                           pithosAccount:self 
+                                                      accountsDictionary:self.syncAccountsDictionary 
+                                                              skipHidden:self.syncSkipHidden 
+                                                         resetLocalState:resetSyncDaemonLocalState];
+        resetSyncDaemonLocalState = NO;
+    }
+    return syncDaemon;
+}
+
+- (NSString *)serverURL {
+    if (![self urlIsValid:serverURL]) {
+        serverURL = @"https://pithos.okeanos.grnet.gr";
+    }
+    return serverURL;
+}
+
+- (void)setServerURL:(NSString *)aServerURL {
+    if (![self.serverURL isEqualToString:aServerURL] && [self urlIsValid:aServerURL]) {
+        serverURL = aServerURL;
+        storageURLPrefix = nil;
+        authURL = nil;
+        publicURLPrefix = nil;
+        loginURLPrefix = nil;
+        userCatalogURL = nil;
+
+        @synchronized(self) {
+            updatePithos = YES;
+            resetSyncDaemonLocalState = YES;
+            syncLastCompleted = nil;
+        }
+    }
+}
+
+- (NSString *)versionResource {
+    if (!versionResource) {
+        versionResource = @"v1";
+    }
+    return versionResource;
+}
+
+- (NSString *)loginResource {
+    if (!loginResource) {
+        loginResource = @"login";
+    }
+    return loginResource;
+}
+
+- (NSString *)userCatalogResource {
+    if (!userCatalogResource) {
+        userCatalogResource = @"user_catalogs";
+    }
+    return userCatalogResource;
+}
+
+- (void)setAuthUser:(NSString *)anAuthUser {
+    if ([anAuthUser length] && ![anAuthUser isEqualToString:authUser]) {
+        authUser = anAuthUser;
+        
+        @synchronized(self) {
+            updatePithos = YES;
+            resetSyncDaemonLocalState = YES;
+            syncLastCompleted = nil;
+
+        }
+    }
+}
+
+- (void)setAuthToken:(NSString *)anAuthToken {
+    if ([anAuthToken length] && ![anAuthToken isEqualToString:authToken]) {
+        authToken = anAuthToken;
+        
+        @synchronized(self) {
+            updatePithos = YES;
+        }
+    }
+}
+
+- (NSString *)storageURLPrefix {
+    if (![self urlIsValid:storageURLPrefix]) {
+        storageURLPrefix = [self.serverURL stringByAppendingFormat:@"/%@", self.versionResource];
+    }
+    return storageURLPrefix;
+}
+
+- (void)setStorageURLPrefix:(NSString *)aStorageURLPrefix {
+    if (![self.storageURLPrefix isEqualToString:aStorageURLPrefix] && [self urlIsValid:aStorageURLPrefix]) {
+        storageURLPrefix = aStorageURLPrefix;
     }
-    return children;
 }
+
+- (NSString *)authURL {
+    if (![self urlIsValid:authURL]) {
+        authURL = [self.serverURL stringByAppendingFormat:@"/%@", self.versionResource];
+    }
+    return authURL;
+}
+
+- (void)setAuthURL:(NSString *)anAuthURL {
+    if (![self.authURL isEqualToString:anAuthURL] && [self urlIsValid:anAuthURL]) {
+        authURL = anAuthURL;
+    }
+}
+
+- (NSString *)publicURLPrefix {
+    if (![self urlIsValid:publicURLPrefix]) {
+        if (publicResource)
+            publicURLPrefix = [self.serverURL stringByAppendingFormat:@"/%@", publicResource];
+        else
+            publicURLPrefix = [self.serverURL copy];
+    }
+    return publicURLPrefix;
+}
+
+- (void)setPublicURLPrefix:(NSString *)aPublicURLPrefix {
+    if (![self.publicURLPrefix isEqualToString:aPublicURLPrefix] && [self urlIsValid:aPublicURLPrefix]) {
+        publicURLPrefix = aPublicURLPrefix;
+    }
+}
+
+- (NSString *)loginURLPrefix {
+    if (![self urlIsValid:loginURLPrefix]) {
+        loginURLPrefix = [self.serverURL stringByAppendingFormat:@"/%@", self.loginResource];
+    }
+    return loginURLPrefix;
+}
+
+- (void)setLoginURLPrefix:(NSString *)aLoginURLPrefix {
+    if (![self.loginURLPrefix isEqualToString:aLoginURLPrefix] && [self urlIsValid:aLoginURLPrefix]) {
+        loginURLPrefix = aLoginURLPrefix;
+    }
+}
+
+- (NSString *)userCatalogURL {
+    if (![self urlIsValid:userCatalogURL]) {
+        userCatalogURL = [self.serverURL stringByAppendingFormat:@"/%@", self.userCatalogResource];
+    }
+    return userCatalogURL;
+}
+
+- (void)setUserCatalogURL:(NSString *)aUserCatalogURL {
+    if (![self.userCatalogURL isEqualToString:aUserCatalogURL] && [self urlIsValid:aUserCatalogURL]) {
+        userCatalogURL = aUserCatalogURL;
+    }
+}
+
+- (NSMutableDictionary *)userCatalog {
+    if (!userCatalog) {
+        userCatalog = [NSMutableDictionary dictionary];
+    }
+    return userCatalog;
+}
+
+- (ASIPithos *)pithos {
+    @synchronized(self) {
+        if (!pithos || updatePithos) {
+            pithos = [ASIPithos pithos];
+            pithos.authUser = authUser;
+            pithos.authToken = authToken;
+            pithos.storageURLPrefix = self.storageURLPrefix;
+            pithos.authURL = self.authURL;
+            pithos.publicURLPrefix = self.publicURLPrefix;
+            pithos.userCatalogURL = self.userCatalogURL;
+            updatePithos = NO;
+        }
+    }
+    return pithos;
+}
+
+- (PithosAccountNode *)accountNode {
+    if (!accountNode) {
+        accountNode = [[PithosAccountNode alloc] initWithPithosAccountManager:self andPithos:self.pithos];
+        accountNode.childrenUpdatedNotificationName = nil;
+        accountNode.inheritChildrenUpdatedNotificationName = YES;
+    }
+    return accountNode;
+}
+
+- (PithosSharingAccountsNode *)sharingAccountsNode {
+    if (!sharingAccountsNode) {
+        sharingAccountsNode = [[PithosSharingAccountsNode alloc] initWithPithosAccountManager:self andPithos:self.pithos];
+        sharingAccountsNode.childrenUpdatedNotificationName = nil;
+        sharingAccountsNode.inheritChildrenUpdatedNotificationName = YES;
+    }
+    return sharingAccountsNode;
+}
+
+#pragma mark -
+#pragma mark Actions
+
+- (void)authenticateWithServerURL:(NSString *)aServerURL authUser:(NSString *)anAuthUser authToken:(NSString *)anAuthToken {
+    self.serverURL = aServerURL;
+    self.authUser = anAuthUser;
+    self.authToken = anAuthToken;
+    DLog(@"Account: %@\nauthentication", self);
+    if (![authUser length] || ![authToken length]) {
+        self.active = NO;
+        self.syncActive = NO;
+        // XXX Show preferences with self as the selected account?
+    } else  {
+        [self updateUserCatalogForForDisplaynames:nil UUIDs:[NSArray arrayWithObject:authUser]];
+        
+        self.active = YES;
+        if (syncDaemon) {
+            self.syncDaemon.pithos = self.pithos;
+            if (self.syncActive)
+                [self.syncDaemon startDaemon];
+        }
+        if (accountNode)
+            self.accountNode.pithos = self.pithos;
+        if (sharingAccountsNode)
+            self.sharingAccountsNode.pithos = self.pithos;
+        if (accountNode) {
+            if (self.accountNode.children) {
+            }
+            [self.accountNode refreshInfo];
+        }
+        if (sharingAccountsNode && self.sharingAccountsNode.children) {
+        }
+    }
+}
+
+- (void)loginWithServerURL:(NSString *)aServerURL {
+    self.serverURL = aServerURL;
+    NSProcessInfo *processInfo = [NSProcessInfo processInfo];
+    NSString *loginURL = [NSString stringWithFormat:@"%@?next=pithos://%d/%@&force=", 
+                          self.loginURLPrefix, [processInfo processIdentifier], [ASIPithosRequest encodeToPercentEscape:self.name]];
+    DLog(@"Account: %@\nloginURL: %@", self, loginURL);
+    [[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:loginURL]];
+}
+
+- (void)updateSyncWithSyncActive:(BOOL)aSyncActive 
+               syncDirectoryPath:(NSString *)aSyncDirectoryPath 
+          syncAccountsDictionary:(NSMutableDictionary *)aSyncAccountsDictionary 
+                  syncSkipHidden:(BOOL)aSyncSkipHidden {
+    self.syncAccountsDictionary = aSyncAccountsDictionary;
+    self.syncDirectoryPath = aSyncDirectoryPath;
+    self.syncSkipHidden = aSyncSkipHidden;
+    self.syncActive = aSyncActive;
+    if (syncDaemon) {
+        self.syncDaemon.accountsDictionary = self.syncAccountsDictionary;
+        self.syncDaemon.directoryPath = self.syncDirectoryPath;
+        self.syncDaemon.skipHidden = self.syncSkipHidden;
+        if (self.syncActive)
+            [self.syncDaemon startDaemon];
+    }    
+}
+
+- (ASIPithosRequest *)updateUserCatalogForForDisplaynames:(NSArray *)displaynames UUIDs:(NSArray *)UUIDs {
+    ASIPithosRequest *userCatalogRequest = [ASIPithosRequest userCatalogRequestWithPithos:self.pithos
+                                                                             displaynames:displaynames
+                                                                                    UUIDs:UUIDs];
+    [PithosUtilities startAndWaitForRequest:userCatalogRequest];
+    if (userCatalogRequest.error || ((userCatalogRequest.responseStatusCode != 200) && (userCatalogRequest.responseStatusCode != 404))) {
+        // Don't show alert on 404, since it can be a pre-UUID server.
+        [PithosUtilities httpRequestErrorAlertWithRequest:userCatalogRequest];
+    } else if (userCatalogRequest.responseStatusCode == 200) {
+        NSDictionary *catalogs = [userCatalogRequest catalogs];
+        NSDictionary *displaynameCatalog = [catalogs objectForKey:@"displayname_catalog"];
+        for (NSString *displayname in displaynameCatalog) {
+            [self.userCatalog setObject:displayname forKey:[displaynameCatalog objectForKey:displayname]];
+        }
+        if (UUIDs) {
+            NSDictionary *UUIDCatalog = [catalogs objectForKey:@"uuid_catalog"];
+            for (NSString *UUID in UUIDs) {
+                NSString *displayname = [UUIDCatalog objectForKey:UUID];
+                if (displayname) {
+                    [self.userCatalog setObject:displayname forKey:UUID];
+                } else {
+                    [self.userCatalog removeObjectForKey:UUID];
+                }
+            }
+        }
+    }
+    return userCatalogRequest;
+}
+
+- (NSString *)displaynameForUUID:(NSString *)UUID safe:(BOOL)safe {
+    NSString *displayName = [userCatalog objectForKey:UUID];
+    if (safe && !displayName) {
+        return UUID;
+    } else {
+        return displayName;
+    }
+}
+
+- (NSString *)displaynameForUUID:(NSString *)UUID {
+    return [self displaynameForUUID:UUID safe:NO];
+}
+
+#pragma mark -
+#pragma mark NSCoding
+
+- (id)initWithCoder:(NSCoder *)decoder {
+    if ((self = [super init])) {
+        self.uniqueName = [decoder decodeObjectForKey:@"uniqueName"];
+        self.active = [decoder decodeBoolForKey:@"active"];
+        name = [decoder decodeObjectForKey:@"name"];
+        self.clientVersion = [decoder decodeObjectForKey:@"clientVersion"];
+
+        self.syncActive = [decoder decodeBoolForKey:@"syncActive"];
+        self.syncDirectoryPath = [decoder decodeObjectForKey:@"syncDirectoryPath"];
+        self.syncAccountsDictionary = [decoder decodeObjectForKey:@"syncAccountsDictionary"];
+        self.syncSkipHidden = [decoder decodeBoolForKey:@"syncSkipHidden"];
+        self.syncLastCompleted = [decoder decodeObjectForKey:@"syncLastCompleted"];
+        
+        self.serverURL = [decoder decodeObjectForKey:@"serverURL"];
+        self.versionResource = [decoder decodeObjectForKey:@"versionResource"];
+        self.loginResource = [decoder decodeObjectForKey:@"loginResource"];
+        self.publicResource = [decoder decodeObjectForKey:@"publicResource"];
+        self.userCatalogResource = [decoder decodeObjectForKey:@"userCatalogResource"];
+        
+        self.authUser = [decoder decodeObjectForKey:@"authUser"];
+        self.authToken = [decoder decodeObjectForKey:@"authToken"];
+        self.storageURLPrefix = [decoder decodeObjectForKey:@"storageURLPrefix"];
+        self.authURL = [decoder decodeObjectForKey:@"authURL"];
+        self.publicURLPrefix = [decoder decodeObjectForKey:@"publicURLPrefix"];
+        self.loginURLPrefix = [decoder decodeObjectForKey:@"loginURLPrefix"];
+        self.userCatalogURL = [decoder decodeObjectForKey:@"userCatalogURL"];
+        self.userCatalog = [decoder decodeObjectForKey:@"userCatalog"];
+        
+        if (![authUser length] || ![authToken length] || ![self.storageURLPrefix length])
+            self.active = NO;
+        
+        NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"];
+        if (!clientVersion || ![clientVersion isEqualToString:currentVersion]) {
+            resetSyncDaemonLocalState = YES;
+            self.clientVersion = currentVersion;
+        } else {
+            resetSyncDaemonLocalState = NO;
+        }
+    }
+    return self;
+}
+
+- (void)encodeWithCoder:(NSCoder *)encoder {
+    [encoder encodeObject:uniqueName forKey:@"uniqueName"];
+    [encoder encodeBool:active forKey:@"active"];
+    [encoder encodeObject:name forKey:@"name"];
+    [encoder encodeObject:clientVersion forKey:@"clientVersion"];
     
+    [encoder encodeBool:syncActive forKey:@"syncActive"];
+    [encoder encodeObject:syncDirectoryPath forKey:@"syncDirectoryPath"];
+    [encoder encodeObject:syncAccountsDictionary forKey:@"syncAccountsDictionary"];
+    [encoder encodeBool:syncSkipHidden forKey:@"syncSkipHidden"];
+    [encoder encodeObject:self.syncLastCompleted forKey:@"syncLastCompleted"];
+
+    [encoder encodeObject:serverURL forKey:@"serverURL"];
+    [encoder encodeObject:versionResource forKey:@"versionResource"];
+    [encoder encodeObject:publicResource forKey:@"publicResource"];
+    [encoder encodeObject:loginResource forKey:@"loginResource"];
+    [encoder encodeObject:loginResource forKey:@"userCatalogResource"];
+    
+    [encoder encodeObject:authUser forKey:@"authUser"];
+    [encoder encodeObject:authToken forKey:@"authToken"];
+    [encoder encodeObject:storageURLPrefix forKey:@"storageURLPrefix"];
+    [encoder encodeObject:authURL forKey:@"authURL"];
+    [encoder encodeObject:publicURLPrefix forKey:@"publicURLPrefix"];
+    [encoder encodeObject:loginURLPrefix forKey:@"loginURLPrefix"];
+    [encoder encodeObject:userCatalogURL forKey:@"userCatalogURL"];
+    [encoder encodeObject:userCatalog forKey:@"userCatalog"];
+}
+
 @end