source: trunk/macosx/Torrent.m @ 506

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

Start and stop transfers for launch/quit without performing checks for waiting transfers, etc. This should fix saving the incorrect states of running transfers between launches.

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