/
WebDAVConnection.m
951 lines (850 loc) · 29.7 KB
/
WebDAVConnection.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
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
/*
Copyright (c) 2004-2006, Greg Hulands <ghulands@mac.com>
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
Neither the name of Greg Hulands nor the names of its contributors may be used to
endorse or promote products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#import "WebDAVConnection.h"
#import "AbstractConnection.h"
#import "DAVDirectoryContentsRequest.h"
#import "DAVCreateDirectoryRequest.h"
#import "DAVUploadFileRequest.h"
#import "DAVDeleteRequest.h"
#import "DAVResponse.h"
#import "DAVDirectoryContentsResponse.h"
#import "DAVCreateDirectoryResponse.h"
#import "DAVUploadFileResponse.h"
#import "DAVDeleteResponse.h"
#import "NSData+Connection.h"
#import "CKHTTPFileDownloadRequest.h"
#import "CKHTTPFileDownloadResponse.h"
#import "CKInternalTransferRecord.h"
#import "CKTransferRecord.h"
#import "NSString+Connection.h"
NSString *WebDAVErrorDomain = @"WebDAVErrorDomain";
@implementation WebDAVConnection
#pragma mark class methods
+ (void)load // registration of this class
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSDictionary *port = [NSDictionary dictionaryWithObjectsAndKeys:@"80", ACTypeValueKey, ACPortTypeKey, ACTypeKey, nil];
NSDictionary *url = [NSDictionary dictionaryWithObjectsAndKeys:@"webdav://", ACTypeValueKey, ACURLTypeKey, ACTypeKey, nil];
[AbstractConnection registerConnectionClass:[WebDAVConnection class] forTypes:[NSArray arrayWithObjects:port, url, nil]];
[pool release];
}
+ (NSString *)name
{
return @"WebDAV";
}
#pragma mark init methods
+ (id)connectionToHost:(NSString *)host
port:(NSString *)port
username:(NSString *)username
password:(NSString *)password
error:(NSError **)error
{
WebDAVConnection *c = [[self alloc] initWithHost:host
port:port
username:username
password:password
error:error];
return [c autorelease];
}
- (id)initWithHost:(NSString *)host
port:(NSString *)port
username:(NSString *)username
password:(NSString *)password
error:(NSError **)error
{
if (!username || [username length] == 0 || !password || [password length] == 0)
{
if (error)
{
NSError *err = [NSError errorWithDomain:WebDAVErrorDomain
code:ConnectionNoUsernameOrPassword
userInfo:[NSDictionary dictionaryWithObject:LocalizedStringInConnectionKitBundle(@"Username and Password are required for WebDAV connections", @"No username or password")
forKey:NSLocalizedDescriptionKey]];
*error = err;
}
[self release];
return nil;
}
if (!port || [port isEqualToString:@""])
{
port = @"80";
}
if (self = [super initWithHost:host
port:port
username:username
password:password
error:error])
{
}
return self;
}
- (void)dealloc
{
[myCurrentDirectory release];
[myDownloadHandle release];
[super dealloc];
}
+ (NSString *)urlScheme
{
return @"webdav";
}
#pragma mark -
#pragma mark Stream Overrides
- (void)processResponse:(CKHTTPResponse *)response
{
KTLog(ProtocolDomain, KTLogDebug, @"%@", response);
switch (GET_STATE)
{
case ConnectionAwaitingDirectoryContentsState:
{
DAVDirectoryContentsResponse *dav = (DAVDirectoryContentsResponse *)response;
NSString *err = nil;
switch ([dav code])
{
case 200:
case 207: //multi-status
{
NSArray *contents = [dav directoryContents];
[self cacheDirectory:[dav path] withContents:contents];
if (_flags.directoryContents)
{
NSString *dirPath = [dav path];
if ([dirPath hasSuffix:@"/"])
dirPath = [dirPath substringToIndex:[dirPath length] - 1];
[_forwarder connection:self didReceiveContents:contents ofDirectory:dirPath];
}
break;
}
case 404:
{
err = [NSString stringWithFormat: @"%@: %@", LocalizedStringInConnectionKitBundle(@"There is no WebDAV access to the directory", @"No WebDAV access to the specified path"), [dav path]];
break;
}
default:
{
err = LocalizedStringInConnectionKitBundle(@"Unknown Error Occurred", @"WebDAV Error");
}
}
if (err)
{
if (_flags.error)
{
NSMutableDictionary *ui = [NSMutableDictionary dictionaryWithObject:err forKey:NSLocalizedDescriptionKey];
[ui setObject:[dav className] forKey:@"DAVResponseClass"];
NSError *error = [NSError errorWithDomain:WebDAVErrorDomain
code:[dav code]
userInfo:ui];
[_forwarder connection:self didReceiveError:error];
}
}
[self setState:ConnectionIdleState];
break;
}
case ConnectionCreateDirectoryState:
{
DAVCreateDirectoryResponse *dav = (DAVCreateDirectoryResponse *)response;
NSString *err = nil;
NSMutableDictionary *ui = [NSMutableDictionary dictionary];
switch ([dav code])
{
case 201:
{
if (_flags.createDirectory)
{
[_forwarder connection:self didCreateDirectory:[dav directory]];
}
break;
}
case 403:
{
err = LocalizedStringInConnectionKitBundle(@"The server does not allow the creation of directories at the current location", @"WebDAV Create Directory Error");
//we fake the directory exists as this is usually the case if it is the root directory
[ui setObject:[NSNumber numberWithBool:YES] forKey:ConnectionDirectoryExistsKey];
break;
}
case 405:
{
if (!_flags.isRecursiveUploading)
{
err = LocalizedStringInConnectionKitBundle(@"The directory already exists", @"WebDAV Create Directory Error");
[ui setObject:[NSNumber numberWithBool:YES] forKey:ConnectionDirectoryExistsKey];
}
break;
}
case 409:
{
err = LocalizedStringInConnectionKitBundle(@"An intermediate directory does not exist and needs to be created before the current directory", @"WebDAV Create Directory Error");
break;
}
case 415:
{
err = LocalizedStringInConnectionKitBundle(@"The body of the request is not supported", @"WebDAV Create Directory Error");
break;
}
case 507:
{
err = LocalizedStringInConnectionKitBundle(@"Insufficient storage space available", @"WebDAV Create Directory Error");
break;
}
default:
{
err = LocalizedStringInConnectionKitBundle(@"An unknown error occured", @"WebDAV Create Directory Error");
break;
}
}
if (err)
{
if (_flags.error)
{
[ui setObject:err forKey:NSLocalizedDescriptionKey];
[ui setObject:[dav className] forKey:@"DAVResponseClass"];
[ui setObject:[[dav request] description] forKey:@"DAVRequest"];
[ui setObject:[(DAVCreateDirectoryRequest *)[dav request] path] forKey:@"directory"];
NSError *error = [NSError errorWithDomain:WebDAVErrorDomain
code:[dav code]
userInfo:ui];
[_forwarder connection:self didReceiveError:error];
}
}
[self setState:ConnectionIdleState];
break;
}
case ConnectionUploadingFileState:
{
DAVUploadFileResponse *dav = (DAVUploadFileResponse *)response;
bytesTransferred = 0;
bytesToTransfer = 0;
transferHeaderLength = 0;
switch ([dav code])
{
case 200:
case 201:
case 204:
{
if (_flags.uploadFinished)
{
[_forwarder connection:self
uploadDidFinish:[[self currentUpload] remotePath]];
}
if ([[self currentUpload] delegateRespondsToTransferDidFinish])
{
[[[self currentUpload] delegate] transferDidFinish:[[self currentUpload] delegate]];
}
break;
}
case 409:
{
if (_flags.error)
{
NSMutableDictionary *ui = [NSMutableDictionary dictionaryWithObject:LocalizedStringInConnectionKitBundle(@"Parent Folder does not exist", @"WebDAV Uploading Error")
forKey:NSLocalizedDescriptionKey];
[ui setObject:[dav className] forKey:@"DAVResponseClass"];
NSError *err = [NSError errorWithDomain:WebDAVErrorDomain
code:[dav code]
userInfo:ui];
[_forwarder connection:self didReceiveError:err];
}
}
break;
}
[self dequeueUpload];
[self setState:ConnectionIdleState];
break;
}
case ConnectionDeleteFileState:
{
DAVDeleteResponse *dav = (DAVDeleteResponse *)response;
switch ([dav code])
{
case 200:
case 201:
case 204:
{
if (_flags.deleteFile)
{
[_forwarder connection:self didDeleteFile:[self currentDeletion]];
}
break;
}
default:
{
if (_flags.error)
{
NSMutableDictionary *ui = [NSMutableDictionary dictionary];
[ui setObject:[NSString stringWithFormat:@"%@: %@", LocalizedStringInConnectionKitBundle(@"Failed to delete file", @"WebDAV File Deletion Error"), [self currentDeletion]] forKey:NSLocalizedDescriptionKey];
[ui setObject:[[dav request] description] forKey:@"DAVRequest"];
[ui setObject:[dav className] forKey:@"DAVResponseClass"];
NSError *err = [NSError errorWithDomain:WebDAVErrorDomain
code:[dav code]
userInfo:ui];
[_forwarder connection:self didReceiveError:err];
}
}
}
[self dequeueDeletion];
[self setState:ConnectionIdleState];
break;
}
case ConnectionDeleteDirectoryState:
{
DAVDeleteResponse *dav = (DAVDeleteResponse *)response;
switch ([dav code])
{
case 200:
case 201:
case 204:
{
if (_flags.deleteDirectory)
{
[_forwarder connection:self didDeleteDirectory:[self currentDeletion]];
}
break;
}
default:
{
if (_flags.error)
{
NSMutableDictionary *ui = [NSMutableDictionary dictionary];
[ui setObject:[NSString stringWithFormat:@"%@: %@", LocalizedStringInConnectionKitBundle(@"Failed to delete directory", @"WebDAV Directory Deletion Error"), [self currentDeletion]] forKey:NSLocalizedDescriptionKey];
[ui setObject:[[dav request] description] forKey:@"DAVRequest"];
[ui setObject:[dav className] forKey:@"DAVResponseClass"];
NSError *err = [NSError errorWithDomain:WebDAVErrorDomain
code:[dav code]
userInfo:ui];
[_forwarder connection:self didReceiveError:err];
}
}
}
[self dequeueDeletion];
[self setState:ConnectionIdleState];
break;
}
case ConnectionAwaitingRenameState:
{
if (_flags.rename)
[_forwarder connection:self didRename:[_fileRenames objectAtIndex:0] to:[_fileRenames objectAtIndex:1]];
[_fileRenames removeObjectAtIndex:0];
[_fileRenames removeObjectAtIndex:0];
[self setState:ConnectionIdleState];
break;
}
default: break;
}
}
- (void)initiatingNewRequest:(CKHTTPRequest *)req withPacket:(NSData *)packet
{
// if we are uploading or downloading set up the transfer sizes
if (GET_STATE == ConnectionUploadingFileState)
{
transferHeaderLength = [req headerLength];
bytesToTransfer = [packet length] - transferHeaderLength;
bytesTransferred = 0;
CKInternalTransferRecord *upload = [self currentUpload];
if (_flags.didBeginUpload)
{
[_forwarder connection:self
uploadDidBegin:[upload remotePath]];
}
if ([upload delegateRespondsToTransferDidBegin])
{
[[upload delegate] transferDidBegin:[upload userInfo]];
}
}
if (GET_STATE == ConnectionDownloadingFileState)
{
bytesToTransfer = 0;
bytesTransferred = 0;
CKInternalTransferRecord *download = [self currentDownload];
if (_flags.didBeginDownload)
{
[_forwarder connection:self
downloadDidBegin:[download remotePath]];
}
if ([download delegateRespondsToTransferDidBegin])
{
[[download delegate] transferDidBegin:[download userInfo]];
}
}
}
- (BOOL)processBufferWithNewData:(NSData *)data
{
if (GET_STATE == ConnectionDownloadingFileState)
{
CKInternalTransferRecord *download = [self currentDownload];
if (bytesToTransfer == 0)
{
NSDictionary *headers = [DAVResponse headersWithData:myResponseBuffer];
NSString *length = [headers objectForKey:@"Content-Length"];
if (length)
{
NSScanner *scanner = [NSScanner scannerWithString:length];
long long daBytes = 0;
[scanner scanLongLong:&daBytes];
bytesToTransfer = daBytes;
[(CKTransferRecord *)[download userInfo] setSize:daBytes];
NSFileManager *fm = [NSFileManager defaultManager];
BOOL isDir;
if ([fm fileExistsAtPath:[download localPath] isDirectory:&isDir] && !isDir)
{
[fm removeFileAtPath:[download localPath] handler:nil];
}
[fm createFileAtPath:[download localPath]
contents:nil
attributes:nil];
[myDownloadHandle release];
myDownloadHandle = [[NSFileHandle fileHandleForWritingAtPath:[download localPath]] retain];
// file data starts after the header
NSRange headerRange = [myResponseBuffer rangeOfData:[[NSString stringWithString:@"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *header = [[myResponseBuffer subdataWithRange:NSMakeRange(0, headerRange.location)] descriptionAsUTF8String];
if ([self transcript])
{
[self appendToTranscript:[[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@\n\n", header]
attributes:[AbstractConnection receivedAttributes]] autorelease]];
}
unsigned start = headerRange.location + headerRange.length;
unsigned len = [myResponseBuffer length] - start;
NSData *fileData = [myResponseBuffer subdataWithRange:NSMakeRange(start,len)];
[myDownloadHandle writeData:fileData];
[myResponseBuffer setLength:0];
bytesTransferred += [fileData length];
if (_flags.downloadProgressed)
{
[_forwarder connection:self download:[download remotePath] receivedDataOfLength:[fileData length]];
}
if ([download delegateRespondsToTransferTransferredData])
{
[[download delegate] transfer:[download userInfo] transferredDataOfLength:[fileData length]];
}
int percent = (100 * bytesTransferred) / bytesToTransfer;
if (_flags.downloadPercent)
{
[_forwarder connection:self download:[download remotePath] progressedTo:[NSNumber numberWithInt:percent]];
}
if ([download delegateRespondsToTransferProgressedTo])
{
[[download delegate] transfer:[download userInfo] progressedTo:[NSNumber numberWithInt:percent]];
}
lastPercent = percent;
}
}
else //add the data at the end of the file
{
[myDownloadHandle writeData:data];
[myResponseBuffer setLength:0];
bytesTransferred += [data length];
if (_flags.downloadProgressed)
{
[_forwarder connection:self download:[download remotePath] receivedDataOfLength:[data length]];
}
if ([download delegateRespondsToTransferTransferredData])
{
[[download delegate] transfer:[download userInfo] transferredDataOfLength:[data length]];
}
int percent = (100 * bytesTransferred) / bytesToTransfer;
if (percent != lastPercent)
{
if (_flags.downloadPercent)
{
[_forwarder connection:self download:[download remotePath] progressedTo:[NSNumber numberWithInt:percent]];
}
if ([download delegateRespondsToTransferProgressedTo])
{
[[download delegate] transfer:[download userInfo] progressedTo:[NSNumber numberWithInt:percent]];
}
lastPercent = percent;
}
}
//check for completion, if the file is really small, then the transfer might be complete on the first pass
//through this method, so check for completion everytime
//
if (bytesTransferred >= bytesToTransfer) //sometimes more data is received than required (i assume on small size file)
{
[myDownloadHandle closeFile];
[myDownloadHandle release];
myDownloadHandle = nil;
[download retain];
[self dequeueDownload];
if (_flags.downloadFinished)
{
[_forwarder connection:self downloadDidFinish:[download remotePath]];
}
if ([download delegateRespondsToTransferDidFinish])
{
[[download delegate] transferDidFinish:[download userInfo]];
}
[download release];
[myCurrentRequest release];
myCurrentRequest = nil;
[self setState:ConnectionIdleState];
}
return NO;
}
return YES;
}
- (void)closeStreams
{
bytesTransferred = 0;
[super closeStreams];
}
#pragma mark -
#pragma mark Abstract Connection Protocol
- (void)threadedConnect
{
[myCurrentDirectory autorelease];
myCurrentDirectory = [[NSString alloc] initWithString:@"/"];
[super threadedConnect];
if (_flags.didAuthenticate)
{
[_forwarder connection:self didAuthenticateToHost:[self host]];
}
}
- (void)davDidChangeToDirectory:(NSString *)dirPath
{
[myCurrentDirectory autorelease];
myCurrentDirectory = [dirPath copy];
if (_flags.changeDirectory)
{
[_forwarder connection:self didChangeToDirectory:dirPath];
}
[myCurrentRequest release];
myCurrentRequest = nil;
[self setState:ConnectionIdleState];
}
- (void)changeToDirectory:(NSString *)dirPath
{
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(davDidChangeToDirectory:)
target:self
arguments:[NSArray arrayWithObjects: dirPath, nil]];
ConnectionCommand *cmd = [ConnectionCommand command:inv
awaitState:ConnectionIdleState
sentState:ConnectionChangedDirectoryState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (NSString *)currentDirectory
{
return myCurrentDirectory;
}
- (NSString *)rootDirectory
{
return nil;
}
- (void)createDirectory:(NSString *)dirPath
{
NSAssert(dirPath && ![dirPath isEqualToString:@""], @"no directory specified");
DAVCreateDirectoryRequest *req = [DAVCreateDirectoryRequest createDirectoryWithPath:dirPath];
ConnectionCommand *cmd = [ConnectionCommand command:req
awaitState:ConnectionIdleState
sentState:ConnectionCreateDirectoryState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (void)createDirectory:(NSString *)dirPath permissions:(unsigned long)permissions
{
//we don't support setting permissions
[self createDirectory:dirPath];
}
- (void)setPermissions:(unsigned long)permissions forFile:(NSString *)path
{
NSAssert(path && ![path isEqualToString:@""], @"no file/path specified");
//no op
}
- (void)rename:(NSString *)fromPath to:(NSString *)toPath
{
NSAssert(fromPath && ![fromPath isEqualToString:@""], @"fromPath is nil!");
NSAssert(toPath && ![toPath isEqualToString:@""], @"toPath is nil!");
CKHTTPRequest *req = [CKHTTPRequest requestWithMethod:@"MOVE" uri:fromPath];
[req setHeader:toPath forKey:@"Destination"];
ConnectionCommand *cmd = [ConnectionCommand command:req
awaitState:ConnectionIdleState
sentState:ConnectionAwaitingRenameState
dependant:nil
userInfo:nil];
[self queueRename:fromPath];
[self queueRename:toPath];
[self queueCommand:cmd];
}
- (void)deleteFile:(NSString *)path
{
NSAssert(path && ![path isEqualToString:@""], @"path is nil!");
DAVDeleteRequest *req = [DAVDeleteRequest deleteFileWithPath:path];
ConnectionCommand *cmd = [ConnectionCommand command:req
awaitState:ConnectionIdleState
sentState:ConnectionDeleteFileState
dependant:nil
userInfo:nil];
[self queueDeletion:path];
[self queueCommand:cmd];
}
- (void)deleteDirectory:(NSString *)dirPath
{
NSAssert(dirPath && ![dirPath isEqualToString:@""], @"dirPath is nil!");
DAVDeleteRequest *req = [DAVDeleteRequest deleteFileWithPath:dirPath];
ConnectionCommand *cmd = [ConnectionCommand command:req
awaitState:ConnectionIdleState
sentState:ConnectionDeleteDirectoryState
dependant:nil
userInfo:nil];
[self queueDeletion:dirPath];
[self queueCommand:cmd];
}
- (void)uploadFile:(NSString *)localPath
{
[self uploadFile:localPath
toFile:[[myCurrentDirectory encodeLegally] stringByAppendingPathComponent:[localPath lastPathComponent]]];
}
- (void)uploadFile:(NSString *)localPath toFile:(NSString *)remotePath
{
[self uploadFile:localPath toFile:remotePath checkRemoteExistence:NO delegate:nil];
}
- (void)uploadFile:(NSString *)localPath toFile:(NSString *)remotePath checkRemoteExistence:(BOOL)flag
{
[self uploadFile:localPath toFile:remotePath checkRemoteExistence:flag delegate:nil];
}
- (CKTransferRecord *)uploadFile:(NSString *)localPath
toFile:(NSString *)remotePath
checkRemoteExistence:(BOOL)flag
delegate:(id)delegate
{
NSAssert(localPath && ![localPath isEqualToString:@""], @"localPath is nil!");
NSAssert(remotePath && ![remotePath isEqualToString:@""], @"remotePath is nil!");
NSDictionary *attribs = [[NSFileManager defaultManager] fileAttributesAtPath:localPath traverseLink:YES];
CKTransferRecord *transfer = [CKTransferRecord recordWithName:remotePath size:[[attribs objectForKey:NSFileSize] unsignedLongLongValue]];
CKInternalTransferRecord *record = [CKInternalTransferRecord recordWithLocal:localPath
data:nil
offset:0
remote:remotePath
delegate:delegate ? delegate : transfer
userInfo:transfer];
[transfer setUpload:YES];
[transfer setObject:localPath forKey:QueueUploadLocalFileKey];
[transfer setObject:remotePath forKey:QueueUploadRemoteFileKey];
DAVUploadFileRequest *req = [DAVUploadFileRequest uploadWithFile:localPath filename:remotePath];
ConnectionCommand *cmd = [ConnectionCommand command:req
awaitState:ConnectionIdleState
sentState:ConnectionUploadingFileState
dependant:nil
userInfo:nil];
[self queueUpload:record];
[self queueCommand:cmd];
return transfer;
}
- (void)resumeUploadFile:(NSString *)localPath fileOffset:(unsigned long long)offset
{
// we don't support upload resumption
[self uploadFile:localPath];
}
- (void)resumeUploadFile:(NSString *)localPath toFile:(NSString *)remotePath fileOffset:(unsigned long long)offset
{
[self uploadFile:localPath toFile:remotePath];
}
- (CKTransferRecord *)resumeUploadFile:(NSString *)localPath
toFile:(NSString *)remotePath
fileOffset:(unsigned long long)offset
delegate:(id)delegate
{
return [self uploadFile:localPath toFile:remotePath checkRemoteExistence:NO delegate:delegate];
}
- (void)uploadFromData:(NSData *)data toFile:(NSString *)remotePath
{
[self uploadFromData:data toFile:remotePath checkRemoteExistence:NO delegate:nil];
}
- (void)uploadFromData:(NSData *)data toFile:(NSString *)remotePath checkRemoteExistence:(BOOL)flag
{
[self uploadFromData:data toFile:remotePath checkRemoteExistence:flag delegate:nil];
}
- (CKTransferRecord *)uploadFromData:(NSData *)data
toFile:(NSString *)remotePath
checkRemoteExistence:(BOOL)flag
delegate:(id)delegate
{
NSAssert(data, @"no data"); // data should not be nil, but it shoud be OK to have zero length!
NSAssert(remotePath && ![remotePath isEqualToString:@""], @"remotePath is nil!");
CKTransferRecord *transfer = [CKTransferRecord recordWithName:remotePath size:[data length]];
CKInternalTransferRecord *record = [CKInternalTransferRecord recordWithLocal:nil
data:data
offset:0
remote:remotePath
delegate:delegate ? delegate : transfer
userInfo:transfer];
[transfer setUpload:YES];
[transfer setObject:remotePath forKey:QueueUploadRemoteFileKey];
DAVUploadFileRequest *req = [DAVUploadFileRequest uploadWithData:data filename:remotePath];
ConnectionCommand *cmd = [ConnectionCommand command:req
awaitState:ConnectionIdleState
sentState:ConnectionUploadingFileState
dependant:nil
userInfo:nil];
[self queueUpload:record];
[self queueCommand:cmd];
return transfer;
}
- (void)resumeUploadFromData:(NSData *)data toFile:(NSString *)remotePath fileOffset:(unsigned long long)offset
{
// we don't support upload resumption
[self uploadFromData:data toFile:remotePath];
}
- (void)downloadFile:(NSString *)remotePath toDirectory:(NSString *)dirPath overwrite:(BOOL)flag
{
[self downloadFile:remotePath toDirectory:dirPath overwrite:YES delegate:nil];
}
- (CKTransferRecord *)downloadFile:(NSString *)remotePath
toDirectory:(NSString *)dirPath
overwrite:(BOOL)flag
delegate:(id)delegate
{
NSAssert(remotePath && ![remotePath isEqualToString:@""], @"no remotePath");
NSAssert(dirPath && ![dirPath isEqualToString:@""], @"no dirPath");
NSString *localPath = [dirPath stringByAppendingPathComponent:[remotePath lastPathComponent]];
CKTransferRecord *transfer = [CKTransferRecord recordWithName:remotePath size:0];
CKInternalTransferRecord *record = [CKInternalTransferRecord recordWithLocal:localPath
data:nil
offset:0
remote:remotePath
delegate:delegate ? delegate : transfer
userInfo:transfer];
[transfer setObject:remotePath forKey:QueueDownloadRemoteFileKey];
[transfer setObject:localPath forKey:QueueDownloadDestinationFileKey];
[transfer setUpload:NO];
CKHTTPFileDownloadRequest *r = [CKHTTPFileDownloadRequest downloadRemotePath:remotePath to:dirPath];
ConnectionCommand *cmd = [ConnectionCommand command:r
awaitState:ConnectionIdleState
sentState:ConnectionDownloadingFileState
dependant:nil
userInfo:nil];
[self queueDownload:record];
[self queueCommand:cmd];
return transfer;
}
- (void)resumeDownloadFile:(NSString *)remotePath toDirectory:(NSString *)dirPath fileOffset:(unsigned long long)offset
{
[self downloadFile:remotePath toDirectory:dirPath overwrite:YES];
}
- (CKTransferRecord *)resumeDownloadFile:(NSString *)remotePath
toDirectory:(NSString *)dirPath
fileOffset:(unsigned long long)offset
delegate:(id)delegate
{
return [self downloadFile:remotePath toDirectory:dirPath overwrite:YES delegate:delegate];
}
- (void)davDirectoryContents:(NSString *)dir
{
CKHTTPRequest *r = [DAVDirectoryContentsRequest directoryContentsForPath:dir != nil ? dir : myCurrentDirectory];
[myCurrentRequest autorelease];
myCurrentRequest = [r retain];
[self sendCommand:r];
}
- (void)directoryContents
{
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(davDirectoryContents:)
target:self
arguments:[NSArray array]];
ConnectionCommand *cmd = [ConnectionCommand command:inv
awaitState:ConnectionIdleState
sentState:ConnectionAwaitingDirectoryContentsState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (void)contentsOfDirectory:(NSString *)dirPath
{
NSAssert(dirPath && ![dirPath isEqualToString:@""], @"no dirPath");
NSArray *cachedContents = [self cachedContentsWithDirectory:dirPath];
if (cachedContents)
{
[_forwarder connection:self didReceiveContents:cachedContents ofDirectory:dirPath];
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"CKDoesNotRefreshCachedListings"])
{
return;
}
}
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(davDirectoryContents:)
target:self
arguments:[NSArray arrayWithObject:dirPath]];
ConnectionCommand *cmd = [ConnectionCommand command:inv
awaitState:ConnectionIdleState
sentState:ConnectionAwaitingDirectoryContentsState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
#pragma mark -
#pragma mark Stream Overrides
- (void)stream:(id<OutputStream>)stream sentBytesOfLength:(unsigned)length
{
[super stream:stream sentBytesOfLength:length]; // call http
if (length == 0) return;
if (GET_STATE == ConnectionUploadingFileState)
{
if (transferHeaderLength > 0)
{
if (length <= transferHeaderLength)
{
transferHeaderLength -= length;
}
else
{
length -= transferHeaderLength;
transferHeaderLength = 0;
bytesTransferred += length;
}
}
else
{
bytesTransferred += length;
}
CKInternalTransferRecord *upload = [self currentUpload];
if (bytesToTransfer > 0)
{
int percent = (100 * bytesTransferred) / bytesToTransfer;
if (percent != lastPercent)
{
if (_flags.uploadPercent)
{
[_forwarder connection:self
upload:[[self currentUpload] remotePath]
progressedTo:[NSNumber numberWithInt:percent]];
}
if ([upload delegateRespondsToTransferProgressedTo])
{
[[upload delegate] transfer:[upload userInfo] progressedTo:[NSNumber numberWithInt:percent]];
}
lastPercent = percent;
}
}
if (_flags.uploadProgressed)
{
[_forwarder connection:self
upload:[[self currentUpload] remotePath]
sentDataOfLength:length];
}
if ([upload delegateRespondsToTransferTransferredData])
{
[[upload delegate] transfer:[upload userInfo] transferredDataOfLength:length];
}
}
}
@end