source: trunk/macosx/Torrent.m @ 1283

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

manual announce in mac gui...only useable once per minute for each torrent

  • Property svn:keywords set to Date Rev Author Id
File size: 38.3 KB
Line 
1/******************************************************************************
2 * $Id: Torrent.m 1283 2006-12-26 21:02:00Z 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#define BAR_HEIGHT 12.0
29
30#define MAX_PIECES 324
31#define BLANK_PIECE -99
32
33@interface Torrent (Private)
34
35- (id) initWithHash: (NSString *) hashString path: (NSString *) path lib: (tr_handle_t *) lib
36        publicTorrent: (NSNumber *) publicTorrent
37        date: (NSDate *) date stopRatioSetting: (NSNumber *) stopRatioSetting
38        ratioLimit: (NSNumber *) ratioLimit waitToStart: (NSNumber *) waitToStart
39        orderValue: (NSNumber *) orderValue;
40
41- (NSImage *) advancedBar;
42
43- (void) trashFile: (NSString *) path;
44
45@end
46
47@implementation Torrent
48
49// Used to optimize drawing. They contain packed RGBA pixels for every color needed.
50#define BE OSSwapBigToHostConstInt32
51
52static uint32_t kRed   = BE(0xFF6450FF), //255, 100, 80
53                kBlue = BE(0x50A0FFFF), //80, 160, 255
54                kBlue2 = BE(0x1E46B4FF), //30, 70, 180
55                kGray  = BE(0x969696FF), //150, 150, 150
56                kGreen1 = BE(0x99FFCCFF), //153, 255, 204
57                kGreen2 = BE(0x66FF99FF), //102, 255, 153
58                kGreen3 = BE(0x00FF66FF), //0, 255, 102
59                kWhite = BE(0xFFFFFFFF); //255, 255, 255
60
61- (id) initWithPath: (NSString *) path forceDeleteTorrent: (BOOL) delete lib: (tr_handle_t *) lib
62{
63    self = [self initWithHash: nil path: path lib: lib
64            publicTorrent: delete ? [NSNumber numberWithBool: NO] : nil
65            date: nil stopRatioSetting: nil ratioLimit: nil waitToStart: nil orderValue: nil];
66   
67    if (self)
68    {
69        fUseIncompleteFolder = [fDefaults boolForKey: @"UseIncompleteDownloadFolder"];
70        fIncompleteFolder = [[fDefaults stringForKey: @"IncompleteDownloadFolder"] copy];
71       
72        if (!fPublicTorrent)
73            [self trashFile: path];
74    }
75    return self;
76}
77
78- (id) initWithHistory: (NSDictionary *) history lib: (tr_handle_t *) lib
79{
80    self = [self initWithHash: [history objectForKey: @"TorrentHash"]
81                path: [history objectForKey: @"TorrentPath"] lib: lib
82                publicTorrent: [history objectForKey: @"PublicCopy"]
83                date: [history objectForKey: @"Date"]
84                stopRatioSetting: [history objectForKey: @"StopRatioSetting"]
85                ratioLimit: [history objectForKey: @"RatioLimit"]
86                waitToStart: [history objectForKey: @"WaitToStart"]
87                orderValue: [history objectForKey: @"OrderValue"]];
88   
89    if (self)
90    {
91        //download folders
92        NSString * downloadFolder;
93        if (!(downloadFolder = [history objectForKey: @"DownloadFolder"]))
94            downloadFolder = [[fDefaults stringForKey: @"DownloadFolder"] stringByExpandingTildeInPath];
95       
96        NSNumber * useIncompleteFolder;
97        if ((useIncompleteFolder = [history objectForKey: @"UseIncompleteFolder"]))
98        {
99            if ((fUseIncompleteFolder = [useIncompleteFolder boolValue]))
100            {
101                NSString * incompleteFolder;
102                if (incompleteFolder = [history objectForKey: @"IncompleteFolder"])
103                    fIncompleteFolder = [incompleteFolder copy];
104                else
105                    fIncompleteFolder = [[[fDefaults stringForKey: @"IncompleteDownloadFolder"]
106                                            stringByExpandingTildeInPath] copy];
107            }
108        }
109        else
110            fUseIncompleteFolder = NO;
111       
112        [self setDownloadFolder: downloadFolder];
113
114        NSString * paused;
115        if (!(paused = [history objectForKey: @"Paused"]) || [paused isEqualToString: @"NO"])
116        {
117            fStat = tr_torrentStat(fHandle);
118            [self startTransfer];
119        }
120    }
121    return self;
122}
123
124- (NSDictionary *) history
125{
126    NSMutableDictionary * history = [NSMutableDictionary dictionaryWithObjectsAndKeys:
127                    [NSNumber numberWithBool: fPublicTorrent], @"PublicCopy",
128                    [self hashString], @"TorrentHash",
129                    fDownloadFolder, @"DownloadFolder",
130                    [NSNumber numberWithBool: fUseIncompleteFolder], @"UseIncompleteFolder",
131                    [self isActive] ? @"NO" : @"YES", @"Paused",
132                    [self date], @"Date",
133                    [NSNumber numberWithInt: fStopRatioSetting], @"StopRatioSetting",
134                    [NSNumber numberWithFloat: fRatioLimit], @"RatioLimit",
135                    [NSNumber numberWithBool: fWaitToStart], @"WaitToStart",
136                    [self orderValue], @"OrderValue", nil];
137   
138    if (fUseIncompleteFolder)
139        [history setObject: fIncompleteFolder forKey: @"IncompleteFolder"];
140
141    if (fPublicTorrent)
142        [history setObject: [self publicTorrentLocation] forKey: @"TorrentPath"];
143   
144    return history;
145}
146
147- (void) dealloc
148{
149    if (fHandle)
150    {
151        tr_torrentClose(fLib, fHandle);
152       
153        if (fDownloadFolder)
154            [fDownloadFolder release];
155        if (fIncompleteFolder)
156            [fIncompleteFolder release];
157       
158        if (fPublicTorrentLocation)
159            [fPublicTorrentLocation release];
160       
161        [fDate release];
162       
163        if (fAnnounceDate)
164            [fAnnounceDate release];
165       
166        [fIcon release];
167        [fIconFlipped release];
168        [fIconSmall release];
169       
170        [fProgressString release];
171        [fStatusString release];
172        [fShortStatusString release];
173        [fRemainingTimeString release];
174       
175        [fBitmap release];
176        free(fPieces);
177    }
178    [super dealloc];
179}
180
181- (void) setDownloadFolder: (NSString *) path
182{
183    if (path)
184        fDownloadFolder = [path copy];
185   
186    if (!fUseIncompleteFolder || [[NSFileManager defaultManager] fileExistsAtPath:
187                                    [path stringByAppendingPathComponent: [self name]]])
188        tr_torrentSetFolder(fHandle, [path UTF8String]);
189    else
190        tr_torrentSetFolder(fHandle, [fIncompleteFolder UTF8String]);
191}
192
193- (NSString *) downloadFolder
194{
195    return [NSString stringWithUTF8String: tr_torrentGetFolder(fHandle)];
196}
197
198- (void) getAvailability: (int8_t *) tab size: (int) size
199{
200    tr_torrentAvailability(fHandle, tab, size);
201}
202
203- (void) getAmountFinished: (float *) tab size: (int) size
204{
205    tr_torrentAmountFinished(fHandle, tab, size);
206}
207
208- (void) update
209{
210    fStat = tr_torrentStat(fHandle);
211   
212    //notification when downloading finished
213    if ([self justFinished])
214    {
215        BOOL canMove = YES;
216       
217        //move file from incomplete folder to download folder
218        if (fUseIncompleteFolder && ![[self downloadFolder] isEqualToString: fDownloadFolder]
219            && (canMove = [self alertForMoveVolumeAvailable]))
220        {
221            tr_torrentStop(fHandle);
222            if ([[NSFileManager defaultManager] movePath: [[self downloadFolder] stringByAppendingPathComponent: [self name]]
223                                    toPath: [fDownloadFolder stringByAppendingPathComponent: [self name]] handler: nil])
224                tr_torrentSetFolder(fHandle, [fDownloadFolder UTF8String]);
225            tr_torrentStart(fHandle);
226        }
227       
228        if (!canMove)
229        {
230            fUseIncompleteFolder = NO;
231           
232            [fDownloadFolder release];
233            fDownloadFolder = fIncompleteFolder;
234            fIncompleteFolder = nil;
235        }
236       
237        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentFinishedDownloading" object: self];
238    }
239   
240    //check to stop for ratio
241    if ([self isSeeding] && ((fStopRatioSetting == RATIO_CHECK && [self ratio] >= fRatioLimit)
242            || (fStopRatioSetting == RATIO_GLOBAL && [fDefaults boolForKey: @"RatioCheck"]
243            && [self ratio] >= [fDefaults floatForKey: @"RatioLimit"])))
244    {
245        [self stopTransfer];
246        [self setStopRatioSetting: RATIO_NO_CHECK];
247        fFinishedSeeding = YES;
248       
249        fStat = tr_torrentStat(fHandle);
250       
251        [[NSNotificationCenter defaultCenter] postNotificationName: @"TorrentStoppedForRatio" object: self];
252    }
253
254    [fProgressString setString: @""];
255    if ([self progress] < 1.0)
256        [fProgressString appendFormat: NSLocalizedString(@"%@ of %@ (%.2f%%)", "Torrent -> progress string"),
257                            [NSString stringForFileSize: [self downloadedValid]],
258                            [NSString stringForFileSize: [self size]], 100.0 * [self progress]];
259    else
260        [fProgressString appendFormat: NSLocalizedString(@"%@, uploaded %@ (Ratio: %@)", "Torrent -> progress string"),
261                [NSString stringForFileSize: [self size]], [NSString stringForFileSize: [self uploadedTotal]],
262                [NSString stringForRatioWithDownload: [self downloadedTotal] upload: [self uploadedTotal]]];
263
264    switch (fStat->status)
265    {
266        NSString * tempString;
267   
268        case TR_STATUS_PAUSE:
269            if (fFinishedSeeding)
270                tempString = NSLocalizedString(@"Seeding complete", "Torrent -> status string");
271            else if (fWaitToStart)
272                tempString = [NSLocalizedString(@"Waiting to start", "Torrent -> status string") stringByAppendingEllipsis];
273            else
274                tempString = NSLocalizedString(@"Paused", "Torrent -> status string");
275           
276            [fStatusString setString: tempString];
277            [fShortStatusString setString: tempString];
278           
279            break;
280
281        case TR_STATUS_CHECK:
282            tempString = [NSLocalizedString(@"Checking existing files", "Torrent -> status string") stringByAppendingEllipsis];
283           
284            [fStatusString setString: tempString];
285            [fShortStatusString setString: tempString];
286            [fRemainingTimeString setString: tempString];
287           
288            break;
289
290        case TR_STATUS_DOWNLOAD:
291            [fStatusString setString: @""];
292            if ([self totalPeers] > 1)
293                [fStatusString appendFormat: NSLocalizedString(@"Downloading from %d of %d peers",
294                                                "Torrent -> status string"), [self peersUploading], [self totalPeers]];
295            else
296                [fStatusString appendFormat: NSLocalizedString(@"Downloading from %d of %d peer",
297                                                "Torrent -> status string"), [self peersUploading], [self totalPeers]];
298           
299            [fRemainingTimeString setString: @""];
300            int eta = [self eta];
301            if (eta < 0)
302            {
303                [fRemainingTimeString setString: NSLocalizedString(@"Unknown", "Torrent -> remaining time")];
304                [fProgressString appendString: NSLocalizedString(@" - remaining time unknown", "Torrent -> progress string")];
305            }
306            else
307            {
308                if (eta < 60)
309                    [fRemainingTimeString appendFormat: NSLocalizedString(@"%d sec", "Torrent -> remaining time"), eta];
310                else if (eta < 3600) //60 * 60
311                    [fRemainingTimeString appendFormat: NSLocalizedString(@"%d min %02d sec", "Torrent -> remaining time"),
312                                                            eta / 60, eta % 60];
313                else if (eta < 86400) //24 * 60 * 60
314                    [fRemainingTimeString appendFormat: NSLocalizedString(@"%d hr %02d min", "Torrent -> remaining time"),
315                                                            eta / 3600, (eta / 60) % 60];
316                else
317                {
318                    if (eta / 86400 > 1)
319                        [fRemainingTimeString appendFormat: NSLocalizedString(@"%d days %d hr", "Torrent -> remaining time"),
320                                                                eta / 86400, (eta / 3600) % 24];
321                    else
322                        [fRemainingTimeString appendFormat: NSLocalizedString(@"%d day %d hr", "Torrent -> remaining time"),
323                                                                eta / 86400, (eta / 3600) % 24];
324                }
325               
326                [fProgressString appendFormat: NSLocalizedString(@" - %@ remaining", "Torrent -> progress string"),
327                                                                    fRemainingTimeString];
328            }
329           
330            break;
331
332        case TR_STATUS_SEED:
333            [fStatusString setString: @""];
334            if ([self totalPeers] > 1)
335                [fStatusString appendFormat: NSLocalizedString(@"Seeding to %d of %d peers", "Torrent -> status string"),
336                                                [self peersDownloading], [self totalPeers]];
337            else
338                [fStatusString appendFormat: NSLocalizedString(@"Seeding to %d of %d peer", "Torrent -> status string"),
339                                                [self peersDownloading], [self totalPeers]];
340           
341            break;
342
343        case TR_STATUS_STOPPING:
344            tempString = [NSLocalizedString(@"Stopping", "Torrent -> status string") stringByAppendingEllipsis];
345       
346            [fStatusString setString: tempString];
347            [fShortStatusString setString: tempString];
348           
349            break;
350    }
351   
352    if (fStat->error & TR_ETRACKER)
353    {
354        [fStatusString setString: [NSLocalizedString(@"Error: ", "Torrent -> status string") stringByAppendingString:
355                                    [self errorMessage]]];
356    }
357   
358    BOOL wasError = fError;
359    if ((fError = fStat->cannotConnect))
360    {
361        if (!wasError && [self isActive] && ![self isSeeding])
362            [[NSNotificationCenter defaultCenter] postNotificationName: @"StoppedDownloading" object: self];
363    }
364
365    if ([self isActive] && fStat->status != TR_STATUS_CHECK )
366    {
367        NSString * stringToAppend = @"";
368        if ([self progress] < 1.0)
369        {
370            stringToAppend = [NSString stringWithFormat: NSLocalizedString(@"DL: %@, ", "Torrent -> status string"),
371                                [NSString stringForSpeed: [self downloadRate]]];
372            [fShortStatusString setString: @""];
373        }
374        else
375        {
376            NSString * ratioString = [NSString stringForRatioWithDownload: [self downloadedTotal]
377                                                upload: [self uploadedTotal]];
378       
379            [fShortStatusString setString: [NSString stringWithFormat: NSLocalizedString(@"Ratio: %@, ",
380                                            "Torrent -> status string"), ratioString]];
381            [fRemainingTimeString setString: [NSLocalizedString(@"Ratio: ", "Torrent -> status string")
382                                                stringByAppendingString: ratioString]];
383        }
384       
385        stringToAppend = [stringToAppend stringByAppendingString: [NSLocalizedString(@"UL: ", "Torrent -> status string")
386                                            stringByAppendingString: [NSString stringForSpeed: [self uploadRate]]]];
387
388        [fStatusString appendFormat: @" - %@", stringToAppend];
389        [fShortStatusString appendString: stringToAppend];
390    }
391}
392
393- (NSDictionary *) infoForCurrentView
394{
395    NSMutableDictionary * info = [NSMutableDictionary dictionaryWithObjectsAndKeys:
396                                    [self name], @"Name",
397                                    [NSNumber numberWithBool: [self isSeeding]], @"Seeding",
398                                    [NSNumber numberWithFloat: [self progress]], @"Progress",
399                                    [NSNumber numberWithBool: [self isActive]], @"Active",
400                                    [NSNumber numberWithBool: [self isError]], @"Error", nil];
401   
402    if (![fDefaults boolForKey: @"SmallView"])
403    {
404        [info setObject: fIconFlipped forKey: @"Icon"];
405        [info setObject: [self progressString] forKey: @"ProgressString"];
406        [info setObject: [self statusString] forKey: @"StatusString"];
407    }
408    else
409    {
410        [info setObject: fIconSmall forKey: @"Icon"];
411        [info setObject: [self remainingTimeString] forKey: @"RemainingTimeString"];
412        [info setObject: [self shortStatusString] forKey: @"ShortStatusString"];
413    }
414   
415    if ([fDefaults boolForKey: @"UseAdvancedBar"])
416        [info setObject: [self advancedBar] forKey: @"AdvancedBar"];
417   
418    return info;
419}
420
421- (void) startTransfer
422{
423    fWaitToStart = NO;
424    fFinishedSeeding = NO;
425   
426    if (![self isActive] && [self alertForVolumeAvailable] && [self alertForRemainingDiskSpace])
427        tr_torrentStart(fHandle);
428}
429
430- (void) stopTransfer
431{
432    fError = NO;
433   
434    if ([self isActive])
435    {
436        BOOL wasSeeding = [self isSeeding];
437   
438        tr_torrentStop(fHandle);
439
440        if (!wasSeeding)
441            [[NSNotificationCenter defaultCenter] postNotificationName: @"StoppedDownloading" object: self];
442    }
443}
444
445- (void) stopTransferForQuit
446{
447    if ([self isActive])
448        tr_torrentStop(fHandle);
449}
450
451- (void) removeForever
452{
453    tr_torrentRemoveSaved(fHandle);
454}
455
456- (void) sleep
457{
458    if ((fResumeOnWake = [self isActive]))
459        tr_torrentStop(fHandle);
460}
461
462- (void) wakeUp
463{
464    if (fResumeOnWake)
465        tr_torrentStart(fHandle);
466}
467
468- (void) announce
469{
470    if (![self isActive])
471        return;
472   
473    tr_manualUpdate(fHandle);
474   
475    if (fAnnounceDate)
476        [fAnnounceDate release];
477    fAnnounceDate = [[NSDate date] retain];
478}
479
480- (NSDate *) announceDate
481{
482    return fAnnounceDate;
483}
484
485- (float) ratio
486{
487    float downloaded = [self downloadedTotal];
488    return downloaded > 0 ? (float)[self uploadedTotal] / downloaded : -1;
489}
490
491- (int) stopRatioSetting
492{
493        return fStopRatioSetting;
494}
495
496- (void) setStopRatioSetting: (int) setting
497{
498    fStopRatioSetting = setting;
499}
500
501- (float) ratioLimit
502{
503    return fRatioLimit;
504}
505
506- (void) setRatioLimit: (float) limit
507{
508    if (limit >= 0)
509        fRatioLimit = limit;
510}
511
512- (void) setWaitToStart: (BOOL) wait
513{
514    fWaitToStart = wait;
515}
516
517- (BOOL) waitingToStart
518{
519    return fWaitToStart;
520}
521
522- (void) revealData
523{
524    [[NSWorkspace sharedWorkspace] selectFile: [self dataLocation] inFileViewerRootedAtPath: nil];
525}
526
527- (void) revealPublicTorrent
528{
529    if (fPublicTorrent)
530        [[NSWorkspace sharedWorkspace] selectFile: fPublicTorrentLocation inFileViewerRootedAtPath: nil];
531}
532
533- (void) trashData
534{
535    [self trashFile: [self dataLocation]];
536}
537
538- (void) trashTorrent
539{
540    if (fPublicTorrent)
541        [self trashFile: [self publicTorrentLocation]];
542}
543
544- (BOOL) alertForRemainingDiskSpace
545{
546    if ([self progress] >= 1.0)
547        return YES;
548   
549    NSString * volumeName = [[[NSFileManager defaultManager] componentsToDisplayForPath: [self downloadFolder]]
550                                                                                                objectAtIndex: 0];
551    NSDictionary * fsAttributes = [[NSFileManager defaultManager] fileSystemAttributesAtPath: [self downloadFolder]];
552    uint64_t remainingSpace = [[fsAttributes objectForKey: NSFileSystemFreeSize] unsignedLongLongValue],
553            torrentRemaining = [self size] - (uint64_t)[self downloadedValid];
554   
555    /*NSLog(@"Volume: %@", volumeName);
556    NSLog(@"Remaining disk space: %qu (%@)", remainingSpace, [NSString stringForFileSize: remainingSpace]);
557    NSLog(@"Torrent remaining size: %qu (%@)", torrentRemaining, [NSString stringForFileSize: torrentRemaining]);*/
558   
559    if (volumeName && remainingSpace <= torrentRemaining)
560    {
561        NSAlert * alert = [[NSAlert alloc] init];
562        [alert setMessageText: [NSString stringWithFormat:
563                                NSLocalizedString(@"Not enough remaining disk space to download \"%@\" completely.",
564                                    "Torrent file disk space alert -> title"), [self name]]];
565        [alert setInformativeText: [NSString stringWithFormat:
566                        NSLocalizedString(@"The transfer will be paused. Clear up space on \"%@\" to continue.",
567                                            "Torrent file disk space alert -> message"), volumeName]];
568        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Torrent file disk space alert -> button")];
569        [alert addButtonWithTitle: NSLocalizedString(@"Download Anyway", "Torrent file disk space alert -> button")];
570       
571        if ([alert runModal] == NSAlertFirstButtonReturn)
572        {
573            [[NSNotificationCenter defaultCenter] postNotificationName: @"StoppedDownloading" object: self];
574            return NO;
575        }
576        else
577            return YES;
578       
579        [alert release];
580    }
581    return YES;
582}
583
584- (BOOL) alertForVolumeAvailable
585{
586    NSArray * pathComponents = [[self downloadFolder] pathComponents];
587    if ([pathComponents count] < 3)
588        return YES;
589   
590    NSString * volume = [[[pathComponents objectAtIndex: 0] stringByAppendingPathComponent:
591                    [pathComponents objectAtIndex: 1]] stringByAppendingPathComponent: [pathComponents objectAtIndex: 2]];
592   
593    /*NSLog(@"%@", [self downloadFolder]);
594    NSLog(@"Volume: %@", volume);*/
595   
596    if (![[NSFileManager defaultManager] fileExistsAtPath: volume])
597    {
598        NSString * volumeName = [pathComponents objectAtIndex: 2];
599       
600        NSAlert * alert = [[NSAlert alloc] init];
601        [alert setMessageText: [NSString stringWithFormat:
602                                NSLocalizedString(@"The volume for downloading \"%@\" cannot be found.",
603                                    "Volume cannot be found alert -> title"), [self name]]];
604        [alert setInformativeText: [NSString stringWithFormat:
605                        NSLocalizedString(@"The transfer will be paused. Mount the volume \"%@\" to continue.",
606                                            "Volume cannot be found alert -> message"), volumeName]];
607        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Volume cannot be found alert -> button")];
608        [alert addButtonWithTitle: [NSLocalizedString(@"Choose New Directory",
609                                    "Volume cannot be found alert -> directory button") stringByAppendingEllipsis]];
610       
611        if ([alert runModal] == NSAlertFirstButtonReturn)
612            [[NSNotificationCenter defaultCenter] postNotificationName: @"StoppedDownloading" object: self];
613        else
614        {
615            NSOpenPanel * panel = [NSOpenPanel openPanel];
616           
617            [panel setPrompt: @"Select"];
618            [panel setAllowsMultipleSelection: NO];
619            [panel setCanChooseFiles: NO];
620            [panel setCanChooseDirectories: YES];
621
622            [panel setMessage: [NSString stringWithFormat: NSLocalizedString(@"Select the download folder for \"%@\"",
623                                "Open torrent -> select destination folder"), [self name]]];
624           
625            [[NSNotificationCenter defaultCenter] postNotificationName: @"MakeWindowKey" object: nil];
626            [panel beginSheetForDirectory: nil file: nil types: nil modalForWindow: [NSApp keyWindow] modalDelegate: self
627                    didEndSelector: @selector(destinationChoiceClosed:returnCode:contextInfo:) contextInfo: nil];
628        }
629       
630        [alert release];
631       
632        return NO;
633    }
634   
635    return YES;
636}
637
638- (void) destinationChoiceClosed: (NSOpenPanel *) openPanel returnCode: (int) code contextInfo: (void *) context
639{
640    NSString * folder = [[openPanel filenames] objectAtIndex: 0];
641    if (code == NSOKButton)
642    {
643        if (fUseIncompleteFolder)
644        {
645            [fIncompleteFolder release];
646            fIncompleteFolder = [folder retain];
647            [self setDownloadFolder: nil];
648        }
649        else
650        {
651            [fDownloadFolder release];
652            fDownloadFolder = folder;
653            [self setDownloadFolder: fDownloadFolder];
654        }
655       
656        [self startTransfer];
657        [self update];
658       
659        [[NSNotificationCenter defaultCenter] postNotificationName: @"UpdateInfoSettings" object: nil];
660    }
661    else
662        [[NSNotificationCenter defaultCenter] postNotificationName: @"StoppedDownloading" object: self];
663}
664
665- (BOOL) alertForMoveVolumeAvailable
666{
667    NSArray * pathComponents = [fDownloadFolder pathComponents];
668    if ([pathComponents count] < 3)
669        return YES;
670   
671    NSString * volume = [[[pathComponents objectAtIndex: 0] stringByAppendingPathComponent:
672                    [pathComponents objectAtIndex: 1]] stringByAppendingPathComponent: [pathComponents objectAtIndex: 2]];
673   
674    /*NSLog(@"%@", [self downloadFolder]);
675    NSLog(@"Volume: %@", volume);*/
676   
677    if (![[NSFileManager defaultManager] fileExistsAtPath: volume])
678    {
679        NSAlert * alert = [[NSAlert alloc] init];
680        [alert setMessageText: [NSString stringWithFormat:
681                                NSLocalizedString(@"The volume for moving the completed \"%@\" cannot be found.",
682                                    "Move volume cannot be found alert -> title"), [self name]]];
683        [alert setInformativeText: NSLocalizedString(@"The file will remain in its current location",
684                                    "Move volume cannot be found alert -> message")];
685        [alert addButtonWithTitle: NSLocalizedString(@"OK", "Move volume cannot be found alert -> button")];
686       
687        [alert runModal];
688        [alert release];
689       
690        return NO;
691    }
692   
693    return YES;
694}
695
696- (NSImage *) icon
697{
698    return fIcon;
699}
700
701- (NSImage *) iconFlipped
702{
703    return fIconFlipped;
704}
705
706- (NSImage *) iconSmall
707{
708    return fIconSmall;
709}
710
711- (NSString *) name
712{
713    return [NSString stringWithUTF8String: fInfo->name];
714}
715
716- (uint64_t) size
717{
718    return fInfo->totalSize;
719}
720
721- (NSString *) trackerAddress
722{
723    return [NSString stringWithFormat: @"http://%s:%d", fStat->trackerAddress, fStat->trackerPort];
724}
725
726- (NSString *) trackerAddressAnnounce
727{
728    return [NSString stringWithUTF8String: fStat->trackerAnnounce];
729}
730
731- (NSString *) comment
732{
733    return [NSString stringWithUTF8String: fInfo->comment];
734}
735
736- (NSString *) creator
737{
738    return [NSString stringWithUTF8String: fInfo->creator];
739}
740
741- (NSDate *) dateCreated
742{
743    int date = fInfo->dateCreated;
744    return date > 0 ? [NSDate dateWithTimeIntervalSince1970: date] : nil;
745}
746
747- (int) pieceSize
748{
749    return fInfo->pieceSize;
750}
751
752- (int) pieceCount
753{
754    return fInfo->pieceCount;
755}
756
757- (NSString *) hashString
758{
759    return [NSString stringWithUTF8String: fInfo->hashString];
760}
761
762- (BOOL) privateTorrent
763{
764    return fInfo->privateTorrent;
765}
766
767- (NSString *) torrentLocation
768{
769    return [NSString stringWithUTF8String: fInfo->torrent];
770}
771
772- (NSString *) publicTorrentLocation
773{
774    return fPublicTorrentLocation;
775}
776
777- (NSString *) dataLocation
778{
779    return [[self downloadFolder] stringByAppendingPathComponent: [self name]];
780}
781
782- (BOOL) publicTorrent
783{
784    return fPublicTorrent;
785}
786
787- (NSString *) stateString
788{
789    switch( fStat->status )
790    {
791        case TR_STATUS_PAUSE:
792            return NSLocalizedString(@"Paused", "Torrent -> status string");
793            break;
794
795        case TR_STATUS_CHECK:
796            return [NSLocalizedString(@"Checking existing files", "Torrent -> status string") stringByAppendingEllipsis];
797            break;
798
799        case TR_STATUS_DOWNLOAD:
800            return NSLocalizedString(@"Downloading", "Torrent -> status string");
801            break;
802
803        case TR_STATUS_SEED:
804            return NSLocalizedString(@"Seeding", "Torrent -> status string");
805            break;
806
807        case TR_STATUS_STOPPING:
808            return [NSLocalizedString(@"Stopping", "Torrent -> status string") stringByAppendingEllipsis];
809            break;
810       
811        default:
812            return NSLocalizedString(@"N/A", "Torrent -> status string");
813    }
814}
815
816- (float) progress
817{
818    return fStat->progress;
819}
820
821- (int) eta
822{
823    return fStat->eta;
824}
825
826- (BOOL) isActive
827{
828    return fStat->status & TR_STATUS_ACTIVE;
829}
830
831- (BOOL) isSeeding
832{
833    return fStat->status == TR_STATUS_SEED;
834}
835
836- (BOOL) isPaused
837{
838    return fStat->status == TR_STATUS_PAUSE;
839}
840
841- (BOOL) isError
842{
843    return fStat->error & TR_ETRACKER;
844}
845
846- (NSString *) errorMessage
847{
848    [NSString stringWithUTF8String: fStat->trackerError];
849}
850
851- (BOOL) justFinished
852{
853    return tr_getFinished(fHandle);
854}
855
856- (NSArray *) peers
857{
858    int totalPeers, i;
859    tr_peer_stat_t * peers = tr_torrentPeers(fHandle, & totalPeers);
860   
861    NSMutableArray * peerDics = [NSMutableArray arrayWithCapacity: totalPeers];
862    NSMutableDictionary * dic;
863   
864    tr_peer_stat_t * peer;
865    NSString * client;
866    for (i = 0; i < totalPeers; i++)
867    {
868        peer = &peers[i];
869       
870        dic = [NSMutableDictionary dictionaryWithObjectsAndKeys:
871            [NSNumber numberWithBool: peer->isConnected], @"Connected",
872            [NSNumber numberWithBool: peer->isIncoming], @"Incoming",
873            [NSString stringWithCString: (char *) peer->addr encoding: NSUTF8StringEncoding], @"IP",
874            [NSString stringWithCString: (char *) peer->client encoding: NSUTF8StringEncoding], @"Client",
875            [NSNumber numberWithFloat: peer->progress], @"Progress",
876            [NSNumber numberWithBool: peer->isDownloading], @"UL To",
877            [NSNumber numberWithBool: peer->isUploading], @"DL From",
878            [NSNumber numberWithInt: peer->port], @"Port", nil];
879       
880        if (peer->isDownloading)
881            [dic setObject: [NSNumber numberWithFloat: peer->uploadToRate] forKey: @"UL To Rate"];
882        if (peer->isUploading)
883            [dic setObject: [NSNumber numberWithFloat: peer->downloadFromRate] forKey: @"DL From Rate"];
884       
885        [peerDics addObject: dic];
886    }
887   
888    tr_torrentPeersFree(peers, totalPeers);
889   
890    return peerDics;
891}
892
893- (NSString *) progressString
894{
895    return fProgressString;
896}
897
898- (NSString *) statusString
899{
900    return fStatusString;
901}
902
903- (NSString *) shortStatusString
904{
905    return fShortStatusString;
906}
907
908- (NSString *) remainingTimeString
909{
910    return fRemainingTimeString;
911}
912
913- (int) seeders
914{
915    return fStat->seeders;
916}
917
918- (int) leechers
919{
920    return fStat->leechers;
921}
922
923- (int) completedFromTracker
924{
925    return fStat->completedFromTracker;
926}
927
928- (int) totalPeers
929{
930    return fStat->peersTotal;
931}
932
933- (int) totalPeersIncoming
934{
935    return fStat->peersIncoming;
936}
937
938- (int) totalPeersOutgoing
939{
940    return [self totalPeers] - [self totalPeersIncoming];
941}
942
943//peers uploading to you
944- (int) peersUploading
945{
946    return fStat->peersUploading;
947}
948
949//peers downloading from you
950- (int) peersDownloading
951{
952    return fStat->peersDownloading;
953}
954
955- (float) downloadRate
956{
957    return fStat->rateDownload;
958}
959
960- (float) uploadRate
961{
962    return fStat->rateUpload;
963}
964
965- (float) downloadedValid
966{
967    return [self progress] * [self size];
968}
969
970- (uint64_t) downloadedTotal
971{
972    return fStat->downloaded;
973}
974
975- (uint64_t) uploadedTotal
976{
977    return fStat->uploaded;
978}
979
980- (float) swarmSpeed
981{
982    return fStat->swarmspeed;
983}
984
985- (NSNumber *) orderValue
986{
987    return [NSNumber numberWithInt: fOrderValue];
988}
989
990- (void) setOrderValue: (int) orderValue
991{
992    fOrderValue = orderValue;
993}
994
995- (NSArray *) fileList
996{
997    int count = fInfo->fileCount, i;
998    tr_file_t file;
999    NSMutableArray * files = [NSMutableArray arrayWithCapacity: count];
1000   
1001    for (i = 0; i < count; i++)
1002    {
1003        file = fInfo->files[i];
1004        [files addObject: [NSDictionary dictionaryWithObjectsAndKeys:
1005            [[self downloadFolder] stringByAppendingPathComponent: [NSString stringWithUTF8String: file.name]], @"Name",
1006            [NSNumber numberWithUnsignedLongLong: file.length], @"Size", nil]];
1007    }
1008   
1009    return files;
1010}
1011
1012- (NSDate *) date
1013{
1014    return fDate;
1015}
1016
1017- (NSNumber *) stateSortKey
1018{
1019    if (![self isActive])
1020        return [NSNumber numberWithInt: 0];
1021    else if ([self isSeeding])
1022        return [NSNumber numberWithInt: 1];
1023    else
1024        return [NSNumber numberWithInt: 2];
1025}
1026
1027- (NSNumber *) progressSortKey
1028{
1029    //if finished downloading sort by ratio instead of progress
1030    float progress = [self progress];
1031    return [NSNumber numberWithFloat: progress < 1.0 ? progress : 2.0 + [self ratio]];
1032}
1033
1034@end
1035
1036
1037@implementation Torrent (Private)
1038
1039//if a hash is given, attempt to load that; otherwise, attempt to open file at path
1040- (id) initWithHash: (NSString *) hashString path: (NSString *) path lib: (tr_handle_t *) lib
1041        publicTorrent: (NSNumber *) publicTorrent
1042        date: (NSDate *) date stopRatioSetting: (NSNumber *) stopRatioSetting
1043        ratioLimit: (NSNumber *) ratioLimit waitToStart: (NSNumber *) waitToStart
1044        orderValue: (NSNumber *) orderValue
1045{
1046    if (!(self = [super init]))
1047        return nil;
1048
1049    fLib = lib;
1050    fDefaults = [NSUserDefaults standardUserDefaults];
1051
1052    fPublicTorrent = path && (publicTorrent ? [publicTorrent boolValue] : ![fDefaults boolForKey: @"DeleteOriginalTorrent"]);
1053    if (fPublicTorrent)
1054        fPublicTorrentLocation = [path retain];
1055
1056    int error;
1057    if (hashString)
1058        fHandle = tr_torrentInitSaved(fLib, [hashString UTF8String], TR_FSAVEPRIVATE, & error);
1059   
1060    if (!fHandle && path)
1061        fHandle = tr_torrentInit(fLib, [path UTF8String], TR_FSAVEPRIVATE, & error);
1062
1063    if (!fHandle)
1064    {
1065        [self release];
1066        return nil;
1067    }
1068   
1069    fInfo = tr_torrentInfo( fHandle );
1070
1071    fDate = date ? [date retain] : [[NSDate alloc] init];
1072   
1073    fStopRatioSetting = stopRatioSetting ? [stopRatioSetting intValue] : -1;
1074    fRatioLimit = ratioLimit ? [ratioLimit floatValue] : [fDefaults floatForKey: @"RatioLimit"];
1075    fFinishedSeeding = NO;
1076   
1077    fWaitToStart = waitToStart ? [waitToStart boolValue] : [fDefaults boolForKey: @"AutoStartDownload"];
1078    fOrderValue = orderValue ? [orderValue intValue] : tr_torrentCount(fLib) - 1;
1079    fError = NO;
1080   
1081    NSString * fileType = fInfo->multifile ? NSFileTypeForHFSTypeCode('fldr') : [[self name] pathExtension];
1082    fIcon = [[NSWorkspace sharedWorkspace] iconForFileType: fileType];
1083    [fIcon retain];
1084   
1085    fIconFlipped = [fIcon copy];
1086    [fIconFlipped setFlipped: YES];
1087   
1088    fIconSmall = [fIconFlipped copy];
1089    [fIconSmall setScalesWhenResized: YES];
1090    [fIconSmall setSize: NSMakeSize(16.0, 16.0)];
1091
1092    fProgressString = [[NSMutableString alloc] initWithCapacity: 50];
1093    fStatusString = [[NSMutableString alloc] initWithCapacity: 75];
1094    fShortStatusString = [[NSMutableString alloc] initWithCapacity: 30];
1095    fRemainingTimeString = [[NSMutableString alloc] initWithCapacity: 30];
1096   
1097    //set up advanced bar
1098    fBitmap = [[NSBitmapImageRep alloc] initWithBitmapDataPlanes: nil
1099        pixelsWide: MAX_PIECES pixelsHigh: BAR_HEIGHT bitsPerSample: 8 samplesPerPixel: 4 hasAlpha: YES
1100        isPlanar: NO colorSpaceName: NSCalibratedRGBColorSpace bytesPerRow: 0 bitsPerPixel: 0];
1101   
1102    fPieces = malloc(MAX_PIECES);
1103    int i;
1104    for (i = 0; i < MAX_PIECES; i++)
1105        fPieces[i] = BLANK_PIECE;
1106
1107    [self update];
1108    return self;
1109}
1110
1111- (NSImage *) advancedBar
1112{
1113    int h, w;
1114    uint32_t * p;
1115    uint8_t * bitmapData = [fBitmap bitmapData];
1116    int bytesPerRow = [fBitmap bytesPerRow];
1117
1118    int8_t * pieces = malloc(MAX_PIECES);
1119    [self getAvailability: pieces size: MAX_PIECES];
1120   
1121    //lines 2 to 14: blue, green, or gray depending on whether we have the piece or not
1122    int have = 0, avail = 0;
1123    uint32_t color;
1124    BOOL change;
1125    for (w = 0; w < MAX_PIECES; w++)
1126    {
1127        change = NO;
1128        if (pieces[w] < 0)
1129        {
1130            if (fPieces[w] != -1)
1131            {
1132                color = kBlue;
1133                fPieces[w] = -1;
1134                change = YES;
1135            }
1136            have++;
1137        }
1138        else if (pieces[w] == 0)
1139        {
1140            if (fPieces[w] != 0)
1141            {
1142                color = kGray;
1143                fPieces[w] = 0;
1144                change = YES;
1145            }
1146        }
1147        else
1148        {
1149            if (pieces[w] == 1)
1150            {
1151                if (fPieces[w] != 1)
1152                {
1153                    color = kGreen1;
1154                    fPieces[w] = 1;
1155                    change = YES;
1156                }
1157            }
1158            else if (pieces[w] == 2)
1159            {
1160                if (fPieces[w] != 2)
1161                {
1162                    color = kGreen2;
1163                    fPieces[w] = 2;
1164                    change = YES;
1165                }
1166            }
1167            else
1168            {
1169                if (fPieces[w] != 3)
1170                {
1171                    color = kGreen3;
1172                    fPieces[w] = 3;
1173                    change = YES;
1174                }
1175            }
1176            avail++;
1177        }
1178       
1179        if (change)
1180        {
1181            //point to pixel (w, 2) and draw "vertically"
1182            p = (uint32_t *)(bitmapData + 2 * bytesPerRow) + w;
1183            for (h = 2; h < BAR_HEIGHT; h++)
1184            {
1185                p[0] = color;
1186                p = (uint32_t *)((uint8_t *)p + bytesPerRow);
1187            }
1188        }
1189    }
1190   
1191    //first two lines: dark blue to show progression, green to show available
1192    p = (uint32_t *) bitmapData;
1193    for (w = 0; w < have; w++)
1194    {
1195        p[w] = kBlue2;
1196        p[w + bytesPerRow / 4] = kBlue2;
1197    }
1198    for (; w < avail + have; w++)
1199    {
1200        p[w] = kGreen3;
1201        p[w + bytesPerRow / 4] = kGreen3;
1202    }
1203    for (; w < MAX_PIECES; w++)
1204    {
1205        p[w] = kWhite;
1206        p[w + bytesPerRow / 4] = kWhite;
1207    }
1208   
1209    free(pieces);
1210   
1211    //actually draw image
1212    NSImage * bar = [[NSImage alloc] initWithSize: [fBitmap size]];
1213    [bar addRepresentation: fBitmap];
1214    [bar setScalesWhenResized: YES];
1215   
1216    return [bar autorelease];
1217}
1218
1219- (void) trashFile: (NSString *) path
1220{
1221    //attempt to move to trash
1222    if (![[NSWorkspace sharedWorkspace] performFileOperation: NSWorkspaceRecycleOperation
1223            source: [path stringByDeletingLastPathComponent] destination: @""
1224            files: [NSArray arrayWithObject: [path lastPathComponent]] tag: nil])
1225    {
1226        //if cannot trash, just delete it (will work if it is on a remote volume)
1227        if (![[NSFileManager defaultManager] removeFileAtPath: path handler: nil])
1228            NSLog(@"Could not trash %@", path);
1229    }
1230}
1231
1232@end
Note: See TracBrowser for help on using the repository browser.