source: trunk/macosx/Torrent.m @ 6265

Last change on this file since 6265 was 6265, checked in by livings124, 14 years ago

trivial changes to sorting by state and other miscellaneous changes

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