a04650d42a5251f5d088485bd6699290f34b73d1
[pithos-macos] / pithos-macos / PithosSharingAccountsNode.m
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 "PithosUtilities.h"
45 #import "PithosActivityFacility.h"
46
47 @implementation PithosSharingAccountsNode
48 @synthesize pithos;
49
50 #pragma mark -
51 #pragma mark Object Lifecycle
52
53 - (id)initWithPithos:(ASIPithos *)aPithos {
54     if ((self = [super init])) {
55         pithos = aPithos;
56         self.sharingAccount = @"";
57     }
58     return self;
59 }
60
61 - (void)dealloc {
62     [sharingAccountsRequest clearDelegatesAndCancel];
63 }
64
65 #pragma mark -
66 #pragma mark Properties
67
68 - (void)setPithos:(ASIPithos *)aPithos {
69     if (aPithos && ![aPithos isEqualTo:pithos]) {
70         pithos = aPithos;
71         url = nil;
72         [sharingAccountsRequest clearDelegatesAndCancel];
73         sharingAccountsRequest = nil;
74         reset = YES;
75     }
76 }
77
78 - (NSString *)url {
79     if (url == nil) 
80         url = [pithos.storageURLPrefix copy];
81     return url;
82 }
83
84 - (NSArray *)children {
85     @synchronized(self) {
86         if (reset) {
87             [sharingAccountsRequest clearDelegatesAndCancel];
88             sharingAccountsRequest = nil;
89             children = nil;
90             newChildren = nil;
91             freshness = PithosNodeStateRefreshNeeded;
92             forcedRefresh = YES;
93             reset = NO;
94             [self postChildrenUpdatedNotificationName];
95         }
96         switch (freshness) {
97             case PithosNodeStateFresh:
98                 break;
99             case PithosNodeStateRefreshNeeded:
100                 freshness = PithosNodeStateRefreshing;
101                 sharingAccountsRequest = [ASIPithosRequest listSharingAccountsRequestWithPithos:pithos limit:0 marker:nil];
102                 sharingAccountsRequest.delegate = self;
103                 sharingAccountsRequest.didFinishSelector = @selector(performRequestFinishedDelegateInBackground:);
104                 sharingAccountsRequest.didFailSelector = @selector(performRequestFailedDelegateInBackground:);
105                 sharingAccountsRequest.userInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
106                                                    [NSNumber numberWithInteger:NSOperationQueuePriorityVeryHigh], @"priority", 
107                                                    [NSNumber numberWithUnsignedInteger:10], @"retries", 
108                                                    NSStringFromSelector(@selector(sharingAccountsRequestFinished:)), @"didFinishSelector", 
109                                                    NSStringFromSelector(@selector(sharingAccountsRequestFailed:)), @"didFailSelector", 
110                                                    nil];
111 //                if (!forcedRefresh)
112 //                    sharingAccountsRequest.downloadCache = [ASIDownloadCache sharedCache];
113                 [[PithosUtilities prepareRequest:sharingAccountsRequest priority:NSOperationQueuePriorityVeryHigh] startAsynchronous];
114                 break;
115             case PithosNodeStateRefreshing:
116                 break;
117             case PithosNodeStateRefreshFinished:
118                 if (newChildren) {
119                     children = newChildren;
120                     newChildren = nil;
121                 }
122                 freshness = PithosNodeStateFresh;
123             default:
124                 break;
125         }
126         return children;
127     }
128 }
129
130 - (NSString *)displayName {
131     if (displayName == nil)
132         return @"sharing accounts";
133     return [displayName copy];
134 }
135
136 #pragma mark -
137 #pragma mark ASIHTTPRequestDelegate
138
139 - (void)sharingAccountsRequestFailed:(ASIPithosRequest *)request {
140     @autoreleasepool {
141         NSString *message;
142         NSError *error = [sharingAccountsRequest error];
143         if (error)
144             message = [NSString stringWithFormat:@"Sharing accounts listing %@ failed: %@", 
145                        sharingAccountsRequest.url, [error localizedDescription]];
146         else
147             message = [NSString stringWithFormat:@"Sharing accounts listing %@ failed: (%d) %@", 
148                        sharingAccountsRequest.url, sharingAccountsRequest.responseStatusCode, sharingAccountsRequest.responseStatusMessage];
149         dispatch_async(dispatch_get_main_queue(), ^{
150             [[PithosActivityFacility defaultPithosActivityFacility] startAndEndActivityWithType:PithosActivityOther message:message];
151         });
152         NSUInteger retries = [[sharingAccountsRequest.userInfo objectForKey:@"retries"] unsignedIntegerValue];
153         if (retries > 0) {
154             ASIPithosRequest *newSharingAccountsRequest = (ASIPithosRequest *)[PithosUtilities copyRequest:sharingAccountsRequest];
155             [(NSMutableDictionary *)(newSharingAccountsRequest.userInfo)setObject:[NSNumber numberWithUnsignedInteger:(--retries)] forKey:@"retries"];
156             sharingAccountsRequest = newSharingAccountsRequest;
157             [[PithosUtilities prepareRequest:sharingAccountsRequest priority:[[sharingAccountsRequest.userInfo objectForKey:@"priority"] integerValue]] startAsynchronous];
158         } else {
159             newChildren = nil;
160             sharingAccountsRequest = nil;
161             sharingAccounts = 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             NSArray *someSharingAccounts = [sharingAccountsRequest sharingAccounts];
176             if (sharingAccounts == nil) {
177                 sharingAccounts = [[NSMutableArray alloc] initWithArray:someSharingAccounts];
178             } else {
179                 [sharingAccounts addObjectsFromArray:someSharingAccounts];
180             }
181             if ([someSharingAccounts count] < 10000) {
182                 if (!sharingAccountsRequest.didUseCachedResponse || ([sharingAccounts count] != [someSharingAccounts count]) || !children) {
183                     // Save new children
184                     DLog(@"using newChildren");
185                     newChildren = [[NSMutableArray alloc] init];
186                     NSMutableIndexSet *keptNodes = [NSMutableIndexSet indexSet];
187                     for (ASIPithosAccount *account in sharingAccounts) {
188                         if (![account.name isEqualToString:pithos.authUser]) {
189                             PithosAccountNode *node = [[PithosAccountNode alloc] initWithPithos:pithos];
190                             node.parent = self;
191                             node.shared = shared;
192                             node.sharingAccount = account.name;
193                             node.inheritChildrenUpdatedNotificationName = inheritChildrenUpdatedNotificationName;
194                             if (children) {
195                                 NSUInteger oldIndex = [children indexOfObject:node];
196                                 if (oldIndex != NSNotFound) {
197                                     // Use the same pointer value, if possible
198                                     node = [children objectAtIndex:oldIndex];
199                                     [keptNodes addIndex:oldIndex];
200                                 }
201                             }
202                             [newChildren addObject:node];
203                         }
204                     }
205                     [[children objectsAtIndexes:
206                       [[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, [children count])] indexesPassingTest:^(NSUInteger idx, BOOL *stop){
207                         if ([keptNodes containsIndex:idx])
208                             return NO;
209                         return YES;
210                     }]] makeObjectsPerformSelector:@selector(pithosNodeWillBeRemoved)];
211                 }
212                 // Else cache was used and all results were fetched during this request, so existing children can be reused
213                 sharingAccountsRequest = nil;
214                 sharingAccounts = nil;
215                 forcedRefresh = NO;
216                 @synchronized(self) {
217                     freshness = PithosNodeStateRefreshFinished;
218                 }
219                 [self postChildrenUpdatedNotificationName];
220             } else {
221                 // Do an additional request to fetch more objects
222                 sharingAccountsRequest = [ASIPithosRequest listSharingAccountsRequestWithPithos:pithos 
223                                                                                            limit:0 
224                                                                                           marker:[[someSharingAccounts lastObject] name]];
225                 sharingAccountsRequest.delegate = self;
226                 sharingAccountsRequest.didFinishSelector = @selector(performRequestFinishedDelegateInBackground:);
227                 sharingAccountsRequest.didFailSelector = @selector(performRequestFailedDelegateInBackground:);
228                 sharingAccountsRequest.userInfo = [NSMutableDictionary dictionaryWithObjectsAndKeys:
229                                                    [NSNumber numberWithInteger:NSOperationQueuePriorityVeryHigh], @"priority", 
230                                                    [NSNumber numberWithUnsignedInteger:10], @"retries", 
231                                                    NSStringFromSelector(@selector(sharingAccountsRequestFinished:)), @"didFinishSelector", 
232                                                    NSStringFromSelector(@selector(sharingAccountsRequestFailed:)), @"didFailSelector", 
233                                                    nil];
234 //              if (!forcedRefresh)
235 //                  sharingAccountsRequest.downloadCache = [ASIDownloadCache sharedCache];
236                 [[PithosUtilities prepareRequest:sharingAccountsRequest priority:NSOperationQueuePriorityVeryHigh] startAsynchronous];
237             }
238         } else {
239             [self sharingAccountsRequestFailed:sharingAccountsRequest];
240         }
241     }
242 }
243
244 @end