source: trunk/gtk/tr_torrent.c @ 2388

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

fold per-torrent ul/dl speed cap settings into libtransmission. synchronize gtk+ client with this change. breaks os x client.

  • Property svn:keywords set to Date Rev Author Id
File size: 16.7 KB
Line 
1/******************************************************************************
2 * $Id: tr_torrent.c 2388 2007-07-18 05:27:45Z 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);
158g_message ("setting handle...");
159      if( self->handle ) {
160          self->ul_cap         = tr_torrentGetMaxSpeedUL       ( self->handle );
161          self->ul_cap_enabled = tr_torrentIsMaxSpeedEnabledUL ( self->handle );
162          self->dl_cap         = tr_torrentGetMaxSpeedDL       ( self->handle );
163          self->dl_cap_enabled = tr_torrentIsMaxSpeedEnabledDL ( self->handle );
164g_message ("ul cap [%d] dl_cap [%d]", self->ul_cap, self->dl_cap );
165      }
166      if(NULL != self->handle && NULL != self->dir)
167        tr_torrent_set_folder(self);
168      break;
169    case TR_TORRENT_DIR:
170      g_assert(NULL == self->dir);
171      self->dir = g_value_dup_string(value);
172      if(NULL != self->handle && NULL != self->dir)
173        tr_torrent_set_folder(self);
174      break;
175    default:
176      G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
177      break;
178  }
179}
180
181static void
182tr_torrent_get_property(GObject *object, guint property_id,
183                        GValue *value, GParamSpec *pspec) {
184  TrTorrent *self = (TrTorrent*)object;
185
186  if(self->severed)
187    return;
188
189  switch(property_id) {
190    case TR_TORRENT_HANDLE:
191      g_value_set_pointer(value, self->handle);
192      break;
193    case TR_TORRENT_DIR:
194      g_value_set_string(value, (NULL != self->dir ? self->dir :
195                                 tr_torrentGetFolder(self->handle)));
196      break;
197    default:
198      G_OBJECT_WARN_INVALID_PROPERTY_ID(object, property_id, pspec);
199      break;
200  }
201}
202
203static void
204tr_torrent_dispose(GObject *obj) {
205  GObjectClass *parent = g_type_class_peek(g_type_parent(TR_TORRENT_TYPE));
206  TrTorrent *self = (TrTorrent*)obj;
207
208  if(self->disposed)
209    return;
210  self->disposed = TRUE;
211
212#ifdef REFDBG
213  fprintf( stderr, "torrent %p dispose\n", self );
214#endif
215
216  if( !self->severed )
217      tr_torrent_sever( self );
218
219  g_free (self->delfile);
220  g_free (self->dir);
221
222  /* Chain up to the parent class */
223  parent->dispose(obj);
224}
225
226void
227tr_torrent_sever( TrTorrent * self )
228{
229    g_return_if_fail (TR_IS_TORRENT( self ));
230
231    if( !self->severed )
232    {
233        self->severed = TRUE;
234
235        if( self->handle )
236            tr_torrentClose( self->handle );
237    }
238}
239
240tr_torrent_t *
241tr_torrent_handle(TrTorrent *tor)
242{
243    g_assert( TR_IS_TORRENT(tor) );
244
245    return tor->severed ? NULL : tor->handle;
246}
247
248static tr_stat_t*
249refreshStat( TrTorrent * tor )
250{
251    tor->lastStatTime= time( NULL );
252    tor->stat = *tr_torrentStat( tor->handle );
253    return &tor->stat;
254}
255
256const tr_stat_t *
257tr_torrent_stat(TrTorrent *tor)
258{
259    g_assert( TR_IS_TORRENT(tor) );
260
261    if( !tor->severed && tor->lastStatTime!=time(NULL) )
262        refreshStat( tor );
263
264    return &tor->stat;
265}
266
267const tr_info_t *
268tr_torrent_info(TrTorrent *tor) {
269  TR_IS_TORRENT(tor);
270
271  if(tor->severed)
272    return NULL;
273
274  return tr_torrentInfo(tor->handle);
275}
276
277void
278tr_torrent_start( TrTorrent * self )
279{
280    TR_IS_TORRENT( self );
281
282    if( !self->severed )
283        tr_torrentStart( self->handle );
284}
285
286void
287tr_torrent_stop( TrTorrent * self )
288{
289    TR_IS_TORRENT( self );
290
291    if( !self->severed )
292        tr_torrentStop( self->handle );
293}
294
295static TrTorrent *
296maketorrent( tr_torrent_t * handle )
297{
298    tr_torrentDisablePex( handle,
299                          !tr_prefs_get_bool_with_default( PREF_ID_PEX ) );
300
301    return g_object_new( TR_TORRENT_TYPE,
302                         "torrent-handle", handle,
303                         NULL);
304}
305
306TrTorrent *
307tr_torrent_new( tr_handle_t * back, const char *torrent, const char *dir,
308                enum tr_torrent_action act, gboolean paused, char **err )
309{
310  TrTorrent *ret;
311  tr_torrent_t *handle;
312  int errcode, flags;
313
314  g_assert(NULL != dir);
315
316  *err = NULL;
317
318  errcode = -1;
319
320  flags = ( TR_TOR_COPY == act || TR_TOR_MOVE == act ? TR_FLAG_SAVE : 0 );
321  if( paused )
322      flags |= TR_FLAG_PAUSED;
323
324  handle = tr_torrentInit( back, torrent, dir, flags, &errcode );
325
326  if(NULL == handle) {
327    switch(errcode) {
328      case TR_EINVALID:
329        *err = g_strdup_printf(_("%s: not a valid torrent file"), torrent);
330        break;
331      case TR_EDUPLICATE:
332        *err = g_strdup_printf(_("%s: torrent is already open"), torrent);
333        break;
334      default:
335        *err = g_strdup(torrent);
336        break;
337    }
338    return NULL;
339  }
340
341  ret = maketorrent( handle );
342
343  if( TR_TOR_MOVE == act )
344    ret->delfile = g_strdup(torrent);
345
346  return ret;
347}
348
349TrTorrent *
350tr_torrent_new_with_data( tr_handle_t * back, uint8_t * data, size_t size,
351                          const char * dir, gboolean paused, char ** err )
352{
353    tr_torrent_t * handle;
354    int            errcode;
355    int            flags;
356
357    g_assert( NULL != dir );
358
359    *err = NULL;
360
361    flags = TR_FLAG_SAVE;
362    if( paused )
363        flags |= TR_FLAG_PAUSED;
364
365    errcode = -1;
366    handle  = tr_torrentInitData( back, data, size, dir, flags, &errcode );
367
368    if( NULL == handle )
369    {
370        switch( errcode )
371        {
372            case TR_EINVALID:
373                *err = g_strdup( _("not a valid torrent file") );
374                break;
375            case TR_EDUPLICATE:
376                *err = g_strdup( _("torrent is already open") );
377                break;
378            default:
379                *err = g_strdup( "" );
380                break;
381        }
382        return NULL;
383    }
384
385    return maketorrent( handle );
386}
387
388TrTorrent *
389tr_torrent_new_with_state( tr_handle_t * back, benc_val_t * state,
390                           gboolean forcedpause, char ** err )
391{
392  TrTorrent * ret;
393  tr_torrent_t * handle;
394  int ii, errcode;
395  int flags;
396  benc_val_t *name, *data;
397  char *torrent, *hash, *dir;
398  gboolean paused = FALSE;
399  gboolean seeding_cap_enabled = FALSE;
400  gdouble seeding_cap = 0.0;
401
402  *err = NULL;
403
404  if(TYPE_DICT != state->type)
405    return NULL;
406
407  torrent = hash = dir = NULL;
408
409  for(ii = 0; ii + 1 < state->val.l.count; ii += 2) {
410    name = state->val.l.vals + ii;
411    data = state->val.l.vals + ii + 1;
412    if(TYPE_STR == name->type &&
413       (TYPE_STR == data->type || TYPE_INT == data->type)) {
414      char * key = name->val.s.s;
415      char * val = data->val.s.s;
416           if (!strcmp (key, "torrent")) torrent = val;
417      else if (!strcmp (key, "hash")) hash = val;
418      else if (!strcmp (key, "dir")) dir = val;
419      else if (!strcmp (key, "paused")) paused = !!data->val.i;
420      else if (!strcmp (key, "seeding-cap-ratio")) seeding_cap = (data->val.i / 100.0);
421      else if (!strcmp (key, "seeding-cap-enabled")) seeding_cap_enabled = !!data->val.i;
422    }
423  }
424
425  if((NULL != torrent && NULL != hash) ||
426     (NULL == torrent && NULL == hash) || NULL == dir)
427    return NULL;
428
429  flags = 0;
430  if( paused || forcedpause )
431      flags |= TR_FLAG_PAUSED;
432
433  if( NULL != hash )
434    handle = tr_torrentInitSaved(back, hash, dir, flags, &errcode);
435  else
436    handle = tr_torrentInit(back, torrent, dir, flags, &errcode);
437
438  if(NULL == handle) {
439    torrent = ( NULL == hash ? torrent : hash );
440    switch(errcode) {
441      case TR_EINVALID:
442        *err = g_strdup_printf(_("%s: not a valid torrent file"), torrent);
443        break;
444      case TR_EDUPLICATE:
445        *err = g_strdup_printf(_("%s: torrent is already open"), torrent);
446        break;
447      default:
448        *err = g_strdup(torrent);
449        break;
450    }
451    return NULL;
452  }
453
454  ret = maketorrent( handle );
455  ret->seeding_cap = seeding_cap;
456  ret->seeding_cap_enabled = seeding_cap_enabled;
457  return ret;
458}
459
460gboolean
461tr_torrent_get_state( TrTorrent * tor, benc_val_t * state )
462{
463    const tr_info_t  * inf;
464
465    TR_IS_TORRENT( tor );
466
467    if( tor->severed )
468    {
469        return FALSE;
470    }
471
472    inf = tr_torrentInfo( tor->handle );
473
474    tr_bencInit( state, TYPE_DICT );
475    if( tr_bencDictReserve( state, 3 ) )
476    {
477        return FALSE;
478    }
479
480    if( TR_FLAG_SAVE & inf->flags )
481    {
482        tr_bencInitStr( tr_bencDictAdd( state, "hash" ),
483                        inf->hashString, -1, 1 );
484    }
485    else
486    {
487        tr_bencInitStr( tr_bencDictAdd( state, "torrent" ),
488                        inf->torrent, -1, 1 );
489    }
490    tr_bencInitStr( tr_bencDictAdd( state, "dir" ),
491                    tr_torrentGetFolder( tor->handle ), -1, 1 );
492    tr_bencInitInt( tr_bencDictAdd( state, "paused" ),
493                    (refreshStat(tor)->status & TR_STATUS_INACTIVE) ? 1 : 0);
494    tr_bencInitInt( tr_bencDictAdd( state, "seeding-cap-ratio" ),
495                    (int)(tor->dl_cap * 100.0)); /* two decimal places */
496    tr_bencInitInt( tr_bencDictAdd( state, "seeding-cap-enabled" ),
497                    tor->seeding_cap_enabled ? 1 : 0);
498
499    return TRUE;
500}
501
502/* XXX this should probably be done with a signal */
503void
504tr_torrent_state_saved(TrTorrent *tor) {
505  TR_IS_TORRENT(tor);
506
507  if(tor->severed)
508    return;
509
510  if(NULL != tor->delfile) {
511    unlink(tor->delfile);
512    g_free(tor->delfile);
513    tor->delfile = NULL;
514  }
515}
516
517static void
518tr_torrent_set_folder(TrTorrent *tor) {
519  char *wd;
520
521  if(NULL != tor->dir)
522    tr_torrentSetFolder(tor->handle, tor->dir);
523  else {
524    wd = g_new(char, MAX_PATH_LENGTH + 1);
525    tr_torrentSetFolder(tor->handle,
526                        (NULL == getcwd(wd, MAX_PATH_LENGTH + 1) ? "." : wd));
527    g_free(wd);
528  }
529}
530
531static void
532refresh_upload_cap ( TrTorrent *gtor )
533{
534  tr_torrentEnableMaxSpeedUL( gtor->handle, gtor->ul_cap_enabled );
535  tr_torrentSetMaxSpeedUL( gtor->handle, gtor->ul_cap );
536}
537void
538tr_torrent_set_upload_cap_speed ( TrTorrent *gtor, int KiB_sec )
539{
540  gtor->ul_cap = KiB_sec;
541  refresh_upload_cap ( gtor );
542}
543void
544tr_torrent_set_upload_cap_enabled ( TrTorrent *gtor, gboolean b )
545{
546  gtor->ul_cap_enabled = b;
547  refresh_upload_cap ( gtor );
548}
549
550static void
551refresh_download_cap ( TrTorrent *gtor )
552{
553  tr_torrentEnableMaxSpeedDL( gtor->handle, gtor->dl_cap_enabled );
554  tr_torrentSetMaxSpeedDL( gtor->handle, gtor->dl_cap );
555}
556void
557tr_torrent_set_download_cap_speed ( TrTorrent *gtor, int KiB_sec )
558{
559  gtor->dl_cap = KiB_sec;
560  refresh_download_cap( gtor );
561}
562void
563tr_torrent_set_download_cap_enabled ( TrTorrent *gtor, gboolean b )
564{
565  gtor->dl_cap_enabled = b;
566  refresh_download_cap( gtor );
567}
568
569void
570tr_torrent_check_seeding_cap ( TrTorrent *gtor)
571{
572  const tr_stat_t * st = tr_torrent_stat( gtor );
573  if ((gtor->seeding_cap_enabled) && (st->ratio >= gtor->seeding_cap))
574    tr_torrent_stop (gtor);
575}
576void
577tr_torrent_set_seeding_cap_ratio ( TrTorrent *gtor, gdouble ratio )
578{
579  gtor->seeding_cap = ratio;
580  tr_torrent_check_seeding_cap (gtor);
581}
582void
583tr_torrent_set_seeding_cap_enabled ( TrTorrent *gtor, gboolean b )
584{
585  if ((gtor->seeding_cap_enabled = b))
586    tr_torrent_check_seeding_cap (gtor);
587}
588
589char *
590tr_torrent_status_str ( TrTorrent * gtor )
591{
592    char * top = 0;
593
594    const tr_stat_t * st = tr_torrent_stat( gtor );
595
596    const int tpeers = MAX (st->peersConnected, 0);
597    const int upeers = MAX (st->peersGettingFromUs, 0);
598    const int eta = st->eta;
599    const double prog = st->percentDone * 100.0; /* [0...100] */
600
601    switch( st->status )
602    {
603        case TR_STATUS_CHECK_WAIT:
604            top = g_strdup_printf( _("Waiting to check existing files (%.1f%%)"), prog );
605            break;
606
607        case TR_STATUS_CHECK:
608            top = g_strdup_printf( _("Checking existing files (%.1f%%)"), prog );
609            break;
610
611        case TR_STATUS_DOWNLOAD:
612            if( eta < 0 )
613                top = g_strdup_printf( _("Stalled (%.1f%%)"), prog );
614            else {
615                char * timestr = readabletime(eta);
616                top = g_strdup_printf( _("%s remaining (%.1f%%)"), timestr, prog );
617                g_free(timestr);
618            }
619            break;
620
621        case TR_STATUS_DONE:
622            top = g_strdup_printf(
623                ngettext( "Uploading to %d of %d peer",
624                          "Uploading to %d of %d peers", tpeers ),
625                          upeers, tpeers );
626            break;
627
628        case TR_STATUS_SEED:
629            top = g_strdup_printf(
630                ngettext( "Seeding to %d of %d peer",
631                          "Seeding to %d of %d peers", tpeers ),
632                          upeers, tpeers );
633            break;
634
635        case TR_STATUS_STOPPING:
636            top = g_strdup( _("Stopping...") );
637            break;
638
639        case TR_STATUS_STOPPED:
640            top = g_strdup_printf( _("Stopped (%.1f%%)"), prog );
641            break;
642
643        default:
644            top = g_strdup_printf("Unrecognized state: %d", st->status );
645            break;
646
647    }
648
649    return top;
650}
Note: See TracBrowser for help on using the repository browser.