source: trunk/macosx/Torrent.m @ 5143

Last change on this file since 5143 was 5143, checked in by charles, 14 years ago

add `verify' command to ipc.

  • Property svn:keywords set to Date Rev Author Id
File size: 57.1 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 5143 2008-02-27 17:38:39Z charles $
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_torrentVerify(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 * allTrackers = [NSMutableArray array];
740   
741    int i, j;
742    for (i = 0; i < fInfo->trackerTiers; i++)
743    {
744        [allTrackers addObject: [NSNumber numberWithInt: i]];
745        for (j = 0; j < fInfo->trackerList[i].count; j++)
746            [allTrackers addObject: [NSString stringWithFormat: @"http://%s:%d",
747                fInfo->trackerList[i].list[j].address, fInfo->trackerList[i].list[j].port]];
748    }
749   
750    return allTrackers;
751}
752
753- (NSString *) comment
754{
755    return [NSString stringWithUTF8String: fInfo->comment];
756}
757
758- (NSString *) creator
759{
760    return [NSString stringWithUTF8String: fInfo->creator];
761}
762
763- (NSDate *) dateCreated
764{
765    int date = fInfo->dateCreated;
766    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
767}
768
769- (int) pieceSize
770{
771    return fInfo->pieceSize;
772}
773
774- (int) pieceCount
775{
776    return fInfo->pieceCount;
777}
778
779- (NSString *) hashString
780{
781    return fHashString;
782}
783
784- (BOOL) privateTorrent
785{
786    return fInfo->isPrivate;
787}
788
789- (NSString *) torrentLocation
790{
791    return [NSString stringWithUTF8String: fInfo->torrent];
792}
793
794- (NSString *) publicTorrentLocation
795{
796    return fPublicTorrentLocation;
797}
798
799- (NSString *) dataLocation
800{
801    return [[self downloadFolder] stringByAppendingPathComponent: [self name]];
802}
803
804- (BOOL) publicTorrent
805{
806    return fPublicTorrent;
807}
808
809- (float) progress
810{
811    return fStat->percentComplete;
812    //return (float)[self haveTotal] / [self size];
813}
814
815- (float) progressDone
816{
817    return fStat->percentDone;
818}
819
820- (float) progressLeft
821{
822    return (float)[self sizeLeft] / [self size];
823}
824
825- (float) checkingProgress
826{
827    return fStat->recheckProgress;
828}
829
830- (int) eta
831{
832    return fStat->eta;
833}
834
835- (int) etaRatio
836{
837    if (![self isSeeding])
838        return -1;
839   
840    float uploadRate = [self uploadRate];
841    if (uploadRate < 0.1)
842        return -1;
843   
844    float stopRatio = [self actualStopRatio], ratio = [self ratio];
845    if (stopRatio == INVALID || ratio >= stopRatio)
846        return -1;
847   
848    return (float)MAX([self downloadedTotal], [self haveVerified]) * (stopRatio - ratio) / uploadRate / 1024.0;
849}
850
851- (float) notAvailableDesired
852{
853    return (float)(fStat->desiredSize - fStat->desiredAvailable) / [self size];
854}
855
856- (BOOL) isActive
857{
858    return fStat->status != TR_STATUS_STOPPED;
859}
860
861- (BOOL) isSeeding
862{
863    return fStat->status == TR_STATUS_SEED || fStat->status == TR_STATUS_DONE;
864}
865
866- (BOOL) isChecking
867{
868    return fStat->status == TR_STATUS_CHECK || fStat->status == TR_STATUS_CHECK_WAIT;
869}
870
871- (BOOL) allDownloaded
872{
873    return [self progressDone] >= 1.0;
874}
875
876- (BOOL) isComplete
877{
878    return [self progress] >= 1.0;
879}
880
881- (BOOL) isError
882{
883    return fStat->error != 0;
884}
885
886- (NSString *) errorMessage
887{
888    if (![self isError])
889        return @"";
890   
891    NSString * error;
892    if (!(error = [NSString stringWithUTF8String: fStat->errorString])
893        && !(error = [NSString stringWithCString: fStat->errorString encoding: NSISOLatin1StringEncoding]))
894        error = NSLocalizedString(@"(unreadable error)", "Torrent -> error string unreadable");
895   
896    return error;
897}
898
899- (NSArray *) peers
900{
901    int totalPeers, i;
902    tr_peer_stat * peers = tr_torrentPeers(fHandle, &totalPeers);
903   
904    NSMutableArray * peerDics = [NSMutableArray arrayWithCapacity: totalPeers];
905    NSMutableDictionary * dic;
906   
907    tr_peer_stat * peer;
908    for (i = 0; i < totalPeers; i++)
909    {
910        peer = &peers[i];
911       
912        dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:
913            [NSNumber numberWithInt: peer->from], @"From",
914            [NSString stringWithUTF8String: peer->addr], @"IP",
915            [NSNumber numberWithInt: peer->port], @"Port",
916            [NSNumber numberWithFloat: peer->progress], @"Progress",
917            [NSNumber numberWithBool: peer->isEncrypted], @"Encryption",
918            [NSString stringWithUTF8String: peer->client], @"Client",
919            [NSString stringWithUTF8String: peer->flagStr], @"Flags", nil];
920       
921        if (peer->isUploadingTo)
922            [dic setObject: [NSNumber numberWithFloat: peer->uploadToRate] forKey: @"UL To Rate"];
923        if (peer->isDownloadingFrom)
924            [dic setObject: [NSNumber numberWithFloat: peer->downloadFromRate] forKey: @"DL From Rate"];
925       
926        [peerDics addObject: dic];
927    }
928   
929    tr_torrentPeersFree(peers, totalPeers);
930   
931    return peerDics;
932}
933
934- (NSString *) progressString
935{
936    NSString * string;
937   
938    if (![self allDownloaded])
939    {
940        if ([fDefaults boolForKey: @"DisplayStatusProgressSelected"])
941        {
942            uint64_t have = [self haveTotal];
943            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@ selected (%.2f%%)", "Torrent -> progress string"),
944                            [NSString stringForFileSize: have], [NSString stringForFileSize: have + [self sizeLeft]],
945                            100.0 * [self progressDone]];
946        }
947        else
948            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@ (%.2f%%)", "Torrent -> progress string"),
949                            [NSString stringForFileSize: [self haveTotal]],
950                            [NSString stringForFileSize: [self size]], 100.0 * [self progress]];
951    }
952    else if (![self isComplete])
953    {
954        if ([fDefaults boolForKey: @"DisplayStatusProgressSelected"])
955            string = [NSString stringWithFormat: NSLocalizedString(@"%@ selected, uploaded %@ (Ratio: %@)",
956                "Torrent -> progress string"), [NSString stringForFileSize: [self haveTotal]],
957                [NSString stringForFileSize: [self uploadedTotal]], [NSString stringForRatio: [self ratio]]];
958        else
959            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@ (%.2f%%), uploaded %@ (Ratio: %@)",
960                "Torrent -> progress string"), [NSString stringForFileSize: [self haveTotal]],
961                [NSString stringForFileSize: [self size]], 100.0 * [self progress],
962                [NSString stringForFileSize: [self uploadedTotal]], [NSString stringForRatio: [self ratio]]];
963    }
964    else
965        string = [NSString stringWithFormat: NSLocalizedString(@"%@, uploaded %@ (Ratio: %@)", "Torrent -> progress string"),
966                [NSString stringForFileSize: [self size]], [NSString stringForFileSize: [self uploadedTotal]],
967                [NSString stringForRatio: [self ratio]]];
968   
969    //add time when downloading
970    if (fStat->status == TR_STATUS_DOWNLOAD || ([self isSeeding]
971        && (fRatioSetting == NSOnState || (fRatioSetting == NSMixedState && [fDefaults boolForKey: @"RatioCheck"]))))
972    {
973        int eta = fStat->status == TR_STATUS_DOWNLOAD ? [self eta] : [self etaRatio];
974        string = eta >= 0 ? [string stringByAppendingFormat: NSLocalizedString(@" - %@ remaining", "Torrent -> progress string"),
975                                [NSString timeString: eta showSeconds: YES maxDigits: 2]]
976            : [string stringByAppendingString: NSLocalizedString(@" - remaining time unknown", "Torrent -> progress string")];
977    }
978   
979    return string;
980}
981
982- (NSString *) statusString
983{
984    NSString * string;
985   
986    if ([self isError])
987    {
988        string = NSLocalizedString(@"Error", "Torrent -> status string");
989        NSString * errorString = [self errorMessage];
990        if (errorString && ![errorString isEqualToString: @""])
991            string = [NSString stringWithFormat: @"%@: %@", string, errorString];
992    }
993    else
994    {
995        switch (fStat->status)
996        {
997            case TR_STATUS_STOPPED:
998                if (fWaitToStart)
999                {
1000                    string = ![self allDownloaded]
1001                            ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
1002                            : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
1003                }
1004                else if (fFinishedSeeding)
1005                    string = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
1006                else
1007                    string = NSLocalizedString(@"Paused", "Torrent -> status string");
1008                break;
1009
1010            case TR_STATUS_CHECK_WAIT:
1011                string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1012                break;
1013
1014            case TR_STATUS_CHECK:
1015                string = [NSString stringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
1016                                        "Torrent -> status string"), 100.0 * [self checkingProgress]];
1017                break;
1018
1019            case TR_STATUS_DOWNLOAD:
1020                if ([self totalPeersConnected] != 1)
1021                    string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of %d peers",
1022                                                    "Torrent -> status string"), [self peersSendingToUs], [self totalPeersConnected]];
1023                else
1024                    string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of 1 peer",
1025                                                    "Torrent -> status string"), [self peersSendingToUs]];
1026                break;
1027
1028            case TR_STATUS_SEED:
1029            case TR_STATUS_DONE:
1030                if ([self totalPeersConnected] != 1)
1031                    string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of %d peers", "Torrent -> status string"),
1032                                                    [self peersGettingFromUs], [self totalPeersConnected]];
1033                else
1034                    string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of 1 peer", "Torrent -> status string"),
1035                                                    [self peersGettingFromUs]];
1036                break;
1037           
1038            default:
1039                string = @"";
1040        }
1041       
1042        if (fStalled)
1043            string = [NSLocalizedString(@"Stalled, ", "Torrent -> status string") stringByAppendingString: string];
1044    }
1045   
1046    //append even if error
1047    if ([self isActive] && ![self isChecking])
1048    {
1049        if (fStat->status == TR_STATUS_DOWNLOAD)
1050            string = [string stringByAppendingFormat: NSLocalizedString(@" - DL: %@, UL: %@", "Torrent -> status string"),
1051                    [NSString stringForSpeed: [self downloadRate]], [NSString stringForSpeed: [self uploadRate]]];
1052        else
1053            string = [string stringByAppendingFormat: NSLocalizedString(@" - UL: %@", "Torrent -> status string"),
1054                        [NSString stringForSpeed: [self uploadRate]]];
1055    }
1056   
1057    return string;
1058}
1059
1060- (NSString *) shortStatusString
1061{
1062    NSString * string;
1063   
1064    switch (fStat->status)
1065    {
1066        case TR_STATUS_STOPPED:
1067            if (fWaitToStart)
1068            {
1069                string = ![self allDownloaded]
1070                        ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
1071                        : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
1072            }
1073            else if (fFinishedSeeding)
1074                string = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
1075            else
1076                string = NSLocalizedString(@"Paused", "Torrent -> status string");
1077            break;
1078
1079        case TR_STATUS_CHECK_WAIT:
1080            string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1081            break;
1082
1083        case TR_STATUS_CHECK:
1084            string = [NSString stringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
1085                                    "Torrent -> status string"), 100.0 * [self checkingProgress]];
1086            break;
1087       
1088        case TR_STATUS_DOWNLOAD:
1089            string = [NSString stringWithFormat: NSLocalizedString(@"DL: %@, UL: %@", "Torrent -> status string"),
1090                            [NSString stringForSpeed: [self downloadRate]], [NSString stringForSpeed: [self uploadRate]]];
1091            break;
1092       
1093        case TR_STATUS_SEED:
1094        case TR_STATUS_DONE:
1095            string = [NSString stringWithFormat: NSLocalizedString(@"Ratio: %@, UL: %@", "Torrent -> status string"),
1096                            [NSString stringForRatio: [self ratio]], [NSString stringForSpeed: [self uploadRate]]];
1097            break;
1098       
1099        default:
1100            string = @"";
1101    }
1102   
1103    return string;
1104}
1105
1106- (NSString *) remainingTimeString
1107{
1108    if (![self isActive] || ([self isSeeding]
1109        && !(fRatioSetting == NSOnState || (fRatioSetting == NSMixedState && [fDefaults boolForKey: @"RatioCheck"]))))
1110        return [self shortStatusString];
1111   
1112    int eta = [self isSeeding] ? [self etaRatio] : [self eta];
1113    return eta >= 0 ? [NSString timeString: eta showSeconds: YES maxDigits: 2]
1114                    : NSLocalizedString(@"Unknown", "Torrent -> remaining time");
1115}
1116
1117- (NSString *) stateString
1118{
1119    switch (fStat->status)
1120    {
1121        case TR_STATUS_STOPPED:
1122            return NSLocalizedString(@"Paused", "Torrent -> status string");
1123
1124        case TR_STATUS_CHECK:
1125            return [NSString stringWithFormat: NSLocalizedString(@"Checking existing data (%.2f%%)",
1126                                    "Torrent -> status string"), 100.0 * [self checkingProgress]];
1127       
1128        case TR_STATUS_CHECK_WAIT:
1129            return [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1130
1131        case TR_STATUS_DOWNLOAD:
1132            return NSLocalizedString(@"Downloading", "Torrent -> status string");
1133
1134        case TR_STATUS_SEED:
1135        case TR_STATUS_DONE:
1136            return NSLocalizedString(@"Seeding", "Torrent -> status string");
1137       
1138        default:
1139            return NSLocalizedString(@"N/A", "Torrent -> status string");
1140    }
1141}
1142
1143- (int) seeders
1144{
1145    return fStat->seeders;
1146}
1147
1148- (int) leechers
1149{
1150    return fStat->leechers;
1151}
1152
1153- (int) completedFromTracker
1154{
1155    return fStat->completedFromTracker;
1156}
1157
1158- (int) totalPeersConnected
1159{
1160    return fStat->peersConnected;
1161}
1162
1163- (int) totalPeersTracker
1164{
1165    return fStat->peersFrom[TR_PEER_FROM_TRACKER];
1166}
1167
1168- (int) totalPeersIncoming
1169{
1170    return fStat->peersFrom[TR_PEER_FROM_INCOMING];
1171}
1172
1173- (int) totalPeersCache
1174{
1175    return fStat->peersFrom[TR_PEER_FROM_CACHE];
1176}
1177
1178- (int) totalPeersPex
1179{
1180    return fStat->peersFrom[TR_PEER_FROM_PEX];
1181}
1182
1183- (int) totalPeersKnown
1184{
1185    return fStat->peersKnown;
1186}
1187
1188- (int) peersSendingToUs
1189{
1190    return fStat->peersSendingToUs;
1191}
1192
1193- (int) peersGettingFromUs
1194{
1195    return fStat->peersGettingFromUs;
1196}
1197
1198- (float) downloadRate
1199{
1200    return fStat->rateDownload;
1201}
1202
1203- (float) uploadRate
1204{
1205    return fStat->rateUpload;
1206}
1207
1208- (float) totalRate
1209{
1210    return [self downloadRate] + [self uploadRate];
1211}
1212
1213- (uint64_t) haveVerified
1214{
1215    return fStat->haveValid;
1216}
1217
1218- (uint64_t) haveTotal
1219{
1220    return [self haveVerified] + fStat->haveUnchecked;
1221}
1222
1223- (uint64_t) downloadedTotal
1224{
1225    return fStat->downloadedEver;
1226}
1227
1228- (uint64_t) uploadedTotal
1229{
1230    return fStat->uploadedEver;
1231}
1232
1233- (uint64_t) failedHash
1234{
1235    return fStat->corruptEver;
1236}
1237
1238- (float) swarmSpeed
1239{
1240    return fStat->swarmspeed;
1241}
1242
1243- (int) orderValue
1244{
1245    return fOrderValue;
1246}
1247
1248- (void) setOrderValue: (int) orderValue
1249{
1250    fOrderValue = orderValue;
1251}
1252
1253- (int) groupValue
1254{
1255    return fGroupValue;
1256}
1257
1258- (void) setGroupValue: (int) goupValue
1259{
1260    fGroupValue = goupValue;
1261}
1262
1263- (int) groupOrderValue
1264{
1265    return [[GroupsWindowController groups] orderValueForIndex: fGroupValue];
1266}
1267
1268- (void) checkGroupValueForRemoval: (NSNotification *) notification
1269{
1270    if (fGroupValue != -1 && [[[notification userInfo] objectForKey: @"Indexes"] containsIndex: fGroupValue])
1271        fGroupValue = -1;
1272}
1273
1274- (NSArray *) fileList
1275{
1276    return fFileList;
1277}
1278
1279- (int) fileCount
1280{
1281    return fInfo->fileCount;
1282}
1283
1284- (void) updateFileStat
1285{
1286    if (fileStat)
1287        tr_torrentFilesFree(fileStat, [self fileCount]);
1288   
1289    int count;
1290    fileStat = tr_torrentFiles(fHandle, &count);
1291}
1292
1293- (float) fileProgress: (int) index
1294{
1295    if (!fileStat)
1296        [self updateFileStat];
1297       
1298    return fileStat[index].progress;
1299}
1300
1301- (BOOL) canChangeDownloadCheckForFile: (int) index
1302{
1303    if (!fileStat)
1304        [self updateFileStat];
1305   
1306    return [self fileCount] > 1 && fileStat[index].progress < 1.0;
1307}
1308
1309- (BOOL) canChangeDownloadCheckForFiles: (NSIndexSet *) indexSet
1310{
1311    if ([self fileCount] <= 1 || [self isComplete])
1312        return NO;
1313   
1314    if (!fileStat)
1315        [self updateFileStat];
1316   
1317    int index;
1318    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1319        if (fileStat[index].progress < 1.0)
1320            return YES;
1321    return NO;
1322}
1323
1324- (int) checkForFiles: (NSIndexSet *) indexSet
1325{
1326    BOOL onState = NO, offState = NO;
1327    int index;
1328    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1329    {
1330        if (tr_torrentGetFileDL(fHandle, index) || ![self canChangeDownloadCheckForFile: index])
1331            onState = YES;
1332        else
1333            offState = YES;
1334       
1335        if (onState && offState)
1336            return NSMixedState;
1337    }
1338    return onState ? NSOnState : NSOffState;
1339}
1340
1341- (void) setFileCheckState: (int) state forIndexes: (NSIndexSet *) indexSet
1342{
1343    int count = [indexSet count], i = 0, index;
1344    int * files = malloc(count * sizeof(int));
1345    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1346    {
1347        files[i] = index;
1348        i++;
1349    }
1350   
1351    tr_torrentSetFileDLs(fHandle, files, count, state != NSOffState);
1352    free(files);
1353   
1354    [self update];
1355}
1356
1357- (void) setFilePriority: (int) priority forIndexes: (NSIndexSet *) indexSet
1358{
1359    int count = [indexSet count], i = 0, index;
1360    int * files = malloc(count * sizeof(int));
1361    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1362    {
1363        files[i] = index;
1364        i++;
1365    }
1366   
1367    tr_torrentSetFilePriorities(fHandle, files, count, priority);
1368    free(files);
1369}
1370
1371- (BOOL) hasFilePriority: (int) priority forIndexes: (NSIndexSet *) indexSet
1372{
1373    int index;
1374    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1375        if (priority == tr_torrentGetFilePriority(fHandle, index) && [self canChangeDownloadCheckForFile: index])
1376            return YES;
1377    return NO;
1378}
1379
1380- (NSSet *) filePrioritiesForIndexes: (NSIndexSet *) indexSet
1381{
1382    BOOL low = NO, normal = NO, high = NO;
1383    NSMutableSet * priorities = [NSMutableSet setWithCapacity: 3];
1384   
1385    int index, priority;
1386    for (index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1387    {
1388        if (![self canChangeDownloadCheckForFile: index])
1389            continue;
1390       
1391        priority = tr_torrentGetFilePriority(fHandle, index);
1392        if (priority == TR_PRI_LOW)
1393        {
1394            if (low)
1395                continue;
1396            low = YES;
1397        }
1398        else if (priority == TR_PRI_HIGH)
1399        {
1400            if (high)
1401                continue;
1402            high = YES;
1403        }
1404        else
1405        {
1406            if (normal)
1407                continue;
1408            normal = YES;
1409        }
1410       
1411        [priorities addObject: [NSNumber numberWithInt: priority]];
1412        if (low && normal && high)
1413            break;
1414    }
1415    return priorities;
1416}
1417
1418- (NSMenu *) fileMenu
1419{
1420    if (!fFileMenu)
1421    {
1422        fFileMenu = [[NSMenu alloc] initWithTitle: [@"TorrentMenu:" stringByAppendingString: [self name]]];
1423        [fFileMenu setAutoenablesItems: NO];
1424    }
1425    return fFileMenu;
1426}
1427
1428- (NSDate *) dateAdded
1429{
1430    return fDateAdded;
1431}
1432
1433- (NSDate *) dateCompleted
1434{
1435    return fDateCompleted;
1436}
1437
1438- (NSDate *) dateActivity
1439{
1440    uint64_t date = fStat->activityDate;
1441    return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date / 1000] : fDateActivity;
1442}
1443
1444- (NSDate *) dateActivityOrAdd
1445{
1446    NSDate * date = [self dateActivity];
1447    return date ? date : [self dateAdded];
1448}
1449
1450- (int) stalledMinutes
1451{
1452    uint64_t start;
1453    if ((start = fStat->startDate) == 0)
1454        return -1;
1455   
1456    NSDate * started = [NSDate dateWithTimeIntervalSince1970: start / 1000],
1457            * activity = [self dateActivity];
1458   
1459    NSDate * laterDate = (!activity || [started compare: activity] == NSOrderedDescending) ? started : activity;
1460    return -1 * [laterDate timeIntervalSinceNow] / 60;
1461}
1462
1463- (BOOL) isStalled
1464{
1465    return fStalled;
1466}
1467
1468- (NSNumber *) stateSortKey
1469{
1470    if (![self isActive])
1471        return [NSNumber numberWithInt: 0];
1472    else if ([self isSeeding])
1473        return [NSNumber numberWithInt: 1];
1474    else
1475        return [NSNumber numberWithInt: 2];
1476}
1477
1478- (int) torrentID
1479{
1480    return fID;
1481}
1482
1483- (const tr_info *) torrentInfo
1484{
1485    return fInfo;
1486}
1487
1488- (const tr_stat *) torrentStat
1489{
1490    return fStat;
1491}
1492
1493@end
1494
1495@implementation Torrent (Private)
1496
1497//if a hash is given, attempt to load that; otherwise, attempt to open file at path
1498- (id) initWithHash: (NSString *) hashString path: (NSString *) path data: (NSData *) data lib: (tr_handle *) lib
1499        publicTorrent: (NSNumber *) publicTorrent
1500        downloadFolder: (NSString *) downloadFolder
1501        useIncompleteFolder: (NSNumber *) useIncompleteFolder incompleteFolder: (NSString *) incompleteFolder
1502        dateAdded: (NSDate *) dateAdded dateCompleted: (NSDate *) dateCompleted
1503        dateActivity: (NSDate *) dateActivity
1504        ratioSetting: (NSNumber *) ratioSetting ratioLimit: (NSNumber *) ratioLimit
1505        waitToStart: (NSNumber *) waitToStart
1506        orderValue: (NSNumber *) orderValue groupValue: (NSNumber *) groupValue;
1507{
1508    if (!(self = [super init]))
1509        return nil;
1510   
1511    static_lastid++;
1512    fID = static_lastid;
1513   
1514    fLib = lib;
1515    fDefaults = [NSUserDefaults standardUserDefaults];
1516
1517    fPublicTorrent = path && (publicTorrent ? [publicTorrent boolValue] : ![fDefaults boolForKey: @"DeleteOriginalTorrent"]);
1518    if (fPublicTorrent)
1519        fPublicTorrentLocation = [path retain];
1520   
1521    fDownloadFolder = downloadFolder ? downloadFolder : [fDefaults stringForKey: @"DownloadFolder"];
1522    fDownloadFolder = [[fDownloadFolder stringByExpandingTildeInPath] retain];
1523   
1524    fUseIncompleteFolder = useIncompleteFolder ? [useIncompleteFolder boolValue]
1525                                : [fDefaults boolForKey: @"UseIncompleteDownloadFolder"];
1526    if (fUseIncompleteFolder)
1527    {
1528        fIncompleteFolder = incompleteFolder ? incompleteFolder : [fDefaults stringForKey: @"IncompleteDownloadFolder"];
1529        fIncompleteFolder = [[fIncompleteFolder stringByExpandingTildeInPath] retain];
1530    }
1531   
1532    //set libtransmission settings for initialization
1533    tr_ctor * ctor = tr_ctorNew(fLib);
1534    tr_ctorSetPaused(ctor, TR_FORCE, YES);
1535    tr_ctorSetMaxConnectedPeers(ctor, TR_FALLBACK, [fDefaults integerForKey: @"PeersTorrent"]);
1536   
1537    tr_info info;
1538    int error;
1539    if (hashString)
1540    {
1541        tr_ctorSetMetainfoFromHash(ctor, [hashString UTF8String]);
1542        if (tr_torrentParse(fLib, ctor, &info) == TR_OK)
1543        {
1544            NSString * currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: info.name]]
1545                                                ? fIncompleteFolder : fDownloadFolder;
1546            tr_ctorSetDestination(ctor, TR_FORCE, [currentDownloadFolder UTF8String]);
1547           
1548            fHandle = tr_torrentNew(fLib, ctor, &error);
1549        }
1550        tr_metainfoFree(&info);
1551    }
1552    if (!fHandle && path)
1553    {
1554        tr_ctorSetMetainfoFromFile(ctor, [path UTF8String]);
1555        if (tr_torrentParse(fLib, ctor, &info) == TR_OK)
1556        {
1557            NSString * currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: info.name]]
1558                                                ? fIncompleteFolder : fDownloadFolder;
1559            tr_ctorSetDestination(ctor, TR_FORCE, [currentDownloadFolder UTF8String]);
1560           
1561            fHandle = tr_torrentNew(fLib, ctor, &error);
1562        }
1563        tr_metainfoFree(&info);
1564    }
1565    if (!fHandle && data)
1566    {
1567        tr_ctorSetMetainfo(ctor, [data bytes], [data length]);
1568        if (tr_torrentParse(fLib, ctor, &info) == TR_OK)
1569        {
1570            NSString * currentDownloadFolder = [self shouldUseIncompleteFolderForName: [NSString stringWithUTF8String: info.name]]
1571                                                ? fIncompleteFolder : fDownloadFolder;
1572            tr_ctorSetDestination(ctor, TR_FORCE, [currentDownloadFolder UTF8String]);
1573           
1574            fHandle = tr_torrentNew(fLib, ctor, &error);
1575        }
1576        tr_metainfoFree(&info);
1577    }
1578   
1579    tr_ctorFree(ctor);
1580   
1581    if (!fHandle)
1582    {
1583        [self release];
1584        return nil;
1585    }
1586   
1587    tr_torrentSetStatusCallback(fHandle, completenessChangeCallback, self);
1588   
1589    fInfo = tr_torrentInfo(fHandle);
1590   
1591    fNameString = [[NSString alloc] initWithUTF8String: fInfo->name];
1592    fHashString = [[NSString alloc] initWithUTF8String: fInfo->hashString];
1593   
1594    fDateAdded = dateAdded ? [dateAdded retain] : [[NSDate alloc] init];
1595        if (dateCompleted)
1596                fDateCompleted = [dateCompleted retain];
1597    if (dateActivity)
1598                fDateActivity = [dateActivity retain];
1599       
1600    fRatioSetting = ratioSetting ? [ratioSetting intValue] : NSMixedState;
1601    fRatioLimit = ratioLimit ? [ratioLimit floatValue] : [fDefaults floatForKey: @"RatioLimit"];
1602    fFinishedSeeding = NO;
1603   
1604    fWaitToStart = waitToStart && [waitToStart boolValue];
1605   
1606    fOrderValue = orderValue ? [orderValue intValue] : tr_torrentCount(fLib) - 1;
1607    fGroupValue = groupValue ? [groupValue intValue] : -1;
1608   
1609    [self createFileList];
1610   
1611    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(checkGroupValueForRemoval:)
1612        name: @"GroupValueRemoved" object: nil];
1613   
1614    [self update];
1615   
1616    //mark incomplete files to be ignored by Time Machine
1617    [self setTimeMachineExclude: ![self allDownloaded] forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
1618   
1619    return self;
1620}
1621
1622- (void) createFileList
1623{
1624    int count = [self fileCount], i;
1625    tr_file * file;
1626    NSMutableArray * pathComponents;
1627    NSString * path;
1628   
1629    NSMutableArray * fileList = [[NSMutableArray alloc] initWithCapacity: count];
1630   
1631    for (i = 0; i < count; i++)
1632    {
1633        file = &fInfo->files[i];
1634       
1635        pathComponents = [[[NSString stringWithUTF8String: file->name] pathComponents] mutableCopy];
1636        if ([self folder])
1637        {
1638            path = [pathComponents objectAtIndex: 0];
1639            [pathComponents removeObjectAtIndex: 0];
1640        }
1641        else
1642            path = @"";
1643       
1644        [self insertPath: pathComponents forSiblings: fileList previousPath: path fileSize: file->length index: i];
1645        [pathComponents release];
1646    }
1647   
1648    fFileList = [[NSArray alloc] initWithArray: fileList];
1649    [fileList release];
1650}
1651
1652- (void) insertPath: (NSMutableArray *) components forSiblings: (NSMutableArray *) siblings previousPath: (NSString *) previousPath
1653            fileSize: (uint64_t) size index: (int) index
1654{
1655    NSString * name = [components objectAtIndex: 0];
1656    BOOL isFolder = [components count] > 1;
1657   
1658    NSMutableDictionary * dict = nil;
1659    if (isFolder)
1660    {
1661        NSEnumerator * enumerator = [siblings objectEnumerator];
1662        while ((dict = [enumerator nextObject]))
1663            if ([[dict objectForKey: @"Name"] isEqualToString: name] && [[dict objectForKey: @"IsFolder"] boolValue])
1664                break;
1665    }
1666   
1667    NSString * currentPath = [previousPath stringByAppendingPathComponent: name];
1668   
1669    //create new folder or item if it doesn't already exist
1670    if (!dict)
1671    {
1672        dict = [NSMutableDictionary dictionaryWithObjectsAndKeys: name, @"Name",
1673                [NSNumber numberWithBool: isFolder], @"IsFolder", currentPath, @"Path", nil];
1674        [siblings addObject: dict];
1675       
1676        if (isFolder)
1677        {
1678            [dict setObject: [NSMutableArray array] forKey: @"Children"];
1679            [dict setObject: [NSMutableIndexSet indexSetWithIndex: index] forKey: @"Indexes"];
1680        }
1681        else
1682        {
1683            [dict setObject: [NSIndexSet indexSetWithIndex: index] forKey: @"Indexes"];
1684            [dict setObject: [NSNumber numberWithUnsignedLongLong: size] forKey: @"Size"];
1685           
1686            NSImage * icon = [[NSWorkspace sharedWorkspace] iconForFileType: [name pathExtension]];
1687            [icon setFlipped: YES];
1688            [dict setObject: icon forKey: @"Icon"];
1689        }
1690    }
1691    else
1692        [[dict objectForKey: @"Indexes"] addIndex: index];
1693   
1694    if (isFolder)
1695    {
1696        [components removeObjectAtIndex: 0];
1697        [self insertPath: components forSiblings: [dict objectForKey: @"Children"] previousPath: currentPath fileSize: size
1698                index: index];
1699    }
1700}
1701
1702- (BOOL) shouldUseIncompleteFolderForName: (NSString *) name
1703{
1704    return fUseIncompleteFolder &&
1705        ![[NSFileManager defaultManager] fileExistsAtPath: [fDownloadFolder stringByAppendingPathComponent: name]];
1706}
1707
1708- (void) updateDownloadFolder
1709{
1710    //remove old Time Machine location
1711    [self setTimeMachineExclude: NO forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
1712   
1713    NSString * folder = [self shouldUseIncompleteFolderForName: [self name]] ? fIncompleteFolder : fDownloadFolder;
1714    tr_torrentSetFolder(fHandle, [folder UTF8String]);
1715   
1716    [self setTimeMachineExclude: ![self allDownloaded] forPath: [folder stringByAppendingPathComponent: [self name]]];
1717}
1718
1719//status has been retained
1720- (void) completenessChange: (NSNumber *) status
1721{
1722    [self update];
1723   
1724    BOOL canMove;
1725    switch ([status intValue])
1726    {
1727        case TR_CP_DONE:
1728        case TR_CP_COMPLETE:
1729            canMove = YES;
1730           
1731            //move file from incomplete folder to download folder
1732            if (fUseIncompleteFolder && ![[self downloadFolder] isEqualToString: fDownloadFolder]
1733                && (canMove = [self alertForMoveFolderAvailable]))
1734            {
1735                [self quickPause];
1736               
1737                if ([[NSFileManager defaultManager] movePath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]
1738                                        toPath: [fDownloadFolder stringByAppendingPathComponent: [self name]] handler: nil])
1739                    [self updateDownloadFolder];
1740                else
1741                    canMove = NO;
1742               
1743                [self endQuickPause];
1744            }
1745           
1746            if (!canMove)
1747            {
1748                fUseIncompleteFolder = NO;
1749               
1750                [fDownloadFolder release];
1751                fDownloadFolder = fIncompleteFolder;
1752                fIncompleteFolder = nil;
1753            }
1754           
1755            [fDateCompleted release];
1756            fDateCompleted = [[NSDate alloc] init];
1757           
1758            //allow to be backed up by Time Machine
1759            [self setTimeMachineExclude: NO forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
1760           
1761            fStat = tr_torrentStat(fHandle);
1762            [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedDownloading" object: self];
1763            break;
1764       
1765        case TR_CP_INCOMPLETE:
1766            //do not allow to be backed up by Time Machine
1767            [self setTimeMachineExclude: YES forPath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]];
1768           
1769            [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentRestartedDownloading" object: self];
1770            break;
1771    }
1772    [status release];
1773}
1774
1775- (void) quickPause
1776{
1777    if (fQuickPauseDict)
1778        return;
1779
1780    fQuickPauseDict = [[NSDictionary alloc] initWithObjectsAndKeys:
1781                    [NSNumber numberWithInt: [self speedMode: YES]], @"UploadSpeedMode",
1782                    [NSNumber numberWithInt: [self speedLimit: YES]], @"UploadSpeedLimit",
1783                    [NSNumber numberWithInt: [self speedMode: NO]], @"DownloadSpeedMode",
1784                    [NSNumber numberWithInt: [self speedLimit: NO]], @"DownloadSpeedLimit", nil];
1785   
1786    [self setSpeedMode: TR_SPEEDLIMIT_SINGLE upload: YES];
1787    [self setSpeedLimit: 0 upload: YES];
1788    [self setSpeedMode: TR_SPEEDLIMIT_SINGLE upload: NO];
1789    [self setSpeedLimit: 0 upload: NO];
1790}
1791
1792- (void) endQuickPause
1793{
1794    if (!fQuickPauseDict)
1795        return;
1796   
1797    [self setSpeedMode: [[fQuickPauseDict objectForKey: @"UploadSpeedMode"] intValue] upload: YES];
1798    [self setSpeedLimit: [[fQuickPauseDict objectForKey: @"UploadSpeedLimit"] intValue] upload: YES];
1799    [self setSpeedMode: [[fQuickPauseDict objectForKey: @"DownloadSpeedMode"] intValue] upload: NO];
1800    [self setSpeedLimit: [[fQuickPauseDict objectForKey: @"DownloadSpeedLimit"] intValue] upload: NO];
1801   
1802    [fQuickPauseDict release];
1803    fQuickPauseDict = nil;
1804}
1805
1806- (void) trashFile: (NSString *) path
1807{
1808    //attempt to move to trash
1809    if (![[NSWorkspace sharedWorkspace] performFileOperation: NSWorkspaceRecycleOperation
1810            source: [path stringByDeletingLastPathComponent] destination: @""
1811            files: [NSArray arrayWithObject: [path lastPathComponent]] tag: nil])
1812    {
1813        //if cannot trash, just delete it (will work if it is on a remote volume)
1814        if (![[NSFileManager defaultManager] removeFileAtPath: path handler: nil])
1815            NSLog(@"Could not trash %@", path);
1816    }
1817}
1818
1819- (void) setTimeMachineExclude: (BOOL) exclude forPath: (NSString *) path
1820{
1821    if ([NSApp isOnLeopardOrBetter])
1822        CSBackupSetItemExcluded((CFURLRef)[NSURL fileURLWithPath: path], exclude, true);
1823}
1824
1825@end
Note: See TracBrowser for help on using the repository browser.