Statistics
| Branch: | Tag: | Revision:

root / pithos-macos / PithosSharingAccountsNode.m @ baaf1397

History | View | Annotate | Download (12.4 kB)

1
//
2
//  PithosAccountNode.m
3
//  pithos-macos
4
//
5
// Copyright 2011-2012 GRNET S.A. All rights reserved.
6
//
7
// Redistribution and use in source and binary forms, with or
8
// without modification, are permitted provided that the following
9
// conditions are met:
10
// 
11
//   1. Redistributions of source code must retain the above
12
//      copyright notice, this list of conditions and the following
13
//      disclaimer.
14
// 
15
//   2. Redistributions in binary form must reproduce the above
16
//      copyright notice, this list of conditions and the following
17
//      disclaimer in the documentation and/or other materials
18
//      provided with the distribution.
19
// 
20
// THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
21
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
22
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23
// PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
24
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
27
// USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28
// AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29
// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
30
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31
// POSSIBILITY OF SUCH DAMAGE.
32
// 
33
// The views and conclusions contained in the software and
34
// documentation are those of the authors and should not be
35
// interpreted as representing official policies, either expressed
36
// or implied, of GRNET S.A.
37

    
38
#import "PithosSharingAccountsNode.h"
39
#import "PithosAccountNode.h"
40
#import "ASIPithosRequest.h"
41
#import "ASIPithos.h"
42
#import "ASIPithosAccount.h"
43
#import "ASIDownloadCache.h"
44
#import "PithosAccount.h"
45
#import "PithosUtilities.h"
46
#import "PithosActivityFacility.h"
47

    
48
@implementation PithosSharingAccountsNode
49
@synthesize pithos, sharingAccountsRequest;
50

    
51
#pragma mark -
52
#pragma mark Object Lifecycle
53

    
54
- (id)initWithPithosAccountManager:(PithosAccount *)aPithosAccountManager andPithos:(ASIPithos *)aPithos {
55
    if ((self = [super initWithPithosAccountManager:aPithosAccountManager])) {
56
        pithos = aPithos;
57
        self.sharingAccount = @"";
58
    }
59
    return self;
60
}
61

    
62
- (void)dealloc {
63
    [sharingAccountsRequest clearDelegatesAndCancel];
64
}
65

    
66
#pragma mark -
67
#pragma mark Properties
68

    
69
- (void)setPithos:(ASIPithos *)aPithos {
70
    if (aPithos && ![aPithos isEqualTo:pithos]) {
71
        pithos = aPithos;
72
        url = nil;
73
        [sharingAccountsRequest clearDelegatesAndCancel];
74
        self.sharingAccountsRequest = nil;
75
        reset = YES;
76
    }
77
}
78

    
79
- (NSString *)url {
80
    if (url == nil) 
81
        url = [[pithos.storageURLPrefix description] copy];
82
    return url;
83
}
84

    
85
- (NSArray *)children {
86
    @synchronized(self) {
87
        if (reset) {
88
            [sharingAccountsRequest clearDelegatesAndCancel];
89
            self.sharingAccountsRequest = nil;
90
            children = nil;
91
            newChildren = nil;
92
            freshness = PithosNodeStateRefreshNeeded;
93
            forcedRefresh = YES;
94
            reset = NO;
95
            [self postChildrenUpdatedNotificationName];
96
        }
97
        switch (freshness) {
98
            case PithosNodeStateFresh:
99
                break;
100
            case PithosNodeStateRefreshNeeded:
101
                freshness = PithosNodeStateRefreshing;
102
                self.sharingAccountsRequest = [ASIPithosRequest listSharingAccountsRequestWithPithos:pithos limit:0 marker:nil];
103
                sharingAccountsRequest.delegate = self;
104
                sharingAccountsRequest.didFinishSelector = @selector(performRequestFinishedDelegateInBackground:);
105
                sharingAccountsRequest.didFailSelector = @selector(performRequestFailedDelegateInBackground:);
106
                sharingAccountsRequest.userInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
107
                                                   [NSNumber numberWithInteger:NSOperationQueuePriorityVeryHigh], @"priority", 
108
                                                   [NSNumber numberWithUnsignedInteger:10], @"retries", 
109
                                                   NSStringFromSelector(@selector(sharingAccountsRequestFinished:)), @"didFinishSelector", 
110
                                                   NSStringFromSelector(@selector(sharingAccountsRequestFailed:)), @"didFailSelector", 
111
                                                   nil];
112
//                if (!forcedRefresh)
113
//                    sharingAccountsRequest.downloadCache = [ASIDownloadCache sharedCache];
114
                [[PithosUtilities prepareRequest:sharingAccountsRequest priority:NSOperationQueuePriorityVeryHigh] startAsynchronous];
115
                break;
116
            case PithosNodeStateRefreshing:
117
                break;
118
            case PithosNodeStateRefreshFinished:
119
                if (newChildren) {
120
                    children = newChildren;
121
                    newChildren = nil;
122
                }
123
                freshness = PithosNodeStateFresh;
124
            default:
125
                break;
126
        }
127
        return children;
128
    }
