/
CKTransferController.m
1190 lines (1014 loc) · 33.1 KB
/
CKTransferController.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
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 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 "CKTransferController.h"
#import "CKTransferProgressCell.h"
#import "KTLog.h"
#import "NSObject+Connection.h"
#import "NSString+Connection.h"
#import "CKTransferRecord.h"
#import "CKFileConnection.h"
#import "RunLoopForwarder.h"
#import "CKFTPConnection.h"
#import "CKSFTPConnection.h"
#import "InterThreadMessaging.h"
NSString *ControllerDomain = @"Controller";
NSString *CKTransferControllerDomain = @"CKTransferControllerDomain";
@interface CKTransferController (Private)
- (CKTransferRecord *)recordWithPath:(NSString *)path root:(CKTransferRecord *)root;
- (CKTransferRecord *)rootRecordWithPath:(NSString *)path;
@end
@implementation CKTransferController
- (id)init
{
if ((self = [super init]))
{
myTransfers = [[NSMutableArray alloc] initWithCapacity:8];
myRootedTransfers = [[NSMutableArray alloc] initWithCapacity:8];
myPathsToVerify = [[NSMutableSet alloc] init];
[NSBundle loadNibNamed:@"CKTransferController" owner:self];
myForwarder = [[RunLoopForwarder alloc] init];
}
return self;
}
- (void)dealloc
{
[myTransfers release];
[myForwarder setDelegate:nil];
[myForwarder release];
[myRootPath release];
[myRootedTransfers release];
[myPathsToVerify release];
[self forceDisconnectAll]; // won't send delegate message
[super dealloc];
}
- (void)awakeFromNib
{
CKTransferProgressCell *cell = [[CKTransferProgressCell alloc] init];
[[oFiles tableColumnWithIdentifier:@"progress"] setDataCell:cell];
[cell release];
[oFiles setIndentationMarkerFollowsCell:YES];
[oFiles setDataSource:self];
[oFiles setDelegate:self];
[oTitle setStringValue:@""];
[oStatus setStringValue:@""];
[oProgress setIndeterminate:YES];
[oProgress setUsesThreadedAnimation:YES];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(progressChanged:)
name:CKTransferRecordProgressChangedNotification
object:nil];
}
#pragma mark -
#pragma mark Operations
- (void)createDirectory:(NSString *)directory
{
KTLog(ControllerDomain, KTLogDebug, @"Queuing create remote directory: %@", directory);
[[self connection] createDirectory:directory];
}
- (void)createDirectory:(NSString *)directory permissions:(unsigned long)permissions
{
KTLog(ControllerDomain, KTLogDebug, @"Queuing create remote directory: %@ (%lo)", directory, permissions);
[[self connection] createDirectory:directory permissions:permissions];
}
- (void)uploadFile:(NSString *)localPath toFile:(NSString *)remotePath
{
KTLog(ControllerDomain, KTLogDebug, @"Queuing upload of file: %@ to %@", localPath, remotePath);
CKTransferRecord *root = [self rootRecordWithPath:[remotePath stringByDeletingLastPathComponent]];
CKTransferRecord *upload = [[self connection] uploadFile:localPath toFile:remotePath checkRemoteExistence:NO delegate:nil];
[upload setName:[remotePath lastPathComponent]];
[[self recordWithPath:[remotePath stringByDeletingLastPathComponent] root:root] addContent:upload];
[myPathsToVerify addObject:remotePath];
}
- (void)uploadFromData:(NSData *)data toFile:(NSString *)remotePath
{
KTLog(ControllerDomain, KTLogDebug, @"Queuing upload of data to %@", remotePath);
CKTransferRecord *root = [self rootRecordWithPath:[remotePath stringByDeletingLastPathComponent]];
CKTransferRecord *upload = [[self connection] uploadFromData:data toFile:remotePath checkRemoteExistence:NO delegate:nil];
[upload setName:[remotePath lastPathComponent]];
[[self recordWithPath:[remotePath stringByDeletingLastPathComponent] root:root] addContent:upload];
[myPathsToVerify addObject:remotePath];
}
- (void)setPermissions:(unsigned long)permissions forFile:(NSString *)remotePath
{
KTLog(ControllerDomain, KTLogDebug, @"Queuing permissions %lo to %@", permissions, remotePath);
NSAssert(remotePath && ![remotePath isEqualToString:@""], @"no file/path specified");
[[self connection] setPermissions:permissions forFile:remotePath];
}
- (void)deleteFile:(NSString *)remotePath
{
KTLog(ControllerDomain, KTLogDebug, @"Queuing delete of %@", remotePath);
[[self connection] deleteFile:remotePath];
}
- (void)recursivelyUpload:(NSString *)localPath to:(NSString *)remotePath
{
CKTransferRecord *root = [self rootRecordWithPath:[remotePath stringByDeletingLastPathComponent]];
CKTransferRecord *upload = [[self connection] recursivelyUpload:localPath to:remotePath];
[upload setName:[remotePath lastPathComponent]];
[[self recordWithPath:[remotePath stringByDeletingLastPathComponent] root:root] addContent:upload];
[myPathsToVerify addObject:remotePath];
}
#pragma mark -
#pragma mark UI
- (void)setTitle:(NSString *)title
{
[[self window] setTitle:title];
[oTitle performSelectorOnMainThread:@selector(setStringValue:)
withObject:title
waitUntilDone:YES];
}
- (void)setIcon:(NSImage *)icon
{
[oIcon setImage:icon];
}
- (void)mainThreadSetStatus:(NSString *)message
{
[oStatus setStringValue:message];
}
- (void)setStatusMessage:(NSString *)message
{
[self performSelectorOnMainThread:@selector(mainThreadSetStatus:)
withObject:message
waitUntilDone:NO];
}
- (void)setProgress:(double)progress
{
if (progress > 0)
{
[oProgress setIndeterminate:NO];
[oProgress setDoubleValue:progress];
}
else
{
[oProgress setIndeterminate:YES];
[oProgress startAnimation:self];
}
}
- (void)setFinished
{
[self setProgress:[oProgress maxValue]];
}
- (void)setDefaultButtonTitle:(NSString *)title
{
[oDefaultButton setTitle:title];
if (!title || [title isEqualToString:@""])
{
[oDefaultButton setHidden:YES];
}
else
{
[oDefaultButton setImagePosition:NSImageRight];
[oDefaultButton setKeyEquivalent:@"\r"];
[oDefaultButton setHidden:NO];
}
}
- (void)setAlternateButtonTitle:(NSString *)title
{
[oAlternateButton setTitle:title];
if (!title || [title isEqualToString:@""])
{
[oAlternateButton setHidden:YES];
}
else
{
[oAlternateButton setHidden:NO];
}
}
- (void)setUploadingStatusPrefix:(NSString *)prefix
{
if (prefix != myUploadingPrefix)
{
[myUploadingPrefix autorelease];
myUploadingPrefix = [prefix copy];
}
}
#pragma mark -
#pragma mark Control Flow
- (void)kickoff:(id)unused
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[NSThread prepareForConnectionInterThreadMessages]; //make sure we have a runloop on this thread
myPhase = CKKickoffPhase;
myFlags.stopTransfer = NO;
BOOL contentGenerationSuccessful = YES; // will be set to NO if provider had error or abort
if (myFlags.delegateProvidesContent)
{
// don't use the forwarder as we want to be called on the current thread
@try {
myPhase = CKContentGenerationPhase;
contentGenerationSuccessful = [myDelegate transferControllerNeedsContent:self];
}
@catch (NSException *ex) {
KTLog(ControllerDomain, KTLogDebug, @"Exception caught in kickoff: %@", ex);
}
}
myPhase = CKFinishedContentGenerationPhase;
// adjust UI on main thread
[self performSelectorOnMainThread:@selector(finishedKickOff:) withObject:nil waitUntilDone:NO];
if (myFlags.stopTransfer || CKFatalErrorStatus == myReturnStatus)
{
[self forceDisconnectAll];
// Tell client that it should finish
if (myFlags.delegateFinishedContentGeneration)
{
[myForwarder transferControllerFinishedContentGeneration:self completed:NO];
}
if (myFlags.delegateDidFinish)
{
[myForwarder transferControllerDidFinish:self returnCode:myReturnStatus];
}
[self forceDisconnectAll];
}
else
{
if (myFlags.delegateFinishedContentGeneration)
{
[myForwarder transferControllerFinishedContentGeneration:self completed:contentGenerationSuccessful];
}
myReturnStatus = CKSuccessStatus; // We have all the content, so we should be OK to set success now.
[[self connection] disconnect];
// let the runloop run incase anyone is using it... like FileConnection.
//
// No longer needed, greg says... Need to test to make sure
// [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantPast]];
}
if (myFlags.useThread)
{
KTLog(ControllerDomain, KTLogDebug, @"kickoff: thread finishing up");
}
[pool release];
}
- (void)finishedKickOff:(id)sender
{
if (myReturnStatus != CKFatalErrorStatus)
{
[oShowHideFilesTitle setHidden:NO];
[oShowFiles setHidden:NO];
}
[oProgress setMinValue:0];
[oProgress setMaxValue:1.0];
[oProgress setDoubleValue:0];
[oProgress setIndeterminate:NO];
KTLog(ControllerDomain, KTLogDebug, @"Set progress bar to determinate");
}
- (void)setupForDisplay
{
myPhase = CKInitialPhase;
myReturnStatus = CKUnknownStatus; // assume an error if we didn't get far, like immediate disconnect.
myConnectionStatus = CKNotConnectedStatus;
KTLog(ControllerDomain, KTLogDebug, @"Beginning modal sheet");
[myTransfers removeAllObjects];
[myPathsToVerify removeAllObjects];
[myRootedTransfers removeAllObjects];
[oFiles reloadData];
//make sure sheet is collapsed
if ([oShowFiles state] != NSOffState)
{
[oShowFiles setState:NSOffState];
[self showHideFiles:oShowFiles];
}
[oShowHideFilesTitle setHidden:YES];
[oShowFiles setHidden:YES];
[oStatus setStringValue:@""];
[oProgress setIndeterminate:YES];
[oProgress setUsesThreadedAnimation:YES];
}
- (void)finishSetupForDisplay
{
[oProgress startAnimation:self];
[[self connection] setName:@"main uploader"];
[[self connection] connect];
if (myFlags.waitForConnection)
{
// Run some runloops for a while, waiting for a change in state. Is this a good way to do it?
// I can't figure out what the return value of runMode:beforeDate: is and how to use it.
// Should the give-up date be an absolute time like it is now, or n seconds relative to each
// run loop invocation?
NSDate *giveUp = [NSDate dateWithTimeIntervalSinceNow:5.0];
while (CKNotConnectedStatus == myConnectionStatus)
{
// let the runloop run incase anyone is using it... like FileConnection.
(void) [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:giveUp];
NSDate *now = [NSDate date];
if (NSOrderedDescending == [now compare:giveUp])
{
break; // give up, keep going, hopefully we are OK if we missed a message.
}
}
}
if (CKDisconnectedStatus != myConnectionStatus) // don't proceed if we already had an error connecting
{
// temporarily turn off verification for sftp until I can sort out the double connection problem
if ([[self connection] isKindOfClass:[CKSFTPConnection class]]) myFlags.verifyTransfers = NO;
/// temporarily turn off FTP verification too just for simplification
if ([[self connection] isKindOfClass:[CKFTPConnection class]]) myFlags.verifyTransfers = NO;
if (!myVerificationConnection && myFlags.verifyTransfers)
{
id <CKConnection> connection = [self connection];
myVerificationConnection = [[[connection class] alloc] initWithRequest:[connection request]];
[myVerificationConnection setDelegate:self];
[myVerificationConnection setName:@"verification"];
[myVerificationConnection connect];
}
if (myFlags.useThread)
{
[NSThread detachNewThreadSelector:@selector(kickoff:) toTarget:self withObject:nil];
}
else
{
[self kickoff:nil];
}
}
}
- (void)runModal
{
[self setupForDisplay];
[NSApp runModalForWindow:[self window]];
[self finishSetupForDisplay];
}
- (void)beginSheetModalForWindow:(NSWindow *)window
{
[self setupForDisplay];
[NSApp beginSheet:[self window]
modalForWindow:window
modalDelegate:nil
didEndSelector:nil
contextInfo:nil];
[self finishSetupForDisplay];
}
- (void) postABogusEvent
{
// Post an event to help the runloop waiting for a connection
NSEvent *theEvent = [NSEvent otherEventWithType:NSApplicationDefined
location:NSZeroPoint
modifierFlags:0
timestamp:0.0
windowNumber:0
context:[NSApp context]
subtype:0
data1:0
data2:0];
[NSApp postEvent:theEvent atStart:YES];
}
#pragma mark -
#pragma mark Actions
- (IBAction)defaultButtonPressed:(id)sender
{
if (myFlags.delegateHandlesDefaultButton)
{
if (![myDelegate transferControllerDefaultButtonAction:self])
return;
}
// Treat as stop/done? Or will it be different when we are done?
[self stopTransfer];
[[NSApplication sharedApplication] stopModal];
[[NSApplication sharedApplication] endSheet:[self window]];
[[self window] orderOut:self];
[myTransfers removeAllObjects];
[myPathsToVerify removeAllObjects];
[myRootedTransfers removeAllObjects];
[oFiles reloadData];
}
- (IBAction)alternateButtonPressed:(id)sender
{
if (myFlags.delegateHandlesAlternateButton)
{
if (![myDelegate transferControllerAlternateButtonAction:self])
return;
}
NSBeep(); // second button really isn't defined without delegate
}
static NSSize openedSize = { 452, 489 };
static NSSize closedSize = { 452, 152 };
- (IBAction)showHideFiles:(id)sender
{
NSRect r = [[self window] frame];
BOOL showing = [sender state] == NSOnState;
NSSize newSize = showing ? openedSize : closedSize;
NSString *name = showing ? LocalizedStringInConnectionKitBundle(@"Hide Files", @"transfer controller") : LocalizedStringInConnectionKitBundle(@"Show Files", @"transfer controller");
r.origin.y -= newSize.height - r.size.height;
r.size = newSize;
[oFiles reloadData];
if (showing) // initially expand the first level
{
NSEnumerator *e = [myRootedTransfers objectEnumerator];
CKTransferRecord *cur;
while ((cur = [e nextObject]))
{
[oFiles expandItem:cur expandChildren:NO];
}
}
[oShowHideFilesTitle setStringValue:name];
[[self window] setFrame:r display:YES animate:YES];
}
- (IBAction)cancelPassword:(id)sender
{
// Is this just not implemented yet?
}
- (IBAction)connectPassword:(id)sender
{
// Is this just not implemented yet?
}
#pragma mark -
#pragma mark Accessors
// set a connection. Generally called when this class maintains its collection.
// If delegate provides collection, then we do not deal with retaining.
- (void)setConnection:(id <CKConnection>)connection
{
if ([myConnection delegate] == self) [myConnection setDelegate:nil];
if (!myFlags.delegateProvidesConnection)
{
[myConnection autorelease];
myConnection = [connection retain];
}
else // weak reference
{
myConnection = connection;
}
}
- (id <CKConnection>)connection
{
if (!myConnection && myFlags.delegateProvidesConnection)
{
// delegate returns a connection; we do not retain it.
id <CKConnection> con = [myDelegate transferControllerNeedsConnection:self createIfNeeded:YES];
[con setDelegate:self];
return con;
}
return myConnection;
}
- (id <CKConnection>)connectionIfAleadyCreated
{
if (!myConnection && myFlags.delegateProvidesConnection)
{
id <CKConnection> con = [myDelegate transferControllerNeedsConnection:self createIfNeeded:NO];
return con;
}
return myConnection;
}
- (void)setRootPath:(NSString *)path
{
if (myRootPath != path)
{
[myRootPath autorelease];
myRootPath = [path copy];
}
}
- (void)setContentGeneratedInSeparateThread:(BOOL)flag
{
myFlags.useThread = flag;
}
- (BOOL)contentGeneratedInSeparateThread
{
return myFlags.useThread;
}
- (void)setWaitForConnection:(BOOL)flag
{
myFlags.waitForConnection = flag;
}
- (BOOL)waitForConnection
{
return myFlags.waitForConnection;
}
- (void)setVerifyTransfers:(BOOL)flag
{
myFlags.verifyTransfers = flag;
}
- (BOOL)verifyTransfers
{
return myFlags.verifyTransfers;
}
- (void)setDelegate:(id)delegate
{
myDelegate = delegate;
[myForwarder setDelegate:myDelegate];
myFlags.delegateProvidesConnection = [delegate respondsToSelector:@selector(transferControllerNeedsConnection:createIfNeeded:)];
myFlags.delegateProvidesContent = [delegate respondsToSelector:@selector(transferControllerNeedsContent:)];
myFlags.delegateFinishedContentGeneration = [delegate respondsToSelector:@selector(transferControllerFinishedContentGeneration:completed:)];
myFlags.delegateHandlesDefaultButton = [delegate respondsToSelector:@selector(transferControllerDefaultButtonAction:)];
myFlags.delegateHandlesAlternateButton = [delegate respondsToSelector:@selector(transferControllerAlternateButtonAction:)];
myFlags.delegateDidFinish = [delegate respondsToSelector:@selector(transferControllerDidFinish:returnCode:)];
}
- (id)delegate
{
return myDelegate;
}
- (NSError *)fatalError
{
return myFatalError;
}
- (void)setFatalError:(NSError *)aFatalError
{
[aFatalError retain];
[myFatalError release];
myFatalError = aFatalError;
}
- (NSArray *)transfers
{
return myTransfers;
}
#pragma mark -
#pragma mark Notification
- (void)progressChanged:(NSNotification *)n
{
if ([oShowFiles state] == NSOnState)
{
[oFiles performSelectorOnMainThread:@selector(reloadData)
withObject:nil
waitUntilDone:NO];
}
unsigned long long totalBytes = 0;
unsigned long long totalTransferred = 0;
NSEnumerator *e = [myTransfers objectEnumerator];
CKTransferRecord *cur;
while ((cur = [e nextObject]))
{
totalBytes += [cur size];
totalTransferred += [cur transferred];
}
double prog = ((double)totalTransferred * 1.0) / ((double)totalBytes * 1.0);
[oProgress setDoubleValue:prog];
if (myFlags.verifyTransfers)
{
CKTransferRecord *enclosedFolder = [(CKTransferRecord *)[n object] parent];
if ([enclosedFolder progress] == 100 && nil != [enclosedFolder error])
{
KTLog(ControllerDomain, KTLogDebug, @"Verifying directory %@", [enclosedFolder path]);
[myVerificationConnection contentsOfDirectory:[enclosedFolder path]];
}
}
}
#pragma mark -
#pragma mark Misc
- (void)mainThreadTableReload:(id)unused
{
[oFiles reloadData];
}
- (void)requestStopTransfer;
{
myFlags.stopTransfer = YES;
myReturnStatus = CKAbortStatus;
}
- (void) stopTransfer
{
[self requestStopTransfer];
[self forceDisconnectAll];
if (myFlags.delegateDidFinish)
{
[myForwarder transferControllerDidFinish:self returnCode:myReturnStatus];
}
}
// Return YES if there were problems, collecting stats into the supplied variables
- (BOOL)problemsTransferringCountingErrors:(int *)outErrors successes:(int *)outSuccesses;
{
NSEnumerator *e = [myTransfers objectEnumerator];
CKTransferRecord *cur;
while ((cur = [e nextObject]))
{
(void) [cur problemsTransferringCountingErrors:outErrors successes:outSuccesses];
}
return (*outErrors > 0);
}
- (BOOL)hadErrorsTransferring
{
BOOL ret = NO;
NSEnumerator *e = [myTransfers objectEnumerator];
CKTransferRecord *cur;
while ((cur = [e nextObject]))
{
if ([cur hasError])
{
ret = YES;
break;
}
}
return ret;
}
- (CKTransferRecord *)recursiveRootRecordWithPath:(NSString *)path root:(CKTransferRecord *)root
{
NSString *first = [path firstPathComponent];
if ([[root name] isEqualToString:first])
{
NSEnumerator *e = [[root contents] objectEnumerator];
CKTransferRecord *cur;
path = [path stringByDeletingFirstPathComponent];
if ([path isEqualToString:@"/"])
return root;
while ((cur = [e nextObject]))
{
CKTransferRecord *child = [self recursiveRootRecordWithPath:path root:cur];
if (child)
return root;
}
// if we get here it doesn't exist so create it
cur = [CKTransferRecord recordWithName:[path firstPathComponent] size:0];
[root addContent:cur];
[self recursiveRootRecordWithPath:path root:cur];
return root;
}
return nil;
}
- (CKTransferRecord *)rootRecordWithPath:(NSString *)path
{
NSEnumerator *e = [myTransfers objectEnumerator];
CKTransferRecord *cur;
while ((cur = [e nextObject]))
{
if ([[cur name] isEqualToString:[path firstPathComponent]])
{
// walk the tree to make sure all folders are created
return [self recursiveRootRecordWithPath:path root:cur];
}
}
if (!cur)
{
cur = [CKTransferRecord recordWithName:[path firstPathComponent] size:0];
path = [path stringByDeletingFirstPathComponent];
CKTransferRecord *thisNode, *subNode = cur;
while ((![path isEqualToString:@"/"]))
{
thisNode = [CKTransferRecord recordWithName:[path firstPathComponent] size:0];
path = [path stringByDeletingFirstPathComponent];
[subNode addContent:thisNode];
subNode = thisNode;
}
[self willChangeValueForKey:@"transfers"];
[myTransfers addObject:cur];
[self didChangeValueForKey:@"transfers"];
/// TJT: changed conditional here: we have to not process 0 length strings, too!
if ( (nil != myRootPath) && ([myRootPath length] > 0) )
{
CKTransferRecord *record = [self recordWithPath:myRootPath root:cur];
if ( nil == record )
{
/// TJT: this seems to the source of the infamous "attempt to add nil object" exception
/// TJT: myRootPath is a 0 length string
NSLog(@"error: recordWithPath:root: returned nil myRootPath=%@ cur=%@", myRootPath, cur);
}
else
{
[myRootedTransfers addObject:record];
}
}
else
{
[myRootedTransfers addObject:cur];
}
[self performSelectorOnMainThread:@selector(mainThreadTableReload:) withObject:nil waitUntilDone:NO];
}
return cur;
}
- (CKTransferRecord *)recursiveRecordWithPath:(NSString *)path root:(CKTransferRecord *)root
{
/// TJT: passing in a path of / is going to return nil
/// so let's not do that, returning nil is a bad idea
if ([path isEqualToString:@"/"])
return root;
NSString *first = [path firstPathComponent];
if ([[root name] isEqualToString:first])
{
CKTransferRecord *child = nil;
NSEnumerator *e = [[root contents] objectEnumerator];
CKTransferRecord *cur;
path = [path stringByDeletingFirstPathComponent];
if ([path isEqualToString:@"/"])
return root;
while ((cur = [e nextObject]))
{
child = [self recursiveRecordWithPath:path root:cur];
if (child)
return child;
}
}
/// TJT: returning nil here seems to be a really bad idea
/// (we get "attempt to add nil object" exception downstream)
return nil;
}
- (CKTransferRecord *)recordWithPath:(NSString *)path root:(CKTransferRecord *)root
{
return [self recursiveRecordWithPath:path root:root];
}
- (CKTransferRecord *)recordWithPath:(NSString *)path
{
NSEnumerator *e = [myTransfers objectEnumerator];
CKTransferRecord *cur;
while ((cur = [e nextObject]))
{
CKTransferRecord *child = [self recordWithPath:path root:cur];
if (child)
{
return child;
}
}
return nil;
}
- (void)forceDisconnectAll // possibly called from backgrond thread, can't use myForwarder
{
// don't use [self connection] because we don't want to create a connection if we've already cleared it
if ([myConnection delegate] == self) [myConnection setDelegate:nil];
[[self connectionIfAleadyCreated] setDelegate:nil];
[[self connectionIfAleadyCreated] forceDisconnect]; // what if we have multiple connections provided by the delegate?
[myVerificationConnection setDelegate:nil];
[myVerificationConnection forceDisconnect];
// Release connections
[self setConnection:nil]; // will only deallocate if it's not a weak ref
[myVerificationConnection release]; myVerificationConnection = nil;
}
#pragma mark -
#pragma mark Outline View Data Source
- (int)outlineView:(NSOutlineView *)outlineView numberOfChildrenOfItem:(id)item
{
if (item == nil)
{
return [myRootedTransfers count];
}
return [[item contents] count];
}
- (id)outlineView:(NSOutlineView *)outlineView child:(int)index ofItem:(id)item
{
if (item == nil)
{
return [myRootedTransfers objectAtIndex:index];
}
return [[item contents] objectAtIndex:index];
}
- (BOOL)outlineView:(NSOutlineView *)outlineView isItemExpandable:(id)item
{
return [item isDirectory];
}
- (id)outlineView:(NSOutlineView *)outlineView objectValueForTableColumn:(NSTableColumn *)tableColumn byItem:(id)item
{
NSString *ident = [tableColumn identifier];
if ([ident isEqualToString:@"progress"])
{
return [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:[item progress]], @"progress", [item name], @"name", nil];
}
else if ([ident isEqualToString:@"file"])
{
return [item name];
}
else if ([ident isEqualToString:@"speed"])
{
return [NSString formattedSpeed:[item speed]];
}
return nil;
}
#pragma mark -
#pragma mark Outline View Delegate Methods
- (NSString *)outlineView:(NSOutlineView *)ov
toolTipForCell:(NSCell *)cell
rect:(NSRectPointer)rect
tableColumn:(NSTableColumn *)tc
item:(id)item // CKTransferRecord
mouseLocation:(NSPoint)mouseLocation
{
if ([item error])
{
return [[[item error] userInfo] objectForKey:NSLocalizedDescriptionKey];
}
else if (nil != item)
{
return [NSString formattedFileSize:(double)[((CKTransferRecord *)item) size]];
}
return nil;
}
#pragma mark -
#pragma mark Connection Delegate Methods
- (void)connection:(id <CKConnection>)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
{
// For now, we're considering authentication to be the delegate's responsibility. Continuing without credentials
// should generally end up causing the connection to fail.
// If anyone needs it, we can probably provide a CKTransferController delegate method to request authentication.
[[challenge sender] continueWithoutCredentialForAuthenticationChallenge:challenge];
}
- (void)connection:(id <CKConnection>)con didConnectToHost:(NSString *)host
{
if (con == [self connection])
{
KTLog(ControllerDomain, KTLogDebug, @"Did Connect to Host");
myConnectionStatus = CKConnectedStatus;
[self postABogusEvent];
[self setStatusMessage:[NSString stringWithFormat:LocalizedStringInConnectionKitBundle(@"Connected to %@", @"transfer controller"), host]];
}
}
- (void)connection:(id <CKConnection>)con didDisconnectFromHost:(NSString *)host
{
if (con == [self connection])
{
myConnectionStatus = CKDisconnectedStatus;
[self postABogusEvent];
}
if (myFlags.verifyTransfers)
{
if (con == [self connection])
{
// we know if the uploader has disconnected, that the final verification dir would have been queued
[myVerificationConnection disconnect];
return;
}
}
else
{
if (con != [self connection])
{
return;
}
}
[self setStatusMessage:[NSString stringWithFormat:LocalizedStringInConnectionKitBundle(@"Disconnected from %@", @"transfer controller"), host]];
if (myFlags.delegateDidFinish)
{
myPhase = CKDonePhase;
// Before sending the callback, check to see if we actually uploaded most of the files. If not,
// then consider it a fatal error.
if (CKSuccessStatus == myReturnStatus)
{
int countErrorUploads = 0;