source: trunk/macosx/Torrent.m @ 310

Last change on this file since 310 was 310, checked in by joshe, 16 years ago

Add support to libtransmission and the MacOS X GUI for saving private copies of

torrent files.

  • Property svn:keywords set to Date Rev Author Id
File size: 15.5 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 310 2006-06-09 19:53:35Z joshe $
3 *
4 * Copyright (c) 2006 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 "StringAdditions.h"
27#import "Utils.h"
28
29@interface Torrent (Private)
30
31- (id) initWithPath: (NSString *) path lib: (tr_handle_t *) lib date: (NSDate *) date
32        stopRatioSetting: (NSNumber *) stopRatioSetting ratioLimit: (NSNumber *) ratioLimit;
33- (id) initWithHash: (NSString *) hashString lib: (tr_handle_t *) lib date: (NSDate *) date
34        stopRatioSetting: (NSNumber *) stopRatioSetting ratioLimit: (NSNumber *) ratioLimit;
35- (id) initForSuccessWithDate: (NSDate *) date stopRatioSetting: (NSNumber *)
36            stopRatioSetting ratioLimit: (NSNumber *) ratioLimit;
37
38- (void) trashPath: (NSString *) path;
39
40@end
41
42
43@implementation Torrent
44
45- (id) initWithPath: (NSString *) path lib: (tr_handle_t *) lib
46{
47    id torrent = [self initWithPath: path lib: lib date: nil
48                    stopRatioSetting: nil ratioLimit: nil];
49                   
50    if (!torrent)
51        return nil;
52
53    if (fPrivateTorrent && [fDefaults boolForKey: @"DeleteOriginalTorrent"])
54        [self trashPath: path];
55   
56    return torrent;
57}
58
59- (id) initWithHistory: (NSDictionary *) history lib: (tr_handle_t *) lib
60{
61    //load from saved torrent file if set to, otherwise try to load from where torrent file should be
62    NSNumber * privateCopy;
63    if ((privateCopy = [history objectForKey: @"PrivateCopy"]) && [privateCopy boolValue])
64        self = [self initWithHash: [history objectForKey: @"TorrentHash"]
65            lib: lib date: [history objectForKey: @"Date"]
66            stopRatioSetting: [history objectForKey: @"StopRatioSetting"]
67            ratioLimit: [history objectForKey: @"RatioLimit"]];
68    else
69        self = [self initWithPath: [history objectForKey: @"TorrentPath"]
70            lib: lib date: [history objectForKey: @"Date"]
71            stopRatioSetting: [history objectForKey: @"StopRatioSetting"]
72            ratioLimit: [history objectForKey: @"RatioLimit"]];
73           
74    if (self)
75    {
76        NSString * downloadFolder;
77        if (!(downloadFolder = [history objectForKey: @"DownloadFolder"]))
78            downloadFolder = [[fDefaults stringForKey: @"DownloadFolder"]
79                                stringByExpandingTildeInPath];
80        [self setDownloadFolder: downloadFolder];
81
82        NSString * paused;
83        if (!(paused = [history objectForKey: @"Paused"]) || [paused isEqualToString: @"NO"])
84            [self start];
85    }
86    return self;
87}
88
89- (NSDictionary *) history
90{
91    NSMutableDictionary * history = [NSMutableDictionary dictionaryWithObjectsAndKeys:
92                    [NSNumber numberWithBool: fPrivateTorrent], @"PrivateCopy",
93                    [self downloadFolder], @"DownloadFolder",
94                    [self isActive] ? @"NO" : @"YES", @"Paused",
95                    [self date], @"Date",
96                    [NSNumber numberWithInt: fStopRatioSetting], @"StopRatioSetting",
97                    [NSNumber numberWithFloat: fRatioLimit], @"RatioLimit", nil];
98           
99    if (fPrivateTorrent)
100        [history setObject: [self hashString] forKey: @"TorrentHash"];
101    else
102        [history setObject: [self torrentLocation] forKey: @"TorrentPath"];
103   
104    return history;
105}
106
107- (void) dealloc
108{
109    if( fHandle )
110    {
111        tr_torrentClose( fLib, fHandle );
112       
113        [fDate release];
114        [fIcon release];
115        [fIconFlipped release];
116        [fProgressString release];
117        [fStatusString release];
118    }
119    [super dealloc];
120}
121
122- (void) setDownloadFolder: (NSString *) path
123{
124    tr_torrentSetFolder( fHandle, [path UTF8String] );
125}
126
127- (NSString *) downloadFolder
128{
129    return [NSString stringWithUTF8String: tr_torrentGetFolder( fHandle )];
130}
131
132- (void) getAvailability: (int8_t *) tab size: (int) size
133{
134    tr_torrentAvailability( fHandle, tab, size );
135}
136
137- (void) update
138{
139    fStat = tr_torrentStat( fHandle );
140   
141    if ([self isSeeding])
142        if ((fStopRatioSetting == RATIO_CHECK && [self ratio] >= fRatioLimit)
143            || (fStopRatioSetting == RATIO_GLOBAL && [fDefaults boolForKey: @"RatioCheck"]
144                && [self ratio] >= [fDefaults floatForKey: @"RatioLimit"]))
145        {
146            [self stop];
147            [self setStopRatioSetting: RATIO_NO_CHECK];
148           
149            fStat = tr_torrentStat( fHandle );
150           
151            [[NSNotificationCenter defaultCenter] postNotificationName:
152                @"TorrentRatioChanged" object: self];
153        }
154   
155    [fProgressString setString: @""];
156    if ([self progress] < 1.0)
157        [fProgressString appendFormat: @"%@ of %@ (%.2f%%)", [NSString stringForFileSize:
158                [self downloaded]], [NSString stringForFileSize: [self size]], 100 * [self progress]];
159    else
160        [fProgressString appendFormat: @"%@, uploaded %@ (ratio: %@)", [NSString stringForFileSize:
161                [self size]], [NSString stringForFileSize: [self uploaded]],
162                [NSString stringForRatioWithDownload: [self downloaded] upload: [self uploaded]]];
163
164    switch( fStat->status )
165    {
166        case TR_STATUS_PAUSE:
167            [fStatusString setString: @"Paused"];
168            break;
169
170        case TR_STATUS_CHECK:
171            [fStatusString setString: [@"Checking existing files" stringByAppendingString: NS_ELLIPSIS]];
172            break;
173
174        case TR_STATUS_DOWNLOAD:
175            [fStatusString setString: @""];
176            [fStatusString appendFormat:
177                @"Downloading from %d of %d peer%s",
178                [self peersUploading], [self totalPeers],
179                ([self totalPeers] == 1) ? "" : "s"];
180           
181            int eta = fStat->eta;
182            if (eta < 0)
183                [fProgressString appendString: @" - remaining time unknown"];
184            else
185            {
186                if (eta < 60)
187                    [fProgressString appendFormat: @" - %d sec remaining", eta];
188                else if (eta < 3600)
189                    [fProgressString appendFormat: @" - %d min %02d sec remaining",
190                                                    eta / 60, eta % 60];
191                else
192                    [fProgressString appendFormat: @" - %d hr %02d min remaining",
193                                                    eta / 3600, (eta / 60) % 60];
194            }
195            break;
196
197        case TR_STATUS_SEED:
198            [fStatusString setString: @""];
199            [fStatusString appendFormat:
200                @"Seeding to %d of %d peer%s",
201                [self peersDownloading], [self totalPeers],
202                ([self totalPeers] == 1) ? "" : "s"];
203            break;
204
205        case TR_STATUS_STOPPING:
206            [fStatusString setString: [@"Stopping" stringByAppendingString: NS_ELLIPSIS]];
207            break;
208    }
209   
210    if( fStat->error & TR_ETRACKER )
211    {
212        [fStatusString setString: [@"Error: " stringByAppendingString:
213            [NSString stringWithUTF8String: fStat->trackerError]]];
214    }
215
216    if ([self isActive])
217    {
218        [fStatusString appendString: @" - "];
219        if ([self progress] < 1.0)
220            [fStatusString appendFormat: @"DL: %@, ", [NSString stringForSpeed: [self downloadRate]]];
221        [fStatusString appendString: [@"UL: " stringByAppendingString:
222                                                [NSString stringForSpeed: [self uploadRate]]]];
223    }
224}
225
226- (void) start
227{
228    if( fStat->status & TR_STATUS_INACTIVE )
229    {
230        tr_torrentStart( fHandle );
231    }
232}
233
234- (void) stop
235{
236    if( fStat->status & TR_STATUS_ACTIVE )
237    {
238        tr_torrentStop( fHandle );
239    }
240}
241
242- (void) removeForever
243{
244    if (fInfo->flags & TR_FSAVEPRIVATE)
245        tr_torrentRemoveSaved(fHandle);
246}
247
248- (void) sleep
249{
250    if( ( fResumeOnWake = ( fStat->status & TR_STATUS_ACTIVE ) ) )
251    {
252        [self stop];
253    }
254}
255
256- (void) wakeUp
257{
258    if( fResumeOnWake )
259    {
260        [self start];
261    }
262}
263
264- (float) ratio
265{
266    float downloaded = [self downloaded];
267    return downloaded > 0 ? (float)[self uploaded] / downloaded : -1;
268}
269
270- (int) stopRatioSetting
271{
272        return fStopRatioSetting;
273}
274
275- (void) setStopRatioSetting: (int) setting
276{
277    fStopRatioSetting = setting;
278}
279
280- (float) ratioLimit
281{
282    return fRatioLimit;
283}
284
285- (void) setRatioLimit: (float) limit
286{
287    if (limit >= 0)
288        fRatioLimit = limit;
289}
290
291- (void) reveal
292{
293    [[NSWorkspace sharedWorkspace] selectFile: [self dataLocation]
294        inFileViewerRootedAtPath: nil];
295}
296
297- (void) trashData
298{
299    [self trashPath: [self dataLocation]];
300}
301
302- (NSImage *) icon
303{
304    return fIcon;
305}
306
307- (NSImage *) iconFlipped
308{
309    return fIconFlipped;
310}
311
312- (NSString *) name
313{
314    return [NSString stringWithUTF8String: fInfo->name];
315}
316
317- (uint64_t) size
318{
319    return fInfo->totalSize;
320}
321
322- (NSString *) tracker
323{
324    return [NSString stringWithFormat: @"%s:%d",
325            fInfo->trackerAddress, fInfo->trackerPort];
326}
327
328- (NSString *) announce
329{
330    return [NSString stringWithUTF8String: fInfo->trackerAnnounce];
331}
332
333- (int) pieceSize
334{
335    return fInfo->pieceSize;
336}
337
338- (int) pieceCount
339{
340    return fInfo->pieceCount;
341}
342
343- (NSString *) hashString
344{
345    return [NSString stringWithUTF8String: fInfo->hashString];
346}
347
348- (NSString *) torrentLocation
349{
350    return [NSString stringWithUTF8String: fInfo->torrent];
351}
352
353- (NSString *) dataLocation
354{
355    return [[self downloadFolder] stringByAppendingPathComponent: [self name]];
356}
357
358- (NSString *) state
359{
360    switch( fStat->status )
361    {
362        case TR_STATUS_PAUSE:
363            return @"Paused";
364            break;
365
366        case TR_STATUS_CHECK:
367            return [@"Checking existing files" stringByAppendingString: NS_ELLIPSIS];
368            break;
369
370        case TR_STATUS_DOWNLOAD:
371            return @"Downloading";
372            break;
373
374        case TR_STATUS_SEED:
375            return @"Seeding";
376            break;
377
378        case TR_STATUS_STOPPING:
379            return [@"Stopping" stringByAppendingString: NS_ELLIPSIS];
380            break;
381       
382        default:
383            return @"N/A";
384    }
385}
386
387- (float) progress
388{
389    return fStat->progress;
390}
391
392- (BOOL) isActive
393{
394    return ( fStat->status & TR_STATUS_ACTIVE );
395}
396
397- (BOOL) isSeeding
398{
399    return ( fStat->status == TR_STATUS_SEED );
400}
401
402- (BOOL) isPaused
403{
404    return ( fStat->status == TR_STATUS_PAUSE );
405}
406
407- (BOOL) justFinished
408{
409    return tr_getFinished( fHandle );
410}
411
412- (NSString *) progressString
413{
414    return fProgressString;
415}
416
417- (NSString *) statusString
418{
419    return fStatusString;
420}
421
422- (int) seeders
423{
424    return fStat->seeders;
425}
426
427- (int) leechers
428{
429    return fStat->leechers;
430}
431
432- (int) totalPeers
433{
434    return fStat->peersTotal;
435}
436
437//peers uploading to you
438- (int) peersUploading
439{
440    return fStat->peersUploading;
441}
442
443//peers downloading from you
444- (int) peersDownloading
445{
446    return fStat->peersDownloading;
447}
448
449- (float) downloadRate
450{
451    return fStat->rateDownload;
452}
453
454- (float) uploadRate
455{
456    return fStat->rateUpload;
457}
458
459- (uint64_t) downloaded
460{
461    return fStat->downloaded;
462}
463
464- (uint64_t) uploaded
465{
466    return fStat->uploaded;
467}
468
469- (NSArray *) fileList
470{
471    int count = fInfo->fileCount, i;
472    NSMutableArray * files = [NSMutableArray arrayWithCapacity: count];
473    for (i = 0; i < count; i++)
474        [files addObject: [[self downloadFolder] stringByAppendingPathComponent:
475            [NSString stringWithUTF8String: fInfo->files[i].name]]];
476    return files;
477}
478
479- (NSDate *) date
480{
481    return fDate;
482}
483
484- (NSNumber *) stateSortKey
485{
486    if (fStat->status & TR_STATUS_INACTIVE)
487        return [NSNumber numberWithInt: 0];
488    else if (fStat->status == TR_STATUS_SEED)
489        return [NSNumber numberWithInt: 1];
490    else
491        return [NSNumber numberWithInt: 2];
492}
493
494- (NSNumber *) progressSortKey
495{
496    return [NSNumber numberWithFloat: [self progress]];
497}
498
499@end
500
501
502@implementation Torrent (Private)
503
504- (id) initWithPath: (NSString *) path lib: (tr_handle_t *) lib date: (NSDate *) date
505        stopRatioSetting: (NSNumber *) stopRatioSetting ratioLimit: (NSNumber *) ratioLimit
506{
507    if (!(self = [super init]))
508        return nil;
509
510    fLib = lib;
511    fDefaults = [NSUserDefaults standardUserDefaults];
512
513    fPrivateTorrent = [fDefaults boolForKey: @"SavePrivateTorrent"];
514
515    int error;
516    if (!path || !(fHandle = tr_torrentInit(fLib, [path UTF8String],
517                    fPrivateTorrent ? TR_FSAVEPRIVATE : 0, & error)))
518    {
519        [self release];
520        return nil;
521    }
522
523    return [self initForSuccessWithDate: date stopRatioSetting: stopRatioSetting ratioLimit: ratioLimit];
524}
525
526- (id) initWithHash: (NSString *) hashString lib: (tr_handle_t *) lib date: (NSDate *) date
527        stopRatioSetting: (NSNumber *) stopRatioSetting ratioLimit: (NSNumber *) ratioLimit
528{
529    if (!(self = [super init]))
530        return nil;
531
532    fLib = lib;
533    fDefaults = [NSUserDefaults standardUserDefaults];
534   
535    fPrivateTorrent = YES;
536
537    int error;
538    if (!hashString || !(fHandle = tr_torrentInitSaved(fLib, [hashString UTF8String], TR_FSAVEPRIVATE, & error)))
539    {
540        [self release];
541        return nil;
542    }
543   
544    return [self initForSuccessWithDate: date stopRatioSetting: stopRatioSetting ratioLimit: ratioLimit];
545}
546
547- (id) initForSuccessWithDate: (NSDate *) date stopRatioSetting: (NSNumber *)
548            stopRatioSetting ratioLimit: (NSNumber *) ratioLimit
549{
550    fInfo = tr_torrentInfo( fHandle );
551
552    fDate = date ? [date retain] : [[NSDate alloc] init];
553    fStopRatioSetting = stopRatioSetting ? [stopRatioSetting intValue] : -1;
554    fRatioLimit = ratioLimit ? [ratioLimit floatValue] : [fDefaults floatForKey: @"RatioLimit"];
555   
556    NSString * fileType = ( fInfo->fileCount > 1 ) ?
557        NSFileTypeForHFSTypeCode('fldr') : [[self name] pathExtension];
558    fIcon = [[NSWorkspace sharedWorkspace] iconForFileType: fileType];
559    [fIcon retain];
560   
561    fIconFlipped = [fIcon copy];
562    [fIconFlipped setFlipped: YES];
563
564    fProgressString = [[NSMutableString alloc] initWithCapacity: 50];
565    fStatusString = [[NSMutableString alloc] initWithCapacity: 75];
566
567    [self update];
568    return self;
569}
570
571
572- (void) trashPath: (NSString *) path
573{
574    if( ![[NSWorkspace sharedWorkspace] performFileOperation:
575           NSWorkspaceRecycleOperation source:
576           [path stringByDeletingLastPathComponent]
577           destination: @""
578           files: [NSArray arrayWithObject: [path lastPathComponent]]
579           tag: nil] )
580    {
581        /* We can't move it to the trash, let's try just to delete it
582           (will work if it is on a remote volume) */
583        if( ![[NSFileManager defaultManager]
584                removeFileAtPath: path handler: nil] )
585        {
586            NSLog( [@"Could not trash " stringByAppendingString: path] );
587        }
588    }
589}
590
591@end
Note: See TracBrowser for help on using the repository browser.