source: trunk/macosx/Torrent.m @ 5273

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

fix display issue on launch when group row is set to show ratio

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