source: branches/save_torrent_files/macosx/Torrent.m @ 299

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

As far as I can see this is now working. Some cosmetic touchups are needed for the interface and it needs a bit more testing, but it's getting there...

  • Property svn:keywords set to Date Rev Author Id
File size: 15.5 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 299 2006-06-08 06:59:04Z 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#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 %@ completed (%.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        if ([self progress] < 1.0)
219            [fStatusString appendFormat: @" - DL: %@, ", [NSString stringForSpeed: [self downloadRate]]];
220        [fStatusString appendString: [@"UL: " stringByAppendingString:
221                                                [NSString stringForSpeed: [self uploadRate]]]];
222    }
223}
224
225- (void) start
226{
227    if( fStat->status & TR_STATUS_INACTIVE )
228    {
229        tr_torrentStart( fHandle );
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 downloaded];
266    return downloaded > 0 ? (float)[self uploaded] / 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 trashPath: [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" stringByAppendingString: NS_ELLIPSIS];
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" stringByAppendingString: NS_ELLIPSIS];
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- (uint64_t) downloaded
459{
460    return fStat->downloaded;
461}
462
463- (uint64_t) uploaded
464{
465    return fStat->uploaded;
466}
467
468- (NSArray *) fileList
469{
470    int count = fInfo->fileCount, i;
471    NSMutableArray * files = [NSMutableArray arrayWithCapacity: count];
472    for (i = 0; i < count; i++)
473        [files addObject: [[self downloadFolder] stringByAppendingPathComponent:
474            [NSString stringWithUTF8String: fInfo->files[i].name]]];
475    return files;
476}
477
478- (NSDate *) date
479{
480    return fDate;
481}
482
483- (NSNumber *) stateSortKey
484{
485    if (fStat->status & TR_STATUS_INACTIVE)
486        return [NSNumber numberWithInt: 0];
487    else if (fStat->status == TR_STATUS_SEED)
488        return [NSNumber numberWithInt: 1];
489    else
490        return [NSNumber numberWithInt: 2];
491}
492
493- (NSNumber *) progressSortKey
494{
495    return [NSNumber numberWithFloat: [self progress]];
496}
497
498@end
499
500
501@implementation Torrent (Private)
502
503- (id) initWithPath: (NSString *) path lib: (tr_handle_t *) lib date: (NSDate *) date
504        stopRatioSetting: (NSNumber *) stopRatioSetting ratioLimit: (NSNumber *) ratioLimit
505{
506    if (!(self = [super init]))
507        return nil;
508
509    fLib = lib;
510    fDefaults = [NSUserDefaults standardUserDefaults];
511
512    fPrivateTorrent = [fDefaults boolForKey: @"SavePrivateTorrent"];
513
514    int error;
515    if (!path || !(fHandle = tr_torrentInit(fLib, [path UTF8String],
516                    fPrivateTorrent ? TR_FSAVEPRIVATE : 0, & error)))
517    {
518        [self release];
519        return nil;
520    }
521
522    return [self initForSuccessWithDate: date stopRatioSetting: stopRatioSetting ratioLimit: ratioLimit];
523}
524
525- (id) initWithHash: (NSString *) hashString lib: (tr_handle_t *) lib date: (NSDate *) date
526        stopRatioSetting: (NSNumber *) stopRatioSetting ratioLimit: (NSNumber *) ratioLimit
527{
528    if (!(self = [super init]))
529        return nil;
530
531    fLib = lib;
532    fDefaults = [NSUserDefaults standardUserDefaults];
533   
534    fPrivateTorrent = YES;
535
536    int error;
537    if (!hashString || !(fHandle = tr_torrentInitSaved(fLib, [hashString UTF8String], TR_FSAVEPRIVATE, & error)))
538    {
539        [self release];
540        return nil;
541    }
542   
543    return [self initForSuccessWithDate: date stopRatioSetting: stopRatioSetting ratioLimit: ratioLimit];
544}
545
546- (id) initForSuccessWithDate: (NSDate *) date stopRatioSetting: (NSNumber *)
547            stopRatioSetting ratioLimit: (NSNumber *) ratioLimit
548{
549    fInfo = tr_torrentInfo( fHandle );
550
551    fDate = date ? [date retain] : [[NSDate alloc] init];
552    fStopRatioSetting = stopRatioSetting ? [stopRatioSetting intValue] : -1;
553    fRatioLimit = ratioLimit ? [ratioLimit floatValue] : [fDefaults floatForKey: @"RatioLimit"];
554   
555    NSString * fileType = ( fInfo->fileCount > 1 ) ?
556        NSFileTypeForHFSTypeCode('fldr') : [[self name] pathExtension];
557    fIcon = [[NSWorkspace sharedWorkspace] iconForFileType: fileType];
558    [fIcon retain];
559   
560    fIconFlipped = [fIcon copy];
561    [fIconFlipped setFlipped: YES];
562
563    fProgressString = [[NSMutableString alloc] initWithCapacity: 50];
564    fStatusString = [[NSMutableString alloc] initWithCapacity: 75];
565
566    [self update];
567    return self;
568}
569
570
571- (void) trashPath: (NSString *) path
572{
573    if( ![[NSWorkspace sharedWorkspace] performFileOperation:
574           NSWorkspaceRecycleOperation source:
575           [path stringByDeletingLastPathComponent]
576           destination: @""
577           files: [NSArray arrayWithObject: [path lastPathComponent]]
578           tag: nil] )
579    {
580        /* We can't move it to the trash, let's try just to delete it
581           (will work if it is on a remote volume) */
582        if( ![[NSFileManager defaultManager]
583                removeFileAtPath: path handler: nil] )
584        {
585            NSLog( [@"Could not trash " stringByAppendingString: path] );
586        }
587    }
588}
589
590@end
Note: See TracBrowser for help on using the repository browser.