-
Notifications
You must be signed in to change notification settings - Fork 72
/
CK2FileOperation.m
756 lines (604 loc) · 31 KB
/
CK2FileOperation.m
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
//
// CK2FileOperation.m
// Connection
//
// Created by Mike on 22/03/2013.
//
//
#import "CK2FileOperation.h"
#import "CK2Protocol.h"
#import <AppKit/AppKit.h> // so icon handling can use NSImage and NSWorkspace for now
@interface CK2FileOperation () <CK2ProtocolClient>
@property(readonly) CK2FileManager *fileManager; // goes to nil once finished/failed
@property (readwrite) int64_t countOfBytesWritten;
@property (readwrite) int64_t countOfBytesExpectedToWrite;
@property(readwrite) CK2FileOperationState state;
@property (readwrite, copy) NSError *error;
@end
#pragma mark -
@interface CK2Protocol (Internals)
// Completion block is guaranteed to be called on our private serial queue
+ (void)classForURL:(NSURL *)url completionHandler:(void (^)(Class protocolClass))block;
@end
@interface CK2FileManager (Internals)
+ (void)setTemporaryResourceValueForKey:(NSString *)key inURL:(NSURL *)url asBlock:(id (^)(void))block;
@end
#pragma mark -
@implementation CK2FileOperation
#pragma mark Lifecycle
- (id)initWithURL:(NSURL *)url
errorDescription:(NSString *)errorDescription
manager:(CK2FileManager *)manager
completionHandler:(void (^)(NSError *))completionBlock
createProtocolBlock:(CK2Protocol *(^)(Class protocolClass))createBlock;
{
NSParameterAssert(url);
NSParameterAssert(manager);
if (self = [self init])
{
_state = CK2FileOperationStateSuspended;
_manager = [manager retain];
_originalURL = [url copy];
_descriptionForErrors = [errorDescription copy];
if (!completionBlock)
{
completionBlock = ^(NSError *error) {
id <CK2FileManagerDelegate> delegate = manager.delegate;
if ([delegate respondsToSelector:@selector(fileManager:operation:didCompleteWithError:)])
{
[delegate fileManager:manager operation:self didCompleteWithError:error];
}
};
}
_completionBlock = [completionBlock copy];
_createProtocolBlock = [createBlock copy];
_queue = dispatch_queue_create("com.karelia.connection.file-operation", NULL);
}
return self;
}
- (id)initEnumerationOperationWithURL:(NSURL *)url
includingPropertiesForKeys:(NSArray *)keys
options:(NSDirectoryEnumerationOptions)mask
manager:(CK2FileManager *)manager
enumerationBlock:(void (^)(NSURL *))enumBlock
completionBlock:(void (^)(NSError *))block;
{
NSString *name = url.lastPathComponent;
NSString *description;
if (name.length)
{
description = [NSString stringWithFormat:NSLocalizedString(@"The folder “%@” could not be accessed.", "error descrption"),
url.lastPathComponent];
}
else
{
description = NSLocalizedString(@"The server could not be accessed.", "error description");
}
self = [self initWithURL:url errorDescription:description manager:manager completionHandler:block createProtocolBlock:^CK2Protocol *(Class protocolClass) {
// If we try to do this outside the block there's a risk the protocol object will be created *before* the enum block has been stored, which ends real badly
_enumerationBlock = [enumBlock copy];
return [[protocolClass alloc] initForEnumeratingDirectoryWithRequest:[self requestWithURL:url]
includingPropertiesForKeys:keys
options:mask
client:self];
}];
return self;
}
- (id)initDirectoryCreationOperationWithURL:(NSURL *)url
withIntermediateDirectories:(BOOL)createIntermediates
openingAttributes:(NSDictionary *)attributes
manager:(CK2FileManager *)manager
completionBlock:(void (^)(NSError *))block;
{
NSString *description = [NSString stringWithFormat:NSLocalizedString(@"The folder “%@” could not be created.", "error descrption"),
url.lastPathComponent];
self = [self initWithURL:url errorDescription:description manager:manager completionHandler:block createProtocolBlock:^CK2Protocol *(Class protocolClass) {
return [[protocolClass alloc] initForCreatingDirectoryWithRequest:[self requestWithURL:url]
withIntermediateDirectories:createIntermediates
openingAttributes:attributes
client:self];
}];
// Special case SFTP for now.
if ([url.scheme caseInsensitiveCompare:@"sftp"] == NSOrderedSame) {
_createIntermediateDirectories = createIntermediates;
}
return self;
}
- (id)initFileCreationOperationWithURL:(NSURL *)url
data:(NSData *)data
withIntermediateDirectories:(BOOL)createIntermediates
openingAttributes:(NSDictionary *)attributes
manager:(CK2FileManager *)manager
progressBlock:(CK2ProgressBlock)progressBlock
completionBlock:(void (^)(NSError *))block;
{
NSString *description = [NSString stringWithFormat:NSLocalizedString(@"The file “%@” could not be uploaded.", "error description"),
url.lastPathComponent];
self = [self initWithURL:url errorDescription:description manager:manager completionHandler:block createProtocolBlock:^CK2Protocol *(Class protocolClass) {
NSMutableURLRequest *request = [[self requestWithURL:url] mutableCopy];
request.HTTPBody = data;
CK2Protocol *result = [[protocolClass alloc] initForCreatingFileWithRequest:request
size:data.length
withIntermediateDirectories:createIntermediates
openingAttributes:attributes
client:self];
[request release];
return result;
}];
_bytesExpectedToWrite = data.length;
_progressBlock = [progressBlock copy];
// Special case SFTP for now.
if ([url.scheme caseInsensitiveCompare:@"sftp"] == NSOrderedSame) {
_createIntermediateDirectories = createIntermediates;
}
return self;
}
- (id)initFileCreationOperationWithURL:(NSURL *)url
file:(NSURL *)sourceURL
withIntermediateDirectories:(BOOL)createIntermediates
openingAttributes:(NSDictionary *)attributes
manager:(CK2FileManager *)manager
progressBlock:(CK2ProgressBlock)progressBlock
completionBlock:(void (^)(NSError *))block;
{
NSString *description = [NSString stringWithFormat:NSLocalizedString(@"The file “%@” could not be uploaded.", "error descrption"),
url.lastPathComponent];
NSNumber *fileSize;
if (![sourceURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:NULL]) fileSize = nil;;
self = [self initWithURL:url errorDescription:description manager:manager completionHandler:block createProtocolBlock:^CK2Protocol *(Class protocolClass) {
_localURL = [sourceURL copy];
NSMutableURLRequest *request = [[self requestWithURL:url] mutableCopy];
// Read the data using an input stream if possible, and know file size
int64_t size = (fileSize ? fileSize.longLongValue : NSURLResponseUnknownLength);
if (size >= 0)
{
NSInputStream *stream = [self protocol:nil needNewBodyStream:nil];
if (stream)
{
[request setHTTPBodyStream:stream];
}
}
if (!request.HTTPBodyStream)
{
NSError *error;
NSData *data = [[NSData alloc] initWithContentsOfURL:sourceURL options:0 error:&error];
if (data)
{
[request setHTTPBody:data];
size = data.length;
[data release];
}
else
{
[request release];
if (!error) error = [NSError errorWithDomain:NSCocoaErrorDomain code:NSFileReadUnknownError userInfo:nil];
[self protocol:nil didCompleteWithError:error];
return nil;
}
}
CK2Protocol *result = [[protocolClass alloc] initForCreatingFileWithRequest:request
size:size
withIntermediateDirectories:createIntermediates
openingAttributes:attributes
client:self];
[request release];
return result;
}];
_bytesExpectedToWrite = fileSize.longLongValue;
_progressBlock = [progressBlock copy];
// Special case SFTP for now.
if ([url.scheme caseInsensitiveCompare:@"sftp"] == NSOrderedSame) {
_createIntermediateDirectories = createIntermediates;
}
return self;
}
- (id)initRemovalOperationWithURL:(NSURL *)url
manager:(CK2FileManager *)manager
completionBlock:(void (^)(NSError *))block;
{
NSString *description = [NSString stringWithFormat:NSLocalizedString(@"The file “%@” could not be deleted.", "error descrption"),
url.lastPathComponent];
return [self initWithURL:url errorDescription:description manager:manager completionHandler:block createProtocolBlock:^CK2Protocol *(Class protocolClass) {
return [[protocolClass alloc] initForRemovingItemWithRequest:[self requestWithURL:url] client:self];
}];
}
- (id)initRenameOperationWithSourceURL:(NSURL *)srcURL
newName:(NSString *)newName
manager:(CK2FileManager *)manager
completionBlock:(void (^)(NSError *))block;
{
NSString *description = [NSString stringWithFormat:NSLocalizedString(@"The file “%@” could not be renamed.", "error descrption"),
srcURL.lastPathComponent];
return [self initWithURL:srcURL errorDescription:description manager:manager completionHandler:block createProtocolBlock:^CK2Protocol *(Class protocolClass) {
return [[protocolClass alloc] initForRenamingItemWithRequest:[self requestWithURL:srcURL] newName:newName client:self];
}];
}
- (id)initResourceValueSettingOperationWithURL:(NSURL *)url
values:(NSDictionary *)keyedValues
manager:(CK2FileManager *)manager
completionBlock:(void (^)(NSError *))block;
{
NSString *description = [NSString stringWithFormat:NSLocalizedString(@"The file “%@” could not be updated.", "error descrption"),
url.lastPathComponent];
return [self initWithURL:url errorDescription:description manager:manager completionHandler:block createProtocolBlock:^CK2Protocol *(Class protocolClass) {
return [[protocolClass alloc] initForSettingAttributes:keyedValues
ofItemWithRequest:[self requestWithURL:url]
client:self];
}];
}
- (void)completeWithError:(NSError *)error;
{
// Run completion block on own queue so that:
// A) It doesn't potentially hold up the calling queue for too long
// B) Serialises access
dispatch_async(_queue, ^{
if (_completionBlock) // only allow "completion" to happen the once!
{
// It's now safe to stop the protocol as it can't misinterpret the message and issue its own cancellation error (or at least if it does, goes ignored)
[_protocol stop];
// Store the error and notify completion handler
// Make all notifications — including KVO — happen on the delegate queue
[self tryToMessageDelegateSelector:NULL usingBlock:^(id<CK2FileManagerDelegate> delegate) { // NULL selector so always executes
self.error = error;
self.state = CK2FileOperationStateCompleted;
_completionBlock(error);
// Clean up now we're done notifying. Have to do this at completion time since it
// most likely breaks a retain cycle.
[_completionBlock release]; _completionBlock = nil;
[_progressBlock release]; _progressBlock = nil;
[_enumerationBlock release];_enumerationBlock = nil;
}];
// Break retain cycle, but deliberately keep weak reference so we know we're associated with it
[_protocol release];
}
});
}
- (void)dealloc
{
//[_protocol release]; DON'T release protocol. It should be a weak reference by the time deallocation happens
[_manager release];
[_originalURL release];
if (_queue) dispatch_release(_queue);
[_completionBlock release];
[_enumerationBlock release];
[_createProtocolBlock release];
[_progressBlock release];
[_localURL release];
[_error release];
[super dealloc];
}
#pragma mark Manager
@synthesize fileManager = _manager;
- (void)tryToMessageDelegateSelector:(SEL)selector usingBlock:(void (^)(id <CK2FileManagerDelegate> delegate))block;
{
CK2FileManager *manager = self.fileManager;
NSAssert(manager, @"%@ disconnected from its manager too early", self.class);
// Clients could change the delegate at any time. If we trust them to do so in concert with the
// delegate queue, then that can be made reasonably safe by only accessing the delegate from
// within the queue.
// It's still inherently a bit dangerous though, as the client could change it on a different
// queue, or could have specified a non-serial delegate queue.
[manager.delegateQueue addOperationWithBlock:^{
id <CK2FileManagerDelegate> delegate = manager.delegate;
if (!selector || [delegate respondsToSelector:selector]) {
block(delegate);
}
}];
}
#pragma mark URL & Requests
@synthesize originalURL = _originalURL;
- (NSURLRequest *)requestWithURL:(NSURL *)url;
{
return [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60.0];
}
#pragma mark Body Data
@synthesize countOfBytesWritten = _bytesWritten;
@synthesize countOfBytesExpectedToWrite = _bytesExpectedToWrite;
#pragma mark Cancellation
- (void)cancel;
{
if (self.state >= CK2FileOperationStateCanceling) return;
/* Any already-enqueued delegate messages will likely still run. That's fine as it seems we might as well report things that are already known to have happened
*/
// FIXME: There's a race condition here where .state could change after our intitial check of it
self.state = CK2FileOperationStateCanceling;
// Report cancellation to completion handler. If protocol has already finished or failed, it'll go ignored
NSError *cancellationError = [[NSError alloc] initWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:nil];
[self completeWithError:cancellationError];
[cancellationError release];
}
#pragma mark State
@synthesize state = _state;
@synthesize error = _error;
- (void)resume;
{
if (self.state == CK2FileOperationStateSuspended)
{
self.state = CK2FileOperationStateRunning;
[self createProtocolAndStart];
}
}
/**
Private method that does the work of creating the protocol instance, and getting it going
*/
- (void)createProtocolAndStart {
NSURL *url = self.originalURL;
[CK2Protocol classForURL:url completionHandler:^(Class protocolClass) {
if (protocolClass)
{
// Bounce over to operation's own queue for kicking off the real work
// Keep an eye out for early opportunity to bail out if get cancelled
dispatch_async(_queue, ^{
if (self.state == CK2FileOperationStateRunning)
{
NSAssert(_protocol == nil, @"Protocol has already been created");
_protocol = _createProtocolBlock(protocolClass);
// Protocol creation block was probably creating a retain cycle back to self, so
// dispose of now we've used it
[_createProtocolBlock release]; _createProtocolBlock = nil;
if (!_protocol)
{
// it's likely that the protocol has already called protocol:didFailWithError:, which will have called finishWithError:, which means that a call to the completion
// block is queue up already with an error in it
// just in case though, we can report a more generic error here - once the completion block is called once it will be cleared out, the protocol's error will win
// if there is one
NSDictionary *info = @{NSURLErrorKey : url, NSURLErrorFailingURLErrorKey : url, NSURLErrorFailingURLStringErrorKey : [url absoluteString]};
NSError *error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:NSURLErrorUnsupportedURL userInfo:info]; // TODO: what's the correct error to report here?
[self completeWithError:error];
[error release];
}
if (self.state == CK2FileOperationStateRunning) [_protocol start];
}
});
}
else
{
NSDictionary *info = @{NSURLErrorKey : url, NSURLErrorFailingURLErrorKey : url, NSURLErrorFailingURLStringErrorKey : [url absoluteString]};
NSError *error = [[NSError alloc] initWithDomain:NSURLErrorDomain code:NSURLErrorUnsupportedURL userInfo:info];
[self completeWithError:error];
[error release];
}
}];
}
#pragma mark CK2ProtocolClient
- (void)protocol:(CK2Protocol *)protocol didCompleteWithError:(NSError *)error;
{
NSAssert(protocol == _protocol, @"Message received from unexpected protocol: %@ (should be %@)", protocol, _protocol);
// Errors should start with our description
if (error)
{
if (_createIntermediateDirectories) {
NSString *path = [CK2FileManager pathOfURL:self.originalURL];
if (path.length && ![path isEqualToString:@"/"]) {
NSURL *directoryURL = [self.originalURL URLByDeletingLastPathComponent];
_createIntermediateDirectories = NO; // avoid doing this again
[self.fileManager createDirectoryAtURL:directoryURL
withIntermediateDirectories:YES
openingAttributes:nil // probably ought to provide something better, but I'm being lazy
completionHandler:^(NSError *directoryError) {
// If creating directory also fails, give up. Otherwise let's try again!
if (directoryError) {
[self protocol:protocol didCompleteWithError:error];
}
else {
[_protocol release]; _protocol = nil;
[self createProtocolAndStart];
}
}];
return;
}
}
if (_descriptionForErrors)
{
NSMutableDictionary *info = [error.userInfo mutableCopy];
NSString *description = [_descriptionForErrors stringByAppendingFormat:@" %@", error.localizedDescription];
[info setObject:description forKey:NSLocalizedDescriptionKey];
error = [NSError errorWithDomain:error.domain code:error.code userInfo:info];
[info release];
}
}
[self completeWithError:error];
}
- (NSURLRequest *)protocol:(CK2Protocol *)protocol willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response;
{
NSAssert(protocol == _protocol, @"Message received from unexpected protocol: %@ (should be %@)", protocol, _protocol);
id <CK2FileManagerDelegate> delegate = self.fileManager.delegate;
if ([delegate respondsToSelector:@selector(fileManager:operation:willSendRequest:redirectResponse:completionHandler:)])
{
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
__block NSURLRequest *weakRequest;
[delegate fileManager:self.fileManager operation:self willSendRequest:request redirectResponse:response completionHandler:^(NSURLRequest *request) {
weakRequest = [request retain];
dispatch_semaphore_signal(semaphore);
}];
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
request = [weakRequest autorelease];
dispatch_release(semaphore);
}
return request;
}
- (void)protocol:(CK2Protocol *)protocol didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(CK2AuthChallengeDisposition, NSURLCredential *))completionHandler;
{
NSAssert(protocol == _protocol, @"Message received from unexpected protocol: %@ (should be %@)", protocol, _protocol);
if (self.state >= CK2FileOperationStateCanceling) return; // don't care about auth once cancelled
// Invent a default credential if needed
if (!challenge.proposedCredential)
{
NSURLProtectionSpace *space = challenge.protectionSpace;
NSString *user = self.originalURL.user;
NSString *password = self.originalURL.password;
NSURLCredential *credential;
if (user)
{
if (password) {
credential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistenceNone];
}
else {
credential = [[NSURLCredentialStorage.sharedCredentialStorage credentialsForProtectionSpace:space] objectForKey:user];
}
}
else
{
credential = [[NSURLCredentialStorage sharedCredentialStorage] defaultCredentialForProtectionSpace:space];
}
challenge = [[NSURLAuthenticationChallenge alloc] initWithProtectionSpace:space
proposedCredential:credential
previousFailureCount:challenge.previousFailureCount
failureResponse:challenge.failureResponse
error:challenge.error
sender:challenge.sender];
[challenge autorelease];
}
// Notify the delegate
CK2FileManager *manager = self.fileManager;
id <CK2FileManagerDelegate> delegate = manager.delegate;
if ([delegate respondsToSelector:@selector(fileManager:operation:didReceiveChallenge:completionHandler:)])
{
[manager.delegateQueue addOperationWithBlock:^{
__block BOOL handlerCalled = NO;
[delegate fileManager:manager operation:self didReceiveChallenge:challenge completionHandler:^(CK2AuthChallengeDisposition disposition, NSURLCredential *credential) {
if (handlerCalled) [NSException raise:NSInvalidArgumentException format:@"Auth Challenge completion handler block called more than once"];
handlerCalled = YES;
dispatch_async(_queue, ^{
completionHandler(disposition, credential);
});
}];
}];
}
else if ([delegate respondsToSelector:@selector(fileManager:didReceiveAuthenticationChallenge:)])
{
NSLog(@"%@ implements the old CK2FileManager authentication delegate method instead of the new one", delegate.class);
}
else
{
dispatch_async(_queue, ^{
completionHandler(CK2AuthChallengePerformDefaultHandling, nil);
});
}
// TODO: Cache credentials per protection space
}
- (void)protocol:(CK2Protocol *)protocol appendString:(NSString *)info toTranscript:(CK2TranscriptType)transcript;
{
NSAssert(protocol == _protocol, @"Message received from unexpected protocol: %@ (should be %@)", protocol, _protocol);
// Pass straight onto delegate and trust it not to take too long handling it
// We used to dispatch off onto one of the global queues, but that does have the nasty downside of messages sometimes arriving out-of-order or concurrently
[self tryToMessageDelegateSelector:@selector(fileManager:appendString:toTranscript:) usingBlock:^(id<CK2FileManagerDelegate> delegate) {
[delegate fileManager:self.fileManager appendString:info toTranscript:transcript];
}];
}
- (void)protocol:(CK2Protocol *)protocol didDiscoverItemAtURL:(NSURL *)url;
{
NSAssert(protocol == _protocol, @"Message received from unexpected protocol: %@ (should be %@)", protocol, _protocol);
// Even if cancelled, allow through as the discovery still stands; might be useful for caching elsewhere
// Provide ancestry and other fairly generic keys on-demand
[self.class setResourceValueBlocksForURL:url protocolClass:protocol.class];
if (_enumerationBlock)
{
[self tryToMessageDelegateSelector:NULL usingBlock:^(id<CK2FileManagerDelegate> delegate) {
_enumerationBlock(url);
}];
}
// It seems poor security to vend out passwords here, so have a quick sanity check
if (CFURLGetByteRangeForComponent((CFURLRef)url, kCFURLComponentPassword, NULL).location != kCFNotFound)
{
NSLog(@"%@ is reporting URLs with a password, such as %@\nThis seems poor security practice", protocol, url);
}
}
+ (void)setResourceValueBlocksForURL:(NSURL *)strongURL protocolClass:(Class)protocolClass;
{
__block NSURL *url = strongURL; // URL retains its resource values; so if the blocks retained the URL would be a cycle
NSString *path = [protocolClass pathOfURLRelativeToHomeDirectory:url];
if ([path isAbsolutePath])
{
[CK2FileManager setTemporaryResourceValueForKey:NSURLParentDirectoryURLKey inURL:url asBlock:^id {
if (path.pathComponents.count > 1) // stop at root
{
NSURL *result = [url URLByDeletingLastPathComponent];
[CK2FileManager setTemporaryResourceValue:@YES forKey:NSURLIsDirectoryKey inURL:result];
// Recurse
[self setResourceValueBlocksForURL:result protocolClass:protocolClass];
return result;
}
return nil;
}];
// Only need supply icon if protocol hasn't done so
NSImage *icon;
if (![url getResourceValue:&icon forKey:NSURLEffectiveIconKey error:NULL] || !icon)
{
// Fill in icon as best we can
[CK2FileManager setTemporaryResourceValueForKey:NSURLEffectiveIconKey inURL:url asBlock:^id{
NSString *fileType = url.pathExtension;
if (path.pathComponents.count == 1)
{
fileType = NSFileTypeForHFSTypeCode(kGenericFileServerIcon);
}
else if ([fileType isEqual:@"app"])
{
fileType = NSFileTypeForHFSTypeCode(kGenericApplicationIcon);
}
else
{
NSNumber *isDirectory;
if (![url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL] || isDirectory == nil)
{
isDirectory = @(CFURLHasDirectoryPath((CFURLRef)url));
}
// Guess based on file type
if (isDirectory.boolValue)
{
if ([protocolClass isHomeDirectoryAtURL:url])
{
fileType = NSFileTypeForHFSTypeCode(kUserFolderIcon);
}
else
{
NSNumber *package;
if (![url getResourceValue:&package forKey:NSURLIsPackageKey error:NULL] || !package.boolValue)
{
return [NSImage imageNamed:NSImageNameFolder];
}
}
}
}
return [[NSWorkspace sharedWorkspace] iconForFileType:fileType];
}];
}
}
}
- (void)protocol:(CK2Protocol *)protocol didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend;
{
self.countOfBytesWritten = totalBytesSent;
self.countOfBytesExpectedToWrite = totalBytesExpectedToSend;
CK2FileManager *manager = self.fileManager;
[manager.delegateQueue addOperationWithBlock:^{
if (_progressBlock)
{
_progressBlock(bytesSent, totalBytesSent, totalBytesExpectedToSend);
}
else
{
id <CK2FileManagerDelegate> delegate = manager.delegate;
if ([delegate respondsToSelector:@selector(fileManager:operation:didWriteBodyData:totalBytesWritten:totalBytesExpectedToWrite:)])
{
[delegate fileManager:manager
operation:self
didWriteBodyData:bytesSent
totalBytesWritten:totalBytesSent
totalBytesExpectedToWrite:totalBytesExpectedToSend];
}
}
}];
}
- (NSInputStream *)protocol:(CK2Protocol *)protocol needNewBodyStream:(NSURLRequest *)request;
{
NSAssert(protocol == _protocol, @"Message received from unexpected protocol: %@ (should be %@)", protocol, _protocol);
NSInputStream *stream = [[NSInputStream alloc] initWithURL:_localURL];
return [stream autorelease];
}
#pragma mark NSCopying
- (id)copyWithZone:(NSZone *)zone;
{
// For easy stashing in dictionaries
return [self retain];
}
@end