source: trunk/macosx/Torrent.m @ 3306

Last change on this file since 3306 was 3306, checked in by livings124, 15 years ago

better remaining space check

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