source: trunk/macosx/Torrent.m @ 7484

Last change on this file since 7484 was 7484, checked in by livings124, 12 years ago

(Mac client) #1029: When removing local data only remove data from the torrent

  • Property svn:keywords set to Date Rev Author Id
File size: 64.7 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 7484 2008-12-24 01:55:33Z livings124 $
3 *
4 * Copyright (c) 2006-2008 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#import "Torrent.h"
26#import "GroupsController.h"
27#import "FileListNode.h"
28#import "NSApplicationAdditions.h"
29#import "NSStringAdditions.h"
30#import "utils.h" //tr_httpIsValidURL
31
32@interface Torrent (Private)
33
34- (id) initWithHash: (NSString *) hashString path: (NSString *) path torrentStruct: (tr_torrent *) torrentStruct lib: (tr_session *) lib
35        publicTorrent: (NSNumber *) publicTorrent
36        downloadFolder: (NSString *) downloadFolder
37        useIncompleteFolder: (NSNumber *) useIncompleteFolder incompleteFolder: (NSString *) incompleteFolder
38        ratioSetting: (NSNumber *) ratioSetting ratioLimit: (NSNumber *) ratioLimit
39        waitToStart: (NSNumber *) waitToStart
40        orderValue: (NSNumber *) orderValue groupValue: (NSNumber *) groupValue addedTrackers: (NSNumber *) addedTrackers;
41
42- (BOOL) shouldUseIncompleteFolderForName: (NSString *) name;
43- (void) updateDownloadFolder;
44
45- (void) createFileList;
46- (void) insertPath: (NSMutableArray *) components forParent: (FileListNode *) parent fileSize: (uint64_t) size
47    index: (NSInteger) index flatList: (NSMutableArray *) flatFileList;
48
49- (void) completenessChange: (NSNumber *) status;
50
51- (void) quickPause;
52- (void) endQuickPause;
53
54- (NSString *) etaString: (NSInteger) eta;
55
56- (void) updateAllTrackers: (NSMutableArray *) trackers;
57
58+ (void) trashFile: (NSString *) path;
59
60- (void) setTimeMachineExclude: (BOOL) exclude forPath: (NSString *) path;
61
62@end
63
64void completenessChangeCallback(tr_torrent * torrent, tr_completeness status, void * torrentData)
65{
66    [(Torrent *)torrentData performSelectorOnMainThread: @selector(completenessChange:)
67                withObject: [[NSNumber alloc] initWithInt: status] waitUntilDone: NO];
68}
69
70int trashDataFile(const char * filename)
71{
72    [Torrent trashFile: [NSString stringWithUTF8String: filename]];
73    return 0;
74}
75
76@implementation Torrent
77
78- (id) initWithPath: (NSString *) path location: (NSString *) location deleteTorrentFile: (torrentFileState) torrentDelete
79        lib: (tr_session *) lib
80{
81    self = [self initWithHash: nil path: path torrentStruct: NULL lib: lib
82            publicTorrent: torrentDelete != TORRENT_FILE_DEFAULT ? [NSNumber numberWithBool: torrentDelete == TORRENT_FILE_SAVE] : nil
83            downloadFolder: location
84            useIncompleteFolder: nil incompleteFolder: nil
85            ratioSetting: nil ratioLimit: nil
86            waitToStart: nil orderValue: nil groupValue: nil addedTrackers: nil];
87   
88    if (self)
89    {
90        //if the public and private torrent files are the same, then there is no public torrent
91        if ([[self torrentLocation] isEqualToString: path])
92        {
93            fPublicTorrent = NO;
94            [fPublicTorrentLocation release];
95            fPublicTorrentLocation = nil;
96        }
97        else if (!fPublicTorrent)
98            [Torrent trashFile: path];
99        else;
100    }
101    return self;
102}
103
104- (id) initWithTorrentStruct: (tr_torrent *) torrentStruct location: (NSString *) location lib: (tr_session *) lib
105{
106    self = [self initWithHash: nil path: nil torrentStruct: torrentStruct lib: lib
107            publicTorrent: [NSNumber numberWithBool: NO]
108            downloadFolder: location
109            useIncompleteFolder: nil incompleteFolder: nil
110            ratioSetting: nil ratioLimit: nil
111            waitToStart: nil orderValue: nil groupValue: nil addedTrackers: nil];
112   
113    return self;
114}
115
116- (id) initWithHistory: (NSDictionary *) history lib: (tr_session *) lib
117{
118    self = [self initWithHash: [history objectForKey: @"TorrentHash"]
119                path: [history objectForKey: @"TorrentPath"] torrentStruct: NULL lib: lib
120                publicTorrent: [history objectForKey: @"PublicCopy"]
121                downloadFolder: [history objectForKey: @"DownloadFolder"]
122                useIncompleteFolder: [history objectForKey: @"UseIncompleteFolder"]
123                incompleteFolder: [history objectForKey: @"IncompleteFolder"]
124                ratioSetting: [history objectForKey: @"RatioSetting"]
125                ratioLimit: [history objectForKey: @"RatioLimit"]
126                waitToStart: [history objectForKey: @"WaitToStart"]
127                orderValue: [history objectForKey: @"OrderValue"]
128                groupValue: [history objectForKey: @"GroupValue"]
129                addedTrackers: [history objectForKey: @"AddedTrackers"]];
130   
131    if (self)
132    {
133        //start transfer
134        NSNumber * active;
135        if ((active = [history objectForKey: @"Active"]) && [active boolValue])
136        {
137            fStat = tr_torrentStat(fHandle);
138            [self startTransfer];
139        }
140       
141        //upgrading from versions < 1.30: get old added, activity, and done dates
142        NSDate * date;
143        if ((date = [history objectForKey: @"Date"]))
144            tr_torrentSetAddedDate(fHandle, [date timeIntervalSince1970]);
145        if ((date = [history objectForKey: @"DateActivity"]))
146            tr_torrentSetActivityDate(fHandle, [date timeIntervalSince1970]);
147        if ((date = [history objectForKey: @"DateCompleted"]))
148            tr_torrentSetDoneDate(fHandle, [date timeIntervalSince1970]);
149    }
150    return self;
151}
152
153- (NSDictionary *) history
154{
155    NSMutableDictionary * history = [NSMutableDictionary dictionaryWithObjectsAndKeys:
156                    [NSNumber numberWithBool: fPublicTorrent], @"PublicCopy",
157                    [self hashString], @"TorrentHash",
158                    fDownloadFolder, @"DownloadFolder",
159                    [NSNumber numberWithBool: fUseIncompleteFolder], @"UseIncompleteFolder",
160                    [NSNumber numberWithBool: [self isActive]], @"Active",
161                    [NSNumber numberWithInt: fRatioSetting], @"RatioSetting",
162                    [NSNumber numberWithFloat: fRatioLimit], @"RatioLimit",
163                    [NSNumber numberWithBool: fWaitToStart], @"WaitToStart",
164                    [NSNumber numberWithInt: fOrderValue], @"OrderValue",
165                    [NSNumber numberWithInt: fGroupValue], @"GroupValue",
166                    [NSNumber numberWithBool: fAddedTrackers], @"AddedTrackers", nil];
167   
168    if (fIncompleteFolder)
169        [history setObject: fIncompleteFolder forKey: @"IncompleteFolder"];
170
171    if (fPublicTorrent)
172        [history setObject: [self publicTorrentLocation] forKey: @"TorrentPath"];
173       
174    return history;
175}
176
177- (void) dealloc
178{
179    [[NSNotificationCenter defaultCenter] removeObserver: self];
180   
181    if (fFileStat)
182        tr_torrentFilesFree(fFileStat, [self fileCount]);
183   
184    [fPreviousFinishedIndexes release];
185    [fPreviousFinishedIndexesDate release];
186   
187    [fNameString release];
188    [fHashString release];
189   
190    [fDownloadFolder release];
191    [fIncompleteFolder release];
192   
193    [fPublicTorrentLocation release];
194   
195    [fIcon release];
196   
197    [fFileList release];
198    [fFlatFileList release];
199   
200    [fQuickPauseDict release];
201   
202    [super dealloc];
203}
204
205- (NSString *) description
206{
207    return [@"Torrent: " stringByAppendingString: [self name]];
208}
209
210- (void) closeRemoveTorrent
211{
212    //allow the file to be index by Time Machine
213    [self setTimeMachineExclude: NO forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
214   
215    tr_torrentRemove(fHandle);
216}
217
218- (void) changeIncompleteDownloadFolder: (NSString *) folder
219{
220    fUseIncompleteFolder = folder != nil;
221   
222    [fIncompleteFolder release];
223    fIncompleteFolder = fUseIncompleteFolder ? [folder retain] : nil;
224   
225    [self updateDownloadFolder];
226}
227
228- (void) changeDownloadFolder: (NSString *) folder
229{
230    if (fDownloadFolder && [folder isEqualToString: fDownloadFolder])
231        return;
232   
233    [fDownloadFolder release];
234    fDownloadFolder = [folder retain];
235   
236    [self updateDownloadFolder];
237}
238
239- (NSString *) downloadFolder
240{
241    return [NSString stringWithUTF8String: tr_torrentGetDownloadDir(fHandle)];
242}
243
244- (void) getAvailability: (int8_t *) tab size: (NSInteger) size
245{
246    tr_torrentAvailability(fHandle, tab, size);
247}
248
249- (void) getAmountFinished: (float *) tab size: (NSInteger) size
250{
251    tr_torrentAmountFinished(fHandle, tab, size);
252}
253
254- (NSIndexSet *) previousFinishedPieces
255{
256    //if the torrent hasn't been seen in a bit, and therefore hasn't been refreshed, return nil
257    if (fPreviousFinishedIndexesDate && [fPreviousFinishedIndexesDate timeIntervalSinceNow] > -2.0)
258        return fPreviousFinishedIndexes;
259    else
260        return nil;
261}
262
263-(void) setPreviousFinishedPieces: (NSIndexSet *) indexes
264{
265    [fPreviousFinishedIndexes release];
266    fPreviousFinishedIndexes = [indexes retain];
267   
268    [fPreviousFinishedIndexesDate release];
269    fPreviousFinishedIndexesDate = indexes != nil ? [[NSDate alloc] init] : nil;
270}
271
272- (void) update
273{
274    //get previous status values before update
275    BOOL wasChecking = NO, wasError = NO, wasStalled = NO;
276    if (fStat != NULL)
277    {
278        wasChecking = [self isChecking];
279        wasError = [self isError];
280        wasStalled = fStalled;
281    }
282   
283    fStat = tr_torrentStat(fHandle);
284   
285    //check to stop for ratio
286    CGFloat stopRatio;
287    if ([self isSeeding] && (stopRatio = [self actualStopRatio]) != INVALID && [self ratio] >= stopRatio)
288    {
289        [self setRatioSetting: NSOffState];
290        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentStoppedForRatio" object: self];
291       
292        [self stopTransfer];
293        fStat = tr_torrentStat(fHandle);
294       
295        fFinishedSeeding = YES;
296    }
297   
298    //check if stalled (stored because based on time and needs to check if it was previously stalled)
299    fStalled = [self isActive] && [fDefaults boolForKey: @"CheckStalled"]
300                && [self stalledMinutes] > [fDefaults integerForKey: @"StalledMinutes"];
301   
302    //update queue for checking (from downloading to seeding), stalled, or error
303    if ((wasChecking && ![self isChecking]) || (wasStalled != fStalled) || (!wasError && [self isError] && [self isActive]))
304        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
305}
306
307- (void) startTransfer
308{
309    fWaitToStart = NO;
310    fFinishedSeeding = NO;
311   
312    if (![self isActive] && [self alertForFolderAvailable] && [self alertForRemainingDiskSpace])
313    {
314        tr_torrentStart(fHandle);
315        [self update];
316    }
317}
318
319- (void) stopTransfer
320{
321    fWaitToStart = NO;
322   
323    if ([self isActive])
324    {
325        tr_torrentStop(fHandle);
326        [self update];
327       
328        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
329    }
330}
331
332- (void) sleep
333{
334    if ((fResumeOnWake = [self isActive]))
335        tr_torrentStop(fHandle);
336}
337
338- (void) wakeUp
339{
340    if (fResumeOnWake)
341        tr_torrentStart(fHandle);
342}
343
344- (void) manualAnnounce
345{
346    tr_torrentManualUpdate(fHandle);
347}
348
349- (BOOL) canManualAnnounce
350{
351    return tr_torrentCanManualUpdate(fHandle);
352}
353
354- (void) resetCache
355{
356    tr_torrentVerify(fHandle);
357    [self update];
358}
359
360- (CGFloat) ratio
361{
362    return fStat->ratio;
363}
364
365- (NSInteger) ratioSetting
366{
367    return fRatioSetting;
368}
369
370- (void) setRatioSetting: (NSInteger) setting
371{
372    fRatioSetting = setting;
373}
374
375- (CGFloat) ratioLimit
376{
377    return fRatioLimit;
378}
379
380- (void) setRatioLimit: (CGFloat) limit
381{
382    if (limit >= 0)
383        fRatioLimit = limit;
384}
385
386- (CGFloat) actualStopRatio
387{
388    if (fRatioSetting == NSOnState)
389        return fRatioLimit;
390    else if (fRatioSetting == NSMixedState && [fDefaults boolForKey: @"RatioCheck"])
391        return [fDefaults floatForKey: @"RatioLimit"];
392    else
393        return INVALID;
394}
395
396- (CGFloat) progressStopRatio
397{
398    CGFloat stopRatio, ratio;
399    if ((stopRatio = [self actualStopRatio]) == INVALID || (ratio = [self ratio]) >= stopRatio)
400        return 1.0;
401    else if (stopRatio > 0.0)
402        return ratio / stopRatio;
403    else
404        return 0.0;
405}
406
407- (tr_speedlimit) speedMode: (BOOL) upload
408{
409    return tr_torrentGetSpeedMode(fHandle, upload ? TR_UP : TR_DOWN);
410}
411
412- (void) setSpeedMode: (tr_speedlimit) mode upload: (BOOL) upload
413{
414    tr_torrentSetSpeedMode(fHandle, upload ? TR_UP : TR_DOWN, mode);
415}
416
417- (NSInteger) speedLimit: (BOOL) upload
418{
419    return tr_torrentGetSpeedLimit(fHandle, upload ? TR_UP : TR_DOWN);
420}
421
422- (void) setSpeedLimit: (NSInteger) limit upload: (BOOL) upload
423{
424    tr_torrentSetSpeedLimit(fHandle, upload ? TR_UP : TR_DOWN, limit);
425}
426
427- (void) setMaxPeerConnect: (uint16_t) count
428{
429    NSAssert(count > 0, @"max peer count must be greater than 0");
430   
431    tr_torrentSetPeerLimit(fHandle, count);
432}
433
434- (uint16_t) maxPeerConnect
435{
436    return tr_torrentGetPeerLimit(fHandle);
437}
438
439- (void) setWaitToStart: (BOOL) wait
440{
441    fWaitToStart = wait;
442}
443
444- (BOOL) waitingToStart
445{
446    return fWaitToStart;
447}
448
449- (void) revealData
450{
451    [[NSWorkspace sharedWorkspace] selectFile: [self dataLocation] inFileViewerRootedAtPath: nil];
452}
453
454- (void) revealPublicTorrent
455{
456    if (fPublicTorrent)
457        [[NSWorkspace sharedWorkspace] selectFile: fPublicTorrentLocation inFileViewerRootedAtPath: nil];
458}
459
460- (void) trashData
461{
462    tr_torrentDeleteLocalData(fHandle, trashDataFile);
463}
464
465- (void) trashTorrent
466{
467    if (fPublicTorrent)
468    {
469        [Torrent trashFile: fPublicTorrentLocation];
470        [fPublicTorrentLocation release];
471        fPublicTorrentLocation = nil;
472       
473        fPublicTorrent = NO;
474    }
475}
476
477- (void) moveTorrentDataFileTo: (NSString *) folder
478{
479    NSString * oldFolder = [self downloadFolder];
480    if (![oldFolder isEqualToString: folder] || ![fDownloadFolder isEqualToString: folder])
481    {
482        //check if moving inside itself
483        NSArray * oldComponents = [oldFolder pathComponents],
484                * newComponents = [folder pathComponents];
485        NSInteger count;
486       
487        if ((count = [oldComponents count]) < [newComponents count]
488                && [[newComponents objectAtIndex: count] isEqualToString: [self name]]
489                && [oldComponents isEqualToArray:
490                        [newComponents objectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, count)]]])
491        {
492            NSAlert * alert = [[NSAlert alloc] init];
493            [alert setMessageText: NSLocalizedString(@"A folder cannot be moved to inside itself.",
494                                                        "Move inside itself alert -> title")];
495            [alert setInformativeText: [NSString stringWithFormat:
496                            NSLocalizedString(@"The move operation of \"%@\" cannot be done.",
497                                                "Move inside itself alert -> message"), [self name]]];
498            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move inside itself alert -> button")];
499           
500            [alert runModal];
501            [alert release];
502           
503            return;
504        }
505       
506        [self quickPause];
507       
508        //allow if file can be moved or does not exist
509        if ([[NSFileManager defaultManager] movePath: [oldFolder stringByAppendingPathComponent: [self name]]
510                            toPath: [folder stringByAppendingPathComponent: [self name]] handler: nil]
511            || ![[NSFileManager defaultManager] fileExistsAtPath: [oldFolder stringByAppendingPathComponent: [self name]]])
512        {
513            //get rid of both incomplete folder and old download folder, even if move failed
514            fUseIncompleteFolder = NO;
515            if (fIncompleteFolder)
516            {
517                [fIncompleteFolder release];
518                fIncompleteFolder = nil;
519            }
520            [self changeDownloadFolder: folder];
521           
522            [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateStats" object: nil];
523           
524            [self endQuickPause];
525        }
526        else
527        {
528            [self endQuickPause];
529       
530            NSAlert * alert = [[NSAlert alloc] init];
531            [alert setMessageText: NSLocalizedString(@"There was an error moving the data file.", "Move error alert -> title")];
532            [alert setInformativeText: [NSString stringWithFormat:
533                            NSLocalizedString(@"The move operation of \"%@\" cannot be done.",
534                                                "Move error alert -> message"), [self name]]];
535            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move error alert -> button")];
536           
537            [alert runModal];
538            [alert release];
539        }
540    }
541}
542
543- (void) copyTorrentFileTo: (NSString *) path
544{
545    [[NSFileManager defaultManager] copyPath: [self torrentLocation] toPath: path handler: nil];
546}
547
548- (BOOL) alertForRemainingDiskSpace
549{
550    if ([self allDownloaded] || ![fDefaults boolForKey: @"WarningRemainingSpace"])
551        return YES;
552   
553    NSFileManager * fileManager = [NSFileManager defaultManager];
554    NSString * downloadFolder = [self downloadFolder];
555   
556    NSString * volumeName;
557    if ((volumeName = [[fileManager componentsToDisplayForPath: downloadFolder] objectAtIndex: 0]))
558    {
559        BOOL onLeopard = [NSApp isOnLeopardOrBetter];
560       
561        NSDictionary * systemAttributes = onLeopard ? [fileManager attributesOfFileSystemForPath: downloadFolder error: NULL]
562                                            : [fileManager fileSystemAttributesAtPath: downloadFolder];
563        uint64_t remainingSpace = [[systemAttributes objectForKey: NSFileSystemFreeSize] unsignedLongLongValue];
564       
565        //if the remaining space is greater than the size left, then there is enough space regardless of preallocation
566        if (remainingSpace < [self sizeLeft] && remainingSpace < tr_torrentGetBytesLeftToAllocate(fHandle))
567        {
568            NSAlert * alert = [[NSAlert alloc] init];
569            [alert setMessageText: [NSString stringWithFormat:
570                                    NSLocalizedString(@"Not enough remaining disk space to download \"%@\" completely.",
571                                        "Torrent disk space alert -> title"), [self name]]];
572            [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"The transfer will be paused."
573                                        " Clear up space on %@ or deselect files in the torrent inspector to continue.",
574                                        "Torrent disk space alert -> message"), volumeName]];
575            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent disk space alert -> button")];
576            [alert addButtonWithTitle: NSLocalizedString(@"Download Anyway", "Torrent disk space alert -> button")];
577           
578            if (onLeopard)
579            {
580                [alert setShowsSuppressionButton: YES];
581                [[alert suppressionButton] setTitle: NSLocalizedString(@"Do not check disk space again",
582                                                        "Torrent disk space alert -> button")];
583            }
584            else
585                [alert addButtonWithTitle: NSLocalizedString(@"Always Download", "Torrent disk space alert -> button")];
586
587            NSInteger result = [alert runModal];
588            if ((onLeopard ? [[alert suppressionButton] state] == NSOnState : result == NSAlertThirdButtonReturn))
589                [fDefaults setBool: NO forKey: @"WarningRemainingSpace"];
590            [alert release];
591           
592            return result != NSAlertFirstButtonReturn;
593        }
594    }
595    return YES;
596}
597
598- (BOOL) alertForFolderAvailable
599{
600    #warning check for change from incomplete to download folder first
601    if (access(tr_torrentGetDownloadDir(fHandle), 0))
602    {
603        NSAlert * alert = [[NSAlert alloc] init];
604        [alert setMessageText: [NSString stringWithFormat:
605                                NSLocalizedString(@"The folder for downloading \"%@\" cannot be used.",
606                                    "Folder cannot be used alert -> title"), [self name]]];
607        [alert setInformativeText: [NSString stringWithFormat:
608                        NSLocalizedString(@"\"%@\" cannot be used. The transfer will be paused.",
609                                            "Folder cannot be used alert -> message"), [self downloadFolder]]];
610        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Folder cannot be used alert -> button")];
611        [alert addButtonWithTitle: [NSLocalizedString(@"Choose New Location",
612                                    "Folder cannot be used alert -> location button") stringByAppendingEllipsis]];
613       
614        if ([alert runModal] != NSAlertFirstButtonReturn)
615        {
616            NSOpenPanel * panel = [NSOpenPanel openPanel];
617           
618            [panel setPrompt: NSLocalizedString(@"Select", "Folder cannot be used alert -> prompt")];
619            [panel setAllowsMultipleSelection: NO];
620            [panel setCanChooseFiles: NO];
621            [panel setCanChooseDirectories: YES];
622            [panel setCanCreateDirectories: YES];
623
624            [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the download folder for \"%@\"",
625                                "Folder cannot be used alert -> select destination folder"), [self name]]];
626           
627            [[NSNotificationCenter defaultCenter] postNotificationName: @"MakeWindowKey" object: nil];
628            [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: [NSApp keyWindow] modalDelegate: self
629                    didEndSelector: @selector(destinationChoiceClosed:returnCode:contextInfo:) contextInfo: nil];
630        }
631       
632        [alert release];
633       
634        return NO;
635    }
636    return YES;
637}
638
639- (void) destinationChoiceClosed: (NSOpenPanel *) openPanel returnCode: (NSInteger) code contextInfo: (void *) context
640{
641    if (code != NSOKButton)
642        return;
643   
644    [self changeDownloadFolder: [[openPanel filenames] objectAtIndex: 0]];
645   
646    [self startTransfer];
647    [self update];
648   
649    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateStats" object: nil];
650}
651
652- (BOOL) alertForMoveFolderAvailable
653{
654    if (access([fDownloadFolder UTF8String], 0))
655    {
656        NSAlert * alert = [[NSAlert alloc] init];
657        [alert setMessageText: [NSString stringWithFormat:
658                                NSLocalizedString(@"The folder for moving the completed \"%@\" cannot be used.",
659                                    "Move folder cannot be used alert -> title"), [self name]]];
660        [alert setInformativeText: [NSString stringWithFormat:
661                                NSLocalizedString(@"\"%@\" cannot be used. The file will remain in its current location.",
662                                    "Move folder cannot be used alert -> message"), fDownloadFolder]];
663        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move folder cannot be used alert -> button")];
664       
665        [alert runModal];
666        [alert release];
667       
668        return NO;
669    }
670   
671    return YES;
672}
673
674- (NSImage *) icon
675{
676    if (!fIcon)
677    {
678        fIcon = [[[NSWorkspace sharedWorkspace] iconForFileType: [self isFolder] ? NSFileTypeForHFSTypeCode('fldr')
679                                                : [[self name] pathExtension]] retain];
680        [fIcon setFlipped: YES];
681    }
682    return fIcon;
683}
684
685- (NSString *) name
686{
687    return fNameString;
688}
689
690- (BOOL) isFolder
691{
692    return fInfo->isMultifile;
693}
694
695- (uint64_t) size
696{
697    return fInfo->totalSize;
698}
699
700- (uint64_t) sizeLeft
701{
702    return fStat->leftUntilDone;
703}
704
705- (NSString *) trackerAddressAnnounce
706{
707    return fStat->announceURL ? [NSString stringWithUTF8String: fStat->announceURL] : nil;
708}
709
710- (NSDate *) lastAnnounceTime
711{
712    NSInteger date = fStat->lastAnnounceTime;
713    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
714}
715
716- (NSInteger) nextAnnounceTime
717{
718    NSInteger date = fStat->nextAnnounceTime;
719    NSTimeInterval difference;
720    switch (date)
721    {
722        case 0:
723            return STAT_TIME_NONE;
724        case 1:
725            return STAT_TIME_NOW;
726        default:
727            difference = [[NSDate dateWithTimeIntervalSince1970: date] timeIntervalSinceNow];
728            return difference > 0 ? (NSInteger)difference : STAT_TIME_NONE;
729    }
730}
731
732- (NSString *) announceResponse
733{
734    return [NSString stringWithUTF8String: fStat->announceResponse];
735}
736
737- (NSString *) trackerAddressScrape
738{
739    return fStat->scrapeURL ? [NSString stringWithUTF8String: fStat->scrapeURL] : nil;
740}
741
742- (NSDate *) lastScrapeTime
743{
744    NSInteger date = fStat->lastScrapeTime;
745    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
746}
747
748- (NSInteger) nextScrapeTime
749{
750    NSInteger date = fStat->nextScrapeTime;
751    NSTimeInterval difference;
752    switch (date)
753    {
754        case 0:
755            return STAT_TIME_NONE;
756        case 1:
757            return STAT_TIME_NOW;
758        default:
759            difference = [[NSDate dateWithTimeIntervalSince1970: date] timeIntervalSinceNow];
760            return difference > 0 ? (NSInteger)difference : STAT_TIME_NONE;
761    }
762}
763
764- (NSString *) scrapeResponse
765{
766    return [NSString stringWithUTF8String: fStat->scrapeResponse];
767}
768
769- (NSMutableArray *) allTrackers: (BOOL) separators
770{
771    NSInteger count = fInfo->trackerCount, capacity = count;
772    if (separators)
773        capacity += fInfo->trackers[count-1].tier + 1;
774    NSMutableArray * allTrackers = [NSMutableArray arrayWithCapacity: capacity];
775   
776    for (NSInteger i = 0, tier = -1; i < count; i++)
777    {
778        if (separators && tier != fInfo->trackers[i].tier)
779        {
780            tier = fInfo->trackers[i].tier;
781            [allTrackers addObject: [NSNumber numberWithInt: fAddedTrackers ? tier : tier + 1]];
782        }
783       
784        [allTrackers addObject: [NSString stringWithUTF8String: fInfo->trackers[i].announce]];
785    }
786   
787    return allTrackers;
788}
789
790- (BOOL) updateAllTrackersForAdd: (NSMutableArray *) trackers
791{
792    //find added tracker at end of first tier
793    NSInteger i;
794    for (i = 1; i < [trackers count]; i++)
795        if ([[trackers objectAtIndex: i] isKindOfClass: [NSNumber class]])
796            break;
797    i--;
798   
799    NSString * tracker = [trackers objectAtIndex: i];
800   
801    tracker = [tracker stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
802   
803    if ([tracker rangeOfString: @"://"].location == NSNotFound)
804    {
805        tracker = [@"http://" stringByAppendingString: tracker];
806        [trackers replaceObjectAtIndex: i withObject: tracker];
807    }
808   
809    if (!tr_httpIsValidURL([tracker UTF8String]))
810        return NO;
811   
812    [self updateAllTrackers: trackers];
813   
814    fAddedTrackers = YES;
815    return YES;
816}
817
818- (void) updateAllTrackersForRemove: (NSMutableArray *) trackers
819{
820    //check if no user-added groups
821    if ([[trackers objectAtIndex: 0] intValue] != 0)
822        fAddedTrackers = NO;
823   
824    [self updateAllTrackers: trackers];
825}
826
827- (BOOL) hasAddedTrackers
828{
829    return fAddedTrackers;
830}
831
832- (NSString *) comment
833{
834    return [NSString stringWithUTF8String: fInfo->comment];
835}
836
837- (NSString *) creator
838{
839    return [NSString stringWithUTF8String: fInfo->creator];
840}
841
842- (NSDate *) dateCreated
843{
844    NSInteger date = fInfo->dateCreated;
845    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
846}
847
848- (NSInteger) pieceSize
849{
850    return fInfo->pieceSize;
851}
852
853- (NSInteger) pieceCount
854{
855    return fInfo->pieceCount;
856}
857
858- (NSString *) hashString
859{
860    return fHashString;
861}
862
863- (BOOL) privateTorrent
864{
865    return fInfo->isPrivate;
866}
867
868- (NSString *) torrentLocation
869{
870    return [NSString stringWithUTF8String: fInfo->torrent];
871}
872
873- (NSString *) publicTorrentLocation
874{
875    return fPublicTorrentLocation;
876}
877
878- (NSString *) dataLocation
879{
880    return [[self downloadFolder] stringByAppendingPathComponent: [self name]];
881}
882
883- (BOOL) publicTorrent
884{
885    return fPublicTorrent;
886}
887
888- (CGFloat) progress
889{
890    return fStat->percentComplete;
891}
892
893- (CGFloat) progressDone
894{
895    return fStat->percentDone;
896}
897
898- (CGFloat) progressLeft
899{
900    return (CGFloat)[self sizeLeft] / [self size];
901}
902
903- (CGFloat) checkingProgress
904{
905    return fStat->recheckProgress;
906}
907
908- (NSInteger) eta
909{
910    return fStat->eta;
911}
912
913- (NSInteger) etaRatio
914{
915    if (![self isSeeding])
916        return TR_ETA_UNKNOWN;
917   
918    CGFloat uploadRate = [self uploadRate];
919    if (uploadRate < 0.1)
920        return TR_ETA_UNKNOWN;
921   
922    CGFloat stopRatio = [self actualStopRatio], ratio = [self ratio];
923    if (stopRatio == INVALID || ratio >= stopRatio)
924        return TR_ETA_UNKNOWN;
925   
926    CGFloat haveDownloaded = (CGFloat)([self downloadedTotal] > 0 ? [self downloadedTotal] : [self haveVerified]);
927    CGFloat needUploaded = haveDownloaded * (stopRatio - ratio);
928    return needUploaded / uploadRate / 1024.0;
929}
930
931- (CGFloat) notAvailableDesired
932{
933    return 1.0 - (CGFloat)fStat->desiredAvailable / [self sizeLeft];
934}
935
936- (BOOL) isActive
937{
938    return fStat->activity != TR_STATUS_STOPPED;
939}
940
941- (BOOL) isSeeding
942{
943    return fStat->activity == TR_STATUS_SEED;
944}
945
946- (BOOL) isChecking
947{
948    return fStat->activity == TR_STATUS_CHECK || fStat->activity == TR_STATUS_CHECK_WAIT;
949}
950
951- (BOOL) isCheckingWaiting
952{
953    return fStat->activity == TR_STATUS_CHECK_WAIT;
954}
955
956- (BOOL) allDownloaded
957{
958    return [self progressDone] >= 1.0;
959}
960
961- (BOOL) isComplete
962{
963    return [self progress] >= 1.0;
964}
965
966- (BOOL) isError
967{
968    return fStat->error != TR_OK;
969}
970
971- (NSString *) errorMessage
972{
973    if (![self isError])
974        return @"";
975   
976    NSString * error;
977    if (!(error = [NSString stringWithUTF8String: fStat->errorString])
978        && !(error = [NSString stringWithCString: fStat->errorString encoding: NSISOLatin1StringEncoding]))
979        error = [NSString stringWithFormat: @"(%@)", NSLocalizedString(@"unreadable error", "Torrent -> error string unreadable")];
980   
981    return error;
982}
983
984- (NSArray *) peers
985{
986    int totalPeers;
987    tr_peer_stat * peers = tr_torrentPeers(fHandle, &totalPeers);
988   
989    NSMutableArray * peerDicts = [NSMutableArray arrayWithCapacity: totalPeers];
990   
991    for (int i = 0; i < totalPeers; i++)
992    {
993        tr_peer_stat * peer = &peers[i];
994        NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 10];
995       
996        [dict setObject: [NSNumber numberWithInt: peer->from] forKey: @"From"];
997        [dict setObject: [NSString stringWithUTF8String: peer->addr] forKey: @"IP"];
998        [dict setObject: [NSNumber numberWithInt: peer->port] forKey: @"Port"];
999        [dict setObject: [NSNumber numberWithFloat: peer->progress] forKey: @"Progress"];
1000        [dict setObject: [NSNumber numberWithBool: peer->isSeed] forKey: @"Seed"];
1001        [dict setObject: [NSNumber numberWithBool: peer->isEncrypted] forKey: @"Encryption"];
1002        [dict setObject: [NSString stringWithUTF8String: peer->client] forKey: @"Client"];
1003        [dict setObject: [NSString stringWithUTF8String: peer->flagStr] forKey: @"Flags"];
1004       
1005        if (peer->isUploadingTo)
1006            [dict setObject: [NSNumber numberWithFloat: peer->rateToPeer] forKey: @"UL To Rate"];
1007        if (peer->isDownloadingFrom)
1008            [dict setObject: [NSNumber numberWithFloat: peer->rateToClient] forKey: @"DL From Rate"];
1009       
1010        [peerDicts addObject: dict];
1011    }
1012   
1013    tr_torrentPeersFree(peers, totalPeers);
1014   
1015    return peerDicts;
1016}
1017
1018- (NSUInteger) webSeedCount
1019{
1020    return fInfo->webseedCount;
1021}
1022
1023- (NSArray *) webSeeds
1024{
1025    const NSInteger webSeedCount = fInfo->webseedCount;
1026    NSMutableArray * webSeeds = [NSMutableArray arrayWithCapacity: webSeedCount];
1027   
1028    float * dlSpeeds = tr_torrentWebSpeeds(fHandle);
1029   
1030    for (NSInteger i = 0; i < webSeedCount; i++)
1031    {
1032        NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 2];
1033       
1034        [dict setObject: [NSString stringWithUTF8String: fInfo->webseeds[i]] forKey: @"Address"];
1035       
1036        if (dlSpeeds[i] != -1.0)
1037            [dict setObject: [NSNumber numberWithFloat: dlSpeeds[i]] forKey: @"DL From Rate"];
1038       
1039        [webSeeds addObject: dict];
1040    }
1041   
1042    tr_free(dlSpeeds);
1043   
1044    return webSeeds;
1045}
1046
1047- (NSString *) progressString
1048{
1049    NSString * string;
1050   
1051    if (![self allDownloaded])
1052    {
1053        CGFloat progress;
1054        if ([self isFolder] && [fDefaults boolForKey: @"DisplayStatusProgressSelected"])
1055        {
1056            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@ selected", "Torrent -> progress string"),
1057                        [NSString stringForFileSize: [self haveTotal]], [NSString stringForFileSize: [self totalSizeSelected]]];
1058            progress = 100.0 * [self progressDone];
1059        }
1060        else
1061        {
1062            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Torrent -> progress string"),
1063                        [NSString stringForFileSize: [self haveTotal]], [NSString stringForFileSize: [self size]]];
1064            progress = 100.0 * [self progress];
1065        }
1066       
1067        string = [NSString localizedStringWithFormat: @"%@ (%.2f%%)", string, progress];
1068    }
1069    else
1070    {
1071        NSString * downloadString;
1072        if (![self isComplete]) //only multifile possible
1073        {
1074            if ([fDefaults boolForKey: @"DisplayStatusProgressSelected"])
1075                downloadString = [NSString stringWithFormat: NSLocalizedString(@"%@ selected", "Torrent -> progress string"),
1076                                    [NSString stringForFileSize: [self haveTotal]]];
1077            else
1078            {
1079                downloadString = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Torrent -> progress string"),
1080                                    [NSString stringForFileSize: [self haveTotal]], [NSString stringForFileSize: [self size]]];
1081               
1082                downloadString = [NSString localizedStringWithFormat: @"%@ (%.2f%%)", downloadString, 100.0 * [self progress]];
1083            }
1084        }
1085        else
1086            downloadString = [NSString stringForFileSize: [self size]];
1087       
1088        NSString * uploadString = [NSString stringWithFormat: NSLocalizedString(@"uploaded %@ (Ratio: %@)",
1089                                    "Torrent -> progress string"), [NSString stringForFileSize: [self uploadedTotal]],
1090                                    [NSString stringForRatio: [self ratio]]];
1091       
1092        string = [downloadString stringByAppendingFormat: @", %@", uploadString];
1093    }
1094   
1095    //add time when downloading
1096    if (fStat->activity == TR_STATUS_DOWNLOAD || ([self isSeeding]
1097        && (fRatioSetting == NSOnState || (fRatioSetting == NSMixedState && [fDefaults boolForKey: @"RatioCheck"]))))
1098    {
1099        NSInteger eta = fStat->activity == TR_STATUS_DOWNLOAD ? [self eta] : [self etaRatio];
1100        string = [string stringByAppendingFormat: @" - %@", [self etaString: eta]];
1101    }
1102   
1103    return string;
1104}
1105
1106- (NSString *) statusString
1107{
1108    NSString * string;
1109   
1110    if ([self isError])
1111    {
1112        string = NSLocalizedString(@"Error", "Torrent -> status string");
1113        NSString * errorString = [self errorMessage];
1114        if (errorString && ![errorString isEqualToString: @""])
1115            string = [string stringByAppendingFormat: @": %@", errorString];
1116    }
1117    else
1118    {
1119        switch (fStat->activity)
1120        {
1121            case TR_STATUS_STOPPED:
1122                if (fWaitToStart)
1123                {
1124                    string = ![self allDownloaded]
1125                            ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
1126                            : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
1127                }
1128                else if (fFinishedSeeding)
1129                    string = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
1130                else
1131                    string = NSLocalizedString(@"Paused", "Torrent -> status string");
1132                break;
1133
1134            case TR_STATUS_CHECK_WAIT:
1135                string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1136                break;
1137
1138            case TR_STATUS_CHECK:
1139                string = [NSString localizedStringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
1140                                        "Torrent -> status string"), 100.0 * [self checkingProgress]];
1141                break;
1142
1143            case TR_STATUS_DOWNLOAD:
1144                if ([self totalPeersConnected] != 1)
1145                    string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of %d peers",
1146                                                    "Torrent -> status string"), [self peersSendingToUs], [self totalPeersConnected]];
1147                else
1148                    string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of 1 peer",
1149                                                    "Torrent -> status string"), [self peersSendingToUs]];
1150               
1151                NSInteger webSeedCount = fStat->webseedsSendingToUs;
1152                if (webSeedCount > 0)
1153                {
1154                    NSString * webSeedString;
1155                    if (webSeedCount == 1)
1156                        webSeedString = NSLocalizedString(@"web seed", "Torrent -> status string");
1157                    else
1158                        webSeedString = [NSString stringWithFormat: NSLocalizedString(@"%d web seeds", "Torrent -> status string"),
1159                                                                    webSeedCount];
1160                   
1161                    string = [string stringByAppendingFormat: @" + %@", webSeedString];
1162                }
1163               
1164                break;
1165
1166            case TR_STATUS_SEED:
1167                if ([self totalPeersConnected] != 1)
1168                    string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of %d peers", "Torrent -> status string"),
1169                                                    [self peersGettingFromUs], [self totalPeersConnected]];
1170                else
1171                    string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of 1 peer", "Torrent -> status string"),
1172                                                    [self peersGettingFromUs]];
1173        }
1174       
1175        if (fStalled)
1176            string = [NSLocalizedString(@"Stalled", "Torrent -> status string") stringByAppendingFormat: @", %@", string];
1177    }
1178   
1179    //append even if error
1180    if ([self isActive] && ![self isChecking])
1181    {
1182        if (fStat->activity == TR_STATUS_DOWNLOAD)
1183            string = [string stringByAppendingFormat: @" - %@: %@, %@: %@",
1184                        NSLocalizedString(@"DL", "Torrent -> status string"), [NSString stringForSpeed: [self downloadRate]],
1185                        NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1186        else
1187            string = [string stringByAppendingFormat: @" - %@: %@",
1188                        NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1189    }
1190   
1191    return string;
1192}
1193
1194- (NSString *) shortStatusString
1195{
1196    NSString * string;
1197   
1198    switch (fStat->activity)
1199    {
1200        case TR_STATUS_STOPPED:
1201            if (fWaitToStart)
1202            {
1203                string = ![self allDownloaded]
1204                        ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
1205                        : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
1206            }
1207            else if (fFinishedSeeding)
1208                string = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
1209            else
1210                string = NSLocalizedString(@"Paused", "Torrent -> status string");
1211            break;
1212
1213        case TR_STATUS_CHECK_WAIT:
1214            string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1215            break;
1216
1217        case TR_STATUS_CHECK:
1218            string = [NSString localizedStringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
1219                                    "Torrent -> status string"), 100.0 * [self checkingProgress]];
1220            break;
1221       
1222        case TR_STATUS_DOWNLOAD:
1223            string = [NSString stringWithFormat: @"%@: %@, %@: %@",
1224                            NSLocalizedString(@"DL", "Torrent -> status string"), [NSString stringForSpeed: [self downloadRate]],
1225                            NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1226            break;
1227       
1228        case TR_STATUS_SEED:
1229            string = [NSString stringWithFormat: @"%@: %@, %@: %@",
1230                            NSLocalizedString(@"Ratio", "Torrent -> status string"), [NSString stringForRatio: [self ratio]],
1231                            NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1232    }
1233   
1234    return string;
1235}
1236
1237- (NSString *) remainingTimeString
1238{
1239    if (![self isActive] || ([self isSeeding]
1240        && !(fRatioSetting == NSOnState || (fRatioSetting == NSMixedState && [fDefaults boolForKey: @"RatioCheck"]))))
1241        return [self shortStatusString];
1242   
1243    return [self etaString: [self isSeeding] ? [self etaRatio] : [self eta]];
1244}
1245
1246- (NSString *) stateString
1247{
1248    switch (fStat->activity)
1249    {
1250        case TR_STATUS_STOPPED:
1251            return NSLocalizedString(@"Paused", "Torrent -> status string");
1252
1253        case TR_STATUS_CHECK:
1254            return [NSString localizedStringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
1255                                    "Torrent -> status string"), 100.0 * [self checkingProgress]];
1256       
1257        case TR_STATUS_CHECK_WAIT:
1258            return [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1259
1260        case TR_STATUS_DOWNLOAD:
1261            return NSLocalizedString(@"Downloading", "Torrent -> status string");
1262
1263        case TR_STATUS_SEED:
1264            return NSLocalizedString(@"Seeding", "Torrent -> status string");
1265    }
1266}
1267
1268- (NSInteger) seeders
1269{
1270    return fStat->seeders;
1271}
1272
1273- (NSInteger) leechers
1274{
1275    return fStat->leechers;
1276}
1277
1278- (NSInteger) completedFromTracker
1279{
1280    return fStat->timesCompleted;
1281}
1282
1283- (NSInteger) totalPeersConnected
1284{
1285    return fStat->peersConnected;
1286}
1287
1288- (NSInteger) totalPeersTracker
1289{
1290    return fStat->peersFrom[TR_PEER_FROM_TRACKER];
1291}
1292
1293- (NSInteger) totalPeersIncoming
1294{
1295    return fStat->peersFrom[TR_PEER_FROM_INCOMING];
1296}
1297
1298- (NSInteger) totalPeersCache
1299{
1300    return fStat->peersFrom[TR_PEER_FROM_CACHE];
1301}
1302
1303- (NSInteger) totalPeersPex
1304{
1305    return fStat->peersFrom[TR_PEER_FROM_PEX];
1306}
1307
1308- (NSInteger) totalPeersKnown
1309{
1310    return fStat->peersKnown;
1311}
1312
1313- (NSInteger) peersSendingToUs
1314{
1315    return fStat->peersSendingToUs;
1316}
1317
1318- (NSInteger) peersGettingFromUs
1319{
1320    return fStat->peersGettingFromUs;
1321}
1322
1323- (CGFloat) downloadRate
1324{
1325    return fStat->pieceDownloadSpeed;
1326}
1327
1328- (CGFloat) uploadRate
1329{
1330    return fStat->pieceUploadSpeed;
1331}
1332
1333- (CGFloat) totalRate
1334{
1335    return [self downloadRate] + [self uploadRate];
1336}
1337
1338- (uint64_t) haveVerified
1339{
1340    return fStat->haveValid;
1341}
1342
1343- (uint64_t) haveTotal
1344{
1345    return [self haveVerified] + fStat->haveUnchecked;
1346}
1347
1348- (uint64_t) totalSizeSelected
1349{
1350    return fStat->sizeWhenDone;
1351}
1352
1353- (uint64_t) downloadedTotal
1354{
1355    return fStat->downloadedEver;
1356}
1357
1358- (uint64_t) uploadedTotal
1359{
1360    return fStat->uploadedEver;
1361}
1362
1363- (uint64_t) failedHash
1364{
1365    return fStat->corruptEver;
1366}
1367
1368- (CGFloat) swarmSpeed
1369{
1370    return fStat->swarmSpeed;
1371}
1372
1373- (NSInteger) orderValue
1374{
1375    return fOrderValue;
1376}
1377
1378- (void) setOrderValue: (NSInteger) orderValue
1379{
1380    fOrderValue = orderValue;
1381}
1382
1383- (NSInteger) groupValue
1384{
1385    return fGroupValue;
1386}
1387
1388- (void) setGroupValue: (NSInteger) goupValue
1389{
1390    fGroupValue = goupValue;
1391}
1392
1393- (NSInteger) groupOrderValue
1394{
1395    return [[GroupsController groups] rowValueForIndex: fGroupValue];
1396}
1397
1398- (void) checkGroupValueForRemoval: (NSNotification *) notification
1399{
1400    if (fGroupValue != -1 && [[[notification userInfo] objectForKey: @"Index"] intValue] == fGroupValue)
1401        fGroupValue = -1;
1402}
1403
1404- (NSArray *) fileList
1405{
1406    return fFileList;
1407}
1408
1409- (NSInteger) fileCount
1410{
1411    return fInfo->fileCount;
1412}
1413
1414- (void) updateFileStat
1415{
1416    if (fFileStat)
1417        tr_torrentFilesFree(fFileStat, [self fileCount]);
1418   
1419    fFileStat = tr_torrentFiles(fHandle, NULL);
1420}
1421
1422- (CGFloat) fileProgress: (FileListNode *) node
1423{
1424    if ([self isComplete])
1425        return 1.0;
1426   
1427    if (!fFileStat)
1428        [self updateFileStat];
1429   
1430    NSIndexSet * indexSet = [node indexes];
1431   
1432    if ([indexSet count] == 1)
1433        return fFileStat[[indexSet firstIndex]].progress;
1434   
1435    uint64_t have = 0;
1436    for (NSInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1437        have += fFileStat[index].bytesCompleted;
1438   
1439    NSAssert([node size], @"director in torrent file has size 0");
1440    return (CGFloat)have / [node size];
1441}
1442
1443- (NSArray *) flatFileList
1444{
1445    return fFlatFileList;
1446}
1447
1448- (BOOL) canChangeDownloadCheckForFile: (NSInteger) index
1449{
1450    if (!fFileStat)
1451        [self updateFileStat];
1452   
1453    return [self fileCount] > 1 && fFileStat[index].progress < 1.0;
1454}
1455
1456- (BOOL) canChangeDownloadCheckForFiles: (NSIndexSet *) indexSet
1457{
1458    if ([self fileCount] <= 1 || [self isComplete])
1459        return NO;
1460   
1461    if (!fFileStat)
1462        [self updateFileStat];
1463   
1464    for (NSInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1465        if (fFileStat[index].progress < 1.0)
1466            return YES;
1467    return NO;
1468}
1469
1470- (NSInteger) checkForFiles: (NSIndexSet *) indexSet
1471{
1472    BOOL onState = NO, offState = NO;
1473    for (NSInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1474    {
1475        if (tr_torrentGetFileDL(fHandle, index) || ![self canChangeDownloadCheckForFile: index])
1476            onState = YES;
1477        else
1478            offState = YES;
1479       
1480        if (onState && offState)
1481            return NSMixedState;
1482    }
1483    return onState ? NSOnState : NSOffState;
1484}
1485
1486- (void) setFileCheckState: (NSInteger) state forIndexes: (NSIndexSet *) indexSet
1487{
1488    NSUInteger count = [indexSet count];
1489    tr_file_index_t * files = malloc(count * sizeof(tr_file_index_t));
1490    for (NSUInteger index = [indexSet firstIndex], i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index], i++)
1491        files[i] = index;
1492   
1493    tr_torrentSetFileDLs(fHandle, files, count, state != NSOffState);
1494    free(files);
1495   
1496    [self update];
1497    [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFileCheckChange" object: self];
1498}
1499
1500- (void) setFilePriority: (NSInteger) priority forIndexes: (NSIndexSet *) indexSet
1501{
1502    const NSUInteger count = [indexSet count];
1503    tr_file_index_t * files = malloc(count * sizeof(tr_file_index_t));
1504    for (NSUInteger index = [indexSet firstIndex], i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index], i++)
1505        files[i] = index;
1506   
1507    tr_torrentSetFilePriorities(fHandle, files, count, priority);
1508    free(files);
1509}
1510
1511- (BOOL) hasFilePriority: (NSInteger) priority forIndexes: (NSIndexSet *) indexSet
1512{
1513    for (NSInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1514        if (priority == tr_torrentGetFilePriority(fHandle, index) && [self canChangeDownloadCheckForFile: index])
1515            return YES;
1516    return NO;
1517}
1518
1519- (NSSet *) filePrioritiesForIndexes: (NSIndexSet *) indexSet
1520{
1521    BOOL low = NO, normal = NO, high = NO;
1522    NSMutableSet * priorities = [NSMutableSet setWithCapacity: 3];
1523   
1524    for (NSInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1525    {
1526        if (![self canChangeDownloadCheckForFile: index])
1527            continue;
1528       
1529        NSInteger priority = tr_torrentGetFilePriority(fHandle, index);
1530        if (priority == TR_PRI_LOW)
1531        {
1532            if (low)
1533                continue;
1534            low = YES;
1535        }
1536        else if (priority == TR_PRI_HIGH)
1537        {
1538            if (high)
1539                continue;
1540            high = YES;
1541        }
1542        else
1543        {
1544            if (normal)
1545                continue;
1546            normal = YES;
1547        }
1548       
1549        [priorities addObject: [NSNumber numberWithInt: priority]];
1550        if (low && normal && high)
1551            break;
1552    }
1553    return priorities;
1554}
1555
1556- (NSDate *) dateAdded
1557{
1558    time_t date = fStat->addedDate;
1559    return [NSDate dateWithTimeIntervalSince1970: date];
1560}
1561
1562- (NSDate *) dateCompleted
1563{
1564    time_t date = fStat->doneDate;
1565    return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
1566}
1567
1568- (NSDate *) dateActivity
1569{
1570    time_t date = fStat->activityDate;
1571    return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
1572}
1573
1574- (NSDate *) dateActivityOrAdd
1575{
1576    NSDate * date = [self dateActivity];
1577    return date ? date : [self dateAdded];
1578}
1579
1580- (NSInteger) stalledMinutes
1581{
1582    time_t start = fStat->startDate;
1583    if (start == 0)
1584        return -1;
1585   
1586    NSDate * started = [NSDate dateWithTimeIntervalSince1970: start],
1587            * activity = [self dateActivity];
1588   
1589    NSDate * laterDate = activity ? [started laterDate: activity] : started;
1590    return -1 * [laterDate timeIntervalSinceNow] / 60;
1591}
1592
1593- (BOOL) isStalled
1594{
1595    return fStalled;
1596}
1597
1598- (NSInteger) stateSortKey
1599{
1600    if (![self isActive]) //paused
1601        return 0;
1602    else if ([self isSeeding]) //seeding
1603        return 1;
1604    else //downloading
1605        return 2;
1606}
1607
1608- (tr_torrent *) torrentStruct
1609{
1610    return fHandle;
1611}
1612
1613@end
1614
1615@implementation Torrent (Private)
1616
1617//if a hash is given, attempt to load that; otherwise, attempt to open file at path
1618- (id) initWithHash: (NSString *) hashString path: (NSString *) path torrentStruct: (tr_torrent *) torrentStruct lib: (tr_session *) lib
1619        publicTorrent: (NSNumber *) publicTorrent
1620        downloadFolder: (NSString *) downloadFolder
1621        useIncompleteFolder: (NSNumber *) useIncompleteFolder incompleteFolder: (NSString *) incompleteFolder
1622        ratioSetting: (NSNumber *) ratioSetting ratioLimit: (NSNumber *) ratioLimit
1623        waitToStart: (NSNumber *) waitToStart
1624        orderValue: (NSNumber *) orderValue groupValue: (NSNumber *) groupValue addedTrackers: (NSNumber *) addedTrackers
1625{
1626    if (!(self = [super init]))
1627        return nil;
1628   
1629    fDefaults = [NSUserDefaults standardUserDefaults];
1630
1631    fPublicTorrent = path && (publicTorrent ? [publicTorrent boolValue] : ![fDefaults boolForKey: @"DeleteOriginalTorrent"]);
1632    if (fPublicTorrent)
1633        fPublicTorrentLocation = [path retain];
1634   
1635    fDownloadFolder = downloadFolder ? downloadFolder : [fDefaults stringForKey: @"DownloadFolder"];
1636    fDownloadFolder = [[fDownloadFolder stringByExpandingTildeInPath] retain];
1637   
1638    fUseIncompleteFolder = useIncompleteFolder ? [useIncompleteFolder boolValue]
1639                                : [fDefaults boolForKey: @"UseIncompleteDownloadFolder"];
1640    if (fUseIncompleteFolder)
1641    {
1642        fIncompleteFolder = incompleteFolder ? incompleteFolder : [fDefaults stringForKey: @"IncompleteDownloadFolder"];
1643        fIncompleteFolder = [[fIncompleteFolder stringByExpandingTildeInPath] retain];
1644    }
1645   
1646    if (torrentStruct)
1647    {
1648        fHandle = torrentStruct;
1649        fInfo = tr_torrentInfo(fHandle);
1650       
1651        NSString * currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: fInfo->name]]
1652                                                ? fIncompleteFolder : fDownloadFolder;
1653        tr_torrentSetDownloadDir(fHandle, [currentDownloadFolder UTF8String]);
1654    }
1655    else
1656    {
1657        //set libtransmission settings for initialization
1658        tr_ctor * ctor = tr_ctorNew(lib);
1659        tr_ctorSetPaused(ctor, TR_FORCE, YES);
1660        tr_ctorSetPeerLimit(ctor, TR_FALLBACK, [fDefaults integerForKey: @"PeersTorrent"]);
1661       
1662        tr_info info;
1663        if (hashString)
1664        {
1665            tr_ctorSetMetainfoFromHash(ctor, [hashString UTF8String]);
1666            if (tr_torrentParse(lib, ctor, &info) == TR_OK)
1667            {
1668                NSString * currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: info.name]]
1669                                                    ? fIncompleteFolder : fDownloadFolder;
1670                tr_ctorSetDownloadDir(ctor, TR_FORCE, [currentDownloadFolder UTF8String]);
1671               
1672                fHandle = tr_torrentNew(lib, ctor, NULL);
1673            }
1674            tr_metainfoFree(&info);
1675        }
1676        if (!fHandle && path)
1677        {
1678            tr_ctorSetMetainfoFromFile(ctor, [path UTF8String]);
1679            if (tr_torrentParse(lib, ctor, &info) == TR_OK)
1680            {
1681                NSString * currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: info.name]]
1682                                                    ? fIncompleteFolder : fDownloadFolder;
1683                tr_ctorSetDownloadDir(ctor, TR_FORCE, [currentDownloadFolder UTF8String]);
1684               
1685                fHandle = tr_torrentNew(lib, ctor, NULL);
1686            }
1687            tr_metainfoFree(&info);
1688        }
1689       
1690        tr_ctorFree(ctor);
1691       
1692        if (!fHandle)
1693        {
1694            [self release];
1695            return nil;
1696        }
1697       
1698        fInfo = tr_torrentInfo(fHandle);
1699    }
1700   
1701    tr_torrentSetCompletenessCallback(fHandle, completenessChangeCallback, self);
1702   
1703    fNameString = [[NSString alloc] initWithUTF8String: fInfo->name];
1704    fHashString = [[NSString alloc] initWithUTF8String: fInfo->hashString];
1705       
1706    fRatioSetting = ratioSetting ? [ratioSetting intValue] : NSMixedState;
1707    fRatioLimit = ratioLimit ? [ratioLimit floatValue] : [fDefaults floatForKey: @"RatioLimit"];
1708    fFinishedSeeding = NO;
1709   
1710    fWaitToStart = waitToStart && [waitToStart boolValue];
1711    fResumeOnWake = NO;
1712   
1713    fOrderValue = orderValue ? [orderValue intValue] : tr_sessionCountTorrents(lib) - 1;
1714    fGroupValue = groupValue ? [groupValue intValue] : [[GroupsController groups] groupIndexForTorrent: self];
1715   
1716    fAddedTrackers = addedTrackers ? [addedTrackers boolValue] : NO;
1717   
1718    [self createFileList];
1719   
1720    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(checkGroupValueForRemoval:)
1721        name: @"GroupValueRemoved" object: nil];
1722   
1723    [self update];
1724   
1725    //mark incomplete files to be ignored by Time Machine
1726    [self setTimeMachineExclude: ![self allDownloaded] forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
1727   
1728    return self;
1729}
1730
1731- (void) createFileList
1732{
1733    if ([self isFolder])
1734    {
1735        NSInteger count = [self fileCount];
1736        NSMutableArray * fileList = [[NSMutableArray alloc] initWithCapacity: count],
1737                    * flatFileList = [[NSMutableArray alloc] initWithCapacity: count];
1738       
1739        for (NSInteger i = 0; i < count; i++)
1740        {
1741            tr_file * file = &fInfo->files[i];
1742           
1743            NSMutableArray * pathComponents = [[[NSString stringWithUTF8String: file->name] pathComponents] mutableCopy];
1744            NSString * path = [pathComponents objectAtIndex: 0];
1745            NSString * name = [pathComponents objectAtIndex: 1];
1746            [pathComponents removeObjectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, 2)]];
1747           
1748            if ([pathComponents count] > 0)
1749            {
1750                //determine if folder node already exists
1751                NSEnumerator * enumerator = [fileList objectEnumerator];
1752                FileListNode * node;
1753                while ((node = [enumerator nextObject]))
1754                    if ([[node name] isEqualToString: name] && [node isFolder])
1755                        break;
1756               
1757                if (!node)
1758                {
1759                    node = [[FileListNode alloc] initWithFolderName: name path: path];
1760                    [fileList addObject: node];
1761                    [node release];
1762                }
1763               
1764                [node insertIndex: i withSize: file->length];
1765                [self insertPath: pathComponents forParent: node fileSize: file->length index: i flatList: flatFileList];
1766            }
1767            else
1768            {
1769                FileListNode * node = [[FileListNode alloc] initWithFileName: name path: path size: file->length index: i];
1770                [fileList addObject: node];
1771                [flatFileList addObject: node];
1772                [node release];
1773            }
1774           
1775            [pathComponents release];
1776        }
1777       
1778        fFileList = [[NSArray alloc] initWithArray: fileList];
1779        [fileList release];
1780       
1781        fFlatFileList = [[NSArray alloc] initWithArray: flatFileList];
1782        [flatFileList release];
1783    }
1784    else
1785    {
1786        FileListNode * node = [[FileListNode alloc] initWithFileName: [self name] path: @"" size: [self size] index: 0];
1787        fFileList = [[NSArray arrayWithObject: node] retain];
1788        fFlatFileList = [fFileList copy];
1789        [node release];
1790    }
1791}
1792
1793- (void) insertPath: (NSMutableArray *) components forParent: (FileListNode *) parent fileSize: (uint64_t) size
1794    index: (NSInteger) index flatList: (NSMutableArray *) flatFileList
1795{
1796    NSString * name = [components objectAtIndex: 0];
1797    BOOL isFolder = [components count] > 1;
1798   
1799    FileListNode * node = nil;
1800    if (isFolder)
1801    {
1802        NSEnumerator * enumerator = [[parent children] objectEnumerator];
1803        while ((node = [enumerator nextObject]))
1804            if ([[node name] isEqualToString: name] && [node isFolder])
1805                break;
1806    }
1807   
1808    //create new folder or file if it doesn't already exist
1809    if (!node)
1810    {
1811        if (isFolder)
1812            node = [[FileListNode alloc] initWithFolderName: name path: [parent fullPath]];
1813        else
1814        {
1815            node = [[FileListNode alloc] initWithFileName: name path: [parent fullPath] size: size index: index];
1816            [flatFileList addObject: node];
1817        }
1818       
1819        [parent insertChild: node];
1820        [node release];
1821    }
1822   
1823    if (isFolder)
1824    {
1825        [node insertIndex: index withSize: size];
1826       
1827        [components removeObjectAtIndex: 0];
1828        [self insertPath: components forParent: node fileSize: size index: index flatList: flatFileList];
1829    }
1830}
1831
1832- (BOOL) shouldUseIncompleteFolderForName: (NSString *) name
1833{
1834    return fUseIncompleteFolder &&
1835        ![[NSFileManager defaultManager] fileExistsAtPath: [fDownloadFolder stringByAppendingPathComponent: name]];
1836}
1837
1838- (void) updateDownloadFolder
1839{
1840    //remove old Time Machine location
1841    [self setTimeMachineExclude: NO forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
1842   
1843    NSString * folder = [self shouldUseIncompleteFolderForName: [self name]] ? fIncompleteFolder : fDownloadFolder;
1844    tr_torrentSetDownloadDir(fHandle, [folder UTF8String]);
1845   
1846    [self setTimeMachineExclude: ![self allDownloaded] forPath: [folder stringByAppendingPathComponent: [self name]]];
1847}
1848
1849//status has been retained
1850- (void) completenessChange: (NSNumber *) status
1851{
1852    fStat = tr_torrentStat(fHandle); //don't call update yet to avoid auto-stop
1853   
1854    BOOL canMove;
1855    switch ([status intValue])
1856    {
1857        case TR_SEED:
1858        case TR_PARTIAL_SEED:
1859            canMove = YES;
1860           
1861            //move file from incomplete folder to download folder
1862            if (fUseIncompleteFolder && ![[self downloadFolder] isEqualToString: fDownloadFolder]
1863                && (canMove = [self alertForMoveFolderAvailable]))
1864            {
1865                [self quickPause];
1866               
1867                if ([[NSFileManager defaultManager] movePath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]
1868                                        toPath: [fDownloadFolder stringByAppendingPathComponent: [self name]] handler: nil])
1869                    [self updateDownloadFolder];
1870                else
1871                    canMove = NO;
1872               
1873                [self endQuickPause];
1874            }
1875           
1876            if (!canMove)
1877            {
1878                fUseIncompleteFolder = NO;
1879               
1880                [fDownloadFolder release];
1881                fDownloadFolder = fIncompleteFolder;
1882                fIncompleteFolder = nil;
1883            }
1884           
1885            //allow to be backed up by Time Machine
1886            [self setTimeMachineExclude: NO forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
1887           
1888            [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedDownloading" object: self];
1889            break;
1890       
1891        case TR_LEECH:
1892            //do not allow to be backed up by Time Machine
1893            [self setTimeMachineExclude: YES forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
1894           
1895            [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentRestartedDownloading" object: self];
1896            break;
1897    }
1898    [status release];
1899   
1900    [self update];
1901}
1902
1903- (void) quickPause
1904{
1905    if (fQuickPauseDict)
1906        return;
1907
1908    fQuickPauseDict = [[NSDictionary alloc] initWithObjectsAndKeys:
1909                    [NSNumber numberWithInt: [self speedMode: YES]], @"UploadSpeedMode",
1910                    [NSNumber numberWithInt: [self speedLimit: YES]], @"UploadSpeedLimit",
1911                    [NSNumber numberWithInt: [self speedMode: NO]], @"DownloadSpeedMode",
1912                    [NSNumber numberWithInt: [self speedLimit: NO]], @"DownloadSpeedLimit", nil];
1913   
1914    [self setSpeedMode: TR_SPEEDLIMIT_SINGLE upload: YES];
1915    [self setSpeedLimit: 0 upload: YES];
1916    [self setSpeedMode: TR_SPEEDLIMIT_SINGLE upload: NO];
1917    [self setSpeedLimit: 0 upload: NO];
1918}
1919
1920- (void) endQuickPause
1921{
1922    if (!fQuickPauseDict)
1923        return;
1924   
1925    [self setSpeedMode: [[fQuickPauseDict objectForKey: @"UploadSpeedMode"] intValue] upload: YES];
1926    [self setSpeedLimit: [[fQuickPauseDict objectForKey: @"UploadSpeedLimit"] intValue] upload: YES];
1927    [self setSpeedMode: [[fQuickPauseDict objectForKey: @"DownloadSpeedMode"] intValue] upload: NO];
1928    [self setSpeedLimit: [[fQuickPauseDict objectForKey: @"DownloadSpeedLimit"] intValue] upload: NO];
1929   
1930    [fQuickPauseDict release];
1931    fQuickPauseDict = nil;
1932}
1933
1934- (NSString *) etaString: (NSInteger) eta
1935{
1936    switch (eta)
1937    {
1938        case TR_ETA_NOT_AVAIL:
1939        case TR_ETA_UNKNOWN:
1940            return NSLocalizedString(@"remaining time unknown", "Torrent -> eta string");
1941        default:
1942            return [NSString stringWithFormat: NSLocalizedString(@"%@ remaining", "Torrent -> eta string"),
1943                        [NSString timeString: eta showSeconds: YES maxFields: 2]];
1944    }
1945}
1946
1947- (void) updateAllTrackers: (NSMutableArray *) trackers
1948{
1949    //get count
1950    NSInteger count = 0;
1951    NSEnumerator * enumerator = [trackers objectEnumerator];
1952    id object;
1953    while ((object = [enumerator nextObject]))
1954        if (![object isKindOfClass: [NSNumber class]])
1955            count++;
1956   
1957    //recreate the tracker structure
1958    tr_tracker_info * trackerStructs = tr_new(tr_tracker_info, count);
1959    NSInteger tier = 0, i = 0;
1960    enumerator = [trackers objectEnumerator];
1961    while ((object = [enumerator nextObject]))
1962    {
1963        if (![object isKindOfClass: [NSNumber class]])
1964        {
1965            trackerStructs[i].tier = tier;
1966            trackerStructs[i].announce = (char *)[object UTF8String];
1967            i++;
1968        }
1969        else
1970            tier++;
1971    }
1972   
1973    tr_torrentSetAnnounceList(fHandle, trackerStructs, count);
1974    tr_free(trackerStructs);
1975}
1976
1977+ (void) trashFile: (NSString *) path
1978{
1979    //attempt to move to trash
1980    if (![[NSWorkspace sharedWorkspace] performFileOperation: NSWorkspaceRecycleOperation
1981        source: [path stringByDeletingLastPathComponent] destination: @""
1982        files: [NSArray arrayWithObject: [path lastPathComponent]] tag: nil])
1983    {
1984        //if cannot trash, just delete it (will work if it's on a remote volume)
1985        if ([NSApp isOnLeopardOrBetter])
1986        {
1987            NSError * error;
1988            if (![[NSFileManager defaultManager] removeItemAtPath: path error: &error])
1989                NSLog(@"Could not trash %@: %@", path, [error localizedDescription]);
1990        }
1991        else
1992        {
1993            if (![[NSFileManager defaultManager] removeFileAtPath: path handler: nil])
1994                NSLog(@"Could not trash %@", path);
1995        }
1996    }
1997}
1998
1999- (void) setTimeMachineExclude: (BOOL) exclude forPath: (NSString *) path
2000{
2001    if ([NSApp isOnLeopardOrBetter])
2002        CSBackupSetItemExcluded((CFURLRef)[NSURL fileURLWithPath: path], exclude, true);
2003}
2004
2005@end
Note: See TracBrowser for help on using the repository browser.