source: trunk/macosx/Torrent.m @ 465

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

I don't think these will be needed anymore.

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