source: trunk/macosx/Torrent.m @ 10255

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

avoid unnecessary setting of id when calling tr_torrentSetAnnounceList

  • Property svn:keywords set to Date Rev Author Id
File size: 55.2 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 10255 2010-02-22 00:15:27Z 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_new
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 + 1) : 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 + 1], @"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        trackerStructs[i] = fInfo->trackers[i];
639   
640    trackerStructs[oldTrackerCount].announce = (char *)[tracker UTF8String];
641    trackerStructs[oldTrackerCount].tier = trackerStructs[oldTrackerCount-1].tier + 1;
642    trackerStructs[oldTrackerCount].id = oldTrackerCount;
643   
644    const BOOL success = tr_torrentSetAnnounceList(fHandle, trackerStructs, oldTrackerCount+1);
645    tr_free(trackerStructs);
646   
647    return success;
648}
649
650- (void) removeTrackersWithIdentifiers: (NSIndexSet *) removeIdentifiers
651{
652    //recreate the tracker structure
653    tr_tracker_info * trackerStructs = tr_new(tr_tracker_info, fInfo->trackerCount);
654   
655    NSUInteger newCount = 0;
656    for (NSUInteger i = 0; i < fInfo->trackerCount; i++)
657    {
658        if (![removeIdentifiers containsIndex: fInfo->trackers[i].id])
659            trackerStructs[newCount++] = fInfo->trackers[i];
660    }
661   
662    const BOOL success = tr_torrentSetAnnounceList(fHandle, trackerStructs, newCount);
663    NSAssert(success, @"Removing tracker addresses failed");
664   
665    tr_free(trackerStructs);
666}
667
668- (NSString *) comment
669{
670    return fInfo->comment ? [NSString stringWithUTF8String: fInfo->comment] : @"";
671}
672
673- (NSString *) creator
674{
675    return fInfo->creator ? [NSString stringWithUTF8String: fInfo->creator] : @"";
676}
677
678- (NSDate *) dateCreated
679{
680    NSInteger date = fInfo->dateCreated;
681    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
682}
683
684- (NSInteger) pieceSize
685{
686    return fInfo->pieceSize;
687}
688
689- (NSInteger) pieceCount
690{
691    return fInfo->pieceCount;
692}
693
694- (NSString *) hashString
695{
696    return fHashString;
697}
698
699- (BOOL) privateTorrent
700{
701    return fInfo->isPrivate;
702}
703
704- (NSString *) torrentLocation
705{
706    return fInfo->torrent ? [NSString stringWithUTF8String: fInfo->torrent] : @"";
707}
708
709- (NSString *) dataLocation
710{
711    if ([self isMagnet])
712        return nil;
713   
714    if ([self isFolder])
715    {
716        NSString * dataLocation = [[self currentDirectory] stringByAppendingPathComponent: [self name]];
717       
718        if (![[NSFileManager defaultManager] fileExistsAtPath: dataLocation])
719            return nil;
720       
721        return dataLocation;
722    }
723    else
724    {
725        char * location = tr_torrentFindFile(fHandle, 0);
726        if (location == NULL)
727            return nil;
728       
729        NSString * dataLocation = [NSString stringWithUTF8String: location];
730        free(location);
731       
732        return dataLocation;
733    }
734}
735
736- (NSString *) fileLocation: (FileListNode *) node
737{
738    if ([node isFolder])
739    {
740        NSString * basePath = [[node path] stringByAppendingPathComponent: [node name]];
741        NSString * dataLocation = [[self currentDirectory] stringByAppendingPathComponent: basePath];
742       
743        if (![[NSFileManager defaultManager] fileExistsAtPath: dataLocation])
744            return nil;
745       
746        return dataLocation;
747    }
748    else
749    {
750        char * location = tr_torrentFindFile(fHandle, [[node indexes] firstIndex]);
751        if (location == NULL)
752            return nil;
753       
754        NSString * dataLocation = [NSString stringWithUTF8String: location];
755        free(location);
756       
757        return dataLocation;
758    }
759}
760
761- (CGFloat) progress
762{
763    return fStat->percentComplete;
764}
765
766- (CGFloat) progressDone
767{
768    return fStat->percentDone;
769}
770
771- (CGFloat) progressLeft
772{
773    if ([self size] == 0) //magnet links
774        return 0.0;
775   
776    return (CGFloat)[self sizeLeft] / [self size];
777}
778
779- (CGFloat) checkingProgress
780{
781    return fStat->recheckProgress;
782}
783
784- (NSInteger) eta
785{
786    return fStat->eta;
787}
788
789- (CGFloat) availableDesired
790{
791    return (CGFloat)fStat->desiredAvailable / [self sizeLeft];
792}
793
794- (BOOL) isActive
795{
796    return fStat->activity != TR_STATUS_STOPPED;
797}
798
799- (BOOL) isSeeding
800{
801    return fStat->activity == TR_STATUS_SEED;
802}
803
804- (BOOL) isChecking
805{
806    return fStat->activity == TR_STATUS_CHECK || fStat->activity == TR_STATUS_CHECK_WAIT;
807}
808
809- (BOOL) isCheckingWaiting
810{
811    return fStat->activity == TR_STATUS_CHECK_WAIT;
812}
813
814- (BOOL) allDownloaded
815{
816    return [self sizeLeft] == 0 && ![self isMagnet];
817}
818
819- (BOOL) isComplete
820{
821    return [self progress] >= 1.0;
822}
823
824- (BOOL) isError
825{
826    return fStat->error == TR_STAT_LOCAL_ERROR;
827}
828
829- (BOOL) isAnyErrorOrWarning
830{
831    return fStat->error != TR_STAT_OK;
832}
833
834- (NSString *) errorMessage
835{
836    if (![self isAnyErrorOrWarning])
837        return @"";
838   
839    NSString * error;
840    if (!(error = [NSString stringWithUTF8String: fStat->errorString])
841        && !(error = [NSString stringWithCString: fStat->errorString encoding: NSISOLatin1StringEncoding]))
842        error = [NSString stringWithFormat: @"(%@)", NSLocalizedString(@"unreadable error", "Torrent -> error string unreadable")];
843   
844    //libtransmission uses "Set Location", Mac client uses "Move data file to..." - very hacky!
845    error = [error stringByReplacingOccurrencesOfString: @"Set Location" withString: [@"Move Data File To" stringByAppendingEllipsis]];
846   
847    return error;
848}
849
850- (NSArray *) peers
851{
852    int totalPeers;
853    tr_peer_stat * peers = tr_torrentPeers(fHandle, &totalPeers);
854   
855    NSMutableArray * peerDicts = [NSMutableArray arrayWithCapacity: totalPeers];
856   
857    for (int i = 0; i < totalPeers; i++)
858    {
859        tr_peer_stat * peer = &peers[i];
860        NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 11];
861       
862        [dict setObject: [self name] forKey: @"Name"];
863        [dict setObject: [NSNumber numberWithInt: peer->from] forKey: @"From"];
864        [dict setObject: [NSString stringWithUTF8String: peer->addr] forKey: @"IP"];
865        [dict setObject: [NSNumber numberWithInt: peer->port] forKey: @"Port"];
866        [dict setObject: [NSNumber numberWithFloat: peer->progress] forKey: @"Progress"];
867        [dict setObject: [NSNumber numberWithBool: peer->isSeed] forKey: @"Seed"];
868        [dict setObject: [NSNumber numberWithBool: peer->isEncrypted] forKey: @"Encryption"];
869        [dict setObject: [NSString stringWithUTF8String: peer->client] forKey: @"Client"];
870        [dict setObject: [NSString stringWithUTF8String: peer->flagStr] forKey: @"Flags"];
871       
872        if (peer->isUploadingTo)
873            [dict setObject: [NSNumber numberWithFloat: peer->rateToPeer] forKey: @"UL To Rate"];
874        if (peer->isDownloadingFrom)
875            [dict setObject: [NSNumber numberWithFloat: peer->rateToClient] forKey: @"DL From Rate"];
876       
877        [peerDicts addObject: dict];
878    }
879   
880    tr_torrentPeersFree(peers, totalPeers);
881   
882    return peerDicts;
883}
884
885- (NSUInteger) webSeedCount
886{
887    return fInfo->webseedCount;
888}
889
890- (NSArray *) webSeeds
891{
892    NSMutableArray * webSeeds = [NSMutableArray arrayWithCapacity: fInfo->webseedCount];
893   
894    float * dlSpeeds = tr_torrentWebSpeeds(fHandle);
895   
896    for (NSInteger i = 0; i < fInfo->webseedCount; i++)
897    {
898        NSMutableDictionary * dict = [NSMutableDictionary dictionaryWithCapacity: 3];
899       
900        [dict setObject: [self name] forKey: @"Name"];
901        [dict setObject: [NSString stringWithUTF8String: fInfo->webseeds[i]] forKey: @"Address"];
902       
903        if (dlSpeeds[i] != -1.0)
904            [dict setObject: [NSNumber numberWithFloat: dlSpeeds[i]] forKey: @"DL From Rate"];
905       
906        [webSeeds addObject: dict];
907    }
908   
909    tr_free(dlSpeeds);
910   
911    return webSeeds;
912}
913
914- (NSString *) progressString
915{
916    if ([self isMagnet])
917    {
918        NSString * progressString = fStat->metadataPercentComplete > 0.0
919                    ? [NSString localizedStringWithFormat: NSLocalizedString(@"%.2f%% of torrent metadata retrieved",
920                        "Torrent -> progress string"), 100.0 * fStat->metadataPercentComplete]
921                    : NSLocalizedString(@"torrent metadata needed", "Torrent -> progress string");
922       
923        return [NSString stringWithFormat: @"%@ - %@", NSLocalizedString(@"Magnetized transfer", "Torrent -> progress string"),
924                                            progressString];
925    }
926   
927    NSString * string;
928   
929    if (![self allDownloaded])
930    {
931        CGFloat progress;
932        if ([self isFolder] && [fDefaults boolForKey: @"DisplayStatusProgressSelected"])
933        {
934            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@ selected", "Torrent -> progress string"),
935                        [NSString stringForFileSize: [self haveTotal]], [NSString stringForFileSize: [self totalSizeSelected]]];
936            progress = 100.0 * [self progressDone];
937        }
938        else
939        {
940            string = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Torrent -> progress string"),
941                        [NSString stringForFileSize: [self haveTotal]], [NSString stringForFileSize: [self size]]];
942            progress = 100.0 * [self progress];
943        }
944       
945        string = [NSString localizedStringWithFormat: @"%@ (%.2f%%)", string, progress];
946    }
947    else
948    {
949        NSString * downloadString;
950        if (![self isComplete]) //only multifile possible
951        {
952            if ([fDefaults boolForKey: @"DisplayStatusProgressSelected"])
953                downloadString = [NSString stringWithFormat: NSLocalizedString(@"%@ selected", "Torrent -> progress string"),
954                                    [NSString stringForFileSize: [self haveTotal]]];
955            else
956            {
957                downloadString = [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "Torrent -> progress string"),
958                                    [NSString stringForFileSize: [self haveTotal]], [NSString stringForFileSize: [self size]]];
959               
960                downloadString = [NSString localizedStringWithFormat: @"%@ (%.2f%%)", downloadString, 100.0 * [self progress]];
961            }
962        }
963        else
964            downloadString = [NSString stringForFileSize: [self size]];
965       
966        NSString * uploadString = [NSString stringWithFormat: NSLocalizedString(@"uploaded %@ (Ratio: %@)",
967                                    "Torrent -> progress string"), [NSString stringForFileSize: [self uploadedTotal]],
968                                    [NSString stringForRatio: [self ratio]]];
969       
970        string = [downloadString stringByAppendingFormat: @", %@", uploadString];
971    }
972   
973    //add time when downloading
974    if (fStat->activity == TR_STATUS_DOWNLOAD || ([self isSeeding] && [self seedRatioSet]))
975        string = [string stringByAppendingFormat: @" - %@", [self etaString]];
976   
977    return string;
978}
979
980- (NSString *) statusString
981{
982    NSString * string;
983   
984    if ([self isAnyErrorOrWarning])
985    {
986        switch (fStat->error)
987        {
988            case TR_STAT_LOCAL_ERROR: string = NSLocalizedString(@"Error", "Torrent -> status string"); break;
989            case TR_STAT_TRACKER_ERROR: string = NSLocalizedString(@"Tracker returned an error", "Torrent -> status string"); break;
990            case TR_STAT_TRACKER_WARNING: string = NSLocalizedString(@"Tracker returned a warning", "Torrent -> status string"); break;
991            default: NSAssert(NO, @"unknown error state");
992        }
993       
994        NSString * errorString = [self errorMessage];
995        if (errorString && ![errorString isEqualToString: @""])
996            string = [string stringByAppendingFormat: @": %@", errorString];
997    }
998    else
999    {
1000        switch (fStat->activity)
1001        {
1002            case TR_STATUS_STOPPED:
1003                if (fWaitToStart)
1004                {
1005                    string = ![self allDownloaded]
1006                            ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
1007                            : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
1008                }
1009                else if (fFinishedSeeding)
1010                    string = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
1011                else
1012                    string = NSLocalizedString(@"Paused", "Torrent -> status string");
1013                break;
1014
1015            case TR_STATUS_CHECK_WAIT:
1016                string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1017                break;
1018
1019            case TR_STATUS_CHECK:
1020                string = [NSString localizedStringWithFormat: @"%@ (%.2f%%)",
1021                            NSLocalizedString(@"Checking existing data", "Torrent -> status string"), 100.0 * [self checkingProgress]];
1022                break;
1023
1024            case TR_STATUS_DOWNLOAD:
1025                if ([self totalPeersConnected] != 1)
1026                    string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of %d peers",
1027                                                    "Torrent -> status string"), [self peersSendingToUs], [self totalPeersConnected]];
1028                else
1029                    string = [NSString stringWithFormat: NSLocalizedString(@"Downloading from %d of 1 peer",
1030                                                    "Torrent -> status string"), [self peersSendingToUs]];
1031               
1032                const NSInteger webSeedCount = fStat->webseedsSendingToUs;
1033                if (webSeedCount > 0)
1034                {
1035                    NSString * webSeedString;
1036                    if (webSeedCount == 1)
1037                        webSeedString = NSLocalizedString(@"web seed", "Torrent -> status string");
1038                    else
1039                        webSeedString = [NSString stringWithFormat: NSLocalizedString(@"%d web seeds", "Torrent -> status string"),
1040                                                                    webSeedCount];
1041                   
1042                    string = [string stringByAppendingFormat: @" + %@", webSeedString];
1043                }
1044               
1045                break;
1046
1047            case TR_STATUS_SEED:
1048                if ([self totalPeersConnected] != 1)
1049                    string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of %d peers", "Torrent -> status string"),
1050                                                    [self peersGettingFromUs], [self totalPeersConnected]];
1051                else
1052                    string = [NSString stringWithFormat: NSLocalizedString(@"Seeding to %d of 1 peer", "Torrent -> status string"),
1053                                                    [self peersGettingFromUs]];
1054        }
1055       
1056        if (fStalled)
1057            string = [NSLocalizedString(@"Stalled", "Torrent -> status string") stringByAppendingFormat: @", %@", string];
1058    }
1059   
1060    //append even if error
1061    if ([self isActive] && ![self isChecking])
1062    {
1063        if (fStat->activity == TR_STATUS_DOWNLOAD)
1064            string = [string stringByAppendingFormat: @" - %@: %@, %@: %@",
1065                        NSLocalizedString(@"DL", "Torrent -> status string"), [NSString stringForSpeed: [self downloadRate]],
1066                        NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1067        else
1068            string = [string stringByAppendingFormat: @" - %@: %@",
1069                        NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1070    }
1071   
1072    return string;
1073}
1074
1075- (NSString *) shortStatusString
1076{
1077    NSString * string;
1078   
1079    switch (fStat->activity)
1080    {
1081        case TR_STATUS_STOPPED:
1082            if (fWaitToStart)
1083            {
1084                string = ![self allDownloaded]
1085                        ? [NSLocalizedString(@"Waiting to download", "Torrent -> status string") stringByAppendingEllipsis]
1086                        : [NSLocalizedString(@"Waiting to seed", "Torrent -> status string") stringByAppendingEllipsis];
1087            }
1088            else if (fFinishedSeeding)
1089                string = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
1090            else
1091                string = NSLocalizedString(@"Paused", "Torrent -> status string");
1092            break;
1093
1094        case TR_STATUS_CHECK_WAIT:
1095            string = [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1096            break;
1097
1098        case TR_STATUS_CHECK:
1099            string = [NSString localizedStringWithFormat: @"%@ (%.2f%%)",
1100                        NSLocalizedString(@"Checking existing data", "Torrent -> status string"), 100.0 * [self checkingProgress]];
1101            break;
1102       
1103        case TR_STATUS_DOWNLOAD:
1104            string = [NSString stringWithFormat: @"%@: %@, %@: %@",
1105                            NSLocalizedString(@"DL", "Torrent -> status string"), [NSString stringForSpeed: [self downloadRate]],
1106                            NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1107            break;
1108       
1109        case TR_STATUS_SEED:
1110            string = [NSString stringWithFormat: @"%@: %@, %@: %@",
1111                            NSLocalizedString(@"Ratio", "Torrent -> status string"), [NSString stringForRatio: [self ratio]],
1112                            NSLocalizedString(@"UL", "Torrent -> status string"), [NSString stringForSpeed: [self uploadRate]]];
1113    }
1114   
1115    return string;
1116}
1117
1118- (NSString *) remainingTimeString
1119{
1120    if (fStat->activity == TR_STATUS_DOWNLOAD || ([self isSeeding] && [self seedRatioSet]))
1121        return [self etaString];
1122    else
1123        return [self shortStatusString];
1124}
1125
1126- (NSString *) stateString
1127{
1128    switch (fStat->activity)
1129    {
1130        case TR_STATUS_STOPPED:
1131            return NSLocalizedString(@"Paused", "Torrent -> status string");
1132
1133        case TR_STATUS_CHECK:
1134            return [NSString localizedStringWithFormat: @"%@ (%.2f%%)",
1135                    NSLocalizedString(@"Checking existing data", "Torrent -> status string"), 100.0 * [self checkingProgress]];
1136       
1137        case TR_STATUS_CHECK_WAIT:
1138            return [NSLocalizedString(@"Waiting to check existing data", "Torrent -> status string") stringByAppendingEllipsis];
1139
1140        case TR_STATUS_DOWNLOAD:
1141            return NSLocalizedString(@"Downloading", "Torrent -> status string");
1142
1143        case TR_STATUS_SEED:
1144            return NSLocalizedString(@"Seeding", "Torrent -> status string");
1145    }
1146}
1147
1148- (NSInteger) totalPeersConnected
1149{
1150    return fStat->peersConnected;
1151}
1152
1153- (NSInteger) totalPeersTracker
1154{
1155    return fStat->peersFrom[TR_PEER_FROM_TRACKER];
1156}
1157
1158- (NSInteger) totalPeersIncoming
1159{
1160    return fStat->peersFrom[TR_PEER_FROM_INCOMING];
1161}
1162
1163- (NSInteger) totalPeersCache
1164{
1165    return fStat->peersFrom[TR_PEER_FROM_RESUME];
1166}
1167
1168- (NSInteger) totalPeersPex
1169{
1170    return fStat->peersFrom[TR_PEER_FROM_PEX];
1171}
1172
1173- (NSInteger) totalPeersDHT
1174{
1175    return fStat->peersFrom[TR_PEER_FROM_DHT];
1176}
1177
1178- (NSInteger) totalPeersLTEP
1179{
1180    return fStat->peersFrom[TR_PEER_FROM_LTEP];
1181}
1182
1183- (NSInteger) totalPeersKnown
1184{
1185    return fStat->peersKnown;
1186}
1187
1188- (NSInteger) peersSendingToUs
1189{
1190    return fStat->peersSendingToUs;
1191}
1192
1193- (NSInteger) peersGettingFromUs
1194{
1195    return fStat->peersGettingFromUs;
1196}
1197
1198- (CGFloat) downloadRate
1199{
1200    return fStat->pieceDownloadSpeed;
1201}
1202
1203- (CGFloat) uploadRate
1204{
1205    return fStat->pieceUploadSpeed;
1206}
1207
1208- (CGFloat) totalRate
1209{
1210    return [self downloadRate] + [self uploadRate];
1211}
1212
1213- (uint64_t) haveVerified
1214{
1215    return fStat->haveValid;
1216}
1217
1218- (uint64_t) haveTotal
1219{
1220    return [self haveVerified] + fStat->haveUnchecked;
1221}
1222
1223- (uint64_t) totalSizeSelected
1224{
1225    return fStat->sizeWhenDone;
1226}
1227
1228- (uint64_t) downloadedTotal
1229{
1230    return fStat->downloadedEver;
1231}
1232
1233- (uint64_t) uploadedTotal
1234{
1235    return fStat->uploadedEver;
1236}
1237
1238- (uint64_t) failedHash
1239{
1240    return fStat->corruptEver;
1241}
1242
1243- (NSInteger) groupValue
1244{
1245    return fGroupValue;
1246}
1247
1248- (void) setGroupValue: (NSInteger) goupValue
1249{
1250    fGroupValue = goupValue;
1251}
1252
1253- (NSInteger) groupOrderValue
1254{
1255    return [[GroupsController groups] rowValueForIndex: fGroupValue];
1256}
1257
1258- (void) checkGroupValueForRemoval: (NSNotification *) notification
1259{
1260    if (fGroupValue != -1 && [[[notification userInfo] objectForKey: @"Index"] integerValue] == fGroupValue)
1261        fGroupValue = -1;
1262}
1263
1264- (NSArray *) fileList
1265{
1266    return fFileList;
1267}
1268
1269- (NSArray *) flatFileList
1270{
1271    return fFlatFileList;
1272}
1273
1274- (NSInteger) fileCount
1275{
1276    return fInfo->fileCount;
1277}
1278
1279- (void) updateFileStat
1280{
1281    if (fFileStat)
1282        tr_torrentFilesFree(fFileStat, [self fileCount]);
1283   
1284    fFileStat = tr_torrentFiles(fHandle, NULL);
1285}
1286
1287- (CGFloat) fileProgress: (FileListNode *) node
1288{
1289    if ([self fileCount] == 1 || [self isComplete])
1290        return [self progress];
1291   
1292    if (!fFileStat)
1293        [self updateFileStat];
1294   
1295    NSIndexSet * indexSet = [node indexes];
1296   
1297    if ([indexSet count] == 1)
1298        return fFileStat[[indexSet firstIndex]].progress;
1299   
1300    uint64_t have = 0;
1301    for (NSInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1302        have += fFileStat[index].bytesCompleted;
1303   
1304    NSAssert([node size], @"directory in torrent file has size 0");
1305    return (CGFloat)have / [node size];
1306}
1307
1308- (BOOL) canChangeDownloadCheckForFile: (NSUInteger) index
1309{
1310    NSAssert2(index < [self fileCount], @"Index %d is greater than file count %d", index, [self fileCount]);
1311   
1312    if ([self fileCount] == 1 || [self isComplete])
1313        return NO;
1314   
1315    if (!fFileStat)
1316        [self updateFileStat];
1317   
1318    return fFileStat[index].progress < 1.0;
1319}
1320
1321- (BOOL) canChangeDownloadCheckForFiles: (NSIndexSet *) indexSet
1322{
1323    if ([self fileCount] == 1 || [self isComplete])
1324        return NO;
1325   
1326    if (!fFileStat)
1327        [self updateFileStat];
1328   
1329    for (NSUInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1330        if (fFileStat[index].progress < 1.0)
1331            return YES;
1332    return NO;
1333}
1334
1335- (NSInteger) checkForFiles: (NSIndexSet *) indexSet
1336{
1337    BOOL onState = NO, offState = NO;
1338    for (NSUInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1339    {
1340        if (!fInfo->files[index].dnd || ![self canChangeDownloadCheckForFile: index])
1341            onState = YES;
1342        else
1343            offState = YES;
1344       
1345        if (onState && offState)
1346            return NSMixedState;
1347    }
1348    return onState ? NSOnState : NSOffState;
1349}
1350
1351- (void) setFileCheckState: (NSInteger) state forIndexes: (NSIndexSet *) indexSet
1352{
1353    NSUInteger count = [indexSet count];
1354    tr_file_index_t * files = malloc(count * sizeof(tr_file_index_t));
1355    for (NSUInteger index = [indexSet firstIndex], i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index], i++)
1356        files[i] = index;
1357   
1358    tr_torrentSetFileDLs(fHandle, files, count, state != NSOffState);
1359    free(files);
1360   
1361    [self update];
1362    [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFileCheckChange" object: self];
1363}
1364
1365- (void) setFilePriority: (tr_priority_t) priority forIndexes: (NSIndexSet *) indexSet
1366{
1367    const NSUInteger count = [indexSet count];
1368    tr_file_index_t * files = tr_malloc(count * sizeof(tr_file_index_t));
1369    for (NSUInteger index = [indexSet firstIndex], i = 0; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index], i++)
1370        files[i] = index;
1371   
1372    tr_torrentSetFilePriorities(fHandle, files, count, priority);
1373    tr_free(files);
1374}
1375
1376- (BOOL) hasFilePriority: (tr_priority_t) priority forIndexes: (NSIndexSet *) indexSet
1377{
1378    for (NSUInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1379        if (priority == fInfo->files[index].priority && [self canChangeDownloadCheckForFile: index])
1380            return YES;
1381    return NO;
1382}
1383
1384- (NSSet *) filePrioritiesForIndexes: (NSIndexSet *) indexSet
1385{
1386    BOOL low = NO, normal = NO, high = NO;
1387    NSMutableSet * priorities = [NSMutableSet setWithCapacity: MIN([indexSet count], 3)];
1388   
1389    for (NSUInteger index = [indexSet firstIndex]; index != NSNotFound; index = [indexSet indexGreaterThanIndex: index])
1390    {
1391        if (![self canChangeDownloadCheckForFile: index])
1392            continue;
1393       
1394        const tr_priority_t priority = fInfo->files[index].priority;
1395        switch (priority)
1396        {
1397            case TR_PRI_LOW:
1398                if (low)
1399                    continue;
1400                low = YES;
1401                break;
1402            case TR_PRI_NORMAL:
1403                if (normal)
1404                    continue;
1405                normal = YES;
1406                break;
1407            case TR_PRI_HIGH:
1408                if (high)
1409                    continue;
1410                high = YES;
1411                break;
1412            default:
1413                NSAssert2(NO, @"Unknown priority %d for file index %d", priority, index);
1414        }
1415       
1416        [priorities addObject: [NSNumber numberWithInteger: priority]];
1417        if (low && normal && high)
1418            break;
1419    }
1420    return priorities;
1421}
1422
1423- (NSDate *) dateAdded
1424{
1425    const time_t date = fStat->addedDate;
1426    return [NSDate dateWithTimeIntervalSince1970: date];
1427}
1428
1429- (NSDate *) dateCompleted
1430{
1431    const time_t date = fStat->doneDate;
1432    return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
1433}
1434
1435- (NSDate *) dateActivity
1436{
1437    const time_t date = fStat->activityDate;
1438    return date != 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
1439}
1440
1441- (NSDate *) dateActivityOrAdd
1442{
1443    NSDate * date = [self dateActivity];
1444    return date ? date : [self dateAdded];
1445}
1446
1447- (NSInteger) stalledMinutes
1448{
1449    const time_t start = fStat->startDate;
1450    if (start == 0)
1451        return -1;
1452   
1453    NSDate * started = [NSDate dateWithTimeIntervalSince1970: start],
1454            * activity = [self dateActivity];
1455   
1456    NSDate * laterDate = activity ? [started laterDate: activity] : started;
1457   
1458    return ABS([laterDate timeIntervalSinceNow]) / 60;
1459}
1460
1461- (BOOL) isStalled
1462{
1463    return fStalled;
1464}
1465
1466- (void) updateTimeMachineExclude
1467{
1468    NSString * currentLocation = ![self allDownloaded] ? [self dataLocation] : nil;
1469   
1470    //return if the locations are the same
1471    if (fTimeMachineExclude && currentLocation && [fTimeMachineExclude isEqualToString: currentLocation])
1472        return;
1473   
1474    //remove old location...
1475    if (fTimeMachineExclude)
1476    {
1477        [self setTimeMachineExclude: NO forPath: fTimeMachineExclude];
1478        [fTimeMachineExclude release];
1479        fTimeMachineExclude = nil;
1480    }
1481   
1482    //...set new location
1483    if (currentLocation)
1484    {
1485        [self setTimeMachineExclude: YES forPath: currentLocation];
1486        fTimeMachineExclude = [currentLocation retain];
1487    }
1488}
1489
1490- (NSInteger) stateSortKey
1491{
1492    if (![self isActive]) //paused
1493    {
1494        if (fWaitToStart)
1495            return 1;
1496        else
1497            return 0;
1498    }
1499    else if ([self isSeeding]) //seeding
1500        return 10;
1501    else //downloading
1502        return 20;
1503}
1504
1505- (NSString *) trackerSortKey
1506{
1507    int count;
1508    tr_tracker_stat * stats = tr_torrentTrackers(fHandle, &count);
1509   
1510    NSString * best = nil;
1511   
1512    for (int i=0; i < count; ++i)
1513    {
1514        NSString * tracker = [NSString stringWithUTF8String: stats[i].host];
1515        if (!best || [tracker localizedCaseInsensitiveCompare: best] == NSOrderedAscending)
1516            best = tracker;
1517    }
1518   
1519    tr_torrentTrackersFree(stats, count);
1520    return best;
1521}
1522
1523- (tr_torrent *) torrentStruct
1524{
1525    return fHandle;
1526}
1527
1528- (NSURL *) previewItemURL
1529{
1530    NSString * location = [self dataLocation];
1531    return location ? [NSURL fileURLWithPath: location] : nil;
1532}
1533
1534@end
1535
1536@implementation Torrent (Private)
1537
1538- (id) initWithPath: (NSString *) path hash: (NSString *) hashString torrentStruct: (tr_torrent *) torrentStruct
1539        magnetAddress: (NSString *) magnetAddress lib: (tr_session *) lib
1540        waitToStart: (NSNumber *) waitToStart
1541        groupValue: (NSNumber *) groupValue
1542        downloadFolder: (NSString *) downloadFolder legacyIncompleteFolder: (NSString *) incompleteFolder
1543{
1544    if (!(self = [super init]))
1545        return nil;
1546   
1547    fDefaults = [NSUserDefaults standardUserDefaults];
1548   
1549    if (torrentStruct)
1550        fHandle = torrentStruct;
1551    else
1552    {
1553        //set libtransmission settings for initialization
1554        tr_ctor * ctor = tr_ctorNew(lib);
1555       
1556        tr_ctorSetPaused(ctor, TR_FORCE, YES);
1557        if (downloadFolder)
1558            tr_ctorSetDownloadDir(ctor, TR_FORCE, [downloadFolder UTF8String]);
1559        if (incompleteFolder)
1560            tr_ctorSetIncompleteDir(ctor, [incompleteFolder UTF8String]);
1561       
1562        tr_parse_result result = TR_PARSE_ERR;
1563        if (path)
1564            result = tr_ctorSetMetainfoFromFile(ctor, [path UTF8String]);
1565       
1566        if (result != TR_PARSE_OK && magnetAddress)
1567            result = tr_ctorSetMetainfoFromMagnetLink(ctor, [magnetAddress UTF8String]);
1568       
1569        //backup - shouldn't be needed after upgrade to 1.70
1570        if (result != TR_PARSE_OK && hashString)
1571            result = tr_ctorSetMetainfoFromHash(ctor, [hashString UTF8String]);
1572       
1573        if (result == TR_PARSE_OK)
1574            fHandle = tr_torrentNew(ctor, NULL);
1575       
1576        tr_ctorFree(ctor);
1577       
1578        if (!fHandle)
1579        {
1580            [self release];
1581            return nil;
1582        }
1583    }
1584
1585    fInfo = tr_torrentInfo(fHandle);
1586   
1587    tr_torrentSetCompletenessCallback(fHandle, completenessChangeCallback, self);
1588    tr_torrentSetRatioLimitHitCallback(fHandle, ratioLimitHitCallback, self);
1589    tr_torrentSetMetadataCallback(fHandle, metadataCallback, self);
1590   
1591    fHashString = [[NSString alloc] initWithUTF8String: fInfo->hashString];
1592       
1593    fFinishedSeeding = NO;
1594   
1595    fWaitToStart = waitToStart && [waitToStart boolValue];
1596    fResumeOnWake = NO;
1597   
1598    //don't do after this point - it messes with auto-group functionality
1599    if (![self isMagnet])
1600        [self createFileList];
1601       
1602    fGroupValue = groupValue ? [groupValue intValue] : [[GroupsController groups] groupIndexForTorrent: self];
1603   
1604    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(checkGroupValueForRemoval:)
1605        name: @"GroupValueRemoved" object: nil];
1606   
1607    fTimeMachineExclude = nil;
1608    [self update];
1609   
1610    return self;
1611}
1612
1613- (void) createFileList
1614{
1615    NSAssert(![self isMagnet], @"Cannot create a file list until the torrent is demagnetized");
1616   
1617    if ([self isFolder])
1618    {
1619        NSInteger count = [self fileCount];
1620        NSMutableArray * fileList = [NSMutableArray arrayWithCapacity: count],
1621                    * flatFileList = [NSMutableArray arrayWithCapacity: count];
1622       
1623        for (NSInteger i = 0; i < count; i++)
1624        {
1625            tr_file * file = &fInfo->files[i];
1626           
1627            NSString * fullPath = [NSString stringWithUTF8String: file->name];
1628            NSArray * pathComponents = [fullPath pathComponents];
1629            NSAssert1([pathComponents count] >= 2, @"Not enough components in path %@", fullPath);
1630           
1631            NSString * path = [pathComponents objectAtIndex: 0];
1632            NSString * name = [pathComponents objectAtIndex: 1];
1633           
1634            if ([pathComponents count] > 2)
1635            {
1636                //determine if folder node already exists
1637                FileListNode * node;
1638                for (node in fileList)
1639                    if ([[node name] isEqualToString: name] && [node isFolder])
1640                        break;
1641               
1642                if (!node)
1643                {
1644                    node = [[FileListNode alloc] initWithFolderName: name path: path];
1645                    [fileList addObject: node];
1646                    [node release];
1647                }
1648               
1649                NSMutableArray * trimmedComponents = [NSMutableArray arrayWithArray: [pathComponents subarrayWithRange:
1650                                                        NSMakeRange(2, [pathComponents count]-2)]];
1651               
1652                [node insertIndex: i withSize: file->length];
1653                [self insertPath: trimmedComponents forParent: node fileSize: file->length index: i flatList: flatFileList];
1654            }
1655            else
1656            {
1657                FileListNode * node = [[FileListNode alloc] initWithFileName: name path: path size: file->length index: i];
1658                [fileList addObject: node];
1659                [flatFileList addObject: node];
1660                [node release];
1661            }
1662        }
1663       
1664        fFileList = [[NSArray alloc] initWithArray: fileList];
1665        fFlatFileList = [[NSArray alloc] initWithArray: flatFileList];
1666    }
1667    else
1668    {
1669        FileListNode * node = [[FileListNode alloc] initWithFileName: [self name] path: @"" size: [self size] index: 0];
1670        fFileList = [[NSArray arrayWithObject: node] retain];
1671        fFlatFileList = [fFileList retain];
1672        [node release];
1673    }
1674}
1675
1676- (void) insertPath: (NSMutableArray *) components forParent: (FileListNode *) parent fileSize: (uint64_t) size
1677    index: (NSInteger) index flatList: (NSMutableArray *) flatFileList
1678{
1679    NSString * name = [components objectAtIndex: 0];
1680    const BOOL isFolder = [components count] > 1;
1681   
1682    FileListNode * node = nil;
1683    if (isFolder)
1684    {
1685        for (node in [parent children])
1686            if ([[node name] isEqualToString: name] && [node isFolder])
1687                break;
1688    }
1689   
1690    //create new folder or file if it doesn't already exist
1691    if (!node)
1692    {
1693        NSString * path = [[parent path] stringByAppendingPathComponent: [parent name]];
1694        if (isFolder)
1695            node = [[FileListNode alloc] initWithFolderName: name path: path];
1696        else
1697        {
1698            node = [[FileListNode alloc] initWithFileName: name path: path size: size index: index];
1699            [flatFileList addObject: node];
1700        }
1701       
1702        [parent insertChild: node];
1703        [node release];
1704    }
1705   
1706    if (isFolder)
1707    {
1708        [node insertIndex: index withSize: size];
1709       
1710        [components removeObjectAtIndex: 0];
1711        [self insertPath: components forParent: node fileSize: size index: index flatList: flatFileList];
1712    }
1713}
1714
1715//status has been retained
1716- (void) completenessChange: (NSNumber *) status
1717{
1718    fStat = tr_torrentStat(fHandle); //don't call update yet to avoid auto-stop
1719   
1720    switch ([status intValue])
1721    {
1722        case TR_SEED:
1723        case TR_PARTIAL_SEED:
1724            [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedDownloading" object: self];
1725            break;
1726       
1727        case TR_LEECH:
1728            [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentRestartedDownloading" object: self];
1729            break;
1730    }
1731    [status release];
1732   
1733    [self update];
1734    [self updateTimeMachineExclude];
1735}
1736
1737- (void) ratioLimitHit
1738{
1739    fStat = tr_torrentStat(fHandle);
1740   
1741    [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentStoppedForRatio" object: self];
1742   
1743    fFinishedSeeding = YES;
1744}
1745
1746- (void) metadataRetrieved
1747{
1748    fStat = tr_torrentStat(fHandle);
1749   
1750    [self createFileList];
1751   
1752    [[NSNotificationCenter defaultCenter] postNotificationName: @"ResetInspector" object: self];
1753}
1754
1755- (NSString *) etaString
1756{
1757    const NSInteger eta = [self eta];
1758    switch (eta)
1759    {
1760        case TR_ETA_NOT_AVAIL:
1761        case TR_ETA_UNKNOWN:
1762            return NSLocalizedString(@"remaining time unknown", "Torrent -> eta string");
1763        default:
1764            return [NSString stringWithFormat: NSLocalizedString(@"%@ remaining", "Torrent -> eta string"),
1765                        [NSString timeString: eta showSeconds: YES maxFields: 2]];
1766    }
1767}
1768
1769- (void) setTimeMachineExclude: (BOOL) exclude forPath: (NSString *) path
1770{
1771    CSBackupSetItemExcluded((CFURLRef)[NSURL fileURLWithPath: path], exclude, true);
1772}
1773
1774@end
Note: See TracBrowser for help on using the repository browser.