source: trunk/macosx/Torrent.m @ 9843

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

avoid copying file paths when unnecessary

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