source: trunk/gtk/tr_torrent.c @ 2389

Last change on this file since 2389 was 2389, checked in by charles, 15 years ago

remove debugging statements that accidentally got checked in r2388

  • Property svn:keywords set to Date Rev Author Id
File size: 16.6 KB
Line 
1/******************************************************************************
2 * $Id: tr_torrent.c 2389 2007-07-18 05:33:20Z charles $
3 *
4 * Copyright (c) 2006-2007 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#include <string.h>
26#include <unistd.h>
27
28#include <gtk/gtk.h>
29#include <glib/gi18n.h>
30
31#include "transmission.h"
32#include "bencode.h"
33
34#include "tr_prefs.h"
35#include "tr_torrent.h"
36#include "util.h"
37
38enum {
39  TR_TORRENT_HANDLE = 1,
40  TR_TORRENT_DIR,
41};
42
43static void
44tr_torrent_init(GTypeInstance *instance, gpointer g_class);
45static void
46tr_torrent_set_property(GObject *object, guint property_id,
47                        const GValue *value, GParamSpec *pspec);
48static void
49tr_torrent_get_property(GObject *object, guint property_id,
50                        GValue *value, GParamSpec *pspec);
51static void
52tr_torrent_class_init(gpointer g_class, gpointer g_class_data);
53static void
54tr_torrent_dispose(GObject *obj);
55static void
56tr_torrent_set_folder(TrTorrent *tor);
57
58static gpointer
59tracker_boxed_fake_copy( gpointer boxed )
60{
61    return boxed;
62}
63
64static void
65tracker_boxed_fake_free( gpointer boxed SHUTUP )
66{
67}
68
69GType
70tr_tracker_boxed_get_type( void )
71{
72    static GType type = 0;
73
74    if( 0 == type )
75    {
76        type = g_boxed_type_register_static( "TrTrackerBoxed",
77                                             tracker_boxed_fake_copy,
78                                             tracker_boxed_fake_free );
79    }
80
81    return type;
82}
83
84GType
85tr_torrent_get_type(void) {
86  static GType type = 0;
87
88  if(0 == type) {
89    static const GTypeInfo info = {
90      sizeof (TrTorrentClass),
91      NULL,   /* base_init */
92      NULL,   /* base_finalize */
93      tr_torrent_class_init,   /* class_init */
94      NULL,   /* class_finalize */
95      NULL,   /* class_data */
96      sizeof (TrTorrent),
97      0,      /* n_preallocs */
98      tr_torrent_init, /* instance_init */
99      NULL,
100    };
101    type = g_type_register_static(G_TYPE_OBJECT, "TrTorrent", &info, 0);
102  }
103  return type;
104}
105
106static void
107tr_torrent_class_init(gpointer g_class, gpointer g_class_data SHUTUP) {
108  GObjectClass *gobject_class = G_OBJECT_CLASS(g_class);
109  GParamSpec *pspec;
110
111  gobject_class->set_property = tr_torrent_set_property;
112  gobject_class->get_property = tr_torrent_get_property;
113  gobject_class->dispose = tr_torrent_dispose;
114
115  pspec = g_param_spec_pointer("torrent-handle", "Torrent handle",
116                               "Torrent handle from libtransmission",
117                               G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
118  g_object_class_install_property(gobject_class, TR_TORRENT_HANDLE, pspec);
119
120  pspec = g_param_spec_string("download-directory", "Download directory",
121                              "Directory to download files to", NULL,
122                              G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
123  g_object_class_install_property(gobject_class, TR_TORRENT_DIR, pspec);
124}
125
126static void
127tr_torrent_init(GTypeInstance *instance, gpointer g_class SHUTUP) {
128  TrTorrent *self = (TrTorrent *)instance;
129
130#ifdef REFDBG
131  fprintf( stderr, "torrent %p init\n", self );
132#endif
133
134  self->handle = NULL;
135  self->lastStatTime = 0;
136  self->dir = NULL;
137  self->delfile = NULL;
138  self->severed = FALSE;
139  self->disposed = FALSE;
140  self->ul_cap_enabled = FALSE;
141  self->ul_cap = 0;
142  self->dl_cap_enabled = FALSE;
143  self->dl_cap = 0;
144}
145
146static void
147tr_torrent_set_property(GObject *object, guint property_id,
148                        const GValue *value, GParamSpec *pspec) {
149  TrTorrent *self = (TrTorrent*)object;
150
151  if(self->severed)
152    return;
153
154  switch(property_id) {
155    case TR_TORRENT_HANDLE:
156      g_assert(NULL == self->handle);
157      self->handle = g_value_get_pointer(value);
158      if( self->handle ) {
159          self->ul_cap         = tr_torrentGetMaxSpeedUL       ( self->handle );
160          self->ul_cap_enabled = tr_torrentIsMaxSpeedEnabledUL ( self->handle );
161          self->dl_cap         = tr_torrentGetMaxSpeedDL       ( self->handle );
162          self->dl_cap_enabled = tr_torrentIsMaxSpeedEnabledDL ( self->handle );
163      }
164      if(NULL != self->handle && NULL != self->dir)
165        tr_torrent_set_folder(self);
166      break;
167    case TR_TORRENT_DIR:
168      g_assert(NULL == self->dir);
169      self->dir = g_value_dup_string(value);
170      if(NULL != self->handle && NULL != self->dir)
171        tr_torrent_set_folder(self);
172      break;
173    default:
174      G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
175      break;
176  }
177}
178
179static void
180tr_torrent_get_property(GObject *object, guint property_id,
181                        GValue *value, GParamSpec *pspec) {
182  TrTorrent *self = (TrTorrent*)object;
183
184  if(self->severed)
185    return;
186
187  switch(property_id) {
188    case TR_TORRENT_HANDLE:
189      g_value_set_pointer(value, self->handle);
190      break;
191    case TR_TORRENT_DIR:
192      g_value_set_string(value, (NULL != self->dir ? self->dir :
193                                 tr_torrentGetFolder(self->handle)));
194      break;
195    default:
196      G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
197      break;
198  }
199}
200
201static void
202tr_torrent_dispose(GObject *obj) {
203  GObjectClass *parent = g_type_class_peek(g_type_parent(TR_TORRENT_TYPE));
204  TrTorrent *self = (TrTorrent*)obj;
205
206  if(self->disposed)
207    return;
208  self->disposed = TRUE;
209
210#ifdef REFDBG
211  fprintf( stderr, "torrent %p dispose\n", self );
212#endif
213
214  if( !self->severed )
215      tr_torrent_sever( self );
216
217  g_free (self->delfile);
218  g_free (self->dir);
219
220  /* Chain up to the parent class */
221  parent->dispose(obj);
222}
223
224void
225tr_torrent_sever( TrTorrent * self )
226{
227    g_return_if_fail (TR_IS_TORRENT( self ));
228
229    if( !self->severed )
230    {
231        self->severed = TRUE;
232
233        if( self->handle )
234            tr_torrentClose( self->handle );
235    }
236}
237
238tr_torrent_t *
239tr_torrent_handle(TrTorrent *tor)
240{
241    g_assert( TR_IS_TORRENT(tor) );
242
243    return tor->severed ? NULL : tor->handle;
244}
245
246static tr_stat_t*
247refreshStat( TrTorrent * tor )
248{
249    tor->lastStatTime= time( NULL );
250    tor->stat = *tr_torrentStat( tor->handle );
251    return &tor->stat;
252}
253
254const tr_stat_t *
255tr_torrent_stat(TrTorrent *tor)
256{
257    g_assert( TR_IS_TORRENT(tor) );
258
259    if( !tor->severed && tor->lastStatTime!=time(NULL) )
260        refreshStat( tor );
261
262    return &tor->stat;
263}
264
265const tr_info_t *
266tr_torrent_info(TrTorrent *tor) {
267  TR_IS_TORRENT(tor);
268
269  if(tor->severed)
270    return NULL;
271
272  return tr_torrentInfo(tor->handle);
273}
274
275void
276tr_torrent_start( TrTorrent * self )
277{
278    TR_IS_TORRENT( self );
279
280    if( !self->severed )
281        tr_torrentStart( self->handle );
282}
283
284void
285tr_torrent_stop( TrTorrent * self )
286{
287    TR_IS_TORRENT( self );
288
289    if( !self->severed )
290        tr_torrentStop( self->handle );
291}
292
293static TrTorrent *
294maketorrent( tr_torrent_t * handle )
295{
296    tr_torrentDisablePex( handle,
297                          !tr_prefs_get_bool_with_default( PREF_ID_PEX ) );
298
299    return g_object_new( TR_TORRENT_TYPE,
300                         "torrent-handle", handle,
301                         NULL);
302}
303
304TrTorrent *
305tr_torrent_new( tr_handle_t * back, const char *torrent, const char *dir,
306                enum tr_torrent_action act, gboolean paused, char **err )
307{
308  TrTorrent *ret;
309  tr_torrent_t *handle;
310  int errcode, flags;
311
312  g_assert(NULL != dir);
313
314  *err = NULL;
315
316  errcode = -1;
317
318  flags = ( TR_TOR_COPY == act || TR_TOR_MOVE == act ? TR_FLAG_SAVE : 0 );
319  if( paused )
320      flags |= TR_FLAG_PAUSED;
321
322  handle = tr_torrentInit( back, torrent, dir, flags, &errcode );
323
324  if(NULL == handle) {
325    switch(errcode) {
326      case TR_EINVALID:
327        *err = g_strdup_printf(_("%s: not a valid torrent file"), torrent);
328        break;
329      case TR_EDUPLICATE:
330        *err = g_strdup_printf(_("%s: torrent is already open"), torrent);
331        break;
332      default:
333        *err = g_strdup(torrent);
334        break;
335    }
336    return NULL;
337  }
338
339  ret = maketorrent( handle );
340
341  if( TR_TOR_MOVE == act )
342    ret->delfile = g_strdup(torrent);
343
344  return ret;
345}
346
347TrTorrent *
348tr_torrent_new_with_data( tr_handle_t * back, uint8_t * data, size_t size,
349                          const char * dir, gboolean paused, char ** err )
350{
351    tr_torrent_t * handle;
352    int            errcode;
353    int            flags;
354
355    g_assert( NULL != dir );
356
357    *err = NULL;
358
359    flags = TR_FLAG_SAVE;
360    if( paused )
361        flags |= TR_FLAG_PAUSED;
362
363    errcode = -1;
364    handle  = tr_torrentInitData( back, data, size, dir, flags, &errcode );
365
366    if( NULL == handle )
367    {
368        switch( errcode )
369        {
370            case TR_EINVALID:
371                *err = g_strdup( _("not a valid torrent file") );
372                break;
373            case TR_EDUPLICATE:
374                *err = g_strdup( _("torrent is already open") );
375                break;
376            default:
377                *err = g_strdup( "" );
378                break;
379        }
380        return NULL;
381    }
382
383    return maketorrent( handle );
384}
385
386TrTorrent *
387tr_torrent_new_with_state( tr_handle_t * back, benc_val_t * state,
388                           gboolean forcedpause, char ** err )
389{
390  TrTorrent * ret;
391  tr_torrent_t * handle;
392  int ii, errcode;
393  int flags;
394  benc_val_t *name, *data;
395  char *torrent, *hash, *dir;
396  gboolean paused = FALSE;
397  gboolean seeding_cap_enabled = FALSE;
398  gdouble seeding_cap = 0.0;
399
400  *err = NULL;
401
402  if(TYPE_DICT != state->type)
403    return NULL;
404
405  torrent = hash = dir = NULL;
406
407  for(ii = 0; ii + 1 < state->val.l.count; ii += 2) {
408    name = state->val.l.vals + ii;
409    data = state->val.l.vals + ii + 1;
410    if(TYPE_STR == name->type &&
411       (TYPE_STR == data->type || TYPE_INT == data->type)) {
412      char * key = name->val.s.s;
413      char * val = data->val.s.s;
414           if (!strcmp (key, "torrent")) torrent = val;
415      else if (!strcmp (key, "hash")) hash = val;
416      else if (!strcmp (key, "dir")) dir = val;
417      else if (!strcmp (key, "paused")) paused = !!data->val.i;
418      else if (!strcmp (key, "seeding-cap-ratio")) seeding_cap = (data->val.i / 100.0);
419      else if (!strcmp (key, "seeding-cap-enabled")) seeding_cap_enabled = !!data->val.i;
420    }
421  }
422
423  if((NULL != torrent && NULL != hash) ||
424     (NULL == torrent && NULL == hash) || NULL == dir)
425    return NULL;
426
427  flags = 0;
428  if( paused || forcedpause )
429      flags |= TR_FLAG_PAUSED;
430
431  if( NULL != hash )
432    handle = tr_torrentInitSaved(back, hash, dir, flags, &errcode);
433  else
434    handle = tr_torrentInit(back, torrent, dir, flags, &errcode);
435
436  if(NULL == handle) {
437    torrent = ( NULL == hash ? torrent : hash );
438    switch(errcode) {
439      case TR_EINVALID:
440        *err = g_strdup_printf(_("%s: not a valid torrent file"), torrent);
441        break;
442      case TR_EDUPLICATE:
443        *err = g_strdup_printf(_("%s: torrent is already open"), torrent);
444        break;
445      default:
446        *err = g_strdup(torrent);
447        break;
448    }
449    return NULL;
450  }
451
452  ret = maketorrent( handle );
453  ret->seeding_cap = seeding_cap;
454  ret->seeding_cap_enabled = seeding_cap_enabled;
455  return ret;
456}
457
458gboolean
459tr_torrent_get_state( TrTorrent * tor, benc_val_t * state )
460{
461    const tr_info_t  * inf;
462
463    TR_IS_TORRENT( tor );
464
465    if( tor->severed )
466    {
467        return FALSE;
468    }
469
470    inf = tr_torrentInfo( tor->handle );
471
472    tr_bencInit( state, TYPE_DICT );
473    if( tr_bencDictReserve( state, 3 ) )
474    {
475        return FALSE;
476    }
477
478    if( TR_FLAG_SAVE & inf->flags )
479    {
480        tr_bencInitStr( tr_bencDictAdd( state, "hash" ),
481                        inf->hashString, -1, 1 );
482    }
483    else
484    {
485        tr_bencInitStr( tr_bencDictAdd( state, "torrent" ),
486                        inf->torrent, -1, 1 );
487    }
488    tr_bencInitStr( tr_bencDictAdd( state, "dir" ),
489                    tr_torrentGetFolder( tor->handle ), -1, 1 );
490    tr_bencInitInt( tr_bencDictAdd( state, "paused" ),
491                    (refreshStat(tor)->status & TR_STATUS_INACTIVE) ? 1 : 0);
492    tr_bencInitInt( tr_bencDictAdd( state, "seeding-cap-ratio" ),
493                    (int)(tor->dl_cap * 100.0)); /* two decimal places */
494    tr_bencInitInt( tr_bencDictAdd( state, "seeding-cap-enabled" ),
495                    tor->seeding_cap_enabled ? 1 : 0);
496
497    return TRUE;
498}
499
500/* XXX this should probably be done with a signal */
501void
502tr_torrent_state_saved(TrTorrent *tor) {
503  TR_IS_TORRENT(tor);
504
505  if(tor->severed)
506    return;
507
508  if(NULL != tor->delfile) {
509    unlink(tor->delfile);
510    g_free(tor->delfile);
511    tor->delfile = NULL;
512  }
513}
514
515static void
516tr_torrent_set_folder(TrTorrent *tor) {
517  char *wd;
518
519  if(NULL != tor->dir)
520    tr_torrentSetFolder(tor->handle, tor->dir);
521  else {
522    wd = g_new(char, MAX_PATH_LENGTH + 1);
523    tr_torrentSetFolder(tor->handle,
524                        (NULL == getcwd(wd, MAX_PATH_LENGTH + 1) ? "." : wd));
525    g_free(wd);
526  }
527}
528
529static void
530refresh_upload_cap ( TrTorrent *gtor )
531{
532  tr_torrentEnableMaxSpeedUL( gtor->handle, gtor->ul_cap_enabled );
533  tr_torrentSetMaxSpeedUL( gtor->handle, gtor->ul_cap );
534}
535void
536tr_torrent_set_upload_cap_speed ( TrTorrent *gtor, int KiB_sec )
537{
538  gtor->ul_cap = KiB_sec;
539  refresh_upload_cap ( gtor );
540}
541void
542tr_torrent_set_upload_cap_enabled ( TrTorrent *gtor, gboolean b )
543{
544  gtor->ul_cap_enabled = b;
545  refresh_upload_cap ( gtor );
546}
547
548static void
549refresh_download_cap ( TrTorrent *gtor )
550{
551  tr_torrentEnableMaxSpeedDL( gtor->handle, gtor->dl_cap_enabled );
552  tr_torrentSetMaxSpeedDL( gtor->handle, gtor->dl_cap );
553}
554void
555tr_torrent_set_download_cap_speed ( TrTorrent *gtor, int KiB_sec )
556{
557  gtor->dl_cap = KiB_sec;
558  refresh_download_cap( gtor );
559}
560void
561tr_torrent_set_download_cap_enabled ( TrTorrent *gtor, gboolean b )
562{
563  gtor->dl_cap_enabled = b;
564  refresh_download_cap( gtor );
565}
566
567void
568tr_torrent_check_seeding_cap ( TrTorrent *gtor)
569{
570  const tr_stat_t * st = tr_torrent_stat( gtor );
571  if ((gtor->seeding_cap_enabled) && (st->ratio >= gtor->seeding_cap))
572    tr_torrent_stop (gtor);
573}
574void
575tr_torrent_set_seeding_cap_ratio ( TrTorrent *gtor, gdouble ratio )
576{
577  gtor->seeding_cap = ratio;
578  tr_torrent_check_seeding_cap (gtor);
579}
580void
581tr_torrent_set_seeding_cap_enabled ( TrTorrent *gtor, gboolean b )
582{
583  if ((gtor->seeding_cap_enabled = b))
584    tr_torrent_check_seeding_cap (gtor);
585}
586
587char *
588tr_torrent_status_str ( TrTorrent * gtor )
589{
590    char * top = 0;
591
592    const tr_stat_t * st = tr_torrent_stat( gtor );
593
594    const int tpeers = MAX (st->peersConnected, 0);
595    const int upeers = MAX (st->peersGettingFromUs, 0);
596    const int eta = st->eta;
597    const double prog = st->percentDone * 100.0; /* [0...100] */
598
599    switch( st->status )
600    {
601        case TR_STATUS_CHECK_WAIT:
602            top = g_strdup_printf( _("Waiting to check existing files (%.1f%%)"), prog );
603            break;
604
605        case TR_STATUS_CHECK:
606            top = g_strdup_printf( _("Checking existing files (%.1f%%)"), prog );
607            break;
608
609        case TR_STATUS_DOWNLOAD:
610            if( eta < 0 )
611                top = g_strdup_printf( _("Stalled (%.1f%%)"), prog );
612            else {
613                char * timestr = readabletime(eta);
614                top = g_strdup_printf( _("%s remaining (%.1f%%)"), timestr, prog );
615                g_free(timestr);
616            }
617            break;
618
619        case TR_STATUS_DONE:
620            top = g_strdup_printf(
621                ngettext( "Uploading to %d of %d peer",
622                          "Uploading to %d of %d peers", tpeers ),
623                          upeers, tpeers );
624            break;
625
626        case TR_STATUS_SEED:
627            top = g_strdup_printf(
628                ngettext( "Seeding to %d of %d peer",
629                          "Seeding to %d of %d peers", tpeers ),
630                          upeers, tpeers );
631            break;
632
633        case TR_STATUS_STOPPING:
634            top = g_strdup( _("Stopping...") );
635            break;
636
637        case TR_STATUS_STOPPED:
638            top = g_strdup_printf( _("Stopped (%.1f%%)"), prog );
639            break;
640
641        default:
642            top = g_strdup_printf("Unrecognized state: %d", st->status );
643            break;
644
645    }
646
647    return top;
648}
Note: See TracBrowser for help on using the repository browser.