source: trunk/gtk/tr_torrent.c @ 2441

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

more work on the speed limits as hammered out w/BentMyWookie

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