Merge branch 'fix-ft' into to-merge
[empathy.git] / libempathy / empathy-tp-file.c
1 /* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- */
2 /*
3  * Copyright (C) 2007-2008 Collabora Ltd.
4  * Copyright (C) 2007 Marco Barisione <marco@barisione.org>
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * Authors: Marco Barisione <marco@barisione.org>
21  *          Jonny Lamb <jonny.lamb@collabora.co.uk>
22  */
23
24 #include <config.h>
25
26 #include <string.h>
27 #include <unistd.h>
28 #include <sys/types.h>
29 #include <sys/socket.h>
30 #include <sys/un.h>
31
32 #include <glib/gi18n-lib.h>
33
34 #include <gio/gio.h>
35 #include <gio/gunixinputstream.h>
36 #include <gio/gunixoutputstream.h>
37
38 #include <telepathy-glib/proxy-subclass.h>
39 #include <telepathy-glib/util.h>
40
41 #include "empathy-tp-file.h"
42 #include "empathy-contact-factory.h"
43 #include "empathy-marshal.h"
44 #include "empathy-time.h"
45 #include "empathy-utils.h"
46
47 #include "extensions/extensions.h"
48
49 #define DEBUG_FLAG EMPATHY_DEBUG_FT
50 #include "empathy-debug.h"
51
52 /**
53  * SECTION:empathy-tp-file
54  * @short_description: File channel
55  * @see_also: #EmpathyTpFile, #EmpathyContact, empathy_dispatcher_send_file()
56  * @include: libempthy/empathy-tp-file.h
57  *
58  * The #EmpathyTpFile object represents a Telepathy file channel.
59  */
60
61 /**
62  * EMPATHY_TP_FILE_UNKNOWN_SIZE:
63  *
64  * Value used for the "size" or "estimated-size" properties when the size of
65  * the transferred file is unknown.
66  */
67
68 /* Functions to copy the content of a GInputStream to a GOutputStream */
69
70 #define N_BUFFERS 2
71 #define BUFFER_SIZE 4096
72
73 typedef struct {
74   GInputStream *in;
75   GOutputStream *out;
76   GCancellable  *cancellable;
77   char *buff[N_BUFFERS]; /* the temporary buffers */
78   gsize count[N_BUFFERS]; /* how many bytes are used in the buffers */
79   gboolean is_full[N_BUFFERS]; /* whether the buffers contain data */
80   gint curr_read; /* index of the buffer used for reading */
81   gint curr_write; /* index of the buffer used for writing */
82   gboolean is_reading; /* we are reading */
83   gboolean is_writing; /* we are writing */
84   guint n_closed; /* number of streams that have been closed */
85   gint ref_count;
86 } CopyData;
87
88 static void schedule_next (CopyData *copy);
89
90 static void
91 copy_data_unref (CopyData *copy)
92 {
93   if (--copy->ref_count == 0)
94     {
95       gint i;
96
97       /* Free the data only if both the input and output streams have
98        * been closed. */
99       copy->n_closed++;
100       if (copy->n_closed < 2)
101         return;
102
103       if (copy->in != NULL)
104         g_object_unref (copy->in);
105
106       if (copy->out != NULL)
107         g_object_unref (copy->out);
108
109       for (i = 0; i < N_BUFFERS; i++)
110         g_free (copy->buff[i]);
111
112       g_object_unref (copy->cancellable);
113       g_free (copy);
114     }
115 }
116
117 static void
118 io_error (CopyData *copy,
119           GError *error)
120 {
121   g_cancellable_cancel (copy->cancellable);
122
123   if (error == NULL)
124     g_warning ("I/O error");
125   else if (error->domain == G_IO_ERROR && error->code == G_IO_ERROR_CANCELLED)
126     ; /* Ignore cancellations */
127   else
128     g_warning ("I/O error: %d: %s\n", error->code, error->message);
129
130   if (copy->in != NULL)
131     g_input_stream_close (copy->in, NULL, NULL);
132
133   if (copy->out != NULL)
134     g_output_stream_close (copy->out, NULL, NULL);
135
136   copy_data_unref (copy);
137 }
138
139 static void
140 close_done (GObject *source_object,
141             GAsyncResult *res,
142             gpointer user_data)
143 {
144   CopyData *copy = user_data;
145
146   g_object_unref (source_object);
147   copy_data_unref (copy);
148 }
149
150 static void
151 write_done_cb (GObject *source_object,
152                GAsyncResult *res,
153                gpointer user_data)
154 {
155   CopyData *copy = user_data;
156   gssize count_write;
157   GError *error = NULL;
158
159   count_write = g_output_stream_write_finish (copy->out, res, &error);
160
161   if (count_write <= 0)
162     {
163       io_error (copy, error);
164       g_error_free (error);
165       return;
166     }
167
168   copy->is_full[copy->curr_write] = FALSE;
169   copy->curr_write = (copy->curr_write + 1) % N_BUFFERS;
170   copy->is_writing = FALSE;
171
172   schedule_next (copy);
173 }
174
175 static void
176 read_done_cb (GObject *source_object,
177               GAsyncResult *res,
178               gpointer user_data)
179 {
180   CopyData *copy = user_data;
181   gssize count_read;
182   GError *error = NULL;
183
184   count_read = g_input_stream_read_finish (copy->in, res, &error);
185
186   if (count_read == 0)
187     {
188       g_input_stream_close_async (copy->in, 0, copy->cancellable,
189           close_done, copy);
190       copy->in = NULL;
191     }
192   else if (count_read < 0)
193     {
194       io_error (copy, error);
195       g_error_free (error);
196       return;
197     }
198
199   copy->count[copy->curr_read] = count_read;
200   copy->is_full[copy->curr_read] = TRUE;
201   copy->curr_read = (copy->curr_read + 1) % N_BUFFERS;
202   copy->is_reading = FALSE;
203
204   schedule_next (copy);
205 }
206
207 static void
208 schedule_next (CopyData *copy)
209 {
210   if (copy->in != NULL &&
211       !copy->is_reading &&
212       !copy->is_full[copy->curr_read])
213     {
214       /* We are not reading and the current buffer is empty, so
215        * start an async read. */
216       copy->is_reading = TRUE;
217       g_input_stream_read_async (copy->in,
218           copy->buff[copy->curr_read],
219           BUFFER_SIZE, 0, copy->cancellable,
220           read_done_cb, copy);
221     }
222
223   if (!copy->is_writing &&
224       copy->is_full[copy->curr_write])
225     {
226       if (copy->count[copy->curr_write] == 0)
227         {
228           /* The last read on the buffer read 0 bytes, this
229            * means that we got an EOF, so we can close
230            * the output channel. */
231           g_output_stream_close_async (copy->out, 0,
232               copy->cancellable,
233               close_done, copy);
234       copy->out = NULL;
235         }
236       else
237         {
238           /* We are not writing and the current buffer contains
239            * data, so start an async write. */
240           copy->is_writing = TRUE;
241           g_output_stream_write_async (copy->out,
242               copy->buff[copy->curr_write],
243               copy->count[copy->curr_write],
244               0, copy->cancellable,
245               write_done_cb, copy);
246         }
247     }
248 }
249
250 static void
251 copy_stream (GInputStream *in,
252              GOutputStream *out,
253              GCancellable *cancellable)
254 {
255   CopyData *copy;
256   gint i;
257
258   g_return_if_fail (in != NULL);
259   g_return_if_fail (out != NULL);
260
261   copy = g_new0 (CopyData, 1);
262   copy->in = g_object_ref (in);
263   copy->out = g_object_ref (out);
264   copy->ref_count = 1;
265
266   if (cancellable != NULL)
267     copy->cancellable = g_object_ref (cancellable);
268   else
269     copy->cancellable = g_cancellable_new ();
270
271   for (i = 0; i < N_BUFFERS; i++)
272     copy->buff[i] = g_malloc (BUFFER_SIZE);
273
274   schedule_next (copy);
275 }
276
277 /* EmpathyTpFile object */
278
279 struct _EmpathyTpFilePriv {
280   EmpathyContactFactory *factory;
281   MissionControl *mc;
282   TpChannel *channel;
283
284   EmpathyContact *contact;
285   GInputStream *in_stream;
286   GOutputStream *out_stream;
287
288   /* org.freedesktop.Telepathy.Channel.Type.FileTransfer D-Bus properties */
289   TpFileTransferState state;
290   gchar *content_type;
291   gchar *filename;
292   guint64 size;
293   TpFileHashType content_hash_type;
294   gchar *content_hash;
295   gchar *description;
296   guint64 transferred_bytes;
297
298   gboolean incoming;
299   TpFileTransferStateChangeReason state_change_reason;
300   time_t start_time;
301   GValue *socket_address;
302   GCancellable *cancellable;
303 };
304
305 enum {
306   PROP_0,
307   PROP_CHANNEL,
308   PROP_STATE,
309   PROP_INCOMING,
310   PROP_FILENAME,
311   PROP_SIZE,
312   PROP_CONTENT_TYPE,
313   PROP_TRANSFERRED_BYTES,
314   PROP_CONTENT_HASH_TYPE,
315   PROP_CONTENT_HASH,
316 };
317
318 G_DEFINE_TYPE (EmpathyTpFile, empathy_tp_file, G_TYPE_OBJECT);
319
320 static void
321 empathy_tp_file_init (EmpathyTpFile *tp_file)
322 {
323   EmpathyTpFilePriv *priv;
324
325   priv = G_TYPE_INSTANCE_GET_PRIVATE ((tp_file),
326       EMPATHY_TYPE_TP_FILE, EmpathyTpFilePriv);
327
328   tp_file->priv = priv;
329 }
330
331 static void
332 tp_file_invalidated_cb (TpProxy       *proxy,
333                         guint          domain,
334                         gint           code,
335                         gchar         *message,
336                         EmpathyTpFile *tp_file)
337 {
338   DEBUG ("Channel invalidated: %s", message);
339
340   if (tp_file->priv->state != TP_FILE_TRANSFER_STATE_COMPLETED &&
341       tp_file->priv->state != TP_FILE_TRANSFER_STATE_CANCELLED)
342     {
343       /* The channel is not in a finished state, an error occured */
344       tp_file->priv->state = TP_FILE_TRANSFER_STATE_CANCELLED;
345       tp_file->priv->state_change_reason =
346           TP_FILE_TRANSFER_STATE_CHANGE_REASON_LOCAL_ERROR;
347       g_object_notify (G_OBJECT (tp_file), "state");
348     }
349 }
350
351 static void
352 tp_file_finalize (GObject *object)
353 {
354   EmpathyTpFile *tp_file = EMPATHY_TP_FILE (object);
355
356   if (tp_file->priv->channel)
357     {
358       g_signal_handlers_disconnect_by_func (tp_file->priv->channel,
359           tp_file_invalidated_cb, object);
360       g_object_unref (tp_file->priv->channel);
361       tp_file->priv->channel = NULL;
362     }
363
364   if (tp_file->priv->factory)
365     {
366       g_object_unref (tp_file->priv->factory);
367     }
368   if (tp_file->priv->mc)
369     {
370       g_object_unref (tp_file->priv->mc);
371     }
372
373   g_free (tp_file->priv->filename);
374   if (tp_file->priv->socket_address != NULL)
375     tp_g_value_slice_free (tp_file->priv->socket_address);
376   g_free (tp_file->priv->description);
377   g_free (tp_file->priv->content_hash);
378   g_free (tp_file->priv->content_type);
379
380   if (tp_file->priv->in_stream)
381     g_object_unref (tp_file->priv->in_stream);
382
383   if (tp_file->priv->out_stream)
384     g_object_unref (tp_file->priv->out_stream);
385
386   if (tp_file->priv->contact)
387     g_object_unref (tp_file->priv->contact);
388
389   if (tp_file->priv->cancellable)
390     g_object_unref (tp_file->priv->cancellable);
391
392   G_OBJECT_CLASS (empathy_tp_file_parent_class)->finalize (object);
393 }
394
395 static void
396 tp_file_start_transfer (EmpathyTpFile *tp_file)
397 {
398   gint fd;
399   struct sockaddr_un addr;
400   GArray *array;
401
402   fd = socket (PF_UNIX, SOCK_STREAM, 0);
403   if (fd < 0)
404     {
405       DEBUG ("Failed to create socket, closing channel");
406       empathy_tp_file_cancel (tp_file);
407       return;
408     }
409
410   array = g_value_get_boxed (tp_file->priv->socket_address);
411
412   memset (&addr, 0, sizeof (addr));
413   addr.sun_family = AF_UNIX;
414   strncpy (addr.sun_path, array->data, array->len);
415
416   if (connect (fd, (struct sockaddr*) &addr, sizeof (addr)) < 0)
417     {
418       DEBUG ("Failed to connect socket, closing channel");
419       empathy_tp_file_cancel (tp_file);
420       close (fd);
421       return;
422     }
423
424   DEBUG ("Start the transfer");
425
426   tp_file->priv->start_time = empathy_time_get_current ();
427   tp_file->priv->cancellable = g_cancellable_new ();
428   if (tp_file->priv->incoming)
429     {
430       GInputStream *socket_stream;
431
432       socket_stream = g_unix_input_stream_new (fd, TRUE);
433       copy_stream (socket_stream, tp_file->priv->out_stream,
434           tp_file->priv->cancellable);
435       g_object_unref (socket_stream);
436     }
437   else
438     {
439       GOutputStream *socket_stream;
440
441       socket_stream = g_unix_output_stream_new (fd, TRUE);
442       copy_stream (tp_file->priv->in_stream, socket_stream,
443           tp_file->priv->cancellable);
444       g_object_unref (socket_stream);
445     }
446 }
447
448 static void
449 tp_file_state_changed_cb (TpChannel *channel,
450                           guint state,
451                           guint reason,
452                           gpointer user_data,
453                           GObject *weak_object)
454 {
455   EmpathyTpFile *tp_file = EMPATHY_TP_FILE (weak_object);
456
457   if (state == tp_file->priv->state)
458     return;
459
460   DEBUG ("File transfer state changed:\n"
461       "\tfilename = %s, old state = %u, state = %u, reason = %u\n"
462       "\tincoming = %s, in_stream = %s, out_stream = %s",
463       tp_file->priv->filename, tp_file->priv->state, state, reason,
464       tp_file->priv->incoming ? "yes" : "no",
465       tp_file->priv->in_stream ? "present" : "not present",
466       tp_file->priv->out_stream ? "present" : "not present");
467
468   /* If the channel is open AND we have the socket path, we can start the
469    * transfer. The socket path could be NULL if we are not doing the actual
470    * data transfer but are just an observer for the channel. */
471   if (state == TP_FILE_TRANSFER_STATE_OPEN &&
472       tp_file->priv->socket_address != NULL)
473     tp_file_start_transfer (tp_file);
474
475   tp_file->priv->state = state;
476   tp_file->priv->state_change_reason = reason;
477
478   g_object_notify (G_OBJECT (tp_file), "state");
479 }
480
481 static void
482 tp_file_transferred_bytes_changed_cb (TpChannel *channel,
483                                       guint64 count,
484                                       gpointer user_data,
485                                       GObject *weak_object)
486 {
487   EmpathyTpFile *tp_file = EMPATHY_TP_FILE (weak_object);
488
489   if (tp_file->priv->transferred_bytes == count)
490     return;
491
492   tp_file->priv->transferred_bytes = count;
493   g_object_notify (G_OBJECT (tp_file), "transferred-bytes");
494 }
495
496 static GObject *
497 tp_file_constructor (GType type,
498                      guint n_props,
499                      GObjectConstructParam *props)
500 {
501   GObject *file_obj;
502   EmpathyTpFile *tp_file;
503   TpHandle handle;
504   GHashTable *properties;
505   McAccount *account;
506   GValue *requested;
507
508   file_obj = G_OBJECT_CLASS (empathy_tp_file_parent_class)->constructor (type,
509       n_props, props);
510
511   tp_file = EMPATHY_TP_FILE (file_obj);
512
513   tp_file->priv->factory = empathy_contact_factory_dup_singleton ();
514   tp_file->priv->mc = empathy_mission_control_dup_singleton ();
515
516   g_signal_connect (tp_file->priv->channel, "invalidated",
517     G_CALLBACK (tp_file_invalidated_cb), tp_file);
518
519   tp_cli_channel_type_file_transfer_connect_to_file_transfer_state_changed (
520       tp_file->priv->channel, tp_file_state_changed_cb, NULL, NULL,
521       G_OBJECT (tp_file), NULL);
522
523   tp_cli_channel_type_file_transfer_connect_to_transferred_bytes_changed (
524       tp_file->priv->channel, tp_file_transferred_bytes_changed_cb,
525       NULL, NULL, G_OBJECT (tp_file), NULL);
526
527   account = empathy_channel_get_account (tp_file->priv->channel);
528
529   handle = tp_channel_get_handle (tp_file->priv->channel, NULL);
530   tp_file->priv->contact = empathy_contact_factory_get_from_handle (
531       tp_file->priv->factory, account, (guint) handle);
532
533   tp_cli_dbus_properties_run_get_all (tp_file->priv->channel,
534       -1, TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER, &properties, NULL, NULL);
535
536   tp_cli_dbus_properties_run_get (tp_file->priv->channel,
537       -1, TP_IFACE_CHANNEL, "Requested", &requested, NULL, NULL);
538
539   tp_file->priv->size = g_value_get_uint64 (
540       g_hash_table_lookup (properties, "Size"));
541
542   tp_file->priv->state = g_value_get_uint (
543       g_hash_table_lookup (properties, "State"));
544
545   tp_file->priv->state_change_reason =
546       TP_FILE_TRANSFER_STATE_CHANGE_REASON_NONE;
547
548   tp_file->priv->transferred_bytes = g_value_get_uint64 (
549       g_hash_table_lookup (properties, "TransferredBytes"));
550
551   tp_file->priv->filename = g_value_dup_string (
552       g_hash_table_lookup (properties, "Filename"));
553
554   tp_file->priv->content_hash = g_value_dup_string (
555       g_hash_table_lookup (properties, "ContentHash"));
556
557   tp_file->priv->content_hash_type = g_value_get_uint (
558       g_hash_table_lookup (properties, "ContentHashType"));
559
560   tp_file->priv->content_type = g_value_dup_string (
561       g_hash_table_lookup (properties, "ContentType"));
562
563   tp_file->priv->description = g_value_dup_string (
564       g_hash_table_lookup (properties, "Description"));
565
566   tp_file->priv->incoming = !g_value_get_boolean (requested);
567
568   g_hash_table_destroy (properties);
569   g_object_unref (account);
570   g_value_unset (requested);
571
572   return file_obj;
573 }
574
575 static void
576 tp_file_get_property (GObject *object,
577                       guint param_id,
578                       GValue *value,
579                       GParamSpec *pspec)
580 {
581   EmpathyTpFile *tp_file;
582
583   tp_file = EMPATHY_TP_FILE (object);
584
585   switch (param_id)
586     {
587       case PROP_CHANNEL:
588         g_value_set_object (value, tp_file->priv->channel);
589         break;
590       case PROP_INCOMING:
591         g_value_set_boolean (value, tp_file->priv->incoming);
592         break;
593       case PROP_STATE:
594         g_value_set_uint (value, tp_file->priv->state);
595         break;
596       case PROP_CONTENT_TYPE:
597         g_value_set_string (value, tp_file->priv->content_type);
598         break;
599       case PROP_FILENAME:
600         g_value_set_string (value, tp_file->priv->filename);
601         break;
602       case PROP_SIZE:
603         g_value_set_uint64 (value, tp_file->priv->size);
604         break;
605       case PROP_CONTENT_HASH_TYPE:
606         g_value_set_uint (value, tp_file->priv->content_hash_type);
607         break;
608       case PROP_CONTENT_HASH:
609         g_value_set_string (value, tp_file->priv->content_hash);
610         break;
611       case PROP_TRANSFERRED_BYTES:
612         g_value_set_uint64 (value, tp_file->priv->transferred_bytes);
613         break;
614       default:
615         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
616         break;
617     };
618 }
619
620 static void
621 tp_file_channel_set_dbus_property (gpointer proxy,
622                                    const gchar *property,
623                                    const GValue *value)
624 {
625         DEBUG ("Setting %s property", property);
626         tp_cli_dbus_properties_call_set (TP_PROXY (proxy), -1,
627             TP_IFACE_CHANNEL_TYPE_FILE_TRANSFER, property, value,
628             NULL, NULL, NULL, NULL);
629 }
630
631 static void
632 tp_file_set_property (GObject *object,
633                       guint param_id,
634                       const GValue *value,
635                       GParamSpec *pspec)
636 {
637   EmpathyTpFile *tp_file = (EmpathyTpFile *) object;
638   switch (param_id)
639     {
640       case PROP_CHANNEL:
641         tp_file->priv->channel = g_object_ref (g_value_get_object (value));
642         break;
643       case PROP_STATE:
644         tp_file->priv->state = g_value_get_uint (value);
645         break;
646       case PROP_INCOMING:
647         tp_file->priv->incoming = g_value_get_boolean (value);
648         break;
649       case PROP_FILENAME:
650         g_free (tp_file->priv->filename);
651         tp_file->priv->filename = g_value_dup_string (value);
652         tp_file_channel_set_dbus_property (tp_file->priv->channel,
653             "Filename", value);
654         break;
655       case PROP_SIZE:
656         tp_file->priv->size = g_value_get_uint64 (value);
657         tp_file_channel_set_dbus_property (tp_file->priv->channel,
658             "Size", value);
659         break;
660       case PROP_CONTENT_TYPE:
661         tp_file_channel_set_dbus_property (tp_file->priv->channel,
662             "ContentType", value);
663         g_free (tp_file->priv->content_type);
664         tp_file->priv->content_type = g_value_dup_string (value);
665         break;
666       case PROP_CONTENT_HASH:
667         tp_file_channel_set_dbus_property (tp_file->priv->channel,
668             "ContentHash", value);
669         g_free (tp_file->priv->content_hash);
670         tp_file->priv->content_hash = g_value_dup_string (value);
671         break;
672       default:
673         G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
674         break;
675     };
676 }
677
678 static GHashTable *ft_table = NULL;
679
680 static void
681 tp_file_weak_notify_cb (gpointer channel,
682                         GObject *tp_file)
683 {
684   g_hash_table_remove (ft_table, channel);
685 }
686
687 /**
688  * empathy_tp_file_new:
689  * @channel: a Telepathy channel
690  *
691  * Creates a new #EmpathyTpFile wrapping @channel, or return a new ref to an
692  * existing #EmpathyTpFile for that channel.
693  *
694  * Returns: a new #EmpathyTpFile
695  */
696 EmpathyTpFile *
697 empathy_tp_file_new (TpChannel *channel)
698 {
699   EmpathyTpFile *tp_file;
700
701   g_return_val_if_fail (TP_IS_CHANNEL (channel), NULL);
702
703   if (ft_table != NULL)
704     {
705       tp_file = g_hash_table_lookup (ft_table, channel);
706       if (tp_file != NULL) {
707         return g_object_ref (tp_file);
708       }
709     }
710   else
711     ft_table = g_hash_table_new_full (empathy_proxy_hash,
712       empathy_proxy_equal, (GDestroyNotify) g_object_unref, NULL);
713
714   tp_file = g_object_new (EMPATHY_TYPE_TP_FILE,
715       "channel", channel,
716       NULL);
717
718   g_hash_table_insert (ft_table, g_object_ref (channel), tp_file);
719   g_object_weak_ref (G_OBJECT (tp_file), tp_file_weak_notify_cb, channel);
720
721   return tp_file;
722 }
723
724 /**
725  * empathy_tp_file_get_channel
726  * @tp_file: an #EmpathyTpFile
727  *
728  * Returns the Telepathy file transfer channel
729  *
730  * Returns: the #TpChannel
731  */
732 TpChannel *
733 empathy_tp_file_get_channel (EmpathyTpFile *tp_file)
734 {
735   g_return_val_if_fail (EMPATHY_IS_TP_FILE (tp_file), NULL);
736
737   return tp_file->priv->channel;
738 }
739
740 static void
741 tp_file_method_cb (TpChannel *channel,
742                    const GValue *address,
743                    const GError *error,
744                    gpointer user_data,
745                    GObject *weak_object)
746 {
747   EmpathyTpFile *tp_file = (EmpathyTpFile *) weak_object;
748   GArray *array;
749
750   if (error)
751     {
752       DEBUG ("Error: %s", error->message);
753       empathy_tp_file_cancel (tp_file);
754       return;
755     }
756
757   if (G_VALUE_TYPE (address) == DBUS_TYPE_G_UCHAR_ARRAY)
758     {
759       tp_file->priv->socket_address = tp_g_value_slice_dup (address);
760     }
761   else if (G_VALUE_TYPE (address) == G_TYPE_STRING)
762     {
763       /* Old bugged version of telepathy-salut used to store the address
764        * as a 's' instead of an 'ay' */
765       const gchar *path;
766
767       path = g_value_get_string (address);
768       array = g_array_sized_new (TRUE, FALSE, sizeof (gchar), strlen (path));
769       g_array_insert_vals (array, 0, path, strlen (path));
770
771       tp_file->priv->socket_address = tp_g_value_slice_new (
772           DBUS_TYPE_G_UCHAR_ARRAY);
773       g_value_set_boxed (tp_file->priv->socket_address, array);
774
775       g_array_free (array, TRUE);
776     }
777   else
778     {
779       DEBUG ("Wrong address type: %s", G_VALUE_TYPE_NAME (address));
780       empathy_tp_file_cancel (tp_file);
781       return;
782     }
783
784   array = g_value_get_boxed (tp_file->priv->socket_address);
785   DEBUG ("Got unix socket path: %s", array->data);
786
787   if (tp_file->priv->state == TP_FILE_TRANSFER_STATE_OPEN)
788     tp_file_start_transfer (tp_file);
789 }
790
791 /**
792  * empathy_tp_file_accept:
793  * @tp_file: an #EmpathyTpFile
794  * @offset: position where to start the transfer
795  * @gfile: a #GFile where to write transfered data
796  * @error: a #GError set if there is an error when opening @gfile
797  *
798  * Accepts a file transfer that's in the "local pending" state (i.e.
799  * TP_FILE_TRANSFER_STATE_LOCAL_PENDING).
800  */
801 void
802 empathy_tp_file_accept (EmpathyTpFile *tp_file,
803                         guint64 offset,
804                         GFile *gfile,
805                         GError **error)
806 {
807   GValue nothing = { 0 };
808
809   g_return_if_fail (EMPATHY_IS_TP_FILE (tp_file));
810   g_return_if_fail (G_IS_FILE (gfile));
811
812   tp_file->priv->out_stream = G_OUTPUT_STREAM (g_file_replace (gfile, NULL,
813         FALSE, 0, NULL, error));
814   if (error && *error)
815     return;
816
817   tp_file->priv->filename = g_file_get_basename (gfile);
818   g_object_notify (G_OBJECT (tp_file), "filename");
819
820   DEBUG ("Accepting file: filename=%s", tp_file->priv->filename);
821
822   g_value_init (&nothing, G_TYPE_STRING);
823   g_value_set_static_string (&nothing, "");
824
825   tp_cli_channel_type_file_transfer_call_accept_file (tp_file->priv->channel,
826       -1, TP_SOCKET_ADDRESS_TYPE_UNIX, TP_SOCKET_ACCESS_CONTROL_LOCALHOST,
827       &nothing, offset, tp_file_method_cb, NULL, NULL, G_OBJECT (tp_file));
828 }
829
830 /**
831  * empathy_tp_file_offer:
832  * @tp_file: an #EmpathyTpFile
833  * @gfile: a #GFile where to read the data to transfer
834  * @error: a #GError set if there is an error when opening @gfile
835  *
836  * Offers a file transfer that's in the "not offered" state (i.e.
837  * TP_FILE_TRANSFER_STATE_NOT_OFFERED).
838  */
839 void
840 empathy_tp_file_offer (EmpathyTpFile *tp_file, GFile *gfile, GError **error)
841 {
842   GValue nothing = { 0 };
843
844   g_return_if_fail (EMPATHY_IS_TP_FILE (tp_file));
845
846   tp_file->priv->in_stream = G_INPUT_STREAM (g_file_read (gfile, NULL, error));
847   if (error && *error)
848         return;
849
850   g_value_init (&nothing, G_TYPE_STRING);
851   g_value_set_static_string (&nothing, "");
852
853   tp_cli_channel_type_file_transfer_call_provide_file (tp_file->priv->channel,
854       -1, TP_SOCKET_ADDRESS_TYPE_UNIX, TP_SOCKET_ACCESS_CONTROL_LOCALHOST,
855       &nothing, tp_file_method_cb, NULL, NULL, G_OBJECT (tp_file));
856 }
857
858 EmpathyContact *
859 empathy_tp_file_get_contact (EmpathyTpFile *tp_file)
860 {
861   g_return_val_if_fail (EMPATHY_IS_TP_FILE (tp_file), NULL);
862   return tp_file->priv->contact;
863 }
864
865 const gchar *
866 empathy_tp_file_get_filename (EmpathyTpFile *tp_file)
867 {
868   g_return_val_if_fail (EMPATHY_IS_TP_FILE (tp_file), NULL);
869   return tp_file->priv->filename;
870 }
871
872 gboolean
873 empathy_tp_file_is_incoming (EmpathyTpFile *tp_file)
874 {
875   g_return_val_if_fail (EMPATHY_IS_TP_FILE (tp_file), FALSE);
876   return tp_file->priv->incoming;
877 }
878
879 TpFileTransferState
880 empathy_tp_file_get_state (EmpathyTpFile *tp_file,
881                            TpFileTransferStateChangeReason *reason)
882 {
883   g_return_val_if_fail (EMPATHY_IS_TP_FILE (tp_file),
884       TP_FILE_TRANSFER_STATE_NONE);
885
886   if (reason != NULL)
887     *reason = tp_file->priv->state_change_reason;
888
889   return tp_file->priv->state;
890 }
891
892 guint64
893 empathy_tp_file_get_size (EmpathyTpFile *tp_file)
894 {
895   g_return_val_if_fail (EMPATHY_IS_TP_FILE (tp_file),
896       EMPATHY_TP_FILE_UNKNOWN_SIZE);
897   return tp_file->priv->size;
898 }
899
900 guint64
901 empathy_tp_file_get_transferred_bytes (EmpathyTpFile *tp_file)
902 {
903   g_return_val_if_fail (EMPATHY_IS_TP_FILE (tp_file), 0);
904   return tp_file->priv->transferred_bytes;
905 }
906
907 gint
908 empathy_tp_file_get_remaining_time (EmpathyTpFile *tp_file)
909 {
910   time_t curr_time, elapsed_time;
911   gdouble time_per_byte;
912   gdouble remaining_time;
913
914   g_return_val_if_fail (EMPATHY_IS_TP_FILE (tp_file), -1);
915
916   if (tp_file->priv->size == EMPATHY_TP_FILE_UNKNOWN_SIZE)
917     return -1;
918
919   if (tp_file->priv->transferred_bytes == tp_file->priv->size)
920     return 0;
921
922   curr_time = empathy_time_get_current ();
923   elapsed_time = curr_time - tp_file->priv->start_time;
924   time_per_byte = (gdouble) elapsed_time /
925       (gdouble) tp_file->priv->transferred_bytes;
926   remaining_time = time_per_byte * (tp_file->priv->size -
927       tp_file->priv->transferred_bytes);
928
929   return (gint) remaining_time;
930 }
931
932 const gchar *
933 empathy_tp_file_get_content_type (EmpathyTpFile *tp_file)
934 {
935   g_return_val_if_fail (EMPATHY_IS_TP_FILE (tp_file), NULL);
936   return tp_file->priv->content_type;
937 }
938
939 void
940 empathy_tp_file_cancel (EmpathyTpFile *tp_file)
941 {
942   g_return_if_fail (EMPATHY_IS_TP_FILE (tp_file));
943
944   DEBUG ("Closing channel..");
945   tp_cli_channel_call_close (tp_file->priv->channel, -1,
946     NULL, NULL, NULL, NULL);
947
948   if (tp_file->priv->cancellable != NULL)
949     g_cancellable_cancel (tp_file->priv->cancellable);
950 }
951
952 void
953 empathy_tp_file_close (EmpathyTpFile *tp_file)
954 {
955   empathy_tp_file_cancel (tp_file);
956 }
957
958 static void
959 empathy_tp_file_class_init (EmpathyTpFileClass *klass)
960 {
961   GObjectClass *object_class = G_OBJECT_CLASS (klass);
962
963   object_class->finalize = tp_file_finalize;
964   object_class->constructor = tp_file_constructor;
965   object_class->get_property = tp_file_get_property;
966   object_class->set_property = tp_file_set_property;
967
968   /* Construct-only properties */
969   g_object_class_install_property (object_class,
970       PROP_CHANNEL,
971       g_param_spec_object ("channel",
972           "telepathy channel",
973           "The file transfer channel",
974           TP_TYPE_CHANNEL,
975           G_PARAM_READWRITE |
976           G_PARAM_CONSTRUCT_ONLY));
977
978   g_object_class_install_property (object_class,
979       PROP_STATE,
980       g_param_spec_uint ("state",
981           "state of the transfer",
982           "The file transfer state",
983           0,
984           G_MAXUINT,
985           G_MAXUINT,
986           G_PARAM_READWRITE |
987           G_PARAM_CONSTRUCT));
988
989   g_object_class_install_property (object_class,
990       PROP_INCOMING,
991       g_param_spec_boolean ("incoming",
992           "incoming",
993           "Whether the transfer is incoming",
994           FALSE,
995           G_PARAM_READWRITE |
996           G_PARAM_CONSTRUCT));
997
998   g_object_class_install_property (object_class,
999       PROP_FILENAME,
1000       g_param_spec_string ("filename",
1001           "name of the transfer",
1002           "The file transfer filename",
1003           "",
1004           G_PARAM_READWRITE));
1005
1006   g_object_class_install_property (object_class,
1007       PROP_SIZE,
1008       g_param_spec_uint64 ("size",
1009           "size of the file",
1010           "The file transfer size",
1011           0,
1012           G_MAXUINT64,
1013           G_MAXUINT64,
1014           G_PARAM_READWRITE));
1015
1016   g_object_class_install_property (object_class,
1017       PROP_CONTENT_TYPE,
1018       g_param_spec_string ("content-type",
1019           "file transfer content-type",
1020           "The file transfer content-type",
1021           "",
1022           G_PARAM_READWRITE));
1023
1024   g_object_class_install_property (object_class,
1025       PROP_CONTENT_HASH_TYPE,
1026       g_param_spec_uint ("content-hash-type",
1027           "file transfer hash type",
1028           "The type of the file transfer hash",
1029           0,
1030           G_MAXUINT,
1031           0,
1032           G_PARAM_READWRITE));
1033
1034   g_object_class_install_property (object_class,
1035       PROP_CONTENT_HASH,
1036       g_param_spec_string ("content-hash",
1037           "file transfer hash",
1038           "The hash of the transfer's contents",
1039           "",
1040           G_PARAM_READWRITE));
1041
1042   g_object_class_install_property (object_class,
1043       PROP_TRANSFERRED_BYTES,
1044       g_param_spec_uint64 ("transferred-bytes",
1045           "bytes transferred",
1046           "The number of bytes transferred",
1047           0,
1048           G_MAXUINT64,
1049           0,
1050           G_PARAM_READWRITE));
1051
1052   g_type_class_add_private (object_class, sizeof (EmpathyTpFilePriv));
1053 }
1054