source: trunk/macosx/Torrent.m @ 357

Last change on this file since 357 was 357, checked in by livings124, 16 years ago

Get rid of unnecessary class by merging ellipsis code into StringAdditions?.

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