source: trunk/macosx/Torrent.m @ 10636

Last change on this file since 10636 was 10636, checked in by charles, 12 years ago

Sync mac client with libtransmission's LDS->LDP changes, maybe

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