source: trunk/macosx/Torrent.m @ 5035

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

fix inspector display error caused by the last commit allowing null field values

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