129
}
130

    
131
- (NSString *)displayName {
132
    if (displayName == nil)
133
        return @"sharing accounts";
134
    return [displayName copy];
135
}
136

    
137
#pragma mark -
138
#pragma mark ASIHTTPRequestDelegate
139

    
140
- (void)sharingAccountsRequestFailed:(ASIPithosRequest *)request {
141
    @autoreleasepool {
142
        NSString *message;
143
        NSError *error = [sharingAccountsRequest error];
144
        if (error)
145
            message = [NSString stringWithFormat:@"Sharing accounts listing %@ failed: %@", 
146
                       sharingAccountsRequest.url, [error localizedDescription]];
147
        else
148
            message = [NSString stringWithFormat:@"Sharing accounts listing %@ failed: (%d) %@", 
149
                       sharingAccountsRequest.url, sharingAccountsRequest.responseStatusCode, sharingAccountsRequest.responseStatusMessage];
150
        dispatch_async(dispatch_get_main_queue(), ^{
151
            [[PithosActivityFacility defaultPithosActivityFacility] startAndEndActivityWithType:PithosActivityOther message:message];
152
        });
153
        NSUInteger retries = [[sharingAccountsRequest.userInfo objectForKey:@"retries"] unsignedIntegerValue];
154
        if (retries > 0) {
155
            ASIPithosRequest *newSharingAccountsRequest = (ASIPithosRequest *)[PithosUtilities copyRequest:sharingAccountsRequest];
156
            [(NSMutableDictionary *)(newSharingAccountsRequest.userInfo)setObject:[NSNumber numberWithUnsignedInteger:(--retries)] forKey:@"retries"];
157
            self.sharingAccountsRequest = newSharingAccountsRequest;
158
            [[PithosUtilities prepareRequest:sharingAccountsRequest priority:[[sharingAccountsRequest.userInfo objectForKey:@"priority"] integerValue]] startAsynchronous];
159
        } else {
160
            newChildren = nil;
161
            self.sharingAccountsRequest = nil;
162
            forcedRefresh = NO;
163
            @synchronized(self) {
164
                freshness = PithosNodeStateRefreshNeeded;
165
            }
166
        }
167
    }
168
}
169

    
170
- (void)sharingAccountsRequestFinished:(ASIPithosRequest *)request {
171
    @autoreleasepool {
172
        DLog(@"List sharing accounts finished: %@", [sharingAccountsRequest url]);
173
        DLog(@"Cached: %d", [sharingAccountsRequest didUseCachedResponse]);
174
        if (sharingAccountsRequest.responseStatusCode == 200) {
175
            NSMutableArray *sharingAccounts = [sharingAccountsRequest.userInfo objectForKey:@"sharingAccounts"];
176
            NSArray *someSharingAccounts = [sharingAccountsRequest sharingAccounts];
177
            if (sharingAccounts == nil) {
178
                sharingAccounts = [NSMutableArray arrayWithArray:someSharingAccounts];
179
            } else {
180
                [sharingAccounts addObjectsFromArray:someSharingAccounts];
181
            }
182
            if ([someSharingAccounts count] < 10000) {
183
                if (!sharingAccountsRequest.didUseCachedResponse || ([sharingAccounts count] != [someSharingAccounts count]) || !children) {
184
                    // Save new children
185
                    DLog(@"using newChildren");
186
                    newChildren = [[NSMutableArray alloc] init];
187
                    NSMutableIndexSet *keptNodes = [NSMutableIndexSet indexSet];
188
                    for (ASIPithosAccount *account in sharingAccounts) {
189
                        if (![account.name isEqualToString:pithos.authUser]) {
190
                            PithosAccountNode *node = [[PithosAccountNode alloc] initWithPithosAccountManager:pithosAccountManager
191
                                                                                                    andPithos:pithos];
192
                            node.parent = self;
193
                            node.shared = shared;
194
                            node.sharingAccount = account.name;
195
                            node.inheritChildrenUpdatedNotificationName = inheritChildrenUpdatedNotificationName;
196
                            if (children) {
197
                                NSUInteger oldIndex = [children indexOfObject:node];
198
                                if (oldIndex != NSNotFound) {
199
                                    // Use the same pointer value, if possible
200
                                    node = [children objectAtIndex:oldIndex];
201
                                    [keptNodes addIndex:oldIndex];
202
                                }
203
                            }
204
                            [newChildren addObject:node];
205
                        }
206
                    }
207
                    [[children objectsAtIndexes:
208
                      [[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [children count])] indexesPassingTest:^(NSUInteger idx, BOOL *stop){
209
                        if ([keptNodes containsIndex:idx])
210
                            return NO;
211
                        return YES;
212
                    }]] makeObjectsPerformSelector:@selector(pithosNodeWillBeRemoved)];
213
                }
214
                // Else cache was used and all results were fetched during this request, so existing children can be reused
215
                // Update user catalog even if cache was used
216
                NSMutableArray *sharingAccountsNames = [NSMutableArray arrayWithCapacity:sharingAccounts.count];
217
                for (ASIPithosAccount *account in sharingAccounts) {
218
                    [sharingAccountsNames addObject:account.name];
219
                }
220
                [pithosAccountManager updateUserCatalogForDisplaynames:nil UUIDs:sharingAccountsNames];
221
                self.sharingAccountsRequest = nil;
222
                forcedRefresh = NO;
223
                @synchronized(self) {
224
                    freshness = PithosNodeStateRefreshFinished;
225
                }
226
                [self postChildrenUpdatedNotificationName];
227
            } else {
228
                // Do an additional request to fetch more objects
229
                self.sharingAccountsRequest = [ASIPithosRequest listSharingAccountsRequestWithPithos:pithos
230
                                                                                               limit:0
231
                                                                                              marker:[[someSharingAccounts lastObject] name]];
232
                sharingAccountsRequest.delegate = self;
233
                sharingAccountsRequest.didFinishSelector = @selector(performRequestFinishedDelegateInBackground:);
234
                sharingAccountsRequest.didFailSelector = @selector(performRequestFailedDelegateInBackground:);
235
                sharingAccountsRequest.userInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
236
                                                   [NSNumber numberWithInteger:NSOperationQueuePriorityVeryHigh], @"priority", 
237
                                                   [NSNumber numberWithUnsignedInteger:10], @"retries", 
238
                                                   NSStringFromSelector(@selector(sharingAccountsRequestFinished:)), @"didFinishSelector", 
239
                                                   NSStringFromSelector(@selector(sharingAccountsRequestFailed:)), @"didFailSelector",
240
                                                   sharingAccounts, @"sharingAccounts",
241
                                                   nil];
242
//              if (!forcedRefresh)
243
//                  sharingAccountsRequest.downloadCache = [ASIDownloadCache sharedCache];
244
                [[PithosUtilities prepareRequest:sharingAccountsRequest priority:NSOperationQueuePriorityVeryHigh] startAsynchronous];
245
            }
246
        } else {
247
            [self sharingAccountsRequestFailed:sharingAccountsRequest];
248
        }
249
    }
250
}
251

    
252
@end