source: trunk/macosx/Torrent.m @ 9343

Last change on this file since 9343 was 9343, checked in by livings124, 13 years ago

lets not leak a string

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