source: trunk/macosx/Torrent.m @ 5099

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

dead code removal

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