source: trunk/macosx/Torrent.m @ 10190

Last change on this file since 10190 was 10190, checked in by livings124, 12 years ago

add the ability to remove trackers when multiple torrents are selected

  • Property svn:keywords set to Date Rev Author Id
File size: 55.4 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 10190 2010-02-13 04:30:47Z livings124 $
3 *
4 * Copyright (c) 2006-2010 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 "GroupsController.h"
27#import "FileListNode.h"
28#import "NSStringAdditions.h"
29#import "TrackerNode.h"
30#import "utils.h" //tr_httpIsValidURL
31
32@interface Torrent (Private)
33
34- (id) initWithPath: (NSString *) path hash: (NSString *) hashString torrentStruct: (tr_torrent *) torrentStruct
35        magnetAddress: (NSString *) magnetAddress lib: (tr_session *) lib
36        waitToStart: (NSNumber *) waitToStart
37        groupValue: (NSNumber *) groupValue
38        downloadFolder: (NSString *) downloadFolder legacyIncompleteFolder: (NSString *) incompleteFolder;
39
40- (void) createFileList;
41- (void) insertPath: (NSMutableArray *) components forParent: (FileListNode *) parent fileSize: (uint64_t) size
42    index: (NSInteger) index flatList: (NSMutableArray *) flatFileList;
43
44- (void) completenessChange: (NSNumber *) status;
45- (void) ratioLimitHit;
46- (void) metadataRetrieved;
47
48- (NSString *) etaString;
49
50- (void) setTimeMachineExclude: (BOOL) exclude forPath: (NSString *) path;
51
52@end
53
54void completenessChangeCallback(tr_torrent * torrent, tr_completeness status, void * torrentData)
55{
56    [(Torrent *)torrentData performSelectorOnMainThread: @selector(completenessChange:)
57        withObject: [[NSNumber alloc] initWithInt: status] waitUntilDone: NO];
58}
59
60void ratioLimitHitCallback(tr_torrent * torrent, void * torrentData)
61{
62    [(Torrent *)torrentData performSelectorOnMainThread: @selector(ratioLimitHit) withObject: nil waitUntilDone: NO];
63}
64
65void metadataCallback(tr_torrent * torrent, void * torrentData)
66{
67    [(Torrent *)torrentData performSelectorOnMainThread: @selector(metadataRetrieved) withObject: nil waitUntilDone: NO];
68}
69
70int trashDataFile(const char * filename)
71{
72    if (filename != NULL)
73        [Torrent trashFile: [NSString stringWithUTF8String: filename]];
74    return 0;
75}
76
77@implementation Torrent
78
79- (id) initWithPath: (NSString *) path location: (NSString *) location deleteTorrentFile: (BOOL) torrentDelete
80        lib: (tr_session *) lib
81{
82    self = [self initWithPath: path hash: nil torrentStruct: NULL magnetAddress: nil lib: lib
83            waitToStart: nil groupValue: nil
84            downloadFolder: location legacyIncompleteFolder: nil];
85   
86    if (self)
87    {
88        if (torrentDelete && ![[self torrentLocation] isEqualToString: path])
89            [Torrent trashFile: path];
90    }
91    return self;
92}
93
94- (id) initWithTorrentStruct: (tr_torrent *) torrentStruct location: (NSString *) location lib: (tr_session *) lib
95{
96    self = [self initWithPath: nil hash: nil torrentStruct: torrentStruct magnetAddress: nil lib: lib
97            waitToStart: nil groupValue: nil
98            downloadFolder: location legacyIncompleteFolder: nil];
99   
100    return self;
101}
102
103#warning need location (and use it)?
104- (id) initWithMagnetAddress: (NSString *) address location: (NSString *) location lib: (tr_session *) lib
105{
106    self = [self initWithPath: nil hash: nil torrentStruct: nil magnetAddress: address
107            lib: lib waitToStart: nil groupValue: nil
108            downloadFolder: location legacyIncompleteFolder: nil];
109   
110    return self;
111}
112
113- (id) initWithHistory: (NSDictionary *) history lib: (tr_session *) lib forcePause: (BOOL) pause
114{
115    self = [self initWithPath: [history objectForKey: @"InternalTorrentPath"]
116                hash: [history objectForKey: @"TorrentHash"]
117                torrentStruct: NULL
118                magnetAddress: nil
119                lib: lib
120                waitToStart: [history objectForKey: @"WaitToStart"]
121                groupValue: [history objectForKey: @"GroupValue"]
122                downloadFolder: [history objectForKey: @"DownloadFolder"] //upgrading from versions < 1.80
123                legacyIncompleteFolder: [[history objectForKey: @"UseIncompleteFolder"] boolValue] //upgrading from versions < 1.80
124                                        ? [history objectForKey: @"IncompleteFolder"] : nil];
125   
126    if (self)
127    {
128        //start transfer
129        NSNumber * active;
130        if (!pause && (active = [history objectForKey: @"Active"]) && [active boolValue])
131        {
132            fStat = tr_torrentStat(fHandle);
133            [self startTransfer];
134        }
135       
136        //upgrading from versions < 1.30: get old added, activity, and done dates
137        NSDate * date;
138        if ((date = [history objectForKey: @"Date"]))
139            tr_torrentSetAddedDate(fHandle, [date timeIntervalSince1970]);
140        if ((date = [history objectForKey: @"DateActivity"]))
141            tr_torrentSetActivityDate(fHandle, [date timeIntervalSince1970]);
142        if ((date = [history objectForKey: @"DateCompleted"]))
143            tr_torrentSetDoneDate(fHandle, [date timeIntervalSince1970]);
144       
145        //upgrading from versions < 1.60: get old stop ratio settings
146        NSNumber * ratioSetting;
147        if ((ratioSetting = [history objectForKey: @"RatioSetting"]))
148        {
149            switch ([ratioSetting intValue])
150            {
151                case NSOnState: [self setRatioSetting: TR_RATIOLIMIT_SINGLE]; break;
152                case NSOffState: [self setRatioSetting: TR_RATIOLIMIT_UNLIMITED]; break;
153                case NSMixedState: [self setRatioSetting: TR_RATIOLIMIT_GLOBAL]; break;
154            }
155        }
156        NSNumber * ratioLimit;
157        if ((ratioLimit = [history objectForKey: @"RatioLimit"]))
158            [self setRatioLimit: [ratioLimit floatValue]];
159    }
160    return self;
161}
162
163- (NSDictionary *) history
164{
165    return [NSDictionary dictionaryWithObjectsAndKeys:
166                [self torrentLocation], @"InternalTorrentPath",
167                [self hashString], @"TorrentHash",
168                [NSNumber numberWithBool: [self isActive]], @"Active",
169                [NSNumber numberWithBool: fWaitToStart], @"WaitToStart",
170                [NSNumber numberWithInt: fGroupValue], @"GroupValue", nil];
171}
172
173- (void) dealloc
174{
175    [[NSNotificationCenter defaultCenter] removeObserver: self];
176   
177    if (fFileStat)
178        tr_torrentFilesFree(fFileStat, [self fileCount]);
179   
180    [fPreviousFinishedIndexes release];
181    [fPreviousFinishedIndexesDate release];
182   
183    [fHashString release];
184   
185    [fIcon release];
186   
187    [fFileList release];
188    [fFlatFileList release];
189   
190    [fTimeMachineExclude release];
191   
192    [super dealloc];
193}
194
195- (NSString *) description
196{
197    return [@"Torrent: " stringByAppendingString: [self name]];
198}
199
200- (id) copyWithZone: (NSZone *) zone
201{
202    return [self retain];
203}
204
205- (void) closeRemoveTorrent
206{
207    //allow the file to be index by Time Machine
208    if (fTimeMachineExclude)
209    {
210        [self setTimeMachineExclude: NO forPath: fTimeMachineExclude];
211        [fTimeMachineExclude release];
212        fTimeMachineExclude = nil;
213    }
214   
215    tr_torrentRemove(fHandle);
216}
217
218- (void) changeDownloadFolderBeforeUsing: (NSString *) folder
219{
220     tr_torrentSetDownloadDir(fHandle, [folder UTF8String]);
221     [self updateTimeMachineExclude];
222}
223
224- (NSString *) currentDirectory
225{
226    return [NSString stringWithUTF8String: tr_torrentGetCurrentDir(fHandle)];
227}
228
229- (void) getAvailability: (int8_t *) tab size: (NSInteger) size
230{
231    tr_torrentAvailability(fHandle, tab, size);
232}
233
234- (void) getAmountFinished: (float *) tab size: (NSInteger) size
235{
236    tr_torrentAmountFinished(fHandle, tab, size);
237}
238
239- (NSIndexSet *) previousFinishedPieces
240{
241    //if the torrent hasn't been seen in a bit, and therefore hasn't been refreshed, return nil
242    if (fPreviousFinishedIndexesDate && [fPreviousFinishedIndexesDate timeIntervalSinceNow] > -2.0)
243        return fPreviousFinishedIndexes;
244    else
245        return nil;
246}
247
248-(void) setPreviousFinishedPieces: (NSIndexSet *) indexes
249{
250    [fPreviousFinishedIndexes release];
251    fPreviousFinishedIndexes = [indexes retain];
252   
253    [fPreviousFinishedIndexesDate release];
254    fPreviousFinishedIndexesDate = indexes != nil ? [[NSDate alloc] init] : nil;
255}
256
257- (void) update
258{
259    //get previous status values before update
260    BOOL wasChecking = NO, wasError = NO, wasStalled = NO;
261    if (fStat != NULL)
262    {
263        wasChecking = [self isChecking];
264        wasError = [self isError];
265        wasStalled = fStalled;
266    }
267   
268    fStat = tr_torrentStat(fHandle);
269   
270    //check if stalled (stored because based on time and needs to check if it was previously stalled)
271    fStalled = [self isActive] && [fDefaults boolForKey: @"CheckStalled"]
272                && [self stalledMinutes] > [fDefaults integerForKey: @"StalledMinutes"];
273   
274    //update queue for checking (from downloading to seeding), stalled, or error
275    if ((wasChecking && ![self isChecking]) || (wasStalled != fStalled) || (!wasError && [self isError] && [self isActive]))
276        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
277   
278    //when the data first appears, update time machine exclusion
279    if (!fTimeMachineExclude)
280        [self updateTimeMachineExclude];
281}
282
283- (void) startTransfer
284{
285    fWaitToStart = NO;
286    fFinishedSeeding = NO;
287   
288    if (![self isActive] && [self alertForRemainingDiskSpace])
289    {
290        tr_torrentStart(fHandle);
291        [self update];
292    }
293}
294
295- (void) stopTransfer
296{
297    fWaitToStart = NO;
298   
299    if ([self isActive])
300    {
301        tr_torrentStop(fHandle);
302        [self update];
303       
304        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateQueue" object: self];
305    }
306}
307
308- (void) sleep
309{
310    if ((fResumeOnWake = [self isActive]))
311        tr_torrentStop(fHandle);
312}
313
314- (void) wakeUp
315{
316    if (fResumeOnWake)
317        tr_torrentStart(fHandle);
318}
319
320- (void) manualAnnounce
321{
322    tr_torrentManualUpdate(fHandle);
323}
324
325- (BOOL) canManualAnnounce
326{
327    return tr_torrentCanManualUpdate(fHandle);
328}
329
330- (void) resetCache
331{
332    tr_torrentVerify(fHandle);
333    [self update];
334}
335
336- (BOOL) isMagnet
337{
338    return !tr_torrentHasMetadata(fHandle);
339}
340
341- (NSString *) magnetLink
342{
343    return [NSString stringWithUTF8String: tr_torrentGetMagnetLink(fHandle)];
344}
345
346- (CGFloat) ratio
347{
348    return fStat->ratio;
349}
350
351- (tr_ratiolimit) ratioSetting
352{
353    return tr_torrentGetRatioMode(fHandle);
354}
355
356- (void) setRatioSetting: (tr_ratiolimit) setting
357{
358    tr_torrentSetRatioMode(fHandle, setting);
359}
360
361- (CGFloat) ratioLimit
362{
363    return tr_torrentGetRatioLimit(fHandle);
364}
365
366- (void) setRatioLimit: (CGFloat) limit
367{
368    NSAssert(limit >= 0, @"Ratio cannot be negative");
369    tr_torrentSetRatioLimit(fHandle, limit);
370}
371
372- (BOOL) seedRatioSet
373{
374    return tr_torrentGetSeedRatio(fHandle, NULL);
375}
376
377- (CGFloat) progressStopRatio
378{
379    return fStat->percentRatio;
380}
381
382- (BOOL) usesSpeedLimit: (BOOL) upload
383{
384    return tr_torrentUsesSpeedLimit(fHandle, upload ? TR_UP : TR_DOWN);
385}
386
387- (void) setUseSpeedLimit: (BOOL) use upload: (BOOL) upload
388{
389    tr_torrentUseSpeedLimit(fHandle, upload ? TR_UP : TR_DOWN, use);
390}
391
392- (NSInteger) speedLimit: (BOOL) upload
393{
394    return tr_torrentGetSpeedLimit(fHandle, upload ? TR_UP : TR_DOWN);
395}
396
397- (void) setSpeedLimit: (NSInteger) limit upload: (BOOL) upload
398{
399    tr_torrentSetSpeedLimit(fHandle, upload ? TR_UP : TR_DOWN, limit);
400}
401
402- (BOOL) usesGlobalSpeedLimit
403{
404    return tr_torrentUsesSessionLimits(fHandle);
405}
406
407- (void) setUseGlobalSpeedLimit: (BOOL) use
408{
409    tr_torrentUseSessionLimits(fHandle, use);
410}
411
412- (void) setMaxPeerConnect: (uint16_t) count
413{
414    NSAssert(count > 0, @"max peer count must be greater than 0");
415   
416    tr_torrentSetPeerLimit(fHandle, count);
417}
418
419- (uint16_t) maxPeerConnect
420{
421    return tr_torrentGetPeerLimit(fHandle);
422}
423
424- (void) setWaitToStart: (BOOL) wait
425{
426    fWaitToStart = wait;
427}
428
429- (BOOL) waitingToStart
430{
431    return fWaitToStart;
432}
433
434- (tr_priority_t) priority
435{
436    return tr_torrentGetPriority(fHandle);
437}
438
439- (void) setPriority: (tr_priority_t) priority
440{
441    return tr_torrentSetPriority(fHandle, priority);
442}
443
444#warning when 10.6-only use recycleURLs:completionHandler:
445+ (void) trashFile: (NSString *) path
446{
447    //attempt to move to trash
448    if (![[NSWorkspace sharedWorkspace] performFileOperation: NSWorkspaceRecycleOperation
449        source: [path stringByDeletingLastPathComponent] destination: @""
450        files: [NSArray arrayWithObject: [path lastPathComponent]] tag: nil])
451    {
452        //if cannot trash, just delete it (will work if it's on a remote volume)
453        NSError * error;
454        if (![[NSFileManager defaultManager] removeItemAtPath: path error: &error])
455            NSLog(@"Could not trash %@: %@", path, [error localizedDescription]);
456    }
457}
458
459- (void) trashData
460{
461    tr_torrentDeleteLocalData(fHandle, trashDataFile);
462}
463
464- (void) moveTorrentDataFileTo: (NSString *) folder
465{
466    NSString * oldFolder = [self currentDirectory];
467    if ([oldFolder isEqualToString: folder])
468        return;
469   
470    //check if moving inside itself
471    NSArray * oldComponents = [oldFolder pathComponents],
472            * newComponents = [folder pathComponents];
473    const NSInteger oldCount = [oldComponents count];
474   
475    if (oldCount < [newComponents count] && [[newComponents objectAtIndex: oldCount] isEqualToString: [self name]]
476        && [folder hasPrefix: oldFolder])
477    {
478        NSAlert * alert = [[NSAlert alloc] init];
479        [alert setMessageText: NSLocalizedString(@"A folder cannot be moved to inside itself.",
480                                                    "Move inside itself alert -> title")];
481        [alert setInformativeText: [NSString stringWithFormat:
482                        NSLocalizedString(@"The move operation of \"%@\" cannot be done.",
483                                            "Move inside itself alert -> message"), [self name]]];
484        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move inside itself alert -> button")];
485       
486        [alert runModal];
487        [alert release];
488       
489        return;
490    }
491   
492    volatile int status;
493    tr_torrentSetLocation(fHandle, [folder UTF8String], YES, NULL, &status);
494   
495    while (status == TR_LOC_MOVING) //block while moving (for now)
496        [NSThread sleepForTimeInterval: 0.05];
497   
498    if (status == TR_LOC_DONE)
499        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateStats" object: nil];
500    else
501    {
502        NSAlert * alert = [[NSAlert alloc] init];
503        [alert setMessageText: NSLocalizedString(@"There was an error moving the data file.", "Move error alert -> title")];
504        [alert setInformativeText: [NSString stringWithFormat:
505                NSLocalizedString(@"The move operation of \"%@\" cannot be done.", "Move error alert -> message"), [self name]]];
506        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move error alert -> button")];
507       
508        [alert runModal];
509        [alert release];
510    }
511   
512    [self updateTimeMachineExclude];
513}
514
515- (void) copyTorrentFileTo: (NSString *) path
516{
517    [[NSFileManager defaultManager] copyItemAtPath: [self torrentLocation] toPath: path error: NULL];
518}
519
520- (BOOL) alertForRemainingDiskSpace
521{
522    if ([self allDownloaded] || ![fDefaults boolForKey: @"WarningRemainingSpace"])
523        return YES;
524   
525    NSString * downloadFolder = [self currentDirectory], * volumeName;
526    if ((volumeName = [[[NSFileManager defaultManager] componentsToDisplayForPath: downloadFolder] objectAtIndex: 0]))
527    {
528        NSDictionary * systemAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath: downloadFolder error: NULL];
529        uint64_t remainingSpace = [[systemAttributes objectForKey: NSFileSystemFreeSize] unsignedLongLongValue];
530       
531        //if the remaining space is greater than the size left, then there is enough space regardless of preallocation
532        if (remainingSpace < [self sizeLeft] && remainingSpace < tr_torrentGetBytesLeftToAllocate(fHandle))
533        {
534            NSAlert * alert = [[NSAlert alloc] init];
535            [alert setMessageText: [NSString stringWithFormat:
536                                    NSLocalizedString(@"Not enough remaining disk space to download \"%@\" completely.",
537                                        "Torrent disk space alert -> title"), [self name]]];
538            [alert setInformativeText: [NSString stringWithFormat: NSLocalizedString(@"The transfer will be paused."
539                                        " Clear up space on %@ or deselect files in the torrent inspector to continue.",
540                                        "Torrent disk space alert -> message"), volumeName]];
541            [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent disk space alert -> button")];
542            [alert addButtonWithTitle: NSLocalizedString(@"Download Anyway", "Torrent disk space alert -> button")];
543           
544            [alert setShowsSuppressionButton: YES];
545            [[alert suppressionButton] setTitle: NSLocalizedString(@"Do not check disk space again",
546                                                    "Torrent disk space alert -> button")];
547
548            const NSInteger result = [alert runModal];
549            if ([[alert suppressionButton] state] == NSOnState)
550                [fDefaults setBool: NO forKey: @"WarningRemainingSpace"];
551            [alert release];
552           
553            return result != NSAlertFirstButtonReturn;
554        }
555    }
556    return YES;
557}
558
559- (NSImage *) icon
560{
561    if ([self isMagnet])
562        return [NSImage imageNamed: @"Magnet.png"];
563   
564    #warning replace 'fldr' stuff with NSImageNameFolder on 10.6
565    if (!fIcon)
566        fIcon = [[[NSWorkspace sharedWorkspace] iconForFileType: [self isFolder] ? NSFileTypeForHFSTypeCode('fldr')
567                                                                                : [[self name] pathExtension]] retain];
568    return fIcon;
569}
570
571- (NSString *) name
572{
573    return fInfo->name != NULL ? [NSString stringWithUTF8String: fInfo->name] : fHashString;
574}
575
576- (BOOL) isFolder
577{
578    return fInfo->isMultifile;
579}
580
581- (uint64_t) size
582{
583    return fInfo->totalSize;
584}
585
586- (uint64_t) sizeLeft
587{
588    return fStat->leftUntilDone;
589}
590
591- (NSMutableArray *) allTrackerStats
592{
593    int count;
594    tr_tracker_stat * stats = tr_torrentTrackers(fHandle, &count);
595   
596    NSMutableArray * trackers = [NSMutableArray arrayWithCapacity: (count > 0 ? count + stats[count-1].tier : 0)];
597   
598    int prevTier = -1;
599    for (int i=0; i < count; ++i)
600    {
601        if (stats[i].tier != prevTier)
602        {
603            [trackers addObject: [NSDictionary dictionaryWithObjectsAndKeys: [NSNumber numberWithInteger: stats[i].tier], @"Tier",
604                                    [self name], @"Name", nil]];
605            prevTier = stats[i].tier;
606        }
607       
608        TrackerNode * tracker = [[TrackerNode alloc] initWithTrackerStat: &stats[i] torrent: self];
609        [trackers addObject: tracker];
610        [tracker release];
611    }
612   
613    tr_torrentTrackersFree(stats, count);
614    return trackers;
615}
616
617- (NSArray *) allTrackersFlat
618{
619    NSMutableArray * allTrackers = [NSMutableArray arrayWithCapacity: fInfo->trackerCount];
620   
621    for (NSInteger i=0; i < fInfo->trackerCount; i++)
622        [allTrackers addObject: [NSString stringWithUTF8String: fInfo->trackers[i].announce]];
623   
624    return allTrackers;
625}
626
627- (BOOL) addTrackerToNewTier: (NSString *) tracker
628{
629    tracker = [tracker stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
630   
631    if ([tracker rangeOfString: @"://"].location == NSNotFound)
632        tracker = [@"http://" stringByAppendingString: tracker];
633   
634    //recreate the tracker structure
635    const int oldTrackerCount = fInfo->trackerCount;
636    tr_tracker_info * trackerStructs = tr_new(tr_tracker_info, oldTrackerCount+1);
637    for (NSUInteger i=0; i < oldTrackerCount; ++i)
638    {
639        trackerStructs[i] = fInfo->trackers[i];
640        trackerStructs[i].id = i;
641    }
642   
643    trackerStructs[oldTrackerCount].announce = (char *)[tracker UTF8String];
644    trackerStructs[oldTrackerCount].tier = trackerStructs[oldTrackerCount-1].tier + 1;
645    trackerStructs[oldTrackerCount].id = oldTrackerCount;
646   
647    const BOOL success = tr_torrentSetAnnounceList(fHandle, trackerStructs, oldTrackerCount+1);
648    tr_free(trackerStructs);
649   
650    return success;
651}
652
653- (void) removeTrackersWithIdentifiers: (NSIndexSet *) removeIdentifiers
654{
655    //recreate the tracker structure
656    tr_tracker_info * trackerStructs = tr_new(tr_tracker_info, fInfo->trackerCount);
657   
658    NSUInteger newCount = 0;
659    for (NSUInteger i = 0; i < fInfo->trackerCount; i++)
660    {
661        if (![removeIdentifiers containsIndex: fInfo->trackers[i].id])
662        {
663            trackerStructs[newCount] = fInfo->trackers[i];
664            trackerStructs[newCount].id = newCount++;
665        }
666    }
667   
668    const BOOL success = tr_torrentSetAnnounceList(fHandle, trackerStructs, newCount);
669    NSAssert(success, @"Removing tracker addresses failed");
670   
671    tr_free(trackerStructs);
672}
673
674- (NSString *) comment
675{
676    return fInfo->comment ? [NSString stringWithUTF8String: fInfo->comment] : @"";
677}
678
679- (NSString *) creator
680{
681    return fInfo->creator ? [NSString stringWithUTF8String: fInfo->creator] : @"";
682}
683
684- (NSDate *) dateCreated
685{
686    NSInteger date = fInfo->dateCreated;
687    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
688}
689
690- (NSInteger) pieceSize
691{
692    return fInfo->pieceSize;
693}
694
695- (NSInteger) pieceCount
696{
697    return fInfo->pieceCount;
698}
699
700- (NSString *) hashString
701{
702    return fHashString;
703}
704
705- (BOOL) privateTorrent
706{
707    return fInfo->isPrivate;
708}
709
710- (NSString *) torrentLocation
711{
712    return fInfo->torrent ? [NSString stringWithUTF8String: fInfo->torrent] : @"";
713}
714
715- (NSString *) dataLocation
716{
717    if ([self isMagnet])
718        return nil;
719   
720    if ([self isFolder])
721    {
722        NSString * dataLocation = [[self currentDirectory] stringByAppendingPathComponent: [self name]];
723       
724        if (![[NSFileManager defaultManager] fileExistsAtPath: dataLocation])
725            return nil;
726       
727        return dataLocation;
728    }
729    else
730    {
731        char * location = tr_torrentFindFile(fHandle, 0);
732        if (location == NULL)
733            return nil;
734       
735        NSString * dataLocation = [NSString stringWithUTF8String: location];
736        free(location);
737       
738        return dataLocation;
739    }
740}
741
742- (NSString *) fileLocation: (FileListNode *) node
743{
744    if ([node isFolder])
745    {
746        NSString * basePath = [[node path] stringByAppendingPathComponent: [node name]];
747        NSString * dataLocation = [[self currentDirectory] stringByAppendingPathComponent: basePath];
748       
749        if (![[NSFileManager defaultManager] fileExistsAtPath: dataLocation])
750            return nil;
751       
752        return dataLocation;
753    }
754    else
755    {
756        char * location = tr_torrentFindFile(fHandle, [[node indexes] firstIndex]);
757        if (location == NULL)
758            return nil;
759       
760        NSString * dataLocation = [NSString stringWithUTF8String: location];
761        free(location);
762       
763        return dataLocation;
764    }
765}
766
767- (CGFloat) progress
768{
769    return fStat->percentComplete;
770}
771
772- (CGFloat) progressDone
773{
774    return fStat->percentDone;
775}
776
777- (CGFloat) progressLeft
778{
779    if ([self size] == 0) //magnet links
780        return 0.0;
781   
782    return (CGFloat)[self sizeLeft] / [self size];
783}
784
785- (CGFloat) checkingProgress
786{
787    return fStat->recheckProgress;
788}
789
790- (NSInteger) eta
791{
792    return fStat->eta;
793}
794
795- (CGFloat) availableDesired
796{
797    return (CGFloat)fStat->desiredAvailable / [self sizeLeft];
798}
799
800- (BOOL) isActive
801{
802    return fStat->activity != TR_STATUS_STOPPED;
803}
804
805- (BOOL) isSeeding
806{
807    return fStat->activity == TR_STATUS_SEED;
808}
809
810- (BOOL) isChecking
811{
812    return fStat->activity == TR_STATUS_CHECK || fStat->activity == TR_STATUS_CHECK_WAIT;
813}
814
815- (BOOL) isCheckingWaiting
816{
817    return fStat->activity == TR_STATUS_CHECK_WAIT;
818}
819
820- (BOOL) allDownloaded
821{
822    return [self sizeLeft] == 0 && ![self isMagnet];
823}
824
825- (BOOL) isComplete
826{
827    return [self progress] >= 1.0;
828}
829
830- (BOOL) isError
831{
832    return fStat->error == TR_STAT_LOCAL_ERROR;
833}
834
835- (BOOL) isAnyErrorOrWarning
836{
837    return fStat->error != TR_STAT_OK;
838}
839
840- (NSString *) errorMessage
841{
842    if (![self isAnyErrorOrWarning])
843        return @"";
844   
845    NSString * error;
846    if (!(error = [NSString stringWithUTF8String: fStat->errorString])
847        && !(error = [NSString stringWithCString: fStat->errorString encoding: NSISOLatin1StringEncoding]))
848        error = [NSString stringWithFormat: @"(%@)", NSLocalizedString(@"unreadable error", "Torrent -> error string unreadable")];
849   
850    //libtransmission uses "Set Location", Mac client uses "Move data file to..." - very hacky!
851    error = [error stringByReplacingOccurrencesOfString: @"Set Location" withString: [@"Move Data File To" stringByAppendingEllipsis]];
852   
853    return error;
854}
855
856- (NSArray *) peers
857{
858    int totalPeers;
859    tr_peer_stat * peers = tr_torrentPeers(fHandle, &totalPeers);
860   
861    NSMutableArray * peerDicts = [NSMutableArray arrayWithCapacity: totalPeers];
862   
863    for (int i = 0; i < totalPeers; i++)
864    {
865        tr_peer_stat * peer = &peers[i];
866        NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 11];
867       
868        [dict setObject: [self name] forKey: @"Name"];
869        [dict setObject: [NSNumber numberWithInt: peer->from] forKey: @"From"];
870        [dict setObject: [NSString stringWithUTF8String: peer->addr] forKey: @"IP"];
871        [dict setObject: [NSNumber numberWithInt: peer->port] forKey: @"Port"];
872        [dict setObject: [NSNumber numberWithFloat: peer->progress] forKey: @"Progress"];
873        [dict setObject: [NSNumber numberWithBool: peer->isSeed] forKey: @"Seed"];
874        [dict setObject: [NSNumber numberWithBool: peer->isEncrypted] forKey: @"Encryption"];
875        [dict setObject: [NSString stringWithUTF8String: peer->client] forKey: @"Client"];
876        [dict setObject: [NSString stringWithUTF8String: peer->flagStr] forKey: @"Flags"];
877       
878        if (peer->isUploadingTo)
879            [dict setObject: [NSNumber numberWithFloat: peer->rateToPeer] forKey: @"UL To Rate"];
880        if (peer->isDownloadingFrom)
881            [dict setObject: [NSNumber numberWithFloat: peer->rateToClient] forKey: @"DL From Rate"];
882       
883        [peerDicts addObject: dict];
884    }
885   
886    tr_torrentPeersFree(peers, totalPeers);
887   
888    return peerDicts;
889}
890
891- (NSUInteger) webSeedCount
892{
893    return fInfo->webseedCount;
894}
895
896- (NSArray *) webSeeds
897{
898    NSMutableArray * webSeeds = [NSMutableArray arrayWithCapacity: fInfo->webseedCount];
899   
900    float * dlSpeeds = tr_torrentWebSpeeds(fHandle);
901   
902    for (NSInteger i = 0; i < fInfo->webseedCount; i++)
903    {
904        NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 3];
905       
906        [dict setObject: [self name] forKey: @"Name"];
907        [dict setObject: [NSString stringWithUTF8String: fInfo->webseeds[i]] forKey: @"Address"];
908       
909        if (dlSpeeds[i] != -1.0)
910            [dict setObject: [NSNumber numberWithFloat: dlSpeeds[i]] forKey: @"DL From Rate"];
911       
912        [webSeeds addObject: dict];
913    }
914   
915    tr_free(dlSpeeds);
916   
917    return webSeeds;
918}
919
920- (NSString *) progressString
921{
922    if ([self isMagnet])
923    {
924        NSString * progressString = fStat->metadataPercentComplete > 0.0
925                    ? [NSString localizedStringWithFormat: NSLocalizedString(@"%.2f%% of torrent metadata retrieved",
926                        "Torrent -> progress string"), 100.0 * fStat->metadataPercentComplete]
927                    : NSLocalizedString(@"torrent metadata needed", "Torrent -> progress string");
928       
929        return [NSString stringWithFormat: @"%@ - %@", NSLocalizedString(@"Magnetized transfer", "Torrent -> progress string"),
930                                            progressString];
931    }
932   
933    NSString * string;
934   
935    if (![self allDownloaded])
936    {
937        CGFloat progress;
938        if ([self isFolder] && [fDefaults boolForKey: @"DisplayStatusProgressSelected"])
939        {
940            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@ selected", "Torrent -> progress string"),
941                        [NSString stringForFileSize: [self haveTotal]], [NSString stringForFileSize: [self totalSizeSelected]]];
942            progress = 100.0 * [self progressDone];
943        }
944        else
945        {
946            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Torrent -> progress string"),
947                        [NSString stringForFileSize: [self haveTotal]], [NSString stringForFileSize: [self size]]];
948            progress = 100.0 * [self progress];
949        }
950       
951        string = [NSString localizedStringWithFormat: @"%@ (%.2f%%)", string, progress];
952    }
953    else
954    {
955        NSString * downloadString;
956        if (![self isComplete]) //only multifile possible
957        {
958            if ([fDefaults boolForKey: @"DisplayStatusProgressSelected"])
959                downloadString = [NSString stringWithFormat: NSLocalizedString(@"%@ selected", "Torrent -> progress string"),
960                                    [NSString stringForFileSize: [self haveTotal]]];
961            else
962            {
963                downloadString = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Torrent -> progress string"),
964                                    [NSString stringForFileSize: [self haveTotal]], [NSString stringForFileSize: [self size]]];
965               
966                downloadString = [NSString localizedStringWithFormat: @"%@ (%.2f%%)", downloadString, 100.0 * [self progress]];
967            }
968        }
969        else
970            downloadString = [NSString stringForFileSize: [self size]];
971       
972        NSString * uploadString = [NSString stringWithFormat: NSLocalizedString(@"uploaded %@ (Ratio: %@)",
973                                    "Torrent -> progress string"), [NSString stringForFileSize: [self uploadedTotal]],
974                                    [NSString stringForRatio: [self ratio]]];
975       
976        string = [downloadString stringByAppendingFormat: @", %@", uploadString];
977    }
978   
979    //add time when downloading
980    if (fStat->activity == TR_STATUS_DOWNLOAD || ([self isSeeding] && [self seedRatioSet]))
981        string = [string stringByAppendingFormat: @" - %@", [self etaString]];
982   
983    return string;
984}
985
986- (NSString *) statusString
987{
988    NSString * string;
989   
990    if ([self isAnyErrorOrWarning])
991    {
992        switch (fStat->error)
993        {
994            case TR_STAT_LOCAL_ERROR: string = NSLocalizedString(@"Error", "Torrent -> status string"); break;
995            case TR_STAT_TRACKER_ERROR: string = NSLocalizedString(@"Tracker returned an error", "Torrent -> status string"); break;
996            case TR_STAT_TRACKER_WARNING: string = NSLocalizedString(@"Tracker returned a warning", "Torrent -> status string"); break;
997            default: NSAssert(NO, @"unknown error state");
998        }
999       
1000        NSString * errorString = [self errorMessage];
1001        if (errorString && ![errorString isEqualToString: @""])
1002            string = [string stringByAppendingFormat: @": %@", errorString];
1003    }
1004    else
1005    {
1006        switch (fStat->activity)
1007        {
1008            case TR_STATUS_STOPPED:
1009                if (fWaitToStart)
1010                {
1011                    string = ![self allDownloaded]
1012                            ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
1013                            : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
1014                }
1015                else if (fFinishedSeeding)
1016                    string = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
1017                else
1018                    string = NSLocalizedString(@"Paused", "Torrent -> status string");
1019                break;
1020
1021            case TR_STATUS_CHECK_WAIT:
1022                string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1023                break;
1024
1025            case TR_STATUS_CHECK:
1026                string = [NSString localizedStringWithFormat: @"%@ (%.2f%%)",
1027                            NSLocalizedString(@"Checking existing data", "Torrent -> status string"), 100.0 * [self checkingProgress]];
1028                break;
1029
1030            case TR_STATUS_DOWNLOAD:
1031                if ([self totalPeersConnected] != 1)
1032                    string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of %d peers",
1033                                                    "Torrent -> status string"), [self peersSendingToUs], [self totalPeersConnected]];
1034                else
1035                    string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of 1 peer",
1036                                                    "Torrent -> status string"), [self peersSendingToUs]];
1037               
1038                const NSInteger webSeedCount = fStat->webseedsSendingToUs;
1039                if (webSeedCount > 0)
1040                {
1041                    NSString * webSeedString;
1042                    if (webSeedCount == 1)
1043                        webSeedString = NSLocalizedString(@"web seed", "Torrent -> status string");
1044                    else
1045                        webSeedString = [NSString stringWithFormat: NSLocalizedString(@"%d web seeds", "Torrent -> status string"),
1046                                                                    webSeedCount];
1047                   
1048                    string = [string stringByAppendingFormat: @" + %@", webSeedString];
1049                }
1050               
1051                break;
1052
1053            case TR_STATUS_SEED:
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        }
1061       
1062        if (fStalled)
1063            string = [NSLocalizedString(@"Stalled", "Torrent -> status string") stringByAppendingFormat: @", %@", string];
1064    }
1065   
1066    //append even if error
1067    if ([self isActive] && ![self isChecking])
1068    {
1069        if (fStat->activity == TR_STATUS_DOWNLOAD)
1070            string = [string stringByAppendingFormat: @" - %@: %@, %@: %@",
1071                        NSLocalizedString(@"DL", "Torrent -> status string"), [NSString stringForSpeed: [self downloadRate]],
1072                        NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1073        else
1074            string = [string stringByAppendingFormat: @" - %@: %@",
1075                        NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1076    }
1077   
1078    return string;
1079}
1080
1081- (NSString *) shortStatusString
1082{
1083    NSString * string;
1084   
1085    switch (fStat->activity)
1086    {
1087        case TR_STATUS_STOPPED:
1088            if (fWaitToStart)
1089            {
1090                string = ![self allDownloaded]
1091                        ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
1092                        : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
1093            }
1094            else if (fFinishedSeeding)
1095                string = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
1096            else
1097                string = NSLocalizedString(@"Paused", "Torrent -> status string");
1098            break;
1099
1100        case TR_STATUS_CHECK_WAIT:
1101            string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1102            break;
1103
1104        case TR_STATUS_CHECK:
1105            string = [NSString localizedStringWithFormat: @"%@ (%.2f%%)",
1106                        NSLocalizedString(@"Checking existing data", "Torrent -> status string"), 100.0 * [self checkingProgress]];
1107            break;
1108       
1109        case TR_STATUS_DOWNLOAD:
1110            string = [NSString stringWithFormat: @"%@: %@, %@: %@",
1111                            NSLocalizedString(@"DL", "Torrent -> status string"), [NSString stringForSpeed: [self downloadRate]],
1112                            NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1113            break;
1114       
1115        case TR_STATUS_SEED:
1116            string = [NSString stringWithFormat: @"%@: %@, %@: %@",
1117                            NSLocalizedString(@"Ratio", "Torrent -> status string"), [NSString stringForRatio: [self ratio]],
1118                            NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1119    }
1120   
1121    return string;
1122}
1123
1124- (NSString *) remainingTimeString
1125{
1126    if (fStat->activity == TR_STATUS_DOWNLOAD || ([self isSeeding] && [self seedRatioSet]))
1127        return [self etaString];
1128    else
1129        return [self shortStatusString];
1130}
1131
1132- (NSString *) stateString
1133{
1134    switch (fStat->activity)
1135    {
1136        case TR_STATUS_STOPPED:
1137            return NSLocalizedString(@"Paused", "Torrent -> status string");
1138
1139        case TR_STATUS_CHECK:
1140            return [NSString localizedStringWithFormat: @"%@ (%.2f%%)",
1141                    NSLocalizedString(@"Checking existing data", "Torrent -> status string"), 100.0 * [self checkingProgress]];
1142       
1143        case TR_STATUS_CHECK_WAIT:
1144            return [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1145
1146        case TR_STATUS_DOWNLOAD:
1147            return NSLocalizedString(@"Downloading", "Torrent -> status string");
1148
1149        case TR_STATUS_SEED:
1150            return NSLocalizedString(@"Seeding", "Torrent -> status string");
1151    }
1152}
1153
1154- (NSInteger) totalPeersConnected
1155{
1156    return fStat->peersConnected;
1157}
1158
1159- (NSInteger) totalPeersTracker
1160{
1161    return fStat->peersFrom[TR_PEER_FROM_TRACKER];
1162}
1163
1164- (NSInteger) totalPeersIncoming
1165{
1166    return fStat->peersFrom[TR_PEER_FROM_INCOMING];
1167}
1168
1169- (NSInteger) totalPeersCache
1170{
1171    return fStat->peersFrom[TR_PEER_FROM_RESUME];
1172}
1173
1174- (NSInteger) totalPeersPex
1175{
1176    return fStat->peersFrom[TR_PEER_FROM_PEX];
1177}
1178
1179- (NSInteger) totalPeersDHT
1180{
1181    return fStat->peersFrom[TR_PEER_FROM_DHT];
1182}
1183
1184- (NSInteger) totalPeersLTEP
1185{
1186    return fStat->peersFrom[TR_PEER_FROM_LTEP];
1187}
1188
1189- (NSInteger) totalPeersKnown
1190{
1191    return fStat->peersKnown;
1192}
1193
1194- (NSInteger) peersSendingToUs
1195{
1196    return fStat->peersSendingToUs;
1197}
1198
1199- (NSInteger) peersGettingFromUs
1200{
1201    return fStat->peersGettingFromUs;
1202}
1203
1204- (CGFloat) downloadRate
1205{
1206    return fStat->pieceDownloadSpeed;
1207}
1208
1209- (CGFloat) uploadRate
1210{
1211    return fStat->pieceUploadSpeed;
1212}
1213
1214- (CGFloat) totalRate
1215{
1216    return [self downloadRate] + [self uploadRate];
1217}
1218
1219- (uint64_t) haveVerified
1220{
1221    return fStat->haveValid;
1222}
1223
1224- (uint64_t) haveTotal
1225{
1226    return [self haveVerified] + fStat->haveUnchecked;
1227}
1228
1229- (uint64_t) totalSizeSelected
1230{
1231    return fStat->sizeWhenDone;
1232}
1233
1234- (uint64_t) downloadedTotal
1235{
1236    return fStat->downloadedEver;
1237}
1238
1239- (uint64_t) uploadedTotal
1240{
1241    return fStat->uploadedEver;
1242}
1243
1244- (uint64_t) failedHash
1245{
1246    return fStat->corruptEver;
1247}
1248
1249- (NSInteger) groupValue
1250{
1251    return fGroupValue;
1252}
1253
1254- (void) setGroupValue: (NSInteger) goupValue
1255{
1256    fGroupValue = goupValue;
1257}
1258
1259- (NSInteger) groupOrderValue
1260{
1261    return [[GroupsController groups] rowValueForIndex: fGroupValue];
1262}
1263
1264- (void) checkGroupValueForRemoval: (NSNotification *) notification
1265{
1266    if (fGroupValue != -1 && [[[notification userInfo] objectForKey: @"Index"] integerValue] == fGroupValue)
1267        fGroupValue = -1;
1268}
1269
1270- (NSArray *) fileList
1271{
1272    return fFileList;
1273}
1274
1275- (NSArray *) flatFileList
1276{
1277    return fFlatFileList;
1278}
1279
1280- (NSInteger) fileCount
1281{
1282    return fInfo->fileCount;
1283}
1284
1285- (void) updateFileStat
1286{
1287    if (fFileStat)
1288        tr_torrentFilesFree(fFileStat, [self fileCount]);
1289   
1290    fFileStat = tr_torrentFiles(fHandle, NULL);
1291}
1292
1293- (CGFloat) fileProgress: (FileListNode *) node
1294{
1295    if ([self fileCount] == 1 || [self isComplete])
1296        return [self progress];
1297   
1298    if (!fFileStat)
1299        [self updateFileStat];
1300   
1301    NSIndexSet * indexSet = [node indexes];
1302   
1303    if ([indexSet count] == 1)
1304        return fFileStat[[indexSet firstIndex]].progress;
1305   
1306    uint64_t have = 0;
1307    for (NSInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1308        have += fFileStat[index].bytesCompleted;
1309   
1310    NSAssert([node size], @"directory in torrent file has size 0");
1311    return (CGFloat)have / [node size];
1312}
1313
1314- (BOOL) canChangeDownloadCheckForFile: (NSUInteger) index
1315{
1316    NSAssert2(index < [self fileCount], @"Index %d is greater than file count %d", index, [self fileCount]);
1317   
1318    if ([self fileCount] == 1 || [self isComplete])
1319        return NO;
1320   
1321    if (!fFileStat)
1322        [self updateFileStat];
1323   
1324    return fFileStat[index].progress < 1.0;
1325}
1326
1327- (BOOL) canChangeDownloadCheckForFiles: (NSIndexSet *) indexSet
1328{
1329    if ([self fileCount] == 1 || [self isComplete])
1330        return NO;
1331   
1332    if (!fFileStat)
1333        [self updateFileStat];
1334   
1335    for (NSUInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1336        if (fFileStat[index].progress < 1.0)
1337            return YES;
1338    return NO;
1339}
1340
1341- (NSInteger) checkForFiles: (NSIndexSet *) indexSet
1342{
1343    NSAssert(indexSet != nil, @"indexSet must not be nil");
1344   
1345    BOOL onState = NO, offState = NO;
1346    for (NSUInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1347    {
1348        if (!fInfo->files[index].dnd || ![self canChangeDownloadCheckForFile: index])
1349            onState = YES;
1350        else
1351            offState = YES;
1352       
1353        if (onState && offState)
1354            return NSMixedState;
1355    }
1356    return onState ? NSOnState : NSOffState;
1357}
1358
1359- (void) setFileCheckState: (NSInteger) state forIndexes: (NSIndexSet *) indexSet
1360{
1361    NSUInteger count = [indexSet count];
1362    tr_file_index_t * files = malloc(count * sizeof(tr_file_index_t));
1363    for (NSUInteger index = [indexSet firstIndex], i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index], i++)
1364        files[i] = index;
1365   
1366    tr_torrentSetFileDLs(fHandle, files, count, state != NSOffState);
1367    free(files);
1368   
1369    [self update];
1370    [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFileCheckChange" object: self];
1371}
1372
1373- (void) setFilePriority: (tr_priority_t) priority forIndexes: (NSIndexSet *) indexSet
1374{
1375    const NSUInteger count = [indexSet count];
1376    tr_file_index_t * files = tr_malloc(count * sizeof(tr_file_index_t));
1377    for (NSUInteger index = [indexSet firstIndex], i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index], i++)
1378        files[i] = index;
1379   
1380    tr_torrentSetFilePriorities(fHandle, files, count, priority);
1381    tr_free(files);
1382}
1383
1384- (BOOL) hasFilePriority: (tr_priority_t) priority forIndexes: (NSIndexSet *) indexSet
1385{
1386    for (NSUInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1387        if (priority == fInfo->files[index].priority && [self canChangeDownloadCheckForFile: index])
1388            return YES;
1389    return NO;
1390}
1391
1392- (NSSet *) filePrioritiesForIndexes: (NSIndexSet *) indexSet
1393{
1394    BOOL low = NO, normal = NO, high = NO;
1395    NSMutableSet * priorities = [NSMutableSet setWithCapacity: MIN([indexSet count], 3)];
1396   
1397    for (NSUInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1398    {
1399        if (![self canChangeDownloadCheckForFile: index])
1400            continue;
1401       
1402        const tr_priority_t priority = fInfo->files[index].priority;
1403        switch (priority)
1404        {
1405            case TR_PRI_LOW:
1406                if (low)
1407                    continue;
1408                low = YES;
1409                break;
1410            case TR_PRI_NORMAL:
1411                if (normal)
1412                    continue;
1413                normal = YES;
1414                break;
1415            case TR_PRI_HIGH:
1416                if (high)
1417                    continue;
1418                high = YES;
1419                break;
1420            default:
1421                NSAssert2(NO, @"Unknown priority %d for file index %d", priority, index);
1422        }
1423       
1424        [priorities addObject: [NSNumber numberWithInteger: priority]];
1425        if (low && normal && high)
1426            break;
1427    }
1428    return priorities;
1429}
1430
1431- (NSDate *) dateAdded
1432{
1433    const time_t date = fStat->addedDate;
1434    return [NSDate dateWithTimeIntervalSince1970: date];
1435}
1436
1437- (NSDate *) dateCompleted
1438{
1439    const time_t date = fStat->doneDate;
1440    return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
1441}
1442
1443- (NSDate *) dateActivity
1444{
1445    const time_t date = fStat->activityDate;
1446    return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
1447}
1448
1449- (NSDate *) dateActivityOrAdd
1450{
1451    NSDate * date = [self dateActivity];
1452    return date ? date : [self dateAdded];
1453}
1454
1455- (NSInteger) stalledMinutes
1456{
1457    const time_t start = fStat->startDate;
1458    if (start == 0)
1459        return -1;
1460   
1461    NSDate * started = [NSDate dateWithTimeIntervalSince1970: start],
1462            * activity = [self dateActivity];
1463   
1464    NSDate * laterDate = activity ? [started laterDate: activity] : started;
1465   
1466    return ABS([laterDate timeIntervalSinceNow]) / 60;
1467}
1468
1469- (BOOL) isStalled
1470{
1471    return fStalled;
1472}
1473
1474- (void) updateTimeMachineExclude
1475{
1476    NSString * currentLocation = ![self allDownloaded] ? [self dataLocation] : nil;
1477   
1478    //return if the locations are the same
1479    if (fTimeMachineExclude && currentLocation && [fTimeMachineExclude isEqualToString: currentLocation])
1480        return;
1481   
1482    //remove old location...
1483    if (fTimeMachineExclude)
1484    {
1485        [self setTimeMachineExclude: NO forPath: fTimeMachineExclude];
1486        [fTimeMachineExclude release];
1487        fTimeMachineExclude = nil;
1488    }
1489   
1490    //...set new location
1491    if (currentLocation)
1492    {
1493        [self setTimeMachineExclude: YES forPath: currentLocation];
1494        fTimeMachineExclude = [currentLocation retain];
1495    }
1496}
1497
1498- (NSInteger) stateSortKey
1499{
1500    if (![self isActive]) //paused
1501    {
1502        if (fWaitToStart)
1503            return 1;
1504        else
1505            return 0;
1506    }
1507    else if ([self isSeeding]) //seeding
1508        return 10;
1509    else //downloading
1510        return 20;
1511}
1512
1513- (NSString *) trackerSortKey
1514{
1515    int count;
1516    tr_tracker_stat * stats = tr_torrentTrackers(fHandle, &count);
1517   
1518    NSString * best = nil;
1519   
1520    for (int i=0; i < count; ++i)
1521    {
1522        NSString * tracker = [NSString stringWithUTF8String: stats[i].host];
1523        if (!best || [tracker localizedCaseInsensitiveCompare: best] == NSOrderedAscending)
1524            best = tracker;
1525    }
1526   
1527    tr_torrentTrackersFree(stats, count);
1528    return best;
1529}
1530
1531- (tr_torrent *) torrentStruct
1532{
1533    return fHandle;
1534}
1535
1536- (NSURL *) previewItemURL
1537{
1538    NSString * location = [self dataLocation];
1539    return location ? [NSURL fileURLWithPath: location] : nil;
1540}
1541
1542@end
1543
1544@implementation Torrent (Private)
1545
1546- (id) initWithPath: (NSString *) path hash: (NSString *) hashString torrentStruct: (tr_torrent *) torrentStruct
1547        magnetAddress: (NSString *) magnetAddress lib: (tr_session *) lib
1548        waitToStart: (NSNumber *) waitToStart
1549        groupValue: (NSNumber *) groupValue
1550        downloadFolder: (NSString *) downloadFolder legacyIncompleteFolder: (NSString *) incompleteFolder
1551{
1552    if (!(self = [super init]))
1553        return nil;
1554   
1555    fDefaults = [NSUserDefaults standardUserDefaults];
1556   
1557    if (torrentStruct)
1558        fHandle = torrentStruct;
1559    else
1560    {
1561        //set libtransmission settings for initialization
1562        tr_ctor * ctor = tr_ctorNew(lib);
1563       
1564        tr_ctorSetPaused(ctor, TR_FORCE, YES);
1565        if (downloadFolder)
1566            tr_ctorSetDownloadDir(ctor, TR_FORCE, [downloadFolder UTF8String]);
1567        if (incompleteFolder)
1568            tr_ctorSetIncompleteDir(ctor, [incompleteFolder UTF8String]);
1569       
1570        tr_parse_result result = TR_PARSE_ERR;
1571        if (path)
1572            result = tr_ctorSetMetainfoFromFile(ctor, [path UTF8String]);
1573       
1574        if (result != TR_PARSE_OK && magnetAddress)
1575            result = tr_ctorSetMetainfoFromMagnetLink(ctor, [magnetAddress UTF8String]);
1576       
1577        //backup - shouldn't be needed after upgrade to 1.70
1578        if (result != TR_PARSE_OK && hashString)
1579            result = tr_ctorSetMetainfoFromHash(ctor, [hashString UTF8String]);
1580       
1581        if (result == TR_PARSE_OK)
1582            fHandle = tr_torrentNew(ctor, NULL);
1583       
1584        tr_ctorFree(ctor);
1585       
1586        if (!fHandle)
1587        {
1588            [self release];
1589            return nil;
1590        }
1591    }
1592
1593    fInfo = tr_torrentInfo(fHandle);
1594   
1595    tr_torrentSetCompletenessCallback(fHandle, completenessChangeCallback, self);
1596    tr_torrentSetRatioLimitHitCallback(fHandle, ratioLimitHitCallback, self);
1597    tr_torrentSetMetadataCallback(fHandle, metadataCallback, self);
1598   
1599    fHashString = [[NSString alloc] initWithUTF8String: fInfo->hashString];
1600       
1601    fFinishedSeeding = NO;
1602   
1603    fWaitToStart = waitToStart && [waitToStart boolValue];
1604    fResumeOnWake = NO;
1605   
1606    //don't do after this point - it messes with auto-group functionality
1607    if (![self isMagnet])
1608        [self createFileList];
1609       
1610    fGroupValue = groupValue ? [groupValue intValue] : [[GroupsController groups] groupIndexForTorrent: self];
1611   
1612    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(checkGroupValueForRemoval:)
1613        name: @"GroupValueRemoved" object: nil];
1614   
1615    fTimeMachineExclude = nil;
1616    [self update];
1617   
1618    return self;
1619}
1620
1621- (void) createFileList
1622{
1623    NSAssert(![self isMagnet], @"Cannot create a file list until the torrent is demagnetized");
1624   
1625    if ([self isFolder])
1626    {
1627        NSInteger count = [self fileCount];
1628        NSMutableArray * fileList = [NSMutableArray arrayWithCapacity: count],
1629                    * flatFileList = [NSMutableArray arrayWithCapacity: count];
1630       
1631        for (NSInteger i = 0; i < count; i++)
1632        {
1633            tr_file * file = &fInfo->files[i];
1634           
1635            NSString * fullPath = [NSString stringWithUTF8String: file->name];
1636            NSArray * pathComponents = [fullPath pathComponents];
1637            NSAssert1([pathComponents count] >= 2, @"Not enough components in path %@", fullPath);
1638           
1639            NSString * path = [pathComponents objectAtIndex: 0];
1640            NSString * name = [pathComponents objectAtIndex: 1];
1641           
1642            if ([pathComponents count] > 2)
1643            {
1644                //determine if folder node already exists
1645                FileListNode * node;
1646                for (node in fileList)
1647                    if ([[node name] isEqualToString: name] && [node isFolder])
1648                        break;
1649               
1650                if (!node)
1651                {
1652                    node = [[FileListNode alloc] initWithFolderName: name path: path];
1653                    [fileList addObject: node];
1654                    [node release];
1655                }
1656               
1657                NSMutableArray * trimmedComponents = [NSMutableArray arrayWithArray: [pathComponents subarrayWithRange:
1658                                                        NSMakeRange(2, [pathComponents count]-2)]];
1659               
1660                [node insertIndex: i withSize: file->length];
1661                [self insertPath: trimmedComponents forParent: node fileSize: file->length index: i flatList: flatFileList];
1662            }
1663            else
1664            {
1665                FileListNode * node = [[FileListNode alloc] initWithFileName: name path: path size: file->length index: i];
1666                [fileList addObject: node];
1667                [flatFileList addObject: node];
1668                [node release];
1669            }
1670        }
1671       
1672        fFileList = [[NSArray alloc] initWithArray: fileList];
1673        fFlatFileList = [[NSArray alloc] initWithArray: flatFileList];
1674    }
1675    else
1676    {
1677        FileListNode * node = [[FileListNode alloc] initWithFileName: [self name] path: @"" size: [self size] index: 0];
1678        fFileList = [[NSArray arrayWithObject: node] retain];
1679        fFlatFileList = [fFileList retain];
1680        [node release];
1681    }
1682}
1683
1684- (void) insertPath: (NSMutableArray *) components forParent: (FileListNode *) parent fileSize: (uint64_t) size
1685    index: (NSInteger) index flatList: (NSMutableArray *) flatFileList
1686{
1687    NSString * name = [components objectAtIndex: 0];
1688    const BOOL isFolder = [components count] > 1;
1689   
1690    FileListNode * node = nil;
1691    if (isFolder)
1692    {
1693        for (node in [parent children])
1694            if ([[node name] isEqualToString: name] && [node isFolder])
1695                break;
1696    }
1697   
1698    //create new folder or file if it doesn't already exist
1699    if (!node)
1700    {
1701        NSString * path = [[parent path] stringByAppendingPathComponent: [parent name]];
1702        if (isFolder)
1703            node = [[FileListNode alloc] initWithFolderName: name path: path];
1704        else
1705        {
1706            node = [[FileListNode alloc] initWithFileName: name path: path size: size index: index];
1707            [flatFileList addObject: node];
1708        }
1709       
1710        [parent insertChild: node];
1711        [node release];
1712    }
1713   
1714    if (isFolder)
1715    {
1716        [node insertIndex: index withSize: size];
1717       
1718        [components removeObjectAtIndex: 0];
1719        [self insertPath: components forParent: node fileSize: size index: index flatList: flatFileList];
1720    }
1721}
1722
1723//status has been retained
1724- (void) completenessChange: (NSNumber *) status
1725{
1726    fStat = tr_torrentStat(fHandle); //don't call update yet to avoid auto-stop
1727   
1728    switch ([status intValue])
1729    {
1730        case TR_SEED:
1731        case TR_PARTIAL_SEED:
1732            [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedDownloading" object: self];
1733            break;
1734       
1735        case TR_LEECH:
1736            [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentRestartedDownloading" object: self];
1737            break;
1738    }
1739    [status release];
1740   
1741    [self update];
1742    [self updateTimeMachineExclude];
1743}
1744
1745- (void) ratioLimitHit
1746{
1747    fStat = tr_torrentStat(fHandle);
1748   
1749    [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentStoppedForRatio" object: self];
1750   
1751    fFinishedSeeding = YES;
1752}
1753
1754- (void) metadataRetrieved
1755{
1756    fStat = tr_torrentStat(fHandle);
1757   
1758    [self createFileList];
1759   
1760    [[NSNotificationCenter defaultCenter] postNotificationName: @"ResetInspector" object: self];
1761}
1762
1763- (NSString *) etaString
1764{
1765    const NSInteger eta = [self eta];
1766    switch (eta)
1767    {
1768        case TR_ETA_NOT_AVAIL:
1769        case TR_ETA_UNKNOWN:
1770            return NSLocalizedString(@"remaining time unknown", "Torrent -> eta string");
1771        default:
1772            return [NSString stringWithFormat: NSLocalizedString(@"%@ remaining", "Torrent -> eta string"),
1773                        [NSString timeString: eta showSeconds: YES maxFields: 2]];
1774    }
1775}
1776
1777- (void) setTimeMachineExclude: (BOOL) exclude forPath: (NSString *) path
1778{
1779    CSBackupSetItemExcluded((CFURLRef)[NSURL fileURLWithPath: path], exclude, true);
1780}
1781
1782@end
Note: See TracBrowser for help on using the repository browser.