source: trunk/macosx/Torrent.m @ 527

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

Predicted time now shows days.

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