/
CKFileConnection.m
902 lines (733 loc) · 32.5 KB
/
CKFileConnection.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
/*
Copyright (c) 2004-2006 Karelia Software. 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 Karelia Software 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 "CKFileConnection.h"
#import "RunLoopForwarder.h"
#import "InterThreadMessaging.h"
#import "CKConnectionThreadManager.h"
#import "CKInternalTransferRecord.h"
#import "CKTransferRecord.h"
#import "CKAbstractQueueConnection.h"
#import "NSFileManager+Connection.h"
#import "CKConnectionProtocol.h"
NSString *CKFileConnectionErrorDomain = @"FileConnectionErrorDomain";
enum { CONNECT = 4000, COMMAND, ABORT, CANCEL_ALL, DISCONNECT, FORCE_DISCONNECT, KILL_THREAD }; // port messages
@interface CKFileConnection (Private)
- (void)processInvocations;
- (void)fcUploadFile:(NSString *)f toFile:(NSString *)t;
- (void)sendPortMessage:(int)message;
- (void)fcUpload:(CKInternalTransferRecord *)upload
checkRemoteExistence:(NSNumber *)check;
@end
@implementation CKFileConnection
+ (void)load // registration of this class
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[[CKConnectionRegistry sharedConnectionRegistry] registerClass:self forName:[self name] URLScheme:@"file"];
[pool release];
}
#pragma mark -
#pragma mark Accessors
- (int)currentOperation
{
return myCurrentOperation;
}
- (void)setCurrentOperation:(int)aCurrentOperation
{
myCurrentOperation = aCurrentOperation;
}
#pragma mark -
#pragma mark Initialization
/*! Simpler initializer since there's none of this information needed
*/
+ (CKFileConnection *)connection
{
CKFileConnection *c = [[CKFileConnection alloc] init];
return [c autorelease];
}
+ (NSString *)name
{
return @"File";
}
+ (NSArray *)URLSchemes { return [NSArray arrayWithObject:@"file"]; }
- (id)initWithRequest:(CKConnectionRequest *)request
{
if (self = [super initWithRequest:request])
{
myCurrentDirectory = [[NSString alloc] initWithString:NSHomeDirectory()];
}
return self;
}
- (id)init
{
return [self initWithRequest:[CKConnectionRequest requestWithURL:[NSURL fileURLWithPath:NSHomeDirectory()]]];
}
- (void)dealloc
{
[myCurrentDirectory release];
[super dealloc];
}
- (void)connect
{
if (!_isConnecting && ![self isConnected])
{
[[self client] appendFormat:LocalizedStringInConnectionKitBundle(@"Starting connection for %@", @"file transcript") toTranscript:CKTranscriptSent, [[[self request] URL] absoluteString]];
[super connect];
}
}
- (void)sendCommand:(id)command
{
[command invoke];
}
- (void)threadedConnect
{
[super threadedConnect];
myFileManager = [[NSFileManager alloc] init];
[[self client] appendString:LocalizedStringInConnectionKitBundle(@"Connected to File System", @"file transcript") toTranscript:CKTranscriptSent];
[self setState:CKConnectionIdleState];
}
- (void)threadedAbort
{
NSString *remotePath = [self currentUpload] ? [[self currentUpload] remotePath] : [[self currentDownload] remotePath];
[[self client] connectionDidCancelTransfer:remotePath];
[self processInvocations];
}
- (void)threadedCancelAll
{
[self threadedAbort];
}
#pragma mark -
#pragma mark Main Methods
- (void)fcChangeToDirectory:(NSString *)aDirectory
{
[self setCurrentOperation:kChangeToDirectory];
if ([myFileManager changeCurrentDirectoryPath:aDirectory])
{
[[self client] connectionDidChangeToDirectory:aDirectory error:nil];
}
[myCurrentDirectory autorelease];
myCurrentDirectory = [aDirectory copy];
[self setState:CKConnectionIdleState];
}
- (void)changeToDirectory:(NSString *)aDirectory // an absolute directory
{
NSAssert(aDirectory && ![aDirectory isEqualToString:@""], @"no directory specified");
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(fcChangeToDirectory:)
target:self
arguments:[NSArray arrayWithObjects:aDirectory, nil]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionChangedDirectoryState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (NSString *)currentDirectory
{
return myCurrentDirectory;
}
- (void)createDirectory:(NSString *)dirPath
{
[self createDirectory:dirPath permissions:0755];
}
- (void)fcCreateDirectory:(NSString *)aName permissions:(NSNumber *)perms
{
[self setCurrentOperation:kCreateDirectory];
unsigned long aPermissions = [perms unsignedLongValue];
[[self client] appendFormat:LocalizedStringInConnectionKitBundle(@"Create Directory %@ (%lo)", @"file transcript")
toTranscript:CKTranscriptSent,
aName,
aPermissions];
NSDictionary *fmDictionary = nil;
if (0 != aPermissions)
{
fmDictionary = [NSDictionary dictionaryWithObject:[NSNumber numberWithLong:aPermissions] forKey:NSFilePosixPermissions];
}
NSError *error = nil;
if (![myFileManager createDirectoryAtPath:aName withIntermediateDirectories:NO attributes:fmDictionary error:NULL])
{
BOOL exists;
[myFileManager fileExistsAtPath:aName isDirectory:&exists];
NSDictionary *ui = [NSDictionary dictionaryWithObjectsAndKeys:
LocalizedStringInConnectionKitBundle(@"Could not create directory", @"FileConnection create directory error"), NSLocalizedDescriptionKey,
aName, NSFilePathErrorKey,
[NSNumber numberWithBool:exists], ConnectionDirectoryExistsKey,
aName, ConnectionDirectoryExistsFilenameKey, nil];
error = [NSError errorWithDomain:CKFileConnectionErrorDomain code:[self currentOperation] userInfo:ui];
}
[[self client] connectionDidCreateDirectory:aName error:error];
[self setState:CKConnectionIdleState];
}
- (void)createDirectory:(NSString *)dirPath permissions:(unsigned long)aPermissions
{
NSAssert(dirPath && ![dirPath isEqualToString:@""], @"no directory specified");
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(fcCreateDirectory:permissions:)
target:self
arguments:[NSArray arrayWithObjects:dirPath, [NSNumber numberWithUnsignedLong:aPermissions], nil]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionCreateDirectoryState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (void)fcSetPermissions:(NSNumber *)perms forFile:(NSString *)path
{
[self setCurrentOperation:kSetPermissions];
NSMutableDictionary *attribs = [[myFileManager attributesOfItemAtPath:path error:NULL] mutableCopy];
[attribs setObject:perms forKey:NSFilePosixPermissions];
NSError *error = nil;
if (![myFileManager setAttributes:attribs ofItemAtPath:path error:NULL])
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
LocalizedStringInConnectionKitBundle(@"Could not change file permissions", @"FileConnection set permissions error"), NSLocalizedDescriptionKey,
path, NSFilePathErrorKey, nil];
error = [NSError errorWithDomain:CKFileConnectionErrorDomain code:[self currentOperation] userInfo:userInfo];
}
[[self client] connectionDidSetPermissionsForFile:path error:error];
[attribs release];
[self setState:CKConnectionIdleState];
}
- (void)setPermissions:(unsigned long)permissions forFile:(NSString *)path
{
NSAssert(path && ![path isEqualToString:@""], @"no file/path specified");
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(fcSetPermissions:forFile:)
target:self
arguments:[NSArray arrayWithObjects:[NSNumber numberWithUnsignedLong:permissions], path, nil]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionSettingPermissionsState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (void)fcRename:(NSString *)fromPath to:(NSString *)toPath
{
[self setCurrentOperation:kRename];
[[self client] appendFormat:LocalizedStringInConnectionKitBundle(@"Renaming %@ to %@", @"file transcript")
toTranscript:CKTranscriptSent, fromPath, toPath];
NSError *error = nil;
if (![myFileManager moveItemAtPath:fromPath toPath:toPath error:NULL])
{
NSString *localizedDescription = LocalizedStringInConnectionKitBundle(@"Failed to rename file.", @"Failed to rename file.");
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:localizedDescription, NSLocalizedDescriptionKey, nil];
error = [NSError errorWithDomain:CKFileConnectionErrorDomain code:[self currentOperation] userInfo:userInfo];
}
[[self client] connectionDidRename:fromPath to:toPath error:error];
[self setState:CKConnectionIdleState];
}
- (void)rename:(NSString *)fromPath to:(NSString *)toPath
{
NSAssert(fromPath && ![fromPath isEqualToString:@""], @"fromPath is nil!");
NSAssert(toPath && ![toPath isEqualToString:@""], @"toPath is nil!");
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(fcRename:to:)
target:self
arguments:[NSArray arrayWithObjects:fromPath, toPath, nil]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionAwaitingRenameState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (void)fcDeleteFile:(NSString *)path
{
[self setCurrentOperation:kDeleteFile];
[[self client] appendFormat:LocalizedStringInConnectionKitBundle(@"Deleting File %@", @"file transcript")
toTranscript:CKTranscriptSent, path];
NSError *error = nil;
if (![myFileManager removeItemAtPath:path error:NULL])
{
NSString *localizedDescription = [NSString stringWithFormat:LocalizedStringInConnectionKitBundle(@"Failed to delete file: %@", @"error for deleting a file"), path];
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
localizedDescription, NSLocalizedDescriptionKey,
path, NSFilePathErrorKey, nil];
error = [NSError errorWithDomain:CKFileConnectionErrorDomain code:kDeleteFile userInfo:userInfo];
}
[[self client] connectionDidDeleteFile:path error:error];
[self setState:CKConnectionIdleState];
}
- (void)deleteFile:(NSString *)path
{
NSAssert(path && ![path isEqualToString:@""], @"path is nil!");
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(fcDeleteFile:)
target:self
arguments:[NSArray arrayWithObject:path]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionDeleteFileState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (void)fcDeleteDirectory:(NSString *)dirPath
{
[self setCurrentOperation:kDeleteDirectory];
NSError *error = nil;
if (![myFileManager removeItemAtPath:dirPath error:NULL])
{
NSString *localizedDescription = [NSString stringWithFormat:LocalizedStringInConnectionKitBundle(@"Failed to delete directory: %@", @"error for deleting a directory"), dirPath];
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
localizedDescription, NSLocalizedDescriptionKey,
dirPath, NSFilePathErrorKey, nil];
error = [NSError errorWithDomain:CKFileConnectionErrorDomain code:kDeleteFile userInfo:userInfo];
}
[[self client] connectionDidDeleteDirectory:dirPath error:error];
[self setState:CKConnectionIdleState];
}
- (void)deleteDirectory:(NSString *)dirPath
{
NSAssert(dirPath && ![dirPath isEqualToString:@""], @"dirPath is nil!");
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(fcDeleteDirectory:)
target:self
arguments:[NSArray arrayWithObject:dirPath]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionDeleteDirectoryState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (void)recursivelyDeleteDirectory:(NSString *)path
{
[self deleteDirectory:path];
}
- (void)fcUpload:(CKInternalTransferRecord *)upload checkRemoteExistence:(NSNumber *)check
{
NSFileManager *fm = myFileManager;
BOOL flag = [check boolValue];
[[self client] appendFormat:LocalizedStringInConnectionKitBundle(@"Copying %@ to %@", @"file transcript")
toTranscript:CKTranscriptSent, [upload localPath], [upload remotePath]];
if (![fm fileExistsAtPath:[upload localPath]])
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
LocalizedStringInConnectionKitBundle(@"File does not exist", @"FileConnection error"), NSLocalizedDescriptionKey,
[upload localPath], NSFilePathErrorKey, nil];
NSError *error = [NSError errorWithDomain:CKFileConnectionErrorDomain code:-1 userInfo:userInfo];
[upload retain];
[self dequeueUpload];
// send finished
[[self client] uploadDidFinish:[upload remotePath] error:error];
if ([upload delegateRespondsToTransferDidFinish])
[[upload delegate] transferDidFinish:[upload userInfo] error:error];
[upload release];
[self setState:CKConnectionIdleState];
return;
}
if (flag)
{
if ([fm fileExistsAtPath:[upload remotePath]])
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
LocalizedStringInConnectionKitBundle(@"File Already Exists", @"FileConnection error"), NSLocalizedDescriptionKey,
[upload remotePath], NSFilePathErrorKey, nil];
NSError *error = [NSError errorWithDomain:CKFileConnectionErrorDomain code:kFileExists userInfo:userInfo];
[upload retain];
[self dequeueUpload];
// send finished
[[self client] uploadDidFinish:[upload remotePath] error:error];
if ([upload delegateRespondsToTransferDidFinish])
[[upload delegate] transferDidFinish:[upload userInfo] error:error];
[upload release];
[self setState:CKConnectionIdleState];
return;
}
}
[fm removeItemAtPath:[upload remotePath] error:NULL];
if ([upload delegateRespondsToTransferDidBegin])
[[upload delegate] transferDidBegin:[upload userInfo]];
[[self client] uploadDidBegin:[upload remotePath]];
FILE *from = fopen([[upload localPath] fileSystemRepresentation], "r"); // Must use -fileSystemRepresentation to handle non-ASCII paths
FILE *to = fopen([[upload remotePath] fileSystemRepresentation], "a");
// I put these assertions back in; it's better to get an assertion failure than a crash!
NSAssert(from, @"path from cannot be found");
NSAssert(to, @"path to cannot be found");
int fno = fileno(from), tno = fileno(to);
char bytes[8096];
int len;
unsigned long long size = [[[fm attributesOfItemAtPath:[upload localPath] error:NULL] objectForKey:NSFileSize] unsignedLongLongValue];
unsigned long long sizeDecrementing = size;
clearerr(from);
// feof() doesn;t seem to work for some reason so we'll just count the byte size of the file
while (sizeDecrementing > 0)
{
len = read(fno, bytes, 8096);
len = write(tno, bytes, len);
sizeDecrementing -= len;
}
fclose(from);
fclose(to);
//need to send the amount of bytes transferred.
[[self client] upload:[upload remotePath] didSendDataOfLength:size];
if ([upload delegateRespondsToTransferTransferredData])
[[upload delegate] transfer:[upload userInfo] transferredDataOfLength:size];
// send 100%
if ([upload delegateRespondsToTransferProgressedTo])
[[upload delegate] transfer:[upload userInfo] progressedTo:[NSNumber numberWithInt:100]];
[[self client] upload:[upload remotePath] didProgressToPercent:[NSNumber numberWithInt:100]];
[upload retain];
[self dequeueUpload];
// send finished
[[self client] uploadDidFinish:[upload remotePath] error:nil];
if ([upload delegateRespondsToTransferDidFinish])
[[upload delegate] transferDidFinish:[upload userInfo] error:nil];
[upload release];
[self setState:CKConnectionIdleState];
}
- (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 = [myFileManager attributesOfItemAtPath:localPath error:NULL];
CKTransferRecord *rec = [CKTransferRecord recordWithName:remotePath size:[[attribs objectForKey:NSFileSize] unsignedLongLongValue]];
CKInternalTransferRecord *upload = [CKInternalTransferRecord recordWithLocal:localPath
data:nil
offset:0
remote:remotePath
delegate:(delegate) ? delegate : rec
userInfo:rec];
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(fcUpload:checkRemoteExistence:)
target:self
arguments:[NSArray arrayWithObjects:upload, [NSNumber numberWithBool:flag], nil]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionUploadingFileState
dependant:nil
userInfo:nil];
[self queueUpload:upload];
[self queueCommand:cmd];
return rec;
}
- (void)fcUploadData:(CKInternalTransferRecord *)upload checkRemoteExistence:(NSNumber *)check
{
BOOL flag = [check boolValue];
[[self client] appendFormat:LocalizedStringInConnectionKitBundle(@"Writing data to %@", @"file transcript")
toTranscript:CKTranscriptSent, [upload remotePath]];
if (flag)
{
if ([myFileManager fileExistsAtPath:[upload remotePath]])
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
LocalizedStringInConnectionKitBundle(@"File Already Exists", @"FileConnection error"), NSLocalizedDescriptionKey,
[upload remotePath], NSFilePathErrorKey, nil];
NSError *error = [NSError errorWithDomain:CKFileConnectionErrorDomain code:kFileExists userInfo:userInfo];
// send finished
[[self client] uploadDidFinish:[upload remotePath] error:error];
if ([upload delegateRespondsToTransferDidFinish])
[[upload delegate] transferDidFinish:[upload userInfo] error:error];
return;
}
}
(void) [myFileManager removeItemAtPath:[upload remotePath] error:NULL];
BOOL success = [myFileManager createFileAtPath:[upload remotePath]
contents:[upload data]
attributes:nil];
if ([upload delegateRespondsToTransferDidBegin])
[[upload delegate] transferDidBegin:[upload userInfo]];
[[self client] uploadDidBegin:[upload remotePath]];
//need to send the amount of bytes transferred.
unsigned long long size = [[[myFileManager attributesOfItemAtPath:[upload remotePath] error:NULL] objectForKey:NSFileSize] unsignedLongLongValue];
[[self client] upload:[upload remotePath] didSendDataOfLength:size];
if ([upload delegateRespondsToTransferTransferredData])
[[upload delegate] transfer:[upload userInfo] transferredDataOfLength:size];
// send 100%
if ([upload delegateRespondsToTransferProgressedTo])
[[upload delegate] transfer:[upload userInfo] progressedTo:[NSNumber numberWithInt:100]];
[[self client] upload:[upload remotePath] didProgressToPercent:[NSNumber numberWithInt:100]];
NSError *error = nil;
if (!success)
{
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
LocalizedStringInConnectionKitBundle(@"Failed to upload data", @"FileConnection copy data error"), NSLocalizedDescriptionKey,
[upload remotePath], NSFilePathErrorKey,nil];
error = [NSError errorWithDomain:CKConnectionErrorDomain code:ConnectionErrorUploading userInfo:userInfo];
}
// send finished
[[self client] uploadDidFinish:[upload remotePath] error:error];
if ([upload delegateRespondsToTransferDidFinish])
[[upload delegate] transferDidFinish:[upload userInfo] error:error];
[self setState:CKConnectionIdleState];
}
- (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 *rec = [CKTransferRecord recordWithName:remotePath
size:[data length]];
CKInternalTransferRecord *upload = [CKInternalTransferRecord recordWithLocal:nil
data:data
offset:0
remote:remotePath
delegate:delegate ? delegate : rec
userInfo:rec];
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(fcUploadData:checkRemoteExistence:)
target:self
arguments:[NSArray arrayWithObjects:upload, [NSNumber numberWithBool:flag], nil]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionUploadingFileState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
return rec;
}
/*! Copy the file to the given directory
*/
- (void)fcDownloadFile:(NSString *)remotePath toDirectory:(NSString *)dirPath overwrite:(NSNumber *)aFlag
{
//BOOL flag = [aFlag boolValue];
[self setCurrentOperation:kDownloadFile];
CKInternalTransferRecord *download = [self currentDownload];
NSString *name = [remotePath lastPathComponent];
[[self client] downloadDidBegin:remotePath];
if ([download delegateRespondsToTransferDidBegin])
[[download delegate] transferDidBegin:[download userInfo]];
if ([[remotePath componentsSeparatedByString:@"/"] count] == 1)
{
remotePath = [NSString stringWithFormat:@"%@/%@", [self currentDirectory], remotePath];
}
NSString *destinationPath = [NSString stringWithFormat:@"%@/%@", dirPath, name];
NSString *tempPath = nil;
if ([aFlag boolValue])
{
//we were asked to overwrite, we'll do it atomically because we are nice:-)
//
if ([myFileManager fileExistsAtPath: destinationPath])
{
tempPath = [dirPath stringByAppendingPathComponent: [[NSProcessInfo processInfo] globallyUniqueString]];
if (![myFileManager moveItemAtPath:destinationPath
toPath:tempPath
error:NULL])
{
//we failed to move it, we'll fail to copy...
//
tempPath = nil;
}
}
}
BOOL success = [myFileManager copyItemAtPath:remotePath toPath: destinationPath error:NULL];
if (success)
{
//we can delete the old file if one was present
//
if (tempPath)
[myFileManager removeItemAtPath:tempPath error:NULL];
//need to send the amount of bytes transferred.
NSFileHandle *fh = [NSFileHandle fileHandleForReadingAtPath:remotePath];
[[self client] download:remotePath didReceiveDataOfLength:[fh seekToEndOfFile]];
[[self client] download:remotePath didProgressToPercent:[NSNumber numberWithInt:100]];
if ([download delegateRespondsToTransferProgressedTo])
[[download delegate] transfer:[download userInfo] progressedTo:[NSNumber numberWithInt:100]];
[download retain];
[self dequeueDownload];
[[self client] downloadDidFinish:remotePath error:nil];
if ([download delegateRespondsToTransferDidFinish])
[[download delegate] transferDidFinish:[download userInfo] error:nil];
[download release];
}
else // no handler, so we send error message 'manually'
{
if (tempPath)
{
//restore the file, hopefully this will work:-)
[myFileManager moveItemAtPath:tempPath toPath:destinationPath error:NULL];
}
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
LocalizedStringInConnectionKitBundle(@"Unable to store data in file", @"FileConnection failed to copy file"), NSLocalizedDescriptionKey,
remotePath, NSFilePathErrorKey, nil];
NSError *error = [NSError errorWithDomain:CKFileConnectionErrorDomain code:[self currentOperation] userInfo:userInfo];
[download retain];
[self dequeueDownload];
[[self client] downloadDidFinish:remotePath error:error];
if ([download delegateRespondsToTransferDidFinish])
[[download delegate] transferDidFinish:[download userInfo] error:error];
[download release];
}
[self setState:CKConnectionIdleState];
}
- (void)downloadFile:(NSString *)remotePath toDirectory:(NSString *)dirPath overwrite:(BOOL)flag
{
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(fcDownloadFile:toDirectory:overwrite:)
target:self
arguments:[NSArray arrayWithObjects:remotePath, dirPath, [NSNumber numberWithBool:flag], nil]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionDownloadingFileState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (CKTransferRecord *)downloadFile:(NSString *)remotePath
toDirectory:(NSString *)dirPath
overwrite:(BOOL)flag
delegate:(id)delegate
{
CKTransferRecord *record = [CKTransferRecord recordWithName:remotePath size:0];
CKTransferRecord *download = [CKInternalTransferRecord recordWithLocal:[dirPath stringByAppendingPathComponent:[remotePath lastPathComponent]]
data:nil
offset:0
remote:remotePath
delegate:(delegate) ? delegate : record
userInfo:record];
[self queueDownload:download];
[self downloadFile:remotePath toDirectory:dirPath overwrite:flag];
return record;
}
- (void)directoryContents
{
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(fcDirectoryContents)
target:self
arguments:[NSArray array]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionAwaitingDirectoryContentsState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (void)fcContentsOfDirectory:(NSString *)dirPath
{
[self setCurrentOperation:kDirectoryContents];
NSArray *array = [myFileManager contentsOfDirectoryAtPath:dirPath error:NULL];
NSMutableArray *packaged = [NSMutableArray arrayWithCapacity:[array count]];
NSEnumerator *e = [array objectEnumerator];
NSString *cur;
while (cur = [e nextObject]) {
NSString *file = [NSString stringWithFormat:@"%@/%@", dirPath, cur];
NSMutableDictionary *attribs = [NSMutableDictionary dictionaryWithDictionary:[myFileManager attributesOfItemAtPath:file
error:NULL]];
[attribs setObject:cur forKey:cxFilenameKey];
if ([[attribs objectForKey:NSFileType] isEqualToString:NSFileTypeSymbolicLink]) {
NSString *target = [file stringByResolvingSymlinksInPath];
BOOL isDir;
[myFileManager fileExistsAtPath:target isDirectory:&isDir];
if (isDir && ![target hasSuffix:@"/"])
{
target = [target stringByAppendingString:@"/"];
}
[attribs setObject:target forKey:cxSymbolicLinkTargetKey];
}
[packaged addObject:attribs];
}
[[self client] connectionDidReceiveContents:packaged ofDirectory:dirPath error:nil];
[self setState:CKConnectionIdleState];
}
- (void)fcDirectoryContents
{
[self fcContentsOfDirectory:[self currentDirectory]];
}
- (void)contentsOfDirectory:(NSString *)dirPath
{
NSAssert(dirPath && ![dirPath isEqualToString:@""], @"no dirPath");
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(fcContentsOfDirectory:)
target:self
arguments:[NSArray arrayWithObject:dirPath]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionAwaitingDirectoryContentsState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (void)fcCheckExistenceOfPath:(NSString *)path
{
[self setCurrentOperation:kDirectoryContents];
BOOL fileExists = [myFileManager fileExistsAtPath: path];
[[self client] connectionDidCheckExistenceOfPath:path pathExists:fileExists error:nil];
}
- (void)checkExistenceOfPath:(NSString *)path
{
NSAssert(path && ![path isEqualToString:@""], @"path not specified");
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(fcCheckExistenceOfPath:)
target:self
arguments:[NSArray arrayWithObject:path]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionCheckingFileExistenceState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
}
- (void)threadedRecursivelyDownload:(NSDictionary *)ui
{
CKTransferRecord *root = [ui objectForKey:@"record"];
NSString *remotePath = [ui objectForKey:@"remote"];
NSString *localPath = [ui objectForKey:@"local"];
BOOL flag = [[ui objectForKey:@"overwrite"] boolValue];
NSEnumerator *e = [[myFileManager subpathsAtPath:remotePath] objectEnumerator];
NSString *cur;
BOOL isDir;
while ((cur = [e nextObject]))
{
NSString *r = [remotePath stringByAppendingPathComponent:cur];
NSString *l = [localPath stringByAppendingPathComponent:cur];
if ([myFileManager fileExistsAtPath:r isDirectory:&isDir] && isDir)
{
[myFileManager createDirectoryAtPath:r withIntermediateDirectories:YES attributes:nil error:NULL];
}
else
{
CKTransferRecord *rec = [self downloadFile:r toDirectory:[l stringByDeletingLastPathComponent] overwrite:flag delegate:nil];
[CKTransferRecord mergeTextPathRecord:rec withRoot:root];
}
}
[self setState:CKConnectionIdleState];
}
- (CKTransferRecord *)recursivelyDownload:(NSString *)remotePath
to:(NSString *)localPath
overwrite:(BOOL)flag
{
CKTransferRecord *root = [CKTransferRecord rootRecordWithPath:remotePath];
NSDictionary *ui = [NSDictionary dictionaryWithObjectsAndKeys:root, @"record", remotePath, @"remote", localPath, @"local", [NSNumber numberWithBool:flag], @"overwrite", nil];
NSInvocation *inv = [NSInvocation invocationWithSelector:@selector(threadedRecursivelyDownload:)
target:self
arguments:[NSArray arrayWithObject:ui]];
CKConnectionCommand *cmd = [CKConnectionCommand command:inv
awaitState:CKConnectionIdleState
sentState:CKConnectionDownloadingFileState
dependant:nil
userInfo:nil];
[self queueCommand:cmd];
return root;
}
#pragma mark -
#pragma mark Delegate Methods
- (BOOL)fileManager:(NSFileManager *)manager shouldProceedAfterError:(NSDictionary *)errorInfo
{
NSString *path = [errorInfo objectForKey:@"Path"];
NSString *toPath = [errorInfo objectForKey:@"ToPath"];
NSString *errorString = [errorInfo objectForKey:@"Error"];
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
errorString, NSLocalizedDescriptionKey,
path, NSFilePathErrorKey,
toPath, @"ToPath", nil]; // "ToPath" might be nil ... that's OK, it's at the end of the list
NSError *error = [NSError errorWithDomain:CKFileConnectionErrorDomain code:[self currentOperation] userInfo:userInfo];
[[self client] connectionDidReceiveError:error];
return NO;
}
@end