source: trunk/macosx/Torrent.m @ 3211

Last change on this file since 3211 was 3211, checked in by livings124, 15 years ago

streamline display string code a little more

  • Property svn:keywords set to Date Rev Author Id
File size: 53.8 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 3211 2007-09-28 02:58:25Z livings124 $
3 *
4 * Copyright (c) 2006-2007 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 "NSStringAdditions.h"
27
28static int static_lastid = 0;
29
30@interface Torrent (Private)
31
32- (id) initWithHash: (NSString *) hashString path: (NSString *) path lib: (tr_handle *) lib
33        publicTorrent: (NSNumber *) publicTorrent
34        downloadFolder: (NSString *) downloadFolder
35        useIncompleteFolder: (NSNumber *) useIncompleteFolder incompleteFolder: (NSString *) incompleteFolder
36        dateAdded: (NSDate *) dateAdded dateCompleted: (NSDate *) dateCompleted
37        dateActivity: (NSDate *) dateActivity
38        ratioSetting: (NSNumber *) ratioSetting ratioLimit: (NSNumber *) ratioLimit
39                pex: (NSNumber *) pex
40        waitToStart: (NSNumber *) waitToStart orderValue: (NSNumber *) orderValue;
41
42- (BOOL) shouldUseIncompleteFolderForName: (NSString *) name;
43- (void) updateDownloadFolder;
44
45- (void) createFileList;
46- (void) insertPath: (NSMutableArray *) components forSiblings: (NSMutableArray *) siblings
47            withParent: (NSMutableDictionary *) parent previousPath: (NSString *) previousPath
48            flatList: (NSMutableArray *) flatList fileSize: (uint64_t) size index: (int) index;
49
50- (void) quickPause;
51- (void) endQuickPause;
52
53- (void) trashFile: (NSString *) path;
54
55@end
56
57@implementation Torrent
58
59- (id) initWithPath: (NSString *) path location: (NSString *) location deleteTorrentFile: (torrentFileState) torrentDelete
60        lib: (tr_handle *) lib
61{
62    self = [self initWithHash: nil path: path lib: lib
63            publicTorrent: torrentDelete != TORRENT_FILE_DEFAULT
64                            ? [NSNumber numberWithBool: torrentDelete == TORRENT_FILE_SAVE] : nil
65            downloadFolder: location
66            useIncompleteFolder: nil incompleteFolder: nil
67            dateAdded: nil dateCompleted: nil
68            dateActivity: nil
69            ratioSetting: nil ratioLimit: nil
70                        pex: nil
71            waitToStart: nil orderValue: nil];
72   
73    if (self)
74    {
75        if (!fPublicTorrent)
76            [self trashFile: path];
77    }
78    return self;
79}
80
81- (id) initWithHistory: (NSDictionary *) history lib: (tr_handle *) lib
82{
83    self = [self initWithHash: [history objectForKey: @"TorrentHash"]
84                path: [history objectForKey: @"TorrentPath"] lib: lib
85                publicTorrent: [history objectForKey: @"PublicCopy"]
86                downloadFolder: [history objectForKey: @"DownloadFolder"]
87                useIncompleteFolder: [history objectForKey: @"UseIncompleteFolder"]
88                incompleteFolder: [history objectForKey: @"IncompleteFolder"]
89                dateAdded: [history objectForKey: @"Date"]
90                                dateCompleted: [history objectForKey: @"DateCompleted"]
91                dateActivity: [history objectForKey: @"DateActivity"]
92                ratioSetting: [history objectForKey: @"RatioSetting"]
93                ratioLimit: [history objectForKey: @"RatioLimit"]
94                                pex: [history objectForKey: @"Pex"]
95                waitToStart: [history objectForKey: @"WaitToStart"]
96                orderValue: [history objectForKey: @"OrderValue"]];
97   
98    if (self)
99    {
100        //start transfer
101        NSNumber * active;
102        if ((active = [history objectForKey: @"Active"]) && [active boolValue])
103        {
104            fStat = tr_torrentStat(fHandle);
105            [self startTransfer];
106        }
107    }
108    return self;
109}
110
111- (NSDictionary *) history
112{
113    NSMutableDictionary * history = [NSMutableDictionary dictionaryWithObjectsAndKeys:
114                    [NSNumber numberWithBool: fPublicTorrent], @"PublicCopy",
115                    [self hashString], @"TorrentHash",
116                    fDownloadFolder, @"DownloadFolder",
117                    [NSNumber numberWithBool: fUseIncompleteFolder], @"UseIncompleteFolder",
118                    [NSNumber numberWithBool: [self isActive]], @"Active",
119                    fDateAdded, @"Date",
120                    [NSNumber numberWithInt: fRatioSetting], @"RatioSetting",
121                    [NSNumber numberWithFloat: fRatioLimit], @"RatioLimit",
122                    [NSNumber numberWithBool: fWaitToStart], @"WaitToStart",
123                    [self orderValue], @"OrderValue", nil];
124   
125    if (fIncompleteFolder)
126        [history setObject: fIncompleteFolder forKey: @"IncompleteFolder"];
127
128    if (fPublicTorrent)
129        [history setObject: [self publicTorrentLocation] forKey: @"TorrentPath"];
130       
131        if (![self privateTorrent])
132                [history setObject: [NSNumber numberWithBool: fPex] forKey: @"Pex"];
133       
134        if (fDateCompleted)
135                [history setObject: fDateCompleted forKey: @"DateCompleted"];
136   
137    NSDate * dateActivity = [self dateActivity];
138    if (dateActivity)
139                [history setObject: dateActivity forKey: @"DateActivity"];
140       
141    return history;
142}
143
144- (void) dealloc
145{
146    if (fileStat)
147        tr_torrentFilesFree(fileStat, [self fileCount]);
148   
149    [fDownloadFolder release];
150    [fIncompleteFolder release];
151   
152    [fPublicTorrentLocation release];
153   
154    [fDateAdded release];
155    [fDateCompleted release];
156    [fDateActivity release];
157   
158    [fIcon release];
159   
160    [fFileList release];
161    [fFlatFileList release];
162   
163    [fFileMenu release];
164   
165    [fQuickPauseDict release];
166   
167    [super dealloc];
168}
169
170- (void) closeTorrent
171{
172    tr_torrentClose(fHandle);
173}
174
175- (void) closeRemoveTorrent
176{
177    tr_torrentRemoveSaved(fHandle);
178    [self closeTorrent];
179}
180
181- (void) changeIncompleteDownloadFolder: (NSString *) folder
182{
183    fUseIncompleteFolder = folder != nil;
184   
185    [fIncompleteFolder release];
186    fIncompleteFolder = fUseIncompleteFolder ? [folder retain] : nil;
187   
188    [self updateDownloadFolder];
189}
190
191- (void) changeDownloadFolder: (NSString *) folder
192{
193    [fDownloadFolder release];
194    fDownloadFolder = [folder retain];
195   
196    [self updateDownloadFolder];
197}
198
199- (NSString *) downloadFolder
200{
201    return [NSString stringWithUTF8String: tr_torrentGetFolder(fHandle)];
202}
203
204- (void) getAvailability: (int8_t *) tab size: (int) size
205{
206    tr_torrentAvailability(fHandle, tab, size);
207}
208
209- (void) getAmountFinished: (float *) tab size: (int) size
210{
211    tr_torrentAmountFinished(fHandle, tab, size);
212}
213
214- (void) update
215{
216    fStat = tr_torrentStat(fHandle);
217   
218    //notification when downloading finished
219    if (tr_getComplete(fHandle) || tr_getDone(fHandle))
220    {
221        BOOL canMove = YES;
222       
223        //move file from incomplete folder to download folder
224        if (fUseIncompleteFolder && ![[self downloadFolder] isEqualToString: fDownloadFolder]
225            && (canMove = [self alertForMoveFolderAvailable]))
226        {
227            [self quickPause];
228           
229            if ([[NSFileManager defaultManager] movePath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]
230                                    toPath: [fDownloadFolder stringByAppendingPathComponent: [self name]] handler: nil])
231                [self updateDownloadFolder];
232            else
233                canMove = NO;
234           
235            [self endQuickPause];
236        }
237       
238        if (!canMove)
239        {
240            fUseIncompleteFolder = NO;
241           
242            [fDownloadFolder release];
243            fDownloadFolder = fIncompleteFolder;
244            fIncompleteFolder = nil;
245        }
246               
247                [fDateCompleted release];
248                fDateCompleted = [[NSDate alloc] init];
249       
250        fStat = tr_torrentStat(fHandle);
251        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedDownloading" object: self];
252    }
253    else if (tr_getIncomplete(fHandle))
254        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentRestartedDownloading" object: self];
255    else;
256   
257    //check to stop for ratio
258    float stopRatio;
259    if ([self isSeeding] && (stopRatio = [self actualStopRatio]) != INVALID && [self ratio] >= stopRatio)
260    {
261        [self stopTransfer];
262        fStat = tr_torrentStat(fHandle);
263       
264        fFinishedSeeding = YES;
265       
266        [self setRatioSetting: NSOffState];
267        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentStoppedForRatio" object: self];
268    }
269
270    BOOL wasChecking = fChecking;
271    fChecking = fStat->status == TR_STATUS_CHECK || fStat->status == TR_STATUS_CHECK_WAIT;
272   
273    //check for error
274    BOOL wasError = fError;
275    fError = [self isError];
276   
277    //check if stalled
278    BOOL wasStalled = fStalled;
279    fStalled = [self isActive] && [fDefaults boolForKey: @"CheckStalled"]
280                && [fDefaults integerForKey: @"StalledMinutes"] < [self stalledMinutes];
281   
282    //update queue for checking (from downloading to seeding), stalled, or error
283    if ((wasChecking && !fChecking) || (!wasStalled && fStalled) || (!wasError && fError && [self isActive]))
284        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
285}
286
287- (void) startTransfer
288{
289    fWaitToStart = NO;
290    fFinishedSeeding = NO;
291   
292    if (![self isActive] && [self alertForFolderAvailable] && [self alertForRemainingDiskSpace])
293    {
294        tr_torrentStart(fHandle);
295        [self update];
296    }
297}
298
299- (void) stopTransfer
300{
301    fWaitToStart = NO;
302   
303    if ([self isActive])
304    {
305        tr_torrentStop(fHandle);
306        [self update];
307       
308        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
309    }
310}
311
312- (void) sleep
313{
314    if ((fResumeOnWake = [self isActive]))
315        tr_torrentStop(fHandle);
316}
317
318- (void) wakeUp
319{
320    if (fResumeOnWake)
321        tr_torrentStart(fHandle);
322}
323
324- (void) manualAnnounce
325{
326    tr_manualUpdate(fHandle);
327}
328
329- (BOOL) canManualAnnounce
330{
331    return tr_torrentCanManualUpdate(fHandle);
332}
333
334- (void) resetCache
335{
336    tr_torrentRecheck(fHandle);
337    [self update];
338}
339
340- (float) ratio
341{
342    return fStat->ratio;
343}
344
345- (int) ratioSetting
346{
347    return fRatioSetting;
348}
349
350- (void) setRatioSetting: (int) setting
351{
352    fRatioSetting = setting;
353}
354
355- (float) ratioLimit
356{
357    return fRatioLimit;
358}
359
360- (void) setRatioLimit: (float) limit
361{
362    if (limit >= 0)
363        fRatioLimit = limit;
364}
365
366- (float) actualStopRatio
367{
368    if (fRatioSetting == NSOnState)
369        return fRatioLimit;
370    else if (fRatioSetting == NSMixedState && [fDefaults boolForKey: @"RatioCheck"])
371        return [fDefaults floatForKey: @"RatioLimit"];
372    else
373        return INVALID;
374}
375
376- (float) progressStopRatio
377{
378    float stopRatio, ratio;
379    if ((stopRatio = [self actualStopRatio]) == INVALID || (ratio = [self ratio]) >= stopRatio)
380        return 1.0;
381    else if (ratio > 0 && stopRatio > 0)
382        return ratio / stopRatio;
383    else
384        return 0;
385}
386
387- (tr_speedlimit) speedMode: (BOOL) upload
388{
389    return tr_torrentGetSpeedMode(fHandle, upload ? TR_UP : TR_DOWN);
390}
391
392- (void) setSpeedMode: (tr_speedlimit) mode upload: (BOOL) upload
393{
394    tr_torrentSetSpeedMode(fHandle, upload ? TR_UP : TR_DOWN, mode);
395}
396
397- (int) speedLimit: (BOOL) upload
398{
399    return tr_torrentGetSpeedLimit(fHandle, upload ? TR_UP : TR_DOWN);
400}
401
402- (void) setSpeedLimit: (int) limit upload: (BOOL) upload
403{
404    tr_torrentSetSpeedLimit(fHandle, upload ? TR_UP : TR_DOWN, limit);
405}
406
407- (void) setWaitToStart: (BOOL) wait
408{
409    fWaitToStart = wait;
410}
411
412- (BOOL) waitingToStart
413{
414    return fWaitToStart;
415}
416
417- (void) revealData
418{
419    [[NSWorkspace sharedWorkspace] selectFile: [self dataLocation] inFileViewerRootedAtPath: nil];
420}
421
422- (void) revealPublicTorrent
423{
424    if (fPublicTorrent)
425        [[NSWorkspace sharedWorkspace] selectFile: fPublicTorrentLocation inFileViewerRootedAtPath: nil];
426}
427
428- (void) trashData
429{
430    [self trashFile: [self dataLocation]];
431}
432
433- (void) trashTorrent
434{
435    if (fPublicTorrent)
436        [self trashFile: [self publicTorrentLocation]];
437}
438
439- (void) moveTorrentDataFileTo: (NSString *) folder
440{
441    NSString * oldFolder = [self downloadFolder];
442    if (![oldFolder isEqualToString: folder] || ![fDownloadFolder isEqualToString: folder])
443    {
444        //check if moving inside itself
445        NSArray * oldComponents = [oldFolder pathComponents],
446                * newComponents = [folder pathComponents];
447        int count;
448       
449        if ((count = [oldComponents count]) < [newComponents count]
450                && [[newComponents objectAtIndex: count] isEqualToString: [self name]]
451                && [oldComponents isEqualToArray:
452                        [newComponents objectsAtIndexes: [NSIndexSet indexSetWithIndexesInRange: NSMakeRange(0, count)]]])
453        {
454            NSAlert * alert = [[NSAlert alloc] init];
455            [alert setMessageText: NSLocalizedString(@"A folder cannot be moved to inside itself.",
456                                                        "Move inside itself alert -> title")];
457            [alert setInformativeText: [NSString stringWithFormat:
458                            NSLocalizedString(@"The move operation of \"%@\" cannot be done.",
459                                                "Move inside itself alert -> message"), [self name]]];
460            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move inside itself alert -> button")];
461           
462            [alert runModal];
463            [alert release];
464           
465            return;
466        }
467       
468        [self quickPause];
469       
470        if ([[NSFileManager defaultManager] movePath: [oldFolder stringByAppendingPathComponent: [self name]]
471                            toPath: [folder stringByAppendingPathComponent: [self name]] handler: nil])
472        {
473            //get rid of both incomplete folder and old download folder, even if move failed
474            fUseIncompleteFolder = NO;
475            if (fIncompleteFolder)
476            {
477                [fIncompleteFolder release];
478                fIncompleteFolder = nil;
479            }
480            [self changeDownloadFolder: folder];
481           
482            [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateInfoSettings" object: nil];
483           
484            [self endQuickPause];
485        }
486        else
487        {
488            [self endQuickPause];
489       
490            NSAlert * alert = [[NSAlert alloc] init];
491            [alert setMessageText: NSLocalizedString(@"There was an error moving the data file.", "Move error alert -> title")];
492            [alert setInformativeText: [NSString stringWithFormat:
493                            NSLocalizedString(@"The move operation of \"%@\" cannot be done.",
494                                                "Move error alert -> message"), [self name]]];
495            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move error alert -> button")];
496           
497            [alert runModal];
498            [alert release];
499        }
500    }
501}
502
503- (void) copyTorrentFileTo: (NSString *) path
504{
505    [[NSFileManager defaultManager] copyPath: [self torrentLocation] toPath: path handler: nil];
506}
507
508- (BOOL) alertForRemainingDiskSpace
509{
510    if ([self allDownloaded] || ![fDefaults boolForKey: @"WarningRemainingSpace"])
511        return YES;
512   
513    NSString * volumeName;
514    if ((volumeName = [[[NSFileManager defaultManager] componentsToDisplayForPath: [self downloadFolder]] objectAtIndex: 0]))
515    {
516        NSDictionary * systemAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath: [self downloadFolder]];
517        uint64_t remainingSpace = [[systemAttributes objectForKey: NSFileSystemFreeSize] unsignedLongLongValue];
518       
519        uint64_t existingSize = 0;
520        NSDirectoryEnumerator * enumerator;
521        if ((enumerator = [[NSFileManager defaultManager] enumeratorAtPath:
522                    [[self downloadFolder] stringByAppendingPathComponent: [self name]]]))
523        {
524            NSDictionary * fileAttributes;
525            while ([enumerator nextObject])
526            {
527                fileAttributes = [enumerator fileAttributes];
528                if (![[fileAttributes objectForKey: NSFileType] isEqualTo: NSFileTypeDirectory])
529                    existingSize += [[fileAttributes objectForKey: NSFileSize] unsignedLongLongValue];
530            }
531        }
532       
533        #warning factor in checked files
534        if (remainingSpace + existingSize <= [self size])
535        {
536            NSAlert * alert = [[NSAlert alloc] init];
537            [alert setMessageText: [NSString stringWithFormat:
538                                    NSLocalizedString(@"Not enough remaining disk space to download \"%@\" completely.",
539                                        "Torrent file disk space alert -> title"), [self name]]];
540            [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"The transfer will be paused."
541                                        " Clear up space on %@ or deselect files in the torrent inspector to continue.",
542                                        "Torrent file disk space alert -> message"), volumeName]];
543            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file disk space alert -> button")];
544            [alert addButtonWithTitle: NSLocalizedString(@"Download Anyway", "Torrent file disk space alert -> button")];
545            [alert addButtonWithTitle: NSLocalizedString(@"Always Download", "Torrent file disk space alert -> button")];
546           
547            int result = [alert runModal];
548            [alert release];
549           
550            if (result == NSAlertThirdButtonReturn)
551                [fDefaults setBool: NO forKey: @"WarningRemainingSpace"];
552           
553            return result != NSAlertFirstButtonReturn;
554        }
555    }
556    return YES;
557}
558
559- (BOOL) alertForFolderAvailable
560{
561    if (access(tr_torrentGetFolder(fHandle), 0))
562    {
563        NSAlert * alert = [[NSAlert alloc] init];
564        [alert setMessageText: [NSString stringWithFormat:
565                                NSLocalizedString(@"The folder for downloading \"%@\" cannot be used.",
566                                    "Folder cannot be used alert -> title"), [self name]]];
567        [alert setInformativeText: [NSString stringWithFormat:
568                        NSLocalizedString(@"\"%@\" cannot be used. The transfer will be paused.",
569                                            "Folder cannot be used alert -> message"), [self downloadFolder]]];
570        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Folder cannot be used alert -> button")];
571        [alert addButtonWithTitle: [NSLocalizedString(@"Choose New Location",
572                                    "Folder cannot be used alert -> location button") stringByAppendingEllipsis]];
573       
574        if ([alert runModal] != NSAlertFirstButtonReturn)
575        {
576            NSOpenPanel * panel = [NSOpenPanel openPanel];
577           
578            [panel setPrompt: NSLocalizedString(@"Select", "Folder cannot be used alert -> prompt")];
579            [panel setAllowsMultipleSelection: NO];
580            [panel setCanChooseFiles: NO];
581            [panel setCanChooseDirectories: YES];
582            [panel setCanCreateDirectories: YES];
583
584            [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the download folder for \"%@\"",
585                                "Folder cannot be used alert -> select destination folder"), [self name]]];
586           
587            [[NSNotificationCenter defaultCenter] postNotificationName: @"MakeWindowKey" object: nil];
588            [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: [NSApp keyWindow] modalDelegate: self
589                    didEndSelector: @selector(destinationChoiceClosed:returnCode:contextInfo:) contextInfo: nil];
590        }
591       
592        [alert release];
593       
594        return NO;
595    }
596   
597    return YES;
598}
599
600- (void) destinationChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) context
601{
602    if (code != NSOKButton)
603        return;
604   
605    NSString * folder = [[openPanel filenames] objectAtIndex: 0];
606    if (fUseIncompleteFolder)
607        [self changeDownloadFolder: folder];
608    else
609        [self changeDownloadFolder: folder];
610   
611    [self startTransfer];
612    [self update];
613   
614    [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateInfoSettings" object: nil];
615}
616
617- (BOOL) alertForMoveFolderAvailable
618{
619    if (access([fDownloadFolder UTF8String], 0))
620    {
621        NSAlert * alert = [[NSAlert alloc] init];
622        [alert setMessageText: [NSString stringWithFormat:
623                                NSLocalizedString(@"The folder for moving the completed \"%@\" cannot be used.",
624                                    "Move folder cannot be used alert -> title"), [self name]]];
625        [alert setInformativeText: [NSString stringWithFormat:
626                                NSLocalizedString(@"\"%@\" cannot be used. The file will remain in its current location.",
627                                    "Move folder cannot be used alert -> message"), fDownloadFolder]];
628        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move folder cannot be used alert -> button")];
629       
630        [alert runModal];
631        [alert release];
632       
633        return NO;
634    }
635   
636    return YES;
637}
638
639- (NSImage *) icon
640{
641    if (!fIcon)
642    {
643        fIcon = [[[NSWorkspace sharedWorkspace] iconForFileType: fInfo->multifile ? NSFileTypeForHFSTypeCode('fldr')
644                                                : [[self name] pathExtension]] retain];
645        [fIcon setFlipped: YES];
646    }
647    return fIcon;
648}
649
650- (NSString *) name
651{
652    return [NSString stringWithUTF8String: fInfo->name];
653}
654
655- (uint64_t) size
656{
657    return fInfo->totalSize;
658}
659
660- (NSString *) trackerAddress
661{
662    return [NSString stringWithFormat: @"http://%s:%d", fStat->tracker->address, fStat->tracker->port];
663}
664
665- (NSString *) trackerAddressAnnounce
666{
667    return [NSString stringWithUTF8String: fStat->tracker->announce];
668}
669
670- (NSString *) comment
671{
672    return [NSString stringWithUTF8String: fInfo->comment];
673}
674
675- (NSString *) creator
676{
677    return [NSString stringWithUTF8String: fInfo->creator];
678}
679
680- (NSDate *) dateCreated
681{
682    int date = fInfo->dateCreated;
683    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
684}
685
686- (int) pieceSize
687{
688    return fInfo->pieceSize;
689}
690
691- (int) pieceCount
692{
693    return fInfo->pieceCount;
694}
695
696- (NSString *) hashString
697{
698    return [NSString stringWithUTF8String: fInfo->hashString];
699}
700
701- (BOOL) privateTorrent
702{
703    return TR_FLAG_PRIVATE & fInfo->flags;
704}
705
706- (NSString *) torrentLocation
707{
708    return [NSString stringWithUTF8String: fInfo->torrent];
709}
710
711- (NSString *) publicTorrentLocation
712{
713    return fPublicTorrentLocation;
714}
715
716- (NSString *) dataLocation
717{
718    return [[self downloadFolder] stringByAppendingPathComponent: [self name]];
719}
720
721- (BOOL) publicTorrent
722{
723    return fPublicTorrent;
724}
725
726- (float) progress
727{
728    return fStat->percentComplete;
729}
730
731- (float) progressDone
732{
733    return fStat->percentDone;
734}
735
736- (float) progressLeft
737{//NSLog(@"left %f",(float)fStat->leftUntilDone / [self size]);
738    return (float)fStat->leftUntilDone / [self size];
739}
740
741- (int) eta
742{
743    return fStat->eta;
744}
745
746- (NSString * ) etaString
747{
748    int eta = [self eta];
749    if (eta < 0)
750        return @"";
751   
752    NSString * timeString;
753    if (eta < 60)
754        return [NSString stringWithFormat: NSLocalizedString(@"%d sec", "Torrent -> remaining time"), eta];
755    else if (eta < 3600) //60 * 60
756        return [NSString stringWithFormat: NSLocalizedString(@"%d min %d sec", "Torrent -> remaining time"),
757                                                eta / 60, eta % 60];
758    else if (eta < 86400) //24 * 60 * 60
759        return [NSString stringWithFormat: NSLocalizedString(@"%d hr %d min", "Torrent -> remaining time"),
760                                                eta / 3600, (eta / 60) % 60];
761    else
762    {
763        int days = eta / 86400;
764        if (days > 1)
765            return [NSString stringWithFormat: NSLocalizedString(@"%d days %d hr", "Torrent -> remaining time"),
766                                                    days, (eta / 3600) % 24];
767        else
768            return [NSString stringWithFormat: NSLocalizedString(@"1 day %d hr", "Torrent -> remaining time"),
769                                                    (eta / 3600) % 24];
770    }
771}
772
773- (float) notAvailableDesired
774{//NSLog(@"not available %f", (float)(fStat->desiredSize - fStat->desiredAvailable) / [self size]);
775    return (float)(fStat->desiredSize - fStat->desiredAvailable) / [self size];
776}
777
778- (BOOL) isActive
779{
780    return fStat->status & TR_STATUS_ACTIVE;
781}
782
783- (BOOL) isSeeding
784{
785    return fStat->status == TR_STATUS_SEED || fStat->status == TR_STATUS_DONE;
786}
787
788- (BOOL) isPaused
789{
790    return fStat->status == TR_STATUS_STOPPED;
791}
792
793- (BOOL) isChecking
794{
795    return fStat->status == TR_STATUS_CHECK || fStat->status == TR_STATUS_CHECK_WAIT;
796}
797
798- (BOOL) allDownloaded
799{
800    return fStat->cpStatus != TR_CP_INCOMPLETE;
801}
802
803- (BOOL) isComplete
804{
805    return fStat->cpStatus == TR_CP_COMPLETE;
806}
807
808- (BOOL) isError
809{
810    return fStat->error != 0;
811}
812
813- (NSString *) errorMessage
814{
815    if (![self isError])
816        return @"";
817   
818    NSString * error;
819    if (!(error = [NSString stringWithUTF8String: fStat->errorString])
820        && !(error = [NSString stringWithCString: fStat->errorString encoding: NSISOLatin1StringEncoding]))
821        error = NSLocalizedString(@"(unreadable error)", "Torrent -> error string unreadable");
822   
823    return error;
824}
825
826- (NSArray *) peers
827{
828    int totalPeers, i;
829    tr_peer_stat * peers = tr_torrentPeers(fHandle, &totalPeers);
830   
831    NSMutableArray * peerDics = [NSMutableArray arrayWithCapacity: totalPeers];
832    NSMutableDictionary * dic;
833   
834    tr_peer_stat * peer;
835    for (i = 0; i < totalPeers; i++)
836    {
837        peer = &peers[i];
838       
839        dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:
840            [NSNumber numberWithBool: peer->isConnected], @"Connected",
841            [NSNumber numberWithInt: peer->from], @"From",
842            [NSString stringWithCString: (char *) peer->addr encoding: NSUTF8StringEncoding], @"IP",
843            [NSNumber numberWithInt: peer->port], @"Port", nil];
844       
845        if (peer->isConnected)
846        {
847            [dic setObject: [NSNumber numberWithFloat: peer->progress] forKey: @"Progress"];
848           
849            if (peer->isDownloading)
850                [dic setObject: [NSNumber numberWithFloat: peer->uploadToRate] forKey: @"UL To Rate"];
851            if (peer->isUploading)
852                [dic setObject: [NSNumber numberWithFloat: peer->downloadFromRate] forKey: @"DL From Rate"];
853           
854            [dic setObject: [NSNumber numberWithBool: peer->isEncrypted] forKey: @"Encryption"];
855        }
856       
857        #warning why would connected clients have null value?
858        if (peer->client)
859            [dic setObject: [NSString stringWithCString: (char *) peer->client encoding: NSUTF8StringEncoding] forKey: @"Client"];
860        else
861            [dic setObject: @"" forKey: @"Client"]; //needed to be set here for client sort
862       
863        [peerDics addObject: dic];
864    }
865   
866    tr_torrentPeersFree(peers, totalPeers);
867   
868    return peerDics;
869}
870
871- (NSString *) progressString
872{
873    NSString * string;
874   
875    if (![self allDownloaded])
876    {
877        if ([fDefaults boolForKey: @"DisplayStatusProgressSelected"])
878        {
879            uint64_t have = [self haveTotal];
880            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@ selected (%.2f%%)", "Torrent -> progress string"),
881                            [NSString stringForFileSize: have], [NSString stringForFileSize: have + fStat->leftUntilDone],
882                            100.0 * [self progressDone]];
883        }
884        else
885            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@ (%.2f%%)", "Torrent -> progress string"),
886                            [NSString stringForFileSize: [self haveTotal]],
887                            [NSString stringForFileSize: [self size]], 100.0 * [self progress]];
888    }
889    else if (![self isComplete])
890    {
891        if ([fDefaults boolForKey: @"DisplayStatusProgressSelected"])
892            string = [NSString stringWithFormat: NSLocalizedString(@"%@ selected, uploaded %@ (Ratio: %@)",
893                "Torrent -> progress string"), [NSString stringForFileSize: [self haveTotal]],
894                [NSString stringForFileSize: [self uploadedTotal]], [NSString stringForRatio: [self ratio]]];
895        else
896            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@ (%.2f%%), uploaded %@ (Ratio: %@)",
897                "Torrent -> progress string"), [NSString stringForFileSize: [self haveTotal]],
898                [NSString stringForFileSize: [self size]], 100.0 * [self progress],
899                [NSString stringForFileSize: [self uploadedTotal]], [NSString stringForRatio: [self ratio]]];
900    }
901    else
902        string = [NSString stringWithFormat: NSLocalizedString(@"%@, uploaded %@ (Ratio: %@)", "Torrent -> progress string"),
903                [NSString stringForFileSize: [self size]], [NSString stringForFileSize: [self uploadedTotal]],
904                [NSString stringForRatio: [self ratio]]];
905   
906    //add time when downloading
907    if (fStat->status == TR_STATUS_DOWNLOAD)
908    {
909        string = [self eta] >= 0
910            ? [string stringByAppendingFormat: NSLocalizedString(@" - %@ remaining", "Torrent -> progress string"), [self etaString]]
911            : [string stringByAppendingString: NSLocalizedString(@" - remaining time unknown", "Torrent -> progress string")];
912    }
913   
914    return string;
915}
916
917- (NSString *) statusString
918{
919    NSString * string;
920   
921    if ([self isError])
922    {
923        NSString * errorString = [self errorMessage];
924        if (!errorString || [errorString isEqualToString: @""])
925            string = NSLocalizedString(@"Error", "Torrent -> status string");
926        else
927            string = [NSLocalizedString(@"Error: ", "Torrent -> status string") stringByAppendingString: errorString];
928    }
929    else
930    {
931        switch (fStat->status)
932        {
933            case TR_STATUS_STOPPED:
934                if (fWaitToStart)
935                {
936                    string = ![self allDownloaded]
937                            ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
938                            : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
939                }
940                else if (fFinishedSeeding)
941                    string = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
942                else
943                    string = NSLocalizedString(@"Paused", "Torrent -> status string");
944                break;
945
946            case TR_STATUS_CHECK_WAIT:
947                string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
948                break;
949
950            case TR_STATUS_CHECK:
951                string = [NSString stringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
952                                        "Torrent -> status string"), 100.0 * fStat->recheckProgress];
953                break;
954
955            case TR_STATUS_DOWNLOAD:
956                if ([self totalPeersConnected] != 1)
957                    string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of %d peers",
958                                                    "Torrent -> status string"), [self peersSendingToUs], [self totalPeersConnected]];
959                else
960                    string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of 1 peer",
961                                                    "Torrent -> status string"), [self peersSendingToUs]];
962                break;
963
964            case TR_STATUS_SEED:
965            case TR_STATUS_DONE:
966                if ([self totalPeersConnected] != 1)
967                    string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of %d peers", "Torrent -> status string"),
968                                                    [self peersGettingFromUs], [self totalPeersConnected]];
969                else
970                    string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of 1 peer", "Torrent -> status string"),
971                                                    [self peersGettingFromUs]];
972                break;
973
974            case TR_STATUS_STOPPING:
975                string = [NSLocalizedString(@"Stopping", "Torrent -> status string") stringByAppendingEllipsis];
976                break;
977           
978            default:
979                string = @"";
980        }
981       
982        if (fStalled)
983            string = [NSLocalizedString(@"Stalled, ", "Torrent -> status string") stringByAppendingString: string];
984    }
985   
986    if ([self isActive] && ![self isChecking])
987    {
988        NSString * stringToAppend;
989        if (![self allDownloaded])
990            stringToAppend = [NSString stringWithFormat: NSLocalizedString(@"DL: %@, ", "Torrent -> status string"),
991                                [NSString stringForSpeed: [self downloadRate]]];
992        else
993            stringToAppend = @"";
994       
995        string = [NSString stringWithFormat: @"%@ - %@UL: %@", string, stringToAppend, [NSString stringForSpeed: [self uploadRate]]];
996    }
997   
998    return string;
999}
1000
1001- (NSString *) shortStatusString
1002{
1003    NSString * string;
1004   
1005    switch (fStat->status)
1006    {
1007        case TR_STATUS_STOPPED:
1008            if (fWaitToStart)
1009            {
1010                string = ![self allDownloaded]
1011                        ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
1012                        : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
1013            }
1014            else if (fFinishedSeeding)
1015                string = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
1016            else
1017                string = NSLocalizedString(@"Paused", "Torrent -> status string");
1018            break;
1019
1020        case TR_STATUS_CHECK_WAIT:
1021            string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1022            break;
1023
1024        case TR_STATUS_CHECK:
1025            string = [NSString stringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
1026                                    "Torrent -> status string"), 100.0 * fStat->recheckProgress];
1027            break;
1028
1029        case TR_STATUS_STOPPING:
1030            string = [NSLocalizedString(@"Stopping", "Torrent -> status string") stringByAppendingEllipsis];
1031            break;
1032       
1033        default:
1034            if ([self isActive])
1035            {
1036                if (![self allDownloaded])
1037                    string = [NSString stringWithFormat: NSLocalizedString(@"DL: %@, ", "Torrent -> status string"),
1038                                        [NSString stringForSpeed: [self downloadRate]]];
1039                else
1040                    string = [NSString stringWithFormat: NSLocalizedString(@"Ratio: %@, ", "Torrent -> status string"),
1041                                [NSString stringForRatio: [self ratio]]];
1042               
1043                string = [string stringByAppendingFormat: NSLocalizedString(@"UL: %@", "Torrent -> status string"),
1044                                [NSString stringForSpeed: [self uploadRate]]];
1045            }
1046            else
1047                string = @"";
1048    }
1049   
1050    return string;
1051}
1052
1053- (NSString *) remainingTimeString
1054{
1055    int eta, days;
1056   
1057    NSString * string;
1058    switch (fStat->status)
1059    {
1060        case TR_STATUS_CHECK_WAIT:
1061            string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1062            break;
1063
1064        case TR_STATUS_CHECK:
1065            string = [NSString stringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
1066                                    "Torrent -> status string"), 100.0 * fStat->recheckProgress];
1067            break;
1068
1069        case TR_STATUS_DOWNLOAD:
1070            string = [self eta] >= 0 ? [self etaString] : NSLocalizedString(@"Unknown", "Torrent -> remaining time");
1071            break;
1072       
1073        case TR_STATUS_SEED:
1074        case TR_STATUS_DONE:
1075            string = [NSLocalizedString(@"Ratio: ", "Torrent -> status string") stringByAppendingString:
1076                                                                            [NSString stringForRatio: [self ratio]]];
1077            break;
1078       
1079        default:
1080            string = @"";
1081    }
1082
1083    return string;
1084}
1085
1086- (NSString *) stateString
1087{
1088    switch (fStat->status)
1089    {
1090        case TR_STATUS_STOPPED:
1091            return NSLocalizedString(@"Paused", "Torrent -> status string");
1092            break;
1093
1094        case TR_STATUS_CHECK:
1095            return [NSString stringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
1096                                    "Torrent -> status string"), 100.0 * fStat->recheckProgress];
1097            break;
1098       
1099        case TR_STATUS_CHECK_WAIT:
1100            return [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1101            break;
1102
1103        case TR_STATUS_DOWNLOAD:
1104            return NSLocalizedString(@"Downloading", "Torrent -> status string");
1105            break;
1106
1107        case TR_STATUS_SEED:
1108        case TR_STATUS_DONE:
1109            return NSLocalizedString(@"Seeding", "Torrent -> status string");
1110            break;
1111
1112        case TR_STATUS_STOPPING:
1113            return [NSLocalizedString(@"Stopping", "Torrent -> status string") stringByAppendingEllipsis];
1114            break;
1115       
1116        default:
1117            return NSLocalizedString(@"N/A", "Torrent -> status string");
1118    }
1119}
1120
1121- (int) seeders
1122{
1123    return fStat->seeders;
1124}
1125
1126- (int) leechers
1127{
1128    return fStat->leechers;
1129}
1130
1131- (int) completedFromTracker
1132{
1133    return fStat->completedFromTracker;
1134}
1135
1136- (int) totalPeersConnected
1137{
1138    return fStat->peersConnected;
1139}
1140
1141- (int) totalPeersTracker
1142{
1143    return fStat->peersFrom[TR_PEER_FROM_TRACKER];
1144}
1145
1146- (int) totalPeersIncoming
1147{
1148    return fStat->peersFrom[TR_PEER_FROM_INCOMING];
1149}
1150
1151- (int) totalPeersCache
1152{
1153    return fStat->peersFrom[TR_PEER_FROM_CACHE];
1154}
1155
1156- (int) totalPeersPex
1157{
1158    return fStat->peersFrom[TR_PEER_FROM_PEX];
1159}
1160
1161- (int) peersSendingToUs
1162{
1163    return fStat->peersSendingToUs;
1164}
1165
1166- (int) peersGettingFromUs
1167{
1168    return fStat->peersGettingFromUs;
1169}
1170
1171- (float) downloadRate
1172{
1173    return fStat->rateDownload;
1174}
1175
1176- (float) uploadRate
1177{
1178    return fStat->rateUpload;
1179}
1180
1181- (uint64_t) haveVerified
1182{
1183    return fStat->haveValid;
1184}
1185
1186- (uint64_t) haveTotal
1187{
1188    return [self haveVerified] + fStat->haveUnchecked;
1189}
1190
1191- (uint64_t) downloadedTotal
1192{
1193    return fStat->downloadedEver;
1194}
1195
1196- (uint64_t) uploadedTotal
1197{
1198    return fStat->uploadedEver;
1199}
1200
1201- (uint64_t) failedHash
1202{
1203    return fStat->corruptEver;
1204}
1205
1206- (float) swarmSpeed
1207{
1208    return fStat->swarmspeed;
1209}
1210
1211- (BOOL) pex
1212{
1213        return fPex;
1214}
1215
1216- (void) setPex: (BOOL) setting
1217{
1218        if (![self privateTorrent])
1219        {
1220                fPex = setting;
1221                tr_torrentDisablePex(fHandle, !setting);
1222        }
1223}
1224
1225- (NSNumber *) orderValue
1226{
1227    return [NSNumber numberWithInt: fOrderValue];
1228}
1229
1230- (void) setOrderValue: (int) orderValue
1231{
1232    fOrderValue = orderValue;
1233}
1234
1235- (NSArray *) fileList
1236{
1237    return fFileList;
1238}
1239
1240- (int) fileCount
1241{
1242    return fInfo->fileCount;
1243}
1244
1245- (void) updateFileStat
1246{
1247    if (fileStat)
1248        tr_torrentFilesFree(fileStat, [self fileCount]);
1249   
1250    int count;
1251    fileStat = tr_torrentFiles(fHandle, &count);
1252}
1253
1254- (float) fileProgress: (int) index
1255{
1256    if (!fileStat)
1257        [self updateFileStat];
1258       
1259    return fileStat[index].progress;
1260}
1261
1262- (BOOL) canChangeDownloadCheckForFile: (int) index
1263{
1264    if (!fileStat)
1265        [self updateFileStat];
1266   
1267    return [self fileCount] > 1 && fileStat[index].completionStatus != TR_CP_COMPLETE;
1268}
1269
1270- (BOOL) canChangeDownloadCheckForFiles: (NSIndexSet *) indexSet
1271{
1272    if ([self fileCount] <= 1 || [self isComplete])
1273        return NO;
1274   
1275    if (!fileStat)
1276        [self updateFileStat];
1277   
1278    int index;
1279    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1280        if (fileStat[index].completionStatus != TR_CP_COMPLETE)
1281            return YES;
1282    return NO;
1283}
1284
1285- (int) checkForFiles: (NSIndexSet *) indexSet
1286{
1287    BOOL onState = NO, offState = NO;
1288    int index;
1289    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1290    {
1291        if (tr_torrentGetFileDL(fHandle, index) || ![self canChangeDownloadCheckForFile: index])
1292            onState = YES;
1293        else
1294            offState = YES;
1295       
1296        if (onState && offState)
1297            return NSMixedState;
1298    }
1299    return onState ? NSOnState : NSOffState;
1300}
1301
1302- (void) setFileCheckState: (int) state forIndexes: (NSIndexSet *) indexSet
1303{
1304    int count = [indexSet count], i = 0, index;
1305    int * files = malloc(count * sizeof(int));
1306    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1307    {
1308        files[i] = index;
1309        i++;
1310    }
1311   
1312    tr_torrentSetFileDLs(fHandle, files, count, state != NSOffState);
1313    free(files);
1314   
1315    [self update];
1316}
1317
1318- (void) setFilePriority: (int) priority forIndexes: (NSIndexSet *) indexSet
1319{
1320    int count = [indexSet count], i = 0, index;
1321    int * files = malloc(count * sizeof(int));
1322    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1323    {
1324        files[i] = index;
1325        i++;
1326    }
1327
1328    tr_torrentSetFilePriorities(fHandle, files, count, priority);
1329    free(files);
1330}
1331
1332- (BOOL) hasFilePriority: (int) priority forIndexes: (NSIndexSet *) indexSet
1333{
1334    int index;
1335    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1336        if (priority == tr_torrentGetFilePriority(fHandle, index) && [self canChangeDownloadCheckForFile: index])
1337            return YES;
1338    return NO;
1339}
1340
1341- (NSSet *) filePrioritiesForIndexes: (NSIndexSet *) indexSet
1342{
1343    BOOL low = NO, normal = NO, high = NO;
1344    NSMutableSet * priorities = [NSMutableSet setWithCapacity: 3];
1345   
1346    int index, priority;
1347    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1348    {
1349        if (![self canChangeDownloadCheckForFile: index])
1350            continue;
1351       
1352        priority = tr_torrentGetFilePriority(fHandle, index);
1353        if (priority == TR_PRI_LOW)
1354        {
1355            if (low)
1356                continue;
1357            low = YES;
1358        }
1359        else if (priority == TR_PRI_HIGH)
1360        {
1361            if (high)
1362                continue;
1363            high = YES;
1364        }
1365        else
1366        {
1367            if (normal)
1368                continue;
1369            normal = YES;
1370        }
1371       
1372        [priorities addObject: [NSNumber numberWithInt: priority]];
1373        if (low && normal && high)
1374            break;
1375    }
1376    return priorities;
1377}
1378
1379- (NSMenu *) fileMenu
1380{
1381    if (!fFileMenu)
1382    {
1383        fFileMenu = [[NSMenu alloc] initWithTitle: [@"TorrentMenu:" stringByAppendingString: [self name]]];
1384        [fFileMenu setAutoenablesItems: NO];
1385    }
1386    return fFileMenu;
1387}
1388
1389- (NSDate *) dateAdded
1390{
1391    return fDateAdded;
1392}
1393
1394- (NSDate *) dateCompleted
1395{
1396    return fDateCompleted;
1397}
1398
1399- (NSDate *) dateActivity
1400{
1401    uint64_t date = fStat->activityDate;
1402    return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date / 1000] : fDateActivity;
1403}
1404
1405- (int) stalledMinutes
1406{
1407    uint64_t start;
1408    if ((start = fStat->startDate) == 0)
1409        return -1;
1410   
1411    NSDate * started = [NSDate dateWithTimeIntervalSince1970: start / 1000],
1412            * activity = [self dateActivity];
1413   
1414    NSDate * laterDate = (!activity || [started compare: activity] == NSOrderedDescending) ? started : activity;
1415    return -1 * [laterDate timeIntervalSinceNow] / 60;
1416}
1417
1418- (BOOL) isStalled
1419{
1420    return fStalled;
1421}
1422
1423- (NSNumber *) stateSortKey
1424{
1425    if (![self isActive])
1426        return [NSNumber numberWithInt: 0];
1427    else if ([self isSeeding])
1428        return [NSNumber numberWithInt: 1];
1429    else
1430        return [NSNumber numberWithInt: 2];
1431}
1432
1433- (NSNumber *) progressSortKey
1434{
1435    return [NSNumber numberWithFloat: [self progress]];
1436}
1437
1438- (NSNumber *) ratioSortKey
1439{
1440    return [NSNumber numberWithFloat: [self ratio]];
1441}
1442
1443- (NSNumber *) ratioProgressSortKey
1444{
1445    return [NSNumber numberWithFloat: [self progressStopRatio]];
1446}
1447
1448- (int) torrentID
1449{
1450    return fID;
1451}
1452
1453- (const tr_info *) torrentInfo
1454{
1455    return fInfo;
1456}
1457
1458- (const tr_stat *) torrentStat
1459{
1460    return fStat;
1461}
1462
1463@end
1464
1465@implementation Torrent (Private)
1466
1467//if a hash is given, attempt to load that; otherwise, attempt to open file at path
1468- (id) initWithHash: (NSString *) hashString path: (NSString *) path lib: (tr_handle *) lib
1469        publicTorrent: (NSNumber *) publicTorrent
1470        downloadFolder: (NSString *) downloadFolder
1471        useIncompleteFolder: (NSNumber *) useIncompleteFolder incompleteFolder: (NSString *) incompleteFolder
1472        dateAdded: (NSDate *) dateAdded dateCompleted: (NSDate *) dateCompleted
1473        dateActivity: (NSDate *) dateActivity
1474        ratioSetting: (NSNumber *) ratioSetting ratioLimit: (NSNumber *) ratioLimit
1475                pex: (NSNumber *) pex
1476        waitToStart: (NSNumber *) waitToStart orderValue: (NSNumber *) orderValue;
1477{
1478    if (!(self = [super init]))
1479        return nil;
1480   
1481    static_lastid++;
1482    fID = static_lastid;
1483   
1484    fLib = lib;
1485    fDefaults = [NSUserDefaults standardUserDefaults];
1486
1487    fPublicTorrent = path && (publicTorrent ? [publicTorrent boolValue] : ![fDefaults boolForKey: @"DeleteOriginalTorrent"]);
1488    if (fPublicTorrent)
1489        fPublicTorrentLocation = [path retain];
1490   
1491    fDownloadFolder = downloadFolder ? downloadFolder : [fDefaults stringForKey: @"DownloadFolder"];
1492    fDownloadFolder = [[fDownloadFolder stringByExpandingTildeInPath] retain];
1493   
1494    fUseIncompleteFolder = useIncompleteFolder ? [useIncompleteFolder boolValue]
1495                                : [fDefaults boolForKey: @"UseIncompleteDownloadFolder"];
1496    if (fUseIncompleteFolder)
1497    {
1498        fIncompleteFolder = incompleteFolder ? incompleteFolder : [fDefaults stringForKey: @"IncompleteDownloadFolder"];
1499        fIncompleteFolder = [[fIncompleteFolder stringByExpandingTildeInPath] retain];
1500    }
1501   
1502    NSString * currentDownloadFolder;
1503    tr_info info;
1504    int error;
1505    if (hashString)
1506    {
1507        if (tr_torrentParseHash(fLib, [hashString UTF8String], NULL, &info) == TR_OK)
1508        {
1509            currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: info.name]]
1510                                        ? fIncompleteFolder : fDownloadFolder;
1511            fHandle = tr_torrentInitSaved(fLib, [hashString UTF8String], [currentDownloadFolder UTF8String],
1512                                            TR_FLAG_SAVE | TR_FLAG_PAUSED, &error);
1513        }
1514        tr_metainfoFree(&info);
1515    }
1516    if (!fHandle && path)
1517    {
1518        if (tr_torrentParse(fLib, [path UTF8String], NULL, &info) == TR_OK)
1519        {
1520            currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: info.name]]
1521                                        ? fIncompleteFolder : fDownloadFolder;
1522            fHandle = tr_torrentInit(fLib, [path UTF8String], [currentDownloadFolder UTF8String],
1523                                        TR_FLAG_SAVE | TR_FLAG_PAUSED, &error);
1524        }
1525        tr_metainfoFree(&info);
1526    }
1527    if (!fHandle)
1528    {
1529        [self release];
1530        return nil;
1531    }
1532   
1533    fInfo = tr_torrentInfo(fHandle);
1534
1535    fDateAdded = dateAdded ? [dateAdded retain] : [[NSDate alloc] init];
1536        if (dateCompleted)
1537                fDateCompleted = [dateCompleted retain];
1538    if (dateActivity)
1539                fDateActivity = [dateActivity retain];
1540       
1541    fRatioSetting = ratioSetting ? [ratioSetting intValue] : NSMixedState;
1542    fRatioLimit = ratioLimit ? [ratioLimit floatValue] : [fDefaults floatForKey: @"RatioLimit"];
1543    fFinishedSeeding = NO;
1544       
1545        if ([self privateTorrent])
1546                fPex = NO;
1547        else
1548                fPex = pex ? [pex boolValue] : YES;
1549        tr_torrentDisablePex(fHandle, !fPex);
1550   
1551    fWaitToStart = waitToStart ? [waitToStart boolValue] : [fDefaults boolForKey: @"AutoStartDownload"];
1552    fOrderValue = orderValue ? [orderValue intValue] : tr_torrentCount(fLib) - 1;
1553    fError = NO;
1554   
1555    [self createFileList];
1556   
1557    [self update];
1558    return self;
1559}
1560
1561- (void) createFileList
1562{
1563    int count = [self fileCount], i;
1564    tr_file * file;
1565    NSMutableArray * pathComponents;
1566    NSString * path;
1567   
1568    NSMutableArray * fileList = [[NSMutableArray alloc] init],
1569                    * flatFileList = [[NSMutableArray alloc] initWithCapacity: count];
1570   
1571    for (i = 0; i < count; i++)
1572    {
1573        file = &fInfo->files[i];
1574       
1575        pathComponents = [[[NSString stringWithUTF8String: file->name] pathComponents] mutableCopy];
1576        if (fInfo->multifile)
1577        {
1578            path = [pathComponents objectAtIndex: 0];
1579            [pathComponents removeObjectAtIndex: 0];
1580        }
1581        else
1582            path = @"";
1583       
1584        [self insertPath: pathComponents forSiblings: fileList withParent: nil previousPath: path
1585                flatList: flatFileList fileSize: file->length index: i];
1586        [pathComponents autorelease];
1587    }
1588   
1589    fFileList = [[NSArray alloc] initWithArray: fileList];
1590    [fileList release];
1591    fFlatFileList = [[NSArray alloc] initWithArray: flatFileList];
1592    [flatFileList release];
1593}
1594
1595- (void) insertPath: (NSMutableArray *) components forSiblings: (NSMutableArray *) siblings
1596        withParent: (NSMutableDictionary *) parent previousPath: (NSString *) previousPath
1597        flatList: (NSMutableArray *) flatList fileSize: (uint64_t) size index: (int) index
1598{
1599    NSString * name = [components objectAtIndex: 0];
1600    BOOL isFolder = [components count] > 1;
1601   
1602    NSMutableDictionary * dict = nil;
1603    if (isFolder)
1604    {
1605        NSEnumerator * enumerator = [siblings objectEnumerator];
1606        while ((dict = [enumerator nextObject]))
1607            if ([[dict objectForKey: @"IsFolder"] boolValue] && [[dict objectForKey: @"Name"] isEqualToString: name])
1608                break;
1609    }
1610   
1611    NSString * currentPath = [previousPath stringByAppendingPathComponent: name];
1612   
1613    //create new folder or item if it doesn't already exist
1614    if (!dict)
1615    {
1616        dict = [NSMutableDictionary dictionaryWithObjectsAndKeys: name, @"Name",
1617                [NSNumber numberWithBool: isFolder], @"IsFolder", currentPath, @"Path", nil];
1618        [siblings addObject: dict];
1619       
1620        if (isFolder)
1621        {
1622            [dict setObject: [NSMutableArray array] forKey: @"Children"];
1623            [dict setObject: [NSMutableIndexSet indexSetWithIndex: index] forKey: @"Indexes"];
1624        }
1625        else
1626        {
1627            [dict setObject: [NSIndexSet indexSetWithIndex: index] forKey: @"Indexes"];
1628            [dict setObject: [NSNumber numberWithUnsignedLongLong: size] forKey: @"Size"];
1629           
1630            NSImage * icon = [[NSWorkspace sharedWorkspace] iconForFileType: [name pathExtension]];
1631            [icon setFlipped: YES];
1632            [dict setObject: icon forKey: @"Icon"];
1633           
1634            [flatList addObject: dict];
1635        }
1636       
1637        if (parent)
1638            [dict setObject: parent forKey: @"Parent"];
1639    }
1640    else
1641        [[dict objectForKey: @"Indexes"] addIndex: index];
1642   
1643    if (isFolder)
1644    {
1645        [components removeObjectAtIndex: 0];
1646        [self insertPath: components forSiblings: [dict objectForKey: @"Children"]
1647            withParent: dict previousPath: currentPath flatList: flatList fileSize: size index: index];
1648    }
1649}
1650
1651- (BOOL) shouldUseIncompleteFolderForName: (NSString *) name
1652{
1653    return fUseIncompleteFolder &&
1654        ![[NSFileManager defaultManager] fileExistsAtPath: [fDownloadFolder stringByAppendingPathComponent: name]];
1655}
1656
1657- (void) updateDownloadFolder
1658{
1659    NSString * folder = [self shouldUseIncompleteFolderForName: [self name]] ? fIncompleteFolder : fDownloadFolder;
1660    tr_torrentSetFolder(fHandle, [folder UTF8String]);
1661}
1662
1663- (void) quickPause
1664{
1665    if (fQuickPauseDict)
1666        return;
1667
1668    fQuickPauseDict = [[NSDictionary alloc] initWithObjectsAndKeys:
1669                    [NSNumber numberWithInt: [self speedMode: YES]], @"UploadSpeedMode",
1670                    [NSNumber numberWithInt: [self speedLimit: YES]], @"UploadSpeedLimit",
1671                    [NSNumber numberWithInt: [self speedMode: NO]], @"DownloadSpeedMode",
1672                    [NSNumber numberWithInt: [self speedLimit: NO]], @"DownloadSpeedLimit", nil];
1673   
1674    [self setSpeedMode: TR_SPEEDLIMIT_SINGLE upload: YES];
1675    [self setSpeedLimit: 0 upload: YES];
1676    [self setSpeedMode: TR_SPEEDLIMIT_SINGLE upload: NO];
1677    [self setSpeedLimit: 0 upload: NO];
1678}
1679
1680- (void) endQuickPause
1681{
1682    if (!fQuickPauseDict)
1683        return;
1684   
1685    [self setSpeedMode: [[fQuickPauseDict objectForKey: @"UploadSpeedMode"] intValue] upload: YES];
1686    [self setSpeedLimit: [[fQuickPauseDict objectForKey: @"UploadSpeedLimit"] intValue] upload: YES];
1687    [self setSpeedMode: [[fQuickPauseDict objectForKey: @"DownloadSpeedMode"] intValue] upload: NO];
1688    [self setSpeedLimit: [[fQuickPauseDict objectForKey: @"DownloadSpeedLimit"] intValue] upload: NO];
1689   
1690    [fQuickPauseDict release];
1691    fQuickPauseDict = nil;
1692}
1693
1694- (void) trashFile: (NSString *) path
1695{
1696    //attempt to move to trash
1697    if (![[NSWorkspace sharedWorkspace] performFileOperation: NSWorkspaceRecycleOperation
1698            source: [path stringByDeletingLastPathComponent] destination: @""
1699            files: [NSArray arrayWithObject: [path lastPathComponent]] tag: nil])
1700    {
1701        //if cannot trash, just delete it (will work if it is on a remote volume)
1702        if (![[NSFileManager defaultManager] removeFileAtPath: path handler: nil])
1703            NSLog(@"Could not trash %@", path);
1704    }
1705}
1706
1707@end
Note: See TracBrowser for help on using the repository browser.