source: trunk/macosx/Torrent.m @ 5296

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

fold similar strings together for easier translation

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